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(console): card-bound confirm, one model-facing sanitiser, linear escape stripping, own-key lookups, wrapped Approvals (0.40.2)

r3991f40670ac
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index 6fb4bbb567..4986653a4f 100644
--- a/plugins/ruflo-console/.claude-plugin/plugin.json
+++ b/plugins/ruflo-console/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",
- "version": "0.40.1",
+ "version": "0.40.2",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.md
index 0c300341f9..cc8902dba3 100644
--- a/plugins/ruflo-console/CHANGELOG.md
+++ b/plugins/ruflo-console/CHANGELOG.md
@@ -2,6 +2,14 @@
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-console`.
+## 0.40.2 — 2026-10-08
+- fix: a Yes runs only the card it was pressed on: every confirm card has an id and the Yes, Always allow and Always accept buttons carry it, so a card that took the first one's place (the person's own ask) is never answered by a Yes meant for the old one; the stale Yes runs nothing and says so (ADR-450 T17)
+- fix: an ask of Claude's that was screened first and landed after its tool call returned is checked against the level and Stop as they are when it lands; a level lowered meanwhile wins
+- fix: everything handed to the model goes through one sanitiser (modelLine: escape sequences, then control and invisible characters removed so they cannot split a credential, then invite codes masked, then the cut, then the line withheld if it holds a secret shape): failed-run details, the "already waiting" refusal, the "waiting for the person" and "started" answers, refusals that echo the model's own input, palette entry ids and thrown errors no longer quote a token or an x.ruv.io invite code; a version such as v2.1.0-beta.3 is no longer masked as an invite
+- fix: escape stripping is linear: a megabyte of unterminated OSC introducers took seconds, now milliseconds; an unterminated OSC ends at the next introducer or the end of the text
+- fix: a mission state, task status, hive role, audit severity or plugin named toString, constructor or __proto__ draws as unknown instead of as native code, and no longer throws in Settings
+- fix: Approvals and a mission's objective wrap at narrow widths (80 columns in tmux) instead of being cut with "…" (#3899)
+
## 0.40.1 — 2026-10-08
- fix: a settings write (or any confirmed ruflo CLI action) no longer aborts with "still running after 90000ms" when the CLI is not in the npm cache (#3914): with the ruflo CLI option on npx it now uses ruflo on PATH, a project-local bin, or the cached npx copy first, and only then a cold download, which gets a 5 minute limit and says "first run downloads the ruflo CLI"
- fix: a timeout or an uncached npx now ends as an error that names the fix (npm i -g ruflo, or npx -y @claude-flow/cli@latest --version once), and a retry after the cache is warm runs at once
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index c018e85b53..01d6a3aeac 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -95,7 +95,14 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
wireActivity(state, host)
const actions: Actions = {
view: setView,
- remember: () => {
+ remember: seen => {
+ // "Always allow" is the person's answer to the card they read: on a card that was replaced it remembers nothing (as a stale Yes runs nothing).
+ if (seen !== undefined && state.pending?.id !== seen) {
+ void runner.confirm(seen)
+
+ return
+ }
+
const key = state.pending?.rememberKey
if (key !== undefined && state.pending !== null) {
@@ -103,7 +110,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
saveAllowed(state, host)
}
- void runner.confirm()
+ void runner.confirm(seen)
},
forget: key => {
if (key === '') state.allowed.clear()
@@ -172,7 +179,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
},
close: () => void close(),
back: () => setView(state.view === 'agent' ? state.back : state.options.look === 'bbs' ? 'menu' : 'overview'),
- confirm: () => void runner.confirm(),
+ confirm: seen => void runner.confirm(seen),
cancel: runner.cancel,
select,
agentNext: () => {
diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts
index 0826f33097..3f8c7c4023 100644
--- a/plugins/ruflo-console/hooks/controller.ts
+++ b/plugins/ruflo-console/hooks/controller.ts
@@ -17,6 +17,7 @@ import { readSnapshot } from './data/snapshot'
import { markPicture } from './gfx/pictures'
import type { Host } from './host'
import { agentLogs } from './ops'
+import { landingRefusal } from './model-tools'
import { createRunner, type Runner } from './runner'
import { advance, loadLedger, mcOf } from './mission-control'
import { hasLiveWork } from './mission-list'
@@ -460,10 +461,9 @@ export function createController(state: State, host: Host): Controller {
}
const runner = createRunner(state, host, {
- freshRead,
- setView,
- drill,
+ freshRead, setView, drill,
command: name => (name === 'refresh' ? actions.refresh() : name === 'help' ? actions.help() : actions.close()),
+ landingRefusal: pending => landingRefusal(state, pending),
})
const actions: Actions = actionsOf(state, host, runner, { freshRead, probe, setView, drill, close, animate })
diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.ts
index ae4b3a58b2..573050a083 100644
--- a/plugins/ruflo-console/hooks/data/cli.ts
+++ b/plugins/ruflo-console/hooks/data/cli.ts
@@ -6,6 +6,7 @@
*/
import { closeOf } from './json-span'
import { idOf, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'
+import { own } from './safe'
import { researchProbe } from './research'
import { CLI_PREFIXES, type CliChoice, type State, type ViewId } from '../state'
@@ -283,7 +284,7 @@ export const auditProbe: Probe<AuditTrend> = {
}
/** A severity word as a 0-4 level, for the trend line; unknown words are null. */
-export const severityOf = (word: string | undefined): number | null => (word === undefined ? null : (SEVERITY[word.toLowerCase()] ?? null))
+export const severityOf = (word: string | undefined): number | null => (word === undefined ? null : (own(SEVERITY, word.toLowerCase()) ?? null))
export type Intelligence = { trajectories?: number; patterns?: number; successRate?: number; moeDecisions?: number; ewcConsolidations?: number; routerDecisions?: number; routerConfidence?: number; neuralRouter?: string }
diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.ts
index 8f2453e22b..4167632288 100644
--- a/plugins/ruflo-console/hooks/data/parse.ts
+++ b/plugins/ruflo-console/hooks/data/parse.ts
@@ -16,7 +16,7 @@ const ID = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/
// Whole escape sequences go first (the CLI colours its output; a hostile file may carry a hyperlink or a title): stripping only the ESC byte
// would leave `[1m` or `]8;;https://…` in the text. Written as \u escapes so no invisible character sits in this source.
-export const ESCAPES = new RegExp('\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)|\\u009d[^\\u0007\\u009c]*[\\u0007\\u009c]|(?:\\u001b\\[|\\u009b)[0-9;?]*[ -/]*[@-~]', 'g')
+export const ESCAPES = new RegExp('\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\|(?=\\u001b)|$)|\\u009d[^\\u0007\\u009c\\u009d]*(?:[\\u0007\\u009c]|(?=\\u009d)|$)|(?:\\u001b\\[|\\u009b)[0-9;?]*[ -/]*[@-~]', 'g')
// Controls, DEL, C1, soft hyphen, combining grapheme joiner, Arabic letter mark, zero-width and bidi characters, invisible operators,
// variation selectors, Hangul fillers and BOM: nothing a person could read, all of them fit for hiding or reordering text.
export const HIDDEN = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180f\\u200b-\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2060-\\u206f\\u3164\\ufe00-\\ufe0d\\ufeff\\uffa0\\ufff9-\\ufffb]|[\\u{e0000}-\\u{e0fff}]', 'gu')
diff --git a/plugins/ruflo-console/hooks/data/safe.ts b/plugins/ruflo-console/hooks/data/safe.ts
index e50a97d13a..6b1960f0d8 100644
--- a/plugins/ruflo-console/hooks/data/safe.ts
+++ b/plugins/ruflo-console/hooks/data/safe.ts
@@ -19,3 +19,6 @@ export const countOf = (value: unknown): number | undefined => (typeof value ===
/** A ratio clamped to 0..1, else undefined. */
export const ratioOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : undefined)
+
+/** A value keyed by a name a file or the CLI supplied: an OWN key only, so `toString`, `constructor` or `__proto__` read as absent, never as a function. */
+export const own = <T>(record: Readonly<Record<string, T>>, key: unknown): T | undefined => (typeof key === 'string' && Object.hasOwn(record, key) ? record[key] : undefined)
diff --git a/plugins/ruflo-console/hooks/data/wf-activity.ts b/plugins/ruflo-console/hooks/data/wf-activity.ts
index f998839d9e..0bfab53944 100644
--- a/plugins/ruflo-console/hooks/data/wf-activity.ts
+++ b/plugins/ruflo-console/hooks/data/wf-activity.ts
@@ -21,7 +21,7 @@ export type Capped = { text: string; /** Characters in the original. */ total: n
// An escape sequence goes whole (stripping only the ESC byte would leave `[1m` in the text), then controls other than the newline, soft hyphen,
// zero-width and bidi characters. Written as \u escapes so no invisible character sits in this source.
-const ANSI = new RegExp('\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)|\\u009d[^\\u0007\\u009c]*[\\u0007\\u009c]|(?:\\u001b\\[|\\u009b)[0-9;?]*[ -/]*[@-~]', 'g')
+const ANSI = new RegExp('\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\|(?=\\u001b)|$)|\\u009d[^\\u0007\\u009c\\u009d]*(?:[\\u0007\\u009c]|(?=\\u009d)|$)|(?:\\u001b\\[|\\u009b)[0-9;?]*[ -/]*[@-~]', 'g')
const HIDE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180f\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2064\\u2066-\\u2069\\u3164\\ufe00-\\ufe0d\\ufeff\\uffa0]|[\\u{e0000}-\\u{e0fff}]', 'gu')
/** Washed text for a block: escapes and controls out (the newline stays), credentials masked, cut to `cap` characters with the original length kept. */
diff --git a/plugins/ruflo-console/hooks/harness.ts b/plugins/ruflo-console/hooks/harness.ts
index 4303a076c7..0b92b47080 100644
--- a/plugins/ruflo-console/hooks/harness.ts
+++ b/plugins/ruflo-console/hooks/harness.ts
@@ -14,6 +14,7 @@ import { ESCAPES, HIDDEN, INVISIBLE } from './data/parse'
import type { Host } from './host'
import { CLI_PREFIXES, PANE_ID, push, termStoreKeyOf, type AgentId, type HarnessId, type State, type TermLine } from './state'
import { claudeParser, codexEvent, eventOf, type Sink } from './stream'
+import { maskInvites } from './xruv'
export const TERM_MAX_LINES = 600
/** The engine ends a spawned child only when its loop ends: the console ends a run at ten minutes. */
@@ -63,12 +64,14 @@ export function argvOf(state: State, agent: AgentId, text: string): readonly str
}
/**
- * One line of an agent's output as the scrollback keeps it: ANSI sequences, control and bidirectional characters
- * gone, tabs as two spaces, indentation kept. `trim` false keeps a trailing space (a token typed mid-sentence).
+ * One line of an agent's output as the scrollback keeps it: escape sequences, control, bidirectional and other invisible
+ * characters gone (the set plain() strips), tabs as two spaces, indentation kept, and any x.ruv.io invite code masked:
+ * it is a bearer secret, so neither the terminal page nor console_state ever carries one. `trim` false keeps a trailing
+ * space (a token typed mid-sentence).
*/
export function termText(line: string, max = 400, trim = true): string {
// The same strip set as plain() (data/parse.ts), so a character one drops cannot get through the other (#3816).
- const cleaned = line.replace(/\t/g, ' ').replace(ESCAPES, '').replace(INVISIBLE, '').replace(HIDDEN, '')
+ const cleaned = maskInvites(line.replace(/\t/g, ' ').replace(ESCAPES, '').replace(INVISIBLE, '').replace(HIDDEN, ''))
const out = trim ? cleaned.trimEnd() : cleaned
return out.length <= max ? out : `${out.slice(0, max - 1)}…`
diff --git a/plugins/ruflo-console/hooks/mission-list.ts b/plugins/ruflo-console/hooks/mission-list.ts
index ff3899f3fd..9d91d0fac5 100644
--- a/plugins/ruflo-console/hooks/mission-list.ts
+++ b/plugins/ruflo-console/hooks/mission-list.ts
@@ -5,6 +5,7 @@
*/
import { money, type Mission } from './data/missions'
import { spinAt } from './spinner'
+import { own } from './data/safe'
export { SPIN, spinAt } from './spinner'
@@ -73,7 +74,7 @@ const GLYPH: Record<string, string> = { completed: '●', failed: '✖', blocked
export function missionRow(mission: Mission, nowMs = 0, maxObjective = 36): string {
const objective = mission.objective === '' ? '(no objective)' : mission.objective
const cut = objective.length > maxObjective ? `${objective.slice(0, maxObjective - 1)}…` : objective
- const glyph = isLive(mission.state) ? spinAt(nowMs) : (GLYPH[mission.state] ?? '○')
+ const glyph = isLive(mission.state) ? spinAt(nowMs) : (own(GLYPH, mission.state) ?? '○')
return `${glyph} ${cut} · ${mission.state} · tasks ${taskProgress(mission)} · verified ${mission.evidence.verified}/${mission.evidence.count} · ${budgetShort(mission)}`
}
diff --git a/plugins/ruflo-console/hooks/model-tools.ts b/plugins/ruflo-console/hooks/model-tools.ts
index 71e4d6011c..0a556fc53c 100644
--- a/plugins/ruflo-console/hooks/model-tools.ts
+++ b/plugins/ruflo-console/hooks/model-tools.ts
@@ -9,7 +9,7 @@ import { LONG_TEXT_MAX } from './full-text'
import type { Register } from 'claude-code'
import type { Controller } from './controller'
-import { plain } from './data/parse'
+import { ESCAPES, INVISIBLE, plain } from './data/parse'
import { askedBy } from './data/room'
import { DEV_FIELDS } from './data/devtools'
import { PROFILES, RIGORS } from './goap'
@@ -18,11 +18,11 @@ import { RESEARCH_DEPTHS } from './mission-options'
import { filterPalette, paletteEntries } from './palette'
import { hasSecret } from './screen'
import { catalogOf } from './plugin-catalog'
-import { hasInvite } from './xruv'
import { pluginNames, settingsOf } from './settings'
import type { ControlEntry, Pending, State, ViewId } from './state'
import { VIEWS } from './state'
import { viewText } from './views/pane'
+import { hasInvite } from './xruv'
export const TOOL_PREFIX = 'mcp__ruflo-console__'
export const LEVELS = ['off', 'read', 'write', 'manage', 'full'] as const
@@ -90,6 +90,19 @@ function classFromWords(pending: Pick<Pending, 'label' | 'args' | 'note' | 'show
/** True when `level` lets Claude run an action of class `kind`. */
export const allows = (level: ControlLevel, kind: ActionClass): boolean => rank(level) >= rank(NEEDS[kind])
+/**
+ * Why an ask of Claude's that was screened first (and so landed after its tool call returned) may not be queued NOW: Stop was pressed, or the level
+ * the person set no longer allows its class. The level is read at landing, not at the call: lowering it while the screen looked wins. Null when allowed.
+ */
+export function landingRefusal(state: State, pending: Pending): string | null {
+ if (state.control.paused) return 'the person took control back'
+
+ const level = levelOf(settingsOf(state).ai.modelControl)
+ const kind = classOf(pending)
+
+ return allows(level, kind) ? null : `a ${kind} action needs "${NEEDS[kind]}" and control is now "${level}"`
+}
+
export const levelOf = (value: unknown): ControlLevel => LEVELS.find(level => level === value) ?? 'off'
export const confirmOf = (value: unknown): ControlConfirm => (value === 'ask' ? 'ask' : 'auto')
@@ -150,7 +163,7 @@ function asModel<T>(state: State, fn: () => T): T {
}
const say = (state: State, tool: string, summary: string, outcome: ControlEntry['outcome'], detail = ''): void => {
- state.control.log.push({ atMs: Date.now(), tool, summary: plain(summary, 80), outcome, detail: plain(detail, 160) })
+ state.control.log.push({ atMs: Date.now(), tool, summary: modelLine(summary, 80), outcome, detail: modelLine(detail, 160) })
if (state.control.log.length > LOG_MAX) state.control.log.splice(0, state.control.log.length - LOG_MAX)
}
@@ -161,31 +174,47 @@ const leaksSecret = (raw: unknown, cleaned: string): boolean => (typeof raw ===
const textOf = (value: unknown): string => (typeof value === 'string' ? plain(value, MAX_TEXT).trim() : '')
-const WITHHELD = '[line withheld: it looks like a secret]'
+const SECRET_LINE = '(line withheld: it looks like a secret: not shown)'
-/** One line of the screen for the model: cleaned, and withheld whole when it looks like a secret or holds a minted invite code (#3816). */
-const lineFor = (text: unknown, max: number): string => {
- const cleaned = plain(text, max)
+// Whitespace becomes a space (so words stay apart); every other control character goes WITHOUT a space, so a code split by one is joined
+// again before the checks run. C0, DEL and C1 (a split by \u0001 or \u0085 included) are covered here, the zero-width and format ones by INVISIBLE.
+const SPACING = /[\t\n\r\u000b\u000c\u2028\u2029]+/g
+const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g
+
+/**
+ * The ONE path a string takes to the model (#3816). Every string this file returns, or puts in console_state, is built here: escape sequences go
+ * first, then control and invisible characters (removed, not spaced, so they cannot split a credential past a check), then the line is cut to
+ * `max`, and it is withheld whole when any form of it (raw, joined, cut) holds a secret shape or a minted invite code. `raw` may be anything:
+ * non-strings are empty.
+ */
+export function modelLine(raw: unknown, max: number): string {
+ const line = typeof raw === 'string' ? raw : ''
+ const joined = line.replace(ESCAPES, '').replace(SPACING, ' ').replace(INVISIBLE, '').replace(CONTROLS, '')
+ const text = plain(joined, max)
- return hasSecret(typeof text === 'string' ? text : '') || hasSecret(cleaned) || hasInvite(typeof text === 'string' ? text : '') || hasInvite(cleaned) ? WITHHELD : cleaned
+ // A line that still holds an invite code (a bearer secret) is withheld whole, like any secret shape; one the terminal already masked is not.
+ return hasSecret(line) || hasSecret(joined) || hasSecret(text) || hasInvite(joined) ? SECRET_LINE : text
}
-/** The console's state for the model: bounded, with control characters stripped. */
+/** Several lines through modelLine one by one (a result's output), each cut to `max`. */
+export const modelLines = (text: string, max = 4000): string => text.split('\n').map(line => modelLine(line, max)).join('\n')
+
+/** The console's state for the model: bounded, with control characters stripped and secrets withheld. */
function stateJson(deps: ModelToolDeps, filter: string): string {
const { state, control } = deps
const ai = settingsOf(state).ai
const now = Date.now()
- const screen = viewText({ state, nowMs: now, columns: 90, act: control.actions }, state.view).split('\n').map(line => lineFor(line, 160)).join('\n').slice(0, SCREEN_MAX)
+ const screen = viewText({ state, nowMs: now, columns: 90, act: control.actions }, state.view).split('\n').map(line => modelLine(line, 160)).join('\n').slice(0, SCREEN_MAX)
const words = filter.toLowerCase().split(/\s+/).filter(word => word !== '')
- const all = paletteEntries(state, now).map(entry => ({ id: entry.id, label: plain(entry.label, 90) }))
+ const all = paletteEntries(state, now).filter(entry => !hasSecret(entry.id)).map(entry => ({ id: entry.id, label: modelLine(entry.label, 90) }))
const entries = (words.length === 0 ? all : all.filter(entry => words.every(word => `${entry.id} ${entry.label}`.toLowerCase().includes(word)))).slice(0, words.length === 0 ? 60 : 40)
return JSON.stringify({
view: state.view,
title: VIEWS.find(view => view.id === state.view)?.label ?? state.view,
screen,
- waiting: state.pending === null ? null : { ...(askedBy(state.pending) !== '' && { askedBy: askedBy(state.pending).replace(/: $/, '') }), label: plain(state.pending.label, 120), expect: plain(state.pending.expect, 160), note: state.pending.note === undefined ? undefined : plain(state.pending.note, 160) },
- lastResult: state.outcome === null ? null : { label: plain(state.outcome.label, 100), ok: state.outcome.ok, detail: lineFor(state.outcome.detail, 200), lines: (state.outcome.lines ?? []).slice(0, 12).map(line => lineFor(line, 160)) },
+ waiting: state.pending === null ? null : { ...(askedBy(state.pending) !== '' && { askedBy: askedBy(state.pending).replace(/: $/, '') }), label: modelLine(state.pending.label, 120), expect: modelLine(state.pending.expect, 160), note: state.pending.note === undefined ? undefined : modelLine(state.pending.note, 160) },
+ lastResult: state.outcome === null ? null : { label: modelLine(state.outcome.label, 100), ok: state.outcome.ok, detail: modelLine(state.outcome.detail, 200), lines: (state.outcome.lines ?? []).slice(0, 12).map(line => modelLine(line, 160)) },
entries,
entryCount: all.length,
entriesNote: entries.length < (words.length === 0 ? all.length : entries.length) || (words.length > 0 && entries.length === 40) ? 'the list is cut: pass filter (words in an id or label) to find other entries' : undefined,
@@ -225,7 +254,7 @@ function setField(deps: ModelToolDeps, field: string, value: string): string | n
} else if (field === 'research.cap') setResearch(state, { cap: value })
else if (field === 'cost.budget') control.actions.costBudgetDraft(value)
else if (field.startsWith('dev.') && DEV_FIELDS.includes(field.slice(4) as never)) control.actions.devtools.draft(field.slice(4) as never, value)
- else return `unknown field "${plain(field, 40)}". Fields: ${[...SET_FIELDS, 'dev.<field>'].join(', ')}`
+ else return `unknown field "${modelLine(field, 40)}". Fields: ${[...SET_FIELDS, 'dev.<field>'].join(', ')}`
control.host.invalidate()
@@ -248,7 +277,7 @@ async function settlePending(deps: ModelToolDeps, tool: string, id: string, aske
if (pending.source === 'you') {
say(state, tool, `${id}: the person's card is waiting`, 'denied', pending.label)
- return { status: 'refused', text: `an action is waiting for the person ("${plain(pending.label, 80)}"), so yours was not queued. Do not run another until they answer. Nothing ran.` }
+ return { status: 'refused', text: `an action is waiting for the person ("${modelLine(pending.label, 80)}"), so yours was not queued. Do not run another until they answer. Nothing ran.` }
}
const kind = classOf(pending)
@@ -261,7 +290,7 @@ async function settlePending(deps: ModelToolDeps, tool: string, id: string, aske
control.runner.cancel()
say(state, tool, `${id}: needs ${NEEDS[kind]}`, 'denied', pending.label)
- return { status: 'refused', text: `"${plain(pending.label, 80)}" is a ${kind} action and control is set to "${level}" (it needs "${NEEDS[kind]}"). The person can raise it in Settings → Claude control. Nothing ran.` }
+ return { status: 'refused', text: `"${modelLine(pending.label, 80)}" is a ${kind} action and control is set to "${level}" (it needs "${NEEDS[kind]}"). The person can raise it in Settings → Claude control. Nothing ran.` }
}
const budget = kind === 'read' ? Infinity : SESSION_BUDGET[kind]
@@ -272,7 +301,7 @@ async function settlePending(deps: ModelToolDeps, tool: string, id: string, aske
control.runner.cancel()
say(state, tool, `${id}: ${kind} budget used`, 'denied', pending.label)
- return { status: 'refused', text: `the session budget for ${kind} actions (${budget}) is used up, so "${plain(pending.label, 80)}" was not queued. Tell the person what you wanted to do and let them do it in the console. Nothing ran.` }
+ return { status: 'refused', text: `the session budget for ${kind} actions (${budget}) is used up, so "${modelLine(pending.label, 80)}" was not queued. Tell the person what you wanted to do and let them do it in the console. Nothing ran.` }
}
state.control.used[kind] = used + 1
@@ -280,13 +309,13 @@ async function settlePending(deps: ModelToolDeps, tool: string, id: string, aske
if (confirmOf(ai.modelConfirm) === 'ask' || ALWAYS_ASK.includes(kind) || over) {
say(state, tool, id, 'waiting', pending.label)
- return { status: 'waiting', text: `Waiting for the person to confirm in the console: "${plain(pending.label, 100)}" (${kind}${over ? `; the session budget of ${budget} auto-confirmed ${kind} actions is used up` : ''}). Expect: ${plain(pending.expect, 160)}. Do not repeat it; call console_state later to see the result.` }
+ return { status: 'waiting', text: `Waiting for the person to confirm in the console: "${modelLine(pending.label, 100)}" (${kind}${over ? `; the session budget of ${budget} auto-confirmed ${kind} actions is used up` : ''}). Expect: ${modelLine(pending.expect, 160)}. Do not repeat it; call console_state later to see the result.` }
}
// Mission Control reports its own actions on `last`, the rest on `outcome`: whichever moved is what happened.
const lastBefore = mcOf(state).last
- await asModel(state, () => control.runner.confirm())
+ await asModel(state, () => control.runner.confirm(pending.id))
await control.runner.settled()
// An action that brings its own run (creating a mission is several CLI calls) is not waited on by confirm: wait here, with a limit.
@@ -301,14 +330,33 @@ async function settlePending(deps: ModelToolDeps, tool: string, id: string, aske
if (!isFinished) {
say(state, tool, id, 'waiting', 'still running')
- return { status: 'waiting', text: `Started: "${plain(pending.label, 100)}". It is still running after ${FINISH_MS / 1000} s; call console_state later to see the result.` }
+ return { status: 'waiting', text: `Started: "${modelLine(pending.label, 100)}". It is still running after ${FINISH_MS / 1000} s; call console_state later to see the result.` }
}
- return { status: 'done', text: `${done === null ? 'Ran' : done.ok ? 'Done' : 'Failed'}: ${plain(pending.label, 100)}.${done === null ? '' : ` ${plain(done.detail, 200)}`}` }
+ return { status: 'done', text: `${done === null ? 'Ran' : done.ok ? 'Done' : 'Failed'}: ${modelLine(pending.label, 100)}.${done === null ? '' : ` ${modelLine(done.detail, 200)}`}` }
}
-/** One tool call. Always answers with text; a refusal says why and which setting to change. */
+/**
+ * One tool call. Always answers with text; a refusal says why and which setting to change. Whatever `answer` builds, every line of the text goes
+ * through modelLine once more on its way out (console_state's JSON is built field by field from modelLine and is not re-cut), so a builder that
+ * forgets it still cannot hand the model a secret.
+ */
export async function callTool(name: string, input: Record<string, unknown>, deps: ModelToolDeps): Promise<string> {
+ // Only a call that settles what it queued (settlePending: run and set) counts as gating a late ask; console_open and console_state settle nothing.
+ const settles = name === 'console_run' || name === 'console_set'
+
+ if (settles) deps.state.control.activeCalls += 1
+
+ try {
+ const out = await answer(name, input, deps)
+
+ return name === 'console_state' ? out : modelLines(out)
+ } finally {
+ if (settles) deps.state.control.activeCalls -= 1
+ }
+}
+
+async function answer(name: string, input: Record<string, unknown>, deps: ModelToolDeps): Promise<string> {
const { state, control } = deps
const spec = TOOL_SPECS.find(candidate => candidate.name === name)
const ai = settingsOf(state).ai
@@ -317,10 +365,10 @@ export async function callTool(name: string, input: Record<string, unknown>, dep
say(state, name, summary, 'denied', why)
control.host.invalidate()
- return `Refused: ${why}`
+ return `Refused: ${modelLine(why, 600)}`
}
- if (spec === undefined) return `Refused: no such console tool "${plain(name, 40)}"`
+ if (spec === undefined) return `Refused: no such console tool "${modelLine(name, 40)}"`
if (level === 'off') return refuse(name, 'Claude control is off. The person turns it on in Settings → Claude control.')
if (state.control.paused) return refuse(name, 'the person took control back. Stop and ask them before trying again.')
if (rank(level) < rank(spec.needs)) return refuse(name, `${name} needs the "${spec.needs}" level and control is set to "${level}". The person can raise it in Settings → Claude control.`)
@@ -349,7 +397,7 @@ export async function callTool(name: string, input: Record<string, unknown>, dep
const picked = chip === '' ? undefined : chips.get(chip) ?? chips.get(chip.replace(/^ruflo-/, ''))
// The chip is checked against the chips that exist before anything moves, and only the settings page has them.
- if (chip !== '' && (view.id !== 'settings' || picked === undefined)) return refuse(`open ${view.id} chip`, view.id !== 'settings' ? 'chip applies only to the settings page.' : `no such chip "${plain(chip, 40)}". Chips: ${[...chips.keys()].join(', ')}`)
+ if (chip !== '' && (view.id !== 'settings' || picked === undefined)) return refuse(`open ${view.id} chip`, view.id !== 'settings' ? 'chip applies only to the settings page.' : `no such chip "${modelLine(chip, 40)}". Chips: ${[...chips.keys()].join(', ')}`)
asModel(state, () => control.setView(view.id as ViewId))
await control.open(false)
@@ -365,7 +413,7 @@ export async function callTool(name: string, input: Record<string, unknown>, dep
if (leaksSecret(input.value, value)) return refuse(`set ${field}`, SECRET_REFUSAL)
- if (state.pending !== null) return refuse(`set ${field}`, `an action is already waiting for the person ("${plain(state.pending.label, 80)}"). Do not change fields until they answer.`)
+ if (state.pending !== null) return refuse(`set ${field}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not change fields until they answer.`)
const askedAt = Date.now()
const problem = asModel(state, () => setField(deps, field, value))
@@ -387,11 +435,11 @@ export async function callTool(name: string, input: Record<string, unknown>, dep
if (leaksSecret(input.text, text)) return refuse(`run ${id}`, SECRET_REFUSAL)
// The person's own waiting action is theirs to answer: never replaced, never cleared.
- if (state.pending !== null) return refuse(`run ${id}`, `an action is already waiting for the person ("${plain(state.pending.label, 80)}"). Do not run another until they answer.`)
+ if (state.pending !== null) return refuse(`run ${id}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not run another until they answer.`)
const askedAt = state.outcome?.atMs ?? 0
- if (!asModel(state, () => control.runner.runById(id, text, { exact: true }))) return refuse(`run ${id}`, `no palette entry "${plain(id, 40)}" right now. Call console_state for the entries.`)
+ if (!asModel(state, () => control.runner.runById(id, text, { exact: true }))) return refuse(`run ${id}`, `no palette entry "${modelLine(id, 40)}" right now. Call console_state for the entries.`)
await control.runner.settled()
@@ -400,7 +448,7 @@ export async function callTool(name: string, input: Record<string, unknown>, dep
say(state, name, `run ${id}`, done === null || done.ok ? 'ok' : 'error', done?.detail ?? '')
- return done === null ? `Ran ${id}.` : `${done.ok ? 'Done' : 'Failed'}: ${plain(done.label, 100)}. ${plain(done.detail, 200)}${(done.lines ?? []).length > 0 ? `\n${(done.lines ?? []).slice(0, 12).map(line => plain(line, 160)).join('\n')}` : ''}`
+ return done === null ? `Ran ${id}.` : `${done.ok ? 'Done' : 'Failed'}: ${modelLine(done.label, 100)}. ${modelLine(done.detail, 200)}${(done.lines ?? []).length > 0 ? `\n${(done.lines ?? []).slice(0, 12).map(line => modelLine(line, 160)).join('\n')}` : ''}`
}
const settled = await settlePending(deps, name, `run ${id}`, askedAt)
@@ -409,7 +457,7 @@ export async function callTool(name: string, input: Record<string, unknown>, dep
} catch (error) {
say(state, name, name, 'error', error instanceof Error ? error.message : 'failed')
- return `Failed: ${plain(error instanceof Error ? error.message : 'the console action failed', 160)}`
+ return `Failed: ${modelLine(error instanceof Error ? error.message : 'the console action failed', 160)}`
} finally {
state.control.viaModel = false
control.host.invalidate()
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index f8123e67d6..382dce3d03 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -14,7 +14,7 @@ import { labLines } from './mh-lab'
import { outputLines } from './ops'
import { filterPalette, paletteEntries, textOfQuery, type PaletteEntry } from './palette'
import { COLD_TIMEOUT_MS, explainFailure, FIRST_RUN_LABEL, forgetLauncher, resolveLauncher } from './launcher'
-import type { State } from './state'
+import type { Pending, State } from './state'
import { prettyLines } from './result-lines'
export const PENDING_TTL_MS = 30_000
@@ -25,11 +25,14 @@ export type RunnerDeps = {
setView: (view: State['view']) => void
drill: (agentId: string) => void
command: (name: 'refresh' | 'help' | 'close') => void
+ /** Why an ask of Claude's that landed after its tool call returned (it was screened first) may no longer be queued: the level was lowered, or Stop pressed, meanwhile. Null when it still may. */
+ landingRefusal?: (pending: Pending) => string | null
}
export type Runner = {
ask: (spec: ActionSpec | null, why: string) => void
- confirm: () => Promise<void>
+ /** `seen` is the id of the card the person said Yes to: when another card took its place meanwhile, nothing runs and the new card stays (ADR-450 T17). */
+ confirm: (seen?: number) => Promise<void>
cancel: () => void
runEntry: (entry: PaletteEntry, text: string) => void
/** `exact` (the model path, ADR-450 T13) resolves the id as written and never falls back to fuzzy matching. */
@@ -42,6 +45,7 @@ export type Runner = {
export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner {
let pendingSpec: ActionSpec | null = null
+ let asks = 0
let inflight: Promise<void> = Promise.resolve()
let background: Promise<void> = Promise.resolve()
@@ -172,12 +176,53 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
return
}
+ asks += 1
+
+ const pending: Pending = { id: asks, view: state.view, ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), source: byModel ? 'claude' : 'you', ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }), ...(spec.declared !== undefined && { declared: spec.declared }) }
+
+ // Claude's ask that was screened first lands after every tool call of Claude's returned, so no call is left to gate it: the level and Stop are
+ // checked now, not as they were when it was raised, and a refused ask is not queued (nothing waits for a Yes the settings no longer allow).
+ // While a call runs, that call's settlePending gates the ask with the same rules.
+ if (spec.byModel === true && state.control.activeCalls === 0) {
+ const refused = state.control.paused ? 'the person took control back' : deps.landingRefusal?.(pending) ?? null
+
+ if (refused !== null) {
+ say(spec.label, false, `Claude's ask was not queued: ${refused}`)
+
+ return
+ }
+ }
+
pendingSpec = spec
- state.pending = { view: state.view, ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), source: byModel ? 'claude' : 'you', ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }), ...(spec.declared !== undefined && { declared: spec.declared }) }
+ state.pending = pending
host.invalidate()
}
- async function confirm(): Promise<void> {
+ async function confirm(seen?: number): Promise<void> {
+ // The Yes answers the card the person read. Another card (the person's own, or Claude's) may have taken its place before the press landed:
+ // that Yes runs nothing, and the new card stays to be read.
+ if (seen !== undefined && state.pending !== null && state.pending.id !== seen) {
+ say(state.pending.label, false, 'the card changed before your Yes: read the new one, then answer it')
+ record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `a Yes for card ${seen} was ignored: card ${state.pending.id ?? '?'} ("${plain(state.pending.label, 60)}") is waiting now` }])
+
+ return
+ }
+
+ // A card Claude raised is run only if Claude may still ask for it: a level lowered (or Stop pressed) after the card went up wins over the
+ // Yes, which would otherwise run something the settings no longer allow Claude to start. The person can run it themselves from the palette.
+ const claudes = state.pending?.source === 'claude' ? deps.landingRefusal?.(state.pending) ?? (state.control.paused ? 'the person took control back' : null) : null
+
+ if (claudes !== null && state.pending !== null) {
+ const label = state.pending.label
+
+ pendingSpec = null
+ state.pending = null
+ say(label, false, `not run: ${claudes}. Run it from the palette yourself if you want it`)
+ record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `Claude's card "${plain(label, 60)}" was not run: ${claudes}` }])
+
+ return
+ }
+
const spec = pendingSpec
const isFresh = state.pending !== null && Date.now() - state.pending.askedAtMs < PENDING_TTL_MS
diff --git a/plugins/ruflo-console/hooks/settings.ts b/plugins/ruflo-console/hooks/settings.ts
index 4aee0d71e1..cf0bcb63c5 100644
--- a/plugins/ruflo-console/hooks/settings.ts
+++ b/plugins/ruflo-console/hooks/settings.ts
@@ -13,6 +13,7 @@ import { adrDirText, patternOf } from './data/adr-write'
import type { ActionSpec } from './actions'
import { budgetAmount } from './cost'
import { plain } from './data/parse'
+import { own } from './data/safe'
import { RUFLO_MARKET } from './data/snapshot'
import { DEFAULT_LOOP, LOOP_INTERVALS, type LoopPrefs, WRITER_CAPS } from './goap'
import type { Host } from './host'
@@ -177,7 +178,7 @@ export function shownKeys(config: PluginConfig, level: Level): string[] {
if (level === 'advanced') return keys
- const simple = SIMPLE[config.name]
+ const simple = own(SIMPLE, config.name)
return simple === undefined ? keys.slice(0, 4) : keys.filter(key => simple.includes(key))
}
@@ -419,7 +420,7 @@ export type SettingsActions = {
core: (key: string, value: string) => void
ai: (patch: Partial<AiPrefs>) => void
/** The confirm row's "always accept": saves the preference and runs the ask that is pending. */
- alwaysAccept: () => void
+ alwaysAccept: (seen?: number) => void
/** Sends an explaining prompt to the AI terminal (claude or codex) now: the reply streams in, no second click. */
ask: (agent: 'claude' | 'codex', title: string, description: string, current: string, where: string) => void
}
@@ -456,11 +457,18 @@ export function settingsActions(state: State, host: Host, runner: Runner, load:
option: (name, key, value) => runner.ask(setOption(state, name, key, value, reloadPlugin), checkLimit(value.trim(), OPTION_MAX, `the ${key} value`).ok ? `“${plain(value, 40)}” is not a value ${key} accepts` : (checkLimit(value.trim(), OPTION_MAX, `the ${key} value`) as { message: string }).message),
core: (key, value) => runner.ask(setCore(state, key, value, reloadCore), `“${plain(value, 40)}” is not a value ${key} accepts`),
ai: patch => saveAiPrefs(state, host, patch),
- alwaysAccept: () => {
+ alwaysAccept: seen => {
+ // On a card that was replaced it changes nothing: no preference saved, the draft kept, and the Yes runs nothing.
+ if (seen !== undefined && state.pending?.id !== seen) {
+ void runner.confirm(seen)
+
+ return
+ }
+
saveAiPrefs(state, host, { autoAccept: true })
state.terminal.asked = null
state.terminal.draft = ''
- void runner.confirm()
+ void runner.confirm(seen)
},
ask: (agent, title, description, current, where) => load(agent, askPrompt(title, description, current, where)),
}
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index 9dc939c024..dd470a8c5a 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -148,7 +148,7 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
}
/** A mutating action waiting for the person's second press; `shows` is the command line when it is not a ruflo one. */
-export type Pending = { label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string; /** The page that raised it: the ask shows in full there, and as a pointer on every other page. */ view?: string; /** Who raised it: Claude's tool call or the person's own action (ADR-450 T14). */ source?: 'claude' | 'you'; /** The class the entry declares for itself; the gate takes the stricter of this and the class read from its words. */ declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** The class of action, set only on Claude's asks. */ kind?: 'write' | 'network' | 'install' | 'spend' | 'delete' }
+export type Pending = { /** Which ask this is (runner.ts hands out ids in order): a Yes names the card it answers, so another card that took its place is never the one run. */ id?: number; label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string; /** The page that raised it: the ask shows in full there, and as a pointer on every other page. */ view?: string; /** Who raised it: Claude's tool call or the person's own action (ADR-450 T14). */ source?: 'claude' | 'you'; /** The class the entry declares for itself; the gate takes the stricter of this and the class read from its words. */ declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** The class of action, set only on Claude's asks. */ kind?: 'write' | 'network' | 'install' | 'spend' | 'delete' }
/** The MetaHarness lab's last run: what it was, how it exited, its cost note, and its output as lines to scroll. */
export type LabResult = { id: string; label: string; ok: boolean; exitCode: number | null; note?: string; lines: string[]; atMs: number }
@@ -326,7 +326,7 @@ export type State = {
/** The Workflows page: the last read of Claude Code's run folders, the cursor, the inspector tab (wf-state.ts). */
wf: WfState
/** Claude's control of the console (ADR-444): paused by the person, the call counts, and the log the dashboard shows. */
- control: { paused: boolean; calls: number; turnCalls: number; /** Model-driven actions this session, by class (ADR-450 T8 budget). */ used: Record<string, number>; log: ControlEntry[]; /** Until when Claude counts as driving (a tool call extends it): the console does not spend a second Claude turn on guidance meanwhile. */ drivingUntilMs: number; /** True while one of Claude's tool calls is running: a person's "always allow" answer must not let Claude's call skip the level and confirm checks (ADR-444). */ viaModel: boolean }
+ control: { paused: boolean; calls: number; turnCalls: number; /** Model-driven actions this session, by class (ADR-450 T8 budget). */ used: Record<string, number>; log: ControlEntry[]; /** Until when Claude counts as driving (a tool call extends it): the console does not spend a second Claude turn on guidance meanwhile. */ drivingUntilMs: number; /** Claude's console_run / console_set calls running now: an ask that lands while one runs is settled (gated) by that call; one that lands with none running (console_open and console_state settle nothing) is checked by the runner. */ activeCalls: number; /** True while one of Claude's tool calls is running: a person's "always allow" answer must not let Claude's call skip the level and confirm checks (ADR-444). */ viaModel: boolean }
}
export function newState(raw: PluginOptions | undefined): State {
@@ -404,7 +404,7 @@ export function newState(raw: PluginOptions | undefined): State {
timers: new Map(),
stats: { renders: [], refreshes: [], frames: [] },
wf: emptyWf(),
- control: { paused: false, calls: 0, turnCalls: 0, used: {}, log: [], drivingUntilMs: 0, viaModel: false },
+ control: { paused: false, calls: 0, turnCalls: 0, used: {}, log: [], drivingUntilMs: 0, activeCalls: 0, viaModel: false },
}
}
diff --git a/plugins/ruflo-console/hooks/updates.ts b/plugins/ruflo-console/hooks/updates.ts
index 5378ccb7be..742d61b180 100644
--- a/plugins/ruflo-console/hooks/updates.ts
+++ b/plugins/ruflo-console/hooks/updates.ts
@@ -5,6 +5,7 @@
* installs is hooks/update-flow.ts. The install itself is Claude Code's own `claude plugin update`, never code of ours, and its own
* confirmation for a marketplace-declared command is never bypassed (no `-y`, no `--accept-command`).
*/
+import { ESCAPES, HIDDEN } from './data/parse'
import { RUFLO_MARKET } from './data/snapshot'
export type UpdatesMode = 'ask' | 'auto' | 'off'
@@ -155,9 +156,10 @@ export const needsConfirmation = (output: string): boolean => /shownCommand|must
export function firstLine(text: string, max = 140): string {
const line =
text
- .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
+ .replace(ESCAPES, '')
.split('\n')
- .map(entry => entry.replace(/[\u0000-\u001f\u007f‪-‮]/g, '').trim())
+ // The console's one strip set (data/parse.ts): the line reaches update toasts and outcome details.
+ .map(entry => entry.replace(HIDDEN, '').trim())
.find(entry => entry !== '') ?? ''
return line.length > max ? `${line.slice(0, max - 1)}…` : line
diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts
index beea741f8a..1f65fec634 100644
--- a/plugins/ruflo-console/hooks/version.ts
+++ b/plugins/ruflo-console/hooks/version.ts
@@ -2,4 +2,4 @@
* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest
* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.
*/
-export const CONSOLE_VERSION = '0.40.1'
+export const CONSOLE_VERSION = '0.40.2'
diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts
index 3ea4b15544..1367feb9a2 100644
--- a/plugins/ruflo-console/hooks/views/common.ts
+++ b/plugins/ruflo-console/hooks/views/common.ts
@@ -50,7 +50,8 @@ export type Actions = {
help: () => void
close: () => void
back: () => void
- confirm: () => void
+ /** Runs the pending ask; `seen` is the id of the card the Yes came from, so a card that took its place meanwhile is not the one run. */
+ confirm: (seen?: number) => void
cancel: () => void
/** j/k: moves the selection of the view in front. */
select: (by: number) => void
@@ -117,7 +118,7 @@ export type Actions = {
/** Empties an entry field after its Enter. */
clearField: (key: string) => void
/** The confirm row's "always allow this kind of action": remembers the kind (Settings forgets it) and runs the pending ask. */
- remember: () => void
+ remember: (seen?: number) => void
/** Forgets one remembered kind of action, or all of them (an empty key). */
forget: (key: string) => void
/** The nav card: show a group's pages, search the pages, clear the search. */
@@ -235,6 +236,20 @@ export function text(ctx: Ctx, children: string, props: { color?: string; bold?:
return ctx.kit.Text({ wrap: 'truncate-end', ...props, children: clip(children, Math.max(4, ctx.columns)) })
}
+/**
+ * Prose a person needs to read in full (an approval's text, a mission's objective): wrapped on word breaks into as many rows as it takes, each
+ * continuation row indented by `indent`, so a narrow terminal (80 columns in tmux) shows all of it instead of cutting it at the edge with "…".
+ */
+export function paragraph(ctx: Ctx, line: string, props: { color?: string; bold?: boolean; dimColor?: boolean; italic?: boolean } = {}, indent = ''): RenderElement[] {
+ const lead = line.match(/^ */)?.[0] ?? ''
+ const width = Math.max(16, ctx.columns - Math.max(lead.length, indent.length))
+ // A word longer than the row (an id, a path) is cut into row-sized pieces, so no character of it is lost to the edge.
+ const words = line.trimStart().split(' ').flatMap(word => (word.length <= width ? [word] : (word.match(new RegExp(`.{1,${width}}`, 'gu')) ?? [word])))
+ const parts = wrap(words.join(' '), width)
+
+ return (parts.length === 0 ? [''] : parts).map((part, i) => text(ctx, `${i === 0 ? lead : indent}${part}`, props))
+}
+
export function row(ctx: Ctx, parts: readonly RenderChildren[], key?: string): RenderElement {
return ctx.kit.Box({ flexDirection: 'row', ...(key !== undefined && { key }), children: [...parts] })
}
@@ -414,12 +429,12 @@ export function confirmRow(ctx: Ctx): RenderElement | null {
flexDirection: 'row',
marginTop: 1,
children: [
- button(ctx, 'confirm', 'Yes, run it (y)', ctx.act.confirm, { hotkey: 'y', primary: true }),
+ button(ctx, 'confirm', 'Yes, run it (y)', () => ctx.act.confirm(pending.id), { hotkey: 'y', primary: true }),
button(ctx, 'cancel', 'Cancel (n)', ctx.act.cancel, { hotkey: 'n' }),
// A low-risk ruflo action may be remembered: it is not asked again (Settings lists and forgets it).
- ...(pending.rememberKey !== undefined ? [button(ctx, 'remember', `Always allow “${pending.rememberKey}”`, () => ctx.act.remember())] : []),
+ ...(pending.rememberKey !== undefined ? [button(ctx, 'remember', `Always allow “${pending.rememberKey}”`, () => ctx.act.remember(pending.id))] : []),
// An AI terminal turn (claude -p in plan mode, codex read-only, the budget cap) may be always accepted: Settings resets it.
- ...(ctx.state.terminal.asked !== null && pending.label === ctx.state.terminal.asked.label && ctx.state.terminal.harness !== 'ruflo' ? [button(ctx, 'always', 'Always accept AI turns', () => ctx.act.settings.alwaysAccept())] : []),
+ ...(ctx.state.terminal.asked !== null && pending.label === ctx.state.terminal.asked.label && ctx.state.terminal.harness !== 'ruflo' ? [button(ctx, 'always', 'Always accept AI turns', () => ctx.act.settings.alwaysAccept(pending.id))] : []),
],
}),
],
diff --git a/plugins/ruflo-console/hooks/views/hive.ts b/plugins/ruflo-console/hooks/views/hive.ts
index aab2e09c35..8798359efb 100644
--- a/plugins/ruflo-console/hooks/views/hive.ts
+++ b/plugins/ruflo-console/hooks/views/hive.ts
@@ -10,6 +10,7 @@ import type { RenderElement } from 'claude-code'
import { Arrivals, faultTolerance, membersOf, nextVoter, nodesOf, pickedProposal, proposalStrategyOf, proposeBlock, requiredVotes, tallyOf, waveOf, type Liveness, type Member, type Tally } from '../data/hive'
import { shortId, type HiveInfo, type Proposal } from '../data/parse'
+import { own } from '../data/safe'
import { hivePicture, type HiveCell, type HivePictureModel, type Role } from '../gfx/hive'
import { chambersPicture, MAX_CHAMBERS, type Chamber } from '../gfx/hive-chamber'
import { eggBottomPicture, eggTopPicture } from '../gfx/hive-egg'
@@ -22,7 +23,7 @@ const ROLE_GLYPH: Record<string, string> = { worker: '●', specialist: '◆', s
const LIVE_THEME = (liveness: Liveness): { color?: string; dimColor?: boolean } =>
liveness === 'busy' ? { color: THEME.warn } : liveness === 'idle' ? { color: THEME.info } : liveness === 'error' ? { color: THEME.bad } : { dimColor: true }
-const glyphOf = (member: Member): string => (member.isKnown ? (ROLE_GLYPH[member.role] ?? '●') : '○')
+const glyphOf = (member: Member): string => (member.isKnown ? (own(ROLE_GLYPH, member.role) ?? '●') : '○')
const roleOf = (member: Member): Role => (member.isKnown && (member.role === 'worker' || member.role === 'specialist' || member.role === 'scout') ? member.role : 'unknown')
/** The starts an empty hive offers: the palette ids `starts.ts` registers, each asking first with its exact argv. */
diff --git a/plugins/ruflo-console/hooks/views/manage.ts b/plugins/ruflo-console/hooks/views/manage.ts
index fad55d275c..208e2438a3 100644
--- a/plugins/ruflo-console/hooks/views/manage.ts
+++ b/plugins/ruflo-console/hooks/views/manage.ts
@@ -6,7 +6,7 @@ import type { RenderElement } from 'claude-code'
import { approvalsOf } from '../data/alerts'
import type { Lane } from '../gfx/maps'
-import { button, col, row, rule, text, THEME, type Ctx } from './common'
+import { button, col, paragraph, row, rule, text, THEME, type Ctx } from './common'
/** Busy time as a share of the time this lane was observed in the window, and its tool calls. */
export function statsOf(lane: Lane, fromMs: number, nowMs: number): { observedMs: number; busyMs: number; calls: number } {
@@ -22,14 +22,14 @@ export function approvalsView(ctx: Ctx): RenderElement {
const rows: RenderElement[] = [rule(ctx, 'Approvals', items.length === 0 ? 'nothing waiting' : `${items.length} waiting · j/k pick`)]
if (items.length === 0) {
- rows.push(text(ctx, 'No hive-mind proposals, stealable claims, refused mods, permission denies or budget alerts waiting.', { dimColor: true }))
+ rows.push(...paragraph(ctx, 'No hive-mind proposals, stealable claims, refused mods, permission denies or budget alerts waiting.', { dimColor: true }))
}
items.slice(0, 12).forEach((item, i) => {
const isPicked = i === picked
- rows.push(text(ctx, `${isPicked ? '▸' : ' '} [${item.kind}] ${item.text}`, isPicked ? { bold: true, color: THEME.head } : { color: item.kind === 'policy-deny' || item.kind === 'mod-trust' ? THEME.bad : THEME.warn }))
- rows.push(text(ctx, ` ${item.detail}`, { dimColor: true }))
+ rows.push(...paragraph(ctx, `${isPicked ? '▸' : ' '} [${item.kind}] ${item.text}`, isPicked ? { bold: true, color: THEME.head } : { color: item.kind === 'policy-deny' || item.kind === 'mod-trust' ? THEME.bad : THEME.warn }, ' '))
+ rows.push(...paragraph(ctx, ` ${item.detail}`, { dimColor: true }, ' '))
if (isPicked && item.actions.length > 0 && ctx.columns >= 44) {
rows.push(row(ctx, item.actions.map((action, a) => button(ctx, `approve-${a}`, action.label, () => void ctx.act.run(action.paletteId), a < 2 ? { hotkey: a === 0 ? 'v' : 'w' } : {}))))
@@ -38,7 +38,7 @@ export function approvalsView(ctx: Ctx): RenderElement {
if (ctx.columns >= 44 && items.length > 1) rows.push(row(ctx, [button(ctx, 'item-prev', 'prev', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'item-next', 'next', () => ctx.act.select(1), { hotkey: 'j' })]))
- rows.push(text(ctx, 'each action asks y/n before it runs; a permission deny is shown, never loosened from here', { dimColor: true }))
+ rows.push(...paragraph(ctx, 'each action asks y/n before it runs; a permission deny is shown, never loosened from here', { dimColor: true }))
return col(ctx, rows, 'approvals')
}
diff --git a/plugins/ruflo-console/hooks/views/missions.ts b/plugins/ruflo-console/hooks/views/missions.ts
index 67f41773a9..97145e82fd 100644
--- a/plugins/ruflo-console/hooks/views/missions.ts
+++ b/plugins/ruflo-console/hooks/views/missions.ts
@@ -2,8 +2,9 @@ import type { RenderElement } from 'claude-code'
import { money, type Mission } from '../data/missions'
import { attentionCount, clampCursor, freshnessOf, isLive, listLayout, spinAt } from '../mission-list'
-import { ago, kv, rule, text, THEME, type Ctx } from './common'
+import { ago, kv, paragraph, rule, text, THEME, type Ctx } from './common'
import { researchRows } from './research-section'
+import { own } from '../data/safe'
const STATE_COLOR: Record<string, string> = { running: THEME.warn, verifying: THEME.warn, completed: THEME.ok, failed: THEME.bad, blocked: THEME.bad, paused: THEME.info, queued: THEME.info }
@@ -13,7 +14,7 @@ const TASK_GLYPH: Record<string, string> = { pending: '○', running: '◐', 're
function missionRows(ctx: Ctx, mission: Mission, isFirst: boolean): RenderElement[] {
const budget = mission.budget
const rows: RenderElement[] = [
- text(ctx, `${isFirst ? '▸' : ' '} ${mission.objective || '(no objective)'}`, { bold: true, ...(STATE_COLOR[mission.state] !== undefined && { color: STATE_COLOR[mission.state] }) }),
+ ...paragraph(ctx, `${isFirst ? '▸' : ' '} ${mission.objective || '(no objective)'}`, { bold: true, ...(own(STATE_COLOR, mission.state) !== undefined && { color: own(STATE_COLOR, mission.state) }) }, ' '),
text(
ctx,
` ${isLive(mission.state) ? `${spinAt(ctx.nowMs)} ` : ''}${mission.state} · rev ${mission.revision} · ${mission.executionMode === 'session-bound' ? 'session-bound (runs only while a session drives it)' : mission.executionMode} · ${mission.id}`,
@@ -21,7 +22,7 @@ function missionRows(ctx: Ctx, mission: Mission, isFirst: boolean): RenderElemen
),
text(
ctx,
- ` plan rev ${mission.plan.revision}: ${mission.plan.taskCount === 0 ? 'no tasks yet' : mission.plan.tasks.map(task => `${task.status === 'running' ? spinAt(ctx.nowMs) : (TASK_GLYPH[task.status] ?? '?')} ${task.id}`).join(' → ')}${mission.plan.taskCount > mission.plan.tasks.length ? ` (+${mission.plan.taskCount - mission.plan.tasks.length})` : ''}`,
+ ` plan rev ${mission.plan.revision}: ${mission.plan.taskCount === 0 ? 'no tasks yet' : mission.plan.tasks.map(task => `${task.status === 'running' ? spinAt(ctx.nowMs) : (own(TASK_GLYPH, task.status) ?? '?')} ${task.id}`).join(' → ')}${mission.plan.taskCount > mission.plan.tasks.length ? ` (+${mission.plan.taskCount - mission.plan.tasks.length})` : ''}`,
),
text(
ctx,
diff --git a/plugins/ruflo-console/hooks/views/settings.ts b/plugins/ruflo-console/hooks/views/settings.ts
index 3d0b01461c..60e13b4e97 100644
--- a/plugins/ruflo-console/hooks/views/settings.ts
+++ b/plugins/ruflo-console/hooks/views/settings.ts
@@ -7,6 +7,7 @@ import { TOAST_MODES, type ToastMode } from '../toast-policy'
import { MUTABLE_SOURCES, summaryOf } from '../toasts'
import { UPDATES_MODES, type UpdatesMode } from '../updates'
import { button, clip, col, row, rule, section, text, THEME, type Ctx } from './common'
+import { own } from '../data/safe'
/** One setting, whatever it belongs to, so a search, a level and "changed only" filter one list. */
type Item = { id: string; source: string; title: string; haystack: string; level: Level; changed: boolean; rows: () => RenderElement[] }
@@ -76,7 +77,7 @@ function settingRows(ctx: Ctx, o: RowSpec): RenderElement[] {
return rows
}
-const simpleKeys = (config: PluginConfig): readonly string[] => SIMPLE[config.name] ?? Object.keys(config.schema).slice(0, 4)
+const simpleKeys = (config: PluginConfig): readonly string[] => own(SIMPLE, config.name) ?? Object.keys(config.schema).slice(0, 4)
function pluginItems(ctx: Ctx, config: PluginConfig): Item[] {
return Object.entries(config.schema).map(([key, entry]) => {
@@ -96,7 +97,7 @@ function pluginItems(ctx: Ctx, config: PluginConfig): Item[] {
settingRows(ctx, {
key: id,
title: entry.title,
- description: OPTION_NOTES[config.name]?.[key] ?? entry.description,
+ description: own(own(OPTION_NOTES, config.name) ?? {}, key) ?? entry.description,
current,
isChanged,
isSecret: entry.isSecret,
diff --git a/plugins/ruflo-console/hooks/xruv.ts b/plugins/ruflo-console/hooks/xruv.ts
index 6ad846b474..a2a45475f8 100644
--- a/plugins/ruflo-console/hooks/xruv.ts
+++ b/plugins/ruflo-console/hooks/xruv.ts
@@ -99,11 +99,14 @@ export function admitArg(raw: string): { pubkey: string; role: 'member' | 'admin
return isPubkey(pubkey) && (role === 'member' || role === 'admin') && extra.length === 0 ? { pubkey: pubkey.toLowerCase(), role } : null
}
+/** A version (v2.1.0-beta.3) has the invite's characters but not its shape: the terminal masks every line, and a version stays readable. */
+const VERSION = /^v2\.\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?$/
+
/** An invite code in any text, masked: it is a bearer secret, so no line the console writes ever carries one. */
-export const maskInvites = (line: string): string => line.replace(INVITE_ANYWHERE, 'v2.•••• (invite code, masked)')
+export const maskInvites = (line: string): string => line.replace(INVITE_ANYWHERE, code => (VERSION.test(code) ? code : 'v2.•••• (invite code, masked)'))
/** True when the text holds an invite code (a bearer secret the person minted: it never goes to a model). */
-export const hasInvite = (text: string): boolean => new RegExp(INVITE_ANYWHERE.source).test(text)
+export const hasInvite = (text: string): boolean => maskInvites(text) !== text
const exec = (tool: string, params: Record<string, unknown>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index a82908d3a8..1dcd9a2a49 100755
--- a/plugins/ruflo-console/scripts/smoke.sh
+++ b/plugins/ruflo-console/scripts/smoke.sh
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares ruflo-console 0.40.1"
+step "1. plugin.json declares ruflo-console 0.40.2"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.40.1"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.40.2"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
diff --git a/plugins/ruflo-console/tests/deferred-asks.spec.ts b/plugins/ruflo-console/tests/deferred-asks.spec.ts
new file mode 100644
index 0000000000..d62647d542
--- /dev/null
+++ b/plugins/ruflo-console/tests/deferred-asks.spec.ts
@@ -0,0 +1,211 @@
+/**
+ * A Yes runs only the card it was pressed on, and an ask of Claude's that lands after its tool call returned is checked against the level and
+ * Stop as they are NOW (ADR-450 T17, #3815). Real controller, runner, palette and model tools; only the engine is faked (fixtures/live-console.ts).
+ * Specs ported from PR #3820 (@proffesor-for-testing), adapted to the runner as it is on main.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { callTool } from '../hooks/model-tools'
+import { settingsOf } from '../hooks/settings'
+import { flush, liveConsole } from './fixtures/live-console'
+
+const note = (label: string, value: string) => ({ label, args: ['memory', 'store', '--key', value, '--value', value], expect: 'stored' })
+
+describe('a Yes runs only the card it was pressed on', () => {
+ it('a Yes pressed on a card that has since been replaced runs nothing, and the new card stays', async () => {
+ const { state, control, log } = liveConsole('read')
+
+ control.runner.ask(note('store note one', 'one'), 'x')
+ const seen = state.pending?.id
+
+ control.runner.ask(note('store note two', 'two'), 'x')
+ expect(seen).toBeDefined()
+ expect(state.pending?.id).not.toBe(seen)
+ await control.runner.confirm(seen)
+ expect(log.runs.filter(argv => argv.includes('store'))).toEqual([])
+ expect(state.pending?.label).toBe('store note two')
+ expect(state.outcome?.ok).toBe(false)
+
+ await control.runner.confirm(state.pending?.id)
+ expect(log.runs.filter(argv => argv.includes('two')).length).toBe(1)
+ expect(log.runs.filter(argv => argv.includes('one'))).toEqual([])
+ })
+
+ it('card ids are unique and rise, so an id is never reused by a later card', () => {
+ const { state, control } = liveConsole('read')
+ const ids: (number | undefined)[] = []
+
+ for (const name of ['a', 'b', 'c']) {
+ control.runner.ask(note(`store ${name}`, name), 'x')
+ ids.push(state.pending?.id)
+ }
+
+ expect(new Set(ids).size).toBe(3)
+ expect(ids).toEqual([...ids].sort((a, b) => (a ?? 0) - (b ?? 0)))
+ })
+
+ it('the confirm row\'s Yes, Always allow and Always accept buttons carry the id of the card they were drawn for', async () => {
+ const { confirmRow } = await import('../hooks/views/common')
+ const { newState } = await import('../hooks/state')
+ 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 seen: Record<string, unknown> = {}
+ const act = { confirm: (id?: number) => (seen.confirm = id), remember: (id?: number) => (seen.remember = id), settings: { alwaysAccept: (id?: number) => (seen.always = id) }, cancel: () => undefined }
+ const flat = (node: unknown): El[] => {
+ const el = node as El
+
+ return typeof node !== 'object' || node === null ? [] : [el, ...(Array.isArray(el.props.children) ? el.props.children.flatMap(flat) : flat(el.props.children))]
+ }
+ const state = newState({ boot: false })
+
+ state.pending = { id: 41, label: 'ask Claude about the terminal', args: [], expect: 'e', askedAtMs: 1, rememberKey: 'ask' }
+ state.terminal.harness = 'claude'
+ state.terminal.asked = { key: 'k', label: 'ask Claude about the terminal' } as never
+
+ const card = confirmRow({ kit, state, act, columns: 100, nowMs: 1_000, pictures: new Map() } as never) as unknown as El
+
+ for (const button of flat(card).filter(el => el.kind === 'Button')) (button.props.onPress as () => void)()
+
+ // The press names the card that was drawn: a card that replaced it since is not the one answered.
+ expect(seen).toEqual({ confirm: 41, remember: 41, always: 41 })
+ })
+
+ it('a Yes with no id still answers the card that is waiting (the /ruflo yes text command)', async () => {
+ const { state, control, log } = liveConsole('read')
+
+ control.runner.ask(note('store only', 'only'), 'x')
+ await control.runner.confirm()
+ expect(log.runs.filter(argv => argv.includes('only')).length).toBe(1)
+ expect(state.pending).toBeNull()
+ })
+
+ it('a second Yes on a card that already ran is a quiet no-op: it does not overwrite the answer', async () => {
+ const { state, control, log } = liveConsole('read')
+
+ control.runner.ask(note('store once', 'once'), 'x')
+ const seen = state.pending?.id
+
+ await control.runner.confirm(seen)
+ const answer = state.outcome
+
+ await control.runner.confirm(seen)
+ expect(log.runs.filter(argv => argv.includes('once')).length).toBe(1)
+ expect(state.outcome).toBe(answer)
+ })
+})
+
+/**
+ * A screened ask can land while ANOTHER of Claude's tool calls is running: console_open settles nothing, so no call gates the ask. It is
+ * still late, and gated in the runner (#3815, #3820 review). Ported in spirit from PR #3820 (@proffesor-for-testing).
+ */
+describe('Claude\'s asks are re-checked when they land and when the Yes arrives', () => {
+ const late = () => ({ label: 'store a late note', args: ['memory', 'store', '--key', 'late', '--value', 'late'], expect: 'stored', byModel: true })
+
+ it('an ask that lands while console_open is running, with the level lowered meanwhile, is not queued', async () => {
+ let release: () => void = () => undefined
+ const held = new Promise<void>(resolve => (release = resolve))
+ const { state, control, deps, log } = liveConsole('full', 'ask', { openPane: () => held })
+ const opening = callTool('console_open', { view: 'overview' }, deps)
+
+ await flush()
+ expect(state.control.activeCalls).toBe(0)
+ Object.assign(settingsOf(state).ai, { modelControl: 'read' })
+ control.runner.ask(late(), 'x')
+ release()
+ expect(await opening).toMatch(/^Opened/)
+ expect(state.pending).toBeNull()
+ expect(log.runs).toEqual([])
+ })
+
+ it('a card Claude raised when the level allowed it, answered Yes after the level was lowered, runs nothing and is cleared', async () => {
+ const { state, control, log } = liveConsole('full', 'ask')
+
+ control.runner.ask(late(), 'x')
+ expect(state.pending).toMatchObject({ source: 'claude' })
+ Object.assign(settingsOf(state).ai, { modelControl: 'read' })
+ await control.runner.confirm(state.pending?.id)
+ expect(log.runs.filter(argv => argv.includes('late'))).toEqual([])
+ expect(state.pending).toBeNull()
+ expect(state.outcome?.detail).toMatch(/not run: .*control is now "read"/)
+ })
+
+ it('the same card answered Yes while the level still allows it runs', async () => {
+ const { state, control, log } = liveConsole('full', 'ask')
+
+ control.runner.ask(late(), 'x')
+ await control.runner.confirm(state.pending?.id)
+ expect(log.runs.filter(argv => argv.includes('late')).length).toBe(1)
+ })
+
+ it('Stop pressed after the card went up: a Yes runs nothing', async () => {
+ const { state, control, log } = liveConsole('full', 'ask')
+
+ control.runner.ask(late(), 'x')
+ state.control.paused = true
+ await control.runner.confirm(state.pending?.id)
+ expect(log.runs.filter(argv => argv.includes('late'))).toEqual([])
+ })
+})
+
+describe('an ask of Claude\'s that lands after its tool call returned is checked when it lands', () => {
+ const late = (label: string) => ({ ...note(label, 'late'), byModel: true })
+
+ it('at full: it waits for the person, marked as Claude\'s', () => {
+ const { state, control } = liveConsole('full')
+
+ control.runner.ask(late('store a late note'), 'x')
+ expect(state.pending).toMatchObject({ source: 'claude', label: 'store a late note' })
+ })
+
+ it('a level lowered while the screen looked wins: the ask is not queued', () => {
+ const { state, control } = liveConsole('full')
+
+ Object.assign(settingsOf(state).ai, { modelControl: 'read' })
+ control.runner.ask(late('store a late note'), 'x')
+ expect(state.pending).toBeNull()
+ expect(state.outcome?.detail).toMatch(/not queued.*control is now "read"/)
+ })
+
+ it('Stop pressed while the screen looked: the ask is not queued', () => {
+ const { state, control } = liveConsole('full')
+
+ state.control.paused = true
+ control.runner.ask(late('store a late note'), 'x')
+ expect(state.pending).toBeNull()
+ })
+
+ it('the person\'s own ask is never held to Claude\'s level', () => {
+ const { state, control } = liveConsole('read')
+
+ control.runner.ask(note('store my note', 'mine'), 'x')
+ expect(state.pending).toMatchObject({ source: 'you' })
+ })
+})
+
+describe('Always accept on a card that was replaced', () => {
+ it('remembers nothing and leaves the draft, as a stale Yes runs nothing', async () => {
+ const { settingsActions } = await import('../hooks/settings')
+ const { newState } = await import('../hooks/state')
+ const { settingsOf } = await import('../hooks/settings')
+ const state = newState({})
+ const confirmed: (number | undefined)[] = []
+ const host = { storeSet: async () => undefined, invalidate: () => undefined, after: () => ({ cancel: () => undefined }) } as never
+ const runner = { confirm: (seen?: number) => void confirmed.push(seen) } as never
+ const actions = settingsActions(state, host, runner, () => undefined, () => [], () => [])
+
+ settingsOf(state).ai.autoAccept = false
+ state.terminal.draft = 'half typed'
+ state.pending = { id: 2, label: 'the new card', args: [], expect: 'x', askedAtMs: Date.now() } as never
+ actions.alwaysAccept(1)
+
+ expect(settingsOf(state).ai.autoAccept).toBe(false)
+ expect(state.terminal.draft).toBe('half typed')
+ // The stale id still goes to the runner, which refuses it with a visible note; nothing is saved.
+ expect(confirmed).toEqual([1])
+
+ actions.alwaysAccept(2)
+ expect(settingsOf(state).ai.autoAccept).toBe(true)
+ expect(confirmed).toEqual([1, 2])
+ })
+})
diff --git a/plugins/ruflo-console/tests/escape-linear.spec.ts b/plugins/ruflo-console/tests/escape-linear.spec.ts
new file mode 100644
index 0000000000..69056af181
--- /dev/null
+++ b/plugins/ruflo-console/tests/escape-linear.spec.ts
@@ -0,0 +1,62 @@
+/**
+ * Stripping escape sequences is linear: a megabyte of unterminated OSC introducers (7-bit and C1), CSI introducers with no final byte and
+ * mixes of them cleans in milliseconds, not seconds. The old pattern rescanned to the end of the text from every unterminated introducer
+ * (7.7 s against a 1 s bound). An unterminated OSC swallows to the next introducer or the end, as a terminal does.
+ * Timing bound ported in spirit from PR #3821 (@proffesor-for-testing).
+ */
+import { describe, expect, it } from 'vitest'
+
+import { ESCAPES, plain } from '../hooks/data/parse'
+import { termText } from '../hooks/harness'
+import { modelLine } from '../hooks/model-tools'
+import { firstLine } from '../hooks/updates'
+
+const MEGABYTE = 1_000_000
+const SHAPES: Record<string, string> = {
+ 'C1 OSC introducers': '\u009d'.repeat(MEGABYTE),
+ 'C1 OSC introducers between text': `x${'\u009d]'.repeat(MEGABYTE / 2)}`,
+ '7-bit OSC introducers': '\u001b]'.repeat(MEGABYTE / 2),
+ '7-bit OSC with a body': '\u001b]a'.repeat(MEGABYTE / 3),
+ 'CSI introducers': '\u001b['.repeat(MEGABYTE / 2),
+ 'CSI with digits and no final byte': '\u001b[1'.repeat(MEGABYTE / 3),
+ 'C1 CSI with parameters': '\u009b;;;'.repeat(MEGABYTE / 4),
+ 'one CSI and a megabyte of parameters': `\u001b[${';'.repeat(MEGABYTE)}`,
+ 'both OSC forms mixed': '\u009dab\u001b]cd'.repeat(MEGABYTE / 6),
+ 'C1 OSC then escape bytes': `\u009d${'a\u001b'.repeat(MEGABYTE / 2)}`,
+}
+const BOUND_MS = 1_000
+const SMALL = 20_000
+const SMALL_BOUND_MS = 250
+
+describe('escape stripping is linear on a megabyte of hostile input', () => {
+ for (const [name, input] of Object.entries(SHAPES)) {
+ it(name, () => {
+ const clean = (text: string) => {
+ const started = Date.now()
+
+ text.replace(ESCAPES, '')
+ plain(text, 200)
+ termText(text)
+ modelLine(text, 200)
+ firstLine(text)
+
+ return Date.now() - started
+ }
+
+ // A quadratic pattern fails on the small input at once, instead of hanging the run on the megabyte one.
+ expect(clean(input.slice(0, SMALL))).toBeLessThan(SMALL_BOUND_MS)
+ expect(clean(input)).toBeLessThan(BOUND_MS)
+ })
+ }
+
+ it('terminated sequences still go whole, and visible text stays', () => {
+ expect('a\u001b]8;;http://x\u0007LINK\u001b]8;;\u0007b'.replace(ESCAPES, '')).toBe('aLINKb')
+ expect('a\u009d52;c;ZZ\u009cb\u001b]0;t\u001b\\c'.replace(ESCAPES, '')).toBe('abc')
+ expect('\u001b[31mred\u001b[0m \u009b1mbold'.replace(ESCAPES, '')).toBe('red bold')
+ })
+
+ it('an unterminated OSC ends at the next introducer or the end of the text', () => {
+ expect('keep\u001b]0;title\u001b[1mbold'.replace(ESCAPES, '')).toBe('keepbold')
+ expect('keep\u001b]0;title with no end'.replace(ESCAPES, '')).toBe('keep')
+ })
+})
diff --git a/plugins/ruflo-console/tests/fixtures/live-console.ts b/plugins/ruflo-console/tests/fixtures/live-console.ts
new file mode 100644
index 0000000000..2d06dd8f7d
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/live-console.ts
@@ -0,0 +1,68 @@
+/**
+ * A real console for the model-control tests: the real controller, runner, palette and model tools, with only the engine (Host) faked. The
+ * fake records every argv, slash command and prompt that would have run, so a test can say "nothing reached the network / no turn started".
+ * Every CLI run answers asynchronously, as the real one does, so an AIDefence screen lands after Claude's tool call has returned.
+ */
+import { createController } from '../../hooks/controller'
+import type { Host } from '../../hooks/host'
+import { mcOf, type MissionRecord } from '../../hooks/mission-control'
+import type { ModelToolDeps } from '../../hooks/model-tools'
+import { settingsOf } from '../../hooks/settings'
+import { newState, type State } from '../../hooks/state'
+
+export type Recorded = { runs: string[][]; slash: string[][]; prompts: string[] }
+
+/** `openPane` replaces the pane opener, so a test can hold `console_open` open while something else (a screened ask) lands. */
+export function liveConsole(level: 'read' | 'write' | 'manage' | 'full', confirm: 'ask' | 'auto' = 'ask', fakes: { openPane?: () => Promise<unknown> } = {}) {
+ const log: Recorded = { runs: [], slash: [], prompts: [] }
+ const host = new Proxy(
+ {},
+ {
+ get: (_target, key) => {
+ if (key === 'after' || key === 'every') return () => ({ cancel: () => undefined, fire: () => undefined })
+ if (key === 'pluginRoot') return '/plugin'
+ if (key === 'fs') return { read: async () => Promise.reject(new Error('ENOENT')), stat: async () => Promise.reject(new Error('ENOENT')), list: async () => Promise.reject(new Error('ENOENT')) }
+ if (key === 'run') return async (argv: readonly string[]) => (log.runs.push([...argv]), { exitCode: 0, stdout: '{"success":true}', stderr: '', isStdoutTruncated: false, isStderrTruncated: false })
+ if (key === 'runSlash') return async (command: string, args: string) => void log.slash.push([command, args])
+ if (key === 'submitPrompt') return async (text: string) => void log.prompts.push(text)
+ if (key === 'fillPrompt') return async () => true
+ if (key === 'storeGet') return async () => undefined
+ if (key === 'openPane') return async () => (await fakes.openPane?.(), { isPlaced: true })
+ if (key === 'invalidate' || key === 'scrollTop' || key === 'blit' || key === 'toast') return () => undefined
+
+ return () => Promise.resolve(undefined)
+ },
+ },
+ ) as unknown as Host
+ const state = newState({})
+ const control = createController(state, host)
+
+ Object.assign(settingsOf(state).ai, { modelControl: level, modelConfirm: confirm })
+
+ return { state, control, host, log, deps: { state, control } as unknown as ModelToolDeps }
+}
+
+/** Lets the console's un-awaited promises (an AIDefence screen, a loader) settle. */
+export async function flush(): Promise<void> {
+ for (let i = 0; i < 30; i += 1) await new Promise(resolve => setImmediate(resolve))
+}
+
+export const MISSION_ID = `msn_${'a'.repeat(24)}`
+
+/** An active mission with one ready task, so auto-run has something to hand out. */
+export function withMission(state: State): MissionRecord {
+ const mission: MissionRecord = {
+ id: MISSION_ID, objective: 'add a dark mode toggle', profile: 'feature', rigor: 'standard',
+ tasks: [{ id: 't1', title: 'Specify', phase: 'S', agent: 'specification', requirement: 'a spec', dependsOn: [], rufloTaskId: 'r1' }],
+ acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 1_000,
+ }
+
+ state.snapshot = { tasks: [{ id: 'r1', type: 'feature', description: '', status: 'pending', assignedTo: [], tags: [`mission:${MISSION_ID}`, 'task:t1'] }], agents: [], claims: [], swarm: null, plugins: { missingFromClone: [], installed: [] }, alerts: [] } as never
+ mcOf(state).missions.set(mission.id, mission)
+ mcOf(state).active = mission.id
+
+ return mission
+}
+
+/** The argv that reach the network: x.ruv.io and federation reads, and `npx skills`. */
+export const networkRuns = (runs: string[][]): string[][] => runs.filter(argv => argv.some(arg => /x_federation|federation/.test(arg)) || (argv[0] === 'npx' && argv.includes('skills')))
diff --git a/plugins/ruflo-console/tests/model-facing.spec.ts b/plugins/ruflo-console/tests/model-facing.spec.ts
new file mode 100644
index 0000000000..824b221e9b
--- /dev/null
+++ b/plugins/ruflo-console/tests/model-facing.spec.ts
@@ -0,0 +1,127 @@
+/**
+ * Everything the console hands the model goes through one path (model-tools.ts modelLine): console_state's fields, every console_run /
+ * console_set / console_open answer, every refusal that quotes a label, a result or the model's own input, and the thrown-error answer. This
+ * enumerates the builders: each is fed a token, a minted invite code (whole, and split by C0, C1 and zero-width characters) and an escape
+ * sequence, and none of it may come out. A new builder that skips modelLine fails here, not in a review.
+ * Specs for the single path ported in part from PR #3821 (@proffesor-for-testing).
+ */
+import { describe, expect, it } from 'vitest'
+
+import { callTool, modelLine, modelLines, type ModelToolDeps } from '../hooks/model-tools'
+import { catalogOf } from '../hooks/plugin-catalog'
+import { setup } from './fixtures/control-setup'
+
+const CODE = 'v2.Zk3pQ9rT_u7WmB2xL0aYc4N'
+// Built at run time so no token-shaped literal sits in this source.
+const TOKEN = `ghp_${'Ab3'.repeat(12)}`
+const SPLITS = [`${CODE.slice(0, 6)}\u0001${CODE.slice(6)}`, `${CODE.slice(0, 6)}\u0085${CODE.slice(6)}`, `${CODE.slice(0, 8)}​${CODE.slice(8)}`, `${CODE.slice(0, 5)}\u001b[0m${CODE.slice(5)}`]
+const ESC = '\u001b]8;;https://evil.example\u0007LINK\u001b]8;;\u0007'
+/** One string holding every hostile shape. */
+const HOSTILE = `token ${TOKEN} code ${CODE} split ${SPLITS.join(' ')} link ${ESC}`
+const LEAKS = [TOKEN, CODE, ...SPLITS.map(() => CODE.slice(8, 16)), CODE.slice(3, 9)]
+// eslint-disable-next-line no-control-regex
+const CONTROL = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/
+
+const clean = (answer: string, where: string) => {
+ for (const leak of LEAKS) expect(answer, `${where} leaked ${leak}`).not.toContain(leak)
+ expect(CONTROL.test(answer), `${where} kept a control character`).toBe(false)
+ expect(answer, `${where} kept an escape residue`).not.toContain('8;;https')
+}
+
+const waiting = (state: ModelToolDeps['state']) => {
+ state.pending = { id: 1, label: `store ${HOSTILE}`, args: [], expect: `stored ${HOSTILE}`, askedAtMs: Date.now(), note: `effect ${HOSTILE}` }
+}
+
+describe('modelLine is the one path', () => {
+ it('masks, withholds and strips in one pass', () => {
+ clean(modelLine(HOSTILE, 4000), 'modelLine')
+ expect(modelLine(`a\u001b[31mred\u001b[0m b`, 40)).toBe('ared b')
+ expect(modelLine(undefined, 40)).toBe('')
+ expect(modelLines(`ok\n${TOKEN}\nfine`)).toBe('ok\n(line withheld: it looks like a secret: not shown)\nfine')
+ })
+
+ it('a version with the invite prefix stays readable', () => {
+ expect(modelLine('upgraded to v2.1.0-beta.3', 80)).toBe('upgraded to v2.1.0-beta.3')
+ })
+})
+
+describe('every model-facing builder', () => {
+ it('console_state: waiting, lastResult and the screen', async () => {
+ const { state, deps } = setup('read')
+
+ waiting(state)
+ state.outcome = { label: `ran ${HOSTILE}`, ok: false, verified: 'n/a', detail: `failed ${HOSTILE}`, atMs: Date.now(), lines: [HOSTILE, `second ${HOSTILE}`] }
+ clean(await callTool('console_state', {}, deps), 'console_state')
+ })
+
+ it('console_run: a read that finished, and one that failed with a token in its stderr', async () => {
+ for (const ok of [true, false]) {
+ const { state, deps } = setup('write', 'auto', { 'mission-open': { label: 'open Mission Control', readOnly: true } })
+ const runner = (deps as unknown as { control: { runner: { runById: (id: string) => boolean } } }).control.runner
+
+ runner.runById = () => ((state.outcome = { label: `open ${HOSTILE}`, ok, verified: 'n/a', detail: `stderr: ${HOSTILE}`, atMs: Date.now() + 1, lines: [HOSTILE] }), true)
+ clean(await callTool('console_run', { id: 'mission-open' }, deps), `console_run read ok=${ok}`)
+ }
+ })
+
+ it('console_run and console_set: the refusal that quotes the card already waiting', async () => {
+ const { state, deps } = setup('write')
+
+ waiting(state)
+ clean(await callTool('console_run', { id: 'mission-open' }, deps), 'console_run already waiting')
+ clean(await callTool('console_set', { field: 'goal', value: 'x' }, deps), 'console_set already waiting')
+ })
+
+ it('console_run: the answers that settle a queued card (waiting, level, budget, started, done)', async () => {
+ const queued = (state: ModelToolDeps['state'], deps: ModelToolDeps) => {
+ const runner = (deps as unknown as { control: { runner: { runById: (id: string) => boolean } } }).control.runner
+
+ runner.runById = () => (waiting(state), true)
+ }
+ const ask = setup('full', 'ask')
+ const low = setup('read', 'ask')
+ const auto = setup('full', 'auto')
+ const slow = setup('full', 'auto')
+
+ for (const { state, deps } of [ask, low, auto, slow]) queued(state, deps)
+ clean(await callTool('console_run', { id: 'x' }, ask.deps), 'settle: waiting')
+ clean(await callTool('console_run', { id: 'x' }, low.deps), 'settle: level refusal')
+ clean(await callTool('console_run', { id: 'x' }, auto.deps), 'settle: done')
+ // A run that does not finish inside the limit answers "Started".
+ slow.calls.finishAfter = new Promise<void>(() => undefined)
+ clean(await callTool('console_run', { id: 'x' }, slow.deps), 'settle: started')
+ })
+
+ it('the refusals that echo what the model typed (an unknown id, field, chip, tool)', async () => {
+ const { deps } = setup('full', 'auto')
+
+ clean(await callTool('console_run', { id: HOSTILE }, deps), 'unknown id')
+ clean(await callTool('console_set', { field: HOSTILE, value: 'x' }, deps), 'unknown field')
+ clean(await callTool('console_open', { view: 'settings', chip: HOSTILE }, deps), 'unknown chip')
+ clean(await callTool(`console_${HOSTILE}`, {}, deps), 'unknown tool')
+ })
+
+ it('console_open: the answer names the plugin the chip selected, and that name is withheld when it holds a secret shape', async () => {
+ const { state, deps } = setup('full', 'auto')
+ // All lower case: the chip is matched lower-cased, and the name must be found for the "Opened … options selected" answer to quote it.
+ const lower = `ghp_${'a1b2c3'.repeat(6)}`
+
+ catalogOf(state).plugins = [{ name: `ruflo-${lower}`, options: ['x'] }] as never
+ state.snapshot = { plugins: { installed: [{ id: `ruflo-${lower}@ruflo`, name: `ruflo-${lower}`, marketplace: 'ruflo', version: '1', scope: 'user', installPath: '/p' }] } } as never
+ const answer = await callTool('console_open', { view: 'settings', chip: lower }, deps)
+
+ // The whole answer line is withheld: only the closing pass over every answer can do that, the builder quotes the name as it is.
+ expect(answer).toContain('withheld')
+ expect(answer).not.toContain(lower)
+ })
+
+ it('the answer to a call that threw', async () => {
+ const { deps } = setup('full', 'auto')
+ const runner = (deps as unknown as { control: { runner: { runById: () => boolean } } }).control.runner
+
+ runner.runById = () => {
+ throw new Error(`boom ${HOSTILE}`)
+ }
+ clean(await callTool('console_run', { id: 'anything' }, deps), 'thrown error')
+ })
+})
diff --git a/plugins/ruflo-console/tests/model-secrets.spec.ts b/plugins/ruflo-console/tests/model-secrets.spec.ts
new file mode 100644
index 0000000000..228c6849ca
--- /dev/null
+++ b/plugins/ruflo-console/tests/model-secrets.spec.ts
@@ -0,0 +1,201 @@
+/**
+ * What console_state hands the model from the terminal page: an x.ruv.io invite code minted there (a bearer secret, xruv.ts
+ * INVITE_COMMAND) is masked in the scrollback itself, and a line holding any other secret shape is withheld whole. Real code
+ * paths: the ruflo harness runs the INVITES row's command through a fake spawn, then callTool reads the console.
+ */
+import { describe, expect, it, vi } from 'vitest'
+
+import { send, termText } from '../hooks/harness'
+import type { Host } from '../hooks/host'
+import { callTool, type ModelToolDeps } from '../hooks/model-tools'
+import { settingsOf } from '../hooks/settings'
+import { newState, type State } from '../hooks/state'
+import { INVITE_COMMAND, maskInvites } from '../hooks/xruv'
+
+const CODE = 'v2.Zk3pQ9rT_u7WmB2xL0aYc4N'
+// Built at run time so no token-shaped literal sits in this source.
+const TOKEN = `ghp_${'Ab3'.repeat(12)}`
+
+function fakeSpawn(stdout: string) {
+ return (_argv: readonly string[]) => {
+ const stream = (async function* () {
+ yield { stream: 'stdout', text: stdout }
+
+ return { code: 0, signal: null }
+ })()
+
+ return Object.assign(stream, { result: Promise.resolve({ code: 0, signal: null }), return: async () => ({ done: true, value: undefined }) }) as never
+ }
+}
+
+/** Every action is a no-op: the view only needs the closures to exist. */
+const deepNoop = (): unknown => new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : deepNoop()) })
+
+const settled = async (state: State) => {
+ for (let i = 0; i < 100 && (state.terminal.runs.size > 0 || i < 2); i++) await new Promise(resolve => setTimeout(resolve, 2))
+}
+
+/** Runs one ruflo command whose output is `stdout`, opens the terminal page as the model, and returns what console_state answers. */
+async function stateAfter(command: string, stdout: string): Promise<{ state: State; answer: string }> {
+ const state = newState({})
+ const host = { spawn: fakeSpawn(stdout), invalidate: () => undefined, after: () => ({ cancel: () => undefined }), storeSet: async () => undefined, focus: async () => undefined } as unknown as Host
+
+ state.terminal.harness = 'ruflo'
+ send(state, host, command)
+ await settled(state)
+
+ expect(settingsOf(state).ai.modelControl).toBe('read')
+ const control = { host, setView: (view: State['view']) => void (state.view = view), open: async () => undefined, actions: deepNoop(), runner: {} }
+ const deps = { state, control } as unknown as ModelToolDeps
+
+ expect(await callTool('console_open', { view: 'terminal' }, deps)).toMatch(/^Opened/)
+
+ return { state, answer: await callTool('console_state', {}, deps) }
+}
+
+describe('console_state never carries a secret from the terminal', () => {
+ it('a minted invite code is masked in the scrollback and never reaches the model', async () => {
+ const { state, answer } = await stateAfter(INVITE_COMMAND, `[OK] Invite minted\n{\n "code": "${CODE}",\n "maxUses": 25\n}\n`)
+
+ expect(state.terminal.lines.some(line => line.text.includes(CODE))).toBe(false)
+ expect(state.terminal.lines.some(line => line.text.includes('invite code, masked'))).toBe(true)
+ expect(answer).not.toContain(CODE)
+ expect(answer).toContain('maxUses')
+ })
+
+ it('a line with a token in it is withheld from the model whole, and the lines around it are not', async () => {
+ const { answer } = await stateAfter('config get', `before the token\nexport GITHUB_TOKEN=${TOKEN}\nafter the token\n`)
+
+ expect(answer).not.toContain(TOKEN)
+ expect(answer).toContain('looks like a secret: not shown')
+ expect(answer).toContain('before the token')
+ expect(answer).toContain('after the token')
+ })
+
+ it('a version with the invite prefix stays readable', () => {
+ expect(maskInvites('upgraded to v2.1.0-beta.3')).toBe('upgraded to v2.1.0-beta.3')
+ expect(termText(`code ${CODE} here`)).toBe('code v2.•••• (invite code, masked) here')
+ })
+})
+
+describe('a result or a waiting note never carries a secret to the model', () => {
+ it('lastResult.detail and waiting.note in console_state withhold a token or an invite code', async () => {
+ const { state } = await stateAfter('memory list', '[OK] nothing\n')
+ const control = { host: { invalidate: () => undefined, after: () => ({ cancel: () => undefined }) }, setView: () => undefined, open: async () => undefined, actions: deepNoop(), runner: {} }
+ const deps = { state, control } as unknown as ModelToolDeps
+
+ state.outcome = { label: 'run it', ok: false, verified: 'n/a', detail: `failed: ${TOKEN}`, atMs: Date.now() }
+ state.pending = { label: 'next', args: [], expect: 'x', askedAtMs: Date.now(), note: `invite ${CODE}` }
+ const answer = await callTool('console_state', {}, deps)
+
+ expect(answer).not.toContain(TOKEN)
+ expect(answer).not.toContain(CODE)
+ })
+
+ it('a console_run answer withholds a token in the failed run\'s detail', async () => {
+ const { setup } = await import('./fixtures/control-setup')
+ const { state, deps } = setup('write', 'auto', { 'mission-open': { label: 'open Mission Control', readOnly: true } })
+ const runner = (deps as unknown as { control: { runner: { runById: (id: string) => boolean } } }).control.runner
+
+ runner.runById = () => ((state.outcome = { label: 'open Mission Control', ok: false, verified: 'n/a', detail: `stderr: ${TOKEN}`, atMs: Date.now() + 1 }), true)
+ const answer = await callTool('console_run', { id: 'mission-open' }, deps)
+
+ expect(answer).toMatch(/Failed/)
+ expect(answer).not.toContain(TOKEN)
+ })
+})
+
+describe('the shared escape set stays linear', () => {
+ it('a long run of OSC introducers with no terminator cleans in linear time', () => {
+ const t0 = Date.now()
+
+ termText('\u009d'.repeat(100_000))
+ termText(`x${'\u009d]'.repeat(50_000)}`)
+ expect(Date.now() - t0).toBeLessThan(1_000)
+ })
+})
+
+describe('labels the person typed never carry a secret to the model', () => {
+ const labelled = async () => {
+ const { state } = await stateAfter('memory list', '[OK] nothing\n')
+ const control = { host: { invalidate: () => undefined, after: () => ({ cancel: () => undefined }) }, setView: () => undefined, open: async () => undefined, actions: deepNoop(), runner: {} }
+
+ return { state, deps: { state, control } as unknown as ModelToolDeps }
+ }
+
+ it('waiting.label, waiting.expect and lastResult.label withhold a token and mask an invite code', async () => {
+ const { state, deps } = await labelled()
+
+ state.outcome = { label: `store "${TOKEN}"`, ok: true, verified: 'n/a', detail: '', atMs: Date.now() }
+ state.pending = { label: `send ${CODE} to the room`, args: [], expect: `stored ${TOKEN}`, askedAtMs: Date.now() }
+ const answer = await callTool('console_state', {}, deps)
+
+ expect(answer).not.toContain(TOKEN)
+ expect(answer).not.toContain(CODE)
+ })
+
+ it('the "already waiting" refusal does not quote a token from the waiting label', async () => {
+ const { state, deps } = await labelled()
+
+ state.pending = { label: `store "${TOKEN}"`, args: [], expect: 'x', askedAtMs: Date.now() }
+ const answer = await callTool('console_run', { id: 'mission-open' }, deps)
+
+ expect(answer).toMatch(/already waiting/)
+ expect(answer).not.toContain(TOKEN)
+ })
+
+ it('an invite split by a zero-width character, or cut by the length limit, is still masked', async () => {
+ const { state, deps } = await labelled()
+ const split = `${CODE.slice(0, 8)}\u200b${CODE.slice(8)}`
+
+ state.outcome = { label: 'joined', ok: true, verified: 'n/a', detail: `${'x'.repeat(190)} ${CODE}`, atMs: Date.now(), lines: [`code ${split}`] }
+ const answer = await callTool('console_state', {}, deps)
+
+ expect(answer).not.toContain(CODE.slice(3, 9))
+ expect(answer).not.toContain(CODE.slice(9, 15))
+ })
+})
+
+describe('the settle answer and control characters', () => {
+ it('the "waiting" settle answer withholds a token in the expectation', async () => {
+ const { setup } = await import('./fixtures/control-setup')
+ const { state, deps } = setup('full', 'ask', { 'set-opt': { label: 'set opt' } })
+ const runner = (deps as unknown as { control: { runner: { runById: (id: string) => boolean } } }).control.runner
+
+ runner.runById = () => ((state.pending = { label: 'set ruflo-x token', args: [], expect: `ruflo-x token = ${TOKEN}`, askedAtMs: Date.now() }), true)
+ const answer = await callTool('console_run', { id: 'set-opt' }, deps)
+
+ expect(answer).toMatch(/Waiting/)
+ expect(answer).not.toContain(TOKEN)
+ })
+
+ it('an invite split by a C0 or C1 control character is still masked, and an escape sequence leaves no residue', async () => {
+ const { state } = await stateAfter('memory list', '[OK] nothing\n')
+ const control = { host: { invalidate: () => undefined, after: () => ({ cancel: () => undefined }) }, setView: () => undefined, open: async () => undefined, actions: deepNoop(), runner: {} }
+ const deps = { state, control } as unknown as ModelToolDeps
+
+ state.outcome = { label: 'joined', ok: true, verified: 'n/a', detail: `code ${CODE.slice(0, 6)}\u0001${CODE.slice(6)}`, atMs: Date.now(), lines: [`code ${CODE.slice(0, 6)}\u0085${CODE.slice(6)}`, '\u001b[31mred\u001b[0m done'] }
+ const answer = await callTool('console_state', {}, deps)
+
+ expect(answer).not.toContain(CODE.slice(6, 14))
+ expect(answer).toContain('red done')
+ expect(answer).not.toContain('[31m')
+ })
+})
+
+describe('palette entry ids', () => {
+ it('an entry whose id holds a secret shape is left out of console_state', async () => {
+ const { state } = await stateAfter('memory list', '[OK] nothing\n')
+ const control = { host: { invalidate: () => undefined, after: () => ({ cancel: () => undefined }) }, setView: () => undefined, open: async () => undefined, actions: deepNoop(), runner: {} }
+ const deps = { state, control } as unknown as ModelToolDeps
+ const palette = await import('../hooks/palette')
+ const key = `AKIA${'Q7XB'.repeat(4)}`
+ const real = palette.paletteEntries
+
+ vi.spyOn(palette, 'paletteEntries').mockImplementation((...args) => [...real(...args), { id: `auto-ses-resume-${key}`, label: 'resume session' } as never])
+ const answer = await callTool('console_state', { filter: 'resume session' }, deps)
+
+ expect(answer).not.toContain(key)
+ vi.restoreAllMocks()
+ })
+})
diff --git a/plugins/ruflo-console/tests/narrow-width.spec.ts b/plugins/ruflo-console/tests/narrow-width.spec.ts
new file mode 100644
index 0000000000..50d36c3923
--- /dev/null
+++ b/plugins/ruflo-console/tests/narrow-width.spec.ts
@@ -0,0 +1,66 @@
+/**
+ * Issue #3899: at 80 columns (tmux, cmux) the Approvals pane and a mission's objective were cut at the edge with "…", so part of the text a
+ * person has to read was gone. Prose now wraps on word breaks (views/common.ts paragraph); a word longer than the row is cut into row-sized
+ * pieces; nothing is clipped. The page still has its title and body at every width down to 40 columns.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { parseMissions } from '../hooks/data/missions'
+import { mcOf } from '../hooks/mission-control'
+import { newState } from '../hooks/state'
+import { viewText } from '../hooks/views/pane'
+
+const act = (() => {
+ const proxy: unknown = new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : proxy), apply: () => undefined })
+
+ return proxy
+})() as never
+
+describe('the Approvals pane at narrow widths (#3899)', () => {
+ for (const columns of [80, 60, 44, 40]) {
+ it(`${columns} columns: the title and the whole empty-state sentence, nothing cut`, () => {
+ const state = newState({})
+
+ state.view = 'approvals'
+ const screen = viewText({ state, nowMs: Date.now(), columns, act }, 'approvals')
+ const lines = screen.split('\n')
+
+ expect(lines[0]).toMatch(/^Approvals /)
+ expect(lines.length).toBeGreaterThan(2)
+ expect(screen).not.toContain('…')
+ expect(screen.replace(/\s+/g, ' ')).toContain('No hive-mind proposals, stealable claims, refused mods, permission denies or budget alerts waiting.')
+ expect(screen.replace(/\s+/g, ' ')).toContain('each action asks y/n before it runs; a permission deny is shown, never loosened from here')
+ expect(Math.max(...lines.map(line => line.length))).toBeLessThanOrEqual(columns)
+ })
+ }
+
+ it('a refused mod and a permission deny keep all of their text on 80 columns', () => {
+ const state = newState({})
+ const provenance = 'github.com/example-org/a-rather-long-mod-name@0123456789abcdef0123456789abcdef01234567'
+
+ state.view = 'approvals'
+ state.mods = [{ name: 'long-mod', isLoaded: false, provenance, reason: 'its signature is not from a trusted publisher' }] as never
+ state.denied = [{ atMs: 1, tool: 'mcp__ruflo__terminal_execute', reason: 'the policy forbids running shell commands from a model turn' }] as never
+ const screen = viewText({ state, nowMs: Date.now(), columns: 80, act }, 'approvals')
+ const flat = screen.replace(/\s+/g, ' ')
+
+ expect(screen).not.toContain('…')
+ expect(Math.max(...screen.split('\n').map(line => line.length))).toBeLessThanOrEqual(80)
+ expect(flat).toContain('its signature is not from a trusted publisher — to allow it, add')
+ expect(flat).toContain('(/config ruflo-mods)')
+ expect(screen.replace(/\s/g, '')).toContain(provenance)
+ expect(flat).toContain('the policy forbids running shell commands from a model turn — a deny is never loosened from here; change the policy if it is wrong')
+ })
+
+ it('a mission objective longer than the row wraps instead of being cut', () => {
+ const objective = 'Add a dark mode toggle to the settings page, persist the choice per user, and cover it with a component test and an end-to-end test'
+ const state = newState({})
+
+ state.view = 'missions'
+ state.snapshot = { plugins: { installed: [] }, missions: parseMissions(JSON.stringify({ schemaVersion: 1, contract: 'ruflo.mission-observation/1', observedAt: '2026-10-02T03:29:44.705Z', missions: [{ missionId: 'msn_wrap', objective, state: 'running', revision: 1, plan: { revision: 1, taskCount: 0, tasks: [] }, evidence: { count: 0, verified: 0 } }] })) } as never
+ mcOf(state).tab = 'record'
+ const screen = viewText({ state, nowMs: Date.now(), columns: 80, act }, 'missions')
+
+ expect(screen.replace(/\s+/g, ' ')).toContain(objective)
+ })
+})
diff --git a/plugins/ruflo-console/tests/prototype-keys.spec.ts b/plugins/ruflo-console/tests/prototype-keys.spec.ts
new file mode 100644
index 0000000000..cec48ad1d9
--- /dev/null
+++ b/plugins/ruflo-console/tests/prototype-keys.spec.ts
@@ -0,0 +1,117 @@
+/**
+ * A mission state, task status, hive role, audit severity or plugin name that is spelled like an Object.prototype key (toString, constructor,
+ * __proto__) draws as unknown, never as native code: every lookup that a file or the CLI can key is an own-key lookup.
+ * Specs ported from PR #3822 (@proffesor-for-testing).
+ */
+import { describe, expect, it } from 'vitest'
+
+import { severityOf } from '../hooks/data/cli'
+import type { ReadCache, ReaderFs } from '../hooks/data/files'
+import { parseMissions } from '../hooks/data/missions'
+import { catalogOf } from '../hooks/plugin-catalog'
+import { readSnapshot } from '../hooks/data/snapshot'
+import { missionRow } from '../hooks/mission-list'
+import { mcOf } from '../hooks/mission-control'
+import { settingsOf, type PluginConfig } from '../hooks/settings'
+import { newState } from '../hooks/state'
+import type { Actions, Ctx } from '../hooks/views/common'
+import { observationRows } from '../hooks/views/missions'
+import { viewText } from '../hooks/views/pane'
+import { HIVE_AGENTS, HIVE_FILES, WORKERS } from './fixtures/hive'
+
+const act: Actions = (() => {
+ const handler: ProxyHandler<() => void> = { get: (_t, key) => (key === 'then' ? undefined : proxy), apply: () => undefined }
+ const proxy: unknown = new Proxy(() => undefined, handler)
+ return proxy as Actions
+})()
+
+describe('a state, status, role or severity named for an Object.prototype key draws as unknown, never as native code', () => {
+ const PROTO = ['toString', 'constructor', 'valueOf', '__proto__', 'hasOwnProperty']
+ const NATIVE = /native code|function |\[object/
+ const observation = (state: string, status: string) =>
+ JSON.stringify({ schemaVersion: 1, contract: 'ruflo.mission-observation/1', observedAt: '2026-10-02T03:29:44.705Z', missions: [{ missionId: 'msn_proto', objective: 'prototype keys', state, revision: 1, plan: { revision: 1, taskCount: 1, tasks: [{ id: 't1', status }] }, evidence: { count: 0, verified: 0 } }] })
+ /** Every color a rendered tree asks for. */
+ const colorsOf = (node: unknown, out: unknown[] = []): unknown[] => {
+ if (Array.isArray(node)) for (const child of node) colorsOf(child, out)
+ else if (node !== null && typeof node === 'object') {
+ const props = (node as { props?: Record<string, unknown> }).props ?? {}
+
+ if ('color' in props) out.push(props.color)
+ colorsOf(props.children, out)
+ }
+
+ return out
+ }
+
+ for (const key of PROTO) {
+ it(`mission state and task status "${key}": the Missions list row, the record tab text and its colors`, () => {
+ const parsed = parseMissions(observation(key, key))
+ const mission = parsed?.missions[0]
+
+ expect(mission).toBeDefined()
+ expect(missionRow(mission as never, 0)).toMatch(/^○ prototype keys · /)
+
+ const state = newState({})
+
+ state.snapshot = { plugins: { installed: [] }, missions: parsed } as never
+ mcOf(state).tab = 'record'
+ const screen = viewText({ state, nowMs: 5_000, columns: 160, act }, 'missions')
+
+ expect(screen).toContain('prototype keys')
+ expect(screen).not.toMatch(NATIVE)
+ expect(screen).toContain('plan rev 1: ? t1')
+
+ const element = (type: string) => (props: Record<string, unknown>) => ({ type, props }) as never
+ const ctx = { state, nowMs: 5_000, columns: 160, act, kit: { Box: element('Box'), Text: element('Text'), Button: element('Button') }, pictures: new Map() } as unknown as Ctx
+ const colors = colorsOf(observationRows(ctx))
+
+ expect(colors.length).toBeGreaterThan(0)
+ expect(colors.filter(color => typeof color !== 'string')).toEqual([])
+ })
+ }
+
+ it('a hive worker whose role in agents.json is "toString" draws with the plain worker glyph', async () => {
+ const agents = { agents: { ...HIVE_AGENTS.agents, [WORKERS[0]]: { ...HIVE_AGENTS.agents[WORKERS[0]], config: { role: 'toString', hiveRole: 'toString' } } } }
+ const files = Object.fromEntries(Object.entries({ ...HIVE_FILES, '.claude-flow/agents.json': JSON.stringify(agents) }).map(([path, text]) => [`/work/${path}`, text]))
+ const fs: ReaderFs = {
+ read: async path => files[path] ?? Promise.reject(new Error('ENOENT')),
+ stat: async path => (files[path] !== undefined ? { mtimeMs: 1, size: (files[path] as string).length, kind: 'file' } : Promise.reject(new Error('ENOENT'))),
+ list: async () => Promise.reject(new Error('ENOENT')),
+ }
+ const state = newState({})
+
+ state.snapshot = await readSnapshot(fs, new Map() as ReadCache, '/work', '/home/dev', {}, 0)
+ expect(state.snapshot.hiveAgents.find(agent => agent.id === WORKERS[0])?.role).toBe('toString')
+ state.view = 'hive'
+ const screen = viewText({ state, nowMs: Date.parse('2026-10-02T01:10:10.000Z'), columns: 160, act }, 'hive')
+ const line = screen.split('\n').find(row => row.includes(WORKERS[0].slice(-4)) && row.includes('toString'))
+
+ expect(screen).not.toMatch(NATIVE)
+ expect(line, screen).toMatch(/●/)
+ })
+
+ it('an audit severity "constructor" ranks as no severity, not as a function', () => {
+ expect(PROTO.map(severityOf)).toEqual([null, null, null, null, null])
+ expect([severityOf('High'), severityOf('clean')]).toEqual([3, 0])
+ })
+
+ for (const name of ['constructor', 'toString']) {
+ it(`Settings for a plugin named "${name}" draws its own option descriptions and its first four options`, () => {
+ const state = newState({})
+ const schema = Object.fromEntries(['name', 'length', 'c', 'd', 'e'].map(key => [key, { title: `${key} title`, description: `${key} described`, type: 'string' }]))
+
+ state.snapshot = { plugins: { installed: [{ id: `${name}@ruflo`, name, marketplace: 'ruflo', version: '1.0.0', scope: 'user', installPath: '/p' }] } } as never
+ catalogOf(state).plugins = [{ name, options: ['name'] }] as never
+ settingsOf(state).plugin = name
+ settingsOf(state).configs.set(name, { pluginId: `${name}@m`, name, schema, inputs: {}, choices: {}, configured: [] } as unknown as PluginConfig)
+ state.view = 'settings'
+ const screen = viewText({ state, nowMs: 5, columns: 160, act }, 'settings')
+
+ expect(screen).toContain('name described')
+ expect(screen).toContain('length described')
+ expect(screen).not.toMatch(NATIVE)
+ expect(screen).not.toMatch(/^\s+(Object|Function|1)\s*$/m)
+ })
+ }
+})
+
diff --git a/v3/docs/adr/ADR-407-ruflo-console-cockpit.md b/v3/docs/adr/ADR-407-ruflo-console-cockpit.md
index 718063915d..55dc3274ca 100644
--- a/v3/docs/adr/ADR-407-ruflo-console-cockpit.md
+++ b/v3/docs/adr/ADR-407-ruflo-console-cockpit.md
@@ -281,3 +281,21 @@ one), was aborted at 90 s and showed the raw "still running after 90000ms". Now
- A timeout, or `ENOTCACHED` from `npx --offline`, ends the action as an error naming the fix: `npm i -g ruflo`, or
`npx -y @claude-flow/cli@latest --version` once. Read probes keep their own limits and the existing "ruflo CLI not cached" hint.
- Reads and other callers that build `[...CLI_PREFIXES[cli], ...]` themselves (drill logs, the terminal harness, mission specs) are unchanged.
+
+## Update 2026-10-08: a Yes names its card (0.40.2)
+
+§8's confirm step ran whatever was pending when the Yes arrived. A second ask that replaced the first card (the person's own ask can still replace a
+waiting card) made a Yes pressed on the first card run the second: a `memory store` argv ran from a Yes meant for something else. Now
+(`hooks/runner.ts`):
+
+- Every ask the runner queues gets an id (`Pending.id`, a counter that only rises). The confirm row's Yes, "Always allow" and "Always accept
+ AI turns" buttons carry the id of the card they were drawn for, and `runner.confirm(seen)` runs only when `seen` is the id of the card now
+ waiting. Otherwise it runs nothing, leaves the new card in place, answers "the card changed before your Yes", and records an event.
+ "Always allow" and "Always accept" on a replaced card also remember nothing and keep the draft.
+- A Yes without an id (`/ruflo yes`, the terminal's Enter on the asked line) still answers the card that is waiting; those read the card on
+ screen in the same step. A second Yes on a card that already ran finds nothing waiting and is a quiet no-op, so it cannot overwrite the answer.
+- An ask of Claude's that was screened first and so landed after its tool call returned is checked against the level and Stop as they are
+ when it lands (`landingRefusal`, model-tools.ts); a level lowered while the screen looked wins.
+
+Regression tests: `tests/deferred-asks.spec.ts`. The same release wraps Approvals and a mission's objective at narrow widths instead of
+cutting them with "…" (#3899, `paragraph` in `views/common.ts`, `tests/narrow-width.spec.ts`).
diff --git a/v3/docs/adr/ADR-444-claude-controls-the-console.md b/v3/docs/adr/ADR-444-claude-controls-the-console.md
index ba8e404ff5..b90586ab92 100644
--- a/v3/docs/adr/ADR-444-claude-controls-the-console.md
+++ b/v3/docs/adr/ADR-444-claude-controls-the-console.md
@@ -65,3 +65,23 @@ With `ask` as the default, a person who had turned control on found Claude parke
## Update (2026-10-05): the default is read + ask
Default `modelControl` is now `read` and default `modelConfirm` is `ask`, at the owner's request, so Claude can open pages and read the state of a console without anyone first finding the setting. `read` never acts, so the earlier "parked on every write" problem that moved the confirm default to `auto` cannot arise at the default level; a pending ask is now also shown as a banner in the console. A missing confirm mode is `ask`: only a saved `auto` is auto, and a saved `off` stays off. Raising the level (write and above) remains the person's choice in Settings → Claude control. The four tools now register in every session by default, which adds their few hundred tokens to each request.
+
+## Update 2026-10-08: one path to the model (0.40.2)
+
+Not every string the tools returned went through the sanitiser: a failed run's `stderr:` detail, the "already waiting" refusal, the "Waiting for
+the person" and "Started" answers, refusals that quote what the model typed (an unknown id, field or chip), a palette entry id and a thrown
+error each quoted their text with `plain()` alone, so a token or an x.ruv.io invite code in a label, an expectation or stderr reached the
+model; an invite split by a control character (C0, C1, zero-width) was not masked; and a version such as `v2.1.0-beta.3` was masked as one.
+`hooks/model-tools.ts` now has one function, `modelLine(raw, max)`:
+
+1. escape sequences are stripped (the shared `ESCAPES`, now linear: an unterminated OSC ends at the next introducer or the end of the text);
+2. tab and line breaks become a space, every other control and invisible character is removed without a space, so none can split a credential
+ past a mask;
+3. the line is cut to `max`;
+4. it is withheld whole (`(line withheld: it looks like a secret: not shown)`) when the original, the joined or the cut form holds a secret
+ shape or an invite code (a version such as `v2.1.0-beta.3` is not one; a code the terminal already masked is not either).
+
+`console_state` builds every field with it, every `callTool` answer leaves through `modelLines` (each line again), `refuse` quotes through it,
+and a palette entry whose id holds a secret shape is left out of the list. A new builder that skips it fails `tests/model-facing.spec.ts`,
+which feeds each builder a token, an invite code (whole and split) and an escape sequence. See also ADR-450 T17 and ADR-407's 2026-10-08 update
+(a Yes runs only the card it was pressed on).
diff --git a/v3/docs/adr/ADR-450-mod-system-threat-model.md b/v3/docs/adr/ADR-450-mod-system-threat-model.md
index 8c332522a9..4ebab82853 100644
--- a/v3/docs/adr/ADR-450-mod-system-threat-model.md
+++ b/v3/docs/adr/ADR-450-mod-system-threat-model.md
@@ -264,3 +264,5 @@ Sections 1-8 are left as written; this section records what happened after. The
**Human decisions still open.** (1) ~~Whether `modelConfirm` should default to `ask`~~ — resolved 2026-10-05: the default is now `ask`, with `modelControl: 'read'`; T8's always-ask classes still bound `auto`. (2) Whether T9's default becomes `refuse-risky`.
**Not verified:** the regression-test counts in section 7 were not re-run for this update; no code or test result was re-measured here, only PR state and the files named above.
+
+**Update 2026-10-08 (console 0.40.2): T17 is no longer "held, no change needed".** A Yes pressed on a card that a later ask replaced ran the later card. Every confirm card now has an id, the Yes buttons carry it, and a stale Yes runs nothing (ADR-407's 2026-10-08 update). An ask of Claude's that was screened first and lands while no `console_run`/`console_set` call is running is checked against the level and Stop as they are then (`landingRefusal`). Everything returned to the model passes one sanitiser, `modelLine` (ADR-444's 2026-10-08 update). Regression tests: `deferred-asks.spec.ts`, `model-facing.spec.ts`, `model-secrets.spec.ts`, `escape-linear.spec.ts`.