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): bound CLI numbers at the reader, keep unreadable counts visible, and a resume by Claude keeps hand-out counts

Dragan Spiridonov31c288db7135
diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.ts
index d5ab3e4e69..fb319c5621 100644
--- a/plugins/ruflo-console/hooks/data/cli.ts
+++ b/plugins/ruflo-console/hooks/data/cli.ts
@@ -7,7 +7,7 @@
import { closeOf } from './json-span'
import { failureReason } from './failure'
import { idOf, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'
-import { own } from './safe'
+import { countOf, measureOf, own, ratioOf } from './safe'
import { researchProbe } from './research'
import { CLI_PREFIXES, type CliChoice, type State, type ViewId } from '../state'
@@ -118,12 +118,12 @@ export const memoryProbe: Probe<MemoryStats> = {
const entries = recordOf(value.entries)
const stats: MemoryStats = { backend: stringOf(value.backend, 60) ?? 'unknown' }
- const total = numberOf(entries?.total)
- const vectors = numberOf(entries?.vectors)
+ const total = countOf(entries?.total)
+ const vectors = countOf(entries?.vectors)
const storage = stringOf(recordOf(value.storage)?.total, 30)
const oldestMs = msOf(value.oldestEntry)
const newestMs = msOf(value.newestEntry)
- const unread = numberOf(recordOf(value.unreadStore)?.rows)
+ const unread = countOf(recordOf(value.unreadStore)?.rows)
if (total !== undefined) stats.total = total
if (unread !== undefined) stats.unread = unread
@@ -162,7 +162,7 @@ export const namespacesProbe: Probe<Namespaces> = {
const record = recordOf(entry)
const name = stringOf(record?.namespace, 40) ?? '(none)'
const key = stringOf(record?.key, 128)
- const size = numberOf(record?.size)
+ const size = countOf(record?.size)
const atMs = msOf(record?.updatedAt ?? record?.createdAt)
counts.set(name, (counts.get(name) ?? 0) + 1)
@@ -198,7 +198,7 @@ export const scoreProbe: Probe<HarnessScore> = {
}
const score: HarnessScore = { dims }
- const costUsd = numberOf(value.estCostPerRunUsd)
+ const costUsd = measureOf(value.estCostPerRunUsd)
const archetype = stringOf(value.archetype, 40)
const constraints = stringOf(value.hardConstraints, 10)
const atMs = msOf(value.generatedAt)
@@ -232,12 +232,12 @@ export const flywheelProbe: Probe<Flywheel> = {
const flywheel: Flywheel = {
isLedgerValid: ledger.valid === true,
- commits: numberOf(ledger.commits) ?? 0,
+ commits: countOf(ledger.commits) ?? 0,
receipts: Object.keys(recordOf(state?.receiptStates) ?? {}).length,
errors: (Array.isArray(ledger.errors) ? ledger.errors : []).slice(0, 3).map(error => plain(error, 100)),
}
const champion = stringOf(state?.activeChampionRef, 80)
- const epoch = numberOf(state?.servingEpoch)
+ const epoch = countOf(state?.servingEpoch)
if (champion !== undefined) flywheel.champion = champion
if (epoch !== undefined) flywheel.epoch = epoch
@@ -271,7 +271,7 @@ export const auditProbe: Probe<AuditTrend> = {
const record = recordOf(entry)
const atMs = msOf(record?.finishedAt ?? record?.startedAt ?? record?.timestamp ?? record?.generatedAt ?? record?.createdAt ?? recordOf(record?.value)?.generatedAt)
const worst = stringOf(record?.worst ?? recordOf(record?.value)?.worst, 12)
- const findings = numberOf(record?.findings ?? recordOf(record?.value)?.findingCount)
+ const findings = countOf(record?.findings ?? recordOf(record?.value)?.findingCount)
const key = idOf(record?.key) ?? undefined
return atMs === undefined ? [] : [{ atMs, ...(worst !== undefined && { worst }), ...(findings !== undefined && { findings }), ...(key !== undefined && { key }) }]
@@ -279,7 +279,7 @@ export const auditProbe: Probe<AuditTrend> = {
points.sort((a, b) => a.atMs - b.atMs)
- return { total: numberOf(value.totalInNamespace) ?? points.length, points }
+ return { total: countOf(value.totalInNamespace) ?? points.length, points }
},
}
@@ -304,13 +304,13 @@ export const intelligenceProbe: Probe<Intelligence> = {
const sona = recordOf(value.sona)
const router = recordOf(value.modelRouter)
const neural = recordOf(value.neuralRouter)
- const routerDecisions = numberOf(router?.totalDecisions)
+ const routerDecisions = countOf(router?.totalDecisions)
const out: Intelligence = {}
- const trajectories = numberOf(sona?.trajectoriesTotal)
- const patterns = numberOf(sona?.patternsLearned)
- const successRate = numberOf(sona?.successRate)
- const moeDecisions = numberOf(recordOf(value.moe)?.routingDecisions)
- const ewc = numberOf(recordOf(value.ewc)?.consolidations)
+ const trajectories = countOf(sona?.trajectoriesTotal)
+ const patterns = countOf(sona?.patternsLearned)
+ const successRate = ratioOf(sona?.successRate)
+ const moeDecisions = countOf(recordOf(value.moe)?.routingDecisions)
+ const ewc = countOf(recordOf(value.ewc)?.consolidations)
if (trajectories !== undefined) out.trajectories = trajectories
if (patterns !== undefined) out.patterns = patterns
@@ -319,7 +319,7 @@ export const intelligenceProbe: Probe<Intelligence> = {
if (ewc !== undefined) out.ewcConsolidations = ewc
if (routerDecisions !== undefined) out.routerDecisions = routerDecisions
// The tool answers a default confidence before the first decision: only a measured one is kept.
- if (routerDecisions !== undefined && routerDecisions > 0 && numberOf(router?.avgConfidence) !== undefined) out.routerConfidence = numberOf(router?.avgConfidence) as number
+ if (routerDecisions !== undefined && routerDecisions > 0 && ratioOf(router?.avgConfidence) !== undefined) out.routerConfidence = ratioOf(router?.avgConfidence) as number
if (neural !== null) out.neuralRouter = neural.enabled === true ? 'on' : `off (${plain(neural.reason, 40) || 'not enabled'})`
return out
@@ -450,7 +450,7 @@ export const registryProbe: Probe<Registry> = {
const reg = recordOf(value.registration)
const limits = recordOf(reg?.limits)
- const limitText = limits === null ? undefined : Object.entries(limits).slice(0, 4).flatMap(([key, n]) => (numberOf(n) === undefined ? [] : [`${plain(key, 16)} ${numberOf(n)}`])).join(' ยท ')
+ const limitText = limits === null ? undefined : Object.entries(limits).slice(0, 4).flatMap(([key, n]) => (measureOf(n) === undefined ? [] : [`${plain(key, 16)} ${measureOf(n)}`])).join(' ยท ')
const out: Registry = {
join: (Array.isArray(value.join) ? value.join : []).slice(0, 6).flatMap(step => (typeof step === 'string' ? [plain(step, 200)] : [])),
channels: (Array.isArray(value.defaultChannels) ? value.defaultChannels : []).slice(0, 8).flatMap(entry => {
diff --git a/plugins/ruflo-console/hooks/data/evolve.ts b/plugins/ruflo-console/hooks/data/evolve.ts
index b517ff29dd..f29760ca9f 100644
--- a/plugins/ruflo-console/hooks/data/evolve.ts
+++ b/plugins/ruflo-console/hooks/data/evolve.ts
@@ -18,7 +18,8 @@
*/
import { jsonAfter } from './cli'
import { readBounded, under, type ReadCache, type ReaderFs } from './files'
-import { jsonObject, msOf, numberOf, plain, recordOf, stringOf } from './parse'
+import { jsonObject, msOf, plain, recordOf, stringOf } from './parse'
+import { countOf, measureOf } from './safe'
export const EVOLVE_FILES = {
flywheel: '.claude-flow/flywheel-v1/transaction-state.json',
@@ -111,7 +112,7 @@ export function parseFlywheel(text: string | null): FlywheelFile | null {
const baseline = refOf(commit.baselineRef)
const receipt = refOf(commit.receiptId)
- const epoch = numberOf(commit.servingEpoch)
+ const epoch = countOf(commit.servingEpoch)
const atMs = msOf(commit.promotedAt)
const proposer = stringOf(commit.proposer, 20)
@@ -119,7 +120,7 @@ export function parseFlywheel(text: string | null): FlywheelFile | null {
})
const champion = refOf(value.activeChampionRef)
const served = refOf(value.servedChampionRef)
- const epoch = numberOf(value.servingEpoch)
+ const epoch = countOf(value.servingEpoch)
const head = refOf(value.ledgerHead)
return { statuses, commits, ...(champion !== undefined && { champion }), ...(served !== undefined && { served }), ...(epoch !== undefined && { epoch }), ...(head !== undefined && { head }) }
@@ -137,7 +138,7 @@ export function parseReceipt(text: string | null): Receipt | null {
const candidate = refOf(payload.candidateId)
const baseline = refOf(payload.baselineRef)
const atMs = msOf(payload.issuedAt)
- const lift = numberOf(recordOf(payload.statistics)?.relativeLift)
+ const lift = measureOf(recordOf(payload.statistics)?.relativeLift)
const signature = recordOf(value.signature)
return {
@@ -153,7 +154,7 @@ export function parseReceipt(text: string | null): Receipt | null {
export function parseGeneration(text: string | null): Generation | null {
const value = jsonObject(text)
- const generation = numberOf(value?.generation)
+ const generation = countOf(value?.generation)
if (value === null || generation === undefined) return null
@@ -183,7 +184,7 @@ export function parseServed(text: string | null): Served | null {
if (value === null) return null
const champion = refOf(value.championHash)
- const fromGeneration = numberOf(value.fromGeneration)
+ const fromGeneration = countOf(value.fromGeneration)
const atMs = msOf(value.servedAt)
return { ...(champion !== undefined && { champion }), ...(fromGeneration !== undefined && { fromGeneration }), ...(atMs !== undefined && { atMs }) }
@@ -215,7 +216,7 @@ export function parseManifest(text: string | null, os: Os): Manifest | null {
const issuedAtMs = msOf(manifest.issuedAt)
const gitCommit = stringOf(manifest.gitCommit, 12)
const branch = stringOf(manifest.branch, 40)
- const fixes = numberOf(recordOf(manifest.summary)?.totalFixes) ?? (Array.isArray(manifest.fixes) ? manifest.fixes.length : undefined)
+ const fixes = countOf(recordOf(manifest.summary)?.totalFixes) ?? (Array.isArray(manifest.fixes) ? manifest.fixes.length : undefined)
return {
os,
@@ -271,7 +272,8 @@ export async function readEvolve(fs: ReaderFs, cache: ReadCache, cwd: string, no
}
}
-const count = (value: unknown): number => numberOf(value) ?? 0
+/** A count from the CLI's JSON: whole, non-negative and capped, else 0 (#3822). */
+const count = (value: unknown): number => countOf(value) ?? 0
/** `metaharness flywheel status`: `{state, ledger: {valid, errors, commits, head}}`, its ledger as checked. */
export function parseLedger(stdout: string, atMs: number): Ledger | null {
diff --git a/plugins/ruflo-console/hooks/data/research.ts b/plugins/ruflo-console/hooks/data/research.ts
index fe85684c30..c3d7c6387a 100644
--- a/plugins/ruflo-console/hooks/data/research.ts
+++ b/plugins/ruflo-console/hooks/data/research.ts
@@ -5,7 +5,8 @@
* validated, never from typed text. Read-only: the section stores and starts nothing.
*/
import type { Probe } from './cli'
-import { jsonObject, msOf, numberOf, recordOf, stringOf } from './parse'
+import { jsonObject, msOf, recordOf, stringOf } from './parse'
+import { measureOf } from './safe'
import type { State } from '../state'
@@ -63,8 +64,9 @@ export function parseResearch(stdout: string): ResearchRecord[] | null {
if (record === null || question === undefined) return []
const findings = (Array.isArray(record.findings) ? record.findings : []).slice(0, MAX_FINDINGS)
- const spent = numberOf(record.spentUsd)
- const cap = numberOf(record.capUsd)
+ // Dollars are bounded where they are read: `1e300` would draw "$1e+300" (#3822).
+ const spent = measureOf(record.spentUsd)
+ const cap = measureOf(record.capUsd)
const status = typeof record.status === 'string' && STATUSES.includes(record.status) ? (record.status as ResearchRecord['status']) : 'unknown'
return [{
diff --git a/plugins/ruflo-console/hooks/data/safe.ts b/plugins/ruflo-console/hooks/data/safe.ts
index a28fdeee6f..594e5aecd3 100644
--- a/plugins/ruflo-console/hooks/data/safe.ts
+++ b/plugins/ruflo-console/hooks/data/safe.ts
@@ -17,6 +17,9 @@ export const isoOf = (value: unknown): string => (typeof value === 'number' && N
/** A whole, non-negative count capped at MAX_COUNT, else undefined (a negative, fractional-hostile, NaN or infinite value is not a count). */
export const countOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.min(Math.floor(value), MAX_COUNT) : undefined)
+/** A signed measurement (a score, a lift, a latency, a percentage) that is finite and within ยฑMAX_COUNT, else undefined: never "Infinity" or "1e+300" on screen (#3822). */
+export const measureOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= MAX_COUNT ? value : undefined)
+
/** 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)
diff --git a/plugins/ruflo-console/hooks/memory-lines.ts b/plugins/ruflo-console/hooks/memory-lines.ts
index e5eaad738b..109ff61d84 100644
--- a/plugins/ruflo-console/hooks/memory-lines.ts
+++ b/plugins/ruflo-console/hooks/memory-lines.ts
@@ -5,8 +5,8 @@
* found) are kept, first. And the recency binning the view draws as a timeline. Pure: strings in, strings out.
*/
import { jsonAfter } from './data/cli'
-import { msOf, numberOf, plain, recordOf } from './data/parse'
-import { isoOf } from './data/safe'
+import { msOf, plain, recordOf } from './data/parse'
+import { countOf, isoOf, measureOf } from './data/safe'
import { labLines } from './mh-lab'
/** An entry's value may be long: the panel scrolls (j/k), so it keeps more lines than the MetaHarness lab. */
@@ -57,15 +57,15 @@ export function wrap(text: string, width = WRAP): string[] {
return out
}
-const short = (value: unknown, max: number): string => (typeof value === 'string' ? plain(value, max) : typeof value === 'number' || typeof value === 'boolean' ? String(value) : '')
-const score = (value: unknown): string => (typeof value === 'number' && Number.isFinite(value) ? value.toFixed(3) : ' n/a')
+const short = (value: unknown, max: number): string => (typeof value === 'string' ? plain(value, max) : typeof value === 'number' ? String(measureOf(value) ?? 'n/a') : typeof value === 'boolean' ? String(value) : '')
+const score = (value: unknown): string => measureOf(value)?.toFixed(3) ?? ' n/a'
/** One stored entry: its name, its size and access count, then the whole value. */
function entryLines(record: Record<string, unknown>): string[] {
const value = record.content ?? record.value
const body = typeof value === 'string' ? value : JSON.stringify(value ?? null, null, 2)
const updated = msOf(record.updatedAt ?? record.storedAt)
- const head = `${short(record.namespace, 40)}/${short(record.key, 128)} ยท ${body.length} chars ยท read ${numberOf(record.accessCount) ?? 'n/a'}ร— ยท ${record.hasEmbedding === true ? 'has a vector' : 'no vector'}${updated !== undefined ? ` ยท updated ${isoOf(updated).slice(0, 16).replace('T', ' ')}` : ''}`
+ const head = `${short(record.namespace, 40)}/${short(record.key, 128)} ยท ${body.length} chars ยท read ${countOf(record.accessCount) ?? 'n/a'}ร— ยท ${record.hasEmbedding === true ? 'has a vector' : 'no vector'}${updated !== undefined ? ` ยท updated ${isoOf(updated).slice(0, 16).replace('T', ' ')}` : ''}`
return [head, ...(Array.isArray(record.tags) && record.tags.length > 0 ? [`tags: ${record.tags.map(tag => short(tag, 24)).join(', ')}`] : []), '', ...wrap(body)]
}
@@ -101,7 +101,7 @@ function listLines(rows: unknown[]): string[] {
...entries.slice(0, 60).map(row => {
const at = msOf(row.updatedAt ?? row.createdAt ?? row.storedAt)
- return `${row.hasEmbedding === true ? 'โ—†' : 'โ—‡'} ${short(row.namespace, 24)}/${short(row.key, 80)} ยท ${numberOf(row.size) ?? 'n/a'} B${at !== undefined ? ` ยท ${isoOf(at).slice(0, 16).replace('T', ' ')}` : ''}`
+ return `${row.hasEmbedding === true ? 'โ—†' : 'โ—‡'} ${short(row.namespace, 24)}/${short(row.key, 80)} ยท ${countOf(row.size) ?? 'n/a'} B${at !== undefined ? ` ยท ${isoOf(at).slice(0, 16).replace('T', ' ')}` : ''}`
}),
]
}
@@ -120,10 +120,11 @@ function vectorLines(record: Record<string, unknown>): string[] | null {
if (vector === null) return null
- const numbers = vector.filter((value): value is number => typeof value === 'number' && Number.isFinite(value))
+ // Only measurements count as elements (#3822): an element of 1e300 would print as "1e+300" in the head and overflow the norm.
+ const numbers = vector.flatMap(value => measureOf(value) ?? [])
const norm = Math.sqrt(numbers.reduce((sum, value) => sum + value * value, 0))
- return [`${numbers.length} dimensions ยท norm ${norm.toFixed(3)}${record.model !== undefined ? ` ยท ${short(record.model, 40)}` : ''}`, `head: ${numbers.slice(0, 8).map(value => value.toFixed(4)).join(' ')} โ€ฆ`]
+ return [`${numbers.length} dimensions ยท norm ${measureOf(norm)?.toFixed(3) ?? 'n/a'}${record.model !== undefined ? ` ยท ${short(record.model, 40)}` : ''}`, `head: ${numbers.slice(0, 8).map(value => value.toFixed(4)).join(' ')} โ€ฆ`]
}
/** One run's JSON as lines, by its shape; empty when nothing specific applies. */
diff --git a/plugins/ruflo-console/hooks/menu-style.ts b/plugins/ruflo-console/hooks/menu-style.ts
index bb5603b3ef..5556d9cfa8 100644
--- a/plugins/ruflo-console/hooks/menu-style.ts
+++ b/plugins/ruflo-console/hooks/menu-style.ts
@@ -8,7 +8,7 @@
*/
import { activeMission, progressOf } from './mission-control'
import { alertsOf, waitingApprovalsOf } from './data/alerts'
-import { secMemo } from './secure'
+import { secMemo, securityBand } from './secure'
import type { State, ViewId } from './state'
import { hasUnseen } from './whatsnew'
import { money } from './views/bar'
@@ -29,8 +29,7 @@ export function badgesOf(state: State, nowMs: number): Partial<Record<ViewId, Ba
const mission = activeMission(state)
const busy = snap?.agents.filter(agent => /busy|active|working/i.test(agent.status)).length ?? 0
const claims = snap?.claims.length ?? 0
- const findings = secMemo(state).findings
- const serious = findings === null ? 0 : findings.counts.critical + findings.counts.high
+ const security = securityBand(secMemo(state).findings)
if (mission !== null && !mission.cancelled) {
const { done, total } = progressOf(mission, snap?.tasks ?? [])
@@ -42,7 +41,7 @@ export function badgesOf(state: State, nowMs: number): Partial<Record<ViewId, Ba
if (alerts > 0) out.overview = { text: `โš  ${alerts}`, tone: 'attention' }
if (busy > 0) out.swarm = { text: `โ–ถ ${busy}`, tone: 'plain' }
if (claims > 0) out.claims = { text: String(claims), tone: 'plain' }
- if (findings !== null && serious > 0) out.secure = { text: `๐Ÿ”’ ${serious}`, tone: findings.counts.critical > 0 ? 'attention' : 'plain' }
+ if (security !== null) out.secure = { text: security.compact, tone: security.isAttention ? 'attention' : 'plain' }
if (state.usage?.costUsd !== undefined && state.usage.costUsd >= 0.01) out.cost = { text: money(state.usage.costUsd), tone: 'plain' }
if (state.terminal.runs.size > 0) out.terminal = { text: 'โ—', tone: 'plain' }
if (hasUnseen(state)) out.whatsnew = { text: 'new', tone: 'attention' }
diff --git a/plugins/ruflo-console/hooks/mh-lab.ts b/plugins/ruflo-console/hooks/mh-lab.ts
index 006b4092e6..2e30c9391c 100644
--- a/plugins/ruflo-console/hooks/mh-lab.ts
+++ b/plugins/ruflo-console/hooks/mh-lab.ts
@@ -10,6 +10,7 @@ import { exec, type ActionSpec } from './actions'
import { jsonAfter, type AuditTrend } from './data/cli'
import { rowsWith, type Findings } from './data/failure'
import { idOf, plain, recordOf } from './data/parse'
+import { countOf, measureOf } from './data/safe'
import type { State } from './state'
/** `read`: $0, changes nothing. `writes`: $0, writes a file or memory. `local`: minutes of local compute that writes. `spends`: may call paid models. */
@@ -126,7 +127,17 @@ export const LAB_MAX_LINES = 40
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const
const SKIP = new Set(['rawStdout', 'stdout', 'durationMs', 'generatedAt', 'schema', 'system'])
-const scalar = (value: unknown): string | null => (value === null ? 'null' : typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? plain(String(value), 120) : null)
+/** A number is shown only when it is a measurement (#3822): `1e999` parses as Infinity and `1e300` prints as "1e+300"; both read n/a. */
+const scalar = (value: unknown): string | null => (value === null ? 'null' : typeof value === 'number' ? (measureOf(value) === undefined ? 'n/a' : String(value)) : typeof value === 'string' || typeof value === 'boolean' ? plain(String(value), 120) : null)
+const tally = (value: unknown, fallback = 'n/a'): string => (value === undefined ? fallback : String(countOf(value) ?? 'n/a'))
+/** A character count the CLI printed, when it is one (whole, 0..1e12): past that it is not a length, and the text's own length is used. */
+const charsOf = (value: unknown): number | undefined => {
+ const n = measureOf(value)
+
+ return n !== undefined && n >= 0 ? Math.floor(n) : undefined
+}
+/** Any answer field as one cleaned cell: a number only when it is a measurement, anything else through plain() (#3822). */
+const cell = (value: unknown, max: number): string => (typeof value === 'number' ? (measureOf(value) === undefined ? 'n/a' : String(value)) : plain(String(value ?? ''), max))
/** Any JSON as readable lines: scalars as `key: value`, short lists inline, objects indented, two levels deep. */
function flatten(value: unknown, out: string[], depth = 0): void {
@@ -166,14 +177,14 @@ function findingLines(record: Record<string, unknown>, findings: unknown[]): str
const rows = findings.map(recordOf).filter((row): row is Record<string, unknown> => row !== null)
const severityOf = (row: Record<string, unknown>) => String(row.severity ?? 'info').toLowerCase()
const counts = SEVERITIES.map(level => `${level} ${rows.filter(row => severityOf(row) === level).length}`).join(' ยท ')
- const out = [`worst ${plain(String(record.worst ?? 'n/a'), 20)}${record.verdict !== undefined ? ` ยท verdict ${plain(String(record.verdict), 20)}` : ''} ยท ${rows.length} finding${rows.length === 1 ? '' : 's'}`, `by severity: ${counts}`]
+ const out = [`worst ${cell(record.worst ?? 'n/a', 20)}${record.verdict !== undefined ? ` ยท verdict ${cell(record.verdict, 20)}` : ''} ยท ${rows.length} finding${rows.length === 1 ? '' : 's'}`, `by severity: ${counts}`]
- for (const row of rows.slice(0, 12)) out.push(`[${severityOf(row)}] ${plain(String(row.title ?? row.message ?? row.id ?? ''), 140)}`)
+ for (const row of rows.slice(0, 12)) out.push(`[${severityOf(row)}] ${cell(row.title ?? row.message ?? row.id, 140)}`)
const flags = ['secretsReachable', 'networkAccess', 'shellAccess', 'fileWrite', 'policyDefaultDeny', 'auditLog'].filter(flag => typeof record[flag] === 'boolean')
if (flags.length > 0) out.push(flags.map(flag => `${flag} ${record[flag] === true ? 'yes' : 'no'}`).join(' ยท '))
- if (typeof record.allowedTools === 'number') out.push(`tools allowed ${record.allowedTools} ยท denied ${String(record.deniedTools ?? 'n/a')}`)
+ if (typeof record.allowedTools === 'number') out.push(`tools allowed ${tally(record.allowedTools)} ยท denied ${tally(record.deniedTools)}`)
return out
}
@@ -181,15 +192,15 @@ function findingLines(record: Record<string, unknown>, findings: unknown[]): str
/** A redblue run: tests, failures by severity, cost, the gates, then each compromised case. */
function redblueLines(record: Record<string, unknown>, summary: Record<string, unknown>): string[] {
const out = [
- `tests ${String(summary.tests_run ?? 'n/a')} ยท failures ${String(summary.failures_found ?? 'n/a')} ยท critical ${String(summary.critical ?? 0)} ยท high ${String(summary.high ?? 0)} ยท med ${String(summary.med ?? 0)} ยท low ${String(summary.low ?? 0)}`,
- `cost $${typeof summary.cost_usd === 'number' ? summary.cost_usd.toFixed(3) : 'n/a'} ยท gates ${record.gates_passed === true ? 'passed' : 'FAILED'} ยท block production ${record.should_block_production === true ? 'yes' : 'no'}`,
+ `tests ${tally(summary.tests_run)} ยท failures ${tally(summary.failures_found)} ยท critical ${tally(summary.critical, '0')} ยท high ${tally(summary.high, '0')} ยท med ${tally(summary.med, '0')} ยท low ${tally(summary.low, '0')}`,
+ `cost $${measureOf(summary.cost_usd)?.toFixed(3) ?? 'n/a'} ยท gates ${record.gates_passed === true ? 'passed' : 'FAILED'} ยท block production ${record.should_block_production === true ? 'yes' : 'no'}`,
]
for (const finding of (Array.isArray(record.findings) ? record.findings : []).map(recordOf)) {
- if (finding?.compromised === true) out.push(`โœ— ${plain(String(finding.family ?? finding.testId ?? ''), 60)} (${plain(String(finding.severity ?? ''), 12)})`)
+ if (finding?.compromised === true) out.push(`โœ— ${cell(finding.family ?? finding.testId, 60)} (${cell(finding.severity, 12)})`)
}
- for (const tip of (Array.isArray(record.recommendations) ? record.recommendations : []).slice(0, 3)) out.push(`โ†’ ${plain(String(tip), 140)}`)
+ for (const tip of (Array.isArray(record.recommendations) ? record.recommendations : []).slice(0, 3)) out.push(`โ†’ ${cell(tip, 140)}`)
return out
}
@@ -204,7 +215,7 @@ function summary(value: unknown): string[] {
return value.slice(0, 20).map(item => {
const row = recordOf(item)
- return row === null ? plain(String(item), 140) : `${plain(String(row.receiptId ?? row.id ?? ''), 24)} ยท ${plain(String(row.decision ?? ''), 20)} ยท ${plain(String(row.state ?? ''), 20)}${row.signed === true ? ' ยท signed' : ''}`
+ return row === null ? cell(item, 140) : `${cell(row.receiptId ?? row.id, 24)} ยท ${cell(row.decision, 20)} ยท ${cell(row.state, 20)}${row.signed === true ? ' ยท signed' : ''}`
})
}
@@ -219,11 +230,11 @@ function summary(value: unknown): string[] {
if (record.subcommand === 'attack' && typeof record.stdout === 'string') {
const cases = recordOf(jsonAfter(record.stdout))?.cases
- return (Array.isArray(cases) ? cases : []).map(recordOf).flatMap(row => (row === null ? [] : [`${plain(String(row.family ?? ''), 32)} ยท ${plain(String(row.input ?? row.objective ?? ''), 120)}`]))
+ return (Array.isArray(cases) ? cases : []).map(recordOf).flatMap(row => (row === null ? [] : [`${cell(row.family, 32)} ยท ${cell(row.input ?? row.objective, 120)}`]))
}
if (typeof record.system === 'string') {
- return [`${String(record.chars ?? record.system.length)} chars from ${plain(String(record.source ?? 'the genome'), 200).split('/').pop() ?? ''}`, ...record.system.split('\n').map(line => plain(line, 160))]
+ return [`${charsOf(record.chars) ?? record.system.length} chars from ${cell(record.source ?? 'the genome', 200).split('/').pop() ?? ''}`, ...record.system.split('\n').map(line => plain(line, 160))]
}
const genome = recordOf(record.genome)
@@ -231,7 +242,7 @@ function summary(value: unknown): string[] {
if (genome !== null) {
const meta = recordOf(genome.meta) ?? {}
- return [`valid ${record.valid === true ? 'yes' : 'NO'} ยท ${Array.isArray(record.errors) ? record.errors.length : 0} errors`, `genome ${String(meta.id ?? 'n/a')} (parent ${String(meta.parent ?? 'n/a')}, mutated ${String(meta.mutated ?? 'n/a')})`, `components: ${Object.keys(recordOf(genome.components) ?? {}).join(', ')}`]
+ return [`valid ${record.valid === true ? 'yes' : 'NO'} ยท ${Array.isArray(record.errors) ? record.errors.length : 0} errors`, `genome ${cell(meta.id ?? 'n/a', 40)} (parent ${cell(meta.parent ?? 'n/a', 40)}, mutated ${cell(meta.mutated ?? 'n/a', 40)})`, `components: ${Object.keys(recordOf(genome.components) ?? {}).join(', ')}`]
}
return []
diff --git a/plugins/ruflo-console/hooks/mission-control.ts b/plugins/ruflo-console/hooks/mission-control.ts
index 132b91d12d..0417cd0ea4 100644
--- a/plugins/ruflo-console/hooks/mission-control.ts
+++ b/plugins/ruflo-console/hooks/mission-control.ts
@@ -357,7 +357,7 @@ export function missionActions(state: State, host: Host, runner: Runner): Missio
runner.ask(dispatchSpec(state, host, mission, task, text => host.submitPrompt(text)), 'nothing to hand out')
},
pause: () => setPaused(state, host, true),
- resume: () => setPaused(state, host, false),
+ resume: by => setPaused(state, host, false, by),
cancel: () => {
const mission = activeMission(state)
diff --git a/plugins/ruflo-console/hooks/mission-palette.ts b/plugins/ruflo-console/hooks/mission-palette.ts
index b83ee8f88c..d7b51cf1d4 100644
--- a/plugins/ruflo-console/hooks/mission-palette.ts
+++ b/plugins/ruflo-console/hooks/mission-palette.ts
@@ -47,7 +47,9 @@ export function missionPalette(state: State): PaletteEntry[] {
}),
},
{ id: 'mission-pause', group: 'missions', label: 'pause: no more tasks are handed out', run: spec(() => local('pause the mission', () => wired?.actions.pause(), 'write')) },
- { id: 'mission-resume', group: 'missions', label: 'resume handing out tasks', run: spec(() => local('resume the mission', () => wired?.actions.resume(), 'write')) },
+ // Who resumes is known when the entry is built: Claude's console_run builds the palette inside its call (state.control.viaModel). Claude's
+ // resume keeps the hand-out counts; only the person's gives an exhausted task more billed turns (#3823).
+ { id: 'mission-resume', group: 'missions', label: 'resume handing out tasks', run: spec(() => (state.control.viaModel ? local('resume the mission (Claude: hand-out counts kept)', () => wired?.actions.resume('model'), 'write') : local('resume the mission', () => wired?.actions.resume('person'), 'write'))) },
{ id: 'mission-cancel', group: 'missions', label: 'cancel the mission and its open tasks (asks first)', run: spec(() => { const mission = activeMission(state); return wired === undefined || mission === null ? null : cancelSpec(state, wired.host, mission, tasks()) }) },
{ id: 'mission-aside', group: 'missions', label: 'mission-aside <question>: /btw beside the running task', run: text('mission-aside', value => local('ask aside', () => wired?.actions.aside(value), 'spend')) },
{ id: 'mission-guide', group: 'missions', label: 'mission-guide <instruction>: a visible instruction to Claude (screened, asks first)', run: text('mission-guide', value => local('guide Claude', () => wired?.actions.guide(value))) },
diff --git a/plugins/ruflo-console/hooks/mission-specs.ts b/plugins/ruflo-console/hooks/mission-specs.ts
index 5cd0ad2cd6..e32b29e450 100644
--- a/plugins/ruflo-console/hooks/mission-specs.ts
+++ b/plugins/ruflo-console/hooks/mission-specs.ts
@@ -7,7 +7,7 @@ import type { Host } from './host'
import { adrBlockFor } from './adr-mission'
import { EVENT_RESUMED, stoppedByAdvisor } from './mission-advisor'
import { activeMission, instructionOf, mcOf, nextTask, record, rufloTaskOf, saveLedger } from './mission-control'
-import type { LedgerTask, MissionRecord } from './mission-types'
+import type { LedgerTask, MissionRecord, ResumeBy } from './mission-types'
import { argvOf } from './mission-create'
import type { State } from './state'
@@ -88,19 +88,30 @@ export function dispatchSpec(state: State, host: Host, mission: MissionRecord, t
}
}
-/** Pause or resume dispatching, kept in the ledger (a session-bound mission has no durable executor to pause). */
-export function setPaused(state: State, host: Host, paused: boolean): void {
+/**
+ * Pause or resume dispatching, kept in the ledger (a session-bound mission has no durable executor to pause). Only the person's resume re-arms
+ * hand-outs: Claude may resume at write:auto without a Yes, so its resume keeps every task's count (and an advisor stop-the-line stays stopped),
+ * and a task that used its MAX_HANDOUTS is not handed out again (no new billed turn) until the person resumes it themselves (#3823).
+ */
+export function setPaused(state: State, host: Host, paused: boolean, by: ResumeBy = 'person'): void {
const mission = activeMission(state)
if (mission === null || mission.cancelled) return
+ const isPerson = by === 'person'
+ const spent = mission.tasks.filter(task => (task.handouts ?? 0) >= MAX_HANDOUTS).length
+
mission.paused = paused
// The person resuming has seen why it stopped: each task gets its hand-outs again.
- if (!paused) for (const task of mission.tasks) task.handouts = 0
- record(mission, { type: paused ? 'mission.paused' : 'mission.resumed', status: paused ? 'paused' : 'running' })
- // ADR-483: resuming after an advisor stop-the-line gives the failing check a fresh run of tries.
- if (!paused && stoppedByAdvisor(mission)) record(mission, { type: EVENT_RESUMED })
- mcOf(state).last = { label: paused ? 'paused: no more tasks are handed out' : 'resumed', ok: true, detail: paused ? 'a task already handed to Claude finishes first' : 'Run next hands out the next ready task' }
+ if (!paused && isPerson) for (const task of mission.tasks) task.handouts = 0
+ record(mission, { type: paused ? 'mission.paused' : 'mission.resumed', status: paused ? 'paused' : 'running', ...(!paused && !isPerson && { note: `resumed by Claude: hand-out counts kept${spent > 0 ? ` (${spent} task${spent === 1 ? '' : 's'} at the limit)` : ''}` }) })
+ // ADR-483: the person resuming after an advisor stop-the-line gives the failing check a fresh run of tries. Claude's resume does not, for the
+ // same reason it keeps the hand-out counts: the next checkpoint stops the line again (#3823).
+ if (!paused && isPerson && stoppedByAdvisor(mission)) record(mission, { type: EVENT_RESUMED })
+
+ const detail = paused ? 'a task already handed to Claude finishes first' : !isPerson && spent > 0 ? `${spent} task${spent === 1 ? '' : 's'} used every hand-out: only your own resume gives them more` : 'Run next hands out the next ready task'
+
+ mcOf(state).last = { label: paused ? 'paused: no more tasks are handed out' : isPerson ? 'resumed' : 'resumed by Claude', ok: true, detail }
saveLedger(state, host)
host.invalidate()
}
diff --git a/plugins/ruflo-console/hooks/mission-types.ts b/plugins/ruflo-console/hooks/mission-types.ts
index b12bef3c09..a4ef28d992 100644
--- a/plugins/ruflo-console/hooks/mission-types.ts
+++ b/plugins/ruflo-console/hooks/mission-types.ts
@@ -49,6 +49,9 @@ export type McState = {
last: { label: string; ok: boolean; detail: string; atMs?: number; next?: string; lines?: string[] } | null
}
+/** Who resumed a mission: only the person re-arms hand-outs that ran out (#3823). */
+export type ResumeBy = 'person' | 'model'
+
export type MissionActions = {
goal: (text: string) => void
profile: (profile: Profile) => void
@@ -59,7 +62,8 @@ export type MissionActions = {
/** Hands the next ready task to the primary session (asks first: it starts a model turn). */
next: () => void
pause: () => void
- resume: () => void
+ /** Resume dispatching. The person's resume gives each task its hand-outs back; Claude's (`'model'`) keeps the counts (#3823). */
+ resume: (by?: ResumeBy) => void
cancel: () => void
/** Auto-run: when a task finishes and the session is idle, hand over the next ready one without asking. */
auto: (on: boolean) => void
diff --git a/plugins/ruflo-console/hooks/neural.ts b/plugins/ruflo-console/hooks/neural.ts
index 92ed4cef37..73bec25ee9 100644
--- a/plugins/ruflo-console/hooks/neural.ts
+++ b/plugins/ruflo-console/hooks/neural.ts
@@ -10,7 +10,8 @@ import type { ActionSpec } from './actions'
import { autoSpec, tool, type AutoEntry } from './automate'
import { recallEntries } from './recall'
import { EPOCHS, freeText, objectIn, parseTrain, PATTERNS, tableRows, type Pattern } from './data/automate'
-import { numberOf, plain, recordOf } from './data/parse'
+import { plain, recordOf } from './data/parse'
+import { ratioOf } from './data/safe'
import { labLines } from './mh-lab'
import type { State } from './state'
@@ -54,11 +55,12 @@ function routeRead(stdout: string, stderr: string): string[] {
if (value === null || primary === null) return labLines('nn-route', stdout, stderr)
- const confidence = numberOf(primary.confidence)
+ // A confidence is a 0..1 ratio: clamped where it is read, so `1e300` is not drawn as "1e+302%" (#3822).
+ const confidence = ratioOf(primary.confidence)
const out = [`โ†’ ${plain(String(primary.type ?? 'n/a'), 30)}${confidence !== undefined ? ` ยท ${Math.round(confidence * 100)}%` : ''} ยท ${plain(String(recordOf(value.routing)?.method ?? 'n/a'), 30)}${value.matchedPattern !== undefined ? ` ยท pattern ${plain(String(value.matchedPattern), 30)}` : ''}`]
for (const alt of (Array.isArray(value.alternativeAgents) ? value.alternativeAgents : []).slice(0, 4).map(recordOf)) {
- const score = numberOf(alt?.confidence ?? alt?.score)
+ const score = ratioOf(alt?.confidence ?? alt?.score)
if (alt !== null) out.push(` or ${plain(String(alt.type ?? alt.agent ?? ''), 30)}${score !== undefined ? ` ยท ${Math.round(score * 100)}%` : ''}`)
}
diff --git a/plugins/ruflo-console/hooks/perf.ts b/plugins/ruflo-console/hooks/perf.ts
index ab4dc54914..09f698e56c 100644
--- a/plugins/ruflo-console/hooks/perf.ts
+++ b/plugins/ruflo-console/hooks/perf.ts
@@ -9,6 +9,7 @@
import { exec } from './actions'
import { jsonAfter } from './data/cli'
import { plain, recordOf } from './data/parse'
+import { measureOf } from './data/safe'
import { labLines } from './mh-lab'
import { mcpReader, textLines, type Reader, type SecCost } from './secure'
import type { State } from './state'
@@ -49,14 +50,21 @@ export function sparkline(values: readonly number[], width = 32): string {
/** Any value as one cleaned cell: numbers must be finite and sane (a hostile 1e300 is "n/a", not a display value), text goes through plain(). */
function show(value: unknown, max = 24): string {
- if (typeof value === 'number') return Number.isFinite(value) && Math.abs(value) <= 1e12 ? String(value) : 'n/a'
+ if (typeof value === 'number') return measureOf(value) === undefined ? 'n/a' : String(value)
if (value === undefined || value === null) return 'n/a'
return plain(typeof value === 'string' ? value : typeof value === 'boolean' ? String(value) : '', max) || 'n/a'
}
-const ms = (value: unknown, digits = 3): string => (typeof value === 'number' && Number.isFinite(value) ? `${value.toFixed(digits)}ms` : 'n/a')
-const mb = (bytes: unknown): string => (typeof bytes === 'number' && Number.isFinite(bytes) ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : 'n/a')
+// Every number below is bounded where it is read (#3822): `1e999` parses as Infinity and `1e300` prints as "1e+300", neither a measurement.
+const as = (value: unknown, text: (n: number) => string): string => {
+ const n = measureOf(value)
+
+ return n === undefined ? 'n/a' : text(n)
+}
+const ms = (value: unknown, digits = 3): string => as(value, n => `${n.toFixed(digits)}ms`)
+const mb = (bytes: unknown): string => as(bytes, n => `${(n / 1024 / 1024).toFixed(1)} MB`)
+const pct = (value: unknown, digits?: number): string => as(value, n => `${digits === undefined ? String(n) : n.toFixed(digits)}%`)
/** `performance metrics --format json`: memory, CPU, load and the event-loop latency, which feeds the sparkline. */
export const metricsReader: Reader = (stdout, stderr, state) => {
@@ -68,18 +76,19 @@ export const metricsReader: Reader = (stdout, stderr, state) => {
const cpu = recordOf(record.cpu) ?? {}
const latency = recordOf(record.latency) ?? {}
const cache = recordOf(record.cache) ?? {}
- const avg = typeof latency.avgMs === 'number' && Number.isFinite(latency.avgMs) ? latency.avgMs : null
+ const avg = measureOf(latency.avgMs) ?? null
+ const heap = measureOf(memory.heapUsed)
const memo = perfMemo(state)
if (avg !== null) memo.loop = [...memo.loop, avg].slice(-KEEP)
- memo.heapMb = typeof memory.heapUsed === 'number' ? memory.heapUsed / 1024 / 1024 : null
+ memo.heapMb = heap === undefined ? null : heap / 1024 / 1024
memo.atMs = Date.now()
- const load = Array.isArray(cpu.loadAverage) ? cpu.loadAverage.filter(value => typeof value === 'number').map(value => value.toFixed(2)).join(' ') : 'n/a'
+ const load = Array.isArray(cpu.loadAverage) ? cpu.loadAverage.flatMap(value => (measureOf(value) === undefined ? [] : [as(value, n => n.toFixed(2))])).join(' ') : 'n/a'
return [
`event-loop latency ${ms(avg)} ยท heap ${mb(memory.heapUsed)} of ${mb(memory.heapTotal)} ยท rss ${mb(memory.rss)}`,
- `system memory ${typeof memory.systemPercent === 'number' ? `${memory.systemPercent}%` : 'n/a'} ยท load ${load}`,
+ `system memory ${pct(memory.systemPercent)} ยท load ${load}`,
`embedding cache ~${show(cache.entries)} entries ยท HNSW ${show(cache.hnswEntries)} entries`,
'measured in the CLI process at the moment it ran: one sample per run',
]
@@ -108,7 +117,9 @@ export const reportReader: Reader = (stdout, stderr, state) => {
const history = (Array.isArray(result.history) ? result.history : []).map(recordOf).flatMap(row => {
const avg = recordOf(row?.latency)?.avg
- return typeof avg === 'number' && Number.isFinite(avg) ? [avg] : []
+ const sample = measureOf(avg)
+
+ return sample === undefined ? [] : [sample]
})
const memo = perfMemo(state)
const cpu = recordOf(current.cpu) ?? {}
@@ -119,7 +130,7 @@ export const reportReader: Reader = (stdout, stderr, state) => {
memo.atMs = Date.now()
return [
- `cpu ${typeof cpu.usage === 'number' ? `${cpu.usage.toFixed(1)}%` : 'n/a'} of ${show(cpu.cores)} cores ยท memory ${show(memory.used)} of ${show(memory.total)} MB ยท heap ${show(memory.heap)} MB`,
+ `cpu ${pct(cpu.usage, 1)} of ${show(cpu.cores)} cores ยท memory ${show(memory.used)} of ${show(memory.total)} MB ยท heap ${show(memory.heap)} MB`,
`latency avg ${ms(latency.avg)} ยท p50 ${ms(latency.p50)} ยท p95 ${ms(latency.p95)} ยท p99 ${ms(latency.p99)}`,
`history: ${history.length} stored sample${history.length === 1 ? '' : 's'} in .claude-flow/performance/metrics.json`,
...labLines('performance_report', JSON.stringify({ trends: result.trends, recommendations: result.recommendations })).slice(0, 12),
diff --git a/plugins/ruflo-console/hooks/secure.ts b/plugins/ruflo-console/hooks/secure.ts
index ba88ce5820..d7c8b19f8e 100644
--- a/plugins/ruflo-console/hooks/secure.ts
+++ b/plugins/ruflo-console/hooks/secure.ts
@@ -11,6 +11,7 @@ import { exec, type ActionSpec } from './actions'
import { jsonAfter } from './data/cli'
import { countsWith, rowsWith, type Findings } from './data/failure'
import { plain, recordOf } from './data/parse'
+import { countOf as wholeCount, measureOf, ratioOf } from './data/safe'
import { labLines } from './mh-lab'
import type { State } from './state'
@@ -44,7 +45,33 @@ export type SecText = { id: string; name: string; about: string; label: string;
export type Check = { status: 'pass' | 'warn' | 'fail'; name: string; message: string }
/** What the view draws beyond the result lines: the last findings by severity, the last doctor checks, the field's text. */
-export type SecMemo = { findings: { source: string; counts: Record<Severity, number>; atMs: number } | null; doctor: { label: string; checks: Check[]; atMs: number } | null; draft: string }
+export type SecMemo = { findings: SecFindings | null; doctor: { label: string; checks: Check[]; atMs: number } | null; draft: string }
+
+/**
+ * Counts by severity. `unreadable` names the levels whose count the tool printed but no reader can trust, and `isTotalUnknown` says the same of
+ * the total (#3822): unknown, never a measured 0. An unknown level's `counts` entry is only a lower bound (the findings listed at that level).
+ */
+export type SecFindings = { source: string; counts: Record<Severity, number>; unreadable?: readonly Severity[]; isTotalUnknown?: boolean; atMs: number }
+
+/** One level's count as text: `?` when it was unreadable, `โ‰ฅn ?` when n findings of that level were listed. */
+export const countText = (findings: SecFindings, level: Severity): string => {
+ if (!(findings.unreadable ?? []).includes(level)) return String(findings.counts[level])
+
+ return findings.counts[level] > 0 ? `โ‰ฅ${findings.counts[level]} ?` : '?'
+}
+
+/** What the band says about the last findings: high or critical ones, or that the counts could not be read. Null when there is nothing to warn of. */
+export function securityBand(findings: SecFindings | null): { text: string; compact: string; isAttention: boolean } | null {
+ if (findings === null) return null
+
+ const serious = findings.counts.critical + findings.counts.high
+ const isUnknown = (findings.unreadable ?? []).length > 0 || findings.isTotalUnknown === true
+ const more = isUnknown ? '+' : ''
+
+ if (serious > 0) return { text: `๐Ÿ”’ ${serious}${more} high or critical`, compact: `๐Ÿ”’ ${serious}${more}`, isAttention: findings.counts.critical > 0 || isUnknown }
+
+ return isUnknown ? { text: '๐Ÿ”’ security counts unreadable', compact: '๐Ÿ”’ ?', isAttention: true } : null
+}
const memos = new WeakMap<State, SecMemo>()
@@ -99,22 +126,50 @@ export const scanReader: Reader = (stdout, stderr, state) => {
if (record === null || summary === null) return textLines(stdout, stderr)
+ const findings = (Array.isArray(record.findings) ? record.findings : []).map(recordOf).filter(row => row !== null)
+ const listed = zero()
const counts = zero()
+ const unreadable: Severity[] = []
- for (const level of SEVERITIES) counts[level] = typeof summary[level] === 'number' ? summary[level] : 0
- secMemo(state).findings = { source: `scan ${plain(String(record.type ?? ''), 8)} ${plain(String(record.depth ?? ''), 10)}`.trim(), counts, atMs: Date.now() }
+ for (const row of findings) listed[levelOf(row.severity) ?? 'low'] += 1
- const findings = (Array.isArray(record.findings) ? record.findings : []).map(recordOf).filter(row => row !== null)
- const total = typeof summary.total === 'number' ? summary.total : findings.length
+ // A count is whole, non-negative and capped where it is read (#3822): `1e999` parses as Infinity. Every count, and the total, is at least what
+ // was listed, so a summary that under-reports cannot hide a finding or read CLEAN beside one. A count the tool printed but no reader can trust
+ // stays UNKNOWN (the listed findings are only its lower bound), and the result, the page and the band all say so.
+ for (const level of SEVERITIES) {
+ const raw = summary[level]
+ const count = wholeCount(raw)
+
+ counts[level] = Math.max(count ?? 0, listed[level])
+ if (count === undefined && raw !== undefined) unreadable.push(level)
+ }
+
+ const readTotal = wholeCount(summary.total)
+ const isTotalUnknown = readTotal === undefined && summary.total !== undefined
+ const total = Math.max(readTotal ?? 0, findings.length)
+ const memo: SecFindings = { source: `scan ${plain(String(record.type ?? ''), 8)} ${plain(String(record.depth ?? ''), 10)}`.trim(), counts, ...(unreadable.length > 0 && { unreadable }), ...(isTotalUnknown && { isTotalUnknown }), atMs: Date.now() }
+
+ secMemo(state).findings = memo
+
+ const isUnknown = unreadable.length > 0 || isTotalUnknown
+ const head = counts.critical + counts.high > 0 ? 'ATTENTION' : isUnknown ? 'COUNTS UNREADABLE' : total === 0 ? 'CLEAN' : 'REVIEW'
+ const totalText = isTotalUnknown ? `${total > 0 ? `โ‰ฅ${total} ` : ''}? findings (total unreadable)` : `${total} finding${total === 1 ? '' : 's'}`
return [
- `${counts.critical + counts.high > 0 ? 'ATTENTION' : total === 0 ? 'CLEAN' : 'REVIEW'} ยท ${total} finding${total === 1 ? '' : 's'} ยท depth ${plain(String(record.depth ?? 'n/a'), 10)} ยท type ${plain(String(record.type ?? 'n/a'), 8)}`,
- `by severity: ${SEVERITIES.map(level => `${level} ${counts[level]}`).join(' ยท ')}`,
+ `${head} ยท ${totalText} ยท depth ${plain(String(record.depth ?? 'n/a'), 10)} ยท type ${plain(String(record.type ?? 'n/a'), 8)}`,
+ `by severity: ${SEVERITIES.map(level => `${level} ${countText(memo, level)}`).join(' ยท ')}${unreadable.length > 0 ? ` (counts unreadable: ${unreadable.join(', ')}; a listed finding is a lower bound)` : ''}`,
...findings.slice(0, 30).map(row => `[${levelOf(row.severity) ?? 'low'}] ${plain(String(row.type ?? ''), 40)} ยท ${plain(String(row.location ?? ''), 60)} ยท ${plain(String(row.description ?? ''), 80)}`),
...(findings.length > 30 ? [`โ€ฆ ${findings.length - 30} more`] : []),
]
}
+/** A confidence as ` 87%`, clamped to 0..100; empty when it is not a finite number (`1e999` would draw "Infinity%") (#3822). */
+const percent = (value: unknown): string => {
+ const ratio = ratioOf(value)
+
+ return ratio === undefined ? '' : ` ${Math.round(ratio * 100)}%`
+}
+
/** One verdict object (defend, aidefence_scan, channel-scan, scan-plan): the verdict first, so an exit 1 reads right. */
function verdictLines(record: Record<string, unknown>, source: string, state: State): string[] | null {
const threats = (Array.isArray(record.threats) ? record.threats : Array.isArray(record.findings) ? record.findings : null)?.map(recordOf).filter(row => row !== null) ?? null
@@ -138,7 +193,7 @@ function verdictLines(record: Record<string, unknown>, source: string, state: St
return [
head.join(' ยท '),
- ...(threats ?? []).slice(0, 20).map(row => `[${levelOf(row.severity) ?? 'low'}] ${plain(String(row.type ?? row.kind ?? ''), 32)}${typeof row.confidence === 'number' ? ` ${Math.round(row.confidence * 100)}%` : ''} ยท ${plain(String(row.description ?? row.reason ?? ''), 110)}`),
+ ...(threats ?? []).slice(0, 20).map(row => `[${levelOf(row.severity) ?? 'low'}] ${plain(String(row.type ?? row.kind ?? ''), 32)}${percent(row.confidence)} ยท ${plain(String(row.description ?? row.reason ?? ''), 110)}`),
]
}
@@ -178,7 +233,7 @@ export const compositionReader: Reader = (stdout, stderr) => {
if (suspects === undefined) return textLines(stdout, stderr)
- return [`${suspects.length} suspect${suspects.length === 1 ? '' : 's'} in the CLI's registered MCP tool descriptions`, ...suspects.slice(0, 25).map(row => `${plain(String(row.tool ?? ''), 32)} ยท ${typeof row.score === 'number' ? row.score.toFixed(2) : 'n/a'} ยท ${plain(String(row.reason ?? ''), 100)}`)]
+ return [`${suspects.length} suspect${suspects.length === 1 ? '' : 's'} in the CLI's registered MCP tool descriptions`, ...suspects.slice(0, 25).map(row => `${plain(String(row.tool ?? ''), 32)} ยท ${measureOf(row.score)?.toFixed(2) ?? 'n/a'} ยท ${plain(String(row.reason ?? ''), 100)}`)]
}
/** Doctor's `โœ“|โš |โœ— Name: message` rows (colours stripped), its summary, and anything after them (suggested fixes). */
diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.ts
index 7350ac3476..b8fe6ff9fe 100644
--- a/plugins/ruflo-console/hooks/views/bar.ts
+++ b/plugins/ruflo-console/hooks/views/bar.ts
@@ -11,7 +11,7 @@ import type { RenderElement } from 'claude-code'
import { alertsOf, waitingApprovalsOf } from '../data/alerts'
import { agentLabels } from '../data/parse'
import { swarmStatusOf } from '../data/swarm-status'
-import { secMemo } from '../secure'
+import { secMemo, securityBand } from '../secure'
import type { State, ViewId } from '../state'
import { sparkline } from '../memory-lines'
import { visibleNotice, type Notice } from '../notices'
@@ -173,10 +173,9 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {
parts.push({ text: `ctx ${Math.round(context)}%${context >= 85 ? ' ยท /compact soon' : ''}`, tone: context >= 80 ? 'attention' : 'plain', go: 'cost', row: 'standing', compact: `ctx ${Math.round(context)}%` })
}
- const findings = secMemo(state).findings
- const serious = findings === null ? 0 : findings.counts.critical + findings.counts.high
+ const security = securityBand(secMemo(state).findings)
- if (findings !== null && serious > 0) parts.push({ text: `๐Ÿ”’ ${serious} high or critical`, tone: findings.counts.critical > 0 ? 'attention' : 'plain', go: 'secure', row: 'standing', compact: `๐Ÿ”’ ${serious}` })
+ if (security !== null) parts.push({ text: security.text, tone: security.isAttention ? 'attention' : 'plain', go: 'secure', row: 'standing', compact: security.compact })
if (state.updateAvailable !== '') parts.push({ text: `โฌ† ${state.updateAvailable} available`, tone: 'attention', go: 'settings', row: 'standing' })
return parts
diff --git a/plugins/ruflo-console/hooks/views/secure.ts b/plugins/ruflo-console/hooks/views/secure.ts
index dddac2a6a9..9f8b11f02f 100644
--- a/plugins/ruflo-console/hooks/views/secure.ts
+++ b/plugins/ruflo-console/hooks/views/secure.ts
@@ -1,6 +1,6 @@
import type { RenderElement } from 'claude-code'
-import { DOCTOR_COMPONENTS, isSecureResult, SECURE, SECURE_TEXT, secMemo, SEVERITIES, type SecCost, type Severity } from '../secure'
+import { countText, DOCTOR_COMPONENTS, isSecureResult, SECURE, SECURE_TEXT, secMemo, SEVERITIES, type SecCost, type Severity } from '../secure'
import { slot } from './attention'
import { spinAt } from '../spinner'
import { sentryRows } from './sentries'
@@ -143,7 +143,7 @@ export function meterRows(ctx: Ctx): RenderElement[] {
row(ctx, [
ctx.kit.Text({ bold: n > 0, color: n > 0 ? SEVERITY_COLOR[level]() : THEME.info, dimColor: n === 0, children: ` ${level.padEnd(9)}` }),
ctx.kit.Text({ color: SEVERITY_COLOR[level](), children: 'โ–ˆ'.repeat(filled) }),
- ctx.kit.Text({ dimColor: true, children: `${'โ–‘'.repeat(width - filled)} ${n}` }),
+ ctx.kit.Text({ dimColor: true, children: `${'โ–‘'.repeat(width - filled)} ${countText(findings, level)}` }),
], `meter-${level}`),
)
}
@@ -261,7 +261,7 @@ export function secureView(ctx: Ctx): RenderElement {
ctx,
'sec-findings',
'Findings',
- findings === null ? 'none measured yet' : `${SEVERITIES.map(level => `${findings.counts[level]} ${level}`).join(' ยท ')} ยท ${ago(findings.atMs, nowMs)}`,
+ findings === null ? 'none measured yet' : `${SEVERITIES.map(level => `${countText(findings, level)} ${level}`).join(' ยท ')}${(findings.unreadable ?? []).length > 0 ? ' ยท counts unreadable' : ''} ยท ${ago(findings.atMs, nowMs)}`,
[...meterRows(ctx), ...anatoleMeterRows(ctx), ...(findings === null ? [] : [sendFindingsRow(ctx)])],
true,
),
diff --git a/plugins/ruflo-console/tests/mission-resume-3823.spec.ts b/plugins/ruflo-console/tests/mission-resume-3823.spec.ts
new file mode 100644
index 0000000000..28089d1f71
--- /dev/null
+++ b/plugins/ruflo-console/tests/mission-resume-3823.spec.ts
@@ -0,0 +1,112 @@
+/**
+ * A resume does not silently re-arm hand-outs that ran out (#3818, #3823). After MAX_HANDOUTS failed hand-outs auto-run pauses the mission and
+ * waits for the person. `mission-resume` is a write action, so at write:auto Claude can resume it without a Yes: that resume keeps each task's
+ * hand-out count, so an exhausted task is not handed out again (no new billed turn). The person's own resume (their click, their palette run)
+ * is the one that gives every task its hand-outs back. Real controller, runner, palette, advance() and callTool over a fake host.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { activeMission, advance, mcOf } from '../hooks/mission-control'
+import { EVENT_RESUMED, EVENT_STOP, stoppedByAdvisor } from '../hooks/mission-advisor'
+import { MAX_HANDOUTS, setPaused } from '../hooks/mission-specs'
+import type { MissionRecord } from '../hooks/mission-types'
+import { callTool } from '../hooks/model-tools'
+import { settingsOf } from '../hooks/settings'
+import { rig } from './fixtures/real-rig'
+
+const ID = 'msn_0123456789abcdef01234567'
+const ok = { exitCode: 0, stdout: 'Result:\n{"success": true}', stderr: '' }
+const mission = (): MissionRecord => ({ id: ID, objective: 'ship it', profile: 'feature', rigor: 'standard', tasks: [{ id: 't1', title: 'one', phase: 'S', agent: 'coder', requirement: 'r', dependsOn: [], rufloTaskId: 'r1' }], acceptance: [], events: [], paused: false, cancelled: false, auto: true, createdAtMs: 1 })
+const settle = () => new Promise(resolve => setTimeout(resolve, 10))
+
+/** A mission whose only task came back unfinished MAX_HANDOUTS times, so auto-run paused it with `handout.limit`. */
+async function exhausted() {
+ const w = rig({ run: () => ok })
+
+ Object.assign(settingsOf(w.state).ai, { modelControl: 'write', modelConfirm: 'auto' })
+ w.state.cwd = '/work'
+ mcOf(w.state).missions.set(ID, mission())
+ mcOf(w.state).active = ID
+ w.state.snapshot = { tasks: [{ id: 'r1', type: 'feature', description: '', status: 'pending', assignedTo: [], tags: [] }], plugins: { installed: [] } } as never
+ w.control.setView('missions')
+
+ for (let i = 0; i < 8; i++) {
+ advance(w.state, w.host)
+ await settle()
+ w.fireTimers()
+ }
+
+ const m = activeMission(w.state) as MissionRecord
+
+ expect(m.paused).toBe(true)
+ expect(m.events.map(event => event.type)).toContain('handout.limit')
+ expect(w.seen.prompts).toHaveLength(MAX_HANDOUTS)
+
+ return { ...w, m }
+}
+
+describe('a resume does not re-arm exhausted hand-outs behind the person (#3823)', () => {
+ it('Claude resuming at write:auto keeps the count, and auto-run hands out no new billed turn for the exhausted task', async () => {
+ const w = await exhausted()
+ const answer = await callTool('console_run', { id: 'mission-resume', text: '' }, w.deps)
+
+ expect(answer).not.toMatch(/^Refused/)
+ expect(w.m.tasks[0]?.handouts).toBe(MAX_HANDOUTS)
+
+ for (let i = 0; i < 4; i++) {
+ advance(w.state, w.host)
+ await settle()
+ w.fireTimers()
+ }
+
+ expect(w.seen.prompts).toHaveLength(MAX_HANDOUTS)
+ expect(w.m.paused).toBe(true)
+ expect(w.m.events.filter(event => event.type === 'mission.resumed').at(-1)?.note).toMatch(/Claude/)
+ })
+
+ it('Claude resuming again and again buys no hand-outs either', async () => {
+ const w = await exhausted()
+
+ for (let round = 0; round < 3; round++) {
+ await callTool('console_run', { id: 'mission-resume', text: '' }, w.deps)
+ advance(w.state, w.host)
+ await settle()
+ w.fireTimers()
+ }
+
+ expect(w.seen.prompts).toHaveLength(MAX_HANDOUTS)
+ })
+
+ it('the person resuming (the Missions button) gives each task its hand-outs back, and auto-run carries on', async () => {
+ const w = await exhausted()
+
+ w.control.actions.mission.resume()
+ expect(w.m.tasks[0]?.handouts).toBe(0)
+ expect(w.m.paused).toBe(false)
+ advance(w.state, w.host)
+ await settle()
+ expect(w.seen.prompts).toHaveLength(MAX_HANDOUTS + 1)
+ })
+
+ it('the person running mission-resume from the palette is the person too', async () => {
+ const w = await exhausted()
+
+ expect(w.control.runner.runById('mission-resume', '', { exact: true })).toBe(true)
+ await w.control.runner.settled()
+ expect(w.m.tasks[0]?.handouts).toBe(0)
+ expect(w.m.paused).toBe(false)
+ })
+
+ it('after an advisor stop-the-line, Claude\'s resume opens no fresh run of tries; the person\'s does (ADR-483)', () => {
+ const w = rig()
+ const m = { ...mission(), paused: true, events: [{ seq: 1, atMs: 1, type: EVENT_STOP, status: 'paused', taskId: 't1' }] }
+
+ mcOf(w.state).missions.set(ID, m)
+ mcOf(w.state).active = ID
+ setPaused(w.state, w.host as never, false, 'model')
+ expect(m.events.map(event => event.type)).not.toContain(EVENT_RESUMED)
+ expect(stoppedByAdvisor(m)).toBe(true)
+ setPaused(w.state, w.host as never, false, 'person')
+ expect(stoppedByAdvisor(m)).toBe(false)
+ })
+})
diff --git a/plugins/ruflo-console/tests/unbounded-numbers-3822.spec.ts b/plugins/ruflo-console/tests/unbounded-numbers-3822.spec.ts
new file mode 100644
index 0000000000..9516441f74
--- /dev/null
+++ b/plugins/ruflo-console/tests/unbounded-numbers-3822.spec.ts
@@ -0,0 +1,222 @@
+/**
+ * A number another process printed is bounded where it is read (#3817, #3822): `JSON.parse('1e999')` is Infinity, and a CLI's JSON can carry a
+ * negative, fractional or absurd count. The severity counts, totals, confidences and the other counts the readers keep must never draw "Infinity",
+ * "NaN", a negative count or "1e+300" on the band or in a result panel. Real readers and the real band over a fresh State.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { memoryProbe, PROBES } from '../hooks/data/cli'
+import { parseLedger, parsePolicyLedger, parseWitness } from '../hooks/data/evolve'
+import { MAX_COUNT } from '../hooks/data/safe'
+import { labLines } from '../hooks/mh-lab'
+import { routeSpec } from '../hooks/neural'
+import { metricsReader, reportReader } from '../hooks/perf'
+import { compositionReader, countText, mcpReader, scanReader, secMemo } from '../hooks/secure'
+import { newState } from '../hooks/state'
+import { barParts, barText } from '../hooks/views/bar'
+import { parseResearch } from '../hooks/data/research'
+import { memLines } from '../hooks/memory-lines'
+
+const NOT_A_NUMBER = /Infinity|NaN|e\+\d/
+const scan = (summary: string, findings = '[]') => `{"type":"all","depth":"quick","summary":${summary},"findings":${findings}}`
+
+describe('security scan counts are bounded at the reader (#3822)', () => {
+ it('a summary count of 1e999 with nothing listed is unknown, not 0: the result, the page and the band say so', () => {
+ const state = newState({})
+ const lines = scanReader(scan('{"critical":1e999,"high":0,"medium":0,"low":0}'), '', state)
+ const findings = secMemo(state).findings
+
+ expect(barText(state)).not.toMatch(NOT_A_NUMBER)
+ expect(lines.join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(findings?.unreadable).toEqual(['critical'])
+ expect(findings === null ? '' : countText(findings, 'critical')).toBe('?')
+ expect(lines[0]).toMatch(/^COUNTS UNREADABLE/)
+ expect(lines[1]).toMatch(/critical \? ยท high 0/)
+ expect(barText(state)).toMatch(/๐Ÿ”’ security counts unreadable/)
+ expect(barParts(state, Date.now()).find(part => part.go === 'secure')?.tone).toBe('attention')
+ })
+
+ it('an unreadable count with a listed critical: at least 1, still unknown, and the band warns (the review case)', () => {
+ const state = newState({})
+ const lines = scanReader(scan('{"critical":1e999,"high":0,"medium":0,"low":0,"total":1}', '[{"severity":"critical","type":"secret","location":"a.ts"}]'), '', state)
+
+ expect(secMemo(state).findings?.counts.critical).toBe(1)
+ expect(secMemo(state).findings?.unreadable).toEqual(['critical'])
+ expect(lines[0]).toMatch(/^ATTENTION ยท 1 finding/)
+ expect(lines[1]).toMatch(/critical โ‰ฅ1 \?/)
+ expect(barText(state)).toMatch(/๐Ÿ”’ 1\+ high or critical/)
+ })
+
+ it('an unreadable critical count with only a LOW finding listed stays unknown: the listed count is a lower bound, and the band warns', () => {
+ const state = newState({})
+ const lines = scanReader(scan('{"critical":1e999,"high":0,"medium":0,"low":0,"total":1}', '[{"severity":"low","type":"x"}]'), '', state)
+ const findings = secMemo(state).findings
+
+ expect(findings?.unreadable).toEqual(['critical'])
+ expect(findings === null ? '' : countText(findings, 'critical')).toBe('?')
+ expect(lines[0]).toMatch(/^COUNTS UNREADABLE/)
+ expect(barText(state)).toMatch(/๐Ÿ”’ security counts unreadable/)
+ })
+
+ it('an unreadable count keeps the listed findings of that severity as its lower bound ("โ‰ฅ2 ?")', () => {
+ const state = newState({})
+
+ scanReader(scan('{"critical":0,"high":-3,"medium":0,"low":0,"total":2}', '[{"severity":"high","type":"x"},{"severity":"high","type":"y"}]'), '', state)
+ const findings = secMemo(state).findings
+
+ expect(findings?.unreadable).toEqual(['high'])
+ expect(findings === null ? '' : countText(findings, 'high')).toBe('โ‰ฅ2 ?')
+ expect(barText(state)).toMatch(/๐Ÿ”’ 2\+ high or critical/)
+ })
+
+ it('an unreadable total with every severity 0 is recorded and warns on the band', () => {
+ const state = newState({})
+ const lines = scanReader(scan('{"critical":0,"high":0,"medium":0,"low":0,"total":1e999}'), '', state)
+
+ expect(secMemo(state).findings?.isTotalUnknown).toBe(true)
+ expect(lines[0]).toMatch(/^COUNTS UNREADABLE ยท \? findings/)
+ expect(barText(state)).toMatch(/๐Ÿ”’ security counts unreadable/)
+ })
+
+ it('the total and each severity are at least the listed findings: never CLEAN while a finding is listed', () => {
+ const state = newState({})
+ const lines = scanReader(scan('{"critical":0,"high":0,"medium":0,"low":0,"total":0}', '[{"severity":"low","type":"x"}]'), '', state)
+
+ expect(lines[0]).toMatch(/^REVIEW ยท 1 finding /)
+ expect(lines[1]).toMatch(/low 1/)
+ expect(secMemo(state).findings?.counts.low).toBe(1)
+ })
+
+ it('a summary that under-reports cannot hide a listed critical finding', () => {
+ const state = newState({})
+
+ scanReader(scan('{"critical":0,"high":0,"medium":0,"low":0,"total":1}', '[{"severity":"critical","type":"x"}]'), '', state)
+ expect(secMemo(state).findings?.counts.critical).toBe(1)
+ expect(barText(state)).toMatch(/๐Ÿ”’ 1 high or critical/)
+ })
+
+ it('an unreadable total with nothing listed reads "? findings", never CLEAN', () => {
+ const lines = scanReader(scan('{"critical":0,"high":0,"medium":0,"low":0,"total":-1}'), '', newState({}))
+
+ expect(lines[0]).toMatch(/\? findings \(total unreadable\)/)
+ expect(lines[0]).not.toMatch(/CLEAN/)
+ })
+
+ it('a finite but absurd count (1e300) is capped, never printed as "1e+300"', () => {
+ const state = newState({})
+
+ scanReader(scan('{"critical":1e300,"high":0,"medium":0,"low":0}'), '', state)
+ expect(secMemo(state).findings?.counts.critical).toBe(MAX_COUNT)
+ expect(barText(state)).toMatch(/๐Ÿ”’ 1000000000000 high or critical/)
+ expect(barText(state)).not.toMatch(NOT_A_NUMBER)
+ })
+
+ it('a total of 1e999 is unknown, with the findings it listed as its lower bound', () => {
+ const state = newState({})
+ const lines = scanReader(scan('{"critical":0,"high":0,"medium":0,"low":0,"total":1e999}', '[{"severity":"low","type":"x"}]'), '', state)
+
+ expect(lines[0]).toMatch(/ยท โ‰ฅ1 \? findings \(total unreadable\) ยท/)
+ })
+
+ it('a negative count is unknown and a fractional one is whole; the band still warns, marked as a lower bound', () => {
+ const state = newState({})
+
+ scanReader(scan('{"critical":-5,"high":2.9,"medium":0,"low":0}'), '', state)
+ expect(secMemo(state).findings?.counts).toMatchObject({ high: 2, medium: 0, low: 0 })
+ expect(secMemo(state).findings?.unreadable).toEqual(['critical'])
+ expect(barText(state)).toMatch(/๐Ÿ”’ 2\+ high or critical/)
+ })
+
+ it('a threat confidence of 1e999 or 1e300 is not drawn as a percentage past 100', () => {
+ const state = newState({})
+ const out = mcpReader('aidefence_scan')(`Result:\n{"safe":false,"threats":[{"severity":"high","type":"inj","confidence":1e300},{"severity":"low","type":"b","confidence":1e999}]}`, '', state)
+
+ expect(out.join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(out.join('\n')).toMatch(/inj 100%/)
+ expect(out.join('\n')).toMatch(/\] b ยท /)
+ })
+
+ it('a composition suspect score of 1e999 reads n/a', () => {
+ const out = compositionReader('{"suspects":[{"tool":"t","score":1e999,"reason":"r"}]}', '', newState({}))
+
+ expect(out.join('\n')).not.toMatch(NOT_A_NUMBER)
+ })
+})
+
+describe('the other readers that take numbers from CLI JSON (#3822 sweep)', () => {
+ it('performance metrics: load, system memory and heap are finite or n/a', () => {
+ const state = newState({})
+ const out = metricsReader('{"memory":{"heapUsed":1e999,"heapTotal":1,"rss":1,"systemPercent":1e999},"cpu":{"loadAverage":[1e999,0.5]},"latency":{"avgMs":1e300},"cache":{}}', '', state)
+
+ expect(out.join('\n')).not.toMatch(NOT_A_NUMBER)
+ })
+
+ it('performance_report: a cpu usage of 1e999 reads n/a', () => {
+ const out = reportReader('Result:\n{"current":{"cpu":{"usage":1e999,"cores":4},"memory":{},"latency":{"avg":1e300}},"history":[]}', '', newState({}))
+
+ expect(out.join('\n')).not.toMatch(NOT_A_NUMBER)
+ })
+
+ it('the gepa render and genome lines never print Infinity or 1e+300 (chars, ids, receipts)', () => {
+ expect(labLines('mh-gepa-render', '{"system":"hello","chars":1e999}').join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(labLines('mh-gepa-render', '{"system":"hello","chars":1e300}')[0]).toMatch(/^5 chars/)
+ expect(labLines('mh-gepa-genome', '{"valid":true,"errors":[],"genome":{"meta":{"id":1e300,"parent":1e999,"mutated":-1e300},"components":{}}}').join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(labLines('mh-receipts', '[{"receiptId":1e300,"decision":1e999,"state":"s"}]').join('\n')).not.toMatch(NOT_A_NUMBER)
+ })
+
+ it('a lab result (genome, redblue, audit) never prints Infinity or a cost of $Infinity', () => {
+ expect(labLines('mh-genome', '{"genome":{"fitness":1e999,"generation":3}}').join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(labLines('mh-redblue', '{"summary":{"tests_run":1e999,"failures_found":2,"critical":-1,"cost_usd":1e999}}').join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(labLines('mh-audit', '{"worst":"low","findings":[],"allowedTools":1e999}').join('\n')).not.toMatch(NOT_A_NUMBER)
+ })
+
+ it('hooks route: a confidence of 1e300 is drawn as at most 100%', () => {
+ const read = routeSpec('fix the bug')?.read
+
+ expect(read).toBeDefined()
+
+ const out = read?.('{"primaryAgent":{"type":"coder","confidence":1e300},"alternativeAgents":[{"type":"tester","confidence":-4}],"routing":{"method":"m"}}', '', true) ?? []
+
+ expect(out.join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(out[0]).toMatch(/coder ยท 100%/)
+ expect(out.join('\n')).toMatch(/tester ยท 0%/)
+ })
+
+ it('evolve: ledger, witness and policy counts are whole, non-negative and capped', () => {
+ expect(parseLedger('{"ledger":{"valid":true,"commits":-3}}', 1)?.commits).toBe(0)
+ expect(parseWitness('{"ok":true,"summary":{"pass":1e300,"drift":2.5,"regressed":-1,"missing":0}}', 'macos', 1)).toMatchObject({ pass: MAX_COUNT, drift: 2, regressed: 0, missing: 0 })
+ expect(parsePolicyLedger('{"mode":"m","rules":1e300,"approvals":-2,"receipts":1.5,"ledger":{"valid":true}}', 1)).toMatchObject({ rules: MAX_COUNT, approvals: 0, receipts: 1 })
+ })
+
+ it('CLI memory stats and intelligence counts are whole, non-negative and capped', () => {
+ expect(memoryProbe.parse('{"backend":"b","entries":{"total":-1,"vectors":1e300},"unreadStore":{"rows":2.5}}')).toMatchObject({ vectors: MAX_COUNT, unread: 2 })
+ expect(memoryProbe.parse('{"backend":"b","entries":{"total":-1}}')?.total).toBeUndefined()
+
+ const intel = PROBES.find(probe => probe.id === 'intelligence')?.parse('Result:\n{"sona":{"trajectoriesTotal":1e300,"patternsLearned":-4},"moe":{"routingDecisions":2.5},"ewc":{"consolidations":1e300}}') as Record<string, unknown>
+
+ expect(intel).toMatchObject({ trajectories: MAX_COUNT, moeDecisions: 2, ewcConsolidations: MAX_COUNT })
+ expect(intel.patterns).toBeUndefined()
+ })
+
+ it('memory search scores and vector elements of 1e300 read n/a, never "1e+300"', () => {
+ expect(memLines('mem-search', '{"results":[{"key":"k","namespace":"n","score":1e300,"content":"c"}]}').join('\n')).not.toMatch(NOT_A_NUMBER)
+ expect(memLines('mem-search', '{"results":[{"key":"k","namespace":"n","score":1e300,"content":"c"}]}').join('\n')).toMatch(/n\/a/)
+
+ const vector = memLines('mem-embed', '{"embedding":[1e300,0.5,1e999,-0.25],"model":"m"}').join('\n')
+
+ expect(vector).not.toMatch(NOT_A_NUMBER)
+ expect(vector).toMatch(/^2 dimensions/)
+ })
+
+ it('a research record spending 1e300 dollars reads n/a, not "$1e+300"', () => {
+ const records = parseResearch(JSON.stringify({ version: 1, records: [] }).replace('[]', '[{"question":"q","status":"done","spentUsd":1e300,"capUsd":1e999,"findings":[]}]'))
+
+ expect(records?.[0]).toMatchObject({ spentUsd: null, capUsd: null })
+ })
+
+ it('intelligence success rate and router confidence are clamped ratios', () => {
+ const intel = PROBES.find(probe => probe.id === 'intelligence')?.parse('Result:\n{"sona":{"trajectoriesTotal":2,"successRate":1e300},"modelRouter":{"totalDecisions":3,"avgConfidence":-7}}') as Record<string, unknown>
+
+ expect(intel).toMatchObject({ successRate: 1, routerConfidence: 0 })
+ })
+})