Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Memories: Sense of Self is the pane (#1154)

Dee59c009ff7719
diff --git a/desktop/assets/store/covers/memories.jpg b/desktop/assets/store/covers/memories.jpg
index 72e5a47a9..f576aade7 100644
Binary files a/desktop/assets/store/covers/memories.jpg and b/desktop/assets/store/covers/memories.jpg differ
diff --git a/desktop/assets/store/covers/sources.json b/desktop/assets/store/covers/sources.json
index 7765d19a8..5e07c4260 100644
--- a/desktop/assets/store/covers/sources.json
+++ b/desktop/assets/store/covers/sources.json
@@ -322,7 +322,7 @@
"asset": "memories.jpg",
"source": "desktop/tool/store_artwork/capture-covers.mjs memories",
"credit": "OpenHarness example",
- "sha256": "def5e19216c090cde07a51a6236ed326920d12b4763053012263446733bffb39",
+ "sha256": "fee78a02f05ce205ec1d4d47159ee41ad10d1a6f1ccca586a30f5a991b140bf5",
"capture": "Synthetic memories and sessions in an empty home directory. No user account, machines, or activity were read.",
"harness": "autonomous/memories"
},
diff --git a/desktop/lib/store/store_cover_art.dart b/desktop/lib/store/store_cover_art.dart
index 2f1174e67..565a2a789 100644
--- a/desktop/lib/store/store_cover_art.dart
+++ b/desktop/lib/store/store_cover_art.dart
@@ -289,7 +289,7 @@ const storeCoverArt = <String, StoreCoverArt>{
),
'autonomous/memories': StoreCoverArt(
asset: 'assets/store/covers/memories.jpg',
- description: 'Memories’ About You and agent notes from an illustrative demo home',
+ description: 'About You as a tree of light, rooted in an illustrative person’s memories',
imageSize: Size(1080, 720),
viewport: Rect.fromLTWH(0, 0, 1080, 540),
background: Color(0xff0e0f11),
diff --git a/desktop/tool/store_artwork/capture-covers.mjs b/desktop/tool/store_artwork/capture-covers.mjs
index e8663c010..5f1808bf8 100644
--- a/desktop/tool/store_artwork/capture-covers.mjs
+++ b/desktop/tool/store_artwork/capture-covers.mjs
@@ -127,24 +127,44 @@ try {
// An invented person's home: what five agents remember and four months of messages, all made up here.
const home = await mkdtemp(join(tmpdir(), 'memories-cover-'));
const put = async (path, text) => { await mkdir(dirname(join(home, path)), { recursive: true }); await writeFile(join(home, path), text); };
+ // Projects, and what Claude Code saved in each: [file, type, description, body].
const notes = {
payments: [
['short-answers', 'feedback', 'Wants replies under five lines', 'Keep replies short; lead with the answer.'],
- ['retries', 'project', 'Webhooks retry with backoff', 'Webhook retries back off to one hour, then page.'],
- ['ledger', 'reference', 'Where the ledger docs live', 'The ledger design is in docs/ledger.md.'],
+ ['merge-when-green', 'feedback', 'Lands pull requests once CI passes', 'Merge green pull requests without asking.'],
+ ['webhook-retries', 'project', 'Retries back off to one hour', 'Webhook retries back off to one hour, then page.'],
],
widgets: [
['tests-first', 'feedback', 'Run the tests before saying done', 'Run `make test` before calling anything done.'],
- ['renderer', 'project', 'The legacy renderer is going away', 'New work targets the grid renderer only.'],
+ ['screenshots-for-ui', 'feedback', 'Reviews UI from screenshots', 'Send a screenshot with every UI change.'],
+ ['legacy-renderer', 'project', 'The legacy renderer is going away', 'New work targets the grid renderer only.'],
],
'docs-site': [
- ['plain-words', 'user', 'Writes docs in plain words', 'Prefers short sentences and no jargon.'],
- ['deploys', 'project', 'Docs deploy from main', 'Every merge to main publishes the site.'],
+ ['plain-words', 'user', 'Writes docs in plain words', 'Short sentences and no jargon in anything a reader sees.'],
+ ['deploys-from-main', 'project', 'Every merge to main publishes the site', 'The docs site deploys on every merge to main.'],
],
'mobile-app': [
- ['screenshots', 'feedback', 'Reviews UI from screenshots', 'Send a screenshot with every UI change.'],
+ ['mockup-first', 'feedback', 'Agree on a mockup before UI code', 'Show a mockup and agree on it before writing UI code.'],
['release-train', 'project', 'Releases go out on Tuesdays', 'Never release on a Friday.'],
],
+ infra: [
+ ['no-weekend-deploys', 'feedback', 'Merge on weekends, deploy on Monday', 'Merges may land over the weekend; deploys wait for Monday.'],
+ ],
+ 'ml-pipeline': [
+ ['measure-first', 'feedback', 'Wants numbers before a change', 'Measure before and after any performance change.'],
+ ['ranker-evals', 'project', 'The eval set is frozen per quarter', 'The ranker eval set is frozen each quarter.'],
+ ],
+ 'design-system': [
+ ['keyboard-first', 'feedback', 'Every action needs a key', 'Every action must be reachable from the keyboard.'],
+ ['terminal-taste', 'user', 'Likes the feel of vim, tmux and fzf', 'Tools should feel quiet, fast and typed.'],
+ ],
+ cli: [
+ ['small-core', 'feedback', 'Keep the core small and stable', 'Features go in services the core can run without.'],
+ ['why-comments', 'feedback', 'Comments say why, not what', 'Comments name the incident or the measurement behind the code.'],
+ ],
+ website: [
+ ['speed-matters', 'feedback', 'Pages should feel instant', 'Every page should feel instant; measure the first paint.'],
+ ],
};
for (const [project, list] of Object.entries(notes)) {
await mkdir(join(home, 'code', project), { recursive: true });
@@ -157,8 +177,8 @@ try {
await put('.codex/memories/memory_summary.md', 'Prefers small pull requests with one change each.\n');
await put('.codex/memories/MEMORY.md', '# Handbook\n\n## Testing\nRun `make test` first.\n\n## Reviews\nOne change per pull request.\n');
await put('.grok/config.toml', '[memory]\nenabled = true\n');
- await put('.grok/memory-v2/global/topics/style.md', '# Code style\n\nTwo-space indentation everywhere.\n');
- await put('.hermes/memories/USER.md', 'Prefers terse answers.\n§\nWorks late in the evening.\n');
+ await put('.grok/memory-v2/global/topics/code-style.md', '# Code style\n\nTwo-space indentation everywhere.\n');
+ await put('.hermes/memories/USER.md', 'Prefers terse answers.\n§\nHands work off overnight and reads a summary in the morning.\n');
await put('.gemini/GEMINI.md', '## Gemini Added Memories\n- Prefers tabs in Go files\n- Lives in UTC+1\n');
const asks = ['keep it short, tldr only', 'run the tests before you say done', 'one change per pull request',
'why does the retry back off that far?', 'walk me through the ledger migration', 'ship it once CI is green',
@@ -179,20 +199,44 @@ try {
}
sessionIndex(join(home, '.harness', 'cli', 'data'), { now, turns });
const env = { MEMORIES_HOME: join(home, '.harness', 'memory') };
- writeAbout(env.MEMORIES_HOME, ['# About you', '', '## How you work',
- '- Works across Claude Code and Codex, most days of the week. [asks:480]',
- '- Asks "why" before agreeing to a design. [asks:41]', '',
- '## What you want from agents',
- '- Short answers that lead with the result. [claude:short-answers.md, hermes:USER.md]',
- '- Tests run before anything is called done. [claude:tests-first.md, codex:MEMORY.md]',
- '- One change per pull request. [codex:memory_summary.md]', '',
- '## Taste', '- Plain words in docs; no jargon. [claude:plain-words.md]', ''].join('\n'), { gen: now, now });
+ const line = (text, ...sources) => `- ${text} [${sources.map((s) => s.includes(':') ? s : `claude:${s}.md`).join(', ')}]`;
+ writeAbout(env.MEMORIES_HOME, ['# About you', '', 'Built from 509 of your messages over the last 120 days.', '',
+ '## How you work',
+ line('Works in Claude Code and Codex side by side, most days of the week.', 'asks:480'),
+ line('Gives UI feedback with screenshots.', 'screenshots-for-ui', 'asks:41'),
+ line('Hands work off overnight and reads a summary in the morning.', 'hermes:USER.md', 'asks:22'),
+ line('Measures before and after any performance change.', 'measure-first'),
+ '', '## What you want from agents',
+ line('Short answers that lead with the result.', 'short-answers', 'hermes:USER.md', 'asks:98'),
+ line('Tests run before anything is called done.', 'tests-first', 'codex:MEMORY.md'),
+ line('Green pull requests merged without asking.', 'merge-when-green', 'asks:36'),
+ line('A mockup agreed before UI code.', 'mockup-first'),
+ line('One change per pull request.', 'codex:memory_summary.md', 'codex:MEMORY.md'),
+ '', '## Taste',
+ line('Tools that feel like vim, tmux and fzf: quiet, fast, typed.', 'terminal-taste', 'asks:26'),
+ line('Every action reachable from the keyboard.', 'keyboard-first'),
+ line('Pages that feel instant.', 'speed-matters'),
+ line('Plain words; no jargon.', 'plain-words'),
+ line('Two-space indentation, tabs in Go.', 'grok:code-style.md', 'gemini:GEMINI.md'),
+ '', '## Engineering principles',
+ line('A small, stable core; features as services.', 'small-core'),
+ line('Comments say why, naming the incident.', 'why-comments'),
+ line('Merge on weekends, deploy on Monday.', 'no-weekend-deploys', 'release-train'),
+ '', '## Right now',
+ line('Freezing the ranker eval set for the quarter.', 'ranker-evals'),
+ line('Retiring the legacy renderer.', 'legacy-renderer'),
+ line('Webhook retries that back off to an hour.', 'webhook-retries', 'deploys-from-main'),
+ ''].join('\n'), { gen: now, now });
const viewer = createViewer({ workspace: home, intervalMs: 60_000, env, home });
const page = await browser.newPage({ viewport: { width: 1080, height: 720 }, deviceScaleFactor: 1, colorScheme: 'dark' });
try {
await page.goto(`http://127.0.0.1:${await viewer.start()}/`);
- await page.waitForSelector('#list > *');
- await page.waitForTimeout(1500); // Let the layout settle before recording.
+ // The pane is Sense of Self: wait for the scene, skip its arrival, and let the light settle.
+ await page.waitForFunction(() => document.getElementById('stage')?.inspectSelf?.().ready);
+ await page.keyboard.press('Escape');
+ // "Short answers that lead with the result": a belief whose roots reach memories, lit.
+ await page.keyboard.press('ArrowRight');
+ await page.waitForTimeout(2500);
await page.screenshot({ path: join(output, `${id}.png`) });
if (process.env.COVER_DUMP_TEXT) console.log(await page.innerText('body'));
} finally { await page.close(); await viewer.close(); await rm(home, { recursive: true, force: true }); }
diff --git a/store/agents/memories/README.md b/store/agents/memories/README.md
index 72def9c30..511a16214 100644
--- a/store/agents/memories/README.md
+++ b/store/agents/memories/README.md
@@ -5,20 +5,24 @@ Every agent learns on its own and keeps what it learned to itself: Claude Code i
Hermes in `~/.hermes/memories/`. Memories reads all of them in one place, beside a year of your work
with those agents from Harness's session index. Opening it sends no prompt and changes nothing.
-## The pane
-
-- **The band** at the top: your messages per day over the past year, each day tinted with the agent you
- talked to most, with totals and each agent's share.
-- **About you**: the profile the agent on the right builds from your own words (below), then everything
- your agents saved about you — Claude Code's user and feedback notes, Hermes and OpenClaw profiles,
- Grok Build's global topics, what you asked Codex to remember.
-- **Projects**: what each agent knows about each repository, with how much you worked there.
-- **Notes and summaries**, **What you told them** (your global CLAUDE.md, AGENTS.md and rules), and
- **Agents**: where each one keeps its memory, whether it is on, and how to turn it on.
-- **Search** filters memories as you type, fzf-style, and searches your past conversations too.
-
-Keys: ↑↓ move, → or ⏎ open, ← back, esc clear. A memory an agent saves while the pane is open glows
-for a moment. Memory files are shown as text; nothing in them can run in the pane.
+## The pane: Sense of Self
+
+- **About You** is a tree of light: every line is a belief, one strand, and each section (How you work,
+ Taste, …) a frond. The focused belief is written large beside it, with **why your agents believe
+ this**: the memories it cites and how many of your messages say it, lit down to where they are.
+- **The lake** below holds every memory your agents keep, one orb each, colored by the agent, in the
+ column of its project, newer nearer the surface; old ones lose letters. Threads rise from a memory to
+ the beliefs it holds up. Dive in, swim between them, lift one out to read it and the conversations
+ about it.
+- **The mist** over the water is your own messages, gathered over the project you said them in.
+- **Recall** is the prompt at the top: type and the memories and messages that answer rise, and the
+ beliefs they hold up pulse. Conversations found by the same search as Cmd-P rise too; open one to read
+ its words.
+
+Keys: ←→ section, ↑↓ belief (↓ past the last dives into the lake), space plucks a belief, tab steps
+through why, ⏎ follows it down. In the lake: arrows swim, ⏎ lifts a memory out, esc rises. Clicking a
+section, a belief or an orb does the same. A memory an agent saves while the pane is open glows when it
+appears. Memory text is shown as text; nothing in it can run in the pane.
## About You
@@ -56,16 +60,20 @@ current request comes first. Saying it in the chat ("stop using my About You") f
## Every machine
-The pane asks each of your online machines for its memories and shows them together, each labeled
-with its machine, with one activity calendar for all of them. About You and the switch are the same
-everywhere: the newest About You and the newest on/off choice reach every machine, and each machine's
-agents get it there. A machine whose Harness is older than its memory service is listed as needing
-the newest Harness.
+The pane asks each of your online machines for its memories and shows them together in one lake, each
+memory labeled with its machine. About You and the switch are the same everywhere: the newest About You
+and the newest on/off choice reach every machine, and each machine's agents get it there. A machine that
+does not answer, or whose Harness is older than its memory service, is named at the foot of the pane
+with why.
`npm run test:agents` proves delivery with the real agents in a throwaway home: a random made-up fact
in About You must reach a new Claude Code session's answer and Codex's model input, and must not reach
either without it.
+`PLAYWRIGHT=<path to playwright/index.mjs> npm run test:self [screenshots folder]` drives the pane in a
+browser on made-up homes only (one the size of a real person's, one without About You, one with
+nothing), by keys and clicks, at two sizes in both themes, and prints what a frame costs.
+
## The `mem` command
The agent uses it; so can you (`$MEM_CLI` in the workspace):
diff --git a/store/agents/memories/package.json b/store/agents/memories/package.json
index cce4f2d42..742deb6ff 100644
--- a/store/agents/memories/package.json
+++ b/store/agents/memories/package.json
@@ -5,7 +5,8 @@
"scripts": {
"test": "node --disable-warning=ExperimentalWarning --import ./test/setup.mjs --test test/*.test.mjs",
"start": "./viewer.sh",
- "test:agents": "node --disable-warning=ExperimentalWarning test/e2e/agents.e2e.mjs"
+ "test:agents": "node --disable-warning=ExperimentalWarning test/e2e/agents.e2e.mjs",
+ "test:self": "node --disable-warning=ExperimentalWarning test/e2e/self.e2e.mjs"
},
"engines": {
"node": ">=22"
diff --git a/store/agents/memories/test/e2e/self.e2e.mjs b/store/agents/memories/test/e2e/self.e2e.mjs
new file mode 100644
index 000000000..ceb4832b6
--- /dev/null
+++ b/store/agents/memories/test/e2e/self.e2e.mjs
@@ -0,0 +1,303 @@
+#!/usr/bin/env node
+/**
+ * Sense of Self in a real browser, on made-up homes only (test/fixtures.mjs): a person with 100
+ * memories, 25 About You lines and 4,000 messages; one with no About You yet; one with nothing at all.
+ *
+ * PLAYWRIGHT=/path/to/playwright/index.mjs node --disable-warning=ExperimentalWarning test/e2e/self.e2e.mjs [screenshots-dir]
+ *
+ * Drives the pane by keys and by clicks at 1000×800 and 700×700, dark and light: arrival, sections and
+ * beliefs, why, pluck, the lake and back, a memory lifted out, recall, a conversation search found,
+ * the empty states, a hidden tab, reduced motion. Fails on any console error or any request that
+ * leaves this machine, and prints the frame script time. Screenshots, when asked for, show only the
+ * made-up homes.
+ */
+import { mkdirSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import '../setup.mjs'
+import { growHome, makeHome } from '../fixtures.mjs'
+import { createViewer } from '../../viewer.mjs'
+
+const shots = process.argv[2] ?? null
+if (shots) mkdirSync(shots, { recursive: true })
+const playwright = process.env.PLAYWRIGHT ?? 'playwright'
+const { chromium } = await import(playwright.startsWith('/') ? pathToFileURL(playwright).href : playwright)
+
+const results = []
+const failed = []
+const check = (ok, what) => { results.push(`${ok ? 'ok ' : 'FAIL'} ${what}`); if (!ok) failed.push(what) }
+
+async function serve(made) {
+ const viewer = createViewer({ workspace: mkdtempSync(join(tmpdir(), 'memories-ws-')), env: made.env, home: made.home, intervalMs: 60_000 })
+ return { viewer, url: `http://127.0.0.1:${await viewer.start()}/` }
+}
+const grown = await serve(growHome(makeHome()))
+const bare = await serve(makeHome())
+const nothing = mkdtempSync(join(tmpdir(), 'memories-empty-'))
+const empty = await serve({ home: nothing, env: { MEMORIES_HOME: join(nothing, '.harness', 'memory') } })
+
+/** Counts frames and times each one's script, so a test can see the loop and what it costs. */
+const COUNT_FRAMES = `(() => {
+ const raf = window.requestAnimationFrame.bind(window)
+ window.__frames = { n: 0, ms: [] }
+ window.requestAnimationFrame = (fn) => raf((t) => { const s = performance.now(); try { fn(t) } finally { window.__frames.n++; window.__frames.ms.push(performance.now() - s); if (window.__frames.ms.length > 4000) window.__frames.ms.shift() } })
+})()`
+
+// ── what a frame costs, on the real-sized person ────────────────────────────────────────────────
+// First, alone, in Chromium's own renderer. Under SwiftShader (the rest of this test) this canvas, like
+// the prototype's, is rastered at a few frames a second, which says nothing about a person's pane.
+// Script time includes the raster of the whole frame: the reflection and the bloom read the canvas back.
+{
+ const plain = await chromium.launch()
+ const context = await plain.newContext({ viewport: { width: 1000, height: 800 }, colorScheme: 'dark' })
+ const page = await context.newPage()
+ await page.addInitScript(COUNT_FRAMES)
+ await page.goto(grown.url)
+ await page.waitForFunction(() => document.getElementById('stage').inspectSelf?.().ready)
+ await page.keyboard.press('Escape')
+ const measure = async (what) => {
+ await page.waitForTimeout(600)
+ await page.evaluate(() => { window.__frames.ms = []; window.__frames.n = 0 })
+ await page.waitForTimeout(3000)
+ const cost = await page.evaluate(() => { const ms = [...window.__frames.ms].sort((a, b) => a - b); return { fps: window.__frames.n / 3, median: ms[Math.floor(ms.length / 2)], p95: ms[Math.floor(ms.length * 0.95)] } })
+ check(cost.fps >= 45 && cost.median < 16.7, `frame cost, ${what}: ${cost.fps.toFixed(0)} fps, script median ${cost.median.toFixed(1)} ms, p95 ${cost.p95.toFixed(1)} ms`)
+ }
+ await measure('About You')
+ await page.keyboard.type('release')
+ await measure('recalling')
+ await page.keyboard.press('Escape')
+ for (let n = 0; n < 6; n++) await page.keyboard.press('ArrowDown')
+ await measure('in the lake')
+ await plain.close()
+}
+
+const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] })
+
+async function open(server, { width = 1000, height = 800, scheme = 'dark', reduced = 'no-preference' } = {}) {
+ const context = await browser.newContext({ viewport: { width, height }, colorScheme: scheme, reducedMotion: reduced })
+ const page = await context.newPage()
+ const errors = [], offsite = []
+ page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
+ page.on('pageerror', (e) => errors.push(String(e)))
+ page.on('request', (r) => { const u = new URL(r.url()); if (!['127.0.0.1', 'localhost'].includes(u.hostname) && u.protocol !== 'data:') offsite.push(r.url()) })
+ await page.addInitScript(COUNT_FRAMES)
+ await page.goto(server.url)
+ await page.waitForFunction(() => document.getElementById('stage').inspectSelf?.().ready)
+ const self = () => page.evaluate(() => document.getElementById('stage').inspectSelf())
+ const text = (selector) => page.locator(selector).first().textContent()
+ const settle = (ms = 450) => page.waitForTimeout(ms)
+ const shot = async (name) => { if (shots) await page.screenshot({ path: join(shots, `${name}.png`) }) }
+ const done = async (tag) => {
+ check(errors.length === 0, `${tag}: no console errors ${errors.join(' ; ')}`)
+ check(offsite.length === 0, `${tag}: no requests off this machine ${offsite.join(' ')}`)
+ await context.close()
+ }
+ return { page, self, text, settle, shot, done }
+}
+
+// ── a real-sized person, 1000×800, dark: everything by keys, then by clicks ─────────────────────
+{
+ const { page, self, text, settle, shot, done } = await open(grown)
+ const tag = 'grown 1000x800 dark'
+ check(await page.locator('.self.arriving').count() === 1, `${tag}: arrives`)
+ await page.waitForTimeout(900)
+ await shot('self-arrival-1000x800')
+ await page.waitForFunction(() => document.getElementById('stage').inspectSelf().arrived, null, { timeout: 4500 })
+ check(true, `${tag}: the arrival ends by itself within four seconds`)
+ await settle(700)
+ let s = await self()
+ check(s.section === 'How you work' && (await text('.self .cap-text')) === s.belief, `${tag}: the first belief, large (${s.section}: ${s.belief})`)
+ check(await page.locator('.self .cap-why li').count() >= 3, `${tag}: why your agents believe this, listed`)
+ check((await text('#count')) === '104', `${tag}: the header counts the memories (${await text('#count')})`)
+ await shot('self-1000x800-dark')
+
+ await page.keyboard.press('ArrowRight')
+ s = await self()
+ check(s.section === 'What you want from agents', `${tag}: → next section (${s.section})`)
+ await page.keyboard.press('ArrowLeft')
+ await page.keyboard.press('ArrowDown')
+ check((await text('.self .kicker .n')) === '2 of 5', `${tag}: ↓ next belief (${await text('.self .kicker .n')})`)
+ await page.keyboard.press('ArrowUp')
+ check((await text('.self .kicker .n')) === '1 of 5', `${tag}: ↑ back`)
+ await page.keyboard.press('Tab')
+ check((await self()).thread === 0 && await page.locator('.self .cap-why li.sel').count() === 1, `${tag}: tab picks a source`)
+ await page.keyboard.press('Tab')
+ check((await self()).thread === 1, `${tag}: tab again, the next source`)
+ await page.keyboard.press(' ')
+ check((await page.inputValue('#q')) === '', `${tag}: space plucks, it does not type`)
+ await settle(300)
+ await shot('self-why-1000x800')
+
+ await page.keyboard.press('Enter')
+ await settle(1500)
+ s = await self()
+ check(s.view === 'lake' && s.orb, `${tag}: enter follows the source down into the lake (${s.orb})`)
+ check(await page.locator('.self .orb-label.on').waitFor({ timeout: 6000 }).then(() => true, () => false), `${tag}: the memory's name floats beside it`)
+ await shot('self-lake-1000x800')
+ const before = s.orbId
+ await page.keyboard.press('ArrowRight')
+ s = await self()
+ check(s.orbId && s.orbId !== before, `${tag}: arrows swim to another memory (${s.orb})`)
+ await page.keyboard.press('Enter')
+ await settle(900)
+ s = await self()
+ check(s.panel === 'memory' && (await text('.self .panel h2')) === s.orb, `${tag}: enter lifts it out (${await text('.self .panel h2')})`)
+ check((await page.locator('.self .panel .body').textContent()).length > 20, `${tag}: its words`)
+ await shot('self-lifted-1000x800')
+ await page.keyboard.press('Escape')
+ await settle(500)
+ check((await self()).panel === null && (await self()).view === 'lake', `${tag}: esc puts it back`)
+ await page.keyboard.press('Escape')
+ await page.waitForFunction(() => { const s = document.getElementById('stage').inspectSelf(); return s.view === 'self' && s.camY < 1 }, null, { timeout: 8000 }).catch(() => {})
+ check((await self()).view === 'self' && (await self()).camY < 1, `${tag}: esc rises`)
+
+ // By clicks: a section's name, then a belief's bead.
+ s = await self()
+ const taste = s.labels.find((label) => label.section === 'Taste')
+ const box = await page.locator('#stage').boundingBox()
+ await page.mouse.click(box.x + taste.x, box.y + taste.y)
+ check((await self()).section === 'Taste', `${tag}: clicking a section's name goes there`)
+ s = await self()
+ const bead = s.beads[12]
+ await page.mouse.click(box.x + bead.x, box.y + bead.y)
+ check((await self()).belief === bead.text, `${tag}: clicking a bead focuses its belief`)
+ const why = page.locator('.self .cap-why li.go').first()
+ await why.click()
+ await settle(1400)
+ check((await self()).view === 'lake', `${tag}: clicking a source goes down to it`)
+ await page.mouse.wheel(0, -200)
+ await settle(1400)
+ check((await self()).view === 'self', `${tag}: scrolling up rises`)
+
+ // Recall: the header prompt.
+ await page.keyboard.type('refund')
+ await settle(700)
+ s = await self()
+ check(s.recall?.q === 'refund' && s.recall.picks > 3 && await page.locator('.self .recall.on').count() === 1, `${tag}: typing recalls (${s.recall?.picks} rise)`)
+ check(/^\d+\/104$/.test(await text('#count')), `${tag}: the header counts what rose (${await text('#count')})`)
+ await shot('self-recall-1000x800')
+ await page.keyboard.press('Enter')
+ await settle(800)
+ check((await self()).panel === 'memory', `${tag}: enter on a risen memory lifts it out`)
+ await page.keyboard.press('Escape')
+ check((await self()).panel === null && (await self()).recall, `${tag}: esc back to the recall`)
+ await page.keyboard.press('Escape')
+ check((await self()).recall === null && (await page.inputValue('#q')) === '', `${tag}: esc again forgets, and empties the prompt`)
+ await page.keyboard.type('1')
+ check((await page.inputValue('#q')) === '1' && (await self()).recall, `${tag}: a digit types into the prompt`)
+ await page.keyboard.press('Escape')
+
+ // A conversation older than the mist: search finds it, it rises, enter shows its words.
+ await page.keyboard.type('zeppelin')
+ await page.waitForFunction(() => document.getElementById('stage').inspectSelf().recall?.extra > 0, null, { timeout: 5000 })
+ check(true, `${tag}: a conversation the mist does not hold rises from search`)
+ const rows = await page.locator('.self .recall-list li:not(.head)').count()
+ for (let n = 1; n < rows; n++) await page.keyboard.press('ArrowDown')
+ await page.keyboard.press('Enter')
+ await page.waitForSelector('.self .panel .turn', { timeout: 5000 })
+ const words = await page.locator('.self .panel .body').textContent()
+ check((await self()).panel === 'message' && /zeppelin manifest/.test(words) && /fixed/.test(words), `${tag}: enter shows that conversation's words and answers`)
+ await settle(600)
+ await shot('self-conversation-1000x800')
+ await page.keyboard.press('Escape')
+ await page.keyboard.press('Escape')
+
+ // Only while visible.
+ await page.evaluate(() => { window.__frames.n = 0 })
+ await page.waitForTimeout(1000)
+ check((await page.evaluate(() => window.__frames.n)) > 0, `${tag}: draws while visible`)
+ await page.evaluate(() => { Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true }); document.dispatchEvent(new Event('visibilitychange')) })
+ const hiddenAt = await page.evaluate(() => window.__frames.n)
+ await page.waitForTimeout(500)
+ check((await page.evaluate(() => window.__frames.n)) === hiddenAt, `${tag}: a hidden tab draws nothing`)
+ await page.evaluate(() => { Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true }); document.dispatchEvent(new Event('visibilitychange')) })
+ // Waits on the frame itself: a software renderer can take longer than a fixed few hundred ms for one under
+ // load, which failed this check one run in five while the loop was right (start() schedules a frame).
+ const drewAgain = await page.waitForFunction((at) => window.__frames.n > at, hiddenAt, { timeout: 3000 }).then(() => true, () => false)
+ check(drewAgain, `${tag}: visible again, it draws again`)
+ await done(tag)
+}
+
+// ── the same person in a small, light pane ──────────────────────────────────────────────────────
+for (const [width, height, scheme] of [[700, 700, 'light'], [700, 700, 'dark'], [1000, 800, 'light']]) {
+ const { page, self, text, settle, shot, done } = await open(grown, { width, height, scheme })
+ const tag = `grown ${width}x${height} ${scheme}`
+ await page.keyboard.press('Enter') // skips the arrival
+ await settle(800)
+ check((await self()).arrived && (await text('.self .cap-text')).length > 5, `${tag}: any key skips the arrival`)
+ const header = await page.evaluate(() => getComputedStyle(document.querySelector('.top')).backgroundColor + ' ' + getComputedStyle(document.body).backgroundColor)
+ const stage = await page.evaluate(() => getComputedStyle(document.getElementById('stage')).backgroundColor)
+ check(stage === 'rgb(3, 4, 7)' && (scheme === 'light' ? header.includes('251, 251, 250') : header.includes('14, 15, 17')), `${tag}: a dark scene under a ${scheme} header (${header}; ${stage})`)
+ await page.keyboard.press('ArrowRight')
+ await page.keyboard.press('ArrowRight')
+ await page.keyboard.press('ArrowDown')
+ await settle(600)
+ await shot(`self-${width}x${height}-${scheme}`)
+ await page.keyboard.type('release')
+ await settle(700)
+ check((await self()).recall?.picks > 0, `${tag}: recall`)
+ await shot(`self-recall-${width}x${height}-${scheme}`)
+ await page.keyboard.press('Escape')
+ await page.keyboard.press('ArrowDown'); await page.keyboard.press('ArrowDown'); await page.keyboard.press('ArrowDown'); await page.keyboard.press('ArrowDown'); await page.keyboard.press('ArrowDown')
+ await settle(1500)
+ check((await self()).view === 'lake', `${tag}: ↓ past the last belief dives into the lake`)
+ await shot(`self-lake-${width}x${height}-${scheme}`)
+ await done(tag)
+}
+
+// ── no About You yet; nothing at all; reduced motion ────────────────────────────────────────────
+{
+ const { page, self, text, settle, shot, done } = await open(bare)
+ const tag = 'no About You 1000x800'
+ await page.keyboard.press('Escape')
+ await settle(700)
+ check((await text('.self .cap-text')) === 'About You is not built yet.' && /build my About You/.test(await text('.self .cap-note')), `${tag}: says how to build it, in the scene`)
+ await shot('self-no-about-1000x800')
+ await page.keyboard.type('pnpm')
+ await settle(500)
+ check(await page.locator('.self .recall-list li', { hasText: 'free' }).count() > 0, `${tag}: a memory that holds up no belief is found by recall`)
+ await page.keyboard.press('Escape')
+ await page.keyboard.press('ArrowDown')
+ await settle(1400)
+ check((await self()).view === 'lake', `${tag}: ↓ dives into the lake`)
+ await page.keyboard.press('Enter')
+ await settle(700)
+ check((await self()).panel === 'memory', `${tag}: and lifts a memory out`)
+ const hostile = await page.evaluate(() => document.querySelectorAll('.self img, .self script:not([src])').length)
+ check(hostile === 0, `${tag}: no element ever comes from a memory`)
+ await done(tag)
+}
+{
+ const { page, text, settle, shot, done } = await open(empty)
+ const tag = 'nothing at all 1000x800'
+ await settle(600)
+ await page.keyboard.press('Escape')
+ await settle(500)
+ check((await text('.self .cap-text')) === 'Nothing here yet.', `${tag}: a calm empty state (${await text('.self .cap-text')})`)
+ await shot('self-empty-1000x800')
+ await page.keyboard.type('anything')
+ await settle(400)
+ check(/nothing rises/.test(await text('.self .recall .kicker')), `${tag}: recall says nothing rises`)
+ await done(tag)
+}
+{
+ const { page, self, settle, done } = await open(grown, { reduced: 'reduce' })
+ const tag = 'reduced motion'
+ check((await self()).arrived, `${tag}: no arrival`)
+ await settle(800)
+ const a = await page.evaluate(() => window.__frames.n)
+ await page.waitForTimeout(800)
+ const b = await page.evaluate(() => window.__frames.n)
+ check(b === a, `${tag}: nothing moves, so nothing is drawn (${a} → ${b})`)
+ await page.keyboard.press('ArrowRight')
+ await page.waitForTimeout(200)
+ check((await page.evaluate(() => window.__frames.n)) > b && (await self()).section === 'What you want from agents', `${tag}: a key draws again`)
+ await done(tag)
+}
+
+await browser.close()
+for (const server of [grown, bare, empty]) await server.viewer.close()
+console.log(results.join('\n'))
+console.log(failed.length ? `\n${failed.length} FAILED` : `\nall ${results.length} passed`)
+process.exit(failed.length ? 1 : 0)
diff --git a/store/agents/memories/test/fixtures.mjs b/store/agents/memories/test/fixtures.mjs
index 938f8775a..043e75261 100644
--- a/store/agents/memories/test/fixtures.mjs
+++ b/store/agents/memories/test/fixtures.mjs
@@ -1,10 +1,11 @@
/**
* A made-up person's computer: a few agents' memory folders and a session index, all synthetic.
*/
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { DatabaseSync } from 'node:sqlite'
+import { writeAbout } from '../lib/about.mjs'
export const DAY = 86_400_000
@@ -109,3 +110,62 @@ export function makeHome({ now = Date.now() } = {}) {
// Each test passes this env, never process.env: the folders come from `home` alone.
return { home, project, key, env: { MEMORIES_HOME: join(home, '.harness', 'memory') } }
}
+
+const GROWN_PROJECTS = ['payments', 'widgets', 'docs-site', 'mobile-app', 'infra', 'ml-pipeline', 'design-system', 'api-gateway']
+const GROWN_TOPICS = ['Release train', 'Test layout', 'Deploy steps', 'Code owners', 'Flaky tests', 'Error budget', 'Naming rules', 'Review rules', 'Build cache', 'Feature flags', 'On-call notes']
+const GROWN_SAYINGS = ['why do the retries pile up after an outage?', 'make the refund flow handle a third partial refund', 'regenerate the snapshots and show me the diff',
+ 'rewrite the quickstart in plain words', 'the app crashes on resume, find out why', 'rotate the staging certs', 'freeze the eval set for this quarter',
+ 'rename the color tokens by role', 'rate limit per key, not per IP', 'tldr the incident from last night', 'one change per pull request', 'merge it once CI is green',
+ 'measure before and after', 'make the empty state clearer', 'never release on a Friday', 'add a test that fails first']
+const GROWN_SECTIONS = ['How you work', 'What you want from agents', 'Taste', 'Engineering principles', 'Right now']
+
+/**
+ * makeHome() grown to the size of a real person's: about `memories` memories across eight projects,
+ * an About You of `lines` lines citing them, and `asks` messages over four months in those folders (a
+ * few in a worktree, a few with no folder). Everything is made up and deterministic.
+ */
+export function growHome(made, { memories = 100, lines = 25, asks = 4200, now = Date.now() } = {}) {
+ const { home } = made
+ let seed = 20261010
+ const random = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648 }
+ const folders = GROWN_PROJECTS.map((name) => { const path = join(home, 'code', name); mkdirSync(path, { recursive: true }); return { name, path, key: path.replace(/[^A-Za-z0-9]/g, '-') } })
+ const notes = []
+ for (let n = 0; notes.length < memories - 22; n++) {
+ const folder = folders[n % folders.length]
+ const topic = GROWN_TOPICS[Math.floor(n / folders.length) % GROWN_TOPICS.length]
+ const file = `${topic.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${folder.name}.md`
+ const type = ['project', 'feedback', 'reference', 'user'][n % 4]
+ const path = put(home, `.claude/projects/${folder.key}/memory/${file}`, `---\nname: ${topic}\ndescription: ${topic} for ${folder.name}\ntype: ${type}\n---\n\n${topic} in ${folder.name}: ${GROWN_SAYINGS[n % GROWN_SAYINGS.length]}.\n\n**Why:** it came up ${2 + (n % 5)} times.\n`)
+ // Saved over four months, the way a person's memories pile up: more of them lately.
+ const saved = new Date(now - Math.floor(Math.pow(((n * 37) % 97) / 97, 1.6) * 140 * DAY))
+ utimesSync(path, saved, saved)
+ notes.push({ file, project: folder.name })
+ }
+ const about = ['# About you', '', `Built from ${asks} of your messages.`, '']
+ for (let i = 0; i < lines; i++) {
+ if (i % 5 === 0) about.push(`## ${GROWN_SECTIONS[(i / 5) % GROWN_SECTIONS.length]}`)
+ const cited = [notes[(i * 3) % notes.length], notes[(i * 7 + 1) % notes.length]].map((note) => `claude:${note.file}`)
+ const text = GROWN_SAYINGS[i % GROWN_SAYINGS.length].replace(/^./, (c) => c.toUpperCase()).replace(/[?.]$/, '')
+ about.push(`- ${text}, in ${notes[i % notes.length].project}. [${cited.join(', ')}, asks:${10 + i}]`)
+ if (i % 5 === 4) about.push('')
+ }
+ writeAbout(made.env.MEMORIES_HOME, about.join('\n') + '\n', { now })
+ const turns = []
+ const engines = ['codex', 'codex', 'claude', 'claude', 'codex', 'grok', 'hermes']
+ for (let n = 0; n < asks; n++) {
+ const daysAgo = Math.floor(Math.pow(random(), 1.3) * 120) + random() * 0.6
+ const folder = folders[Math.floor(Math.pow(random(), 1.5) * folders.length)]
+ const engine = engines[Math.floor(random() * engines.length)]
+ const where = n % 97 === 0 ? '' : n % 41 === 0 ? join(home, 'code', 'worktrees', folder.name, 'fix') : folder.path
+ turns.push({ session: `g-${folder.name}-${Math.floor(daysAgo / 3)}-${engine}`, engine, cwd: where, title: `${folder.name}: ${GROWN_SAYINGS[n % 7]}`,
+ ask: `${GROWN_SAYINGS[Math.floor(random() * GROWN_SAYINGS.length)]} (${folder.name}, ${n})`, answer: 'done', daysAgo })
+ }
+ // Older than the newest messages the pane loads: only search finds these.
+ for (let n = 0; n < 12; n++) {
+ turns.push({ session: 'g-old-zeppelin', engine: 'codex', cwd: folders[1].path, title: 'widgets: the zeppelin migration', ask: `the zeppelin manifest is wrong again, step ${n}`, answer: 'fixed', daysAgo: 130 + n / 10 })
+ }
+ const data = join(home, '.harness', 'cli', 'data')
+ rmSync(join(data, 'session-search.db'), { force: true })
+ sessionIndex(data, { now, turns })
+ return { ...made, projects: folders }
+}
diff --git a/store/agents/memories/test/page.test.mjs b/store/agents/memories/test/page.test.mjs
index cc66088c7..b7e1786d2 100644
--- a/store/agents/memories/test/page.test.mjs
+++ b/store/agents/memories/test/page.test.mjs
@@ -1,12 +1,10 @@
-/** The page's pure parts: Markdown never becomes HTML, matching ranks like fzf, the calendar is right. */
+/** The page's pure parts: a memory's text never becomes HTML, and the text helpers survive any shape. */
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { inline, parse, render } from '../viewer/markdown.js'
-import { scoreFields, scoreTerm } from '../viewer/fuzzy.js'
-import { buildGrid, dayKey } from '../viewer/heatmap.js'
+import { marked, renderBody } from '../viewer/self.js'
import { frontmatter, sections, entries, encodePath, clip } from '../lib/text.mjs'
-/** Just enough of a document to watch what render() builds: elements and text nodes, no HTML parser. */
+/** Just enough of a document to watch what renderBody() builds: elements and text nodes, no HTML parser. */
function fakeDocument() {
const node = (tag) => ({ tag, children: [], style: {}, dataset: {}, textContent: '', className: '', title: '', append(...items) { this.children.push(...items) } })
return { createElement: node, createTextNode: (text) => ({ tag: '#text', text }) }
@@ -14,48 +12,22 @@ function fakeDocument() {
const texts = (tree) => tree.tag === '#text' ? [tree.text] : [tree.textContent, ...tree.children.flatMap(texts)]
const tags = (tree) => tree.tag === '#text' ? [] : [tree.tag, ...tree.children.flatMap(tags)]
-test('markdown blocks and spans', () => {
- const blocks = parse('# Title\n\nSome **bold** and `code`.\n\n- one\n continued\n- [x] done\n\n```\nraw <b>\n```\n> quoted')
- assert.deepEqual(blocks.map((block) => block.type), ['heading', 'paragraph', 'list', 'code', 'quote'])
- assert.equal(blocks[2].items[0].spans.map((span) => span.text).join(''), 'one continued')
- assert.equal(blocks[2].items[1].checked, true)
- assert.equal(blocks[3].text, 'raw <b>')
- assert.deepEqual(inline('[docs](https://x.y) and _it_'), [{ type: 'link', text: 'docs', href: 'https://x.y' }, { type: 'text', text: ' and ' }, { type: 'em', text: 'it' }])
+test('a memory body: headings, bullets, code and bold, as elements the page makes', () => {
+ const doc = fakeDocument()
+ const root = renderBody(doc, doc.createElement('div'), '# Title\n\nSome **bold** and `code`.\n\n- one\n- two\n\n```\nraw <b>\n```')
+ assert.deepEqual(root.children.map((child) => child.tag), ['h4', 'p', 'div', 'div', 'pre'])
+ assert.deepEqual(tags(root.children[1]), ['p', 'strong', 'code'])
+ assert.equal(root.children[4].textContent, 'raw <b>\n')
})
test('hostile text is rendered as text: no element comes from the memory', () => {
const doc = fakeDocument()
- const root = render(doc, doc.createElement('div'), parse('<script>alert(1)</script>\n\n<img src=x onerror=alert(2)> **<b>x</b>**'))
+ const root = renderBody(doc, doc.createElement('div'), '<script>alert(1)</script>\n\n<img src=x onerror=alert(2)> **<b>x</b>**')
assert.deepEqual([...new Set(tags(root))].sort(), ['div', 'p', 'strong'])
assert.ok(texts(root).join('').includes('<script>alert(1)</script>'))
-})
-
-test('fzf-style ranking: word starts and runs first; long text matches only as typed', () => {
- assert.ok(scoreTerm('sa', 'Short answers') > scoreTerm('sa', 'xsxxxxxxxa'), 'word starts beat a scattered match')
- assert.ok(scoreTerm('ans', 'Short answers') > scoreTerm('sa', 'Short answers'), 'a run beats word starts')
- assert.equal(scoreTerm('xyz', 'Short answers'), 0)
- assert.ok(scoreTerm('rel', 'No weekend releases') > 0)
- assert.equal(scoreTerm('release', 'r e l e a s e scattered', true), 0)
- assert.equal(scoreFields('short five', [['Short answers', 3], ['wants replies under five lines', 1, true]]) > 0, true)
- assert.equal(scoreFields('short nothing', [['Short answers', 3]]), 0)
-})
-
-test('the calendar: weeks end today, Monday first, levels by quartile', () => {
- const now = new Date('2026-10-09T15:00:00').getTime() // a Friday
- const day = (offset) => dayKey(now - offset * 86_400_000)
- const grid = buildGrid([
- { day: day(0), engine: 'codex', asks: 40 }, { day: day(0), engine: 'claude', asks: 10 },
- { day: day(1), engine: 'claude', asks: 2 }, { day: day(2), engine: 'claude', asks: 5 },
- ], { now, weeks: 4 })
- assert.equal(grid.columns.length, 4)
- const last = grid.columns.at(-1)
- assert.equal(last[4].day, day(0), 'Friday is the fifth row')
- assert.equal(last[5], null, 'the days after today are empty')
- assert.equal(last[4].top, 'codex')
- assert.equal(last[4].level, 4)
- assert.equal(grid.max.total, 50)
- assert.equal(grid.streak, 3)
- assert.equal(grid.activeDays, 3)
+ const snippet = marked(doc, doc.createElement('span'), 'say \u0002<img src=x onerror=alert(3)>\u0003 twice')
+ assert.deepEqual(tags(snippet), ['span', 'mark'])
+ assert.equal(snippet.children[1].textContent, '<img src=x onerror=alert(3)>')
})
test('text helpers survive any shape', () => {
diff --git a/store/agents/memories/test/review.test.mjs b/store/agents/memories/test/review.test.mjs
index f5f3a4593..82a1a1bae 100644
--- a/store/agents/memories/test/review.test.mjs
+++ b/store/agents/memories/test/review.test.mjs
@@ -1,18 +1,22 @@
/** Regressions from the first review of this package: each test names the failure it guards. */
import assert from 'node:assert/strict'
-import { execFileSync } from 'node:child_process'
import { mkdtempSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'
import { request } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { fileURLToPath } from 'node:url'
import { test } from 'node:test'
import { firstHeading, frontmatter, sections } from '../lib/text.mjs'
import { parseAbout, writeAbout } from '../lib/about.mjs'
import { projectsFor } from '../lib/state.mjs'
-import { parse } from '../viewer/markdown.js'
+import { renderBody } from '../viewer/self.js'
import { createViewer } from '../viewer.mjs'
+/** A memory body as the pane renders it, into elements that only record what they hold. */
+function body(text) {
+ const node = (tag) => ({ tag, children: [], textContent: '', className: '', append(...items) { this.children.push(...items) } })
+ return renderBody({ createElement: node, createTextNode: (value) => ({ tag: '#text', value }) }, node('div'), text)
+}
+
const fast = (label, fn, budgetMs = 200) => {
const started = performance.now()
fn()
@@ -24,14 +28,14 @@ test('a heading line of thousands of spaces parses in linear time (it once took
const line = '# a' + ' '.repeat(20_000) + 'b'
fast('firstHeading', () => firstHeading(line))
fast('sections', () => sections('## a' + ' '.repeat(20_000) + 'b\ntext'))
- fast('markdown', () => parse(line + '\n\n' + '`'.repeat(30_000)))
+ fast('memory body', () => body(line + '\n\n' + '`'.repeat(30_000)))
fast('About You', () => parseAbout('## A\n- x' + ' '.repeat(30_000) + 'y [' + ' '.repeat(30_000)))
assert.equal(firstHeading('## Title ##'), 'Title')
assert.equal(firstHeading('#hashtag\n### C# tips'), 'C# tips')
})
test('thousands of nested quotes do not exhaust the stack', () => {
- assert.doesNotThrow(() => parse('>'.repeat(20_000) + ' deep'))
+ assert.doesNotThrow(() => body('>'.repeat(20_000) + ' deep'))
})
test('a front-matter key followed by indented text is a string, never "[object Object]"', () => {
@@ -65,18 +69,6 @@ test('About You never writes through a link planted at its file names', () => {
assert.match(readFileSync(join(dir, 'about-you.prev.md'), 'utf8'), /one/)
})
-test('the streak counts calendar days across daylight-saving changes', () => {
- const heatmap = fileURLToPath(new URL('../viewer/heatmap.js', import.meta.url))
- const script = `
- const { streak, dayKey } = await import(${JSON.stringify(heatmap)})
- const days = (list) => new Map(list.map((d) => [d, { total: 1 }]))
- const spring = streak(days(['2027-03-12', '2027-03-13', '2027-03-14', '2027-03-15']), new Date('2027-03-15T00:30:00').getTime())
- const fall = streak(days(['2026-10-31', '2026-11-01']), new Date('2026-11-01T23:30:00').getTime())
- console.log(JSON.stringify([spring, fall]))`
- const out = execFileSync(process.execPath, ['--input-type=module', '-e', script], { env: { ...process.env, TZ: 'America/New_York' } }).toString()
- assert.deepEqual(JSON.parse(out), [4, 2])
-})
-
test('a request during the first read gets the snapshot, not an empty answer', async () => {
let calls = 0
const slow = async () => { calls++; await new Promise((ok) => setTimeout(ok, 150)); return { spec: 1, observedAt: Date.now(), memories: [{ id: 'x', title: 't', description: '', body: '', modified: 1, size: 1 }], agents: [], projects: [] } }
@@ -110,7 +102,7 @@ test('second review: full-path privacy skip, worktree beats parent, literal bloc
assert.equal(projects.find((p) => p.name === 'autonomous-harness').sessions, 3)
assert.deepEqual(frontmatter('---\ndescription: |\n Triggers: build it\n and more\nname: z\n---\n').data, { description: 'Triggers: build it and more', name: 'z' })
- fast('brackets', () => parse('['.repeat(20_000)))
- fast('backticks', () => parse('`'.repeat(8_000) + ' text'))
+ fast('brackets', () => body('['.repeat(20_000)))
+ fast('backticks', () => body('`'.repeat(8_000) + ' text'))
assert.equal(parseAbout('## A\n-\titem\n').lines[0].text, 'item')
})
diff --git a/store/agents/memories/test/self.test.mjs b/store/agents/memories/test/self.test.mjs
new file mode 100644
index 000000000..41d195f37
--- /dev/null
+++ b/store/agents/memories/test/self.test.mjs
@@ -0,0 +1,249 @@
+/** Sense of Self without a browser: the render loop, the data it reads, and the mind it draws. */
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { agent, createMemoryData, refs } from '../viewer/memory-data.js'
+import { createLoop } from '../viewer/loop.js'
+import { buildMind, recallMatch } from '../viewer/self-model.js'
+import { snapshot } from '../lib/state.mjs'
+import { asks as readAsks, openIndex } from '../lib/sessions.mjs'
+import { homes } from '../lib/agents.mjs'
+import { growHome, makeHome } from './fixtures.mjs'
+
+// ── loop.js: one loop, only while visible, asleep when nothing moves ────────────────────────────
+
+/** Frames that run only when the test says so. */
+function frames() {
+ let next = 1
+ const queued = new Map()
+ return {
+ frame: (fn) => { const id = next++; queued.set(id, fn); return id },
+ cancelFrame: (id) => queued.delete(id),
+ pending: () => queued.size,
+ run(times = 1, at = 1000) { for (let n = 0; n < times; n++) { const batch = [...queued.values()]; queued.clear(); for (const fn of batch) fn(at + n * 16) } },
+ }
+}
+
+test('the loop draws only while the tab is visible', () => {
+ let hide = false
+ const clock = frames()
+ const loop = createLoop({ frame: clock.frame, cancelFrame: clock.cancelFrame, hidden: () => hide })
+ let drawn = 0
+ loop.set(() => { drawn++; return true })
+ clock.run(3)
+ assert.equal(drawn, 0, 'nothing before the pane says the tab is visible')
+ loop.start()
+ clock.run(3)
+ assert.equal(drawn, 3)
+ assert.equal(clock.pending(), 1, 'one frame at a time')
+ loop.stop()
+ assert.equal(clock.pending(), 0, 'hidden: the frame waiting is cancelled')
+ clock.run(5)
+ assert.equal(drawn, 3)
+ hide = true
+ loop.start()
+ assert.equal(clock.pending(), 0, 'a hidden document gets no frame even when asked')
+ hide = false
+ loop.wake()
+ clock.run(2)
+ assert.equal(drawn, 5)
+})
+
+test('a scene with nothing moving sleeps until woken, and one that throws stops', () => {
+ const clock = frames()
+ const errors = []
+ const loop = createLoop({ frame: clock.frame, cancelFrame: clock.cancelFrame, hidden: () => false, report: (error) => errors.push(error) })
+ let moving = 2
+ let drawn = 0
+ loop.start()
+ loop.set((at, dt) => { drawn++; assert.ok(dt >= 0 && dt <= 0.1); return moving-- > 0 })
+ clock.run(10)
+ assert.equal(drawn, 3, 'two frames moving, then one that says it is still')
+ assert.equal(clock.pending(), 0)
+ loop.wake(); loop.wake()
+ assert.equal(clock.pending(), 1, 'waking twice is one frame')
+ loop.set(() => { throw new Error('draw') })
+ clock.run(3)
+ assert.deepEqual(errors.map((error) => error.message), ['draw'])
+ assert.equal(clock.pending(), 0)
+})
+
+// ── self-model.js: the mind Sense of Self draws ─────────────────────────────────────────────────
+
+async function mindOf(made) {
+ const snap = await snapshot({ env: made.env, home: made.home, now: Date.now() })
+ const index = await openIndex(homes(made.env, made.home).harnessData)
+ const asks = index.db ? readAsks(index.db, { limit: 4000, maxChars: 400 }) : []
+ index.db?.close()
+ return { snap, asks, mind: buildMind({ snapshot: snap, asks }, { agent, refs }) }
+}
+
+test('a real-sized home: every memory in the lake, every line a belief held up by what it cites', async () => {
+ const made = growHome(makeHome())
+ const started = performance.now()
+ const { snap, asks, mind } = await mindOf(made)
+ const built = performance.now() - started
+ assert.equal(asks.length, 4000)
+ assert.ok(snap.memories.length >= 100, `${snap.memories.length} memories`)
+ assert.equal(mind.orbs.length, snap.memories.length, 'every memory is an orb')
+ assert.equal(mind.beliefs.length, 25)
+ assert.deepEqual(mind.sections.map((s) => s.name), ['How you work', 'What you want from agents', 'Taste', 'Engineering principles', 'Right now'])
+ assert.ok(mind.beliefs.every((b) => b.mems.length === 2 && b.askN > 0 && b.motes.length > 0), 'each belief: its two memories and its messages')
+ assert.ok(mind.orbs.some((o) => !o.beliefs.length), 'memories that hold up no belief stay in the lake')
+ assert.equal(mind.motes.n, 4000)
+ // Messages gather over their project: its folder, a folder in a worktree of it.
+ const payments = mind.columns.find((c) => c.name === 'payments')
+ assert.ok(payments.asks > 300 && payments.orbs.length >= 10, `payments: ${payments.asks} messages, ${payments.orbs.length} memories`)
+ const placed = mind.motes.col.filter(Boolean).length
+ assert.ok(placed > 3900, `${placed} of 4000 messages placed in a project`)
+ assert.ok(built < 5000, `built in ${Math.round(built)} ms`)
+})
+
+test('recall: memories by every word, your messages, and the beliefs they stir', async () => {
+ const { mind } = await mindOf(growHome(makeHome()))
+ const found = recallMatch(mind, 'release train payments')
+ assert.ok(found.mems.length >= 1 && found.mems[0].m.title === 'Release train', found.mems.map((o) => o.m.title).join(', '))
+ assert.ok(found.mems.every((o) => o.lp === 'payments' || o.lb.includes('payments')))
+ const words = recallMatch(mind, 'refund flow')
+ assert.ok(words.local.length > 50, `${words.local.length} messages`)
+ assert.ok(words.direct.some((b) => b.text.includes('refund')), 'a belief that says it')
+ assert.ok(words.beliefs.size >= words.direct.length)
+ assert.ok(words.local.every((i, n) => n === 0 || mind.asks[words.local[n - 1]].at >= mind.asks[i].at), 'newest first')
+ assert.deepEqual(recallMatch(mind, ' ').mems, [])
+})
+
+test('the quiet homes: no About You yet, and nothing at all', async () => {
+ const fresh = await mindOf(makeHome())
+ assert.equal(fresh.mind.beliefs.length, 0, 'no About You: no beliefs, and the scene says how to build one')
+ assert.ok(fresh.mind.orbs.length > 10)
+ assert.ok(fresh.mind.orbs.some((o) => o.lb.includes('<img src=x')), 'hostile text is still just a memory')
+ const empty = buildMind({ snapshot: { memories: [], agents: [], projects: [] }, asks: [] }, { agent, refs })
+ assert.deepEqual([empty.orbs.length, empty.beliefs.length, empty.motes.n, empty.columns.length], [0, 0, 0, 0])
+ const odd = buildMind({ snapshot: { about: { lines: [{ text: 'Cites nothing here.', refs: ['claude:gone.md', 'session:abc', 'asks:3'] }, { text: ' ' }] } }, asks: [] }, { agent, refs })
+ assert.equal(odd.beliefs.length, 1)
+ assert.deepEqual(odd.beliefs[0].threads.map((th) => th.kind), ['asks', 'session', 'missing'])
+})
+
+// ── memory-data.js: the MemoryData interface over this viewer's routes ──────────────────────────
+
+const SNAP = {
+ memories: [
+ { id: 'claude:.claude/projects/x/memory/short-answers.md', agent: 'claude', title: 'Short answers', path: '~/.claude/projects/x/memory/short-answers.md' },
+ { id: 'claude:.claude/projects/x/memory/b.md', agent: 'claude', title: 'Merge when green', path: '~/.claude/projects/x/memory/b.md' },
+ { id: 'codex:.codex/memories/MEMORY.md#1', agent: 'codex', title: 'Testing', path: '~/.codex/memories/MEMORY.md' },
+ ],
+ agents: [{ id: 'claude', name: 'Claude Code', color: '#d97757' }],
+ sessions: { asks: 4 },
+}
+
+function fakeFetch(routes) {
+ const calls = []
+ const fetch = async (path) => {
+ calls.push(path)
+ const route = Object.keys(routes).find((prefix) => path.startsWith(prefix))
+ if (!route) return { ok: false, status: 404, json: async () => ({}) }
+ const value = await routes[route](path)
+ return { ok: true, status: 200, json: async () => value }
+ }
+ return { fetch, calls }
+}
+
+test('load: the snapshot the pane received, and your messages read once', async () => {
+ const { fetch, calls } = fakeFetch({ '/api/asks': () => ({ asks: [{ at: 1, text: 'hi' }] }) })
+ const data = createMemoryData({ fetch, graceMs: 10_000 })
+ const loading = data.load()
+ data.receive(SNAP)
+ const loaded = await loading
+ assert.equal(loaded.snapshot, SNAP)
+ assert.deepEqual(loaded.asks, [{ at: 1, text: 'hi' }])
+ assert.equal(loaded.real, true)
+ assert.equal(loaded.asksError, null)
+ await data.load()
+ assert.deepEqual(calls, ['/api/asks'], 'no /api/state while /events delivers, and the messages once')
+ data.receive({ ...SNAP, observedAt: 2 })
+ await data.load()
+ assert.equal(calls.length, 1, 'a new snapshot with the same messages: not read again')
+ data.receive({ ...SNAP, sessions: { asks: 5 } })
+ await data.load()
+ assert.equal(calls.length, 2, 'new messages: read again')
+})
+
+test('load: no snapshot from /events in time, so /api/state', async () => {
+ const { fetch, calls } = fakeFetch({ '/api/state': () => SNAP, '/api/asks': () => ({ asks: [], error: 'No session index on this computer yet.' }) })
+ const data = createMemoryData({ fetch, graceMs: 5 })
+ const [a, b] = await Promise.all([data.load(), data.load()])
+ assert.equal(a.snapshot.memories.length, 3)
+ assert.equal(b.snapshot, a.snapshot)
+ assert.equal(a.asksError, 'No session index on this computer yet.')
+ assert.deepEqual(calls, ['/api/state', '/api/asks'], 'two loads, one read of each')
+ const viaPane = createMemoryData({ fetch: async () => { throw new Error('not this') }, graceMs: 5, fallback: async () => ({ ...SNAP, from: 'pane' }) })
+ assert.equal((await viaPane.load()).snapshot.from, 'pane', 'the pane’s own read, through its instance check')
+ const failing = createMemoryData({ fetch: async () => ({ ok: false, status: 503, json: async () => ({}) }), graceMs: 5 })
+ await assert.rejects(failing.load(), /503/)
+})
+
+test('search: one question asked once, shared by every view', async () => {
+ let answers = 0
+ const { fetch, calls } = fakeFetch({ '/api/search': () => ({ q: 'x', hits: [{ sessionId: `s${++answers}` }] }) })
+ const data = createMemoryData({ fetch })
+ data.receive(SNAP)
+ assert.deepEqual(await data.search(' '), [])
+ assert.equal(calls.length, 0)
+ const [one, two] = await Promise.all([data.search('release'), data.searchAnswer('release ')])
+ assert.deepEqual(one, two.hits)
+ assert.equal(calls.length, 1)
+ assert.equal(calls[0], '/api/search?q=release')
+ data.receive({ ...SNAP, sessions: { asks: 9 } })
+ await data.search('release')
+ assert.equal(calls.length, 2, 'new messages: asked again')
+ for (let n = 0; n < 12; n++) await data.search(`q${n}`)
+ await data.search('release')
+ assert.equal(calls.length, 2 + 12 + 1, 'only the last few questions are kept')
+ const down = createMemoryData({ fetch: async () => { throw new Error('offline') } })
+ assert.deepEqual(await down.searchAnswer('x'), { q: 'x', hits: [], error: 'Search is not available right now.' })
+})
+
+test('refs and agents, as the prototypes read them', () => {
+ const line = { refs: ['claude:short-answers.md', 'claude:merge-when-green.md', 'codex:MEMORY.md', 'asks:12', 'session:abc', 'nonsense', 'gemini:none.md'] }
+ assert.deepEqual(refs(line, SNAP).map((row) => row.title), ['Short answers', 'Merge when green', 'Testing'])
+ assert.deepEqual(refs({}, SNAP), [])
+ assert.deepEqual(refs(line, null), [])
+ assert.deepEqual(agent('claude', SNAP), { id: 'claude', name: 'Claude Code', color: '#d97757' })
+ assert.deepEqual(agent('amp', SNAP), { id: 'amp', name: 'Amp', color: '#c9a227' })
+ assert.equal(agent('zed', SNAP).color, '#8a8f98')
+ const data = createMemoryData({ fetch: async () => ({ ok: true, json: async () => ({}) }) })
+ data.receive(SNAP)
+ assert.equal(data.refs({ refs: ['claude:b.md'] })[0].title, 'Merge when green', 'the latest snapshot by default')
+ assert.equal(data.agent('claude').name, 'Claude Code')
+})
+
+test('onChange hears every snapshot after the first, and can stop', () => {
+ const data = createMemoryData({ fetch: async () => ({ ok: true, json: async () => ({}) }) })
+ const heard = []
+ const stop = data.onChange((snap) => heard.push(snap.observedAt))
+ data.onChange(() => { throw new Error('a broken listener') })
+ data.receive({ ...SNAP, observedAt: 1 })
+ data.receive({ ...SNAP, observedAt: 2 })
+ data.receive(null)
+ stop()
+ data.receive({ ...SNAP, observedAt: 3 })
+ assert.deepEqual(heard, [2])
+ assert.equal(data.snapshot().observedAt, 3)
+})
+
+test('a conversation and the conversations about a memory, from the viewer', async () => {
+ const { fetch, calls } = fakeFetch({
+ '/api/conversation': () => ({ sessionId: 's1', title: 'Fix login', cwd: '/w', turns: [{ turn: 0, at: 1, ask: 'hi', answer: 'hello' }] }),
+ '/api/related': () => ({ id: 'm', hits: [{ sessionId: 's1', turn: 0 }] }),
+ })
+ const data = createMemoryData({ fetch })
+ const found = await data.conversation('s 1/x', 3)
+ assert.deepEqual(found, { title: 'Fix login', cwd: '/w', turns: [{ turn: 0, at: 1, ask: 'hi', answer: 'hello' }], error: null })
+ assert.equal(calls[0], '/api/conversation?sessionId=s+1%2Fx&turn=3')
+ await data.conversation('s1', -1)
+ assert.equal(calls[1], '/api/conversation?sessionId=s1', 'a hit on the name has no turn')
+ assert.deepEqual(await data.related('claude:a b.md'), [{ sessionId: 's1', turn: 0 }])
+ assert.equal(calls[2], '/api/related?id=claude%3Aa%20b.md')
+ const down = createMemoryData({ fetch: async () => { throw new Error('offline') } })
+ assert.deepEqual((await down.conversation('s1', 0)).turns, [])
+ assert.deepEqual(await down.related('x'), [])
+})
diff --git a/store/agents/memories/test/viewer.test.mjs b/store/agents/memories/test/viewer.test.mjs
index c977cbb7c..6cf413cdc 100644
--- a/store/agents/memories/test/viewer.test.mjs
+++ b/store/agents/memories/test/viewer.test.mjs
@@ -5,8 +5,8 @@ import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { after, before, test } from 'node:test'
-import { createViewer } from '../viewer.mjs'
-import { makeHome } from './fixtures.mjs'
+import { ASKS_CHARS, ASKS_LIMIT, createViewer } from '../viewer.mjs'
+import { makeHome, sessionIndex } from './fixtures.mjs'
const { home, env } = makeHome()
const workspace = mkdtempSync(join(tmpdir(), 'memories-ws-'))
@@ -15,9 +15,9 @@ let viewer, port
before(async () => { viewer = createViewer({ workspace, env, home, intervalMs: 50 }); port = await viewer.start() })
after(async () => { await viewer.close() })
-function get(path, { method = 'GET', host = `127.0.0.1:${port}`, headers = {}, until } = {}) {
+function get(path, { port: to = port, method = 'GET', host = `127.0.0.1:${to}`, headers = {}, until } = {}) {
return new Promise((resolve, reject) => {
- const req = request({ host: '127.0.0.1', port, path, method, headers: { host, ...headers } }, (res) => {
+ const req = request({ host: '127.0.0.1', port: to, path, method, headers: { host, ...headers } }, (res) => {
let body = ''
res.on('data', (chunk) => {
body += chunk
@@ -38,7 +38,7 @@ test('the page is served with a policy that runs only its own scripts', async ()
const instance = /name="memories-instance" content="([0-9a-f]{12})"/.exec(page.body)?.[1]
assert.ok(instance, 'the page knows which viewer served it')
assert.equal(JSON.parse((await get('/api/state')).body).instance, instance, 'and the snapshot says the same, so a restart is noticed')
- for (const asset of ['/app.js', '/app.css', '/markdown.js', '/fuzzy.js', '/heatmap.js']) assert.equal((await get(asset)).status, 200, asset)
+ for (const asset of ['/app.js', '/app.css', '/self.css', '/self.js']) assert.equal((await get(asset)).status, 200, asset)
})
test('only loopback hosts and same-origin requests are answered; nothing can be posted', async () => {
@@ -75,3 +75,73 @@ test('the event stream opens with a snapshot', async () => {
assert.match(stream.headers['content-type'], /text\/event-stream/)
assert.match(stream.body, /^event: snapshot\ndata: \{/)
})
+
+test('your messages: newest first, from the session index', async () => {
+ const answer = JSON.parse((await get('/api/asks')).body)
+ assert.equal(answer.limit, ASKS_LIMIT)
+ assert.equal(answer.maxChars, ASKS_CHARS)
+ assert.deepEqual(answer.asks.map((ask) => ask.text).sort(), ['never release on fridays', 'no, too long again', 'please keep it short, tldr only', 'write the docs in plain words'], 'a turn with no ask is not a message')
+ assert.ok(answer.asks.every((ask, n) => n === 0 || answer.asks[n - 1].at >= ask.at), 'newest first')
+ assert.equal(answer.asks.at(-1).text, 'write the docs in plain words')
+ assert.deepEqual(Object.keys(answer.asks[0]).sort(), ['at', 'cwd', 'engine', 'length', 'sessionId', 'text', 'title', 'turn'])
+})
+
+test('your messages are answered only to this pane, and only read', async () => {
+ assert.equal((await get('/api/asks', { host: 'evil.example' })).status, 403)
+ assert.equal((await get('/api/asks', { host: `evil.example:${port}` })).status, 403)
+ assert.equal((await get('/api/asks', { headers: { origin: 'https://evil.example' } })).status, 403)
+ assert.equal((await get('/api/asks', { headers: { origin: 'null' } })).status, 403)
+ assert.equal((await get('/api/asks', { headers: { 'sec-fetch-site': 'cross-site' } })).status, 403)
+ assert.equal((await get('/api/asks', { headers: { 'sec-fetch-site': 'same-site' } })).status, 403)
+ assert.equal((await get('/api/asks', { headers: { 'sec-fetch-site': 'same-origin', origin: `http://127.0.0.1:${port}` } })).status, 200)
+ assert.equal((await get('/api/asks', { headers: { 'sec-fetch-site': 'none' } })).status, 200)
+ assert.equal((await get('/api/asks', { host: `localhost:${port}` })).status, 200)
+ for (const method of ['POST', 'PUT', 'DELETE']) assert.equal((await get('/api/asks', { method })).status, 405, method)
+ const head = await get('/api/asks', { method: 'HEAD' })
+ assert.equal(head.status, 200)
+ assert.equal(head.body, '')
+ assert.equal(head.headers['cache-control'], 'no-store')
+})
+
+test('your messages: at most 4000, each at most 400 characters, whatever the page asks for', async () => {
+ const many = mkdtempSync(join(tmpdir(), 'memories-many-'))
+ const long = `${'word '.repeat(300)}end`
+ sessionIndex(join(many, '.harness', 'cli', 'data'), {
+ turns: Array.from({ length: ASKS_LIMIT + 150 }, (_, n) => ({ session: `s${n % 40}`, engine: n % 2 ? 'codex' : 'claude', cwd: '/work', title: 'Many', ask: n === 0 ? long : `message ${n}`, daysAgo: n / 100 })),
+ })
+ const other = createViewer({ env: { MEMORIES_HOME: join(many, '.harness', 'memory') }, home: many, intervalMs: 60_000 })
+ const otherPort = await other.start()
+ try {
+ const answer = JSON.parse((await get('/api/asks?limit=999999&maxChars=999999&since=0', { port: otherPort })).body)
+ assert.equal(answer.asks.length, ASKS_LIMIT)
+ const first = answer.asks.find((ask) => ask.text.startsWith('word'))
+ assert.equal(first.text.length, ASKS_CHARS)
+ assert.equal(first.length, long.length, 'the full length is still said')
+ assert.ok(answer.asks.every((ask) => ask.text.length <= ASKS_CHARS))
+ } finally { await other.close() }
+})
+
+test('your messages with no session index: none, and why', async () => {
+ const bare = mkdtempSync(join(tmpdir(), 'memories-bare-'))
+ const other = createViewer({ env: { MEMORIES_HOME: join(bare, '.harness', 'memory') }, home: bare, intervalMs: 60_000 })
+ const otherPort = await other.start()
+ try {
+ const answer = JSON.parse((await get('/api/asks', { port: otherPort })).body)
+ assert.deepEqual(answer.asks, [])
+ assert.match(answer.error, /No session index/)
+ } finally { await other.close() }
+})
+
+test('one page: the header with its switch, and Sense of Self under it; nothing else is served', async () => {
+ for (const asset of ['/self.js', '/self-model.js', '/loop.js', '/memory-data.js']) {
+ const answer = await get(asset)
+ assert.equal(answer.status, 200, asset)
+ assert.match(answer.headers['content-type'], /text\/javascript/)
+ }
+ assert.match((await get('/self.css')).headers['content-type'], /text\/css/)
+ for (const gone of ['/markdown.js', '/fuzzy.js', '/heatmap.js', '/views.js']) assert.equal((await get(gone)).status, 404, gone)
+ const page = await get('/')
+ for (const id of ['q', 'count', 'switch', 'switch-button', 'stage']) assert.match(page.body, new RegExp(`id="${id}"`), id)
+ for (const gone of ['list', 'preview', 'band', 'views']) assert.doesNotMatch(page.body, new RegExp(`id="${gone}"`), gone)
+ assert.doesNotMatch(page.body, /<script(?![^>]*\bsrc=)/, 'no inline script')
+})
diff --git a/store/agents/memories/viewer.mjs b/store/agents/memories/viewer.mjs
index 8ca345881..a5b297637 100644
--- a/store/agents/memories/viewer.mjs
+++ b/store/agents/memories/viewer.mjs
@@ -1,7 +1,8 @@
/**
* The Memories pane: a loopback server that reads every agent's memory and the session index, and
- * serves one page to browse them. It never writes anything an agent owns and needs no model: opening
- * the pane sends no prompt. The only file it writes is the pane header's verdict.
+ * serves one page to see them: Sense of Self, About You held up by every memory (viewer/self.js). It
+ * never writes anything an agent owns and needs no model: opening the pane sends no prompt. The only
+ * file it writes is the pane header's verdict.
*
* While a pane is connected it looks again every few seconds and pushes a new snapshot when anything
* changed — an agent saved a memory, the About You was rebuilt, you finished a turn somewhere.
@@ -16,7 +17,7 @@ import { homes } from './lib/agents.mjs'
import { noteSeen, writeAbout } from './lib/about.mjs'
import { DEFAULT_CHOICE_AT, deliver } from './lib/deliver.mjs'
import { askMachines, merge, newestChoice, syncAbout, syncChoice } from './lib/fleet.mjs'
-import { around, headings, search } from './lib/sessions.mjs'
+import { around, asks, headings, search } from './lib/sessions.mjs'
import { closeIndex, fingerprint, sessionIndex, snapshot as takeSnapshot, writeVerdict } from './lib/state.mjs'
const PACKAGE = dirname(fileURLToPath(import.meta.url))
@@ -24,10 +25,16 @@ const ASSETS = {
'/': ['index.html', 'text/html; charset=utf-8'],
'/app.js': ['app.js', 'text/javascript; charset=utf-8'],
'/app.css': ['app.css', 'text/css; charset=utf-8'],
- '/markdown.js': ['markdown.js', 'text/javascript; charset=utf-8'],
- '/fuzzy.js': ['fuzzy.js', 'text/javascript; charset=utf-8'],
- '/heatmap.js': ['heatmap.js', 'text/javascript; charset=utf-8'],
+ '/self.css': ['self.css', 'text/css; charset=utf-8'],
+ '/self.js': ['self.js', 'text/javascript; charset=utf-8'],
+ '/self-model.js': ['self-model.js', 'text/javascript; charset=utf-8'],
+ '/loop.js': ['loop.js', 'text/javascript; charset=utf-8'],
+ '/memory-data.js': ['memory-data.js', 'text/javascript; charset=utf-8'],
}
+// What /api/asks answers: the person's latest messages, cut short. Fixed, not asked for: a page can
+// never read more of what the person typed than the scene draws as mist.
+export const ASKS_LIMIT = 4000
+export const ASKS_CHARS = 400
const STOP = new Set(['the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'your', 'you', 'are', 'not', 'but', 'use', 'when', 'what', 'how', 'why', 'all', 'any', 'one', 'its', 'has', 'have', 'was', 'were', 'out', 'new', 'via', 'per'])
/**
@@ -245,6 +252,12 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, env = pro
} catch (error) { return { turns: [], error: String(error?.message ?? error) } }
}
+ async function recentAsks() {
+ const index = await sessionIndex(homes(env, home))
+ if (!index.db) return { asks: [], error: index.error }
+ try { return { asks: asks(index.db, { limit: ASKS_LIMIT, maxChars: ASKS_CHARS }) } } catch (error) { return { asks: [], error: String(error?.message ?? error) } }
+ }
+
const server = createServer(async (req, res) => {
try {
const address = server.address()
@@ -287,6 +300,12 @@ export function createViewer({ workspace, port = 0, intervalMs = 4000, env = pro
json(res, 200, sessionId ? await conversation(sessionId, Number.isInteger(turn) ? turn : null) : { turns: [] })
return
}
+ if (url.pathname === '/api/asks') {
+ // Your own latest messages, the mist over the lake (viewer/memory-data.js). Takes no
+ // parameters: how many and how long is fixed here.
+ json(res, 200, { limit: ASKS_LIMIT, maxChars: ASKS_CHARS, ...(await recentAsks()) })
+ return
+ }
if (url.pathname === '/api/related') {
// Conversations that talk about the same thing as a memory: its title and description, any word.
const row = (current ?? await look())?.memories.find((memory) => memory.id === url.searchParams.get('id'))
diff --git a/store/agents/memories/viewer/app.css b/store/agents/memories/viewer/app.css
index c04cd7127..dc8fdb7b1 100644
--- a/store/agents/memories/viewer/app.css
+++ b/store/agents/memories/viewer/app.css
@@ -55,121 +55,8 @@ kbd { font: inherit; color: var(--text); }
.switch-detail:empty { display: none; }
.switch-problem { padding: 6px 14px; border-bottom: 1px solid var(--line); color: var(--accent); }
-/* ── band: your year with agents ────────────────────────────────────────────────────────────── */
-.band { display: flex; gap: 22px; align-items: flex-start; padding: 14px 14px 12px; border-bottom: 1px solid var(--line); overflow: hidden; }
-.heat { flex: 0 1 auto; min-width: 0; }
-#heat { display: block; overflow: visible; }
-#heat rect { shape-rendering: crispEdges; }
-#heat rect.cell { fill: var(--cell); }
-#heat rect.today { stroke: var(--text); stroke-width: 1; }
-#heat text { fill: var(--faint); font: 10px var(--mono); }
-.heat-note { color: var(--faint); font-size: 11px; margin-top: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
-.stats { flex: 1 1 220px; min-width: 200px; }
-.big { display: flex; align-items: baseline; gap: 8px; }
-.big span { font-size: 26px; font-weight: 700; letter-spacing: -.02em; }
-.big small { color: var(--muted); font-size: 11.5px; }
-.stat-line { color: var(--muted); margin: 2px 0 8px; }
-.bar { display: flex; height: 6px; border-radius: 1px; overflow: hidden; background: var(--cell); }
-.bar span { display: block; height: 100%; }
-.legend { display: flex; flex-wrap: wrap; gap: 2px 12px; margin-top: 7px; font-size: 11.5px; }
-.legend span::before { content: "■ "; color: var(--swatch); }
-.legend b { font-weight: 400; color: var(--muted); }
-/* ── split: the list and the preview ────────────────────────────────────────────────────────── */
-.split { flex: 1; display: grid; grid-template-columns: minmax(280px, 44%) 1fr; min-height: 0; }
-.list { overflow-y: auto; padding: 4px 0 18px; border-right: 1px solid var(--line); outline: none; }
-.preview { overflow-y: auto; padding: 14px 18px 40px; min-width: 0; }
-
-.group { display: flex; align-items: baseline; gap: 8px; padding: 12px 14px 3px; color: var(--faint); font-size: 10.5px; letter-spacing: .12em; text-transform: uppercase; cursor: pointer; user-select: none; }
-.group:hover { color: var(--muted); }
-.group .n { letter-spacing: 0; }
-.group .fold { width: 1ch; }
-.section { padding: 7px 14px 1px 26px; color: var(--muted); font-size: 11px; }
-
-.row { position: relative; display: flex; align-items: baseline; gap: 8px; height: 23px; padding: 0 14px 0 12px; white-space: nowrap; cursor: default; }
-.row:hover { background: var(--panel); }
-.row .gutter { width: 1ch; color: var(--accent); }
-.row .dot { width: 1ch; flex: none; }
-.row .label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
-.row .label .soft { color: var(--muted); }
-.row .tag { color: var(--muted); font-size: 11.5px; flex: none; }
-.row .age { color: var(--faint); font-size: 11.5px; width: 4ch; text-align: right; flex: none; }
-.row.depth1 { padding-left: 30px; }
-.row.muted .label { color: var(--faint); font-style: italic; }
-.row.build .label { color: var(--accent); }
-.row[aria-selected="true"] { background: var(--select); color: var(--select-text); }
-.row[aria-selected="true"] .tag, .row[aria-selected="true"] .age, .row[aria-selected="true"] .soft { color: inherit; opacity: .75; }
-.row[aria-selected="true"] .gutter { color: inherit; }
-.row.recent .dot::after { content: ""; }
-.row.fresh { animation: fresh 6s ease-out; }
-@keyframes fresh { 0% { background: color-mix(in srgb, var(--glow, var(--accent)) 45%, transparent); } 100% { background: transparent; } }
-.empty-list { padding: 18px 14px; color: var(--muted); }
-
-/* ── preview ────────────────────────────────────────────────────────────────────────────────── */
-.pv-title { font-size: 15px; font-weight: 700; line-height: 1.35; margin: 0 0 4px; letter-spacing: -.01em; }
-.pv-meta { color: var(--muted); }
-.pv-meta .who { font-weight: 700; }
-.pv-path { color: var(--faint); font-size: 11.5px; margin-top: 2px; word-break: break-all; user-select: all; }
-.pv-rule { border: 0; border-top: 1px dashed var(--line); margin: 12px 0; }
-.pv-h { color: var(--faint); font-size: 10.5px; letter-spacing: .12em; text-transform: uppercase; margin: 18px 0 6px; }
-.pv-text { white-space: pre-wrap; }
-.pv-big { font-size: 15px; line-height: 1.5; margin: 6px 0 10px; }
-.kv { display: grid; grid-template-columns: max-content 1fr; gap: 2px 14px; margin: 8px 0; }
-.kv dt { color: var(--faint); }
-.kv dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
-.code { background: var(--panel); border: 1px solid var(--line); border-radius: 3px; padding: 8px 10px; white-space: pre-wrap; margin: 6px 0; }
-.hit { display: flex; gap: 8px; align-items: baseline; padding: 3px 6px; margin: 0 -6px; border-radius: 2px; cursor: pointer; }
-.hit:hover { background: var(--panel); }
-.hit .who { flex: none; width: 9ch; overflow: hidden; text-overflow: ellipsis; font-weight: 700; }
-.hit .what { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.hit .when { flex: none; color: var(--faint); }
-.snippet { color: var(--muted); }
-mark { background: var(--mark); color: var(--mark-text); border-radius: 2px; padding: 0 1px; }
-.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0; }
-.chip { border: 1px solid var(--line); border-radius: 2px; padding: 0 6px; color: var(--muted); background: transparent; cursor: pointer; }
-.chip:hover { border-color: var(--muted); color: var(--text); }
-.mini { display: flex; height: 4px; width: 220px; max-width: 100%; margin: 6px 0 2px; background: var(--cell); }
-.mini span { display: block; height: 100%; }
-.callout { border-left: 2px solid var(--accent); padding: 4px 0 4px 12px; margin: 10px 0; }
-.callout .say { color: var(--accent); font-weight: 700; }
-
-/* Markdown, rendered as a terminal pager would: no big headings, no colors beyond emphasis. */
-.md { line-height: 1.6; }
-.md h3, .md h4, .md h5, .md h6, .md h7, .md h8 { font-size: 12.5px; margin: 14px 0 4px; }
-.md h3 { color: var(--accent); }
-.md h3::before { content: "# "; color: var(--faint); }
-.md h4::before { content: "## "; color: var(--faint); }
-.md p { margin: 0 0 9px; }
-.md ul, .md ol { margin: 0 0 9px; padding-left: 2.2ch; }
-.md li { margin: 1px 0; }
-.md ul { list-style: none; }
-.md ul > li::before { content: "– "; color: var(--faint); margin-left: -2ch; }
-.md li[data-checked="true"]::before { content: "✓ "; color: #3fae8c; }
-.md li[data-checked="false"]::before { content: "□ "; }
-.md code { background: var(--panel); border-radius: 2px; padding: 0 3px; }
-.md pre { background: var(--panel); border: 1px solid var(--line); border-radius: 3px; padding: 8px 10px; overflow-x: auto; white-space: pre; }
-.md blockquote { margin: 0 0 9px; padding-left: 12px; border-left: 2px solid var(--line); color: var(--muted); }
-.md hr { border: 0; border-top: 1px dashed var(--line); margin: 12px 0; }
-.md strong { font-weight: 700; }
-.md em { font-style: italic; }
-.md .md-link { text-decoration: underline dotted var(--faint); text-underline-offset: 2px; }
-
-/* ── footer: the keys, like fzf's header ────────────────────────────────────────────────────── */
-.keys { display: flex; gap: 16px; padding: 5px 14px; border-top: 1px solid var(--line); color: var(--faint); font-size: 11px; white-space: nowrap; overflow: hidden; }
-.keys kbd { color: var(--muted); }
-.keys .spacer { flex: 1; }
+/* ── the stage: Sense of Self (self.css) fills everything under the header ─────────────────── */
+.stage { flex: 1; min-height: 0; }
:focus-visible { outline: 1px solid var(--muted); outline-offset: -1px; }
-
-/* A narrow pane: one column; the preview takes over while reading and ← comes back. */
-@media (max-width: 760px) {
- .band { flex-direction: column; gap: 10px; }
- .stats { flex: none; width: 100%; }
- .split { grid-template-columns: 1fr; }
- .list { border-right: 0; }
- .preview { display: none; }
- body.reading .list { display: none; }
- body.reading .preview { display: block; }
- .keys span:nth-child(n+3):not(.spacer):not(#updated) { display: none; }
-}
-@media (prefers-reduced-motion: reduce) { .row.fresh { animation: none; } }
diff --git a/store/agents/memories/viewer/app.js b/store/agents/memories/viewer/app.js
index 9244b8f6e..14f83c749 100644
--- a/store/agents/memories/viewer/app.js
+++ b/store/agents/memories/viewer/app.js
@@ -1,76 +1,21 @@
/**
- * The Memories pane. One job: browse what your agents remember, beside how you actually work.
+ * The Memories pane: Sense of Self (self.js), what your agents believe about you, held up by every
+ * memory they keep, under a one-row header with the About You switch.
*
- * The prompt is always focused, as in fzf: type to filter, ↑↓ to move, → or ⏎ to open, ← to go back,
- * esc to clear. Everything a memory says is rendered as text (markdown.js); nothing in this file ever
- * assigns HTML.
+ * The header prompt is always focused, as in fzf: typing anywhere types there, and what it holds is the
+ * scene's recall. The scene reads its data through memory-data.js and draws in the pane's one render
+ * loop (loop.js), which runs only while the tab is visible. Nothing in this file assigns HTML.
*/
-import { parse, render } from './markdown.js'
-import { scoreFields } from './fuzzy.js'
-import { buildGrid } from './heatmap.js'
+import { agent as agentOf, createMemoryData } from './memory-data.js'
+import { createLoop } from './loop.js'
+import { mountSelf } from './self.js'
const $ = (id) => document.getElementById(id)
-const el = (tag, className, text) => {
- const node = document.createElement(tag)
- if (className) node.className = className
- if (text !== undefined && text !== null) node.textContent = String(text)
- return node
-}
-
-const state = {
- snap: null,
- query: '',
- closed: new Set(),
- expanded: new Set(),
- selected: null,
- rows: [],
- hits: { q: '', items: [], error: null },
- related: new Map(),
- known: null,
- fresh: new Map(),
-}
-
-// ── helpers ────────────────────────────────────────────────────────────────────────────────────
-
-const FALLBACK = { amp: '#c9a227', kilo: '#5fb3b3', devin: '#6aa6f8', muse: '#c77dff', agy: '#8bd3a0', commandcode: '#d4a5a5' }
-function agent(id) {
- const known = state.snap?.agents.find((row) => row.id === id)
- if (known) return known
- return { id, name: id ? id[0].toUpperCase() + id.slice(1) : 'Unknown', color: FALLBACK[id] ?? '#8a8f98' }
-}
+const state = { snap: null }
+const agent = (id) => agentOf(id, state.snap)
const number = (n) => Number(n ?? 0).toLocaleString()
-function age(at, now = Date.now()) {
- if (!at) return ''
- const minutes = Math.max(0, (now - at) / 60_000)
- if (minutes < 1) return 'now'
- if (minutes < 60) return `${Math.round(minutes)}m`
- if (minutes < 48 * 60) return `${Math.round(minutes / 60)}h`
- if (minutes < 14 * 1440) return `${Math.round(minutes / 1440)}d`
- if (minutes < 120 * 1440) return `${Math.round(minutes / 10080)}w`
- return new Date(at).toLocaleDateString(undefined, { month: 'short', year: '2-digit' })
-}
-const longAge = (at) => {
- const short = age(at)
- if (!short) return ''
- if (short === 'now') return 'just now'
- const unit = { m: 'minutes', h: 'hours', d: 'days', w: 'weeks' }[short.at(-1)]
- return unit ? `${short.slice(0, -1)} ${unit} ago` : short
-}
-const kindLabel = (row) => row.type && row.type !== row.kind ? row.type : row.kind
-/** More than one machine answered: rows then say which machine they live on. */
-const manyMachines = () => (state.snap?.machines ?? []).filter((machine) => machine.ok).length > 1
-const where = (memory) => (manyMachines() && memory.machine ? memory.machine.name : null)
-
-const short = (id) => agent(id).name.split(' ')[0].toLowerCase()
-
-function who(id, tag = 'span', name = agent(id).name) {
- const info = agent(id)
- const node = el(tag, 'who', name)
- node.style.color = info.color
- return node
-}
// ── the switch: About You in every agent ───────────────────────────────────────────────────────
@@ -90,8 +35,7 @@ function drawSwitch() {
button.setAttribute('aria-checked', String(on))
$('switch-word').textContent = switching ? '…' : on ? 'ON' : 'OFF'
button.disabled = switching || !delivery.built
- // One row: the switch and, beside it, only what explains its state. Which agents get it and what it
- // costs are in About You's own panel; machines that need an update are in the machines list.
+ // One row: the switch and, beside it, only what explains its state.
const machines = (snap.machines ?? [])
const names = (delivery.agents ?? []).filter((row) => row.delivered).map((row) => agent(row.agent).name)
const onMachines = 1 + machines.filter((machine) => !machine.current && machine.ok && machine.deliveryOn).length
@@ -127,598 +71,6 @@ $('switch-button').addEventListener('click', async () => {
$('q').focus()
})
-// ── the band: your year with agents ────────────────────────────────────────────────────────────
-
-function drawBand() {
- const sessions = state.snap?.sessions
- const band = $('band')
- if (!sessions || !sessions.asks) { band.hidden = true; return }
- band.hidden = false
-
- const width = band.clientWidth - 28
- const statsWidth = width > 760 ? 300 : 0
- const fit = Math.floor((width - statsWidth - 30) / 12)
- const span = sessions.firstAt ? Math.ceil((Date.now() - sessions.firstAt) / (7 * 86_400_000)) + 2 : 26
- const weeks = Math.max(12, Math.min(53, fit, Math.max(span, 20)))
- const grid = buildGrid(sessions.activity, { weeks })
-
- const svg = $('heat')
- const ns = 'http://www.w3.org/2000/svg'
- svg.replaceChildren()
- const size = 10, gap = 2, left = 22, top = 14
- svg.setAttribute('width', String(left + weeks * (size + gap)))
- svg.setAttribute('height', String(top + 7 * (size + gap)))
- const label = (x, y, text) => { const t = document.createElementNS(ns, 'text'); t.setAttribute('x', String(x)); t.setAttribute('y', String(y)); t.textContent = text; svg.append(t) }
- label(0, top + 1 * (size + gap) + 8, 'tue')
- label(0, top + 3 * (size + gap) + 8, 'thu')
- label(0, top + 5 * (size + gap) + 8, 'sat')
- let lastMonth = null
- const today = new Date().toDateString()
- grid.columns.forEach((column, week) => {
- const first = column.find(Boolean)
- if (first) {
- const month = new Date(first.at).getMonth()
- if (month !== lastMonth && new Date(first.at).getDate() <= 7) label(left + week * (size + gap), 9, new Date(first.at).toLocaleDateString(undefined, { month: 'short' }).toLowerCase())
- if (lastMonth === null || new Date(first.at).getDate() <= 7) lastMonth = month
- }
- column.forEach((day, d) => {
- if (!day) return
- const rect = document.createElementNS(ns, 'rect')
- rect.setAttribute('x', String(left + week * (size + gap)))
- rect.setAttribute('y', String(top + d * (size + gap)))
- rect.setAttribute('width', String(size)); rect.setAttribute('height', String(size)); rect.setAttribute('rx', '1.5')
- if (day.total > 0) {
- rect.setAttribute('fill', agent(day.top).color)
- rect.setAttribute('fill-opacity', String([0, 0.32, 0.55, 0.78, 1][day.level]))
- } else rect.setAttribute('class', 'cell')
- if (new Date(day.at).toDateString() === today) rect.classList.add('today')
- const title = document.createElementNS(ns, 'title')
- const parts = Object.entries(day.agents).sort((a, b) => b[1] - a[1]).map(([engine, n]) => `${agent(engine).name} ${number(n)}`)
- title.textContent = `${new Date(day.at).toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })} · ${day.total ? `${number(day.total)} messages — ${parts.join(', ')}` : 'no messages'}`
- rect.append(title)
- svg.append(rect)
- })
- })
- const notes = []
- if (grid.max.total) notes.push(`busiest ${new Date(grid.max.day + 'T12:00').toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} (${number(grid.max.total)})`)
- notes.push(`${grid.activeDays} active days`)
- if (grid.streak > 1) notes.push(`${grid.streak}-day streak`)
- $('heat-note').textContent = notes.join(' · ')
-
- $('stat-asks').textContent = number(sessions.asks)
- const agents = sessions.engines.filter((row) => row.asks > 0)
- const since = sessions.firstAt ? new Date(sessions.firstAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : ''
- const answered = (state.snap.machines ?? []).filter((machine) => machine.ok).length
- $('stat-line').textContent = `${number(sessions.sessions)} sessions · ${agents.length} ${agents.length === 1 ? 'agent' : 'agents'}${answered > 1 ? ` · ${answered} machines` : ''}${since ? ` · since ${since}` : ''}`
- const bar = $('bar'), legend = $('legend')
- bar.replaceChildren(); legend.replaceChildren()
- for (const row of agents) {
- const share = row.asks / sessions.asks
- const piece = el('span'); piece.style.width = `${(share * 100).toFixed(2)}%`; piece.style.background = agent(row.engine).color
- piece.title = `${agent(row.engine).name}: ${number(row.asks)} messages`
- bar.append(piece)
- const item = el('span', null, `${agent(row.engine).name} `)
- item.style.setProperty('--swatch', agent(row.engine).color)
- item.append(el('b', null, share >= 0.01 ? `${Math.round(share * 100)}%` : '<1%'))
- legend.append(item)
- }
-}
-
-// ── rows: what the list shows ──────────────────────────────────────────────────────────────────
-
-function memoryRow(memory, depth = 0, parent = null) {
- return { key: `m:${memory.id}${parent ? `@${parent}` : ''}`, type: 'memory', memory, depth, parent }
-}
-
-function buildRows() {
- const snap = state.snap
- if (!snap) return []
- const rows = []
- const memories = snap.memories
- const group = (id, label, count) => {
- rows.push({ key: `g:${id}`, type: 'group', id, label, count, open: !state.closed.has(id) })
- return !state.closed.has(id)
- }
-
- if (state.query.trim()) {
- const q = state.query
- const scored = []
- for (const memory of memories) {
- // Only the title is matched loosely (fzf-style); longer text must contain the words as typed, or a
- // short query matches nearly every description as a scattered subsequence.
- const score = scoreFields(q, [[memory.title, 3], [memory.description, 2, true], [memory.project?.name, 1.5, true], [agent(memory.agent).name, 1, true], [memory.type, 1, true], [memory.body, 1, true]])
- if (score > 0) scored.push([score, memory])
- }
- for (const [n, line] of (snap.about?.lines ?? []).entries()) {
- const score = scoreFields(q, [[line.text, 3, true], [line.section, 1, true]])
- if (score > 0) scored.push([score + 50, { about: n, line }])
- }
- scored.sort((a, b) => b[0] - a[0])
- if (group('found', 'memories', scored.length)) {
- for (const [, item] of scored.slice(0, 300)) rows.push(item.line ? { key: `a:${item.about}`, type: 'about', line: item.line, index: item.about } : memoryRow(item))
- if (!scored.length) rows.push({ key: 'empty:found', type: 'empty', label: 'No memory says that.' })
- }
- const hits = state.hits.q === q.trim() ? state.hits.items : []
- if (group('sessions', 'in your sessions', hits.length)) {
- for (const hit of hits) rows.push({ key: `s:${hit.sessionId}`, type: 'session', hit })
- if (!hits.length) rows.push({ key: 'empty:sessions', type: 'empty', label: state.hits.q === q.trim() ? (state.hits.error ?? 'No conversation says that.') : 'Searching…' })
- }
- return rows
- }
-
- const yours = memories.filter((memory) => memory.kind === 'you')
- const aboutLines = snap.about?.lines ?? []
- if (group('about', 'about you', aboutLines.length + yours.length)) {
- if (aboutLines.length) {
- let section = null
- aboutLines.forEach((line, n) => {
- if (line.section !== section) { section = line.section; rows.push({ key: `h:${section}`, type: 'section', label: section }) }
- rows.push({ key: `a:${n}`, type: 'about', line, index: n })
- })
- } else rows.push({ key: 'build', type: 'build' })
- if (yours.length) {
- if (aboutLines.length) rows.push({ key: 'h:saved', type: 'section', label: 'Saved by your agents' })
- for (const memory of yours) rows.push(memoryRow(memory))
- }
- }
-
- if (group('projects', 'projects', snap.projects.length)) {
- for (const project of snap.projects) {
- const key = `p:${project.key}`
- const open = state.expanded.has(key)
- rows.push({ key, type: 'project', project, open })
- if (open) for (const id of project.memories) { const memory = memories.find((row) => row.id === id); if (memory) rows.push(memoryRow(memory, 1, key)) }
- }
- if (!snap.projects.length) rows.push({ key: 'empty:projects', type: 'empty', label: 'No agent has saved anything about a project yet.' })
- }
-
- const notes = memories.filter((memory) => ['note', 'summary', 'reference'].includes(memory.kind) && !memory.project)
- if (notes.length && group('notes', 'notes and summaries', notes.length)) for (const memory of notes) rows.push(memoryRow(memory))
-
- const told = memories.filter((memory) => memory.kind === 'instructions')
- if (told.length && group('told', 'what you told them', told.length)) for (const memory of told) rows.push(memoryRow(memory))
-
- const agents = snap.agents.filter((row) => row.present || row.memories || row.sessions)
- if (group('agents', 'agents', agents.length)) {
- for (const info of agents) {
- const key = `ag:${info.id}`
- const own = memories.filter((memory) => memory.agent === info.id && memory.kind !== 'instructions')
- const open = state.expanded.has(key)
- rows.push({ key, type: 'agent', agent: info, open, children: own.length })
- if (open) for (const memory of own) rows.push(memoryRow(memory, 1, key))
- }
- }
- return rows
-}
-
-const selectable = (row) => row && !['group', 'section', 'empty'].includes(row.type)
-
-// ── the list ───────────────────────────────────────────────────────────────────────────────────
-
-function drawList({ keepScroll = true } = {}) {
- const list = $('list')
- const scroll = list.scrollTop
- state.rows = buildRows()
- if (!state.rows.some((row) => row.key === state.selected && selectable(row))) {
- state.selected = state.rows.find(selectable)?.key ?? null
- }
- const now = Date.now()
- const fragment = document.createDocumentFragment()
- for (const row of state.rows) fragment.append(drawRow(row, now))
- list.replaceChildren(fragment)
- if (!state.rows.length) list.append(el('div', 'empty-list', 'Reading your agents…'))
- if (keepScroll) list.scrollTop = scroll
- const total = state.snap ? state.snap.memories.filter((row) => row.kind !== 'instructions').length : 0
- const shown = state.query.trim() ? state.rows.filter((row) => row.type === 'memory' || row.type === 'about').length : total
- $('count').textContent = state.snap ? (state.query.trim() ? `${shown}/${total}` : `${total}`) : ''
- revealSelected()
- drawPreview()
-}
-
-function drawRow(row, now) {
- if (row.type === 'group') {
- const node = el('div', 'group')
- node.append(el('span', 'fold', row.open ? '▾' : '▸'), el('span', null, row.label), el('span', 'n', row.count ? String(row.count) : ''))
- node.addEventListener('click', () => {
- const opening = state.closed.has(row.id)
- if (opening) state.closed.delete(row.id); else state.closed.add(row.id)
- drawList()
- // Opening a group puts the cursor on its first row, so the preview shows something at once.
- if (opening) {
- const index = state.rows.findIndex((r) => r.key === row.key)
- const next = state.rows.findIndex((r, i) => i > index && r.type === 'group')
- const first = state.rows.slice(index + 1, next < 0 ? undefined : next).find(selectable)
- if (first) select(first.key)
- }
- })
- return node
- }
- if (row.type === 'section') return el('div', 'section', row.label)
- if (row.type === 'empty') { const node = el('div', 'row muted'); node.append(el('span', 'gutter'), el('span', 'label', row.label)); return node }
-
- const node = el('div', `row${row.depth ? ` depth${row.depth}` : ''}`)
- node.setAttribute('role', 'option')
- node.dataset.key = row.key
- node.setAttribute('aria-selected', String(row.key === state.selected))
- const gutter = el('span', 'gutter', row.key === state.selected ? '▌' : '')
- const label = el('span', 'label')
- node.append(gutter)
-
- if (row.type === 'memory') {
- const memory = row.memory
- const dot = el('span', 'dot', '•'); dot.style.color = agent(memory.agent).color
- label.textContent = memory.title
- const tag = el('span', 'tag', [row.parent?.startsWith('ag:') ? kindLabel(memory) : short(memory.agent), where(memory)].filter(Boolean).join(' · '))
- node.append(dot, label, tag, el('span', 'age', age(memory.modified, now)))
- if (state.fresh.has(memory.id) && now - state.fresh.get(memory.id) < 6000) { node.classList.add('fresh'); node.style.setProperty('--glow', agent(memory.agent).color) }
- } else if (row.type === 'about') {
- node.append(el('span', 'dot', '✦'))
- label.textContent = row.line.text
- node.append(label, el('span', 'tag', row.line.refs.length ? `${row.line.refs.length} src` : ''))
- } else if (row.type === 'build') {
- node.classList.add('build')
- node.append(el('span', 'dot', '✦'))
- label.textContent = 'Build your About You'
- node.append(label, el('span', 'tag', 'ask the agent →'))
- } else if (row.type === 'project') {
- const project = row.project
- node.append(el('span', 'dot', row.open ? '▾' : '▸'))
- label.append(el('span', null, project.name), el('span', 'soft', ` ${project.memories.length} ${project.memories.length === 1 ? 'memory' : 'memories'}`))
- node.append(label, el('span', 'tag', project.sessions ? `${number(project.sessions)} ${project.sessions === 1 ? 'session' : 'sessions'}` : ''), el('span', 'age', age(project.lastAt, now)))
- } else if (row.type === 'agent') {
- const info = row.agent
- const dot = el('span', 'dot', row.children ? (row.open ? '▾' : '▸') : '•'); dot.style.color = info.color
- label.append(el('span', null, info.name), el('span', 'soft', info.memory === 'none' ? ' no memory' : ` ${info.memory}`))
- node.append(dot, label, el('span', 'tag', info.memories ? `${info.memories} saved` : ''), el('span', 'age', info.sessions ? String(info.sessions) : ''))
- } else if (row.type === 'session') {
- const hit = row.hit
- const dot = el('span', 'dot', '›'); dot.style.color = agent(hit.engine).color
- label.textContent = hit.title || hit.snippet.replace(/[\u0002\u0003]/g, '')
- node.append(dot, label, el('span', 'tag', short(hit.engine)), el('span', 'age', age(hit.at, now)))
- }
- node.addEventListener('mousedown', (event) => { event.preventDefault(); select(row.key); if (row.type === 'project' || row.type === 'agent') toggle(row) })
- return node
-}
-
-function revealSelected() {
- const node = $('list').querySelector(`[data-key="${CSS.escape(state.selected ?? '')}"]`)
- node?.scrollIntoView({ block: 'nearest' })
-}
-
-function select(key) {
- if (key === state.selected) return
- state.selected = key
- for (const node of $('list').querySelectorAll('.row[role="option"]')) {
- const on = node.dataset.key === key
- node.setAttribute('aria-selected', String(on))
- node.querySelector('.gutter').textContent = on ? '▌' : ''
- }
- revealSelected()
- drawPreview()
-}
-
-function move(delta) {
- const options = state.rows.filter(selectable)
- if (!options.length) return
- const at = options.findIndex((row) => row.key === state.selected)
- const next = delta === Infinity ? options.length - 1 : delta === -Infinity ? 0 : Math.max(0, Math.min(options.length - 1, (at < 0 ? 0 : at) + delta))
- select(options[next].key)
-}
-
-function current() { return state.rows.find((row) => row.key === state.selected) }
-
-function toggle(row, open = !row.open) {
- if (row.type !== 'project' && row.type !== 'agent') return
- if (open) state.expanded.add(row.key); else state.expanded.delete(row.key)
- drawList()
-}
-
-function forward() {
- const row = current()
- if (!row) return
- if ((row.type === 'project' || row.type === 'agent') && !row.open && (row.type === 'project' || row.children)) { toggle(row, true); return }
- if ((row.type === 'project' || row.type === 'agent') && row.open) { const index = state.rows.indexOf(row); if (selectable(state.rows[index + 1])) select(state.rows[index + 1].key); return }
- document.body.classList.add('reading')
- $('preview').scrollTop = 0
-}
-
-function back() {
- if (document.body.classList.contains('reading')) { document.body.classList.remove('reading'); return }
- const row = current()
- if (!row) return
- if (row.parent) { select(row.parent); return }
- if ((row.type === 'project' || row.type === 'agent') && row.open) toggle(row, false)
-}
-
-// ── the preview ────────────────────────────────────────────────────────────────────────────────
-
-function head(title, meta, path) {
- const box = el('div')
- box.append(el('h2', 'pv-title', title))
- if (meta) box.append(meta)
- if (path) box.append(el('div', 'pv-path', path))
- return box
-}
-
-function metaLine(parts) {
- const line = el('div', 'pv-meta')
- parts.filter(Boolean).forEach((part, n) => {
- if (n) line.append(document.createTextNode(' · '))
- line.append(typeof part === 'string' ? document.createTextNode(part) : part)
- })
- return line
-}
-
-function hitRow(hit, onClick) {
- const row = el('div', 'hit')
- row.append(who(hit.engine, 'span', short(hit.engine)), el('span', 'what', hit.title || hit.snippet.replace(/[\u0002\u0003]/g, '')), el('span', 'when', age(hit.at)))
- row.title = hit.cwd || ''
- if (onClick) row.addEventListener('click', onClick)
- return row
-}
-
-function snippet(text) {
- const node = el('div', 'snippet')
- let marked = false
- for (const part of String(text ?? '').split(/([\u0002\u0003])/)) {
- if (part === '\u0002') marked = true
- else if (part === '\u0003') marked = false
- else if (part) node.append(marked ? el('mark', null, part) : document.createTextNode(part))
- }
- return node
-}
-
-async function relatedFor(memory, box) {
- let found = state.related.get(memory.id)
- if (!found) {
- try { found = await (await fetch(`/api/related?id=${encodeURIComponent(memory.id)}`)).json() } catch { found = { hits: [] } }
- state.related.set(memory.id, found)
- }
- if (current()?.memory?.id !== memory.id) return
- box.replaceChildren()
- if (!found.hits?.length) return
- box.append(el('div', 'pv-h', 'in your sessions'))
- for (const hit of found.hits) { box.append(hitRow(hit)); box.append(snippet(hit.snippet)) }
-}
-
-function drawPreview() {
- const preview = $('preview')
- const row = current()
- preview.replaceChildren()
- if (!state.snap) { preview.append(el('div', 'pv-meta', 'Reading what your agents remember…')); return }
- if (!row) { (state.snap.memories.length || state.snap.about ? drawOverview : drawWelcome)(preview); return }
-
- if (row.type === 'memory') {
- const memory = row.memory
- const scope = memory.project ? memory.project.name : memory.scope === 'global' ? 'every project' : null
- preview.append(head(memory.title, metaLine([who(memory.agent), kindLabel(memory), scope, where(memory) ?? (memory.machine && !memory.machine.current ? memory.machine.name : null), longAge(memory.modified)]), memory.path))
- if (memory.description && memory.description !== memory.title && !memory.body.startsWith(memory.description)) preview.append(el('p', 'pv-big', memory.description))
- preview.append(el('hr', 'pv-rule'))
- preview.append(render(document, el('div', 'md'), parse(memory.body)))
- const related = el('div')
- preview.append(related)
- void relatedFor(memory, related)
- return
- }
- if (row.type === 'about') {
- const { line } = row
- preview.append(head('About you', metaLine([line.section, state.snap.about?.modified ? `built ${longAge(state.snap.about.modified)}` : null]), state.snap.aboutPath))
- preview.append(el('p', 'pv-big', line.text))
- preview.append(deliveryLine())
- if (line.refs.length) {
- preview.append(el('div', 'pv-h', 'where this comes from'))
- const chips = el('div', 'chips')
- for (const ref of line.refs) {
- const chip = el('button', 'chip', refLabel(ref))
- const target = refMemory(ref)
- if (target) chip.addEventListener('click', () => reveal(target))
- else chip.disabled = !ref.startsWith('session:')
- chips.append(chip)
- }
- preview.append(chips)
- }
- return
- }
- if (row.type === 'build') { drawBuild(preview); return }
- if (row.type === 'project') {
- const project = row.project
- preview.append(head(project.name, metaLine([`${project.memories.length} ${project.memories.length === 1 ? 'memory' : 'memories'}`, project.sessions ? `${number(project.sessions)} ${project.sessions === 1 ? 'session' : 'sessions'}` : null, project.lastAt ? `last worked ${longAge(project.lastAt)}` : null]), project.path))
- const engines = Object.entries(project.engines).filter(([, n]) => n > 0).sort((a, b) => b[1] - a[1])
- if (engines.length) {
- const total = engines.reduce((sum, [, n]) => sum + n, 0)
- const mini = el('div', 'mini')
- for (const [engine, n] of engines) { const piece = el('span'); piece.style.width = `${(n / total) * 100}%`; piece.style.background = agent(engine).color; mini.append(piece) }
- preview.append(el('div', 'pv-h', 'your messages here'), mini, metaLine(engines.map(([engine, n]) => { const node = who(engine); node.textContent = `${agent(engine).name} ${number(n)}`; return node })))
- }
- preview.append(el('div', 'pv-h', 'what your agents know'))
- for (const id of project.memories) {
- const memory = state.snap.memories.find((m) => m.id === id)
- if (!memory) continue
- const item = el('div', 'hit')
- item.append(who(memory.agent, 'span', short(memory.agent)), el('span', 'what', memory.title), el('span', 'when', kindLabel(memory)))
- item.addEventListener('click', () => { state.expanded.add(row.key); drawList(); select(`m:${memory.id}@${row.key}`) })
- preview.append(item)
- }
- return
- }
- if (row.type === 'agent') { drawAgent(preview, row.agent); return }
- if (row.type === 'session') {
- const hit = row.hit
- preview.append(head(hit.title || 'A conversation', metaLine([who(hit.engine), hit.cwd, longAge(hit.at)]), `session ${hit.sessionId}`))
- preview.append(el('hr', 'pv-rule'), snippet(hit.snippet))
- }
-}
-
-/** Show one memory in the list wherever it lives: clear the search, open its group, select its row. */
-function reveal(memory) {
- state.query = ''; $('q').value = ''; state.hits = { q: '', items: [], error: null }
- let key = `m:${memory.id}`
- if (memory.kind === 'you') state.closed.delete('about')
- else if (memory.kind === 'instructions') state.closed.delete('told')
- else if (memory.project) {
- const project = state.snap.projects.find((entry) => entry.memories.includes(memory.id))
- if (project) { state.closed.delete('projects'); state.expanded.add(`p:${project.key}`); key = `m:${memory.id}@p:${project.key}` }
- } else state.closed.delete('notes')
- drawList()
- if (!state.rows.some((row) => row.key === key)) { state.closed.delete('agents'); state.expanded.add(`ag:${memory.agent}`); drawList(); key = `m:${memory.id}@ag:${memory.agent}` }
- select(key)
-}
-
-/** Which agents start every new session with About You, said in one line under it. */
-function deliveryLine() {
- const delivery = state.snap.delivery
- const box = el('div', 'callout')
- const using = (delivery?.agents ?? []).filter((row) => row.delivered)
- if (delivery?.on && using.length) {
- const names = using.map((row) => agent(row.agent).name + (row.current ? '' : ' (older copy)'))
- box.append(el('div', null, `Every new session of ${names.join(', ')} starts with this.`))
- box.append(el('div', 'pv-meta', 'Sessions already open keep what they started with. Turn it off at the top any time.'))
- } else {
- box.append(el('div', null, 'Your agents do not use this. Turn on "About You in your agents" at the top.'))
- }
- return box
-}
-
-function refMemory(ref) {
- const at = ref.indexOf(':')
- if (at < 0) return null
- const who = ref.slice(0, at), file = ref.slice(at + 1)
- return state.snap.memories.find((memory) => memory.agent === who && (memory.path.endsWith('/' + file) || memory.id.endsWith(file))) ?? null
-}
-
-function refLabel(ref) {
- const asks = /^asks:(\d+)$/.exec(ref)
- if (asks) return `${number(asks[1])} of your messages`
- const target = refMemory(ref)
- if (target) return `${agent(target.agent).name}: ${target.title}`
- if (ref.startsWith('session:')) return `a conversation (${ref.slice(8, 16)}…)`
- return ref
-}
-
-function drawBuild(preview) {
- const sessions = state.snap.sessions
- const yours = state.snap.memories.filter((memory) => memory.kind === 'you').length
- preview.append(head('About you', metaLine(['not built yet']), state.snap.aboutPath))
- preview.append(el('p', 'pv-big', 'A short profile of how you work, built from your own words across every agent.'))
- const call = el('div', 'callout')
- call.append(el('div', null, 'Ask the agent on the right, on the model you picked for this harness:'), el('div', 'say', 'build my About You'))
- preview.append(call)
- const facts = []
- if (sessions?.asks) facts.push(`${number(sessions.asks)} messages you sent to ${sessions.engines.filter((row) => row.asks).length} agents`)
- if (yours) facts.push(`${yours} notes your agents saved about you`)
- if (facts.length) preview.append(el('p', null, `It reads ${facts.join(' and ')}, and writes the profile here. Every line says where it came from.`))
- preview.append(el('p', 'pv-meta', 'Only this harness\'s agent builds it, as a turn you can see on the right. Then every agent gets it; the switch at the top turns that off.'))
-}
-
-const TURN_ON = {
- codex: ['Codex keeps memory only when it is turned on. Add this to ~/.codex/config.toml:', '[features]\nmemories = true'],
- grok: ['Grok Build keeps memory only when it is turned on. Add this to ~/.grok/config.toml:', '[memory]\nenabled = true'],
- claude: ['Claude Code memory is off. Turn it back on with /memory in Claude Code.', null],
-}
-
-function drawAgent(preview, info) {
- const status = info.memory === 'none' ? 'keeps no memory of its own' : `memory ${info.memory}`
- const title = el('h2', 'pv-title', info.name); title.style.color = info.color
- preview.append(title, metaLine([status, info.sessions ? `${number(info.sessions)} sessions here` : null]))
- preview.append(el('p', 'pv-big', info.says))
- const facts = el('dl', 'kv')
- const add = (k, v) => { if (v === null || v === undefined || v === '') return; facts.append(el('dt', null, k), el('dd', null, v)) }
- add('saved', info.memories ? `${info.memories} ${info.memories === 1 ? 'memory' : 'memories'}` : 'nothing yet')
- if (info.instructions) add('instructions', `${info.instructions} file${info.instructions === 1 ? '' : 's'} you wrote`)
- if (info.unreadable) add('unreadable', `${info.unreadable} memories in a format Harness cannot read`)
- add('kept in', info.where)
- add('home', info.present ? info.home : 'not installed here')
- if (info.machines?.length > 1) add('machines', info.machines.join(', '))
- preview.append(facts)
- const turnOn = info.memory === 'off' ? TURN_ON[info.id] : null
- if (turnOn) {
- preview.append(el('div', 'pv-h', 'turn it on'), el('p', null, turnOn[0]))
- if (turnOn[1]) preview.append(el('div', 'code', turnOn[1]))
- }
-}
-
-/** Nothing selected — every group folded, or a search with no match: say what is here, not "nothing". */
-function drawOverview(preview) {
- const snap = state.snap
- const memories = snap.memories.filter((row) => row.kind !== 'instructions')
- const agents = snap.agents.filter((row) => row.memories > 0)
- preview.append(head(`${number(memories.length)} ${memories.length === 1 ? 'memory' : 'memories'}`, metaLine([`from ${agents.map((row) => row.name).join(', ') || 'no agent yet'}`, 'on this computer'])))
- const facts = el('dl', 'kv')
- const add = (k, v) => { if (v) facts.append(el('dt', null, k), el('dd', null, v)) }
- add('about you', `${snap.about?.lines.length ?? 0} lines built · ${memories.filter((row) => row.kind === 'you').length} saved by agents`)
- add('projects', `${snap.projects.length}`)
- add('sessions', snap.sessions ? `${number(snap.sessions.sessions)} with ${number(snap.sessions.asks)} of your messages` : null)
- preview.append(facts)
- drawMachines(preview)
- preview.append(el('p', 'pv-meta', state.query.trim() ? 'Nothing matches that yet. Esc clears the search.' : 'Open a group on the left, or type to search.'))
-}
-
-/** Which machines answered, and why the others did not. */
-function drawMachines(preview) {
- const list = state.snap.machines ?? []
- if (list.length < 2) return
- preview.append(el('div', 'pv-h', 'machines'))
- const facts = el('dl', 'kv')
- for (const machine of list) {
- const count = state.snap.memories.filter((row) => row.machine?.id === machine.id && row.kind !== 'instructions').length
- facts.append(el('dt', null, machine.name + (machine.current ? ' (this one)' : '')), el('dd', null, machine.ok ? `${number(count)} memories` : machine.error ?? 'did not answer'))
- }
- preview.append(facts)
-}
-
-function drawWelcome(preview) {
- preview.append(head('Nothing here yet', metaLine(['your agents have not saved any memories on this computer'])))
- preview.append(el('p', null, 'Claude Code saves memories as you work. Codex and Grok Build save them once memory is turned on. Hermes and OpenClaw keep a profile. They will appear here as soon as any agent writes one.'))
-}
-
-// ── search: memories here, conversations from the session index ────────────────────────────────
-
-let searchTimer = null
-let searchSeq = 0
-function searchSessions(q) {
- clearTimeout(searchTimer)
- const text = q.trim()
- if (text.length < 2) { state.hits = { q: text, items: [], error: null }; return }
- searchTimer = setTimeout(async () => {
- const seq = ++searchSeq
- let answer
- try { answer = await (await fetch(`/api/search?q=${encodeURIComponent(text)}`)).json() } catch { answer = { hits: [], error: 'Search is not available right now.' } }
- if (seq !== searchSeq) return
- state.hits = { q: text, items: answer.hits ?? [], error: answer.error ?? null }
- if (state.query.trim() === text) drawList()
- }, 160)
-}
-
-$('q').addEventListener('input', (event) => {
- state.query = event.target.value
- document.body.classList.remove('reading')
- searchSessions(state.query)
- state.selected = null
- drawList({ keepScroll: false })
- $('list').scrollTop = 0
-})
-
-document.addEventListener('keydown', (event) => {
- const input = $('q')
- if (event.metaKey || event.ctrlKey && !['n', 'p', 'j', 'k'].includes(event.key)) return
- const key = event.ctrlKey ? { n: 'ArrowDown', j: 'ArrowDown', p: 'ArrowUp', k: 'ArrowUp' }[event.key] : event.key
- if (key === 'ArrowDown') { event.preventDefault(); move(1) }
- else if (key === 'ArrowUp') { event.preventDefault(); move(-1) }
- else if (key === 'PageDown') { event.preventDefault(); move(12) }
- else if (key === 'PageUp') { event.preventDefault(); move(-12) }
- else if (key === 'Home' && !input.value) { event.preventDefault(); move(-Infinity) }
- else if (key === 'End' && !input.value) { event.preventDefault(); move(Infinity) }
- else if (key === 'Enter') { event.preventDefault(); forward() }
- else if (key === 'ArrowRight' && (input.selectionStart === input.value.length || document.activeElement !== input)) { event.preventDefault(); forward() }
- else if (key === 'ArrowLeft' && (input.selectionStart === 0 || document.activeElement !== input)) { event.preventDefault(); back() }
- else if (key === 'Escape') {
- event.preventDefault()
- if (document.body.classList.contains('reading')) document.body.classList.remove('reading')
- else if (input.value) { input.value = ''; state.query = ''; state.hits = { q: '', items: [], error: null }; drawList({ keepScroll: false }) }
- input.focus()
- } else if (document.activeElement !== input && key.length === 1 && !event.altKey) input.focus()
-})
-
// ── live: a snapshot on connect and whenever something changed ─────────────────────────────────
const instance = document.querySelector('meta[name="memories-instance"]')?.content ?? ''
@@ -726,17 +78,9 @@ const instance = document.querySelector('meta[name="memories-instance"]')?.conte
function receive(snap) {
// The viewer restarted under this page: its token is gone, so the switch would refuse. Reload.
if (snap.instance && instance && snap.instance !== instance) { location.reload(); return }
- const firstLoad = !state.snap
- const ids = new Set(snap.memories.map((memory) => memory.id))
- if (state.known) for (const id of ids) if (!state.known.has(id)) state.fresh.set(id, Date.now())
- state.known = ids
state.snap = snap
- if (firstLoad && snap.about?.lines?.length) state.selected = 'a:0'
+ data.receive(snap)
drawSwitch()
- drawBand()
- drawList()
- $('updated').textContent = `read ${new Date(snap.observedAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}`
- if (state.fresh.size) setTimeout(() => { for (const [id, at] of state.fresh) if (Date.now() - at > 6000) state.fresh.delete(id) }, 6500)
}
function connect() {
@@ -750,8 +94,48 @@ function connect() {
source.addEventListener('error', () => { live.textContent = 'reconnecting…'; live.classList.add('lost') })
}
+// ── the scene ──────────────────────────────────────────────────────────────────────────────────
+
+const data = createMemoryData({
+ // No snapshot from /events yet: read one, through the same instance check.
+ fallback: async () => { const snap = await (await fetch('/api/state')).json(); receive(snap); return snap },
+})
+const loop = createLoop()
+const motion = matchMedia('(prefers-reduced-motion: reduce)')
+const input = $('q')
+
+function setQuery(text) {
+ input.value = String(text ?? '')
+ scene.recall(input.value)
+}
+
+const scene = mountSelf({
+ root: $('stage'),
+ data,
+ loop,
+ setQuery,
+ count: (text) => { $('count').textContent = String(text ?? '') },
+ reducedMotion: () => motion.matches,
+})
+
+input.addEventListener('input', () => scene.recall(input.value))
+
+document.addEventListener('keydown', (event) => {
+ if (event.isComposing) return
+ const inInput = document.activeElement === input
+ const info = { typing: input.value !== '' }
+ if (scene.key(event, info)) { event.preventDefault(); if (!inInput) input.focus(); return }
+ if (event.key === 'Escape') { event.preventDefault(); if (input.value) setQuery(''); input.focus(); return }
+ if (!inInput && event.key.length === 1 && !event.metaKey && !event.ctrlKey && !event.altKey) input.focus()
+})
+
+// One render loop, and only while the tab is visible.
+function visibility() {
+ if (document.visibilityState === 'hidden') { loop.stop(); scene.stop() } else { scene.start(); loop.start() }
+}
+document.addEventListener('visibilitychange', visibility)
let resizeTimer = null
-new ResizeObserver(() => { clearTimeout(resizeTimer); resizeTimer = setTimeout(drawBand, 80) }).observe(document.body)
+new ResizeObserver(() => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => scene.resize(), 60) }).observe($('stage'))
-drawList()
+visibility()
connect()
diff --git a/store/agents/memories/viewer/fuzzy.js b/store/agents/memories/viewer/fuzzy.js
deleted file mode 100644
index 9a1143e97..000000000
--- a/store/agents/memories/viewer/fuzzy.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * fzf-style matching: every query character in order, rewarded for word starts and runs.
- *
- * Several words must all match (each anywhere, in any field), like fzf's space-separated terms. The
- * score is only for ordering; zero or less means no match.
- */
-
-const boundary = (text, index) => index === 0 || /[\s/_\-.:([{"'`]/.test(text[index - 1]) || (/[a-z]/.test(text[index - 1]) && /[A-Z]/.test(text[index]))
-
-/** One term against one text: the best ordered match's score, or 0. */
-export function scoreTerm(term, text, substringOnly = false) {
- const needle = term.toLowerCase()
- const haystack = String(text ?? '')
- const lower = haystack.toLowerCase()
- if (!needle) return 1
- const exact = lower.indexOf(needle)
- if (exact >= 0) return 100 + needle.length * 8 + (boundary(haystack, exact) ? 40 : 0) - Math.min(30, exact / 4)
- // A long body contains almost any short query as a scattered subsequence; only exact text counts there.
- if (substringOnly) return 0
- let score = 0
- let at = -1
- let run = 0
- for (const char of needle) {
- const next = lower.indexOf(char, at + 1)
- if (next < 0) return 0
- run = next === at + 1 ? run + 1 : 0
- score += 1 + run * 3 + (boundary(haystack, next) ? 6 : 0) - Math.min(4, (next - at - 1) / 6)
- at = next
- }
- return Math.max(0.1, score)
-}
-
-/** A query (space-separated terms) against weighted fields: `[[text, weight, substringOnly?], …]`. */
-export function scoreFields(query, fields) {
- const terms = String(query ?? '').trim().split(/\s+/).filter(Boolean)
- if (!terms.length) return 1
- let total = 0
- for (const term of terms) {
- let best = 0
- for (const [text, weight, substringOnly] of fields) best = Math.max(best, scoreTerm(term, text, substringOnly) * weight)
- if (best <= 0) return 0
- total += best
- }
- return total
-}
diff --git a/store/agents/memories/viewer/heatmap.js b/store/agents/memories/viewer/heatmap.js
deleted file mode 100644
index 021516cba..000000000
--- a/store/agents/memories/viewer/heatmap.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * Your messages per day as a calendar grid: one column per week, Monday at the top, each day tinted
- * with the agent you talked to most that day and shaded by how much.
- */
-
-const DAY = 86_400_000
-
-/** `YYYY-MM-DD` in local time. */
-export function dayKey(at) {
- const date = new Date(at)
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
-}
-
-/**
- * The grid for the `weeks` weeks ending with the one containing `now`: `columns[week][weekday]` is
- * `{ day, total, agents: { engine: n }, top, level }`, or null for days after today. `level` is 0..4,
- * cut at the quartiles of the active days so a light month and a heavy one both show their shape.
- */
-export function buildGrid(activity, { now = Date.now(), weeks = 53 } = {}) {
- const byDay = new Map()
- for (const row of activity ?? []) {
- const entry = byDay.get(row.day) ?? { total: 0, agents: {} }
- entry.total += row.asks
- entry.agents[row.engine] = (entry.agents[row.engine] ?? 0) + row.asks
- byDay.set(row.day, entry)
- }
- const totals = [...byDay.values()].map((entry) => entry.total).filter((n) => n > 0).sort((a, b) => a - b)
- const quantile = (q) => totals.length ? totals[Math.min(totals.length - 1, Math.floor(q * totals.length))] : 0
- const cuts = [quantile(0.25), quantile(0.5), quantile(0.8)]
- const top = totals.at(-1) ?? 0
- // The busiest day is always the darkest, even when it is also the 80th percentile of a short history.
- const level = (n) => (n <= 0 ? 0 : n >= top ? 4 : n <= cuts[0] ? 1 : n <= cuts[1] ? 2 : n <= cuts[2] ? 3 : 4)
-
- const today = new Date(now)
- today.setHours(12, 0, 0, 0)
- const weekday = (today.getDay() + 6) % 7 // Monday = 0
- const start = today.getTime() - (weekday + (weeks - 1) * 7) * DAY
- const columns = []
- let max = { day: null, total: 0 }
- for (let week = 0; week < weeks; week++) {
- const column = []
- for (let d = 0; d < 7; d++) {
- const at = start + (week * 7 + d) * DAY
- if (at > today.getTime() + DAY / 2) { column.push(null); continue }
- const day = dayKey(at)
- const entry = byDay.get(day) ?? { total: 0, agents: {} }
- const top = Object.entries(entry.agents).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
- if (entry.total > max.total) max = { day, total: entry.total }
- column.push({ day, at, total: entry.total, agents: entry.agents, top, level: level(entry.total) })
- }
- columns.push(column)
- }
- const active = [...byDay.entries()].filter(([, entry]) => entry.total > 0)
- return { columns, max, activeDays: active.length, streak: streak(byDay, now) }
-}
-
-/** Consecutive days with at least one message, ending today or yesterday. */
-export function streak(byDay, now = Date.now()) {
- // Step by calendar day from noon, not by 24 hours: across a daylight-saving change a 24-hour step
- // from just after midnight skips a day, and one from late evening lands on the same day twice.
- const day = new Date(now)
- day.setHours(12, 0, 0, 0)
- let count = 0
- if (!(byDay.get(dayKey(day.getTime()))?.total > 0)) day.setDate(day.getDate() - 1)
- while (byDay.get(dayKey(day.getTime()))?.total > 0) { count++; day.setDate(day.getDate() - 1) }
- return count
-}
diff --git a/store/agents/memories/viewer/index.html b/store/agents/memories/viewer/index.html
index c721a4966..aedaff284 100644
--- a/store/agents/memories/viewer/index.html
+++ b/store/agents/memories/viewer/index.html
@@ -7,6 +7,7 @@
<meta name="memories-instance" content="__MEMORIES_INSTANCE__">
<title>Memories</title>
<link rel="stylesheet" href="app.css">
+ <link rel="stylesheet" href="self.css">
</head>
<body>
<header class="top">
@@ -22,26 +23,7 @@
</div>
</header>
<div id="switch-problem" class="switch-problem" role="alert" hidden></div>
- <section id="band" class="band" aria-label="Your work with agents" hidden>
- <div class="heat">
- <svg id="heat" role="img" aria-label="Your messages per day, colored by agent"></svg>
- <div id="heat-note" class="heat-note"></div>
- </div>
- <div class="stats">
- <div class="big"><span id="stat-asks">0</span><small>messages to your agents</small></div>
- <div id="stat-line" class="stat-line"></div>
- <div id="bar" class="bar" aria-hidden="true"></div>
- <div id="legend" class="legend"></div>
- </div>
- </section>
- <main class="split">
- <div id="list" class="list" role="listbox" aria-label="Memories" tabindex="-1"></div>
- <article id="preview" class="preview" aria-live="polite"></article>
- </main>
- <footer class="keys">
- <span><kbd>↑↓</kbd> move</span><span><kbd>→</kbd> open</span><span><kbd>←</kbd> back</span><span><kbd>esc</kbd> clear</span>
- <span class="spacer"></span><span id="updated"></span>
- </footer>
+ <main id="stage" class="stage" aria-label="Sense of Self"></main>
<script type="module" src="app.js"></script>
</body>
</html>
diff --git a/store/agents/memories/viewer/loop.js b/store/agents/memories/viewer/loop.js
new file mode 100644
index 000000000..1c8d128bb
--- /dev/null
+++ b/store/agents/memories/viewer/loop.js
@@ -0,0 +1,42 @@
+/**
+ * The pane's one render loop. It runs only while the tab is visible, and only while the scene says
+ * something moves: draw(now, dt) returns false to sleep until wake(). Everything that touches the page
+ * comes in as an option, so the rules are tested without a browser.
+ */
+export function createLoop({
+ frame = (fn) => globalThis.requestAnimationFrame(fn),
+ cancelFrame = (handle) => globalThis.cancelAnimationFrame(handle),
+ hidden = () => globalThis.document?.visibilityState === 'hidden',
+ report = (error) => { queueMicrotask(() => { throw error }) },
+} = {}) {
+ let draw = null
+ let handle = null
+ let last = 0
+ let running = false
+
+ function tick(now) {
+ handle = null
+ if (!running || !draw || hidden()) return
+ const dt = last ? Math.min(0.1, Math.max(0, (now - last) / 1000)) : 0
+ last = now
+ let more
+ try { more = draw(now, dt) } catch (error) { report(error); more = false }
+ if (more !== false && running && handle === null) handle = frame(tick)
+ }
+ function wake() {
+ if (handle !== null || !running || !draw || hidden()) return
+ last = 0
+ handle = frame(tick)
+ }
+
+ return {
+ /** What to draw each frame. */
+ set(fn) { draw = typeof fn === 'function' ? fn : null; wake() },
+ wake,
+ /** The tab is visible: draw again. */
+ start() { running = true; wake() },
+ /** The tab is hidden: draw nothing. */
+ stop() { running = false; if (handle !== null) { cancelFrame(handle); handle = null } },
+ get running() { return running && handle !== null },
+ }
+}
diff --git a/store/agents/memories/viewer/markdown.js b/store/agents/memories/viewer/markdown.js
deleted file mode 100644
index 73402b777..000000000
--- a/store/agents/memories/viewer/markdown.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/**
- * Markdown to DOM, for memory files written by models and people.
- *
- * Nothing from a memory file ever becomes HTML: `parse` turns the text into plain blocks and inline
- * spans, and `render` builds elements with `textContent`. A memory that contains `<script>` or an
- * `onerror=` shows those characters, and nothing else. Links are shown as text: the pane is a viewer of
- * what agents remembered, not a browser, and a click must never navigate it away.
- */
-
-const MAX_INLINE = 8_000
-const MAX_QUOTE_DEPTH = 8
-
-/** `## Title ##` → { level, text }, without a backtracking pattern (see lib/text.mjs headingText). */
-function heading(line) {
- if (line.length > 2000 || line[0] !== '#') return null
- let level = 0
- while (line[level] === '#') level++
- if (level > 6 || (line[level] !== ' ' && line[level] !== '\t')) return null
- let text = line.slice(level).trim()
- let end = text.length
- while (end > 0 && text[end - 1] === '#') end--
- if (end < text.length && (end === 0 || text[end - 1] === ' ' || text[end - 1] === '\t')) text = text.slice(0, end).trim()
- return text ? { level, text } : null
-}
-
-/** Inline spans: code, bold, italic, links (as their text), plain text. */
-export function inline(text) {
- const spans = []
- // Past this length a paragraph is shown as plain text: the span pattern is fast on prose but a
- // model can write anything, and the preview must never stall.
- if (String(text ?? '').length > MAX_INLINE) return [{ type: 'text', text: String(text) }]
- const source = String(text ?? '')
- const pattern = /(?<!`)(`+)([^`]+?)\1|\*\*([^*]+?)\*\*|__([^_]+?)__|(?<![\w*])\*([^*\s][^*]*?)\*(?!\w)|(?<![\w_])_([^_\s][^_]*?)_(?!\w)|\[([^\][]+)\]\(([^)\s]+)\)/g
- let last = 0
- for (const match of source.matchAll(pattern)) {
- if (match.index > last) spans.push({ type: 'text', text: source.slice(last, match.index) })
- if (match[2] !== undefined) spans.push({ type: 'code', text: match[2] })
- else if (match[3] !== undefined || match[4] !== undefined) spans.push({ type: 'strong', text: match[3] ?? match[4] })
- else if (match[5] !== undefined || match[6] !== undefined) spans.push({ type: 'em', text: match[5] ?? match[6] })
- else spans.push({ type: 'link', text: match[7], href: match[8] })
- last = match.index + match[0].length
- }
- if (last < source.length) spans.push({ type: 'text', text: source.slice(last) })
- return spans
-}
-
-/** Blocks: headings, paragraphs, lists, quotes, code, rules, tables (kept as monospace text). */
-export function parse(text, depth = 0) {
- const lines = String(text ?? '').replace(/\r\n?/g, '\n').split('\n')
- const blocks = []
- let i = 0
- const isBreak = (line) => /^\s*$/.test(line) || /^#{1,6}[ \t]/.test(line) || /^\s*```/.test(line) || /^\s*([-*+]|\d+[.)])\s+/.test(line) || /^\s*>/.test(line) || /^\s*([-*_])(\s*\1){2,}\s*$/.test(line) || /^\s*\|/.test(line)
- while (i < lines.length) {
- const line = lines[i]
- if (/^\s*$/.test(line)) { i++; continue }
- const fence = /^\s*```(.*)$/.exec(line)
- if (fence) {
- const body = []
- i++
- while (i < lines.length && !/^\s*```\s*$/.test(lines[i])) body.push(lines[i++])
- i++
- blocks.push({ type: 'code', text: body.join('\n'), lang: fence[1].trim() })
- continue
- }
- const title = heading(line)
- if (title) { blocks.push({ type: 'heading', level: title.level, spans: inline(title.text) }); i++; continue }
- if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { blocks.push({ type: 'rule' }); i++; continue }
- if (/^\s*\|/.test(line)) {
- const rows = []
- while (i < lines.length && /^\s*\|/.test(lines[i])) rows.push(lines[i++])
- blocks.push({ type: 'table', text: rows.join('\n') })
- continue
- }
- if (/^\s*>/.test(line)) {
- const body = []
- while (i < lines.length && /^\s*>/.test(lines[i])) body.push(lines[i++].replace(/^\s*>\s?/, ''))
- // Quotes nest by recursion; a file of thousands of `>` must not exhaust the stack.
- blocks.push({ type: 'quote', blocks: depth < MAX_QUOTE_DEPTH ? parse(body.join('\n'), depth + 1) : [{ type: 'paragraph', spans: inline(body.join(' ')) }] })
- continue
- }
- const item = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line)
- if (item) {
- const ordered = /\d/.test(item[2])
- const items = []
- while (i < lines.length) {
- const next = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(lines[i])
- if (next) {
- const check = /^\[([ xX])\]\s+(.*)$/.exec(next[3])
- items.push({ depth: Math.min(4, Math.floor(next[1].replace(/\t/g, ' ').length / 2)), checked: check ? check[1] !== ' ' : null, spans: inline(check ? check[2] : next[3]) })
- i++
- } else if (/^\s{2,}\S/.test(lines[i]) && items.length) {
- items.at(-1).spans.push({ type: 'text', text: ' ' }, ...inline(lines[i].trim()))
- i++
- } else break
- }
- blocks.push({ type: 'list', ordered, items })
- continue
- }
- const body = [line.trim()]
- i++
- while (i < lines.length && !isBreak(lines[i])) body.push(lines[i++].trim())
- blocks.push({ type: 'paragraph', spans: inline(body.join(' ')) })
- }
- return blocks
-}
-
-function spansTo(doc, parent, spans) {
- for (const span of spans) {
- if (span.type === 'text') { parent.append(doc.createTextNode(span.text)); continue }
- const tag = { code: 'code', strong: 'strong', em: 'em', link: 'span' }[span.type]
- const element = doc.createElement(tag)
- element.textContent = span.text
- if (span.type === 'link') { element.className = 'md-link'; element.title = span.href }
- parent.append(element)
- }
-}
-
-/** The blocks as elements, appended to `parent`. */
-export function render(doc, parent, blocks) {
- for (const block of blocks) {
- let element
- if (block.type === 'heading') { element = doc.createElement(`h${Math.min(6, block.level + 2)}`); spansTo(doc, element, block.spans) }
- else if (block.type === 'paragraph') { element = doc.createElement('p'); spansTo(doc, element, block.spans) }
- else if (block.type === 'code' || block.type === 'table') { element = doc.createElement('pre'); element.textContent = block.text }
- else if (block.type === 'rule') element = doc.createElement('hr')
- else if (block.type === 'quote') { element = doc.createElement('blockquote'); render(doc, element, block.blocks) }
- else if (block.type === 'list') {
- element = doc.createElement(block.ordered ? 'ol' : 'ul')
- for (const item of block.items) {
- const li = doc.createElement('li')
- if (item.depth) li.style.marginLeft = `${item.depth * 1.4}em`
- if (item.checked !== null) li.dataset.checked = String(item.checked)
- spansTo(doc, li, item.spans)
- element.append(li)
- }
- }
- if (element) parent.append(element)
- }
- return parent
-}
diff --git a/store/agents/memories/viewer/memory-data.js b/store/agents/memories/viewer/memory-data.js
new file mode 100644
index 000000000..62d7b835a
--- /dev/null
+++ b/store/agents/memories/viewer/memory-data.js
@@ -0,0 +1,165 @@
+/**
+ * What Sense of Self reads, over this viewer's own routes: the interface the prototypes in
+ * docs/research/2026-10-10-memory-brain/memory-data.js were built on, with the same names.
+ *
+ * data.load() → Promise<{ snapshot, asks, asksError, real: true }>
+ * data.search(q) → Promise<hits> hit: { at, engine, title, cwd, sessionId, turn, snippet }
+ * snippet marks matches with \u0002 … \u0003
+ * data.conversation(sessionId, turn) → Promise<{ title, cwd, turns: [{ turn, at, ask, answer }] }>
+ * data.related(memoryId) → Promise<hits>: conversations about the same thing as a memory
+ * data.refs(line, snapshot) → the memory rows an About You line cites
+ * data.agent(id, snapshot) → { id, name, color }
+ *
+ * The snapshot is the one the pane already receives on /events (app.js hands it over with receive());
+ * only when none has come yet is /api/state asked. Your messages come from /api/asks, read once and
+ * again only after the snapshot counts new ones. Search is /api/search (the daemon's session search,
+ * as Cmd-P's); the same question within a snapshot is asked once.
+ *
+ * Everything in here is untrusted text written by models and people: render it with textContent only.
+ */
+
+export const DAY = 86_400_000
+const FALLBACK = { amp: '#c9a227', kilo: '#5fb3b3', devin: '#6aa6f8', muse: '#c77dff', agy: '#8bd3a0', commandcode: '#d4a5a5' }
+const SEARCHES_KEPT = 8
+const count = (snap) => snap?.sessions?.asks ?? 0
+
+/** The memory rows an About You line cites: `claude:short-answers.md` → that note, by file or title. */
+export function refs(line, snapshot) {
+ const found = []
+ for (const ref of line?.refs ?? []) {
+ const at = String(ref).indexOf(':')
+ if (at < 1) continue
+ const who = ref.slice(0, at), file = ref.slice(at + 1).trim()
+ if (!file || who === 'asks' || who === 'session') continue
+ const base = file.replace(/\.md$/i, '').toLowerCase()
+ for (const row of snapshot?.memories ?? []) {
+ if (row.agent !== who) continue
+ const name = String(row.path ?? '').split('/').pop().replace(/\.md$/i, '').toLowerCase()
+ const titled = String(row.title ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
+ if (String(row.path ?? '').endsWith('/' + file) || String(row.id).endsWith(file) || name === base || titled === base) found.push(row)
+ }
+ }
+ return [...new Set(found)]
+}
+
+/** An agent's name and color; an agent the snapshot does not list still gets a stable color. */
+export function agent(id, snapshot) {
+ const row = snapshot?.agents?.find((entry) => entry.id === id)
+ if (row) return { id, name: row.name, color: row.color }
+ return { id, name: id ? id[0].toUpperCase() + id.slice(1) : 'Unknown', color: FALLBACK[id] ?? '#8a8f98' }
+}
+
+/**
+ * `fallback` is how a snapshot is fetched when /events has not delivered one within `graceMs`; app.js
+ * passes its own, so a snapshot read that way still goes through its instance check.
+ */
+export function createMemoryData({ fetch: get = (...args) => globalThis.fetch(...args), fallback = null, graceMs = 1500 } = {}) {
+ let snapshot = null
+ let waiting = []
+ let asked = null // { count, promise } for the asks read at that many messages
+ const searches = new Map() // q → Promise<{ q, hits, error }>, newest last
+ const listeners = new Set()
+ const read = async (path) => {
+ const response = await get(path)
+ if (!response.ok) throw new Error(`${path} answered ${response.status}`)
+ return response.json()
+ }
+
+ /** A snapshot from /events (or /api/state). Views that subscribed hear about it. */
+ function receive(next) {
+ if (!next || typeof next !== 'object') return
+ const before = snapshot
+ snapshot = next
+ // New messages since the last read: the asks and every remembered search are out of date.
+ if (asked && count(next) !== asked.count) asked = null
+ if (before && count(before) !== count(next)) searches.clear()
+ for (const done of waiting) done(next)
+ waiting = []
+ if (before) for (const listener of listeners) { try { listener(next) } catch { /* one view's mistake is not the others' */ } }
+ }
+
+ // Every load() before the first snapshot shares one wait, and at most one fallback read.
+ let pending = null
+ function snapshotNow() {
+ if (snapshot) return Promise.resolve(snapshot)
+ if (pending) return pending
+ pending = new Promise((resolve, reject) => {
+ waiting.push(resolve)
+ setTimeout(() => {
+ if (snapshot) return
+ const ask = fallback ?? (() => read('/api/state'))
+ Promise.resolve().then(ask).then((snap) => { if (!snapshot) receive(snap) }).catch((error) => {
+ if (snapshot) return
+ waiting = waiting.filter((entry) => entry !== resolve)
+ reject(error)
+ })
+ }, graceMs)
+ })
+ pending.then(() => { pending = null }, () => { pending = null })
+ return pending
+ }
+
+ async function asksFor(snap) {
+ if (!asked) {
+ const promise = read('/api/asks').then((answer) => ({ asks: Array.isArray(answer.asks) ? answer.asks : [], error: answer.error ?? null }))
+ asked = { count: count(snap), promise }
+ promise.catch(() => { if (asked?.promise === promise) asked = null })
+ }
+ try { return await asked.promise } catch (error) { return { asks: [], error: error instanceof Error ? error.message : String(error) } }
+ }
+
+ async function load() {
+ const snap = await snapshotNow()
+ const { asks, error } = await asksFor(snap)
+ return { snapshot: snap, asks, asksError: error, real: true }
+ }
+
+ /** The list's search and the views': one answer per question, `{ q, hits, error }`. */
+ function searchAnswer(q) {
+ const text = String(q ?? '').trim().slice(0, 200)
+ if (!text) return Promise.resolve({ q: text, hits: [], error: null })
+ if (searches.has(text)) {
+ const kept = searches.get(text)
+ searches.delete(text); searches.set(text, kept)
+ return kept
+ }
+ const promise = read(`/api/search?q=${encodeURIComponent(text)}`)
+ .then((answer) => ({ q: text, hits: Array.isArray(answer.hits) ? answer.hits : [], error: answer.error ?? null }))
+ .catch(() => { searches.delete(text); return { q: text, hits: [], error: 'Search is not available right now.' } })
+ searches.set(text, promise)
+ while (searches.size > SEARCHES_KEPT) searches.delete(searches.keys().next().value)
+ return promise
+ }
+
+ /** What was said around where a search found a conversation: { title, cwd, turns: [{ turn, at, ask, answer }] }. */
+ async function conversation(sessionId, turn) {
+ const params = new URLSearchParams({ sessionId: String(sessionId ?? '') })
+ if (Number.isInteger(turn) && turn >= 0) params.set('turn', String(turn))
+ try {
+ const answer = await read(`/api/conversation?${params}`)
+ return { title: answer.title ?? '', cwd: answer.cwd ?? '', turns: Array.isArray(answer.turns) ? answer.turns : [], error: answer.error ?? null }
+ } catch (error) { return { title: '', cwd: '', turns: [], error: error instanceof Error ? error.message : String(error) } }
+ }
+
+ /** Conversations that talk about the same thing as a memory: its title and description, any word. */
+ async function related(id) {
+ try { const answer = await read(`/api/related?id=${encodeURIComponent(String(id ?? ''))}`); return Array.isArray(answer.hits) ? answer.hits : [] } catch { return [] }
+ }
+
+ return {
+ real: true,
+ DAY,
+ load,
+ search: async (q) => (await searchAnswer(q)).hits,
+ searchAnswer,
+ conversation,
+ related,
+ refs: (line, snap = snapshot) => refs(line, snap),
+ agent: (id, snap = snapshot) => agent(id, snap),
+ receive,
+ snapshot: () => snapshot,
+ /** Called with every snapshot after the first; returns the way to stop listening. */
+ onChange(listener) { listeners.add(listener); return () => listeners.delete(listener) },
+ }
+}
+
diff --git a/store/agents/memories/viewer/self-model.js b/store/agents/memories/viewer/self-model.js
new file mode 100644
index 000000000..854c3b52e
--- /dev/null
+++ b/store/agents/memories/viewer/self-model.js
@@ -0,0 +1,309 @@
+/**
+ * Sense of Self, without a screen: what the pane draws, worked out from the snapshot and your messages.
+ * self.js lays it out and draws it; this file only does the arithmetic, so it runs (and is tested) in
+ * Node too. Ported from docs/research/2026-10-10-memory-brain/self.js.
+ *
+ * Every About You line is a belief, grouped by section. Every memory note is an orb in the lake, in the
+ * column of its project, with the beliefs it holds up (memory-data.js refs). Every message you sent is a
+ * mote in the mist over the water; an "asks:N" source is sampled from the motes whose words match it.
+ *
+ * Its text is untrusted (written by models and people); nothing here renders it.
+ */
+
+export const DAY = 86_400_000
+export const TAU = Math.PI * 2
+export const YOU = [196, 218, 255] // the person's own words
+export const GOLD = [255, 226, 170]
+const SECTION_HUES = [192, 266, 334, 36, 150, 222, 300, 82]
+
+// ── small helpers ─────────────────────────────────────────────────────────────────────────────────
+
+export const clamp = (v, a, b) => (v < a ? a : v > b ? b : v)
+export const lerp = (a, b, t) => a + (b - a) * t
+export const smooth = (t) => (t <= 0 ? 0 : t >= 1 ? 1 : t * t * (3 - 2 * t))
+export const easeOut = (t) => 1 - Math.pow(1 - clamp(t, 0, 1), 3)
+export const easeInOut = (t) => { t = clamp(t, 0, 1); return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2 }
+export const frac = (x) => x - Math.floor(x)
+export function hash(str) { let h = 2166136261; str = String(str); for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619) } return h >>> 0 }
+export const h01 = (str) => hash(str) / 4294967296
+export function rng(seed) {
+ return function () {
+ seed |= 0; seed = (seed + 0x6d2b79f5) | 0
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+export function gauss(r) { const u = Math.max(1e-6, r()), v = r(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * v) }
+export function rgbOf(hex) { const m = /^#?([0-9a-f]{6})$/i.exec(String(hex || '').trim()); const n = m ? parseInt(m[1], 16) : 0x8b8f96; return [(n >> 16) & 255, (n >> 8) & 255, n & 255] }
+export function hslRgb(h, s, l) {
+ h = ((h % 360) + 360) % 360 / 360
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s, p = 2 * l - q
+ const f = (t) => { t = frac(t); return t < 1 / 6 ? p + (q - p) * 6 * t : t < 1 / 2 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p }
+ return [Math.round(f(h + 1 / 3) * 255), Math.round(f(h) * 255), Math.round(f(h - 1 / 3) * 255)]
+}
+export const mix = (a, b, t) => [Math.round(lerp(a[0], b[0], t)), Math.round(lerp(a[1], b[1], t)), Math.round(lerp(a[2], b[2], t))]
+export const css = (rgb, a = 1) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a})`
+export const hexOf = (rgb) => '#' + rgb.map((v) => v.toString(16).padStart(2, '0')).join('')
+
+const STOP = new Set(('the and for with that this from your you are was were have has had not but all any can our out who when ' +
+ 'where into onto over under than then them they their there these those its about after before again also just only very ' +
+ 'more most much many some such each every both other others same own off once here even ever still yet nor too will would could ' +
+ 'should shall may might must does did doing done being been get gets got make makes made like want wants wanted need needs use ' +
+ 'uses used using one two three four five six seven eight nine ten per via let lets now right way ways thing things time times work ' +
+ 'works asks ask says said tell told give gives keep keeps going good well yes okay please mostly nearly about alongside while away ' +
+ 'end new old say goes put set see seen look find its it’s don’t i’m isn’t through without before between them always never').split(/\s+/))
+export const wordsOf = (text) => String(text ?? '').toLowerCase().match(/[\p{L}\p{N}_]{2,}/gu) ?? []
+const stem = (w) => (w.length > 4 ? w.replace(/(ing|ed|es|s)$/, '') : w)
+
+export function ago(ms) {
+ const d = ms / DAY
+ if (d < 1) { const h = Math.round(ms / 3_600_000); return h <= 1 ? 'just now' : `${h}h ago` }
+ if (d < 14) return `${Math.round(d)}d ago`
+ if (d < 60) return `${Math.round(d / 7)}w ago`
+ if (d < 365) return `${Math.round(d / 30)}mo ago`
+ return `${(d / 365).toFixed(1)}y ago`
+}
+export const short = (s, n) => { s = String(s ?? ''); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s }
+export const clean = (s) => String(s ?? '').replace(/\[Image #\d+\]/g, ' ').replace(/\s+/g, ' ').trim()
+
+/** Eternal Sunshine: old titles lose their letters. */
+export function decay(text, loss, seed) {
+ if (loss <= 0) return short(text, 30)
+ const r = rng(hash(seed))
+ let out = ''
+ for (const ch of short(text, 30)) out += ch !== ' ' && r() < loss ? ' ' : ch
+ return out
+}
+
+// ── data → a mind ─────────────────────────────────────────────────────────────────────────────────
+
+/**
+ * data: { snapshot, asks } as memory-data.js load() gives them. agent(id, snapshot) → { name, color };
+ * refs(line, snapshot) → the memory rows an About You line cites.
+ */
+export function buildMind(data, { agent, refs }) {
+ const snap = data.snapshot || {}
+ const mind = { snapshot: snap, asks: (data.asks ?? []).filter((ask) => ask && Number.isFinite(ask.at)), now: snap.observedAt || Date.now(), sections: [], beliefs: [], orbs: [], columns: [], motes: null }
+ const lines = (snap.about?.lines ?? []).filter((line) => line && String(line.text ?? '').trim())
+ const names = [...new Set(lines.map((l) => l.section || 'About you'))]
+ mind.sections = names.map((name, k) => {
+ const hue = SECTION_HUES[k % SECTION_HUES.length]
+ return { name, k, hue, rgb: hslRgb(hue, 0.8, 0.74), deep: hslRgb(hue, 0.7, 0.58), beliefs: [] }
+ })
+
+ // Orbs: every memory note.
+ mind.orbs = (snap.memories ?? []).filter((m) => m && m.id).map((m, i) => {
+ const ag = agent(m.agent, snap)
+ const age = Math.max(0, mind.now - (m.modified || mind.now))
+ const ageDays = age / DAY
+ return {
+ i, m, ag, rgb: rgbOf(ag.color), age, ageDays, fresh: Math.exp(-ageDays / 40),
+ r: clamp(4.5 + 2.2 * Math.log10(Math.max(60, m.size || (m.body || '').length || 60) / 60), 4.5, 10),
+ beliefs: [], col: null, jx: h01(m.id + 'x'), ph: h01(m.id) * TAU,
+ bx: 0, by: 0, by0: 0, x: 0, y: 0, lift: 0, glow: 0, appear: 0, delay: 0, match: -1,
+ loss: clamp((ageDays - 21) / 200, 0, 0.42),
+ lt: String(m.title ?? '').toLowerCase(), ld: String(m.description ?? '').toLowerCase(),
+ lb: String(m.body ?? '').toLowerCase(), lp: String(m.project?.name ?? '').toLowerCase(), la: String(ag.name ?? '').toLowerCase(),
+ }
+ })
+ for (const o of mind.orbs) o.label = decay(String(o.m.title || o.m.path || 'untitled'), o.loss, o.m.id)
+ const byId = new Map(mind.orbs.map((o) => [o.m.id, o]))
+
+ // Beliefs: every About You line, with the memories and messages that hold it up.
+ mind.beliefs = lines.map((line, idx) => {
+ const sec = mind.sections[names.indexOf(line.section || 'About you')]
+ const b = { idx, line: (snap.about.lines ?? []).indexOf(line), sec, j: sec.beliefs.length, text: String(line.text ?? ''), mems: [], missing: [], askN: 0, sessions: [], motes: [], quotes: [], threads: [],
+ phase: frac(idx * 0.61803398875) * TAU, n: 0, len: 1, pluckT: -99, pluckA: 0, flash: 0, roots: [], v: 1 }
+ for (const ref of line.refs ?? []) {
+ const at = String(ref).indexOf(':')
+ const kind = at < 0 ? String(ref) : String(ref).slice(0, at), name = at < 0 ? '' : String(ref).slice(at + 1)
+ if (kind === 'asks') { b.askN += Number(name) || 0; continue }
+ if (kind === 'session') { b.sessions.push(name); continue }
+ const found = refs({ refs: [ref] }, snap)
+ if (!found.length) b.missing.push({ agent: agent(kind, snap), name })
+ for (const row of found) { const o = byId.get(row.id); if (o && !b.mems.includes(o)) b.mems.push(o) }
+ }
+ for (const o of b.mems) o.beliefs.push(b)
+ sec.beliefs.push(b)
+ return b
+ })
+ for (const sec of mind.sections) for (const b of sec.beliefs) {
+ const n = sec.beliefs.length
+ b.v = n === 1 ? 1 : 1 - b.j * (0.6 / (n - 1))
+ }
+
+ buildMotes(mind)
+ buildColumns(mind)
+ for (const b of mind.beliefs) {
+ b.weight = b.mems.length + (b.askN || b.sessionAsks ? 1 + Math.log10(1 + (b.askN || b.sessionAsks)) * 0.6 : 0) + b.missing.length * 0.3
+ b.threads = [
+ ...b.mems.map((o) => ({ kind: 'memory', o })),
+ ...(b.askN ? [{ kind: 'asks' }] : []),
+ ...b.sessions.map((id) => ({ kind: 'session', id })),
+ ...b.missing.map((x) => ({ kind: 'missing', x })),
+ ]
+ }
+ return mind
+}
+
+function buildMotes(mind) {
+ const asks = mind.asks, N = asks.length
+ const M = { n: N, bx: new Float32Array(N), by: new Float32Array(N), ph: new Float32Array(N), a: new Float32Array(N),
+ bucket: new Uint8Array(N), lift: new Float32Array(N), match: new Uint8Array(N), col: new Array(N), lower: new Array(N), key: new Map(), bel: new Map(), session: new Map() }
+ for (let i = 0; i < N; i++) {
+ const ask = asks[i]
+ M.lower[i] = String(ask.text ?? '').toLowerCase()
+ M.key.set(`${ask.sessionId}#${ask.turn}`, i)
+ const list = M.session.get(ask.sessionId)
+ if (list) list.push(i); else M.session.set(ask.sessionId, [i])
+ const ageDays = Math.max(0, mind.now - (ask.at || mind.now)) / DAY
+ const a = 0.12 + 0.5 * Math.exp(-ageDays / 18)
+ M.a[i] = a
+ M.bucket[i] = a > 0.45 ? 3 : a > 0.32 ? 2 : a > 0.2 ? 1 : 0
+ M.ph[i] = h01(ask.sessionId + ':' + ask.turn) * TAU
+ }
+ for (const list of M.session.values()) list.sort((p, q) => asks[p].turn - asks[q].turn || asks[p].at - asks[q].at)
+ mind.motes = M
+
+ // Which messages each belief rests on: its "asks:N" sampled by matching the message text, then by count.
+ const df = new Map()
+ const stemsOf = (text) => [...new Set(wordsOf(text).filter((w) => w.length >= 3 && !STOP.has(w) && !/^\d+$/.test(w)).map(stem))]
+ for (const b of mind.beliefs) {
+ b.stems = stemsOf(b.text)
+ for (const s of b.stems) if (!df.has(s)) { let c = 0; for (let i = 0; i < N; i++) if (M.lower[i].includes(s)) c++; df.set(s, c) }
+ }
+ for (const b of mind.beliefs) {
+ const chosen = []
+ const seen = new Set()
+ for (const id of b.sessions) {
+ const own = M.session.get(id) ?? []
+ b.sessionAsks = (b.sessionAsks || 0) + own.length
+ for (const i of own) { if (chosen.length >= 64) break; chosen.push(i); seen.add(i) }
+ }
+ if (b.askN && N) {
+ const idf = b.stems.map((s) => { const c = df.get(s) || 0; return c && c / N < 0.22 ? Math.log(N / (1 + c)) : 0 })
+ const scored = []
+ for (let i = 0; i < N; i++) {
+ let sc = 0
+ for (let k = 0; k < b.stems.length; k++) if (idf[k] && M.lower[i].includes(b.stems[k])) sc += idf[k]
+ if (sc > 0) scored.push([sc, i])
+ }
+ scored.sort((p, q) => q[0] - p[0] || asks[q[1]].at - asks[p[1]].at)
+ const want = Math.min(b.askN, 56)
+ for (const [, i] of scored) { if (chosen.length >= want) break; if (!seen.has(i)) { chosen.push(i); seen.add(i) } }
+ // Quotes: the person's own words, short and clearly about this.
+ const top = scored.slice(0, 80).map(([sc, i]) => [sc, clean(asks[i].text), i]).filter(([, t]) => t.length >= 6 && t.length <= 120 && !/[{}<>]|```/.test(t))
+ top.sort((p, q) => q[0] - p[0] || p[1].length - q[1].length)
+ const qs = new Set()
+ for (const [, t] of top) { const k = t.toLowerCase(); if (!qs.has(k)) { qs.add(k); b.quotes.push(t) } if (b.quotes.length >= 2) break }
+ // Then by count: an even, stable sample of the rest.
+ const r = rng(hash(b.text))
+ let guard = 0
+ while (chosen.length < want && guard++ < want * 30) { const i = Math.floor(r() * N); if (!seen.has(i)) { chosen.push(i); seen.add(i) } }
+ }
+ b.motes = chosen
+ for (const i of chosen) { const list = M.bel.get(i); if (list) list.push(b); else M.bel.set(i, [b]) }
+ }
+}
+
+/** A folder said the way a project's path is written: `~/code/app`, from `/Users/sam/code/app`. */
+const tilde = (path) => String(path ?? '').replace(/^\/(?:Users|home)\/[^/]+/, '~').replace(/\/+$/, '')
+
+function buildColumns(mind) {
+ const cols = new Map()
+ const col = (key, name) => { let c = cols.get(key); if (!c) { c = { key, name, orbs: [], asks: 0 }; cols.set(key, c) } return c }
+ for (const o of mind.orbs) { const name = o.m.project?.name; o.col = name ? col('p:' + name, name) : col('*', 'everywhere'); o.col.orbs.push(o) }
+ // Messages gather over the project they were said in: its folder, a folder inside it, or one of its
+ // worktrees, as the pane's Projects count them; else a folder named like the project.
+ const projects = (mind.snapshot.projects ?? []).filter((p) => p && p.name)
+ const paths = projects
+ .flatMap((p) => [p.key && !String(p.key).startsWith('name:') ? p.key : null, p.path].filter(Boolean).map((path) => ({ name: p.name, path: tilde(path), base: tilde(path).split('/').pop() })))
+ .filter((p) => p.path && p.path !== '~')
+ .sort((a, b) => b.path.length - a.path.length)
+ const placeOf = (cwd) => {
+ const c = tilde(cwd)
+ if (!c) return null
+ for (const p of paths) if (c === p.path || c.startsWith(p.path + '/')) return p.name
+ for (const p of paths) if (p.base && c.includes(`/worktrees/${p.base}/`)) return p.name
+ const base = c.split('/').filter(Boolean).pop()
+ if (base && (cols.has('p:' + base) || projects.some((p) => p.name === base))) return base
+ return null
+ }
+ const M = mind.motes
+ const placed = new Map()
+ for (let i = 0; i < M.n; i++) {
+ const cwd = String(mind.asks[i].cwd || '')
+ if (!placed.has(cwd)) placed.set(cwd, placeOf(cwd))
+ const name = placed.get(cwd)
+ if (name) { const c = col('p:' + name, name); c.asks++; M.col[i] = c } else M.col[i] = null
+ }
+ mind.columns = [...cols.values()]
+ for (const c of mind.columns) c.weight = Math.max(1.3, Math.pow(c.orbs.length, 0.72)) + (c.asks ? 0.5 + Math.log10(1 + c.asks) * 0.4 : 0)
+ // Biggest in the middle, smaller ones outward.
+ const sorted = [...mind.columns].sort((a, b) => b.weight - a.weight || a.name.localeCompare(b.name))
+ const left = [], right = []
+ sorted.forEach((c, i) => (i % 2 ? left : right).push(c))
+ mind.columns = [...left.reverse(), ...right]
+}
+
+// ── recall ────────────────────────────────────────────────────────────────────────────────────────
+
+/**
+ * What a query stirs: the memories with every word somewhere in them (best first), your messages that
+ * say every word (indices into mind.asks), the beliefs whose words match (direct), and every belief
+ * they hold up.
+ */
+export function recallMatch(mind, q) {
+ const terms = wordsOf(q)
+ const mems = []
+ for (const o of mind.orbs) {
+ let score = 0, ok = terms.length > 0
+ for (const term of terms) {
+ let s = 0
+ if (o.lt.includes(term)) s += 6
+ if (o.ld.includes(term)) s += 3
+ if (o.lp.includes(term)) s += 2
+ if (o.la.includes(term)) s += 2
+ if (o.lb.includes(term)) s += 1
+ if (!s) { ok = false; break }
+ score += s
+ }
+ if (ok) mems.push([score + o.fresh, o])
+ }
+ mems.sort((a, b) => b[0] - a[0])
+ const M = mind.motes
+ const local = []
+ if (terms.length) {
+ for (let i = 0; i < M.n; i++) {
+ const text = M.lower[i]
+ let ok = true
+ for (const term of terms) if (!text.includes(term)) { ok = false; break }
+ if (ok) local.push(i)
+ }
+ }
+ const beliefs = new Set()
+ for (const b of mind.beliefs) { const lt = b.text.toLowerCase(); if (terms.length && terms.every((term) => lt.includes(term))) beliefs.add(b) }
+ const direct = [...beliefs]
+ for (const [, o] of mems) for (const b of o.beliefs) beliefs.add(b)
+ for (const i of local) { const list = M.bel.get(i); if (list) for (const b of list) beliefs.add(b) }
+ local.sort((a, b) => mind.asks[b].at - mind.asks[a].at)
+ return { terms, mems: mems.map(([, o]) => o), local, beliefs, direct }
+}
+
+/** Matches of `terms` in text, marked \u0002 … \u0003 as /api/search marks them. */
+export function mark(text, terms) {
+ let out = String(text ?? '')
+ for (const term of terms) out = out.replace(new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), (m) => `\u0002${m}\u0003`)
+ return out
+}
+
+/** A window of the message around its first match, with matches marked. */
+export function snippetOf(text, terms) {
+ const lower = text.toLowerCase()
+ let at = -1
+ for (const term of terms) { const k = lower.indexOf(term); if (k >= 0 && (at < 0 || k < at)) at = k }
+ let out = text
+ if (at > 40) { const from = text.lastIndexOf(' ', at - 30); out = '…' + text.slice(from > 0 ? from + 1 : at - 30) }
+ return mark(short(out, 150), terms)
+}
diff --git a/store/agents/memories/viewer/self.css b/store/agents/memories/viewer/self.css
new file mode 100644
index 000000000..e7f80d92a
--- /dev/null
+++ b/store/agents/memories/viewer/self.css
@@ -0,0 +1,111 @@
+/* Sense of Self (self.js). The scene stays dark in a light pane; only the header follows the theme.
+ Sizes come from the stage, not the window: self.js sets --gutter, --col, --cap-top and the type sizes. */
+.self {
+ --s-bg: #030407; --s-ink: #eef2f8; --s-ink2: #b8c0ce; --s-dim: #7a8394; --s-faint: #4b5262; --s-gold: #ffe3ad; --sec: #9fd8ff;
+ --serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;
+ --gutter: 24px; --col: 300px; --cap-top: 40px; --cap-size: 24px; --whisper-size: 30px; --panel-size: 24px;
+ position: relative; overflow: hidden; background: var(--s-bg); color: var(--s-ink); color-scheme: dark;
+ font: 12px/1.5 var(--mono); -webkit-font-smoothing: antialiased;
+}
+.self .scene { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.self .vignette { position: absolute; inset: 0; pointer-events: none; background: radial-gradient(ellipse 85% 80% at 50% 45%, transparent 55%, rgba(0, 0, 0, .5) 100%); }
+
+.self .col { position: absolute; left: var(--gutter); top: var(--cap-top); width: var(--col); }
+.self .kicker { font: 500 11px/1.4 var(--mono); letter-spacing: .14em; text-transform: uppercase; color: var(--sec); display: flex; gap: 12px; align-items: baseline; }
+.self .kicker .n { color: var(--s-faint); letter-spacing: .08em; }
+
+.self .whisper { opacity: 0; transition: opacity 1.1s ease; pointer-events: none; }
+.self .whisper.on { opacity: 1; }
+.self .whisper .t { font: 400 var(--whisper-size)/1.1 var(--serif); color: #fbf6ea; letter-spacing: .01em; text-shadow: 0 0 30px rgba(255, 230, 190, .25); }
+.self .whisper .s { margin-top: 12px; color: var(--s-dim); font-size: 11px; letter-spacing: .04em; max-width: 34ch; }
+
+.self .caption { opacity: 0; transition: opacity .6s ease; pointer-events: none; }
+.self .caption.on { opacity: 1; pointer-events: auto; }
+.self .cap-text { font: 400 var(--cap-size)/1.24 var(--serif); margin: 14px 0 24px; color: #fbf7ee; text-wrap: pretty; text-shadow: 0 0 26px rgba(255, 234, 196, .16); overflow-wrap: anywhere; }
+.self .cap-why-label { color: var(--s-dim); font-size: 11px; letter-spacing: .05em; margin-bottom: 7px; }
+.self .cap-why { list-style: none; margin: 0; padding: 0; }
+.self .cap-why li { display: grid; grid-template-columns: 12px 1fr auto; column-gap: 9px; padding: 4px 7px; margin: 0 -7px; border-radius: 5px; color: var(--s-ink2); transition: background .15s, color .15s; }
+.self .cap-why li.go { cursor: pointer; }
+.self .cap-why li.go:hover { background: rgba(255, 255, 255, .04); }
+.self .cap-why li.sel { background: rgba(255, 255, 255, .065); color: var(--s-ink); box-shadow: inset 2px 0 0 var(--s-gold); }
+.self .cap-why li .w { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
+.self .cap-why li .w small { color: var(--s-dim); font-size: 10.5px; margin-left: 6px; }
+.self .cap-why li .a { color: var(--s-faint); font-size: 10.5px; }
+.self .cap-why li.missing { color: var(--s-faint); }
+.self .cap-why li .q { grid-column: 2 / 4; font: italic 13px/1.4 var(--serif); color: var(--s-dim); margin-top: 3px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
+.self .cap-note { color: var(--s-dim); font-size: 11.5px; line-height: 1.6; max-width: 46ch; }
+.self .cap-note p { margin: 0 0 10px; }
+.self .cap-note .ask { border-left: 2px solid var(--s-gold); padding: 3px 0 3px 12px; margin: 0 0 14px; color: var(--s-ink2); }
+.self .cap-note .ask .say { font: 400 18px/1.35 var(--serif); color: var(--s-gold); margin-top: 3px; }
+.self .caption.empty .cap-text { margin-bottom: 16px; }
+.self .dot { width: 8px; height: 8px; border-radius: 50%; margin-top: 4.5px; background: currentColor; box-shadow: 0 0 8px currentColor; }
+.self .dot.ring { background: transparent; border: 1.5px solid currentColor; box-shadow: 0 0 6px currentColor; }
+.self .dot.diamond { border-radius: 1px; transform: rotate(45deg) scale(.85); }
+
+.self .recall { display: none; padding: 14px 16px 12px; margin: -14px -16px; background: rgba(4, 6, 11, .84); border: 1px solid rgba(255, 255, 255, .05); border-radius: 10px; width: calc(var(--col) + 120px); max-width: calc(100% - 2 * var(--gutter)); max-height: calc(100% - var(--cap-top) - 44px); overflow-y: auto; scrollbar-width: thin; scrollbar-color: #2a3040 transparent; }
+.self .recall.on { display: block; }
+.self .recall .kicker { color: var(--s-dim); }
+.self .recall-list { list-style: none; margin: 10px 0 0; padding: 0; }
+.self .recall-list li { display: grid; grid-template-columns: 12px 1fr auto; column-gap: 9px; padding: 4px 7px; margin: 0 -7px; border-radius: 5px; color: var(--s-ink2); cursor: pointer; }
+.self .recall-list li:hover { background: rgba(255, 255, 255, .04); }
+.self .recall-list li.sel { background: rgba(255, 255, 255, .07); color: var(--s-ink); box-shadow: inset 2px 0 0 var(--s-gold); }
+.self .recall-list li .w { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
+.self .recall-list li .a { color: var(--s-faint); font-size: 10.5px; white-space: nowrap; }
+.self .recall-list li.head { color: var(--s-faint); font-size: 10px; letter-spacing: .14em; text-transform: uppercase; padding-top: 9px; grid-template-columns: 1fr; cursor: default; }
+.self .recall-list li.head:hover { background: none; }
+.self .recall-list li .w.serif { font: 13.5px/1.35 var(--serif); }
+.self mark { background: none; color: var(--s-gold); text-shadow: 0 0 10px rgba(255, 220, 150, .5); }
+
+.self .orb-label { position: absolute; left: 0; top: 0; max-width: min(340px, 44%); padding: 10px 13px 11px; background: rgba(5, 7, 13, .78); border: 1px solid rgba(255, 255, 255, .07); border-radius: 9px; pointer-events: none; opacity: 0; transition: opacity .25s; will-change: transform; }
+.self .orb-label.on { opacity: 1; }
+.self .orb-label .m { color: var(--s-dim); font-size: 10.5px; letter-spacing: .03em; display: flex; gap: 7px; align-items: center; }
+.self .orb-label .m .dot { margin-top: 0; width: 7px; height: 7px; }
+.self .orb-label .t { font: 17px/1.25 var(--serif); color: #fbf7ee; margin: 5px 0 4px; overflow-wrap: anywhere; }
+.self .orb-label .h { color: var(--s-ink2); font-size: 11px; }
+.self .orb-label .h div { font: italic 12.5px/1.35 var(--serif); color: var(--s-gold); opacity: .85; margin-top: 3px; }
+.self .orb-label .h.none { color: var(--s-faint); }
+
+.self .veil { position: absolute; inset: 0; background: radial-gradient(ellipse at 50% 45%, rgba(2, 3, 6, .5), rgba(2, 3, 6, .88)); opacity: 0; pointer-events: none; transition: opacity .45s ease; }
+.self .veil.on { opacity: 1; }
+.self .panel { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(720px, calc(100% - 32px)); max-height: min(80%, 780px); display: none; flex-direction: column; background: linear-gradient(180deg, rgba(15, 18, 28, .97), rgba(7, 9, 15, .98)); border: 1px solid rgba(255, 255, 255, .08); border-radius: 14px; box-shadow: 0 30px 120px rgba(0, 0, 0, .65), 0 0 90px -10px var(--glow, rgba(255, 220, 160, .25)); overflow: hidden; }
+.self .panel.on { display: flex; }
+.self .panel::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 1px; background: linear-gradient(90deg, transparent, var(--glow, #ffe3ad), transparent); opacity: .8; }
+.self .panel header { padding: 22px 28px 12px; }
+.self .panel .meta { display: flex; flex-wrap: wrap; gap: 4px 9px; align-items: center; font-size: 11px; color: var(--s-dim); letter-spacing: .03em; }
+.self .panel .meta .dot { margin-top: 0; }
+.self .panel h2 { font: 400 var(--panel-size)/1.2 var(--serif); margin: 10px 0 6px; color: #fbf7ee; overflow-wrap: anywhere; }
+.self .panel .desc { font: italic 15px/1.45 var(--serif); color: var(--s-ink2); margin: 0; }
+.self .panel .desc:empty { display: none; }
+.self .panel .body { overflow: auto; padding: 6px 28px 22px; font: 15.5px/1.62 var(--serif); color: #d9dee8; overflow-wrap: anywhere; scrollbar-width: thin; scrollbar-color: #2a3040 transparent; outline: none; }
+.self .panel .body p { margin: 0 0 .8em; }
+.self .panel .body h4 { font: 600 11px/1.4 var(--mono); letter-spacing: .12em; text-transform: uppercase; color: var(--s-dim); margin: 1.3em 0 .5em; }
+.self .panel .body .li { padding-left: 1.1em; text-indent: -1.1em; margin: 0 0 .35em; }
+.self .panel .body .li::before { content: "· "; color: var(--s-dim); }
+.self .panel .body code { font: 12.5px var(--mono); background: rgba(255, 255, 255, .06); border-radius: 3px; padding: 1px 4px; }
+.self .panel .body pre { font: 12px/1.5 var(--mono); background: rgba(255, 255, 255, .04); border-radius: 6px; padding: 10px 12px; overflow: auto; white-space: pre-wrap; }
+.self .panel .body strong { color: #fff; font-weight: 600; }
+.self .panel .body .msg { display: grid; grid-template-columns: 12px 1fr; column-gap: 10px; padding: 7px 0; border-bottom: 1px solid rgba(255, 255, 255, .04); }
+.self .panel .body .msg.here { background: rgba(255, 255, 255, .035); margin: 0 -12px; padding: 7px 12px; border-radius: 6px; }
+.self .panel .body .msg .a { grid-column: 2; font: 10.5px var(--mono); color: var(--s-faint); }
+.self .panel .body .msg .x { grid-column: 2; font: 14px/1.45 var(--serif); color: var(--s-ink2); }
+.self .panel .body .msg.here .x { color: #fbf7ee; }
+.self .panel .body .msg.go { cursor: pointer; }
+.self .panel .body .msg.go:hover .x { color: #fbf7ee; }
+.self .panel .body .related h4 { margin-top: 1.8em; }
+.self .panel .body .turn { display: grid; grid-template-columns: 6ch 1fr; column-gap: 12px; row-gap: 4px; padding: 10px 0; border-bottom: 1px solid rgba(255, 255, 255, .04); }
+.self .panel .body .turn.here { background: rgba(255, 255, 255, .035); margin: 0 -12px; padding: 10px 12px; border-radius: 6px; }
+.self .panel .body .turn .who { font: 10.5px/1.9 var(--mono); color: var(--s-faint); text-align: right; }
+.self .panel .body .turn .x { font: 14.5px/1.5 var(--serif); color: #e9edf4; white-space: pre-wrap; }
+.self .panel .body .turn .y { font: 13.5px/1.5 var(--serif); color: var(--s-dim); white-space: pre-wrap; }
+.self .panel .body .turn .a { grid-column: 2; font: 10.5px var(--mono); color: var(--s-faint); }
+.self .panel footer { border-top: 1px solid rgba(255, 255, 255, .06); padding: 11px 28px 14px; font-size: 11px; color: var(--s-dim); }
+.self .panel footer .b { font: italic 13.5px/1.4 var(--serif); color: var(--s-gold); margin-top: 4px; }
+.self .panel footer .p { color: var(--s-faint); margin-top: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: all; }
+
+.self .hint { position: absolute; left: var(--gutter); right: var(--gutter); bottom: 10px; display: flex; justify-content: space-between; align-items: baseline; gap: 16px; color: var(--s-faint); font-size: 11px; letter-spacing: .02em; pointer-events: none; white-space: nowrap; }
+.self .hint .keys { overflow: hidden; text-overflow: ellipsis; min-width: 0; }
+.self .hint .status { overflow: hidden; text-overflow: ellipsis; flex: none; }
+.self.narrow .hint .status { display: none; }
+.self .toast { position: absolute; right: var(--gutter); top: 14px; color: var(--s-dim); font-size: 11px; opacity: 0; transition: opacity .3s; pointer-events: none; }
+.self .toast.on { opacity: 1; }
+.self .error { position: absolute; inset: 0; display: none; place-items: center; color: var(--s-dim); font-size: 12px; padding: 24px; text-align: center; }
diff --git a/store/agents/memories/viewer/self.js b/store/agents/memories/viewer/self.js
new file mode 100644
index 000000000..f0002400f
--- /dev/null
+++ b/store/agents/memories/viewer/self.js
@@ -0,0 +1,1976 @@
+/**
+ * Sense of Self: the Memories pane. About You as a luminous structure, held up by the lake of memories
+ * below it. Ported from docs/research/2026-10-10-memory-brain/self.js.
+ *
+ * Above the water, every About You line is a belief: one strand of light. The strands braid into a trunk
+ * and open into one frond per section. Below the water, every memory note is an orb, colored by the
+ * agent that wrote it, brighter and nearer the surface when it is new. Threads rise from each orb to the
+ * beliefs it holds up, and your own messages hang over the water as mist; "asks:N" sources rise out of it.
+ *
+ * Keys. The header prompt is the recall: typing anywhere types there, and once it holds anything,
+ * letters, digits and space belong to it.
+ * ←→ section · ↑↓ belief (↓ past the last dives into the lake) · space pluck · tab why · ⏎ follow it down
+ * in the lake: ←↑↓→ swim · ⏎ lift a memory out · space follow its light up · esc rise
+ * recalling: ↑↓ or tab choose · ⏎ open · esc forget. A memory lifted out: ↑↓ scroll · esc back.
+ * Clicking a section, a belief, an orb or a row does what its key does.
+ *
+ * Reads memory-data.js only and writes nothing. Memory text is written by models: it reaches the screen
+ * through textContent and canvas fillText only, never as HTML.
+ */
+
+import {
+ GOLD, TAU, YOU, ago, buildMind, clamp, clean, css, easeInOut, easeOut, frac, gauss, h01, hexOf, lerp, mark, mix,
+ recallMatch, rgbOf, rng, short, smooth, snippetOf, wordsOf,
+} from './self-model.js'
+
+const NA = 18 // points along the trunk
+const NC = 12 // points from where a strand leaves its frond to its bead
+const MAXP = NA + 30 + NC + 2
+const ROOTN = 16
+const ARRIVE_END = 4.8
+// The arrival plays half again as fast as the prototype's: about three seconds. Any key skips it.
+const PACE = 1.5
+const TWIST = Math.PI * 3.2, TWIST2 = Math.PI * 2.4
+const ORB_K = 1 / 0.17 // sprite size per unit of sphere radius
+const MONO = 'ui-monospace, "SF Mono", SFMono-Regular, Menlo, monospace'
+// A rebuilt scene can move things: it waits until you have left it alone this long.
+const QUIET_MS = 6000
+const REBUILD_MS = 20000
+
+function make(doc, tag, cls, text) { const e = doc.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e }
+
+/** Simple, safe markdown: headings, bullets, code, bold. Elements and text nodes only, never HTML. */
+export function renderBody(doc, root, text) {
+ root.textContent = ''
+ const lines = String(text ?? '').replace(/\r/g, '').split('\n')
+ let para = null, code = null
+ for (const raw of lines) {
+ if (/^\s*```/.test(raw)) { if (code) code = null; else { code = make(doc, 'pre'); root.append(code) } para = null; continue }
+ if (code) { code.textContent += raw + '\n'; continue }
+ const line = raw.trimEnd()
+ if (!line.trim()) { para = null; continue }
+ let m
+ if ((m = /^\s*#{1,6}\s+(.*)$/.exec(line))) { const h = make(doc, 'h4'); inline(doc, h, m[1]); root.append(h); para = null; continue }
+ if ((m = /^\s*(?:[-*+]|\d+[.)])\s+(.*)$/.exec(line))) { const li = make(doc, 'div', 'li'); inline(doc, li, m[1]); root.append(li); para = null; continue }
+ if (!para) { para = make(doc, 'p'); root.append(para) } else para.append(doc.createElement('br'))
+ inline(doc, para, line)
+ }
+ return root
+}
+function inline(doc, node, text) {
+ const re = /(`[^`]+`|\*\*[^*]+\*\*)/g
+ let last = 0, m
+ while ((m = re.exec(text))) {
+ if (m.index > last) node.append(doc.createTextNode(text.slice(last, m.index)))
+ const tok = m[0]
+ node.append(make(doc, tok[0] === '`' ? 'code' : 'strong', null, tok[0] === '`' ? tok.slice(1, -1) : tok.slice(2, -2)))
+ last = m.index + tok.length
+ }
+ if (last < text.length) node.append(doc.createTextNode(text.slice(last)))
+}
+/** A snippet with \u0002 … \u0003 around its matches, as text with <mark> elements. */
+export function marked(doc, node, snippet) {
+ const parts = String(snippet ?? '').split(/([\u0002\u0003])/)
+ let on = false
+ for (const p of parts) {
+ if (p === '\u0002') { on = true; continue }
+ if (p === '\u0003') { on = false; continue }
+ if (!p) continue
+ node.append(on ? make(doc, 'mark', null, p) : doc.createTextNode(p))
+ }
+ return node
+}
+
+/**
+ * Draws Sense of Self into `root`. `data` is memory-data.js; `loop` the pane's render loop (loop.js);
+ * setQuery/count reach the header prompt. Returns what the pane calls: start, stop, recall, key, resize.
+ */
+export function mountSelf({ root, data, loop, setQuery = () => {}, count = () => {}, reducedMotion = () => false }) {
+ const doc = root.ownerDocument
+ const view = doc.defaultView
+ const el = (tag, cls, text) => make(doc, tag, cls, text)
+ const dot = (rgb, kind) => { const d = el('span', 'dot' + (kind ? ' ' + kind : '')); d.style.color = hexOf(rgb); return d }
+ let reduce = reducedMotion()
+
+ // ── the page ────────────────────────────────────────────────────────────────────────────────────
+ root.classList.add('self', 'arriving')
+ const canvas = el('canvas', 'scene')
+ canvas.setAttribute('role', 'img')
+ canvas.setAttribute('aria-label', 'Sense of Self: what your agents believe about you, held up by the memories in the lake below')
+ const ctx = canvas.getContext('2d')
+ const whisper = el('div', 'whisper col')
+ whisper.setAttribute('aria-hidden', 'true')
+ whisper.append(el('div', 't', 'Sense of Self'), el('div', 's', 'what your agents believe about you, and the memories that hold it up'))
+ const caption = el('section', 'caption col')
+ caption.setAttribute('aria-live', 'polite')
+ const capKicker = el('div', 'kicker'), capSection = el('span'), capCount = el('span', 'n')
+ capKicker.append(capSection, capCount)
+ const capText = el('h2', 'cap-text'), capWhyLabel = el('div', 'cap-why-label'), capWhy = el('ol', 'cap-why'), capNote = el('div', 'cap-note')
+ caption.append(capKicker, capText, capWhyLabel, capWhy, capNote)
+ const recallBox = el('section', 'recall col')
+ recallBox.setAttribute('aria-live', 'polite')
+ const recallSum = el('div', 'kicker'), recallList = el('ol', 'recall-list')
+ recallBox.append(recallSum, recallList)
+ const orbLabel = el('div', 'orb-label'), olDot = el('span', 'dot'), olMeta = el('span'), olTitle = el('div', 't'), olHolds = el('div', 'h')
+ const olM = el('div', 'm'); olM.append(olDot, olMeta)
+ orbLabel.append(olM, olTitle, olHolds)
+ const veil = el('div', 'veil')
+ const panel = el('article', 'panel')
+ panel.setAttribute('role', 'dialog')
+ const pMeta = el('div', 'meta'), pTitle = el('h2'), pDesc = el('p', 'desc'), pBody = el('div', 'body'), pFoot = el('footer')
+ pBody.tabIndex = -1
+ const pHead = el('header'); pHead.append(pMeta, pTitle, pDesc)
+ panel.append(pHead, pBody, pFoot)
+ const toastBox = el('div', 'toast'), errorBox = el('div', 'error')
+ const hint = el('footer', 'hint'), hintKeys = el('span', 'keys'), hintStatus = el('span', 'status')
+ hint.append(hintKeys, hintStatus)
+ root.append(canvas, el('div', 'vignette'), whisper, caption, recallBox, orbLabel, veil, panel, toastBox, errorBox, hint)
+
+ const refl = doc.createElement('canvas'), rctx = refl.getContext('2d')
+ const bloom = doc.createElement('canvas'), bctx = bloom.getContext('2d')
+ // Bloom needs canvas filters; without them, no bloom rather than a blocky one.
+ const bloomOk = (() => { try { bctx.filter = 'blur(2px)'; const ok = bctx.filter === 'blur(2px)'; bctx.filter = 'none'; return ok } catch { return false } })()
+
+ // Glow sprites: a soft radial light per color, drawn with additive blending.
+ const sprites = new Map()
+ function sprite(rgb, hard) {
+ const key = rgb.join(',') + (hard ? 'h' : 's')
+ let c = sprites.get(key)
+ if (c) return c
+ const n = 64
+ c = doc.createElement('canvas'); c.width = c.height = n
+ const g = c.getContext('2d')
+ const grd = g.createRadialGradient(n / 2, n / 2, 0, n / 2, n / 2, n / 2)
+ const w = mix(rgb, [255, 255, 255], 0.72)
+ if (hard) {
+ grd.addColorStop(0, css(w, 1)); grd.addColorStop(0.12, css(w, 0.95)); grd.addColorStop(0.24, css(rgb, 0.85))
+ grd.addColorStop(0.3, css(rgb, 0.32)); grd.addColorStop(0.55, css(rgb, 0.1)); grd.addColorStop(1, css(rgb, 0))
+ } else {
+ grd.addColorStop(0, css(w, 1)); grd.addColorStop(0.08, css(w, 0.8)); grd.addColorStop(0.22, css(rgb, 0.4))
+ grd.addColorStop(0.5, css(rgb, 0.1)); grd.addColorStop(1, css(rgb, 0))
+ }
+ g.fillStyle = grd; g.fillRect(0, 0, n, n)
+ sprites.set(key, c)
+ return c
+ }
+ // A memory orb: a glassy sphere of the agent's color, lit from above, in its own halo.
+ const orbSprites = new Map()
+ function orbSprite(rgb) {
+ const key = rgb.join(',')
+ let c = orbSprites.get(key)
+ if (c) return c
+ const n = 128, h = n / 2, R = n * 0.17
+ c = doc.createElement('canvas'); c.width = c.height = n
+ const g = c.getContext('2d')
+ const halo = g.createRadialGradient(h, h, R * 0.6, h, h, h)
+ halo.addColorStop(0, css(rgb, 0.42)); halo.addColorStop(0.35, css(rgb, 0.12)); halo.addColorStop(1, css(rgb, 0))
+ g.fillStyle = halo; g.fillRect(0, 0, n, n)
+ const body = g.createRadialGradient(h - R * 0.35, h - R * 0.4, R * 0.05, h, h, R)
+ body.addColorStop(0, css(mix(rgb, [255, 255, 255], 0.85), 1))
+ body.addColorStop(0.35, css(mix(rgb, [255, 255, 255], 0.35), 0.95))
+ body.addColorStop(0.8, css(rgb, 0.8))
+ body.addColorStop(1, css(mix(rgb, [0, 0, 0], 0.3), 0.7))
+ g.fillStyle = body; g.beginPath(); g.arc(h, h, R, 0, TAU); g.fill()
+ g.strokeStyle = css(mix(rgb, [255, 255, 255], 0.6), 0.45); g.lineWidth = 1.2
+ g.beginPath(); g.arc(h, h, R - 0.6, 0, TAU); g.stroke()
+ orbSprites.set(key, c)
+ return c
+ }
+
+ // ── state ───────────────────────────────────────────────────────────────────────────────────────
+
+ const S = {
+ ready: false, snapshot: null, asks: [], now: Date.now(),
+ sections: [], beliefs: [], orbs: [], columns: [], motes: null,
+ view: 'self', sec: 0, bel: 0, thread: -1, orb: -1,
+ panel: null, recall: null,
+ arrival: { t: 0, done: false },
+ cam: { y: 0, from: 0, to: 0, t0: 0, dur: 0.001 },
+ pulses: [], ripples: [], flakes: [], extra: [],
+ time: 0, capRect: null, labelHits: [],
+ lastInput: 0, builtAt: 0, stale: false, loading: false, query: '',
+ }
+ const G = {}
+ let DPR = 1
+ const fronds = []
+ const tmp = new Float32Array(4)
+ const now = () => view.performance.now()
+
+ // ── data → the scene ────────────────────────────────────────────────────────────────────────────
+
+ function install(loaded, { arrive }) {
+ const before = S.ready ? { ids: new Set(S.orbs.map((o) => o.m.id)), belief: focusedBelief()?.text, orb: focusedOrb()?.m.id } : null
+ const mind = buildMind(loaded, { agent: data.agent, refs: data.refs })
+ S.snapshot = mind.snapshot; S.asks = mind.asks; S.now = mind.now
+ S.sections = mind.sections; S.beliefs = mind.beliefs; S.orbs = mind.orbs; S.columns = mind.columns; S.motes = mind.motes
+ for (const b of S.beliefs) { b.pts = new Float32Array(MAXP * 2); b.cum = new Float32Array(MAXP) }
+ S.pulses = []; S.ripples = []; S.flakes = []; S.extra = []; S.recall = null; S.thread = -1
+ layout()
+ if (before) {
+ // Where you were stays where you were; a memory saved while you watched glows.
+ const b = S.beliefs.find((x) => x.text === before.belief)
+ if (b) { S.sec = b.sec.k; S.bel = b.j } else { S.sec = clamp(S.sec, 0, Math.max(0, S.sections.length - 1)); S.bel = 0 }
+ S.orb = before.orb ? S.orbs.findIndex((o) => o.m.id === before.orb) : -1
+ if (S.view === 'lake' && S.orb < 0) { S.view = 'self'; camTo(0, 0.001) }
+ for (const o of S.orbs) if (!before.ids.has(o.m.id)) o.glow = 1
+ } else { S.sec = 0; S.bel = 0; S.orb = -1 }
+ S.ready = true
+ S.builtAt = now()
+ S.stale = false
+ errorBox.style.display = 'none'
+ renderStatus()
+ if (arrive && !reduce) { S.arrival = { t: 0, done: false, start: now() }; root.classList.add('arriving') } else finishArrival()
+ renderCaption(false)
+ showCaption()
+ renderHint()
+ // What was typed while the scene loaded, or before it was rebuilt, is recalled now.
+ if (S.query) recall(S.query)
+ else showCount()
+ loop.wake()
+ }
+
+ let loadSeq = 0
+ function load({ arrive }) {
+ const seq = ++loadSeq
+ S.loading = true
+ return data.load().then((loaded) => {
+ if (seq !== loadSeq) return
+ install(loaded, { arrive })
+ }).catch((error) => {
+ if (S.ready) return
+ errorBox.style.display = 'grid'
+ errorBox.textContent = 'Could not read memories: ' + String(error?.message ?? error)
+ }).finally(() => { if (seq === loadSeq) S.loading = false })
+ }
+
+ /** A newer snapshot: taken in once you have left the scene alone, or straight away if it was empty. */
+ const canRebuild = () => S.ready && !S.loading && (
+ (!S.orbs.length && !S.beliefs.length && !S.asks.length) ||
+ (S.arrival.done && S.view === 'self' && !S.recall && !S.panel && now() - S.lastInput > QUIET_MS && now() - S.builtAt > REBUILD_MS))
+ data.onChange?.(() => { S.stale = true })
+ const staleTimer = view.setInterval(() => { if (S.stale && running && canRebuild()) load({ arrive: false }) }, 2500)
+
+ // ── layout ──────────────────────────────────────────────────────────────────────────────────────
+
+ function layout() {
+ const W = Math.max(320, root.clientWidth), H = Math.max(320, root.clientHeight)
+ DPR = Math.min(2, view.devicePixelRatio || 1)
+ canvas.width = Math.round(W * DPR); canvas.height = Math.round(H * DPR)
+ G.W = W; G.H = H
+ G.gutter = clamp(W * 0.03, 16, 44)
+ G.col = clamp(W * 0.3, 210, 420)
+ G.capRight = G.gutter + G.col
+ root.style.setProperty('--gutter', `${G.gutter}px`)
+ root.style.setProperty('--col', `${G.col}px`)
+ root.style.setProperty('--cap-top', `${clamp(H * 0.065, 16, 64)}px`)
+ root.style.setProperty('--cap-size', `${clamp(W * 0.0235, 19, 34)}px`)
+ root.style.setProperty('--whisper-size', `${clamp(W * 0.03, 26, 42)}px`)
+ root.style.setProperty('--panel-size', `${clamp(W * 0.025, 21, 32)}px`)
+ root.classList.toggle('narrow', W < 900)
+ G.hz = Math.round(H * 0.6)
+ G.treeX = G.capRight + (W - G.capRight) * 0.5
+ G.trunkLen = H * 0.2
+ const hw = (W - G.capRight) / 2 - 8
+ G.L = Math.max(90, Math.min((hw - 128) / 1.07, (G.hz - G.trunkLen - 40) / 1.15))
+ const total = S.beliefs.length || 1
+ G.trunkR = 5 + Math.min(10, total * 0.36)
+ G.lakeTop = G.hz + 44
+ G.depth = H * 0.68
+ G.lakeCam = G.hz - H * 0.13
+ // From above, the whole lake folds into the band under the surface; diving unfolds it.
+ G.sqSelf = clamp((H - 40 - G.hz) / (G.lakeTop + G.depth + 8 - G.hz), 0.3, 1)
+ G.sq = G.sqSelf
+ G.maxAge = Math.max(30, ...S.orbs.map((o) => o.ageDays))
+
+ const n = S.sections.length
+ const spread = n > 1 ? (Math.min(144, 38 * (n - 1)) * Math.PI) / 180 : 0
+ fronds.length = 0
+ for (let k = 0; k < Math.max(1, n); k++) {
+ const a = -Math.PI / 2 + (n > 1 ? (k / (n - 1) - 0.5) * spread : 0)
+ fronds.push({ a, dx: Math.cos(a), side: Math.cos(a) >= -1e-6 ? -1 : 1, p0: [0, 0], p1: [0, 0], p2: [0, 0], p3: [0, 0], end: [0, 0], T: [0, -1] })
+ }
+
+ // Gradients, cached per size.
+ G.sky = ctx.createLinearGradient(0, 0, 0, G.hz)
+ G.sky.addColorStop(0, '#030407'); G.sky.addColorStop(0.7, '#05060d'); G.sky.addColorStop(1, '#090b1c')
+ G.water = ctx.createLinearGradient(0, G.hz, 0, G.hz + G.depth + H * 0.3)
+ G.water.addColorStop(0, '#070a1a'); G.water.addColorStop(0.18, '#04060f'); G.water.addColorStop(1, '#010103')
+ G.surf = ctx.createLinearGradient(0, 0, W, 0)
+ const tx = G.treeX / W
+ G.surf.addColorStop(0, 'rgba(140,170,255,0)'); G.surf.addColorStop(clamp(tx - 0.35, 0.01, 0.98), 'rgba(160,185,255,0.25)')
+ G.surf.addColorStop(tx, 'rgba(235,240,255,0.85)'); G.surf.addColorStop(clamp(tx + 0.3, tx + 0.01, 0.995), 'rgba(160,185,255,0.25)'); G.surf.addColorStop(1, 'rgba(140,170,255,0)')
+ G.ray = ctx.createLinearGradient(0, G.hz, 0, G.hz + G.depth)
+ G.ray.addColorStop(0, 'rgba(120,150,255,0.07)'); G.ray.addColorStop(1, 'rgba(120,150,255,0)')
+ const cy = G.hz - G.trunkLen - G.L * 0.5
+ G.aura = ctx.createRadialGradient(G.treeX, cy, 0, G.treeX, cy, G.L * 1.35)
+ G.aura.addColorStop(0, 'rgba(150,175,255,0.10)'); G.aura.addColorStop(0.5, 'rgba(120,120,255,0.035)'); G.aura.addColorStop(1, 'rgba(80,80,200,0)')
+
+ // Thought dust in the sky.
+ const r = rng(7)
+ G.dust = Array.from({ length: Math.round((W * H) / 9000) }, () => ({ x: r() * W, y: r() * G.hz, s: 0.6 + r() * 1.1, a: 0.05 + r() * 0.16, v: 2 + r() * 6, ph: r() * TAU }))
+
+ layoutLake()
+ measureCaption()
+ if (S.view === 'lake') S.cam.y = S.cam.from = S.cam.to = G.lakeCam
+ }
+
+ function layoutLake() {
+ const margin = Math.max(28, G.gutter)
+ const total = G.W - margin * 2
+ const sum = S.columns.reduce((s, c) => s + c.weight, 0) || 1
+ let x = margin
+ for (const c of S.columns) { c.x0 = x; c.w = (total * c.weight) / sum; c.x1 = x + c.w; c.cx = x + c.w / 2; x = c.x1 }
+ G.ages = S.orbs.map((o) => o.ageDays).sort((a, b) => a - b)
+ for (const o of S.orbs) {
+ const c = o.col, pad = Math.min(16, c.w * 0.22)
+ o.depthF = depthOf(o.ageDays)
+ o.bx = c.x0 + pad + o.jx * Math.max(1, c.w - pad * 2)
+ o.by0 = G.lakeTop + o.depthF * G.depth
+ o.by = o.by0
+ }
+ const orbs = S.orbs
+ for (let it = 0; it < 70; it++) {
+ for (let i = 0; i < orbs.length; i++) for (let j = i + 1; j < orbs.length; j++) {
+ const a = orbs[i], b = orbs[j]
+ let dx = b.bx - a.bx, dy = b.by - a.by
+ const min = a.r + b.r + 16
+ const d2 = dx * dx + dy * dy
+ if (d2 >= min * min) continue
+ let d = Math.sqrt(d2)
+ if (d < 0.01) { dx = h01(a.m.id + b.m.id) - 0.5; dy = 0.3; d = Math.hypot(dx, dy) }
+ const push = (min - d) / 2, ux = dx / d, uy = dy / d
+ a.bx -= ux * push; a.by -= uy * push * 0.7; b.bx += ux * push; b.by += uy * push * 0.7
+ }
+ for (const o of orbs) { const c = o.col; o.bx = clamp(o.bx, c.x0 + 5, c.x1 - 5); o.by = clamp(o.by, o.by0 - 30, o.by0 + 30) }
+ }
+ for (const o of orbs) { o.vivid = 1 - o.depthF; o.x = o.bx; o.y = o.by; const dx = o.bx - G.treeX, dy = o.by - G.hz; o.delay = clamp(Math.hypot(dx, dy) / Math.hypot(G.W, G.depth), 0, 1) * 0.9 }
+
+ // The mist: each message a mote over the water, gathered by project, or by conversation when the folder is unknown.
+ const M = S.motes
+ const r = rng(11)
+ for (let i = 0; i < M.n; i++) {
+ const c = M.col[i]
+ let cx, sp
+ if (c) { cx = c.cx; sp = Math.max(14, c.w * 0.26) } else { cx = margin + h01(S.asks[i].sessionId) * total; sp = 22 + h01(S.asks[i].sessionId + 'w') * 26 }
+ M.bx[i] = clamp(cx + gauss(r) * sp, 4, G.W - 4)
+ const up = -Math.log(Math.max(1e-4, r())) * 11
+ M.by[i] = G.hz - up + (r() < 0.22 ? r() * 12 : 0) - 1
+ }
+ }
+
+ // Depth is time: newest at the surface. Spread by rank so a burst of recent notes does not pile up,
+ // blended with the real scale so a month still looks like a month.
+ function depthOf(days) {
+ const a = G.ages || [], n = a.length
+ let p = 0
+ if (n > 1) {
+ if (days >= a[n - 1]) p = 1
+ else if (days > a[0]) {
+ let i = 0
+ while (i < n - 2 && a[i + 1] <= days) i++
+ p = (i + (days - a[i]) / ((a[i + 1] - a[i]) || 1)) / (n - 1)
+ }
+ }
+ return clamp(0.55 * p + 0.45 * Math.sqrt(clamp(days / G.maxAge, 0, 1)), 0, 1)
+ }
+
+ // Greedy label placement: skip a label that would overlap one already placed.
+ const placed = []
+ function claim(x, y, w, h) {
+ for (const r of placed) if (x < r[0] + r[2] && x + w > r[0] && y < r[1] + r[3] && y + h > r[1]) return false
+ placed.push([x, y, w, h])
+ return true
+ }
+
+ function measureCaption() {
+ const t = capText.getBoundingClientRect(), r = root.getBoundingClientRect()
+ S.capRect = t.width ? { left: t.left - r.left, right: t.right - r.left, top: t.top - r.top, height: t.height } : null
+ }
+
+ // ── the structure, per frame ────────────────────────────────────────────────────────────────────
+
+ function bez(f, v, out) {
+ const u = 1 - v, a = u * u * u, b = 3 * u * u * v, c = 3 * u * v * v, d = v * v * v
+ out[0] = a * f.p0[0] + b * f.p1[0] + c * f.p2[0] + d * f.p3[0]
+ out[1] = a * f.p0[1] + b * f.p1[1] + c * f.p2[1] + d * f.p3[1]
+ const da = -3 * u * u, db = 3 * u * u - 6 * u * v, dc = 6 * u * v - 3 * v * v, dd = 3 * v * v
+ const tx = da * f.p0[0] + db * f.p1[0] + dc * f.p2[0] + dd * f.p3[0], ty = da * f.p0[1] + db * f.p1[1] + dc * f.p2[1] + dd * f.p3[1]
+ const len = Math.hypot(tx, ty) || 1
+ out[2] = tx / len; out[3] = ty / len
+ }
+
+ function frondsFrame(t) {
+ const breathe = reduce ? 0 : Math.sin(t * 0.55)
+ const L = G.L * (1 + 0.014 * breathe)
+ const fx = G.treeX + (reduce ? 0 : Math.sin(t * 0.37) * 2.2), fy = G.hz - G.trunkLen * (1 + 0.012 * breathe)
+ G.fork = [fx, fy]; G.Lnow = L
+ for (let k = 0; k < fronds.length; k++) {
+ const f = fronds[k]
+ const a = f.a + (reduce ? 0 : Math.sin(t * 0.43 + k * 1.7) * 0.022)
+ const dx = Math.cos(a), dy = Math.sin(a)
+ f.p0[0] = fx; f.p0[1] = fy
+ f.p1[0] = fx + dx * L * 0.1; f.p1[1] = fy - L * 0.36
+ f.p2[0] = fx + dx * L * 0.72; f.p2[1] = fy + dy * L * 0.72 - L * 0.14
+ f.p3[0] = fx + dx * L; f.p3[1] = fy + dy * L
+ bez(f, 1, tmp); f.T[0] = tmp[2]; f.T[1] = tmp[3]
+ }
+ }
+
+ function strandFrame(b, t) {
+ const f = fronds[b.sec.k], pts = b.pts, L = G.Lnow
+ let n = 0
+ const ph = b.phase, R0 = G.trunkR
+ // The trunk: every strand braided together, flared where it meets the water.
+ const lean = G.W * 0.004
+ for (let i = 0; i < NA; i++) {
+ const u = i / (NA - 1)
+ const cx = lerp(G.treeX, f.p0[0], u) + Math.sin(u * Math.PI) * lean
+ const cy = lerp(G.hz, f.p0[1], u)
+ const r = R0 * (0.62 + 0.38 * (1 - u) + 0.9 * Math.pow(1 - u, 4))
+ pts[n++] = cx + r * Math.sin(ph + u * TWIST + t * 0.15); pts[n++] = cy
+ }
+ // Along its frond until it leaves.
+ const nb = Math.max(3, Math.round(28 * b.v))
+ const rf = R0 * 0.62
+ for (let i = 1; i <= nb; i++) {
+ const v = (b.v * i) / nb
+ bez(f, v, tmp)
+ const off = rf * (1 - 0.6 * v) * Math.sin(ph + TWIST + v * TWIST2 + t * 0.15)
+ pts[n++] = tmp[0] - tmp[3] * off; pts[n++] = tmp[1] + tmp[2] * off
+ }
+ // Out to its bead.
+ bez(f, b.v, tmp)
+ const Tx = tmp[2], Ty = tmp[3]
+ const Ux = -Ty * f.side, Uy = Tx * f.side
+ const qx = pts[n - 2], qy = pts[n - 1]
+ let tipx, tipy, cx, cy
+ if (b.j === 0) {
+ tipx = tmp[0] + Tx * L * 0.12; tipy = tmp[1] + Ty * L * 0.12
+ cx = qx + Tx * L * 0.06; cy = qy + Ty * L * 0.06
+ } else {
+ const side = b.j % 2 ? 1 : -1
+ const reach = L * (0.12 + 0.02 * (b.j % 3))
+ tipx = tmp[0] + Ux * side * reach + Tx * L * 0.05; tipy = tmp[1] + Uy * side * reach + Ty * L * 0.05
+ cx = qx + Tx * L * 0.07; cy = qy + Ty * L * 0.07
+ }
+ for (let i = 1; i <= NC; i++) {
+ const s = i / NC, u = 1 - s
+ pts[n++] = u * u * qx + 2 * u * s * cx + s * s * tipx
+ pts[n++] = u * u * qy + 2 * u * s * cy + s * s * tipy
+ }
+ b.n = n / 2
+ b.fork = NA - 1
+ // Arc length.
+ const cum = b.cum
+ cum[0] = 0
+ for (let i = 1; i < b.n; i++) cum[i] = cum[i - 1] + Math.hypot(pts[2 * i] - pts[2 * i - 2], pts[2 * i + 1] - pts[2 * i - 1])
+ b.len = cum[b.n - 1] || 1
+ // A plucked strand rings between the fork and its bead.
+ const since = t - b.pluckT
+ if (b.pluckA > 0 && since < 4 && !reduce) {
+ const A = b.pluckA * Math.exp(-since / 0.95)
+ if (A > 0.05) {
+ const c0 = cum[b.fork], span = b.len - c0 || 1
+ const w = TAU * 6.2 * since
+ for (let i = 1; i < b.n - 1; i++) {
+ let s, amp
+ if (i <= b.fork) { s = cum[i] / (c0 || 1); amp = A * 0.12 * Math.sin(Math.PI * s) }
+ else { s = (cum[i] - c0) / span; amp = A * (Math.sin(Math.PI * s) * Math.sin(w) + 0.3 * Math.sin(TAU * s) * Math.sin(2.01 * w + 1)) }
+ const dx = pts[2 * i + 2] - pts[2 * i - 2], dy = pts[2 * i + 3] - pts[2 * i - 1]
+ const dl = Math.hypot(dx, dy) || 1
+ pts[2 * i] += (-dy / dl) * amp; pts[2 * i + 1] += (dx / dl) * amp
+ }
+ }
+ }
+ b.tip = [pts[2 * b.n - 2], pts[2 * b.n - 1]]
+ b.root = [pts[0], pts[1]]
+ }
+
+ function pointAt(pts, cum, n, s, out) {
+ const target = clamp(s, 0, 1) * cum[n - 1]
+ let lo = 0, hi = n - 1
+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (cum[mid] < target) lo = mid; else hi = mid }
+ const seg = cum[hi] - cum[lo] || 1, k = (target - cum[lo]) / seg
+ out[0] = lerp(pts[2 * lo], pts[2 * hi], k); out[1] = lerp(pts[2 * lo + 1], pts[2 * hi + 1], k)
+ return hi
+ }
+
+ // A smooth stroke through pts from arc length a to b (0..1 of the strand).
+ function tracePath(pts, cum, n, a = 0, z = 1) {
+ const total = cum[n - 1]
+ const A = a * total, Z = z * total
+ ctx.beginPath()
+ let started = false, px = 0, py = 0
+ for (let i = 0; i < n; i++) {
+ const c = cum[i]
+ if (c < A) continue
+ if (!started) {
+ if (i > 0) { const k = (A - cum[i - 1]) / ((c - cum[i - 1]) || 1); px = lerp(pts[2 * i - 2], pts[2 * i], k); py = lerp(pts[2 * i - 1], pts[2 * i + 1], k) } else { px = pts[0]; py = pts[1] }
+ ctx.moveTo(px, py); started = true
+ }
+ if (c > Z) {
+ const k = (Z - cum[i - 1]) / ((c - cum[i - 1]) || 1)
+ ctx.lineTo(lerp(pts[2 * i - 2], pts[2 * i], k), lerp(pts[2 * i - 1], pts[2 * i + 1], k))
+ return
+ }
+ const x = pts[2 * i], y = pts[2 * i + 1]
+ ctx.quadraticCurveTo(px, py, (px + x) / 2, (py + y) / 2)
+ px = x; py = y
+ }
+ if (started) ctx.lineTo(px, py)
+ }
+
+ // Threads from an orb up to where its belief meets the water.
+ function rootFrame(root, b) {
+ const o = root.o, pts = root.pts, R = b.root
+ const x0 = o.x, y0 = o.y, x3 = R[0], y3 = R[1]
+ const depth = Math.max(10, y0 - G.hz)
+ const x1 = x0, y1 = y0 - depth * 0.6
+ const x2 = lerp(x3, x0, 0.22), y2 = G.hz + depth * 0.2 + 10
+ let n = 0
+ for (let i = 0; i < ROOTN; i++) {
+ const s = i / (ROOTN - 1), u = 1 - s
+ pts[n++] = u * u * u * x0 + 3 * u * u * s * x1 + 3 * u * s * s * x2 + s * s * s * x3
+ pts[n++] = u * u * u * y0 + 3 * u * u * s * y1 + 3 * u * s * s * y2 + s * s * s * y3
+ }
+ const cum = root.cum
+ cum[0] = 0
+ for (let i = 1; i < ROOTN; i++) cum[i] = cum[i - 1] + Math.hypot(pts[2 * i] - pts[2 * i - 2], pts[2 * i + 1] - pts[2 * i - 1])
+ }
+
+ const focusedBelief = () => S.sections[S.sec]?.beliefs[S.bel] ?? null
+ const focusedOrb = () => (S.orb >= 0 ? S.orbs[S.orb] ?? null : null)
+
+ // ── update ──────────────────────────────────────────────────────────────────────────────────────
+
+ function update(dt) {
+ const t = S.time
+ const c = S.cam
+ const p = clamp((t - c.t0) / c.dur, 0, 1)
+ c.y = lerp(c.from, c.to, easeInOut(p))
+
+ const A = S.arrival.done ? 99 : S.arrival.t
+ const R = S.recall
+ const k = 1 - Math.exp(-dt * 5)
+ const sq = lerp(G.sqSelf, 1, clamp(c.y / G.lakeCam, 0, 1))
+ G.sq = sq
+ for (const o of S.orbs) {
+ o.appear = smooth((A - 0.35 - o.delay) / 0.7)
+ const ys = G.hz + (o.by - G.hz) * sq
+ let target = 0
+ if (R && o.match >= 0) target = Math.max(0, ys - (G.hz + 24 + Math.min(o.match, 18) * 11))
+ if (S.panel && S.panel.o === o) target = Math.max(target, Math.min(40, ys - G.hz - 20))
+ o.lift = lerp(o.lift, target, reduce ? 1 : k * 0.8)
+ const bob = reduce ? 0 : Math.sin(t * 0.6 + o.ph) * (1 + 2 * o.fresh) * sq
+ o.x = o.bx + (reduce ? 0 : Math.sin(t * 0.21 + o.ph * 2) * 1.5)
+ o.y = ys - o.lift + bob
+ o.glow = Math.max(0, o.glow - dt * 0.9)
+ }
+ for (const b of S.beliefs) b.flash = Math.max(0, b.flash - dt * 0.8)
+
+ const M = S.motes
+ for (let i = 0; i < M.n; i++) {
+ const target = R && M.match[i] ? 26 + (M.ph[i] / TAU) * 34 : 0
+ M.lift[i] += (target - M.lift[i]) * (reduce ? 1 : k * 0.6)
+ }
+
+ // Flakes: old memories crumble at the edges.
+ if (!reduce && S.arrival.done) {
+ for (const o of S.orbs) {
+ if (o.loss <= 0 || S.flakes.length > 240) continue
+ if (Math.random() < o.loss * dt * 2.2) {
+ const a = Math.random() * TAU
+ S.flakes.push({ x: o.x + Math.cos(a) * o.r * 1.1, y: o.y + Math.sin(a) * o.r * 1.1, vx: Math.cos(a) * (3 + Math.random() * 5), vy: -3 - Math.random() * 7, life: 0, max: 2 + Math.random() * 2.5, rgb: o.rgb, s: 0.8 + Math.random() * 0.9 })
+ }
+ }
+ }
+ for (let i = S.flakes.length - 1; i >= 0; i--) {
+ const f = S.flakes[i]
+ f.life += dt; f.x += f.vx * dt; f.y += f.vy * dt; f.vx *= 0.985
+ if (f.life > f.max) S.flakes.splice(i, 1)
+ }
+ for (let i = S.ripples.length - 1; i >= 0; i--) if (t - S.ripples[i].t0 > 2.2) S.ripples.splice(i, 1)
+
+ // Pulses: light running down a plucked strand to its memories, or up from a memory to its beliefs.
+ for (let i = S.pulses.length - 1; i >= 0; i--) {
+ const P = S.pulses[i], e = t - P.t0
+ if (P.kind === 'down') {
+ if (!P.hit && e > 0.75 + 0.55) { P.hit = true; for (const o of P.b.mems) o.glow = 1 }
+ if (e > 2.4) S.pulses.splice(i, 1)
+ } else {
+ // Follow the light: the camera rises with it to the belief it reaches.
+ if (!P.rose && e > 0.4) { P.rose = true; if (S.view === 'lake' && S.orb === P.o.i && !S.panel) rise(1.0) }
+ if (!P.hit && e > 0.55 + 0.75) {
+ P.hit = true
+ for (const b of P.o.beliefs) { b.flash = 1; b.pluckT = t; b.pluckA = 6 }
+ }
+ if (e > 2.4) S.pulses.splice(i, 1)
+ }
+ }
+ }
+
+ /** Nothing moves: with reduced motion the loop can sleep until something happens. */
+ function still() {
+ if (!reduce || !S.arrival.done || S.pulses.length || S.ripples.length || S.flakes.length) return false
+ if (S.time - S.cam.t0 < S.cam.dur) return false
+ for (const o of S.orbs) if (o.glow > 0) return false
+ for (const b of S.beliefs) if (b.flash > 0) return false
+ return true
+ }
+
+ // ── draw ────────────────────────────────────────────────────────────────────────────────────────
+
+ function draw() {
+ const { W, H } = G
+ const t = S.time
+ const A = S.arrival.done ? 99 : S.arrival.t
+ const camY = S.cam.y
+ const lk = clamp(camY / G.lakeCam, 0, 1)
+ const fb = S.arrival.done ? focusedBelief() : null
+ const fo = focusedOrb()
+ const R = S.recall
+ const breath = reduce ? 0.5 : 0.5 + 0.5 * Math.sin(t * 0.55)
+
+ frondsFrame(reduce ? 0 : t)
+ for (const b of S.beliefs) strandFrame(b, reduce ? 0 : t)
+
+ ctx.setTransform(DPR, 0, 0, DPR, 0, -camY * DPR)
+ ctx.globalCompositeOperation = 'source-over'
+ ctx.globalAlpha = 1
+ // Sky.
+ ctx.fillStyle = G.sky
+ ctx.fillRect(0, camY - 2, W, G.hz - camY + 4)
+
+ ctx.globalCompositeOperation = 'lighter'
+ // Thought dust.
+ ctx.fillStyle = '#c8d4ff'
+ for (const d of G.dust) {
+ const y = reduce ? d.y : (d.y - t * d.v + G.hz * 10) % G.hz
+ if (y < camY - 4) continue
+ ctx.globalAlpha = d.a * (0.6 + 0.4 * Math.sin(t * 0.8 + d.ph)) * smooth(A / 1.5)
+ ctx.fillRect(d.x, y, d.s, d.s)
+ }
+ // Aura behind the crown, breathing.
+ const crownIn = smooth((A - 2.4) / 1.6) * (S.beliefs.length ? 1 : 0.45)
+ ctx.globalAlpha = (0.55 + 0.45 * breath) * crownIn
+ ctx.fillStyle = G.aura
+ ctx.fillRect(G.treeX - G.L * 1.4, G.hz - G.trunkLen - G.L * 1.9, G.L * 2.8, G.L * 2.8)
+
+ drawStructure(t, A, fb, R, breath)
+
+ // Copy the band above the water for the reflection, then the water itself. Reading the canvas back
+ // makes the browser draw everything so far at once (measured without a GPU at 1000×800: 7 ms for the
+ // reflection, 15 ms for the blurred bloom), so they take turns, each refreshed every third frame,
+ // which the eye does not see in a soft, rippling light. Reduced motion draws rarely: both, always.
+ const hzS = G.hz - camY
+ const RH = Math.min(hzS - 2, H * 0.42)
+ let reflOk = false
+ S.frameNo = (S.frameNo ?? 0) + 1
+ if (RH > 20) {
+ const sc = 0.5 * DPR
+ const rw = Math.max(1, Math.ceil(W * sc)), rh = Math.max(1, Math.ceil(RH * sc))
+ const fresh = refl.width !== rw || refl.height !== rh || S.reflAt !== Math.round(hzS)
+ if (fresh) { refl.width = rw; refl.height = rh; S.reflAt = Math.round(hzS) }
+ if (fresh || S.frameNo % 3 === 0 || reduce) {
+ rctx.globalCompositeOperation = 'copy'
+ rctx.drawImage(canvas, 0, Math.max(0, Math.round((hzS - RH) * DPR)), Math.round(W * DPR), Math.round(RH * DPR), 0, 0, rw, rh)
+ }
+ reflOk = true
+ }
+ ctx.globalCompositeOperation = 'source-over'
+ ctx.globalAlpha = 1
+ ctx.fillStyle = G.water
+ ctx.fillRect(0, G.hz, W, camY + H - G.hz + 2)
+ ctx.globalCompositeOperation = 'lighter'
+ if (reflOk) drawReflection(t, lk, hzS, RH, A)
+ ctx.setTransform(DPR, 0, 0, DPR, 0, -camY * DPR)
+
+ drawWater(t, A, lk)
+ drawRoots(t, A, fb, fo, R)
+ drawOrbs(t, A, fb, fo, R, lk)
+ drawMist(t, A, fb, R)
+ drawPulses(t)
+ drawLakeLabels(t, lk, fo, R)
+ drawLeader(t, A, fb, lk)
+
+ // Bloom: a blurred, smaller copy of the light, added back.
+ ctx.setTransform(DPR, 0, 0, DPR, 0, 0)
+ if (bloomOk) {
+ const bw = Math.ceil(W / 3), bh = Math.ceil(H / 3)
+ const fresh = bloom.width !== bw || bloom.height !== bh
+ if (fresh) { bloom.width = bw; bloom.height = bh }
+ if (fresh || S.frameNo % 3 === 1 || reduce) {
+ bctx.globalCompositeOperation = 'source-over'
+ bctx.filter = 'none'
+ bctx.clearRect(0, 0, bw, bh)
+ bctx.filter = 'blur(4px)'
+ bctx.drawImage(canvas, 0, 0, bw, bh)
+ bctx.filter = 'none'
+ }
+ ctx.globalCompositeOperation = 'lighter'
+ ctx.globalAlpha = 0.75
+ ctx.drawImage(bloom, 0, 0, W, H)
+ }
+ ctx.globalCompositeOperation = 'source-over'
+ ctx.globalAlpha = 1
+ positionOrbLabel()
+ }
+
+ function strandColor(b, fb, R) {
+ if (fb === b && !R) return mix(b.sec.rgb, GOLD, 0.65)
+ if (R && R.beliefs.has(b)) return mix(b.sec.rgb, GOLD, 0.5)
+ return b.sec.rgb
+ }
+
+ function strandAlpha(b, fb, R, t) {
+ let a = 0.2 + 0.06 * Math.min(5, b.weight)
+ if (R) {
+ if (R.beliefs.has(b)) a = 0.75 + 0.25 * Math.sin(t * 4 + b.idx)
+ else a *= 0.35
+ } else if (S.view === 'lake' && focusedOrb()) {
+ a *= focusedOrb().beliefs.includes(b) ? 2.6 : 0.6
+ } else if (fb) {
+ if (b === fb) a = 1
+ else a *= b.sec === fb.sec ? 0.85 : 0.6
+ }
+ return clamp(a + b.flash * 0.6, 0, 1)
+ }
+
+ function drawStructure(t, A, fb, R, breath) {
+ S.labelHits = []
+ if (!S.beliefs.length) { drawSeed(t, A, breath); return }
+ // A soft core of light up the trunk.
+ const grow0 = smooth((A - 1.7) / 1.4)
+ ctx.globalAlpha = 0.05 * grow0 * (0.7 + 0.3 * breath)
+ ctx.strokeStyle = '#dfe6ff'
+ ctx.lineWidth = G.trunkR * 2 + 18
+ ctx.lineCap = 'round'
+ ctx.beginPath(); ctx.moveTo(G.treeX, G.hz); ctx.quadraticCurveTo(G.treeX + G.W * 0.004, G.hz - G.trunkLen * 0.5, G.fork[0], G.fork[1]); ctx.stroke()
+
+ for (const b of S.beliefs) {
+ const grow = S.arrival.done ? 1 : easeOut((A - 1.7 - b.idx * 0.05) / 1.5)
+ b.grow = grow
+ if (grow <= 0) continue
+ const rgb = strandColor(b, fb, R)
+ const a = strandAlpha(b, fb, R, t) * (0.85 + 0.15 * breath)
+ const lit = b === fb && !R
+ tracePath(b.pts, b.cum, b.n, 0, grow)
+ ctx.strokeStyle = css(rgb, 1)
+ ctx.globalAlpha = a * 0.09; ctx.lineWidth = lit ? 10 : 7; ctx.stroke()
+ ctx.globalAlpha = a * 0.26; ctx.lineWidth = lit ? 3.2 : 2.2; ctx.stroke()
+ ctx.globalAlpha = Math.min(1, a * (lit ? 1 : 0.85)); ctx.lineWidth = lit ? 1.4 : 0.9; ctx.stroke()
+ // While it grows, a needle of light weaves it.
+ if (grow < 1) {
+ pointAt(b.pts, b.cum, b.n, grow, tmp)
+ ctx.globalAlpha = 0.9
+ const sp = sprite(mix(rgb, [255, 255, 255], 0.4), false)
+ ctx.drawImage(sp, tmp[0] - 9, tmp[1] - 9, 18, 18)
+ }
+ }
+
+ // Sparks climbing every strand: memories sending up the belief.
+ if (S.arrival.done && !reduce) {
+ for (const b of S.beliefs) {
+ const count = 2 + Math.min(5, Math.round(b.weight))
+ const sp = sprite(strandColor(b, fb, R), false)
+ const a0 = strandAlpha(b, fb, R, t)
+ for (let c = 0; c < count; c++) {
+ const s = frac(t * (0.05 + 0.012 * (c % 3)) + c / count + b.phase)
+ pointAt(b.pts, b.cum, b.n, s, tmp)
+ ctx.globalAlpha = Math.min(1, a0 * 0.9) * Math.sin(Math.PI * s)
+ const z = b === fb ? 9 : 6
+ ctx.drawImage(sp, tmp[0] - z / 2, tmp[1] - z / 2, z, z)
+ }
+ }
+ }
+
+ // Beads: where each belief is held.
+ for (const b of S.beliefs) {
+ const start = 1.7 + b.idx * 0.05 + 1.5
+ const open = S.arrival.done ? 1 : smooth((A - start + 0.25) / 0.4)
+ if (open <= 0) continue
+ const pop = S.arrival.done ? 0 : Math.max(0, Math.sin(Math.PI * clamp((A - start + 0.25) / 0.5, 0, 1))) * 0.8
+ const lit = b === fb && !R
+ const pulse = R && R.beliefs.has(b) ? 0.5 + 0.5 * Math.sin(t * 4 + b.idx) : 0
+ const rgb = strandColor(b, fb, R)
+ const base = 7 + Math.min(8, b.weight * 1.9)
+ const z = (base * (lit ? 1.7 : 1) + pulse * 6 + b.flash * 14 + pop * 14) * open
+ ctx.globalAlpha = clamp(strandAlpha(b, fb, R, t) + 0.25, 0, 1)
+ ctx.drawImage(sprite(rgb, true), b.tip[0] - z, b.tip[1] - z, z * 2, z * 2)
+ if (lit) {
+ // A lens flare across the focused bead.
+ const fl = 0.35 + 0.15 * Math.sin(t * 2.1)
+ const g = ctx.createLinearGradient(b.tip[0] - 90, 0, b.tip[0] + 90, 0)
+ g.addColorStop(0, 'rgba(255,230,180,0)'); g.addColorStop(0.5, `rgba(255,236,200,${fl})`); g.addColorStop(1, 'rgba(255,230,180,0)')
+ ctx.globalAlpha = 1; ctx.fillStyle = g
+ ctx.fillRect(b.tip[0] - 90, b.tip[1] - 0.6, 180, 1.2)
+ ctx.strokeStyle = css(GOLD, 0.5); ctx.lineWidth = 1
+ ctx.beginPath(); ctx.arc(b.tip[0], b.tip[1], 13 + 2 * Math.sin(t * 2.4), 0, TAU); ctx.stroke()
+ }
+ }
+
+ // Section names, beyond each frond. Each is also where a click goes to that section.
+ const labelsIn = S.arrival.done ? 1 : smooth((A - 3.4) / 0.7)
+ if (labelsIn > 0) {
+ ctx.font = `500 10.5px ${MONO}`
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '1.6px'
+ for (const sec of S.sections) {
+ const f = fronds[sec.k]
+ const b0 = sec.beliefs[0]
+ if (!b0 || !b0.tip) continue
+ const ax = b0.tip[0] + f.T[0] * 24, ay = b0.tip[1] + f.T[1] * 22
+ const isF = fb && fb.sec === sec
+ ctx.globalAlpha = labelsIn * (isF ? 0.95 : 0.5)
+ ctx.fillStyle = css(isF ? mix(sec.rgb, [255, 255, 255], 0.35) : sec.rgb)
+ ctx.textAlign = f.T[0] < -0.35 ? 'right' : f.T[0] > 0.35 ? 'left' : 'center'
+ const lines = wrapLabel(sec.name.toUpperCase(), 14)
+ const dy = f.T[1] < -0.5 ? -(lines.length - 1) * 13 - 2 : f.T[1] > 0.3 ? 10 : -((lines.length - 1) * 13) / 2 + 4
+ const wmax = Math.max(...lines.map((line) => ctx.measureText(line).width))
+ const left = ctx.textAlign === 'right' ? ax - wmax : ctx.textAlign === 'center' ? ax - wmax / 2 : ax
+ const shift = left < 8 ? 8 - left : left + wmax > G.W - 10 ? G.W - 10 - (left + wmax) : 0
+ // Inside the stage, which is shorter than a window: the name of a frond that points up stays in view.
+ const lift = Math.max(0, 14 - (ay + dy - 10))
+ lines.forEach((line, i) => ctx.fillText(line, ax + shift, ay + dy + lift + i * 13))
+ S.labelHits.push({ sec, x: left + shift, y: ay + dy + lift - 10, w: wmax, h: lines.length * 13 + 2 })
+ }
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '0px'
+ ctx.textAlign = 'left'
+ }
+ }
+
+ /** No About You yet: a seed of light at the water where it will grow, your words rising into it. */
+ function drawSeed(t, A, breath) {
+ if (!S.ready || (!S.orbs.length && !S.asks.length)) return
+ const a = smooth((A - 1.2) / 1.2) * (0.65 + 0.35 * breath)
+ const top = G.hz - G.trunkLen * 0.9, x = G.treeX
+ // A soft column of light, and a thread through it.
+ ctx.globalAlpha = 0.16 * a
+ ctx.drawImage(sprite(YOU, false), x - 16, top, 32, (G.hz - top) * 1.25)
+ const g = ctx.createLinearGradient(0, G.hz, 0, top)
+ g.addColorStop(0, 'rgba(255,226,170,0.9)'); g.addColorStop(0.4, 'rgba(200,214,255,0.3)'); g.addColorStop(1, 'rgba(200,214,255,0)')
+ ctx.globalAlpha = a
+ ctx.fillStyle = g
+ ctx.fillRect(x - 0.6, top, 1.2, G.hz - top)
+ // The seed.
+ ctx.globalAlpha = 0.75 * a
+ const z = 20 + 6 * breath
+ ctx.drawImage(sprite(GOLD, false), x - z, G.hz - z, z * 2, z * 2)
+ if (reduce) return
+ const sp = sprite(mix(YOU, GOLD, 0.4), false)
+ for (let k = 0; k < 6; k++) {
+ const s = frac(t * 0.07 + k / 6)
+ ctx.globalAlpha = a * Math.sin(Math.PI * s) * 0.8
+ ctx.drawImage(sp, x - 4 + Math.sin(t * 0.9 + k * 1.7) * 4 * s, lerp(G.hz - 4, top, s) - 4, 8, 8)
+ }
+ }
+
+ function wrapLabel(text, max) {
+ if (text.length <= max) return [text]
+ const words = text.match(/\([^)]*\)|\S+/g) ?? [text]
+ const lines = ['']
+ for (const w of words) {
+ const cur = lines[lines.length - 1]
+ if (cur && (cur + ' ' + w).length > max && lines.length < 3) lines.push(w)
+ else lines[lines.length - 1] = cur ? cur + ' ' + w : w
+ }
+ return lines
+ }
+
+ function drawReflection(t, lk, hzS, RH, A) {
+ ctx.setTransform(DPR, 0, 0, DPR, 0, 0)
+ const sc = 0.5 * DPR
+ const squash = 0.6, total = RH * squash, step = 3
+ const rw = refl.width
+ const base = 0.3 * (1 - lk * 0.85) * smooth(A / 2)
+ for (let y = 0; y < total && hzS + y < G.H; y += step) {
+ const srcY = (RH - (y + step) / squash) * sc
+ if (srcY < 0) break
+ const srcH = Math.max(1, (step / squash) * sc)
+ const fade = 1 - y / total
+ ctx.globalAlpha = base * fade * fade
+ const dx = reduce ? 0 : Math.sin(y * 0.09 + t * 1.3) * (0.6 + y * 0.045) + Math.sin(y * 0.031 - t * 0.7) * 1.4
+ ctx.drawImage(refl, 0, srcY, rw, srcH, dx, hzS + y, G.W, step + 0.6)
+ }
+ }
+
+ function drawWater(t, A, lk) {
+ const W = G.W, hz = G.hz
+ // Light from above, falling through the water.
+ ctx.fillStyle = G.ray
+ for (let i = 0; i < 6; i++) {
+ const x = W * (0.08 + i * 0.17) + (reduce ? 0 : Math.sin(t * 0.07 + i * 2.1) * 40)
+ const w0 = 18 + i * 6, w1 = 120 + i * 18, len = G.depth * 0.95, slant = 70
+ const a = (0.55 + 0.45 * Math.sin(t * 0.21 + i * 1.3)) * (0.3 + 0.7 * lk) * smooth(A / 1.2)
+ for (const k of [0.45, 0.8, 1.2]) {
+ ctx.globalAlpha = a * 0.4
+ ctx.beginPath(); ctx.moveTo(x - w0 * k, hz); ctx.lineTo(x + w0 * k, hz); ctx.lineTo(x + w1 * k + slant, hz + len); ctx.lineTo(x - w1 * k + slant, hz + len); ctx.closePath(); ctx.fill()
+ }
+ }
+ // The surface, opening out from where the trunk meets it.
+ const open = S.arrival.done ? 1 : easeOut(A / 0.9)
+ const x0 = G.treeX - open * W, x1 = G.treeX + open * W
+ ctx.fillStyle = G.surf
+ ctx.globalAlpha = 0.85; ctx.fillRect(Math.max(0, x0), hz - 0.5, Math.min(W, x1) - Math.max(0, x0), 1)
+ ctx.globalAlpha = 0.16; ctx.fillRect(Math.max(0, x0), hz - 3, Math.min(W, x1) - Math.max(0, x0), 6)
+ // Glints.
+ ctx.fillStyle = '#e8eeff'
+ for (let i = 0; i < 26; i++) {
+ const x = (i * 97.3 + (reduce ? 0 : t * (6 + (i % 4) * 5))) % W
+ if (x < x0 || x > x1) continue
+ ctx.globalAlpha = 0.25 * Math.max(0, Math.sin(t * 1.7 + i * 2.3))
+ ctx.fillRect(x, hz - 0.5 + (i % 3), 6 + (i % 5) * 3, 0.8)
+ }
+ // Ripples from a dive.
+ for (const r of S.ripples) {
+ const e = (t - r.t0) / 2.2
+ for (let k = 0; k < 3; k++) {
+ const ek = e - k * 0.12
+ if (ek <= 0) continue
+ ctx.globalAlpha = 0.5 * (1 - ek) * (1 - k * 0.3)
+ ctx.strokeStyle = '#dfe8ff'; ctx.lineWidth = 1
+ ctx.beginPath(); ctx.ellipse(r.x, hz, 12 + ek * 340, 2 + ek * 30, 0, 0, TAU); ctx.stroke()
+ }
+ }
+ }
+
+ function drawRoots(t, A, fb, fo, R) {
+ const rootIn = S.arrival.done ? 1 : easeOut((A - 0.9) / 1.0)
+ if (rootIn <= 0) return
+ ctx.lineCap = 'round'
+ for (const b of S.beliefs) {
+ if (b.roots.length !== b.mems.length) b.roots = b.mems.map((o) => ({ o, pts: new Float32Array(ROOTN * 2), cum: new Float32Array(ROOTN) }))
+ for (const root of b.roots) {
+ rootFrame(root, b)
+ const o = root.o
+ let a = 0.09 + 0.05 * o.fresh, lit = false
+ if (R) { a = R.beliefs.has(b) || o.match >= 0 ? 0.32 + 0.2 * Math.sin(t * 4 + b.idx) : 0.03 }
+ else if (S.view === 'lake' && fo) { lit = fo === o; a = lit ? 0.75 : 0.05 }
+ else if (fb) { lit = fb === b; a = lit ? 0.7 : 0.06 }
+ if (lit) {
+ const sel = S.thread >= 0 && fb && fb.threads[S.thread]?.o === o
+ if (S.view === 'self' && S.thread >= 0 && !sel) a *= 0.55
+ }
+ a *= o.appear
+ tracePath(root.pts, root.cum, ROOTN, 0, rootIn)
+ ctx.strokeStyle = css(mix(o.rgb, [255, 255, 255], lit ? 0.25 : 0.1))
+ if (lit) { ctx.globalAlpha = a * 0.18; ctx.lineWidth = 5; ctx.stroke() }
+ ctx.globalAlpha = a; ctx.lineWidth = lit ? 1.2 : 0.8; ctx.stroke()
+ if (lit && !reduce) {
+ // Light climbing the thread.
+ const sp = sprite(o.rgb, false)
+ for (let c = 0; c < 3; c++) {
+ const s = frac(t * 0.35 + c / 3 + o.ph)
+ pointAt(root.pts, root.cum, ROOTN, s, tmp)
+ ctx.globalAlpha = 0.8 * Math.sin(Math.PI * s)
+ ctx.drawImage(sp, tmp[0] - 5, tmp[1] - 5, 10, 10)
+ }
+ }
+ }
+ }
+ }
+
+ function drawOrbs(t, A, fb, fo, R, lk) {
+ const sel = recallSelection()
+ for (const o of S.orbs) {
+ if (o.appear <= 0) continue
+ let a = (0.28 + 0.72 * Math.pow(o.vivid, 1.3)) * o.appear
+ let z = o.r * lerp(0.78, 1, lk) * (0.82 + 0.28 * o.vivid)
+ const heldByFocus = fb && !R && S.view === 'self' && fb.mems.includes(o)
+ if (R) a *= o.match >= 0 ? 1.25 : 0.2
+ else if (S.view === 'self' && fb) a *= heldByFocus ? 1.5 : 0.75
+ if (heldByFocus) z *= 1.25
+ if (fo === o && S.view === 'lake') { z *= 1.45; a = 1 }
+ if (sel && sel.o === o) { z *= 1.5; a = 1 }
+ z *= 1 + o.glow * 0.8
+ a = clamp(a + o.glow * 0.6, 0, 1)
+ const d = z * ORB_K
+ ctx.globalAlpha = a
+ ctx.drawImage(orbSprite(o.rgb), o.x - d / 2, o.y - d / 2, d, d)
+ // Core memories, which hold up a belief, wear a faint ring.
+ if (o.beliefs.length) {
+ ctx.globalAlpha = a * 0.35
+ ctx.strokeStyle = css(mix(o.rgb, [255, 255, 255], 0.4))
+ ctx.lineWidth = 0.8
+ ctx.beginPath(); ctx.arc(o.x, o.y, z * 1.75, 0, TAU); ctx.stroke()
+ }
+ // Old ones crack at the edge.
+ if (o.loss > 0.08) {
+ ctx.globalAlpha = a * 0.3
+ ctx.strokeStyle = css(o.rgb)
+ ctx.lineWidth = 0.7
+ ctx.setLineDash([1.5, 3 + o.loss * 8])
+ ctx.beginPath(); ctx.arc(o.x, o.y, z * 1.35, o.ph, o.ph + TAU); ctx.stroke()
+ ctx.setLineDash([])
+ }
+ if ((fo === o && S.view === 'lake') || (sel && sel.o === o)) {
+ ctx.globalAlpha = 0.7
+ ctx.strokeStyle = css(GOLD)
+ ctx.lineWidth = 1
+ ctx.beginPath(); ctx.arc(o.x, o.y, z * 2.3 + Math.sin(t * 3) * 1.5, 0, TAU); ctx.stroke()
+ }
+ }
+ // Flakes.
+ for (const f of S.flakes) {
+ ctx.globalAlpha = 0.5 * (1 - f.life / f.max)
+ ctx.fillStyle = css(f.rgb)
+ ctx.fillRect(f.x, f.y, f.s, f.s)
+ }
+ }
+
+ function drawMist(t, A, fb, R) {
+ const M = S.motes
+ if (!M || !M.n) return
+ const mistIn = S.arrival.done ? 1 : smooth((A - 0.3) / 1.3)
+ if (mistIn <= 0) return
+ // Faint banks of fog where a project's messages gather.
+ for (const c of S.columns) {
+ if (!c.asks) continue
+ const w = Math.max(40, c.w * 0.7), h = 14 + Math.log10(1 + c.asks) * 6
+ ctx.globalAlpha = 0.05 * mistIn * Math.min(1, 0.4 + Math.log10(1 + c.asks) / 3)
+ ctx.drawImage(sprite(YOU, false), c.cx - w, G.hz - h * 1.6, w * 2, h * 2.4)
+ }
+ const drift = !reduce
+ const levels = [0.16, 0.28, 0.4, 0.56]
+ ctx.fillStyle = css(YOU)
+ for (let lv = 0; lv < 4; lv++) {
+ ctx.globalAlpha = levels[lv] * mistIn * (R ? 0.45 : 1)
+ ctx.beginPath()
+ for (let i = 0; i < M.n; i++) {
+ if (M.bucket[i] !== lv || M.lift[i] > 4) continue
+ const ph = M.ph[i]
+ const x = M.bx[i] + (drift ? Math.sin(t * 0.13 + ph) * 4 : 0)
+ const y = M.by[i] + (drift ? Math.sin(t * 0.21 + ph * 1.7) * 2.5 : 0)
+ ctx.rect(x, y, 1.3, 1.3)
+ }
+ ctx.fill()
+ }
+ // Messages that answer a recall rise out of the mist.
+ if (R) {
+ const sp = sprite(GOLD, false)
+ const selM = recallSelection()
+ for (let i = 0; i < M.n; i++) {
+ if (M.lift[i] <= 4) continue
+ const x = M.bx[i] + (drift ? Math.sin(t * 0.13 + M.ph[i]) * 4 : 0), y = M.by[i] - M.lift[i]
+ const big = selM && selM.mote === i
+ const z = big ? 22 : 8
+ ctx.globalAlpha = big ? 1 : 0.55 + 0.25 * Math.sin(t * 3 + M.ph[i])
+ ctx.drawImage(sp, x - z / 2, y - z / 2, z, z)
+ }
+ // Conversations older than the messages loaded here rise from where they were said.
+ for (const e of S.extra) {
+ const age = t - e.t0
+ const y = e.y - (reduce ? 1 : Math.min(1, age / 1.2)) * e.rise
+ const big = selM && selM.extra === e
+ const z = big ? 22 : 8
+ ctx.globalAlpha = (reduce ? 1 : Math.min(1, age * 2)) * (big ? 1 : 0.6)
+ ctx.drawImage(sp, e.x - z / 2, y - z / 2, z, z)
+ }
+ }
+ // While the structure is woven, the person's words rise out of the mist into it.
+ if (!S.arrival.done && !reduce && A > 1.1 && A < 4.4) {
+ const sp = sprite(mix(YOU, GOLD, 0.25), false)
+ for (const b of S.beliefs) {
+ if (!b.root) continue
+ for (let k = 0; k < Math.min(10, b.motes.length); k++) {
+ const i = b.motes[k]
+ const q = clamp((A - 1.1 - (k * 0.13 + b.idx * 0.04)) / 1.3, 0, 1)
+ if (q <= 0 || q >= 1) continue
+ const e = easeInOut(q)
+ const x = lerp(M.bx[i], b.root[0], e), y = lerp(M.by[i], b.root[1], e) - Math.sin(q * Math.PI) * 22
+ ctx.globalAlpha = Math.sin(Math.PI * q) * 0.8
+ ctx.drawImage(sp, x - 4, y - 4, 8, 8)
+ }
+ }
+ }
+ // The focused belief's own words rise from the mist into it.
+ const b = fb && !R && S.view === 'self' && S.arrival.done ? fb : null
+ if (b && b.motes.length) {
+ const sp = sprite(mix(YOU, GOLD, 0.35), false)
+ const rx = b.root[0], ry = b.root[1]
+ const lit = S.thread >= 0 && (b.threads[S.thread]?.kind === 'asks' || b.threads[S.thread]?.kind === 'session')
+ for (let k = 0; k < b.motes.length; k++) {
+ const i = b.motes[k]
+ const x0 = M.bx[i], y0 = M.by[i]
+ // Where it rests, a little brighter.
+ ctx.globalAlpha = lit ? 0.9 : 0.6
+ ctx.drawImage(sp, x0 - 3, y0 - 3, 6, 6)
+ if (reduce) continue
+ const P = 3.6 + (k % 5) * 0.5
+ const q = frac((t + (M.ph[i] / TAU) * P) / P)
+ const e = easeInOut(q)
+ const x = lerp(x0, rx, e) + Math.sin(q * Math.PI) * (x0 - rx) * 0.15
+ const y = lerp(y0, ry, e) - Math.sin(q * Math.PI) * 26
+ ctx.globalAlpha = Math.sin(Math.PI * q) * (lit ? 1 : 0.7)
+ ctx.drawImage(sp, x - 4, y - 4, 8, 8)
+ }
+ }
+ }
+
+ function drawPulses(t) {
+ const sp = sprite(GOLD, false)
+ for (const P of S.pulses) {
+ const e = t - P.t0
+ if (P.kind === 'down') {
+ const b = P.b
+ if (e < 0.75) {
+ const s = 1 - easeInOut(e / 0.75)
+ pointAt(b.pts, b.cum, b.n, s, tmp)
+ ctx.globalAlpha = 1; ctx.drawImage(sp, tmp[0] - 14, tmp[1] - 14, 28, 28)
+ tracePath(b.pts, b.cum, b.n, s, Math.min(1, s + 0.14))
+ ctx.strokeStyle = css(GOLD); ctx.lineWidth = 2.2; ctx.globalAlpha = 0.8; ctx.stroke()
+ } else if (e < 1.3) {
+ const s = 1 - easeOut((e - 0.75) / 0.55)
+ for (const root of b.roots) {
+ pointAt(root.pts, root.cum, ROOTN, s, tmp)
+ ctx.globalAlpha = 1; ctx.drawImage(sp, tmp[0] - 11, tmp[1] - 11, 22, 22)
+ }
+ // And through the mist, to the words.
+ const M = S.motes
+ for (let k = 0; k < Math.min(24, b.motes.length); k++) {
+ const i = b.motes[k]
+ const x = lerp(M.bx[i], b.root[0], s), y = lerp(M.by[i], b.root[1], s)
+ ctx.globalAlpha = 0.7; ctx.drawImage(sp, x - 5, y - 5, 10, 10)
+ }
+ } else {
+ const k = 1 - (e - 1.3) / 1.1
+ for (const o of b.mems) { ctx.globalAlpha = Math.max(0, k); const z = 60 * (1.2 - k); ctx.drawImage(sprite(o.rgb, false), o.x - z / 2, o.y - z / 2, z, z) }
+ }
+ } else {
+ const o = P.o
+ if (e < 0.55) {
+ const s = easeInOut(e / 0.55)
+ for (const b of o.beliefs) {
+ const root = b.roots.find((r) => r.o === o)
+ if (!root) continue
+ pointAt(root.pts, root.cum, ROOTN, s, tmp)
+ ctx.globalAlpha = 1; ctx.drawImage(sp, tmp[0] - 12, tmp[1] - 12, 24, 24)
+ }
+ } else if (e < 1.3) {
+ const s = easeInOut((e - 0.55) / 0.75)
+ for (const b of o.beliefs) {
+ pointAt(b.pts, b.cum, b.n, s, tmp)
+ ctx.globalAlpha = 1; ctx.drawImage(sp, tmp[0] - 14, tmp[1] - 14, 28, 28)
+ }
+ }
+ }
+ }
+ }
+
+ // Text over light needs a dark edge to stay legible.
+ function outlined(text, x, y) {
+ const op = ctx.globalCompositeOperation
+ ctx.globalCompositeOperation = 'source-over'
+ ctx.strokeStyle = 'rgba(3,4,10,0.85)'; ctx.lineWidth = 3.2; ctx.lineJoin = 'round'
+ ctx.strokeText(text, x, y)
+ ctx.fillText(text, x, y)
+ ctx.globalCompositeOperation = op
+ }
+
+ function drawLakeLabels(t, lk, fo, R) {
+ const sel = recallSelection()
+ ctx.textAlign = 'left'
+ placed.length = 0
+ // In the lake: the names of the memories around you; old ones are missing letters.
+ if (lk > 0.02 && !R) {
+ ctx.font = `10.5px ${MONO}`
+ if (fo && G.olRect) placed.push([G.olRect[0] - 8, G.olRect[1] + S.cam.y - 6, G.olRect[2] + 16, G.olRect[3] + 12])
+ if (fo) placed.push([fo.x - fo.r * 2.5, fo.y - fo.r * 2.5, fo.r * 5, fo.r * 5])
+ const near = S.orbs.filter((o) => o !== fo && o.appear > 0.2).map((o) => [fo ? Math.hypot(o.x - fo.x, (o.y - fo.y) * 1.3) : 0, o]).sort((a, b) => a[0] - b[0])
+ let shown = 0
+ for (const [d, o] of near) {
+ const fall = fo ? clamp(1 - (d - 80) / 170, 0, 1) : 0.6
+ if (fall <= 0 || shown >= 7) break
+ const x = o.x + o.r * 1.6 + 6, y = o.y + 3.5
+ const w = o.label.length * 6.4
+ if (!claim(x - 2, y - 10, w + 4, 14)) continue
+ ctx.globalAlpha = lk * (0.3 + 0.45 * o.vivid) * fall * o.appear
+ ctx.fillStyle = css(mix(o.rgb, [255, 255, 255], 0.55))
+ outlined(o.label, x, y)
+ shown++
+ }
+ // Columns and depth: place and time.
+ ctx.font = `500 10px ${MONO}`
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '1.4px'
+ ctx.textAlign = 'center'
+ // Above the keys at the foot of the pane, however short it is; a column too narrow for a name has none.
+ const y = Math.min(G.hz + (G.lakeTop + G.depth + 36 - G.hz) * G.sq, S.cam.y + G.H - 50)
+ for (const c of S.columns) {
+ if (!c.orbs.length || c.w < 34) continue
+ ctx.globalAlpha = lk * 0.42
+ ctx.fillStyle = '#8f9ab0'
+ ctx.fillText(short(c.name, Math.max(3, Math.floor((c.w - 6) / 8))).toUpperCase(), c.cx, y)
+ ctx.globalAlpha = lk * 0.25
+ ctx.fillText(String(c.orbs.length), c.cx, y + 14)
+ }
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '0px'
+ ctx.textAlign = 'right'
+ ctx.font = `10px ${MONO}`
+ for (const [d, label] of [[0, 'today'], [7, '1 week'], [30, '1 month'], [90, '3 months'], [180, '6 months'], [365, '1 year'], [730, '2 years']]) {
+ if (d > G.maxAge * 1.02) break
+ const yy = G.hz + (G.lakeTop + depthOf(d) * G.depth - G.hz) * G.sq
+ ctx.globalAlpha = lk * 0.34
+ ctx.fillStyle = '#7d889e'
+ ctx.fillText(label, G.W - 12, yy + 3)
+ ctx.fillRect(G.W - 8, yy, 5, 0.8)
+ }
+ ctx.textAlign = 'left'
+ }
+ // During recall: what rose, by name.
+ if (R) {
+ ctx.font = `11px ${MONO}`
+ const risen = S.orbs.filter((o) => o.match >= 0 && o.match < 14).sort((a, b) => (sel && sel.o === a ? -1 : sel && sel.o === b ? 1 : a.match - b.match))
+ for (const o of risen) {
+ const isSel = sel && sel.o === o
+ const text = short(o.m.title, 34)
+ const x = o.x + o.r * 2 + 6, y = o.y + 4
+ if (!claim(x - 2, y - 11, text.length * 6.7 + 4, 15) && !isSel) continue
+ ctx.globalAlpha = isSel ? 1 : 0.75
+ ctx.fillStyle = isSel ? css(GOLD) : css(mix(o.rgb, [255, 255, 255], 0.65))
+ outlined(text, x, y)
+ }
+ }
+ }
+
+ // A faint line from the words to the bead that holds them.
+ function drawLeader(t, A, fb, lk) {
+ if (!fb || S.recall || S.view !== 'self' || !S.arrival.done || !S.capRect || !fb.tip) return
+ const a = (1 - lk) * 0.3
+ if (a <= 0.01) return
+ const r = S.capRect
+ const x0 = Math.min(r.right + 14, G.capRight + 8), y0 = r.top + Math.min(r.height / 2, 40) + S.cam.y
+ const x1 = fb.tip[0], y1 = fb.tip[1]
+ const g = ctx.createLinearGradient(x0, y0, x1, y1)
+ g.addColorStop(0, 'rgba(255,226,170,0)'); g.addColorStop(0.6, 'rgba(255,226,170,0.5)'); g.addColorStop(1, 'rgba(255,226,170,0.9)')
+ ctx.globalAlpha = a
+ ctx.strokeStyle = g
+ ctx.lineWidth = 0.8
+ ctx.setLineDash([2, 5])
+ ctx.lineDashOffset = reduce ? 0 : -t * 8
+ ctx.beginPath(); ctx.moveTo(x0, y0); ctx.bezierCurveTo(lerp(x0, x1, 0.5), y0, lerp(x0, x1, 0.5), y1, x1 - 14, y1); ctx.stroke()
+ ctx.setLineDash([])
+ }
+
+ // ── the words: caption, orb label, recall list, panel, hint ─────────────────────────────────────
+
+ function renderCaption(animate) {
+ const b = focusedBelief()
+ capNote.textContent = ''
+ caption.classList.toggle('empty', !b)
+ if (!b) {
+ capCount.textContent = ''
+ capWhy.textContent = ''
+ capWhyLabel.textContent = ''
+ if (!S.orbs.length && !S.asks.length) {
+ // Nothing at all yet: say so, calmly, and how it fills.
+ capSection.textContent = 'Memories'
+ capText.textContent = 'Nothing here yet.'
+ capNote.append(el('p', null, 'Your agents have not saved any memories on this computer. Claude Code saves them as you work; Codex and Grok Build once memory is turned on; Hermes and OpenClaw keep a profile.'),
+ el('p', null, 'They appear here as soon as any agent writes one.'))
+ } else {
+ capSection.textContent = 'About you'
+ capText.textContent = 'About You is not built yet.'
+ const ask = el('div', 'ask')
+ ask.append(el('div', null, 'Ask the agent on the right:'), el('div', 'say', 'build my About You'))
+ const facts = []
+ if (S.asks.length) facts.push(`${S.asks.length.toLocaleString('en-US')} of your messages`)
+ const yours = S.orbs.filter((o) => o.m.kind === 'you').length
+ if (yours) facts.push(`${yours} ${yours === 1 ? 'note' : 'notes'} your agents saved about you`)
+ capNote.append(ask, el('p', null, `It reads ${facts.join(' and ') || 'what your agents remember'} and writes a short profile here, every line with its sources. The lake below is everything your agents remember.`))
+ }
+ measureCaption()
+ return
+ }
+ caption.style.setProperty('--sec', hexOf(mix(b.sec.rgb, [255, 255, 255], 0.2)))
+ capSection.textContent = b.sec.name
+ capCount.textContent = `${b.j + 1} of ${b.sec.beliefs.length}`
+ capText.textContent = b.text
+ capWhyLabel.textContent = b.threads.length ? 'why your agents believe this' : 'nothing cited; a belief with no memory under it'
+ capWhy.textContent = ''
+ b.threads.forEach((th, i) => {
+ const li = el('li')
+ if (i === S.thread) li.className = 'sel'
+ if (th.kind === 'memory') {
+ const o = th.o
+ li.append(dot(o.rgb))
+ const w = el('span', 'w', o.m.title || o.m.path)
+ w.append(el('small', null, o.ag.name + (o.m.project?.name ? ' · ' + o.m.project.name : '')))
+ li.append(w, el('span', 'a', ago(o.age)))
+ } else if (th.kind === 'asks') {
+ li.append(dot(YOU, 'ring'))
+ li.append(el('span', 'w', `${b.askN.toLocaleString('en-US')} of your messages`), el('span', 'a', 'you'))
+ if (b.quotes.length) li.append(el('span', 'q', b.quotes.map((q) => `“${short(q, 70)}”`).join(' ')))
+ } else if (th.kind === 'session') {
+ li.append(dot(YOU, 'ring'))
+ li.append(el('span', 'w', b.sessionAsks ? `one conversation · ${b.sessionAsks} messages` : 'one conversation'), el('span', 'a', 'you'))
+ } else {
+ li.className = 'missing' + (i === S.thread ? ' sel' : '')
+ li.append(dot(rgbOf(th.x.agent.color), 'ring'))
+ li.append(el('span', 'w', `${th.x.name}`), el('span', 'a', 'not on this computer'))
+ }
+ if (th.kind !== 'missing') {
+ li.classList.add('go')
+ li.addEventListener('mousedown', (event) => event.preventDefault())
+ li.addEventListener('click', () => { touch(); S.thread = i; renderCaption(false); follow(b, th) })
+ }
+ capWhy.append(li)
+ })
+ measureCaption()
+ if (animate && !reduce && caption.animate) {
+ capText.animate([{ opacity: 0, transform: 'translateY(8px)', filter: 'blur(3px)' }, { opacity: 1, transform: 'none', filter: 'blur(0)' }], { duration: 380, easing: 'cubic-bezier(.2,.8,.2,1)' })
+ capWhy.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 420, delay: 60, easing: 'ease-out', fill: 'backwards' })
+ }
+ }
+
+ function renderOrbLabel() {
+ const o = focusedOrb()
+ if (!o) return
+ olDot.style.color = hexOf(o.rgb)
+ olMeta.textContent = [o.ag.name, o.m.project?.name || 'everywhere', elsewhere(o.m), ago(o.age)].filter(Boolean).join(' · ')
+ olTitle.textContent = o.m.title || o.m.path
+ olHolds.textContent = ''
+ if (o.beliefs.length) {
+ olHolds.className = 'h'
+ olHolds.append(el('span', null, o.beliefs.length === 1 ? 'holds up a belief' : `holds up ${o.beliefs.length} beliefs`))
+ for (const b of o.beliefs.slice(0, 3)) olHolds.append(el('div', null, short(b.text, 90)))
+ } else {
+ olHolds.className = 'h none'
+ olHolds.textContent = 'holds up no belief: a free-floating memory'
+ }
+ }
+
+ function positionOrbLabel() {
+ const o = focusedOrb()
+ const on = S.view === 'lake' && o && !S.panel && !S.recall && S.cam.y > G.lakeCam * 0.6
+ orbLabel.classList.toggle('on', !!on)
+ if (!on) { G.olRect = null; return }
+ const w = orbLabel.offsetWidth, h = orbLabel.offsetHeight
+ const sx = o.x, sy = o.y - S.cam.y
+ let x = sx + o.r * 3 + 16
+ if (x + w > G.W - 12) x = sx - o.r * 3 - 16 - w
+ const y = clamp(sy - h / 2, 12, G.H - h - 34)
+ G.olRect = [Math.max(8, x), y, w, h]
+ orbLabel.style.transform = `translate(${Math.round(Math.max(8, x))}px, ${Math.round(y)}px)`
+ }
+
+ function showCaption() {
+ caption.classList.toggle('on', S.arrival.done && S.view === 'self' && !S.recall)
+ recallBox.classList.toggle('on', !!S.recall)
+ }
+
+ function renderHint() {
+ let text
+ if (!S.arrival.done) text = 'any key to skip'
+ else if (S.panel) text = '↑↓ scroll · esc back'
+ else if (S.recall) text = '↑↓ choose · enter open · esc forget'
+ else if (S.view === 'lake') text = '←↑↓→ swim · enter lift out · space follow its light up · esc rise · type to recall'
+ else if (S.beliefs.length) text = '←→ section · ↑↓ belief · space pluck · tab why · enter dive · type to recall'
+ else if (S.orbs.length) text = '↓ dive into the lake · type to recall'
+ else text = 'type to recall'
+ hintKeys.textContent = text
+ }
+
+ function renderStatus() {
+ const n = (x) => x.toLocaleString('en-US')
+ const parts = [`${n(S.beliefs.length)} beliefs`, `${n(S.orbs.length)} memories`, `${n(S.asks.length)} messages`]
+ // Every machine that answered is in the lake; one that did not is named, with why.
+ const machines = S.snapshot?.machines ?? []
+ const answered = machines.filter((machine) => machine.ok).length
+ if (answered > 1) parts.push(`${answered} machines`)
+ for (const machine of machines.filter((m) => !m.ok)) parts.push(`${machine.name}: ${short(machine.error ?? 'did not answer', 48)}`)
+ hintStatus.textContent = parts.join(' · ')
+ }
+
+ /** Where a memory lives, when it is not this computer. */
+ const elsewhere = (m) => (m.machine && !m.machine.current && (S.snapshot?.machines ?? []).filter((x) => x.ok).length > 1 ? `on ${m.machine.name}` : null)
+
+ function showCount() {
+ const R = S.recall
+ count(R && wordsOf(R.q).length ? `${R.mems.length}/${S.orbs.length}` : S.ready ? String(S.orbs.length) : '')
+ }
+
+ let toastTimer = 0
+ function toast(text) {
+ toastBox.textContent = text; toastBox.classList.add('on')
+ view.clearTimeout(toastTimer); toastTimer = view.setTimeout(() => toastBox.classList.remove('on'), 1400)
+ }
+
+ function openPanel(spec, from) {
+ S.panel = spec
+ pMeta.textContent = ''; pFoot.textContent = ''; pDesc.textContent = ''
+ let glow = GOLD
+ if (spec.kind === 'memory') {
+ const o = spec.o, m = o.m
+ glow = o.rgb
+ pMeta.append(dot(o.rgb), el('span', null, o.ag.name), el('span', null, '·'), el('span', null, m.type || m.kind || 'note'),
+ el('span', null, '·'), el('span', null, m.project?.name || 'everywhere'), el('span', null, '·'), el('span', null, ago(o.age)))
+ if (elsewhere(m)) pMeta.append(el('span', null, '·'), el('span', null, elsewhere(m)))
+ pTitle.textContent = m.title || m.path
+ const d = String(m.description ?? '').trim()
+ if (d && d.toLowerCase() !== String(m.title ?? '').toLowerCase() && !/^(rules|summary|handbook|topic|saved|profile|notes|observation|conversation summary|remembered on request)$/i.test(d)) pDesc.textContent = d
+ renderBody(doc, pBody, m.body)
+ const related = el('div', 'related')
+ pBody.append(related)
+ relatedInto(related, spec)
+ if (o.beliefs.length) {
+ pFoot.append(el('div', null, o.beliefs.length === 1 ? 'holds up this belief' : `holds up ${o.beliefs.length} beliefs`))
+ for (const b of o.beliefs) pFoot.append(el('div', 'b', b.text))
+ } else pFoot.append(el('div', null, 'holds up no belief yet: a free-floating memory'))
+ pFoot.append(el('div', 'p', m.path || ''))
+ o.glow = 1
+ } else if (spec.kind === 'messages') {
+ const b = spec.b
+ pMeta.append(dot(YOU, 'ring'), el('span', null, 'your own words'), el('span', null, '·'), el('span', null, `${(b.askN || b.sessionAsks || b.motes.length).toLocaleString('en-US')} messages`))
+ pTitle.textContent = b.text
+ pDesc.textContent = b.askN > b.motes.length ? `The ${b.motes.length} that rise closest to it, out of ${b.askN.toLocaleString('en-US')}; nearest first.` : ''
+ pBody.textContent = ''
+ for (const i of b.motes) pBody.append(messageRow(S.asks[i]))
+ pFoot.append(el('div', null, `${b.sec.name}`))
+ } else if (spec.kind === 'message') {
+ glow = conversationPanel(spec)
+ }
+ panel.style.setProperty('--glow', css(glow, 0.35))
+ panel.classList.add('on')
+ veil.classList.add('on')
+ pBody.scrollTop = 0
+ if (!reduce && panel.animate) {
+ const dx = (from ? from[0] : G.W / 2) - G.W / 2, dy = (from ? from[1] : G.H / 2) - G.H / 2
+ panel.animate([
+ { opacity: 0, transform: `translate(-50%, -50%) translate(${dx}px, ${dy}px) scale(.05)`, filter: 'blur(8px)' },
+ { opacity: 1, offset: 0.55, filter: 'blur(1px)' },
+ { opacity: 1, transform: 'translate(-50%, -50%)', filter: 'blur(0)' },
+ ], { duration: 620, easing: 'cubic-bezier(.16,.84,.24,1)' })
+ }
+ renderHint()
+ }
+
+ function messageRow(ask, here = false) {
+ const ag = data.agent(ask.engine, S.snapshot)
+ const row = el('div', 'msg' + (here ? ' here' : ''))
+ row.append(dot(rgbOf(ag.color)))
+ if (here) row.append(marked(doc, el('div', 'x'), mark(clean(ask.text) || '(an image)', wordsOf(S.recall?.q ?? ''))))
+ else row.append(el('div', 'x', short(clean(ask.text) || '(an image)', 400)))
+ row.append(el('div', 'a', `${ag.name} · ${ago(S.now - ask.at)}${ask.cwd ? ' · ' + ask.cwd.split('/').filter(Boolean).pop() : ''}`))
+ return row
+ }
+
+ /**
+ * A message you sent, or a conversation search found: at once its words as the mist has them, then
+ * the conversation around them from the index, your words and the answers.
+ */
+ function conversationPanel(spec) {
+ const ask = spec.ask, hit = spec.hit
+ const engine = ask?.engine ?? hit?.engine
+ const ag = data.agent(engine, S.snapshot)
+ const at = ask?.at ?? hit?.at
+ const cwd = ask?.cwd || hit?.cwd || ''
+ const sessionId = ask?.sessionId ?? hit?.sessionId
+ const turn = Number.isInteger(ask?.turn) ? ask.turn : Number.isInteger(hit?.turn) && hit.turn >= 0 ? hit.turn : null
+ const terms = wordsOf(S.recall?.q ?? '')
+ pMeta.append(dot(YOU, 'ring'), el('span', null, 'you said, to ' + ag.name), el('span', null, '·'), el('span', null, at ? ago(S.now - at) : ''))
+ if (cwd) pMeta.append(el('span', null, '·'), el('span', null, cwd.split('/').filter(Boolean).pop()))
+ pTitle.textContent = (ask?.title || hit?.title) ? short(ask?.title || hit?.title, 90) : 'A conversation'
+ pBody.textContent = ''
+ const own = sessionId != null ? S.motes.session.get(sessionId) ?? [] : []
+ if (ask && own.length > 1) {
+ const at = own.indexOf(spec.mote)
+ for (const i of own.slice(Math.max(0, at - 4), at + 5)) pBody.append(messageRow(S.asks[i], i === spec.mote))
+ } else {
+ const p = el('p')
+ if (ask) marked(doc, p, mark(String(ask.text ?? ''), terms))
+ else marked(doc, p, hit?.snippet)
+ pBody.append(p)
+ }
+ if (sessionId != null) {
+ data.conversation(sessionId, turn).then((found) => {
+ if (S.panel !== spec || !found.turns.length) return
+ if (!(ask?.title || hit?.title) && found.title) pTitle.textContent = short(found.title, 90)
+ pBody.textContent = ''
+ let here = null
+ for (const t of found.turns) {
+ const row = turnRow(t, t.turn === turn, ag.name, terms)
+ if (t.turn === turn) here = row
+ pBody.append(row)
+ }
+ if (here && here.scrollIntoView) here.scrollIntoView({ block: 'nearest' })
+ })
+ }
+ const bel = spec.mote != null ? S.motes.bel.get(spec.mote) : null
+ if (bel && bel.length) { pFoot.append(el('div', null, 'part of what holds up')); for (const b of bel) pFoot.append(el('div', 'b', b.text)) }
+ else pFoot.append(el('div', null, spec.mote != null ? 'a message in the mist' : 'older than the mist: found by search'))
+ return rgbOf(ag.color)
+ }
+
+ /** One turn of a conversation: what you said, and what the agent answered, cut short. */
+ function turnRow(t, here, agentName, terms) {
+ const row = el('div', 'turn' + (here ? ' here' : ''))
+ const words = String(t.ask ?? '').trim()
+ const answer = String(t.answer ?? '').trim()
+ if (words) { row.append(el('div', 'who', 'you')); row.append(marked(doc, el('div', 'x'), here ? mark(short(words, 1200), terms) : short(words, 1200))) }
+ if (answer) { row.append(el('div', 'who', agentName)); row.append(el('div', 'y', short(answer, 900))) }
+ if (t.at) row.append(el('div', 'a', `turn ${Number(t.turn) + 1} · ${ago(S.now - t.at)}`))
+ return row
+ }
+
+ /** Under a lifted memory: the conversations about the same thing. */
+ function relatedInto(box, spec) {
+ data.related(spec.o.m.id).then((hits) => {
+ if (S.panel !== spec || !hits.length) return
+ box.append(el('h4', null, 'in your conversations'))
+ for (const hit of hits.slice(0, 5)) {
+ const ag = data.agent(hit.engine, S.snapshot)
+ const row = el('div', 'msg go')
+ row.append(dot(rgbOf(ag.color)))
+ row.append(el('div', 'x', short(hit.title || clean(String(hit.snippet ?? '').replace(/[\u0002\u0003]/g, '')), 120)))
+ row.append(el('div', 'a', `${ag.name} · ${hit.at ? ago(S.now - hit.at) : ''}`))
+ const mote = S.motes.key.get(`${hit.sessionId}#${hit.turn}`)
+ row.addEventListener('click', () => { touch(); openPanel({ kind: 'message', hit, ask: mote != null ? S.asks[mote] : null, mote: mote ?? null }) })
+ box.append(row)
+ }
+ })
+ }
+
+ function closePanel() {
+ const spec = S.panel
+ S.panel = null
+ veil.classList.remove('on')
+ const done = () => { if (!S.panel) panel.classList.remove('on') }
+ if (!reduce && panel.animate && spec) {
+ let from = null
+ if (spec.kind === 'memory') from = [spec.o.x, spec.o.y - S.cam.y]
+ const dx = (from ? from[0] : G.W / 2) - G.W / 2, dy = (from ? from[1] : G.H / 2) - G.H / 2
+ const anim = panel.animate([{ opacity: 1, transform: 'translate(-50%, -50%)' }, { opacity: 0, transform: `translate(-50%, -50%) translate(${dx}px, ${dy}px) scale(.08)`, filter: 'blur(6px)' }], { duration: 380, easing: 'cubic-bezier(.5,0,.75,0)' })
+ anim.onfinish = done
+ } else done()
+ renderHint()
+ }
+
+ // ── actions ─────────────────────────────────────────────────────────────────────────────────────
+
+ function finishArrival() {
+ if (S.arrival.done) return
+ S.arrival.done = true
+ S.arrival.t = ARRIVE_END
+ whisper.classList.remove('on')
+ root.classList.remove('arriving')
+ renderCaption(true)
+ showCaption()
+ renderHint()
+ }
+
+ function focusBelief(sec, bel, animate = true) {
+ const s = S.sections[sec]
+ if (!s) return
+ S.sec = sec; S.bel = clamp(bel, 0, s.beliefs.length - 1); S.thread = -1
+ renderCaption(animate)
+ }
+
+ function pluck(b) {
+ if (!b) return
+ b.pluckT = S.time; b.pluckA = 10; b.flash = 1
+ for (const o of b.sec.beliefs) if (o !== b) { o.pluckT = S.time + 0.06; o.pluckA = 2.2 }
+ S.pulses.push({ kind: 'down', b, t0: S.time })
+ }
+
+ function descend(o) {
+ if (!S.orbs.length) return
+ S.view = 'lake'
+ if (!o) {
+ const b = focusedBelief()
+ o = b?.mems[0] ?? S.orbs.reduce((best, x) => (!best || Math.hypot(x.bx - G.treeX, x.by - G.hz) < Math.hypot(best.bx - G.treeX, best.by - G.hz) ? x : best), null)
+ }
+ S.orb = o.i
+ camTo(G.lakeCam, 1.25)
+ if (!reduce) S.ripples.push({ x: focusedBelief()?.root?.[0] ?? G.treeX, t0: S.time })
+ renderOrbLabel(); showCaption(); renderHint()
+ }
+
+ function rise(dur = 1.1) {
+ const o = focusedOrb()
+ S.view = 'self'
+ if (o && o.beliefs.length) { const b = o.beliefs[0]; focusBelief(b.sec.k, b.j, false) }
+ camTo(0, dur)
+ showCaption(); renderCaption(true); renderHint()
+ }
+
+ function camTo(y, dur) { S.cam.from = S.cam.y; S.cam.to = y; S.cam.t0 = S.time; S.cam.dur = reduce ? 0.001 : dur }
+
+ function swim(dx, dy) {
+ const o = focusedOrb()
+ if (!o) { S.orb = 0; renderOrbLabel(); return true }
+ let best = null, bestScore = Infinity
+ for (const c of S.orbs) {
+ if (c === o) continue
+ const vx = c.bx - o.bx, vy = c.by - o.by
+ const along = vx * dx + vy * dy
+ if (along <= 2) continue
+ const perp = Math.abs(vx * dy - vy * dx)
+ const score = along + perp * 2.4
+ if (score < bestScore) { bestScore = score; best = c }
+ }
+ if (!best) return false
+ S.orb = best.i
+ renderOrbLabel()
+ return true
+ }
+
+ /** Enter on a belief's source: down to the memory, or the messages that hold it up. */
+ function follow(b, th) {
+ if (th?.kind === 'memory') descend(th.o)
+ else if (th && (th.kind === 'asks' || th.kind === 'session') && b.motes.length) openPanel({ kind: 'messages', b }, [b.root[0], b.root[1] - S.cam.y])
+ else descend(null)
+ }
+
+ // ── recall ──────────────────────────────────────────────────────────────────────────────────────
+
+ let searchTimer = 0
+ function startRecall(q) {
+ S.recall = { q: '', sel: 0, beliefs: new Set(), results: [], hits: null, mems: [], direct: [], local: [], localSet: new Set(), pick: [] }
+ S.thread = -1
+ runRecall(q)
+ showCaption()
+ }
+
+ function closeRecall() {
+ S.recall = null
+ for (const o of S.orbs) o.match = -1
+ S.motes.match.fill(0)
+ S.extra = []
+ view.clearTimeout(searchTimer)
+ showCaption(); renderCaption(false); renderHint(); showCount()
+ }
+
+ function runRecall(q) {
+ const R = S.recall
+ R.q = q
+ const M = S.motes
+ const found = recallMatch(S, q)
+ for (const o of S.orbs) o.match = -1
+ found.mems.forEach((o, i) => { o.match = i })
+ M.match.fill(0)
+ for (const i of found.local) M.match[i] = 1
+ R.beliefs = found.beliefs
+ R.mems = found.mems
+ R.direct = found.direct
+ R.local = found.local
+ R.localSet = new Set(found.local)
+ R.hits = null
+ S.extra = []
+ R.sel = 0
+ buildResults()
+ renderHint()
+ showCount()
+ view.clearTimeout(searchTimer)
+ if (found.terms.length) {
+ const asked = q
+ searchTimer = view.setTimeout(() => {
+ data.search(asked).then((hits) => {
+ if (S.recall !== R || R.q !== asked) return
+ // Copies: the same answer may be shared with another question's results.
+ R.hits = (hits || []).map((hit) => ({ ...hit }))
+ for (const hit of R.hits) {
+ const i = M.key.get(`${hit.sessionId}#${hit.turn}`)
+ if (i != null) { M.match[i] = 1; hit.mote = i; const list = M.bel.get(i); if (list) for (const b of list) R.beliefs.add(b) }
+ else {
+ const base = String(hit.cwd || '').split('/').filter(Boolean).pop()
+ const c = S.columns.find((col) => col.name === base)
+ const x = c ? c.cx + (h01(hit.sessionId + hit.turn) - 0.5) * c.w * 0.6 : 30 + h01(hit.sessionId) * (G.W - 60)
+ const e = { x, y: G.hz - 4, rise: 30 + h01(String(hit.turn)) * 40, t0: S.time, hit }
+ S.extra.push(e); hit.extra = e
+ }
+ }
+ buildResults()
+ loop.wake()
+ }).catch(() => {})
+ }, 160)
+ }
+ }
+
+ function buildResults() {
+ const R = S.recall
+ const roomy = G.H > 700
+ const results = []
+ const memMax = R.local.length || R.hits?.length ? (roomy ? 6 : 4) : roomy ? 11 : 8
+ if (R.mems.length) {
+ results.push({ head: `memories · ${R.mems.length}` })
+ for (const o of R.mems.slice(0, memMax)) results.push({ kind: 'memory', o })
+ }
+ if (R.direct.length) {
+ results.push({ head: `beliefs · ${R.direct.length}` })
+ for (const b of R.direct.slice(0, 3)) results.push({ kind: 'belief', b })
+ }
+ const msgMax = roomy ? 6 : 4
+ const messages = []
+ const terms = wordsOf(R.q)
+ const byText = new Map()
+ const add = (row, key) => {
+ const k = key.toLowerCase().replace(/\s+/g, ' ').trim()
+ const seen = byText.get(k)
+ if (seen) { seen.times++; return }
+ byText.set(k, row)
+ if (messages.length < msgMax) messages.push(row)
+ }
+ for (const i of R.local) {
+ const text = clean(S.asks[i].text)
+ add({ kind: 'message', ask: S.asks[i], mote: i, snippet: snippetOf(text, terms), times: 1 }, text)
+ }
+ for (const hit of R.hits ?? []) {
+ if (hit.mote != null && R.localSet.has(hit.mote)) continue
+ const snip = clean(hit.snippet)
+ add({ kind: 'message', hit, ask: hit.mote != null ? S.asks[hit.mote] : null, mote: hit.mote ?? null, extra: hit.extra ?? null, snippet: snip, times: 1 }, snip.replace(/[\u0002\u0003]/g, ''))
+ }
+ const msgCount = Math.max(R.local.length, R.hits?.length ?? 0)
+ if (messages.length) { results.push({ head: `your messages · ${msgCount}${R.hits && R.hits.length >= 20 ? '+' : ''}` }); results.push(...messages) }
+ R.results = results
+ R.pick = results.filter((r) => !r.head)
+ R.sel = clamp(R.sel, 0, Math.max(0, R.pick.length - 1))
+ renderRecall()
+ }
+
+ function renderRecall() {
+ const R = S.recall
+ if (!R) return
+ const terms = wordsOf(R.q)
+ recallSum.textContent = !terms.length ? 'recall: keep typing' : R.pick.length ? `recall “${short(R.q, 28)}” · ${R.beliefs.size} belief${R.beliefs.size === 1 ? '' : 's'} stir` : `nothing rises for “${short(R.q, 28)}”`
+ recallList.textContent = ''
+ const picked = R.pick[R.sel]
+ for (const r of R.results) {
+ const li = el('li')
+ if (r.head) { li.className = 'head'; li.textContent = r.head; recallList.append(li); continue }
+ if (r === picked) li.className = 'sel'
+ if (r.kind === 'memory') {
+ const o = r.o
+ li.append(dot(o.rgb))
+ li.append(marked(doc, el('span', 'w'), mark(o.m.title || o.m.path, terms)))
+ li.append(el('span', 'a', `${short(o.m.project?.name || 'everywhere', 16)} · ${ago(o.age)}${o.beliefs.length ? '' : ' · free'}`))
+ } else if (r.kind === 'belief') {
+ li.append(dot(r.b.sec.rgb, 'diamond'))
+ li.append(marked(doc, el('span', 'w serif'), mark(r.b.text, terms)))
+ li.append(el('span', 'a', short(r.b.sec.name, 16)))
+ } else {
+ const engine = r.ask?.engine ?? r.hit?.engine
+ const ag = data.agent(engine, S.snapshot)
+ li.append(dot(YOU, 'ring'))
+ li.append(marked(doc, el('span', 'w serif'), r.snippet ?? clean(r.hit?.snippet ?? '')))
+ const at = r.ask?.at ?? r.hit?.at
+ li.append(el('span', 'a', `${r.times > 1 ? '×' + r.times + ' · ' : ''}${ag.name} · ${at ? ago(S.now - at) : ''}`))
+ }
+ const index = R.pick.indexOf(r)
+ li.addEventListener('mousedown', (event) => event.preventDefault())
+ li.addEventListener('click', () => { touch(); R.sel = index; renderRecall(); activateRecall() })
+ recallList.append(li)
+ }
+ // Keep the selection in view when the list is long.
+ const sel = recallList.querySelector('.sel')
+ if (sel && sel.scrollIntoView) sel.scrollIntoView({ block: 'nearest' })
+ }
+
+ function recallSelection() {
+ const R = S.recall
+ if (!R || !R.pick || !R.pick.length) return null
+ return R.pick[R.sel] ?? null
+ }
+
+ function activateRecall() {
+ const r = recallSelection()
+ if (!r) return
+ if (r.kind === 'memory') {
+ const o = r.o
+ S.orb = o.i
+ openPanel({ kind: 'memory', o }, [o.x, o.y - S.cam.y])
+ } else if (r.kind === 'belief') {
+ // To the belief: the recall is done, so the prompt empties.
+ const b = r.b
+ setQuery('')
+ if (S.recall) closeRecall()
+ focusBelief(b.sec.k, b.j)
+ if (S.view === 'lake') rise()
+ pluck(b)
+ } else {
+ let from = null
+ if (r.mote != null) from = [S.motes.bx[r.mote], S.motes.by[r.mote] - S.motes.lift[r.mote] - S.cam.y]
+ else if (r.extra) from = [r.extra.x, r.extra.y - r.extra.rise - S.cam.y]
+ openPanel({ kind: 'message', ask: r.ask, hit: r.hit, mote: r.mote }, from)
+ }
+ }
+
+ // ── what the pane calls ─────────────────────────────────────────────────────────────────────────
+
+ function touch() { S.lastInput = now(); loop.wake() }
+
+ /** The header prompt changed. A leading "/" only says "this is a query". */
+ function recall(raw) {
+ S.query = String(raw ?? '')
+ if (!S.ready) return
+ touch()
+ if (!S.arrival.done) finishArrival()
+ if (!S.query) { if (S.recall) closeRecall(); return }
+ if (S.panel) closePanel()
+ const q = S.query.replace(/^\//, '')
+ if (!S.recall) startRecall(q); else runRecall(q)
+ }
+
+ /** A key, before the prompt sees it. True when the scene took it. */
+ function key(e, info = {}) {
+ if (!S.ready) return false
+ if (e.metaKey || e.ctrlKey || e.altKey) return false
+ const k = e.key
+ const typing = Boolean(info.typing)
+ touch()
+ if (!S.arrival.done) {
+ finishArrival()
+ // The key that skips the arrival still types, if it types.
+ return !(k.length === 1 && k !== ' ')
+ }
+
+ if (S.panel) {
+ if (k === 'Escape' || (k === 'Backspace' && !typing)) { closePanel(); return true }
+ if (k === 'ArrowDown') { pBody.scrollBy({ top: 64 }); return true }
+ if (k === 'ArrowUp') { pBody.scrollBy({ top: -64 }); return true }
+ if ((k === ' ' && !typing) || k === 'PageDown') { pBody.scrollBy({ top: pBody.clientHeight * 0.85 * (e.shiftKey ? -1 : 1) }); return true }
+ if (k === 'PageUp') { pBody.scrollBy({ top: -pBody.clientHeight * 0.85 }); return true }
+ if (k === 'Home' && !typing) { pBody.scrollTop = 0; return true }
+ if (k === 'End' && !typing) { pBody.scrollTop = pBody.scrollHeight; return true }
+ if (k === 'Tab' || k === 'Enter') return true
+ return false
+ }
+
+ if (S.recall) {
+ const R = S.recall
+ if (k === 'Escape') { setQuery(''); if (S.recall) closeRecall(); return true }
+ if (k === 'ArrowDown' || (k === 'Tab' && !e.shiftKey)) { R.sel = Math.min(R.pick.length - 1, R.sel + 1); renderRecall(); return true }
+ if (k === 'ArrowUp' || (k === 'Tab' && e.shiftKey)) { R.sel = Math.max(0, R.sel - 1); renderRecall(); return true }
+ if (k === 'Enter') { activateRecall(); return true }
+ return false
+ }
+ if (typing) return false
+
+ if (S.view === 'self') {
+ const b = focusedBelief()
+ if (k === 'ArrowLeft' || k === 'ArrowRight') {
+ const next = S.sec + (k === 'ArrowLeft' ? -1 : 1)
+ if (next >= 0 && next < S.sections.length) focusBelief(next, S.bel)
+ return true
+ }
+ if (k === 'ArrowUp') { if (b && S.bel > 0) focusBelief(S.sec, S.bel - 1); return true }
+ if (k === 'ArrowDown') {
+ if (b && S.bel < b.sec.beliefs.length - 1) focusBelief(S.sec, S.bel + 1)
+ else descend(null)
+ return true
+ }
+ if (k === ' ') { pluck(b); return true }
+ if (k === 'Tab') {
+ if (!b || !b.threads.length) return true
+ const n = b.threads.length
+ S.thread = S.thread < 0 ? (e.shiftKey ? n - 1 : 0) : (S.thread + (e.shiftKey ? -1 : 1) + n) % n
+ renderCaption(false)
+ return true
+ }
+ if (k === 'Enter') {
+ if (!b) { descend(null); return true }
+ follow(b, b.threads[S.thread >= 0 ? S.thread : b.threads.findIndex((x) => x.kind === 'memory')] ?? b.threads[0])
+ return true
+ }
+ if (k === 'Escape') { if (S.thread >= 0) { S.thread = -1; renderCaption(false) } return true }
+ return false
+ }
+ // In the lake.
+ if (k === 'ArrowLeft') { swim(-1, 0); return true }
+ if (k === 'ArrowRight') { swim(1, 0); return true }
+ if (k === 'ArrowDown') { swim(0, 1); return true }
+ if (k === 'ArrowUp') { if (!swim(0, -1)) rise(); return true }
+ if (k === 'Enter') { const o = focusedOrb(); if (o) openPanel({ kind: 'memory', o }, [o.x, o.y - S.cam.y]); return true }
+ if (k === 'Escape') { rise(); return true }
+ if (k === ' ') {
+ const o = focusedOrb()
+ if (o && o.beliefs.length) S.pulses.push({ kind: 'up', o, t0: S.time })
+ else if (o) { o.glow = 1; toast('this memory holds up no belief') }
+ return true
+ }
+ if (k === 'Tab') return true
+ return false
+ }
+
+ // The mouse works too: click a section, a bead or an orb; scroll to dive or rise.
+ function pointAtEvent(e) { const r = root.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top + S.cam.y] }
+ canvas.addEventListener('mousedown', (e) => e.preventDefault())
+ canvas.addEventListener('click', (e) => {
+ if (!S.ready) return
+ touch()
+ if (!S.arrival.done) { finishArrival(); return }
+ if (S.panel) { closePanel(); return }
+ const [x, y] = pointAtEvent(e)
+ const label = S.view === 'self' && S.labelHits.find((h) => x >= h.x - 6 && x <= h.x + h.w + 6 && y >= h.y - 6 && y <= h.y + h.h + 6)
+ let best = null, bd = 22
+ for (const b of S.beliefs) { if (!b.tip) continue; const d = Math.hypot(b.tip[0] - x, b.tip[1] - y); if (d < bd) { bd = d; best = b } }
+ if (label || best) {
+ if (S.recall) { setQuery(''); if (S.recall) closeRecall() }
+ if (S.view === 'lake') rise()
+ if (best) { focusBelief(best.sec.k, best.j); pluck(best) } else focusBelief(label.sec.k, 0)
+ return
+ }
+ let bo = null; bd = 18
+ for (const o of S.orbs) { const d = Math.hypot(o.x - x, o.y - y); if (d < bd) { bd = d; bo = o } }
+ if (!bo) return
+ // A risen orb, or the one you swam to, lifts out; any other, you dive to.
+ if (S.recall || (S.view === 'lake' && S.orb === bo.i)) { S.orb = bo.i; openPanel({ kind: 'memory', o: bo }, [bo.x, bo.y - S.cam.y]) } else descend(bo)
+ })
+ canvas.addEventListener('mousemove', (e) => {
+ if (!S.ready || !S.arrival.done) return
+ const [x, y] = pointAtEvent(e)
+ const over = (S.view === 'self' && S.labelHits.some((h) => x >= h.x - 6 && x <= h.x + h.w + 6 && y >= h.y - 6 && y <= h.y + h.h + 6)) ||
+ S.beliefs.some((b) => b.tip && Math.hypot(b.tip[0] - x, b.tip[1] - y) < 22) || S.orbs.some((o) => Math.hypot(o.x - x, o.y - y) < 18)
+ canvas.style.cursor = over ? 'pointer' : ''
+ })
+ let wheelLock = 0
+ canvas.addEventListener('wheel', (e) => {
+ if (!S.ready || S.panel || !S.arrival.done || S.time < wheelLock) return
+ touch()
+ if (e.deltaY > 30 && S.view === 'self') { descend(null); wheelLock = S.time + 1.2 }
+ else if (e.deltaY < -30 && S.view === 'lake') { rise(); wheelLock = S.time + 1.2 }
+ }, { passive: true })
+
+ // ── the loop ────────────────────────────────────────────────────────────────────────────────────
+
+ function frame(at, step) {
+ if (!S.ready) return false
+ const dt = Math.min(0.1, step || 1 / 60)
+ S.time += dt
+ if (!S.arrival.done) {
+ S.arrival.t = ((now() - S.arrival.start) / 1000) * PACE // by the clock: slow first frames do not lengthen it
+ whisper.classList.toggle('on', S.arrival.t > 0.3 && S.arrival.t < 3.3)
+ if (S.arrival.t >= ARRIVE_END) finishArrival()
+ }
+ update(dt)
+ draw()
+ return !still()
+ }
+
+ let running = false
+ loop.set(frame)
+ load({ arrive: true })
+
+ // For automated checks, read-only: where things are and what is focused. No global, nothing to call.
+ const inspect = () => ({
+ ready: S.ready, arrived: S.arrival.done, view: S.view, section: S.sections[S.sec]?.name ?? null, belief: focusedBelief()?.text ?? null,
+ thread: S.thread, orb: focusedOrb()?.m.title ?? null, orbId: focusedOrb()?.m.id ?? null, panel: S.panel?.kind ?? null, recall: S.recall ? { q: S.recall.q, picks: S.recall.pick.length, extra: S.extra.length } : null,
+ camY: S.cam.y, labels: S.labelHits.map((h) => ({ section: h.sec.name, x: h.x + h.w / 2, y: h.y + h.h / 2 - S.cam.y })),
+ beads: S.beliefs.filter((b) => b.tip).map((b) => ({ text: b.text, x: b.tip[0], y: b.tip[1] - S.cam.y })),
+ orbs: S.orbs.filter((o) => o.appear > 0.5).slice(0, 40).map((o) => ({ title: o.m.title, beliefs: o.beliefs.length, x: o.x, y: o.y - S.cam.y })),
+ })
+ Object.defineProperty(root, 'inspectSelf', { value: inspect })
+
+ return {
+ /** Shown (the tab is visible): a snapshot that came while hidden is taken in now. */
+ start() {
+ running = true
+ reduce = reducedMotion()
+ if (S.stale && S.ready && !S.loading && !S.panel && !S.recall) load({ arrive: false })
+ loop.wake()
+ },
+ stop() { running = false },
+ recall,
+ key,
+ resize() { if (!S.ready) return; layout(); loop.wake() },
+ close() { view.clearInterval(staleTimer); loop.set(null) },
+ }
+}