🌊 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
feat(ruflo-console): Memory Lab — browse, search, store, delete, AgentDB and embeddings as buttons
ruv1cdd04d39e1b
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.tsindex 5fb683024c..4668598bfc 100644--- a/plugins/ruflo-console/hooks/actions.ts+++ b/plugins/ruflo-console/hooks/actions.ts@@ -23,6 +23,8 @@ export type ActionSpec = {note?: string/** How long the CLI may take; 90 s when unset. */timeoutMs?: number+ /** A lab entry's own reading of what it printed; the MetaHarness reader when unset. */+ lines?: (stdout: string, stderr: string) => string[]}export const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as constdiff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.tsindex a52ccfc673..a1cf9727b2 100644--- a/plugins/ruflo-console/hooks/bindings.ts+++ b/plugins/ruflo-console/hooks/bindings.ts@@ -7,6 +7,7 @@ import { EVENT_KINDS } from './data/events'import { HARNESSES, harnessSpec, isLive, newSession, send, whyNotRun } from './harness'import { plain } from './data/parse'import type { Host } from './host'+import { memoryActions } from './memory-lab'import { filterPalette, paletteEntries } from './palette'import type { Runner } from './runner'import { skillActions } from './skills'@@ -250,6 +251,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps},// ▸ edit hands the skill to the AI terminal, as x.ruv.io's ▸ open does: typed, not run.skills: skillActions(state, host, runner, text => actions.term.load('claude', text)),+ memory: memoryActions(state, runner, host.invalidate),}return actionsdiff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.tsindex cede4dd459..9c62a5745a 100644--- a/plugins/ruflo-console/hooks/data/cli.ts+++ b/plugins/ruflo-console/hooks/data/cli.ts@@ -54,7 +54,8 @@ export const versionProbe: Probe<string> = {parse: stdout => /v?(\d+\.\d+\.\d+[\w.-]*)/.exec(stdout)?.[1] ?? null,}-export type MemoryStats = { backend: string; total?: number; vectors?: number; storage?: string; oldestMs?: number; newestMs?: number }+/** `unread`: rows in the second store (.swarm/agentdb-memory.db, the MCP path's) that the CLI's counts leave out. */+export type MemoryStats = { backend: string; total?: number; vectors?: number; storage?: string; oldestMs?: number; newestMs?: number; unread?: number }export const memoryProbe: Probe<MemoryStats> = {id: 'memory',@@ -76,8 +77,10 @@ export const memoryProbe: Probe<MemoryStats> = {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)if (total !== undefined) stats.total = total+ if (unread !== undefined) stats.unread = unreadif (vectors !== undefined) stats.vectors = vectorsif (storage !== undefined) stats.storage = storageif (oldestMs !== undefined) stats.oldestMs = oldestMs@@ -87,7 +90,10 @@ export const memoryProbe: Probe<MemoryStats> = {},}-export type Namespaces = { sampled: number; byName: { name: string; count: number }[] }+/** One listed entry, as `memory list --format json` answers it: what the Memory Lab browses and opens. */+export type MemoryEntry = { key: string; namespace: string; size?: number; atMs?: number; hasVector: boolean }++export type Namespaces = { sampled: number; byName: { name: string; count: number }[]; entries?: MemoryEntry[] }/** Namespaces of the newest 500 entries: a sample, and the view says so. */export const namespacesProbe: Probe<Namespaces> = {@@ -104,14 +110,22 @@ export const namespacesProbe: Probe<Namespaces> = {}const counts = new Map<string, number>()+ const entries: MemoryEntry[] = []for (const entry of value.slice(0, 500)) {- const name = stringOf(recordOf(entry)?.namespace, 40) ?? '(none)'+ const record = recordOf(entry)+ const name = stringOf(record?.namespace, 40) ?? '(none)'+ const key = stringOf(record?.key, 128)+ const size = numberOf(record?.size)+ const atMs = msOf(record?.updatedAt ?? record?.createdAt)counts.set(name, (counts.get(name) ?? 0) + 1)+ if (key !== undefined) entries.push({ key, namespace: name, hasVector: record?.hasEmbedding === true, ...(size !== undefined && { size }), ...(atMs !== undefined && { atMs }) })}- return { sampled: Math.min(500, value.length), byName: [...counts].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count).slice(0, 12) }+ entries.sort((a, b) => (b.atMs ?? 0) - (a.atMs ?? 0))++ return { sampled: Math.min(500, value.length), byName: [...counts].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count).slice(0, 12), entries }},}diff --git a/plugins/ruflo-console/hooks/memory-lab.ts b/plugins/ruflo-console/hooks/memory-lab.tsnew file mode 100644index 0000000000..d6aa256f50--- /dev/null+++ b/plugins/ruflo-console/hooks/memory-lab.ts@@ -0,0 +1,292 @@+/**+ * The Memory Lab: ruflo's memory, AgentDB and embeddings surface as fixed argv, each checked against the CLI's own+ * source (commands/memory.ts, mcp-tools/{memory,agentdb,embeddings}-tools.ts) and its `--help`. A read ($0, local)+ * runs at once and shows what it printed in the lab's result panel; a write, a delete, or a call that may download the+ * embedding model asks first, and its confirm row says so. Free text (a query, a key, a value) is validated here and+ * always travels as one argv element or one JSON string, never through a shell. Pure: entries, validators and specs,+ * no `$`; the actions at the bottom hand specs to the runner.+ */+import type { ActionSpec } from './actions'+import type { MemoryEntry } from './data/cli'+import { plain } from './data/parse'+import { memLines } from './memory-lines'+import { textArg } from './ops'+import type { Runner } from './runner'+import type { State } from './state'++/** `read`: $0, local, changes nothing. `writes`: $0, writes the store or a file. `deletes`: removes for good. `net`: may download the embedding model. */+export type MemCost = 'read' | 'writes' | 'deletes' | 'net'+export type MemGroup = 'inspect' | 'agentdb' | 'embeddings' | 'maintain'+/**+ * What an entry takes, as the headless text after its id (`/ruflo run mem-store notes alpha the value`):+ * `text` free text · `node` one id · `pair` two texts split by | · `edge` source relation target ·+ * `entry` namespace key · `kv` namespace key value.+ */+export type MemTakes = 'text' | 'node' | 'pair' | 'edge' | 'entry' | 'kv'++/** What the parsed input carries: the fields an entry's argv is built from. */+export type MemInput = { text?: string; other?: string; key?: string; namespace?: string; value?: string; relation?: string }++export type MemEntry = {+ id: string+ group: MemGroup+ name: string+ about: string+ label: string+ cost: MemCost+ takes?: MemTakes+ /** The argv after the CLI prefix, from the parsed input (and the picked namespace filter); null when it cannot run. */+ args: (input: MemInput, state: State) => readonly string[] | null+ note?: string+ timeoutMs?: number+}++export const MEM_GROUPS: readonly { id: MemGroup; title: string; right: string }[] = [+ { id: 'inspect', title: 'Lab · memory', right: 'stats, health, search, browse · $0 reads run at once' },+ { id: 'agentdb', title: 'Lab · AgentDB', right: 'patterns, tiers, causal graph · reads at once, writes ask' },+ { id: 'embeddings', title: 'Lab · embeddings', right: 'vectors and RaBitQ · may fetch the model once: asks' },+ { id: 'maintain', title: 'Lab · maintain', right: 'import, export, migrate, cleanup · each asks first' },+]++const NAMESPACE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/+const KEY = /^[A-Za-z0-9_][A-Za-z0-9._:/@-]{0,127}$/+const RELATION = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/++/** A namespace as one argv element: letters, digits, . _ -, at most 64, not starting with - or .; else null. */+export const namespaceOf = (value: string | undefined): string | null => (value !== undefined && NAMESPACE.test(value.trim()) ? value.trim() : null)+/** A memory key: letters, digits and . _ : / @ -, at most 128, no spaces, not starting with - (keys like api/auth pass). */+export const keyOf = (value: string | undefined): string | null => (value !== undefined && KEY.test(value.trim()) ? value.trim() : null)++/** Free text as one argv element, refused (not clipped) when longer than `max`: a stored value is never cut short. */+const bounded = (value: string, max: number): string | null => (value.trim().length > max ? null : textArg(value, max))++/** The text after an entry's id, read into the fields it takes; null when any part would not survive the CLI. */+export function parseInput(takes: MemTakes, raw: string): MemInput | null {+ const words = raw.trim().split(/\s+/).filter(Boolean)++ switch (takes) {+ case 'text': {+ const text = bounded(raw, 300)++ return text === null ? null : { text }+ }+ case 'node': {+ const key = words.length === 1 ? keyOf(words[0]) : null++ return key === null ? null : { key }+ }+ case 'pair': {+ const [a = '', b = '', ...extra] = raw.split('|')+ const text = bounded(a, 300)+ const other = bounded(b, 300)++ return text === null || other === null || extra.length > 0 ? null : { text, other }+ }+ case 'edge': {+ const [source, relation = '', target, ...extra] = words+ const key = keyOf(source)+ const other = keyOf(target)++ return key === null || other === null || !RELATION.test(relation) || extra.length > 0 ? null : { key, relation, other }+ }+ case 'entry':+ case 'kv': {+ const [space, name] = words+ const namespace = namespaceOf(space)+ const key = keyOf(name)+ const value = takes === 'kv' ? bounded(raw.trim().slice((space?.length ?? 0) + 1).trim().slice(name?.length ?? 0), 2000) : undefined++ if (namespace === null || key === null || (takes === 'entry' && words.length !== 2) || value === null) return null++ return { namespace, key, ...(value !== undefined && { value }) }+ }+ }+}++/** What each takes looks like, for the footer when the text does not parse. */+export const TAKES_RULE: Record<MemTakes, string> = {+ text: 'text: 1-300 printable characters, not starting with -',+ node: 'one node id: letters, digits, . _ : / @ -, no spaces',+ pair: 'two texts split by |, e.g. jwt refresh | token rotation',+ edge: '<source> <relation> <target>, e.g. auth-bug causes login-fail',+ entry: '<namespace> <key>, e.g. auth jwt/refresh',+ kv: '<namespace> <key> <value…> (value up to 2000 characters), e.g. notes alpha the quick brown fox',+}++const JSON_OUT = ['--format', 'json'] as const++/** An MCP tool call as one fixed argv; the params are typed as the tool's schema declares them, one JSON element. */+export const tool = (name: string, params: Record<string, string | number | boolean> = {}) => ['mcp', 'exec', '-t', name, '-p', JSON.stringify(params)] as const++/** The namespace the browse list is narrowed to, as a `--namespace` pair for CLI reads. */+const inFilter = (state: State): string[] => {+ const space = namespaceOf(state.memoryLab.filter ?? undefined)++ return space === null ? [] : ['--namespace', space]+}++const MODEL_NOTE = '$0, but may download the all-MiniLM-L6-v2 model from Hugging Face the first time (network), then cached'+const EXPORT_PATH = '.claude-flow/memory-export.json'++export const MEM_LAB: readonly MemEntry[] = [+ // Memory: what is stored, how healthy it is, and search over it.+ { id: 'mem-stats', group: 'inspect', name: 'STATS', about: 'entries, storage, oldest and newest, the unread store', label: 'memory stats: entries, storage, oldest and newest', cost: 'read', args: () => ['memory', 'stats', ...JSON_OUT] },+ { id: 'mem-detailed', group: 'inspect', name: 'DETAILED', about: 'entries per namespace, backend, index', label: 'memory detailed stats: per namespace and index', cost: 'read', args: () => tool('memory_detailed-stats') },+ { id: 'mem-bridge', group: 'inspect', name: 'BRIDGE', about: 'Claude Code memory files beside AgentDB entries', label: 'memory bridge status: Claude memories beside AgentDB', cost: 'read', args: () => tool('memory_bridge_status') },+ { id: 'mem-health', group: 'inspect', name: 'HEALTH', about: 'AgentDB available, each controller on or off', label: 'AgentDB health: each controller on or off', cost: 'read', args: () => tool('agentdb_health') },+ { id: 'mem-controllers', group: 'inspect', name: 'CONTROLLERS', about: 'the controller registry and their levels', label: 'AgentDB controllers: the registry and levels', cost: 'read', args: () => tool('agentdb_controllers') },+ { id: 'mem-list', group: 'inspect', name: 'LIST', about: 'the newest 50 entries (in the picked namespace)', label: 'memory list: the newest 50 entries', cost: 'read', args: (_, state) => ['memory', 'list', ...inFilter(state), '--limit', '50', ...JSON_OUT] },+ { id: 'mem-search', group: 'inspect', name: 'SEARCH', about: 'semantic search of the memory store', label: 'memory search <query>: semantic search', cost: 'read', takes: 'text', args: (input, state) => (input.text === undefined ? null : ['memory', 'search', '--query', input.text, ...inFilter(state), '--limit', '10', ...JSON_OUT]) },+ { id: 'mem-unified', group: 'inspect', name: 'UNIFIED', about: 'one search over Claude memories, AgentDB and patterns', label: 'unified search <query>: Claude + AgentDB + patterns', cost: 'read', takes: 'text', args: input => (input.text === undefined ? null : tool('memory_search_unified', { query: input.text, limit: 10 })) },+ { id: 'mem-retrieve', group: 'inspect', name: 'RETRIEVE', about: 'one entry’s whole value: <namespace> <key>', label: 'retrieve <namespace> <key>: one entry’s value', cost: 'read', takes: 'entry', args: input => (input.key === undefined || input.namespace === undefined ? null : ['memory', 'retrieve', '--key', input.key, '--namespace', input.namespace, ...JSON_OUT]) },+ { id: 'mem-compress', group: 'inspect', name: 'COMPRESS', about: 'sizes before and after; this build rewrites nothing', label: 'memory compress: the size report (rewrites nothing)', cost: 'read', args: () => tool('memory_compress') },+ { id: 'mem-cleanup-plan', group: 'inspect', name: 'CLEANUP PLAN', about: 'how many TTL-expired entries a cleanup would delete', label: 'cleanup dry run: expired entries a cleanup would delete', cost: 'read', args: () => tool('memory_cleanup', { dryRun: true }) },++ // AgentDB: the pattern bank, the tiered memory and the causal graph.+ { id: 'mem-pattern-search', group: 'agentdb', name: 'PATTERN SEARCH', about: 'the ReasoningBank patterns nearest the text', label: 'pattern search <text>: nearest ReasoningBank patterns', cost: 'read', takes: 'text', args: input => (input.text === undefined ? null : tool('agentdb_pattern-search', { query: input.text, topK: 5 })) },+ { id: 'mem-recall', group: 'agentdb', name: 'RECALL', about: 'hierarchical recall across working/episodic/semantic', label: 'hierarchical recall <text>: across the three tiers', cost: 'read', takes: 'text', args: input => (input.text === undefined ? null : tool('agentdb_hierarchical-recall', { query: input.text, topK: 5 })) },+ { id: 'mem-graph', group: 'agentdb', name: 'GRAPH', about: 'the causal graph two hops out from a node id', label: 'graph query <node>: k-hop, depth 2', cost: 'read', takes: 'node', args: input => (input.key === undefined ? null : tool('agentdb_graph-query', { nodeId: input.key, mode: 'k-hop', depth: 2, topK: 10 })) },+ { id: 'mem-pattern-store', group: 'agentdb', name: 'PATTERN STORE', about: 'save the text as a ReasoningBank pattern', label: 'pattern store <text>: save a ReasoningBank pattern', cost: 'writes', takes: 'text', args: input => (input.text === undefined ? null : tool('agentdb_pattern-store', { pattern: input.text, type: 'console' })), note: '$0, local: writes one pattern to AgentDB' },+ { id: 'mem-hstore', group: 'agentdb', name: 'TIER STORE', about: 'the store fields into the working tier', label: 'hierarchical store <namespace> <key> <value>: working tier', cost: 'writes', takes: 'kv', args: input => (input.key === undefined || input.value === undefined ? null : tool('agentdb_hierarchical-store', { key: input.key, value: input.value, tier: 'working' })), note: '$0, local: writes one entry to the working tier (the namespace is not used by this tool)' },+ { id: 'mem-edge', group: 'agentdb', name: 'CAUSAL EDGE', about: 'link two nodes: <source> <relation> <target>', label: 'causal edge <source> <relation> <target>: link two nodes', cost: 'writes', takes: 'edge', args: input => (input.key === undefined || input.other === undefined || input.relation === undefined ? null : tool('agentdb_causal-edge', { sourceId: input.key, targetId: input.other, relation: input.relation })), note: '$0, local: writes one edge to the AgentDB causal graph' },+ { id: 'mem-consolidate', group: 'agentdb', name: 'CONSOLIDATE', about: 'merge and promote memories across tiers', label: 'AgentDB consolidate: merge and promote across tiers', cost: 'writes', args: () => tool('agentdb_consolidate'), note: '$0, local: may merge, promote or prune stored memories (answers unsupported when the controller is a stub)' },++ // Embeddings: generate, compare, search and the 1-bit RaBitQ index.+ { id: 'mem-embed-status', group: 'embeddings', name: 'STATUS', about: 'model, dimensions, cache; embeds a probe text', label: 'embeddings status: model, dimensions, cache', cost: 'net', args: () => tool('embeddings_status'), note: MODEL_NOTE },+ { id: 'mem-embed', group: 'embeddings', name: 'GENERATE', about: 'the vector for the text: dimensions and head', label: 'embed <text>: generate its vector', cost: 'net', takes: 'text', args: input => (input.text === undefined ? null : tool('embeddings_generate', { text: input.text })), note: MODEL_NOTE },+ { id: 'mem-compare', group: 'embeddings', name: 'COMPARE', about: 'cosine similarity of two texts: a | b', label: 'compare <a> | <b>: cosine similarity', cost: 'net', takes: 'pair', args: input => (input.text === undefined || input.other === undefined ? null : tool('embeddings_compare', { text1: input.text, text2: input.other, metric: 'cosine' })), note: MODEL_NOTE },+ { id: 'mem-esearch', group: 'embeddings', name: 'VECTOR SEARCH', about: 'nearest stored vectors to the text', label: 'vector search <text>: nearest stored vectors', cost: 'net', takes: 'text', args: input => (input.text === undefined ? null : tool('embeddings_search', { query: input.text, topK: 5 })), note: MODEL_NOTE },+ { id: 'mem-rabitq-status', group: 'embeddings', name: 'RABITQ STATUS', about: 'is the 1-bit index built, its size and ratio', label: 'RaBitQ status: built, vectors, compression', cost: 'read', args: () => tool('embeddings_rabitq_status') },+ { id: 'mem-rabitq-search', group: 'embeddings', name: 'RABITQ SEARCH', about: 'the 1-bit index’s nearest entries to the text', label: 'RaBitQ search <text>: nearest in the 1-bit index', cost: 'net', takes: 'text', args: input => (input.text === undefined ? null : tool('embeddings_rabitq_search', { query: input.text, k: 10 })), note: MODEL_NOTE },+ { id: 'mem-rabitq-build', group: 'embeddings', name: 'RABITQ BUILD', about: 'quantize the stored vectors into the 1-bit index', label: 'RaBitQ build: quantize the stored vectors', cost: 'writes', args: () => tool('embeddings_rabitq_build'), note: '$0, local: writes .swarm/rabitq.meta.json; the index itself stays in memory' },+ { id: 'mem-embed-init', group: 'embeddings', name: 'INIT', about: 'write the embeddings config (MiniLM, hyperbolic)', label: 'embeddings init: write .claude-flow/embeddings.json', cost: 'writes', args: () => tool('embeddings_init'), note: '$0, local: writes .claude-flow/embeddings.json and .claude-flow/models/; refuses if a config exists' },++ // Maintain: what moves memories in, out, or away.+ { id: 'mem-store', group: 'maintain', name: 'STORE', about: 'the store fields: <namespace> <key> <value>', label: 'store <namespace> <key> <value>: save one entry', cost: 'writes', takes: 'kv', args: input => (input.key === undefined || input.namespace === undefined || input.value === undefined ? null : ['memory', 'store', '--key', input.key, '--value', input.value, '--namespace', input.namespace]), note: '$0, local: writes (or replaces) one entry and its embedding; r re-lists the browse list' },+ { id: 'mem-import-claude', group: 'maintain', name: 'IMPORT CLAUDE', about: 'this project’s Claude Code memories into AgentDB', label: 'import Claude memories: this project into AgentDB', cost: 'writes', args: () => tool('memory_import_claude'), note: '$0, local: reads this project’s ~/.claude/projects/<hash>/memory/*.md, writes one entry per section to namespace claude-memories', timeoutMs: 180_000 },+ { id: 'mem-import-all', group: 'maintain', name: 'IMPORT ALL', about: 'every project’s Claude Code memories into AgentDB', label: 'import Claude memories from every project', cost: 'writes', args: () => tool('memory_import_claude', { allProjects: true }), note: '$0, local: reads every ~/.claude/projects/*/memory/*.md, writes one entry per section to namespace claude-memories', timeoutMs: 300_000 },+ { id: 'mem-export', group: 'maintain', name: 'EXPORT', about: `every entry as JSON to ${EXPORT_PATH}`, label: `memory export: every entry to ${EXPORT_PATH}`, cost: 'writes', args: (_, state) => ['memory', 'export', '--output', EXPORT_PATH, ...inFilter(state)], note: `$0, local: writes (overwrites) ${EXPORT_PATH}` },+ { id: 'mem-migrate', group: 'maintain', name: 'MIGRATE', about: 'the legacy JSON store into the sql.js store, once', label: 'memory migrate: the legacy JSON store into sql.js', cost: 'writes', args: () => tool('memory_migrate'), note: '$0, local: imports the legacy JSON store once; a marker file stops a second run' },+ { id: 'mem-delete', group: 'maintain', name: 'DELETE', about: 'one entry for good: <namespace> <key>', label: 'delete <namespace> <key>: remove one entry for good', cost: 'deletes', takes: 'entry', args: input => (input.key === undefined || input.namespace === undefined ? null : ['memory', 'delete', '--key', input.key, '--namespace', input.namespace, '--force']), note: 'DELETES FOR GOOD: the entry and its AgentDB mirror; there is no undo' },+ { id: 'mem-cleanup', group: 'maintain', name: 'CLEANUP', about: 'delete every entry whose TTL has expired', label: 'memory cleanup: delete every TTL-expired entry', cost: 'deletes', args: () => tool('memory_cleanup', { dryRun: false }), note: 'DELETES FOR GOOD: every entry whose TTL has expired; run CLEANUP PLAN first to see how many' },+]++/** The ids that take text, for the palette's keyword list: `/ruflo run mem-search jwt refresh`. */+export const MEM_KEYWORDS: readonly string[] = MEM_LAB.flatMap(entry => (entry.takes === undefined ? [] : [entry.id]))++export const memEntry = (id: string): MemEntry | undefined => MEM_LAB.find(entry => entry.id === id)++/** The spec for an entry and its input: reads run at once; the rest ask, their note on the confirm row. */+export function memSpec(entry: MemEntry, input: MemInput, state: State): ActionSpec | null {+ const args = entry.args(input, state)++ if (args === null) return null++ const what = input.namespace !== undefined && input.key !== undefined ? ` (${input.namespace}/${input.key})` : input.text !== undefined ? ` "${plain(input.text, 40)}"` : ''++ return {+ label: `${entry.label.split(':')[0] ?? entry.label}${what}`,+ args,+ expect: entry.cost === 'read' ? 'its output in the lab' : `its result in the lab${entry.note !== undefined ? `; ${entry.note}` : ''}`,+ lab: entry.id,+ lines: (stdout, stderr) => memLines(entry.id, stdout, stderr),+ ...(entry.cost === 'read' && { isReadOnly: true }),+ ...(entry.note !== undefined && { note: entry.note }),+ ...(entry.timeoutMs !== undefined && { timeoutMs: entry.timeoutMs }),+ }+}++/** The spec from headless text (the palette, `/ruflo run`): null when the text does not parse. */+export function memSpecOf(entry: MemEntry, text: string, state: State): ActionSpec | null {+ const input = entry.takes === undefined ? {} : parseInput(entry.takes, text)++ return input === null ? null : memSpec(entry, input, state)+}++export const memWhy = (entry: MemEntry): string => (entry.takes === undefined ? 'cannot run now' : `type ${entry.id} ${TAKES_RULE[entry.takes]}`)++/** The lab's fields and picks: the search box, the store fields, the lab's text field, and the browse filter. */+export type MemoryLabState = {+ query: string+ scope: 'memory' | 'unified'+ key: string+ value: string+ namespace: string+ text: string+ filter: string | null+ page: number+}++export const emptyMemoryLab = (): MemoryLabState => ({ query: '', scope: 'memory', key: '', value: '', namespace: 'default', text: '', filter: null, page: 0 })++export type MemField = 'query' | 'key' | 'value' | 'namespace' | 'text'++/** The headless text a button builds from the fields, so the view and `/ruflo run` take one path. */+export function textOfFields(entry: MemEntry, lab: MemoryLabState): string {+ switch (entry.takes) {+ case 'entry':+ return `${lab.namespace} ${lab.key}`+ case 'kv':+ return `${lab.namespace} ${lab.key} ${lab.value}`+ case undefined:+ return ''+ default:+ return entry.id === 'mem-search' || entry.id === 'mem-unified' ? lab.query : lab.text+ }+}++export type MemoryActions = {+ draft: (field: MemField, text: string) => void+ /** Enter in the search box: memory search or the unified search, as the scope toggle says. */+ search: (text: string) => void+ scope: () => void+ /** A lab button: the entry with the fields as its input. */+ run: (id: string) => void+ open: (entry: MemoryEntry) => void+ remove: (entry: MemoryEntry) => void+ filter: (namespace: string | null) => void+ page: (by: number) => void+}++export function memoryActions(state: State, runner: Runner, invalidate: () => void): MemoryActions {+ const lab = state.memoryLab+ const go = (id: string, text: string) => {+ const entry = memEntry(id)++ if (entry === undefined) return++ // A fresh result reads from its top.+ state.select.item = 0+ runner.ask(memSpecOf(entry, text, state), memWhy(entry))+ }++ return {+ draft: (field, text) => {+ lab[field] = text+ },+ search: text => {+ lab.query = text+ go(lab.scope === 'unified' ? 'mem-unified' : 'mem-search', text)+ },+ scope: () => {+ lab.scope = lab.scope === 'memory' ? 'unified' : 'memory'+ invalidate()+ },+ run: id => {+ const entry = memEntry(id)++ if (entry !== undefined) go(id, textOfFields(entry, lab))+ },+ open: entry => go('mem-retrieve', `${entry.namespace} ${entry.key}`),+ remove: entry => go('mem-delete', `${entry.namespace} ${entry.key}`),+ filter: namespace => {+ lab.filter = lab.filter === namespace ? null : namespace+ lab.page = 0+ invalidate()+ },+ page: by => {+ lab.page = Math.max(0, lab.page + by)+ invalidate()+ },+ }+}diff --git a/plugins/ruflo-console/hooks/memory-lines.ts b/plugins/ruflo-console/hooks/memory-lines.tsnew file mode 100644index 0000000000..c165833afb--- /dev/null+++ b/plugins/ruflo-console/hooks/memory-lines.ts@@ -0,0 +1,196 @@+/**+ * What the Memory Lab's runs printed, as lines worth reading: an entry's whole value wrapped, search hits by score,+ * listed entries with their size and age, AgentDB's controllers as on/off marks; anything else as the MetaHarness lab+ * reads JSON. The CLI's own warnings that change the meaning of an answer (a second store it did not read, a key not+ * 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 { 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. */+export const MEM_MAX_LINES = 80+const WRAP = 100++const NOISE = /^(Transformers\.js loaded|✅ Using native|\[INFO\] Executing tool|Parameters:|\[OK\] Tool executed|Result:|─+$)/++/** The CLI's warnings and errors, cleaned: these say the answer is partial or did not happen, so they lead. */+function warnings(stdout: string, stderr: string): string[] {+ return `${stdout}\n${stderr}`+ .split('\n')+ .map(line => plain(line, 200))+ .filter(line => /^\[(WARN|ERROR)\]/.test(line))+ .map(line => `⚠ ${line.replace(/^\[(WARN|ERROR)\]\s*/, '')}`)+ .slice(0, 3)+}++/** Text cut into lines of at most `width`, at spaces where it can; control characters never reach the terminal. */+export function wrap(text: string, width = WRAP): string[] {+ const out: string[] = []++ for (const paragraph of text.split('\n')) {+ let line = ''++ for (const whole of plain(paragraph, 20_000).split(' ')) {+ let word = whole++ // A word wider than the panel is cut, so a long token (a hash, a URL) still shows whole across lines.+ while (word.length > width) {+ if (line !== '') out.push(line)+ out.push(word.slice(0, width))+ word = word.slice(width)+ line = ''+ }++ if (line === '') line = word+ else if (line.length + 1 + word.length <= width) line = `${line} ${word}`+ else {+ out.push(line)+ line = word+ }+ }++ out.push(line)+ }++ 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')++/** 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 ${new Date(updated).toISOString().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)]+}++/** Search hits, best first: score, where it lives, and the start of its text. */+function hitLines(record: Record<string, unknown>, hits: unknown[]): string[] {+ const rows = hits.map(recordOf).filter((row): row is Record<string, unknown> => row !== null)+ const head = `${rows.length} hit${rows.length === 1 ? '' : 's'}${record.searchType !== undefined ? ` · ${short(record.searchType, 20)}` : ''}${record.searchTime !== undefined ? ` · ${short(record.searchTime, 20)}` : ''}${Array.isArray(record.searchedNamespaces) ? ` · searched ${record.searchedNamespaces.map(name => short(name, 24)).join(', ')}` : ''}`+ const notes = [record.degraded === true ? `degraded: ${short(record.reason, 80)}` : '', short(record.note, 160)].filter(note => note !== '')++ if (rows.length === 0) return [head, ...notes, '(no matches)']++ return [+ head,+ ...notes,+ ...rows.slice(0, 20).map(row => {+ const where = row.namespace !== undefined ? `${short(row.namespace, 24)}/${short(row.key ?? row.id, 60)}` : short(row.key ?? row.id ?? row.pattern ?? row.nodeId, 60)+ const text = short(row.preview ?? row.content ?? row.value ?? row.pattern ?? row.text ?? '', 90)++ return `${score(row.score ?? row.similarity ?? row.confidence ?? row.distance)} ${where}${row.source !== undefined ? ` [${short(row.source, 12)}]` : ''}${text !== '' ? ` ${text}` : ''}`+ }),+ ]+}++/** Listed entries, newest first: name, size, vector mark and age. */+function listLines(rows: unknown[]): string[] {+ const entries = rows.map(recordOf).filter((row): row is Record<string, unknown> => row !== null)++ if (entries.length === 0) return ['(no entries)']++ return [+ `${entries.length} entr${entries.length === 1 ? 'y' : 'ies'}`,+ ...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 ? ` · ${new Date(at).toISOString().slice(0, 16).replace('T', ' ')}` : ''}`+ }),+ ]+}++/** AgentDB's controllers: an on/off mark, the name and its level. */+function controllerLines(record: Record<string, unknown>, controllers: unknown[]): string[] {+ const rows = controllers.map(recordOf).filter((row): row is Record<string, unknown> => row !== null)+ const on = rows.filter(row => row.enabled === true).length++ return [`AgentDB ${record.available === true ? 'available' : 'NOT available'} · ${on}/${rows.length} controllers on`, ...rows.map(row => `${row.enabled === true ? '✓' : '·'} ${short(row.name, 40)}${row.level !== undefined ? ` L${short(row.level, 4)}` : ''}`)]+}++/** A vector: its dimensions, norm and first values, never all 384. */+function vectorLines(record: Record<string, unknown>): string[] | null {+ const vector = Array.isArray(record.embedding) ? record.embedding : Array.isArray(record.vector) ? record.vector : null++ if (vector === null) return null++ const numbers = vector.filter((value): value is number => typeof value === 'number' && Number.isFinite(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(' ')} …`]+}++/** One run's JSON as lines, by its shape; empty when nothing specific applies. */+function shaped(value: unknown): string[] {+ if (Array.isArray(value)) return listLines(value)++ const record = recordOf(value)++ if (record === null) return []+ if (record.content !== undefined || (record.value !== undefined && record.key !== undefined)) return entryLines(record)+ if (Array.isArray(record.results)) return hitLines(record, record.results)+ if (Array.isArray(record.entries) && record.total !== undefined) return listLines(record.entries)+ if (Array.isArray(record.controllers)) return controllerLines(record, record.controllers)++ return vectorLines(record) ?? []+}++/** What a Memory Lab run printed, at most MEM_MAX_LINES: its warnings, then its JSON read by shape, else the text. */+export function memLines(id: string, stdout: string, stderr = ''): string[] {+ const warned = warnings(stdout, stderr)+ const json = jsonAfter(stdout)+ const body = json === null ? [] : shaped(json)++ if (body.length > 0) return [...warned, ...body].slice(0, MEM_MAX_LINES)++ // Text output (store, delete, export print no JSON): its own lines, without the banners.+ const text = stdout+ .split('\n')+ .map(line => plain(line, 160))+ .filter(line => line !== '' && !NOISE.test(line) && !/^\[(WARN|ERROR)\]/.test(line))++ if (json === null && (text.length > 0 || warned.length > 0)) return [...warned, ...text].slice(0, MEM_MAX_LINES)++ return [...warned, ...labLines(id, stdout, stderr)].slice(0, MEM_MAX_LINES)+}++/** Times bucketed into `bins` equal spans from the oldest to now, oldest first, with the span's start. */+export function recency(times: readonly number[], nowMs: number, bins = 32): { counts: number[]; fromMs: number } | null {+ const past = times.filter(at => Number.isFinite(at) && at <= nowMs)++ if (past.length === 0) return null++ const fromMs = Math.min(...past)+ // At least an hour across, so a fresh store does not pile into one bar.+ const span = Math.max(3_600_000, nowMs - fromMs)+ const counts = Array.from({ length: bins }, () => 0)++ for (const at of past) {+ const bin = Math.min(bins - 1, Math.floor(((at - fromMs) / span) * bins))++ counts[bin] = (counts[bin] ?? 0) + 1+ }++ return { counts, fromMs }+}++const SPARK = ' ▁▂▃▄▅▆▇█'++/** Counts as one row of bars, the tallest a full block; an empty bin is a dot so the axis reads. */+export function sparkline(counts: readonly number[]): string {+ const top = Math.max(1, ...counts)++ return counts.map(n => (n === 0 ? '·' : (SPARK[Math.max(1, Math.round((n / top) * 8))] ?? '█'))).join('')+}++/** A filled share of `width` cells: ████░░░░. */+export function gauge(part: number, whole: number, width: number): string {+ const filled = whole <= 0 ? 0 : Math.round((Math.min(part, whole) / whole) * width)++ return `${'█'.repeat(filled)}${'░'.repeat(Math.max(0, width - filled))}`+}diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.tsindex 320a67f328..e891ac16cf 100644--- a/plugins/ruflo-console/hooks/palette.ts+++ b/plugins/ruflo-console/hooks/palette.ts@@ -6,6 +6,7 @@import { HIVE_ROLES, pickedProposal } from './data/hive'import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'+import { MEM_KEYWORDS, MEM_LAB, memSpecOf, memWhy } from './memory-lab'import { LAB, labSpec, labWhy } from './mh-lab'import { AGENT_TYPES, agentLogs, dispatchWorker, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops'import { VIEWS, type State, type ViewId } from './state'@@ -49,7 +50,7 @@ export function fuzzy(query: string, label: string): number | null {return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)}-const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast'] as const+const TEXT_KEYWORDS: readonly string[] = ['route', 'store', 'search', 'propose', 'broadcast', ...MEM_KEYWORDS]/** Every entry for the state as it is, before filtering. */export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {@@ -116,6 +117,11 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {// The MetaHarness lab: reads run at once, the rest ask first; promotion is never an entry (see mh-lab.ts).for (const entry of LAB) add(entry.id, 'metaharness', entry.label, { kind: 'spec', spec: labSpec(entry, state), why: labWhy(entry) })+ // The Memory Lab: an entry that takes text reads it after its id (`mem-search jwt refresh`), the rest run as they are.+ for (const entry of MEM_LAB) {+ add(entry.id, 'memory', entry.label, entry.takes === undefined ? { kind: 'spec', spec: memSpecOf(entry, '', state), why: memWhy(entry) } : { kind: 'text', keyword: entry.id, make: text => memSpecOf(entry, text, state) })+ }+for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' })add('route', 'learning', 'route <task words>: ask the router for a pick', { kind: 'text', keyword: 'route', make: reroute })diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.tsindex 6a61fe2313..c17b9aaa68 100644--- a/plugins/ruflo-console/hooks/runner.ts+++ b/plugins/ruflo-console/hooks/runner.ts@@ -60,7 +60,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner// A lab run's output goes to the lab's result panel, scrolled from its top; the footer keeps the one-line outcome.if (spec.lab !== undefined) {- state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() }+ state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: spec.lines?.(result.stdout, result.stderr) ?? labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() }state.select.item = 0}diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.tsindex 4270e97672..0ab8ea5403 100644--- a/plugins/ruflo-console/hooks/state.ts+++ b/plugins/ruflo-console/hooks/state.ts@@ -4,6 +4,7 @@ import type { ProbeResult } from './data/cli'import type { ConsoleEvent } from './data/events'import type { ReadCache } from './data/files'import { emptySkills, type SkillsState } from './data/skills'+import { emptyMemoryLab, type MemoryLabState } from './memory-lab'import type { Snapshot } from './data/snapshot'import type { RufloRoute, RufloSnapshot } from '../types'@@ -32,7 +33,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st{ id: 'plugins', key: '5', label: 'Plugins', short: 'Plg', icon: '🧩', blurb: 'ruflo plugins: installed, enabled, in the marketplace clone, and loaded as mods', rows: 30 },{ id: 'learning', key: '6', label: 'Learning', short: 'Lrn', icon: '🧠', blurb: 'router picks and outcomes, and the RETRIEVE → JUDGE → DISTILL → CONSOLIDATE pipeline', rows: 30 },{ id: 'metaharness', key: '7', label: 'MetaHarness', short: 'MH', icon: '🔬', blurb: 'harness readiness, the flywheel, the audit trend, and a lab that runs every MetaHarness verb', rows: 40 },- { id: 'memory', key: '8', label: 'Memory', short: 'Mem', icon: '💾', blurb: 'AgentDB entries by namespace: what the swarm has stored', rows: 22 },+ { id: 'memory', key: '8', label: 'Memory', short: 'Mem', icon: '💾', blurb: 'the Memory Lab: browse, search, store and delete entries; AgentDB, embeddings and upkeep, each a button', rows: 60 },{ id: 'cost', key: '9', label: 'Cost', short: 'Cst', icon: '💰', blurb: 'this session spend against the budget, and how fast it is burning', rows: 20 },{ id: 'timeline', key: 'g', label: 'Timeline', short: 'Gnt', icon: '🕒', blurb: 'each agent busy or idle over the last minutes, beside Claude Code tool calls', rows: 24 },{ id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', icon: '✅', blurb: 'decisions waiting for a person: votes, stealable claims, refused mods, budget', rows: 24 },@@ -217,6 +218,8 @@ export type State = {}/** The skills view: installed skills, the last search, and the change running now. */skills: SkillsState+ /** The Memory Lab's fields and picks (its last run is `lab.result`, under a mem- id). */+ memoryLab: MemoryLabStatetimers: Map<string, Timer>stats: { renders: number[]; refreshes: number[]; frames: number[] }}@@ -261,6 +264,7 @@ export function newState(raw: PluginOptions | undefined): State {barDrawnAtMs: 0,terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, scroll: 0, unseen: 0, asked: null },skills: emptySkills(),+ memoryLab: emptyMemoryLab(),timers: new Map(),stats: { renders: [], refreshes: [], frames: [] },}diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.tsindex 482d9f5b70..175b08acca 100644--- a/plugins/ruflo-console/hooks/views/common.ts+++ b/plugins/ruflo-console/hooks/views/common.ts@@ -7,6 +7,7 @@ import type { Elements, RenderChildren, RenderElement } from 'claude-code'import type { ProbeResult } from '../data/cli'import type { Grid } from '../gfx/raster'+import type { MemoryActions } from '../memory-lab'import type { SkillActions } from '../skills'import type { HarnessId, State, ViewId } from '../state'@@ -44,6 +45,8 @@ export type Actions = {term: { harness: (id: HarnessId) => void; draft: (text: string) => void; submit: (text: string) => void; stop: () => void; fresh: () => void; clear: () => void; load: (id: HarnessId, text: string) => void; /** Moves the window up (positive) or down by screen rows. */ scroll: (by: number) => void; /** Puts an earlier question back in the field. */ reuse: (text: string) => void }/** The skills view: list, search, and the confirm-gated add, remove, update and create; edit loads the terminal. */skills: SkillActions+ /** The Memory Lab: its fields, search, browse filter, and an entry's open or delete (each through the runner). */+ memory: MemoryActions}export type Ctx = {diff --git a/plugins/ruflo-console/hooks/views/memory-lab.ts b/plugins/ruflo-console/hooks/views/memory-lab.tsnew file mode 100644index 0000000000..f5b507489a--- /dev/null+++ b/plugins/ruflo-console/hooks/views/memory-lab.ts@@ -0,0 +1,140 @@+import type { RenderElement } from 'claude-code'++import { MEM_GROUPS, MEM_LAB, memSpecOf, textOfFields, type MemCost, type MemEntry, type MemField } from '../memory-lab'+import { ago, button, clip, row, rule, text, THEME, type Ctx } from './common'++/** Result lines in view at once; j/k scroll the rest. */+export const MEM_ROWS = 16++/** Each cost as a four-cell tag: $0 reads, writes, deletes, and what may reach the network. */+const TAG: Record<MemCost, { text: string; color: () => string }> = {+ read: { text: ' $0 ', color: () => THEME.ok },+ writes: { text: ' wr ', color: () => THEME.info },+ deletes: { text: 'del ', color: () => THEME.bad },+ net: { text: 'net ', color: () => THEME.warn },+}++/** A text field bound to one of the lab's fields; on a surface without fields, a line saying how to type it instead. */+function field(ctx: Ctx, name: MemField, label: string, placeholder: string, submitLabel: string, onSubmit: (value: string) => void): RenderElement {+ if (ctx.kit.Input === undefined) return text(ctx, ` ${label}: this surface has no text field; use /ruflo run <entry id> <text>`, { dimColor: true })++ return ctx.kit.Input({+ key: `mem-${name}`,+ label,+ placeholder,+ value: ctx.state.memoryLab[name],+ submitLabel,+ onInput: value => ctx.act.memory.draft(name, value),+ // The field's text is the input even when no keystroke reached onInput (a paste, a headless submit).+ onSubmit: value => {+ ctx.act.memory.draft(name, value)+ onSubmit(value)+ },+ })+}++/** The search box and its scope: the memory store alone, or one search over Claude memories, AgentDB and patterns. */+function searchRows(ctx: Ctx): RenderElement[] {+ const lab = ctx.state.memoryLab+ const isUnified = lab.scope === 'unified'++ return [+ rule(ctx, 'Search', isUnified ? 'memory_search_unified · Claude + AgentDB + patterns' : `memory search · semantic${lab.filter !== null ? ` · in ${lab.filter}` : ''}`),+ field(ctx, 'query', 'search', 'what to find, in words: jwt refresh, the login bug …', 'search', value => ctx.act.memory.search(value)),+ row(ctx, [+ text(ctx, ` scope: ${isUnified ? 'everything (unified)' : 'the memory store'} `, { color: THEME.info }),+ button(ctx, 'mem-scope', isUnified ? 'memory store only' : 'search everything', ctx.act.memory.scope),+ ]),+ ]+}++/** The entry fields: namespace, key and value, and the three things to do with them. */+function entryRows(ctx: Ctx): RenderElement[] {+ return [+ rule(ctx, 'Entry', 'store asks first · delete asks and cannot be undone'),+ field(ctx, 'namespace', 'namespace', 'default', 'set', value => ctx.act.memory.draft('namespace', value)),+ field(ctx, 'key', 'key', 'a key: api/auth, notes.alpha …', 'retrieve', () => ctx.act.memory.run('mem-retrieve')),+ field(ctx, 'value', 'value', 'what to store under the key', 'store', () => ctx.act.memory.run('mem-store')),+ row(ctx, [+ button(ctx, 'mem-do-store', '▸ store', () => ctx.act.memory.run('mem-store'), { primary: true }),+ button(ctx, 'mem-do-retrieve', '▸ retrieve', () => ctx.act.memory.run('mem-retrieve')),+ button(ctx, 'mem-do-delete', '▸ delete', () => ctx.act.memory.run('mem-delete')),+ ]),+ ]+}++/** One lab row, dotted to its purpose: the cost tag, the name, what it does, and its button. */+function entryRow(ctx: Ctx, entry: MemEntry, lead: number): RenderElement {+ const tag = TAG[entry.cost]+ const isReady = memSpecOf(entry, textOfFields(entry, ctx.state.memoryLab), ctx.state) !== null++ return row(+ ctx,+ [+ ctx.kit.Text({ bold: true, color: tag.color(), children: ` ${tag.text}` }),+ ctx.kit.Text({ bold: true, color: entry.cost === 'deletes' ? THEME.bad : THEME.head, children: ` ${entry.name} `.padEnd(lead, '.') }),+ ctx.kit.Text({ color: THEME.info, dimColor: !isReady, wrap: 'truncate-end', children: clip(` ${entry.about}`, Math.max(4, ctx.columns - lead - 16)) }),+ ctx.kit.Button({ key: `mem-lab-${entry.id}`, label: ' ▸ run', plain: true, dimColor: true, onPress: () => ctx.act.memory.run(entry.id) }),+ ],+ `mem-row-${entry.id}`,+ )+}++/** The last Memory Lab run: what it was, how it exited, its note, and a window of its lines. */+function resultRows(ctx: Ctx): RenderElement[] {+ const { state, nowMs } = ctx+ const result = state.lab.result?.id.startsWith('mem-') === true ? state.lab.result : null+ const running = state.lab.running?.id.startsWith('mem-') === true ? state.lab.running : null+ const right = running !== null ? `running ${Math.round((nowMs - running.startedAtMs) / 1000)}s` : result === null ? 'nothing run yet' : `${result.ok ? '✓' : '✗'} exit ${result.exitCode ?? 'n/a'} · ${ago(result.atMs, nowMs)}`+ const rows: RenderElement[] = [rule(ctx, 'Result', right)]++ // Data, not decoration: the block blinks only while the CLI is still working.+ if (running !== null) rows.push(text(ctx, ` ▸ ${running.label} … ${Math.floor(nowMs / 500) % 2 === 0 ? '█' : ' '}`, { color: THEME.warn }))++ if (result === null) {+ if (running === null) rows.push(text(ctx, ' ▸ open an entry above, search, or run a lab row: reads show here at once, the rest after you confirm (y)', { dimColor: true }))++ return rows+ }++ rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad }))+ if (result.note !== undefined) rows.push(text(ctx, ` ${result.note}`, { color: /DELETES|network/i.test(result.note) ? THEME.bad : THEME.warn }))++ const top = Math.max(0, Math.min(state.select.item, result.lines.length - MEM_ROWS))++ for (const line of result.lines.slice(top, top + MEM_ROWS)) rows.push(text(ctx, ` ${line}`, line.startsWith('⚠') ? { color: THEME.warn } : {}))++ if (result.lines.length > MEM_ROWS) {+ rows.push(+ row(ctx, [+ text(ctx, ` lines ${top + 1}-${Math.min(result.lines.length, top + MEM_ROWS)} of ${result.lines.length} `, { dimColor: true }),+ button(ctx, 'mem-up', 'up', () => ctx.act.select(-1), { hotkey: 'k' }),+ button(ctx, 'mem-down', 'down', () => ctx.act.select(1), { hotkey: 'j' }),+ ]),+ )+ }++ return rows+}++/**+ * The lab under the browse list: search, the entry fields, one text field for AgentDB and embeddings, every verb by+ * group with its cost tag, then the last run's output.+ */+export function memoryLabRows(ctx: Ctx): RenderElement[] {+ const lead = Math.max(15, Math.min(18, ctx.columns - 40))+ const rows: RenderElement[] = [...searchRows(ctx), ...entryRows(ctx), ...resultRows(ctx)]++ rows.push(rule(ctx, 'Lab text', 'the input for the rows below that take text'))+ rows.push(field(ctx, 'text', 'text', 'a query or pattern · a node id · a | b to compare · source relation target', 'keep', value => ctx.act.memory.draft('text', value)))++ for (const group of MEM_GROUPS) {+ rows.push(rule(ctx, group.title, group.right))++ for (const entry of MEM_LAB.filter(candidate => candidate.group === group.id)) rows.push(entryRow(ctx, entry, lead))+ }++ rows.push(text(ctx, ' $0 read, runs at once · wr writes · del deletes for good · net may fetch the model: each of these asks, its cost on the confirm row', { dimColor: true }))++ return rows+}diff --git a/plugins/ruflo-console/hooks/views/memory.ts b/plugins/ruflo-console/hooks/views/memory.tsindex ec40d48ce0..711fbb6db2 100644--- a/plugins/ruflo-console/hooks/views/memory.ts+++ b/plugins/ruflo-console/hooks/views/memory.ts@@ -1,13 +1,16 @@import type { RenderElement } from 'claude-code'-import type { MemoryStats, Namespaces } from '../data/cli'-import { ago, col, count, kv, live, rule, sourceLine, text, type Ctx } from './common'+import type { MemoryEntry, MemoryStats, Namespaces } from '../data/cli'+import { gauge, recency, sparkline } from '../memory-lines'+import { ago, button, clip, col, count, kv, live, row, rule, sourceLine, text, THEME, type Ctx } from './common'+import { memoryLabRows } from './memory-lab'-/** AgentDB counts and namespaces from the ruflo CLI. */-export function memoryView(ctx: Ctx): RenderElement {+/** Entries in the browse list at once; ◂ ▸ page the rest. */+export const BROWSE = 8++/** AgentDB's counts, the share of listed entries that carry a vector, and the second store the counts leave out. */+function storeRows(ctx: Ctx, memory: MemoryStats | null, spaces: Namespaces | null): RenderElement[] {const { state, nowMs } = ctx- const memory = live<MemoryStats>(state.probes.get('memory'))- const spaces = live<Namespaces>(state.probes.get('namespaces'))const rows: RenderElement[] = [rule(ctx, 'AgentDB', memory?.backend ?? '')]if (memory === null) {@@ -16,26 +19,126 @@ export function memoryView(ctx: Ctx): RenderElement {rows.push(kv(ctx, 'entries', `${count(memory.total)} · ${count(memory.vectors)} with vectors`))rows.push(kv(ctx, 'storage', memory.storage ?? 'n/a'))rows.push(kv(ctx, 'span', `oldest ${ago(memory.oldestMs, nowMs)} · newest ${ago(memory.newestMs, nowMs)}`))++ // Two stores: the CLI reads .swarm/memory.db; the MCP tools write .swarm/agentdb-memory.db as well. Never summed.+ if ((memory.unread ?? 0) > 0) rows.push(text(ctx, ` ⚠ ${memory.unread} more rows in .swarm/agentdb-memory.db (the MCP path’s store) are not in these counts or the list; unified search reads them`, { color: THEME.warn }))}- rows.push(rule(ctx, 'Namespaces', spaces === null ? '' : `newest ${spaces.sampled} entries`))+ const entries = spaces?.entries ?? []++ if (entries.length > 0) {+ const width = Math.max(8, Math.min(30, ctx.columns - 50))+ const withVector = entries.filter(entry => entry.hasVector).length++ // The stats' own vector count is a placeholder in this CLI; the listed entries say which carry an embedding.+ rows.push(kv(ctx, 'embedded', `${gauge(withVector, entries.length, width)} ${withVector}/${entries.length} of the newest listed carry a vector`, withVector === entries.length ? THEME.ok : THEME.warn))+ }++ return rows+}++/** One bar per namespace over the listed sample; a click narrows the browse list (and search, list, export) to it. */+function namespaceRows(ctx: Ctx, spaces: Namespaces | null): RenderElement[] {+ const { state, nowMs } = ctx+ const filter = state.memoryLab.filter+ const rows: RenderElement[] = [rule(ctx, 'Namespaces', spaces === null ? '' : `newest ${spaces.sampled} entries${filter !== null ? ` · showing ${filter}` : ''}`)]if (spaces === null) {rows.push(text(ctx, sourceLine(state.probes.get('namespaces'), nowMs, 'memory list').text, { dimColor: true }))- } else if (spaces.byName.length === 0) {- rows.push(text(ctx, 'no entries', { dimColor: true }))- } else {- const top = spaces.byName[0]?.count ?? 1- const width = Math.max(4, Math.min(30, ctx.columns - 30))- for (const space of spaces.byName.slice(0, 6)) {- rows.push(text(ctx, `${space.name.slice(0, 20).padEnd(21)}${'█'.repeat(Math.max(1, Math.round((space.count / top) * width)))} ${space.count}`))- }+ return rows+ }++ if (spaces.byName.length === 0) {+ rows.push(text(ctx, 'no entries: store one below (▸ store), or import your Claude memories (IMPORT CLAUDE)', { dimColor: true }))- rows.push(text(ctx, 'a sample: counts over the newest entries `memory list` returns, not the whole store', { dimColor: true }))+ return rows}- rows.push(text(ctx, 'spend, budget gauge and burn: Cost (9)', { dimColor: true }))+ const top = spaces.byName[0]?.count ?? 1+ const width = Math.max(4, Math.min(30, ctx.columns - 30))++ spaces.byName.slice(0, 8).forEach((space, i) => {+ const isPicked = filter === space.name++ rows.push(+ row(ctx, [+ ctx.kit.Button({ key: `mem-ns-${i}`, label: `${isPicked ? '▸' : ' '}${space.name.slice(0, 20).padEnd(21)}`, plain: true, ...(!isPicked && { dimColor: true }), onPress: () => ctx.act.memory.filter(space.name) }),+ ctx.kit.Text({ color: isPicked ? THEME.head : THEME.info, children: `${'█'.repeat(Math.max(1, Math.round((space.count / top) * width)))} ${space.count}` }),+ ], `mem-ns-row-${i}`),+ )+ })++ rows.push(text(ctx, `a sample: counts over the newest entries \`memory list\` returns, not the whole store · click a namespace to ${filter === null ? 'browse it' : 'show all again'}`, { dimColor: true }))++ return rows+}++/** When the listed entries were last written, oldest to now, as one row of bars. */+function timelineRows(ctx: Ctx, entries: readonly MemoryEntry[]): RenderElement[] {+ const { nowMs } = ctx+ const bins = Math.max(12, Math.min(48, ctx.columns - 30))+ const binned = recency(entries.flatMap(entry => (entry.atMs === undefined ? [] : [entry.atMs])), nowMs, bins)++ if (binned === null) return []++ return [+ rule(ctx, 'Recency', `${entries.length} entries by last write`),+ row(ctx, [+ ctx.kit.Text({ dimColor: true, children: ` ${ago(binned.fromMs, nowMs).padStart(8)} ` }),+ ctx.kit.Text({ color: THEME.ok, children: sparkline(binned.counts) }),+ ctx.kit.Text({ dimColor: true, children: ' now' }),+ ], 'mem-recency'),+ ]+}++/** The listed entries, newest first, in the picked namespace: each one opens (retrieve) or deletes (asks first). */+function browseRows(ctx: Ctx, entries: readonly MemoryEntry[]): RenderElement[] {+ const { state, nowMs } = ctx+ const lab = state.memoryLab+ const shown = lab.filter === null ? entries : entries.filter(entry => entry.namespace === lab.filter)+ const pages = Math.max(1, Math.ceil(shown.length / BROWSE))+ const page = Math.min(lab.page, pages - 1)+ const lead = Math.max(18, Math.min(34, ctx.columns - 60))+ const rows: RenderElement[] = [rule(ctx, 'Browse', shown.length === 0 ? '' : `${shown.length} listed · page ${page + 1}/${pages}`)]++ if (shown.length === 0) {+ rows.push(text(ctx, entries.length === 0 ? ' nothing listed yet' : ` nothing listed in ${lab.filter ?? ''}`, { dimColor: true }))++ return rows+ }++ shown.slice(page * BROWSE, page * BROWSE + BROWSE).forEach((entry, i) => {+ rows.push(+ row(ctx, [+ ctx.kit.Text({ bold: true, color: entry.hasVector ? THEME.head : THEME.info, children: clip(` ${entry.hasVector ? '◆' : '◇'} ${entry.key} `, lead).padEnd(lead, '.') }),+ ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip(` ${entry.namespace} · ${entry.size === undefined ? 'n/a' : `${entry.size} B`} · ${ago(entry.atMs, nowMs)}`, Math.max(4, ctx.columns - lead - 22)) }),+ ctx.kit.Button({ key: `mem-open-${i}`, label: ' ▸ view', plain: true, dimColor: true, onPress: () => ctx.act.memory.open(entry) }),+ ctx.kit.Button({ key: `mem-del-${i}`, label: ' ▸ delete', plain: true, dimColor: true, onPress: () => ctx.act.memory.remove(entry) }),+ ], `mem-entry-${i}`),+ )+ })++ rows.push(+ row(ctx, [+ text(ctx, ' ◆ has a vector · ▸ view reads it at once · ▸ delete asks · r re-lists ', { dimColor: true }),+ ...(page > 0 ? [button(ctx, 'mem-prev', '◂ newer', () => ctx.act.memory.page(-1))] : []),+ ...(page < pages - 1 ? [button(ctx, 'mem-next', 'older ▸', () => ctx.act.memory.page(1))] : []),+ ]),+ )++ return rows+}++/**+ * The Memory Lab: AgentDB's counts and how much of it is embedded, a bar per namespace, when entries were written,+ * the newest entries to open or delete, then search, the entry fields and every memory, AgentDB and embeddings verb+ * as a button. On open it runs only the view's two local probes (memory stats, memory list).+ */+export function memoryView(ctx: Ctx): RenderElement {+ const memory = live<MemoryStats>(ctx.state.probes.get('memory'))+ const spaces = live<Namespaces>(ctx.state.probes.get('namespaces'))+ const entries = spaces?.entries ?? []- return col(ctx, rows, 'memory')+ return col(ctx, [...storeRows(ctx, memory, spaces), ...namespaceRows(ctx, spaces), ...timelineRows(ctx, entries), ...browseRows(ctx, entries), ...memoryLabRows(ctx), text(ctx, 'spend, budget gauge and burn: Cost (9)', { dimColor: true })], 'memory')}diff --git a/plugins/ruflo-console/hooks/views/mh-lab.ts b/plugins/ruflo-console/hooks/views/mh-lab.tsindex 5ecbf4906a..449398129f 100644--- a/plugins/ruflo-console/hooks/views/mh-lab.ts+++ b/plugins/ruflo-console/hooks/views/mh-lab.ts@@ -37,7 +37,9 @@ function entryRow(ctx: Ctx, entry: LabEntry, lead: number): RenderElement {/** The last run: what it was, how it exited, what it cost, and a window of its lines. */function resultRows(ctx: Ctx): RenderElement[] {const { state, nowMs } = ctx- const { result, running } = state.lab+ // Other labs (the Memory Lab's mem- runs) share the runner's lab slot: only MetaHarness runs show here.+ const result = state.lab.result?.id.startsWith('mh-') === true ? state.lab.result : null+ const running = state.lab.running?.id.startsWith('mh-') === true ? state.lab.running : nullconst right = running !== null ? `running ${Math.round((nowMs - running.startedAtMs) / 1000)}s` : result === null ? 'nothing run yet' : `${result.ok ? '✓' : '✗'} exit ${result.exitCode ?? 'n/a'} · ${ago(result.atMs, nowMs)}`const rows: RenderElement[] = [rule(ctx, 'Result', right)]diff --git a/plugins/ruflo-console/tests/fixtures/memory.ts b/plugins/ruflo-console/tests/fixtures/memory.tsnew file mode 100644index 0000000000..563691cf4d--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/memory.ts@@ -0,0 +1,14 @@+/** What the Memory Lab's reads printed, captured from ruflo v3.51.1 in a throwaway project (two entries, auth/beta and notes/alpha) on 2026-10-02. In `list`, alpha's hasEmbedding is set false so the vector gauge reads a part, not all. */++const ESC = '\u001b'++export const MEM_OUT: Readonly<Record<string, string>> = {+ retrieve: `Transformers.js loaded: Xenova/all-MiniLM-L6-v2\n${ESC}[33m${ESC}[1m[WARN]${ESC}[0m Partial result: 1 match came from the store read here. 2 entries are in /work/.swarm/agentdb-memory.db and were not searched. That store is written by the MCP/AgentDB path; read it with --path /work/.swarm/agentdb-memory.db.\n{\n "id": "entry_1790977477874_7d2e03d2c624edd8",\n "key": "beta",\n "namespace": "auth",\n "content": "jwt refresh tokens rotate",\n "accessCount": 1,\n "createdAt": 1790977477874,\n "updatedAt": 1790977477874,\n "hasEmbedding": true,\n "tags": []\n}\n`,+ search: `${ESC}[34m${ESC}[1m[INFO]${ESC}[0m Searching: "token rotation" (semantic)\n\nTransformers.js loaded: Xenova/all-MiniLM-L6-v2\n{\n "query": "token rotation",\n "searchType": "semantic",\n "results": [\n {\n "key": "beta",\n "score": 0.6842397315513365,\n "namespace": "auth",\n "preview": "jwt refresh tokens rotate",\n "provenanceType": "unknown"\n }\n ],\n "searchTime": "9ms"\n}\n`,+ unified: `${ESC}[34m${ESC}[1m[INFO]${ESC}[0m Executing tool: memory_search_unified\n${ESC}[2m Parameters: {"query":"token rotation","limit":10}${ESC}[0m\n\n${ESC}[32m${ESC}[1m[OK]${ESC}[0m Tool executed in 292.69ms\n\n${ESC}[1mResult:${ESC}[0m\n{\n "success": true,\n "query": "token rotation",\n "results": [\n {\n "key": "beta",\n "content": "jwt refresh tokens rotate",\n "score": 0.6842397315513365,\n "namespace": "auth",\n "source": "agentdb"\n }\n ],\n "total": 1,\n "searchedNamespaces": [\n "auth",\n "notes"\n ],\n "namespaceSource": "dynamic",\n "searchTime": 1790977486140\n}\n`,+ health: `${ESC}[34m${ESC}[1m[INFO]${ESC}[0m Executing tool: agentdb_health\n\n${ESC}[32m${ESC}[1m[OK]${ESC}[0m Tool executed in 267.21ms\n\n${ESC}[1mResult:${ESC}[0m\n{\n "available": true,\n "controllers": [\n { "name": "hierarchicalMemory", "enabled": true, "level": 1 },\n { "name": "reasoningBank", "enabled": true, "level": 1 },\n { "name": "mutationGuard", "enabled": false, "level": 2 }\n ]\n}\n`,+ list: `Transformers.js loaded: Xenova/all-MiniLM-L6-v2\n[\n {\n "id": "entry_1790977477874_",\n "key": "beta",\n "namespace": "auth",\n "size": 25,\n "accessCount": 0,\n "createdAt": 1790977477874,\n "updatedAt": 1790977477874,\n "hasEmbedding": true,\n "provenanceType": "unknown"\n },\n {\n "id": "entry_1790977477126_",\n "key": "alpha",\n "namespace": "notes",\n "size": 19,\n "accessCount": 0,\n "createdAt": 1790977477126,\n "updatedAt": 1790977477126,\n "hasEmbedding": false,\n "provenanceType": "unknown"\n }\n]\n`,+ stats: `Transformers.js loaded: Xenova/all-MiniLM-L6-v2\n{\n "unreadStore": {\n "path": "/work/.swarm/agentdb-memory.db",\n "rows": 2\n },\n "backend": "sqlite (bridge, brute-force cosine)",\n "entries": {\n "total": 2,\n "vectors": 0,\n "text": 2\n },\n "storage": {\n "total": "643072 B",\n "location": "/work/.swarm/memory.db"\n },\n "version": "3.0.0",\n "oldestEntry": "2026-10-02T21:44:37.126Z",\n "newestEntry": "2026-10-02T21:44:37.874Z"\n}\n`,+ deleteMissing: `Transformers.js loaded: Xenova/all-MiniLM-L6-v2\n${ESC}[33m${ESC}[1m[WARN]${ESC}[0m Key not found: "nonexist" in namespace "notes"\n`,+ stored: `${ESC}[34m${ESC}[1m[INFO]${ESC}[0m Storing in notes/alpha...\n✅ Using native better-sqlite3\n\n${ESC}[32m${ESC}[1m[OK]${ESC}[0m Data stored successfully\n`,+}diff --git a/plugins/ruflo-console/tests/memory-lab.spec.ts b/plugins/ruflo-console/tests/memory-lab.spec.tsnew file mode 100644index 0000000000..c206b0c364--- /dev/null+++ b/plugins/ruflo-console/tests/memory-lab.spec.ts@@ -0,0 +1,198 @@+/**+ * The Memory Lab's pure parts under vitest: the catalog's invariants (fixed argv, what asks first and why, no shell),+ * the input validators, the argv each entry builds, the output readers against what the CLI printed, and the recency+ * timeline. Run with+ * npx vitest run plugins/ruflo-console/tests/memory-lab.spec.ts+ */+import { describe, expect, it } from 'vitest'++import { PROBES, type Namespaces } from '../hooks/data/cli'+import { keyOf, MEM_KEYWORDS, MEM_LAB, memEntry, memSpecOf, namespaceOf, parseInput, textOfFields } from '../hooks/memory-lab'+import { gauge, memLines, recency, sparkline, wrap } from '../hooks/memory-lines'+import { filterPalette, paletteEntries } from '../hooks/palette'+import { newState } from '../hooks/state'+import { MEM_OUT } from './fixtures/memory'++const entry = (id: string) => {+ const found = memEntry(id)++ if (found === undefined) throw new Error(`no entry ${id}`)++ return found+}++/** A plausible input for each takes, so every entry builds its argv. */+const SAMPLE = { text: 'jwt refresh', node: 'beta', pair: 'jwt refresh | token rotation', edge: 'auth-bug causes login-fail', entry: 'auth beta', kv: 'notes alpha the quick brown fox' } as const++describe('the memory lab catalog', () => {+ it('every entry has a unique mem- id, builds one fixed argv, and none reaches a shell', () => {+ const ids = MEM_LAB.map(candidate => candidate.id)+ const state = newState({})++ expect(new Set(ids).size).toBe(ids.length)+ expect(ids.every(id => id.startsWith('mem-'))).toBe(true)++ for (const candidate of MEM_LAB) {+ const spec = memSpecOf(candidate, candidate.takes === undefined ? '' : SAMPLE[candidate.takes], state)++ expect(spec, candidate.id).not.toBeNull()+ expect(spec?.lab).toBe(candidate.id)+ expect(spec?.args.some(word => /^(sh|bash|rm)$/.test(word)), candidate.id).toBe(false)+ expect(spec?.args[0] === 'memory' || (spec?.args[0] === 'mcp' && spec.args[1] === 'exec'), candidate.id).toBe(true)+ }+ })++ it('reads run at once; writes, deletes and network ask first with a note that says which', () => {+ const state = newState({})++ for (const candidate of MEM_LAB) {+ const spec = memSpecOf(candidate, candidate.takes === undefined ? '' : SAMPLE[candidate.takes], state)++ expect(spec?.isReadOnly === true, candidate.id).toBe(candidate.cost === 'read')+ if (candidate.cost !== 'read') expect(spec?.note, candidate.id).toBeDefined()+ if (candidate.cost === 'deletes') expect(spec?.note, candidate.id).toMatch(/DELETES FOR GOOD/)+ if (candidate.cost === 'net') expect(spec?.note, candidate.id).toMatch(/download.*network/)+ }++ expect(MEM_LAB.filter(candidate => candidate.cost === 'deletes').map(candidate => candidate.id)).toEqual(['mem-delete', 'mem-cleanup'])+ })++ it('builds the argv the CLI source and --help name', () => {+ const state = newState({})+ const args = (id: string, text = '') => memSpecOf(entry(id), text, state)?.args++ expect(args('mem-stats')).toEqual(['memory', 'stats', '--format', 'json'])+ expect(args('mem-list')).toEqual(['memory', 'list', '--limit', '50', '--format', 'json'])+ expect(args('mem-search', 'jwt refresh')).toEqual(['memory', 'search', '--query', 'jwt refresh', '--limit', '10', '--format', 'json'])+ expect(args('mem-retrieve', 'auth jwt/refresh')).toEqual(['memory', 'retrieve', '--key', 'jwt/refresh', '--namespace', 'auth', '--format', 'json'])+ expect(args('mem-store', 'notes alpha the quick brown fox')).toEqual(['memory', 'store', '--key', 'alpha', '--value', 'the quick brown fox', '--namespace', 'notes'])+ expect(args('mem-delete', 'auth beta')).toEqual(['memory', 'delete', '--key', 'beta', '--namespace', 'auth', '--force'])+ expect(args('mem-export')).toEqual(['memory', 'export', '--output', '.claude-flow/memory-export.json'])+ expect(args('mem-unified', 'token rotation')).toEqual(['mcp', 'exec', '-t', 'memory_search_unified', '-p', '{"query":"token rotation","limit":10}'])+ expect(args('mem-cleanup-plan')).toEqual(['mcp', 'exec', '-t', 'memory_cleanup', '-p', '{"dryRun":true}'])+ expect(args('mem-cleanup')).toEqual(['mcp', 'exec', '-t', 'memory_cleanup', '-p', '{"dryRun":false}'])+ expect(args('mem-import-all')).toEqual(['mcp', 'exec', '-t', 'memory_import_claude', '-p', '{"allProjects":true}'])+ expect(args('mem-graph', 'beta')).toEqual(['mcp', 'exec', '-t', 'agentdb_graph-query', '-p', '{"nodeId":"beta","mode":"k-hop","depth":2,"topK":10}'])+ expect(args('mem-edge', 'auth-bug causes login-fail')).toEqual(['mcp', 'exec', '-t', 'agentdb_causal-edge', '-p', '{"sourceId":"auth-bug","targetId":"login-fail","relation":"causes"}'])+ expect(args('mem-compare', 'jwt | token')).toEqual(['mcp', 'exec', '-t', 'embeddings_compare', '-p', '{"text1":"jwt","text2":"token","metric":"cosine"}'])+ expect(args('mem-rabitq-search', 'auth')).toEqual(['mcp', 'exec', '-t', 'embeddings_rabitq_search', '-p', '{"query":"auth","k":10}'])+ })++ it('a picked namespace narrows list, search and export', () => {+ const state = newState({})++ state.memoryLab.filter = 'auth'+ expect(memSpecOf(entry('mem-list'), '', state)?.args).toEqual(['memory', 'list', '--namespace', 'auth', '--limit', '50', '--format', 'json'])+ expect(memSpecOf(entry('mem-search'), 'x', state)?.args).toContain('auth')+ expect(memSpecOf(entry('mem-export'), '', state)?.args.slice(-2)).toEqual(['--namespace', 'auth'])+ })+})++describe('the input validators', () => {+ it('keys and namespaces: no leading -, no spaces, capped; keys may hold / and :', () => {+ expect(keyOf('api/auth')).toBe('api/auth')+ expect(keyOf('notes:alpha@v2')).toBe('notes:alpha@v2')+ expect(keyOf('--force')).toBeNull()+ expect(keyOf('a b')).toBeNull()+ expect(keyOf('k'.repeat(129))).toBeNull()+ expect(namespaceOf('claude-memories')).toBe('claude-memories')+ expect(namespaceOf('a/b')).toBeNull()+ expect(namespaceOf('-n')).toBeNull()+ expect(namespaceOf('.hidden')).toBeNull()+ })++ it('each takes reads its shape and refuses the rest', () => {+ expect(parseInput('text', '-rf /')).toBeNull()+ expect(parseInput('text', ' ')).toBeNull()+ expect(parseInput('text', 'a\u001b[31mred\u0007bell')?.text).toBe('ared bell')+ expect(parseInput('node', 'two words')).toBeNull()+ expect(parseInput('pair', 'only one')).toBeNull()+ expect(parseInput('pair', 'a | b | c')).toBeNull()+ expect(parseInput('edge', 'a causes')).toBeNull()+ expect(parseInput('edge', 'a "causes" b')).toBeNull()+ expect(parseInput('entry', 'auth')).toBeNull()+ expect(parseInput('entry', 'auth beta extra')).toBeNull()+ expect(parseInput('kv', 'notes alpha')).toBeNull()+ expect(parseInput('kv', 'notes alpha --upsert')).toBeNull()+ expect(parseInput('kv', 'notes alpha x'.padEnd(2100, 'y'))).toBeNull()+ })++ it('a button builds the same text from the fields that a headless run would type', () => {+ const lab = { ...newState({}).memoryLab, query: 'q', key: 'beta', value: 'v v', namespace: 'auth', text: 't' }++ expect(textOfFields(entry('mem-store'), lab)).toBe('auth beta v v')+ expect(textOfFields(entry('mem-delete'), lab)).toBe('auth beta')+ expect(textOfFields(entry('mem-search'), lab)).toBe('q')+ expect(textOfFields(entry('mem-recall'), lab)).toBe('t')+ expect(textOfFields(entry('mem-stats'), lab)).toBe('')+ })+})++describe('the palette and headless runs', () => {+ it('every lab entry is a palette id; a text entry takes the words after its id', () => {+ const state = newState({})+ const entries = paletteEntries(state, 0)++ for (const candidate of MEM_LAB) expect(entries.some(found => found.id === candidate.id), candidate.id).toBe(true)++ const [best] = filterPalette(entries, 'mem-search jwt refresh', 'all')++ expect(best?.id).toBe('mem-search')+ expect(best?.run.kind === 'text' ? best.run.make('jwt refresh')?.args : null).toContain('jwt refresh')+ expect(MEM_KEYWORDS).toContain('mem-delete')+ expect(MEM_KEYWORDS).not.toContain('mem-stats')+ })+})++describe('the output readers', () => {+ it('retrieve: the CLI warning about the other store first, then the whole value', () => {+ const lines = memLines('mem-retrieve', MEM_OUT.retrieve ?? '')++ expect(lines[0]).toMatch(/^⚠ Partial result: .*agentdb-memory\.db/)+ expect(lines[1]).toContain('auth/beta · 25 chars · read 1× · has a vector')+ expect(lines).toContain('jwt refresh tokens rotate')+ expect(lines.join('\n')).not.toMatch(/\u001b/)+ })++ it('search and unified search: hits by score, where each lives', () => {+ expect(memLines('mem-search', MEM_OUT.search ?? '')).toEqual(['1 hit · semantic · 9ms', '0.684 auth/beta jwt refresh tokens rotate'])+ expect(memLines('mem-unified', MEM_OUT.unified ?? '')[1]).toBe('0.684 auth/beta [agentdb] jwt refresh tokens rotate')+ })++ it('list, health, and the text answers of store and delete', () => {+ expect(memLines('mem-list', MEM_OUT.list ?? '')[0]).toBe('2 entries')+ expect(memLines('mem-list', MEM_OUT.list ?? '')[1]).toMatch(/^◆ auth\/beta · 25 B · 2026-10-02/)+ expect(memLines('mem-health', MEM_OUT.health ?? '')).toEqual(['AgentDB available · 2/3 controllers on', '✓ hierarchicalMemory L1', '✓ reasoningBank L1', '· mutationGuard L2'])+ expect(memLines('mem-delete', MEM_OUT.deleteMissing ?? '')).toEqual(['⚠ Key not found: "nonexist" in namespace "notes"'])+ expect(memLines('mem-store', MEM_OUT.stored ?? '')).toEqual(['[INFO] Storing in notes/alpha...', '[OK] Data stored successfully'])+ })++ it('wraps long values at the panel width without losing a character', () => {+ const long = `${'word '.repeat(50)}${'x'.repeat(250)}`+ const lines = wrap(long, 40)++ expect(lines.every(line => line.length <= 40)).toBe(true)+ expect(lines.join('').replace(/\s/g, '')).toBe(long.replace(/\s/g, ''))+ })+})++describe('the probes and the pictures', () => {+ it('memory list keeps each entry newest first; memory stats counts the unread store', () => {+ const spaces = PROBES.find(probe => probe.id === 'namespaces')?.parse(MEM_OUT.list ?? '') as Namespaces | null+ const stats = PROBES.find(probe => probe.id === 'memory')?.parse(MEM_OUT.stats ?? '') as { unread?: number } | null++ expect(spaces?.entries?.map(item => `${item.namespace}/${item.key}:${item.hasVector}`)).toEqual(['auth/beta:true', 'notes/alpha:false'])+ expect(stats?.unread).toBe(2)+ })++ it('recency bins from the oldest write to now; the sparkline and gauge scale to their max', () => {+ const hour = 3_600_000+ const binned = recency([0, hour, hour, 4 * hour], 4 * hour, 4)++ expect(binned).toEqual({ counts: [1, 2, 0, 1], fromMs: 0 })+ expect(sparkline(binned?.counts ?? [])).toBe('▄█·▄')+ expect(recency([], 1)).toBeNull()+ expect(gauge(1, 2, 10)).toBe('█████░░░░░')+ expect(gauge(0, 0, 4)).toBe('░░░░')+ })+})diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.tsindex 39a1187e2b..04c46f6abb 100644--- a/plugins/ruflo-console/tests/views.test.ts+++ b/plugins/ruflo-console/tests/views.test.ts@@ -2,6 +2,7 @@ import type { TestBody } from 'claude-code/testing'import { describe, expect, mock, test } from 'claude-code/testing'import { HIVE_FILES, RAFT_ID, WORKERS } from './fixtures/hive'+import { MEM_OUT } from './fixtures/memory'import { MISSION_OBSERVATION } from './fixtures/missions'import { HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'import { FIND_OUT, LS_GLOBAL } from './fixtures/skills'@@ -21,6 +22,26 @@ const HOME_FILES = {type Engine = Parameters<TestBody>[0]+/** The captured world, with the Memory Lab's reads answered from a two-entry store (auth/beta, notes/alpha). */+function memoryWorld(on: Parameters<TestBody>[1]) {+ const world = worldOf(on, RUFLO_FILES)+ const out = (stdout: string) => ({ exitCode: 0, stdout, stderr: '' })++ world.respond = argv => {+ const line = argv.join(' ')++ if (line.includes('memory stats')) return out(MEM_OUT.stats ?? '')+ if (line.includes('memory list')) return out(MEM_OUT.list ?? '')+ if (line.includes('memory retrieve')) return out(MEM_OUT.retrieve ?? '')+ if (line.includes('memory search')) return out(MEM_OUT.search ?? '')+ if (line.includes('memory_search_unified')) return out(MEM_OUT.unified ?? '')++ return cliAnswer(argv)+ }++ return world+}+/** Opens the console on `view` via /ruflo, waits for its probes, and answers its drawing and its Raster keys. */async function drawn($: Engine, view: string, columns = 110) {await $.command.run(command(view))@@ -223,6 +244,94 @@ describe('views', () => {expect(cost.text).toContain('WARNING · $3.90 of $5.00 (78%)')})+ test('memory lab: gauge, namespace bars, recency, browse, search, entry fields and every group; nothing runs unasked', { options: { boot: false } }, async ($, on) => {+ const world = memoryWorld(on)++ mock.clock(on)+ await $.session.start(SESSION)++ const { text, tree } = await drawn($, 'memory')++ for (const section of ['AGENTDB', 'NAMESPACES', 'RECENCY', 'BROWSE', 'SEARCH', 'ENTRY', 'RESULT', 'LAB · MEMORY', 'LAB · AGENTDB', 'LAB · EMBEDDINGS', 'LAB · MAINTAIN']) expect(text).toContain(`▓▒░ ${section} ░▒▓`)+ expect(text).toContain('1/2 of the newest listed carry a vector')+ expect(text).toContain('2 more rows in .swarm/agentdb-memory.db')+ expect(text).toMatch(/ ◆ beta \.+/)+ expect(text).toMatch(/del \n DELETE \.+/)+ expect(elementsOf(tree, 'Input').map(keyOf)).toEqual(['mem-query', 'mem-namespace', 'mem-key', 'mem-value', 'mem-text'])+ expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['mem-ns-0', 'mem-open-0', 'mem-del-0', 'mem-lab-mem-stats', 'mem-lab-mem-cleanup', 'mem-lab-mem-rabitq-build']))+ // Opening it runs only its two local probes.+ expect(world.runs.filter(argv => /memory (retrieve|search|store|delete|export)|mcp exec -t (memory_|agentdb_|embeddings_)/.test(argv.join(' ')))).toEqual([])+ })++ test('memory lab: view reads at once with one fixed argv; delete and store ask with their argv, then run it on yes', { options: { boot: false } }, async ($, on) => {+ const world = memoryWorld(on)+ const ran = (word: string) => world.runs.filter(argv => argv[5] === word).map(argv => argv.slice(4).join(' '))++ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('memory'))++ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })++ await pane.drawn()+ await pane.press({ key: 'mem-open-0' })++ const opened = textOf(await pane.drawn())++ expect(opened).not.toContain('Confirm:')+ expect(opened).toContain('auth/beta · 25 chars · read 1× · has a vector')+ expect(opened).toContain('jwt refresh tokens rotate')+ expect(ran('retrieve')).toEqual(['memory retrieve --key beta --namespace auth --format json'])++ await pane.press({ key: 'mem-del-0' })++ const asked = textOf(await pane.drawn())++ expect(asked).toContain('runs: ruflo memory delete --key beta --namespace auth --force')+ expect(asked).toContain('DELETES FOR GOOD')+ expect(ran('delete')).toEqual([])+ await pane.press({ key: 'confirm' })+ await pane.drawn()+ expect(ran('delete')).toEqual(['memory delete --key beta --namespace auth --force'])++ await pane.input({ key: 'mem-namespace', text: 'notes', kind: 'change' })+ await pane.input({ key: 'mem-key', text: 'alpha', kind: 'change' })+ await pane.input({ key: 'mem-value', text: 'the quick brown fox', kind: 'submit' })+ expect(textOf(await pane.drawn())).toContain('runs: ruflo memory store --key alpha --value the quick brown fox --namespace notes')+ expect(ran('store')).toEqual([])+ await pane.press({ key: 'confirm' })+ await pane.drawn()+ expect(ran('store')).toEqual(['memory store --key alpha --value the quick brown fox --namespace notes'])+ await pane.unmount()+ })++ test('memory lab: search runs at once from its field and headless, a bad key never reaches the CLI', { options: { boot: false } }, async ($, on) => {+ const world = memoryWorld(on)++ mock.clock(on)+ await $.session.start(SESSION)++ const answer = (await $.command.run(command('run mem-search token rotation'))).text ?? ''++ expect(answer).toContain('0.684 auth/beta jwt refresh tokens rotate')+ expect((await $.command.run(command('run mem-delete auth --force'))).text).not.toMatch(/^Asked/)+ expect((await $.command.run(command('run mem-cleanup'))).text).toBe('Asked: memory cleanup. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.')+ await $.command.run(command('no'))+ await $.command.run(command('memory'))++ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })++ await pane.drawn()+ await pane.press({ key: 'mem-scope' })+ await pane.input({ key: 'mem-query', text: 'token rotation', kind: 'submit' })+ expect(textOf(await pane.drawn())).toContain('0.684 auth/beta [agentdb] jwt refresh tokens rotate')+ expect(world.runs.map(argv => argv.slice(4).join(' ')).filter(line => /search|delete|cleanup/.test(line))).toEqual([+ 'memory search --query token rotation --limit 10 --format json',+ 'mcp exec -t memory_search_unified -p {"query":"token rotation","limit":10}',+ ])+ await pane.unmount()+ })+test('timeline, approvals and events draw from what was seen; the drill-down opens an agent', { options: { boot: false } }, async ($, on) => {const world = worldOf(on, RUFLO_FILES)mock.clock(on)