Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

fix: address Ruflo mod and console beta feedback (#3698)

rUv668f99dc337d
diff --git a/.claude/helpers/hook-handler.cjs b/.claude/helpers/hook-handler.cjs
index 24635591a7..3fda14ca1a 100755
--- a/.claude/helpers/hook-handler.cjs
+++ b/.claude/helpers/hook-handler.cjs
@@ -388,13 +388,14 @@ const handlers = {
if (router && router.routeTask) {
const result = router.routeTask(prompt);
// Format output for Claude Code hook consumption — real data only
+ const row = (text) => `| ${text.substring(0, 60).padEnd(60)} |`;
const output = [
`[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,
'',
'+------------------- Primary Recommendation -------------------+',
- `| Agent: ${result.agent.padEnd(53)}|`,
- `| Confidence: ${(result.confidence * 100).toFixed(1)}%${' '.repeat(44)}|`,
- `| Reason: ${(result.reason || '').substring(0, 53).padEnd(53)}|`,
+ row(`Agent: ${result.agent}`),
+ row(`Confidence: ${(result.confidence * 100).toFixed(1)}%`),
+ row(`Reason: ${result.reason || ''}`),
'+--------------------------------------------------------------+',
];
console.log(output.join('\n'));
@@ -462,8 +463,77 @@ const handlers = {
// (silently exiting 0 and letting the dangerous command through).
const cmd = String(hookInput.command || toolInput.command || prompt || '').toLowerCase();
const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:'];
+ // Join literal quote fragments and normalize root paths without shell evaluation.
+ function hasRootDelete(command, depth = 0) {
+ let word = '', quote = '', started = false, redirect = false
+ let inRm = false, optionsEnded = false, recursive = false, force = false, root = false
+ const isRoot = (operand) => {
+ if (!operand.startsWith('/')) return false
+ const parts = []
+ for (const part of operand.split('/')) {
+ if (!part || part === '.') continue
+ if (part === '..') parts.pop()
+ else parts.push(part)
+ }
+ return parts.length === 0 || /[*?\[]/.test(parts[0])
+ }
+ const finishWord = () => {
+ if (!started) return false
+ // Literal shell strings (e.g. sh -c 'rm -rf /') also carried the old guard.
+ // Bound rescanning to four levels; beyond that retain its conservative check.
+ if (word.includes('rm') && /[\s;&|()]/.test(word)) {
+ if (depth < 4 ? hasRootDelete(word, depth + 1) : word.includes('rm -rf /')) return true
+ }
+ if (!inRm) inRm = word === 'rm' || word.endsWith('/rm')
+ else if (!optionsEnded && word === '--') optionsEnded = true
+ else if (!optionsEnded && word.startsWith('-')) {
+ recursive = recursive || word === '--recursive' || /^-[a-z]*r[a-z]*$/.test(word)
+ force = force || word === '--force' || /^-[a-z]*f[a-z]*$/.test(word)
+ } else root = root || isRoot(word)
+ word = ''; started = false
+ return inRm && recursive && force && root
+ }
+ const finishCommand = () => {
+ const denied = inRm && recursive && force && root
+ inRm = optionsEnded = recursive = force = root = false
+ return denied
+ }
+ for (let i = 0; i < command.length; i++) {
+ const char = command[i]
+ const redirectionAmpersand = char === '&' && (redirect || command[i + 1] === '>')
+ redirect = false
+ if (quote) {
+ if (char === quote) quote = ''
+ else if (quote === '"' && char === '\\' && i + 1 < command.length &&
+ (command[i + 1] === '"' || command[i + 1] === '\\' || command[i + 1] === '$' ||
+ command.charCodeAt(i + 1) === 96 || command[i + 1] === '\n')) {
+ const next = command[++i]
+ if (next !== '\n') word += next
+ } else word += char
+ continue
+ }
+ if (char === '\\' && i + 1 < command.length) {
+ const next = command[++i]
+ if (next !== '\n') { word += next; started = true }
+ } else if (char === '"' || char === "'") {
+ quote = char; started = true
+ } else if (char === '#' && !started) {
+ while (i < command.length && command[i] !== '\n') i++
+ if (finishCommand()) return true
+ } else if (char === ' ' || char === '\t' || char === '\r' || char === '\n' ||
+ ';|&()<>'.includes(char)) {
+ if (finishWord()) return true
+ // Redirections separate words, but later operands still belong to rm.
+ redirect = char === '<' || char === '>'
+ if (!redirectionAmpersand && (char === '\n' || ';|&()'.includes(char)) && finishCommand()) return true
+ } else {
+ word += char; started = true
+ }
+ }
+ return finishWord() || finishCommand()
+ }
for (const d of dangerous) {
- if (cmd.includes(d)) {
+ if (d === 'rm -rf /' ? hasRootDelete(cmd) : cmd.includes(d)) {
console.error(`[BLOCKED] Dangerous command detected: ${d}`);
// Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.
process.exit(2);
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts
index 7aa354a6c0..d2f19bb00c 100644
--- a/plugins/ruflo-console/hooks/actions.ts
+++ b/plugins/ruflo-console/hooks/actions.ts
@@ -5,6 +5,7 @@
*/
import { idOf, type AgentRecord, type ClaimRecord, type Claimant, type TaskRecord } from './data/parse'
import type { Snapshot } from './data/snapshot'
+import type { Host } from './host'
export type ActionSpec = {
label: string
@@ -14,6 +15,8 @@ export type ActionSpec = {
stdin?: string
expect: string
verify?: (snapshot: Snapshot) => boolean
+ /** A local check after a confirmed action succeeds; never part of background refreshes. */
+ verifyLocal?: (host: Pick<Host, 'fs' | 'home'>) => Promise<boolean>
/** Reads only: runs at once, without the confirm step, and shows what the CLI printed. */
isReadOnly?: boolean
/** Not a ruflo CLI call: what runs instead once confirmed (a terminal harness), reporting for itself. */
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index eeaaebc567..b42e7a1860 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -214,7 +214,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
},
focus: key => void host.focus(PANE_ID, key).catch(() => undefined),
plugin: op => runner.ask(pluginSpec(op), 'that cannot run here'),
- start: (id, text = '') => runner.ask(startSpec(id, Date.now(), text), id === 'mission' || id === 'task' ? 'type it first (it may not start with -)' : 'that start cannot run here'),
+ start: (id, text = '') => runner.ask(startSpec(id, Date.now(), text, present => { state.nostrKeyVerifiedAtMs = present ? Date.now() : null }), id === 'mission' || id === 'task' ? 'type it first (it may not start with -)' : 'that start cannot run here'),
// The main menu's prompt, as a board's: a key (2, w, i), a name (swarm, x.ruv.io), ? for help, O to log off.
menu: text => {
const word = text.trim().toLowerCase()
diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts
index 8970c86ce7..1d1d4855d3 100644
--- a/plugins/ruflo-console/hooks/controller.ts
+++ b/plugins/ruflo-console/hooks/controller.ts
@@ -5,7 +5,7 @@
*/
import { actionsOf } from './bindings'
import type { Catalog } from './data/catalog'
-import { PROBES, probeArgv, probeReady, type ProbeResult } from './data/cli'
+import { PROBES, probeArgv, probeError, probeReady, type ProbeResult } from './data/cli'
import { ALL_COST_PROBES as COST_PROBES } from './data/cost-probes'
import { X_PROBES } from './data/xruv'
import { diffEvents, record } from './data/events'
@@ -133,8 +133,8 @@ export function createController(state: State, host: Host): Controller {
])
const previous = state.snapshot
const now = Date.now()
- const snapshot = await readSnapshot(host.fs, state.cache, state.cwd, state.home, settings, now, state.configDir)
-
+ const snapshot = await readSnapshot(host.fs, state.cache, state.cwd, state.home, settings, now, state.configDir, state.options.federationNetwork)
+ if (snapshot.hasNostrKey === false) state.nostrKeyVerifiedAtMs = null
state.snapshot = snapshot
record(state.events, diffEvents(previous, snapshot, now))
@@ -208,9 +208,9 @@ export function createController(state: State, host: Host): Controller {
lastAttempt.set(probe.id, Date.now())
try {
- const result = await host.run(probeArgv(probe, state.options.cli, state), probe.timeoutMs)
+ const argv = probeArgv(probe, state.options.cli, state)
+ const result = await host.run(argv, probe.timeoutMs)
const value = result.exitCode === 0 ? (probe.parse(result.stdout) as unknown) : null
-
state.probes.set(
probe.id,
value !== null
@@ -219,7 +219,7 @@ export function createController(state: State, host: Host): Controller {
...held,
isRunning: false,
errorAtMs: Date.now(),
- error: result.exitCode !== 0 ? `exit ${result.exitCode}: ${plain(result.stderr.split('\n').find(line => line.trim() !== '') ?? '', 100) || 'no message'}` : 'no JSON in the CLI output',
+ error: probeError(argv, result),
},
)
} catch (error) {
diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.ts
index c06c00e3a3..6fa836394e 100644
--- a/plugins/ruflo-console/hooks/data/cli.ts
+++ b/plugins/ruflo-console/hooks/data/cli.ts
@@ -482,4 +482,13 @@ export type ProbeId = (typeof PROBES)[number]['id']
/** What a probe came to: the last good value and when, and the last error, so a failing source is never drawn as live. */
export type ProbeResult<T = unknown> = { value: T | null; okAtMs: number | null; error: string | null; errorAtMs: number | null; isRunning: boolean }
+/** An empty offline npm cache needs one explicit install; probes never download it themselves. */
+export function probeError(argv: readonly string[], result: { exitCode: number; stdout: string; stderr: string }): string {
+ if (result.exitCode === 0) return 'no JSON in the CLI output'
+ if (argv[0] === 'npx' && argv.includes('--offline') && argv.includes('@claude-flow/cli@latest') && /\bENOTCACHED\b/.test(`${result.stderr}\n${result.stdout}`)) {
+ return 'ruflo CLI not cached; run: npx -y @claude-flow/cli@latest --version'
+ }
+ return `exit ${result.exitCode}: ${plain(result.stderr.split('\n').find(line => line.trim() !== '') ?? '', 100) || 'no message'}`
+}
+
export const emptyResult = (): ProbeResult => ({ value: null, okAtMs: null, error: null, errorAtMs: null, isRunning: false })
diff --git a/plugins/ruflo-console/hooks/data/files.ts b/plugins/ruflo-console/hooks/data/files.ts
index 2e10c04091..7f117a3425 100644
--- a/plugins/ruflo-console/hooks/data/files.ts
+++ b/plugins/ruflo-console/hooks/data/files.ts
@@ -4,7 +4,7 @@
* fact, and a file over READ_MAX bytes is never read (`.claude-flow/policy/state.json` reaches 40 MB in a busy project).
*
* Never listed here, never read: `.claude-flow/federation/key-*.json`, `~/.ruflo/nostr.key` and `~/.ruflo/channels.json`
- * hold private keys. The console names the first by listing the folder and the second by `stat` alone.
+ * hold private keys. The console names the first by listing the folder and stats the second only with federation enabled.
*/
/** The `$.fs` calls a reader makes; each may reject. */
@@ -112,7 +112,7 @@ export const under = (root: string, path: string): string => `${root.replace(/\/
export type DiskRead = { project: Record<ProjectKey, Read>; home: Record<keyof typeof HOME, Read>; changed: number; federationNodes: string[] | null; hasNostrKey: boolean | null }
/** Reads every file in parallel; nothing here rejects. `home` and `configDir` are null when unknown. */
-export async function readDisk(fs: ReaderFs, cache: ReadCache, cwd: string, home: string | null, configDir: string | null = home === null ? null : `${home}/.claude`): Promise<DiskRead> {
+export async function readDisk(fs: ReaderFs, cache: ReadCache, cwd: string, home: string | null, configDir: string | null = home === null ? null : `${home}/.claude`, federationNetwork = false): Promise<DiskRead> {
const mtimeOf = (held: ReadCache extends Map<string, infer V> ? V : never) => ('mtimeMs' in held ? held.mtimeMs : -1)
const before = new Map([...cache].map(([path, held]) => [path, mtimeOf(held)]))
const projectKeys = Object.keys(PROJECT) as ProjectKey[]
@@ -125,7 +125,7 @@ export async function readDisk(fs: ReaderFs, cache: ReadCache, cwd: string, home
.list(under(cwd, FEDERATION_DIR))
.then(entries => entries.flatMap(entry => (/^key-[A-Za-z0-9._-]{1,64}\.json$/.test(entry.name) ? [entry.name.slice(4, -5)] : [])).slice(0, 50))
.catch(() => null),
- home === null ? Promise.resolve(null) : fs.stat(under(home, NOSTR_KEY)).then(() => true, () => false),
+ home === null || !federationNetwork ? Promise.resolve(null) : fs.stat(under(home, NOSTR_KEY)).then(stat => stat !== undefined, () => false),
])
const project = Object.fromEntries(projectKeys.map((key, i) => [key, projectReads[i] as Read])) as Record<ProjectKey, Read>
const homeRecord = Object.fromEntries(homeKeys.map((key, i) => [key, homeReads[i] as Read])) as Record<keyof typeof HOME, Read>
diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.ts
index b19ee41194..6163409a81 100644
--- a/plugins/ruflo-console/hooks/data/snapshot.ts
+++ b/plugins/ruflo-console/hooks/data/snapshot.ts
@@ -90,8 +90,8 @@ export type ReadStatus = 'ok' | 'missing' | 'too-large' | 'refused'
const statusOf = (read: Read): ReadStatus => (read.text !== null ? 'ok' : read.reason)
/** Reads and parses everything; never rejects. `settings` is the merged settings, for `enabledPlugins`. */
-export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string, home: string | null, settings: unknown, nowMs: number, configDir?: string | null): Promise<Snapshot> {
- const disk = await readDisk(fs, cache, cwd, home, configDir === undefined ? (home === null ? null : `${home}/.claude`) : configDir)
+export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string, home: string | null, settings: unknown, nowMs: number, configDir?: string | null, federationNetwork = false): Promise<Snapshot> {
+ const disk = await readDisk(fs, cache, cwd, home, configDir === undefined ? (home === null ? null : `${home}/.claude`) : configDir, federationNetwork)
const text = (key: ProjectKey) => textOf(disk.project[key])
const stored = parseSwarmStore(text('swarm'))
const pointer = parseSwarmPointer(text('pointer'))
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 33149d2cf0..c599cfc2d6 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -102,7 +102,7 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
for (const type of AGENT_TYPES) add(`spawn-${type}`, 'swarm', `spawn ${/^[aeiou]/.test(type) ? 'an' : 'a'} ${type} agent`, { kind: 'spec', spec: spawnAgent(type, nowMs), why: 'unknown agent type' })
// One-click starts, also reachable as `/ruflo run <id>`: everything an empty section offers.
- for (const id of START_IDS) add(id, 'start', `${START_LABEL[id]}`, { kind: 'spec', spec: startSpec(id, nowMs), why: 'that start cannot run here' })
+ for (const id of START_IDS) add(id, 'start', `${START_LABEL[id]}`, { kind: 'spec', spec: startSpec(id, nowMs, '', present => { state.nostrKeyVerifiedAtMs = present ? Date.now() : null }), why: 'that start cannot run here' })
add('task', 'start', 'task <text>: put a task on the board', { kind: 'text', keyword: 'task', make: text => startSpec('task', nowMs, text) })
add('mission', 'start', 'mission <objective>: create an ADR-406 mission', { kind: 'text', keyword: 'mission', make: text => startSpec('mission', nowMs, text) })
diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts
index 1249fac0f3..0e0e591f0d 100644
--- a/plugins/ruflo-console/hooks/register.ts
+++ b/plugins/ruflo-console/hooks/register.ts
@@ -139,6 +139,7 @@ export const register: Register = (on, raw: PluginOptions) => {
control?.stop()
host = hostOf($, e.cwd)
state.cwd = e.cwd
+ state.nostrKeyVerifiedAtMs = null
state.isInteractive = e.isInteractive !== false
control = createController(state, host)
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index 4ae1129527..6d19ed9cf7 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -87,7 +87,9 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
await deps.freshRead()
- const verified = spec.verify === undefined || state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no'
+ const verified = spec.verifyLocal !== undefined
+ ? ok && await spec.verifyLocal(host) ? 'yes' : 'no'
+ : spec.verify === undefined || state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no'
state.outcome = {
label: spec.label,
diff --git a/plugins/ruflo-console/hooks/starts.ts b/plugins/ruflo-console/hooks/starts.ts
index baec45406e..d14d71efb1 100644
--- a/plugins/ruflo-console/hooks/starts.ts
+++ b/plugins/ruflo-console/hooks/starts.ts
@@ -6,6 +6,7 @@
* reaches the network, and `mods install` writes Claude Code settings; both say so on the confirm row.
*/
import type { ActionSpec } from './actions'
+import { NOSTR_KEY, under } from './data/files'
import { spawnAgent, swarmInit, textArg } from './ops'
export type StartId =
@@ -43,7 +44,7 @@ export const START_LABEL: Record<StartId, string> = {
}
/** The ask for a start, or null when its text cannot be passed (a mission objective is the only text). */
-export function startSpec(id: StartId, nowMs: number, text = ''): ActionSpec | null {
+export function startSpec(id: StartId, nowMs: number, text = '', observeKey?: (present: boolean) => void): ActionSpec | null {
switch (id) {
case 'init':
return {
@@ -85,8 +86,13 @@ export function startSpec(id: StartId, nowMs: number, text = ''): ActionSpec | n
return {
label: 'join the open federation with your own key (makes ~/.ruflo/nostr.key, registers on x.ruv.io: network)',
args: ['federation', 'join'],
- expect: 'a nostr key and a registration',
- verify: snapshot => snapshot.hasNostrKey === true,
+ expect: 'a local Nostr key (the CLI reports registration separately)',
+ verifyLocal: async host => {
+ const home = await host.home().catch(() => undefined)
+ const present = home === undefined ? false : await host.fs.stat(under(home, NOSTR_KEY)).then(stat => stat !== undefined, () => false)
+ observeKey?.(present)
+ return present
+ },
}
case 'channel-read':
return { label: 'read the pub:announce channel (network)', args: ['federation', 'channel', '--action', 'read', '--channel', 'pub:announce', '--limit', '10'], expect: 'the latest announcements', isReadOnly: true }
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index 1ce128f152..1108675af7 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -174,6 +174,8 @@ export type State = {
options: Options
cwd: string
home: string | null
+ /** Session evidence from a confirmed JOIN, kept without background key access. */
+ nostrKeyVerifiedAtMs: number | null
/** Claude Code's config directory: `$CLAUDE_CONFIG_DIR`, else `~/.claude`. Its plugin records are read from here. */
configDir: string | null
/** False in a session with no pane to show (claude -p, an SDK host): views are then answered as text. */
@@ -300,6 +302,7 @@ export function newState(raw: PluginOptions | undefined): State {
options: optionsOf(raw),
cwd: '',
home: null,
+ nostrKeyVerifiedAtMs: null,
configDir: null,
isInteractive: true,
loadedAtMs: Date.now(),
diff --git a/plugins/ruflo-console/hooks/views/attention.ts b/plugins/ruflo-console/hooks/views/attention.ts
index fd14a05ab8..0479a5195d 100644
--- a/plugins/ruflo-console/hooks/views/attention.ts
+++ b/plugins/ruflo-console/hooks/views/attention.ts
@@ -65,8 +65,9 @@ const keyOfElement = (element: unknown): string | null => {
* one that holds the origin's element gets the panel after that child. Otherwise the kit is returned as it is, so a quiet page costs
* nothing extra. Which element was pressed is recorded by the `ui.press` and `ui.input` hooks (register.ts), not here.
*/
-export function wrapKit(kit: Ctx['kit'], _state: State, attention: Attention): Ctx['kit'] {
- if (attention.key === null) return kit
+export function wrapKit(kit: Ctx['kit'], state: State, attention: Attention): Ctx['kit'] {
+ // A headless ask still needs its inline confirm tracked, so the pane can fall back when that section is folded.
+ if (attention.key === null && state.pending === null) return kit
const Box: Ctx['kit']['Box'] = props => {
const kids = flat((props as { children?: unknown }).children)
diff --git a/plugins/ruflo-console/hooks/views/federation.ts b/plugins/ruflo-console/hooks/views/federation.ts
index 2be3d9ee18..adab0165bc 100644
--- a/plugins/ruflo-console/hooks/views/federation.ts
+++ b/plugins/ruflo-console/hooks/views/federation.ts
@@ -22,13 +22,17 @@ export function federationView(ctx: Ctx): RenderElement {
rows.push(text(ctx, '● pinned peer or own key: solid · channel: dashed', { dimColor: true }))
rows.push(text(ctx, '○ roster member: sparse, unvetted · a dot runs an edge for 2 s after a sync', { dimColor: true }))
rows.push(rule(ctx, 'This node', 'local only'))
+ const confirmed = snap?.hasNostrKey === null && state.nostrKeyVerifiedAtMs !== null
+ const present = confirmed
+ ? `confirmed by JOIN ${ago(state.nostrKeyVerifiedAtMs, nowMs)} (never read here)`
+ : '~/.ruflo/nostr.key present (never read here)'
rows.push(
kv(
ctx,
'nostr identity',
- snap?.hasNostrKey === true ? '~/.ruflo/nostr.key present (never read here)' : snap?.hasNostrKey === false ? 'none yet (join below makes one)' : 'n/a',
- snap?.hasNostrKey === true ? THEME.ok : undefined,
+ snap?.hasNostrKey === true || confirmed ? present : snap?.hasNostrKey === false ? 'none yet (join below makes one)' : 'n/a',
+ snap?.hasNostrKey === true || confirmed ? THEME.ok : undefined,
),
)
rows.push(kv(ctx, 'federation keys', nodes === null ? 'n/a — no .claude-flow/federation' : nodes.length === 0 ? 'none' : `${nodes.length} node ids: ${nodes.slice(0, 4).join(', ')}${nodes.length > 4 ? ' …' : ''} (keys never read)`))
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index b9dae826a9..a682e7716d 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -20,7 +20,7 @@ import { isBooting, isCompactPane, NAV_STYLES, VIEWS, type ViewId } from '../sta
import { agentView } from './agent'
import { automateResult, automateView } from './automate'
import { claimsView } from './claims'
-import { ago, button, clip, col, confirmInline, confirmRow, isBbs, row, setLook, text, THEME, type Ctx } from './common'
+import { ago, button, clip, col, confirmRow, isBbs, row, setLook, text, THEME, type Ctx } from './common'
import { costView } from './cost'
import { evolveResult, evolveView } from './evolve'
import { catalogView } from './plugin-catalog'
@@ -218,18 +218,21 @@ function footer(ctx: Ctx, isPlaced = false): RenderElement {
{ id: 'help', full: 'Help', short: 'h', priority: 3 },
{ id: 'close', full: 'Close', short: '×', priority: 4 },
]
- const fit = fitFooter(items, ctx.columns - 2)
+ // Keep the focus state whole: a clipped "keys …" does not tell the person where their typing will go.
+ const fit = fitFooter(items, ctx.columns - 2, isBbs() && state.snapshot !== null ? 23 : 10)
const press: Record<string, () => void> = { palette: () => ctx.act.palette('all'), actions: () => ctx.act.palette('selection'), 'ask-claude': () => ctx.act.ask.ask(), 'ask-slash': () => ctx.act.ask.slash(), refresh: ctx.act.restart, help: ctx.act.help, close: ctx.act.close }
const hotkey: Record<string, string> = { palette: 'p', actions: 'x', refresh: 'r', help: 'h' }
const full = new Map(items.map(item => [item.id, item.full]))
const statusRoom = Math.max(10, ctx.columns - fit.used - 3)
+ const focusLabel = !state.pane.isFocused && keys.length + 25 > statusRoom ? 'keys off' : keys
+ const syncRoom = Math.max(0, statusRoom - 9 - focusLabel.length - 1)
// BBS: the link in colour ([LINK OK] green, how fresh the read is, whether the keys are on); plain: one dim line, as before.
const status =
isBbs() && state.snapshot !== null
? [
ctx.kit.Text({ bold: true, color: THEME.ok, children: '[LINK OK]' }),
- ctx.kit.Text({ dimColor: true, children: clip(` ▸ sync ${ago(state.snapshot.readAtMs, nowMs).replace(' ago', '')} · `, Math.max(4, statusRoom - 9)) }),
- ctx.kit.Text({ bold: state.pane.isFocused, color: state.pane.isFocused ? THEME.ok : THEME.warn, children: clip(`${keys} `, Math.max(4, statusRoom - 28)) }),
+ ...(syncRoom === 0 ? [] : [ctx.kit.Text({ dimColor: true, children: clip(` ▸ sync ${ago(state.snapshot.readAtMs, nowMs).replace(' ago', '')} · `, syncRoom) })]),
+ ctx.kit.Text({ bold: state.pane.isFocused, color: state.pane.isFocused ? THEME.ok : THEME.warn, children: `${focusLabel} ` }),
]
: [text(ctx, `${clip(`${read} · ${keys}`, statusRoom)} `, { dimColor: true })]
@@ -403,6 +406,8 @@ export function paneView(base: Ctx): RenderElement {
// Placed under what was clicked: not drawn again at the top.
const confirm = attention.placed ? null : confirmRow(ctx)
+ // An inline view may fold away its confirm, or be covered by Help. Suppress the fallback only when the body actually drew it.
+ const hasInlineConfirm = attention.keys.get(body)?.has('confirm') === true
const header = ctx.pictures.get('header')
const isCompact = isCompactPane(ctx.state)
// The logo banner leads the main menu in every layout, compact too (the other pages lead with their own title art there).
@@ -417,11 +422,11 @@ export function paneView(base: Ctx): RenderElement {
// The confirm row sits above the body in both layouts: below it, a tall view would push the question off the screen.
// Compact keeps every page's title and its line of purpose; only the banner and the spacing go. The title leads, then the tabs, as in the wide layout.
const parts = isCompact
- ? [...(ctx.state.view === 'menu' && title.length > 0 ? title : bbs.art), ...(about !== null ? [about] : []), tabs(ctx), ...(confirm !== null && !confirmInline(ctx.state.view, ctx.state.pending?.scope) ? [confirm] : []), footer(ctx, attention.placed), body]
+ ? [...(ctx.state.view === 'menu' && title.length > 0 ? title : bbs.art), ...(about !== null ? [about] : []), tabs(ctx), ...(confirm !== null && !hasInlineConfirm ? [confirm] : []), footer(ctx, attention.placed), body]
: !isMenu && isBbs()
? // Every page but the main menu leads with its own title and purpose line; the welcome line and network links follow, with a blank row between the blocks.
- [...bbs.art, ...(about !== null ? [about] : []), ...(cardsOn ? [] : [...gap, ...bbs.strip, ...gap]), tabs(ctx), ...(cardsOn ? [] : gap), footer(ctx, attention.placed), ...(confirm !== null && !isTerminal && !confirmInline(ctx.state.view, ctx.state.pending?.scope) ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : [])]
- : [...title, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...bbs.strip, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...gap, tabs(ctx), ...gap, ...(isMenu && isBbs() ? [] : [...bbs.art, ...(about !== null ? [about] : [])]), ...gap, ...(isMenu ? [] : [footer(ctx, attention.placed)]), ...(confirm !== null && !isTerminal && !confirmInline(ctx.state.view, ctx.state.pending?.scope) ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : []), ...gap, ...(isMenu ? [footer(ctx, attention.placed)] : [])]
+ [...bbs.art, ...(about !== null ? [about] : []), ...(cardsOn ? [] : [...gap, ...bbs.strip, ...gap]), tabs(ctx), ...(cardsOn ? [] : gap), footer(ctx, attention.placed), ...(confirm !== null && !isTerminal && !hasInlineConfirm ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : [])]
+ : [...title, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...bbs.strip, ...(isMenu && isBbs() ? [text(ctx, ' ')] : []), ...gap, tabs(ctx), ...gap, ...(isMenu && isBbs() ? [] : [...bbs.art, ...(about !== null ? [about] : [])]), ...gap, ...(isMenu ? [] : [footer(ctx, attention.placed)]), ...(confirm !== null && !isTerminal && !hasInlineConfirm ? [confirm] : []), body, ...(confirm !== null && isTerminal ? [confirm] : []), ...gap, ...(isMenu ? [footer(ctx, attention.placed)] : [])]
// The leading rows that sit beside the icons: the header art (one picture) and the line that says what the page is for; on the menu, the banner and the blank row under it.
const lead = isCompact
@@ -484,4 +489,3 @@ export function viewText(ctx: Omit<Ctx, 'kit' | 'pictures'>, view: ViewId): stri
return out.map(line => line.trimEnd()).filter(line => line !== '').join('\n')
}
-
diff --git a/plugins/ruflo-console/hooks/views/steps.ts b/plugins/ruflo-console/hooks/views/steps.ts
index f551806f41..f4ffe8ee6a 100644
--- a/plugins/ruflo-console/hooks/views/steps.ts
+++ b/plugins/ruflo-console/hooks/views/steps.ts
@@ -101,7 +101,9 @@ export function stepsRows(ctx: Ctx): RenderElement[] {
if (plan === undefined || snapshot === null || ctx.state.palette.isOpen || ctx.state.isHelp) return []
- const done = plan.steps.map(step => step.done?.(snapshot) === true)
+ // A JOIN receipt completes this card only; unknown current key status must still ask before a read can create a key.
+ const done = plan.steps.map(step => step.done?.(snapshot) === true ||
+ ('start' in step.go && step.go.start === 'federation-join' && snapshot.hasNostrKey === null && ctx.state.nostrKeyVerifiedAtMs !== null))
const checkable = plan.steps.filter(step => step.done !== undefined).length
// Every step the disk can check is done (and there is at least one): the card has done its job.
diff --git a/plugins/ruflo-console/hooks/views/xruv.ts b/plugins/ruflo-console/hooks/views/xruv.ts
index 4079d6ec7b..7d3ae407c2 100644
--- a/plugins/ruflo-console/hooks/views/xruv.ts
+++ b/plugins/ruflo-console/hooks/views/xruv.ts
@@ -73,8 +73,12 @@ function identityRows(ctx: Ctx, lead: number): RenderElement[] {
const hasKey = state.snapshot?.hasNostrKey ?? null
const reg = live<Registry>(state.probes.get('registry'))?.registration
const rows: RenderElement[] = [rule(ctx, 'Identity', 'your own key · the file is never read')]
+ const confirmed = hasKey === null && state.nostrKeyVerifiedAtMs !== null
+ const present = confirmed
+ ? `confirmed by JOIN ${ago(state.nostrKeyVerifiedAtMs, ctx.nowMs)} (never read here)`
+ : 'present: ~/.ruflo/nostr.key (never read here)'
- rows.push(kv(ctx, 'nostr key', hasKey === null ? 'n/a' : hasKey ? 'present: ~/.ruflo/nostr.key (never read here)' : 'none yet: JOIN makes ~/.ruflo/nostr.key', hasKey === true ? THEME.ok : undefined))
+ rows.push(kv(ctx, 'nostr key', hasKey || confirmed ? present : hasKey === null ? 'n/a' : 'none yet: JOIN makes ~/.ruflo/nostr.key', hasKey || confirmed ? THEME.ok : undefined))
rows.push(kv(ctx, 'pubkey', state.xruv.pubkey !== null ? `${state.xruv.pubkey.slice(0, 16)}…${state.xruv.pubkey.slice(-6)}` : 'n/a — named by the next JOIN, ACCEPT or PUBLISH result'))
rows.push(kv(ctx, 'registration', reg === undefined ? 'n/a — open or closed is in the registry (▸ fetch below)' : `${reg.isOpen ? 'open' : 'closed'}${reg.auth !== undefined ? ` · ${reg.auth}` : ''} · JOIN checks membership first and registers only if needed`, reg?.isOpen === true ? THEME.ok : undefined))
diff --git a/plugins/ruflo-console/tests/attention.spec.ts b/plugins/ruflo-console/tests/attention.spec.ts
new file mode 100644
index 0000000000..ea6b10e8fb
--- /dev/null
+++ b/plugins/ruflo-console/tests/attention.spec.ts
@@ -0,0 +1,76 @@
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { newState, type State } from '../hooks/state'
+import { setLook, type Ctx } from '../hooks/views/common'
+import { paneView } from '../hooks/views/pane'
+
+type El = { kind: string; props: Record<string, unknown> }
+const make = (kind: string) => (props: Record<string, unknown>): El => ({ kind, props })
+const kit = { Box: make('Box'), Text: make('Text'), Button: make('Button'), Input: make('Input') }
+const act = (() => {
+ const proxy: unknown = new Proxy(() => undefined, { get: (_target, key) => key === 'then' ? undefined : proxy, apply: () => undefined })
+
+ return proxy
+})() as Ctx['act']
+const flat = (node: unknown): El[] => {
+ 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 keys = (tree: unknown): string[] => flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.key))
+const draw = (state: State, columns: number) => paneView({ kit, state, act, columns, nowMs: 1_000, pictures: new Map() } as unknown as Ctx)
+const asking = (origin: string | null): State => {
+ const state = newState({ boot: false })
+
+ state.view = 'memory'
+ state.origin = origin
+ state.memoryLab.origin = 'agentdb'
+ state.pending = { view: 'memory', scope: 'mem:agentdb', label: 'consolidate memories', args: ['mcp', 'exec', '-t', 'agentdb_consolidate'], expect: 'the result', askedAtMs: 1_000 }
+
+ return state
+}
+
+afterEach(() => setLook('plain'))
+
+describe('an inline ask is always reachable', () => {
+ for (const origin of [null, 'mem-lab-mem-consolidate']) {
+ for (const columns of [36, 120]) {
+ it(`draws one confirm while the memory group is open or folded, origin ${origin}, at ${columns} columns`, () => {
+ const state = asking(origin)
+
+ expect(keys(draw(state, columns)).filter(key => key === 'confirm')).toHaveLength(1)
+ state.sections.add('memory/mem-g-agentdb')
+
+ const folded = keys(draw(state, columns))
+
+ expect(folded).not.toContain('mem-lab-mem-consolidate')
+ expect(folded.filter(key => key === 'confirm')).toHaveLength(1)
+ expect(folded.filter(key => key === 'cancel')).toHaveLength(1)
+ })
+ }
+ }
+
+ it('keeps the ask reachable while Help covers the view, then restores its inline placement once', () => {
+ const state = asking('mem-lab-mem-consolidate')
+
+ state.isHelp = true
+ expect(keys(draw(state, 120)).filter(key => key === 'confirm')).toHaveLength(1)
+ state.isHelp = false
+ expect(keys(draw(state, 120)).filter(key => key === 'confirm')).toHaveLength(1)
+ })
+
+ it('shows a way back to the pending ask when the new view normally draws its own confirms', () => {
+ const state = asking('mem-lab-mem-consolidate')
+
+ state.view = 'missions'
+
+ const away = keys(draw(state, 120))
+
+ expect(away).toContain('confirm-go')
+ expect(away).not.toContain('confirm')
+ expect(away.filter(key => key === 'cancel')).toHaveLength(1)
+ })
+})
diff --git a/plugins/ruflo-console/tests/attention.test.ts b/plugins/ruflo-console/tests/attention.test.ts
index 87419cf0bd..5105138144 100644
--- a/plugins/ruflo-console/tests/attention.test.ts
+++ b/plugins/ruflo-console/tests/attention.test.ts
@@ -26,9 +26,10 @@ async function opened($: Body[0], on: Body[1], view: string) {
}
describe('attention: the ask and its answer sit under what was clicked', () => {
- for (const [view, key] of [['metaharness', 'lab-mh-flywheel-run'], ['devtools', 'dt-llm-hnsw']] as const) {
+ for (const [view, key, section] of [['metaharness', 'lab-mh-flywheel-run', 'sec-mh-evolve'], ['devtools', 'dt-llm-hnsw', 'sec-dt-ruvllm']] as const) {
test(`${view}: the confirm is the next thing after ${key}, the result follows it, and nothing is drawn twice`, { options: { boot: false } }, async ($, on) => {
const pane = await opened($, on, view)
+ await pane.press({ key: section })
const before = keys(await pane.drawn())
const at = before.indexOf(key)
@@ -64,16 +65,21 @@ describe('attention: the ask and its answer sit under what was clicked', () => {
test('a page whose clicked row is folded away shows the confirm at the top instead, once', { options: { boot: false } }, async ($, on) => {
const pane = await opened($, on, 'memory')
- await pane.press({ key: 'mem-do-store' })
+ await pane.press({ key: 'mem-lab-mem-consolidate' })
+ expect(keys(await pane.drawn()).filter(key => key === 'confirm')).toHaveLength(1)
+ await pane.press({ key: 'sec-mem-g-agentdb' })
const tree = await pane.drawn()
- expect(keys(tree).filter(candidate => candidate === 'confirm').length).toBeLessThanOrEqual(1)
+ expect(keys(tree)).not.toContain('mem-lab-mem-consolidate')
+ expect(keys(tree).filter(candidate => candidate === 'confirm')).toHaveLength(1)
+ expect(keys(tree).indexOf('confirm')).toBeLessThan(keys(tree).indexOf('mem-do-store'))
await pane.unmount()
})
test('a headless ask (no press) is drawn at the top, above the body', { options: { boot: false } }, async ($, on) => {
const pane = await opened($, on, 'metaharness')
+ await pane.press({ key: 'sec-mh-evolve' })
await $.command.run(command('run mh-flywheel-run'))
diff --git a/plugins/ruflo-console/tests/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.ts
index c0b778324c..4f03f4895c 100644
--- a/plugins/ruflo-console/tests/behaviour.test.ts
+++ b/plugins/ruflo-console/tests/behaviour.test.ts
@@ -246,7 +246,8 @@ describe('behaviour', () => {
const band = textOf(await $.ui.render(BAND)).replace(/\n/g, '')
// Urgent first, then what is happening now (a fresh event), then the standing context.
- expect(band).toContain('ruflo · 3 to approve (q) · ⚠ 1 alert · router picked tester (60%) · 0s ago · 2 claims')
+ expect(band).toContain('ruflo · 3 to approve (q) · ⚠ 1 alert · router picked tester (60%) · 0s ago')
+ expect(band).toContain('2 claims (1 stealable)')
expect(band).not.toMatch(/0\/\d+ busy|\d patterns/)
expect(band).toContain('open console')
expect(textOf(await $.ui.render({ ...BAND, props: { ...BAND.props, hasSurvey: true } }))).toBe('engine')
diff --git a/plugins/ruflo-console/tests/devtools.test.ts b/plugins/ruflo-console/tests/devtools.test.ts
index 3385401b62..04c99a2fbe 100644
--- a/plugins/ruflo-console/tests/devtools.test.ts
+++ b/plugins/ruflo-console/tests/devtools.test.ts
@@ -31,10 +31,10 @@ describe('dev tools', () => {
mock.clock(on)
await $.session.start(SESSION)
- const { text, tree } = await drawn($, 'devtools')
+ const { text, tree } = await drawn($, 'devtools', 110, ['dt-github', 'dt-ruvllm', 'dt-managed', 'dt-maint', 'dt-result'])
for (const title of ['CAPABILITY BRAIN', 'ANALYZE · GIT DIFF', 'GITHUB & DELIVERY', 'AGENTICOW', 'WASM AGENTS', 'BROWSER', 'TERMINAL SESSIONS', 'PROVIDERS', 'PLUGIN REGISTRY', 'RUVLLM', 'DAA', 'MANAGED AGENTS', 'MAINTENANCE']) expect(text.toUpperCase()).toContain(title)
- expect(text).toMatch(/ net \n PULL REQUESTS \.+/)
+ expect(text).toMatch(/net \n PULL REQUESTS \.+/)
expect(text).toContain(' n/a ')
expect(text).toContain('nothing run yet')
expect(inputKeys(tree)).toEqual(expect.arrayContaining(['dt-field-brain-task', 'dt-field-analyze-ref', 'dt-field-browser-url', 'dt-field-terminal-cmd']))
@@ -59,6 +59,7 @@ describe('dev tools', () => {
expect(text).toContain('totalFiles: 3')
expect(runsOf('analyze_diff-stats')).toEqual([['mcp', 'exec', '-t', 'analyze_diff-stats', '-p', '{"ref":"HEAD"}']])
+ await pane.press({ key: 'sec-dt-github' })
await pane.press({ key: 'dt-gh-prs' })
text = textOf(await pane.drawn())
expect(text).toContain('Confirm: list pull requests?')
@@ -86,6 +87,7 @@ describe('dev tools', () => {
expect(world.runs.filter(argv => argv.includes('terminal_execute')).map(argv => argv.slice(4))).toEqual([['mcp', 'exec', '-t', 'terminal_execute', '-p', '{"command":"git status"}']])
expect((await $.command.run(command('run dt-wasm-gallery'))).text).toBe('✗ WASM gallery: the templates · exit 0\n ✗ Error: Failed to initialize @ruvector/rvagent-wasm')
- expect((await $.command.run(command('run dt-br-open javascript:alert(1)'))).text).toMatch(/^nothing to do: type "dt-br-open <text>"/)
+ expect((await $.command.run(command('run dt-br-open javascript:alert(1)'))).text).toMatch(/^nothing to do: url field: an http\(s\) URL/)
+ expect(world.runs.some(argv => argv.includes('browser_open'))).toBe(false)
})
})
diff --git a/plugins/ruflo-console/tests/fixtures/views.ts b/plugins/ruflo-console/tests/fixtures/views.ts
index addb2a8eca..e6fc132356 100644
--- a/plugins/ruflo-console/tests/fixtures/views.ts
+++ b/plugins/ruflo-console/tests/fixtures/views.ts
@@ -27,15 +27,16 @@ export function memoryWorld(on: Parameters<TestBody>[1]) {
}
/** Opens the console on `view` via /ruflo, waits for its probes, and answers its drawing and its Raster keys. */
-export async function drawn($: Engine, view: string, columns = 110) {
+export async function drawn($: Engine, view: string, columns = 110, sections: readonly string[] = []) {
await $.command.run(command(view))
await $.command.run(command('status'))
const pane = await $.ui.mount({ ...paneAt(columns), plugin: PLUGIN })
+ await pane.drawn()
+ for (const section of sections) await pane.press({ key: `sec-${section}` })
const tree = await pane.drawn()
await pane.unmount()
return { text: textOf(tree), tree, rasters: elementsOf(tree, 'Raster').map(keyOf) }
}
-
diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.ts
index 4db024bdef..56a45b2653 100644
--- a/plugins/ruflo-console/tests/fixtures/world.ts
+++ b/plugins/ruflo-console/tests/fixtures/world.ts
@@ -35,6 +35,8 @@ export type World = {
runs: string[][]
/** Every path the mod asked fs.read for, refused or not. */
reads: string[]
+ /** Every path the mod asked fs.stat for, including cached and refused reads. */
+ stats: string[]
inputs: string[]
/** Prompts the mod submitted to the primary session (`$.prompt.submit`). */
prompts: string[]
@@ -89,6 +91,7 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
files: all,
runs: [],
reads: [],
+ stats: [],
inputs: [],
prompts: [],
fills: [],
@@ -110,6 +113,7 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
on('session.start', ($, e) => ({ cwd: e.cwd }))
on('fs.read', ($, e) => (world.reads.push(e.path), refuse || !all.has(e.path) ? { deny: `ENOENT: ${e.path}` } : { value: all.get(e.path) as string }))
on('fs.stat', ($, e) => {
+ world.stats.push(e.path)
const text = all.get(e.path)
return refuse || text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: { kind: 'file' as const, size: text.length, mtimeMs: mtimes.get(e.path) ?? 0, isLink: false } }
diff --git a/plugins/ruflo-console/tests/missions.test.ts b/plugins/ruflo-console/tests/missions.test.ts
index cd84a9db5d..ec9e5f20f9 100644
--- a/plugins/ruflo-console/tests/missions.test.ts
+++ b/plugins/ruflo-console/tests/missions.test.ts
@@ -41,6 +41,7 @@ describe('mission control', () => {
const { pane, clock } = await opened($, on, { ...RUFLO_FILES, '.claude-flow/missions/observation.json': MISSION_OBSERVATION })
await pane.press({ key: 'mc-tab-record' })
+ await $.command.run(command('next'))
const text = textOf(await pane.drawn())
@@ -71,7 +72,7 @@ describe('mission control', () => {
expect(text).toContain('SPARC plan')
expect(text).toContain('Reproduce the problem with a failing case')
expect(text).toMatch(/Research.*→.*Build.*→.*Test.*→.*Validate.*→.*Secure.*→.*Learn/)
- expect(text).toContain('● bug fix')
+ expect(text).toContain('bug fix · standard')
expect(toolsRun(world.runs)).toEqual([])
const field = (tree: Awaited<ReturnType<typeof pane.drawn>>) => elementsOf(tree, 'Input').find(input => keyOf(input) === 'mc-goal') as { props?: { value?: string } } | undefined
@@ -79,6 +80,8 @@ describe('mission control', () => {
expect(field(await pane.drawn())?.props?.value ?? '').toBe('')
await pane.press({ key: 'mc-edit-goal' })
expect(field(await pane.drawn())?.props?.value).toBe('fix the crash when the password is empty')
+ await pane.press({ key: 'sec-options' })
+ expect(textOf(await pane.drawn())).toContain('● bug fix')
await pane.press({ key: 'mc-profile-feature' })
expect(textOf(await pane.drawn())).toContain('Specify the requirements and acceptance criteria')
await pane.unmount()
@@ -225,11 +228,12 @@ describe('mission control', () => {
await $.command.run(command())
const pane = await $.ui.mount({ ...paneAt(150), surface: 'terminal' as const, plugin: PLUGIN })
- const menu = textOf(await pane.drawn())
+ const tree = await pane.drawn()
+ const menu = textOf(tree)
expect(at(menu, 'MISSION CONTROL')).toBeGreaterThan(-1)
- expect(at(menu, 'MISSION CONTROL')).toBeLessThan(at(menu, '▓▒░ SWARM ░▒▓'))
- expect(at(menu, '(1)')).toBeLessThan(at(menu, '(2)'))
+ const entries = elementsOf(tree, 'Button').map(keyOf).filter(key => key.startsWith('menu-go-') && key !== 'menu-go-missions-top')
+ expect(entries.slice(0, 2)).toEqual(['menu-go-missions', 'menu-go-overview'])
expect(elementsOf(await pane.drawn(), 'Input').map(keyOf)).toContain('menu-goal')
await pane.input({ key: 'menu-goal', text: 'add a dark mode toggle to settings', kind: 'submit' })
diff --git a/plugins/ruflo-console/tests/palette.test.ts b/plugins/ruflo-console/tests/palette.test.ts
index 1bbdc30560..6ba84daf60 100644
--- a/plugins/ruflo-console/tests/palette.test.ts
+++ b/plugins/ruflo-console/tests/palette.test.ts
@@ -42,7 +42,7 @@ describe('palette and /ruflo', () => {
const filtered = await pane.drawn()
- expect(elementsOf(filtered, 'Button').map(keyOf).filter(key => key.startsWith('pal-'))[0]).toBe('pal-spawn-coder')
+ expect(elementsOf(filtered, 'Button').map(keyOf).filter(key => key.startsWith('pal-') && !key.startsWith('pal-kw-'))[0]).toBe('pal-spawn-coder')
await pane.press({ key: 'pal-spawn-coder' })
expect(textOf(await pane.drawn())).toMatch(/Confirm: spawn a coder agent named coder-\d+\?/)
@@ -142,6 +142,8 @@ describe('palette and /ruflo', () => {
const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })
+ expect(elementsOf(await pane.drawn(), 'Button').map(keyOf)).not.toContain('lab-mh-redblue-real')
+ await pane.press({ key: 'sec-mh-evolve' })
await pane.press({ key: 'lab-mh-redblue-real' })
const text = textOf(await pane.drawn())
@@ -154,13 +156,15 @@ describe('palette and /ruflo', () => {
await pane.unmount()
})
- test('lab: promote is never run, not even with every lab button pressed and every ask confirmed', { options: { boot: false } }, async ($, on) => {
+ test('lab: promote is never run, not even with every lab button pressed and every ask confirmed', { options: { boot: false }, timeoutMs: 30_000 }, async ($, on) => {
const world = worldOf(on, RUFLO_FILES)
mock.clock(on)
await $.session.start(SESSION)
await $.command.run(command('metaharness'))
const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })
+ await pane.press({ key: 'sec-mh-record' })
+ await pane.press({ key: 'sec-mh-evolve' })
const keys = elementsOf(await pane.drawn(), 'Button').map(keyOf).filter(key => key.startsWith('lab-mh-'))
expect(keys.length).toBeGreaterThan(20)
diff --git a/plugins/ruflo-console/tests/pane-icons.spec.ts b/plugins/ruflo-console/tests/pane-icons.spec.ts
index 79447a22a1..9418efc801 100644
--- a/plugins/ruflo-console/tests/pane-icons.spec.ts
+++ b/plugins/ruflo-console/tests/pane-icons.spec.ts
@@ -6,6 +6,7 @@
import { afterEach, describe, expect, it } from 'vitest'
import { Grid } from '../hooks/gfx/raster'
+import { readSnapshot } from '../hooks/data/snapshot'
import { newState, type ViewId } from '../hooks/state'
import { setLook, type Ctx } from '../hooks/views/common'
import { paneView } from '../hooks/views/pane'
@@ -235,6 +236,22 @@ describe('the icon row does not shrink in the host\'s flex layout', () => {
describe('a narrow pane reads cleanly', () => {
const rowOf = (grid: { columns: number; glyph: (x: number, y: number) => number }, y: number): string => Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, y))).join('')
+ it.each([44, 60, 90, 110, 140, 180])('keeps the focus state whole at %i columns, so the person knows where typing goes', async columns => {
+ const missing = async (): Promise<never> => { throw new Error('ENOENT') }
+ const snapshot = await readSnapshot({ read: missing, stat: missing, list: async () => [] }, new Map(), '/work', null, {}, Date.now())
+
+ for (const isFocused of [true, false]) {
+ const tree = draw('swarm', columns, 40, state => {
+ state.pane.isFocused = isFocused
+ state.snapshot = snapshot
+ })
+ const focus = flat(tree).find(node => node.kind === 'Text' && String(node.props.children).startsWith(isFocused ? 'keys on' : 'keys off'))
+
+ expect(focus, `focus ${isFocused}`).toBeDefined()
+ expect(String(focus?.props.children)).not.toMatch(/…\s*$/)
+ }
+ })
+
it('keeps the banner\'s title whole: the longest of version, title, shorter title that fits', async () => {
const { bannerPicture } = await import('../hooks/gfx/pictures')
diff --git a/plugins/ruflo-console/tests/setup.spec.ts b/plugins/ruflo-console/tests/setup.spec.ts
new file mode 100644
index 0000000000..a3cc876a67
--- /dev/null
+++ b/plugins/ruflo-console/tests/setup.spec.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from 'vitest'
+
+import { probeArgv, probeError, versionProbe } from '../hooks/data/cli'
+import { NOSTR_KEY, type ReaderFs } from '../hooks/data/files'
+import { readSnapshot } from '../hooks/data/snapshot'
+import { startSpec } from '../hooks/starts'
+
+const keyPath = `/home/dev/${NOSTR_KEY}`
+
+function keyFs(answer: 'present' | 'missing' | 'undefined' | 'refused') {
+ const stats: string[] = []
+ const reads: string[] = []
+ const fs: ReaderFs = {
+ stat: async path => {
+ stats.push(path)
+ if (path !== keyPath || answer === 'undefined') return undefined
+ if (answer !== 'present') throw new Error(answer === 'missing' ? 'ENOENT' : 'EACCES')
+ return { size: 64, mtimeMs: 1 }
+ },
+ read: async path => {
+ reads.push(path)
+ throw new Error('ENOENT')
+ },
+ list: async () => [],
+ }
+ return { fs, stats, reads }
+}
+
+describe('federation key checks', () => {
+ it('the default snapshot never stats or reads the private key, even when it exists', async () => {
+ const { fs, stats, reads } = keyFs('present')
+ const snapshot = await readSnapshot(fs, new Map(), '/work', '/home/dev', {}, 0)
+
+ expect(snapshot.hasNostrKey).toBeNull()
+ expect(stats).not.toContain(keyPath)
+ expect(reads).not.toContain(keyPath)
+ })
+
+ it.each(['present', 'missing', 'undefined', 'refused'] as const)('the explicit federation option checks %s without reading key contents', async answer => {
+ const { fs, stats, reads } = keyFs(answer)
+ const snapshot = await readSnapshot(fs, new Map(), '/work', '/home/dev', {}, 0, undefined, true)
+
+ expect(snapshot.hasNostrKey).toBe(answer === 'present')
+ expect(stats.filter(path => path === keyPath)).toHaveLength(1)
+ expect(reads).not.toContain(keyPath)
+ })
+
+ it('turning federation off clears the key observation and stops further checks', async () => {
+ const { fs, stats } = keyFs('present')
+ const cache = new Map()
+
+ expect((await readSnapshot(fs, cache, '/work', '/home/dev', {}, 0, undefined, true)).hasNostrKey).toBe(true)
+ stats.length = 0
+ expect((await readSnapshot(fs, cache, '/work', '/home/dev', {}, 1, undefined, false)).hasNostrKey).toBeNull()
+ expect(stats).not.toContain(keyPath)
+ })
+
+ it.each(['present', 'missing', 'undefined', 'refused'] as const)('the consented join verifies %s once without enabling background key checks', async answer => {
+ const { fs, stats, reads } = keyFs(answer)
+ const spec = startSpec('federation-join', 0)
+
+ expect(await spec?.verifyLocal?.({ fs, home: async () => '/home/dev' })).toBe(answer === 'present')
+ expect(stats).toEqual([keyPath])
+ expect(reads).toEqual([])
+ stats.length = 0
+ expect((await readSnapshot(fs, new Map(), '/work', '/home/dev', {}, 0)).hasNostrKey).toBeNull()
+ expect(stats).not.toContain(keyPath)
+ })
+})
+
+describe('offline CLI setup guidance', () => {
+ const argv = probeArgv(versionProbe, 'npx-offline')
+ const result = { exitCode: 1, stdout: '', stderr: 'npm warn unrelated warning\nnpm error code ENOTCACHED\nnpm error cache mode is only-if-cached' }
+
+ it('an empty offline cache names the explicit command that installs the CLI without changing probe argv', () => {
+ expect(probeError(argv, result)).toBe('ruflo CLI not cached; run: npx -y @claude-flow/cli@latest --version')
+ expect(argv).toEqual(['npx', '--offline', '-y', '@claude-flow/cli@latest', '--version'])
+ })
+
+ it('recognizes the cache failure when npm writes it to stdout', () => {
+ expect(probeError(argv, { ...result, stdout: result.stderr, stderr: '' })).toContain('ruflo CLI not cached')
+ })
+
+ it('keeps other failures and failures from non-Ruflo commands accurate', () => {
+ expect(probeError(argv, { ...result, stderr: 'npm error code EACCES' })).toBe('exit 1: npm error code EACCES')
+ expect(probeError(['npx', '--offline', 'other-cli'], result)).not.toContain('ruflo CLI not cached')
+ expect(probeError(['ruflo', '--version'], result)).not.toContain('ruflo CLI not cached')
+ expect(probeError(argv, { ...result, exitCode: 0 })).toBe('no JSON in the CLI output')
+ })
+})
diff --git a/plugins/ruflo-console/tests/setup.test.ts b/plugins/ruflo-console/tests/setup.test.ts
new file mode 100644
index 0000000000..9cd333d008
--- /dev/null
+++ b/plugins/ruflo-console/tests/setup.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, mock, test } from 'claude-code/testing'
+
+import { RUFLO_FILES } from './fixtures/ruflo-run'
+import { cliAnswer, command, HOME, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'
+
+describe('first-time setup', () => {
+ test('an empty offline CLI cache shows an explicit install command and never retries online', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+ world.respond = argv => argv[0] === 'npx'
+ ? { exitCode: 1, stdout: '', stderr: 'npm warn unrelated warning\nnpm error code ENOTCACHED' }
+ : cliAnswer(argv)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.command.run(command('overview'))
+
+ const pane = await $.ui.mount({ ...paneAt(160), plugin: PLUGIN })
+ const text = textOf(await pane.drawn())
+
+ expect(text).toContain('ruflo CLI not cached')
+ expect(text).toContain('npx -y @claude-flow/cli@latest --version')
+ expect(text).not.toContain('npm error code ENOTCACHED')
+ const runs = world.runs.filter(argv => argv[0] === 'npx')
+ expect(runs.length).toBeGreaterThan(0)
+ expect(runs.every(argv => argv.includes('--offline'))).toBe(true)
+ await pane.unmount()
+ })
+
+ for (const present of [true, false]) {
+ test(`a confirmed federation join verifies key presence ${present} once while background federation is off`, { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES, { home: present ? { '.ruflo/nostr.key': 'never read this private key' } : {} })
+ world.respond = argv => argv.includes('federation') && argv.includes('join')
+ ? { exitCode: 0, stdout: 'joined', stderr: '' }
+ : cliAnswer(argv)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.command.run(command('run federation-join'))
+
+ const keyStats = () => world.stats.filter(path => path === `${HOME}/.ruflo/nostr.key`)
+ const joins = () => world.runs.filter(argv => argv.includes('federation') && argv.includes('join'))
+
+ expect(keyStats()).toEqual([])
+ expect(joins()).toEqual([])
+ await $.command.run(command('yes'))
+ expect(joins()).toHaveLength(1)
+ expect(keyStats()).toHaveLength(1)
+
+ const pane = await $.ui.mount({ ...paneAt(160), plugin: PLUGIN })
+ const text = textOf(await pane.drawn())
+
+ expect(text).toContain(present ? ' · on disk' : ' · not on disk yet')
+ expect(world.reads).not.toContain(`${HOME}/.ruflo/nostr.key`)
+ await $.command.run(command('status'))
+ expect(keyStats()).toHaveLength(1)
+ if (present) {
+ await $.command.run(command('federation'))
+ const federation = textOf(await pane.drawn())
+ expect(federation).toContain('confirmed by JOIN')
+ expect(federation).not.toMatch(/Start here: Join the federation/i)
+ expect(keyStats()).toHaveLength(1)
+
+ // A receipt is display evidence, not proof the key still exists: a later read may create it again.
+ world.files.delete(`${HOME}/.ruflo/nostr.key`)
+ await $.command.run(command('status'))
+ await $.command.run(command('xruv'))
+ expect(textOf(await pane.drawn())).toContain('confirmed by JOIN')
+ await $.command.run(command('run x-read pub:general'))
+ expect(textOf(await pane.drawn())).toContain('Confirm: read x.ruv.io channel pub:general?')
+ expect(world.runs.some(argv => argv.includes('x_federation_channel_read'))).toBe(false)
+ expect(keyStats()).toHaveLength(1)
+ await $.command.run(command('no'))
+ }
+ await pane.unmount()
+ })
+ }
+
+ test('cancelled and failed joins never inspect the private key', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES, { home: { '.ruflo/nostr.key': 'never read this private key' } })
+ world.respond = argv => argv.includes('federation') && argv.includes('join')
+ ? { exitCode: 1, stdout: '', stderr: 'relay unavailable' }
+ : cliAnswer(argv)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.command.run(command('run federation-join'))
+ await $.command.run(command('no'))
+ expect(world.runs.some(argv => argv.includes('join'))).toBe(false)
+ await $.command.run(command('run federation-join'))
+ await $.command.run(command('yes'))
+ expect(world.runs.filter(argv => argv.includes('join'))).toHaveLength(1)
+ expect(world.stats.some(path => path.endsWith('nostr.key'))).toBe(false)
+ expect(world.reads.some(path => path.endsWith('nostr.key'))).toBe(false)
+ })
+})
diff --git a/plugins/ruflo-console/tests/skills-secure.test.ts b/plugins/ruflo-console/tests/skills-secure.test.ts
index 60fb121811..b0c0549815 100644
--- a/plugins/ruflo-console/tests/skills-secure.test.ts
+++ b/plugins/ruflo-console/tests/skills-secure.test.ts
@@ -77,11 +77,11 @@ describe('skills, security and performance', () => {
mock.clock(on)
await $.session.start(SESSION)
- const { text, tree } = await drawn($, 'secure')
+ const { text, tree } = await drawn($, 'secure', 110, ['sec-scan', 'sec-doctor'])
for (const section of ['FINDINGS', 'CHECK TEXT', 'SCAN & INSPECT', 'DOCTOR', 'RESULT']) expect(text).toContain(section)
expect(text).toContain('nothing run yet')
- expect(text).toMatch(/n\/a {2}VALIDATE/)
+ expect(text).toMatch(/n\/a\s+VALIDATE/)
expect(inputKeys(tree)).toEqual(['sec-text'])
expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['run-sec-scan-quick', 'run-sec-threats', 'run-doc-all', 'run-doc-fix', 'run-doc-node', 'run-aid-pii', 'run-policy-status']))
expect(ours()).toEqual([])
@@ -132,6 +132,7 @@ describe('skills, security and performance', () => {
await pane.press({ key: 'run-perf-metrics' })
expect(textOf(await pane.drawn())).toMatch(/event loop\s+\n?▁█/)
+ await pane.press({ key: 'sec-perf-record' })
await pane.press({ key: 'run-perf-report' })
expect(textOf(await pane.drawn())).toContain('runs: ruflo mcp exec -t performance_report -p {"format":"detailed"}')
expect(world.runs.some(argv => argv.includes('performance_report'))).toBe(false)
diff --git a/plugins/ruflo-console/tests/sweep.test.ts b/plugins/ruflo-console/tests/sweep.test.ts
index c1b6203e38..dfe6e534ad 100644
--- a/plugins/ruflo-console/tests/sweep.test.ts
+++ b/plugins/ruflo-console/tests/sweep.test.ts
@@ -11,11 +11,11 @@ const SCROLL = /^(prev|next|up|down|older|newer|page|older-|newer-|refresh|close
describe('every button does something', () => {
for (const view of VIEWS) {
- test(`${view}: pressing each button changes the screen, asks, or runs one thing`, { options: { boot: false } }, async ($, on) => {
+ test(`${view}: pressing each button changes the screen, asks, or runs one thing`, { options: { boot: false }, timeoutMs: 30_000 }, async ($, on) => {
const world = worldOf(on, RUFLO_FILES)
world.respond = argv => cliAnswer(argv)
- mock.clock(on)
+ const clock = mock.clock(on)
await $.session.start(SESSION)
await $.command.run(command(view))
@@ -29,6 +29,7 @@ describe('every button does something', () => {
const before = textOf(await pane.drawn())
const runs = world.runs.length
+ const stats = world.stats.length
try {
await pane.press({ key })
@@ -39,13 +40,45 @@ describe('every button does something', () => {
continue
}
+ // Refresh can leave cached data and the text unchanged, but must ask the filesystem again. Let its async read start,
+ // without issuing /ruflo status (which would itself refresh and hide a broken button).
+ if (key === 'pane-icon-refresh' || key === 'refresh') for (let i = 0; i < 6; i++) await clock.advance(0)
const after = textOf(await pane.drawn())
- if (after === before && world.runs.length === runs && !SCROLL.test(key)) dead.push(key)
+ if (after === before && world.runs.length === runs && world.stats.length === stats && !SCROLL.test(key)) dead.push(key)
}
await pane.unmount()
expect(dead).toEqual([])
})
}
+
+ test('the refresh icon reads changed disk data on a view with no CLI probes, without a status command', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+ const clock = mock.clock(on)
+
+ await $.session.start(SESSION)
+ await $.command.run(command('swarm'))
+
+ const pane = await $.ui.mount({ ...paneAt(140), plugin: PLUGIN })
+
+ expect(textOf(await pane.drawn())).not.toContain('refreshed-coder')
+ const store = JSON.parse(RUFLO_FILES['.claude-flow/agents/store.json'] as string) as { agents: Record<string, { name: string }> }
+ ;(Object.values(store.agents)[0] as { name: string }).name = 'refreshed-coder'
+ world.put('.claude-flow/agents/store.json', JSON.stringify(store))
+ const before = world.reads.length
+ const runsBefore = world.runs.length
+ await pane.press({ key: 'pane-icon-refresh' })
+
+ let refreshed = ''
+ for (let i = 0; i < 10 && !refreshed.includes('refreshed-coder'); i++) {
+ await clock.advance(5)
+ refreshed = textOf(await pane.drawn())
+ }
+
+ expect(world.reads.slice(before)).toContain('/work/.claude-flow/agents/store.json')
+ expect(refreshed).toContain('refreshed-coder')
+ expect(world.runs).toHaveLength(runsBefore)
+ await pane.unmount()
+ })
})
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index 20e2af7c39..512b57dcb1 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -180,7 +180,9 @@ describe('views', () => {
mock.clock(on)
await $.session.start(SESSION)
- const { text, rasters } = await drawn($, 'learning')
+ const folded = await drawn($, 'learning')
+ expect(folded.rasters).toEqual(['title', 'curve'])
+ const { text, rasters } = await drawn($, 'learning', 110, ['learn-pipeline'])
expect(rasters).toEqual(['title', 'curve', 'pipeline', 'patterns'])
expect(text).toContain('tester 60% · keyword match')
@@ -193,7 +195,9 @@ describe('views', () => {
mock.clock(on)
await $.session.start(SESSION)
- const { text, rasters } = await drawn($, 'metaharness')
+ const folded = await drawn($, 'metaharness')
+ expect(folded.rasters).toEqual(['title', 'radar'])
+ const { text, rasters } = await drawn($, 'metaharness', 110, ['mh-trend'])
expect(rasters).toEqual(['title', 'radar', 'trend'])
expect(text).toContain('$0.024')
@@ -206,7 +210,7 @@ describe('views', () => {
mock.clock(on)
await $.session.start(SESSION)
- const { text, tree } = await drawn($, 'metaharness')
+ const { text, tree } = await drawn($, 'metaharness', 110, ['mh-record', 'mh-evolve', 'mh-promote'])
const buttons = elementsOf(tree, 'Button').map(keyOf)
expect(text).toMatch(/LAB · INSPECT/i)
@@ -215,7 +219,7 @@ describe('views', () => {
expect(text).toContain('ruflo metaharness flywheel promote <receipt-id> --public-key <approved-ed25519.pem> --confirm')
expect(text).toContain('nothing run yet')
expect(buttons).toEqual(expect.arrayContaining(['lab-mh-genome', 'lab-mh-mcp-scan', 'lab-mh-audit', 'lab-mh-redblue-real', 'lab-mh-learn-run', 'lab-mh-flywheel-run']))
- expect(buttons.some(key => /promote/.test(key))).toBe(false)
+ expect(buttons.some(key => key.startsWith('lab-') && /promote/.test(key))).toBe(false)
// Drawing the lab runs nothing but the view's own probes.
expect(world.runs.some(argv => /genome|mcp-scan|redblue|evolve|learn/.test(argv.join(' ')))).toBe(false)
})
@@ -305,7 +309,7 @@ describe('views', () => {
})
test('main menu: bare /ruflo lands on it in the BBS look; its prompt takes a key or a name', { options: { boot: false } }, async ($, on) => {
- worldOf(on, RUFLO_FILES)
+ const world = worldOf(on, RUFLO_FILES)
mock.clock(on)
await $.session.start(SESSION)
await $.command.run(command())
@@ -313,15 +317,16 @@ describe('views', () => {
const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
const menu = await pane.drawn()
- expect(elementsOf(menu, 'Raster').map(keyOf)).toEqual(['header'])
+ expect(elementsOf(menu, 'Raster').map(keyOf)).toEqual(['header', 'palette'])
expect(textOf(menu)).toContain('▓▒░ SWARM ░▒▓')
- expect(textOf(menu)).toContain('── live')
+ expect(textOf(menu)).toContain('── start here')
expect(textOf(menu)).toContain('Swarm Topology')
expect(textOf(menu)).toContain('ANSI-BBS')
expect(inputKeys(menu)).toEqual(['menu-goal', 'menu-prompt'])
await pane.input({ key: 'menu-prompt', text: 'w', kind: 'submit' })
- expect(textOf(await pane.drawn())).toContain('MAIN MENU')
+ expect(textOf(await pane.drawn()).toLowerCase()).toContain('x.ruv.io')
+ expect(world.stored.get('ruflo-console/ui:/work')).toMatchObject({ view: 'xruv' })
await pane.press({ key: 'tab-menu' })
await pane.input({ key: 'menu-prompt', text: 'nope', kind: 'submit' })
@@ -391,6 +396,7 @@ describe('views', () => {
const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
+ await pane.press({ key: 'sec-nn-train' })
await pane.press({ key: 'run-nn-train-coordination-20' })
const asked = textOf(await pane.drawn())
diff --git a/plugins/ruflo-console/tests/xruv.test.ts b/plugins/ruflo-console/tests/xruv.test.ts
index 183d4c5f6f..a8e23be702 100644
--- a/plugins/ruflo-console/tests/xruv.test.ts
+++ b/plugins/ruflo-console/tests/xruv.test.ts
@@ -43,11 +43,12 @@ describe('x.ruv.io board', () => {
expect(inputKeys(tree)).toEqual(expect.arrayContaining(['xr-in-x-bbs-register', 'xr-in-x-bbs-publish', 'xr-in-x-bbs-watch', 'xr-in-x-bbs-peer-add', 'xr-in-x-bbs-sync']))
expect(inputKeys(tree)).toEqual(expect.arrayContaining(['xr-in-x-join', 'xr-in-x-read', 'xr-in-x-publish', 'xr-in-x-create', 'xr-in-x-grant']))
expect(text).toContain(' JOIN ....')
- expect(text).toContain('present: ~/.ruflo/nostr.key (never read here)')
+ expect(text).not.toContain('present: ~/.ruflo/nostr.key')
expect(text).toContain('unregister: not offered by the x.ruv.io gateway yet')
expect(text).toContain('admin token: set it in the environment to enable')
expect(text).toContain('Turn on federationNetwork in /config')
expect(fedRuns(world.runs)).toEqual([])
+ expect(world.stats.some(path => path.endsWith('nostr.key'))).toBe(false)
expect(world.reads.some(path => path.endsWith('nostr.key') || path.endsWith('channels.json'))).toBe(false)
await pane.unmount()
})
diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.md
index b249ad423a..a818e569a1 100644
--- a/plugins/ruflo-mods/README.md
+++ b/plugins/ruflo-mods/README.md
@@ -60,7 +60,7 @@ In a session, `/ruflo mods` (through ruflo-console's `/ruflo`) reports what the
## What it does
-- **Routing:** `prompt.submit` routes each prompt in-process and hands the route, plus ranked memory, to the model as context. The text is the same as the classic `route` hook produces.
+- **Routing:** in an initialized Ruflo project (an existing `.claude-flow/` directory), `prompt.submit` routes each prompt in-process and hands the route, plus ranked memory, to the model as context. The text is the same as the classic `route` hook produces.
- **Edit learning:** `tool.call` records finished edits for the intelligence consolidator, once per turn.
- **Tool checks:** `tool.check` only tightens. It applies the dangerous-command list and ruflo policy rules that name `claude-code.*` actions (written by the CLI to `.claude-flow/policy/claude-code.json`). It never loosens a verdict.
- **Trust gate:** `plugin.register` names what a later-installed mod can do (host commands, network, environment, tool verdicts) and, under `modTrust: refuse-risky`, refuses it unless allow-listed.
@@ -69,6 +69,8 @@ In a session, `/ruflo mods` (through ruflo-console's `/ruflo`) reports what the
The classic `hook-handler.cjs` hooks stay installed and remain the fallback. The mod takes an event only where the classic helper hands it over (`RUFLO_MODS_OWNS`), so nothing fires twice. When the mod is not loaded, every classic hook runs as before.
+At user scope, an unrelated project receives no routing context, edit-learning writes or `.claude-flow/mods/session.json` heartbeat. The mod does not initialize projects itself. Tool guards, trust checks and explicitly configured budgets remain active there.
+
## Options
Claude Code reads a plugin's options from `pluginConfigs["ruflo-mods@ruflo"].options` in user settings, `--settings` or managed settings. Project settings are not read for this. Every option has a default:
diff --git a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts
index 3d17e29d34..3d8a762f07 100644
--- a/plugins/ruflo-mods/hooks/guard/dangerous-command.ts
+++ b/plugins/ruflo-mods/hooks/guard/dangerous-command.ts
@@ -1,12 +1,83 @@
import type { Verdict } from './verdict'
/**
- * The commands hook-handler.cjs `pre-bash` refuses, matched the same way
- * (lowercased substring). The parity test reads the list out of
- * hook-handler.cjs and fails CI if the two drift.
+ * The commands hook-handler.cjs `pre-bash` refuses. The root-delete entry
+ * matches a root operand, not the prefix of every absolute path. The parity
+ * tests exercise the same commands against the mod and classic helpers.
*/
export const DANGEROUS_COMMANDS: readonly string[] = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:']
+// Keep this literal-word scanner in sync with the classic helpers/fallback.
+// It joins quote fragments and escapes, but never evaluates expansions or links.
+function hasRootDelete(command: string, depth = 0): boolean {
+ let word = '', quote = '', started = false, redirect = false
+ let inRm = false, optionsEnded = false, recursive = false, force = false, root = false
+ const isRoot = (operand: string) => {
+ if (!operand.startsWith('/')) return false
+ const parts: string[] = []
+ for (const part of operand.split('/')) {
+ if (!part || part === '.') continue
+ if (part === '..') parts.pop()
+ else parts.push(part)
+ }
+ return parts.length === 0 || /[*?\[]/.test(parts[0])
+ }
+ const finishWord = () => {
+ if (!started) return false
+ // Literal shell strings (e.g. sh -c 'rm -rf /') also carried the old guard.
+ // Bound rescanning to four levels; beyond that retain its conservative check.
+ if (word.includes('rm') && /[\s;&|()]/.test(word)) {
+ if (depth < 4 ? hasRootDelete(word, depth + 1) : word.includes('rm -rf /')) return true
+ }
+ if (!inRm) inRm = word === 'rm' || word.endsWith('/rm')
+ else if (!optionsEnded && word === '--') optionsEnded = true
+ else if (!optionsEnded && word.startsWith('-')) {
+ recursive = recursive || word === '--recursive' || /^-[a-z]*r[a-z]*$/.test(word)
+ force = force || word === '--force' || /^-[a-z]*f[a-z]*$/.test(word)
+ } else root = root || isRoot(word)
+ word = ''; started = false
+ return inRm && recursive && force && root
+ }
+ const finishCommand = () => {
+ const denied = inRm && recursive && force && root
+ inRm = optionsEnded = recursive = force = root = false
+ return denied
+ }
+ for (let i = 0; i < command.length; i++) {
+ const char = command[i]
+ const redirectionAmpersand = char === '&' && (redirect || command[i + 1] === '>')
+ redirect = false
+ if (quote) {
+ if (char === quote) quote = ''
+ else if (quote === '"' && char === '\\' && i + 1 < command.length &&
+ (command[i + 1] === '"' || command[i + 1] === '\\' || command[i + 1] === '$' ||
+ command.charCodeAt(i + 1) === 96 || command[i + 1] === '\n')) {
+ const next = command[++i]
+ if (next !== '\n') word += next
+ } else word += char
+ continue
+ }
+ if (char === '\\' && i + 1 < command.length) {
+ const next = command[++i]
+ if (next !== '\n') { word += next; started = true }
+ } else if (char === '"' || char === "'") {
+ quote = char; started = true
+ } else if (char === '#' && !started) {
+ while (i < command.length && command[i] !== '\n') i++
+ if (finishCommand()) return true
+ } else if (char === ' ' || char === '\t' || char === '\r' || char === '\n' ||
+ ';|&()<>'.includes(char)) {
+ if (finishWord()) return true
+ // Redirections separate words, but later operands still belong to rm.
+ redirect = char === '<' || char === '>'
+ if (!redirectionAmpersand && (char === '\n' || ';|&()'.includes(char)) && finishCommand()) return true
+ } else {
+ word += char; started = true
+ }
+ }
+ return finishWord() || finishCommand()
+}
+
/**
* A deny for a Bash call whose command is on the list, else undefined.
*
@@ -19,7 +90,7 @@ export function dangerousCommandVerdict(tool: string, input: unknown): Verdict |
// Same belt-and-braces as #2017: a non-string command is checked as text,
// never skipped.
const command = String(raw ?? '').toLowerCase()
- const hit = DANGEROUS_COMMANDS.find(d => command.includes(d))
+ const hit = DANGEROUS_COMMANDS.find(d => d === 'rm -rf /' ? hasRootDelete(command) : command.includes(d))
return hit === undefined
? undefined
: { decision: 'deny', reason: `ruflo: dangerous command blocked (${hit})` }
diff --git a/plugins/ruflo-mods/hooks/route/format.ts b/plugins/ruflo-mods/hooks/route/format.ts
index 0d3c369b64..094da27bed 100644
--- a/plugins/ruflo-mods/hooks/route/format.ts
+++ b/plugins/ruflo-mods/hooks/route/format.ts
@@ -11,13 +11,14 @@ export function formatRoute(prompt: string, result: RouteResult): string {
// The structured result says `no-match-default` (#3567); the box keeps the
// classic wording, so the text the model reads is the same on both paths.
const reason = result.matched ? result.reason : 'Default routing - no specific keyword matched'
+ const row = (text: string) => `| ${text.substring(0, 60).padEnd(60)} |`
return [
`[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,
'',
'+------------------- Primary Recommendation -------------------+',
- `| Agent: ${result.agent.padEnd(53)}|`,
- `| Confidence: ${(result.confidence * 100).toFixed(1)}%${' '.repeat(44)}|`,
- `| Reason: ${reason.substring(0, 53).padEnd(53)}|`,
+ row(`Agent: ${result.agent}`),
+ row(`Confidence: ${(result.confidence * 100).toFixed(1)}%`),
+ row(`Reason: ${reason}`),
'+--------------------------------------------------------------+',
].join('\n')
}
diff --git a/plugins/ruflo-mods/hooks/session.ts b/plugins/ruflo-mods/hooks/session.ts
index d424b57df3..d463d41b16 100644
--- a/plugins/ruflo-mods/hooks/session.ts
+++ b/plugins/ruflo-mods/hooks/session.ts
@@ -46,16 +46,22 @@ function hasClassicStatusLine(settings: unknown): boolean {
export function registerSession(on: On, state: ModState, options: ModOptions) {
on('session.start', async ($, e, next) => {
state.root = await $.session.root()
+ // A user-scoped install loads in every project. Existing Ruflo state is
+ // the opt-in boundary: a missing, unreadable or non-directory path must
+ // neither own project events nor be created by the display heartbeat.
+ const project = await $.fs.stat(under(state, '.claude-flow')).then(stat => stat.kind === 'dir').catch(() => false)
const settings = await $.settings.read()
- state.owned = new Set(ownedEvents(settings, await helperHonours($)))
+ state.owned = new Set(project ? ownedEvents(settings, await helperHonours($)) : [])
await $.env.set('RUFLO_MODS_OWNS', state.owned.size ? [...state.owned].join(',') : undefined)
state.statusLine = options.statusLine && !hasClassicStatusLine(settings)
redraw(state)
await $.command
.register({ name: 'ruflo-mods', description: 'Same as /ruflo mods: what this session routed, recorded and tightened' })
.catch(() => undefined)
- const heartbeat = { startedAt: new Date().toISOString(), owned: [...state.owned], statusLine: state.statusLine }
- await $.fs.write(under(state, HEARTBEAT_PATH), `${JSON.stringify(heartbeat, null, 2)}\n`).catch(() => undefined)
+ if (project) {
+ const heartbeat = { startedAt: new Date().toISOString(), owned: [...state.owned], statusLine: state.statusLine }
+ await $.fs.write(under(state, HEARTBEAT_PATH), `${JSON.stringify(heartbeat, null, 2)}\n`).catch(() => undefined)
+ }
return next(e)
}).catch(async ($, e, next) => {
state.owned = new Set()
diff --git a/plugins/ruflo-mods/tests/fixtures/world.ts b/plugins/ruflo-mods/tests/fixtures/world.ts
index 0df2026441..366cec25f5 100644
--- a/plugins/ruflo-mods/tests/fixtures/world.ts
+++ b/plugins/ruflo-mods/tests/fixtures/world.ts
@@ -7,6 +7,7 @@ import type { On } from 'claude-code'
*/
export type World = {
readonly files: Map<string, string>
+ readonly dirs: Set<string>
readonly env: Map<string, string>
readonly statuses: (string | undefined)[]
readonly logs: string[]
@@ -17,7 +18,7 @@ export const ROOT = '/work'
export const HELPER = `${ROOT}/.claude/helpers/hook-handler.cjs`
export function world(on: On, settings: unknown = {}, files: Record<string, string> = {}): World {
- const w: World = { files: new Map(Object.entries(files)), env: new Map(), statuses: [], logs: [], commands: [] }
+ const w: World = { files: new Map(Object.entries(files)), dirs: new Set([ROOT, `${ROOT}/.claude-flow`]), env: new Map(), statuses: [], logs: [], commands: [] }
on('session.start', ($, e) => ({ cwd: e.cwd }))
on('session.root', () => ({ value: ROOT }))
@@ -28,9 +29,10 @@ export function world(on: On, settings: unknown = {}, files: Record<string, stri
else w.env.set(e.name, e.value)
return { value: undefined }
})
- on('fs.exists', ($, e) => ({ value: w.files.has(e.path) }))
+ on('fs.exists', ($, e) => ({ value: w.files.has(e.path) || w.dirs.has(e.path) }))
on('fs.stat', ($, e) => {
const text = w.files.get(e.path)
+ if (text === undefined && w.dirs.has(e.path)) return { value: { kind: 'dir', size: 0, mtimeMs: 0, isLink: false } }
if (text === undefined) return { deny: `ENOENT: no such file or directory, '${e.path}'` }
return { value: { kind: 'file', size: text.length, mtimeMs: text.length, isLink: false } }
})
diff --git a/plugins/ruflo-mods/tests/register.test.ts b/plugins/ruflo-mods/tests/register.test.ts
index ae7ec67efb..244aa66efd 100644
--- a/plugins/ruflo-mods/tests/register.test.ts
+++ b/plugins/ruflo-mods/tests/register.test.ts
@@ -42,6 +42,35 @@ describe('register', () => {
expect(JSON.parse(w.files.get(`${ROOT}/.claude-flow/mods/session.json`) ?? '{}').owned).toEqual(['route', 'post-edit'])
})
+ test('a user-scoped mod does not inject routing or create state in an unrelated project; its guard stays active', async ($, on) => {
+ const w = world(on)
+ w.dirs.delete(`${ROOT}/.claude-flow`)
+ w.env.set('RUFLO_MODS_OWNS', 'route,post-edit')
+ let context: readonly string[] | undefined
+ on('prompt.submit', ($, e) => ((context = e.context), { text: e.text }))
+ on('tool.call', () => ({ result: 'edited' }))
+ on('turn.complete', ($, e) => ({ text: e.answer }))
+ on('tool.check', () => ({ decision: 'allow' }))
+
+ await $.session.start(START)
+ await $.prompt.submit(prompt('review this code'))
+ await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/a.ts`, old_string: 'a', new_string: 'b' })
+ await $.turn.complete({ answer: 'done', durationMs: 1, isAborted: false, turnId: 't1', reason: 'answer' })
+
+ expect(context).toBeUndefined()
+ expect(w.env.has('RUFLO_MODS_OWNS')).toBe(false)
+ expect(w.files.size).toBe(0)
+ expect((await $.tool.check({ tool: 'Bash', input: { command: 'rm -rf /' } })).decision).toBe('deny')
+ })
+
+ test('a file named .claude-flow does not enable project event ownership or a heartbeat', async ($, on) => {
+ const w = world(on, {}, { [`${ROOT}/.claude-flow`]: 'not a directory' })
+ await $.session.start(START)
+
+ expect(w.env.has('RUFLO_MODS_OWNS')).toBe(false)
+ expect(w.files.size).toBe(1)
+ })
+
test('stands down where a classic helper too old for the handshake runs route', async ($, on) => {
const w = world(on, CLASSIC_ROUTE, { [HELPER]: '// an older helper' })
let context: readonly string[] | undefined
diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txt
index 34ac2fd56b..8f6b348b15 100644
--- a/scripts/ci-test-baseline.txt
+++ b/scripts/ci-test-baseline.txt
@@ -182,3 +182,4 @@ plugins/ruflo-console/tests/skills-secure.test.ts
plugins/ruflo-console/tests/xruv.test.ts
plugins/ruflo-console/tests/steps.test.ts
plugins/ruflo-console/tests/nav.test.ts
+plugins/ruflo-console/tests/setup.test.ts
diff --git a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
index 24635591a7..3fda14ca1a 100755
--- a/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
+++ b/v3/@claude-flow/cli/.claude/helpers/hook-handler.cjs
@@ -388,13 +388,14 @@ const handlers = {
if (router && router.routeTask) {
const result = router.routeTask(prompt);
// Format output for Claude Code hook consumption — real data only
+ const row = (text) => `| ${text.substring(0, 60).padEnd(60)} |`;
const output = [
`[INFO] Routing task: ${prompt.substring(0, 80) || '(no prompt)'}`,
'',
'+------------------- Primary Recommendation -------------------+',
- `| Agent: ${result.agent.padEnd(53)}|`,
- `| Confidence: ${(result.confidence * 100).toFixed(1)}%${' '.repeat(44)}|`,
- `| Reason: ${(result.reason || '').substring(0, 53).padEnd(53)}|`,
+ row(`Agent: ${result.agent}`),
+ row(`Confidence: ${(result.confidence * 100).toFixed(1)}%`),
+ row(`Reason: ${result.reason || ''}`),
'+--------------------------------------------------------------+',
];
console.log(output.join('\n'));
@@ -462,8 +463,77 @@ const handlers = {
// (silently exiting 0 and letting the dangerous command through).
const cmd = String(hookInput.command || toolInput.command || prompt || '').toLowerCase();
const dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\', ':(){:|:&};:'];
+ // Join literal quote fragments and normalize root paths without shell evaluation.
+ function hasRootDelete(command, depth = 0) {
+ let word = '', quote = '', started = false, redirect = false
+ let inRm = false, optionsEnded = false, recursive = false, force = false, root = false
+ const isRoot = (operand) => {
+ if (!operand.startsWith('/')) return false
+ const parts = []
+ for (const part of operand.split('/')) {
+ if (!part || part === '.') continue
+ if (part === '..') parts.pop()
+ else parts.push(part)
+ }
+ return parts.length === 0 || /[*?\[]/.test(parts[0])
+ }
+ const finishWord = () => {
+ if (!started) return false
+ // Literal shell strings (e.g. sh -c 'rm -rf /') also carried the old guard.
+ // Bound rescanning to four levels; beyond that retain its conservative check.
+ if (word.includes('rm') && /[\s;&|()]/.test(word)) {
+ if (depth < 4 ? hasRootDelete(word, depth + 1) : word.includes('rm -rf /')) return true
+ }
+ if (!inRm) inRm = word === 'rm' || word.endsWith('/rm')
+ else if (!optionsEnded && word === '--') optionsEnded = true
+ else if (!optionsEnded && word.startsWith('-')) {
+ recursive = recursive || word === '--recursive' || /^-[a-z]*r[a-z]*$/.test(word)
+ force = force || word === '--force' || /^-[a-z]*f[a-z]*$/.test(word)
+ } else root = root || isRoot(word)
+ word = ''; started = false
+ return inRm && recursive && force && root
+ }
+ const finishCommand = () => {
+ const denied = inRm && recursive && force && root
+ inRm = optionsEnded = recursive = force = root = false
+ return denied
+ }
+ for (let i = 0; i < command.length; i++) {
+ const char = command[i]
+ const redirectionAmpersand = char === '&' && (redirect || command[i + 1] === '>')
+ redirect = false
+ if (quote) {
+ if (char === quote) quote = ''
+ else if (quote === '"' && char === '\\' && i + 1 < command.length &&
+ (command[i + 1] === '"' || command[i + 1] === '\\' || command[i + 1] === '$' ||
+ command.charCodeAt(i + 1) === 96 || command[i + 1] === '\n')) {
+ const next = command[++i]
+ if (next !== '\n') word += next
+ } else word += char
+ continue
+ }
+ if (char === '\\' && i + 1 < command.length) {
+ const next = command[++i]
+ if (next !== '\n') { word += next; started = true }
+ } else if (char === '"' || char === "'") {
+ quote = char; started = true
+ } else if (char === '#' && !started) {
+ while (i < command.length && command[i] !== '\n') i++
+ if (finishCommand()) return true
+ } else if (char === ' ' || char === '\t' || char === '\r' || char === '\n' ||
+ ';|&()<>'.includes(char)) {
+ if (finishWord()) return true
+ // Redirections separate words, but later operands still belong to rm.
+ redirect = char === '<' || char === '>'
+ if (!redirectionAmpersand && (char === '\n' || ';|&()'.includes(char)) && finishCommand()) return true
+ } else {
+ word += char; started = true
+ }
+ }
+ return finishWord() || finishCommand()
+ }
for (const d of dangerous) {
- if (cmd.includes(d)) {
+ if (d === 'rm -rf /' ? hasRootDelete(cmd) : cmd.includes(d)) {
console.error(`[BLOCKED] Dangerous command detected: ${d}`);
// Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.
process.exit(2);
diff --git a/v3/@claude-flow/cli/__tests__/mods/harness.ts b/v3/@claude-flow/cli/__tests__/mods/harness.ts
index 406bb24f13..684b1a3138 100644
--- a/v3/@claude-flow/cli/__tests__/mods/harness.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/harness.ts
@@ -29,6 +29,8 @@ export interface World {
root: string;
/** Real files under `root`, or an in-memory map of absolute path → text. */
files: 'real' | Map<string, { text: string; mtimeMs: number }>;
+ /** In-memory directories; initialized projects have a .claude-flow directory. */
+ dirs: Set<string>;
env: Map<string, string>;
settings: unknown | (() => unknown);
statuses: (string | undefined)[];
@@ -37,15 +39,16 @@ export interface World {
commands: string[];
/** Per-op failure injection: `fs.read` → error to throw for a path. */
failRead?: (path: string) => Error | undefined;
+ failStat?: (path: string) => Error | undefined;
failLog?: boolean;
}
export function memoryWorld(root = '/work', settings: unknown = {}): World {
- return { root, files: new Map(), env: new Map(), settings, statuses: [], logs: [], toasts: [], commands: [] };
+ return { root, files: new Map(), dirs: new Set([root, `${root}/.claude-flow`]), env: new Map(), settings, statuses: [], logs: [], toasts: [], commands: [] };
}
export function realWorld(root: string, settings: unknown = {}): World {
- return { root, files: 'real', env: new Map(), settings, statuses: [], logs: [], toasts: [], commands: [] };
+ return { root, files: 'real', dirs: new Set(), env: new Map(), settings, statuses: [], logs: [], toasts: [], commands: [] };
}
const enoent = (path: string) => Object.assign(new Error(`ENOENT: no such file or directory, '${path}'`), { code: 'ENOENT' });
@@ -55,8 +58,11 @@ function engineOf(world: World) {
return {
fs: {
async stat(path: string) {
+ const injected = world.failStat?.(path);
+ if (injected) throw injected;
if (mem) {
const f = mem.get(path);
+ if (!f && world.dirs.has(path)) return { kind: 'dir', size: 0, mtimeMs: 1, isLink: false };
if (!f) throw enoent(path);
return { kind: 'file', size: Buffer.byteLength(f.text), mtimeMs: f.mtimeMs, isLink: false };
}
@@ -85,7 +91,7 @@ function engineOf(world: World) {
writeFileSync(path, text);
},
async exists(path: string) {
- return mem ? mem.has(path) : existsSync(path);
+ return mem ? mem.has(path) || world.dirs.has(path) : existsSync(path);
},
},
env: {
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
index 4f9531a956..f1470bfabb 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cli-bin.test.ts
@@ -44,7 +44,9 @@ describe.skipIf(!CLI_BUILT)('ADR-404 mods through the built CLI', () => {
// No marketplace clone in this isolated config yet: a warning (Claude
// Code clones it at its next interactive start), not a failure.
- const status = JSON.parse(t.run('mods', 'status', '--json').replace(/^[^[]*/, ''));
+ // Startup integrity warnings begin with [WARN]; the JSON array begins on its own line.
+ const statusOutput = t.run('mods', 'status', '--json');
+ const status = JSON.parse(statusOutput.match(/^\[\s*\n[\s\S]*^\]$/m)?.[0] ?? statusOutput);
const named = (name: string) => status.find((f: { name: string }) => f.name === name);
expect(named('ruflo-mods plugin').status).toBe('pass'); // enabled in settings
expect(named('ruflo marketplace')).toMatchObject({ status: 'warn', fix: expect.stringContaining('--scope project') });
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
index be2b48cea1..fe81a58af8 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-guard.test.ts
@@ -3,16 +3,19 @@
* every chain verdict, the fail-closed paths, ruflo policy modes, and parity
* with the real policy evaluator and hook-handler.cjs pre-bash list.
*/
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { ruleMatches as engineRuleMatches, type PolicyRule, type PolicyRequest } from '@claude-flow/security';
import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
-import { DANGEROUS_COMMANDS } from '../../../../../plugins/ruflo-mods/hooks/guard/dangerous-command';
+import { DANGEROUS_COMMANDS, dangerousCommandVerdict } from '../../../../../plugins/ruflo-mods/hooks/guard/dangerous-command';
import { parseProjection, ruleMatches, toolRequest, type ProjectedRule } from '../../../../../plugins/ruflo-mods/hooks/guard/policy';
import { stricter } from '../../../../../plugins/ruflo-mods/hooks/guard/verdict';
import { loadMod, memoryWorld, type World } from './harness';
+import { generateHookHandler } from '../../src/init/helpers-generator';
const HELPERS = join(resolve(__dirname, '../..'), '.claude', 'helpers');
const PROJECTION = '/work/.claude-flow/policy/claude-code.json';
@@ -199,3 +202,116 @@ describe('ADR-404 parity', () => {
expect(compared).toBeGreaterThan(10_000);
});
});
+
+describe('#3698 root deletion guard parity', () => {
+ let project: string;
+ let fallback: string;
+ const helpers = [
+ join(HELPERS, 'hook-handler.cjs'),
+ resolve(HELPERS, '../../../../../.claude/helpers/hook-handler.cjs'),
+ ];
+ beforeAll(() => {
+ project = mkdtempSync(join(tmpdir(), 'ruflo-root-guard-'));
+ fallback = join(project, 'hook-handler.cjs');
+ writeFileSync(fallback, generateHookHandler());
+ });
+ afterAll(() => rmSync(project, { recursive: true, force: true }));
+
+ // Only hook helpers run. These command strings are inert stdin JSON data.
+ const cases: Array<[string, boolean]> = [
+ ['rm -rf /tmp/ruflo-test', false],
+ ['rm -rf /var/tmp/ruflo-test', false],
+ ['sudo RM -RF /tmp/ruflo-test', false],
+ ['rm -rf "/tmp/ruflo test"', false],
+ ["rm -rf '/tmp/ruflo-test'", false],
+ ['rm -rf /tmp/*', false],
+ ['rm -rf /tmp/""', false],
+ ["rm -rf /tmp/''", false],
+ ['rm -rf "/tmp"/"ruflo test"', false],
+ ['rm -rf /tmp/scratch/../test', false],
+ ['rm -rf "/tmp;folder"', false],
+ ['rm -rf /tmp/ruflo-test; printf /', false],
+ ['rm -rf /tmp/ruflo-test && printf /', false],
+ ['rm -rf /tmp/ruflo-test & printf /', false],
+ ['rm -rf /tmp 2>&1 & printf /', false],
+ ['rm -rf /tmp 2>&1 && printf /', false],
+ ['rm -rf /tmp &>/dev/null && printf /', false],
+ ['rm -rf /tmp > /tmp/log & printf /', false],
+ ['rm -rf /tmp \\> & printf /', false],
+ ['rm -rf /tmp/ruflo-test\nprintf /', false],
+ ['rm -rf ./temporary', false],
+ ['rm -rf /tmp/ruflo-test # ignored /', false],
+ ['sh -c "rm -rf /tmp/ruflo-test"', false],
+ ['rm -rf /', true],
+ ['rm -rf /"" --no-preserve-root', true],
+ ["rm -rf /'' --no-preserve-root", true],
+ ['rm -rf /""*', true],
+ ["rm -rf /''*", true],
+ ['rm -rf ""/""', true],
+ ["rm -rf ''/''", true],
+ ['rm -rf "/""/"', true],
+ ["rm -rf '/'\"\"'/'", true],
+ ['rm -rf /\\\n --no-preserve-root', true],
+ ['rm -rf /\\\n*', true],
+ ['rm -rf "/\\\n"*', true],
+ ['rm -rf /tmp/../ --no-preserve-root', true],
+ ['rm -rf /tmp/../*', true],
+ ['rm -rf /tmp/nested/../../', true],
+ ['rm -rf "/tmp"/../*', true],
+ ['rm -rf /tmp/../""*', true],
+ ['rm -rf /tmp > /tmp/log /', true],
+ ['rm -rf /tmp 2>&1 / --no-preserve-root', true],
+ ['rm -rf /tmp &>/dev/null / --no-preserve-root', true],
+ ['rm -rf /tmp 1>/tmp/log 2>&1 / --no-preserve-root', true],
+ ['rm -rf /tmp &>>/dev/null / --no-preserve-root', true],
+ ['rm -rf /tmp 0<&0 / --no-preserve-root', true],
+ ['rm -rf "/tmp;folder" /', true],
+ ['sh -c "rm -rf /"', true],
+ ["sh -c 'rm -rf /'", true],
+ ["sh -c \"echo 'rm -rf /tmp'; rm -rf /\"", true],
+ ['sudo RM -RF / --no-preserve-root', true],
+ ['/bin/rm -rf /', true],
+ ['rm -rf --no-preserve-root /', true],
+ ['rm -rf /tmp/ruflo-test /', true],
+ ['rm -rf /tmp/ruflo-test; rm -rf /', true],
+ ['rm -rf //', true],
+ ['rm -rf /./', true],
+ ['rm -rf /../', true],
+ ['rm -rf "/"', true],
+ ["rm -rf '/'", true],
+ ['rm -fr /', true],
+ ['rm -r -f /', true],
+ ['rm --recursive --force /', true],
+ ['rm -rf /*', true],
+ ['rm -rf /.*', true],
+ ['rm -rf /**', true],
+ ['rm -rf /[a-z]*', true],
+ ['rm -rf /;printf ok', true],
+ ['rm -rf /&&printf ok', true],
+ ['rm -rf /||printf ok', true],
+ ['rm -rf /|cat', true],
+ ['(rm -rf /)', true],
+ ['rm -rf /\nprintf ok', true],
+ ['format c: /q /y', true],
+ ['del /s /q c:\\', true],
+ [':(){:|:&};:', true],
+ ];
+ function expectParity(command: string, denied: boolean) {
+ expect(dangerousCommandVerdict('Bash', { command })?.decision === 'deny').toBe(denied);
+ for (const helper of [...helpers, fallback]) {
+ const result = spawnSync(process.execPath, [helper, 'pre-bash'], {
+ input: JSON.stringify({ tool_name: 'Bash', tool_input: { command } }),
+ cwd: project, encoding: 'utf8', timeout: 10_000,
+ env: { PATH: process.env.PATH, HOME: project, CI: '1', RUFLO_MODS_OWNS: 'route,post-edit,pre-bash' },
+ });
+ expect(result.error, helper).toBeUndefined();
+ expect(result.status, `${helper}: ${result.stderr}`).toBe(denied ? 2 : 0);
+ expect(denied ? result.stderr : result.stdout).toContain(denied ? '[BLOCKED]' : '[OK] Command validated');
+ }
+ }
+ it.each(cases)('%j: denied=%s in mod, shipped helpers and fallback', expectParity);
+
+ it('scans a 60 KB safe cleanup input without losing classic/fallback parity', () => {
+ expectParity('rm -rf /tmp '.repeat(5000), false);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
index ff28c29203..ee3e30f962 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-ownership.test.ts
@@ -29,9 +29,9 @@ const CLASSIC = {
async function start(world: World, options: Record<string, unknown> = {}) {
const mod = loadMod(register, world, options);
- await mod.create(); // the engine runs the engine.create fold before any other hook
+ const built = await mod.create(); // the engine runs the engine.create fold before any other hook
const next = await mod.dispatch('session.start', { cwd: world.root, surface: 'terminal', isInteractive: true }, (e) => ({ cwd: e.cwd }));
- return { mod, next };
+ return { mod, next, built };
}
describe('ADR-404 ownership rule', () => {
@@ -56,6 +56,50 @@ describe('ADR-404 ownership rule', () => {
});
describe('ADR-404 session start', () => {
+ it.each(['missing', 'file'] as const)('does not route, learn or create project state when .claude-flow is %s', async (kind) => {
+ const project = mkdtempSync(join(tmpdir(), 'ruflo-mods-uninitialized-'));
+ const home = mkdtempSync(join(tmpdir(), 'ruflo-mods-initialized-home-'));
+ try {
+ if (kind === 'file') writeFileSync(join(project, '.claude-flow'), 'not a directory');
+ mkdirSync(join(home, '.claude-flow'));
+ const world = realWorld(project);
+ world.env.set('HOME', home);
+ world.env.set('RUFLO_MODS_OWNS', 'route,post-edit');
+ const before = readdirSync(project);
+ const { mod, next, built } = await start(world);
+ expect(next).toEqual({ cwd: project });
+ expect(world.env.has('RUFLO_MODS_OWNS')).toBe(false);
+
+ const original = { text: 'review this code', context: ['existing context'], wait: false, origin: { kind: 'composer' } };
+ expect(await mod.dispatch('prompt.submit', original, (e) => e)).toEqual(original);
+ await mod.dispatch('tool.call', { tool: 'Edit', file_path: join(project, 'a.ts') }, () => ({ result: 'edited' }));
+ await mod.dispatch('turn.complete', { reason: 'answer' }, () => ({ text: 'done' }));
+ await mod.dispatch('session.end', {}, () => ({ ended: true }));
+ expect(await built.ruflo.snapshot()).toMatchObject({ owned: [], routed: 0, edits: 0, lastRoute: null });
+ expect(readdirSync(project)).toEqual(before);
+ expect(existsSync(join(project, '.claude-flow', 'mods', 'session.json'))).toBe(false);
+ expect(existsSync(join(project, '.claude-flow', 'data', 'pending-insights.jsonl'))).toBe(false);
+ // The project gate only controls side effects; the installed guard still protects this session.
+ expect(await mod.dispatch('tool.check', { tool: 'Bash', input: { command: 'rm -rf /' } }, () => ({ decision: 'allow' }))).toMatchObject({ decision: 'deny' });
+ } finally {
+ rmSync(project, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ it('owns nothing and writes no heartbeat when the project directory cannot be verified', async () => {
+ const world = memoryWorld();
+ world.failStat = (path) => path === '/work/.claude-flow' ? new Error('EACCES: permission denied') : undefined;
+ world.env.set('RUFLO_MODS_OWNS', 'route');
+ const { mod, next, built } = await start(world);
+ expect(next).toEqual({ cwd: '/work' });
+ expect(world.env.has('RUFLO_MODS_OWNS')).toBe(false);
+ expect((world.files as Map<string, unknown>).size).toBe(0);
+ const prompt = { text: 'implement the api', wait: false, origin: { kind: 'composer' } };
+ expect(await mod.dispatch('prompt.submit', prompt, (e) => e)).toEqual(prompt);
+ expect(await built.ruflo.snapshot()).toMatchObject({ owned: [], routed: 0, edits: 0 });
+ });
+
it('with a handshake-aware helper: owns both, sets RUFLO_MODS_OWNS, registers /ruflo-mods, writes a heartbeat', async () => {
const world = memoryWorld('/work', CLASSIC);
(world.files as Map<string, any>).set('/work/.claude/helpers/hook-handler.cjs', { text: '... RUFLO_MODS_OWNS ...', mtimeMs: 1 });
@@ -124,6 +168,7 @@ describe('ADR-404 no double fire with the real classic hooks', () => {
project = mkdtempSync(join(tmpdir(), 'ruflo-mods-own-'));
home = mkdtempSync(join(tmpdir(), 'ruflo-mods-own-home-'));
dedup = mkdtempSync(join(tmpdir(), 'ruflo-mods-dedup-'));
+ mkdirSync(join(project, '.claude-flow'));
mkdirSync(join(project, '.claude', 'helpers'), { recursive: true });
for (const f of ['hook-handler.cjs', 'router.cjs', 'session.cjs', 'memory.cjs', 'intelligence.cjs']) {
copyFileSync(join(PKG_HELPERS, f), join(project, '.claude', 'helpers', f));
@@ -165,6 +210,12 @@ describe('ADR-404 no double fire with the real classic hooks', () => {
expect(await promptRound('implement the api')).toBe(1);
});
+ it('outside a Ruflo project the configured classic route keeps ownership and the mod writes nothing', async () => {
+ rmSync(join(project, '.claude-flow'), { recursive: true });
+ expect(await promptRound('implement the api')).toBe(1);
+ expect(existsSync(join(project, '.claude-flow'))).toBe(false);
+ });
+
it('exactly one edit record: classic post-edit and ruflo-core post-edit stand down for the mod', async () => {
const world = realWorld(project, CLASSIC);
const { mod } = await start(world);
diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts
index 0c643c2a2c..ccf7876024 100644
--- a/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mods/mods-route.test.ts
@@ -7,7 +7,7 @@
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
import { execFileSync } from 'node:child_process';
import { createRequire } from 'node:module';
-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
@@ -16,6 +16,8 @@ vi.mock('../../src/memory/memory-bridge.js', () => ({ bridgeRouteTask: vi.fn(asy
import { NO_MATCH_CONFIDENCE as CLI_NO_MATCH } from '../../src/mcp-tools/hooks-tools.js';
import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
import { MATCH_CONFIDENCE, NO_MATCH_CONFIDENCE, routeTask, TASK_PATTERNS } from '../../../../../plugins/ruflo-mods/hooks/route/route-task';
+import { formatRoute } from '../../../../../plugins/ruflo-mods/hooks/route/format';
+import { generateHookHandler } from '../../src/init/helpers-generator';
import { loadMod, memoryWorld, realWorld } from './harness';
const CLI_ROOT = resolve(__dirname, '../..');
@@ -105,7 +107,11 @@ describe('ADR-404 mod route context equals hook-handler.cjs route output', () =>
return { text: e.text, context: e.context };
});
expect(context).toHaveLength(1);
- expect(context![0]).toBe(classicRoute(prompt));
+ const classic = classicRoute(prompt);
+ expect(context![0]).toBe(classic);
+ const box = classic.split('\n').filter((line) => /^[+|]/.test(line));
+ expect(box).toHaveLength(5);
+ expect(box.map((line) => line.length)).toEqual([64, 64, 64, 64, 64]);
});
it('adds nothing and passes the prompt through when it does not own route', async () => {
@@ -121,3 +127,31 @@ describe('ADR-404 mod route context equals hook-handler.cjs route output', () =>
expect(seen.text).toBe('build it');
});
});
+
+describe('#3698 route box width and fallback parity', () => {
+ let project: string;
+ const prompt = 'implement';
+ beforeAll(() => { project = mkdtempSync(join(tmpdir(), 'ruflo-route-width-')); });
+ afterAll(() => rmSync(project, { recursive: true, force: true }));
+
+ it.each([0, 0.6, 0.85, 1])('confidence %s keeps every row at 64 columns', (confidence) => {
+ const result = { agent: 'agent'.repeat(20), confidence, reason: 'reason '.repeat(20), matched: true };
+ const expected = formatRoute(prompt, result);
+ const lines = expected.split('\n').slice(2);
+ expect(lines).toHaveLength(5);
+ expect(lines.map((line) => line.length)).toEqual([64, 64, 64, 64, 64]);
+ expect(expected).toContain(`Confidence: ${(confidence * 100).toFixed(1)}%`);
+
+ writeFileSync(join(project, 'router.cjs'), `exports.routeTask = () => (${JSON.stringify(result)});`);
+ const sources = [readFileSync(join(HELPERS, 'hook-handler.cjs'), 'utf8'), generateHookHandler()];
+ for (const source of sources) {
+ const helper = join(project, 'hook-handler.cjs');
+ writeFileSync(helper, source);
+ const actual = execFileSync(process.execPath, [helper, 'route'], {
+ input: JSON.stringify({ prompt }), cwd: project, encoding: 'utf8',
+ env: { PATH: process.env.PATH, HOME: project, CLAUDE_PROJECT_DIR: project, CI: '1' },
+ }).trim();
+ expect(actual).toBe(expected);
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts
index 97c62b7ff7..3a95ef6075 100644
--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts
+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts
@@ -441,6 +441,76 @@ module.exports = commands;
`;
}
+// Literal-word root guard mirrored in the mod and both shipped classic helpers.
+const ROOT_DELETE_CHECK_SOURCE = String.raw`function hasRootDelete(command, depth = 0) {
+ let word = '', quote = '', started = false, redirect = false
+ let inRm = false, optionsEnded = false, recursive = false, force = false, root = false
+ const isRoot = (operand) => {
+ if (!operand.startsWith('/')) return false
+ const parts = []
+ for (const part of operand.split('/')) {
+ if (!part || part === '.') continue
+ if (part === '..') parts.pop()
+ else parts.push(part)
+ }
+ return parts.length === 0 || /[*?\[]/.test(parts[0])
+ }
+ const finishWord = () => {
+ if (!started) return false
+ // Literal shell strings (e.g. sh -c 'rm -rf /') also carried the old guard.
+ // Bound rescanning to four levels; beyond that retain its conservative check.
+ if (word.includes('rm') && /[\s;&|()]/.test(word)) {
+ if (depth < 4 ? hasRootDelete(word, depth + 1) : word.includes('rm -rf /')) return true
+ }
+ if (!inRm) inRm = word === 'rm' || word.endsWith('/rm')
+ else if (!optionsEnded && word === '--') optionsEnded = true
+ else if (!optionsEnded && word.startsWith('-')) {
+ recursive = recursive || word === '--recursive' || /^-[a-z]*r[a-z]*$/.test(word)
+ force = force || word === '--force' || /^-[a-z]*f[a-z]*$/.test(word)
+ } else root = root || isRoot(word)
+ word = ''; started = false
+ return inRm && recursive && force && root
+ }
+ const finishCommand = () => {
+ const denied = inRm && recursive && force && root
+ inRm = optionsEnded = recursive = force = root = false
+ return denied
+ }
+ for (let i = 0; i < command.length; i++) {
+ const char = command[i]
+ const redirectionAmpersand = char === '&' && (redirect || command[i + 1] === '>')
+ redirect = false
+ if (quote) {
+ if (char === quote) quote = ''
+ else if (quote === '"' && char === '\\' && i + 1 < command.length &&
+ (command[i + 1] === '"' || command[i + 1] === '\\' || command[i + 1] === '$' ||
+ command.charCodeAt(i + 1) === 96 || command[i + 1] === '\n')) {
+ const next = command[++i]
+ if (next !== '\n') word += next
+ } else word += char
+ continue
+ }
+ if (char === '\\' && i + 1 < command.length) {
+ const next = command[++i]
+ if (next !== '\n') { word += next; started = true }
+ } else if (char === '"' || char === "'") {
+ quote = char; started = true
+ } else if (char === '#' && !started) {
+ while (i < command.length && command[i] !== '\n') i++
+ if (finishCommand()) return true
+ } else if (char === ' ' || char === '\t' || char === '\r' || char === '\n' ||
+ ';|&()<>'.includes(char)) {
+ if (finishWord()) return true
+ // Redirections separate words, but later operands still belong to rm.
+ redirect = char === '<' || char === '>'
+ if (!redirectionAmpersand && (char === '\n' || ';|&()'.includes(char)) && finishCommand()) return true
+ } else {
+ word += char; started = true
+ }
+ }
+ return finishWord() || finishCommand()
+}`;
+
/**
* Generate hook-handler.cjs (cross-platform hook dispatcher)
* This is the inline fallback when file copy from the package fails.
@@ -577,13 +647,14 @@ export function generateHookHandler(): string {
' }',
' if (router && router.routeTask) {',
' const result = router.routeTask(prompt);',
+ " const row = (text) => '| ' + text.substring(0, 60).padEnd(60) + ' |';",
' var output = [];',
" output.push('[INFO] Routing task: ' + (prompt.substring(0, 80) || '(no prompt)'));",
" output.push('');",
" output.push('+------------------- Primary Recommendation -------------------+');",
- " output.push('| Agent: ' + result.agent.padEnd(53) + '|');",
- " output.push('| Confidence: ' + (result.confidence * 100).toFixed(1) + '%' + ' '.repeat(44) + '|');",
- " output.push('| Reason: ' + result.reason.substring(0, 53).padEnd(53) + '|');",
+ " output.push(row('Agent: ' + result.agent));",
+ " output.push(row('Confidence: ' + (result.confidence * 100).toFixed(1) + '%'));",
+ " output.push(row('Reason: ' + (result.reason || '')));",
" output.push('+--------------------------------------------------------------+');",
" console.log(output.join('\\n'));",
' } else {',
@@ -645,8 +716,9 @@ export function generateHookHandler(): string {
" 'pre-bash': () => {",
" var cmd = String(hookInput.command || toolInputObj.command || prompt || '').toLowerCase();",
" var dangerous = ['rm -rf /', 'format c:', 'del /s /q c:\\\\', ':(){:|:&};:'];",
+ ROOT_DELETE_CHECK_SOURCE.split('\n').map((line) => ' ' + line).join('\n'),
' for (var i = 0; i < dangerous.length; i++) {',
- ' if (cmd.includes(dangerous[i])) {',
+ " if (dangerous[i] === 'rm -rf /' ? hasRootDelete(cmd) : cmd.includes(dangerous[i])) {",
" console.error('[BLOCKED] Dangerous command detected: ' + dangerous[i]);",
' // Claude Code PreToolUse: exit 2 blocks execution; exit 1 is non-blocking.',
' process.exit(2);',