🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(console): Workflows review - unread cost is n/a not $0, export carries the Cost figure, key hints name real keys
ruv7ee6b0a567cc
diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.tsindex 799a40b305..052a95ed8e 100644--- a/plugins/ruflo-console/hooks/data/parse.ts+++ b/plugins/ruflo-console/hooks/data/parse.ts@@ -15,10 +15,10 @@ 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.-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\\\\)|\\u009d[^\\u0007\\u009c]*[\\u0007\\u009c]|(?:\\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.-const HIDDEN = new RegExp('[\\u0000-\\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')+export const HIDDEN = new RegExp('[\\u0000-\\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')/** Plain printable text of at most `max` characters: no escape sequence, control, hidden or bidi-override character reaches the terminal. */export function plain(value: unknown, max = 200): string {diff --git a/plugins/ruflo-console/hooks/data/wf-alerts.ts b/plugins/ruflo-console/hooks/data/wf-alerts.tsindex 9d3771b492..80a23e72b6 100644--- a/plugins/ruflo-console/hooks/data/wf-alerts.ts+++ b/plugins/ruflo-console/hooks/data/wf-alerts.ts@@ -12,7 +12,6 @@ import type { WfRun } from './workflows'export type GuardOptions = { wfBudgetRunUsd: number; wfBudgetDayUsd: number; wfAlertRules: string }-export const GUARD_DEFAULTS: GuardOptions = { wfBudgetRunUsd: 0, wfBudgetDayUsd: 0, wfAlertRules: '' }const usdOption = (value: unknown): number => {const amount = typeof value === 'number' ? value : typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value.trim()) ? Number(value) : Number.NaNdiff --git a/plugins/ruflo-console/hooks/data/wf-clean.ts b/plugins/ruflo-console/hooks/data/wf-clean.tsindex a54dce502b..a23f575b52 100644--- a/plugins/ruflo-console/hooks/data/wf-clean.ts+++ b/plugins/ruflo-console/hooks/data/wf-clean.ts@@ -4,13 +4,11 @@* the last tool, a result preview), so a token a prompt or a result carried can reach no cell, log line or notice.* Ids, paths and numbers are left alone: a session id is 36 characters of `[0-9a-f-]` and would read as a key to the mask.*/+import { ESCAPES, HIDDEN } from './parse'import { maskSecrets, type WfAgent, type WfPhase, type WfRun } from './workflows'-// eslint-disable-next-line no-control-regex-const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g--/** Free text for a cell or a notice: control characters (an ANSI escape drives a terminal) become spaces, credentials are masked. */-export const cleanText = (value: string): string => maskSecrets(value.replace(CONTROL, ' '))+/** Free text for a cell or a notice: escape sequences are dropped whole, control, zero-width and bidi characters become spaces, credentials are masked. */+export const cleanText = (value: string): string => maskSecrets(value.replace(ESCAPES, '').replace(HIDDEN, ' '))const opt = (value: string | undefined): string | undefined => (value === undefined ? undefined : cleanText(value))diff --git a/plugins/ruflo-console/hooks/data/wf-cost.ts b/plugins/ruflo-console/hooks/data/wf-cost.tsindex 2eda1d8517..b64fb9f61b 100644--- a/plugins/ruflo-console/hooks/data/wf-cost.ts+++ b/plugins/ruflo-console/hooks/data/wf-cost.ts@@ -261,9 +261,12 @@ export function fmtUsd(usd: number): string {return usd <= 0 ? '$0' : usd < 0.001 ? '<$0.001' : usd < 0.1 ? `$${usd.toFixed(3)}` : usd < 100 ? `$${usd.toFixed(2)}` : `$${Math.round(usd)}`}+/** A sum of nothing read: no token seen and some part missing. It is not $0, it is unknown. */+export const isUnread = (cost: Costed): boolean => cost.pricedTokens === 0 && cost.unpricedTokens === 0 && cost.isFloor+/** A cost as a cell says it: `≥` for a floor, `≈` for a rough price, "no price" where tokens had none, "n/a" where nothing was read. */export function fmtCosted(cost: Costed | undefined): string {- if (cost === undefined) return 'n/a'+ if (cost === undefined || isUnread(cost)) return 'n/a'if (cost.pricedTokens === 0 && cost.unpricedTokens > 0) return 'no price'if (cost.pricedTokens === 0) return '$0'diff --git a/plugins/ruflo-console/hooks/data/wf-triage.ts b/plugins/ruflo-console/hooks/data/wf-triage.tsindex cf1a26a20c..10c635ca05 100644--- a/plugins/ruflo-console/hooks/data/wf-triage.ts+++ b/plugins/ruflo-console/hooks/data/wf-triage.ts@@ -7,15 +7,14 @@* result (the page says so). A result that merely MENTIONS an error is not an error: for an agent that finished, only a result that begins* with one is.*/+import { ESCAPES, HIDDEN } from './parse'import { maskSecrets, jsonLines, type WfAgent, type WfRun } from './workflows'export type TriageKind = 'ok' | 'empty' | 'error' | 'timeout' | 'stale' | 'pending'export type Triage = { kind: TriageKind; /** One short reason, for the row. */ why: string; /** The first error line of the result, masked and without control characters. */ firstError?: string }-// eslint-disable-next-line no-control-regex-const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g-const tidy = (value: string, max: number): string => maskSecrets(value.replace(CONTROL, ' ').replace(/\s+/g, ' ').trim()).slice(0, max)+const tidy = (value: string, max: number): string => maskSecrets(value.replace(ESCAPES, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()).slice(0, max)const ERROR_START = /^\W{0,3}(?:[A-Z][A-Za-z]*Error\s*[:(]|error\s*[:(]|fatal\s*[:(]|panic(?:ked)?\b|exception\s*[:(]|traceback \(most recent|npm ERR!|✖|✗)/iconst ERROR_ANYWHERE = /\b(?:[A-Z][A-Za-z]*Error|ENOENT|EACCES|EPERM|ECONN[A-Z]+|ETIMEDOUT|ENOSPC)\b|\b(?:error|fatal|panic|failed|exception)\s*[:(]|\bTraceback\b|\bcould not\b|\bunable to\b|\bcannot\b/idiff --git a/plugins/ruflo-console/hooks/data/wf-worktrees.ts b/plugins/ruflo-console/hooks/data/wf-worktrees.tsindex 3efd7c5030..0aafe6aa86 100644--- a/plugins/ruflo-console/hooks/data/wf-worktrees.ts+++ b/plugins/ruflo-console/hooks/data/wf-worktrees.ts@@ -35,6 +35,8 @@ export const REMOVE_MAX = 10/** The process check must be this fresh to plan a removal, and must have seen at least MIN_PROCS working directories. */export const PROCS_FRESH_MS = 120_000export const MIN_PROCS = 3+/** The ignored listing is read up to here; the names are matched, never shown. */+export const IGNORED_MAX_BYTES = 1_000_000/** Dirty lines are counted up to here. */export const DIRTY_CAP = 200/** The process listing is read up to here; a longer one makes the check refuse rather than guess. */@@ -43,7 +45,11 @@ export const PROCS_MAX_BYTES = 4_000_000export const REMOVABLE_DIRS = ['.claude/worktrees', '.git-worktrees'] as constexport const LIST_ARGV = (dir: string): readonly string[] => ['git', '-C', dir, 'worktree', 'list', '--porcelain']-export const STATUS_ARGV = (dir: string): readonly string[] => ['git', '-C', dir, 'status', '--porcelain=v1']+// status is the one probe that can run a program from the repository's config (core.fsmonitor) and that refreshes the index (a write, and a lock another+// session's git may want): both are switched off, after '-C <dir>' so the directory stays the third word.+export const STATUS_ARGV = (dir: string): readonly string[] => ['git', '-C', dir, '--no-optional-locks', '-c', 'core.fsmonitor=false', 'status', '--porcelain=v1']+/** Ignored files and folders (a folder is one entry): 'git worktree remove' deletes these too, and they are where a .env or a key lives. */+export const IGNORED_ARGV = (dir: string): readonly string[] => ['git', '-C', dir, '--no-optional-locks', 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory']export const AHEAD_ARGV = (dir: string): readonly string[] => ['git', '-C', dir, 'rev-list', '--left-right', '--count', 'origin/main...HEAD']export const REF_ARGV = (dir: string): readonly string[] => ['git', '-C', dir, 'log', '-1', '--format=%ct', 'origin/main']export const REMOVE_ARGV = (main: string, path: string): readonly string[] => ['git', '-C', main, 'worktree', 'remove', path]@@ -55,6 +61,12 @@ const CONTROL = /[\u0000-\u001f\u007f-\u009f]//** An absolute path with no control character and no `..` part: the only kind that reaches a command. */export const isSafePath = (path: string): boolean => path.length > 1 && path.length <= 1024 && path.startsWith('/') && !CONTROL.test(path) && !path.split('/').includes('..')+const SECRETISH_NAME = /^(?:\.env(?:\..+)?|\.npmrc|\.netrc|\.pgpass|\.secrets?|secrets?(?:\..+)?|credentials(?:\..+)?|id_(?:rsa|dsa|ecdsa|ed25519)|.+\.(?:pem|key|p12|pfx|jks|keystore|secret))\/?$/i++/** How many entries of an ignored listing (git ls-files --ignored) are named like a secret or a key (.env*, *.pem, id_rsa, credentials…). Null input is unknown. */+export const countIgnoredSecrets = (listing: string | null): number | null =>+ listing === null ? null : listing.slice(0, IGNORED_MAX_BYTES).split('\n').filter(line => SECRETISH_NAME.test(line.slice(line.lastIndexOf('/', line.length - 2) + 1))).length+export type WtEntry = { path: string; head: string; branch: string | null; isDetached: boolean; isBare: boolean; isLocked: boolean; isPrunable: boolean; isMain: boolean; isSafe: boolean }/** `git worktree list --porcelain` as entries. Blocks end at a blank line; unknown keys are ignored; the first entry is the main worktree. */@@ -146,6 +158,8 @@ export function makerOf(entry: Pick<WtEntry, 'path' | 'branch'>, runs: readonlyexport type WtRow = WtEntry & {/** Dirty lines (untracked files count), up to DIRTY_CAP; null when the probe failed. */dirty: number | null+ /** Ignored files named like a secret (they would go with the directory); null when the probe failed. */+ ignoredSecrets: number | nullahead: number | nullbehind: number | nullcreatedMs: number | null@@ -165,16 +179,17 @@ const oneLine = async (io: WtIo, argv: readonly string[], timeoutMs: number): Prexport const isCurrentDir = (cwd: string, path: string): boolean => cwd === path || cwd.startsWith(`${path}/`)async function probeOne(io: WtIo, entry: WtEntry, cwd: string, runs: readonly WfRun[]): Promise<WtRow> {- const base: WtRow = { ...entry, dirty: null, ahead: null, behind: null, createdMs: null, maker: makerOf(entry, runs), isCurrent: isCurrentDir(cwd, entry.path) }+ const base: WtRow = { ...entry, dirty: null, ignoredSecrets: null, ahead: null, behind: null, createdMs: null, maker: makerOf(entry, runs), isCurrent: isCurrentDir(cwd, entry.path) }if (!entry.isSafe || entry.isBare || entry.isPrunable) return base- const [status, counts, link] = await Promise.all([oneLine(io, STATUS_ARGV(entry.path), 30_000), oneLine(io, AHEAD_ARGV(entry.path), 15_000), io.stat(`${entry.path}/.git`).catch(() => undefined)])+ const [status, counts, ignored, link] = await Promise.all([oneLine(io, STATUS_ARGV(entry.path), 30_000), oneLine(io, AHEAD_ARGV(entry.path), 15_000), oneLine(io, IGNORED_ARGV(entry.path), 30_000), io.stat(`${entry.path}/.git`).catch(() => undefined)])const pair = counts === null ? null : /^(\d+)\s+(\d+)\s*$/.exec(counts)return {...base,dirty: status === null ? null : Math.min(DIRTY_CAP, status.split('\n').filter(line => line.trim() !== '').length),+ ignoredSecrets: countIgnoredSecrets(ignored),behind: pair === null ? null : Number(pair[1]),ahead: pair === null ? null : Number(pair[2]),createdMs: typeof link?.mtimeMs === 'number' && link.mtimeMs > 0 ? link.mtimeMs : null,@@ -233,6 +248,8 @@ export function whyKept(row: WtRow, read: Pick<WtRead, 'root' | 'hasRef'>, checkif (!isRemovableDir(read.root, row.path)) return `outside ${REMOVABLE_DIRS.join(' and ')} under the main worktree`if (row.dirty === null) return 'not known whether it has changes'if (row.dirty > 0) return `${row.dirty >= DIRTY_CAP ? `${DIRTY_CAP}+` : row.dirty} changed or untracked file${row.dirty === 1 ? '' : 's'}`+ if (row.ignoredSecrets === null) return 'not known whether it has ignored files such as a .env'+ if (row.ignoredSecrets > 0) return `${row.ignoredSecrets} ignored file${row.ignoredSecrets === 1 ? '' : 's'} named like a secret (.env, a key): removing the directory would delete ${row.ignoredSecrets === 1 ? 'it' : 'them'}`if (!read.hasRef || row.ahead === null) return 'origin/main is not known here, so merged cannot be told'if (row.ahead > 0) return `${row.ahead} commit${row.ahead === 1 ? '' : 's'} not in origin/main`if (row.createdMs === null) return 'its age is not known'diff --git a/plugins/ruflo-console/hooks/data/workflows-read.ts b/plugins/ruflo-console/hooks/data/workflows-read.tsindex 3dbb8bce7e..6deab5d4dc 100644--- a/plugins/ruflo-console/hooks/data/workflows-read.ts+++ b/plugins/ruflo-console/hooks/data/workflows-read.ts@@ -67,7 +67,7 @@ export async function readWorkflowRuns(fs: WorkflowFs, cache: ReadCache, optionschosen.map(async ({ session, id }) => {const dir = under(root, `${session}/subagents/workflows/${id}`)const entries = await safeList(fs, dir)- const text = async (path: string, max?: number) => (await readBounded(fs, cache, path, max)).text+ const text = async (path: string, max?: number) => (await readBounded(fs, cache, path, max, true)).textconst record = await text(under(root, `${session}/workflows/${id}.json`), 6_000_000)const scripts = record === null ? await safeList(fs, under(root, `${session}/workflows/scripts`)) : []const scriptName = scripts.find(entry => entry.name.endsWith(`-${id}.js`))?.namediff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.tsindex 419d51937d..f3a347800c 100644--- a/plugins/ruflo-console/hooks/data/workflows.ts+++ b/plugins/ruflo-console/hooks/data/workflows.ts@@ -11,7 +11,7 @@* Unknown event types and keys are ignored, a half-written last line is dropped, and a missing source is a missing fact:* nothing here is estimated.*/-import { agentLabels, shortId, type AgentRecord, type SwarmInfo } from './parse'+import { agentLabels, ESCAPES, HIDDEN, shortId, type AgentRecord, type SwarmInfo } from './parse'export type AgentState = 'running' | 'done' | 'failed' | 'stale' | 'idle' | 'queued'@@ -64,17 +64,35 @@ export type WfRun = {}const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)-/** Control characters (an ANSI escape in a label would drive the terminal) are dropped from every string a file supplies. */-// eslint-disable-next-line no-control-regex-const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g+/** Escape sequences go whole (an OSC title or a hyperlink would otherwise leave its text behind), then control, zero-width and bidi-override characters (they reorder or hide text) become spaces: every string a file supplies passes here. */+const CONTROL = HIDDENconst str = (value: unknown, max = 200): string | undefined => {- const clean = typeof value === 'string' ? value.replace(CONTROL, ' ').slice(0, max) : ''+ const clean = typeof value === 'string' ? value.replace(ESCAPES, '').replace(CONTROL, ' ').slice(0, max) : ''return clean === '' ? undefined : clean}/** A result preview is agent output: anything shaped like a credential is masked before it is kept or drawn. */-const SECRETISH = /\b(?:sk|pk|ghp|gho|ghs|github_pat|xox[abprs]|AKIA|AIza)[-_A-Za-z0-9]{12,}|\bBearer\s+\S{8,}|\b[A-Za-z0-9+_-]{32,}={0,2}|(?:key|token|secret|passw(?:or)?d)\s*[=:]\s*\S+/gi+const SECRETISH = new RegExp(+ [+ // Vendor prefixes with a long tail (sk-ant-..., ghp_..., xoxb-..., AKIA..., AIza...), and the ones that need a separator so a plain word cannot match.+ String.raw`\b(?:sk|pk|ghp|gho|ghs|github_pat|xox[abprs]|xapp|AKIA|ASIA|AIza)[-_A-Za-z0-9]{12,}`,+ String.raw`\b(?:glpat|npm|hf|dop_v1|shpat|whsec|rk_live|sk_live|ya29)[-_.][-_.A-Za-z0-9]{12,}`,+ String.raw`\bBearer\s+\S{8,}`,+ // A JSON web token: three dot-separated base64url parts, the first starting eyJ.+ String.raw`\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.?[A-Za-z0-9_-]*`,+ // A long unbroken run of key-alphabet characters.+ String.raw`\b[A-Za-z0-9+_-]{32,}={0,2}`,+ // A private key block (whole when it ends in the text, else from its header to the end), and user:password@ in a URL.+ String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)`,+ String.raw`\b[a-z][a-z0-9+.-]*://[^\s/:@]+:[^\s/@]+@`,+ // key=value, "key": "value", Authorization: Bearer x, --token x. The key may be quoted; the value may be a quoted string or follow Bearer/Basic/Token.+ String.raw`(?:key|token|secret|passw(?:or)?d|pwd|passphrase|credential|authorization)["']?\s*[=:]\s*(?:(?:Bearer|Basic|Token)\s+)?(?:"[^"]*"|'[^']*'|\S+)`,+ String.raw`\bpass["']?\s*=\s*(?:"[^"]*"|'[^']*'|\S+)`,+ String.raw`(?:^|\s)--?(?:token|password|passwd|pwd|secret|api-?key|auth(?:orization)?|access-?key|client-?secret)(?:=|\s+)\S+`,+ ].join('|'),+ 'gi',+)export const maskSecrets = (text: string): string => text.replace(SECRETISH, '‹masked›')const num = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)@@ -116,7 +134,7 @@ export function parseJournal(text: string | null): { isLaunched: boolean; agentsbyId.set(id, { agentId: id, label: str(event.label, 80) ?? id, hasResult: false, ...(phase !== undefined && { phase }) })} else if (event.type === 'result' && id !== undefined) {const held = byId.get(id) ?? { agentId: id, label: id, hasResult: false }- const preview = typeof event.result === 'string' ? maskSecrets(event.result.replace(CONTROL, ' ').replace(/\s+/g, ' ')).slice(0, 160) : asRecord(event.result) !== null ? `structured result (${Object.keys(event.result as object).length} fields)` : undefined+ const preview = typeof event.result === 'string' ? maskSecrets(event.result.replace(ESCAPES, '').replace(CONTROL, ' ').replace(/\s+/g, ' ')).slice(0, 160) : asRecord(event.result) !== null ? `structured result (${Object.keys(event.result as object).length} fields)` : undefinedbyId.set(id, { ...held, hasResult: true, ...(preview !== undefined && preview !== '' && { resultPreview: preview }) })}diff --git a/plugins/ruflo-console/hooks/views/wf-fold.ts b/plugins/ruflo-console/hooks/views/wf-fold.tsindex 5cd5473f54..a66ca077b2 100644--- a/plugins/ruflo-console/hooks/views/wf-fold.ts+++ b/plugins/ruflo-console/hooks/views/wf-fold.ts@@ -8,8 +8,6 @@ import { button, row, text, type Ctx } from './common'const open = new Set<string>()-export const isFolded = (id: string): boolean => !open.has(id)-/** For tests. */export const resetFolds = (): void => open.clear()diff --git a/plugins/ruflo-console/hooks/views/wf-templates.ts b/plugins/ruflo-console/hooks/views/wf-templates.tsindex f10d668668..74f5ef83ac 100644--- a/plugins/ruflo-console/hooks/views/wf-templates.ts+++ b/plugins/ruflo-console/hooks/views/wf-templates.ts@@ -9,6 +9,7 @@ import type { RenderElement } from 'claude-code'import type { ActionSpec } from '../actions'import { plain } from '../data/parse'+import { cleanText } from '../data/wf-clean'import { estimate, hasMasked, missingOf, promptOf, templateById, TEMPLATES, valuesOf, AGENTS_MAX, TEXT_MAX, type Param, type Template } from '../data/wf-templates'import type { Host } from '../host'import type { State } from '../state'@@ -108,7 +109,7 @@ export function launchSpec(env: SlotEnv): ActionSpec | null {if (state.turnActive) await host.fillPrompt(prompt)else await host.submitPrompt(prompt)} catch (error) {- state.outcome = { label: 'launch workflow template', ok: false, verified: 'n/a', detail: plain(error instanceof Error ? error.message : String(error), 140) || 'refused', atMs: Date.now() }+ state.outcome = { label: 'launch workflow template', ok: false, verified: 'n/a', detail: cleanText(plain(error instanceof Error ? error.message : String(error), 140)) || 'refused', atMs: Date.now() }host.invalidate()}},diff --git a/plugins/ruflo-console/hooks/views/wf-triage.ts b/plugins/ruflo-console/hooks/views/wf-triage.tsindex 1753bd9129..ad5f6f47f5 100644--- a/plugins/ruflo-console/hooks/views/wf-triage.ts+++ b/plugins/ruflo-console/hooks/views/wf-triage.ts@@ -7,7 +7,7 @@import type { RenderElement } from 'claude-code'import { newAlerts } from '../data/wf-alerts'-import { billedTokens, fmtCosted, fmtUsd } from '../data/wf-cost'+import { billedTokens, fmtCosted, fmtUsd, isUnread } from '../data/wf-cost'import { failedOf, rerunText, resultsOfJournal, triageRun, triageStrip, type TriageItem } from '../data/wf-triage'import { fmtTokens, modelName, type WfRun } from '../data/workflows'import { under } from '../data/files'@@ -132,7 +132,7 @@ export function costRows(env: SlotEnv): RenderElement[] {const { coverage } = guards- rows.push(kv(ctx, 'run', `${fmtCosted(cost.total)} · ${fmtTokens(billedTokens(cost.total), cost.total.isFloor)} billed tokens (all request buckets) · ${cost.covered} of ${cost.count} agents read`, cost.total.isFloor ? THEME.warn : undefined))+ rows.push(kv(ctx, 'run', `${fmtCosted(cost.total)} · ${isUnread(cost.total) ? 'n/a' : fmtTokens(billedTokens(cost.total), cost.total.isFloor)} billed tokens (all request buckets) · ${cost.covered} of ${cost.count} agents read`, cost.total.isFloor ? THEME.warn : undefined))rows.push(...notes(ctx, `Transcripts: up to ${mb(TRANSCRIPT_CAP)} each (a larger one is read from its end: ≥); at most ${mb(READ_BUDGET)} parsed per refresh; ${coverage.read} of ${coverage.total} read${coverage.left > 0 ? `, ${coverage.left} wait for the next refresh` : ''}. ≥ marks a floor, ≈ a family price.`))if (cost.total.unpricedModels.length > 0) rows.push(text(ctx, `no price for ${cost.total.unpricedModels.slice(0, 3).map(model => modelName(model)).join(', ')}: its tokens are counted, its dollars are not`, { color: THEME.warn }))@@ -141,7 +141,7 @@ export function costRows(env: SlotEnv): RenderElement[] {const mine = cost.phases.get(entry.title)const here = entry.title === phase?.title- rows.push(text(ctx, `${here ? '▸' : ' '} ${clip(entry.title, 24).padEnd(24)} ${fmtCosted(mine).padEnd(14)} ${mine === undefined ? 'n/a' : `${fmtTokens(billedTokens(mine), mine.isFloor)} tok`}`, here ? { bold: true } : { dimColor: true }))+ rows.push(text(ctx, `${here ? '▸' : ' '} ${clip(entry.title, 24).padEnd(24)} ${fmtCosted(mine).padEnd(14)} ${mine === undefined || isUnread(mine) ? 'n/a' : `${fmtTokens(billedTokens(mine), mine.isFloor)} tok`}`, here ? { bold: true } : { dimColor: true }))}if (run.phases.length > 10) rows.push(text(ctx, `+${run.phases.length - 10} more phases`, { dimColor: true }))@@ -149,7 +149,7 @@ export function costRows(env: SlotEnv): RenderElement[] {if (phase !== null) {for (const agent of phase.agents.slice(0, 10)) {const mine = cost.agents.get(agent.id)- rows.push(text(ctx, ` ${clip(agent.label, 26).padEnd(26)} ${modelName(agent.model).padEnd(11)} ${fmtCosted(mine).padEnd(12)} ${mine === undefined ? 'n/a' : `${fmtTokens(billedTokens(mine), mine.isFloor)} tok`}`, { dimColor: true }))+ rows.push(text(ctx, ` ${clip(agent.label, 26).padEnd(26)} ${modelName(agent.model).padEnd(11)} ${fmtCosted(mine).padEnd(12)} ${mine === undefined || isUnread(mine) ? 'n/a' : `${fmtTokens(billedTokens(mine), mine.isFloor)} tok`}`, { dimColor: true }))}if (phase.agents.length > 10) rows.push(text(ctx, ` +${phase.agents.length - 10} more agents`, { dimColor: true }))diff --git a/plugins/ruflo-console/hooks/views/wf-worktrees.ts b/plugins/ruflo-console/hooks/views/wf-worktrees.tsindex fc6c1fd95d..bf02454fa4 100644--- a/plugins/ruflo-console/hooks/views/wf-worktrees.ts+++ b/plugins/ruflo-console/hooks/views/wf-worktrees.ts@@ -158,7 +158,7 @@ export function removalSpec(env: SlotEnv): ActionSpec | null {declared: 'delete',shows: targets.map(path => REMOVE_ARGV(root, path).join(' ')).join(' · '),expect: 'each directory gone and no longer in git worktree list',- note: `Removes only these ${count} worktree director${count === 1 ? 'y' : 'ies'} (branches stay). Each is re-checked just before it goes, one at a time, with no --force: git refuses a dirty or locked one.${plan.more > 0 ? ` ${plan.more} more qualify and wait for the next confirm.` : ''}`,+ note: `Removes only these ${count} worktree director${count === 1 ? 'y' : 'ies'} (branches stay; files git ignores, such as build output, go with the directory). Each is re-checked just before it goes, one at a time, with no --force: git refuses a dirty or locked one.${plan.more > 0 ? ` ${plan.more} more qualify and wait for the next confirm.` : ''}`,run: async () => {const io = ioOf(host)const gone: string[] = []@@ -182,7 +182,7 @@ export function removalSpec(env: SlotEnv): ActionSpec | null {const result = await host.run(REMOVE_ARGV(root, path), 60_000)if (result.exitCode === 0) gone.push(label)- else skipped.push(`${label}: git said ${plain(result.stderr || result.stdout, 100) || `exit ${result.exitCode}`}`)+ else skipped.push(`${label}: git said ${cleanText(plain(result.stderr || result.stdout, 100)) || `exit ${result.exitCode}`}`)} catch (error) {skipped.push(`${label}: ${failureOf(error)}`)}diff --git a/plugins/ruflo-console/hooks/views/workflows.ts b/plugins/ruflo-console/hooks/views/workflows.tsindex e9387adb69..a237352c2d 100644--- a/plugins/ruflo-console/hooks/views/workflows.ts+++ b/plugins/ruflo-console/hooks/views/workflows.ts@@ -123,7 +123,7 @@ function inspect(ctx: Ctx, run: WfRun, agent: WfAgent, hooks: WorkflowsHooks): R* is the ruflo agents' stop and spawn, each behind the confirm card.*/export function workflowsView(ctx: Ctx, model: WorkflowsModel | null, ui: WfUi, hooks: WorkflowsHooks): RenderElement {- const rows: RenderElement[] = [rule(ctx, 'Workflows', model === null ? '' : `${model.runs.length} runs · j/k move · h/l column · Enter inspect`)]+ const rows: RenderElement[] = [rule(ctx, 'Workflows', model === null ? '' : `${model.runs.length} runs · j/k move · b/l column · d inspect`)]if (model === null) return col(ctx, [...rows, text(ctx, 'reading workflow runs…', { dimColor: true })], 'workflows')@@ -177,7 +177,7 @@ export function workflowsView(ctx: Ctx, model: WorkflowsModel | null, ui: WfUi,}if (model.more > 0) rows.push(text(ctx, `+${model.more} older runs not shown`, { dimColor: true }))- if (wide && !here.ui.isInspecting) rows.push(text(ctx, `${shortId(run.id)} · Enter inspects the agent · [ ] switches run`, { dimColor: true }))+ if (wide && !here.ui.isInspecting) rows.push(text(ctx, `${shortId(run.id)} · d inspects the agent · u/i switches run`, { dimColor: true }))return col(ctx, rows, 'workflows')}diff --git a/plugins/ruflo-console/hooks/wf-cost-live.ts b/plugins/ruflo-console/hooks/wf-cost-live.tsindex 1c16f3d67b..5a17229e76 100644--- a/plugins/ruflo-console/hooks/wf-cost-live.ts+++ b/plugins/ruflo-console/hooks/wf-cost-live.ts@@ -11,6 +11,7 @@import { agentKey, evaluateGuards, NO_RULES, parseGuardRules, trackProgress, type GuardAlert, type GuardRules, type Mark } from './data/wf-alerts'import { costRun, parsePriceBook, spendOf, usageOfTranscript, type AgentUsage, type PriceBook, type RunCost } from './data/wf-cost'import { trackerOf } from './data/cost-ledger'+import { cleanText } from './data/wf-clean'import { readBounded, under } from './data/files'import { TAIL_BYTES, TRANSCRIPT_CAP, type WorkflowFs } from './data/workflows-read'import type { WfRun } from './data/workflows'@@ -71,7 +72,8 @@ const rememberParsed = (path: string, entry: Parsed): void => {async function usageOf(fs: WorkflowFs, path: string, budget: { left: number; bytes: number }): Promise<{ usage: AgentUsage } | { later: boolean }> {const stat = await fs.stat(path).catch(() => undefined)- if (stat === undefined || typeof stat.size !== 'number') return { later: false }+ // A link or anything but a file (a device, a pipe) is never read: its size would say 0 and the read would not end.+ if (stat === undefined || typeof stat.size !== 'number' || stat.isLink === true || (stat.kind !== undefined && stat.kind !== 'file')) return { later: false }const sig = `${stat.size}:${stat.mtimeMs ?? 0}`const held = parsed.get(path)@@ -193,7 +195,7 @@ export async function refreshWfGuards(state: State, host: Host, force = false, n// The first reading announces nothing, as the page's own notices do: what is already true when the console looks is on the Cost board, and only a crossing after it raises a notice.if (isFirst) store.raised = new Set(activeAlerts(state.wf.read.runs, nowMs).map(alert => alert.key))} catch (error) {- store.error = error instanceof Error ? error.message.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').slice(0, 100) : 'the read was refused'+ store.error = error instanceof Error ? cleanText(error.message).slice(0, 100) : 'the read was refused'} finally {store.isReading = falsehost.invalidate()diff --git a/plugins/ruflo-console/hooks/wf-saved-live.ts b/plugins/ruflo-console/hooks/wf-saved-live.tsindex 933b15463e..ad9f96f8e9 100644--- a/plugins/ruflo-console/hooks/wf-saved-live.ts+++ b/plugins/ruflo-console/hooks/wf-saved-live.ts@@ -9,7 +9,8 @@*/import type { ActionSpec } from './actions'import { decodeSaved, emptySaved, encodeSaved, captureDrill, restoreDrill, sameDrill, SAVED_FILE, SAVED_MAX_BYTES, type Saved } from './data/wf-saved'-import { dirOf, removeFileArgv, replaceFileArgv } from './data/wf-file'+import { cleanText } from './data/wf-clean'+import { checkNoLinks, dirOf, removeFileArgv, replaceFileArgv } from './data/wf-file'import { readBounded } from './data/files'import type { Host } from './host'import type { State } from './state'@@ -129,13 +130,22 @@ export async function syncSavedViews(state: State, host: SavedHost, nowMs: numbetry {const path = savedPathOf(state.cwd)+ // dd follows a link: a `.claude-flow` folder or a wf-views.json that is one (a repository can ship either) would send this write to any file the person can write. Refused, and said.+ const clear = await checkNoLinks(host.fs, path, { cwd: state.cwd }, { allowExisting: true })++ if (!clear.ok) {+ own.error = cleanText(clear.why).slice(0, 80)++ return+ }+const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefinedconst result = await host.run(replaceFileArgv(path, hasDir), 10_000, encodeSaved(own.saved, nowMs))own.error = result.exitCode === 0 ? null : `the write exited ${result.exitCode}`if (result.exitCode === 0) own.isDirty = false} catch (error) {- own.error = error instanceof Error ? error.message.slice(0, 80) : 'the write was refused'+ own.error = error instanceof Error ? cleanText(error.message).slice(0, 80) : 'the write was refused'} finally {own.isWriting = false}diff --git a/plugins/ruflo-console/hooks/wf-wire.ts b/plugins/ruflo-console/hooks/wf-wire.tsindex 8ba04aa19c..f2070db29c 100644--- a/plugins/ruflo-console/hooks/wf-wire.ts+++ b/plugins/ruflo-console/hooks/wf-wire.ts@@ -6,21 +6,36 @@*/import type { Host } from './host'import type { State } from './state'-import { refreshWfGuards } from './wf-cost-live'+import { isUnread } from './data/wf-cost'+import type { ExportCost } from './data/wf-export'+import type { WfRun } from './data/workflows'+import { guards, refreshWfGuards } from './wf-cost-live'import { bindWorkflowDrill } from './wf-drill'import { afterRead } from './wf-live'import { syncSavedViews } from './wf-saved-live'import { recordRunEvents } from './views/wf-guide'-import { setExportFs } from './views/wf-export'+import { setExportCostSource, setExportFs } from './views/wf-export'import { wireWfAnatole } from './views/wf-anatole'import { wireWfTemplates } from './views/wf-templates'import { wireWfWorktrees } from './views/wf-worktrees'let isWired = false+/** The export's cost, from the figures the Cost section shows (ADR-462), never a number the page does not hold: an unread run, or one with no priced token, is null (n/a). A floor or an estimate says so in the source words. */+export function exportCostOf(run: WfRun): ExportCost | null {+ const cost = guards.costs.get(run.id)++ if (cost === undefined || isUnread(cost.total) || cost.total.pricedTokens === 0) return null++ const caveats = [cost.total.isFloor || cost.total.unpricedTokens > 0 ? `a floor: ${cost.covered} of ${cost.count} agents read or some tokens unpriced` : '', cost.total.isApprox ? 'rough family price' : ''].filter(Boolean)++ return { usd: cost.total.usd, source: `price-book estimate, not a bill${caveats.length > 0 ? `; ${caveats.join('; ')}` : ''}` }+}+export function wireWorkflows(state: State, host: Host): void {bindWorkflowDrill(state, host)setExportFs(host.fs)+ setExportCostSource(exportCostOf)wireWfWorktrees(state, host)wireWfTemplates(state, host)wireWfAnatole(state, host)diff --git a/plugins/ruflo-console/tests/fixtures/wf-git.ts b/plugins/ruflo-console/tests/fixtures/wf-git.tsindex c41f845858..96970b6813 100644--- a/plugins/ruflo-console/tests/fixtures/wf-git.ts+++ b/plugins/ruflo-console/tests/fixtures/wf-git.ts@@ -1,7 +1,7 @@/*** A stand-in for git and /proc for the worktree specs: a fixed list, per-path dirty and ahead counts, ages and a process listing.*/-import { AHEAD_ARGV, LIST_ARGV, parseProcs, PROCS_ARGV, REF_ARGV, STATUS_ARGV, type WtIo, type WtRead, type WtRow } from '../../hooks/data/wf-worktrees'+import { AHEAD_ARGV, IGNORED_ARGV, LIST_ARGV, parseProcs, PROCS_ARGV, REF_ARGV, STATUS_ARGV, type WtIo, type WtRead, type WtRow } from '../../hooks/data/wf-worktrees'import type { Kit } from '../../hooks/views/common'export const NOW = Date.parse('2026-10-06T12:00:00.000Z')@@ -28,7 +28,7 @@ export const words = (tree: unknown): string => flat(tree).filter(el => el.kindexport const block = (path: string, branch: string | null, extra: string[] = [], head = 'a'.repeat(40)): string => [`worktree ${path}`, `HEAD ${head}`, branch === null ? 'detached' : `branch refs/heads/${branch}`, ...extra].join('\n')-export type World = { dirty: Record<string, number>; ahead: Record<string, number | null>; created: Record<string, number | null>; procs: string; list: string; calls: (readonly string[])[]; removed: string[]; failRemove: Set<string>; hasRef: boolean }+export type World = { dirty: Record<string, number>; ahead: Record<string, number | null>; created: Record<string, number | null>; procs: string; list: string; calls: (readonly string[])[]; removed: string[]; failRemove: Set<string>; hasRef: boolean; ignored: Record<string, string> }export const procLines = (rows: [number, string, string][]): string => rows.map(([pid, kind, target]) => `/proc/${pid}/${kind}\t${target}`).join('\n')export const BASE_PROCS = procLines([[1, 'cwd', '/'], [2, 'cwd', '/home/u'], [3, 'cwd', '/tmp']])@@ -46,6 +46,7 @@ export function world(over: Partial<World> = {}): World {removed: [],failRemove: new Set(),hasRef: true,+ ignored: {},...over,}}@@ -66,6 +67,7 @@ export function ioOf(w: World): WtIo {if (key === LIST_ARGV(dir).join(' ')) return { stdout: w.list, stderr: '', exitCode: 0 }if (key === REF_ARGV(dir).join(' ')) return w.hasRef ? { stdout: `${Math.floor((NOW - 2 * 3_600_000) / 1000)}\n`, stderr: '', exitCode: 0 } : { stdout: '', stderr: 'unknown revision', exitCode: 128 }if (key === STATUS_ARGV(dir).join(' ')) return { stdout: Array.from({ length: w.dirty[dir] ?? 0 }, (_, i) => ` M f${i}`).join('\n'), stderr: '', exitCode: 0 }+ if (key === IGNORED_ARGV(dir).join(' ')) return { stdout: w.ignored[dir] ?? '', stderr: '', exitCode: 0 }if (key === AHEAD_ARGV(dir).join(' ')) return w.ahead[dir] === null ? { stdout: '', stderr: 'bad', exitCode: 128 } : { stdout: `0\t${w.ahead[dir] ?? 0}\n`, stderr: '', exitCode: 0 }if (key.startsWith(`git -C ${ROOT} worktree remove `)) {const path = argv[5] ?? ''@@ -88,7 +90,7 @@ export function ioOf(w: World): WtIo {}}-export const row = (over: Partial<WtRow> = {}): WtRow => ({ path: wt('x'), head: 'a'.repeat(40), branch: 'feat/x', isDetached: false, isBare: false, isLocked: false, isPrunable: false, isMain: false, isSafe: true, dirty: 0, ahead: 0, behind: 3, createdMs: NOW - 5 * DAY, maker: null, isCurrent: false, ...over })+export const row = (over: Partial<WtRow> = {}): WtRow => ({ path: wt('x'), head: 'a'.repeat(40), branch: 'feat/x', isDetached: false, isBare: false, isLocked: false, isPrunable: false, isMain: false, isSafe: true, dirty: 0, ignoredSecrets: 0, ahead: 0, behind: 3, createdMs: NOW - 5 * DAY, maker: null, isCurrent: false, ...over })export const readOf = (rows: WtRow[]): WtRead => ({ root: ROOT, rows, total: rows.length, isCut: false, refAtMs: NOW - 3_600_000, hasRef: true, atMs: NOW })export const okCheck = (paths: string[], counts: Record<string, number> = {}, atMs = NOW) => parseProcs(`${BASE_PROCS}\n${procLines(Object.entries(counts).map(([path], i) => [50 + i, 'cwd', path] as [number, string, string]))}`, paths, atMs)diff --git a/plugins/ruflo-console/tests/wf-cost.spec.ts b/plugins/ruflo-console/tests/wf-cost.spec.tsindex 92a2937ed9..a2f14e8a92 100644--- a/plugins/ruflo-console/tests/wf-cost.spec.ts+++ b/plugins/ruflo-console/tests/wf-cost.spec.ts@@ -6,7 +6,7 @@import { describe, expect, it } from 'vitest'import { alertKey, evaluateGuards, guardOptionsOf, newAlerts, parseGuardRules, trackProgress, type GuardInput, type GuardRules, NO_RULES } from '../hooks/data/wf-alerts'-import { billedTokens, costOfUsage, costRun, fmtCosted, fmtUsd, parsePriceBook, priceFor, spendOf, usageOfTranscript, usdOf, zeroUsage, type AgentUsage, type PriceBook } from '../hooks/data/wf-cost'+import { billedTokens, costOfUsage, costRun, fmtCosted, fmtUsd, isUnread, parsePriceBook, priceFor, spendOf, usageOfTranscript, usdOf, zeroUsage, type AgentUsage, type PriceBook } from '../hooks/data/wf-cost'import { buildRun, type WfRun } from '../hooks/data/workflows'import { journal, meta, result, started, T0, transcript } from './fixtures/workflows'@@ -305,3 +305,29 @@ describe('trackProgress and newAlerts', () => {expect(newAlerts([alert], cleared.raised).fresh).toHaveLength(1)})})++describe('review fixes: nothing read is n/a, never $0', () => {+ it('a run whose agents were not read has no figure, and a read zero-token agent is still $0', () => {+ const none = costRun(run('wf_c9'), new Map(), BOOK)++ expect(fmtCosted(none.total)).toBe('n/a')+ expect([...none.phases.values()].map(fmtCosted)).toEqual(['n/a', 'n/a'])+ expect(isUnread(none.total)).toBe(true)+ expect(fmtCosted(costOfUsage({ byModel: new Map([['claude-sonnet-5-5', zeroUsage()]]), isTail: false }, BOOK))).toBe('$0')+ })+})++describe('review fixes: the export cost is the Cost section figure, labelled', () => {+ it('carries a floor caveat when agents are unread and null when no token was priced', async () => {+ const { exportCostOf } = await import('../hooks/wf-wire')+ const { guards } = await import('../hooks/wf-cost-live')+ const r = run('wf_c7')++ guards.costs.clear()+ guards.costs.set('wf_c7', costRun(r, new Map([['wf_c7/a1', usageOf('claude-sonnet-5-5', { output: 1e6 })]]), BOOK))+ expect(exportCostOf(r)).toMatchObject({ usd: 10, source: expect.stringContaining('a floor: 1 of 3 agents') })+ guards.costs.set('wf_c7', costRun(r, new Map([['wf_c7/a1', usageOf('claude-mystery-9', { output: 1e6 })]]), BOOK))+ expect(exportCostOf(r)).toBeNull()+ guards.costs.clear()+ })+})diff --git a/plugins/ruflo-console/tests/wf-merge.spec.ts b/plugins/ruflo-console/tests/wf-merge.spec.tsindex 50501f6012..b4d986d3b5 100644--- a/plugins/ruflo-console/tests/wf-merge.spec.ts+++ b/plugins/ruflo-console/tests/wf-merge.spec.ts@@ -82,3 +82,19 @@ describe('guard options', () => {expect(optionsOf(undefined).wfAlertRules).toBe('')})})++describe('review fixes: the export takes its cost from the Cost section', () => {+ it('is null where nothing was read and a labelled estimate where something was', async () => {+ const { exportCostOf } = await import('../hooks/wf-wire')+ const { guards } = await import('../hooks/wf-cost-live')+ const { costRun } = await import('../hooks/data/wf-cost')+ const { buildRun } = await import('../hooks/data/workflows')+ const { journal, meta, started } = await import('./fixtures/workflows')+ const wfRun = buildRun({ id: 'wf_x', journal: journal(started('a1', 'build:a', 'Build')), agents: new Map([['a1', { meta: meta('a1', 'Build'), transcript: null, isTail: false, path: '/p/a1.jsonl' }]]), nowMs: 0 } as never)++ guards.costs.clear()+ expect(exportCostOf(wfRun)).toBeNull()+ guards.costs.set('wf_x', costRun(wfRun, new Map(), null))+ expect(exportCostOf(wfRun)).toBeNull()+ })+})diff --git a/plugins/ruflo-console/tests/wf-security.spec.ts b/plugins/ruflo-console/tests/wf-security.spec.tsnew file mode 100644index 0000000000..21316cf4b0--- /dev/null+++ b/plugins/ruflo-console/tests/wf-security.spec.ts@@ -0,0 +1,297 @@+/**+ * Security audit of the Workflows board (ADR-464 follow-up): what must never reach a cell, a log line, an export, a notice or a saved+ * file, where a write may land, what an argv may carry, and that hostile JSON cannot pollute a prototype. Real files and real `dd`+ * where the property is about the disk; no engine. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-security.spec.ts --testTimeout=30000+ */+import { spawn } from 'node:child_process'+import { lstat, mkdir, mkdtemp, readFile, rm, stat as statOf, symlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { decodeSaved, encodeSaved, emptySaved, setFilter } from '../hooks/data/wf-saved'+import { cleanBlock, cleanPath } from '../hooks/data/wf-activity'+import { cleanText } from '../hooks/data/wf-clean'+import { checkNoLinks, newFileArgv, resolveExportPath } from '../hooks/data/wf-file'+import { exportName, exportSpec, runMarkdown } from '../hooks/data/wf-export'+import { maskSecrets, parseAgentMeta, parseJournal } from '../hooks/data/workflows'+import { guardText } from '../hooks/data/wf-guide'+import { newState } from '../hooks/state'+import { resetSavedLive, savedFor, savedPathOf, syncSavedViews, updateSaved } from '../hooks/wf-saved-live'+import { setSearch } from '../hooks/data/wf-saved'+import { BASE, runOf } from './fixtures/wf-runs'++const ESC = '\u001b'+const BEL = '\u0007'++/** Every credential shape the console must not show, each with the secret part that must be gone. */+const SECRETS: [string, string][] = [+ ['sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789', 'AbCdEfGhIjKlMnOpQr'],+ ['ghp_abcdefghijklmnopqrstuvwxyz0123456789', 'abcdefghijklmnop'],+ ['glpat-abcdefghij0123456789', 'abcdefghij0123456789'],+ ['npm_abcdefghijklmnopqrstuvwxyz0123456789', 'abcdefghijklmnop'],+ ['xo' + 'xb-123456789012-abcdefghijklmnop', 'abcdefghijklmnop'],+ ['AKIAIOSFODNN7EXAMPLE', 'IOSFODNN7EXAMPLE'],+ ['Authorization: Bearer abc123def456ghi', 'abc123def456ghi'],+ ['Authorization: Basic dXNlcjpwYXNz', 'dXNlcjpwYXNz'],+ ['{"password": "hunter2hunter2"}', 'hunter2hunter2'],+ ["{'api_key': 'abcd1234efgh'}", 'abcd1234efgh'],+ ['DATABASE_PASSWORD=correcthorse', 'correcthorse'],+ ['STRIPE_SECRET_KEY=whatever1234', 'whatever1234'],+ ['DB_PASS=letmein99', 'letmein99'],+ ['curl --token tok_123456789 https://x', 'tok_123456789'],+ ['run --password=swordfish1', 'swordfish1'],+ ['postgres://admin:[email protected]/app', 's3cr3tpw'],+ ['eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dBjftJeZ4CVPmB92K27uhbUJU1p1r', 'eyJzdWIiOiIxMjM0NTY3ODkw'],+ ['-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmU\n-----END OPENSSH PRIVATE KEY-----', 'b3BlbnNzaC1rZXktdjE'],+ ['-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA', 'MIIEowIBAAKCAQEA'],+]++describe('secrets never survive the wash', () => {+ it.each(SECRETS)('masks %s', (input, secret) => {+ for (const out of [maskSecrets(input), cleanText(`before ${input} after`), cleanBlock(input).text, cleanBlock(`${ESC}[31m${input}${ESC}[0m`).text]) {+ expect(out).not.toContain(secret)+ expect(out).toContain('‹masked›')+ }+ })++ it('masks a credential in a journal result, an agent meta and a run summary export', () => {+ const journal = JSON.stringify({ type: 'result', key: 'k', agentId: 'a1', result: 'done. {"api_key": "zzzz1234yyyy"} and Authorization: Bearer ttt999uuu888' })+ const preview = parseJournal(`${JSON.stringify({ type: 'launched' })}\n${journal}\n`).agents[0]?.resultPreview ?? ''++ expect(preview).not.toMatch(/zzzz1234yyyy|ttt999uuu888/)++ const run = runOf('wf_s', [{ id: 'a', label: 'ghp_abcdefghijklmnopqrstuvwxyz0123456789', phase: 'Build', at: 0, ms: 5 }], { workflowName: 'name DB_PASS=letmein99' })+ const md = runMarkdown({ ...run, name: cleanText(run.name) }, { nowMs: 1 })++ expect(md).not.toMatch(/letmein99|ghp_abcdefghij/)+ })++ it('keeps ordinary prose and ids readable (no false-positive storm)', () => {+ for (const fine of ['the build passed in 12 s', 'bypass: the cache', 'agent-3 finished phase Review', 'wf_a1b2c3', '/home/u/projects/ruflo/.claude/worktrees/feat-x']) expect(cleanText(fine)).toBe(fine)+ })++ it('does not take a pathological line hostage (1 MB of each hostile shape in well under a second)', () => {+ const shapes = ['a'.repeat(1_000_000), `${'-----BEGIN PRIVATE KEY-----'.repeat(40_000)}`, 'key='.repeat(250_000), `${'Bearer '.repeat(150_000)}`, `${'x:'.repeat(500_000)}`, 'password"'.repeat(100_000), `${'://a:'.repeat(200_000)}`, ' '.repeat(1_000_000), `--token ${'t '.repeat(300_000)}`]++ for (const shape of shapes) {+ const t0 = performance.now()++ cleanBlock(shape)+ maskSecrets(shape.slice(0, 1_000_000))+ expect(performance.now() - t0).toBeLessThan(1500)+ }+ })+})++describe('terminal injection', () => {+ const HOSTILE = [`${ESC}]0;pwned title${BEL}label`, `${ESC}]8;;https://evil.example/${ESC}\\click${ESC}]8;;${ESC}\\`, `${ESC}[2J${ESC}[H${ESC}[31mred`, '\u009d0;c1 title\u009cx', 'aevil', 'zwix', 'line1\r\nline2\rline3\u0000\u0008', '\u{e0041}tagged']++ it.each(HOSTILE)('strips %j from a cell, a block and a path', input => {+ for (const out of [cleanText(input), cleanBlock(input).text, cleanPath(input)]) {+ // eslint-disable-next-line no-control-regex+ expect(out).not.toMatch(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f---\u{e0000}-\u{e0fff}]/u)+ expect(out).not.toMatch(/pwned|c1 title|evil\.example|\[2J|\[31m/)+ }+ })++ it('strips the same from every string a run file supplies (meta, journal, labels) before a cell sees it', () => {+ const meta = parseAgentMeta(JSON.stringify({ description: `${ESC}]0;t${BEL}d`, workflowPhase: 'p', worktreePath: `/w/exe${ESC}[31m`, agentType: 'x' }))++ expect(JSON.stringify(meta)).not.toMatch(/\\u001b|\\u202e|\\u200b|\[31m|\]0;t/)+ })++ it('keeps a very long label to its cap and a binary blob from becoming a cell', () => {+ const meta = parseAgentMeta(JSON.stringify({ description: 'x'.repeat(100_000), worktreePath: 'y'.repeat(100_000) }))++ expect((meta.description ?? '').length).toBeLessThanOrEqual(80)+ expect((meta.worktreePath ?? '').length).toBeLessThanOrEqual(300)+ expect(cleanBlock('\u0000\u0001\u0002binaryÿ\u0000'.repeat(10_000)).text.length).toBeLessThanOrEqual(6000)+ })+})++describe('export and saved-view paths', () => {+ let dir: string+ let outside: string++ const fsOf = {+ stat: async (path: string) => {+ const link = await lstat(path).catch(() => undefined)++ if (link === undefined) return undefined+ if (link.isSymbolicLink()) return { isLink: true, kind: 'symlink', size: link.size, mtimeMs: link.mtimeMs }++ return { isLink: false, kind: link.isDirectory() ? 'dir' : 'file', size: link.size, mtimeMs: link.mtimeMs }+ },+ read: async (path: string) => readFile(path, 'utf8'),+ list: async () => [],+ }+ const run = (argv: readonly string[], _ms: number, stdin?: string): Promise<{ exitCode: number; stdout: string; stderr: string }> =>+ new Promise(resolve => {+ const child = spawn(argv[0] as string, argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] })+ let stdout = ''+ let stderr = ''++ child.stdout.on('data', chunk => (stdout += chunk))+ child.stderr.on('data', chunk => (stderr += chunk))+ child.on('close', code => resolve({ exitCode: code ?? -1, stdout, stderr }))+ child.on('error', error => resolve({ exitCode: 127, stdout, stderr: String(error) }))+ child.stdin.end(stdin ?? '')+ })++ beforeEach(async () => {+ const base = await mkdtemp(join(tmpdir(), 'wf-sec-'))++ dir = join(base, 'proj')+ outside = join(base, 'outside')+ await mkdir(dir, { recursive: true })+ await mkdir(outside, { recursive: true })+ resetSavedLive()+ })+ afterEach(async () => {+ await rm(join(dir, '..'), { recursive: true, force: true })+ })++ it('refuses every traversal, absolute escape, home, backslash, control and bad-name path', () => {+ const roots = { cwd: dir, scratch: null }++ for (const bad of ['../x.md', 'a/../../x.md', `${outside}/x.md`, '/etc/passwd.md', '~/x.md', 'a\\b.md', 'x\n.md', `x${ESC}[0m.md`, '-rf.md', '.hidden.md', 'x.md.sh', 'x', '', ' ', 'a'.repeat(400), `${dir}-evil/x.md`, `${dir}/../outside/x.md`, 'x.md']) {+ expect(resolveExportPath(bad, roots).ok, bad).toBe(false)+ }++ expect(resolveExportPath('out/with space.md', roots)).toEqual({ ok: true, path: `${dir}/out/with space.md` })+ })++ it('refuses to write through a link (folder or file) and never overwrites an existing file', async () => {+ await symlink(outside, join(dir, 'linked'))+ await writeFile(join(outside, 'victim.md'), 'keep')+ await symlink(join(outside, 'victim.md'), join(dir, 'file-link.md'))+ await writeFile(join(dir, 'exists.md'), 'mine')++ const roots = { cwd: dir, scratch: null }++ for (const rel of ['linked/new.md', 'file-link.md', 'exists.md']) {+ const wanted = resolveExportPath(rel, roots)++ expect(wanted.ok).toBe(true)+ expect((await checkNoLinks(fsOf, (wanted as { path: string }).path, roots)).ok, rel).toBe(false)+ }++ // The disk half holds even if the check were skipped: conv=excl refuses an existing file and a dangling link.+ await symlink(join(outside, 'not-yet.md'), join(dir, 'dangling.md'))++ for (const rel of ['exists.md', 'dangling.md']) {+ const result = await run(newFileArgv(join(dir, rel), true), 5000, 'PWNED')++ expect(result.exitCode, rel).not.toBe(0)+ }++ expect(await readFile(join(outside, 'victim.md'), 'utf8')).toBe('keep')+ expect(await readFile(join(dir, 'exists.md'), 'utf8')).toBe('mine')+ expect(await statOf(join(outside, 'not-yet.md')).catch(() => null)).toBeNull()+ })++ it('writes a summary whose name has spaces and a leading dash-free base as one argv element, content on stdin', async () => {+ const path = `${dir}/odd name; $(touch pwned) \`id\`.md`+ const result = await run(newFileArgv(path, true), 5000, '# hi\n')++ expect(result.exitCode).toBe(0)+ expect(await readFile(path, 'utf8')).toBe('# hi\n')+ expect(await statOf(join(dir, 'pwned')).catch(() => null)).toBeNull()+ })++ it('the export spec carries a fixed argv with no shell and the text only on stdin', () => {+ const spec = exportSpec(`${dir}/a.md`, '# x', 'run', true)++ expect(spec.argv?.[0]).toBe('dd')+ expect(spec.stdin).toBe('# x')+ expect(spec.declared).toBe('write')+ expect(exportName(runOf('wf_x', BASE, {}, '../../etc/passwd; rm -rf /'))).toMatch(/^[A-Za-z0-9][A-Za-z0-9._-]*\.md$/)+ })++ it('does not write saved views through a linked .claude-flow folder or a linked wf-views.json', async () => {+ const victim = join(outside, 'victim.txt')++ await writeFile(victim, 'precious')++ const state = newState()++ state.cwd = dir+ state.view = 'workflows'+ state.wf.read = { runs: [runOf('wf_a', BASE), runOf('wf_b', BASE)], root: '/x', capBytes: 1, skipped: 0, more: 0 }++ const host = { fs: fsOf, run } as never++ // 1. wf-views.json is a link to a file the person can write.+ await mkdir(join(dir, '.claude-flow/console'), { recursive: true })+ await symlink(victim, join(dir, '.claude-flow/console/wf-views.json'))+ await syncSavedViews(state, host, 1000)+ updateSaved(dir, s => setSearch(s, 'x'))+ await syncSavedViews(state, host, 100_000)+ expect(await readFile(victim, 'utf8')).toBe('precious')+ expect(savedFor(dir).error).toMatch(/link/)++ // 2. the whole console folder is a link to somewhere else.+ await rm(join(dir, '.claude-flow'), { recursive: true })+ await mkdir(join(outside, 'console'))+ await symlink(outside, join(dir, '.claude-flow'))+ resetSavedLive()+ await syncSavedViews(state, host, 200_000)+ updateSaved(dir, s => setSearch(s, 'y'))+ await syncSavedViews(state, host, 300_000)+ expect(await statOf(join(outside, 'console/wf-views.json')).catch(() => null)).toBeNull()+ expect(savedFor(dir).error).toMatch(/link/)+ })++ it('writes the saved views normally when nothing is a link', async () => {+ const state = newState()++ state.cwd = dir+ state.view = 'workflows'+ state.wf.read = { runs: [runOf('wf_a', BASE)], root: '/x', capBytes: 1, skipped: 0, more: 0 }+ await syncSavedViews(state, { fs: fsOf, run } as never, 1000)+ updateSaved(dir, s => setSearch(s, 'needle'))+ await syncSavedViews(state, { fs: fsOf, run } as never, 100_000)+ expect(decodeSaved(await readFile(savedPathOf(dir), 'utf8')).saved.search).toBe('needle')+ })+})++describe('JSON from files cannot pollute or smuggle', () => {+ it('ignores __proto__, constructor and prototype keys in the saved file and in a run record', () => {+ const text = '{"version":1,"__proto__":{"polluted":"yes"},"filters":{"__proto__":"x","constructor":"c","prototype":"p","state":"ok"},"drill":{"__proto__":{"polluted":"drill"},"runId":"wf_a"},"pins":[{"__proto__":{"polluted":"pin"},"runId":"wf_a","name":"n"}]}'+ const decoded = decodeSaved(text)++ expect(({} as Record<string, unknown>).polluted).toBeUndefined()+ expect(Object.getPrototypeOf(decoded.saved.filters)).toBe(Object.prototype)+ expect(decoded.saved.filters.state).toBe('ok')+ expect(Object.keys(decoded.saved.filters)).not.toContain('__proto__')+ expect(setFilter(emptySaved(), '__proto__', 'x')).toEqual(emptySaved())+ expect(JSON.parse(encodeSaved(decoded.saved, 1)).polluted).toBeUndefined()++ const run = runOf('wf_p', BASE, JSON.parse('{"__proto__":{"polluted":"run"},"constructor":{"prototype":{"polluted":"ctor"}}}'))++ expect(({} as Record<string, unknown>).polluted).toBeUndefined()+ expect(run.id).toBe('wf_p')+ })++ it('survives deep nesting, huge arrays and non-object roots without throwing', () => {+ const deep = `${'['.repeat(5000)}${']'.repeat(5000)}`++ expect(() => decodeSaved(deep)).not.toThrow()+ expect(decodeSaved(JSON.stringify({ version: 1, pins: Array.from({ length: 100_000 }, (_, i) => ({ runId: `wf_${i}`, name: 'n' })) })).saved.pins.length).toBeLessThanOrEqual(20)+ expect(() => parseJournal(`${'{"type":"started","agentId":'.repeat(50_000)}`)).not.toThrow()+ })+})++describe('free text that becomes an argv', () => {+ it('refuses a leading dash, a credential and control characters; keeps the text one element', () => {+ for (const bad of ['--force', '-rf /', ' -x', `${ESC}[31m--x`, 'use sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789', 'DB_PASS=letmein99', '', ' ']) expect(guardText(bad, 300).ok, bad).toBe(false)++ const ok = guardText('line one\nline two; $(id) `x` ', 300)++ expect(ok.ok).toBe(true)+ expect((ok as { text: string }).text).not.toMatch(/[\n]/)+ })+})diff --git a/plugins/ruflo-console/tests/wf-wire.spec.ts b/plugins/ruflo-console/tests/wf-wire.spec.tsindex a154881878..4034a05f27 100644--- a/plugins/ruflo-console/tests/wf-wire.spec.ts+++ b/plugins/ruflo-console/tests/wf-wire.spec.ts@@ -271,6 +271,20 @@ describe('the keys', () => {expect(world.state.wf.ui.column).toBe('agents')})+ it('the keys the page names in its own text are keys its buttons carry (h is Help\'s, [ and ] are not hotkeys)', async () => {+ const world = worldOf(live())++ await refreshWorkflows(world.state, world.host, true, NOW)++ const { tree } = pageOf(world.state, world.host)+ const shown = words(tree)++ expect(shown).toContain('b/l column')+ expect(shown).toContain('d inspect')+ expect(shown).not.toContain('h/l column')+ expect(shown).not.toContain('[ ] switches run')+ })+it('opens a transcript path only inside the config directory\'s projects folder', () => {expect(isRunPath(`${ROOT}/${SESSION}/subagents/workflows/wf_live/agent-a1.jsonl`, CONFIG)).toBe(true)expect(isRunPath(`${CONFIG}/projects/../secrets.json`, CONFIG)).toBe(false)diff --git a/plugins/ruflo-console/tests/wf-worktrees.spec.ts b/plugins/ruflo-console/tests/wf-worktrees.spec.tsindex e260f83c14..81dc4e2d31 100644--- a/plugins/ruflo-console/tests/wf-worktrees.spec.ts+++ b/plugins/ruflo-console/tests/wf-worktrees.spec.ts@@ -165,7 +165,8 @@ describe('the probes', () => {expect(w.calls.length).toBeGreaterThan(10)for (const argv of w.calls) {expect(argv[0] === 'git' ? argv[1] : argv[0]).toMatch(/^(-C|\/usr\/bin\/find)$/)- expect(argv.join(' ')).not.toMatch(/(^| )(sh|bash|-c|eval)( |$)/)+ expect(argv[0]).toMatch(/^(git|\/usr\/bin\/find)$/)+ expect(argv.join(' ')).not.toMatch(/(^| )(sh|bash|eval)( |$)/)expect(argv.every(part => !/[\n\r]/.test(part))).toBe(true)}