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): wire the recall probe and nn-recall entries, mask credentials, fit the lifecycle table at 80 columns, tighten tests (ADR-456)

ruv60ef7c5a30f5
diff --git a/plugins/ruflo-console/hooks/data/recall.ts b/plugins/ruflo-console/hooks/data/recall.ts
index bc19830e17..6af378fcba 100644
--- a/plugins/ruflo-console/hooks/data/recall.ts
+++ b/plugins/ruflo-console/hooks/data/recall.ts
@@ -13,6 +13,7 @@
* 0.6 * match + 0.4 * pageRank, threshold 0.05, top 5) and is labelled a recomputation. `.claude-flow/neural/patterns.json`
* (the ReasoningBank) is usually over READ_MAX and is not read; `reads.bank` says so.
*/
+import { looksSecret } from './automate'
import { jsonObject, msOf, numberOf, plain, recordOf } from './parse'
import { PROJECT, READ_MAX, readBounded, under, type ReaderFs, type ReadCache } from './files'
@@ -66,11 +67,14 @@ export function jaccard(a: ReadonlySet<string>, b: ReadonlySet<string>): number
return shared / (a.size + b.size - shared)
}
-export type RankedEntry = { id: string; summary: string; category: string; confidence: number; pageRank: number; accessCount: number; words: string[] }
+/** Text drawn from a file or typed in: control characters out, and any word shaped like a credential masked (a task text can hold a pasted key). */
+export const shown = (value: unknown, max: number): string => plain(value, max * 2).split(' ').map(word => (looksSecret(word) ? '••••' : word)).join(' ').slice(0, max)
+
+export type RankedEntry = { id: string; summary: string; category: string; confidence: number | null; pageRank: number; accessCount: number; words: string[] }
export type Ranked = { computedAtMs: number | null; entries: RankedEntry[] }
/** The order the hook sorts its own entries in (intelligence.cjs: 0.6 pageRank + 0.4 confidence). */
-export const compositeRank = (entry: Pick<RankedEntry, 'pageRank' | 'confidence'>): number => ALPHA * entry.pageRank + (1 - ALPHA) * entry.confidence
+export const compositeRank = (entry: Pick<RankedEntry, 'pageRank' | 'confidence'>): number => ALPHA * entry.pageRank + (1 - ALPHA) * (entry.confidence ?? 0.5)
export function parseRanked(text: string | null): Ranked | null {
const value = jsonObject(text)
@@ -84,7 +88,7 @@ export function parseRanked(text: string | null): Ranked | null {
const words = Array.isArray(row.words) ? row.words.filter((word): word is string => typeof word === 'string') : []
- return [{ id: plain(row.id, 80), summary: plain(typeof row.summary === 'string' ? row.summary : typeof row.content === 'string' ? row.content : '', 80), category: plain(typeof row.category === 'string' ? row.category : '', 24), confidence: numberOf(row.confidence) ?? 0.5, pageRank: numberOf(row.pageRank) ?? 0, accessCount: numberOf(row.accessCount) ?? 0, words }]
+ return [{ id: plain(row.id, 80), summary: shown(typeof row.summary === 'string' ? row.summary : typeof row.content === 'string' ? row.content : '', 80), category: plain(typeof row.category === 'string' ? row.category : '', 24), confidence: numberOf(row.confidence) ?? null, pageRank: numberOf(row.pageRank) ?? 0, accessCount: numberOf(row.accessCount) ?? 0, words }]
})
return { computedAtMs: msOf(value.computedAt) ?? null, entries }
@@ -154,7 +158,7 @@ export function parsePrompts(text: string | null): PastPrompt[] {
const row = recordOf(raw)
const atMs = msOf(row?.timestamp)
- return row === null || atMs === undefined || typeof row.task !== 'string' || row.task.trim() === '' ? [] : [{ task: plain(row.task, 160), agent: plain(typeof row.agent === 'string' ? row.agent : '?', 30), ok: row.success === true, atMs }]
+ return row === null || atMs === undefined || typeof row.task !== 'string' || row.task.trim() === '' ? [] : [{ task: shown(row.task, 160), agent: plain(typeof row.agent === 'string' ? row.agent : '?', 30), ok: row.success === true, atMs }]
})
const seen = new Set<string>()
const out: PastPrompt[] = []
@@ -186,7 +190,7 @@ export function parseNeuralStore(text: string | null): NeuralPattern[] | null {
const verdict = recordOf(row.metadata)?.verdict
- return [{ id: plain(row.id, 80), name: plain(typeof row.name === 'string' ? row.name : '', 90), type: plain(typeof row.type === 'string' ? row.type : '?', 24), content: plain(typeof row.content === 'string' ? row.content : '', 600), createdAtMs: msOf(row.createdAt) ?? null, usageCount: numberOf(row.usageCount) ?? 0, verdict: typeof verdict === 'string' ? plain(verdict, 20) : null }]
+ return [{ id: plain(row.id, 80), name: shown(typeof row.name === 'string' ? row.name : '', 90), type: plain(typeof row.type === 'string' ? row.type : '?', 24), content: plain(typeof row.content === 'string' ? row.content : '', 600), createdAtMs: msOf(row.createdAt) ?? null, usageCount: numberOf(row.usageCount) ?? 0, verdict: typeof verdict === 'string' ? plain(verdict, 20) : null }]
})
}
diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.ts
index c498aec248..de307bec11 100644
--- a/plugins/ruflo-console/hooks/data/snapshot.ts
+++ b/plugins/ruflo-console/hooks/data/snapshot.ts
@@ -4,6 +4,7 @@
* draw that as n/a, missing or too large, never as zero.
*/
import { readAnatole, type AnatoleFacts } from './anatole'
+import { readRecall, type RecallFacts } from './recall'
import {
enabledOf,
parseActivity,
@@ -85,6 +86,8 @@ export type Snapshot = {
agentdbMod: AgentdbMod | null
/** Project Anatole's reported files (ADR-453): unauthenticated, bounded, shape-checked. */
anatole?: AnatoleFacts
+ /** What the intelligence hook recalls from and what the neural verbs act on (ADR-456): bounded reads, never a prompt the hook did not keep. */
+ recall?: RecallFacts
/** Every `.claude-flow/<short>-mod/status.json` the per-plugin mods wrote (ADR-446), bounded and shape-checked. */
mods: ModsFacts
changed: number
@@ -139,6 +142,7 @@ export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string,
agentdbMod: parseAgentdbMod(text('agentdbMod')),
mods: await readMods(fs, cache, cwd),
anatole: await readAnatole(fs, cache, cwd),
+ recall: await readRecall(fs, cache, cwd),
changed: disk.changed,
readAtMs: nowMs,
}
diff --git a/plugins/ruflo-console/hooks/neural.ts b/plugins/ruflo-console/hooks/neural.ts
index 7a9a700422..de52b599b6 100644
--- a/plugins/ruflo-console/hooks/neural.ts
+++ b/plugins/ruflo-console/hooks/neural.ts
@@ -7,6 +7,7 @@
*/
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 { labLines } from './mh-lab'
@@ -122,6 +123,7 @@ export function neuralEntries(state: State): AutoEntry[] {
out.push({ id: 'nn-route', group: 'neural', label: 'nn-route <task>: which agent for this task?', make: routeSpec })
out.push({ id: 'nn-explain', group: 'neural', label: 'nn-explain <task>: why the router picks that agent', make: explainSpec })
out.push({ id: 'nn-predict', group: 'neural', label: 'nn-predict <text>: the trained models’ top predictions', make: predictSpec })
+ out.push(...recallEntries(state))
return out
}
diff --git a/plugins/ruflo-console/hooks/views/recall-rows.ts b/plugins/ruflo-console/hooks/views/recall-rows.ts
index 83998e3d70..dab796c7eb 100644
--- a/plugins/ruflo-console/hooks/views/recall-rows.ts
+++ b/plugins/ruflo-console/hooks/views/recall-rows.ts
@@ -1,6 +1,6 @@
import type { RenderElement } from 'claude-code'
-import { compositeRank, explainPrompt, lifecycleOrder, recallOf, wouldPrune, type RecallFacts, type SessionRecall } from '../data/recall'
+import { compositeRank, explainPrompt, lifecycleOrder, recallOf, shown, wouldPrune, type RecallFacts, type SessionRecall } from '../data/recall'
import { ago, button, clip, kv, row, text, THEME, type Ctx } from './common'
/** Rows of a table drawn at most; the rest are counted, not hidden silently. */
@@ -11,7 +11,7 @@ const BAR = 10
let picked: string | null = null
export const pickPrompt = (value: string | null): void => {
- picked = value === null || value.trim() === '' ? null : value.trim().slice(0, 300)
+ picked = value === null || shown(value, 300) === '' ? null : shown(value, 300)
}
export const pickedPrompt = (): string | null => picked
@@ -30,7 +30,7 @@ function sessionRows(ctx: Ctx, facts: RecallFacts, session: SessionRecall): Rend
return session.ids.map((id, index) => {
const entry = byId.get(id)
- return text(ctx, entry === undefined ? ` ${index + 1}. ${clip(id, 40)} (no longer in the ranked file)` : ` ${index + 1}. rank ${n3(compositeRank(entry))} ${entry.summary} [${entry.category || 'n/a'} · conf ${entry.confidence.toFixed(2)} · pr ${n3(entry.pageRank)} · ${entry.accessCount}x]`, entry === undefined ? { dimColor: true } : {})
+ return text(ctx, entry === undefined ? ` ${index + 1}. ${clip(id, 40)} (no longer in the ranked file)` : ` ${index + 1}. rank ${n3(compositeRank(entry))} ${entry.summary} [${entry.category || 'n/a'} · conf ${entry.confidence === null ? 'n/a' : entry.confidence.toFixed(2)} · pr ${n3(entry.pageRank)} · ${entry.accessCount}x]`, entry === undefined ? { dimColor: true } : {})
})
}
@@ -102,14 +102,19 @@ export function lifecycleRows(ctx: Ctx): RenderElement[] {
const idle = wouldPrune(patterns, 1).length
rows.push(text(ctx, ' columns: only what models.json records (age, uses, verdict at creation); rank and last-used time are not recorded there', { dimColor: true }))
- rows.push(text(ctx, ` ${'pattern'.padEnd(26)} ${'type'.padEnd(14)} ${'age'.padEnd(8)} ${'uses'.padEnd(5)} ${'verdict'.padEnd(8)} name`, { dimColor: true }))
+ // Column widths follow the width: the wide table (id 26 + type 14 + age 8 + uses 5 + verdict 8, then the name) needs 86 columns plus the two buttons; narrower, the columns shrink and the name goes.
+ const wide = ctx.columns >= 120
+ const [wId, wType, wAge, wUses, wVerdict] = wide ? [26, 14, 8, 5, 8] : [16, 12, 6, 4, 7]
+ const wName = wide ? Math.max(10, ctx.columns - 86 - 20) : 0
+
+ rows.push(text(ctx, ` ${'pattern'.padEnd(wId)} ${'type'.padEnd(wType)} ${'age'.padEnd(wAge)} ${'uses'.padEnd(wUses)} ${'verdict'.padEnd(wVerdict)}${wide ? ' name' : ''}`, { dimColor: true }))
sorted.slice(0, SHOWN).forEach((pattern, index) => {
rows.push(
row(
ctx,
[
- ctx.kit.Text({ children: ` ${clip(pattern.id, 26).padEnd(26)} ${clip(pattern.type, 14).padEnd(14)} ${(pattern.createdAtMs === null ? 'n/a' : ago(pattern.createdAtMs, nowMs).replace(' ago', '')).padEnd(8)} ${String(pattern.usageCount).padEnd(5)} ${(pattern.verdict ?? 'n/a').padEnd(8)} ${clip(pattern.name, Math.max(10, ctx.columns - 96))} ` }),
+ ctx.kit.Text({ children: ` ${clip(pattern.id, wId).padEnd(wId)} ${clip(pattern.type, wType).padEnd(wType)} ${clip(pattern.createdAtMs === null ? 'n/a' : ago(pattern.createdAtMs, nowMs).replace(' ago', ''), wAge).padEnd(wAge)} ${String(pattern.usageCount).padEnd(wUses)} ${clip(pattern.verdict ?? 'n/a', wVerdict).padEnd(wVerdict)}${wide ? ` ${clip(pattern.name, wName)}` : ''} ` }),
ctx.kit.Button({ key: `recall-promote-${index}`, label: 'â–² promote', plain: true, onPress: () => void ctx.act.run('nn-recall-promote', pattern.id) }),
ctx.kit.Button({ key: `recall-prune-${index}`, label: ' ✂ prune', plain: true, onPress: () => void ctx.act.run('nn-recall-prune', pattern.id) }),
],
diff --git a/plugins/ruflo-console/tests/recall.spec.ts b/plugins/ruflo-console/tests/recall.spec.ts
index f3aac59a54..d77547dfa5 100644
--- a/plugins/ruflo-console/tests/recall.spec.ts
+++ b/plugins/ruflo-console/tests/recall.spec.ts
@@ -8,6 +8,8 @@ import { describe, expect, it } from 'vitest'
import { compositeRank, explainPrompt, jaccard, lifecycleOrder, parseNeuralStore, parsePrompts, parseRanked, parseSessionRecall, readRecall, tokenize, trigrams, wouldPrune, type RecallFacts } from '../hooks/data/recall'
import { promoteSpec, pruneSpec, pruneUnusedSpec, recallEntries } from '../hooks/recall'
+import { readSnapshot } from '../hooks/data/snapshot'
+import { paletteEntries } from '../hooks/palette'
import { newState } from '../hooks/state'
import type { Ctx } from '../hooks/views/common'
import { lifecycleRows, pickPrompt, recallRows } from '../hooks/views/recall-rows'
@@ -255,3 +257,94 @@ describe('the reader', () => {
expect(got).toMatchObject({ ranked: null, sessions: [], prompts: [], neural: null, reads: { ranked: 'missing', bank: 'missing' } })
})
})
+
+describe('wired into the console', () => {
+ const fsOf = (files: Record<string, string>) => ({
+ read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')),
+ stat: async (path: string) => (files[path] !== undefined ? { mtimeMs: 1, size: files[path]?.length ?? 0, kind: 'file' } : Promise.reject(new Error('ENOENT'))),
+ list: async () => Promise.reject(new Error('ENOENT')),
+ })
+
+ it('puts the recall facts in the snapshot and its ids in the palette, every mutation asking first', async () => {
+ const state = newState({ boot: false })
+
+ state.snapshot = await readSnapshot(fsOf({ '/w/.claude-flow/data/ranked-context.json': RANKED, '/w/.claude-flow/neural/models.json': MODELS }), new Map(), '/w', '/h', {}, 0)
+
+ expect(state.snapshot.recall?.ranked?.entries).toHaveLength(3)
+ expect(state.snapshot.recall?.neural).toHaveLength(2)
+
+ const entries = paletteEntries(state, 0)
+ const byId = (id: string) => entries.find(candidate => candidate.id === id)
+
+ for (const id of ['nn-recall-prune', 'nn-recall-promote', 'nn-recall-prune-unused']) expect(byId(id), id).toBeDefined()
+
+ const prune = byId('nn-recall-prune')?.run
+ const bulk = byId('nn-recall-prune-unused')?.run
+ const promote = byId('nn-recall-promote')?.run
+
+ expect(prune?.kind === 'text' ? prune.make('pattern-1-a')?.isReadOnly : 'x').not.toBe(true)
+ expect(promote?.kind === 'text' ? promote.make('pattern-2-b')?.isReadOnly : 'x').not.toBe(true)
+ expect(bulk?.kind === 'spec' ? bulk.spec?.isReadOnly : 'x').not.toBe(true)
+ })
+
+ it('says it is not wired only when the probe is absent', async () => {
+ const state = newState({ boot: false })
+
+ state.snapshot = await readSnapshot(fsOf({}), new Map(), '/w', '/h', {}, 0)
+ expect(state.snapshot.recall?.reads).toMatchObject({ ranked: 'missing', neural: 'missing' })
+ })
+})
+
+describe('what the scoring and the table promise', () => {
+ const many = ranked(Array.from({ length: 9 }, (_, index) => entry(`m${index}`, 'authentication token refresh login service', 0.02 + index / 1000)))
+
+ it('surfaces at most five, as the hook does', () => {
+ expect(explainPrompt('authentication token refresh login service', parseRanked(many)?.entries ?? [])).toHaveLength(5)
+ })
+
+ it('drops an entry that scores under 0.05 and keeps one that reaches it', () => {
+ const low = parseRanked(ranked([{ ...entry('lo', 'zzz', 0.0499 / 0.4), words: [] }, { ...entry('hi', 'zzz', 0.05 / 0.4), words: [] }]))?.entries ?? []
+
+ expect(explainPrompt('authentication', [{ ...low[0], pageRank: 0.1249 } as never, { ...low[1], pageRank: 0.125 } as never]).map(item => item.entry.id)).toEqual(['hi'])
+ })
+
+ it('prunes strictly below the threshold, never at it', () => {
+ const rows = parseNeuralStore(MODELS) ?? []
+
+ expect(wouldPrune(rows, 4)).toEqual(['pattern-1-a'])
+ expect(wouldPrune(rows, 5)).toEqual(['pattern-1-a', 'pattern-2-b'])
+ })
+
+ it('masks a credential-shaped word in a task or summary and never draws a missing confidence as a number', () => {
+ const key = `sk-${'a1'.repeat(20)}`
+ const [past] = parsePrompts(JSON.stringify({ outcomes: [{ task: `deploy with ${key} now`, agent: 'coder', success: true, timestamp: '2026-09-27T10:00:00Z' }] }))
+ const [bare] = parseRanked(JSON.stringify({ entries: [{ id: 'x', summary: `use ${key}`, pageRank: 0.1, words: [] }] }))?.entries ?? []
+
+ expect(past?.task).toBe('deploy with •••• now')
+ expect(bare?.summary).toBe('use ••••')
+ expect(bare?.confidence).toBeNull()
+ pickPrompt(`explain ${key}`)
+
+ const facts: RecallFacts = { ranked: { computedAtMs: 1, entries: bare === undefined ? [] : [bare] }, sessions: [{ file: 's', startedAtMs: 1, updatedAtMs: 1, ids: ['x'] }], prompts: [], neural: null, reads: { ranked: 'ok', sessions: 'ok', prompts: 'ok', neural: 'missing', bank: 'missing' } }
+ const text = words(recallRows(ctxOf(facts)))
+
+ pickPrompt(null)
+ expect(text).toMatch(/conf n\/a/)
+ expect(text).not.toContain(key)
+ })
+
+ it('fits the lifecycle table in 80, 120 and 160 columns, and shows only SHOWN rows with the rest counted', () => {
+ const patterns = Object.fromEntries(Array.from({ length: 15 }, (_, index) => [`pattern-1791244689589-${index}-abcdefg`, { id: `pattern-1791244689589-${index}-abcdefg`, name: 'fix: wire recordTrajectory into the hooks tools handler for everything', type: 'history-commit', content: 'c', metadata: { verdict: 'success' }, createdAt: '2026-09-27T17:34:15.801Z', usageCount: index }]))
+ const facts: RecallFacts = { ranked: null, sessions: [], prompts: [], neural: parseNeuralStore(JSON.stringify({ patterns })), reads: { ranked: 'missing', sessions: 'ok', prompts: 'missing', neural: 'ok', bank: 'ok' } }
+
+ for (const columns of [80, 120, 160]) {
+ const ctx = { ...ctxOf(facts), columns } as Ctx
+ const rows = lifecycleRows(ctx)
+ const lines = rows.map(rowEl => flat(rowEl).filter(el => el.kind === 'Text' || el.kind === 'Button').map(el => String(el.props.children ?? el.props.label ?? '')).join(''))
+
+ for (const line of lines) expect(line.length, `${columns}: ${line}`).toBeLessThanOrEqual(columns)
+ expect(lines.some(line => /\+ 3 more in the file/.test(line))).toBe(true)
+ expect(lines.filter(line => /pattern-1791/.test(line))).toHaveLength(12)
+ }
+ })
+})