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

feat(console): memory map in the Memory Lab (ADR-454)

ruv3030d6af513f
diff --git a/plugins/ruflo-console/hooks/data/memmap.ts b/plugins/ruflo-console/hooks/data/memmap.ts
new file mode 100644
index 0000000000..aac9b15feb
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/memmap.ts
@@ -0,0 +1,67 @@
+/**
+ * What the memory map reads: the entries `memory list` prints (with the access count the Memory Lab's own probe leaves out)
+ * and the entries a search named. Pure; the probe is registered by the integrator, never run from here.
+ */
+import { jsonAfter, type Probe } from './cli'
+import { numberOf, recordOf, stringOf } from './parse'
+
+import type { MapEntry } from '../gfx/memmap'
+
+/** Entries the map draws at most: `memory list` is asked for the newest 500, as the Namespaces sample is. */
+export const MAP_LIMIT = 500
+
+/**
+ * `memory list` JSON as map entries. `vector` is set only if a row carries an `embedding` array (the CLI's list does not
+ * today, so the map says 'hash layout'); never invented.
+ */
+export function mapEntriesOf(stdout: string): MapEntry[] | null {
+ const value = jsonAfter(stdout)
+
+ if (!Array.isArray(value)) return null
+
+ return value.slice(0, MAP_LIMIT).flatMap((row): MapEntry[] => {
+ const record = recordOf(row)
+ const key = stringOf(record?.key, 128)
+
+ if (key === undefined) return []
+
+ const accessCount = numberOf(record?.accessCount)
+ const raw = Array.isArray(record?.embedding) ? record.embedding : null
+ const vector = raw !== null && raw.length > 1 && raw.every(item => typeof item === 'number' && Number.isFinite(item)) ? (raw as number[]) : undefined
+
+ return [{ key, namespace: stringOf(record?.namespace, 40) ?? '(none)', hasVector: record?.hasEmbedding === true, ...(accessCount !== undefined && { accessCount }), ...(vector !== undefined && { vector }) }]
+ })
+}
+
+/** Same call as the Namespaces probe, kept apart because the map needs the access count that probe drops. */
+export const memmapProbe: Probe<MapEntry[]> = {
+ id: 'memmap',
+ args: ['memory', 'list', '--format', 'json', '--limit', String(MAP_LIMIT)],
+ views: ['memory'],
+ everyMs: 60_000,
+ timeoutMs: 30_000,
+ parse: mapEntriesOf,
+}
+
+/**
+ * The `namespace/key` of each hit in a search run's printed lines (`0.684 auth/beta [agentdb] text`; the lab prints
+ * a key at most 60 characters, so a key that long matches by prefix in `isHit`). Lines that are not hits yield nothing.
+ */
+export function hitsOf(lines: readonly string[]): Set<string> {
+ const hits = new Set<string>()
+
+ for (const line of lines) {
+ const found = /^\s*(?:\d+\.\d+|n\/a)\s+([^\s/]+)\/(\S+)/.exec(line)
+
+ if (found !== null) hits.add(`${found[1]}/${found[2]}`)
+ }
+
+ return hits
+}
+
+/** Whether a listed entry is among the hits, allowing for the lab's 60-character key cut. */
+export function isHit(hits: ReadonlySet<string>, entry: { namespace: string; key: string }): boolean {
+ const id = `${entry.namespace}/${entry.key}`
+
+ return hits.has(id) || (entry.key.length > 60 && hits.has(`${entry.namespace}/${entry.key.slice(0, 60)}`))
+}
diff --git a/plugins/ruflo-console/hooks/gfx/memmap.ts b/plugins/ruflo-console/hooks/gfx/memmap.ts
new file mode 100644
index 0000000000..23a1ca02c1
--- /dev/null
+++ b/plugins/ruflo-console/hooks/gfx/memmap.ts
@@ -0,0 +1,134 @@
+/**
+ * The memory map: one dot per stored entry on a 2D plane, coloured by namespace, sized by access count. Pure functions of the
+ * entries, the size and the search hits; nothing is drawn that the entries did not carry.
+ *
+ * Where a dot sits is a LAYOUT, not a measurement. `memory list` does not print vectors, so by default each namespace gets a
+ * fixed place on a ring and each entry a hash-scattered place inside its namespace's cluster ('hash'): closeness means
+ * "same namespace" and nothing more. When every entry carries its embedding, a fixed random projection puts similar
+ * vectors nearby ('embedding'). The caller labels the mode; this file never claims more than it did.
+ */
+import { COLOR, Grid, mix } from './raster'
+
+export type MapEntry = { key: string; namespace: string; accessCount?: number; hasVector: boolean; /** The stored embedding, only when a probe read it. */ vector?: readonly number[] }
+
+export type MapMode = 'hash' | 'embedding'
+
+export type MapPoint = { key: string; namespace: string; /** 0..1 across, 0..1 down. */ x: number; y: number; accessCount?: number; hasVector: boolean }
+
+/** One colour per namespace, cycling; chosen to stay apart on dark and light themes. */
+export const SPACE_COLORS = [0x2fa4c9, 0xe0a526, 0x2bb673, 0x8b7cf6, 0xe5534b, 0xd96fb0, 0x7fc8a9, 0xc9b458, 0x5f8bd6, 0xe08a4b] as const
+
+/** 32-bit FNV-1a over a string, then a finaliser so near strings scatter. */
+export function hash32(text: string, seed = 0): number {
+ let h = (0x811c9dc5 ^ seed) >>> 0
+
+ for (let i = 0; i < text.length; i++) {
+ h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0
+ }
+
+ h ^= h >>> 15
+ h = Math.imul(h, 0x2c1b3c6d) >>> 0
+ h ^= h >>> 12
+
+ return h >>> 0
+}
+
+/** A hash as a number in [0, 1). */
+const unit = (text: string, seed: number): number => hash32(text, seed) / 0x1_0000_0000
+
+/** Namespaces in a fixed order (by name), so a namespace keeps its colour and its place whatever else is listed. */
+export const spacesOf = (entries: readonly { namespace: string }[]): string[] => [...new Set(entries.map(entry => entry.namespace))].sort()
+
+/** A vector onto the plane through two fixed ±1 hyperplanes seeded by the dimension index; tanh keeps it inside 0..1. */
+export function projectVector(vector: readonly number[]): { x: number; y: number } {
+ let a = 0
+ let b = 0
+
+ vector.forEach((value, i) => {
+ a += (hash32(String(i), 1) & 1 ? 1 : -1) * value
+ b += (hash32(String(i), 2) & 1 ? 1 : -1) * value
+ })
+
+ const scale = Math.sqrt(Math.max(1, vector.length)) / 2
+
+ return { x: 0.5 + 0.5 * Math.tanh(a / scale), y: 0.5 + 0.5 * Math.tanh(b / scale) }
+}
+
+/** Every entry is embedded and carries its vector: the only case the map may call 'embedding'. */
+export const modeOf = (entries: readonly MapEntry[]): MapMode => (entries.length > 0 && entries.every(entry => entry.vector !== undefined && entry.vector.length > 1) ? 'embedding' : 'hash')
+
+/** The plane: positions in 0..1 for each entry, by `modeOf`. Deterministic: the same entries land in the same places. */
+export function layout(entries: readonly MapEntry[]): { mode: MapMode; points: MapPoint[] } {
+ const mode = modeOf(entries)
+ const spaces = spacesOf(entries)
+ const n = spaces.length
+ // Ring radius and cluster radius, in -1..1 units: clusters of neighbouring namespaces on the ring just touch.
+ const ring = n === 1 ? 0 : 0.6
+ const spread = n === 1 ? 0.85 : Math.min(0.4, 0.9 * ring * Math.sin(Math.PI / n))
+
+ const points = entries.map((entry): MapPoint => {
+ const meta = { key: entry.key, namespace: entry.namespace, hasVector: entry.hasVector, ...(entry.accessCount !== undefined && { accessCount: entry.accessCount }) }
+
+ if (mode === 'embedding') return { ...meta, ...projectVector(entry.vector as readonly number[]) }
+
+ const angle = (Math.max(0, spaces.indexOf(entry.namespace)) / Math.max(1, n)) * Math.PI * 2 - Math.PI / 2
+ const around = unit(entry.key, 3) * Math.PI * 2
+ const reach = Math.sqrt(unit(entry.key, 4)) * spread
+
+ return { ...meta, x: (Math.cos(angle) * ring + Math.cos(around) * reach + 1) / 2, y: (Math.sin(angle) * ring + Math.sin(around) * reach + 1) / 2 }
+ })
+
+ return { mode, points }
+}
+
+/** A dot's glyph by how often the entry was read: a speck for never or unknown, then growing discs. */
+export function glyphOf(accessCount: number | undefined): string {
+ const reads = accessCount ?? 0
+
+ return reads <= 0 ? '·' : reads < 3 ? '•' : reads < 10 ? '●' : '◉'
+}
+
+export const MAP_ROWS = 14
+
+/**
+ * The map. With hits, those entries are drawn bright as ◆ with a white ring cell beside them and every other dot is dimmed, so a
+ * search reads as a lit set; with none, all dots are full colour. The busiest entry of a cell wins it, a hit always wins.
+ */
+export function memmapPicture(points: readonly MapPoint[], spaces: readonly string[], hits: ReadonlySet<string>, columns: number, rows = MAP_ROWS): Grid {
+ const grid = new Grid(columns, rows)
+ const searching = hits.size > 0
+ const best = new Map<number, { rank: number; point: MapPoint }>()
+ const rings: { x: number; y: number; color: number }[] = []
+
+ for (const point of points) {
+ const cx = Math.max(0, Math.min(columns - 1, Math.floor(point.x * columns)))
+ const cy = Math.max(0, Math.min(rows - 1, Math.floor(point.y * rows)))
+ const rank = (hits.has(`${point.namespace}/${point.key}`) ? 1_000_000 : 0) + (point.accessCount ?? 0)
+ const held = best.get(cy * columns + cx)
+
+ if (held === undefined || rank > held.rank) best.set(cy * columns + cx, { rank, point })
+ }
+
+ for (const [at, { rank, point }] of best) {
+ const x = at % columns
+ const y = Math.floor(at / columns)
+ const color = SPACE_COLORS[Math.max(0, spaces.indexOf(point.namespace)) % SPACE_COLORS.length] as number
+
+ if (rank >= 1_000_000) {
+ grid.set(x, y, '◆', 0xffffff)
+ rings.push({ x, y, color })
+ } else {
+ grid.set(x, y, glyphOf(point.accessCount), searching ? mix(color, 0x000000, 0.65) : color)
+ }
+ }
+
+ // Rings go only into cells nothing else holds, so a hit never overwrites a neighbour.
+ for (const { x, y, color } of rings) {
+ if (grid.glyph(x - 1, y) === 0x20) grid.set(x - 1, y, '(', color)
+ if (grid.glyph(x + 1, y) === 0x20) grid.set(x + 1, y, ')', color)
+ }
+
+ if (points.length === 0) grid.text(0, 0, 'no entries', COLOR.dim)
+
+ return grid
+}
diff --git a/plugins/ruflo-console/hooks/views/memmap.ts b/plugins/ruflo-console/hooks/views/memmap.ts
new file mode 100644
index 0000000000..6bda968d0a
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/memmap.ts
@@ -0,0 +1,132 @@
+import type { RenderElement } from 'claude-code'
+
+import type { Namespaces } from '../data/cli'
+import { hitsOf, isHit } from '../data/memmap'
+import { layout, MAP_ROWS, memmapPicture, SPACE_COLORS, spacesOf, type MapEntry, type MapPoint } from '../gfx/memmap'
+import type { Grid } from '../gfx/raster'
+import type { State } from '../state'
+import { clip, count, live, row, rule, text, type Ctx } from './common'
+import { note } from './subhead'
+
+const hex = (color: number): string => `#${color.toString(16).padStart(6, '0')}`
+
+/** The entries the map draws: the map's own probe (has read counts), else the Namespaces sample (no counts, so every dot is a speck). */
+export function mapEntriesFrom(state: State): { entries: MapEntry[]; hasCounts: boolean } {
+ const own = live<MapEntry[]>(state.probes.get('memmap'))
+
+ if (own !== null) return { entries: own, hasCounts: true }
+
+ const sample = live<Namespaces>(state.probes.get('namespaces'))
+
+ return { entries: (sample?.entries ?? []).map(entry => ({ key: entry.key, namespace: entry.namespace, hasVector: entry.hasVector })), hasCounts: false }
+}
+
+/** The last memory search's hits as the `namespace/key` of entries on the map. */
+function litOf(state: State, points: readonly MapPoint[]): { lit: Set<string>; named: number } {
+ const result = state.lab.result
+ const hits = result !== null && result.ok && (result.id === 'mem-search' || result.id === 'mem-unified') ? hitsOf(result.lines) : new Set<string>()
+ const lit = new Set(points.filter(point => isHit(hits, point)).map(point => `${point.namespace}/${point.key}`))
+
+ return { lit, named: hits.size }
+}
+
+/** The map for one frame, by Raster key; none while there is nothing to draw (the view then says so). */
+export function memmapPictures(state: State, columns: number): Map<string, Grid> {
+ const { entries } = mapEntriesFrom(state)
+ const pictures = new Map<string, Grid>()
+
+ if (entries.length === 0) return pictures
+
+ const { points } = layout(entries)
+
+ pictures.set('memmap', memmapPicture(points, spacesOf(entries), litOf(state, points).lit, Math.max(20, Math.min(columns, 100)), MAP_ROWS))
+
+ return pictures
+}
+
+/** The frame's mounted map if the integrator wired one, else the same picture drawn here (static: the map does not animate). */
+function mapPicture(ctx: Ctx, entries: number, spaces: number): RenderElement {
+ const grid = ctx.pictures.get('memmap') ?? memmapPictures(ctx.state, ctx.columns - 2).get('memmap')
+
+ return grid === undefined || ctx.kit.Raster === undefined ? text(ctx, `the map needs a terminal that draws pictures: ${entries} entries in ${spaces} namespaces`, { dimColor: true }) : ctx.kit.Raster(grid.toRaster('memmap'))
+}
+
+/** The memory map section: the picture, what its places mean (said plainly), the namespace colours and what the last search lit. */
+export function memmapRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const { entries, hasCounts } = mapEntriesFrom(state)
+
+ if (entries.length === 0) {
+ return [rule(ctx, 'Memory map'), text(ctx, sourceFallback(state, nowMs), { dimColor: true })]
+ }
+
+ const { mode, points } = layout(entries)
+ const spaces = spacesOf(entries)
+ const { lit, named } = litOf(state, points)
+ const result = state.lab.result
+ const searched = result !== null && (result.id === 'mem-search' || result.id === 'mem-unified')
+ const rows: RenderElement[] = [
+ rule(ctx, 'Memory map', `${entries.length} entries · ${spaces.length} namespace${spaces.length === 1 ? '' : 's'} · ${mode === 'embedding' ? 'embedding layout' : 'hash layout'}`),
+ mapPicture(ctx, entries.length, spaces.length),
+ ]
+
+ // Namespace colours, in rows no wider than the pane: the entry count is the listed sample's, like the bars above.
+ const perSpace = new Map<string, number>()
+
+ for (const entry of entries) perSpace.set(entry.namespace, (perSpace.get(entry.namespace) ?? 0) + 1)
+
+ let line: RenderElement[] = []
+ let used = 0
+ let index = 0
+
+ for (const space of spaces) {
+ const label = ` ● ${clip(space, 20)} ${count(perSpace.get(space))} `
+
+ if (used + label.length > ctx.columns - 4 && line.length > 0) {
+ rows.push(row(ctx, line, `memmap-key-${index}`))
+ line = []
+ used = 0
+ }
+
+ line.push(ctx.kit.Text({ color: hex(SPACE_COLORS[index % SPACE_COLORS.length] as number), children: label }))
+ used += label.length
+ index += 1
+ }
+
+ if (line.length > 0) rows.push(row(ctx, line, `memmap-key-${index}`))
+
+ rows.push(note(ctx, hasCounts ? 'dot size is how often the entry was read: · never • 1-2 ● 3-9 ◉ 10 or more' : 'read counts n/a (the map’s own list is not loaded yet): every dot is drawn as a speck'))
+
+ rows.push(
+ note(
+ ctx,
+ mode === 'embedding'
+ ? 'layout: each entry’s stored embedding projected to 2D by a fixed random projection; near means similar, but a 2D projection loses most of the distance'
+ : 'layout: NOT similarity. `memory list` does not print vectors, so each namespace has a fixed place and each entry a hash of its key scatters it inside; near means the same namespace only',
+ ),
+ )
+
+ rows.push(
+ text(
+ ctx,
+ searched
+ ? lit.size > 0
+ ? ` ◆ ${lit.size} of ${entries.length} listed entries lit by “${clip(state.memoryLab.query, 40)}”${named > lit.size ? ` · ${named - lit.size} more hit${named - lit.size === 1 ? ' is' : 's are'} outside the listed sample` : ''}`
+ : ` the last search named ${named === 0 ? 'no entries' : `${named} entr${named === 1 ? 'y' : 'ies'}, none in the listed sample`}: nothing to light`
+ : ' search below (Enter) to light the entries it finds',
+ lit.size > 0 ? {} : { dimColor: true },
+ ),
+ )
+
+ return rows
+}
+
+/** Why there is nothing to map: the probe's own state, or an empty store. */
+function sourceFallback(state: State, nowMs: number): string {
+ const probe = state.probes.get('memmap') ?? state.probes.get('namespaces')
+
+ if (probe === undefined || (probe.value === null && probe.error === null)) return ' reading `memory list` …'
+ if (probe.error !== null && probe.value === null) return ` n/a: ${probe.error} (${Math.round((nowMs - (probe.errorAtMs ?? nowMs)) / 1000)}s ago)`
+
+ return ' nothing stored yet: store an entry or import your Claude memories, and it appears here'
+}
diff --git a/plugins/ruflo-console/hooks/views/memory.ts b/plugins/ruflo-console/hooks/views/memory.ts
index 965bf70be2..bc68fefb70 100644
--- a/plugins/ruflo-console/hooks/views/memory.ts
+++ b/plugins/ruflo-console/hooks/views/memory.ts
@@ -4,6 +4,7 @@ import type { MemoryEntry, MemoryStats, Namespaces } from '../data/cli'
import { gauge, recency, sparkline } from '../memory-lines'
import { agentdbModRows } from './agentdb-mod'
import { ago, button, clip, col, count, kv, live, row, rule, sourceLine, text, THEME, type Ctx } from './common'
+import { memmapRows } from './memmap'
import { areaPanel, memoryLabRows } from './memory-lab'
/** Entries in the browse list at once; ◂ ▸ page the rest. */
@@ -141,5 +142,5 @@ export function memoryView(ctx: Ctx): RenderElement {
const spaces = live<Namespaces>(ctx.state.probes.get('namespaces'))
const entries = spaces?.entries ?? []
- return col(ctx, [...storeRows(ctx, memory, spaces), ...agentdbModRows(ctx), ...namespaceRows(ctx, spaces), ...timelineRows(ctx, entries), ...browseRows(ctx, entries), ...areaPanel(ctx, 'browse'), ...memoryLabRows(ctx), text(ctx, 'spend, budget gauge and burn: Cost (9)', { dimColor: true })], 'memory')
+ return col(ctx, [...storeRows(ctx, memory, spaces), ...agentdbModRows(ctx), ...namespaceRows(ctx, spaces), ...memmapRows(ctx), ...timelineRows(ctx, entries), ...browseRows(ctx, entries), ...areaPanel(ctx, 'browse'), ...memoryLabRows(ctx), text(ctx, 'spend, budget gauge and burn: Cost (9)', { dimColor: true })], 'memory')
}
diff --git a/plugins/ruflo-console/tests/memmap.spec.ts b/plugins/ruflo-console/tests/memmap.spec.ts
new file mode 100644
index 0000000000..eb1c615088
--- /dev/null
+++ b/plugins/ruflo-console/tests/memmap.spec.ts
@@ -0,0 +1,174 @@
+/**
+ * The memory map's pure parts under vitest: the layout (deterministic, honest about its mode), the glyphs, the picture's
+ * hit lighting, the readers for `memory list` and search lines, and the view's empty and filled states. Run with
+ * npx vitest run plugins/ruflo-console/tests/memmap.spec.ts
+ */
+import { describe, expect, it } from 'vitest'
+
+import { memmapProbe, hitsOf, isHit, mapEntriesOf } from '../hooks/data/memmap'
+import { glyphOf, hash32, layout, memmapPicture, modeOf, projectVector, spacesOf, type MapEntry } from '../hooks/gfx/memmap'
+import { memLines } from '../hooks/memory-lines'
+import { newState } from '../hooks/state'
+import type { Ctx } from '../hooks/views/common'
+import { memmapPictures, memmapRows } from '../hooks/views/memmap'
+import { MEM_OUT } from './fixtures/memory'
+
+const entries = (): MapEntry[] => [
+ ...Array.from({ length: 12 }, (_, i) => ({ key: `tok-${i}`, namespace: 'auth', hasVector: true, accessCount: i })),
+ ...Array.from({ length: 12 }, (_, i) => ({ key: `note-${i}`, namespace: 'notes', hasVector: false, accessCount: 0 })),
+]
+
+describe('the layout', () => {
+ it('is deterministic and keeps every point inside the plane', () => {
+ const a = layout(entries())
+ const b = layout(entries())
+
+ expect(a).toEqual(b)
+ for (const point of a.points) {
+ expect(point.x).toBeGreaterThanOrEqual(0)
+ expect(point.x).toBeLessThanOrEqual(1)
+ expect(point.y).toBeGreaterThanOrEqual(0)
+ expect(point.y).toBeLessThanOrEqual(1)
+ }
+ })
+
+ it('says hash unless every entry carries a vector, and clusters a namespace together in hash mode', () => {
+ const { mode, points } = layout(entries())
+ const centre = (space: string) => {
+ const own = points.filter(point => point.namespace === space)
+
+ return { x: own.reduce((sum, p) => sum + p.x, 0) / own.length, y: own.reduce((sum, p) => sum + p.y, 0) / own.length }
+ }
+ const [a, n] = [centre('auth'), centre('notes')]
+
+ expect(mode).toBe('hash')
+ expect(Math.hypot(a.x - n.x, a.y - n.y)).toBeGreaterThan(0.3)
+ expect(modeOf([{ key: 'a', namespace: 'x', hasVector: true, vector: [1, 2, 3] }])).toBe('embedding')
+ expect(modeOf([{ key: 'a', namespace: 'x', hasVector: true, vector: [1, 2, 3] }, { key: 'b', namespace: 'x', hasVector: true }])).toBe('hash')
+ expect(modeOf([])).toBe('hash')
+ })
+
+ it('projects equal vectors to equal places and near vectors nearer than opposite ones', () => {
+ const v = Array.from({ length: 64 }, (_, i) => Math.sin(i))
+ const near = v.map((x, i) => x + 0.01 * Math.cos(i))
+ const far = v.map(x => -x)
+ const d = (p: { x: number; y: number }, q: { x: number; y: number }) => Math.hypot(p.x - q.x, p.y - q.y)
+
+ expect(projectVector(v)).toEqual(projectVector(v))
+ expect(d(projectVector(v), projectVector(near))).toBeLessThan(d(projectVector(v), projectVector(far)))
+ })
+
+ it('hashes stably, and orders namespaces by name so colour and place do not depend on the listing', () => {
+ expect(hash32('auth/beta')).toBe(hash32('auth/beta'))
+ expect(hash32('a')).not.toBe(hash32('b'))
+ expect(spacesOf([{ namespace: 'z' }, { namespace: 'a' }, { namespace: 'z' }])).toEqual(['a', 'z'])
+ })
+})
+
+describe('the picture', () => {
+ const draw = (hits: Set<string>) => {
+ const { points } = layout(entries())
+
+ return memmapPicture(points, spacesOf(entries()), hits, 60, 14)
+ }
+ const glyphs = (grid: ReturnType<typeof draw>) => Array.from({ length: grid.columns * grid.rows }, (_, i) => String.fromCodePoint(grid.cells[i * 3] as number))
+
+ it('sizes a dot by reads', () => {
+ expect([undefined, 0, 1, 2, 3, 9, 10, 400].map(glyphOf)).toEqual(['·', '·', '•', '•', '●', '●', '◉', '◉'])
+ })
+
+ it('lights only the entries it was told, ringed, and draws none when nothing hit', () => {
+ expect(glyphs(draw(new Set())).includes('◆')).toBe(false)
+
+ const lit = glyphs(draw(new Set(['auth/tok-3', 'notes/note-5'])))
+
+ expect(lit.filter(glyph => glyph === '◆').length).toBeGreaterThanOrEqual(1)
+ expect(lit.filter(glyph => glyph === '◆').length).toBeLessThanOrEqual(2)
+ expect(lit.includes('(')).toBe(true)
+ })
+
+ it('draws an honest note and no dots for an empty store', () => {
+ const grid = memmapPicture([], [], new Set(), 30, 14)
+
+ expect(glyphs(grid).join('').startsWith('no entries')).toBe(true)
+ })
+})
+
+describe('the readers', () => {
+ it('reads the access count and namespace from `memory list` and never invents a vector', () => {
+ const list = mapEntriesOf(MEM_OUT.list as string)
+
+ expect(list).toEqual([
+ { key: 'beta', namespace: 'auth', hasVector: true, accessCount: 0 },
+ { key: 'alpha', namespace: 'notes', hasVector: false, accessCount: 0 },
+ ])
+ expect(mapEntriesOf('not json')).toBeNull()
+ expect(mapEntriesOf(JSON.stringify([{ key: 'k', namespace: 'n', accessCount: 4, embedding: [0.1, 0.2] }]))?.[0]?.vector).toEqual([0.1, 0.2])
+ })
+
+ it('asks for the same bounded list as the Namespaces sample, on the memory view only', () => {
+ expect(memmapProbe.args).toEqual(['memory', 'list', '--format', 'json', '--limit', '500'])
+ expect(memmapProbe.views).toEqual(['memory'])
+ })
+
+ it('finds the hits the lab printed, and nothing in a non-hit line', () => {
+ const hits = hitsOf(memLines('mem-search', MEM_OUT.search as string))
+
+ expect([...hits]).toEqual(['auth/beta'])
+ expect(hitsOf(['1 hit · semantic', '(no matches)', 'degraded: no model'])).toEqual(new Set())
+ expect(isHit(new Set(['auth/beta']), { namespace: 'auth', key: 'beta' })).toBe(true)
+ expect(isHit(new Set(['auth/beta']), { namespace: 'notes', key: 'beta' })).toBe(false)
+ expect(isHit(new Set([`n/${'k'.repeat(60)}`]), { namespace: 'n', key: 'k'.repeat(90) })).toBe(true)
+ })
+})
+
+type El = { kind: string; props: Record<string, unknown> }
+const make = (kind: string) => (props: Record<string, unknown>): El => ({ kind, props })
+const kit = { Box: make('Box'), Text: make('Text'), Button: make('Button'), Input: make('Input'), Raster: make('Raster') }
+const act = new Proxy({}, { get: () => () => undefined }) as unknown as Ctx['act']
+const flat = (node: unknown): El[] => {
+ if (Array.isArray(node)) return node.flatMap(flat)
+ if (typeof node !== 'object' || node === null) return []
+ const el = node as El
+ const children = el.props.children
+
+ return [el, ...(Array.isArray(children) ? children.flatMap(flat) : flat(children))]
+}
+const texts = (nodes: unknown): string[] => flat(nodes).filter(el => el.kind === 'Text').map(el => String(el.props.children))
+const ctxOf = (state: ReturnType<typeof newState>): Ctx => ({ kit, state, act, columns: 100, nowMs: 5_000, pictures: new Map() }) as unknown as Ctx
+
+describe('the view', () => {
+ it('says what it is waiting for, not a blank map, when nothing is listed', () => {
+ const shown = texts(memmapRows(ctxOf(newState({ boot: false })))).join('\n')
+
+ expect(shown).toContain('Memory map')
+ expect(shown).toContain('reading `memory list`')
+ expect(flat(memmapRows(ctxOf(newState({ boot: false })))).some(el => el.kind === 'Raster')).toBe(false)
+ })
+
+ it('draws a raster, labels the hash layout as not similarity, and counts what the last search lit', () => {
+ const state = newState({ boot: false })
+
+ state.probes.set('memmap', { value: entries(), error: null, okAtMs: 4_000 } as never)
+ state.memoryLab.query = 'token'
+ state.lab.result = { id: 'mem-search', label: 'search', ok: true, exitCode: 0, lines: ['2 hits · semantic', '0.912 auth/tok-3 jwt', '0.500 auth/tok-4 jwt', '0.400 other/zzz elsewhere'], atMs: 4_500 }
+
+ const nodes = memmapRows(ctxOf(state))
+ const shown = texts(nodes).join('\n')
+
+ expect(flat(nodes).filter(el => el.kind === 'Raster')).toHaveLength(1)
+ expect(shown).toContain('hash layout')
+ expect(shown).toContain('NOT similarity')
+ expect(shown).toContain('2 of 24 listed entries lit by “token”')
+ expect(shown).toContain('1 more hit is outside the listed sample')
+ expect(memmapPictures(state, 100).get('memmap')?.columns).toBe(100)
+ })
+
+ it('falls back to the Namespaces sample and says read counts are n/a', () => {
+ const state = newState({ boot: false })
+
+ state.probes.set('namespaces', { value: { sampled: 1, byName: [{ name: 'auth', count: 1 }], entries: [{ key: 'beta', namespace: 'auth', hasVector: true }] }, error: null, okAtMs: 4_000 } as never)
+
+ expect(texts(memmapRows(ctxOf(state))).join('\n')).toContain('read counts n/a')
+ })
+})
diff --git a/v3/docs/adr/ADR-454-memory-map.md b/v3/docs/adr/ADR-454-memory-map.md
new file mode 100644
index 0000000000..dbecc40dc1
--- /dev/null
+++ b/v3/docs/adr/ADR-454-memory-map.md
@@ -0,0 +1,43 @@
+# ADR 454: The memory map: a 2D picture of the AgentDB store in the Memory Lab
+
+Status: Accepted
+
+Date: 2026-10-05
+
+Builds on: ADR-445 (AgentDB as a mod); the Memory Lab (`views/memory.ts`, `memory-lab.ts`)
+
+## 1. Context
+
+The Memory Lab lists AgentDB's counts, a bar per namespace, a recency strip and a paged browse list. Nothing shows the store as a whole: how entries group, which are read often, and where a search lands. A picture does that at a glance, but a 2D picture of a vector store invites the reading "near means similar", and that reading is only true when the positions come from the embeddings.
+
+What the console can read today, without a new network call or a read of the database files: `memory list --format json` prints, per entry, `key`, `namespace`, `size`, `accessCount`, `updatedAt`, `hasEmbedding`. It does not print the embedding vector. Search output (`memory search`, unified search) prints hits as `score namespace/key`.
+
+## 2. Decision
+
+Add a **Memory map** section to the Memory view, under the namespace bars.
+
+- **Positions are a layout, labelled as one.** The stored embedding is not readable through `memory list`, so the default layout is `hash`: namespaces sit on a fixed ring ordered by name, and each entry is scattered inside its namespace's cluster by a hash of its key (FNV-1a). Near means the same namespace and nothing more. The section says so in words ("layout: NOT similarity") and its rule reads `hash layout`.
+- **Embedding layout exists, but only on real vectors.** If every listed entry carries an `embedding` array, positions come from a fixed two-hyperplane random projection (`projectVector`) and the label reads `embedding layout`; one missing vector drops the whole map back to `hash`. No current probe supplies vectors, so today the map is always `hash`; the path is there so a future read-only vector probe lights it with no view change.
+- **Colour is the namespace** (stable by sorted name, ten colours cycling), with a legend row per width showing each namespace's listed count.
+- **Dot size is the access count**: `·` never or unknown, `•` 1-2, `●` 3-9, `◉` 10 or more. When the map's own list is not loaded and it falls back to the Namespaces sample (which drops `accessCount`), every dot is a speck and the legend says "read counts n/a".
+- **Search lights its hits.** After a memory or unified search, entries named in the last result's lines (parsed from `score namespace/key`) are drawn as a white `◆` with `( )` beside it and every other dot is dimmed. The line below the map says how many of the listed entries lit and how many hits fall outside the listed sample (the map covers the newest 500 entries, like the namespace bars).
+- **Empty states are honest**: `reading memory list …`, the probe's error, or `nothing stored yet`; no placeholder dots.
+
+Data comes only from `memory list` (one new probe, `memmap`, same argv as the Namespaces probe plus the `accessCount` it drops) and from the last Lab result already in state. No private memory content is read: keys and namespaces are already shown by the browse list. No mutation is added.
+
+Files: `gfx/memmap.ts` (layout, projection, picture), `data/memmap.ts` (probe, readers), `views/memmap.ts` (section), the one-line mount in `views/memory.ts`, `tests/memmap.spec.ts`.
+
+## 3. Consequences
+
+- The picture can mislead only through its layout; the label is on the rule and in a note, and the embedding label cannot appear without vectors.
+- A second `memory list --limit 500` every 60 s while the Memory view is open (the same cost as the Namespaces probe). The integrator may instead add `accessCount` to `MemoryEntry` and the Namespaces parser and drop the `memmap` probe; the view already falls back to the sample.
+- Two dots in one cell show the busier one (or a hit); with 500 entries on a ~100x14 plane some overlap is unavoidable.
+- A search hit whose key is over 60 characters is matched by the lab's 60-character prefix; hits from another store (unified search over the second DB) are counted as outside the sample, not drawn.
+
+## 4. Test and benchmark plan
+
+`tests/memmap.spec.ts`: layout determinism and bounds, namespace clusters apart, mode rules (vectors on all or hash), projection near/far, hash stability, glyph tiers, hit lighting and ringing, empty picture, `memory list` and search-line readers against the captured fixtures, probe argv, and the view's empty, filled and fallback states. Benchmark: layout and picture for 500 entries should take well under a frame (a few ms); not gated in CI.
+
+## 5. Rollback
+
+Delete the `...memmapRows(ctx)` item in `views/memory.ts` and the new files; unregister the `memmap` probe. Nothing persists and no state shape changes.