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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Memories research: four ways to walk into the brain (#1140)
Dee0b2dd18f8202
diff --git a/docs/research/2026-10-10-memory-brain/README.md b/docs/research/2026-10-10-memory-brain/README.mdnew file mode 100644index 000000000..7bdb51e5e--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/README.md@@ -0,0 +1,77 @@+# Walking into the brain: Memories prototypes++2026-10-10. The Memories viewer works, but it is a list: groups to open, rows to click. The agent chat+beside it already answers questions, so the viewer's job is something a list cannot do: let a person+**walk into their own memory** and find things the way one finds a memory, by place, by association+and by time. These are experiments toward that, built on the viewer's real data.++## How to open them++```bash+node docs/research/2026-10-10-memory-brain/serve.mjs 47611+open http://127.0.0.1:47611/ # an invented person+open "http://127.0.0.1:47611/?real" # your own memories on this computer+```++`?real` reads what the Memories viewer reads (`store/agents/memories/lib`): agents' memory files,+About You and your messages from the session index. It is read on each request, only on loopback,+and never written anywhere. Every page also opens straight from the file system on invented data.++## What films do with a mind++| Film | How it shows a mind | What we take |+|---|---|---|+| Inside Out (2015) | Memories are glowing orbs on endless shelves of Long Term Memory; core memories power Islands of Personality; recall tubes fetch an orb; faded orbs crumble in the Memory Dump | memory as an object you can hold; color by feeling; forgetting as fading |+| Inside Out 2 (2024) | The Sense of Self: memories send up belief strings that weave into a glowing structure | **About You is exactly this**: each line is a belief, each is held up by the memories it cites |+| Eternal Sunshine of the Spotless Mind (2004) | Walking through memory scenes that collapse while you are in them; books lose their words, faces blur, lights go out | age as decay: old memories lose letters at the edges |+| Inception (2010) | Dream levels stacked inside each other; architecture that folds; the secret in the deepest level | depth as abstraction: About You, then memories, then conversations, then your words |+| Sherlock, "The Hounds of Baskerville" (2012) | The mind palace: words float in the air and are swept aside with a hand | typing makes memories float up around you |+| Interstellar (2014) | The tesseract: one bookshelf at every moment in time, laid out as space; a pulled string reaches across time | time as a place you move through |+| Harry Potter (Pensieve) | Silver strands of memory in a basin; lean in and fall into the moment | diving into one memory |+| The Cell (2000), Lucy (2014) | Flying through a mind's own landscape; neurons firing | the connectome as a place; activity as light |+| Westworld (2016) | The maze: consciousness is a journey inward, to the center | the center of the brain is "you" |+| Black Mirror, "The Entire History of You" (2011) | Rewinding and replaying any moment | scrubbing through time |+| Severance (2022) | Macrodata Refinement: a terminal of drifting numbers sorted by how they feel | the terminal can feel alive |++Recall in cognitive science is **spreading activation**: a cue lights one memory, and the light spreads+to what is associated with it. That is a better search than a filter box.++## Four concepts++1. **Synapse** (`synapse.html`). Fly into a brain built from your data. Every message is a neuron, memories+ are bright engrams, projects are regions, About You sits at the core with axons to what it cites. Type,+ and recall spreads through the brain as light; the camera follows it to the memory. Scrub time and watch+ the brain grow from your first message to today.+2. **Sense of Self** (`self.html`). Inside Out 2's belief strings, literally. About You hangs above as a+ luminous structure, one strand per line; below is the lake of memories; threads rise from each memory to+ the beliefs it holds up. Pluck a belief and see why your agents believe it.+3. **Mind Palace** (`palace.html`). Walk the halls in first person, vector-drawn like an old arcade game.+ About You is carved in the atrium; each project is a wing; old rooms gather dust and lose letters. Type,+ and words float up around you, Sherlock-style.+4. **Tesseract** (`tesseract.html`). Your months unrolled as a corridor of days. Each day is a frame holding+ what you said and what your agents wrote down; strings tie a memory to every day it came up. Fly through+ time; pull a string.++Each is keyboard first (the person this is for works like vim and tmux), runs without libraries or network,+and renders memory text as text only: it is written by models and may hold anything.++## What was built (2026-10-10)++All four run in both modes and from `file://`. In headless Chromium at 1360×900 none logged an error+or fetched anything from outside, and all respect reduced motion. Recall starts as soon as you type;+where a letter is also a command, start with `/`.++| | Keys | Notes |+|---|---|---|+| [Synapse](synapse.html) | type · ←→ orbit · ↑↓ fly · ⏎ dive · esc · `[ ]` time · `\` replay | WebGL point cloud. About You is a gold arch between the hemispheres; `\` replays the brain growing from the first message |+| [Sense of Self](self.html) | type · ←→ branch · ↑↓ belief · space pluck · tab thread · ⏎ into the lake | Canvas. About You as a tree of light whose roots run to the memories below the water; old orbs sink, crack and lose letters |+| [Mind Palace](palace.html) | type · ↑↓ walk · ←→ turn · ⏎ go in or read · tab map · `~` home | WebGL vector halls with bloom. About You on standing stones; a wing per project; recalled memories fly in as cards and you glide to their room |+| [Tesseract](tesseract.html) | type · ↑↓ days · ⇧ weeks · ←→ messages · space pull · tab follow · `~` About You | Canvas corridor of days. A pulled string ripples through every day a memory came up |++## Found on the way++- **Sessions Harness launched are indexed without their folder.** `externalFields` in+ `cli/src/lib/sessionSearch/indexer.ts` records `cwd` only for sessions started outside Harness, so on+ one real machine 165 of 328 sessions, and 98% of messages, have no folder. Memories' Projects and+ every project-shaped view here undercount because of it. The transcripts know the folder (Claude+ Code's project directory, Codex's `session_meta`); the indexer should keep it.diff --git a/docs/research/2026-10-10-memory-brain/index.html b/docs/research/2026-10-10-memory-brain/index.htmlnew file mode 100644index 000000000..c98e8eb5f--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/index.html@@ -0,0 +1,41 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Memory Brain</title>+<style>+ :root { --bg: #0b0c0e; --panel: #131518; --text: #e6e7e9; --muted: #8b8f96; --faint: #5a5e65; --line: #24272c; --accent: #e8875f; color-scheme: dark; }+ * { box-sizing: border-box; }+ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.55 ui-monospace, "SF Mono", Menlo, monospace; }+ main { max-width: 1240px; margin: 0 auto; padding: 40px 16px 64px; }+ h1 { font-size: 22px; margin: 0 0 6px; letter-spacing: .01em; }+ h1 span { color: var(--accent); }+ .lede { color: var(--muted); margin: 0 0 8px; max-width: 72ch; }+ .mode { color: var(--faint); margin: 0 0 28px; }+ .mode a { color: var(--text); }+ .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(520px, 1fr)); gap: 22px; }+ @media (max-width: 560px) { .grid { grid-template-columns: 1fr; } }+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; overflow: hidden; display: flex; flex-direction: column; }+ .card a.shot { display: block; aspect-ratio: 1360 / 900; background: #000 center / cover no-repeat; border-bottom: 1px solid var(--line); }+ .card .body { padding: 14px 16px 16px; display: flex; flex-direction: column; gap: 6px; flex: 1; }+ .card h2 { font-size: 16px; margin: 0; }+ .card .film { color: var(--faint); font-size: 12px; }+ .card p { margin: 0; color: var(--muted); }+ .card .keys { color: var(--faint); font-size: 12px; margin-top: auto; padding-top: 8px; }+ .card .open { display: flex; gap: 14px; padding-top: 6px; }+ .card .open a { color: var(--text); text-decoration: none; border-bottom: 1px solid var(--faint); }+ .card .open a:hover { border-color: var(--text); }+ .card .open a.real { color: var(--accent); border-color: var(--accent); }+</style>+</head>+<body>+<main>+ <h1><span>◉</span> walking into the brain</h1>+ <p class="lede">Four ways to explore what your agents remember: by place, by association and by time, the way a mind finds a memory. The chat beside Memories answers questions; this is for wandering in. Every one is keyboard first: just start typing to recall.</p>+ <p class="mode" id="mode"></p>+ <div class="grid" id="grid"></div>+</main>+<script src="index.js"></script>+</body>+</html>diff --git a/docs/research/2026-10-10-memory-brain/index.js b/docs/research/2026-10-10-memory-brain/index.jsnew file mode 100644index 000000000..93b812f9e--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/index.js@@ -0,0 +1,46 @@+// The lookbook: one card per prototype. Opened by serve.mjs, each card also opens on your own memories.+(function () {+ 'use strict'+ const served = location.protocol.startsWith('http')+ const real = /[?&]real\b/.test(location.search)+ const PROTOTYPES = [+ ['synapse', 'Synapse', 'The Cell · Lucy · neural imaging',+ 'Fly into a brain grown from your messages. Memories are bright engrams, projects are regions, About You sits at the core. Type, and recall spreads through it as light. Scrub time and watch it grow.',+ 'type to recall · ←→ orbit · ↑↓ fly · enter dive · esc back · [ ] time · \\ replay'],+ ['self', 'Sense of Self', 'Inside Out 2',+ 'About You hangs above as a luminous structure, one strand per belief. Below, the lake of memories. Threads rise from each memory to the beliefs it holds up: pluck one and see why your agents believe it.',+ 'type to recall · ←→ branches · ↑↓ beliefs · space pluck · enter into the lake'],+ ['palace', 'Mind Palace', 'Sherlock · method of loci · Westworld',+ 'Walk the halls in first person, drawn in light. About You is carved in the atrium; every project is a wing; old rooms gather dust and lose letters. Type, and words float up around you.',+ 'type to recall · ↑↓ walk · ←→ turn · enter go in or read · tab map · ~ home'],+ ['tesseract', 'Tesseract', 'Interstellar',+ 'Your months unrolled as a corridor of days. Each day holds what you said and what your agents wrote down. Strings tie a memory to every day it came up: pull one and the corridor lights.',+ 'type to recall · ↑↓ days · shift weeks · ←→ messages · space pull · ~ about you'],+ ]+ const SHOTS = { synapse: 'synapse.png', self: 'self.jpg', palace: 'palace.jpg', tesseract: 'tesseract.png' }+ const mode = document.getElementById('mode')+ if (!served) mode.textContent = 'Opened as a file: invented memories. Run serve.mjs (see README.md) to open them on your own.'+ else if (real) mode.append('Showing your own memories on this computer. ', Object.assign(document.createElement('a'), { href: './', textContent: 'Show the invented person instead' }))+ else mode.append('Showing an invented person. ', Object.assign(document.createElement('a'), { href: './?real', textContent: 'Open them on your own memories' }))+ const grid = document.getElementById('grid')+ for (const [id, name, film, says, keys] of PROTOTYPES) {+ const card = document.createElement('article')+ card.className = 'card'+ const href = `${id}.html${real ? '?real' : ''}`+ const shot = Object.assign(document.createElement('a'), { className: 'shot', href, title: `Open ${name}` })+ shot.style.backgroundImage = `url("${SHOTS[id]}")`+ const body = document.createElement('div')+ body.className = 'body'+ const title = Object.assign(document.createElement('h2'), { textContent: name })+ const from = Object.assign(document.createElement('div'), { className: 'film', textContent: film })+ const text = Object.assign(document.createElement('p'), { textContent: says })+ const hint = Object.assign(document.createElement('div'), { className: 'keys', textContent: keys })+ const open = document.createElement('div')+ open.className = 'open'+ open.append(Object.assign(document.createElement('a'), { href: `${id}.html`, textContent: 'open' }))+ if (served) open.append(Object.assign(document.createElement('a'), { className: 'real', href: `${id}.html?real`, textContent: 'open on my memories' }))+ body.append(title, from, text, hint, open)+ card.append(shot, body)+ grid.append(card)+ }+})()diff --git a/docs/research/2026-10-10-memory-brain/memory-data.js b/docs/research/2026-10-10-memory-brain/memory-data.jsnew file mode 100644index 000000000..c8006de0a--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/memory-data.js@@ -0,0 +1,291 @@+/*+ * The one data source every prototype here reads: what the Memories viewer is given (its snapshot), plus+ * the person's own messages to their agents, plus search.+ *+ * MemoryData.load() → Promise<{ snapshot, asks, real }>+ * MemoryData.search(q) → Promise<hits> hit: { at, engine, title, cwd, sessionId, turn, snippet }+ * snippet marks matches with \u0002 … \u0003 (as the viewer's /api/search does)+ * MemoryData.refs(line, snapshot) → the memory rows an About You line cites+ * MemoryData.agent(id, snapshot) → { id, name, color }+ *+ * Opened as a file, or without ?real, it is an invented person on an invented computer (made here, below).+ * Served by serve.mjs and opened with ?real, it is this computer's own memories, read on request and+ * never written anywhere. A classic script, so the pages work from file:// too.+ *+ * Everything in here is untrusted text written by models and people: render it with textContent only.+ */+(function () {+ 'use strict'+ const DAY = 86_400_000+ const real = /[?&]real\b/.test(location.search) && location.protocol.startsWith('http')++ // ── an invented person ───────────────────────────────────────────────────────────────────────────++ 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+ }+ }++ const AGENTS = [+ ['claude', 'Claude Code', '#d97757', true, 'on', 'Learns as you work, one folder per repository.'],+ ['codex', 'Codex', '#3fae8c', true, 'on', 'Learns in the background from idle conversations.'],+ ['grok', 'Grok Build', '#8a93a6', true, 'on', 'Keeps topics and observations, global and per workspace.'],+ ['gemini', 'Gemini CLI', '#4f8ef7', true, 'on', 'Saves what you ask it to remember into GEMINI.md.'],+ ['hermes', 'Hermes', '#d4a72c', true, 'on', 'Keeps a short profile of you and a notebook.'],+ ['pi', 'Pi', '#b07cd8', true, 'none', 'Reads your instructions; keeps no memory of its own.'],+ ['opencode', 'OpenCode', '#e0e0e0', true, 'none', 'Reads your instructions; keeps no memory of its own.'],+ ['openclaw', 'OpenClaw', '#e5534b', false, 'none', 'Keeps a workspace profile and daily notes.'],+ ['cursor', 'Cursor', '#7fb2ff', false, 'none', 'Memories live in its cloud, not on disk.'],+ ['copilot', 'Copilot', '#9aa4b2', false, 'none', 'Keeps no memory on disk.'],+ ['windsurf', 'Windsurf', '#36c5b0', false, 'unreadable', 'Keeps memories in a binary format.'],+ ]++ const PROJECTS = ['payments', 'widgets', 'docs-site', 'mobile-app', 'infra', 'ml-pipeline', 'design-system', 'api-gateway', 'cli', 'firmware', 'website']++ // [agent, project|null, kind, type, title, description, body]+ const NOTES = [+ ['claude', 'payments', 'you', 'feedback', 'Short answers', 'Wants replies under five lines', 'Keep replies short; lead with the answer.\n\n**Why:** asked for a tl;dr many times.\n**How to apply:** one paragraph, then stop.'],+ ['claude', 'payments', 'project', 'project', 'Webhook retries', 'Retries back off to one hour, then page', 'Webhook retries back off exponentially to one hour, then page the on-call.\n\n**Why:** a provider outage once retried 40k times in a minute.'],+ ['claude', 'payments', 'reference', 'reference', 'Ledger docs', 'Where the ledger design lives', 'The ledger design is in docs/ledger.md; the migration plan beside it.'],+ ['claude', 'payments', 'project', 'project', 'Refund flow', 'Partial refunds are allowed twice', 'A charge may be partially refunded at most twice; the third is a support ticket.'],+ ['claude', 'payments', 'you', 'feedback', 'Merge when green', 'Lands pull requests once CI passes', 'Merge green pull requests without asking.\n\n**Why:** waiting on a yes cost a day twice.'],+ ['claude', 'widgets', 'you', 'feedback', 'Tests first', 'Run the tests before saying done', 'Run `make test` before calling anything done.\n\n**Why:** "done" twice meant "compiles".'],+ ['claude', 'widgets', 'project', 'project', 'Legacy renderer', 'The legacy renderer is going away', 'New work targets the grid renderer only; the legacy one is frozen.'],+ ['claude', 'widgets', 'project', 'project', 'Snapshot tests', 'Grid snapshots live beside each widget', 'Snapshot tests sit next to each widget, regenerated with `make snap`.'],+ ['claude', 'widgets', 'you', 'feedback', 'Screenshots for UI', 'Reviews UI from screenshots', 'Send a screenshot with every UI change; review happens on the picture.'],+ ['claude', 'docs-site', 'you', 'user', 'Plain words', 'Writes docs in plain words', 'Prefers short sentences and no jargon in anything a reader sees.'],+ ['claude', 'docs-site', 'project', 'project', 'Deploys from main', 'Every merge to main publishes the site', 'The docs site deploys on every merge to main; previews per pull request.'],+ ['claude', 'docs-site', 'reference', 'reference', 'Style guide', 'The house style guide', 'The style guide is at docs/style.md: sentence case, no exclamation marks.'],+ ['claude', 'mobile-app', 'you', 'feedback', 'Mockup first', 'Agree on a mockup before UI code', 'Show a mockup and agree on it before writing UI code.\n\n**Why:** two screens were rebuilt from scratch.'],+ ['claude', 'mobile-app', 'project', 'project', 'Release train', 'Releases go out on Tuesdays', 'The app ships on Tuesdays; never on a Friday.'],+ ['claude', 'mobile-app', 'project', 'project', 'Crash on resume', 'Resume crash fixed by restoring the session first', 'The resume crash came from reading the session before it was restored.'],+ ['claude', 'infra', 'project', 'project', 'Staging certs', 'Certificates rotate every 60 days', 'Staging certificates rotate every 60 days by the cron in infra/certs.'],+ ['claude', 'infra', 'you', 'feedback', 'No weekend deploys', 'Merge on weekends, deploy on Monday', 'Merges may land over the weekend; deploys wait for Monday.'],+ ['claude', 'infra', 'reference', 'reference', 'Runbooks', 'Where the runbooks are', 'Runbooks are in the ops wiki under On-call.'],+ ['claude', 'ml-pipeline', 'project', 'project', 'Ranker evals', 'The eval set is frozen per quarter', 'The ranker eval set is frozen each quarter so scores stay comparable.'],+ ['claude', 'ml-pipeline', 'you', 'feedback', 'Measure first', 'Wants numbers before a change', 'Measure before and after any performance change, on the same workload.'],+ ['claude', 'ml-pipeline', 'project', 'project', 'Tokenizer regression', 'A tokenizer upgrade broke emoji', 'The tokenizer upgrade split emoji; pinned until the fix ships.'],+ ['claude', 'design-system', 'project', 'project', 'Token rename', 'Color tokens renamed by role', 'Color tokens are named by role (surface, text, accent), not by hue.'],+ ['claude', 'design-system', 'you', 'feedback', 'Keyboard first', 'Every action needs a key', 'Every action must be reachable from the keyboard; mouse is optional.'],+ ['claude', 'design-system', 'you', 'user', 'Terminal taste', 'Likes the feel of vim, tmux and fzf', 'Draws on vim, tmux and fzf for how tools should feel: quiet, fast, typed.'],+ ['claude', 'api-gateway', 'project', 'project', 'Rate limits', 'Limits are per key, not per IP', 'Rate limits apply per API key; IP limits only for anonymous traffic.'],+ ['claude', 'api-gateway', 'reference', 'reference', 'OpenAPI diff', 'CI fails on a breaking API change', 'CI runs an OpenAPI diff and fails on breaking changes.'],+ ['claude', 'cli', 'you', 'feedback', 'Small core', 'Keep the core small and stable', 'Features go in services the core can run without.\n\n**Why:** a feature crash once took every session down.'],+ ['claude', 'cli', 'project', 'project', 'Release from main', 'Releases are cut from main only', 'Every release is cut from main by the release script; tags are never moved.'],+ ['claude', 'cli', 'you', 'feedback', 'Why comments', 'Comments say why, not what', 'Comments name the incident or the measurement behind the code.'],+ ['claude', 'firmware', 'project', 'project', 'Flash over USB', 'The dial flashes over USB-C', 'The dial flashes over USB-C; hold the knob to enter the bootloader.'],+ ['claude', 'firmware', 'reference', 'reference', 'Pin map', 'Where the pin map lives', 'The pin map is in firmware/board.md.'],+ ['claude', 'website', 'you', 'feedback', 'Speed matters', 'Pages should feel instant', 'Every page should feel instant; measure the first paint.'],+ ['claude', 'website', 'project', 'project', 'Launch copy', 'The launch page copy is final', 'The launch copy is signed off; change only typos.'],+ ['claude', null, 'instructions', 'CLAUDE.md', 'CLAUDE.md for every project', 'Rules', 'Always run the tests before saying done.\nNever push to main directly.'],+ ['codex', null, 'summary', 'summary v1', 'What Codex keeps about you', 'Summary', 'Prefers small pull requests with one change each. Works late. Asks why before agreeing to a design.'],+ ['codex', null, 'summary', 'handbook v1', 'Testing', 'Handbook', 'Run `make test` first; integration tests only when the change touches the network.'],+ ['codex', null, 'summary', 'handbook v1', 'Reviews', 'Handbook', 'One change per pull request; review while CI runs.'],+ ['codex', null, 'summary', 'handbook v1', 'Releases', 'Handbook', 'Releases are cut on Mondays; a failed release is fixed forward.'],+ ['codex', null, 'you', 'remembered on request', 'Use pnpm', 'Remembered on request', 'Use pnpm, not npm.'],+ ['codex', null, 'note', 'conversation summary', 'Fixed the login bug', 'Conversation summary', 'The token expired early because the clock skew was not allowed for.'],+ ['codex', null, 'note', 'conversation summary', 'Sped up the search index', 'Conversation summary', 'Search got 8x faster by ranking before building snippets.'],+ ['codex', null, 'note', 'conversation summary', 'Mobile onboarding', 'Conversation summary', 'Onboarding went from four steps to one by scanning a code.'],+ ['grok', null, 'you', 'topic', 'Code style', 'Topic', 'Two-space indentation everywhere; no semicolons in new JavaScript.'],+ ['grok', 'api-gateway', 'project', 'topic', 'Gateway build', 'Topic', 'The gateway builds with Bazel; cache on the build box.'],+ ['grok', null, 'note', 'observation', 'Asked for dark mode twice', 'Observation', 'Asked twice for a dark mode in the docs site.'],+ ['grok', null, 'note', 'observation', 'Prefers diagrams', 'Observation', 'Understands a design faster from a diagram than from prose.'],+ ['gemini', null, 'you', 'saved', 'Prefers tabs in Go files', 'Saved', 'Prefers tabs in Go files'],+ ['gemini', null, 'you', 'saved', 'Lives in UTC+1', 'Saved', 'Lives in UTC+1'],+ ['gemini', null, 'you', 'saved', 'Reads on a large monitor', 'Saved', 'Reads on a large monitor; wide tables are fine.'],+ ['hermes', null, 'you', 'profile', 'Prefers terse answers.', 'Profile', 'Prefers terse answers.'],+ ['hermes', null, 'you', 'profile', 'Works late in the evening.', 'Profile', 'Works late in the evening.'],+ ['hermes', null, 'you', 'profile', 'Hands work off overnight.', 'Profile', 'Hands work off overnight and reads a summary in the morning.'],+ ['hermes', null, 'note', 'notes', 'Postgres 16', 'Notes', 'The main database is Postgres 16.'],+ ['pi', null, 'instructions', 'AGENTS.md', 'AGENTS.md for every project', 'Rules', 'Keep diffs small.'],+ ]++ const ABOUT = [+ ['How you work', 'Works mostly in Codex and Claude Code, side by side.', ['asks:1480']],+ ['How you work', 'Gives UI feedback with screenshots.', ['asks:212', 'claude:screenshots-for-ui.md']],+ ['How you work', 'Hands work off overnight and reads a summary in the morning.', ['asks:64', 'hermes:USER.md']],+ ['How you work', 'Asks "why" before agreeing to a design.', ['asks:41', 'codex:memory_summary.md']],+ ['How you work', 'Thinks in diagrams more than prose.', ['grok:prefers-diagrams.md']],+ ['What you want from agents', 'Short answers that lead with the result.', ['claude:short-answers.md', 'hermes:USER.md', 'asks:98']],+ ['What you want from agents', 'Tests run before anything is called done.', ['claude:tests-first.md', 'codex:MEMORY.md']],+ ['What you want from agents', 'Green pull requests merged without asking.', ['claude:merge-when-green.md', 'asks:106']],+ ['What you want from agents', 'A mockup agreed before UI code.', ['claude:mockup-first.md']],+ ['What you want from agents', 'One change per pull request.', ['codex:memory_summary.md', 'codex:MEMORY.md']],+ ['Taste', 'Wants tools to feel like vim, tmux and fzf: quiet, fast, typed.', ['claude:terminal-taste.md', 'asks:126']],+ ['Taste', 'Every action reachable from the keyboard.', ['claude:keyboard-first.md']],+ ['Taste', 'Pages that feel instant.', ['claude:speed-matters.md', 'asks:111']],+ ['Taste', 'Plain words; no jargon.', ['claude:plain-words.md']],+ ['Taste', 'Two-space indentation, tabs in Go.', ['grok:code-style.md', 'gemini:GEMINI.md']],+ ['Engineering principles', 'A small, stable core; features as services.', ['claude:small-core.md']],+ ['Engineering principles', 'Measure before and after any performance change.', ['claude:measure-first.md']],+ ['Engineering principles', 'Comments say why, naming the incident.', ['claude:why-comments.md']],+ ['Engineering principles', 'Merge on weekends, deploy on Monday.', ['claude:no-weekend-deploys.md', 'codex:MEMORY.md']],+ ['Right now', 'Shipping the mobile onboarding in one step.', ['codex:mobile-onboarding.md', 'asks:58']],+ ['Right now', 'Freezing the ranker eval set for the quarter.', ['claude:ranker-evals.md']],+ ['Right now', 'Retiring the legacy renderer.', ['claude:legacy-renderer.md']],+ ]++ const SAYINGS = {+ payments: ['why do webhook retries pile up after an outage?', 'make the refund flow handle a third partial refund', 'walk me through the ledger migration', 'add a test for the retry backoff', 'tldr the incident from last night'],+ widgets: ['the grid flickers on resize, fix it', 'regenerate the snapshots and show me the diff', 'drop the legacy renderer from the build', 'why is this widget re-rendering twice?', 'screenshot the empty state'],+ 'docs-site': ['rewrite the quickstart in plain words', 'find every broken link', 'add a dark mode to the docs', 'make the search box faster', 'shorter, please'],+ 'mobile-app': ['onboarding in one step: scan a code', 'the app crashes on resume, find out why', 'mockup the settings screen first', 'release notes for 1.4', 'make the swipe feel instant'],+ infra: ['rotate the staging certs', 'why did the deploy hang at 90%?', 'write the runbook for a failed migration', 'terraform drift report', 'no deploys this weekend'],+ 'ml-pipeline': ['freeze the eval set for this quarter', 'measure the ranker before and after', 'the tokenizer splits emoji now', 'backfill the features for September', 'plot the regression'],+ 'design-system': ['rename the color tokens by role', 'every action needs a keyboard shortcut', 'audit the icon set', 'make it feel like fzf', 'contrast check in light mode'],+ 'api-gateway': ['rate limit per key, not per IP', 'add the OpenAPI diff to CI', 'why is p99 latency up?', 'cache the auth lookups', 'one change per pull request'],+ cli: ['keep this out of the core', 'why did the daemon restart?', 'cut a release from main', 'comments should say why', 'merge it once CI is green'],+ firmware: ['flash the dial over USB', 'the knob skips steps when turned fast', 'update the pin map', 'measure the battery drain overnight', 'why does it reboot on wake?'],+ website: ['make the landing page load instantly', 'the launch copy is final, only typos', 'compress the hero video', 'add the pricing table', 'check it on a phone'],+ }++ function invented(now) {+ const random = rng(20261010)+ const pick = (list) => list[Math.floor(random() * list.length)]+ const home = '~'+ const slug = (title) => title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')+ const memories = NOTES.map(([agent, project, kind, type, title, description, body], i) => {+ const file = agent === 'claude' ? (kind === 'instructions' ? '~/.claude/CLAUDE.md' : `~/.claude/projects/-home-you-code-${project}/memory/${slug(title)}.md`)+ : agent === 'codex' ? (type === 'summary v1' ? '~/.codex/memories/memory_summary.md' : type === 'handbook v1' ? '~/.codex/memories/MEMORY.md' : `~/.codex/memories/${slug(title)}.md`)+ : agent === 'gemini' ? '~/.gemini/GEMINI.md' : agent === 'hermes' ? (kind === 'you' ? '~/.hermes/memories/USER.md' : '~/.hermes/memories/MEMORY.md')+ : agent === 'pi' ? '~/.pi/agent/AGENTS.md' : `~/.grok/memory-v2/global/topics/${slug(title)}.md`+ return {+ id: `${agent}:${file}#${i}`, agent, kind, type, scope: project ? 'project' : 'global',+ project: project ? { name: project, path: `~/code/${project}` } : null,+ title, description, body, path: file,+ modified: now - Math.floor(random() * 110 + 0.5) * DAY - Math.floor(random() * DAY), size: body.length,+ }+ })+ const asks = []+ const sessions = new Map()+ for (let day = 0; day < 120; day++) {+ const date = new Date(now - day * DAY)+ const weekend = date.getDay() === 0 || date.getDay() === 6+ const holiday = day >= 50 && day < 57+ const count = holiday ? 0 : weekend ? Math.floor(random() * 6) : 6 + Math.floor(random() * 22)+ for (let n = 0; n < count; n++) {+ const project = PROJECTS[Math.floor(Math.pow(random(), 1.6) * PROJECTS.length)]+ const engine = random() < 0.72 ? 'codex' : random() < 0.85 ? 'claude' : pick(['grok', 'hermes'])+ const sessionId = `s-${project}-${Math.floor(day / 5)}-${engine}`+ const at = now - day * DAY - Math.floor(random() * DAY * 0.6)+ const title = `${project}: ${pick(SAYINGS[project]).replace(/[?.,]+$/, '')}`+ if (!sessions.has(sessionId)) sessions.set(sessionId, { title, engine, cwd: `~/code/${project}`, lastAt: at, firstAt: at, asks: 0 })+ const session = sessions.get(sessionId)+ session.asks++; session.lastAt = Math.max(session.lastAt, at); session.firstAt = Math.min(session.firstAt, at)+ asks.push({ at, engine, cwd: session.cwd, title: session.title, sessionId, turn: session.asks - 1, text: pick(SAYINGS[project]), length: 40 })+ }+ }+ asks.sort((a, b) => b.at - a.at)+ const dayKey = (at) => { const d = new Date(at); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` }+ const activityMap = new Map()+ for (const ask of asks) { const key = `${dayKey(ask.at)} ${ask.engine}`; activityMap.set(key, (activityMap.get(key) ?? 0) + 1) }+ const activity = [...activityMap].map(([key, count]) => ({ day: key.split(' ')[0], engine: key.split(' ')[1], asks: count })).sort((a, b) => a.day.localeCompare(b.day))+ const engineRows = AGENTS.map(([id]) => id).map((engine) => {+ const own = [...sessions.values()].filter((s) => s.engine === engine)+ return { engine, sessions: own.length, asks: own.reduce((sum, s) => sum + s.asks, 0), lastAt: Math.max(0, ...own.map((s) => s.lastAt)), firstAt: Math.min(now, ...own.map((s) => s.firstAt)) }+ }).filter((row) => row.sessions)+ const folders = PROJECTS.map((project) => {+ const own = [...sessions.values()].filter((s) => s.cwd === `~/code/${project}`)+ const engines = {}+ for (const s of own) engines[s.engine] = (engines[s.engine] ?? 0) + 1+ return { cwd: `~/code/${project}`, sessions: own.length, asks: own.reduce((sum, s) => sum + s.asks, 0), lastAt: Math.max(0, ...own.map((s) => s.lastAt)), engines }+ })+ const projects = folders.map((folder) => {+ const name = folder.cwd.split('/').pop()+ return { key: `/home/you/code/${name}`, name, path: folder.cwd, memories: memories.filter((m) => m.project?.name === name).map((m) => m.id), sessions: folder.sessions, asks: folder.asks, engines: folder.engines, lastAt: folder.lastAt }+ })+ const lines = ABOUT.map(([section, text, refs]) => ({ section, text, refs }))+ const sections = [...new Set(lines.map((l) => l.section))]+ const aboutText = ['# About you', '', `Built from ${asks.length.toLocaleString('en-US')} of your messages over the last 120 days.`, '',+ ...sections.flatMap((section) => [`## ${section}`, ...lines.filter((l) => l.section === section).map((l) => `- ${l.text} [${l.refs.join(', ')}]`), ''])].join('\n')+ const agents = AGENTS.map(([id, name, color, present, memory, says]) => ({+ id, name, color, present, home: `~/.${id}`, memory, where: '', says,+ memories: memories.filter((m) => m.agent === id && m.kind !== 'instructions').length,+ instructions: memories.filter((m) => m.agent === id && m.kind === 'instructions').length,+ unreadable: id === 'windsurf' ? 3 : 0, sessions: engineRows.find((row) => row.engine === id)?.sessions ?? 0,+ }))+ const snapshot = {+ spec: 1, observedAt: now, memories, agents,+ about: { text: aboutText, modified: now - 3 * 3600_000, gen: now - 3 * 3600_000, intro: `Built from ${asks.length.toLocaleString('en-US')} of your messages over the last 120 days.`, lines },+ aboutPath: '~/.harness/memory/about-you.md',+ delivery: { on: true, choseOff: false, choiceAt: now - 5 * DAY, tokens: 412, built: true, agents: ['claude', 'codex', 'grok', 'gemini'].map((agent) => ({ agent, file: '', delivered: true, current: true })) },+ projects,+ sessions: { sessions: sessions.size, asks: asks.length, firstAt: Math.min(...asks.map((a) => a.at)), engines: engineRows, activity, folders },+ sessionsError: null, problems: [],+ machines: [+ { id: 'studio', name: 'studio', here: true, state: 'ok', memories: memories.length },+ { id: 'laptop', name: 'laptop', here: false, state: 'ok', memories: 14 },+ { id: 'build-box', name: 'build-box', here: false, state: 'offline' },+ ],+ }+ return { snapshot, asks, real: false }+ }++ // ── search and references ────────────────────────────────────────────────────────────────────────++ const words = (text) => String(text).toLowerCase().match(/[\p{L}\p{N}_]{2,}/gu) ?? []++ function inventedSearch(asks, q) {+ const terms = words(q)+ if (!terms.length) return []+ const seen = new Set()+ const hits = []+ for (const ask of asks) {+ const lower = ask.text.toLowerCase()+ if (!terms.every((term) => lower.includes(term)) || seen.has(ask.sessionId)) continue+ seen.add(ask.sessionId)+ let snippet = ask.text+ for (const term of terms) snippet = snippet.replace(new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), (m) => `\u0002${m}\u0003`)+ hits.push({ at: ask.at, engine: ask.engine, title: ask.title, cwd: ask.cwd, sessionId: ask.sessionId, turn: ask.turn, snippet })+ if (hits.length >= 24) break+ }+ return hits+ }++ /** The memory rows an About You line cites, e.g. "claude:short-answers.md" → that note. */+ function refs(line, snapshot) {+ const found = []+ for (const ref of line.refs ?? []) {+ const [agent, name] = ref.split(':')+ if (!name || agent === 'asks' || agent === 'session') continue+ const base = name.replace(/\.md$/, '')+ for (const row of snapshot.memories) {+ if (row.agent !== agent) continue+ const file = row.path.split('/').pop().replace(/\.md$/, '').replace(/#.*$/, '')+ const titled = row.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')+ if (file === base || titled === base) found.push(row)+ }+ }+ return [...new Set(found)]+ }++ function agent(id, snapshot) {+ const row = snapshot?.agents?.find((a) => a.id === id)+ return row ? { id, name: row.name, color: row.color } : { id, name: id, color: '#8b8f96' }+ }++ let loaded = null+ async function load() {+ if (loaded) return loaded+ if (!real) { loaded = invented(Date.now()); return loaded }+ const [snapshot, asks] = await Promise.all([+ fetch('/real/snapshot').then((r) => r.json()),+ fetch('/real/asks').then((r) => r.json()),+ ])+ loaded = { snapshot, asks: asks.asks ?? [], real: true }+ return loaded+ }++ async function search(q) {+ if (!String(q).trim()) return []+ if (!real) return inventedSearch((await load()).asks, q)+ const answer = await fetch(`/real/search?q=${encodeURIComponent(q)}`).then((r) => r.json())+ return answer.hits ?? []+ }++ window.MemoryData = { load, search, refs, agent, real, DAY }+})()diff --git a/docs/research/2026-10-10-memory-brain/palace-recall.jpg b/docs/research/2026-10-10-memory-brain/palace-recall.jpgnew file mode 100644index 000000000..3464e9332Binary files /dev/null and b/docs/research/2026-10-10-memory-brain/palace-recall.jpg differdiff --git a/docs/research/2026-10-10-memory-brain/palace.html b/docs/research/2026-10-10-memory-brain/palace.htmlnew file mode 100644index 000000000..bb6ddfe73--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/palace.html@@ -0,0 +1,82 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Mind Palace</title>+<style>+ :root {+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ --fg: #cfe6f1;+ --dim: #6b8592;+ --faint: #3a4d58;+ --cyan: #5ad7ff;+ --gold: #ffc982;+ --ink: #d8e7ee;+ }+ html, body { margin: 0; height: 100%; background: #000; color: var(--fg); font-family: var(--mono); overflow: hidden; }+ canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; outline: none; }+ #hud { pointer-events: none; }+ .quiet { position: fixed; pointer-events: none; font-size: 11px; letter-spacing: 0.02em; color: var(--dim); white-space: nowrap; }+ #where { top: 14px; left: 16px; color: #9cc3d3; font-size: 12px; text-shadow: 0 0 8px rgba(90, 215, 255, 0.35); }+ #where b { font-weight: 500; color: #e6f6ff; }+ #mode { top: 32px; left: 16px; color: var(--faint); }+ #keys { left: 0; right: 0; bottom: 12px; text-align: center; overflow: hidden; text-overflow: ellipsis; padding: 0 16px; }+ #keys kbd { font-family: var(--mono); color: #9fbccb; }+ #prompt { left: 0; right: 0; bottom: 36px; text-align: center; font-size: 14px; color: #eaf8ff; text-shadow: 0 0 10px rgba(90, 215, 255, 0.6); }+ #prompt .count { color: var(--dim); font-size: 11px; text-shadow: none; margin-left: 14px; }+ #prompt .caret { display: inline-block; width: 0.55em; height: 1.05em; vertical-align: -0.18em; background: #bff0ff; margin-left: 1px; animation: blink 1s steps(2, start) infinite; box-shadow: 0 0 8px rgba(90, 215, 255, 0.8); }+ @keyframes blink { to { visibility: hidden; } }+ #loading { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--dim); font-size: 12px; letter-spacing: 0.2em; }+ #loading::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--cyan); margin-right: 12px; box-shadow: 0 0 12px var(--cyan); animation: pulse 1.2s ease-in-out infinite; }+ @keyframes pulse { 50% { opacity: 0.2; } }++ #read { position: fixed; inset: 0; display: flex; justify-content: center; align-items: center;+ background: radial-gradient(ellipse at 50% 40%, rgba(2, 14, 22, 0.80), rgba(0, 0, 0, 0.93)); }+ #read[hidden] { display: none; }+ #sheet { --accent: #5ad7ff; position: relative; box-sizing: border-box; width: min(88ch, calc(100vw - 48px)); max-height: calc(100vh - 72px); margin: 0 0 18px;+ overflow: auto; padding: 26px 32px 30px; border: 1px solid color-mix(in srgb, var(--accent) 55%, transparent);+ background: linear-gradient(180deg, rgba(4, 14, 20, 0.92), rgba(1, 5, 8, 0.96));+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.6), 0 0 28px color-mix(in srgb, var(--accent) 30%, transparent), inset 0 0 40px color-mix(in srgb, var(--accent) 7%, transparent);+ transform-origin: 0 0; scrollbar-width: thin; scrollbar-color: #24414f transparent; }+ #sheet.fly { transition: transform 420ms cubic-bezier(0.2, 0.8, 0.2, 1), opacity 300ms ease-out; }+ #r-kicker { font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--accent); opacity: 0.9; }+ #r-title { margin: 10px 0 6px; font-size: 22px; line-height: 1.3; color: #f2fbff; text-shadow: 0 0 14px color-mix(in srgb, var(--accent) 60%, transparent); }+ #r-meta { font-size: 11.5px; color: var(--dim); line-height: 1.6; }+ #r-meta span + span::before { content: " · "; color: var(--faint); }+ #r-links { margin: 16px 0 4px; }+ #r-links:empty { display: none; }+ #r-links .head { font-size: 10.5px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--faint); margin: 12px 0 6px; }+ #r-links .link { font-size: 12.5px; color: #a9c4d1; padding: 5px 10px; margin: 2px -10px; border-left: 2px solid transparent; line-height: 1.45; }+ #r-links .link .dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 9px; vertical-align: 1px; }+ #r-links .link.on { color: #fff; background: rgba(90, 215, 255, 0.08); border-left-color: var(--accent); }+ #r-links .link .sub { color: var(--dim); }+ #r-links .line { font-size: 13.5px; color: #e9dcc6; margin: 10px 0 2px; line-height: 1.5; }+ #r-body { margin-top: 18px; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13.5px; line-height: 1.62; color: var(--ink);+ text-shadow: 0 0 7px color-mix(in srgb, var(--accent) 22%, transparent); }+ #r-body:empty { display: none; }+ #r-foot { margin-top: 18px; font-size: 10.5px; color: var(--faint); overflow-wrap: anywhere; }+</style>+</head>+<body>+<canvas id="gl" tabindex="0" aria-label="Mind Palace: walk through your memories"></canvas>+<canvas id="hud" aria-hidden="true"></canvas>+<div id="where" class="quiet"></div>+<div id="mode" class="quiet"></div>+<div id="prompt" class="quiet" aria-live="polite"></div>+<div id="keys" class="quiet"></div>+<div id="read" hidden>+ <div id="sheet" role="dialog" aria-modal="true">+ <div id="r-kicker"></div>+ <div id="r-title"></div>+ <div id="r-meta"></div>+ <div id="r-links"></div>+ <div id="r-body"></div>+ <div id="r-foot"></div>+ </div>+</div>+<div id="loading">remembering</div>+<script src="memory-data.js"></script>+<script src="palace.js"></script>+</body>+</html>diff --git a/docs/research/2026-10-10-memory-brain/palace.jpg b/docs/research/2026-10-10-memory-brain/palace.jpgnew file mode 100644index 000000000..469d968ddBinary files /dev/null and b/docs/research/2026-10-10-memory-brain/palace.jpg differdiff --git a/docs/research/2026-10-10-memory-brain/palace.js b/docs/research/2026-10-10-memory-brain/palace.jsnew file mode 100644index 000000000..c60bfdbba--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/palace.js@@ -0,0 +1,2252 @@+/*+ * Mind Palace: the method of loci, walked in first person and drawn as glowing vector lines.+ *+ * About You is carved into a circle of standing stones at the centre (you stand inside it). Corridors lead+ * out to wings, one per project, brighter where you work most and longer the longer you have been away.+ * Rooms hold the memories as plaques coloured by agent; old ones gather dust and lose letters at the edges.+ * Type, and your words float up around you while matching memories fly out of their rooms toward you.+ *+ * Data comes only from MemoryData (memory-data.js). Memory text is untrusted: it is drawn as glyph quads+ * from an atlas made with fillText, or set with textContent. Nothing is written anywhere.+ */+(function () {+ 'use strict'++ // ── small things ─────────────────────────────────────────────────────────────────────────────────++ const TAU = Math.PI * 2, DEG = Math.PI / 180, DAY = 86_400_000+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches+ const $ = (id) => document.getElementById(id)+ const clamp = (x, a, b) => (x < a ? a : x > b ? b : x)+ const lerp = (a, b, t) => a + (b - a) * t+ const lerp3 = (a, b, t) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]+ const sstep = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t) }+ const smoother = (t) => { t = clamp(t, 0, 1); return t * t * t * (t * (t * 6 - 15) + 10) }+ const easeOut = (t) => 1 - Math.pow(1 - clamp(t, 0, 1), 3)+ const angWrap = (a) => { a = (a + Math.PI) % TAU; if (a < 0) a += TAU; return a - Math.PI }+ const angLerp = (a, b, t) => a + angWrap(b - a) * t+ function hash3(a, b, c) {+ let h = Math.imul(a | 0, 374761393) ^ Math.imul((b | 0) + 7, 668265263) ^ Math.imul((c | 0) + 13, 1440662683)+ h = Math.imul(h ^ (h >>> 13), 1274126177); h ^= h >>> 16+ return (h >>> 0) / 4294967296+ }+ function rng(seed) {+ let s = seed >>> 0+ return () => { s = (s + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296 }+ }+ function strSeed(s) { let h = 2166136261; s = String(s); for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0 }++ function hexRGB(c) {+ const m = /^#?([0-9a-f]{6})$/i.exec(String(c ?? '').trim())+ if (!m) return [0.62, 0.66, 0.72]+ const n = parseInt(m[1], 16)+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]+ }+ function lift(c, min = 0.66) { const mx = Math.max(c[0], c[1], c[2], 0.01); const k = mx < min ? min / mx : 1; return [Math.min(1, c[0] * k), Math.min(1, c[1] * k), Math.min(1, c[2] * k)] }+ const mixc = (a, b, t) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]+ const css = (c, a = 1) => `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${a})`+ const COL = {+ struct: [0.32, 0.78, 1.0], self: [1.0, 0.75, 0.44], words: [0.74, 0.66, 1.0], label: [0.84, 0.95, 1.0],+ path: [1.0, 0.3, 0.68], type: [0.9, 0.97, 1.0], dust: [0.62, 0.66, 0.72], white: [1, 1, 1], ink: [0.86, 0.92, 0.95],+ }++ const fmt = (n) => Number(n || 0).toLocaleString('en-US')+ function ago(at, now = Date.now()) {+ if (!at) return 'never'+ const s = Math.max(0, now - at) / 1000+ if (s < 90) return 'just now'+ const m = s / 60; if (m < 60) return `${Math.round(m)} min ago`+ const h = m / 60; if (h < 24) return `${Math.round(h)} h ago`+ const d = h / 24; if (d < 1.8) return 'yesterday'+ if (d < 14) return `${Math.round(d)} days ago`+ if (d < 60) return `${Math.round(d / 7)} weeks ago`+ if (d < 365) return `${Math.round(d / 30.4)} months ago`+ return `${(d / 365).toFixed(1)} years ago`+ }+ const dateOf = (at) => (at ? new Date(at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '')+ const shortDate = (at) => (at ? new Date(at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '')+ const timeOf = (at) => (at ? new Date(at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }) : '')+ function middle(s, n) { s = String(s); if (s.length <= n) return s; const a = Math.ceil((n - 1) * 0.55); return s.slice(0, a) + '…' + s.slice(s.length - (n - 1 - a)) }+ function tail(p, n = 46) { p = String(p || ''); return p.length <= n ? p : '…' + p.slice(p.length - n + 1) }++ // ── text ─────────────────────────────────────────────────────────────────────────────────────────++ const CTRL = /[\u0000\u0001\u0004-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/g+ const clean = (s) => String(s ?? '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').replace(CTRL, '')+ const oneLine = (s) => clean(s).replace(/[\u0002\u0003]/g, '').replace(/\s+/g, ' ').trim()+ function plain(md) {+ let s = clean(md).replace(/[\u0002\u0003]/g, '')+ s = s.replace(/^```.*$/gm, '').replace(/^#{1,6}\s+/gm, '').replace(/\*\*(.+?)\*\*/g, '$1').replace(/__(.+?)__/g, '$1')+ s = s.replace(/`([^`\n]+)`/g, '$1').replace(/!?\[([^\]\n]*)\]\([^)\n]*\)/g, '$1').replace(/^\s*[-*+]\s+/gm, '· ').replace(/^\s*>\s?/gm, '')+ s = s.replace(/^\s*\|?[-:| ]{3,}\|?\s*$/gm, '').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n')+ return s.trim()+ }+ const toChars = (s, col, a) => Array.from(String(s), (ch) => ({ ch, col, a }))+ function marked(s, col, hiCol, a = 1, hiA = 1) {+ const out = []; let hi = false+ for (const ch of Array.from(clean(s).replace(/\s+/g, ' '))) {+ if (ch === '\u0002') { hi = true; continue }+ if (ch === '\u0003') { hi = false; continue }+ out.push(hi ? { ch, col: hiCol, a: hiA, hi: true } : { ch, col, a })+ }+ return out+ }+ /** Word wrap an array of {ch} into rows of at most `cols`; the last row ends in … when cut. */+ function wrapChars(cs, cols, maxRows = 99) {+ const rows = []; let row = []+ const push = () => { while (row.length && row[row.length - 1].ch === ' ') row.pop(); rows.push(row); row = [] }+ let i = 0, cut = false+ while (i < cs.length) {+ if (rows.length > maxRows) { cut = true; break }+ if (cs[i].ch === '\n') { push(); i++; continue }+ let j = i; while (j < cs.length && cs[j].ch !== ' ' && cs[j].ch !== '\n') j+++ let word = cs.slice(i, j)+ if (word.length) {+ if (row.length && row.length + word.length > cols) push()+ while (word.length > cols) { if (row.length) push(); rows.push(word.slice(0, cols)); word = word.slice(cols) }+ row.push(...word)+ }+ while (j < cs.length && cs[j].ch === ' ') { if (row.length && row.length < cols) row.push(cs[j]); j++ }+ i = j+ }+ if (row.length) push()+ while (rows.length && !rows[rows.length - 1].length) rows.pop()+ // collapse runs of blank rows+ const out = []+ for (const r of rows) if (r.length || (out.length && out[out.length - 1].length)) out.push(r)+ if (out.length > maxRows || cut) {+ out.length = Math.min(out.length, maxRows)+ const last = out[out.length - 1] || []+ while (last.length > cols - 1) last.pop()+ while (last.length && last[last.length - 1].ch === ' ') last.pop()+ const ref = last[last.length - 1] || cs.find((x) => x.col) || {}+ last.push({ ch: '…', col: ref.col, a: ref.a })+ out[out.length - 1] = last+ }+ return out+ }+ const words = (q) => String(q).toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []++ // ── glyph atlas: every character is drawn once with fillText, then used as a textured quad ───────++ const Atlas = (() => {+ const SIZE = 2048, EM = 58, PAD = 7+ const FONT = `500 ${EM}px ui-monospace, "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, monospace`+ const cv = document.createElement('canvas'); cv.width = cv.height = SIZE+ const ctx = cv.getContext('2d')+ ctx.font = FONT+ const adv = ctx.measureText('M').width+ const m = ctx.measureText('Mgjy|')+ const asc = m.fontBoundingBoxAscent || EM * 0.95, desc = m.fontBoundingBoxDescent || EM * 0.26+ const cellW = Math.ceil(adv) + PAD * 2, cellH = Math.ceil(asc + desc) + PAD * 2+ const cols = Math.floor(SIZE / cellW), rows = Math.floor(SIZE / cellH)+ const map = new Map()+ let cx = 0, cy = 0+ const alloc = (span) => { if (cx + span > cols) { cx = 0; cy++ } if (cy >= rows) return null; const at = [cx, cy]; cx += span; return at }+ ctx.fillStyle = '#fff'; ctx.textBaseline = 'alphabetic'+ const s0 = alloc(1)+ ctx.fillRect(s0[0] * cellW + 2, s0[1] * cellH + 2, cellW - 4, cellH - 4)+ const solid = { u0: (s0[0] * cellW + PAD) / SIZE, v0: (s0[1] * cellH + PAD) / SIZE, u1: (s0[0] * cellW + cellW - PAD) / SIZE, v1: (s0[1] * cellH + cellH - PAD) / SIZE }+ const A = { canvas: cv, solid, dirty: true, advEm: adv / EM, padEm: PAD / EM, hEm: cellH / EM, cellEm: cellW / EM }+ A.get = function (ch) {+ let g = map.get(ch)+ if (g) return g+ ctx.font = FONT+ const w = ctx.measureText(ch).width+ const span = w > adv * 1.45 ? 2 : 1+ const at = alloc(span)+ if (!at) { g = map.get('?') || A.get('?'); map.set(ch, g); return g }+ const x = at[0] * cellW, y = at[1] * cellH+ ctx.save(); ctx.beginPath(); ctx.rect(x, y, cellW * span, cellH); ctx.clip()+ ctx.fillText(ch, x + PAD + Math.max(0, (adv * span - w) / 2), y + PAD + asc)+ ctx.restore()+ g = { u0: x / SIZE, v0: y / SIZE, u1: (x + cellW * span) / SIZE, v1: (y + cellH) / SIZE, span, wEm: (cellW * span) / EM }+ map.set(ch, g)+ A.dirty = true+ return g+ }+ for (let c = 32; c < 127; c++) A.get(String.fromCharCode(c))+ for (const ch of '·…—–’‘“”•◆◇▸›‹→←↑↓↵⌫§¶°×±') A.get(ch)+ return A+ })()++ // ── matrices ─────────────────────────────────────────────────────────────────────────────────────++ function perspective(o, fovy, asp, n, f) {+ const t = 1 / Math.tan(fovy / 2), nf = 1 / (n - f)+ o.fill(0); o[0] = t / asp; o[5] = t; o[10] = (f + n) * nf; o[11] = -1; o[14] = 2 * f * n * nf+ return o+ }+ function lookAt(o, e, c, up) {+ let zx = e[0] - c[0], zy = e[1] - c[1], zz = e[2] - c[2]+ let l = Math.hypot(zx, zy, zz); zx /= l; zy /= l; zz /= l+ let xx = up[1] * zz - up[2] * zy, xy = up[2] * zx - up[0] * zz, xz = up[0] * zy - up[1] * zx+ l = Math.hypot(xx, xy, xz); xx /= l; xy /= l; xz /= l+ const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx+ o[0] = xx; o[1] = yx; o[2] = zx; o[3] = 0+ o[4] = xy; o[5] = yy; o[6] = zy; o[7] = 0+ o[8] = xz; o[9] = yz; o[10] = zz; o[11] = 0+ o[12] = -(xx * e[0] + xy * e[1] + xz * e[2]); o[13] = -(yx * e[0] + yy * e[1] + yz * e[2]); o[14] = -(zx * e[0] + zy * e[1] + zz * e[2]); o[15] = 1+ return o+ }+ function mul(o, a, b) {+ for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) { let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + j] * b[i * 4 + k]; o[i * 4 + j] = s }+ return o+ }++ // ── geometry: lines, glyph quads and black fills, kept as flat float arrays ──────────────────────++ const EYE = 1.6+ const CWH = 1.6, CH = 4.0, OPEN_H = 3.3 // corridor half width and height; door opening height+ const OCT_A = 4.2, OCT_R = OCT_A / Math.cos(Math.PI / 8), RD = 2 * OCT_A, RH = 4.8 // octagonal chambers: apothem, corner radius, length, height+ const OCT_HALF = OCT_A * Math.tan(Math.PI / 8) // half a side+ const PLAQUE_SIDES = [7, 1, 6, 2, 5, 3] // front diagonals first: what you see as you come in+ const FH = 2.7 // half width of a door's facade on the atrium wall+ const R_STONE = 5.4, H_ATRIUM = 6.6+ const PW = 2.7, PH = 2.7 // a plaque+ const SLOTS = PLAQUE_SIDES+ /** Old memories decay: nothing for ten days, then slowly over five months. */+ const decayOf = (at, now) => (at ? Math.pow(clamp((Math.max(0, now - at) / DAY - 10) / 150, 0, 1), 0.85) : 0.8)+ const LINE_F = 16, GLYPH_F = 13, FILL_F = 8++ let LN = [], GLY = [], FL = [], WALLS = [], MAPSEG = [], INTER = []++ const birthAt = (x, z) => 0.4 + Math.min(4.0, Math.pow(Math.hypot(x, z), 0.86) * 0.1)++ function seg(a, b, col, alpha, w = 1.3, birth = null, obj = 0, fx = 0, out = LN) {+ if (out === LN && Math.hypot(a[0], a[2]) > Math.hypot(b[0], b[2])) { const t = a; a = b; b = t }+ if (birth == null) birth = birthAt(a[0], a[2])+ for (let k = 0; k < 4; k++) out.push(a[0], a[1], a[2], b[0], b[1], b[2], k & 1 ? 1 : -1, k >> 1, col[0], col[1], col[2], alpha, w, birth, obj, fx)+ }+ function segs(a, b, col, alpha, w, birth, obj, fx, max = 3) {+ const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) / max))+ for (let i = 0; i < n; i++) seg(lerp3(a, b, i / n), lerp3(a, b, (i + 1) / n), col, alpha, w, birth == null ? null : birth + i * 0.02, obj, fx)+ }+ function poly(pts, closed, col, alpha, w, birth, obj, fx) {+ const n = pts.length - (closed ? 0 : 1)+ for (let i = 0; i < n; i++) seg(pts[i], pts[(i + 1) % pts.length], col, alpha, w, birth == null ? null : birth + i * 0.01, obj, fx)+ }+ function fill(tl, tr, bl, br, top, bot = top, birth = null) {+ if (birth == null) birth = birthAt((tl[0] + br[0]) / 2, (tl[2] + br[2]) / 2)+ for (const [p, c] of [[tl, top], [tr, top], [bl, bot], [br, bot]]) FL.push(p[0], p[1], p[2], c[0], c[1], c[2], 1, birth)+ }+ function wall(ax, az, bx, bz, kind = 'wall', wing = -1) { WALLS.push([ax, az, bx, bz]); MAPSEG.push([ax, az, bx, bz, kind, wing]) }++ /** One glyph quad. x, y are in em units inside a text block whose top left is o; r, u span the plane. */+ function glyph(out, ch, o, r, u, x, y, e, col, a, birth, obj, fx, occ) {+ const g = Atlas.get(ch)+ const x0 = (x - Atlas.padEm) * e, y0 = (y - Atlas.padEm) * e, w = g.wEm * e, h = Atlas.hEm * e+ for (let k = 0; k < 4; k++) {+ const dx = x0 + (k & 1 ? w : 0), dy = y0 + (k >> 1 ? h : 0)+ out.push(o[0] + r[0] * dx - u[0] * dy, o[1] + r[1] * dx - u[1] * dy, o[2] + r[2] * dx - u[2] * dy,+ k & 1 ? g.u1 : g.u0, k >> 1 ? g.v1 : g.v0, col[0], col[1], col[2], a, birth, obj, fx, occ)+ }+ }+ function solidQuad(out, tl, tr, bl, br, col, a, occ = 1) {+ const s = Atlas.solid+ const P = [tl, tr, bl, br]+ for (let k = 0; k < 4; k++) { const p = P[k]; out.push(p[0], p[1], p[2], k & 1 ? s.u1 : s.u0, k >> 1 ? s.v1 : s.v0, col[0], col[1], col[2], a, -1, 0, 0, occ) }+ }+ /**+ * Rows of {ch, col, a} from the top-left o. Old text (decay > 0) loses letters toward the edges of the+ * block, and the ones about to go sag a little: Eternal Sunshine, one plaque at a time.+ */+ function emit(out, rows, o, r, u, opt) {+ const e = opt.em, lh = opt.lh ?? 1.3, adv = Atlas.advEm+ const cols = opt.cols ?? Math.max(1, ...rows.map((row) => row.length))+ const decay = opt.decay ?? 0, seed = opt.seed ?? 1, nRows = opt.rowsTotal ?? rows.length, row0 = opt.row0 ?? 0+ const spread = opt.spread ?? 1.2+ let n = 0+ for (let ri = 0; ri < rows.length; ri++) {+ let c = 0+ for (const g of rows[ri]) {+ const ch = g.ch+ const span = ch.charCodeAt(0) < 128 ? 1 : Atlas.get(ch).span+ if (ch !== ' ') {+ let alpha = (g.a ?? opt.alpha ?? 1), dy = 0+ if (decay > 0.03) {+ const uu = cols > 1 ? c / (cols - 1) : 0.5+ const vv = nRows > 1 ? (ri + row0) / (nRows - 1) : 0.5+ const edge = Math.max(Math.abs(uu * 2 - 1), Math.abs(vv * 2 - 1) * 0.5)+ const rnd = hash3(seed, ri + row0, c)+ const lose = decay < 0.15 ? 0 : Math.pow(decay, 1.7) * (sstep(0.55, 1.0, edge) * 1.3 + 0.02)+ if (rnd < lose) { c += span; continue }+ if (rnd < lose * 1.7) dy = ((lose * 1.7 - rnd) / (lose * 0.7 + 1e-4)) * 0.22 * decay+ alpha *= (1 - 0.45 * decay) * (1 - 0.45 * edge * decay)+ }+ const birth = (opt.birth ?? 0) + Math.min(spread, n * (opt.step ?? 0))+ glyph(out, ch, o, r, u, c * adv, ri * lh + dy, e, g.col ?? opt.color ?? COL.ink, alpha, birth, opt.obj ?? 0, opt.fx ?? 0, opt.occ ?? 0)+ n+++ }+ c += span+ }+ }+ return rows.length * lh * e+ }+ const at3 = (o, r, u, x, y) => [o[0] + r[0] * x + u[0] * y, o[1] + r[1] * x + u[1] * y, o[2] + r[2] * x + u[2] * y]+ const colsFor = (width, em) => Math.max(4, Math.floor(width / (em * Atlas.advEm)))++ // ── the palace, built from the snapshot ──────────────────────────────────────────────────────────++ const KIND_ORDER = ['you', 'project', 'reference', 'note', 'summary', 'instructions']+ const KIND_TITLE = { you: 'how you want it', project: 'the work', reference: 'where things are', note: 'notes', summary: 'what they keep', instructions: 'what you told it' }++ function cleanAsk(t) {+ let s = oneLine(t)+ s = s.replace(/^(\[(Image|Pasted text|File)[^\]]*\]\s*)+/i, '').replace(/^\/goal\s+/i, '').trim()+ return s+ }+ const usefulAsk = (s) => s.length >= 14 && !/^[<{[]/.test(s) && !/^(continue|continuing|ok|okay|yes|no|thanks|thank you|hi|hello)\b.{0,12}$/i.test(s)++ let WORLD = null++ function buildWorld(data) {+ LN = []; GLY = []; FL = []; WALLS = []; MAPSEG = []; INTER = []+ const NOW = Date.now()+ const snap = data.snapshot || {}+ const memories = (Array.isArray(snap.memories) ? snap.memories : []).filter((m) => m && m.id)+ const agentOf = (id) => MemoryData.agent(id, snap)+ const W = { NOW, snap, data, agentOf, memInter: new Map(), stones: [], inscriptions: new Map(), reverse: new Map() }++ // About You: one standing stone per section+ const sections = []+ for (const line of snap.about?.lines ?? []) {+ if (!line || !line.text) continue+ let s = sections.find((x) => x.name === (line.section || 'About you'))+ if (!s) sections.push((s = { name: line.section || 'About you', lines: [] }))+ s.lines.push({ ...line, mems: MemoryData.refs(line, snap) })+ }+ if (!sections.length) sections.push({ name: 'About you', empty: true, lines: [{ text: 'Nothing here yet. About You writes itself from your messages as you work.', refs: [], mems: [] }] })+ sections.forEach((sec, k) => sec.lines.forEach((line, li) => line.mems.forEach((m) => {+ if (!W.reverse.has(m.id)) W.reverse.set(m.id, [])+ W.reverse.get(m.id).push({ k, li, text: line.text, section: sec.name })+ })))+ W.sections = sections++ // wings: projects by activity, then the halls+ const byId = new Map(memories.map((m) => [m.id, m]))+ const placed = new Set()+ const projects = []+ for (const p of snap.projects ?? []) {+ const mems = (p.memories ?? []).map((id) => byId.get(id)).filter((m) => m && !placed.has(m.id))+ mems.forEach((m) => placed.add(m.id))+ projects.push({ kind: 'project', key: 'p:' + (p.key || p.name), name: p.name || 'project', path: p.path || '', mems, asks: [], sessions: p.sessions || 0, askCount: p.asks || 0, lastAt: p.lastAt || 0 })+ }+ for (const m of memories) {+ if (placed.has(m.id) || !m.project) continue+ let w = projects.find((x) => x.name === m.project.name)+ if (!w) projects.push((w = { kind: 'project', key: 'p:' + m.project.name, name: m.project.name || 'project', path: m.project.path || '', mems: [], asks: [], sessions: 0, askCount: 0, lastAt: 0 }))+ w.mems.push(m); placed.add(m.id)+ }+ const asks = (data.asks ?? []).filter((a) => a && a.text)+ const loose = []+ for (const a of asks) {+ const cwd = String(a.cwd || '')+ const w = cwd && projects.find((p) => (p.path && (cwd === p.path || cwd.startsWith(p.path + '/'))) ||+ (p.name.length >= 4 && (cwd.endsWith('/' + p.name) || cwd.includes('/' + p.name + '/'))))+ if (w) w.asks.push(a); else loose.push(a)+ }+ const newest = (w) => Math.max(w.lastAt || 0, ...w.mems.map((m) => m.modified || 0), ...w.asks.slice(0, 1).map((a) => a.at || 0))+ const score = (w) => w.askCount + w.sessions * 6 + w.asks.length+ projects.sort((a, b) => score(b) - score(a) || b.mems.length - a.mems.length || newest(b) - newest(a))+ if (projects.length > 16) {+ const rest = projects.splice(15)+ projects.push({ kind: 'project', groupBy: 'project', key: 'p:elsewhere', name: `${rest.length} more projects`, path: '', mems: rest.flatMap((w) => w.mems), asks: rest.flatMap((w) => w.asks), sessions: rest.reduce((s, w) => s + w.sessions, 0), askCount: rest.reduce((s, w) => s + w.askCount, 0), lastAt: Math.max(0, ...rest.map((w) => w.lastAt)) })+ }+ const globalNotes = memories.filter((m) => !placed.has(m.id) && m.kind !== 'instructions')+ const told = memories.filter((m) => !placed.has(m.id) && m.kind === 'instructions')+ const halls = []+ if (globalNotes.length) halls.push({ kind: 'notes', key: 'h:notes', name: "agents' notes", mems: globalNotes, asks: [], sessions: 0, askCount: 0, lastAt: 0 })+ const said = pickWords(loose.length >= 12 ? loose : asks, NOW)+ if (said.length) halls.push({ kind: 'words', key: 'h:words', name: 'your words', mems: [], asks: [], wordRooms: said, sessions: 0, askCount: 0, lastAt: (loose[0] || asks[0])?.at || 0 })+ if (told.length) halls.push({ kind: 'told', key: 'h:told', name: 'what you told them', mems: told, asks: [], sessions: 0, askCount: 0, lastAt: 0 })+ const wings = [...projects, ...halls]++ const maxScore = Math.max(1, ...projects.map(score))+ for (const w of wings) {+ w.label = middle(w.name, 28)+ w.rooms = roomsFor(w, agentOf)+ const last = newest(w) || Math.max(0, ...(w.wordRooms ?? []).flatMap((r) => r.items.map((it) => it.a.at || 0)))+ w.last = last+ const days = last ? Math.max(0, NOW - last) / DAY : 365+ w.staleF = clamp(Math.log1p(days) / Math.log1p(120), 0, 1)+ w.act = w.kind === 'project'+ ? (score(w) > 0 ? 0.18 + 0.82 * Math.log1p(score(w)) / Math.log1p(maxScore) : 0.12 + 0.2 * Math.min(1, w.mems.length / 10))+ : 0.45 + 0.35 * (1 - w.staleF)+ }++ // the plan: n spokes around a round atrium+ const K = sections.length, n = wings.length+ const R = n ? Math.max(13.5, FH / Math.sin((Math.PI / Math.max(n, 3)) * 0.82)) : 13.5+ const sMin = n >= 3 ? OCT_R / Math.tan(Math.PI / n) + 1.8 : 18+ W.R = R; W.K = K; W.wings = wings+ wings.forEach((w, i) => {+ w.i = i+ w.theta = Math.PI / Math.max(K, 1) + (i * TAU) / Math.max(n, 1)+ w.d = [Math.sin(w.theta), -Math.cos(w.theta)]+ w.r = [Math.cos(w.theta), Math.sin(w.theta)]+ w.alpha = Math.asin(FH / R)+ w.s0 = R * Math.cos(w.alpha)+ w.s1 = Math.max(w.s0 + 7 + 21 * w.staleF, sMin)+ w.sEnd = w.s1 + RD * w.rooms.length+ })+ W.alpha = Math.asin(FH / R)+ WORLD = W++ buildAtrium(W)+ for (const w of wings) buildWing(W, w)+ let maxR = R+ for (const w of wings) maxR = Math.max(maxR, w.sEnd + 2)+ W.extent = maxR+ const xs = MAPSEG.flatMap((m) => [m[0], m[2]]), zs = MAPSEG.flatMap((m) => [m[1], m[3]])+ W.bounds = { x0: Math.min(...xs, -R) - 3, x1: Math.max(...xs, R) + 3, z0: Math.min(...zs, -R) - 3, z1: Math.max(...zs, R) + 3 }+ return W+ }++ function roomsFor(w, agentOf) {+ if (w.kind === 'words') return w.wordRooms+ const groups = new Map()+ const keyOf = w.kind === 'notes' ? (m) => m.agent : w.groupBy === 'project' ? (m) => m.project?.name || 'elsewhere' : (m) => (KIND_ORDER.includes(m.kind) ? m.kind : m.kind || 'note')+ for (const m of w.mems) { const k = keyOf(m); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(m) }+ let keys = [...groups.keys()]+ if (w.kind === 'project' && w.groupBy !== 'project') keys.sort((a, b) => (KIND_ORDER.indexOf(a) + 99 * (KIND_ORDER.indexOf(a) < 0)) - (KIND_ORDER.indexOf(b) + 99 * (KIND_ORDER.indexOf(b) < 0)))+ else keys.sort((a, b) => groups.get(b).length - groups.get(a).length)+ const rooms = []+ for (const k of keys) {+ const list = groups.get(k).sort((a, b) => (b.modified || 0) - (a.modified || 0))+ const title = w.kind === 'notes' ? agentOf(k).name : w.kind === 'told' ? 'the rules' : w.groupBy === 'project' ? middle(k, 22) : (KIND_TITLE[k] || k)+ const parts = Math.ceil(list.length / SLOTS.length)+ for (let p = 0; p < parts; p++) rooms.push({ title, part: p + 1, parts, items: list.slice(p * SLOTS.length, (p + 1) * SLOTS.length).map((m) => ({ type: 'memory', m })) })+ }+ if (!rooms.length) rooms.push({ title: 'empty', part: 1, parts: 1, items: [] })+ return rooms+ }++ /** Your own words, by time: today, yesterday, this week… each room a stretch of time. */+ function pickWords(list, now) {+ const seen = new Set(), picked = []+ for (const a of list) {+ const text = cleanAsk(a.text)+ if (!usefulAsk(text)) continue+ const key = text.toLowerCase().slice(0, 60)+ if (seen.has(key)) continue+ seen.add(key); picked.push({ a, text })+ }+ picked.sort((x, y) => (y.a.at || 0) - (x.a.at || 0))+ const startOf = (at) => { const d = new Date(at); d.setHours(0, 0, 0, 0); return d.getTime() }+ const today0 = startOf(now)+ const bucketOf = (at) => {+ const back = Math.round((today0 - startOf(at)) / DAY)+ if (back <= 0) return 'today'+ if (back === 1) return 'yesterday'+ if (back < 7) return 'this week'+ if (back < 14) return 'last week'+ if (back < 31) return 'this month'+ return new Date(at).toLocaleDateString('en-US', { month: 'long', year: 'numeric' }).toLowerCase()+ }+ const buckets = new Map()+ for (const it of picked) { const b = bucketOf(it.a.at || now); if (!buckets.has(b)) buckets.set(b, []); buckets.get(b).push(it) }+ const rooms = []+ for (const [title, items] of buckets) {+ const pick = []+ const step = items.length / SLOTS.length+ for (let i = 0; i < Math.min(SLOTS.length, items.length); i++) pick.push(items[Math.floor(i * Math.max(1, step))])+ rooms.push({ title, part: 1, parts: 1, said: items.length, items: pick.map((it) => ({ type: 'ask', a: it.a, text: it.text })) })+ if (rooms.length >= 8) break+ }+ return rooms+ }++ const polar = (r, a, y = 0) => [r * Math.sin(a), y, -r * Math.cos(a)]+ const WP = (w, s, t, y) => [s * w.d[0] + t * w.r[0], y, s * w.d[1] + t * w.r[1]]++ const FILL = {+ wallTop: [0.004, 0.011, 0.017], wallBot: [0.016, 0.036, 0.05], floor: [0.006, 0.016, 0.024], ceil: [0.002, 0.005, 0.008],+ stone: [0.03, 0.022, 0.013], stoneTop: [0.012, 0.009, 0.006],+ }++ function buildAtrium(W) {+ const { R, K, wings } = W+ const rand = rng(7)+ // floor+ const steps = 96+ for (let i = 0; i < steps; i++) {+ const a0 = (i / steps) * TAU, a1 = ((i + 1) / steps) * TAU+ for (const [r0, r1] of [[0, R * 0.5], [R * 0.5, R + 0.4]]) fill(polar(r1, a0), polar(r1, a1), polar(r0, a0), polar(r0, a1), FILL.floor, FILL.floor, 0.2)+ }+ // Westworld's maze in the floor, with you at its centre+ const self = COL.self+ const rings = [0.85, 1.5, 2.15, 2.8, 3.45, 4.1]+ rings.forEach((r, ri) => {+ const gaps = [rand() * TAU, rand() * TAU]+ const gw = 0.42 / r+ const nSeg = Math.ceil(r * 14)+ for (let s = 0; s < nSeg; s++) {+ const a0 = (s / nSeg) * TAU, a1 = ((s + 1) / nSeg) * TAU, am = (a0 + a1) / 2+ if (gaps.some((g) => Math.abs(angWrap(am - g)) < gw)) continue+ seg(polar(r, a0, 0.012), polar(r, a1, 0.012), self, 0.42 - ri * 0.035, 1.2, 0.15 + r * 0.16)+ }+ if (ri < rings.length - 1) for (let j = 0; j < 2; j++) { const a = rand() * TAU; seg(polar(r, a, 0.012), polar(rings[ri + 1], a, 0.012), self, 0.34, 1.2, 0.2 + r * 0.16) }+ })+ poly(Array.from({ length: 24 }, (_, i) => polar(0.32, (i / 24) * TAU, 0.012)), true, self, 0.8, 1.6, 0.1)+ const you = toChars('you', self, 0.85)+ emit(GLY, [you], [-(3 * Atlas.advEm * 0.11) / 2, 0.015, -0.6], [1, 0, 0], [0, 0, -1], { em: 0.11, birth: 0.3 })+ // the light at the centre, up through the oculus+ for (let i = 0; i < 6; i++) {+ const a = (i / 6) * TAU+ seg(polar(0.2, a, 0.0), polar(0.2, a, 4.5), self, 0.3, 1.0, 0.5)+ seg(polar(0.2, a, 4.5), polar(0.14, a, H_ATRIUM + 7.5), self, 0.18, 1.0, 0.9)+ }+ // floor rings and a lit path from the stones to every door+ for (const r of [R_STONE + 0.95, R - 0.7]) poly(Array.from({ length: 96 }, (_, i) => polar(r, (i / 96) * TAU, 0.01)), true, COL.struct, 0.16, 1.1, null)+ for (const w of wings) {+ segs(polar(R_STONE + 0.95, w.theta, 0.012), polar(w.s0 - 0.05, w.theta, 0.012), COL.struct, 0.12 + 0.35 * w.act, 1.3, null, 0, 0, 2)+ for (const off of [-0.5, 0.5]) segs(WP(w, R - 0.7, off, 0.012), WP(w, w.s0, off, 0.012), COL.struct, 0.1 + 0.25 * w.act, 1.0, null, 0, 0, 2)+ }++ // the wall: arcs between the doors, a flat facade for each door+ const H = H_ATRIUM+ const arc = (a0, a1) => {+ const m = Math.max(1, Math.ceil(Math.abs(a1 - a0) / (5 * DEG)))+ const pts = []+ for (let i = 0; i <= m; i++) pts.push(lerp(a0, a1, i / m))+ for (let i = 0; i < m; i++) {+ const p = polar(R, pts[i]), q = polar(R, pts[i + 1])+ fill([p[0], H, p[2]], [q[0], H, q[2]], [p[0], 0, p[2]], [q[0], 0, q[2]], FILL.wallTop, FILL.wallBot)+ wall(p[0], p[2], q[0], q[2], 'wall')+ for (const [y, a] of [[0.02, 0.55], [H, 0.5], [0.95, 0.16], [H - 0.5, 0.2]]) seg(polar(R, pts[i], y), polar(R, pts[i + 1], y), COL.struct, a, 1.2)+ }+ for (let i = 0; i <= m; i += 2) segs(polar(R, pts[i], 0), polar(R, pts[i], H), COL.struct, i === 0 || i === m ? 0.5 : 0.22, 1.1, null, 0, 0, 1.5)+ }+ if (!wings.length) arc(0, TAU)+ wings.forEach((w, i) => {+ const next = wings[(i + 1) % wings.length]+ let a1 = next.theta - next.alpha+ if (i === wings.length - 1) a1 += TAU+ if (a1 > w.theta + w.alpha + 0.001) arc(w.theta + w.alpha, a1)+ buildFacade(W, w)+ })++ // the dome+ const mer = 32+ for (let i = 0; i < mer; i++) {+ const a = (i / mer) * TAU+ const pts = []+ for (let j = 0; j <= 12; j++) { const u = (j / 12) * 0.9; pts.push(polar(R * Math.cos((u * Math.PI) / 2) + 0.01, a, H + (R - 3) * 0.62 * Math.sin((u * Math.PI) / 2))) }+ for (let j = 0; j < 12; j++) seg(pts[j], pts[j + 1], COL.struct, 0.2 - j * 0.008, 1.0, 1.2 + j * 0.09)+ }+ for (const u of [0.3, 0.6, 0.9]) {+ const r = R * Math.cos((u * Math.PI) / 2) + 0.01, y = H + (R - 3) * 0.62 * Math.sin((u * Math.PI) / 2)+ poly(Array.from({ length: 64 }, (_, i) => polar(r, (i / 64) * TAU, y)), true, COL.struct, u === 0.9 ? 0.42 : 0.14, 1.0, 1.3 + u * 1.2)+ }++ buildStones(W)+ }++ function buildFacade(W, w) {+ const H = H_ATRIUM, s = w.s0+ const top = FILL.wallTop, bot = FILL.wallBot+ const P = (t, y) => WP(w, s, t, y)+ fill(P(-FH, H), P(-CWH, H), P(-FH, 0), P(-CWH, 0), top, bot)+ fill(P(CWH, H), P(FH, H), P(CWH, 0), P(FH, 0), top, bot)+ fill(P(-CWH, H), P(CWH, H), P(-CWH, OPEN_H), P(CWH, OPEN_H), top, top)+ const a = P(-FH, 0), b = P(-CWH, 0), c = P(CWH, 0), d = P(FH, 0)+ wall(a[0], a[2], b[0], b[2], 'wall', w.i); wall(c[0], c[2], d[0], d[2], 'wall', w.i)+ const k = 0.25 + 0.75 * w.act+ const obj = INTER.length + 1+ // edges, the opening, a frame around it and a sign board above it+ for (const y of [0.02, H]) seg(P(-FH, y), P(FH, y), COL.struct, 0.5, 1.2)+ for (const y of [0.95, H - 0.5]) { seg(P(-FH, y), P(-CWH - 0.25, y), COL.struct, 0.18, 1.1); seg(P(CWH + 0.25, y), P(FH, y), COL.struct, 0.18, 1.1) }+ for (const t of [-FH, FH]) seg(P(t, 0), P(t, H), COL.struct, 0.5, 1.2)+ poly([P(-CWH, 0), P(-CWH, OPEN_H), P(CWH, OPEN_H), P(CWH, 0)], false, COL.struct, 0.35 + 0.6 * k, 1.6, null, obj)+ poly([P(-CWH - 0.25, 0), P(-CWH - 0.25, OPEN_H + 0.25), P(CWH + 0.25, OPEN_H + 0.25), P(CWH + 0.25, 0)], false, COL.struct, 0.15 + 0.35 * k, 1.1, null, obj)+ const by0 = OPEN_H + 0.4, by1 = OPEN_H + 2.05+ poly([P(-FH + 0.25, by0), P(FH - 0.25, by0), P(FH - 0.25, by1), P(-FH + 0.25, by1)], true, COL.struct, 0.12 + 0.4 * k, 1.1, null, obj)+ // the sign: name, then how much you work there+ const n = [-w.d[0], 0, -w.d[1]], r = [w.r[0], 0, w.r[1]], u = [0, 1, 0]+ const name = w.label+ const em = Math.min(0.46, (2 * FH - 0.9) / (Array.from(name).length * Atlas.advEm))+ const nameW = Array.from(name).length * Atlas.advEm * em+ const ink = mixc(COL.label, COL.struct, 0.25)+ const birth = birthAt(P(0, 0)[0], P(0, 0)[2]) + 0.4+ const o1 = at3(P(0, by1 - 0.22), r, u, -nameW / 2, 0); o1[0] += n[0] * 0.03; o1[2] += n[2] * 0.03+ emit(GLY, [toChars(name, ink, 0.45 + 0.55 * k)], o1, r, u, { em, birth, step: 0.02, obj })+ const stats = w.kind === 'words'+ ? [`${fmt(w.rooms.reduce((s, x) => s + (x.said || x.items.length), 0))} things you said`, `newest ${ago(w.last, WORLD.NOW)}`]+ : [`${fmt(w.mems.length)} memories` + (w.kind === 'project' ? ` · ${fmt(w.sessions)} sessions · ${fmt(w.askCount)} asks` : ''),+ w.kind === 'project' ? (w.lastAt ? `last here ${ago(w.lastAt, WORLD.NOW)}` : 'no sessions here') : `newest ${ago(w.last, WORLD.NOW)}`]+ stats.forEach((line, li) => {+ const e2 = Math.min(0.13, (2 * FH - 0.9) / (line.length * Atlas.advEm))+ const lw = line.length * Atlas.advEm * e2+ const o2 = at3(P(0, by1 - 0.34 - em * 1.3 - li * 0.21), r, u, -lw / 2, 0); o2[0] += n[0] * 0.03; o2[2] += n[2] * 0.03+ emit(GLY, [toChars(line, COL.label, 0.3 + 0.35 * k)], o2, r, u, { em: e2, birth: birth + 0.3, step: 0.01, obj })+ })+ INTER.push({ id: obj, kind: 'door', wing: w, at: 'facade', c: P(0, 1.65), n, rt: r, hw: CWH, hh: 1.65, twoSided: true, reach: 46, color: COL.struct, label: w.label })+ }++ function buildStones(W) {+ const { K, sections } = W+ const ws = Math.min(3.6, ((TAU * R_STONE) / K) * 0.6)+ const adv = Atlas.advEm+ sections.forEach((sec, k) => {+ const phi = (k * TAU) / K+ const dir = [Math.sin(phi), -Math.cos(phi)]+ const n = [-dir[0], 0, -dir[1]], rt = [n[2], 0, -n[0]], up = [0, 1, 0]+ const cx = dir[0] * R_STONE, cz = dir[1] * R_STONE+ const obj = INTER.length + 1+ // lay the text out first; the stone is as tall as what it says+ const uw = ws - 0.42+ let em = 0.128, layout+ for (let tries = 0; tries < 8; tries++) {+ const cols = colsFor(uw, em)+ const blocks = sec.lines.map((line) => {+ const cites = (line.refs ?? []).length+ const body = wrapChars(toChars(oneLine(line.text), COL.self, 0.92), cols - 2, 6)+ const rows = body.map((row, ri) => [...toChars(ri === 0 ? '· ' : ' ', COL.self, 0.5), ...row])+ if (cites) {+ const mark = toChars(` [${cites}]`, mixc(COL.self, COL.dust, 0.4), 0.45)+ const last = rows[rows.length - 1]+ if (last.length + mark.length <= cols) last.push(...mark); else rows.push([...toChars(' ', COL.self, 0), ...mark.slice(1)])+ }+ return rows+ })+ const rowsN = blocks.reduce((s, b) => s + b.length, 0)+ const h = 0.3 + 0.075 * 1.4 + 0.1 + 0.165 * 1.35 + 0.16 + rowsN * em * 1.3 + (blocks.length - 1) * em * 0.55 + 0.42 + (k === 0 ? 0.22 : 0)+ layout = { cols, blocks, h }+ if (h <= 4.15) break+ em *= 0.92+ }+ const hs = Math.max(3.1, layout.h + 0.25)+ const front = (t, y) => [cx + rt[0] * t, y, cz + rt[2] * t]+ const back = (t, y) => [cx + rt[0] * t + dir[0] * 0.5, y, cz + rt[2] * t + dir[1] * 0.5]+ const hw = ws / 2+ const bt = 0.75 + k * 0.12+ fill(front(-hw, hs), front(hw, hs), front(-hw, 0), front(hw, 0), FILL.stone, mixc(FILL.stone, [0.05, 0.035, 0.02], 0.6), bt)+ fill(back(hw, hs), back(-hw, hs), back(hw, 0), back(-hw, 0), FILL.stoneTop, FILL.stone, bt)+ fill(front(-hw, hs), back(-hw, hs), front(-hw, 0), back(-hw, 0), FILL.stoneTop, FILL.stone, bt)+ fill(front(hw, hs), back(hw, hs), front(hw, 0), back(hw, 0), FILL.stoneTop, FILL.stone, bt)+ fill(back(-hw, hs), back(hw, hs), front(-hw, hs), front(hw, hs), FILL.stoneTop, FILL.stoneTop, bt)+ const fp = [front(-hw, 0), front(hw, 0), back(hw, 0), back(-hw, 0)]+ for (let i = 0; i < 4; i++) wall(fp[i][0], fp[i][2], fp[(i + 1) % 4][0], fp[(i + 1) % 4][2], 'stone')+ const b0 = 0.55 + k * 0.12+ poly([front(-hw, 0.01), front(-hw, hs), front(hw, hs), front(hw, 0.01)], false, COL.self, 0.75, 1.5, b0, obj)+ poly([back(-hw, hs), back(hw, hs)], false, COL.self, 0.3, 1.1, b0 + 0.2, obj)+ seg(front(-hw, hs), back(-hw, hs), COL.self, 0.35, 1.1, b0 + 0.2, obj); seg(front(hw, hs), back(hw, hs), COL.self, 0.35, 1.1, b0 + 0.2, obj)+ seg(back(-hw, 0), back(-hw, hs), COL.self, 0.12, 1.0, b0 + 0.3, obj); seg(back(hw, 0), back(hw, hs), COL.self, 0.12, 1.0, b0 + 0.3, obj)+ poly([front(-hw + 0.1, 0.3), front(-hw + 0.1, hs - 0.1), front(hw - 0.1, hs - 0.1), front(hw - 0.1, 0.3)], true, COL.self, 0.22, 1.0, b0 + 0.3, obj)+ seg(front(-hw, 0.3), front(hw, 0.3), COL.self, 0.3, 1.0, b0 + 0.3, obj)+ // the carving+ const o = [cx + rt[0] * (-hw + 0.21) + n[0] * 0.012, hs - 0.3, cz + rt[2] * (-hw + 0.21) + n[2] * 0.012]+ let y = 0+ const tb = 1.0 + k * 0.16+ const step = Math.min(0.0016, 1.5 / Math.max(1, layout.blocks.flat().flat().length))+ y += emit(GLY, [toChars('about you', COL.self, 0.42)], o, rt, up, { em: 0.075, birth: tb, obj }) + 0.1 * 1+ y += emit(GLY, [toChars(sec.name.toUpperCase(), mixc(COL.self, COL.white, 0.35), 1)], at3(o, rt, up, 0, -y), rt, up, { em: 0.165, birth: tb + 0.05, step: 0.02, obj }) + 0.16+ let gi = 0+ for (const rows of layout.blocks) {+ y += emit(GLY, rows, at3(o, rt, up, 0, -y), rt, up, { em, birth: tb + 0.25 + gi * step, step, spread: 1.6, obj }) + em * 0.55+ gi += rows.flat().length+ }+ if (k === 0 && W.snap.about?.intro) {+ const intro = oneLine(W.snap.about.intro)+ const e3 = 0.07+ emit(GLY, wrapChars(toChars(intro, COL.self, 0.38), colsFor(uw, e3), 2), [o[0], 0.62, o[2]], rt, up, { em: e3, birth: tb + 1.2, obj })+ }+ const it = { id: obj, kind: 'stone', k, sec, c: [cx, hs / 2, cz], n, rt, hw, hh: hs / 2, reach: 14, color: COL.self, label: sec.name,+ view: { x: dir[0] * (R_STONE - 4.0), z: dir[1] * (R_STONE - 4.0), yaw: phi, wing: null } }+ INTER.push(it); W.stones.push(it)+ })+ }++ function buildWing(W, w) {+ const k = 0.25 + 0.75 * w.act+ const sc = COL.struct+ const P = (s, t, y) => WP(w, s, t, y)+ const wq = (s0, t0, s1, t1, y0, y1, top = FILL.wallTop, bot = FILL.wallBot, collide = true) => {+ fill(P(s0, t0, y1), P(s1, t1, y1), P(s0, t0, y0), P(s1, t1, y0), top, bot)+ if (collide && y0 === 0) { const a = P(s0, t0, 0), b = P(s1, t1, 0); wall(a[0], a[2], b[0], b[2], 'wall', w.i) }+ }+ // corridor+ const s0 = w.s0, s1 = w.s1+ wq(s0, -CWH, s1, -CWH, 0, CH); wq(s0, CWH, s1, CWH, 0, CH)+ fill(P(s0, -CWH, CH), P(s1, -CWH, CH), P(s0, CWH, CH), P(s1, CWH, CH), FILL.ceil)+ fill(P(s0, -CWH, 0), P(s1, -CWH, 0), P(s0, CWH, 0), P(s1, CWH, 0), FILL.floor)+ for (const t of [-CWH, CWH]) { segs(P(s0, t, 0.02), P(s1, t, 0.02), sc, 0.35 + 0.35 * k, 1.2); segs(P(s0, t, CH), P(s1, t, CH), sc, 0.25 + 0.35 * k, 1.2) }+ for (const t of [-0.55, 0.55]) segs(P(s0, t, 0.012), P(s1, t, 0.012), sc, 0.06 + 0.22 * k, 1.1)+ for (let s = s0 + 1.2; s < s1 - 0.5; s += 2.4) {+ const ri = 0.12 + 0.55 * k+ seg(P(s, -CWH, 0), P(s, -CWH, CH), sc, ri, 1.2); seg(P(s, CWH, 0), P(s, CWH, CH), sc, ri, 1.2)+ seg(P(s, -CWH, CH), P(s, CWH, CH), sc, ri * 0.8, 1.2); seg(P(s, -CWH, 0.012), P(s, CWH, 0.012), sc, ri * 0.35, 1.0)+ }+ // your words along the corridor walls, faint+ const said = []+ const seen = new Set()+ for (const a of w.asks) { const text = cleanAsk(a.text); if (!usefulAsk(text)) continue; const key = text.toLowerCase().slice(0, 60); if (seen.has(key)) continue; seen.add(key); said.push({ a, text, n: 1 }) }+ const nSlots = Math.max(0, Math.floor((s1 - s0 - 3.2) / 3.5)) * 2+ said.slice(0, nSlots).forEach((it, j) => {+ const side = j % 2 === 0 ? -1 : 1+ const s = s0 + 2.6 + Math.floor(j / 2) * 3.5+ const t = side * (CWH - 0.02)+ const n = [-side * w.r[0], 0, -side * w.r[1]]+ const rt = [n[2], 0, -n[0]], up = [0, 1, 0]+ const c = P(s, t, 2.05)+ const obj = INTER.length + 1+ const decay = decayOf(it.a.at, W.NOW)+ const em = 0.105, pw = 2.5+ const rows = wrapChars(toChars(it.text, COL.words, 0.62 * (1 - decay * 0.4)), colsFor(pw, em), 4)+ const o = at3(c, rt, up, -pw / 2, 0.45)+ const hgt = emit(GLY, rows, o, rt, up, { em, decay, seed: obj * 31, obj, birth: birthAt(c[0], c[2]) + 0.4, step: 0.004 })+ emit(GLY, [toChars(`you said · ${shortDate(it.a.at)}`, COL.words, 0.35)], at3(o, rt, up, 0, -hgt - 0.08), rt, up, { em: 0.065, obj, birth: birthAt(c[0], c[2]) + 0.6 })+ const v = P(s, -side * 0.5, 0)+ const item = { id: obj, kind: 'ask', a: it.a, text: it.text, wing: w, c, n, rt, hw: pw / 2, hh: 0.55, reach: 6, color: COL.words, label: it.text.slice(0, 40),+ view: { x: v[0], z: v[2], yaw: Math.atan2(-n[0], n[2]), wing: w, s } }+ INTER.push(item)+ W.inscriptions.set(`${it.a.engine}|${it.a.at}`, item)+ })++ // chambers: octagons one after another down the spoke, each sharing a door with the next+ const nR = w.rooms.length+ const ra = 0.3 + 0.3 * k+ for (let ri = 0; ri <= nR; ri++) {+ const s = s1 + ri * RD+ const solid = ri === nR+ const up = [0, 1, 0]+ if (solid) wq(s, -OCT_HALF, s, OCT_HALF, 0, RH)+ else {+ wq(s, -OCT_HALF, s, -CWH, 0, RH); wq(s, CWH, s, OCT_HALF, 0, RH)+ fill(P(s, -CWH, RH), P(s, CWH, RH), P(s, -CWH, OPEN_H), P(s, CWH, OPEN_H), FILL.wallTop, FILL.wallTop)+ const obj = INTER.length + 1+ poly([P(s, -CWH, 0), P(s, -CWH, OPEN_H), P(s, CWH, OPEN_H), P(s, CWH, 0)], false, sc, 0.45 + 0.4 * k, 1.5, null, obj)+ const room = w.rooms[ri]+ INTER.push({ id: obj, kind: 'door', wing: w, at: 'room', room: ri, c: P(s, 0, 1.65), n: [-w.d[0], 0, -w.d[1]], rt: [w.r[0], 0, w.r[1]], hw: CWH, hh: 1.65, twoSided: true, reach: 34, color: sc,+ label: `${room.title}${room.parts > 1 ? ` ${room.part}/${room.parts}` : ''}` })+ // the chamber's name above its door, seen as you come+ const title = `${room.title}${room.parts > 1 ? ` ${room.part}/${room.parts}` : ''}`+ const em = Math.min(0.2, (2 * CWH - 0.3) / (Array.from(title).length * Atlas.advEm))+ const tw = Array.from(title).length * Atlas.advEm * em+ const r = [w.r[0], 0, w.r[1]]+ const o = at3(P(s - 0.03, 0, OPEN_H + 0.12 + em * 1.25), r, up, -tw / 2, 0)+ emit(GLY, [toChars(title, COL.label, 0.75)], o, r, up, { em, obj, birth: birthAt(o[0], o[2]) + 0.3, step: 0.02 })+ // and on the way back, where it leads+ const back = ri === 0 ? '‹ atrium' : `‹ ${w.rooms[ri - 1].title}`+ const e2 = 0.1, bw = Array.from(back).length * Atlas.advEm * e2+ const rb = [-w.r[0], 0, -w.r[1]]+ emit(GLY, [toChars(back, COL.label, 0.4)], at3(P(s + 0.03, 0, OPEN_H + 0.3), rb, up, -bw / 2, 0), rb, up, { em: e2, birth: birthAt(o[0], o[2]) + 0.4 })+ }+ if (solid) continue+ const scn = s + OCT_A+ const corner = (q, y) => { const ph = (q * Math.PI) / 4 - Math.PI / 8; return P(scn + OCT_R * Math.cos(ph), OCT_R * Math.sin(ph), y) }+ const apex = P(scn, 0, RH + 1.4), mid = P(scn, 0, 0)+ for (let q = 0; q < 8; q++) {+ const a = corner(q, 0), b = corner(q + 1, 0), at = corner(q, RH), bt = corner(q + 1, RH)+ if (q !== 0 && q !== 4) { fill(at, bt, a, b, FILL.wallTop, FILL.wallBot); wall(a[0], a[2], b[0], b[2], 'wall', w.i) }+ fill(a, b, mid, mid, FILL.floor)+ fill(at, bt, apex, apex, FILL.ceil)+ seg(corner(q, 0.02), corner(q + 1, 0.02), sc, ra + 0.1, 1.2)+ seg(at, bt, sc, ra * 0.85, 1.2)+ segs(corner(q, 0), corner(q, RH), sc, ra, 1.2, null, 0, 0, 1.6)+ segs(at, apex, sc, ra * 0.45, 1.1, null, 0, 0, 1.2)+ segs(P(scn, 0, 0.01), corner(q, 0.01), sc, 0.05 + 0.06 * k, 1.0, null, 0, 0, 1.5)+ }+ for (const f of [0.35, 0.7]) poly(Array.from({ length: 8 }, (_, q) => { const ph = (q * Math.PI) / 4 - Math.PI / 8; return P(scn + OCT_R * f * Math.cos(ph), OCT_R * f * Math.sin(ph), 0.01) }), true, sc, 0.05 + 0.06 * k, 1.0, null)+ poly(Array.from({ length: 8 }, (_, q) => { const ph = (q * Math.PI) / 4 - Math.PI / 8; return P(scn + 0.5 * Math.cos(ph), 0.5 * Math.sin(ph), RH + 1.25) }), true, sc, ra * 0.6, 1.1, null)+ buildRoomItems(W, w, ri, scn)+ if (ri === nR - 1) buildColophon(W, w, s + RD)+ }+ }++ function buildColophon(W, w, s) {+ const r = [w.r[0], 0, w.r[1]], up = [0, 1, 0]+ const c = WP(w, s - 0.03, 0, 2.3)+ const name = w.label+ const em = Math.min(0.34, (2 * OCT_HALF - 0.5) / (Array.from(name).length * Atlas.advEm))+ const nw = Array.from(name).length * Atlas.advEm * em+ const b = birthAt(c[0], c[2]) + 0.4+ emit(GLY, [toChars(name, COL.label, 0.55)], at3(c, r, up, -nw / 2, 0.8), r, up, { em, birth: b, step: 0.02 })+ const e2 = 0.07+ const line = middle(w.kind === 'words' ? 'older words are further back than this' : w.kind === 'project' ? (w.path ? tail(w.path, 60) : 'no folder on this computer') : 'the end of the hall', colsFor(2 * OCT_HALF - 0.4, e2))+ const lw = Array.from(line).length * Atlas.advEm * e2+ emit(GLY, [toChars(line, COL.label, 0.3)], at3(c, r, up, -lw / 2, 0.8 - em * 1.5), r, up, { em: e2, birth: b + 0.2 })+ poly([at3(c, r, up, -nw / 2 - 0.2, 0.95), at3(c, r, up, nw / 2 + 0.2, 0.95)], false, COL.struct, 0.25, 1.0, b)+ }++ function buildRoomItems(W, w, ri, scn) {+ const room = w.rooms[ri]+ room.items.forEach((item, j) => {+ const ph = (PLAQUE_SIDES[j] * Math.PI) / 4+ const ds = Math.cos(ph), dt = Math.sin(ph)+ const n = [-(ds * w.d[0] + dt * w.r[0]), 0, -(ds * w.d[1] + dt * w.r[1])]+ const rt = [n[2], 0, -n[0]]+ const c = WP(w, scn + ds * (OCT_A - 0.03), dt * (OCT_A - 0.03), 1.95)+ const obj = INTER.length + 1+ const vs = scn + ds * 0.45, v = WP(w, vs, dt * 0.45, 0)+ const view = { x: v[0], z: v[2], yaw: Math.atan2(-n[0], n[2]), wing: w, s: vs }+ if (item.type === 'memory') {+ const m = item.m+ const ag = W.agentOf(m.agent)+ const col = lift(hexRGB(ag.color))+ const decay = decayOf(m.modified, W.NOW)+ plaque(W, m, ag, col, c, n, rt, obj, decay)+ const it = { id: obj, kind: 'memory', m, wing: w, room: ri, c, n, rt, hw: PW / 2, hh: PH / 2, reach: 11, color: col, label: oneLine(m.title), decay, view }+ INTER.push(it); W.memInter.set(m.id, it)+ } else {+ const decay = decayOf(item.a.at, W.NOW)+ inscription(W, item, c, n, rt, obj, decay)+ const it = { id: obj, kind: 'ask', a: item.a, text: item.text, wing: w, room: ri, c, n, rt, hw: PW / 2, hh: PH / 2, reach: 11, color: COL.words, label: item.text.slice(0, 48), decay, view }+ INTER.push(it); W.inscriptions.set(`${item.a.engine}|${item.a.at}`, it)+ }+ })+ }++ function plaque(W, m, ag, col, c, n, rt, obj, decay) {+ const up = [0, 1, 0]+ const hw = PW / 2, hh = PH / 2+ const front = 0.006+ const P = (x, y, z = front) => [c[0] + rt[0] * x + n[0] * z, c[1] + y, c[2] + rt[2] * x + n[2] * z]+ const rand = rng(strSeed(m.id))+ const fresh = Math.max(0, W.NOW - (m.modified || 0)) < 3 * DAY+ const fx = fresh ? 1 : decay > 0.55 ? -decay : 0+ const b = birthAt(c[0], c[2])+ const fa = 0.85 * (1 - decay * 0.55)+ const fcol = mixc(col, COL.dust, decay * 0.55)+ // the frame, broken in places when old+ const edge = (a, bb) => {+ const len = Math.hypot(bb[0] - a[0], bb[1] - a[1], bb[2] - a[2]), pieces = Math.max(1, Math.round(len / 0.3))+ for (let i = 0; i < pieces; i++) { if (decay > 0.25 && rand() < (decay - 0.2) * 0.55) continue; seg(lerp3(a, bb, i / pieces), lerp3(a, bb, (i + 1) / pieces), fcol, fa, 1.4, b + 0.1, obj, fx) }+ }+ const tl = P(-hw, hh), tr = P(hw, hh), bl = P(-hw, -hh), br = P(hw, -hh)+ edge(tl, tr); edge(tr, br); edge(br, bl); edge(bl, tl)+ poly([P(-hw + 0.07, hh - 0.07), P(hw - 0.07, hh - 0.07), P(hw - 0.07, -hh + 0.07), P(-hw + 0.07, -hh + 0.07)], true, fcol, fa * 0.28, 1.0, b + 0.2, obj, fx)+ if (!decay || decay < 0.3) for (const [x, y] of [[-1, 1], [1, 1], [1, -1], [-1, -1]]) {+ const cx = x * (hw + 0.08), cy = y * (hh + 0.08)+ seg(P(cx, cy), P(cx - x * 0.28, cy), col, 0.9, 1.5, b + 0.3, obj, fx); seg(P(cx, cy), P(cx, cy - y * 0.28), col, 0.9, 1.5, b + 0.3, obj, fx)+ }+ // text+ const ink = mixc(mixc(COL.white, col, 0.22), COL.dust, decay * 0.5)+ const o = P(-hw + 0.17, hh - 0.18, front + 0.006)+ const uw = PW - 0.34+ const kick = `${String(m.type || m.kind || 'memory').toUpperCase()} · ${ag.name}`+ let y = 0+ const step = 0.0025+ const bt = b + 0.35+ y += emit(GLY, [toChars(middle(kick, colsFor(uw, 0.078)), col, 0.85)], o, rt, up, { em: 0.078, decay: decay * 0.6, seed: obj * 7, obj, birth: bt, fx, cols: colsFor(uw, 0.078) }) + 0.07+ const tEm = 0.18+ const title = wrapChars(toChars(oneLine(m.title || m.description || 'untitled'), ink, 1), colsFor(uw, tEm), 2)+ y += emit(GLY, title, at3(o, rt, up, 0, -y), rt, up, { em: tEm, lh: 1.22, decay: decay * 0.75, seed: obj * 11, obj, birth: bt + 0.05, step, fx, cols: colsFor(uw, tEm) }) + 0.08+ const desc = oneLine(m.description || '')+ const bodyText = plain(m.body || '')+ const bEm = 0.104, bCols = colsFor(uw, bEm)+ if (desc && desc.toLowerCase() !== oneLine(m.title).toLowerCase() && !bodyText.toLowerCase().startsWith(desc.toLowerCase().slice(0, 30)) && desc.length > 12) {+ const dr = wrapChars(toChars(desc, ink, 0.5), colsFor(uw, 0.09), 2)+ y += emit(GLY, dr, at3(o, rt, up, 0, -y), rt, up, { em: 0.09, decay, seed: obj * 13, obj, birth: bt + 0.1, step, fx, cols: colsFor(uw, 0.09) }) + 0.07+ }+ const avail = PH - 0.36 - y - 0.2+ const maxRows = Math.max(1, Math.floor(avail / (bEm * 1.3)))+ const body = wrapChars(toChars(bodyText.slice(0, bCols * maxRows * 2 + 40), ink, 0.72), bCols, maxRows)+ emit(GLY, body, at3(o, rt, up, 0, -y), rt, up, { em: bEm, decay, seed: obj * 17, obj, birth: bt + 0.15, step, fx, cols: bCols })+ const foot = `${ago(m.modified, W.NOW)} · ${dateOf(m.modified)}`+ emit(GLY, [toChars(foot, col, 0.55)], P(-hw + 0.17, -hh + 0.24, front + 0.006), rt, up, { em: 0.072, decay: decay * 0.5, seed: obj * 19, obj, birth: bt + 0.3, fx, cols: colsFor(uw, 0.072) })+ if (fresh) emit(GLY, [toChars('new', col, 0.95)], P(hw - 0.17 - 3 * Atlas.advEm * 0.072, -hh + 0.24, front + 0.006), rt, up, { em: 0.072, obj, birth: bt + 0.3, fx })+ // dust on the plaque and the floor below; cobwebs in the corners of the oldest+ if (decay > 0.12) {+ const nD = Math.round(decay * 40)+ for (let i = 0; i < nD; i++) {+ const x = (rand() * 2 - 1) * hw, yy = (rand() * 2 - 1) * hh, a = rand() * Math.PI, l = 0.012 + rand() * 0.02+ seg(P(x, yy, front + 0.008), P(x + Math.cos(a) * l, yy + Math.sin(a) * l, front + 0.008), COL.dust, 0.35 * decay, 1.2, b + 0.6)+ }+ for (let i = 0; i < nD; i++) {+ const x = (rand() * 2 - 1) * (hw + 0.3), z = 0.05 + rand() * rand() * 1.1, a = rand() * TAU, l = 0.025 + rand() * 0.05+ const p = [c[0] + rt[0] * x + n[0] * z, 0.012, c[2] + rt[2] * x + n[2] * z]+ seg(p, [p[0] + Math.cos(a) * l, 0.012, p[2] + Math.sin(a) * l], COL.dust, 0.22 * decay, 1.1, b + 0.6)+ }+ }+ if (decay > 0.5) {+ for (const sx of [-1, 1]) {+ const cx = sx * hw, cy = hh+ const spokes = [0, 0.3, 0.62, 1].map((f) => { const a = Math.PI / 2 * f; const L = 0.42 + rand() * 0.25; return [-sx * Math.cos(a) * L, -Math.sin(a) * L] })+ const wa = 0.28 * decay+ for (const [dx, dy] of spokes) seg(P(cx, cy, front + 0.01), P(cx + dx, cy + dy, front + 0.01), COL.dust, wa, 1.0, b + 0.8)+ for (const f of [0.35, 0.62, 0.88]) {+ const pts = spokes.map(([dx, dy]) => P(cx + dx * f, cy + dy * f - 0.015 * f, front + 0.01))+ poly(pts, false, COL.dust, wa * 0.8, 1.0, b + 0.9)+ }+ }+ }+ }++ function inscription(W, item, c, n, rt, obj, decay) {+ const up = [0, 1, 0]+ const hw = PW / 2, hh = PH / 2+ const P = (x, y, z = 0.012) => [c[0] + rt[0] * x + n[0] * z, c[1] + y, c[2] + rt[2] * x + n[2] * z]+ const b = birthAt(c[0], c[2])+ const col = mixc(COL.words, COL.dust, decay * 0.5)+ emit(GLY, [toChars('“', col, 0.22)], P(-hw + 0.05, hh + 0.12), rt, up, { em: 0.7, obj, birth: b + 0.2 })+ const em = 0.142, cols = colsFor(PW - 0.3, em)+ const rows = wrapChars(toChars(item.text, col, 0.85 * (1 - decay * 0.45)), cols, 8)+ const hgt = emit(GLY, rows, P(-hw + 0.15, hh - 0.42), rt, up, { em, decay, seed: obj * 23, obj, birth: b + 0.35, step: 0.003, cols })+ const eng = WORLD.agentOf(item.a.engine).name+ emit(GLY, [toChars(`— you, to ${eng} · ${shortDate(item.a.at)} ${timeOf(item.a.at)}`, col, 0.45)], P(-hw + 0.15, hh - 0.42 - hgt - 0.12), rt, up, { em: 0.07, obj, birth: b + 0.6 })+ seg(P(-hw + 0.15, -hh + 0.12), P(-hw + 0.9, -hh + 0.12), col, 0.25, 1.0, b + 0.5, obj)+ }++ // ── WebGL ────────────────────────────────────────────────────────────────────────────────────────++ const canvas = $('gl'), hud = $('hud'), hctx = hud.getContext('2d')+ let gl = null, isGL2 = false+ const prog = {}+ let quadIdx = null, triBuf = null, atlasTex = null+ let chunks = { lines: [], glyphs: [], fills: [] }+ const dynBufs = []+ let targets = null+ let cssW = 0, cssH = 0, dpr = 1, pxW = 0, pxH = 0+ const P_ = new Float32Array(16), V_ = new Float32Array(16), VP = new Float32Array(16)++ const LINE_VS = `+precision highp float;+attribute vec3 aA; attribute vec3 aB; attribute vec2 aC; attribute vec4 aCol; attribute vec4 aM;+uniform mat4 uVP; uniform vec2 uRes; uniform float uPx, uT, uHi, uHi2, uFog, uFlick, uDraw, uWorld;+varying vec4 vCol; varying float vE; varying float vH;+float h1(float n) { return fract(sin(n * 12.9898) * 43758.5453); }+void main() {+ float born = uT - aM.y;+ float p = clamp(born / 0.55, 0.0, 1.0);+ if (uDraw > 0.5) p = 1.0;+ vec3 B = mix(aA, aB, p);+ vec4 ca = uVP * vec4(aA, 1.0);+ vec4 cb = uVP * vec4(B, 1.0);+ float nw = 0.06;+ if ((ca.w < nw && cb.w < nw) || (born < 0.0 && uDraw < 0.5)) { gl_Position = vec4(0.0, 0.0, -2.0, 1.0); vCol = vec4(0.0); vE = 0.0; vH = 1.0; return; }+ if (ca.w < nw) ca = mix(ca, cb, (nw - ca.w) / (cb.w - ca.w));+ if (cb.w < nw) cb = mix(cb, ca, (nw - cb.w) / (ca.w - cb.w));+ vec2 sa = ca.xy / ca.w * uRes * 0.5;+ vec2 sb = cb.xy / cb.w * uRes * 0.5;+ vec2 dir = sb - sa; float len = length(dir);+ dir = len > 1e-4 ? dir / len : vec2(1.0, 0.0);+ vec2 nrm = vec2(-dir.y, dir.x);+ float hw = aM.x * uPx * 0.5;+ float ext = hw + uPx * 1.2;+ vec4 c = aC.y < 0.5 ? ca : cb;+ vec2 off = nrm * aC.x * ext + dir * (aC.y < 0.5 ? -0.5 : 0.5) * uPx;+ c.xy += off / (uRes * 0.5) * c.w;+ c.z -= 0.00003 * c.w;+ gl_Position = c;+ vE = aC.x * ext; vH = hw;+ float depth = c.w;+ float fog = exp(-pow(depth / uFog, 2.0) * 1.4);+ float nearFade = smoothstep(0.2, 1.0, depth);+ float hi = (aM.z > 0.5 && abs(aM.z - uHi) < 0.5) ? 1.0 : 0.0;+ float hi2 = (aM.z > 0.5 && abs(aM.z - uHi2) < 0.5) ? 1.0 : 0.0;+ float flash = uDraw > 0.5 ? 0.0 : 1.0 - smoothstep(0.0, 1.1, born);+ float k = 1.0;+ if (aM.w > 0.0) k *= 1.0 + 0.25 * aM.w * sin(uT * 2.3 + aM.z);+ if (aM.w < 0.0) { float n = h1(floor(uT * 9.0) + aM.z * 7.31); k *= mix(1.0, 0.3, step(1.0 + aM.w * 0.1 * uFlick, n)); }+ vec3 col = mix(aCol.rgb, vec3(1.0), clamp(flash * 0.7 + hi * 0.3 + hi2 * 0.35, 0.0, 1.0));+ vCol = vec4(col, aCol.a * k * (1.0 + flash * 1.6 + hi * 0.9 + hi2 * 1.2) * fog * nearFade * uWorld);+}`+ const LINE_FS = `+precision highp float;+uniform float uPx;+varying vec4 vCol; varying float vE; varying float vH;+void main() {+ float d = abs(vE);+ float cov = clamp((vH + 0.6 * uPx - d) / (1.2 * uPx), 0.0, 1.0);+ float halo = exp(-d * d / (vH * vH * 5.0 + uPx * uPx * 1.5)) * 0.4;+ gl_FragColor = vec4(vCol.rgb * vCol.a * max(cov, halo), 0.0);+}`+ const GLYPH_VS = `+precision highp float;+attribute vec3 aP; attribute vec2 aUV; attribute vec4 aCol; attribute vec4 aM;+uniform mat4 uVP; uniform float uT, uHi, uHi2, uFog, uFlick, uWorld;+varying vec2 vUV; varying vec4 vCol; varying float vOcc;+float h1(float n) { return fract(sin(n * 12.9898) * 43758.5453); }+void main() {+ vec4 c = uVP * vec4(aP, 1.0);+ gl_Position = c - vec4(0.0, 0.0, 0.00003 * c.w, 0.0);+ float born = uT - aM.x;+ float vis = aM.x < -0.5 ? 1.0 : step(0.0, born);+ float flash = aM.x < -0.5 ? 0.0 : vis * (1.0 - smoothstep(0.0, 0.6, born));+ float fog = exp(-pow(c.w / uFog, 2.0) * 1.4);+ float nearFade = smoothstep(0.15, 0.7, c.w);+ float hi = (aM.y > 0.5 && abs(aM.y - uHi) < 0.5) ? 1.0 : 0.0;+ float hi2 = (aM.y > 0.5 && abs(aM.y - uHi2) < 0.5) ? 1.0 : 0.0;+ float k = 1.0;+ if (aM.z > 0.0) k *= 1.0 + 0.18 * aM.z * sin(uT * 2.3 + aM.y);+ if (aM.z < 0.0) { float n = h1(floor(uT * 9.0) + aM.y * 7.31); k *= mix(1.0, 0.35, step(1.0 + aM.z * 0.1 * uFlick, n)); }+ vec3 col = mix(aCol.rgb, vec3(1.0), clamp(flash * 0.8 + hi * 0.25 + hi2 * 0.3, 0.0, 1.0));+ vCol = vec4(col, aCol.a * vis * k * (1.0 + flash * 2.0 + hi * 0.45 + hi2 * 0.6) * (aM.w > 0.5 ? 1.0 : fog * nearFade * uWorld));+ vOcc = aM.w; vUV = aUV;+}`+ const GLYPH_FS = `+precision highp float;+uniform sampler2D uAtlas;+varying vec2 vUV; varying vec4 vCol; varying float vOcc;+void main() {+ float cov = texture2D(uAtlas, vUV).a;+ cov = pow(cov, 0.8);+ gl_FragColor = vec4(vCol.rgb * vCol.a * cov * (1.0 - vOcc), cov * vCol.a * vOcc);+}`+ const FILL_VS = `+precision highp float;+attribute vec3 aP; attribute vec4 aCol; attribute float aB;+uniform mat4 uVP; uniform float uT, uFog, uWorld;+varying vec4 vCol;+void main() {+ vec4 c = uVP * vec4(aP, 1.0);+ gl_Position = c;+ float fog = exp(-pow(c.w / uFog, 2.0) * 1.4);+ vCol = vec4(aCol.rgb * fog * uWorld, step(aB, uT));+}`+ const FILL_FS = `+precision highp float;+varying vec4 vCol;+void main() { if (vCol.a < 0.5) discard; gl_FragColor = vec4(vCol.rgb, 1.0); }`+ const POST_VS = `+attribute vec2 aP; varying vec2 vUV;+void main() { vUV = aP * 0.5 + 0.5; gl_Position = vec4(aP, 0.0, 1.0); }`+ const DOWN_FS = `+precision highp float;+uniform sampler2D uSrc; uniform vec2 uTexel; uniform float uGain, uKnee;+varying vec2 vUV;+vec3 tap(vec2 o) { vec3 c = texture2D(uSrc, vUV + uTexel * o).rgb; float m = max(c.r, max(c.g, c.b)); return c * smoothstep(uKnee, uKnee * 4.0 + 0.001, m); }+void main() {+ vec3 c = tap(vec2(-1.0, -1.0)) + tap(vec2(1.0, -1.0)) + tap(vec2(-1.0, 1.0)) + tap(vec2(1.0, 1.0));+ gl_FragColor = vec4(c * 0.25 * uGain, 1.0);+}`+ const BLUR_FS = `+precision highp float;+uniform sampler2D uSrc; uniform vec2 uDir;+varying vec2 vUV;+void main() {+ vec3 c = texture2D(uSrc, vUV).rgb * 0.227027;+ c += texture2D(uSrc, vUV + uDir * 1.3846154).rgb * 0.3162162;+ c += texture2D(uSrc, vUV - uDir * 1.3846154).rgb * 0.3162162;+ c += texture2D(uSrc, vUV + uDir * 3.2307692).rgb * 0.0702703;+ c += texture2D(uSrc, vUV - uDir * 3.2307692).rgb * 0.0702703;+ gl_FragColor = vec4(c, 1.0);+}`+ const COMP_FS = `+precision highp float;+uniform sampler2D uScene, uB1, uB2, uB3, uB4; uniform vec2 uRes; uniform float uDim, uT, uPx, uScan, uFade;+varying vec2 vUV;+void main() {+ vec3 s = texture2D(uScene, vUV).rgb;+ vec3 b = texture2D(uB1, vUV).rgb * 0.35 + texture2D(uB2, vUV).rgb * 0.6 + texture2D(uB3, vUV).rgb * 0.8 + texture2D(uB4, vUV).rgb * 1.0;+ vec3 col = s + b * 0.75;+ col += vec3(0.0, 0.006, 0.012) * (1.0 - vUV.y);+ float vig = smoothstep(1.3, 0.3, length((vUV - 0.5) * vec2(uRes.x / uRes.y, 1.0)));+ col *= mix(0.5, 1.0, vig);+ float scan = 0.93 + 0.07 * sin(gl_FragCoord.y * 3.14159 / (1.5 * uPx));+ col *= mix(1.0, scan, uScan);+ col *= (1.0 - uDim * 0.72) * (1.0 - uFade);+ col += (fract(sin(dot(gl_FragCoord.xy + fract(uT) * 37.0, vec2(12.9898, 78.233))) * 43758.5453) - 0.5) / 200.0;+ gl_FragColor = vec4(col, 1.0);+}`+ const LINE_L = [3, 3, 2, 4, 4], GLYPH_L = [3, 2, 4, 4], FILL_L = [3, 4, 1], POST_L = [2]++ function initGL() {+ const opts = { antialias: false, alpha: false, depth: true, stencil: false, premultipliedAlpha: false, preserveDrawingBuffer: false, powerPreference: 'high-performance' }+ gl = canvas.getContext('webgl2', opts)+ isGL2 = !!gl+ if (!gl) gl = canvas.getContext('webgl', opts) || canvas.getContext('experimental-webgl', opts)+ if (!gl) return false+ const compile = (vs, fs, attribs) => {+ const p = gl.createProgram()+ for (const [type, src] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {+ const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s)+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s))+ gl.attachShader(p, s)+ }+ attribs.forEach((name, i) => gl.bindAttribLocation(p, i, name))+ gl.linkProgram(p)+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p))+ const u = {}+ const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS)+ for (let i = 0; i < n; i++) { const info = gl.getActiveUniform(p, i); u[info.name] = gl.getUniformLocation(p, info.name) }+ return { p, u }+ }+ prog.line = compile(LINE_VS, LINE_FS, ['aA', 'aB', 'aC', 'aCol', 'aM'])+ prog.glyph = compile(GLYPH_VS, GLYPH_FS, ['aP', 'aUV', 'aCol', 'aM'])+ prog.fill = compile(FILL_VS, FILL_FS, ['aP', 'aCol', 'aB'])+ prog.down = compile(POST_VS, DOWN_FS, ['aP'])+ prog.blur = compile(POST_VS, BLUR_FS, ['aP'])+ prog.comp = compile(POST_VS, COMP_FS, ['aP'])+ const idx = new Uint16Array(16384 * 6)+ for (let q = 0; q < 16384; q++) idx.set([q * 4, q * 4 + 1, q * 4 + 2, q * 4 + 2, q * 4 + 1, q * 4 + 3], q * 6)+ quadIdx = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, quadIdx); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW)+ triBuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, triBuf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW)+ atlasTex = gl.createTexture()+ return true+ }++ function uploadAtlas() {+ gl.bindTexture(gl.TEXTURE_2D, atlasTex)+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false)+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, Atlas.canvas)+ gl.generateMipmap(gl.TEXTURE_2D)+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)+ const an = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')+ if (an) gl.texParameterf(gl.TEXTURE_2D, an.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(8, gl.getParameter(an.MAX_TEXTURE_MAX_ANISOTROPY_EXT)))+ Atlas.dirty = false+ }++ function makeChunks(arr, stride) {+ const all = new Float32Array(arr), perQuad = stride * 4, quads = all.length / perQuad, out = []+ for (let q = 0; q < quads; q += 16384) {+ const n = Math.min(16384, quads - q)+ const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf)+ gl.bufferData(gl.ARRAY_BUFFER, all.subarray(q * perQuad, (q + n) * perQuad), gl.STATIC_DRAW)+ out.push({ buf, quads: n })+ }+ return out+ }+ function layout(sizes) {+ const stride = sizes.reduce((a, b) => a + b, 0)+ let off = 0+ for (let i = 0; i < 6; i++) {+ if (i < sizes.length) { gl.enableVertexAttribArray(i); gl.vertexAttribPointer(i, sizes[i], gl.FLOAT, false, stride * 4, off * 4); off += sizes[i] }+ else gl.disableVertexAttribArray(i)+ }+ }+ function drawChunks(list, sizes) {+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, quadIdx)+ for (const c of list) { gl.bindBuffer(gl.ARRAY_BUFFER, c.buf); layout(sizes); gl.drawElements(gl.TRIANGLES, c.quads * 6, gl.UNSIGNED_SHORT, 0) }+ }+ let dynSlot = 0+ function drawDyn(arr, sizes) {+ if (!arr.length) return+ const stride = sizes.reduce((a, b) => a + b, 0), perQuad = stride * 4+ const all = new Float32Array(arr), quads = all.length / perQuad+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, quadIdx)+ for (let q = 0; q < quads; q += 16384) {+ const n = Math.min(16384, quads - q)+ if (!dynBufs[dynSlot]) dynBufs[dynSlot] = gl.createBuffer()+ gl.bindBuffer(gl.ARRAY_BUFFER, dynBufs[dynSlot++])+ gl.bufferData(gl.ARRAY_BUFFER, all.subarray(q * perQuad, (q + n) * perQuad), gl.DYNAMIC_DRAW)+ layout(sizes); gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0)+ }+ }++ function makeTarget(w, h, depth) {+ const tex = gl.createTexture()+ gl.bindTexture(gl.TEXTURE_2D, tex)+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null)+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)+ const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb)+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0)+ let rb = null+ if (depth) {+ rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb)+ gl.renderbufferStorage(gl.RENDERBUFFER, isGL2 ? gl.DEPTH_COMPONENT24 : gl.DEPTH_COMPONENT16, w, h)+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, rb)+ }+ return { tex, fb, rb, w, h }+ }+ function freeTarget(t) { if (!t) return; gl.deleteTexture(t.tex); gl.deleteFramebuffer(t.fb); if (t.rb) gl.deleteRenderbuffer(t.rb) }++ function resize() {+ const w = Math.max(1, window.innerWidth), h = Math.max(1, window.innerHeight)+ const d = Math.min(2, window.devicePixelRatio || 1)+ if (w === cssW && h === cssH && d === dpr && targets) return+ cssW = w; cssH = h; dpr = d+ pxW = Math.round(w * d); pxH = Math.round(h * d)+ canvas.width = pxW; canvas.height = pxH+ hud.width = pxW; hud.height = pxH+ if (targets) Object.values(targets).forEach(freeTarget)+ const q = (k) => [Math.max(1, Math.round(pxW / k)), Math.max(1, Math.round(pxH / k))]+ targets = { scene: makeTarget(pxW, pxH, true), b1: makeTarget(...q(2)), b2: makeTarget(...q(4)), t2: makeTarget(...q(4)), b3: makeTarget(...q(8)), t3: makeTarget(...q(8)), b4: makeTarget(...q(16)), t4: makeTarget(...q(16)) }+ }++ // ── state ────────────────────────────────────────────────────────────────────────────────────────++ const cam = { x: 0, z: 0, y: EYE, yaw: 0, pitch: 0, v: 0, sv: 0, w: 0, bob: 0, fov: 62 }+ const keys = {}+ let clock = 0, arrival = true, ready = false+ let target = null, hiPulse = { id: 0, until: 0 }+ let travel = null+ let fade = 0+ let dim = 0, recallDim = 0+ const ARRIVE = 4.9+ const recall = { q: '', chars: [], cards: [], sel: 0, gone: [], goneWords: [], msgs: [], msgQ: '', timer: 0 }+ const reader = { open: false, item: null, links: [], sel: -1, restore: null }+ const mapUI = { open: false, sel: 0 }++ // ── walking, collision, looking ──────────────────────────────────────────────────────────────────++ function collide(x, z, r = 0.38) {+ for (let it = 0; it < 3; it++) {+ for (const s of WALLS) {+ const dx = s[2] - s[0], dz = s[3] - s[1]+ const l2 = dx * dx + dz * dz || 1e-6+ const t = clamp(((x - s[0]) * dx + (z - s[1]) * dz) / l2, 0, 1)+ const px = s[0] + dx * t, pz = s[1] + dz * t+ const ex = x - px, ez = z - pz, d = Math.hypot(ex, ez)+ if (d < r && d > 1e-6) { x = px + (ex / d) * r; z = pz + (ez / d) * r }+ }+ }+ return [x, z]+ }+ function rayWalls(px, pz, fx, fz, max) {+ let best = max+ for (const s of WALLS) {+ const ex = s[2] - s[0], ez = s[3] - s[1]+ const den = fx * ez - fz * ex+ if (Math.abs(den) < 1e-9) continue+ const ax = s[0] - px, az = s[1] - pz+ const t = (ax * ez - az * ex) / den, u = (ax * fz - az * fx) / den+ if (t > 0 && t < best && u >= 0 && u <= 1) best = t+ }+ return best+ }+ function pick() {+ const fx = Math.sin(cam.yaw), fz = -Math.cos(cam.yaw)+ const wallT = rayWalls(cam.x, cam.z, fx, fz, 80)+ let best = null, bestT = Infinity+ for (const it of INTER) {+ const den = fx * it.n[0] + fz * it.n[2]+ if (it.twoSided ? Math.abs(den) < 0.25 : den > -0.25) continue+ const t = ((it.c[0] - cam.x) * it.n[0] + (it.c[2] - cam.z) * it.n[2]) / den+ if (t < 0.3 || t > it.reach || t > wallT + 0.15 || t >= bestT) continue+ const hx = cam.x + fx * t - it.c[0], hz = cam.z + fz * t - it.c[2]+ if (Math.abs(hx * it.rt[0] + hz * it.rt[2]) > it.hw * 1.06) continue+ best = it; bestT = t+ }+ if (best) return best+ // nothing straight ahead: a door a little to one side, if you can see it+ let bestA = 9 * DEG+ for (const it of INTER) {+ if (it.kind !== 'door') continue+ const dx = it.c[0] - cam.x, dz = it.c[2] - cam.z, d = Math.hypot(dx, dz)+ if (d < 1 || d > it.reach) continue+ const a = Math.abs(angWrap(Math.atan2(dx, -dz) - cam.yaw))+ if (a >= bestA) continue+ if (rayWalls(cam.x, cam.z, dx / d, dz / d, d) < d - 0.2) continue+ best = it; bestA = a+ }+ return best+ }++ function locate(x, z) {+ for (const w of WORLD.wings) {+ const s = x * w.d[0] + z * w.d[1], t = x * w.r[0] + z * w.r[1]+ if (s < w.s0 - 0.3 || s > w.sEnd + 0.3) continue+ if (s < w.s1) { if (Math.abs(t) < CWH + 0.4) return { wing: w, s, t, room: -1 } }+ else if (Math.abs(t) < OCT_R + 0.3) return { wing: w, s, t, room: clamp(Math.floor((s - w.s1) / RD), 0, w.rooms.length - 1) }+ }+ return { wing: null, r: Math.hypot(x, z) }+ }++ // ── travel: a path through the palace, then a glide along it ─────────────────────────────────────++ function nearestGap(a) {+ const K = WORLD.K+ let best = 0, bd = Infinity+ for (let k = 0; k < K; k++) { const g = (k * TAU) / K + Math.PI / K; const d = Math.abs(angWrap(g - a)); if (d < bd) { bd = d; best = g } }+ return best+ }+ function route(dest) {+ const pts = [[cam.x, cam.z]]+ const here = locate(cam.x, cam.z)+ const ringR = (R_STONE + 1.0 + WORLD.R * Math.cos(WORLD.alpha)) / 2+ const pol = (r, a) => [r * Math.sin(a), -r * Math.cos(a)]+ const axis = (w, s) => [s * w.d[0], s * w.d[1]]+ let ang, rad+ if (here.wing) {+ if (dest.wing === here.wing) { pts.push(axis(here.wing, here.s), axis(dest.wing, dest.s), [dest.x, dest.z]); return pts }+ pts.push(axis(here.wing, here.s), axis(here.wing, here.wing.s0 - 1.0))+ ang = here.wing.theta; rad = here.wing.s0 - 1.0+ } else { rad = Math.hypot(cam.x, cam.z); ang = Math.atan2(cam.x, -cam.z) }+ const dr = Math.hypot(dest.x, dest.z)+ const destIn = !dest.wing && dr < R_STONE+ const destAng = dest.wing ? dest.wing.theta : dr < 0.5 ? ang : Math.atan2(dest.x, -dest.z)+ if (rad < R_STONE + 0.6) {+ if (destIn) { pts.push([dest.x, dest.z]); return pts }+ const g = nearestGap(destAng)+ pts.push(pol(R_STONE - 1.5, g), pol(R_STONE + 1.5, g))+ ang = g; rad = R_STONE + 1.5+ }+ const goal = destIn ? nearestGap(destAng) : destAng+ pts.push(pol(ringR, ang))+ const d = angWrap(goal - ang), steps = Math.ceil(Math.abs(d) / (14 * DEG))+ for (let i = 1; i <= steps; i++) pts.push(pol(ringR, ang + (d * i) / steps))+ if (destIn) { pts.push(pol(R_STONE + 1.5, goal), pol(R_STONE - 1.5, goal), [dest.x, dest.z]); return pts }+ if (dest.wing) pts.push(axis(dest.wing, dest.wing.s0 - 1.0), axis(dest.wing, dest.s))+ pts.push([dest.x, dest.z])+ return pts+ }+ function cr(p0, p1, p2, p3, t) {+ const dd = (a, b) => Math.pow(Math.hypot(b[0] - a[0], b[1] - a[1]), 0.5) || 1e-4+ const t0 = 0, t1 = t0 + dd(p0, p1), t2 = t1 + dd(p1, p2), t3 = t2 + dd(p2, p3)+ const u = lerp(t1, t2, t)+ const L = (a, b, ta, tb) => { const k = (u - ta) / (tb - ta || 1e-4); return [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k] }+ const A1 = L(p0, p1, t0, t1), A2 = L(p1, p2, t1, t2), A3 = L(p2, p3, t2, t3)+ return L(L(A1, A2, t0, t2), L(A2, A3, t1, t3), t1, t2)+ }+ function spline(pts) {+ const P = []+ for (const p of pts) if (!P.length || Math.hypot(p[0] - P[P.length - 1][0], p[1] - P[P.length - 1][1]) > 0.35) P.push(p)+ if (P.length < 2) P.push([P[0][0] + 0.01, P[0][1]])+ const out = []+ for (let i = 0; i < P.length - 1; i++) {+ const p0 = i > 0 ? P[i - 1] : [2 * P[0][0] - P[1][0], 2 * P[0][1] - P[1][1]]+ const p3 = i + 2 < P.length ? P[i + 2] : [2 * P[i + 1][0] - P[i][0], 2 * P[i + 1][1] - P[i][1]]+ const n = Math.max(2, Math.ceil(Math.hypot(P[i + 1][0] - P[i][0], P[i + 1][1] - P[i][1]) / 0.35))+ for (let j = 0; j < n; j++) out.push(cr(p0, P[i], P[i + 1], p3, j / n))+ }+ out.push(P[P.length - 1])+ const cum = [0]+ for (let i = 1; i < out.length; i++) cum.push(cum[i - 1] + Math.hypot(out[i][0] - out[i - 1][0], out[i][1] - out[i - 1][1]))+ return { pts: out, cum, len: cum[cum.length - 1] }+ }+ function sampleAt(path, d) {+ const { pts, cum } = path+ if (d <= 0) return pts[0]+ if (d >= path.len) return pts[pts.length - 1]+ let lo = 0, hi = cum.length - 1+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (cum[mid] < d) lo = mid; else hi = mid }+ const t = (d - cum[lo]) / (cum[hi] - cum[lo] || 1)+ return [lerp(pts[lo][0], pts[hi][0], t), lerp(pts[lo][1], pts[hi][1], t)]+ }++ function travelTo(dest) {+ if (!dest) return+ closeMap()+ const path = spline(route(dest))+ if (reduced || path.len < 0.05) {+ fadeCut(() => { cam.x = dest.x; cam.z = dest.z; cam.yaw = dest.yaw; cam.v = cam.w = cam.sv = 0; if (dest.hi) hiPulse = { id: dest.hi, until: clock + 2.5 } })+ return+ }+ travel = { path, t: 0, show: 0, T: clamp(0.9 + path.len / 24, 1.1, 5.2), dest, settle: 0, phase: 'show' }+ cam.v = cam.w = cam.sv = 0+ }+ function fadeCut(fn) { fade = 1; setTimeout(() => { fn(); setTimeout(() => { fade = 0 }, 30) }, 130) }+ function stopTravel() { travel = null }++ function homeDest() { return { x: 0, z: 0, yaw: 0, wing: null } }+ function doorDest(it) {+ const w = it.wing+ const here = locate(cam.x, cam.z)+ if (it.at === 'facade') {+ if (here.wing === w) return { x: 0, z: 0, yaw: w.theta, wing: null }+ return { x: WP(w, w.s1 + 2.4, 0, 0)[0], z: WP(w, w.s1 + 2.4, 0, 0)[2], yaw: w.theta, wing: w, s: w.s1 + 2.4 }+ }+ const sOpen = w.s1 + it.room * RD+ const camS = cam.x * w.d[0] + cam.z * w.d[1]+ if (camS < sOpen) { const s = sOpen + 2.4; const p = WP(w, s, 0, 0); return { x: p[0], z: p[2], yaw: w.theta, wing: w, s } }+ if (it.room === 0) { const s = w.s0 + (w.s1 - w.s0) * 0.5; const p = WP(w, s, 0, 0); return { x: p[0], z: p[2], yaw: w.theta + Math.PI, wing: w, s } }+ const s = w.s1 + (it.room - 1) * RD + RD / 2; const p = WP(w, s, 0, 0)+ return { x: p[0], z: p[2], yaw: w.theta + Math.PI, wing: w, s }+ }+ /** Seen from the far side, a door leads back: name where it goes. */+ function doorBack(it) {+ if (it.kind !== 'door') return ''+ const w = it.wing, camS = cam.x * w.d[0] + cam.z * w.d[1]+ if (it.at === 'facade') return camS > w.s0 ? 'the atrium' : ''+ if (camS <= w.s1 + it.room * RD) return ''+ return it.room === 0 ? 'the corridor' : w.rooms[it.room - 1].title+ }+ function stepBack() {+ const here = locate(cam.x, cam.z)+ if (here.wing) {+ const w = here.wing+ if (here.room > 0) { const s = w.s1 + (here.room - 1) * RD + RD / 2; const p = WP(w, s, 0, 0); travelTo({ x: p[0], z: p[2], yaw: w.theta, wing: w, s }); return }+ const p = WP(w, w.s0 - 3.2, 0, 0)+ travelTo({ x: p[0], z: p[2], yaw: w.theta, wing: null })+ return+ }+ if (Math.hypot(cam.x, cam.z) > 0.6) travelTo(homeDest())+ }+ function interDest(it) {+ if (!it) return null+ if (it.kind === 'door') return doorDest(it)+ return { ...it.view, hi: it.id }+ }++ // ── Sherlock recall: type, and memories fly to you ───────────────────────────────────────────────++ function matchLocal(q) {+ const terms = words(q).filter((t) => t.length >= 2)+ if (!terms.length) return []+ const out = []+ for (const it of INTER) {+ if (it.kind !== 'memory') continue+ const m = it.m+ const title = oneLine(m.title).toLowerCase(), desc = oneLine(m.description).toLowerCase(), body = String(m.body || '').toLowerCase()+ const meta = `${m.project?.name || ''} ${WORLD.agentOf(m.agent).name} ${m.type || ''} ${m.kind || ''}`.toLowerCase()+ let score = 0, ok = true+ for (const t of terms) {+ let s = 0+ const ti = title.indexOf(t)+ if (ti >= 0) s += 8 + (ti === 0 || /\W/.test(title[ti - 1]) ? 3 : 0)+ if (desc.includes(t)) s += 4+ if (meta.includes(t)) s += 2.5+ let c = 0, i = body.indexOf(t)+ while (i >= 0 && c < 6) { c++; i = body.indexOf(t, i + t.length) }+ s += c+ if (!s) { ok = false; break }+ score += s+ }+ if (!ok) continue+ score += 2.5 * (1 - (it.decay || 0))+ out.push({ key: 'm:' + m.id, kind: 'memory', it, score, terms })+ }+ for (const st of WORLD.stones) st.sec.lines.forEach((line, li) => {+ const text = oneLine(line.text).toLowerCase()+ if (terms.every((t) => text.includes(t) || st.sec.name.toLowerCase().includes(t))) out.push({ key: `a:${st.k}:${li}`, kind: 'about', it: st, line, score: 9 + terms.length, terms })+ })+ out.sort((a, b) => b.score - a.score)+ return out.slice(0, 9)+ }++ function snippet(text, terms, len = 200) {+ const s = oneLine(text)+ const low = s.toLowerCase()+ let at = -1+ for (const t of terms) { const i = low.indexOf(t); if (i >= 0 && (at < 0 || i < at)) at = i }+ let a = at < 0 ? 0 : Math.max(0, at - 48)+ if (a > 0) { const sp = s.lastIndexOf(' ', a + 8); if (sp > a - 12 && sp >= 0) a = sp + 1 }+ let out = (a > 0 ? '…' : '') + s.slice(a, a + len)+ for (const t of terms) out = out.replace(new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), (x) => `\u0002${x}\u0003`)+ return out+ }++ /** A card's text, laid out once in card space (metres from its top left). */+ function cardLayout(r) {+ const W0 = 1.56, pad = 0.09, uw = W0 - pad * 2+ const g = []+ let y = pad+ const add = (rows, em, lh = 1.28) => { rows.forEach((row, ri) => { let c = 0; for (const ch of row) { if (ch.ch !== ' ') g.push({ ch: ch.ch, x: pad + c * Atlas.advEm * em, y: y + ri * lh * em, e: em, col: ch.col, a: ch.a ?? 1, hi: ch.hi }); c += 1 } }); y += rows.length * lh * em }+ let color, origin, kick+ const dimInk = [0.72, 0.82, 0.88]+ if (r.kind === 'memory') {+ const m = r.it.m, ag = WORLD.agentOf(m.agent)+ color = r.it.color; origin = r.it.c+ kick = `${String(m.type || m.kind).toUpperCase()} · ${ag.name}${m.project ? ' · ' + m.project.name : ''}`+ add([toChars(middle(kick, colsFor(uw, 0.05)), color, 0.9)], 0.05); y += 0.035+ add(wrapChars(toChars(oneLine(m.title || 'untitled'), mixc(COL.white, color, 0.15), 1), colsFor(uw, 0.092), 2), 0.092, 1.2); y += 0.035+ add(wrapChars(marked(snippet(plain(m.body || m.description || ''), r.terms, 240), dimInk, [1, 1, 1], 0.78, 1), colsFor(uw, 0.06), 5), 0.06, 1.32)+ y += 0.03+ add([toChars(`${ago(m.modified, WORLD.NOW)}`, color, 0.6)], 0.046)+ } else if (r.kind === 'about') {+ color = COL.self; origin = [r.it.c[0], r.it.c[1] + 0.6, r.it.c[2]]+ add([toChars(`ABOUT YOU · ${r.it.sec.name}`, color, 0.9)], 0.05); y += 0.04+ add(wrapChars(marked(snippet(r.line.text, r.terms, 300), mixc(COL.self, COL.white, 0.5), [1, 1, 1], 0.88, 1), colsFor(uw, 0.078), 4), 0.078, 1.28); y += 0.03+ const cites = (r.line.refs ?? []).length+ add([toChars(cites ? `held up by ${cites} source${cites === 1 ? '' : 's'}` : 'about you', color, 0.55)], 0.046)+ } else {+ const h = r.hit, ag = WORLD.agentOf(h.engine)+ color = COL.words+ const ins = WORLD.inscriptions.get(`${h.engine}|${h.at}`)+ r.ins = ins+ const hall = WORLD.wings.find((w) => w.kind === 'words')+ origin = ins ? ins.c : hall ? WP(hall, hall.s1 + 4, 0, 2) : polar(60, cam.yaw + Math.PI, 3)+ add([toChars(`YOU SAID · to ${ag.name} · ${shortDate(h.at)}`, color, 0.9)], 0.05); y += 0.04+ add(wrapChars(marked(h.snippet || '', dimInk, [1, 1, 1], 0.82, 1), colsFor(uw, 0.066), 6), 0.066, 1.32); y += 0.03+ add([toChars(h.title ? middle(oneLine(h.title), 40) : ago(h.at, WORLD.NOW), color, 0.55)], 0.046)+ }+ return { w: W0, h: y + pad, g, color, origin }+ }++ function setCards(list) {+ const old = new Map(recall.cards.map((c) => [c.key, c]))+ const selKey = recall.cards[recall.sel]?.key+ const next = []+ list.forEach((r, i) => {+ let c = old.get(r.key)+ if (c) { old.delete(r.key); c.r = r; const L = cardLayout(r); L.origin = c.L.origin; c.L = L }+ else {+ const L = cardLayout(r)+ c = { key: r.key, r, L, born: clock + i * 0.06, pos: L.origin.slice(), start: L.origin.slice(), live: 0 }+ }+ next.push(c)+ })+ for (const c of old.values()) recall.gone.push({ c, at: clock, mode: 'fade' })+ recall.cards = next+ const keep = next.findIndex((c) => c.key === selKey)+ recall.sel = keep >= 0 ? keep : 0+ }++ function refreshRecall() {+ const q = recall.q+ const local = matchLocal(q)+ const msgs = recall.msgQ === q ? recall.msgs : recall.cards.filter((c) => c.r.kind === 'ask').map((c) => c.r)+ setCards([...local, ...msgs].slice(0, 12))+ clearTimeout(recall.timer)+ if (words(q).some((t) => t.length >= 2)) {+ recall.timer = setTimeout(() => {+ MemoryData.search(q).then((hits) => {+ if (recall.q !== q) return+ const terms = words(q)+ recall.msgs = (hits || []).slice(0, 4).map((hit) => ({ key: `s:${hit.sessionId}:${hit.turn}:${hit.at}`, kind: 'ask', hit, terms }))+ recall.msgQ = q+ setCards([...matchLocal(q), ...recall.msgs].slice(0, 12))+ }).catch(() => {})+ }, 170)+ } else { recall.msgs = []; recall.msgQ = q }+ }+ function typeChar(ch) {+ if (travel) stopTravel()+ if (!recall.q && ch === ' ') return+ recall.q += ch+ recall.chars.push({ ch, born: clock })+ refreshRecall()+ }+ function backspace() {+ if (!recall.chars.length) return+ recall.chars.pop()+ recall.q = recall.chars.map((c) => c.ch).join('')+ if (!recall.q.trim()) { dismissRecall(false); return }+ refreshRecall()+ }+ function dismissRecall(sweep = true, keepKey = null) {+ const lx = -Math.cos(cam.yaw), lz = -Math.sin(cam.yaw)+ for (const c of recall.cards) if (c.key !== keepKey) recall.gone.push({ c, at: clock, mode: sweep ? 'sweep' : 'fade', vx: lx * 9, vz: lz * 9 })+ if (recall.chars.length) recall.goneWords.push({ frames: wordFrames(), at: clock, vx: lx * 8, vz: lz * 8 })+ recall.cards = []; recall.chars = []; recall.q = ''; recall.sel = 0; recall.msgs = []; recall.msgQ = ''+ clearTimeout(recall.timer)+ }+ function chooseCard() {+ const c = recall.cards[recall.sel]+ if (!c) return+ const r = c.r+ dismissRecall(true)+ if (r.kind === 'memory') travelTo(interDest(r.it))+ else if (r.kind === 'about') travelTo(interDest(r.it))+ else if (r.ins) travelTo(interDest(r.ins))+ else openRead({ kind: 'hit', hit: r.hit }, null)+ }++ /** Where the floating words of the query hang right now: one billboard frame per word. */+ function wordFrames() {+ const groups = []+ let cur = null+ recall.chars.forEach((c) => {+ if (c.ch === ' ') { cur = null; return }+ if (!cur) groups.push((cur = []))+ cur.push(c)+ })+ const n = groups.length+ const em = 0.27+ return groups.map((g, wi) => {+ const a = cam.yaw + (wi - (n - 1) / 2) * 17 * DEG + Math.sin(wi * 2.1) * 2 * DEG+ const dist = 3.5 + (wi % 2) * 0.4+ const px = cam.x + Math.sin(a) * dist, pz = cam.z - Math.cos(a) * dist+ const nrm = [-Math.sin(a), 0, Math.cos(a)]+ const rt = [nrm[2], 0, -nrm[0]]+ const bobT = reduced ? 0 : clock+ const y = EYE + 1.22 + (wi % 2 ? 0.2 : 0) + Math.sin(bobT * 1.1 + wi * 1.9) * 0.045+ const width = g.length * Atlas.advEm * em+ const o = [px - rt[0] * width / 2, y, pz - rt[2] * width / 2]+ return { o, rt, em, chars: g }+ })+ }++ // ── reading a memory up close ────────────────────────────────────────────────────────────────────++ const R_ = { read: $('read'), sheet: $('sheet'), kicker: $('r-kicker'), title: $('r-title'), meta: $('r-meta'), links: $('r-links'), body: $('r-body'), foot: $('r-foot') }+ function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e }++ function openRead(item, it) {+ reader.open = true; reader.item = item; reader.links = []; reader.sel = -1; reader.restore = null+ const { sheet } = R_+ R_.kicker.textContent = ''; R_.title.textContent = ''; R_.meta.textContent = ''; R_.links.textContent = ''; R_.body.textContent = ''; R_.foot.textContent = ''+ let accent = COL.struct+ const meta = (...parts) => parts.filter(Boolean).forEach((p) => R_.meta.appendChild(el('span', null, p)))+ if (item.kind === 'memory') {+ const m = item.m, ag = WORLD.agentOf(m.agent)+ accent = lift(hexRGB(ag.color))+ R_.kicker.textContent = `${m.type || m.kind || 'memory'} · ${ag.name}${m.project ? ' · ' + m.project.name : ' · every project'}`+ R_.title.textContent = oneLine(m.title || 'untitled')+ meta(ago(m.modified, WORLD.NOW), dateOf(m.modified), m.kind ? `kind: ${m.kind}` : '', m.size ? `${fmt(m.size)} bytes` : '')+ const cited = WORLD.reverse.get(m.id) || []+ if (cited.length) {+ R_.links.appendChild(el('div', 'head', 'About You stands on this'))+ for (const c of cited) addLink(`${c.text}`, c.section, COL.self, () => travelTo(interDest(WORLD.stones[c.k])))+ }+ const body = clean(m.body || '')+ const desc = oneLine(m.description || '')+ R_.body.textContent = (desc && !body.toLowerCase().includes(desc.toLowerCase().slice(0, 40)) ? desc + '\n\n' : '') + body+ R_.foot.textContent = m.path || ''+ const d = it?.decay ?? 0+ if (d > 0.12 && !reduced) startRestore(R_.body.textContent, d)+ } else if (item.kind === 'stone') {+ const sec = item.sec+ accent = COL.self+ R_.kicker.textContent = 'about you'+ R_.title.textContent = sec.name+ const ab = WORLD.snap.about || {}+ meta(ab.intro ? oneLine(ab.intro) : '', ab.modified ? `written ${ago(ab.modified, WORLD.NOW)}` : '')+ for (const line of sec.lines) {+ R_.links.appendChild(el('div', 'line', oneLine(line.text)))+ const asksRef = (line.refs ?? []).filter((r) => String(r).startsWith('asks:'))+ for (const m of line.mems) {+ const ag = WORLD.agentOf(m.agent)+ addLink(oneLine(m.title), `${ag.name}${m.project ? ' · ' + m.project.name : ''} · ${ago(m.modified, WORLD.NOW)}`, lift(hexRGB(ag.color)), () => travelTo(interDest(WORLD.memInter.get(m.id))))+ }+ for (const r of asksRef) { const n = Number(String(r).split(':')[1]) || 0; R_.links.appendChild(el('div', 'link', `from ${fmt(n)} of your messages`)).classList.add('static') }+ }+ R_.foot.textContent = WORLD.snap.aboutPath || ''+ } else {+ const a = item.kind === 'hit' ? item.hit : item.a+ const ag = WORLD.agentOf(a.engine)+ accent = COL.words+ R_.kicker.textContent = `you said · to ${ag.name}`+ R_.title.textContent = `${dateOf(a.at)} ${timeOf(a.at)}`+ meta(ago(a.at, WORLD.NOW), a.title ? oneLine(a.title) : '', a.cwd ? tail(a.cwd, 48) : '', a.turn != null ? `turn ${a.turn + 1}` : '')+ if (item.kind === 'hit') {+ let hi = false+ for (const part of clean(a.snippet || '').split(/([\u0002\u0003])/)) {+ if (part === '\u0002') { hi = true; continue }+ if (part === '\u0003') { hi = false; continue }+ if (!part) continue+ const span = el('span', null, part)+ if (hi) { span.style.color = '#fff'; span.style.textShadow = '0 0 10px rgba(190,170,255,0.9)' }+ R_.body.appendChild(span)+ }+ } else R_.body.textContent = clean(a.text || item.text || '')+ R_.foot.textContent = a.sessionId ? `session ${a.sessionId}` : ''+ }+ sheet.style.setProperty('--accent', css(accent))+ R_.read.hidden = false+ sheet.scrollTop = 0+ // the memory comes to you: from where it hangs on the wall to the middle of the screen+ sheet.classList.remove('fly')+ const rect = it ? screenRect(it) : null+ if (rect && !reduced) {+ const f = sheet.getBoundingClientRect()+ sheet.style.transform = `translate(${rect.x - f.left}px, ${rect.y - f.top}px) scale(${Math.max(0.05, rect.w / f.width)}, ${Math.max(0.05, rect.h / f.height)})`+ sheet.style.opacity = '0.2'+ void sheet.offsetWidth+ sheet.classList.add('fly')+ }+ sheet.style.transform = 'none'; sheet.style.opacity = '1'+ updateKeys()+ }+ function addLink(text, sub, col, go) {+ const d = el('div', 'link')+ const dot = el('span', 'dot'); dot.style.background = css(col); dot.style.boxShadow = `0 0 8px ${css(col, 0.8)}`+ d.appendChild(dot); d.appendChild(el('span', null, text))+ if (sub) { d.appendChild(el('span', 'sub', ' ' + sub)) }+ R_.links.appendChild(d)+ reader.links.push({ node: d, go })+ }+ function selectLink(i) {+ if (!reader.links.length) return+ reader.sel = ((i % reader.links.length) + reader.links.length) % reader.links.length+ reader.links.forEach((l, j) => l.node.classList.toggle('on', j === reader.sel))+ reader.links[reader.sel].node.scrollIntoView({ block: 'nearest' })+ }+ function closeRead(then) {+ if (!reader.open) return+ reader.open = false; reader.restore = null+ R_.read.hidden = true+ R_.sheet.classList.remove('fly')+ updateKeys()+ if (then) then()+ }+ /** Old memories come back whole as you look at them: the lost letters at the edges fill in. */+ function startRestore(text, decay) {+ const lines = text.split('\n').slice(0, 160)+ const rest = text.split('\n').slice(160).join('\n')+ const masks = lines.map((line, li) => Array.from(line).map((ch, i, arr) => {+ const u = arr.length > 1 ? i / (arr.length - 1) : 0.5+ const edge = Math.abs(u * 2 - 1)+ const lose = Math.pow(decay, 1.7) * (sstep(0.55, 1, edge) * 1.3 + 0.02)+ const r = hash3(li, i, 99)+ return r < lose ? r / Math.max(lose, 1e-3) : -1+ }))+ reader.restore = { lines, rest, masks, t0: performance.now(), dur: 1100 }+ stepRestore(0)+ }+ function stepRestore(f) {+ const r = reader.restore+ if (!r) return+ const out = r.lines.map((line, li) => Array.from(line).map((ch, i) => (r.masks[li][i] > f ? ' ' : ch)).join(''))+ R_.body.textContent = out.join('\n') + (r.rest ? '\n' + r.rest : '')+ if (f >= 1) reader.restore = null+ }+ function screenRect(it) {+ const corners = []+ for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {+ const p = [it.c[0] + it.rt[0] * it.hw * sx, it.c[1] + it.hh * sy, it.c[2] + it.rt[2] * it.hw * sx]+ const s = project(p)+ if (!s) return null+ corners.push(s)+ }+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1])+ const x = Math.min(...xs), y = Math.min(...ys)+ return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y }+ }+ function project(p) {+ const m = VP+ const x = m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12]+ const y = m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13]+ const w = m[3] * p[0] + m[7] * p[1] + m[11] * p[2] + m[15]+ if (w < 0.08) return null+ return [(x / w * 0.5 + 0.5) * cssW, (1 - (y / w * 0.5 + 0.5)) * cssH, w]+ }++ function activate() {+ const it = target+ if (!it) { return }+ if (it.kind === 'door') { travelTo(doorDest(it)); return }+ if (it.kind === 'memory') openRead({ kind: 'memory', m: it.m }, it)+ else if (it.kind === 'stone') openRead({ kind: 'stone', sec: it.sec }, it)+ else if (it.kind === 'ask') openRead({ kind: 'ask', a: it.a, text: it.text }, it)+ }++ // ── the map ──────────────────────────────────────────────────────────────────────────────────────++ function openMap() {+ mapUI.open = true+ const here = locate(cam.x, cam.z)+ mapUI.sel = here.wing ? here.wing.i : 0+ updateKeys()+ }+ function closeMap() { if (mapUI.open) { mapUI.open = false; updateKeys() } }++ function drawMap(ctx, x0, y0, w, h, cx, cz, scale, big) {+ ctx.save()+ ctx.beginPath(); ctx.rect(x0, y0, w, h); ctx.clip()+ ctx.fillStyle = big ? 'rgba(0, 4, 8, 0.86)' : 'rgba(0, 6, 10, 0.62)'+ ctx.fillRect(x0, y0, w, h)+ const ox = x0 + w / 2, oy = y0 + h / 2+ const X = (x) => ox + (x - cx) * scale, Y = (z) => oy + (z - cz) * scale+ const selW = big ? WORLD.wings[mapUI.sel] : null+ ctx.lineCap = 'round'+ for (const pass of [0, 1]) {+ ctx.beginPath()+ for (const s of MAPSEG) {+ const isSel = selW && s[5] === selW.i+ if ((pass === 1) !== !!isSel) continue+ if (s[4] === 'stone') continue+ ctx.moveTo(X(s[0]), Y(s[1])); ctx.lineTo(X(s[2]), Y(s[3]))+ }+ ctx.strokeStyle = pass ? 'rgba(160, 235, 255, 0.95)' : 'rgba(90, 215, 255, 0.42)'+ ctx.lineWidth = (pass ? 1.6 : 1) * dpr+ ctx.shadowColor = 'rgba(90, 215, 255, 0.8)'; ctx.shadowBlur = pass ? 8 * dpr : 0+ ctx.stroke()+ }+ ctx.shadowBlur = 0+ ctx.beginPath()+ for (const s of MAPSEG) if (s[4] === 'stone') { ctx.moveTo(X(s[0]), Y(s[1])); ctx.lineTo(X(s[2]), Y(s[3])) }+ ctx.strokeStyle = 'rgba(255, 196, 120, 0.85)'; ctx.lineWidth = 1.2 * dpr; ctx.stroke()+ // memories as dots, dimmer when old+ for (const it of INTER) {+ if (it.kind !== 'memory' && it.kind !== 'ask') continue+ ctx.fillStyle = css(it.color, 0.85 * (1 - (it.decay || 0) * 0.65))+ const r = (big ? 1.7 : 1.2) * dpr+ ctx.fillRect(X(it.c[0]) - r, Y(it.c[2]) - r, r * 2, r * 2)+ }+ if (big) {+ ctx.font = `${11 * dpr}px ui-monospace, "SF Mono", Menlo, monospace`+ ctx.textBaseline = 'middle'+ for (const w2 of WORLD.wings) {+ const p = WP(w2, w2.sEnd + 2.5, 0, 0)+ const on = selW === w2+ const sx = X(p[0]), sy = Y(p[2])+ ctx.textAlign = Math.abs(w2.d[0]) < 0.25 ? 'center' : w2.d[0] > 0 ? 'left' : 'right'+ ctx.fillStyle = on ? '#ffffff' : css(COL.label, 0.4 + 0.5 * w2.act)+ ctx.shadowColor = 'rgba(90, 215, 255, 0.9)'; ctx.shadowBlur = on ? 10 * dpr : 0+ ctx.fillText(w2.label, sx, sy + (Math.abs(w2.d[0]) < 0.25 ? Math.sign(w2.d[1]) * 4 * dpr : 0))+ }+ ctx.textAlign = 'center'+ ctx.shadowBlur = 0+ ctx.fillStyle = css(COL.self, 0.9); ctx.fillText('you', X(0), Y(0) + 14 * dpr)+ }+ // the path being travelled+ if (travel) {+ ctx.beginPath()+ travel.path.pts.forEach((p, i) => (i ? ctx.lineTo(X(p[0]), Y(p[1])) : ctx.moveTo(X(p[0]), Y(p[1]))))+ ctx.strokeStyle = css(COL.path, 0.95); ctx.lineWidth = 1.6 * dpr; ctx.shadowColor = css(COL.path); ctx.shadowBlur = 8 * dpr; ctx.stroke(); ctx.shadowBlur = 0+ }+ // where the chosen recall lives+ const chosen = recall.cards[recall.sel]+ if (chosen) {+ const o = chosen.L.origin, pulse2 = (clock * 1.2) % 1+ ctx.beginPath(); ctx.arc(X(o[0]), Y(o[2]), (2.5 + pulse2 * 7) * dpr, 0, TAU)+ ctx.strokeStyle = css(chosen.L.color, 0.9 * (1 - pulse2)); ctx.lineWidth = 1.3 * dpr; ctx.stroke()+ ctx.fillStyle = css(chosen.L.color, 1); ctx.fillRect(X(o[0]) - 2 * dpr, Y(o[2]) - 2 * dpr, 4 * dpr, 4 * dpr)+ }+ // you are here+ const px = X(cam.x), py = Y(cam.z), fx = Math.sin(cam.yaw), fz = -Math.cos(cam.yaw)+ const s = (big ? 9 : 7) * dpr+ ctx.beginPath()+ ctx.moveTo(px + fx * s, py + fz * s)+ ctx.lineTo(px - fx * s * 0.6 - fz * s * 0.55, py - fz * s * 0.6 + fx * s * 0.55)+ ctx.lineTo(px - fx * s * 0.25, py - fz * s * 0.25)+ ctx.lineTo(px - fx * s * 0.6 + fz * s * 0.55, py - fz * s * 0.6 - fx * s * 0.55)+ ctx.closePath()+ ctx.fillStyle = '#fff'; ctx.shadowColor = 'rgba(255,255,255,0.9)'; ctx.shadowBlur = 10 * dpr; ctx.fill(); ctx.shadowBlur = 0+ const pulse = (clock * 0.8) % 1+ ctx.beginPath(); ctx.arc(px, py, s * (1 + pulse * 2.2), 0, TAU); ctx.strokeStyle = `rgba(255,255,255,${0.5 * (1 - pulse)})`; ctx.lineWidth = dpr; ctx.stroke()+ ctx.restore()+ ctx.strokeStyle = big ? 'rgba(90, 215, 255, 0.35)' : 'rgba(90, 215, 255, 0.22)'+ ctx.lineWidth = dpr+ ctx.strokeRect(x0 + 0.5, y0 + 0.5, w - 1, h - 1)+ }++ // ── the HUD: brackets on what you face, the map, the prompt, the key line ────────────────────────++ function drawHud() {+ const ctx = hctx+ ctx.setTransform(1, 0, 0, 1, 0, 0)+ ctx.clearRect(0, 0, pxW, pxH)+ if (!ready) return+ const showTarget = target && !travel && !reader.open && !mapUI.open && !recall.cards.length && !arrival+ if (showTarget) {+ const r = screenRect(target)+ if (r) {+ const x = clamp(r.x, 8, cssW - 8) * dpr, y = clamp(r.y, 8, cssH - 8) * dpr+ const x2 = clamp(r.x + r.w, 8, cssW - 8) * dpr, y2 = clamp(r.y + r.h, 8, cssH - 8) * dpr+ const pulse = reduced ? 0 : (Math.sin(clock * 3) * 0.5 + 0.5) * 4 * dpr+ const L = Math.min(22 * dpr, (x2 - x) / 4, (y2 - y) / 4)+ const c = target.color+ ctx.strokeStyle = css(mixc(c, COL.white, 0.35), 0.95)+ ctx.lineWidth = 1.4 * dpr+ ctx.shadowColor = css(c, 0.9); ctx.shadowBlur = 10 * dpr+ ctx.beginPath()+ for (const [cx, cy, sx, sy] of [[x - pulse, y - pulse, 1, 1], [x2 + pulse, y - pulse, -1, 1], [x2 + pulse, y2 + pulse, -1, -1], [x - pulse, y2 + pulse, 1, -1]]) {+ ctx.moveTo(cx + sx * L, cy); ctx.lineTo(cx, cy); ctx.lineTo(cx, cy + sy * L)+ }+ ctx.stroke()+ ctx.shadowBlur = 0+ const verb = target.kind === 'door' ? (doorBack(target) ? 'back to' : 'enter') : 'read'+ const label = `↵ ${verb} ${middle(oneLine(doorBack(target) || target.label || ''), 54)}`+ ctx.font = `${12 * dpr}px ui-monospace, "SF Mono", Menlo, monospace`+ ctx.textAlign = 'center'; ctx.textBaseline = 'top'+ const ly = Math.min(y2 + 10 * dpr + pulse, (cssH - 74) * dpr)+ const tw = ctx.measureText(label).width+ const lx = clamp((x + x2) / 2, tw / 2 + 12 * dpr, pxW - tw / 2 - 12 * dpr)+ ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'; ctx.fillRect(lx - tw / 2 - 8 * dpr, ly - 4 * dpr, tw + 16 * dpr, 20 * dpr)+ ctx.fillStyle = css(mixc(c, COL.white, 0.5), 0.95)+ ctx.fillText(label, lx, ly)+ }+ }+ // tiny map, always; the big one on tab+ const mm = Math.round(Math.min(150, cssW * 0.16)) * dpr+ if (!reader.open) drawMap(ctx, pxW - mm - 14 * dpr, 14 * dpr, mm, mm, cam.x, cam.z, (mm / 72), false)+ if (mapUI.open) {+ const pad = 40 * dpr+ const w = pxW - pad * 2, h = pxH - pad * 2 - 30 * dpr+ const b = WORLD.bounds+ const scale = Math.min(w / (b.x1 - b.x0 + 70), h / (b.z1 - b.z0 + 16))+ drawMap(ctx, pad, pad, w, h, (b.x0 + b.x1) / 2, (b.z0 + b.z1) / 2, scale, true)+ }+ }++ const where = $('where'), mode = $('mode'), promptEl = $('prompt'), keysEl = $('keys')+ let lastWhere = ''+ function updateWhere() {+ const here = locate(cam.x, cam.z)+ let parts+ if (!here.wing) parts = ['you', here.r < R_STONE ? 'among the stones' : 'the atrium']+ else {+ const w = here.wing+ parts = ['you', w.label]+ if (here.room < 0) parts.push('corridor')+ else { const room = w.rooms[here.room]; parts.push(`${room.title}${room.parts > 1 ? ` ${room.part}/${room.parts}` : ''} · room ${here.room + 1} of ${w.rooms.length}`) }+ }+ const text = parts.join(' › ')+ if (text === lastWhere) return+ lastWhere = text+ where.textContent = ''+ parts.forEach((p, i) => { if (i) where.appendChild(document.createTextNode(' › ')); where.appendChild(i === parts.length - 1 ? el('b', null, p) : document.createTextNode(p)) })+ }+ let lastKeys = ''+ function updateKeys() {+ let k+ if (!ready) k = []+ else if (arrival) k = [['any key', 'skip']]+ else if (reader.open) k = reader.links.length ? [['↑↓', 'scroll'], ['tab', 'choose'], ['↵', 'go there'], ['esc', 'back']] : [['↑↓', 'scroll'], ['space', 'page'], ['esc', 'back']]+ else if (mapUI.open) k = [['←→', 'wing'], ['↵', 'go'], ['esc', 'close']]+ else if (recall.chars.length) k = [['tab ←→', 'choose'], ['↵', 'go there'], ['⌫', 'edit'], ['esc', 'sweep away']]+ else if (travel) k = [['esc', 'stop']]+ else k = [['↑↓', 'walk'], ['←→', 'turn'], ['⇧←→', 'step aside'], ['↵', 'enter / read'], ['type', 'recall'], ['tab', 'map'], ['~', 'home'], ['esc', 'back']]+ const sig = JSON.stringify(k)+ if (sig === lastKeys) return+ lastKeys = sig+ keysEl.textContent = ''+ k.forEach(([a, b], i) => { if (i) keysEl.appendChild(document.createTextNode(' ')); keysEl.appendChild(el('kbd', null, a)); keysEl.appendChild(document.createTextNode(' ' + b)) })+ }+ let lastPrompt = ''+ function updatePrompt() {+ const q = recall.q+ const nm = recall.cards.filter((c) => c.r.kind !== 'ask').length, na = recall.cards.filter((c) => c.r.kind === 'ask').length+ const sig = q + '|' + nm + '|' + na + '|' + recall.sel+ if (sig === lastPrompt) return+ lastPrompt = sig+ promptEl.textContent = ''+ if (!recall.chars.length) return+ promptEl.appendChild(document.createTextNode('› ' + q))+ promptEl.appendChild(el('span', 'caret'))+ const words2 = words(q).filter((t) => t.length >= 2).length+ const count = !words2 ? 'keep typing' : (nm || na) ? `${nm} ${nm === 1 ? 'memory' : 'memories'}${na ? ` · ${na} ${na === 1 ? 'message' : 'messages'}` : ''} · ${recall.sel + 1}/${recall.cards.length}` : 'nothing remembered'+ promptEl.appendChild(el('span', 'count', count))+ }++ // ── input ────────────────────────────────────────────────────────────────────────────────────────++ function skipArrival() { arrival = false; clock = Math.max(clock, ARRIVE + 0.5); cam.y = EYE; cam.pitch = 0; cam.yaw = 0; updateKeys() }++ window.addEventListener('keydown', (e) => {+ if (!ready) return+ if (e.metaKey || e.ctrlKey) return+ const k = e.key+ const nav = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Tab', ' ', 'PageUp', 'PageDown', 'Home', 'End', 'Enter', 'Escape', 'Backspace']+ if (nav.includes(k)) e.preventDefault()+ if (arrival) { skipArrival(); return }+ if (reader.open) {+ const sh = R_.sheet+ if (k === 'Escape') closeRead()+ else if (k === 'ArrowDown' || k === 'j') sh.scrollTop += 48+ else if (k === 'ArrowUp' || k === 'k') sh.scrollTop -= 48+ else if (k === ' ' || k === 'PageDown') sh.scrollTop += sh.clientHeight * 0.85+ else if (k === 'PageUp') sh.scrollTop -= sh.clientHeight * 0.85+ else if (k === 'Home' || k === 'g') sh.scrollTop = 0+ else if (k === 'End' || k === 'G') sh.scrollTop = sh.scrollHeight+ else if (k === 'Tab') selectLink(reader.sel + (e.shiftKey ? -1 : 1))+ else if (k === 'Enter' && reader.links.length) { const l = reader.links[Math.max(0, reader.sel)]; closeRead(l.go) }+ return+ }+ if (mapUI.open) {+ const n = WORLD.wings.length+ if (k === 'Escape' || k === 'Tab') closeMap()+ else if ((k === 'ArrowRight' || k === 'ArrowDown') && n) mapUI.sel = (mapUI.sel + 1) % n+ else if ((k === 'ArrowLeft' || k === 'ArrowUp') && n) mapUI.sel = (mapUI.sel + n - 1) % n+ else if (k === 'Enter' && n) { const w = WORLD.wings[mapUI.sel]; const s = w.s1 + 2.4; const p = WP(w, s, 0, 0); closeMap(); travelTo({ x: p[0], z: p[2], yaw: w.theta, wing: w, s }) }+ else if (k.length === 1 && k !== ' ') { closeMap(); typeChar(k) }+ return+ }+ if (recall.chars.length) {+ const n = recall.cards.length+ if (k === 'Escape') dismissRecall(true)+ else if (k === 'Backspace') backspace()+ else if (k === 'Enter') chooseCard()+ else if ((k === 'Tab' && !e.shiftKey) || k === 'ArrowRight' || k === 'ArrowDown') { if (n) recall.sel = (recall.sel + 1) % n }+ else if ((k === 'Tab' && e.shiftKey) || k === 'ArrowLeft' || k === 'ArrowUp') { if (n) recall.sel = (recall.sel + n - 1) % n }+ else if (k.length === 1 && !e.altKey) typeChar(k)+ updateKeys()+ return+ }+ if (k === 'Escape') { if (travel) stopTravel(); else stepBack() }+ else if (k === 'Enter') { if (!travel) activate() }+ else if (k === 'Tab') openMap()+ else if (k === '~' || k === '`' || k === 'Home') travelTo(homeDest())+ else if (k.startsWith('Arrow')) { if (travel) stopTravel(); keys[k] = true; keys.shift = e.shiftKey }+ else if (k === 'Shift') keys.shift = true+ else if (k.length === 1 && k !== ' ' && !e.altKey) typeChar(k)+ updateKeys()+ })+ window.addEventListener('keyup', (e) => { keys[e.key] = false; if (e.key === 'Shift') keys.shift = false; else keys.shift = e.shiftKey })+ window.addEventListener('blur', () => { for (const k in keys) keys[k] = false })+ canvas.addEventListener('pointerdown', () => canvas.focus())++ // ── the frame ────────────────────────────────────────────────────────────────────────────────────++ function update(dt) {+ if (arrival) {+ const t = smoother(clock / 4.4)+ cam.y = EYE + 1.5 * (1 - t); cam.pitch = -0.34 * (1 - t); cam.yaw = -0.5 * (1 - t)+ if (clock >= ARRIVE) { arrival = false; updateKeys() }+ }+ let fovBoost = 0+ if (travel) {+ const tr = travel+ if (tr.phase === 'show') { tr.show += dt; if (tr.show > 0.45) tr.phase = 'move' }+ else if (tr.phase === 'move') {+ const prev = smoother(tr.t / tr.T) * tr.path.len+ tr.t = Math.min(tr.T, tr.t + dt)+ const d = smoother(tr.t / tr.T) * tr.path.len+ const p = sampleAt(tr.path, d), q = sampleAt(tr.path, Math.min(tr.path.len, d + 2.2))+ cam.x = p[0]; cam.z = p[1]+ const speed = (d - prev) / Math.max(dt, 1e-3)+ fovBoost = clamp(speed / 22, 0, 1) * 9+ let want = Math.hypot(q[0] - p[0], q[1] - p[1]) > 0.2 ? Math.atan2(q[0] - p[0], -(q[1] - p[1])) : cam.yaw+ const u = d / Math.max(tr.path.len, 1e-3)+ want = angLerp(want, tr.dest.yaw, sstep(0.62, 1.0, u))+ cam.yaw = angLerp(cam.yaw, want, 1 - Math.exp(-dt * 7))+ if (tr.t >= tr.T) { tr.phase = 'settle'; tr.settle = 0 }+ } else {+ tr.settle += dt+ cam.yaw = angLerp(cam.yaw, tr.dest.yaw, 1 - Math.exp(-dt * 9))+ if (tr.settle > 0.5 || Math.abs(angWrap(cam.yaw - tr.dest.yaw)) < 0.002) {+ cam.yaw = tr.dest.yaw+ if (tr.dest.hi) hiPulse = { id: tr.dest.hi, until: clock + 2.4 }+ travel = null; updateKeys()+ }+ }+ } else if (!arrival && !reader.open && !mapUI.open && !recall.chars.length) {+ const fwd = (keys.ArrowUp ? 1 : 0) - (keys.ArrowDown ? 1 : 0)+ const side = (keys.ArrowRight ? 1 : 0) - (keys.ArrowLeft ? 1 : 0)+ const strafe = keys.shift ? side : 0, turn = keys.shift ? 0 : side+ cam.v += (fwd * 4.4 - cam.v) * (1 - Math.exp(-dt * 5.5))+ cam.sv += (strafe * 3.0 - cam.sv) * (1 - Math.exp(-dt * 6))+ cam.w += (turn * 1.9 - cam.w) * (1 - Math.exp(-dt * 8))+ cam.yaw += cam.w * dt+ const fx = Math.sin(cam.yaw), fz = -Math.cos(cam.yaw)+ const nx = cam.x + (fx * cam.v + Math.cos(cam.yaw) * cam.sv) * dt, nz = cam.z + (fz * cam.v + Math.sin(cam.yaw) * cam.sv) * dt+ const [cx, cz] = collide(nx, nz)+ cam.x = cx; cam.z = cz+ const moving = Math.hypot(cam.v, cam.sv)+ if (!reduced) cam.bob += dt * moving * 2.2+ } else { cam.v = cam.w = cam.sv = 0 }+ cam.fov = lerp(cam.fov, 62 + fovBoost, 1 - Math.exp(-dt * 6))+ dim = lerp(dim, reader.open ? 1 : mapUI.open ? 0.55 : 0, 1 - Math.exp(-dt * 10))+ recallDim = lerp(recallDim, recall.chars.length ? 1 : 0, 1 - Math.exp(-dt * (recall.chars.length ? 5 : 8)))+ if (reader.restore) { const f = (performance.now() - reader.restore.t0) / reader.restore.dur; stepRestore(clamp(f, 0, 1)) }+ target = (!travel && !arrival && !reader.open) ? pick() : null+ }++ function render() {+ resize()+ if (Atlas.dirty) uploadAtlas()+ const aspect = pxW / pxH+ perspective(P_, cam.fov * DEG, aspect, 0.1, 300)+ const bob = reduced ? 0 : Math.sin(cam.bob * 2) * 0.022 * Math.min(1, Math.abs(cam.v) / 3)+ const eye = [cam.x, cam.y + bob, cam.z]+ const cp = Math.cos(cam.pitch)+ lookAt(V_, eye, [eye[0] + Math.sin(cam.yaw) * cp, eye[1] + Math.sin(cam.pitch), eye[2] - Math.cos(cam.yaw) * cp], [0, 1, 0])+ mul(VP, P_, V_)+ const T = targets+ gl.bindFramebuffer(gl.FRAMEBUFFER, T.scene.fb)+ gl.viewport(0, 0, pxW, pxH)+ gl.clearColor(0, 0, 0, 1); gl.clearDepth(1); gl.depthMask(true)+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)+ const fog = 44+ const hi = target ? target.id : 0+ const hi2 = hiPulse.until > clock ? hiPulse.id : 0+ const common = (p) => {+ gl.useProgram(p.p)+ gl.uniformMatrix4fv(p.u.uVP, false, VP)+ if (p.u.uT) gl.uniform1f(p.u.uT, clock)+ if (p.u.uFog) gl.uniform1f(p.u.uFog, fog)+ if (p.u.uHi) gl.uniform1f(p.u.uHi, hi)+ if (p.u.uHi2) gl.uniform1f(p.u.uHi2, hi2)+ if (p.u.uFlick) gl.uniform1f(p.u.uFlick, reduced ? 0 : 1)+ if (p.u.uRes) gl.uniform2f(p.u.uRes, pxW, pxH)+ if (p.u.uPx) gl.uniform1f(p.u.uPx, dpr)+ if (p.u.uDraw) gl.uniform1f(p.u.uDraw, 0)+ if (p.u.uWorld) gl.uniform1f(p.u.uWorld, 1 - 0.74 * recallDim)+ }+ // black walls first, so lines behind them are hidden+ gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.depthMask(true)+ gl.disable(gl.BLEND)+ gl.enable(gl.POLYGON_OFFSET_FILL); gl.polygonOffset(1, 2)+ common(prog.fill); drawChunks(chunks.fills, FILL_L)+ gl.disable(gl.POLYGON_OFFSET_FILL)+ gl.depthMask(false)+ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)+ dynSlot = 0+ const dyn = buildDynamic()+ common(prog.line); drawChunks(chunks.lines, LINE_L)+ gl.uniform1f(prog.line.u.uDraw, 1); drawDyn(dyn.linesDepth, LINE_L)+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, atlasTex)+ common(prog.glyph); gl.uniform1i(prog.glyph.u.uAtlas, 0); drawChunks(chunks.glyphs, GLYPH_L)+ // what floats in the air: over everything+ gl.disable(gl.DEPTH_TEST)+ gl.uniform1f(prog.glyph.u.uHi, 0); gl.uniform1f(prog.glyph.u.uHi2, 0); gl.uniform1f(prog.glyph.u.uWorld, 1)+ drawDyn(dyn.back, GLYPH_L)+ common(prog.line); gl.uniform1f(prog.line.u.uDraw, 1); gl.uniform1f(prog.line.u.uHi, 0); gl.uniform1f(prog.line.u.uHi2, 0); gl.uniform1f(prog.line.u.uWorld, 1); drawDyn(dyn.linesTop, LINE_L)+ common(prog.glyph); gl.uniform1i(prog.glyph.u.uAtlas, 0); gl.uniform1f(prog.glyph.u.uHi, 0); gl.uniform1f(prog.glyph.u.uHi2, 0); gl.uniform1f(prog.glyph.u.uWorld, 1); drawDyn(dyn.glyphs, GLYPH_L)+ gl.disable(gl.BLEND)+ // bloom+ gl.bindBuffer(gl.ARRAY_BUFFER, triBuf); layout(POST_L)+ const pass = (p, dst, setup) => { gl.bindFramebuffer(gl.FRAMEBUFFER, dst ? dst.fb : null); gl.viewport(0, 0, dst ? dst.w : pxW, dst ? dst.h : pxH); gl.useProgram(p.p); setup(p.u); gl.drawArrays(gl.TRIANGLES, 0, 3) }+ const tex = (unit, t, loc) => { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, t.tex); gl.uniform1i(loc, unit) }+ const down = (src, dst, gain, knee = 0) => pass(prog.down, dst, (u) => { tex(0, src, u.uSrc); gl.uniform2f(u.uTexel, 1 / src.w, 1 / src.h); gl.uniform1f(u.uGain, gain); gl.uniform1f(u.uKnee, knee) })+ const blur = (src, tmp) => {+ pass(prog.blur, tmp, (u) => { tex(0, src, u.uSrc); gl.uniform2f(u.uDir, 1 / src.w, 0) })+ pass(prog.blur, src, (u) => { tex(0, tmp, u.uSrc); gl.uniform2f(u.uDir, 0, 1 / tmp.h) })+ }+ down(T.scene, T.b1, 1.2, 0.07)+ down(T.b1, T.b2, 1.15); blur(T.b2, T.t2)+ down(T.b2, T.b3, 1.1); blur(T.b3, T.t3)+ down(T.b3, T.b4, 1.1); blur(T.b4, T.t4)+ pass(prog.comp, null, (u) => {+ tex(0, T.scene, u.uScene); tex(1, T.b1, u.uB1); tex(2, T.b2, u.uB2); tex(3, T.b3, u.uB3); tex(4, T.b4, u.uB4)+ gl.uniform2f(u.uRes, pxW, pxH); gl.uniform1f(u.uDim, dim); gl.uniform1f(u.uT, clock); gl.uniform1f(u.uPx, dpr); gl.uniform1f(u.uScan, 1); gl.uniform1f(u.uFade, fade)+ })+ }++ /** Per-frame geometry: the travel path, belief strings, recall words and cards. */+ function buildDynamic() {+ const linesDepth = [], linesTop = [], back = [], glyphs = []+ const up = [0, 1, 0]+ // the path, drawn ahead of you on the floor, dashes running toward the goal+ if (travel) {+ const tr = travel, path = tr.path+ const from = tr.phase === 'show' ? 0 : smoother(tr.t / tr.T) * path.len+ const to = tr.phase === 'show' ? path.len * easeOut(tr.show / 0.45) : path.len+ const step = 0.5+ for (let d = from; d < to - 0.01; d += step) {+ const a = sampleAt(path, d), b = sampleAt(path, Math.min(to, d + step))+ const dash = ((d / 1.4 - clock * 3) % 1 + 1) % 1+ const al = (dash < 0.5 ? 1 : 0.35) * (0.5 + 0.5 * sstep(0, 6, d - from))+ seg([a[0], 0.05, a[1]], [b[0], 0.05, b[1]], COL.path, al, 2.2, 0, 0, 0, linesDepth)+ }+ const e = path.pts[path.pts.length - 1]+ for (let i = 0; i < 5; i++) { const a = (i / 5) * TAU + clock; seg([e[0] + Math.cos(a) * 0.3, 0.02, e[1] + Math.sin(a) * 0.3], [e[0] + Math.cos(a) * 0.12, 3.2, e[1] + Math.sin(a) * 0.12], COL.path, 0.5, 1.4, 0, 0, 0, linesDepth) }+ }+ // motes of light drifting up around you in the atrium+ if (Math.hypot(cam.x, cam.z) < WORLD.R + 30) {+ const tm = reduced ? 0 : clock+ for (let i = 0; i < 90; i++) {+ const r = 0.35 + Math.pow(hash3(i, 2, 7), 0.7) * (WORLD.R - 1.5)+ const sp = 0.12 + hash3(i, 3, 7) * 0.3+ const y = (hash3(i, 4, 7) * 9 + tm * sp) % 9+ const a = hash3(i, 1, 7) * TAU + tm * 0.04 * (0.5 + hash3(i, 5, 7)) * (r < 3 ? 2 : 1)+ const p = [Math.sin(a) * r, y, -Math.cos(a) * r]+ const al = 0.55 * Math.sin((Math.PI * y) / 9) * (0.35 + 0.65 * (1 - r / WORLD.R))+ seg(p, [p[0], p[1] + 0.04, p[2]], r < 3 ? COL.self : mixc(COL.self, COL.struct, 0.5), al, 2.0, 0, 0, 0, linesDepth)+ }+ }+ // belief strings: from the stone you face to the wings that hold what it cites+ const stone = (target && target.kind === 'stone' && !travel) ? target : null+ if (stone) {+ const seen = new Set()+ stone.sec.lines.forEach((line) => line.mems.forEach((m) => {+ const it = WORLD.memInter.get(m.id)+ if (!it || seen.has(it.wing.i)) return+ seen.add(it.wing.i)+ const a = [stone.c[0], stone.hh * 2 + 0.05, stone.c[2]]+ const b = WP(it.wing, it.wing.s0, 0, OPEN_H + 0.2)+ const n = 28+ let prev = a+ for (let i = 1; i <= n; i++) {+ const t = i / n+ const p = [lerp(a[0], b[0], t), lerp(a[1], b[1], t) + Math.sin(t * Math.PI) * 3.2, lerp(a[2], b[2], t)]+ const flow = (((t * 4 - clock * 0.9) % 1) + 1) % 1+ seg(prev, p, COL.self, 0.08 + 0.32 * (flow < 0.12 ? 1 : 0), 1.1, 0, 0, 0, linesDepth)+ prev = p+ }+ }))+ }+ // recall: the words in the air+ const wordsNow = recall.chars.length ? wordFrames() : []+ const drawWord = (f, alphaK, shift) => {+ f.chars.forEach((c, i) => {+ const age = clock - c.born+ const rise = reduced ? 0 : (1 - easeOut(age / 0.45)) * 0.55+ const a = clamp(age / 0.18, 0, 1) * alphaK+ const wob = reduced ? 0 : Math.sin(clock * 2 + i * 0.7) * 0.01+ const o = [f.o[0] + shift[0], f.o[1] - rise + wob + shift[1], f.o[2] + shift[2]]+ const flash = Math.max(0, 1 - age / 0.35)+ glyph(glyphs, c.ch, o, f.rt, up, i * Atlas.advEm, 0, f.em, mixc(COL.type, COL.white, flash), a * (1 + flash), -1, 0, 0, 0)+ })+ }+ wordsNow.forEach((f) => drawWord(f, 1, [0, 0, 0]))+ if (wordsNow.length && recall.chars.length) {+ const f = wordsNow[wordsNow.length - 1]+ if (recall.chars[recall.chars.length - 1].ch !== ' ' && Math.floor(clock * 2) % 2 === 0) {+ const x = f.chars.length * Atlas.advEm * f.em + 0.03+ seg(at3(f.o, f.rt, up, x, 0.02), at3(f.o, f.rt, up, x, -f.em * 1.05), COL.type, 0.9, 2, 0, 0, 0, linesTop)+ }+ }+ recall.goneWords = recall.goneWords.filter((g) => clock - g.at < 0.6)+ for (const g of recall.goneWords) {+ const t = clock - g.at+ g.frames.forEach((f) => drawWord(f, 1 - t / 0.6, [g.vx * t * (1 + t * 2), t * 0.6, g.vz * t * (1 + t * 2)]))+ }+ // recall: the cards, flying in from where they live+ const n = recall.cards.length+ recall.cards.forEach((c, j) => {+ const k = ((j - recall.sel + Math.floor(n / 2)) % n + n) % n - Math.floor(n / 2)+ const sel = k === 0+ const a = cam.yaw + k * 32 * DEG+ const dist = sel ? 2.35 : 3.15+ const slot = [cam.x + Math.sin(a) * dist, EYE - 0.12 + (sel ? 0.02 : -0.04), cam.z - Math.cos(a) * dist]+ const fly = reduced ? 1 : clamp((clock - c.born) / 1.0, 0, 1)+ if (fly < 1) {+ const f = easeOut(fly)+ const mid = [(c.start[0] + slot[0]) / 2, Math.max(c.start[1], slot[1]) + 2 + Math.hypot(c.start[0] - slot[0], c.start[2] - slot[2]) * 0.06, (c.start[2] + slot[2]) / 2]+ const bz = (t) => [lerp(lerp(c.start[0], mid[0], t), lerp(mid[0], slot[0], t), t), lerp(lerp(c.start[1], mid[1], t), lerp(mid[1], slot[1], t), t), lerp(lerp(c.start[2], mid[2], t), lerp(mid[2], slot[2], t), t)]+ c.pos = bz(f)+ if (fly > 0) for (let i = 0; i < 8; i++) { const t0 = Math.max(0, f - (i + 1) * 0.03), t1 = Math.max(0, f - i * 0.03); seg(bz(t0), bz(t1), c.L.color, 0.9 * (1 - i / 8), 2.2 - i * 0.2, 0, 0, 0, linesTop) }+ } else c.pos = reduced ? slot : lerp3(c.pos, slot, 1 - Math.exp(-1 / 60 * 10))+ const show = fly > 0 ? 1 : 0+ drawCard(c, c.pos, sel ? 1 : 0.82, (sel ? 1 : 0.62) * show * sstep(0, 0.25, fly), sel, back, linesTop, glyphs)+ if (sel && fly >= 1) {+ // where it lives: a thread from the card back to its room, light running toward you+ const a0 = [c.pos[0], c.pos[1] - c.L.h / 2, c.pos[2]], b0 = c.L.origin+ const lift2 = 1.5 + Math.hypot(b0[0] - a0[0], b0[2] - a0[2]) * 0.05+ let prev = a0+ for (let i = 1; i <= 40; i++) {+ const t = i / 40+ const p = [lerp(a0[0], b0[0], t), lerp(a0[1], b0[1], t) - Math.sin(t * Math.PI) * 0.4 + Math.sin(t * Math.PI) * lift2 * t, lerp(a0[2], b0[2], t)]+ const flow = (((t * 6 + clock * 1.6) % 1) + 1) % 1+ seg(prev, p, c.L.color, (0.1 + (flow < 0.2 ? 0.45 : 0)) * (1 - t * 0.5), 1.3, 0, 0, 0, linesTop)+ prev = p+ }+ }+ })+ void n+ recall.gone = recall.gone.filter((g) => clock - g.at < 0.55)+ for (const g of recall.gone) {+ const t = clock - g.at+ const p = g.mode === 'sweep' ? [g.c.pos[0] + g.vx * t * (1 + t * 3), g.c.pos[1] + t * 0.8, g.c.pos[2] + g.vz * t * (1 + t * 3)] : g.c.pos+ drawCard(g.c, p, 0.82 * (g.mode === 'fade' ? 1 - t : 1), 0.6 * (1 - t / 0.55), false, back, linesTop, glyphs)+ }+ return { linesDepth, linesTop, back, glyphs }+ }++ function drawCard(c, pos, scale, alpha, sel, back, lines, glyphs) {+ if (alpha <= 0.01) return+ const dx = cam.x - pos[0], dz = cam.z - pos[2], d = Math.hypot(dx, dz) || 1+ const n = [dx / d, 0, dz / d], rt = [n[2], 0, -n[0]], up = [0, 1, 0]+ const W = c.L.w * scale, H = c.L.h * scale+ const tl = [pos[0] - rt[0] * W / 2, pos[1] + H / 2, pos[2] - rt[2] * W / 2]+ const P = (x, y) => [tl[0] + rt[0] * x, tl[1] - y, tl[2] + rt[2] * x]+ solidQuad(back, P(0, 0), P(W, 0), P(0, H), P(W, H), [0, 0, 0], 0.95 * Math.min(1, alpha * 2.2), 1)+ const col = c.L.color+ poly([P(0, 0), P(W, 0), P(W, H), P(0, H)], true, col, (sel ? 0.95 : 0.5) * alpha, sel ? 1.6 : 1.1, 0, 0, 0)+ for (const [x, y, sx, sy] of [[0, 0, 1, 1], [W, 0, -1, 1], [W, H, -1, -1], [0, H, 1, -1]]) { seg(P(x, y), P(x + sx * 0.12 * scale, y), col, alpha, 2, 0, 0, 0, lines); seg(P(x, y), P(x, y + sy * 0.12 * scale), col, alpha, 2, 0, 0, 0, lines) }+ for (const g of c.L.g) glyph(glyphs, g.ch, P(g.x * scale, g.y * scale), rt, up, 0, 0, g.e * scale, g.col || COL.ink, (g.a ?? 1) * alpha * (sel || g.hi ? 1 : 0.85), -1, 0, 0, 0)+ function poly(pts, closed, cc, a, w) { for (let i = 0; i < pts.length; i++) seg(pts[i], pts[(i + 1) % pts.length], cc, a, w, 0, 0, 0, lines) }+ }++ const DBG = {}+ let running = true, lastTs = 0+ function frame(ts) {+ if (!running) return+ const dt = Math.min(0.1, lastTs ? (ts - lastTs) / 1000 : 0.016)+ lastTs = ts+ clock += dt+ const t0 = performance.now()+ update(dt)+ render()+ drawHud()+ updateWhere(); updatePrompt()+ DBG.cpu = (DBG.cpu || 0) * 0.9 + (performance.now() - t0) * 0.1+ requestAnimationFrame(frame)+ }+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) running = false+ else if (!running) { running = true; lastTs = 0; requestAnimationFrame(frame) }+ })++ // ── start ────────────────────────────────────────────────────────────────────────────────────────++ async function start() {+ if (!initGL()) { $('loading').textContent = 'This needs WebGL.'; return }+ let data+ try { data = await MemoryData.load() } catch (err) { $('loading').textContent = 'Could not read memories: ' + String(err?.message || err).slice(0, 120); return }+ const W = buildWorld(data)+ chunks = { lines: makeChunks(LN, LINE_F), glyphs: makeChunks(GLY, GLYPH_F), fills: makeChunks(FL, FILL_F) }+ W.counts = { lines: LN.length / LINE_F / 4, glyphs: GLY.length / GLYPH_F / 4, fills: FL.length / FILL_F / 4, inter: INTER.length }+ window.__palace = { DBG, W, cam, recall, reader, mapUI, get travel() { return travel }, get clock() { return clock }, get target() { return target }, counts: W.counts }+ LN = []; GLY = []; FL = []+ $('loading').remove()+ mode.textContent = data.real ? `your memories · ${fmt(data.snapshot.memories?.length)} notes · ${fmt(data.asks.length)} messages` : 'an invented person · add ?real for yours'+ ready = true+ resize()+ if (reduced) skipArrival()+ updateKeys()+ canvas.focus()+ requestAnimationFrame(frame)+ }+ start()+})()diff --git a/docs/research/2026-10-10-memory-brain/self-lake.jpg b/docs/research/2026-10-10-memory-brain/self-lake.jpgnew file mode 100644index 000000000..231957fedBinary files /dev/null and b/docs/research/2026-10-10-memory-brain/self-lake.jpg differdiff --git a/docs/research/2026-10-10-memory-brain/self.html b/docs/research/2026-10-10-memory-brain/self.htmlnew file mode 100644index 000000000..91e0112fe--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/self.html@@ -0,0 +1,160 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="color-scheme" content="dark">+<title>Sense of Self</title>+<style>+ :root {+ --bg: #030407;+ --ink: #eef2f8;+ --ink2: #b8c0ce;+ --dim: #7a8394;+ --faint: #4b5262;+ --gold: #ffe3ad;+ --sec: #9fd8ff;+ --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ --serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;+ --gutter: clamp(16px, 3vw, 44px);+ --col: min(30vw, 420px);+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--ink); }+ body { font: 12px/1.5 var(--mono); -webkit-font-smoothing: antialiased; }+ #scene { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }+ #vignette { position: fixed; inset: 0; pointer-events: none; background: radial-gradient(ellipse 85% 80% at 50% 45%, transparent 55%, rgba(0, 0, 0, .5) 100%); }++ .col { position: fixed; left: var(--gutter); top: clamp(16px, 6.5vh, 64px); width: var(--col); }+ .kicker { font: 500 11px/1.4 var(--mono); letter-spacing: .14em; text-transform: uppercase; color: var(--sec); display: flex; gap: 12px; align-items: baseline; }+ .kicker .n { color: var(--faint); letter-spacing: .08em; }++ #whisper { opacity: 0; transition: opacity 1.1s ease; pointer-events: none; }+ #whisper.on { opacity: 1; }+ #whisper .t { font: 400 clamp(26px, 3vw, 42px)/1.1 var(--serif); color: #fbf6ea; letter-spacing: .01em; text-shadow: 0 0 30px rgba(255, 230, 190, .25); }+ #whisper .s { margin-top: 12px; color: var(--dim); font-size: 11px; letter-spacing: .04em; max-width: 34ch; }++ #caption { opacity: 0; transition: opacity .6s ease; pointer-events: none; }+ #caption.on { opacity: 1; }+ #cap-text { font: 400 clamp(20px, 2.35vw, 34px)/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; }+ #cap-why-label { color: var(--dim); font-size: 11px; letter-spacing: .05em; margin-bottom: 7px; }+ #cap-why { list-style: none; margin: 0; padding: 0; }+ #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(--ink2); transition: background .15s, color .15s; }+ #cap-why li.sel { background: rgba(255, 255, 255, .065); color: var(--ink); box-shadow: inset 2px 0 0 var(--gold); }+ #cap-why li .w { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }+ #cap-why li .w small { color: var(--dim); font-size: 10.5px; margin-left: 6px; }+ #cap-why li .a { color: var(--faint); font-size: 10.5px; }+ #cap-why li.missing { color: var(--faint); }+ #cap-why li .q { grid-column: 2 / 4; font: italic 13px/1.4 var(--serif); color: var(--dim); margin-top: 3px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }+ .dot { width: 8px; height: 8px; border-radius: 50%; margin-top: 4.5px; background: currentColor; box-shadow: 0 0 8px currentColor; }+ .dot.ring { background: transparent; border: 1.5px solid currentColor; box-shadow: 0 0 6px currentColor; }+ .dot.diamond { border-radius: 1px; transform: rotate(45deg) scale(.85); }++ #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(100vw - 2 * var(--gutter)); }+ #recall.on { display: block; }+ #recall-sum { color: var(--dim); }+ #recall-list { list-style: none; margin: 10px 0 0; padding: 0; }+ #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(--ink2); }+ #recall-list li.sel { background: rgba(255, 255, 255, .07); color: var(--ink); box-shadow: inset 2px 0 0 var(--gold); }+ #recall-list li .w { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }+ #recall-list li .a { color: var(--faint); font-size: 10.5px; white-space: nowrap; }+ #recall-list li.head { color: var(--faint); font-size: 10px; letter-spacing: .14em; text-transform: uppercase; padding-top: 9px; grid-template-columns: 1fr; }+ #recall-list li .w.serif { font: 13.5px/1.35 var(--serif); }+ mark { background: none; color: var(--gold); text-shadow: 0 0 10px rgba(255, 220, 150, .5); }++ #orb-label { position: fixed; left: 0; top: 0; max-width: min(340px, 44vw); 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; }+ #orb-label.on { opacity: 1; }+ #orb-label .m { color: var(--dim); font-size: 10.5px; letter-spacing: .03em; display: flex; gap: 7px; align-items: center; }+ #orb-label .m .dot { margin-top: 0; width: 7px; height: 7px; }+ #orb-label .t { font: 17px/1.25 var(--serif); color: #fbf7ee; margin: 5px 0 4px; }+ #orb-label .h { color: var(--ink2); font-size: 11px; }+ #orb-label .h div { font: italic 12.5px/1.35 var(--serif); color: var(--gold); opacity: .85; margin-top: 3px; }+ #orb-label .h.none { color: var(--faint); }++ #veil { position: fixed; 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; }+ #veil.on { opacity: 1; }+ #panel { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); width: min(720px, calc(100vw - 32px)); max-height: min(80vh, 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; }+ #panel.on { display: flex; }+ #panel::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 1px; background: linear-gradient(90deg, transparent, var(--glow, #ffe3ad), transparent); opacity: .8; }+ #panel header { padding: 22px 28px 12px; }+ #panel .meta { display: flex; flex-wrap: wrap; gap: 4px 9px; align-items: center; font-size: 11px; color: var(--dim); letter-spacing: .03em; }+ #panel .meta .dot { margin-top: 0; }+ #panel h2 { font: 400 clamp(22px, 2.5vw, 32px)/1.2 var(--serif); margin: 10px 0 6px; color: #fbf7ee; overflow-wrap: anywhere; }+ #panel .desc { font: italic 15px/1.45 var(--serif); color: var(--ink2); margin: 0; }+ #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; }+ #panel .body p { margin: 0 0 .8em; }+ #panel .body h4 { font: 600 11px/1.4 var(--mono); letter-spacing: .12em; text-transform: uppercase; color: var(--dim); margin: 1.3em 0 .5em; }+ #panel .body .li { padding-left: 1.1em; text-indent: -1.1em; margin: 0 0 .35em; }+ #panel .body .li::before { content: "· "; color: var(--dim); }+ #panel .body code { font: 12.5px var(--mono); background: rgba(255, 255, 255, .06); border-radius: 3px; padding: 1px 4px; }+ #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; }+ #panel .body strong { color: #fff; font-weight: 600; }+ #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); }+ #panel .body .msg .a { grid-column: 2; font: 10.5px var(--mono); color: var(--faint); }+ #panel .body .msg .x { grid-column: 2; font: 14px/1.45 var(--serif); color: var(--ink2); }+ #panel footer { border-top: 1px solid rgba(255, 255, 255, .06); padding: 11px 28px 14px; font-size: 11px; color: var(--dim); }+ #panel footer .b { font: italic 13.5px/1.4 var(--serif); color: var(--gold); margin-top: 4px; }+ #panel footer .p { color: var(--faint); margin-top: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++ #hint { position: fixed; left: var(--gutter); right: var(--gutter); bottom: 10px; display: flex; justify-content: space-between; align-items: baseline; gap: 16px; color: var(--faint); font-size: 11px; letter-spacing: .02em; pointer-events: none; white-space: nowrap; }+ #hint b { color: var(--dim); font-weight: 500; }+ #prompt { color: var(--ink); font-size: 13px; margin-right: 18px; }+ #prompt:empty { display: none; margin: 0; }+ #prompt .c { display: inline-block; width: 7px; height: 14px; margin-left: 2px; vertical-align: -2px; background: var(--gold); animation: blink 1.05s steps(1) infinite; }+ #prompt .p { color: var(--gold); margin-right: 8px; }+ @keyframes blink { 50% { opacity: 0; } }+ #status { overflow: hidden; text-overflow: ellipsis; }+ #toast { position: fixed; right: var(--gutter); top: 14px; color: var(--dim); font-size: 11px; opacity: 0; transition: opacity .3s; pointer-events: none; }+ #toast.on { opacity: 1; }+ #error { position: fixed; inset: 0; display: none; place-items: center; color: var(--dim); font-size: 12px; }+ @media (max-width: 1080px) { #status { display: none; } }+ @media (prefers-reduced-motion: reduce) { #prompt .c { animation: none; } }+</style>+</head>+<body>+<canvas id="scene" aria-label="Sense of Self: what your agents believe about you, held up by the memories in the lake below"></canvas>++<div id="vignette"></div>++<div id="whisper" class="col" aria-hidden="true">+ <div class="t">Sense of Self</div>+ <div class="s" id="whisper-s">what your agents believe about you, and the memories that hold it up</div>+</div>++<section id="caption" class="col" aria-live="polite">+ <div class="kicker"><span id="cap-section"></span><span class="n" id="cap-count"></span></div>+ <h1 id="cap-text"></h1>+ <div id="cap-why-label">why your agents believe this</div>+ <ol id="cap-why"></ol>+</section>++<section id="recall" class="col" aria-live="polite">+ <div class="kicker" id="recall-sum"></div>+ <ol id="recall-list"></ol>+</section>++<div id="orb-label" aria-live="polite">+ <div class="m"><span class="dot" id="ol-dot"></span><span id="ol-meta"></span></div>+ <div class="t" id="ol-title"></div>+ <div class="h" id="ol-holds"></div>+</div>++<div id="veil"></div>+<article id="panel" role="dialog" aria-modal="true" aria-labelledby="p-title">+ <header>+ <div class="meta" id="p-meta"></div>+ <h2 id="p-title"></h2>+ <p class="desc" id="p-desc"></p>+ </header>+ <div class="body" id="p-body" tabindex="-1"></div>+ <footer id="p-foot"></footer>+</article>++<div id="toast"></div>+<div id="error"></div>+<footer id="hint"><span><span id="prompt"></span><span id="keys"></span></span><span id="status"></span></footer>++<script src="memory-data.js"></script>+<script src="self.js"></script>+</body>+</html>diff --git a/docs/research/2026-10-10-memory-brain/self.jpg b/docs/research/2026-10-10-memory-brain/self.jpgnew file mode 100644index 000000000..0d2e464fdBinary files /dev/null and b/docs/research/2026-10-10-memory-brain/self.jpg differdiff --git a/docs/research/2026-10-10-memory-brain/self.js b/docs/research/2026-10-10-memory-brain/self.jsnew file mode 100644index 000000000..c09a5a7a0--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/self.js@@ -0,0 +1,1976 @@+/*+ * Sense of Self: About You as a luminous structure, held up by the lake of memories below it.+ *+ * 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 (MemoryData.refs), and the person's own messages hang over the water as mist; "asks:N"+ * refs rise out of that mist.+ *+ * Reads MemoryData only and writes nothing. Memory text is written by models: it is rendered with+ * textContent or canvas fillText, never as HTML.+ */+(function () {+ 'use strict'++ const DAY = 86_400_000+ const TAU = Math.PI * 2+ const ARRIVE_END = 4.8+ 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 YOU = [196, 218, 255] // the person's own words+ const GOLD = [255, 226, 170]+ const SECTION_HUES = [192, 266, 334, 36, 150, 222, 300, 82]++ const $ = (id) => document.getElementById(id)+ const canvas = $('scene')+ const ctx = canvas.getContext('2d')+ const refl = document.createElement('canvas')+ const rctx = refl.getContext('2d')+ const bloom = document.createElement('canvas')+ const 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 } })()+ const motion = matchMedia('(prefers-reduced-motion: reduce)')+ let reduce = motion.matches+ if (motion.addEventListener) motion.addEventListener('change', (e) => { reduce = e.matches })++ // ── small helpers ───────────────────────────────────────────────────────────────────────────────++ const clamp = (v, a, b) => (v < a ? a : v > b ? b : v)+ const lerp = (a, b, t) => a + (b - a) * t+ const smooth = (t) => (t <= 0 ? 0 : t >= 1 ? 1 : t * t * (3 - 2 * t))+ const easeOut = (t) => 1 - Math.pow(1 - clamp(t, 0, 1), 3)+ const easeInOut = (t) => { t = clamp(t, 0, 1); return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2 }+ const frac = (x) => x - Math.floor(x)+ 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 }+ const h01 = (str) => hash(str) / 4294967296+ 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+ }+ }+ function gauss(r) { const u = Math.max(1e-6, r()), v = r(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * v) }+ 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] }+ 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)]+ }+ 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))]+ const css = (rgb, a = 1) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a})`+ 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+/))+ 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)++ 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`+ }+ const short = (s, n) => { s = String(s ?? ''); return s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s }+ const clean = (s) => String(s ?? '').replace(/\[Image #\d+\]/g, ' ').replace(/\s+/g, ' ').trim()+ function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e }+ function dot(rgb, kind) { const d = el('span', 'dot' + (kind ? ' ' + kind : '')); d.style.color = hexOf(rgb); return d }++ // 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 = document.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 = document.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+ }+ const ORB_K = 1 / 0.17 // sprite size per unit of sphere radius++ // ── state ───────────────────────────────────────────────────────────────────────────────────────++ const S = {+ ready: false, real: 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, sound: false,+ 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,+ }+ const G = {}+ let DPR = 1+ const fronds = []+ const tmp = new Float32Array(4)++ // ── data → a mind ───────────────────────────────────────────────────────────────────────────────++ function build(data) {+ const snap = data.snapshot+ S.snapshot = snap; S.asks = data.asks ?? []; S.real = data.real+ S.now = snap.observedAt || Date.now()+ const lines = snap.about?.lines ?? []+ const names = [...new Set(lines.map((l) => l.section || 'About you'))]+ S.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.+ S.orbs = (snap.memories ?? []).map((m, i) => {+ const ag = MemoryData.agent(m.agent, snap)+ const age = Math.max(0, S.now - (m.modified || S.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: ag.name.toLowerCase(),+ }+ })+ for (const o of S.orbs) o.label = decay(String(o.m.title || o.m.path || 'untitled'), o.loss, o.m.id)+ const byId = new Map(S.orbs.map((o) => [o.m.id, o]))++ // Beliefs: every About You line, with the memories and messages that hold it up.+ S.beliefs = lines.map((line, idx) => {+ const sec = S.sections[names.indexOf(line.section || 'About you')]+ const b = { idx, sec, j: sec.beliefs.length, text: String(line.text ?? ''), mems: [], missing: [], askN: 0, sessions: [], motes: [], quotes: [], threads: [],+ phase: frac(idx * 0.61803398875) * TAU, pts: new Float32Array(MAXP * 2), cum: new Float32Array(MAXP), n: 0, len: 1, fork: NA - 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 = MemoryData.refs({ refs: [ref] }, snap)+ if (!found.length) b.missing.push({ agent: MemoryData.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 S.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()+ buildColumns()+ for (const b of S.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 })),+ ]+ }+ }++ // Eternal Sunshine: old titles lose their letters.+ 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+ }++ function buildMotes() {+ const asks = S.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() }+ 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 ageDays = Math.max(0, S.now - (ask.at || S.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+ }+ S.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 S.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 S.beliefs) {+ const chosen = []+ const seen = new Set()+ for (const id of b.sessions) {+ let c = 0+ for (let i = 0; i < N; i++) if (asks[i].sessionId === id) { c++; if (chosen.length < 64) { chosen.push(i); seen.add(i) } }+ b.sessionAsks = (b.sessionAsks || 0) + c+ }+ 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]) }+ }+ }++ function buildColumns() {+ 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 S.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, when the folder says so.+ const projects = S.snapshot.projects ?? []+ const keyFor = new Map()+ for (const p of projects) {+ for (const k of [p.key, p.path]) if (k) keyFor.set(String(k), p.name)+ }+ const M = S.motes+ for (let i = 0; i < M.n; i++) {+ const cwd = String(S.asks[i].cwd || '')+ let name = cwd ? keyFor.get(cwd) : null+ if (!name && cwd) {+ const base = cwd.split('/').filter(Boolean).pop()+ if (base && (cols.has('p:' + base) || projects.some((p) => p.name === base))) name = base+ }+ if (name) { const c = col('p:' + name, name); c.asks++; M.col[i] = c } else M.col[i] = null+ }+ S.columns = [...cols.values()]+ for (const c of S.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 = [...S.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))+ S.columns = [...left.reverse(), ...right]+ }++ // ── layout ──────────────────────────────────────────────────────────────────────────────────────++ function layout() {+ const W = Math.max(320, innerWidth), H = Math.max(320, innerHeight)+ DPR = Math.min(2, window.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.capRight = G.gutter + Math.min(W * 0.3, 420)+ 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()+ }++ 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 = $('cap-text').getBoundingClientRect()+ S.capRect = t.width ? t : 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]+ }+ }++ const TWIST = Math.PI * 3.2, TWIST2 = Math.PI * 2.4+ 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.+ const ROOTN = 16+ 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])+ }++ // ── focus helpers ───────────────────────────────────────────────────────────────────────────────++ const focusedBelief = () => S.sections[S.sec]?.beliefs[S.bel] ?? null+ const focusedOrb = () => (S.orb >= 0 ? S.orbs[S.orb] : 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; tone(b) }+ }+ if (e > 2.4) S.pulses.splice(i, 1)+ }+ }+ }++ // ── 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)+ 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.+ const hzS = G.hz - camY+ const RH = Math.min(hzS - 2, H * 0.42)+ let reflOk = false+ 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))+ if (refl.width !== rw || refl.height !== rh) { refl.width = rw; refl.height = rh }+ 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)+ if (bloom.width !== bw || bloom.height !== bh) { bloom.width = bw; bloom.height = bh }+ 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) {+ if (!S.beliefs.length) return+ const L = G.Lnow+ // 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 bloom = S.arrival.done ? 1 : smooth((A - start + 0.25) / 0.4)+ if (bloom <= 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) * bloom+ 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.+ const labelsIn = S.arrival.done ? 1 : smooth((A - 3.4) / 0.7)+ if (labelsIn > 0) {+ ctx.font = '500 10.5px ui-monospace, "SF Mono", SFMono-Regular, Menlo, monospace'+ 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+ lines.forEach((line, i) => ctx.fillText(line, ax + shift, ay + dy + i * 13))+ }+ if ('letterSpacing' in ctx) ctx.letterSpacing = '0px'+ ctx.textAlign = 'left'+ }+ }++ 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)+ }+ for (const e of S.extra) {+ const age = t - e.t0+ const y = e.y - Math.min(1, age / 1.2) * e.rise+ const big = selM && selM.extra === e+ const z = big ? 22 : 8+ ctx.globalAlpha = 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+ const MONO = 'ui-monospace, "SF Mono", SFMono-Regular, Menlo, monospace'+ // 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'+ const y = G.hz + (G.lakeTop + G.depth + 36 - G.hz) * G.sq+ for (const c of S.columns) {+ if (!c.orbs.length) continue+ ctx.globalAlpha = lk * 0.42+ ctx.fillStyle = '#8f9ab0'+ ctx.fillText(short(c.name, Math.max(4, Math.floor(c.w / 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([])+ }++ // ── DOM: caption, orb label, recall list, panel, hint ───────────────────────────────────────────++ function renderCaption(animate) {+ const b = focusedBelief()+ const cap = $('caption')+ if (!b) {+ $('cap-section').textContent = 'About you'+ $('cap-count').textContent = ''+ $('cap-text').textContent = 'About You has not been written yet. The lake below is everything your agents remember.'+ $('cap-why-label').textContent = ''+ $('cap-why').textContent = ''+ return+ }+ cap.style.setProperty('--sec', hexOf(mix(b.sec.rgb, [255, 255, 255], 0.2)))+ $('cap-section').textContent = b.sec.name+ $('cap-count').textContent = `${b.j + 1} of ${b.sec.beliefs.length}`+ $('cap-text').textContent = b.text+ $('cap-why-label').textContent = b.threads.length ? 'why your agents believe this' : 'nothing cited; a belief with no memory under it'+ const list = $('cap-why')+ list.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'))+ }+ list.append(li)+ })+ measureCaption()+ if (animate && !reduce && cap.animate) {+ $('cap-text').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)' })+ list.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 420, delay: 60, easing: 'ease-out', fill: 'backwards' })+ }+ }++ function renderOrbLabel() {+ const o = focusedOrb()+ if (!o) return+ $('ol-dot').style.color = hexOf(o.rgb)+ $('ol-meta').textContent = [o.ag.name, o.m.project?.name || 'everywhere', ago(o.age)].join(' · ')+ $('ol-title').textContent = o.m.title || o.m.path+ const h = $('ol-holds')+ h.textContent = ''+ if (o.beliefs.length) {+ h.className = 'h'+ h.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)) h.append(el('div', null, short(b.text, 90)))+ } else {+ h.className = 'h none'+ h.textContent = 'holds up no belief: a free-floating memory'+ }+ }++ function positionOrbLabel() {+ const lab = $('orb-label')+ const o = focusedOrb()+ const on = S.view === 'lake' && o && !S.panel && !S.recall && S.cam.y > G.lakeCam * 0.6+ lab.classList.toggle('on', !!on)+ if (!on) { G.olRect = null; return }+ const w = lab.offsetWidth, h = lab.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]+ lab.style.transform = `translate(${Math.round(Math.max(8, x))}px, ${Math.round(y)}px)`+ }++ function showCaption() {+ const on = S.arrival.done && S.view === 'self' && !S.recall+ $('caption').classList.toggle('on', on)+ $('recall').classList.toggle('on', !!S.recall)+ }++ function renderHint() {+ const keys = $('keys')+ 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 text = `←→ branch · ↑↓ belief · space pluck · tab thread · enter dive · type to recall · m sound ${S.sound ? 'on' : 'off'}`+ keys.textContent = text+ const p = $('prompt')+ p.textContent = ''+ if (S.recall && !S.panel) {+ p.append(el('span', 'p', 'recall ›'), document.createTextNode(S.recall.q), el('span', 'c'))+ }+ }++ function renderStatus() {+ const n = (x) => x.toLocaleString('en-US')+ $('status').textContent = `${S.real ? 'your memories' : 'an invented person'} · ${n(S.beliefs.length)} beliefs · ${n(S.orbs.length)} memories · ${n(S.asks.length)} messages`+ }++ let toastTimer = 0+ function toast(text) {+ const t = $('toast'); t.textContent = text; t.classList.add('on')+ clearTimeout(toastTimer); toastTimer = setTimeout(() => t.classList.remove('on'), 1400)+ }++ // Simple, safe markdown: headings, bullets, code, bold. Text nodes only.+ function renderBody(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 = el('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 = el('h4'); inline(h, m[1]); root.append(h); para = null; continue }+ if ((m = /^\s*(?:[-*+]|\d+[.)])\s+(.*)$/.exec(line))) { const li = el('div', 'li'); inline(li, m[1]); root.append(li); para = null; continue }+ if (!para) { para = el('p'); root.append(para) } else para.append(document.createElement('br'))+ inline(para, line)+ }+ }+ function inline(node, text) {+ const re = /(`[^`]+`|\*\*[^*]+\*\*)/g+ let last = 0, m+ while ((m = re.exec(text))) {+ if (m.index > last) node.append(document.createTextNode(text.slice(last, m.index)))+ const tok = m[0]+ node.append(el(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(document.createTextNode(text.slice(last)))+ }+ function marked(node, snippet) {+ // \u0002 … \u0003 mark matches.+ 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 ? el('mark', null, p) : document.createTextNode(p))+ }+ }++ function openPanel(spec, from) {+ S.panel = spec+ const panel = $('panel')+ const meta = $('p-meta'), title = $('p-title'), desc = $('p-desc'), body = $('p-body'), foot = $('p-foot')+ meta.textContent = ''; foot.textContent = ''; desc.textContent = ''+ let glow = GOLD+ if (spec.kind === 'memory') {+ const o = spec.o, m = o.m+ glow = o.rgb+ meta.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)))+ title.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)) desc.textContent = d+ renderBody(body, m.body)+ if (o.beliefs.length) {+ foot.append(el('div', null, o.beliefs.length === 1 ? 'holds up this belief' : `holds up ${o.beliefs.length} beliefs`))+ for (const b of o.beliefs) foot.append(el('div', 'b', b.text))+ } else foot.append(el('div', null, 'holds up no belief yet: a free-floating memory'))+ foot.append(el('div', 'p', m.path || ''))+ o.glow = 1+ } else if (spec.kind === 'messages') {+ const b = spec.b+ meta.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`))+ title.textContent = b.text+ desc.textContent = b.askN > b.motes.length ? `The ${b.motes.length} that rise closest to it, out of ${b.askN.toLocaleString('en-US')}; nearest first.` : ''+ body.textContent = ''+ const rows = b.motes.map((i) => S.asks[i])+ for (const ask of rows) {+ const row = el('div', 'msg')+ row.append(dot(rgbOf(MemoryData.agent(ask.engine, S.snapshot).color)))+ row.append(el('div', 'x', short(clean(ask.text) || '(an image)', 400)))+ row.append(el('div', 'a', `${MemoryData.agent(ask.engine, S.snapshot).name} · ${ago(S.now - ask.at)}${ask.cwd ? ' · ' + ask.cwd.split('/').filter(Boolean).pop() : ''}`))+ body.append(row)+ }+ foot.append(el('div', null, `${b.sec.name}`))+ } else if (spec.kind === 'message') {+ const ask = spec.ask, hit = spec.hit+ const engine = ask?.engine ?? hit?.engine+ const ag = MemoryData.agent(engine, S.snapshot)+ const at = ask?.at ?? hit?.at+ const cwd = ask?.cwd || hit?.cwd || ''+ glow = rgbOf(ag.color)+ meta.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) meta.append(el('span', null, '·'), el('span', null, cwd.split('/').filter(Boolean).pop()))+ title.textContent = (ask?.title || hit?.title) ? short(ask?.title || hit?.title, 90) : 'Your message'+ body.textContent = ''+ const p = el('p')+ if (ask) {+ const terms = wordsOf(S.recall?.q ?? '')+ let text = String(ask.text ?? '')+ for (const term of terms) text = text.replace(new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), (m) => `\u0002${m}\u0003`)+ marked(p, text)+ } else marked(p, hit?.snippet)+ body.append(p)+ const bel = spec.mote != null ? S.motes.bel.get(spec.mote) : null+ if (bel && bel.length) { foot.append(el('div', null, 'part of what holds up')); for (const b of bel) foot.append(el('div', 'b', b.text)) }+ else foot.append(el('div', null, 'a message in the mist'))+ }+ panel.style.setProperty('--glow', css(glow, 0.35))+ panel.classList.add('on')+ $('veil').classList.add('on')+ body.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 closePanel() {+ const spec = S.panel+ S.panel = null+ const panel = $('panel')+ $('veil').classList.remove('on')+ const done = () => 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')+ 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 })+ tone(b)+ }++ 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+ }++ // ── recall ──────────────────────────────────────────────────────────────────────────────────────++ let searchTimer = 0+ function startRecall(q) {+ S.recall = { q: '', sel: 0, beliefs: new Set(), results: [], hits: null, memCount: 0, moteCount: 0 }+ S.thread = -1+ setQuery(q)+ showCaption()+ }++ function closeRecall() {+ S.recall = null+ for (const o of S.orbs) o.match = -1+ S.motes.match.fill(0)+ S.extra = []+ clearTimeout(searchTimer)+ showCaption(); renderCaption(false); renderHint()+ }++ function setQuery(q) {+ const R = S.recall+ R.q = q+ const terms = wordsOf(q)+ const M = S.motes+ // Memories: every term somewhere in the note.+ const mems = []+ for (const o of S.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])+ for (const o of S.orbs) o.match = -1+ mems.forEach(([, o], i) => { o.match = i })+ // Your messages, here first; then the full index.+ M.match.fill(0)+ 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) { M.match[i] = 1; local.push(i) }+ }+ }+ // Beliefs: by their words, or by what holds them up.+ R.beliefs = new Set()+ for (const b of S.beliefs) { const lt = b.text.toLowerCase(); if (terms.length && terms.every((term) => lt.includes(term))) R.beliefs.add(b) }+ const direct = new Set(R.beliefs)+ for (const [, o] of mems) for (const b of o.beliefs) R.beliefs.add(b)+ for (const i of local) { const list = M.bel.get(i); if (list) for (const b of list) R.beliefs.add(b) }+ R.mems = mems.map(([, o]) => o)+ R.direct = [...direct]+ R.local = local.sort((a, b) => S.asks[b].at - S.asks[a].at)+ R.localSet = new Set(local)+ R.hits = null+ S.extra = []+ R.sel = 0+ buildResults()+ renderHint()+ clearTimeout(searchTimer)+ if (terms.length) {+ const asked = q+ searchTimer = setTimeout(() => {+ MemoryData.search(asked).then((hits) => {+ if (S.recall !== R || R.q !== asked) return+ R.hits = hits || []+ 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()+ }).catch(() => {})+ }, 160)+ }+ }++ function buildResults() {+ const R = S.recall+ const roomy = G.H > 760+ 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 && M_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 >= 24 ? '+' : ''}` }); 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 sum = $('recall-sum')+ const terms = wordsOf(R.q)+ sum.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)}”`+ const list = $('recall-list')+ list.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; list.append(li); continue }+ if (r === picked) li.className = 'sel'+ if (r.kind === 'memory') {+ const o = r.o+ li.append(dot(o.rgb))+ const w = el('span', 'w'); marked(w, mark(o.m.title || o.m.path, terms)); li.append(w)+ 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'))+ const w = el('span', 'w serif'); marked(w, mark(r.b.text, terms)); li.append(w)+ li.append(el('span', 'a', short(r.b.sec.name, 16)))+ } else {+ const engine = r.ask?.engine ?? r.hit?.engine+ const ag = MemoryData.agent(engine, S.snapshot)+ li.append(dot(YOU, 'ring'))+ const w = el('span', 'w serif'); marked(w, r.snippet ?? clean(r.hit?.snippet ?? '')); li.append(w)+ 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) : ''}`))+ }+ list.append(li)+ }+ // Keep the selection in view when the list is long.+ const sel = list.querySelector('.sel')+ if (sel && sel.scrollIntoView) sel.scrollIntoView({ block: 'nearest' })+ }++ // Local matches already listed (hits for the same message are not repeated).+ function M_has(i) { return S.recall && S.recall.local && S.recall.localSet && S.recall.localSet.has(i) }++ // A window of the message around its first match, with matches marked.+ 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)+ }++ 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+ }++ 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') {+ const b = r.b+ 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)+ }+ }++ // ── sound (off until m) ─────────────────────────────────────────────────────────────────────────++ let audio = null+ function tone(b) {+ if (!S.sound || !b) return+ try {+ audio = audio || new (window.AudioContext || window.webkitAudioContext)()+ if (audio.state === 'suspended') audio.resume()+ const now = audio.currentTime+ const scale = [0, 2, 4, 7, 9]+ const deg = b.sec.k * 2 + (b.sec.beliefs.length - 1 - b.j)+ const semis = scale[deg % 5] + 12 * Math.floor(deg / 5)+ const f = 174.6 * Math.pow(2, semis / 12)+ const out = audio.createGain()+ const lp = audio.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 2600+ out.connect(lp); lp.connect(audio.destination)+ out.gain.setValueAtTime(0.0001, now)+ out.gain.exponentialRampToValueAtTime(0.13, now + 0.006)+ out.gain.exponentialRampToValueAtTime(0.0001, now + 2.8)+ for (const [mult, g, det] of [[1, 1, 0], [1, 0.5, 4], [2, 0.32, 0], [3, 0.12, -3], [4.01, 0.05, 0]]) {+ const osc = audio.createOscillator(); osc.type = 'sine'; osc.frequency.value = f * mult; osc.detune.value = det+ const og = audio.createGain(); og.gain.value = g+ osc.connect(og); og.connect(out); osc.start(now); osc.stop(now + 2.9)+ }+ } catch { /* no sound here */ }+ }++ // ── keys ────────────────────────────────────────────────────────────────────────────────────────++ addEventListener('keydown', (e) => {+ if (!S.ready) return+ if (e.metaKey || e.ctrlKey || e.altKey) return+ const k = e.key+ if (!S.arrival.done) { e.preventDefault(); finishArrival(); return }++ if (S.panel) {+ const body = $('p-body')+ if (k === 'Escape' || k === 'Backspace') { e.preventDefault(); closePanel() }+ else if (k === 'ArrowDown' || k === 'j') { e.preventDefault(); body.scrollBy({ top: 64 }) }+ else if (k === 'ArrowUp' || k === 'k') { e.preventDefault(); body.scrollBy({ top: -64 }) }+ else if (k === ' ' || k === 'PageDown') { e.preventDefault(); body.scrollBy({ top: body.clientHeight * 0.85 * (e.shiftKey ? -1 : 1) }) }+ else if (k === 'PageUp') { e.preventDefault(); body.scrollBy({ top: -body.clientHeight * 0.85 }) }+ else if (k === 'Home') { e.preventDefault(); body.scrollTop = 0 }+ else if (k === 'End') { e.preventDefault(); body.scrollTop = body.scrollHeight }+ return+ }++ if (S.recall) {+ const R = S.recall+ if (k === 'Escape') { e.preventDefault(); closeRecall(); return }+ if (k === 'Backspace') { e.preventDefault(); const q = R.q.slice(0, -1); if (!q) closeRecall(); else setQuery(q); return }+ if (k === 'ArrowDown' || (k === 'Tab' && !e.shiftKey)) { e.preventDefault(); R.sel = Math.min(R.pick.length - 1, R.sel + 1); renderRecall(); return }+ if (k === 'ArrowUp' || (k === 'Tab' && e.shiftKey)) { e.preventDefault(); R.sel = Math.max(0, R.sel - 1); renderRecall(); return }+ if (k === 'Enter') { e.preventDefault(); activateRecall(); return }+ if (k.length === 1) { e.preventDefault(); if (R.q.length < 60) setQuery(R.q + k); return }+ return+ }++ if (k === 'm') { e.preventDefault(); S.sound = !S.sound; toast(S.sound ? 'sound on' : 'sound off'); renderHint(); if (S.sound) tone(focusedBelief()); return }+ if (k === '/') { e.preventDefault(); startRecall(''); return }++ if (S.view === 'self') {+ const b = focusedBelief()+ if (k === 'ArrowLeft' || k === 'ArrowRight') {+ e.preventDefault()+ const d = k === 'ArrowLeft' ? -1 : 1+ const next = S.sec + d+ if (next >= 0 && next < S.sections.length) focusBelief(next, S.bel)+ return+ }+ if (k === 'ArrowUp') { e.preventDefault(); if (b && S.bel > 0) focusBelief(S.sec, S.bel - 1); return }+ if (k === 'ArrowDown') {+ e.preventDefault()+ if (b && S.bel < b.sec.beliefs.length - 1) focusBelief(S.sec, S.bel + 1)+ else descend(null)+ return+ }+ if (k === ' ') { e.preventDefault(); pluck(b); return }+ if (k === 'Tab') {+ e.preventDefault()+ if (!b || !b.threads.length) return+ 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+ }+ if (k === 'Enter') {+ e.preventDefault()+ if (!b) { descend(null); return }+ const th = b.threads[S.thread >= 0 ? S.thread : b.threads.findIndex((x) => x.kind === 'memory')] ?? b.threads[0]+ 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)+ return+ }+ if (k === 'Escape') { e.preventDefault(); if (S.thread >= 0) { S.thread = -1; renderCaption(false) } return }+ } else {+ if (k === 'ArrowLeft') { e.preventDefault(); swim(-1, 0); return }+ if (k === 'ArrowRight') { e.preventDefault(); swim(1, 0); return }+ if (k === 'ArrowDown') { e.preventDefault(); swim(0, 1); return }+ if (k === 'ArrowUp') { e.preventDefault(); if (!swim(0, -1)) rise(); return }+ if (k === 'Enter') { e.preventDefault(); const o = focusedOrb(); if (o) openPanel({ kind: 'memory', o }, [o.x, o.y - S.cam.y]); return }+ if (k === 'Escape') { e.preventDefault(); rise(); return }+ if (k === ' ') {+ e.preventDefault()+ 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+ }+ }+ if (k.length === 1 && /[\p{L}\p{N}]/u.test(k)) { e.preventDefault(); startRecall(k) }+ })++ // The mouse works too, quietly: click a bead or an orb; scroll to dive or rise.+ canvas.addEventListener('click', (e) => {+ if (!S.ready || S.panel || S.recall) return+ if (!S.arrival.done) { finishArrival(); return }+ const x = e.clientX, y = e.clientY + S.cam.y+ 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 (best) { if (S.view === 'lake') rise(); focusBelief(best.sec.k, best.j); pluck(best); 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) { if (S.view === 'lake' && S.orb === bo.i) openPanel({ kind: 'memory', o: bo }, [bo.x, bo.y - S.cam.y]); else descend(bo) }+ })+ let wheelLock = 0+ addEventListener('wheel', (e) => {+ if (!S.ready || S.panel || !S.arrival.done || S.time < wheelLock) return+ 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 })++ // ── loop ────────────────────────────────────────────────────────────────────────────────────────++ let raf = 0, last = 0+ function frame(now) {+ raf = 0+ const dt = Math.min(0.05, last ? (now - last) / 1000 : 1 / 60)+ last = now+ S.time += dt+ if (!S.arrival.done) {+ S.arrival.t += dt+ if (S.arrival.t > 0.3 && S.arrival.t < 3.3) $('whisper').classList.add('on')+ else $('whisper').classList.remove('on')+ if (S.arrival.t >= ARRIVE_END) finishArrival()+ }+ const t0 = performance.now()+ update(dt)+ draw()+ S.frameMs = S.frameMs ? S.frameMs * 0.95 + (performance.now() - t0) * 0.05 : performance.now() - t0+ if (!document.hidden) raf = requestAnimationFrame(frame)+ }+ function start() { if (!raf && !document.hidden) { last = 0; raf = requestAnimationFrame(frame) } }+ document.addEventListener('visibilitychange', () => { if (document.hidden) { if (raf) cancelAnimationFrame(raf); raf = 0 } else if (S.ready) start() })+ let resizeTimer = 0+ addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { if (!S.ready) return; layout(); if (S.view === 'lake') { S.cam.y = S.cam.to = G.lakeCam } }, 60) })++ async function main() {+ let data+ try { data = await MemoryData.load() } catch (error) {+ const box = $('error'); box.style.display = 'grid'; box.textContent = 'Could not read memories: ' + String(error?.message ?? error)+ return+ }+ build(data)+ layout()+ S.ready = true+ renderStatus()+ renderHint()+ renderCaption(false)+ if (reduce) finishArrival()+ // Measure once fonts settle, for the leader line.+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(measureCaption)+ // A hook for automated checks; read-only.+ window.__self = { S, G, finishArrival }+ start()+ }+ main()+})()diff --git a/docs/research/2026-10-10-memory-brain/serve.mjs b/docs/research/2026-10-10-memory-brain/serve.mjsnew file mode 100644index 000000000..7b2241fe8--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/serve.mjs@@ -0,0 +1,56 @@+#!/usr/bin/env node+/**+ * Serves these prototypes on this computer, and, for pages opened with ?real, this computer's own+ * memories: what the Memories viewer reads (store/agents/memories/lib), read on each request and never+ * written anywhere. Loopback only; it only reads.+ *+ * node docs/research/2026-10-10-memory-brain/serve.mjs [port]+ * open http://127.0.0.1:<port>/ invented memories+ * open http://127.0.0.1:<port>/?real yours+ */+import { createServer } from 'node:http'+import { readFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { dirname, extname, join, normalize, sep } from 'node:path'+import { fileURLToPath } from 'node:url'++const here = dirname(fileURLToPath(import.meta.url))+const lib = (name) => import(new URL(`../../../store/agents/memories/lib/${name}`, import.meta.url).href)+const { snapshot } = await lib('state.mjs')+const { sessionIndex } = await lib('state.mjs')+const { asks, search } = await lib('sessions.mjs')+const { homes } = await lib('agents.mjs')++const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.md': 'text/plain; charset=utf-8' }+const json = (res, status, body) => { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)) }++async function index() {+ const found = await sessionIndex(homes(process.env, homedir()))+ if (!found.db) throw new Error(found.error ?? 'No session index.')+ return found.db+}++const server = createServer(async (req, res) => {+ try {+ const { port } = server.address()+ if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(req.headers.host)) { json(res, 403, { error: 'Loopback only.' }); return }+ const site = req.headers['sec-fetch-site']+ if (site && site !== 'same-origin' && site !== 'none') { json(res, 403, { error: 'Only these pages may ask.' }); return }+ const url = new URL(req.url, `http://${req.headers.host}`)+ if (url.pathname === '/real/snapshot') { json(res, 200, await snapshot({ env: process.env, home: homedir(), now: Date.now() })); return }+ if (url.pathname === '/real/asks') { json(res, 200, { asks: asks(await index(), { limit: 4000, maxChars: 400 }) }); return }+ if (url.pathname === '/real/search') { json(res, 200, { hits: search(await index(), (url.searchParams.get('q') ?? '').slice(0, 200), { limit: 24 }) }); return }+ const path = normalize(join(here, url.pathname === '/' ? 'index.html' : decodeURIComponent(url.pathname)))+ if (!path.startsWith(here + sep) || !TYPES[extname(path)]) { json(res, 404, { error: 'Not found.' }); return }+ const body = await readFile(path).catch(() => null)+ if (!body) { json(res, 404, { error: 'Not found.' }); return }+ res.writeHead(200, { 'content-type': TYPES[extname(path)], 'cache-control': 'no-store' })+ res.end(body)+ } catch (error) {+ json(res, 500, { error: String(error?.message ?? error) })+ }+})++server.listen(Number(process.argv[2] ?? 0), '127.0.0.1', () => {+ console.log(`Memory brain prototypes: http://127.0.0.1:${server.address().port}/ (yours: add ?real)`)+})diff --git a/docs/research/2026-10-10-memory-brain/synapse-recall.png b/docs/research/2026-10-10-memory-brain/synapse-recall.pngnew file mode 100644index 000000000..09297124aBinary files /dev/null and b/docs/research/2026-10-10-memory-brain/synapse-recall.png differdiff --git a/docs/research/2026-10-10-memory-brain/synapse.html b/docs/research/2026-10-10-memory-brain/synapse.htmlnew file mode 100644index 000000000..08075098b--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/synapse.html@@ -0,0 +1,97 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Synapse</title>+<style>+ :root {+ --bg: #020305; --text: #d7dae0; --muted: #8a909b; --faint: #4d535d; --line: #1b1f26;+ --gold: #ffd89a; --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;+ color-scheme: dark;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text); font: 12px/1.5 var(--mono); }+ canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }+ #ink { pointer-events: none; }+ #vignette { position: fixed; inset: 0; pointer-events: none;+ background: radial-gradient(ellipse at 50% 46%, transparent 52%, rgba(0,0,0,.55) 100%); }+ #veil { position: fixed; inset: 0; pointer-events: none; opacity: 0; }++ .chrome { transition: opacity .8s; }+ body.arriving .chrome { opacity: 0; }+ #top { position: fixed; left: 16px; top: 12px; right: 16px; display: flex; gap: 14px; align-items: baseline; pointer-events: none; color: var(--faint); white-space: nowrap; overflow: hidden; }+ #top b { color: var(--muted); font-weight: 500; letter-spacing: .32em; text-transform: lowercase; }+ #stats { overflow: hidden; text-overflow: ellipsis; }++ #title { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; pointer-events: none; opacity: 0; }+ #title .t1 { font-size: 30px; letter-spacing: .9em; padding-left: .9em; color: #e9ecf2; font-weight: 300; text-transform: lowercase; }+ #title .t2 { margin-top: 18px; color: var(--muted); letter-spacing: .08em; min-height: 1.5em; }++ #clock { position: fixed; left: 0; right: 0; top: 34px; text-align: center; pointer-events: none; opacity: 0; transition: opacity .35s; }+ #clock .d { font-size: 30px; letter-spacing: .34em; padding-left: .34em; font-weight: 300; color: #eef0f4; }+ #clock .s { margin-top: 4px; color: var(--muted); letter-spacing: .06em; }+ #clock .s i { font-style: normal; color: var(--gold); }++ #strip { position: fixed; top: auto; left: 16px; right: 16px; bottom: 34px; height: 44px; width: calc(100% - 32px); opacity: 0; transition: opacity .35s; pointer-events: none; }++ #prompt { position: fixed; left: 50%; transform: translateX(-50%); bottom: 40px; display: flex; align-items: baseline; gap: 8px; max-width: calc(100% - 32px);+ padding: 7px 14px; border: 1px solid #262b33; border-radius: 4px; background: rgba(6,8,11,.78); backdrop-filter: blur(6px);+ font-size: 14px; opacity: 0; transition: opacity .2s; pointer-events: none; white-space: nowrap; }+ #prompt.on { opacity: 1; }+ #prompt .caret { color: var(--gold); }+ #q { color: #f2f3f5; overflow: hidden; text-overflow: ellipsis; }+ #cursor { display: inline-block; width: .6em; height: 1.05em; background: #f2f3f5; transform: translateY(2px); animation: blink 1.05s steps(1) infinite; }+ @keyframes blink { 50% { opacity: 0; } }+ #count { color: var(--faint); margin-left: 8px; font-size: 12px; }++ #rhythm { position: fixed; left: 16px; bottom: 12px; color: var(--faint); pointer-events: none; white-space: nowrap; opacity: 0; transition: opacity .6s; }+ #keys { position: fixed; left: 0; right: 0; bottom: 12px; text-align: center; color: var(--faint); pointer-events: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 0 16px; }+ #keys kbd { font: inherit; color: var(--muted); }+ #loading { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--faint); letter-spacing: .3em; pointer-events: none; }++ #dive { position: fixed; inset: 0; display: flex; justify-content: center; overflow: hidden; opacity: 0; pointer-events: none; transition: opacity .45s; }+ #dive.on { opacity: 1; pointer-events: auto; }+ #dive .scroll { width: 100%; height: 100%; overflow-y: auto; padding: 9vh 24px 120px;+ -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 44px, #000 calc(100% - 96px), transparent calc(100% - 40px));+ mask-image: linear-gradient(to bottom, transparent 0, #000 44px, #000 calc(100% - 96px), transparent calc(100% - 40px)); scrollbar-width: thin; scrollbar-color: #2a2f37 transparent; }+ #dive .col { max-width: 78ch; margin: 0 auto; transform: translateY(10px); transition: transform .6s cubic-bezier(.2,.7,.2,1); }+ #dive.on .col { transform: none; }+ #dive .kicker { color: var(--muted); letter-spacing: .14em; text-transform: uppercase; font-size: 11px; display: flex; flex-wrap: wrap; gap: 0 12px; align-items: center; }+ #dive .kicker .dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; box-shadow: 0 0 10px currentColor; background: currentColor; }+ #dive h1 { font-size: 30px; line-height: 1.25; font-weight: 400; color: #f4f5f7; margin: 16px 0 10px; letter-spacing: -.005em; text-wrap: balance; overflow-wrap: anywhere; }+ #dive h1.long { font-size: 21px; line-height: 1.45; }+ #dive .desc { color: #a9afba; font-size: 14px; margin: 0 0 22px; }+ #dive .body { color: #c9cdd4; font-size: 13.5px; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; border-left: 1px solid #262b33; padding-left: 18px; }+ #dive .body .h { color: #eef0f3; font-weight: 600; display: block; margin-top: .6em; }+ #dive .body .em { color: #f0d9b0; }+ #dive .meta { color: var(--faint); margin-top: 18px; font-size: 11px; overflow-wrap: anywhere; }+ #dive .group { margin-top: 30px; }+ #dive .group h2 { font-size: 11px; font-weight: 400; color: var(--muted); letter-spacing: .14em; text-transform: uppercase; margin: 0 0 8px; }+ #dive .row { display: flex; gap: 10px; align-items: baseline; padding: 6px 10px; margin: 0 -10px; border-radius: 3px; color: #b8bdc6; cursor: pointer; }+ #dive .row .dot { flex: none; width: 6px; height: 6px; border-radius: 50%; transform: translateY(-1px); }+ #dive .row .txt { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ #dive .row .when { flex: none; color: var(--faint); font-size: 11px; }+ #dive .row.sel { background: rgba(255,255,255,.07); color: #f4f5f7; }+ #dive .row.sel::before { content: '›'; color: var(--gold); margin-left: -2px; }+ #dive .row.self { color: var(--gold); }+</style>+</head>+<body class="arriving">+<canvas id="gl" aria-label="A brain built from your memories"></canvas>+<canvas id="ink"></canvas>+<div id="vignette"></div>+<div id="veil"></div>+<div id="loading">gathering memories</div>+<header id="top" class="chrome"><b>synapse</b><span id="stats"></span></header>+<div id="title"><div class="t1">synapse</div><div class="t2"></div></div>+<div id="clock"><div class="d"></div><div class="s"></div></div>+<canvas id="strip"></canvas>+<div id="prompt"><span class="caret">›</span><span id="q"></span><span id="cursor"></span><span id="count"></span></div>+<section id="dive" aria-live="polite"><div class="scroll"><div class="col"></div></div></section>+<div id="rhythm"></div>+<footer id="keys" class="chrome"></footer>+<script src="memory-data.js"></script>+<script src="synapse.js"></script>+</body>+</html>diff --git a/docs/research/2026-10-10-memory-brain/synapse.js b/docs/research/2026-10-10-memory-brain/synapse.jsnew file mode 100644index 000000000..c16e99334--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/synapse.js@@ -0,0 +1,2049 @@+/*+ * Synapse: fly into a brain built from what your agents remember about you.+ *+ * Every message you sent is a neuron, placed in the region of its project and tinted by the agent it went to.+ * Memory notes are bright engrams on the cortex; memories kept for every project sit in the hippocampi. About+ * You lines are hubs along the bridge between the hemispheres, with axons to the memories they cite. Older+ * activity whose words are not loaded here lies deep inside as faint dust. The brain fires in the rhythm of+ * your last two weeks. Type to recall (spreading activation), Enter to dive, [ ] to move through time.+ *+ * Reads only MemoryData. Its text is untrusted (written by models and people): it reaches the screen only+ * through canvas fillText and textContent. Nothing here writes anywhere.+ */+(function () {+ 'use strict'++ const DAY = 86_400_000+ const HOUR = 3_600_000+ const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches+ const $ = (id) => document.getElementById(id)+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n }++ // ── numbers ──────────────────────────────────────────────────────────────────────────────────────++ 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+ }+ }+ function hash(s) { let h = 2166136261; s = String(s); for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) } return h >>> 0 }+ const clamp = (x, a, b) => (x < a ? a : x > b ? b : x)+ const lerp = (a, b, t) => a + (b - a) * t+ const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t) }+ const easeOut = (t) => 1 - Math.pow(1 - clamp(t, 0, 1), 3)+ const easeInOut = (t) => { t = clamp(t, 0, 1); return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2 }+ const dist2 = (a, b) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2++ // Perlin noise, for the folds of the cortex and the borders between regions.+ const perm = new Uint8Array(512)+ ;(function () { const r = rng(7); const p = Array.from({ length: 256 }, (_, i) => i); for (let i = 255; i > 0; i--) { const j = Math.floor(r() * (i + 1)); const t = p[i]; p[i] = p[j]; p[j] = t } for (let i = 0; i < 512; i++) perm[i] = p[i & 255] })()+ const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10)+ function grad(h, x, y, z) { h &= 15; const u = h < 8 ? x : y; const v = h < 4 ? y : h === 12 || h === 14 ? x : z; return ((h & 1) ? -u : u) + ((h & 2) ? -v : v) }+ function noise(x, y, z) {+ const fx = Math.floor(x), fy = Math.floor(y), fz = Math.floor(z)+ const X = fx & 255, Y = fy & 255, Z = fz & 255+ x -= fx; y -= fy; z -= fz+ const u = fade(x), v = fade(y), w = fade(z)+ const A = perm[X] + Y, AA = perm[A] + Z, AB = perm[A + 1] + Z, B = perm[X + 1] + Y, BA = perm[B] + Z, BB = perm[B + 1] + Z+ return lerp(+ lerp(lerp(grad(perm[AA], x, y, z), grad(perm[BA], x - 1, y, z), u), lerp(grad(perm[AB], x, y - 1, z), grad(perm[BB], x - 1, y - 1, z), u), v),+ lerp(lerp(grad(perm[AA + 1], x, y, z - 1), grad(perm[BA + 1], x - 1, y, z - 1), u), lerp(grad(perm[AB + 1], x, y - 1, z - 1), grad(perm[BB + 1], x - 1, y - 1, z - 1), u), v), w)+ }++ // ── colour ───────────────────────────────────────────────────────────────────────────────────────++ function hexRGB(hex) { const m = /^#?([0-9a-f]{6})$/i.exec(String(hex || '').trim()); const n = m ? parseInt(m[1], 16) : 0x8b8f96; return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255] }+ const mix = (a, b, t) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]+ const css = (c, a = 1) => `rgba(${Math.round(c[0] * 255)},${Math.round(c[1] * 255)},${Math.round(c[2] * 255)},${a})`+ function hsl(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 = (t + 1) % 1; return t < 1 / 6 ? p + (q - p) * 6 * t : t < 0.5 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p }+ return [f(h + 1 / 3), f(h), f(h - 1 / 3)]+ }+ const WHITE = [1, 1, 1]+ const GOLD = [1, 0.84, 0.56]+ const BG = [0.008, 0.012, 0.02]++ // ── words and time ───────────────────────────────────────────────────────────────────────────────++ const words = (text) => String(text ?? '').toLowerCase().match(/[\p{L}\p{N}_]{2,}/gu) ?? []+ const STOP = new Set('the and for with that this from into when what where which have has are was were will would should could about after before every never always only than then them they their there here your you our its not but all any each one two also just like make made does done keep more most some such over under very much many same other need needs use used uses using via per why how apply user users memory memories note notes summary saved topic profile observation handbook remembered request rules description file files line lines thing things want wants work works working please can let lets now new get got see look looks into onto been being able way does did doing dont don isn didn wasn won yes okay ok'.split(' '))+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']+ const pad = (n) => String(n).padStart(2, '0')+ const hm = (ms) => { const d = new Date(ms); return `${pad(d.getHours())}:${pad(d.getMinutes())}` }+ const dayShort = (ms) => { const d = new Date(ms); return `${d.getDate()} ${MONTHS[d.getMonth()]}` }+ const dayLong = (ms) => { const d = new Date(ms); return `${WEEKDAYS[d.getDay()]} ${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}` }+ const dayKey = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` }+ const num = (n) => Number(n).toLocaleString('en-US')+ const plural = (n, one, many) => `${num(n)} ${n === 1 ? one : many || one + 's'}`+ function ago(ms, now) {+ const d = Math.max(0, now - ms)+ if (d < 90e3) return 'just now'+ if (d < HOUR) return `${Math.round(d / 60e3)} min ago`+ if (d < DAY) return `${Math.round(d / HOUR)} h ago`+ if (d < 45 * DAY) return plural(Math.round(d / DAY), 'day') + ' ago'+ return plural(Math.round(d / (30 * DAY)), 'month') + ' ago'+ }+ const flat = (s) => String(s ?? '').replace(/\s+/g, ' ').trim()+ /** A folder-derived project name as a person would say it. */+ const pretty = (name) => String(name ?? '').replace(/^Library-Application-Support-/i, '').replace(/-[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i, '').replace(/-projects$/i, '') || String(name ?? '')+ const short = (s, n) => { s = flat(s); return s.length > n ? s.slice(0, n - 1) + '…' : s }++ // ── the shape of a brain ─────────────────────────────────────────────────────────────────────────+ // x: left/right, y: up, z: front. Each function returns ~1 at the surface, smaller inside, -1 outside.++ const CENTER = { x: 0, y: 0.0, z: -0.06 }++ function cerebrum(x, y, z) {+ const ax = Math.abs(x)+ if (ax < 0.03 && y > -0.26) return -1 // the longitudinal fissure between the hemispheres+ const qx = ax - 0.42, qy = y - 0.04, qz = z+ const front = smooth(0.1, 1.0, qz), back = smooth(0.4, 1.05, -qz)+ const rx = (qx > 0 ? 0.43 : 0.42) * (1 - 0.2 * front)+ const ry = qy > 0 ? 0.6 * (1 - 0.24 * front - 0.32 * back) : 0.34 * (1 - 0.3 * back - 0.42 * smooth(0.25, 0.95, qz))+ const rz = qz > 0 ? 0.98 : 1.04+ const px = Math.abs(qx / rx)+ const e1 = Math.sqrt((qx > 0 ? px * px : Math.pow(px, 6)) + (qy / ry) ** 2 + (qz / rz) ** 2)+ const tx = ax - 0.5, ty = y + 0.25, tz = z - 0.03+ const e2 = Math.sqrt((tx / 0.31) ** 2 + (ty / 0.25) ** 2 + (tz / (tz > 0 ? 0.5 : 0.48)) ** 2)+ const e = Math.min(e1, e2)+ if (e > 1) return -1+ // the lateral fissure: the groove above the temporal lobe+ if (ax > 0.48 && z > -0.42 && z < 0.5 && e > 0.78) {+ const fy = -0.12 + 0.17 * smooth(0.45, -0.4, z)+ if (Math.abs(y - fy) < 0.03) return -1+ }+ return e+ }++ function cerebellum(x, y, z) {+ const qx = Math.abs(x) - 0.22, qy = y + 0.53, qz = z + 0.72+ const e = Math.sqrt((qx / 0.37) ** 2 + (qy / 0.2) ** 2 + (qz / 0.29) ** 2)+ if (e > 1) return -1+ if (e > 0.7) { const r = Math.hypot(qy + 0.03, qz + 0.14); if ((r * 38) % 1 < 0.3) return -1 } // folia+ return e+ }++ function stem(x, y, z) {+ if (y > -0.2 || y < -1.08) return -1+ const t = (-0.2 - y) / 0.88+ const cz = -0.25 - 0.16 * t+ const r = 0.1 - 0.03 * t + 0.05 * Math.exp(-(((t - 0.2) / 0.13) ** 2))+ const d = Math.hypot(x / 1.2, z - cz) / r+ return d <= 1 ? d : -1+ }++ /** Points filling the brain: a dense cortex (the shell), a sparse interior, and the brain stem. */+ function samplePool(nShell, nInner, nStem, seed) {+ const r = rng(seed)+ const shell = [], inner = [], stemPts = []+ let guard = 0+ while ((shell.length < nShell || inner.length < nInner) && guard++ < 3e6) {+ const x = (r() * 2 - 1) * 0.88, y = -0.75 + r() * 1.44, z = -1.06 + r() * 2.06+ let e = cerebrum(x, y, z), part = 0+ if (e < 0) { e = cerebellum(x, y, z); part = 1 }+ if (e < 0) continue+ if (e > 0.8) {+ if (shell.length >= nShell) continue+ let fold = 1+ if (part === 0 && e > 0.84) {+ const n = Math.abs(noise(x * 3.7 + 5.1, y * 3.7 + 1.7, z * 3.7))+ if (n < 0.09) continue // sulci+ fold = smooth(0.09, 0.42, n)+ }+ shell.push({ x, y, z, e, part, fold, region: -1, used: false })+ } else {+ if (inner.length >= nInner || r() > 0.5) continue+ inner.push({ x, y, z, e, part, region: -1, used: false })+ }+ }+ guard = 0+ while (stemPts.length < nStem && guard++ < 4e5) {+ const x = (r() * 2 - 1) * 0.2, y = -1.08 + r() * 0.9, z = -0.62 + r() * 0.55+ const e = stem(x, y, z)+ if (e >= 0 && (e > 0.7 || r() < 0.3)) stemPts.push({ x, y, z, e })+ }+ return { shell, inner, stem: stemPts }+ }++ /** A spatial hash, to grow a conversation as one patch of cortex. */+ function makeGrid(points, cell) {+ const map = new Map()+ const key = (ix, iy, iz) => ix + iy * 128 + iz * 16384+ const cellOf = (v) => Math.floor((v + 1.3) / cell)+ for (const p of points) {+ const k = key(cellOf(p.x), cellOf(p.y), cellOf(p.z))+ let list = map.get(k)+ if (!list) map.set(k, (list = []))+ list.push(p)+ }+ function claim(seed, k, accept) {+ const out = []+ const cx = cellOf(seed.x), cy = cellOf(seed.y), cz = cellOf(seed.z)+ for (let r = 0; r <= 26 && out.length < k; r++) {+ const ring = []+ for (let dx = -r; dx <= r; dx++) for (let dy = -r; dy <= r; dy++) for (let dz = -r; dz <= r; dz++) {+ if (Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz)) !== r) continue+ const list = map.get(key(cx + dx, cy + dy, cz + dz))+ if (!list) continue+ for (const p of list) if (!p.used && accept(p)) ring.push(p)+ }+ ring.sort((a, b) => dist2(a, seed) - dist2(b, seed))+ for (const p of ring) { if (out.length >= k) break; p.used = true; out.push(p) }+ }+ return out+ }+ return { claim }+ }++ // Lobes, in the order regions are given them (largest first).+ const ANCHORS = [+ [-0.45, 0.3, 0.45], [0.45, 0.3, 0.45], [-0.45, 0.42, -0.4], [0.45, 0.42, -0.4], [-0.64, -0.3, 0.05], [0.64, -0.3, 0.05],+ [-0.32, 0.08, -0.92], [0.32, 0.08, -0.92], [0, -0.55, -0.74], [-0.4, 0.58, 0.05], [0.4, 0.58, 0.05], [-0.3, -0.02, 0.9],+ [0.3, -0.02, 0.9], [-0.68, 0.04, -0.52], [0.68, 0.04, -0.52], [-0.28, -0.2, 0.58], [0.28, -0.2, 0.58],+ ]++ /** Capacity-constrained Voronoi over the cortex: each region gets a lobe sized to what it holds. */+ function partition(points, targets) {+ const K = targets.length+ const seeds = targets.map((_, i) => {+ const a = ANCHORS[i % ANCHORS.length]+ const j = Math.floor(i / ANCHORS.length)+ return { x: a[0] * (1 - 0.18 * j), y: a[1] - 0.1 * j, z: a[2] * (1 - 0.2 * j) }+ })+ const warped = points.map((p) => ({+ x: p.x + 0.07 * noise(p.x * 2.6 + 11, p.y * 2.6, p.z * 2.6),+ y: p.y + 0.07 * noise(p.x * 2.6, p.y * 2.6 + 23, p.z * 2.6),+ z: p.z + 0.07 * noise(p.x * 2.6, p.y * 2.6, p.z * 2.6 + 37),+ }))+ const w = new Float64Array(K)+ const counts = new Float64Array(K)+ for (let iter = 0; iter < 28; iter++) {+ counts.fill(0)+ for (let i = 0; i < points.length; i++) {+ const q = warped[i]+ let best = 0, bestD = Infinity+ for (let k = 0; k < K; k++) { const d = dist2(q, seeds[k]) - w[k]; if (d < bestD) { bestD = d; best = k } }+ points[i].region = best+ counts[best]+++ }+ for (let k = 0; k < K; k++) w[k] += 0.9 * (targets[k] - counts[k] / points.length)+ }+ return { seeds, warped, w }+ }++ // ── the model: regions, neurons, engrams, hubs, and how they connect ─────────────────────────────++ const NEURON = 1, GHOST = 2, ENGRAM = 3, HUB = 4++ function buildModel(data) {+ const { snapshot } = data+ const asks = (data.asks || []).filter((a) => a && Number.isFinite(a.at))+ const now = snapshot.observedAt || Date.now()+ const R = rng(1010)+ const agentCache = new Map()+ const agentOf = (id) => {+ if (!agentCache.has(id)) { const a = MemoryData.agent(id, snapshot); agentCache.set(id, { id, name: a.name || id, rgb: hexRGB(a.color) }) }+ return agentCache.get(id)+ }++ // Regions: the person's projects, by folder; conversations with no folder recorded are placed by the+ // project names their words mention.+ const projects = (snapshot.projects || []).filter((p) => p && p.name)+ const tilde = (p) => String(p || '').replace(/^\/(?:Users|home)\/[^/]+/, '~').replace(/\/+$/, '')+ const projectPaths = projects+ .map((p) => ({ name: p.name, path: tilde(p.path || (p.key && !String(p.key).startsWith('name:') ? p.key : '')) }))+ .filter((p) => p.path && p.path !== '~')+ .sort((a, b) => b.path.length - a.path.length)+ function placeOfCwd(cwd) {+ const c = tilde(cwd)+ if (!c) return null+ for (const p of projectPaths) if (c === p.path || c.startsWith(p.path + '/') || c.startsWith(p.path + '.')) return p.name+ const segments = c.split('/')+ for (const p of projects) if (segments.includes(p.name)) return p.name // a worktree named after its repository+ if (/^\/(private\/)?(tmp|var)(\/|$)/.test(c)) return 'scratch folders'+ if (c === '~') return 'home folder'+ return segments.slice(0, 2).join('/').replace(/^~\//, '') || c+ }+ const GENERIC = new Set(['autonomous', 'code', 'harnesses', 'projects', 'project', 'library', 'application', 'support', 'app', 'page', 'main', 'test', 'tests', 'agent', 'agents', 'claude', 'codex', 'brainstorms', 'chat', 'live', 'first', 'shell', 'home'])+ const tokenDf = new Map()+ const projectTokens = projects.map((p) => {+ const tokens = [...new Set(String(p.name).toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length >= 4 && !/^\d+$/.test(t) && !/^[0-9a-f]{6,}$/.test(t) && !GENERIC.has(t)))]+ for (const t of tokens) tokenDf.set(t, (tokenDf.get(t) || 0) + 1)+ return { name: p.name, full: String(p.name).toLowerCase(), tokens, prior: Math.log(1 + (p.asks || 0)) }+ })+ function placeOfWords(text) {+ let best = null, bestScore = 0+ for (const p of projectTokens) {+ let hits = 0, score = 0+ const full = text.split(p.full).length - 1+ if (full) { hits += full; score += 4 * Math.log(1 + full) }+ for (const t of p.tokens) {+ const n = text.split(t).length - 1+ if (n) { hits += n; score += Math.log(1 + projects.length / tokenDf.get(t)) * Math.log(1 + n) }+ }+ if (!hits) continue+ score = score / Math.max(1, Math.sqrt(p.tokens.length)) + 0.5 * p.prior+ if (score > bestScore) { bestScore = score; best = p.name }+ }+ return best+ }++ // Conversations+ const sessions = new Map()+ for (const ask of asks) {+ let s = sessions.get(ask.sessionId)+ if (!s) sessions.set(ask.sessionId, (s = { id: ask.sessionId, asks: [], engine: ask.engine, title: '', places: new Map() }))+ s.asks.push(ask)+ if (!s.title && ask.title) s.title = ask.title+ const place = placeOfCwd(ask.cwd)+ if (place) s.places.set(place, (s.places.get(place) || 0) + 1)+ }+ for (const s of sessions.values()) {+ s.asks.sort((a, b) => a.turn - b.turn || a.at - b.at)+ s.start = Math.min(...s.asks.map((a) => a.at))+ s.end = Math.max(...s.asks.map((a) => a.at))+ if (s.places.size) s.place = [...s.places].sort((a, b) => b[1] - a[1])[0][0]+ else {+ const text = (s.title + ' ' + s.asks.map((a) => a.text).join(' ')).toLowerCase().slice(0, 40000)+ s.place = placeOfWords(text) || 'no folder recorded'+ s.inferred = true+ }+ }++ // Region sizes, then merge the crumbs+ const memories = (snapshot.memories || []).filter((m) => m && m.id)+ const size = new Map()+ const bump = (name, n, mem) => { const r = size.get(name) || { name, neurons: 0, memories: 0 }; r.neurons += n; r.memories += mem; size.set(name, r) }+ for (const s of sessions.values()) bump(s.place, s.asks.length, 0)+ for (const m of memories) if (m.project && m.project.name) bump(m.project.name, 0, 1)+ const total = [...size.values()].reduce((sum, r) => sum + r.neurons, 0) || 1+ let list = [...size.values()].sort((a, b) => (b.neurons + b.memories * 6) - (a.neurons + a.memories * 6))+ const keep = new Set()+ for (const r of list) {+ if (keep.size >= 15) break+ if (r.memories || r.neurons >= Math.max(6, total * 0.004)) keep.add(r.name)+ }+ const ELSEWHERE = 'elsewhere'+ const regionName = (name) => (keep.has(name) ? name : ELSEWHERE)+ const merged = new Map()+ for (const r of list) {+ const name = regionName(r.name)+ const m = merged.get(name) || { name, neurons: 0, memories: 0, parts: [] }+ m.neurons += r.neurons; m.memories += r.memories; m.parts.push(r.name)+ merged.set(name, m)+ }+ list = [...merged.values()].sort((a, b) => (b.neurons + b.memories * 6) - (a.neurons + a.memories * 6))+ const regions = list.map((r, id) => ({ id, name: r.name, label: pretty(r.name), parts: r.parts, neuronCount: r.neurons, memoryCount: r.memories, nodes: [], engrams: [], color: null }))+ const regionByName = new Map(regions.map((r) => [r.name, r]))+ const regionOf = (name) => regionByName.get(regionName(name)) || regionByName.get(ELSEWHERE) || regions[0]++ // Older activity: the days the session index counted but whose words are not among the messages loaded here.+ const loadedPerDay = new Map()+ for (const a of asks) { const k = `${dayKey(a.at)} ${a.engine}`; loadedPerDay.set(k, (loadedPerDay.get(k) || 0) + 1) }+ const ghostDays = []+ for (const row of (snapshot.sessions && snapshot.sessions.activity) || []) {+ if (!row || !row.day) continue+ const extra = (row.asks || 0) - (loadedPerDay.get(`${row.day} ${row.engine}`) || 0)+ if (extra > 0) ghostDays.push({ day: row.day, engine: row.engine, count: extra })+ }+ let ghostTotal = ghostDays.reduce((s, d) => s + d.count, 0)+ const ghostScale = ghostTotal > 7000 ? 7000 / ghostTotal : 1+ ghostTotal = 0+ for (const d of ghostDays) { d.count = Math.max(1, Math.round(d.count * ghostScale)); ghostTotal += d.count }++ // ── layout ──+ const nShell = clamp(Math.round(asks.length * 3.4 + memories.length * 4), 21000, 26000)+ const nInner = clamp(Math.round(ghostTotal * 1.45), 2600, 10500)+ const pool = samplePool(nShell, nInner, 900, 31)+ const capacityNeed = regions.map((r) => (r.neuronCount + r.memoryCount + 4) * 1.12 / pool.shell.length)+ let targets = regions.map((r) => Math.max(0.025, Math.pow(Math.max(1, r.neuronCount + r.memoryCount * 8), 0.72)))+ const tSum = targets.reduce((a, b) => a + b, 0)+ targets = targets.map((t, i) => Math.max(t / tSum, capacityNeed[i]))+ const t2 = targets.reduce((a, b) => a + b, 0)+ targets = targets.map((t) => t / t2)+ const parts = regions.length ? partition(pool.shell, targets) : { seeds: [] }+ for (const p of pool.inner) {+ let best = 0, bestD = Infinity+ for (let k = 0; k < parts.seeds.length; k++) { const d = dist2(p, parts.seeds[k]); if (d < bestD) { bestD = d; best = k } }+ p.region = best+ }+ const shellGrid = makeGrid(pool.shell, 0.06)+ const innerGrid = makeGrid(pool.inner, 0.08)++ // Region tints for the scaffold: quiet, cool, distinct.+ const HUES = [212, 168, 262, 32, 196, 300, 140, 232, 12, 186, 280, 54, 224, 152, 336, 248]+ regions.forEach((r, i) => { r.color = hsl(HUES[i % HUES.length], 0.5, 0.64) })+ for (const r of regions) {+ const own = pool.shell.filter((p) => p.region === r.id)+ r.slots = own+ const c = own.reduce((acc, p) => ({ x: acc.x + p.x, y: acc.y + p.y, z: acc.z + p.z }), { x: 0, y: 0, z: 0 })+ const n = Math.max(1, own.length)+ r.centroid = { x: c.x / n, y: c.y / n, z: c.z / n }+ }++ const nodes = []+ const add = (node) => { node.index = nodes.length; node.edges = []; nodes.push(node); return node }++ // Engrams first: the outermost cortex of their region, spread apart.+ const memoryNodes = new Map()+ const globalMemories = []+ for (const m of memories) {+ if (!(m.project && m.project.name)) { globalMemories.push(m); continue }+ const region = regionOf(m.project.name)+ region.engrams.push(m)+ }+ for (const region of regions) {+ if (!region.engrams.length) continue+ let candidates = region.slots.filter((p) => p.e > 0.9 && !p.used)+ if (candidates.length < region.engrams.length * 2) candidates = region.slots.filter((p) => !p.used)+ const chosen = []+ if (candidates.length) {+ let first = candidates[0], bd = Infinity+ for (const p of candidates) { const d = dist2(p, region.centroid); if (d < bd) { bd = d; first = p } }+ chosen.push(first); first.used = true+ const minD = candidates.map((p) => dist2(p, first))+ while (chosen.length < region.engrams.length && chosen.length < candidates.length) {+ let bi = -1, best = -1+ for (let i = 0; i < candidates.length; i++) if (!candidates[i].used && minD[i] > best) { best = minD[i]; bi = i }+ if (bi < 0) break+ const p = candidates[bi]; p.used = true; chosen.push(p)+ for (let i = 0; i < candidates.length; i++) { const d = dist2(candidates[i], p); if (d < minD[i]) minD[i] = d }+ }+ }+ region.engrams.sort((a, b) => (a.modified || 0) - (b.modified || 0))+ region.engrams.forEach((m, i) => {+ const p = chosen[i] || region.centroid+ const agent = agentOf(m.agent)+ const node = add({+ k: ENGRAM, x: p.x, y: p.y, z: p.z, rgb: mix(agent.rgb, WHITE, 0.42), glow: 1.5,+ size: 0.017 + 0.006 * clamp(Math.log10(1 + (m.size || (m.body || '').length)) / 4.5, 0, 1),+ birth: m.modified || now, region: region.id, memory: m, agent,+ hay: { title: flat(m.title).toLowerCase(), desc: flat(m.description).toLowerCase(), body: String(m.body || '').toLowerCase() },+ })+ region.nodes.push(node)+ memoryNodes.set(m.id, node)+ })+ }+ // Memories kept for every project live in the hippocampi: memory's own organ.+ const hippocampus = (side, u) => ({ x: side * (0.27 - 0.05 * u), y: -0.24 + 0.2 * u * u, z: 0.2 - 0.62 * u })+ globalMemories.sort((a, b) => String(a.agent).localeCompare(String(b.agent)) || (a.modified || 0) - (b.modified || 0))+ globalMemories.forEach((m, i) => {+ const side = hash(m.agent) % 2 ? 1 : -1+ const u = (i + 0.5) / globalMemories.length+ const p = hippocampus(side, (u * 2) % 1 * 0.9 + 0.05)+ const agent = agentOf(m.agent)+ const node = add({+ k: ENGRAM, x: p.x + (R() - 0.5) * 0.03, y: p.y + (R() - 0.5) * 0.03, z: p.z + (R() - 0.5) * 0.03,+ rgb: mix(agent.rgb, WHITE, 0.42), glow: 1.5,+ size: 0.017 + 0.006 * clamp(Math.log10(1 + (m.size || (m.body || '').length)) / 4.5, 0, 1),+ birth: m.modified || now, region: -1, memory: m, agent,+ hay: { title: flat(m.title).toLowerCase(), desc: flat(m.description).toLowerCase(), body: String(m.body || '').toLowerCase() },+ })+ memoryNodes.set(m.id, node)+ })++ // Neurons: each conversation grows as one patch, older ones nearer the region's root.+ const neuronByTurn = new Map()+ const bySession = new Map()+ for (const region of regions) {+ const own = [...sessions.values()].filter((s) => regionOf(s.place) === region).sort((a, b) => a.start - b.start)+ if (!own.length) continue+ let root = region.slots[0] || region.centroid, rd = Infinity+ for (const p of region.slots) { const d = dist2(p, CENTER); if (d < rd) { rd = d; root = p } }+ const ordered = region.slots.slice().sort((a, b) => dist2(a, root) - dist2(b, root))+ const totalAsks = own.reduce((s, x) => s + x.asks.length, 0)+ let cum = 0+ for (const s of own) {+ const q = (cum + s.asks.length / 2) / totalAsks+ cum += s.asks.length+ const seed = ordered.length ? ordered[Math.min(ordered.length - 1, Math.floor(q * (ordered.length - 1)))] : region.centroid+ const spots = shellGrid.claim(seed, s.asks.length, (p) => p.region === region.id)+ const agent = agentOf(s.engine)+ const chain = []+ s.asks.forEach((ask, i) => {+ const p = spots[i] || { x: seed.x + (R() - 0.5) * 0.06, y: seed.y + (R() - 0.5) * 0.06, z: seed.z + (R() - 0.5) * 0.06 }+ const node = add({+ k: NEURON, x: p.x + (R() - 0.5) * 0.008, y: p.y + (R() - 0.5) * 0.008, z: p.z + (R() - 0.5) * 0.008,+ rgb: agentOf(ask.engine).rgb, glow: 1.5,+ size: 0.0068 * (1 + 0.35 * clamp(Math.log10(1 + (ask.length || ask.text.length)) / 3.4, 0, 1)),+ birth: ask.at, region: region.id, ask, agent: agentOf(ask.engine), session: s, lower: String(ask.text || '').toLowerCase(),+ })+ region.nodes.push(node)+ chain.push(node)+ neuronByTurn.set(`${ask.sessionId}:${ask.turn}`, node)+ })+ s.nodes = chain+ s.region = region+ s.agent = agent+ bySession.set(s.id, s)+ }+ }++ // Ghosts: older days, deep inside, oldest nearest the centre.+ const ghostsByDay = new Map()+ if (ghostTotal) {+ const ordered = pool.inner.slice().sort((a, b) => dist2(a, CENTER) - dist2(b, CENTER))+ ghostDays.sort((a, b) => a.day.localeCompare(b.day) || String(a.engine).localeCompare(String(b.engine)))+ let cum = 0+ for (const d of ghostDays) {+ const q = (cum + d.count / 2) / ghostTotal+ cum += d.count+ const seed = ordered[Math.min(ordered.length - 1, Math.floor(q * (ordered.length - 1)))]+ const spots = innerGrid.claim(seed, d.count, () => true)+ const dayStart = new Date(d.day + 'T00:00:00').getTime()+ const agent = agentOf(d.engine)+ const rgb = mix(agent.rgb, [0.55, 0.6, 0.7], 0.45)+ const list = []+ for (let i = 0; i < d.count; i++) {+ const p = spots[i] || { x: seed.x + (R() - 0.5) * 0.08, y: seed.y + (R() - 0.5) * 0.08, z: seed.z + (R() - 0.5) * 0.08 }+ const hour = 8 + 16 * Math.pow(R(), 0.8)+ const node = add({+ k: GHOST, x: p.x, y: p.y, z: p.z, rgb, glow: 0.55, size: 0.0052,+ birth: dayStart + hour * HOUR, region: p.region ?? -1, agent, day: d.day,+ })+ list.push(node)+ }+ const key = `${d.day} ${d.engine}`+ ghostsByDay.set(key, (ghostsByDay.get(key) || []).concat(list))+ }+ }++ // About You: hubs along the bridge between the hemispheres.+ const about = snapshot.about || {}+ const lines = (about.lines || []).filter((l) => l && l.text)+ const aboutBirth = about.gen || about.modified || now+ const hubs = []+ lines.forEach((line, i) => {+ const u = (i + 0.5) / Math.max(1, lines.length)+ const z = 0.46 - 1.0 * u+ const y = 0.1 + 0.13 * Math.sin(Math.PI * clamp(u * 1.05, 0, 1))+ const node = add({ k: HUB, x: (i % 2 ? 1 : -1) * 0.012, y, z, rgb: GOLD, glow: 1.6, size: 0.026, birth: aboutBirth, region: -1, line, lower: line.text.toLowerCase() })+ const askRef = (line.refs || []).map((r) => /^asks:(\d+)$/.exec(r)).find(Boolean)+ node.askCount = askRef ? Number(askRef[1]) : 0+ node.cites = MemoryData.refs(line, snapshot).map((m) => memoryNodes.get(m.id)).filter(Boolean)+ hubs.push(node)+ })++ // ── connections ──+ const lineVerts = []+ const link = (a, b, w) => { a.edges.push([b.index, w]); b.edges.push([a.index, w]) }+ function straight(a, b, alpha, kind) { lineVerts.push({ a, b, t0: 0, t1: 1, p: a, q: b, ca: a.rgb, cb: b.rgb, alpha, kind }) }+ function fiber(a, b, alpha, kind, bulge = 0.16) {+ const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2, mz = (a.z + b.z) / 2+ let dx = mx - CENTER.x, dy = my - CENTER.y + 0.25, dz = mz - CENTER.z+ const dl = Math.hypot(dx, dy, dz) || 1+ const len = Math.sqrt(dist2(a, b))+ const c = { x: mx + (dx / dl) * bulge * len, y: my + (dy / dl) * bulge * len, z: mz + (dz / dl) * bulge * len }+ const curve = { a, b, c }+ const N = 14+ let prev = a+ for (let i = 1; i <= N; i++) {+ const t = i / N+ const p = bez(a, c, b, t)+ lineVerts.push({ a, b, t0: (i - 1) / N, t1: t, p: prev, q: p, ca: mix(a.rgb, b.rgb, (i - 1) / N), cb: mix(a.rgb, b.rgb, t), alpha, kind })+ prev = p+ }+ return curve+ }+ // conversation chains+ for (const s of bySession.values()) for (let i = 1; i < s.nodes.length; i++) { link(s.nodes[i - 1], s.nodes[i], 0.55); straight(s.nodes[i - 1], s.nodes[i], 0.05, 'chain') }++ // memories ↔ messages that share their rarer words+ const neurons = nodes.filter((n) => n.k === NEURON)+ const postings = new Map()+ neurons.forEach((n) => { for (const w of new Set(words(n.ask.text))) { if (w.length < 4 || STOP.has(w)) continue; let l = postings.get(w); if (!l) postings.set(w, (l = [])); l.push(n) } })+ const engrams = nodes.filter((n) => n.k === ENGRAM)+ for (const e of engrams) {+ const tokens = [...new Set(words(e.memory.title + ' ' + e.memory.description))].filter((w) => w.length >= 4 && !STOP.has(w))+ const score = new Map()+ for (const t of tokens) {+ const l = postings.get(t)+ if (!l || l.length > Math.max(12, neurons.length * 0.06)) continue+ const idf = Math.log(1 + neurons.length / l.length)+ for (const n of l) score.set(n, (score.get(n) || 0) + idf + (n.region === e.region ? 0.6 : 0))+ }+ const top = [...score].filter(([, s]) => s > 2.2).sort((a, b) => b[1] - a[1]).slice(0, 6)+ e.related = top.map(([n]) => n)+ for (const n of e.related) { link(e, n, 0.65); straight(e, n, 0.022, 'assoc'); (n.memories ||= []).push(e) }+ }+ // memories ↔ their nearest neighbours in the same region+ for (const region of regions) {+ const es = region.nodes.filter((n) => n.k === ENGRAM)+ for (const e of es) {+ const near = es.filter((o) => o !== e).sort((a, b) => dist2(a, e) - dist2(b, e)).slice(0, 2)+ for (const o of near) if (!e.edges.some(([j]) => j === o.index)) { link(e, o, 0.35); straight(e, o, 0.05, 'mesh') }+ }+ }+ // global memories along the hippocampus+ const globals = engrams.filter((e) => e.region < 0).sort((a, b) => a.z - b.z)+ for (let i = 1; i < globals.length; i++) if (Math.sign(globals[i].x) === Math.sign(globals[i - 1].x)) { link(globals[i], globals[i - 1], 0.3); straight(globals[i], globals[i - 1], 0.06, 'mesh') }++ // About You axons: to the memories each line cites, and to the regions those memories hold+ const fibers = []+ const anchorOf = (region) => {+ if (region.anchor !== undefined) return region.anchor+ let best = null, bd = Infinity+ for (const n of region.nodes) if (n.k === NEURON) { const d = dist2(n, region.centroid); if (d < bd) { bd = d; best = n } }+ region.anchor = best || region.nodes[0] || null+ return region.anchor+ }+ const biggest = regions.filter((r) => r.nodes.some((n) => n.k === NEURON)).sort((a, b) => b.neuronCount - a.neuronCount)+ for (const h of hubs) {+ for (const e of h.cites) { link(h, e, 0.85); fibers.push(fiber(h, e, 0.13, 'axon')) }+ const touched = new Set(h.cites.filter((e) => e.region >= 0).map((e) => e.region))+ for (const id of touched) { const a = anchorOf(regions[id]); if (a) { link(h, a, 0.35); fibers.push(fiber(h, a, 0.09, 'axon', 0.25)) } }+ if (h.askCount && biggest.length) {+ const fan = clamp(Math.round(Math.log10(1 + h.askCount) * 1.6), 1, 5)+ const r = rng(hash(h.line.text))+ for (let i = 0; i < fan; i++) {+ const region = biggest[Math.min(biggest.length - 1, Math.floor(Math.pow(r(), 2) * biggest.length))]+ const cands = region.nodes.filter((n) => n.k === NEURON)+ const n = cands[Math.floor(r() * cands.length)]+ if (n) { link(h, n, 0.3); fibers.push(fiber(h, n, 0.07, 'axon', 0.3)) }+ }+ }+ if (!h.cites.length && !h.askCount && biggest.length) { const a = anchorOf(biggest[0]); if (a) { link(h, a, 0.3); fibers.push(fiber(h, a, 0.07, 'axon', 0.25)) } }+ }+ for (let i = 1; i < hubs.length; i++) if (hubs[i].line.section === hubs[i - 1].line.section) { link(hubs[i], hubs[i - 1], 0.3); straight(hubs[i], hubs[i - 1], 0.22, 'spine') }+ // reverse citations, for the dive+ for (const h of hubs) for (const e of h.cites) (e.heldBy ||= []).push(h)++ // ── scaffold: the faint tissue that gives the brain its shape ──+ const scaffold = []+ for (const p of pool.shell) if (!p.used) { const r = regions[p.region]; scaffold.push({ x: p.x, y: p.y, z: p.z, rgb: r ? r.color : [0.5, 0.6, 0.8], glow: (0.3 + 0.75 * (p.e - 0.8) * 5) * (0.06 + 0.94 * Math.pow(p.fold ?? 1, 1.6)) * (p.part === 1 ? 1.4 : 1), size: 0.0048 }) }+ for (const p of pool.inner) if (!p.used) { const r = regions[p.region]; scaffold.push({ x: p.x, y: p.y, z: p.z, rgb: mix(r ? r.color : [0.5, 0.6, 0.8], [0.45, 0.5, 0.65], 0.5), glow: 0.16, size: 0.0042 }) }+ for (const p of pool.stem) scaffold.push({ x: p.x, y: p.y, z: p.z, rgb: [0.5, 0.56, 0.72], glow: 0.3 + 0.25 * p.e, size: 0.0044 })+ const hr = rng(77)+ for (let i = 0; i < 520; i++) {+ const side = i % 2 ? 1 : -1+ const p = hippocampus(side, hr())+ scaffold.push({ x: p.x + (hr() - 0.5) * 0.05, y: p.y + (hr() - 0.5) * 0.04, z: p.z + (hr() - 0.5) * 0.04, rgb: [0.72, 0.62, 0.95], glow: 0.55, size: 0.0048 })+ }+ for (let i = 0; i < 260; i++) {+ const u = hr()+ scaffold.push({ x: (hr() - 0.5) * 0.05, y: 0.1 + 0.13 * Math.sin(Math.PI * clamp(u * 1.05, 0, 1)) - 0.03 + hr() * 0.02, z: 0.46 - u, rgb: [0.9, 0.78, 0.55], glow: 0.45, size: 0.0046 })+ }++ // timeline bounds+ const births = nodes.map((n) => n.birth).filter(Number.isFinite)+ const tMin = births.length ? Math.min(...births) - 6 * HOUR : now - DAY+ const tMax = Math.max(now, births.length ? Math.max(...births) : now) + 60_000++ return {+ now, snapshot, real: data.real, regions, nodes, scaffold, lineVerts, fibers, hubs, engrams, neurons, bySession,+ neuronByTurn, ghostsByDay, tMin, tMax, aboutBirth, asksCount: asks.length, ghostTotal,+ totals: { messages: snapshot.sessions?.asks || asks.length, loaded: asks.length, memories: memories.length, lines: lines.length, regions: regions.length, sessions: sessions.size },+ inferred: [...sessions.values()].filter((s) => s.inferred).length,+ }+ }++ function bez(a, c, b, t) {+ const u = 1 - t+ return { x: u * u * a.x + 2 * u * t * c.x + t * t * b.x, y: u * u * a.y + 2 * u * t * c.y + t * t * b.y, z: u * u * a.z + 2 * u * t * c.z + t * t * b.z }+ }++ // ── matrices ─────────────────────────────────────────────────────────────────────────────────────++ function perspective(fovy, aspect, near, far) {+ const f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far)+ return new Float32Array([f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) * nf, -1, 0, 0, 2 * far * near * nf, 0])+ }+ function lookAt(e, t) {+ let zx = e.x - t.x, zy = e.y - t.y, zz = e.z - t.z+ let l = Math.hypot(zx, zy, zz) || 1; zx /= l; zy /= l; zz /= l+ let xx = zz, xy = 0, xz = -zx // up (0,1,0) × z+ l = Math.hypot(xx, xy, xz) || 1; xx /= l; xy /= l; xz /= l+ const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx+ return new Float32Array([xx, yx, zx, 0, xy, yy, zy, 0, xz, yz, zz, 0,+ -(xx * e.x + xy * e.y + xz * e.z), -(yx * e.x + yy * e.y + yz * e.z), -(zx * e.x + zy * e.y + zz * e.z), 1])+ }++ // ── renderers ────────────────────────────────────────────────────────────────────────────────────++ function glRenderer(canvas) {+ let gl = null+ try { gl = canvas.getContext('webgl', { antialias: false, alpha: false, depth: false, stencil: false, premultipliedAlpha: false, powerPreference: 'high-performance' }) } catch { gl = null }+ if (!gl) return null+ const compile = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s)); return s }+ const program = (vs, fs) => { const p = gl.createProgram(); gl.attachShader(p, compile(gl.VERTEX_SHADER, vs)); gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fs)); gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p)); return p }+ const points = program(`+ attribute vec3 aPos; attribute vec3 aStart; attribute vec3 aColor; attribute float aSize; attribute float aDelay; attribute vec2 aDyn;+ uniform mat4 uView; uniform mat4 uProj; uniform float uPx; uniform float uMaxPx; uniform float uArrive; uniform float uMul;+ varying vec3 vColor; varying float vAlpha; varying float vPx;+ void main() {+ float k = clamp((uArrive - aDelay) / 1.9, 0.0, 1.0);+ float e = 1.0 - pow(1.0 - k, 3.0);+ vec3 p = mix(aStart, aPos, e);+ vec4 v = uView * vec4(p, 1.0);+ float depth = -v.z;+ gl_Position = uProj * v;+ float px = aSize * aDyn.y * uPx / max(depth, 0.001);+ float a = aDyn.x * uMul * smoothstep(0.012, 0.14, depth) * (1.0 - 0.8 * smoothstep(5.0, 18.0, depth));+ a *= mix(2.2, 1.0, k) + 1.4 * k * (1.0 - k); // brighter in flight: a field of stars falling into place+ if (px < 1.6) { a *= px * px / 2.56; px = 1.6; }+ gl_PointSize = min(px, uMaxPx);+ vColor = aColor; vAlpha = a; vPx = px;+ if (a < 0.0015 || depth < 0.004) gl_Position = vec4(0.0, 0.0, 2.0, 1.0);+ }`, `+ precision mediump float; varying vec3 vColor; varying float vAlpha; varying float vPx;+ void main() {+ vec2 d = gl_PointCoord * 2.0 - 1.0; float r2 = dot(d, d); if (r2 > 1.0) discard;+ // tiny points are soft discs; larger ones get a hot core and a halo+ float big = smoothstep(3.0, 14.0, vPx);+ float core = exp(-r2 * mix(1.4, 9.0, big));+ float halo = 0.34 * exp(-r2 * 2.6) * (1.0 - r2) * big;+ float a = (core + halo) * vAlpha;+ vec3 c = mix(vColor, vec3(1.0), clamp(core * vAlpha - 0.9, 0.0, 0.6));+ gl_FragColor = vec4(c * a, 1.0);+ }`)+ const lines = program(`+ attribute vec3 aPos; attribute vec3 aColor; attribute float aAlpha;+ uniform mat4 uView; uniform mat4 uProj; uniform float uMul;+ varying vec3 vColor; varying float vA;+ void main() { vec4 v = uView * vec4(aPos, 1.0); gl_Position = uProj * v; float depth = -v.z;+ vA = aAlpha * uMul * smoothstep(0.02, 0.2, depth) * (1.0 - 0.7 * smoothstep(5.0, 18.0, depth)); vColor = aColor; }`, `+ precision mediump float; varying vec3 vColor; varying float vA;+ void main() { gl_FragColor = vec4(vColor * vA, 1.0); }`)+ const loc = (p, names) => Object.fromEntries(names.map((n) => [n, n[0] === 'a' ? gl.getAttribLocation(p, n) : gl.getUniformLocation(p, n)]))+ const P = loc(points, ['aPos', 'aStart', 'aColor', 'aSize', 'aDelay', 'aDyn', 'uView', 'uProj', 'uPx', 'uMaxPx', 'uArrive', 'uMul'])+ const L = loc(lines, ['aPos', 'aColor', 'aAlpha', 'uView', 'uProj', 'uMul'])+ const maxPx = Math.min(256, gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE)[1] || 64)+ const buf = (data, usage) => { const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, data, usage || gl.STATIC_DRAW); return b }+ const bind = (l, b, size) => { if (l < 0) return; gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.enableVertexAttribArray(l); gl.vertexAttribPointer(l, size, gl.FLOAT, false, 0, 0) }+ const sets = {}+ let lineSet = null+ return {+ kind: 'webgl',+ maxPx,+ points(name, a) {+ sets[name] = { count: a.count, pos: buf(a.pos, a.dynamicPos ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW), start: a.start === a.pos ? null : buf(a.start), color: buf(a.color, a.dynamicPos ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW), size: buf(a.size, a.dynamicPos ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW), delay: buf(a.delay), dyn: buf(a.dyn, gl.DYNAMIC_DRAW) }+ },+ update(name, field, data, count) {+ const s = sets[name]; if (!s) return+ gl.bindBuffer(gl.ARRAY_BUFFER, s[field]); gl.bufferSubData(gl.ARRAY_BUFFER, 0, data)+ if (count != null) s.count = count+ },+ lines(a) { lineSet = { count: a.count, pos: buf(a.pos), color: buf(a.color), alpha: buf(a.alpha, gl.DYNAMIC_DRAW) } },+ updateLines(alpha) { if (!lineSet) return; gl.bindBuffer(gl.ARRAY_BUFFER, lineSet.alpha); gl.bufferSubData(gl.ARRAY_BUFFER, 0, alpha) },+ resize(w, h) { gl.viewport(0, 0, w, h) },+ draw(f) {+ gl.clearColor(BG[0], BG[1], BG[2], 1); gl.clear(gl.COLOR_BUFFER_BIT)+ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); gl.disable(gl.DEPTH_TEST)+ if (lineSet && f.lineMul > 0.001) {+ gl.useProgram(lines)+ gl.uniformMatrix4fv(L.uView, false, f.view); gl.uniformMatrix4fv(L.uProj, false, f.proj); gl.uniform1f(L.uMul, f.lineMul)+ for (let i = 0; i < 8; i++) gl.disableVertexAttribArray(i)+ bind(L.aPos, lineSet.pos, 3); bind(L.aColor, lineSet.color, 3); bind(L.aAlpha, lineSet.alpha, 1)+ gl.drawArrays(gl.LINES, 0, lineSet.count)+ }+ gl.useProgram(points)+ gl.uniformMatrix4fv(P.uView, false, f.view); gl.uniformMatrix4fv(P.uProj, false, f.proj)+ gl.uniform1f(P.uPx, f.px); gl.uniform1f(P.uMaxPx, maxPx); gl.uniform1f(P.uArrive, f.arrive)+ for (const name of ['scaffold', 'nodes', 'pulses']) {+ const s = sets[name]; if (!s || !s.count) continue+ for (let i = 0; i < 8; i++) gl.disableVertexAttribArray(i)+ gl.uniform1f(P.uMul, f.mul[name] ?? 1)+ bind(P.aPos, s.pos, 3); bind(P.aStart, s.start || s.pos, 3); bind(P.aColor, s.color, 3); bind(P.aSize, s.size, 1); bind(P.aDelay, s.delay, 1); bind(P.aDyn, s.dyn, 2)+ gl.drawArrays(gl.POINTS, 0, s.count)+ }+ },+ }+ }++ /** Without WebGL: the same scene through canvas 2D, lighter on the tissue. */+ function canvasRenderer(canvas) {+ const ctx = canvas.getContext('2d')+ const sprites = new Map()+ const sprite = (rgb) => {+ const key = rgb.map((c) => Math.round(c * 15)).join(',')+ if (sprites.has(key)) return sprites.get(key)+ const s = document.createElement('canvas'); s.width = s.height = 32+ const g = s.getContext('2d'); const gr = g.createRadialGradient(16, 16, 0, 16, 16, 16)+ gr.addColorStop(0, css(mix(rgb, WHITE, 0.3), 1)); gr.addColorStop(0.25, css(rgb, 0.55)); gr.addColorStop(1, css(rgb, 0))+ g.fillStyle = gr; g.fillRect(0, 0, 32, 32); sprites.set(key, s); return s+ }+ const sets = {}+ let lineSet = null+ let W = 1, H = 1+ return {+ kind: 'canvas',+ maxPx: 96,+ points(name, a) { sets[name] = { ...a } },+ update(name, field, data, count) { const s = sets[name]; if (!s) return; s[field] = data; if (count != null) s.count = count },+ lines(a) { lineSet = a },+ updateLines(alpha) { if (lineSet) lineSet.alpha = alpha },+ resize(w, h) { W = w; H = h },+ draw(f) {+ const v = f.view, pr = f.proj+ ctx.globalCompositeOperation = 'source-over'+ ctx.fillStyle = css(BG); ctx.fillRect(0, 0, W, H)+ ctx.globalCompositeOperation = 'lighter'+ const proj = (x, y, z) => {+ const vx = v[0] * x + v[4] * y + v[8] * z + v[12], vy = v[1] * x + v[5] * y + v[9] * z + v[13], vz = v[2] * x + v[6] * y + v[10] * z + v[14]+ if (vz > -0.01) return null+ return [(pr[0] * vx / -vz + 1) * 0.5 * W, (1 - pr[5] * vy / -vz) * 0.5 * H, -vz]+ }+ if (lineSet && f.lineMul > 0.001) {+ ctx.lineWidth = 1+ for (let i = 0; i < lineSet.count; i += 2) {+ const a = lineSet.alpha[i] * f.lineMul; if (a < 0.03) continue+ const p = proj(lineSet.pos[i * 3], lineSet.pos[i * 3 + 1], lineSet.pos[i * 3 + 2]); const q = proj(lineSet.pos[i * 3 + 3], lineSet.pos[i * 3 + 4], lineSet.pos[i * 3 + 5])+ if (!p || !q) continue+ ctx.strokeStyle = css([lineSet.color[i * 3], lineSet.color[i * 3 + 1], lineSet.color[i * 3 + 2]], Math.min(1, a))+ ctx.beginPath(); ctx.moveTo(p[0], p[1]); ctx.lineTo(q[0], q[1]); ctx.stroke()+ }+ }+ for (const name of ['scaffold', 'nodes', 'pulses']) {+ const s = sets[name]; if (!s || !s.count) continue+ const mul = f.mul[name] ?? 1+ const step = name === 'scaffold' ? 3 : 1+ for (let i = 0; i < s.count; i += step) {+ let k = clamp((f.arrive - s.delay[i]) / 1.9, 0, 1); const e = 1 - Math.pow(1 - k, 3)+ const st = s.start || s.pos+ const x = lerp(st[i * 3], s.pos[i * 3], e), y = lerp(st[i * 3 + 1], s.pos[i * 3 + 1], e), z = lerp(st[i * 3 + 2], s.pos[i * 3 + 2], e)+ const p = proj(x, y, z); if (!p) continue+ let a = s.dyn[i * 2] * mul * (lerp(2.2, 1, k) + 1.4 * k * (1 - k)) * smooth(0.012, 0.14, p[2]) * step+ let px = s.size[i] * s.dyn[i * 2 + 1] * f.px / p[2] * 2.2+ if (px < 1.6) { a *= px * px / 2.56; px = 1.6 }+ if (a < 0.01) continue+ px = Math.min(px, 96)+ ctx.globalAlpha = Math.min(1, a)+ ctx.drawImage(sprite([s.color[i * 3], s.color[i * 3 + 1], s.color[i * 3 + 2]]), p[0] - px / 2, p[1] - px / 2, px, px)+ }+ }+ ctx.globalAlpha = 1+ ctx.globalCompositeOperation = 'source-over'+ },+ }+ }++ // ── the page ─────────────────────────────────────────────────────────────────────────────────────++ const glCanvas = $('gl'), ink = $('ink'), inkCtx = ink.getContext('2d'), strip = $('strip'), stripCtx = strip.getContext('2d')+ let renderer = null+ try { renderer = glRenderer(glCanvas) } catch (error) { console.warn('WebGL unavailable, drawing with canvas 2D:', error.message); renderer = null }+ if (!renderer) {+ const fresh = glCanvas.cloneNode(false); glCanvas.replaceWith(fresh)+ renderer = canvasRenderer(fresh)+ }+ const surface = document.getElementById('gl')++ let M = null // the model+ let W = 1, H = 1, dpr = 1+ const FOV = 50 * Math.PI / 180+ const HOME = { tx: 0, ty: -0.12, tz: -0.04, yaw: -1.12, pitch: 0.28, dist: 2.85 }+ const cam = { ...HOME }+ const want = { ...HOME }+ let camRate = 3+ let view = new Float32Array(16), proj = new Float32Array(16), pxScale = 1+ let eye = { x: 0, y: 0, z: 3 }++ // dynamic state+ let dyn = null, spikeAt = null, spikeAmp = null, bornAt = null, recallLevel = null, recallStart = null+ let lineAlpha = null, lineBase = null, lineA = null, lineB = null, lineT = null+ let order = null, birthsSorted = null+ const MAXPULSE = 900+ const pulseTrail = 3+ let pulsePos, pulseCol, pulseSize, pulseDyn, pulseDelay+ const pulses = []++ const state = {+ mode: 'loading', // loading | arrival | explore | dive+ arrivalStart: 0, arrivalDur: reduceMotion ? 1.0 : 4.8,+ lastInput: performance.now(), mouse: { x: 0, y: 0, at: -1e9, down: false, dragged: false, lx: 0, ly: 0 },+ keys: new Set(),+ aim: -1, aimSince: 0,+ }+ const recall = { q: '', terms: [], items: [], focus: 0, seq: 0, active: false, fade: 0, camAt: 0, camDone: true, before: null, region: -1, hits: new Map() }+ const time = { on: false, u: 1, want: 1, playing: false, rewinding: false, T: Infinity, lastT: Infinity, rate: 0, endHold: 0, table: null }+ const dive = { stack: [], rows: [], sel: -1, before: null, showAt: 0, node: -1, rgb: WHITE }+ const ambient = { window: 14 * DAY, loop: 46, clock: 0, last: 0, label: '' }++ function resize() {+ dpr = Math.min(2, window.devicePixelRatio || 1)+ W = Math.max(1, Math.round(innerWidth * dpr)); H = Math.max(1, Math.round(innerHeight * dpr))+ surface.width = W; surface.height = H+ ink.width = W; ink.height = H+ strip.width = Math.round(strip.clientWidth * dpr) || 1; strip.height = Math.round(strip.clientHeight * dpr) || 1+ renderer.resize(W, H)+ }+ addEventListener('resize', resize)++ // ── building the GPU side ──++ function upload() {+ const S = M.scaffold, N = M.nodes+ const r = rng(99)+ const far = () => { const u = r() * 2 - 1, th = r() * Math.PI * 2, rad = 3.5 + 9 * Math.pow(r(), 0.7), s = Math.sqrt(1 - u * u); return [Math.cos(th) * s * rad, u * rad * 0.7, Math.sin(th) * s * rad] }+ {+ const pos = new Float32Array(S.length * 3), start = new Float32Array(S.length * 3), color = new Float32Array(S.length * 3), size = new Float32Array(S.length), delay = new Float32Array(S.length), d = new Float32Array(S.length * 2)+ S.forEach((p, i) => {+ pos.set([p.x, p.y, p.z], i * 3); start.set(reduceMotion ? [p.x, p.y, p.z] : far(), i * 3); color.set(p.rgb, i * 3); size[i] = p.size+ delay[i] = reduceMotion ? 0 : 0.5 + 2.2 * r() * (0.6 + 0.4 * (1 - Math.min(1, Math.hypot(p.x, p.y, p.z))))+ d[i * 2] = p.glow; d[i * 2 + 1] = 1+ })+ renderer.points('scaffold', { count: S.length, pos, start, color, size, delay, dyn: d })+ }+ {+ const pos = new Float32Array(N.length * 3), start = new Float32Array(N.length * 3), color = new Float32Array(N.length * 3), size = new Float32Array(N.length), delay = new Float32Array(N.length)+ dyn = new Float32Array(N.length * 2)+ N.forEach((n, i) => {+ pos.set([n.x, n.y, n.z], i * 3); start.set(reduceMotion ? [n.x, n.y, n.z] : far(), i * 3); color.set(n.rgb, i * 3); size[i] = n.size+ const base = n.k === HUB ? 0.2 : n.k === ENGRAM ? 0.7 : n.k === GHOST ? 1.0 : 1.2+ delay[i] = reduceMotion ? 0 : base + (n.k === HUB ? 0.25 * r() : n.k === ENGRAM ? 0.6 * r() : 1.5 * r())+ dyn[i * 2] = n.glow; dyn[i * 2 + 1] = 1+ })+ renderer.points('nodes', { count: N.length, pos, start, color, size, delay, dyn })+ }+ {+ const cap = MAXPULSE * pulseTrail+ pulsePos = new Float32Array(cap * 3); pulseCol = new Float32Array(cap * 3); pulseSize = new Float32Array(cap); pulseDyn = new Float32Array(cap * 2); pulseDelay = new Float32Array(cap).fill(-100)+ renderer.points('pulses', { count: 0, pos: pulsePos, start: pulsePos, color: pulseCol, size: pulseSize, delay: pulseDelay, dyn: pulseDyn, dynamicPos: true })+ }+ {+ const V = M.lineVerts.length * 2+ const pos = new Float32Array(V * 3), color = new Float32Array(V * 3)+ lineAlpha = new Float32Array(V); lineBase = new Float32Array(V); lineA = new Int32Array(V); lineB = new Int32Array(V); lineT = new Float32Array(V)+ M.lineVerts.forEach((s, i) => {+ const j = i * 2+ pos.set([s.p.x, s.p.y, s.p.z, s.q.x, s.q.y, s.q.z], j * 3)+ color.set([...s.ca, ...s.cb], j * 3)+ lineBase[j] = lineBase[j + 1] = s.alpha+ lineA[j] = lineA[j + 1] = s.a.index; lineB[j] = lineB[j + 1] = s.b.index+ lineT[j] = s.t0; lineT[j + 1] = s.t1+ })+ renderer.lines({ count: V, pos, color, alpha: lineAlpha })+ }+ spikeAt = new Float64Array(N.length).fill(-1e9)+ spikeAmp = new Float32Array(N.length)+ bornAt = new Float64Array(N.length).fill(-1e9)+ recallLevel = new Float32Array(N.length)+ recallStart = new Float64Array(N.length).fill(1e15)+ order = N.map((n) => n.index).sort((a, b) => N[a].birth - N[b].birth)+ birthsSorted = new Float64Array(order.map((i) => N[i].birth))+ buildTimeTable()+ }++ // ── time ──++ function buildTimeTable() {+ const n = 1024, table = new Float64Array(n + 1)+ const span = M.tMax - M.tMin+ // progress u over the timeline: three parts births (busy weeks pass slowly), one part calendar+ const F = (t) => 0.72 * (upperBound(birthsSorted, t) / Math.max(1, birthsSorted.length)) + 0.28 * (t - M.tMin) / span+ const samples = 4096+ const ts = new Float64Array(samples + 1), fs = new Float64Array(samples + 1)+ for (let i = 0; i <= samples; i++) { ts[i] = M.tMin + span * i / samples; fs[i] = F(ts[i]) }+ let j = 0+ for (let i = 0; i <= n; i++) {+ const u = i / n * fs[samples]+ while (j < samples && fs[j + 1] < u) j+++ const f0 = fs[j], f1 = fs[Math.min(samples, j + 1)]+ table[i] = ts[j] + (f1 > f0 ? (u - f0) / (f1 - f0) : 0) * (span / samples)+ }+ time.table = table+ time.F = F+ time.Fmax = fs[samples] || 1+ }+ const tToU = (t) => clamp(time.F(t) / time.Fmax, 0, 1)+ const uToT = (u) => { const t = time.table, x = clamp(u, 0, 1) * (t.length - 1), i = Math.floor(x); return i >= t.length - 1 ? t[t.length - 1] : lerp(t[i], t[i + 1], x - i) }+ function upperBound(arr, v) { let lo = 0, hi = arr.length; while (lo < hi) { const m = (lo + hi) >> 1; if (arr[m] <= v) lo = m + 1; else hi = m } return lo }++ function startTime(u) {+ if (!time.on) {+ time.on = true; time.u = 1; time.lastT = M.tMax; time.T = M.tMax+ clearRecall(true)+ }+ time.want = clamp(u, 0, 1)+ }+ function stopTime() {+ time.on = false; time.playing = false; time.rewinding = false; time.u = time.want = 1; time.T = Infinity+ bornAt.fill(-1e9)+ }+ function stepTime(now, dt) {+ if (!time.on) return+ if (time.rewinding) {+ time.want = 0+ time.u = Math.max(0, time.u - dt / 1.5 * Math.max(0.3, time.u))+ if (time.u <= 0.002) { time.u = 0; time.rewinding = false; time.playing = true; time.want = 0 }+ } else if (time.playing) {+ time.want = Math.min(1, time.want + dt / 19)+ time.u = time.want+ if (time.u >= 1) { time.playing = false; time.endHold = now + 2400 }+ } else {+ const k = 1 - Math.exp(-dt * 7)+ time.u += (time.want - time.u) * k+ if (Math.abs(time.want - time.u) < 1e-4) time.u = time.want+ }+ const T = uToT(time.u)+ const prev = time.lastT+ if (T !== prev) {+ const a = Math.min(T, prev), b = Math.max(T, prev)+ const lo = upperBound(birthsSorted, a), hi = upperBound(birthsSorted, b)+ for (let k = lo; k < hi; k++) bornAt[order[k]] = now+ }+ time.rate = Math.abs(T - prev) / Math.max(dt, 1e-3)+ time.lastT = time.T = T+ if (time.endHold && now > time.endHold && !time.playing && time.u >= 1) { time.endHold = 0; stopTime() }+ }++ // ── ambient life: the brain fires in the rhythm of your last two weeks ──++ function stepAmbient(now, dt) {+ if (!M || !M.nodes.length) return+ const end = M.now, start = end - ambient.window+ const rate = ambient.window / ambient.loop+ const prev = ambient.clock || start+ let clock = prev + dt * rate+ const fire = (a, b) => {+ const lo = upperBound(birthsSorted, a), hi = upperBound(birthsSorted, b)+ for (let k = lo; k < hi && k - lo < 400; k++) spike(order[k], now, 1)+ }+ if (clock > end) { fire(prev, end); clock = start + (clock - end); fire(start, clock) } else fire(prev, clock)+ ambient.clock = clock+ // a little background chatter everywhere+ const n = M.nodes.length+ for (let i = 0; i < (reduceMotion ? 1 : 4); i++) if (Math.random() < dt * 2) spike(Math.floor(Math.random() * n), now, 0.45, true)+ if (Math.random() < dt * 2.2 && M.fibers.length) {+ const f = M.fibers[Math.floor(Math.random() * M.fibers.length)]+ if (isVisible(f.a.index) && isVisible(f.b.index)) addPulse(f.a, f.b, f.c, now, 1400 + 600 * Math.random(), GOLD, f.b.index, 0.9)+ }+ if (now - ambient.last > 250) { ambient.last = now; ambient.label = `${dayLong(clock).replace(/ \d{4}$/, '')} · ${hm(clock)}` }+ }+ function spike(i, now, amp, quiet) {+ if (!isVisible(i)) return+ spikeAt[i] = now; spikeAmp[i] = amp * (reduceMotion ? 0.45 : 1)+ if (quiet) return+ const n = M.nodes[i]+ if (n.k === NEURON && Math.random() < 0.3) {+ const s = n.session+ const at = s ? s.nodes.indexOf(n) : -1+ const next = at >= 0 ? s.nodes[at + 1] : null+ if (next && isVisible(next.index)) addPulse(n, next, null, now, 500, n.rgb, next.index, 0.5)+ else if (n.memories && n.memories.length) { const e = n.memories[0]; addPulse(n, e, null, now, 900, n.rgb, e.index, 0.8) }+ }+ }+ const isVisible = (i) => !time.on || M.nodes[i].birth <= time.T++ function addPulse(a, b, c, now, dur, rgb, target, glow, delay = 0) {+ if (pulses.length >= MAXPULSE) pulses.shift()+ pulses.push({ a, b, c, t0: now + delay, dur, rgb, target, glow, done: false })+ }+ function stepPulses(now) {+ let count = 0+ for (let i = pulses.length - 1; i >= 0; i--) {+ const p = pulses[i]+ const t = (now - p.t0) / p.dur+ if (t >= 1) {+ if (!p.done && p.target >= 0) { p.done = true; if (spikeAmp[p.target] < 0.7 || now - spikeAt[p.target] > 300) { spikeAt[p.target] = now; spikeAmp[p.target] = 0.7 * (reduceMotion ? 0.45 : 1) } }+ pulses.splice(i, 1); continue+ }+ }+ for (const p of pulses) {+ const t = (now - p.t0) / p.dur+ if (t < 0) continue+ for (let k = 0; k < pulseTrail; k++) {+ const tt = clamp(easeInOut(t) - k * 0.035, 0, 1)+ const q = p.c ? bez(p.a, p.c, p.b, tt) : { x: lerp(p.a.x, p.b.x, tt), y: lerp(p.a.y, p.b.y, tt), z: lerp(p.a.z, p.b.z, tt) }+ pulsePos[count * 3] = q.x; pulsePos[count * 3 + 1] = q.y; pulsePos[count * 3 + 2] = q.z+ const c = mix(p.rgb, WHITE, 0.5 - k * 0.15)+ pulseCol[count * 3] = c[0]; pulseCol[count * 3 + 1] = c[1]; pulseCol[count * 3 + 2] = c[2]+ pulseSize[count] = 0.011 * (1 - k * 0.25)+ pulseDyn[count * 2] = p.glow * (1 - k * 0.32) * Math.sin(Math.PI * clamp(t * 1.15, 0, 1)) ; pulseDyn[count * 2 + 1] = 1+ count+++ }+ }+ renderer.update('pulses', 'pos', pulsePos, count)+ renderer.update('pulses', 'color', pulseCol)+ renderer.update('pulses', 'size', pulseSize)+ renderer.update('pulses', 'dyn', pulseDyn)+ }++ // ── per-frame glow ──++ function stepGlow(now) {+ const N = M.nodes+ const recalling = recall.fade > 0.001+ const dim = recalling ? lerp(1, 0.22, recall.fade) : 1+ for (let i = 0; i < N.length; i++) {+ const n = N[i]+ let g = 0, s = 1+ const born = !time.on || n.birth <= time.T+ if (born) {+ g = n.glow * dim+ const sp = spikeAmp[i] ? Math.exp(-(now - spikeAt[i]) / 380) * spikeAmp[i] : 0+ if (sp > 0.001) { g += sp * (n.k === NEURON ? 1.5 : n.k === GHOST ? 1.1 : 0.7) * (recalling ? 0.4 : 1); s += sp * 0.7 }+ if (time.on) { const b = Math.exp(-(now - bornAt[i]) / 650); if (b > 0.001) { g += b * (n.k === GHOST ? 1.6 : 2.6); s += b * 1.6 } }+ if (recalling && recallLevel[i] > 0) {+ const t = now - recallStart[i]+ if (t > 0) {+ const lv = recallLevel[i] * recall.fade+ const env = smooth(0, 120, t) * (0.75 + 1.8 * Math.exp(-t / 520))+ g += lv * env * (n.k === NEURON ? 1.8 : n.k === GHOST ? 2.4 : 1.6)+ s += lv * env * (n.k === GHOST ? 1.6 : 0.9)+ }+ }+ if (n.k === HUB) g *= 0.85 + 0.15 * Math.sin(now / 900 + i)+ } else if (time.on) {+ const b = Math.exp(-(now - bornAt[i]) / 260)+ if (b > 0.01) { g = b * 1.6; s = 1 + b }+ }+ dyn[i * 2] = g; dyn[i * 2 + 1] = s+ }+ renderer.update('nodes', 'dyn', dyn)++ // lines follow their ends; fibers grow out from the hub when it is born+ for (let j = 0; j < lineAlpha.length; j++) {+ const a = lineA[j], b = lineB[j]+ let alpha = lineBase[j]+ if (time.on) {+ const na = N[a], nb = N[b]+ if (na.birth > time.T || nb.birth > time.T) { lineAlpha[j] = 0; continue }+ const since = (now - Math.max(bornAt[a], bornAt[b])) / 1400+ if (since < 1.2) { const grow = clamp(since * 1.4 - lineT[j], 0, 1); alpha *= grow * (1 + 2 * Math.exp(-since * 2)) }+ }+ if (recalling) {+ const ra = recallLevel[a] > 0 && now > recallStart[a] ? recallLevel[a] : 0+ const rb = recallLevel[b] > 0 && now > recallStart[b] ? recallLevel[b] : 0+ alpha = alpha * dim + (Math.min(ra, rb) > 0.3 ? Math.min(ra, rb) * recall.fade * 0.32 : 0)+ }+ lineAlpha[j] = alpha+ }+ renderer.updateLines(lineAlpha)+ }++ // ── camera ──++ function updateCamera(dt) {+ const k = 1 - Math.exp(-dt * camRate)+ let dy = want.yaw - cam.yaw+ cam.yaw += dy * k; cam.pitch += (want.pitch - cam.pitch) * k+ cam.dist = Math.exp(lerp(Math.log(cam.dist), Math.log(want.dist), k))+ cam.tx += (want.tx - cam.tx) * k; cam.ty += (want.ty - cam.ty) * k; cam.tz += (want.tz - cam.tz) * k+ const cp = Math.cos(cam.pitch)+ eye = { x: cam.tx + cam.dist * cp * Math.sin(cam.yaw), y: cam.ty + cam.dist * Math.sin(cam.pitch), z: cam.tz + cam.dist * cp * Math.cos(cam.yaw) }+ view = lookAt(eye, { x: cam.tx, y: cam.ty, z: cam.tz })+ proj = perspective(FOV, W / H, 0.005, 60)+ pxScale = H / (2 * Math.tan(FOV / 2))+ }+ function project(x, y, z) {+ const v = view+ const vx = v[0] * x + v[4] * y + v[8] * z + v[12], vy = v[1] * x + v[5] * y + v[9] * z + v[13], vz = v[2] * x + v[6] * y + v[10] * z + v[14]+ if (vz > -0.02) return null+ return { x: (proj[0] * vx / -vz + 1) * 0.5 * W / dpr, y: (1 - proj[5] * vy / -vz) * 0.5 * H / dpr, depth: -vz }+ }+ function nearestYaw(target) { let y = target; while (y - cam.yaw > Math.PI) y -= 2 * Math.PI; while (y - cam.yaw < -Math.PI) y += 2 * Math.PI; return y }+ /** Look at a point from outside the brain, along the line from the centre through it. */+ function lookFromOutside(p, dist, instant) {+ let dx = p.x - CENTER.x, dy = p.y - CENTER.y, dz = p.z - CENTER.z+ const l = Math.hypot(dx, dy, dz)+ if (l < 0.12) { dx = Math.sin(cam.yaw); dz = Math.cos(cam.yaw); dy = 0.3 } else { dx /= l; dy /= l; dz /= l }+ want.yaw = nearestYaw(Math.atan2(dx, dz))+ want.pitch = clamp(Math.asin(clamp(dy, -1, 1)) * 0.85 + 0.12, -0.75, 1.1)+ want.dist = dist+ want.tx = p.x; want.ty = p.y; want.tz = p.z+ if (instant || reduceMotion) Object.assign(cam, want)+ }+ const saveCam = () => ({ ...want })++ function steer(dt) {+ const k = state.keys+ const fast = k.has('Shift') ? 3 : 1+ let moved = false+ if (state.mode !== 'explore') return+ const listMode = recall.active && recall.items.length+ if (k.has('ArrowLeft')) { want.yaw -= 1.25 * fast * dt; moved = true }+ if (k.has('ArrowRight')) { want.yaw += 1.25 * fast * dt; moved = true }+ if (k.has('PageUp') || (k.has('Alt') && k.has('ArrowUp'))) { want.pitch = clamp(want.pitch + 1 * fast * dt, -1.4, 1.4); moved = true }+ if (k.has('PageDown') || (k.has('Alt') && k.has('ArrowDown'))) { want.pitch = clamp(want.pitch - 1 * fast * dt, -1.4, 1.4); moved = true }+ if (!listMode && !k.has('Alt')) {+ if (k.has('ArrowUp')) { fly(1.1 * fast * dt); moved = true }+ if (k.has('ArrowDown')) { fly(-1.1 * fast * dt); moved = true }+ }+ if (moved) { state.lastInput = performance.now(); camRate = 6 }+ else if (!reduceMotion && performance.now() - state.lastInput > 7000 && !recall.active && !time.on) { want.yaw += 0.045 * dt; camRate = 3 }+ else if (time.playing && !reduceMotion) want.yaw += 0.12 * dt+ }+ function fly(amount) {+ // forward: close in on the target, then carry the target forward through the brain+ if (amount > 0 && want.dist > 0.32) want.dist = Math.max(0.32, want.dist * Math.exp(-amount * 0.9))+ else if (amount > 0) {+ const cp = Math.cos(want.pitch)+ const fx = -cp * Math.sin(want.yaw), fy = -Math.sin(want.pitch), fz = -cp * Math.cos(want.yaw)+ want.tx = clamp(want.tx + fx * amount * 0.6, -1.6, 1.6); want.ty = clamp(want.ty + fy * amount * 0.6, -1.6, 1.6); want.tz = clamp(want.tz + fz * amount * 0.6, -1.8, 1.8)+ } else {+ want.dist = Math.min(9, want.dist * Math.exp(-amount * 0.9))+ // drifting back out, the target eases home so the brain stays in view+ const pull = clamp(-amount * 0.4, 0, 0.2) * smooth(1.2, 3, want.dist)+ want.tx = lerp(want.tx, HOME.tx, pull); want.ty = lerp(want.ty, HOME.ty, pull); want.tz = lerp(want.tz, HOME.tz, pull)+ }+ }++ // ── recall: spreading activation ──++ function snippetSegments(text, terms, width) {+ const t = flat(text)+ const lower = t.toLowerCase()+ let first = -1+ for (const term of terms) { const i = lower.indexOf(term); if (i >= 0 && (first < 0 || i < first)) first = i }+ let start = 0+ if (first > width * 0.45) start = first - Math.floor(width * 0.3)+ let s = t.slice(start, start + width)+ const pre = start > 0 ? '…' : '', post = start + width < t.length ? '…' : ''+ s = pre + s + post+ return markTerms(s, terms)+ }+ function markTerms(s, terms) {+ const lower = s.toLowerCase()+ const marks = new Uint8Array(s.length)+ for (const term of terms) { let i = 0; while ((i = lower.indexOf(term, i)) >= 0) { marks.fill(1, i, i + term.length); i += term.length } }+ const segs = []+ let cur = '', hit = marks[0] === 1+ for (let i = 0; i < s.length; i++) {+ const h = marks[i] === 1+ if (h !== hit) { if (cur) segs.push({ t: cur, hit }); cur = ''; hit = h }+ cur += s[i]+ }+ if (cur) segs.push({ t: cur, hit })+ return segs+ }+ function snippetFromHit(snippet) {+ const segs = []+ const parts = String(snippet || '').split(/(\u0002[^\u0003]*\u0003)/)+ for (const part of parts) {+ if (!part) continue+ if (part[0] === '\u0002') segs.push({ t: part.slice(1, -1), hit: true })+ else segs.push({ t: part.replace(/[\u0002\u0003]/g, ''), hit: false })+ }+ for (const s of segs) s.t = s.t.replace(/\s+/g, ' ')+ return segs+ }++ function setQuery(q) {+ const was = recall.q+ recall.q = q+ $('q').textContent = q+ $('prompt').classList.toggle('on', q.length > 0)+ if (!q.trim()) { clearRecall(); return }+ if (!was.trim()) { recall.before = saveCam(); recall.hits = new Map() }+ if (time.on) stopTime()+ runRecall()+ const seq = ++recall.seq+ clearTimeout(recall.timer)+ recall.timer = setTimeout(() => {+ MemoryData.search(q).then((hits) => { if (seq === recall.seq) { recall.hits = new Map((hits || []).map((h, i) => [i, h])); runRecall(true) } }).catch(() => {})+ }, 140)+ }++ function clearRecall(keepCamera) {+ const had = recall.active+ recall.active = false; recall.items = []; recall.terms = []; recall.focus = 0; recall.region = -1+ if (recall.q) { recall.q = ''; $('q').textContent = '' }+ $('prompt').classList.remove('on')+ clearTimeout(recall.timer); recall.seq+++ if (had && recall.before && !keepCamera) { Object.assign(want, recall.before); camRate = 2.4 }+ recall.before = null+ $('count').textContent = ''+ }++ function runRecall(fromSearch) {+ const now = performance.now()+ const terms = [...new Set(words(recall.q))]+ recall.terms = terms+ const N = M.nodes+ const direct = new Map() // node index → score (0..1)+ const items = []+ if (terms.length) {+ // memories+ let maxE = 0+ const es = []+ for (const e of M.engrams) {+ let s = 0, all = true+ for (const t of terms) {+ const inT = e.hay.title.includes(t), inD = e.hay.desc.includes(t), inB = e.hay.body.includes(t)+ if (!inT && !inD && !inB) { all = false; break }+ s += inT ? 3 : inD ? 2 : 1+ if (inB) s += Math.min(5, e.hay.body.split(t).length - 1) * 0.15+ }+ if (all) { es.push([e, s]); maxE = Math.max(maxE, s) }+ }+ for (const [e, s] of es) { const a = 0.6 + 0.4 * s / maxE; direct.set(e.index, a); items.push({ i: e.index, rank: 2.4 + a }) }+ // About You+ for (const h of M.hubs) if (terms.every((t) => h.lower.includes(t))) { direct.set(h.index, 1); items.push({ i: h.index, rank: 3.5 }) }+ // messages (local)+ const ns = []+ for (const n of M.neurons) {+ let s = 0, all = true+ for (const t of terms) { const i = n.lower.indexOf(t); if (i < 0) { all = false; break } s += 1 + (n.lower.indexOf(t, i + t.length) >= 0 ? 0.3 : 0) }+ if (all) ns.push([n, s + 0.3 * (n.birth - M.tMin) / (M.tMax - M.tMin)])+ }+ ns.sort((a, b) => b[1] - a[1])+ const maxN = ns.length ? ns[0][1] : 1+ for (const [n, s] of ns.slice(0, 900)) { const a = 0.5 + 0.4 * s / maxN; direct.set(n.index, a) }+ // search hits: the session index's own ranking; those older than what is loaded come back as ghosts with words+ const seenHit = new Set()+ let rank = 0+ for (const n of recall.hitNodes || []) n.hitSnippet = null+ recall.hitNodes = []+ for (const h of recall.hits.values()) {+ if (!fromSearch) { const plain = String(h.snippet || '').toLowerCase(); if (!terms.every((t) => plain.includes(t))) continue }+ const key = `${h.sessionId}:${h.turn}`+ let n = M.neuronByTurn.get(key)+ if (!n && M.ghostsByDay.size) {+ const list = M.ghostsByDay.get(`${dayKey(h.at)} ${h.engine}`)+ if (list && list.length) { n = list[hash(key) % list.length]; n.hit = h; n.hitKey = key }+ }+ if (!n || seenHit.has(n.index)) continue+ seenHit.add(n.index)+ n.hitSnippet = h.snippet+ recall.hitNodes.push(n)+ direct.set(n.index, Math.max(direct.get(n.index) || 0, 0.95 - rank * 0.01))+ items.push({ i: n.index, rank: 1.9 - rank * 0.02, hit: h })+ rank+++ }+ for (const [n, s] of ns.slice(0, 60)) if (!seenHit.has(n.index)) items.push({ i: n.index, rank: 1 + 0.4 * s / maxN })+ // a region named by the query+ recall.region = -1+ const q = recall.q.trim().toLowerCase()+ if (q.length >= 3) for (const r of M.regions) if (r.label.toLowerCase().includes(q) || r.name.toLowerCase().includes(q)) { recall.region = r.id; break }+ if (recall.region >= 0) {+ for (const n of M.regions[recall.region].nodes) if (!direct.has(n.index)) direct.set(n.index, 0.32)+ // a place named: step through the memories that live there+ for (const n of M.regions[recall.region].nodes) if (n.k === ENGRAM) items.push({ i: n.index, rank: 2 + (n.birth - M.tMin) / (M.tMax - M.tMin) })+ }+ }++ // spread: light passes along connections, losing strength each hop+ const act = new Map()+ for (const [i, a] of direct) act.set(i, { a, d: 0, from: -1 })+ let frontier = [...direct.keys()].sort((x, y) => direct.get(y) - direct.get(x)).slice(0, 700)+ for (let hop = 1; hop <= 3 && frontier.length; hop++) {+ const next = []+ for (const i of frontier) {+ const src = act.get(i)+ for (const [j, w] of N[i].edges) {+ const a = src.a * w * 0.78+ if (a < 0.1) continue+ const d = src.d + 160 + 900 * Math.sqrt(dist2(N[i], N[j]))+ const cur = act.get(j)+ if (!cur || (cur.from >= 0 && cur.a < a)) { act.set(j, { a, d: Math.min(d, 1300), from: i }); if (!cur) next.push(j) }+ }+ }+ frontier = next.slice(0, 1500)+ }+ // apply, keeping what was already lit so typing another letter does not re-flash it+ const nextLevel = new Float32Array(N.length)+ let spreadPulses = 0+ for (const [i, v] of act) {+ nextLevel[i] = v.a+ if (recallLevel[i] <= 0 || recallStart[i] > 1e14) {+ recallStart[i] = now + v.d+ if (v.from >= 0 && spreadPulses < 260 && !reduceMotion) {+ const p = act.get(v.from)+ addPulse(N[v.from], N[i], null, now, Math.max(140, v.d - p.d), mix(N[i].rgb, WHITE, 0.3), -1, 1.1, p.d)+ spreadPulses+++ }+ }+ }+ for (let i = 0; i < N.length; i++) if (nextLevel[i] <= 0) recallStart[i] = 1e15+ recallLevel.set(nextLevel)++ items.sort((a, b) => b.rank - a.rank)+ const seen = new Set()+ recall.items = items.filter((it) => (seen.has(it.i) ? false : seen.add(it.i))).slice(0, 80)+ recall.active = true+ if (!fromSearch) recall.focus = 0+ recall.focus = clamp(recall.focus, 0, Math.max(0, recall.items.length - 1))+ recall.camAt = now + (fromSearch ? 60 : 260)+ recall.camDone = false+ recall.direct = direct+ const mem = recall.items.filter((it) => N[it.i].k === ENGRAM).length+ const hubs = recall.items.filter((it) => N[it.i].k === HUB).length+ const msgs = [...direct].filter(([i, a]) => (N[i].k === NEURON || N[i].k === GHOST) && a >= 0.5).length+ const bits = []+ if (msgs) bits.push(plural(msgs, 'message'))+ if (mem) bits.push(plural(mem, 'memory', 'memories'))+ if (hubs) bits.push(hubs + ' About You')+ if (recall.region >= 0) bits.push('the ' + M.regions[recall.region].label + ' region')+ $('count').textContent = terms.length ? (bits.length ? bits.join(' · ') : 'nothing comes back') : ''+ }++ function recallCamera(now) {+ if (!recall.active || recall.camDone || now < recall.camAt) return+ recall.camDone = true+ const N = M.nodes+ const cands = [...(recall.direct || new Map())].sort((a, b) => b[1] - a[1]).slice(0, 320)+ if (!cands.length) return+ if (recall.region >= 0 && cands.every(([i]) => N[i].region === recall.region)) { const r = M.regions[recall.region]; lookFromOutside(r.centroid, 1.9); camRate = 2.2; return }+ // the densest knot of recalled memories+ let best = cands[0][0], bestD = -1+ const s2 = 2 * 0.2 * 0.2+ for (const [i, a] of cands) {+ let d = 0+ for (const [j, b] of cands) d += b * Math.exp(-dist2(N[i], N[j]) / s2) * (N[j].k === ENGRAM || N[j].k === HUB ? 2.5 : 1)+ d *= N[i].k === ENGRAM || N[i].k === HUB ? 1.3 : 1+ if (d > bestD) { bestD = d; best = i }+ }+ const focusNode = recall.items.length ? N[recall.items[0].i] : N[best]+ const p = N[best]+ const target = Math.sqrt(dist2(p, focusNode)) < 0.5 ? { x: (p.x * 2 + focusNode.x) / 3, y: (p.y * 2 + focusNode.y) / 3, z: (p.z * 2 + focusNode.z) / 3 } : p+ lookFromOutside(target, 1.5)+ camRate = 2.2+ }++ function focusItem(delta) {+ if (!recall.items.length) return+ recall.focus = (recall.focus + delta + recall.items.length) % recall.items.length+ const n = M.nodes[recall.items[recall.focus].i]+ lookFromOutside(n, n.k === HUB ? 1.4 : 1.15)+ camRate = 2.6+ recall.camDone = true+ state.lastInput = performance.now()+ }++ // ── dive ──++ function diveable(i) { const n = M.nodes[i]; return n && (n.k !== GHOST || !!n.hit) }++ function enterDive(i, fromRow) {+ if (i < 0 || !diveable(i)) return+ const n = M.nodes[i]+ if (state.mode !== 'dive') { dive.before = saveCam(); dive.stack = [] }+ if (fromRow && dive.node >= 0) dive.stack.push(dive.node)+ dive.node = i+ state.mode = 'dive'+ // fall into it: the camera closes until its light fills the view+ want.tx = n.x; want.ty = n.y; want.tz = n.z+ want.dist = 0.05+ camRate = reduceMotion ? 50 : 2.4+ if (reduceMotion) Object.assign(cam, want)+ dive.rgb = n.rgb+ dive.showAt = performance.now() + (reduceMotion ? 0 : fromRow ? 380 : 650)+ $('dive').classList.remove('on')+ buildDive(n)+ renderKeys()+ }+ function leaveDive() {+ if (dive.stack.length) { const prev = dive.stack.pop(); dive.node = -1; enterDive(prev, false); return }+ state.mode = 'explore'+ dive.node = -1+ $('dive').classList.remove('on')+ if (dive.before) Object.assign(want, dive.before)+ camRate = reduceMotion ? 50 : 2.2+ if (reduceMotion) Object.assign(cam, want)+ renderKeys()+ }++ function bodyInto(container, text) {+ const lines = String(text || '').split('\n')+ lines.forEach((line, i) => {+ const m = /^(#{1,6})\s+(.*)$/.exec(line)+ if (m) container.appendChild(el('span', 'h', m[2]))+ else {+ const b = /^(\s*[-*]?\s*)\*\*([^*]+)\*\*(.*)$/.exec(line)+ if (b) { container.appendChild(document.createTextNode(b[1])); container.appendChild(el('span', 'em', b[2])); container.appendChild(document.createTextNode(b[3])) }+ else container.appendChild(document.createTextNode(line))+ }+ if (i < lines.length - 1) container.appendChild(document.createTextNode('\n'))+ })+ }++ function buildDive(n) {+ const col = document.querySelector('#dive .col')+ col.replaceChildren()+ const kicker = el('div', 'kicker')+ const dot = el('span', 'dot'); dot.style.color = css(n.k === HUB ? GOLD : n.agent ? n.agent.rgb : n.rgb)+ kicker.appendChild(dot)+ const rows = []+ const group = (title, list) => {+ if (!list.length) return+ const g = el('div', 'group'); g.appendChild(el('h2', null, title))+ for (const r of list) {+ const row = el('div', 'row' + (r.self ? ' self' : ''))+ const d = el('span', 'dot'); d.style.background = css(r.rgb); row.appendChild(d)+ row.appendChild(el('span', 'txt', r.label))+ if (r.when) row.appendChild(el('span', 'when', r.when))+ if (!r.self && r.node >= 0) { r.el = row; rows.push(r); row.addEventListener('click', () => { dive.sel = rows.indexOf(r); enterDive(r.node, true) }) }+ g.appendChild(row)+ }+ col.appendChild(g)+ }+ const now = M.now+ const regionName = (id) => (id >= 0 && M.regions[id] ? M.regions[id].label : null)+ const msgRow = (m, self) => ({ label: flat(m.ask ? m.ask.text : m.hit ? snippetFromHit(m.hit.snippet).map((s) => s.t).join('') : ''), when: `${dayShort(m.birth)} ${hm(m.birth)}`, rgb: m.rgb, node: m.index, self })+ const memRow = (e) => ({ label: flat(e.memory.title), when: `${e.agent.name} · ${regionName(e.region) || 'every project'}`, rgb: e.rgb, node: e.index })+ const hubRow = (h) => ({ label: flat(h.line.text), when: h.line.section || '', rgb: GOLD, node: h.index })++ if (n.k === ENGRAM) {+ const m = n.memory+ for (const t of ['memory', n.agent.name, regionName(n.region) || 'every project', ago(m.modified || now, now), m.type]) if (t) kicker.appendChild(el('span', null, t))+ col.appendChild(kicker)+ col.appendChild(el('h1', null, flat(m.title) || 'Untitled memory'))+ if (m.description && flat(m.description) !== flat(m.title) && flat(m.description).length > 12) col.appendChild(el('p', 'desc', flat(m.description)))+ const body = el('div', 'body'); bodyInto(body, m.body); col.appendChild(body)+ col.appendChild(el('div', 'meta', [m.path, m.size ? plural(m.size, 'byte') : ''].filter(Boolean).join(' · ')))+ group('Holds up About You', (n.heldBy || []).map(hubRow))+ group('Said near it', (n.related || []).slice(0, 6).map((x) => msgRow(x)))+ const near = M.engrams.filter((e) => e !== n && e.region === n.region).sort((a, b) => dist2(a, n) - dist2(b, n)).slice(0, 4)+ group('Nearby memories', near.map(memRow))+ } else if (n.k === HUB) {+ const l = n.line+ for (const t of ['About You', l.section]) if (t) kicker.appendChild(el('span', null, t))+ col.appendChild(kicker)+ col.appendChild(el('h1', null, flat(l.text)))+ const bits = []+ if (n.askCount) bits.push(`drawn from ${plural(n.askCount, 'of your messages', 'of your messages').replace(/^(\S+) of/, '$1 of')}`)+ if (n.cites.length) bits.push(`held up by ${plural(n.cites.length, 'memory', 'memories')}`)+ if (bits.length) col.appendChild(el('p', 'desc', bits.join(' · ').replace(/^./, (c) => c.toUpperCase())))+ group('Held up by', n.cites.map(memRow))+ group('Same section', M.hubs.filter((h) => h !== n && h.line.section === l.section).map(hubRow))+ const about = M.snapshot.about || {}+ if (about.intro) col.appendChild(el('div', 'meta', flat(about.intro)))+ } else {+ const text = n.ask ? n.ask.text : n.hit ? snippetFromHit(n.hit.snippet).map((s) => s.t).join('') : ''+ const when = `${dayLong(n.birth)} · ${hm(n.birth)}`+ for (const t of ['message', n.agent.name, when, n.ask ? `turn ${n.ask.turn + 1}` : 'older than this view']) kicker.appendChild(el('span', null, t))+ col.appendChild(kicker)+ const h = el('h1', flat(text).length > 90 ? 'long' : null, flat(text) || '(no words)')+ col.appendChild(h)+ const s = n.session+ const bits = []+ bits.push(s && s.title ? flat(s.title) : 'Untitled conversation')+ const rn = regionName(n.region)+ if (rn && n.k === NEURON) bits.push((s && s.inferred ? 'placed by its words in ' : 'in ') + rn)+ if (s) bits.push(`${plural(s.nodes.length, 'message')}, ${dayShort(s.start)}${dayKey(s.start) !== dayKey(s.end) ? ' – ' + dayShort(s.end) : ''}`)+ col.appendChild(el('p', 'desc', bits.join(' · ')))+ if (n.ask && n.ask.length > String(n.ask.text).length) col.appendChild(el('div', 'meta', `The first ${num(String(n.ask.text).length)} of ${num(n.ask.length)} characters.`))+ if (n.k === GHOST) col.appendChild(el('div', 'meta', 'Older than the messages loaded here: what the search found of it.'))+ if (s) {+ const at = s.nodes.indexOf(n)+ const around = s.nodes.slice(Math.max(0, at - 3), at + 4)+ group('The conversation', around.map((m) => msgRow(m, m === n)))+ }+ group('Memories it touches', (n.memories || []).map(memRow))+ }+ dive.rows = rows+ dive.sel = rows.length ? 0 : -1+ markSel()+ document.querySelector('#dive .scroll').scrollTop = 0+ $('veil').style.background = `radial-gradient(ellipse at 50% 45%, ${css(mix(n.rgb, BG, 0.35), 0.5)} 0%, ${css(mix(n.rgb, BG, 0.82), 0.92)} 45%, rgba(2,3,5,.97) 100%)`+ }+ function markSel() {+ dive.rows.forEach((r, i) => r.el.classList.toggle('sel', i === dive.sel))+ const r = dive.rows[dive.sel]+ if (r) r.el.scrollIntoView({ block: 'nearest' })+ }++ // ── the ink layer: labels and floating type ──++ let charW = {}+ function font(px, weight = 400) { inkCtx.font = `${weight} ${px}px ui-monospace, "SF Mono", Menlo, Consolas, monospace`; if (!charW[px]) charW[px] = inkCtx.measureText('MMMMMMMMMM').width / 10; return charW[px] }++ function drawInk(now) {+ const c = inkCtx+ c.setTransform(1, 0, 0, 1, 0, 0)+ c.clearRect(0, 0, W, H)+ c.setTransform(dpr, 0, 0, dpr, 0, 0)+ if (!M || state.mode === 'loading') return+ const w = W / dpr, h = H / dpr+ const arriving = state.mode === 'arrival'+ const inDive = state.mode === 'dive'+ const k = arriving ? smooth(3.2, 4.6, (now - state.arrivalStart) / 1000) : inDive ? 0 : 1+ if (k <= 0.01) return++ // region labels: names on the lobes, quiet, like an anatomy plate+ const ex = eye.x - CENTER.x, ey = eye.y - CENTER.y, ez = eye.z - CENTER.z, el2 = Math.hypot(ex, ey, ez) || 1+ font(10)+ c.textBaseline = 'middle'+ c.textAlign = 'center'+ if ('letterSpacing' in c) c.letterSpacing = '2px'+ const placed = []+ for (const r of M.regions) {+ if (!r.slots.length) continue+ const p0 = r.centroid+ let dx = p0.x - CENTER.x, dy = p0.y - CENTER.y, dz = p0.z - CENTER.z+ const dl = Math.hypot(dx, dy, dz) || 1+ const facing = (dx * ex + dy * ey + dz * ez) / (dl * el2)+ const p = project(p0.x + dx / dl * 0.12, p0.y + dy / dl * 0.12, p0.z + dz / dl * 0.12)+ if (!p || p.depth < 0.4) continue+ let a = smooth(-0.25, 0.45, facing) * 0.62 * k * smooth(0.4, 1.4, p.depth)+ if (recall.active) a *= recall.region === r.id ? 1.6 : 0.35+ if (time.on) a *= 0.6+ if (a < 0.03) continue+ const name = short(r.label, 26).toUpperCase()+ const tw = name.length * (charW[10] + 2)+ if (placed.some((q) => Math.abs(q.x - p.x) < (q.w + tw) / 2 + 8 && Math.abs(q.y - p.y) < 22)) continue+ placed.push({ x: p.x, y: p.y, w: tw })+ c.fillStyle = css(mix(r.color, WHITE, 0.25), a)+ c.fillText(name, p.x, p.y)+ if (p.depth < 2.3 || recall.region === r.id) {+ font(9)+ c.fillStyle = css([0.6, 0.64, 0.7], a * 0.7 * smooth(2.3, 1.7, p.depth))+ const sub = [r.neuronCount ? plural(r.neuronCount, 'message') : '', r.memoryCount ? plural(r.memoryCount, 'memory', 'memories') : ''].filter(Boolean).join(' · ')+ c.fillText(sub, p.x, p.y + 13)+ font(10)+ }+ }+ if ('letterSpacing' in c) c.letterSpacing = '0px'+ c.textAlign = 'left'++ const boxes = []+ if (recall.active && recall.items.length) {+ const N = M.nodes+ const show = []+ const f = recall.items[recall.focus]+ if (f) show.push({ it: f, focus: true })+ for (const it of recall.items) {+ if (show.length >= 7) break+ if (it === f) continue+ show.push({ it, focus: false })+ }+ for (const s of show) {+ const n = N[s.it.i]+ if (now < recallStart[n.index]) continue+ const p = project(n.x, n.y, n.z)+ if (!p || p.x < -40 || p.x > w + 40 || p.y < -20 || p.y > h + 20) continue+ drawLabel(n, p, s.focus, boxes, now - recallStart[n.index], w, h)+ }+ } else if (state.mode === 'explore' && state.aim >= 0 && !time.playing) {+ const n = M.nodes[state.aim]+ const p = project(n.x, n.y, n.z)+ if (p) drawLabel(n, p, true, boxes, now - state.aimSince, w, h, true)+ } else if (state.mode === 'explore' && !recall.active && cam.dist <= 2.2 && now - state.mouse.at > 2500) {+ // close enough to aim: a quiet crosshair shows where Enter would dive+ c.strokeStyle = 'rgba(200,206,216,0.22)'+ c.beginPath(); c.moveTo(w / 2 - 7, h / 2); c.lineTo(w / 2 - 3, h / 2); c.moveTo(w / 2 + 3, h / 2); c.lineTo(w / 2 + 7, h / 2)+ c.moveTo(w / 2, h / 2 - 7); c.lineTo(w / 2, h / 2 - 3); c.moveTo(w / 2, h / 2 + 3); c.lineTo(w / 2, h / 2 + 7); c.stroke()+ }+ }++ function labelLines(n, terms) {+ const N = 64+ if (n.k === ENGRAM) {+ const m = n.memory+ const sub = [n.agent.name, n.region >= 0 ? short(M.regions[n.region].label, 22) : 'every project', ago(m.modified || M.now, M.now)].join(' · ')+ const lines = [{ segs: markTerms(short(m.title, 52), terms), size: 13, color: [0.96, 0.97, 0.99], weight: 500 }, { segs: [{ t: sub }], size: 10, color: [0.55, 0.59, 0.66] }]+ const hay = terms.length ? [m.description, ...String(m.body || '').split('\n')].find((l) => terms.some((t) => String(l || '').toLowerCase().includes(t))) : m.description+ if (hay && flat(hay) !== flat(m.title)) lines.push({ segs: terms.length ? snippetSegments(hay, terms, N) : [{ t: short(hay, N) }], size: 11, color: [0.72, 0.75, 0.8] })+ return lines+ }+ if (n.k === HUB) {+ return [{ segs: [{ t: 'ABOUT YOU · ' + String(n.line.section || '').toUpperCase() }], size: 9.5, color: GOLD }, { segs: markTerms(short(n.line.text, 60), terms), size: 12.5, color: [0.98, 0.95, 0.88], weight: 500 }]+ }+ const text = n.ask ? n.ask.text : ''+ const segs = n.hitSnippet && terms.length ? snippetFromHit(n.hitSnippet) : text ? (terms.length ? snippetSegments(text, terms, N) : [{ t: short(text, N) }]) : null+ if (segs) {+ let total = 0+ const trimmed = []+ for (const s of segs) { if (total >= N) break; const t = s.t.slice(0, N - total); trimmed.push({ t, hit: s.hit }); total += t.length }+ if (total >= N && trimmed.length) trimmed[trimmed.length - 1].t += '…'+ const title = n.session && n.session.title ? ' · ' + short(n.session.title, 26) : n.region >= 0 && M.regions[n.region] && n.k === NEURON ? ' · ' + short(M.regions[n.region].label, 22) : ''+ return [{ segs: trimmed, size: 12, color: [0.84, 0.86, 0.9], quote: true }, { segs: [{ t: `${n.agent.name} · ${dayShort(n.birth)} ${hm(n.birth)}${title}` }], size: 10, color: [0.5, 0.54, 0.6] }]+ }+ return [{ segs: [{ t: `a message to ${n.agent.name}` }], size: 11.5, color: [0.7, 0.73, 0.78] }, { segs: [{ t: `${dayLong(n.birth)} · its words are older than this view` }], size: 10, color: [0.48, 0.52, 0.58] }]+ }++ function drawLabel(n, p, focus, boxes, age, w, h, aimOnly) {+ const c = inkCtx+ const lines = labelLines(n, recall.terms)+ const reveal = reduceMotion ? 1e9 : Math.max(0, age) / 9 // characters typed out per ms+ let width = 0, height = 0+ for (const l of lines) { const cw = font(l.size, l.weight); const len = l.segs.reduce((s, x) => s + x.t.length, 0) + (l.quote ? 2 : 0); width = Math.max(width, len * cw); height += l.size * 1.45 }+ const pad = 8+ let x = p.x + 22, y = p.y - height / 2+ if (x + width + pad > w - 8) x = p.x - 22 - width+ x = clamp(x, 8, Math.max(8, w - width - 8))+ let ok = false+ for (const dy of [0, height + 10, -(height + 10), 2 * (height + 10), -2 * (height + 10), 3 * (height + 10)]) {+ const yy = clamp(y + dy, 40, h - height - 70)+ const box = { x: x - pad, y: yy - pad / 2, w: width + pad * 2, h: height + pad }+ if (!boxes.some((b) => box.x < b.x + b.w && b.x < box.x + box.w && box.y < b.y + b.h && b.y < box.y + box.h)) { y = yy; boxes.push(box); ok = true; break }+ }+ if (!ok && !focus) return+ if (!ok) { y = clamp(y, 40, h - height - 70); boxes.push({ x: x - pad, y, w: width + pad * 2, h: height }) }+ const alpha = focus ? 1 : 0.74+ const rgb = n.k === HUB ? GOLD : n.rgb+ // the leader and a ring on the neuron+ c.strokeStyle = css(rgb, focus ? 0.75 : 0.35)+ c.lineWidth = 1+ c.beginPath(); c.arc(p.x, p.y, focus ? 9 : 6, 0, Math.PI * 2); c.stroke()+ const lx = x > p.x ? x - 6 : x + width + 6+ c.beginPath(); c.moveTo(p.x + (lx > p.x ? 9 : -9), p.y); c.lineTo(lx, y + lines[0].size * 0.72); c.stroke()+ c.fillStyle = focus ? 'rgba(3,5,8,0.78)' : 'rgba(3,5,8,0.55)'+ c.fillRect(x - pad, y - pad / 2, width + pad * 2, height + pad)+ if (focus) { c.fillStyle = css(rgb, 0.9); c.fillRect(x - pad, y - pad / 2, 2, height + pad) }+ let yy = y+ let budget = reveal+ for (const l of lines) {+ const cw = font(l.size, l.weight)+ c.textBaseline = 'top'+ let xx = x+ const segs = l.quote ? [{ t: '“' }, ...l.segs, { t: '”' }] : l.segs+ for (const s of segs) {+ if (budget <= 0) break+ const t = s.t.slice(0, Math.max(0, Math.floor(budget)))+ budget -= s.t.length+ c.fillStyle = s.hit ? css([1, 0.93, 0.74], alpha) : css(l.color, alpha * (s.hit === false && l.quote ? 0.92 : 1))+ if (s.hit) { c.fillStyle = css(mix(rgb, WHITE, 0.55), alpha) }+ c.fillText(t, xx, yy)+ if (s.hit && t) { c.fillRect(xx, yy + l.size * 1.18, t.length * cw, 1) }+ xx += t.length * cw+ }+ yy += l.size * 1.45+ }+ if (focus && !aimOnly && recall.items.length > 1) {+ font(9.5)+ c.fillStyle = css([0.5, 0.54, 0.6], 0.9)+ c.fillText(`${recall.focus + 1}/${recall.items.length}`, x + width - 30, y - pad / 2 - 13)+ }+ }++ // ── aiming: what is under the reticle (or the mouse) ──++ function aim(now) {+ if (state.mode !== 'explore' || recall.active) { state.aim = -1; return }+ const mouse = now - state.mouse.at < 2500+ if (!mouse && cam.dist > 2.2) { state.aim = -1; return }+ const ax = mouse ? state.mouse.x : W / dpr / 2, ay = mouse ? state.mouse.y : H / dpr / 2+ const N = M.nodes+ let best = -1, bestS = 30+ for (let i = 0; i < N.length; i++) {+ const n = N[i]+ if (time.on && n.birth > time.T) continue+ const p = project(n.x, n.y, n.z)+ if (!p || p.depth > 7) continue+ const d = Math.hypot(p.x - ax, p.y - ay)+ if (d > 30) continue+ const s = d + p.depth * 2.5 - (n.k === ENGRAM ? 12 : n.k === HUB ? 14 : 0) + (n.k === GHOST ? 6 : 0) - (i === state.aim ? 6 : 0)+ if (s < bestS) { bestS = s; best = i }+ }+ if (best !== state.aim) { state.aim = best; state.aimSince = now }+ }++ // ── the timeline strip ──++ let stripDays = null+ function buildStrip() {+ const days = new Map()+ for (const n of M.nodes) {+ if (n.k !== NEURON && n.k !== GHOST) continue+ const k = dayKey(n.birth)+ let d = days.get(k)+ if (!d) days.set(k, (d = { at: new Date(k + 'T00:00:00').getTime(), engines: new Map(), total: 0 }))+ const e = d.engines.get(n.agent.id) || { count: 0, rgb: n.agent.rgb }+ e.count++; d.engines.set(n.agent.id, e); d.total+++ }+ stripDays = [...days.values()].sort((a, b) => a.at - b.at)+ stripDays.max = Math.max(1, ...stripDays.map((d) => d.total))+ }+ function drawStrip() {+ const c = stripCtx, w = strip.width, h = strip.height+ c.clearRect(0, 0, w, h)+ if (!time.on || !stripDays) return+ // the strip runs on the replay's own clock: busy weeks get room, quiet months pass in a sliver+ const x = (t) => tToU(t) * w+ const base = h - 14 * dpr+ for (const d of stripDays) {+ const x0 = x(d.at), bw = Math.max(1, x(d.at + DAY) - x0 - (x(d.at + DAY) - x0 > 4 ? 1 : 0))+ const past = d.at <= time.T+ let y = base+ const hh = Math.sqrt(d.total / stripDays.max) * (base - 4 * dpr)+ for (const { count, rgb } of d.engines.values()) {+ const seg = hh * count / d.total+ c.fillStyle = css(rgb, past ? 0.85 : 0.16)+ c.fillRect(x0, y - seg, bw, seg)+ y -= seg+ }+ }+ for (const e of M.engrams) {+ c.fillStyle = css(WHITE, e.birth <= time.T ? 0.8 : 0.15)+ c.fillRect(x(e.birth) - dpr, base + 3 * dpr, 2 * dpr, 2 * dpr)+ }+ c.fillStyle = css(GOLD, M.aboutBirth <= time.T ? 1 : 0.25)+ c.fillRect(x(M.aboutBirth) - dpr, base + 2 * dpr, 2 * dpr, 4 * dpr)+ // months+ c.font = `${9 * dpr}px ui-monospace, "SF Mono", Menlo, monospace`+ c.textBaseline = 'bottom'+ const d0 = new Date(M.tMin); d0.setDate(1); d0.setHours(0, 0, 0, 0)+ let lastLabel = -1e9+ for (let m = new Date(d0); m.getTime() < M.tMax; m.setMonth(m.getMonth() + 1)) {+ const xx = x(m.getTime()); if (xx < 0) continue+ c.fillStyle = 'rgba(120,128,140,.5)'; c.fillRect(xx, base + 1 * dpr, 1, 9 * dpr)+ if (xx - lastLabel > 34 * dpr) { c.fillText(MONTHS[m.getMonth()].toUpperCase(), xx + 4 * dpr, h); lastLabel = xx }+ }+ // weeks, where there is room for them+ const w0 = new Date(M.tMin); w0.setHours(0, 0, 0, 0); w0.setDate(w0.getDate() - ((w0.getDay() + 6) % 7))+ for (let k = new Date(w0); k.getTime() < M.tMax; k.setDate(k.getDate() + 7)) {+ const xx = x(k.getTime()), next = x(k.getTime() + 7 * DAY)+ if (next - xx < 30 * dpr || xx < 0) continue+ c.fillStyle = 'rgba(120,128,140,.22)'; c.fillRect(xx, base + 1 * dpr, 1, 4 * dpr)+ }+ const cx = x(time.T)+ c.fillStyle = css(GOLD, 0.95); c.fillRect(cx - 0.5 * dpr, 0, 1 * dpr, base + 6 * dpr)+ c.beginPath(); c.arc(cx, 2 * dpr, 2.5 * dpr, 0, Math.PI * 2); c.fill()+ }++ // ── HUD ──++ function renderKeys() {+ const k = $('keys')+ k.replaceChildren()+ let list+ if (state.mode === 'dive') list = [['↑↓', 'choose'], ['enter', 'dive deeper'], ['esc', 'back'], ['type', 'recall']]+ else if (time.on) list = [['[ ]', 'scrub'], ['{ }', 'faster'], ['\\', time.playing ? 'pause' : 'play'], ['←→', 'orbit'], ['esc', 'today']]+ else if (recall.active) list = [['tab ↑↓', 'next memory'], ['enter', 'dive'], ['←→', 'orbit'], ['esc', 'let go']]+ else list = [['type', 'to recall'], ['←→', 'orbit'], ['↑↓', 'fly'], ['⇧', 'faster'], ['enter', 'dive'], ['esc', 'back'], ['[ ]', 'time'], ['\\', 'replay']]+ list.forEach(([key, label], i) => {+ if (i) k.appendChild(document.createTextNode(' · '))+ k.appendChild(el('kbd', null, key)); k.appendChild(document.createTextNode(' ' + label))+ })+ }+ let keysSig = ''+ function hud(now) {+ const sig = `${state.mode}|${time.on}|${time.playing}|${recall.active}`+ if (sig !== keysSig) { keysSig = sig; renderKeys() }+ // the clock+ const clock = $('clock')+ if (time.on) {+ clock.style.opacity = 1+ const T = Math.min(time.T, M.tMax)+ const d = new Date(T)+ clock.firstChild.textContent = `${d.getDate()} ${MONTHS[d.getMonth()].toUpperCase()} ${d.getFullYear()}`+ const lo = upperBound(birthsSorted, T)+ let msgs = 0, mems = 0+ for (let i = 0; i < lo; i++) { const kk = M.nodes[order[i]].k; if (kk === NEURON || kk === GHOST) msgs++; else if (kk === ENGRAM) mems++ }+ const s = clock.lastChild+ s.replaceChildren()+ s.appendChild(document.createTextNode(`${plural(msgs, 'message')} · ${plural(mems, 'memory', 'memories')}`))+ if (T >= M.aboutBirth) { s.appendChild(document.createTextNode(' · ')); s.appendChild(el('i', null, 'About You')) }+ if (time.rewinding) s.appendChild(document.createTextNode(' ◂◂ rewinding'))+ else if (time.playing) s.appendChild(document.createTextNode(' ▸ growing'))+ strip.style.opacity = 1+ } else { clock.style.opacity = 0; strip.style.opacity = 0 }+ drawStrip()+ const rhythm = $('rhythm')+ const showRhythm = state.mode === 'explore' && !time.on && !recall.active && innerWidth > 980+ rhythm.style.opacity = showRhythm ? 1 : 0+ if (showRhythm) rhythm.textContent = `firing as on ${ambient.label}`+ $('prompt').style.visibility = state.mode === 'dive' ? 'hidden' : ''+ const veil = $('veil')+ if (state.mode === 'dive') {+ const close = smooth(0.6, 0.07, cam.dist)+ veil.style.opacity = String(close)+ if (now >= dive.showAt && cam.dist < 0.3 && !$('dive').classList.contains('on')) $('dive').classList.add('on')+ } else veil.style.opacity = String(Math.max(0, Number(veil.style.opacity || 0) - 0.06))+ }++ // ── arrival ──++ function arrival(now) {+ const t = (now - state.arrivalStart) / 1000+ const title = $('title')+ if (reduceMotion) {+ title.style.opacity = String(smooth(0, 0.3, t) * (1 - smooth(0.7, 1.0, t)))+ } else {+ const e = easeInOut(t / 4.4)+ cam.dist = want.dist = lerp(12, HOME.dist, e)+ cam.yaw = want.yaw = HOME.yaw + 1.5 * (1 - e)+ cam.pitch = want.pitch = lerp(1.05, HOME.pitch, e)+ title.style.opacity = String(smooth(0.3, 1.1, t) * (1 - smooth(3.1, 4.0, t)))+ const line = title.lastChild+ const full = line.dataset.full || ''+ line.textContent = full.slice(0, Math.max(0, Math.floor((t - 1.0) * 46)))+ }+ if (t >= state.arrivalDur) endArrival()+ }+ function endArrival() {+ if (state.mode !== 'arrival') return+ state.mode = 'explore'+ state.arrivalStart = performance.now() - 1e6+ if (!reduceMotion) { Object.assign(want, HOME); cam.dist = Math.min(cam.dist, 5) }+ $('title').style.opacity = 0+ document.body.classList.remove('arriving')+ state.lastInput = performance.now()+ renderKeys()+ }++ // ── input ──++ addEventListener('keydown', (e) => {+ if (!M || e.isComposing) return+ if (e.metaKey || (e.ctrlKey && !['u', 'w'].includes(e.key.toLowerCase()))) return+ const key = e.key+ if (state.mode === 'arrival') endArrival()+ state.lastInput = performance.now()+ if (['Shift', 'Alt', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown'].includes(key)) state.keys.add(key)++ if (state.mode === 'dive') {+ if (key === 'Escape' || key === 'ArrowLeft' || key === 'Backspace') { e.preventDefault(); leaveDive(); return }+ if (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Tab') {+ e.preventDefault()+ const d = key === 'ArrowUp' || (key === 'Tab' && e.shiftKey) ? -1 : 1+ if (dive.rows.length) { dive.sel = clamp(dive.sel + d, 0, dive.rows.length - 1); markSel() }+ else document.querySelector('#dive .scroll').scrollBy({ top: d * 80 })+ return+ }+ if (key === 'Enter' || key === 'ArrowRight') { e.preventDefault(); const r = dive.rows[dive.sel]; if (r) enterDive(r.node, true); return }+ if (key === 'PageDown' || key === ' ') { e.preventDefault(); document.querySelector('#dive .scroll').scrollBy({ top: innerHeight * 0.7 }); return }+ if (key === 'PageUp') { e.preventDefault(); document.querySelector('#dive .scroll').scrollBy({ top: -innerHeight * 0.7 }); return }+ if (key.length === 1 && !e.ctrlKey && !e.altKey && !'[]{}\\'.includes(key) && key !== ' ') {+ e.preventDefault()+ dive.stack = []; leaveDive()+ setQuery(key)+ }+ return+ }++ if (key === 'Escape') {+ e.preventDefault()+ if (recall.q) setQuery('')+ else if (time.on) stopTime()+ else { Object.assign(want, HOME); camRate = 2.2 }+ return+ }+ if (key === 'Enter') {+ e.preventDefault()+ const target = recall.active && recall.items.length ? recall.items[recall.focus].i : state.aim+ if (target >= 0) enterDive(target)+ return+ }+ if (key === 'Tab') { e.preventDefault(); if (recall.active) focusItem(e.shiftKey ? -1 : 1); return }+ if ((key === 'ArrowDown' || key === 'ArrowUp') && recall.active && recall.items.length && !e.altKey) { e.preventDefault(); focusItem(key === 'ArrowUp' ? -1 : 1); return }+ if (key.startsWith('Arrow') || key === 'PageUp' || key === 'PageDown') { e.preventDefault(); return }+ if (key === 'Home') { Object.assign(want, HOME); camRate = 2.2; return }++ // time+ if (key === '[' || key === ']' || key === '{' || key === '}') {+ e.preventDefault()+ const step = key === '{' || key === '}' ? 0.12 : 0.03+ const dir = key === '[' || key === '{' ? -1 : 1+ if (!time.on && dir > 0) return+ if (!time.on) startTime(1)+ time.playing = false; time.rewinding = false; time.endHold = 0+ time.want = clamp(time.want + dir * step, 0, 1)+ if (time.want >= 1 && dir > 0) time.endHold = performance.now() + 900+ return+ }+ if (key === '\\') {+ e.preventDefault()+ if (time.on && (time.playing || time.rewinding)) { time.playing = false; time.rewinding = false; time.want = time.u; return }+ if (time.on && time.u < 0.999) { time.playing = true; time.endHold = 0; return }+ startTime(1)+ time.rewinding = !reduceMotion+ if (reduceMotion) { time.u = time.want = 0; time.playing = true }+ return+ }++ // typing is recall+ if (key === 'Backspace') { e.preventDefault(); if (e.altKey || e.ctrlKey) setQuery(recall.q.replace(/\S+\s*$/, '')); else setQuery(recall.q.slice(0, -1)); return }+ if (e.ctrlKey && key.toLowerCase() === 'u') { e.preventDefault(); setQuery(''); return }+ if (e.ctrlKey && key.toLowerCase() === 'w') { e.preventDefault(); setQuery(recall.q.replace(/\S+\s*$/, '')); return }+ if (key.length === 1 && !e.ctrlKey && !e.altKey) {+ if (key === ' ' && !recall.q) { e.preventDefault(); return }+ e.preventDefault()+ setQuery((recall.q + key).slice(0, 120))+ }+ })+ addEventListener('keyup', (e) => { state.keys.delete(e.key); if (e.key === 'Alt' || e.key === 'Shift') return })+ addEventListener('blur', () => state.keys.clear())++ surface.addEventListener('pointerdown', (e) => { state.mouse.down = true; state.mouse.dragged = false; state.mouse.lx = e.clientX; state.mouse.ly = e.clientY; surface.setPointerCapture?.(e.pointerId) })+ addEventListener('pointermove', (e) => {+ state.mouse.x = e.clientX; state.mouse.y = e.clientY; state.mouse.at = performance.now()+ if (state.mouse.down && state.mode === 'explore') {+ const dx = e.clientX - state.mouse.lx, dy = e.clientY - state.mouse.ly+ if (Math.abs(dx) + Math.abs(dy) > 2) state.mouse.dragged = true+ want.yaw -= dx * 0.006; want.pitch = clamp(want.pitch + dy * 0.005, -1.4, 1.4)+ state.mouse.lx = e.clientX; state.mouse.ly = e.clientY+ camRate = 8; state.lastInput = performance.now()+ }+ })+ addEventListener('pointerup', () => {+ if (state.mouse.down && !state.mouse.dragged && state.mode === 'explore') {+ if (recall.active && recall.items.length) {+ // click a recalled memory to dive into it+ let best = -1, bd = 26+ for (const it of recall.items) { const n = M.nodes[it.i]; const p = project(n.x, n.y, n.z); if (!p) continue; const d = Math.hypot(p.x - state.mouse.x, p.y - state.mouse.y); if (d < bd) { bd = d; best = it.i } }+ if (best >= 0) enterDive(best)+ } else if (state.aim >= 0) enterDive(state.aim)+ }+ state.mouse.down = false+ })+ surface.addEventListener('wheel', (e) => {+ e.preventDefault()+ if (state.mode !== 'explore') return+ fly(-e.deltaY * 0.0022)+ camRate = 6; state.lastInput = performance.now()+ }, { passive: false })++ // ── the loop ──++ let running = false, last = 0+ const perf = { ms: 0 }+ function frame(now) {+ if (!running) return+ const t0 = performance.now()+ const dt = Math.min(0.05, Math.max(0.001, (now - last) / 1000))+ last = now+ if (state.mode === 'arrival') arrival(now)+ steer(dt)+ stepTime(now, dt)+ if (recall.active) { recall.fade = Math.min(1, recall.fade + dt * 3) } else recall.fade = Math.max(0, recall.fade - dt * 1.8)+ if (!recall.active && recall.fade <= 0 && recall.dirty !== false) { recallLevel.fill(0); recallStart.fill(1e15); recall.dirty = false }+ if (recall.active) recall.dirty = true+ recallCamera(now)+ if (!time.on || !time.playing) stepAmbient(now, dt)+ updateCamera(dt)+ aim(now)+ stepPulses(now)+ stepGlow(now)+ const arrive = state.mode === 'arrival' ? (now - state.arrivalStart) / 1000 : 1e4+ const lineIn = state.mode === 'arrival' ? smooth(3.0, 4.6, arrive) : 1+ renderer.draw({+ view, proj, px: pxScale, arrive,+ mul: { scaffold: (recall.fade > 0 ? lerp(1, 0.55, recall.fade) : 1) * (time.on ? 0.85 : 1), nodes: 1, pulses: 1 },+ lineMul: lineIn * (state.mode === 'dive' ? 0.6 : 1),+ })+ drawInk(now)+ hud(now)+ const cost = performance.now() - t0+ perf.ms = perf.ms * 0.95 + cost * 0.05+ requestAnimationFrame(frame)+ }+ function start() { if (running || document.hidden) return; running = true; last = performance.now(); requestAnimationFrame(frame) }+ function stop() { running = false }+ document.addEventListener('visibilitychange', () => (document.hidden ? stop() : start()))++ // ── begin ──++ resize()+ MemoryData.load().then((data) => {+ const t0 = performance.now()+ M = buildModel(data)+ upload()+ buildStrip()+ const built = performance.now() - t0+ $('loading').remove()+ if (reduceMotion) document.body.classList.remove('arriving')+ const t = M.totals+ const who = data.real ? 'this computer' : 'an invented person'+ $('stats').textContent = `${who} · ${plural(t.loaded, 'message')}${M.ghostTotal ? ` (+${num(M.ghostTotal)} older)` : ''} · ${plural(t.memories, 'memory', 'memories')} · ${t.lines} About You · ${plural(t.regions, 'region')}`+ $('title').lastChild.dataset.full = `${plural(t.loaded + M.ghostTotal, 'thing you said', 'things you said')} · ${plural(t.memories, 'memory', 'memories')} · ${plural(t.lines, 'line', 'lines')} about you`+ state.mode = 'arrival'+ state.arrivalStart = performance.now()+ if (!reduceMotion) { cam.dist = 12; want.dist = 12 }+ renderKeys()+ window.__synapse = { perf, screenOf: (i) => { const n = M.nodes[i]; return n ? project(n.x, n.y, n.z) : null }, firstOf: (k) => M.nodes.findIndex((n) => n.k === ({ hub: HUB, engram: ENGRAM, neuron: NEURON })[k]), look: (yaw, pitch, dist) => { Object.assign(want, { ...HOME, yaw, pitch, dist: dist || HOME.dist }); Object.assign(cam, want); state.lastInput = performance.now() + 1e5 }, built: Math.round(built), renderer: renderer.kind, nodes: M.nodes.length, scaffold: M.scaffold.length, lines: M.lineVerts.length, regions: M.regions.map((r) => [r.name, r.neuronCount, r.memoryCount]), inferred: M.inferred, state: () => ({ mode: state.mode, recall: recall.items.length, focus: recall.focus, time: time.on ? time.u : 1, aim: state.aim, dive: dive.node }) }+ start()+ }).catch((error) => {+ const l = $('loading')+ if (l) { l.textContent = 'could not read memories: ' + String(error && error.message || error); l.style.letterSpacing = '0' }+ console.error(error)+ })+})()diff --git a/docs/research/2026-10-10-memory-brain/synapse.png b/docs/research/2026-10-10-memory-brain/synapse.pngnew file mode 100644index 000000000..58df94629Binary files /dev/null and b/docs/research/2026-10-10-memory-brain/synapse.png differdiff --git a/docs/research/2026-10-10-memory-brain/tesseract-string.png b/docs/research/2026-10-10-memory-brain/tesseract-string.pngnew file mode 100644index 000000000..61b60ee85Binary files /dev/null and b/docs/research/2026-10-10-memory-brain/tesseract-string.png differdiff --git a/docs/research/2026-10-10-memory-brain/tesseract.html b/docs/research/2026-10-10-memory-brain/tesseract.htmlnew file mode 100644index 000000000..22d790e95--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/tesseract.html@@ -0,0 +1,143 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Tesseract</title>+<meta name="description" content="Your months unrolled as a corridor of days: fly through time, pull a memory's string, type to recall.">+<style>+ :root {+ --bg: #060608;+ --ink: #ece4d4;+ --dim: #9a9285;+ --faint: #625d55;+ --gold: #f4c56c;+ --cool: #96d4ff;+ --rule: rgba(233, 221, 199, .16);+ --panel: rgba(8, 8, 11, .94);+ --mono: ui-monospace, "SF Mono", Menlo, Monaco, Consolas, monospace;+ }+ * { box-sizing: border-box }+ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--ink); overflow: hidden;+ font: 12px/1.5 var(--mono); -webkit-font-smoothing: antialiased }+ #scene { position: fixed; inset: 0; width: 100%; height: 100%; display: block; outline: none }+ #vignette { position: fixed; inset: 0; pointer-events: none;+ background: radial-gradient(125% 95% at 50% 46%, transparent 52%, rgba(0, 0, 0, .62) 100%) }++ .hud { transition: opacity .6s ease }+ body.arriving .hud { opacity: 0 }+ body.reading .hud.fadeable { opacity: .18 }++ #day { position: fixed; left: 18px; top: 14px; max-width: 44vw; pointer-events: none }+ #date { font-size: 19px; letter-spacing: .16em; text-transform: uppercase; color: var(--ink); white-space: nowrap }+ #ago { color: var(--dim); margin-top: 1px }+ #counts { margin-top: 9px; color: var(--ink) }+ #chips { margin-top: 3px; color: var(--dim); display: flex; flex-wrap: wrap; gap: 2px 14px }+ .dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; vertical-align: 1px; flex: none }+ .note { color: var(--faint); margin-top: 4px; max-width: 42ch }++ #corner { position: fixed; right: 18px; top: 14px; text-align: right; color: var(--faint); max-width: 40vw; pointer-events: none }+ #lane { color: var(--dim); margin-top: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis }+ #lane b { color: var(--ink); font-weight: normal }++ #ticker { position: fixed; left: 50%; transform: translateX(-50%); bottom: 60px; width: min(900px, calc(100vw - 32px)) }+ .row { display: flex; gap: 12px; white-space: nowrap; overflow: hidden; color: var(--dim); padding: 1px 10px;+ border-left: 2px solid transparent; opacity: .62; cursor: default }+ .row .time { color: var(--faint); flex: none; width: 7ch; text-align: right }+ .row .who { flex: none; width: 13ch; overflow: hidden; text-overflow: ellipsis }+ .row .where { flex: none; width: 17ch; overflow: hidden; text-overflow: ellipsis; color: var(--faint) }+ .row .text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis }+ .row.mem .text { color: #efe2c4 }+ .row.mem .text::before { content: "▮ "; color: var(--gold) }+ .row.sel { opacity: 1; color: var(--ink); background: linear-gradient(90deg, rgba(244, 197, 108, .10), rgba(244, 197, 108, 0) 85%);+ border-left-color: var(--gold); white-space: normal; padding-top: 3px; padding-bottom: 3px }+ .row.sel .time { color: var(--gold) }+ .row.sel .who, .row.sel .where { white-space: nowrap }+ .row.lit .time { color: var(--gold) }+ .row.lit .time::before { content: "◆"; margin-right: 4px; font-size: 8px; vertical-align: 1px }+ .row .time { white-space: nowrap }+ .row.sel .text { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; white-space: normal }+ .row.quiet { opacity: .7; color: var(--faint); justify-content: center }+ mark { background: none; color: var(--cool); text-decoration: underline; text-decoration-color: rgba(150, 212, 255, .5); text-underline-offset: 2px }++ #status { position: fixed; left: 50%; transform: translateX(-50%); bottom: 32px; width: min(900px, calc(100vw - 32px));+ padding: 0 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--dim); min-height: 18px }+ #status .q { color: var(--cool) }+ #status .q::after { content: "▏"; animation: blink 1.05s steps(1) infinite; color: var(--cool) }+ #status .pulled { color: var(--gold) }+ #status .k { color: var(--faint) }+ @keyframes blink { 50% { opacity: 0 } }++ #hint { position: fixed; left: 0; right: 0; bottom: 9px; text-align: center; color: var(--faint); font-size: 11px;+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding: 0 16px; pointer-events: none }+ #hint b { color: var(--dim); font-weight: normal }++ #load { position: fixed; left: 50%; top: 46%; transform: translate(-50%, -50%); color: var(--faint); letter-spacing: .2em; text-transform: uppercase; font-size: 11px }++ #card { position: fixed; left: 50%; top: 47%; transform: translate(-50%, -50%); width: min(700px, calc(100vw - 32px));+ max-height: 74vh; overflow: auto; background: var(--panel); border: 1px solid var(--rule);+ box-shadow: 0 40px 120px rgba(0, 0, 0, .7), 0 0 0 1px rgba(0, 0, 0, .6); padding: 18px 22px 16px; scrollbar-width: thin }+ #card[hidden], #about[hidden] { display: none }+ #card .kick { color: var(--dim); display: flex; flex-wrap: wrap; gap: 2px 12px; align-items: center }+ #card h2 { font-size: 16px; font-weight: normal; margin: 10px 0 4px; color: var(--ink); line-height: 1.35 }+ #card .desc { color: var(--dim); margin: 0 0 10px }+ #card .body { white-space: pre-wrap; word-break: break-word; margin: 12px 0 0; color: #e6dccb; font: inherit; line-height: 1.6 }+ #card .meta { color: var(--faint); margin-top: 14px; word-break: break-all }+ #card .foot { color: var(--faint); margin-top: 14px; border-top: 1px solid var(--rule); padding-top: 9px }+ #card .foot b { color: var(--gold); font-weight: normal }+ #card ul { list-style: none; padding: 0; margin: 10px 0 0 }+ #card li { padding: 3px 0; color: #e6dccb; display: flex; gap: 8px; align-items: baseline }+ #card li .when { color: var(--faint); margin-left: auto; flex: none }+ #card .tag { color: var(--gold) }++ #about { position: fixed; overflow: hidden; pointer-events: auto; padding: 2.6% 3.2% 1%; font-size: 13px; line-height: 1.55;+ display: flex; flex-direction: column;+ background: linear-gradient(180deg, rgba(10, 9, 8, .62), rgba(8, 8, 10, .40) 70%, rgba(8, 8, 10, 0)); transition: opacity .25s }+ #about .ah { display: flex; align-items: baseline; gap: 4px 16px; margin-bottom: 16px; flex-wrap: wrap; flex: none }+ #about h1 { font-size: 16px; letter-spacing: .3em; text-transform: uppercase; font-weight: normal; margin: 0; color: var(--gold) }+ #about .intro { color: var(--dim) }+ #about .scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; scrollbar-width: none;+ scroll-padding: 6px 0 26px;+ -webkit-mask-image: linear-gradient(180deg, #000 92%, transparent); mask-image: linear-gradient(180deg, #000 92%, transparent) }+ #about .scroll::-webkit-scrollbar { display: none }+ #about .cols { column-count: 2; column-gap: 5% }+ #about .sec { break-inside: avoid-column; margin-bottom: 16px }+ #about h3 { font-size: 10px; letter-spacing: .24em; text-transform: uppercase; font-weight: normal; color: #8a7a5c; margin: 0 0 5px }+ #about .line { color: #d9cfbd; padding: 2px 6px; margin-left: -8px; border-left: 2px solid transparent; break-inside: avoid; cursor: default }+ #about .line .c { white-space: nowrap; margin-left: 6px }+ #about .line .c .dot { width: 5px; height: 5px; margin-right: 3px }+ #about .line.sel { color: var(--ink); border-left-color: var(--gold); background: rgba(244, 197, 108, .08) }+ #about.small { font-size: 11.5px; line-height: 1.45 }+ #about.small .sec { margin-bottom: 10px }+ #about.small .ah { margin-bottom: 10px }+ #about.narrow { font-size: 11px }+ #about.narrow .cols { column-count: 1 }+</style>+</head>+<body class="arriving">+<canvas id="scene" tabindex="0" aria-label="Tesseract: your days as a corridor"></canvas>+<div id="vignette"></div>+<div id="load">unfolding</div>++<div id="day" class="hud fadeable">+ <div id="date"></div>+ <div id="ago"></div>+ <div id="counts"></div>+ <div id="chips"></div>+ <div id="daynote" class="note"></div>+</div>+<div id="corner" class="hud fadeable">+ <div id="source"></div>+ <div id="lane"></div>+</div>+<div id="ticker" class="hud fadeable"></div>+<div id="status" class="hud"></div>+<div id="hint" class="hud"></div>++<div id="about" hidden></div>+<div id="card" hidden role="dialog" aria-modal="true"></div>++<script src="memory-data.js"></script>+<script src="tesseract.js"></script>+</body>+</html>diff --git a/docs/research/2026-10-10-memory-brain/tesseract.js b/docs/research/2026-10-10-memory-brain/tesseract.jsnew file mode 100644index 000000000..1ca85f4c4--- /dev/null+++ b/docs/research/2026-10-10-memory-brain/tesseract.js@@ -0,0 +1,1988 @@+/*+ * Tesseract: your months unrolled as a corridor of days you float through (Interstellar, 2014).+ *+ * Each day is a frame in depth. Its height is how much happened that day, so the corridor's skyline is the+ * rhythm of your weeks. Your messages hang from the frame as strands: colour is the agent, x is the project+ * lane plus the time of day, length is how much you wrote. Memories an agent wrote that day stand on its floor+ * as books. Projects run along the floor as lanes through every day. Month gates and Monday ribs are the+ * architecture; quiet stretches are empty halls.+ *+ * Pull a string (Space) on a memory or a message and a thread runs through every day it came up, vibrating+ * as it lights them. Type, and recall pulses down the corridor. About You is the window at the corridor's+ * mouth, looking back at you, with a thread from each line to the memories it cites.+ *+ * Reads only MemoryData. All memory text is untrusted (written by models): textContent and fillText only.+ */+(function () {+ 'use strict'++ // ── constants ────────────────────────────────────────────────────────────────────────────────────++ const DAY = 86_400_000+ const S = 0.34 // depth between two days+ const D = 1.25 // the camera stands this far in front of the day it looks at+ const HW = 0.8 // half the width of a day frame+ const FLOOR = -0.5+ const FOG = 30 // days of depth for the fog+ const NEAR = 0.045+ const ABOUT_Z = D + 0.42 // the About You window: just behind the camera while it looks at today+ const ABOUT_D = 1.12+ const STATION = -(ABOUT_Z + ABOUT_D - D) / S // the camera's day position in front of the window+ const AHW = 1.0, AH = 1.24 // window half width and height+ const BOOK_H = 0.118, BOOK_W = 0.017+ const WAVE = 55 // days per second a pulled string's wave travels+ const PULSE = 75 // days per second a recall pulse travels+ const MONO = 'ui-monospace, "SF Mono", Menlo, Monaco, Consolas, monospace'+ const WARM = '233,221,199', GOLD = '244,197,108', COOL = '150,212,255', WHITE = '255,251,242'+ const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']+ const NONE = 'no project'++ const $ = (id) => document.getElementById(id)+ const clamp = (v, a = 0, b = 1) => (v < a ? a : v > b ? b : v)+ const lerp = (a, b, t) => a + (b - a) * t+ const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2)+ const easeOut = (t) => 1 - Math.pow(1 - t, 3)+ const nowS = () => performance.now() / 1000+ const plural = (n, one, many = one + 's') => `${n.toLocaleString('en-US')} ${n === 1 ? one : many}`+ function hash(s) { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) } return (h >>> 0) / 4294967296 }+ 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+ }+ }+ function el(tag, cls, text) {+ const node = document.createElement(tag)+ if (cls) node.className = cls+ if (text != null) node.textContent = text+ return node+ }++ // ── words: for strings (what came up when) and recall ─────────────────────────────────────────────++ const STOP = new Set((+ 'the and for are but not you your yours with this that these those from have has had was were will would should could ' ++ 'can cant just like into onto over under about after before then than them they their there here what when where which ' ++ 'while who whom why how all any each every some such only own same very too also its itself our ours out off one two ' ++ 'new now get got use used using make made let lets need needs want wants see look looks way more most less much many few ' ++ 'lot lots thing things okay yes yeah please thanks thank sure does did done doing being been because via per etc dont ' ++ 'didnt isnt thats theres whats ive youre well still even back again going gonna know think right good really other ' ++ 'another him her his she ask asked tell said say says try work works working first last next time times day days week ' ++ 'keep kept show shows run runs ran put take takes give gives come comes call called'+ ).split(/\s+/).filter(Boolean))+ function stem(w) {+ if (w.length > 4 && w.endsWith('ies')) w = w.slice(0, -3) + 'y'+ else if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss')) w = w.slice(0, -1)+ if (w.length > 5 && w.endsWith('ing')) w = w.slice(0, -3)+ else if (w.length > 4 && w.endsWith('ed')) w = w.slice(0, -2)+ if (w.length > 4 && w.endsWith('e')) w = w.slice(0, -1)+ return w+ }+ const WORD = /[\p{L}\p{N}_]{3,}/gu+ function stems(text) {+ const out = new Set()+ const found = String(text ?? '').slice(0, 5000).toLowerCase().replace(/[’']/g, '').match(WORD)+ if (found) for (const w of found) {+ if (STOP.has(w) || /^\d+$/.test(w) || w.length > 28) continue+ const s = stem(w)+ if (s.length >= 3 && !STOP.has(s)) out.add(s)+ }+ return out+ }+ const queryTerms = (q) => String(q).toLowerCase().match(/[\p{L}\p{N}_.\-/]{2,}/gu) ?? []++ // ── the model: days, lanes, items ─────────────────────────────────────────────────────────────────++ let M = null++ function build(loaded) {+ const { snapshot, asks } = loaded+ const memories = snapshot.memories ?? []+ const start = new Date(); start.setHours(0, 0, 0, 0)+ const today0 = start.getTime()+ const kOf = (t) => { const d = new Date(t); d.setHours(0, 0, 0, 0); return Math.round((today0 - d.getTime()) / DAY) }+ const kOfDay = (s) => { const [y, m, d] = String(s).split('-').map(Number); return Math.round((today0 - new Date(y, m - 1, d).getTime()) / DAY) }+ const agents = new Map()+ const agentOf = (id) => { if (!agents.has(id)) agents.set(id, MemoryData.agent(id, snapshot)); return agents.get(id) }+ const activity = snapshot.sessions?.activity ?? []++ let maxK = 27+ for (const a of asks) maxK = Math.max(maxK, kOf(a.at))+ for (const m of memories) if (m.modified) maxK = Math.max(maxK, kOf(m.modified))+ for (const r of activity) maxK = Math.max(maxK, kOfDay(r.day))+ maxK = Math.min(370, maxK)++ const days = []+ for (let k = 0; k <= maxK; k++) {+ const d = new Date(today0); d.setDate(d.getDate() - k)+ days.push({ k, t: d.getTime(), date: d, dow: d.getDay(), dom: d.getDate(), month: d.getMonth(), year: d.getFullYear(),+ items: [], askItems: [], memItems: [], groups: [], by: {}, act: {}, ghostBy: {}, ghostN: 0, asks: 0, mems: 0, h: 0.13, quiet: true, bright: 0 })+ }++ // Lanes: a project is the folder a conversation ran in. A conversation keeps the lane of any message that has one.+ const projects = (snapshot.projects ?? []).filter((p) => p.name)+ const names = [...new Set([...projects.map((p) => p.name), ...memories.map((m) => m.project?.name).filter(Boolean)])].sort((a, b) => b.length - a.length)+ const laneOfCwd = (cwd) => {+ if (!cwd) return null+ const parts = String(cwd).split('/')+ for (const n of names) if (parts.includes(n)) return n+ return null+ }+ const sessionLane = new Map()+ for (const a of asks) if (!sessionLane.has(a.sessionId)) { const n = laneOfCwd(a.cwd); if (n) sessionLane.set(a.sessionId, n) }+ const laneNameOfAsk = (a) => sessionLane.get(a.sessionId) ?? laneOfCwd(a.cwd) ?? NONE+ const weight = new Map()+ for (const a of asks) { const n = laneNameOfAsk(a); weight.set(n, (weight.get(n) ?? 0) + 1) }+ for (const m of memories) { const n = m.project?.name || NONE; weight.set(n, (weight.get(n) ?? 0) + 4) }+ let order = [...weight.keys()].filter((n) => n !== NONE).sort((a, b) => weight.get(b) - weight.get(a) || a.localeCompare(b))+ const merged = new Map()+ if (order.length > 12) {+ let w = 0+ for (const n of order.slice(12)) { merged.set(n, 'other projects'); w += weight.get(n) }+ order = order.slice(0, 12); order.push('other projects'); weight.set('other projects', w)+ }+ if (weight.has(NONE)) order.push(NONE)+ if (!order.length) order.push(NONE)+ const raw = order.map((n) => Math.sqrt(weight.get(n) ?? 1))+ let share = raw.map((r) => r / raw.reduce((s, x) => s + x, 0))+ share = share.map((s) => Math.max(s, 0.036))+ const total = share.reduce((s, x) => s + x, 0)+ let u = 0+ const lanes = order.map((name, i) => {+ const w = share[i] / total+ const lane = { i, name, u0: u, u1: u + w, weight: weight.get(name) ?? 0 }+ u += w+ return lane+ })+ const laneIdx = new Map(lanes.map((l) => [l.name, l.i]))+ const laneFor = (name) => laneIdx.get(merged.get(name) ?? name) ?? laneIdx.get(NONE) ?? lanes.length - 1+ const uOf = (lane, tod) => {+ const l = lanes[lane], pad = Math.min(0.006, (l.u1 - l.u0) * 0.1)+ return l.u0 + pad + (l.u1 - l.u0 - 2 * pad) * tod+ }++ const askItems = [], memItems = [], bySession = new Map(), byAskKey = new Map()+ asks.forEach((a, n) => {+ const k = kOf(a.at)+ if (k < 0 || k > maxK) return+ const day = days[k]+ const lane = laneFor(laneNameOfAsk(a))+ const len = Math.max(a.length || 0, String(a.text ?? '').length)+ const tod = clamp((a.at - day.t) / DAY, 0, 0.9999)+ const item = { type: 'ask', a, k, lane, tod, len, engine: a.engine, color: agentOf(a.engine).color, n,+ hang: 0.16 + 0.62 * clamp(Math.log(Math.max(1, len) / 10) / Math.log(160)), lower: String(a.text ?? '').toLowerCase(), stems: null }+ item.u = uOf(lane, tod); item.x = -HW + 2 * HW * item.u+ day.askItems.push(item); day.asks++; day.by[a.engine] = (day.by[a.engine] ?? 0) + 1+ askItems.push(item)+ if (!bySession.has(a.sessionId)) bySession.set(a.sessionId, [])+ bySession.get(a.sessionId).push(item)+ byAskKey.set(`${a.sessionId}@${a.at}`, item)+ })+ const memById = new Map()+ memories.forEach((m, n) => {+ if (!m.modified) return+ const k = kOf(m.modified)+ if (k < 0 || k > maxK) return+ const day = days[k]+ const lane = laneFor(m.project?.name || NONE)+ const tod = clamp((m.modified - day.t) / DAY, 0, 0.9999)+ const item = { type: 'mem', m, k, lane, tod, color: agentOf(m.agent).color, n, stems: null,+ lower: `${m.title ?? ''}\n${m.description ?? ''}\n${m.body ?? ''}`.toLowerCase() }+ item.u = uOf(lane, tod); item.x = -HW + 2 * HW * item.u+ day.memItems.push(item); day.mems+++ memItems.push(item); memById.set(m.id, item)+ })+ for (const r of activity) {+ const k = kOfDay(r.day)+ if (k < 0 || k > maxK) continue+ days[k].act[r.engine] = (days[k].act[r.engine] ?? 0) + (r.asks || 0)+ }++ // Day shape: height from activity (messages, including older ones only counted), quiet days stay low.+ for (const day of days) {+ for (const [engine, n] of Object.entries(day.act)) {+ const g = Math.max(0, n - (day.by[engine] ?? 0))+ if (g) { day.ghostBy[engine] = g; day.ghostN += g }+ }+ day.items = [...day.askItems, ...day.memItems].sort((a, b) => a.lane - b.lane || a.tod - b.tod)+ const groups = new Map()+ for (const it of day.askItems.sort((a, b) => a.lane - b.lane || a.tod - b.tod)) {+ if (!groups.has(it.color)) groups.set(it.color, [])+ groups.get(it.color).push(it)+ }+ day.groups = [...groups].map(([color, items]) => ({ color, items }))+ if (day.ghostN) {+ const random = rng(day.k * 7919 + 17)+ const cap = Math.min(day.ghostN, 320)+ const ghosts = new Map()+ for (const [engine, n] of Object.entries(day.ghostBy)) {+ const color = agentOf(engine).color+ const share = Math.max(1, Math.round(cap * n / day.ghostN))+ const xs = new Float32Array(share), hs = new Float32Array(share)+ for (let i = 0; i < share; i++) { xs[i] = -HW + 2 * HW * (0.015 + 0.97 * random()); hs[i] = 0.12 + 0.3 * random() }+ ghosts.set(color, { color, xs, hs })+ }+ day.ghosts = [...ghosts.values()]+ }+ }+ const volume = days.map((d) => d.asks + d.ghostN + 3 * d.mems).filter((v) => v > 0).sort((a, b) => a - b)+ const p92 = volume.length ? Math.max(4, volume[Math.floor(volume.length * 0.92)]) : 1+ for (const day of days) {+ const v = day.asks + day.ghostN + 3 * day.mems+ day.quiet = !v+ day.bright = Math.sqrt(Math.min(1, v / p92))+ day.h = v ? 0.3 + 0.82 * day.bright : 0.13+ }++ // Quiet stretches: four or more days in a row without a message or a memory.+ const stretches = []+ for (let k = 0; k <= maxK;) {+ if (!days[k].quiet) { k++; continue }+ let j = k+ while (j + 1 <= maxK && days[j + 1].quiet) j+++ if (j - k + 1 >= 4) stretches.push({ from: k, to: j, n: j - k + 1, mid: (k + j) / 2 })+ k = j + 1+ }++ // Text index: which words came up, how often.+ const DF = new Map()+ for (const it of askItems) { it.stems = stems(it.a.text); for (const s of it.stems) DF.set(s, (DF.get(s) ?? 0) + 1) }+ for (const it of memItems) it.stems = stems(`${it.m.title ?? ''} ${it.m.description ?? ''} ${String(it.m.body ?? '').slice(0, 1500)}`)++ // About You: each line and the memories it cites.+ const about = snapshot.about ?? null+ const aboutLines = (about?.lines ?? []).map((line, i) => {+ const cited = MemoryData.refs(line, snapshot).map((row) => memById.get(row.id)).filter(Boolean)+ const asksRef = (line.refs ?? []).map((r) => /^asks:(\d+)/.exec(r)).filter(Boolean).reduce((s, m) => s + Number(m[1]), 0)+ return { i, line, cited, asksRef, sessionRef: (line.refs ?? []).some((r) => r.startsWith('session:')) }+ })++ return { snapshot, real: loaded.real, days, maxK, lanes, askItems, memItems, bySession, byAskKey, memById, DF, N: askItems.length,+ stretches, about, aboutLines, agentOf, laneOfCwd, laneFor, uOf, kOf, today0, loadedFrom: askItems.length ? askItems[askItems.length - 1].k : -1 }+ }++ // ── strings: everything a memory, a message or a belief is tied to ────────────────────────────────++ function keyTerms(parts, limit, minDf = 1) {+ const N = M.N || 1+ const score = new Map()+ for (const [text, w] of parts) for (const s of stems(text)) {+ const df = M.DF.get(s) || 0+ if (df < minDf || df > Math.max(6, N * 0.05)) continue+ const v = w * Math.log(1 + N / df)+ score.set(s, Math.max(score.get(s) ?? 0, v))+ }+ return [...score].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([s]) => s)+ }+ // Two of a memory's key words together, or its single strongest word when that word is rare.+ function matches(itemStems, terms) {+ if (!terms.length || !itemStems) return false+ let hit = 0+ for (const t of terms) if (itemStems.has(t)) hit+++ if (hit >= Math.min(2, terms.length)) return true+ return itemStems.has(terms[0]) && (M.DF.get(terms[0]) || 0) <= Math.max(3, M.N * 0.006)+ }++ function buildString(source) {+ const lit = new Map()+ const add = (it) => {+ if (!it || it.k == null) return+ if (!lit.has(it.k)) lit.set(it.k, [])+ const list = lit.get(it.k)+ if (!list.includes(it)) list.push(it)+ }+ let label = '', terms = [], origin = 0, from = null, kind = source.type+ const tieMemory = (mem) => {+ const t = keyTerms([[mem.m.title, 3], [mem.m.description, 1.6], [String(mem.m.body ?? '').slice(0, 700), 0.6]], 3)+ add(mem)+ for (const it of M.askItems) if (matches(it.stems, t)) add(it)+ return t+ }+ if (source.type === 'mem') {+ terms = tieMemory(source)+ origin = source.k; label = source.m.title || 'a memory'+ } else if (source.type === 'ask' || source.type === 'hit') {+ add(source); origin = source.k+ const sid = source.type === 'ask' ? source.a.sessionId : source.h.sessionId+ for (const it of M.bySession.get(sid) ?? []) add(it)+ const text = source.type === 'ask' ? source.a.text : String(source.h.snippet ?? '').replace(/[\u0002\u0003…]/g, '')+ terms = keyTerms([[text, 1]], 2, 2)+ if (terms.length) {+ for (const it of M.askItems) if (it !== source && matches(it.stems, terms)) add(it)+ for (const it of M.memItems) if (matches(it.stems, terms)) add(it)+ }+ label = oneLine(text).slice(0, 60) || 'a message'+ } else if (source.type === 'about') {+ const row = source.row+ for (const mem of row.cited) tieMemory(mem)+ terms = keyTerms([[row.line.text, 1]], 3, 2)+ if (terms.length) for (const it of M.askItems) if (matches(it.stems, terms)) add(it)+ origin = STATION + 1; label = row.line.text+ from = aboutFrom(row.i)+ }+ const order = [...lit.keys()].sort((a, b) => a - b)+ const anchors = new Map()+ for (const k of order) {+ const list = lit.get(k)+ anchors.set(k, list.includes(source) ? source : list.find((it) => it.type === 'mem') ?? list[Math.floor(list.length / 2)])+ }+ const set = new Set()+ for (const list of lit.values()) for (const it of list) set.add(it)+ const path = []+ if (from) path.push({ ...from, k: STATION + 1 })+ for (const k of order) { const p = anchorPoint(anchors.get(k)); path.push({ ...p, k }) }+ return { source, kind, label, terms, lit, order, anchors, set, origin, path, t0: nowS() }+ }++ function anchorPoint(it) {+ const day = M.days[it.k]+ if (it.type === 'mem') return { x: it.x, y: FLOOR + BOOK_H + 0.012, z: -it.k * S }+ const top = FLOOR + day.h+ return { x: it.x, y: top - (it.hang ?? 0.3) * day.h * 0.86, z: -it.k * S }+ }++ // ── state ─────────────────────────────────────────────────────────────────────────────────────────++ const canvas = $('scene'), ctx = canvas.getContext('2d')+ const ui = { day: $('day'), date: $('date'), ago: $('ago'), counts: $('counts'), chips: $('chips'), daynote: $('daynote'),+ source: $('source'), lane: $('lane'), ticker: $('ticker'), status: $('status'), hint: $('hint'), card: $('card'), about: $('about'), load: $('load') }+ let vw = 0, vh = 0, dpr = 1, F0 = 500, F = 500, OX = 0, OY = 0+ const cam = { k: -1.6, x: 1, y: 0.38, yaw: -0.46, pitch: -0.11 }+ let camZ = 0, cY = 1, sY = 0, cP = 1, sP = 0+ const fly = { from: 0, to: 0, t0: 0, dur: 0, ease: easeOut, active: false }+ let mode = 'corridor' // 'corridor' | 'about'+ const focus = { k: 0, item: null, lane: 0, u: 0.5 }+ let aboutSel = 0+ let pulled = null+ const recall = { open: false, q: '', terms: [], hits: [], set: new Set(), byDay: new Map(), t0: -99, origin: 0, extras: [], seq: 0, timer: 0, mems: 0 }+ let reading = null // the item (or About line) open in the card+ let arrival = null+ const mouse = { x: 0, y: 0 }+ let raf = 0, lastT = 0, speed = 0, prevK = 0, wheelAcc = 0+ const motion = matchMedia('(prefers-reduced-motion: reduce)')+ let reduced = motion.matches+ motion.addEventListener?.('change', (e) => { reduced = e.matches; kick() })+ const perf = { frames: 0, ms: 0, worst: 0 }+ let aboutRects = null, aboutBars = null, aboutOpacity = 0, aboutBox = ''++ // ── projection ────────────────────────────────────────────────────────────────────────────────────++ const V = { x: 0, y: 0, d: 0 }+ function view(x, y, z) {+ const dx = x - cam.x, dy = y - cam.y, dz = z - camZ+ const d0 = dx * sY - dz * cY+ V.x = dx * cY + dz * sY+ V.d = d0 * cP + dy * sP+ V.y = dy * cP - d0 * sP+ return V+ }+ // A frame is a plane at one depth; points on it project through a fixed linear map (an exact homography).+ const P = { ox: 0, oy: 0, od: 0, xx: 0, xy: 0, xd: 0, yx: 0, yy: 0, yd: 0 }+ function plane(z) {+ view(0, 0, z); const ox = V.x, oy = V.y, od = V.d+ view(1, 0, z); P.xx = V.x - ox; P.xy = V.y - oy; P.xd = V.d - od+ view(0, 1, z); P.yx = V.x - ox; P.yy = V.y - oy; P.yd = V.d - od+ P.ox = ox; P.oy = oy; P.od = od+ return od+ }+ let PX = 0, PY = 0, PD = 0+ function ps(x, y) {+ const d = P.od + x * P.xd + y * P.yd+ PD = d+ const inv = F / (d > NEAR ? d : NEAR)+ PX = OX + (P.ox + x * P.xx + y * P.yx) * inv+ PY = OY - (P.oy + x * P.xy + y * P.yy) * inv+ return d > NEAR+ }+ function p3(x, y, z) {+ view(x, y, z)+ PD = V.d+ const inv = F / (V.d > NEAR ? V.d : NEAR)+ PX = OX + V.x * inv; PY = OY - V.y * inv+ return V.d > NEAR+ }++ // During the arrival the corridor unfolds: every day starts at today and flies back to its place.+ function unfold(k, T) {+ if (!arrival) return 1+ return easeOut(clamp((T - arrival.t0 - 0.35 - k * arrival.stagger) / 1.15))+ }+ function unfoldAlpha(k, T) {+ if (!arrival) return 1+ return clamp((T - arrival.t0 - 0.25 - k * arrival.stagger) / 0.3)+ }+ const zOf = (k, T) => -k * S * unfold(k, T)++ // ── glow from strings and recall ─────────────────────────────────────────────────────────────────++ function litGlow(k, T) {+ if (!pulled || !pulled.lit.has(k)) return 0+ if (reduced) return 0.85+ const at = pulled.t0 + Math.abs(k - pulled.origin) / WAVE+ if (T < at) return 0+ return 0.6 + 0.4 * Math.exp(-(T - at) / 0.6)+ }+ function hitGlow(k, T) {+ const n = recall.byDay.get(k)+ if (!n) return 0+ const strength = 0.5 + 0.5 * Math.min(1, n / 4)+ if (reduced) return strength+ const at = recall.t0 + Math.abs(k - recall.origin) / PULSE+ if (T < at) return 0+ return strength * (0.75 + 0.5 * Math.exp(-(T - at) / 0.45))+ }+ const recallOn = () => recall.q.trim().length >= 2++ // ── drawing ───────────────────────────────────────────────────────────────────────────────────────++ function render(T) {+ const t0 = performance.now()+ const trails = !reduced && (speed > 14 || (arrival && T - arrival.t0 > 0.4))+ ctx.globalCompositeOperation = 'source-over'+ ctx.globalAlpha = 1+ if (trails) { ctx.fillStyle = `rgba(6,6,8,${speed > 40 ? 0.36 : 0.5})`; ctx.fillRect(0, 0, vw, vh) }+ else { ctx.fillStyle = '#060608'; ctx.fillRect(0, 0, vw, vh) }+ if (!M) return++ // Light at the far end, where the past goes.+ if (p3(0, FLOOR + 0.45, -(cam.k + 140) * S)) {+ const g = ctx.createRadialGradient(PX, PY, 0, PX, PY, Math.max(vw, vh) * 0.42)+ g.addColorStop(0, 'rgba(244,197,108,0.075)'); g.addColorStop(0.4, 'rgba(244,197,108,0.02)'); g.addColorStop(1, 'rgba(244,197,108,0)')+ ctx.fillStyle = g; ctx.fillRect(0, 0, vw, vh)+ }++ const kNear = Math.max(0, Math.floor(cam.k) - 1)+ const kFar = Math.min(M.maxK, Math.ceil(Math.max(cam.k, 0) + 118))+ drawFloor(kNear, kFar, T)+ labelQueue.length = 0+ for (let k = kFar; k >= kNear; k--) drawDay(M.days[k], T)+ drawLabels()+ drawDust(T)+ drawPulse(T)+ drawPulled(T)+ drawFocus(T)+ drawAbout(T)+ ctx.globalCompositeOperation = 'source-over'+ ctx.globalAlpha = 1+ const ms = performance.now() - t0+ perf.frames++; perf.ms += ms; perf.worst = Math.max(perf.worst, ms)+ }++ // Dust hanging in the corridor: still when you stand, streaks when you fly.+ const DUST_SPAN = 26+ const dust = (() => {+ const random = rng(4242)+ return Array.from({ length: 260 }, () => ({ x: (random() * 2 - 1) * 1.05, y: FLOOR + 0.02 + random() * 1.3, k: random() * DUST_SPAN, r: 0.4 + random() * 0.9 }))+ })()+ function drawDust(T) {+ const base = cam.k - 1.2+ const dir = fly.active ? Math.sign(fly.to - fly.from) : 0+ const streak = reduced ? 0 : Math.min(2.2, speed * 0.035) * dir+ ctx.globalCompositeOperation = 'lighter'+ ctx.fillStyle = `rgb(${WARM})`; ctx.strokeStyle = `rgb(${WARM})`+ ctx.lineWidth = 1+ for (const m of dust) {+ const kk = base + ((((m.k - base) % DUST_SPAN) + DUST_SPAN) % DUST_SPAN)+ const rel = kk - cam.k+ const a = clamp((rel + 1.0) / 1.0) * Math.exp(-Math.max(0, rel) / 9) * (arrival ? unfoldAlpha(0, T) : 1)+ if (a < 0.02 || !p3(m.x, m.y, -kk * S)) continue+ const x = PX, y = PY, size = clamp(F / PD * 0.0022 * m.r, 0.4, 2.2)+ if (Math.abs(streak) > 0.05) {+ if (!p3(m.x, m.y, -(kk + streak) * S)) continue+ ctx.globalAlpha = a * 0.35+ ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(PX, PY); ctx.stroke()+ } else {+ ctx.globalAlpha = a * 0.3+ ctx.fillRect(x - size / 2, y - size / 2, size, size)+ }+ }+ ctx.globalCompositeOperation = 'source-over'+ }++ function dayAlpha(k, T) {+ const rel = k - cam.k+ const near = clamp((rel + 0.8) / 0.8)+ return near * Math.exp(-Math.max(0, rel) / FOG) * unfoldAlpha(k, T)+ }++ function drawFloor(kNear, kFar, T) {+ // Rails start just in front of the day you look at: days nearer than that are behind you.+ const kStart = Math.max(kNear, Math.ceil(cam.k - 0.25))+ const zn = -Math.max(0, cam.k - 0.25) * S + S * 0.3, zf = zOf(kFar, T)+ ctx.globalCompositeOperation = 'source-over'+ ctx.lineWidth = 1+ // Floor edges and the skyline (each side's top edge through every day: the rhythm of your weeks).+ for (const side of [-1, 1]) {+ if (p3(side * HW, FLOOR, zn)) {+ const ax = PX, ay = PY+ p3(side * HW, FLOOR, zf)+ const g = ctx.createLinearGradient(ax, ay, PX, PY)+ g.addColorStop(0, `rgba(${WARM},0.30)`); g.addColorStop(1, `rgba(${WARM},0)`)+ ctx.strokeStyle = g; ctx.globalAlpha = 1+ ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(PX, PY); ctx.stroke()+ }+ ctx.strokeStyle = `rgb(${WARM})`+ for (let k0 = kStart; k0 < kFar; k0 += 8) {+ const k1 = Math.min(kFar, k0 + 8)+ ctx.globalAlpha = 0.22 * dayAlpha(k0 + 4, T)+ if (ctx.globalAlpha < 0.004) continue+ ctx.beginPath()+ let started = false+ for (let k = k0; k <= k1; k++) {+ const day = M.days[k], z = zOf(k, T)+ if (!p3(side * HW, FLOOR + day.h, z)) { started = false; continue }+ if (!started) { ctx.moveTo(PX, PY); started = true } else ctx.lineTo(PX, PY)+ }+ ctx.stroke()+ }+ }+ // Project lanes along the floor: faint the whole way, bright on the days the project was busy.+ const levels = [0.05, 0.12, 0.22, 0.36, 0.55]+ const paths = levels.map(() => new Path2D())+ const focusLane = focus.item ? focus.item.lane : focus.lane+ for (const lane of M.lanes) {+ const x = -HW + 2 * HW * (lane.u0 + lane.u1) / 2+ if (p3(x, FLOOR, zn)) {+ const ax = PX, ay = PY+ p3(x, FLOOR, zf)+ const g = ctx.createLinearGradient(ax, ay, PX, PY)+ const base = lane.i === focusLane && mode === 'corridor' ? `rgba(${GOLD},0.34)` : `rgba(${WARM},0.075)`+ g.addColorStop(0, base); g.addColorStop(1, `rgba(${WARM},0)`)+ ctx.strokeStyle = g; ctx.globalAlpha = 1+ ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(PX, PY); ctx.stroke()+ }+ }+ for (let k = kStart; k <= Math.min(kFar, Math.floor(cam.k) + 70); k++) {+ const day = M.days[k]+ if (!day.askItems.length && !day.memItems.length) continue+ const a = dayAlpha(k, T)+ if (a < 0.02) continue+ const counts = new Map()+ for (const it of day.items) counts.set(it.lane, (counts.get(it.lane) ?? 0) + (it.type === 'mem' ? 3 : 1))+ const z = zOf(k, T)+ for (const [li, n] of counts) {+ const lane = M.lanes[li]+ const x = -HW + 2 * HW * (lane.u0 + lane.u1) / 2+ const v = a * (0.25 + 0.75 * Math.min(1, Math.sqrt(n / 12)))+ let lvl = 0+ while (lvl < levels.length - 1 && levels[lvl + 1] <= v) lvl+++ if (v < levels[0] * 0.6) continue+ if (!p3(x, FLOOR, z + S * 0.45)) continue+ const ax = PX, ay = PY+ if (!p3(x, FLOOR, z - S * 0.45)) continue+ paths[lvl].moveTo(ax, ay); paths[lvl].lineTo(PX, PY)+ }+ }+ ctx.globalCompositeOperation = 'lighter'+ ctx.strokeStyle = `rgb(${WARM})`+ ctx.lineWidth = 1.4+ levels.forEach((lvl, i) => { ctx.globalAlpha = lvl; ctx.stroke(paths[i]) })+ ctx.globalCompositeOperation = 'source-over'+ // The end of the corridor: the first day anything was said or written down.+ if (kFar === M.maxK && !arrival) {+ const k = M.maxK + 1.4+ const a = dayAlpha(k, T)+ if (a > 0.04 && p3(0, FLOOR + 0.02, -k * S)) {+ const size = clamp(F / PD * 0.045, 0, 13)+ if (size >= 6.5) {+ ctx.font = `${size.toFixed(1)}px ${MONO}`+ ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'+ ctx.fillStyle = `rgb(${GOLD})`; ctx.globalAlpha = 0.55 * a+ const first = M.days[M.maxK]+ ctx.fillText(`WHERE YOUR MEMORY BEGINS · ${fmtDate(first.t).toUpperCase()}`, PX, PY)+ }+ }+ }+ // Quiet stretches are written on the floor.+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle'+ for (const st of M.stretches) {+ if (st.to < Math.max(kNear, cam.k + 1) || st.from > kFar) continue+ const k = clamp(st.mid, Math.max(kNear, cam.k + 1.5), kFar)+ const a = dayAlpha(k, T)+ if (a < 0.05 || !p3(0, FLOOR, zOf(k, T))) continue+ const size = clamp(F / PD * 0.05, 0, 14)+ if (size < 7) continue+ ctx.font = `${size.toFixed(1)}px ${MONO}`+ ctx.fillStyle = `rgba(${WARM},${(0.5 * a).toFixed(3)})`+ ctx.fillText(`${st.n} quiet days`.toUpperCase().split('').join(' '), PX, PY - size * 0.9)+ }+ }++ function drawDay(day, T) {+ const k = day.k+ const a = dayAlpha(k, T)+ if (a < 0.006) return+ const z = zOf(k, T)+ const od = plane(z)+ if (od < NEAR * 2) return+ const sc = F / od // pixels per world unit on this frame+ const h = arrival ? lerp(0.13, day.h, unfold(k, T)) : day.h+ const top = FLOOR + h+ const lit = litGlow(k, T), hit = hitGlow(k, T)+ const isFocus = k === focus.k && mode === 'corridor' && !arrival+ const strong = Math.max(lit, hit)+ const tint = lit >= hit && lit > 0 ? GOLD : hit > 0 ? COOL : WARM+ const lw = clamp(sc * 0.0019, 0.5, 1.6) * (day.dow === 1 ? 1.9 : 1)++ // Month gate, between the first of a month and the month before it.+ if (day.dom === 1 && k < M.maxK) drawGate(day, T, a)++ ctx.globalCompositeOperation = 'source-over'+ // The frame, a doorway with no sill: sides and lintel.+ ps(-HW, FLOOR); const blx = PX, bly = PY+ ps(-HW, top); const tlx = PX, tly = PY+ ps(HW, top); const trx = PX, try_ = PY+ ps(HW, FLOOR); const brx = PX, bry = PY+ if (strong > 0) {+ ctx.globalAlpha = a * 0.028 * strong+ ctx.fillStyle = `rgb(${tint})`+ ctx.beginPath(); ctx.moveTo(blx, bly); ctx.lineTo(tlx, tly); ctx.lineTo(trx, try_); ctx.lineTo(brx, bry); ctx.closePath(); ctx.fill()+ }+ ctx.globalAlpha = clamp(a * ((day.quiet ? 0.2 : 0.2 + 0.42 * day.bright) + 0.62 * strong + (isFocus ? 0.3 : 0)))+ ctx.strokeStyle = `rgb(${strong > 0 ? tint : isFocus ? WHITE : WARM})`+ ctx.lineWidth = lw * (strong > 0 ? 1.5 : 1)+ if (day.quiet) ctx.setLineDash([2, 5])+ ctx.beginPath(); ctx.moveTo(blx, bly); ctx.lineTo(tlx, tly); ctx.lineTo(trx, try_); ctx.lineTo(brx, bry); ctx.stroke()+ if (day.quiet) ctx.setLineDash([])+ if (strong > 0) {+ ctx.globalCompositeOperation = 'lighter'+ ctx.globalAlpha = a * 0.22 * strong+ ctx.lineWidth = lw * 7+ ctx.stroke()+ ctx.globalCompositeOperation = 'source-over'+ ctx.lineWidth = lw+ }+ // The floor line of the frame: the shelf the books stand on.+ ctx.globalAlpha = a * (0.1 + 0.2 * day.bright)+ ctx.beginPath(); ctx.moveTo(blx, bly); ctx.lineTo(brx, bry); ctx.stroke()++ const hpx = sc * h+ const dim = (pulled || recallOn()) ? 0.28 : 1+ ctx.globalCompositeOperation = 'lighter'+ // Older messages that are counted but not loaded here: a faint haze of their colours.+ if (day.ghosts && hpx > 3) {+ const wpx = sc * 2 * HW+ const stride = Math.max(1, Math.ceil(day.ghostN / Math.max(8, wpx / 2.4)))+ ctx.lineWidth = clamp(sc * 0.0016, 0.5, 1.2)+ for (const g of day.ghosts) {+ ctx.strokeStyle = g.color+ ctx.globalAlpha = a * 0.2 * dim+ ctx.beginPath()+ for (let i = 0; i < g.xs.length; i += stride) {+ ps(g.xs[i], top); ctx.moveTo(PX, PY)+ ps(g.xs[i], top - g.hs[i] * h); ctx.lineTo(PX, PY)+ }+ ctx.stroke()+ }+ }+ // Your messages, hanging from the lintel.+ if (day.groups.length && hpx > 2.5) {+ const wpx = sc * 2 * HW+ const stride = Math.max(1, Math.ceil(day.asks / Math.max(14, wpx / 1.25)))+ const slw = clamp(sc * 0.0021, 0.55, 1.8)+ const glow = sc > 230+ const crowd = clamp(1.7 / Math.sqrt(Math.max(1, day.asks) / 18), 0.32, 1)+ const sa = a * (0.5 + 0.4 * clamp(sc / 500)) * dim * crowd+ for (const g of day.groups) {+ ctx.strokeStyle = g.color+ ctx.beginPath()+ for (let i = 0; i < g.items.length; i += stride) {+ const it = g.items[i]+ ps(it.x, top); ctx.moveTo(PX, PY)+ ps(it.x, top - it.hang * h * 0.86); ctx.lineTo(PX, PY)+ }+ if (glow) { ctx.globalAlpha = sa * 0.17; ctx.lineWidth = slw * 3.6; ctx.stroke() }+ ctx.globalAlpha = sa; ctx.lineWidth = slw; ctx.stroke()+ }+ // A bead of light at each tip, close up.+ if (sc > 330) {+ for (const g of day.groups) {+ ctx.fillStyle = g.color; ctx.globalAlpha = sa * 0.9+ for (let i = 0; i < g.items.length; i += stride) {+ const it = g.items[i]+ ps(it.x, top - it.hang * h * 0.86)+ ctx.fillRect(PX - slw, PY - slw * 0.5, slw * 2, slw * 2)+ }+ }+ }+ }+ // Strands a pulled string or a recall touches.+ const marked = []+ if (pulled && lit > 0) for (const it of pulled.lit.get(k) ?? []) marked.push([it, GOLD, lit])+ if (hit > 0) for (const it of day.items) if (recall.set.has(it)) marked.push([it, COOL, hit])+ if (marked.length) {+ const slw = clamp(sc * 0.0026, 0.8, 2.4)+ for (const [it, color, g] of marked) {+ if (it.type === 'mem') continue+ const tipY = top - (it.hang ?? 0.3) * h * 0.86+ ps(it.x, top); const x0 = PX, y0 = PY+ ps(it.x, tipY)+ ctx.strokeStyle = `rgb(${color})`+ ctx.globalAlpha = a * 0.22 * g; ctx.lineWidth = slw * 4+ ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(PX, PY); ctx.stroke()+ ctx.globalAlpha = a * 0.95 * g; ctx.lineWidth = slw+ ctx.stroke()+ }+ }+ ctx.globalCompositeOperation = 'source-over'++ // Memories written that day: books on the floor.+ if (day.memItems.length && sc * BOOK_H > 1.2) {+ for (const it of day.memItems) {+ const pop = it === focus.item && mode === 'corridor' ? 1 : 0+ if (pop) continue // drawn by drawFocus, pulled out of the shelf+ const touched = (pulled && pulled.set.has(it) && lit > 0) || (recall.set.has(it) && hit > 0)+ drawBook(it, a, sc, touched ? (pulled && pulled.set.has(it) ? GOLD : COOL) : null, z)+ }+ }++ // Labels: the date over the lintel, close up; Mondays carry their week far away.+ const rel = k - cam.k+ if (!arrival || unfoldAlpha(k, T) > 0.9) {+ const size = clamp(sc * 0.042, 0, 14)+ const weekday = day.dow === 1+ if (size >= 6.5 && (rel < 10 || weekday || k === 0)) {+ const label = k === 0 ? 'TODAY' : rel < 10 ? `${WD[day.dow]} ${day.dom}`.toUpperCase() : `W${isoWeek(day.date)}`+ ps(-HW, top)+ labelQueue.push({ rel, size, label, x: PX + 1, y: PY - size * 0.45, alpha: clamp(a * (isFocus ? 1 : 0.55 + 0.4 * strong)),+ color: isFocus ? WHITE : strong > 0 ? tint : WARM, week: weekday && rel < 10 && size >= 9 ? `W${isoWeek(day.date)}` : null })+ }+ }+ }++ const labelQueue = []+ function drawLabels() {+ labelQueue.sort((a, b) => a.rel - b.rel)+ const placed = []+ ctx.globalCompositeOperation = 'source-over'+ ctx.textAlign = 'left'; ctx.textBaseline = 'bottom'+ for (const l of labelQueue) {+ ctx.font = `${l.size.toFixed(1)}px ${MONO}`+ const w = ctx.measureText(l.label).width+ const box = [l.x - 2, l.y - l.size * (l.week ? 2.3 : 1.15), l.x + w + 4, l.y + 2]+ if (placed.some((b) => box[0] < b[2] && box[2] > b[0] && box[1] < b[3] && box[3] > b[1])) continue+ placed.push(box)+ ctx.globalAlpha = l.alpha+ ctx.fillStyle = `rgb(${l.color})`+ ctx.fillText(l.label, l.x, l.y)+ if (l.week) { ctx.globalAlpha = l.alpha * 0.6; ctx.fillText(l.week, l.x, l.y - l.size * 1.15) }+ }+ }++ function drawBook(it, a, sc, touched, z) {+ const x0 = it.x - BOOK_W / 2, x1 = it.x + BOOK_W / 2+ ps(x0, FLOOR); const ax = PX, ay = PY+ ps(x1, FLOOR + BOOK_H); const bx = PX, by = PY+ const w = Math.max(1, bx - ax), hgt = ay - by+ ctx.globalAlpha = a * 0.92+ ctx.fillStyle = touched ? `rgb(${touched})` : '#efe3c8'+ ctx.fillRect(ax, by, w, hgt)+ ctx.fillStyle = it.color+ ctx.fillRect(ax, by, w, Math.max(1, hgt * 0.16))+ if (touched) {+ ctx.globalCompositeOperation = 'lighter'+ ctx.globalAlpha = a * 0.28+ ctx.fillStyle = `rgb(${touched})`+ ctx.fillRect(ax - w, by - w, w * 3, hgt + w * 2)+ ctx.globalCompositeOperation = 'source-over'+ }+ if (hgt > 54 && w > 7) {+ ctx.save()+ ctx.translate(ax + w / 2, ay - hgt * 0.22)+ ctx.rotate(-Math.PI / 2)+ ctx.font = `${clamp(w * 0.62, 7, 11).toFixed(1)}px ${MONO}`+ ctx.textAlign = 'left'; ctx.textBaseline = 'middle'+ ctx.fillStyle = '#2a241b'; ctx.globalAlpha = a+ ctx.beginPath(); ctx.rect(0, -w / 2, hgt * 0.62, w); ctx.clip()+ ctx.fillText(String(it.m.title ?? ''), 0, 0.5)+ ctx.restore()+ }+ }++ function drawGate(day, T, a) {+ const z = zOf(day.k, T) - S * 0.5+ const od = plane(z)+ if (od < NEAR * 2) return+ const sc = F / od+ const gh = 1.36, gw = HW + 0.07, pw = 0.028+ const alpha = clamp(a * 1.25)+ ctx.globalCompositeOperation = 'source-over'+ ctx.strokeStyle = `rgb(${WARM})`+ ctx.fillStyle = `rgb(${WARM})`+ ctx.lineWidth = clamp(sc * 0.002, 0.5, 1.4)+ for (const side of [-1, 1]) {+ const x0 = side * gw, x1 = side * (gw + pw)+ ps(Math.min(x0, x1), FLOOR); const ax = PX, ay = PY+ ps(Math.max(x0, x1), FLOOR + gh); const bx = PX, by = PY+ ctx.globalAlpha = alpha * 0.13; ctx.fillRect(ax, by, bx - ax, ay - by)+ ctx.globalAlpha = alpha * 0.62; ctx.strokeRect(ax, by, bx - ax, ay - by)+ }+ ps(-(gw + pw * 2.2), FLOOR + gh); const lx = PX, ly = PY+ ps(gw + pw * 2.2, FLOOR + gh + 0.036); const rx = PX, ry = PY+ ctx.globalAlpha = alpha * 0.14; ctx.fillRect(lx, ry, rx - lx, ly - ry)+ ctx.globalAlpha = alpha * 0.6; ctx.strokeRect(lx, ry, rx - lx, ly - ry)+ const size = clamp(sc * 0.08, 0, 26)+ if (size >= 6) {+ const older = M.days[day.k + 1]+ ctx.font = `${size.toFixed(1)}px ${MONO}`+ ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'+ ctx.globalAlpha = alpha * 0.85+ ctx.fillStyle = `rgb(${GOLD})`+ ps(0, FLOOR + gh + 0.05)+ const name = MONTHS[older.month].toUpperCase().split('').join(size > 12 ? ' ' : ' ')+ ctx.fillText(name, PX, PY)+ if (size >= 10) {+ ctx.font = `${(size * 0.5).toFixed(1)}px ${MONO}`+ ctx.globalAlpha = alpha * 0.5+ ctx.fillStyle = `rgb(${WARM})`+ ctx.fillText(String(older.year), PX, PY - size * 1.15)+ }+ }+ }++ function drawPulse(T) {+ if (!recallOn() || reduced) return+ const t = T - recall.t0+ if (t > 2.6) return+ const fade = 1 - t / 2.6+ for (const dir of [1, -1]) {+ const k = recall.origin + dir * t * PULSE+ if (k < 0 || k > M.maxK || k < cam.k - 0.5) continue+ const od = plane(-k * S)+ if (od < NEAR * 2) continue+ const h = 1.2+ ps(-HW - 0.03, FLOOR); const ax = PX, ay = PY+ ps(HW + 0.03, FLOOR + h)+ ctx.globalCompositeOperation = 'lighter'+ ctx.strokeStyle = `rgb(${COOL})`+ ctx.lineWidth = 1.5+ ctx.globalAlpha = 0.5 * fade * Math.exp(-Math.max(0, k - cam.k) / (FOG * 1.4))+ ctx.strokeRect(ax, PY, PX - ax, ay - PY)+ }+ ctx.globalCompositeOperation = 'source-over'+ }++ function drawPulled(T) {+ if (!pulled || !pulled.path.length) return+ const pts = pulled.path+ const levels = [0.08, 0.2, 0.4, 0.65, 0.95]+ const glowPaths = levels.map(() => new Path2D()), corePaths = levels.map(() => new Path2D()), sidePaths = levels.map(() => new Path2D())+ const t = T+ // Three threads braided between the knots, each with its own phase, like the film's golden strings.+ const BRAID = [[0, 0, 1], [0.009, 2.1, 0.85], [-0.009, 4.2, 0.85]]+ const segPoint = (A, B, s, b, out) => {+ const kk = lerp(A.k, B.k, s)+ const span = Math.abs(B.k - A.k)+ const [off, phase, ampK] = BRAID[b]+ const open = Math.sin(Math.PI * s) * Math.min(1, span / 3)+ let y = lerp(A.y, B.y, s) - Math.sin(Math.PI * s) * Math.min(0.09, 0.012 * span) + off * open * Math.cos(kk * 3.1 + phase)+ let x = lerp(A.x, B.x, s) + off * open * Math.sin(kk * 3.1 + phase)+ const at = pulled.t0 + Math.abs(kk - pulled.origin) / WAVE+ const on = reduced || t >= at+ if (on && !reduced) {+ const amp = (0.05 * Math.exp(-(t - at) / 0.7) + 0.0035) * ampK+ y += amp * Math.sin(kk * 1.9 - t * 15 + phase)+ x += amp * 0.35 * Math.cos(kk * 1.3 - t * 11 + phase)+ }+ out.on = on; out.k = kk+ const ok = p3(x, y, lerp(A.z, B.z, s))+ out.x = PX; out.y = PY; out.ok = ok+ return out+ }+ const q0 = {}, q1 = {}+ const single = pts.length === 1+ const list = single ? [pts[0], { ...pts[0], y: pts[0].y + 0.001 }] : pts+ for (let b = 0; b < BRAID.length; b++) {+ for (let i = 0; i + 1 < list.length; i++) {+ const A = list[i], B = list[i + 1]+ const n = Math.round(clamp(Math.abs(B.k - A.k) * 1.6, 6, 52))+ segPoint(A, B, 0, b, q0)+ for (let j = 1; j <= n; j++) {+ segPoint(A, B, j / n, b, q1)+ if (q0.ok && q1.ok) {+ const fog = Math.exp(-Math.max(0, q1.k - cam.k) / FOG) * clamp((q1.k - cam.k + 0.55) / 0.6)+ const v = PD > 0.32 ? (q1.on ? 0.95 : 0.12) * fog : 0+ let lvl = 0+ while (lvl < levels.length - 1 && levels[lvl + 1] <= v) lvl+++ if (v > 0.03) {+ if (b === 0) {+ glowPaths[lvl].moveTo(q0.x, q0.y); glowPaths[lvl].lineTo(q1.x, q1.y)+ corePaths[lvl].moveTo(q0.x, q0.y); corePaths[lvl].lineTo(q1.x, q1.y)+ } else { sidePaths[lvl].moveTo(q0.x, q0.y); sidePaths[lvl].lineTo(q1.x, q1.y) }+ }+ }+ q0.x = q1.x; q0.y = q1.y; q0.ok = q1.ok; q0.k = q1.k; q0.on = q1.on+ }+ }+ }+ ctx.globalCompositeOperation = 'lighter'+ ctx.strokeStyle = `rgb(${GOLD})`+ levels.forEach((lvl, i) => {+ ctx.globalAlpha = lvl * 0.2; ctx.lineWidth = 6; ctx.stroke(glowPaths[i])+ ctx.globalAlpha = lvl * 0.5; ctx.lineWidth = 0.8; ctx.stroke(sidePaths[i])+ ctx.globalAlpha = lvl; ctx.lineWidth = 1.3; ctx.stroke(corePaths[i])+ })+ // Knots where the string touches a day.+ ctx.fillStyle = `rgb(${GOLD})`+ for (const p of pts) {+ const at = reduced ? -Infinity : pulled.t0 + Math.abs(p.k - pulled.origin) / WAVE+ if (T < at || !p3(p.x, p.y, p.z)) continue+ const r = clamp(F / PD * 0.006, 1, 4)+ const fog = Math.exp(-Math.max(0, p.k - cam.k) / FOG) * clamp((p.k - cam.k + 0.55) / 0.6)+ if (PD < 0.32 || fog < 0.01) continue+ ctx.globalAlpha = 0.9 * fog+ ctx.beginPath(); ctx.arc(PX, PY, r, 0, Math.PI * 2); ctx.fill()+ if (!reduced) {+ const flare = Math.exp(-(T - at) / 0.5)+ if (flare > 0.02) { ctx.globalAlpha = 0.5 * flare * fog; ctx.beginPath(); ctx.arc(PX, PY, r * 5, 0, Math.PI * 2); ctx.fill() }+ }+ }+ ctx.globalCompositeOperation = 'source-over'+ }++ function drawFocus(T) {+ if (mode !== 'corridor' || arrival || !M) return+ const day = M.days[focus.k]+ const a = dayAlpha(focus.k, T)+ if (a < 0.05) return+ const z = zOf(focus.k, T)+ const od = plane(z)+ if (od < NEAR * 2) return+ const sc = F / od+ const top = FLOOR + day.h+ // The lane you stand in, as a faint band of light through this day.+ const laneI = focus.item ? focus.item.lane : focus.lane+ const lane = M.lanes[laneI]+ if (lane) {+ const x0 = -HW + 2 * HW * lane.u0, x1 = -HW + 2 * HW * lane.u1+ ps(x0, FLOOR); const ax = PX, ay = PY+ ps(x1, top); const bx = PX, by = PY+ ctx.globalCompositeOperation = 'lighter'+ ctx.globalAlpha = 0.045 * a+ ctx.fillStyle = `rgb(${GOLD})`+ ctx.fillRect(ax, by, bx - ax, ay - by)+ ctx.globalCompositeOperation = 'source-over'+ // Lane names on the floor, and the hours of the day under the lane you are in.+ ctx.textBaseline = 'top'; ctx.textAlign = 'center'+ ctx.font = `10px ${MONO}`+ const labels = []+ for (const l of M.lanes) {+ ps(-HW + 2 * HW * l.u0, FLOOR); const lx0 = PX+ ps(-HW + 2 * HW * l.u1, FLOOR); const lx1 = PX+ const mine = l.i === laneI+ let name = l.name+ const room = lx1 - lx0 - 6+ let w = ctx.measureText(name).width+ if (!mine && w > room) {+ if (room < 30) continue+ while (name.length > 3 && ctx.measureText(name + '…').width > room) name = name.slice(0, -1)+ name += '…'; w = ctx.measureText(name).width+ }+ labels.push({ name, cx: clamp((lx0 + lx1) / 2, w / 2 + 4, vw - w / 2 - 4), w, mine })+ }+ const taken = []+ const ly = PY + 8+ for (const lb of [...labels.filter((l) => l.mine), ...labels.filter((l) => !l.mine)]) {+ const x0 = lb.cx - lb.w / 2 - 7, x1 = lb.cx + lb.w / 2 + 7+ if (!lb.mine && taken.some(([a, b]) => x0 < b && x1 > a)) continue+ taken.push([x0, x1])+ ctx.globalAlpha = lb.mine ? 0.95 * a : 0.4 * a+ ctx.fillStyle = lb.mine ? `rgb(${GOLD})` : `rgb(${WARM})`+ ctx.fillText(lb.name, lb.cx, ly)+ }+ ps(x0, FLOOR); const hx0 = PX, hy = PY+ ps(x1, FLOOR); const hx1 = PX+ const pad = Math.min(0.006, (lane.u1 - lane.u0) * 0.1) * 2 * HW * sc+ ctx.strokeStyle = `rgb(${GOLD})`; ctx.lineWidth = 1+ ctx.font = `9px ${MONO}`; ctx.textBaseline = 'bottom'+ for (let hr = 0; hr <= 24; hr += 6) {+ const x = hx0 + pad + (hx1 - hx0 - 2 * pad) * hr / 24+ ctx.globalAlpha = 0.5 * a+ ctx.beginPath(); ctx.moveTo(x, hy); ctx.lineTo(x, hy + 4); ctx.stroke()+ if (hx1 - hx0 > 150 && hr > 0 && hr < 24) { ctx.globalAlpha = 0.45 * a; ctx.fillStyle = `rgb(${GOLD})`; ctx.fillText(String(hr).padStart(2, '0'), x, hy - 2) }+ }+ }+ const it = focus.item+ if (!it) return+ ctx.globalCompositeOperation = 'lighter'+ if (it.type === 'mem') {+ // The focused book slides out of the shelf toward you.+ plane(z + 0.07)+ const x0 = it.x - BOOK_W * 0.6, x1 = it.x + BOOK_W * 0.6+ ctx.globalCompositeOperation = 'source-over'+ plane(z); ps(x0, FLOOR); const bax = PX, bay = PY; ps(x1, FLOOR + BOOK_H * 1.05); const bbx = PX, bby = PY+ plane(z + 0.07); ps(x0, FLOOR); const fax = PX, fay = PY; ps(x1, FLOOR + BOOK_H * 1.05); const fbx = PX, fby = PY+ ctx.globalAlpha = a+ ctx.fillStyle = '#8c7d63'+ ctx.beginPath(); ctx.moveTo(bax, bby); ctx.lineTo(bbx, bby); ctx.lineTo(fbx, fby); ctx.lineTo(fax, fby); ctx.closePath(); ctx.fill()+ ctx.fillStyle = '#b9a988'+ ctx.beginPath(); ctx.moveTo(bbx, bby); ctx.lineTo(bbx, bay); ctx.lineTo(fbx, fay); ctx.lineTo(fbx, fby); ctx.closePath(); ctx.fill()+ const fake = { ...it, x: it.x }+ plane(z + 0.07)+ const scF = F / P.od+ ctx.save()+ drawBookAt(fake, a, scF, x0, x1, BOOK_H * 1.05)+ ctx.restore()+ ctx.globalCompositeOperation = 'lighter'+ ctx.strokeStyle = `rgb(${WHITE})`; ctx.lineWidth = 1.5; ctx.globalAlpha = 0.9 * a+ ctx.strokeRect(fax - 2, fby - 2, fbx - fax + 4, fay - fby + 4)+ ctx.fillStyle = `rgb(${WHITE})`+ caret(fax + (fbx - fax) / 2, fby - 8, a)+ } else {+ plane(z)+ const tipY = top - (it.hang ?? 0.3) * day.h * 0.86+ ps(it.x, top); const x0 = PX, y0 = PY+ ps(it.x, tipY)+ const w = clamp(sc * 0.004, 1.2, 3)+ ctx.strokeStyle = `rgb(${WHITE})`+ ctx.globalAlpha = 0.25 * a; ctx.lineWidth = w * 5+ ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(PX, PY); ctx.stroke()+ ctx.globalAlpha = a; ctx.lineWidth = w+ ctx.stroke()+ ctx.fillStyle = `rgb(${WHITE})`+ ctx.beginPath(); ctx.arc(PX, PY, w * 1.8, 0, Math.PI * 2); ctx.fill()+ ctx.globalAlpha = 0.35 * a+ ctx.beginPath(); ctx.arc(PX, PY, w * 5, 0, Math.PI * 2); ctx.fill()+ caret(x0, y0 - 6, a)+ }+ ctx.globalCompositeOperation = 'source-over'+ }++ function drawBookAt(it, a, sc, x0, x1, bh) {+ ps(x0, FLOOR); const ax = PX, ay = PY+ ps(x1, FLOOR + bh); const bx = PX, by = PY+ const w = Math.max(1, bx - ax), hgt = ay - by+ ctx.globalCompositeOperation = 'source-over'+ ctx.globalAlpha = a+ ctx.fillStyle = '#fff4dc'+ ctx.fillRect(ax, by, w, hgt)+ ctx.fillStyle = it.color+ ctx.fillRect(ax, by, w, Math.max(1, hgt * 0.16))+ if (hgt > 40 && w > 6) {+ ctx.translate(ax + w / 2, ay - hgt * 0.2)+ ctx.rotate(-Math.PI / 2)+ ctx.font = `${clamp(w * 0.6, 7, 11).toFixed(1)}px ${MONO}`+ ctx.textAlign = 'left'; ctx.textBaseline = 'middle'+ ctx.fillStyle = '#2a241b'+ ctx.beginPath(); ctx.rect(0, -w / 2, hgt * 0.64, w); ctx.clip()+ ctx.fillText(String(it.m.title ?? ''), 0, 0.5)+ }+ }++ function caret(x, y, a) {+ ctx.globalAlpha = 0.9 * a+ ctx.beginPath(); ctx.moveTo(x - 4, y - 5); ctx.lineTo(x + 4, y - 5); ctx.lineTo(x, y); ctx.closePath(); ctx.fill()+ }++ // ── About You: the window at the mouth of the corridor ───────────────────────────────────────────++ function layoutAboutBars() {+ // A model of the window's text for the canvas (bars) and for string anchors: two columns of lines.+ const rows = M.aboutLines+ const bars = [], ends = []+ if (!rows.length) { aboutBars = { bars, ends }; return }+ const colW = 0.44, x0s = [0.04, 0.53]+ const heights = rows.map((r) => Math.ceil(r.line.text.length / 62))+ const sections = []+ rows.forEach((r, i) => { if (!sections.length || sections[sections.length - 1].name !== r.line.section) sections.push({ name: r.line.section, rows: [] }); sections[sections.length - 1].rows.push(i) })+ const totalRows = heights.reduce((s, h) => s + h, 0) + sections.length * 1.6+ const rowH = Math.min(0.034, 0.8 / (totalRows / 2))+ let col = 0, v = 0.14+ for (const sec of sections) {+ const need = sec.rows.reduce((s, i) => s + heights[i], 0) * rowH + rowH * 1.6+ if (v + need > 0.95 && col === 0) { col = 1; v = 0.14 }+ bars.push({ u0: x0s[col], u1: x0s[col] + 0.12, v, head: true })+ v += rowH * 1.4+ for (const i of sec.rows) {+ const len = rows[i].line.text.length+ for (let r = 0; r < heights[i]; r++) {+ const frac = r < heights[i] - 1 ? 1 : ((len % 62) || 62) / 62+ bars.push({ u0: x0s[col], u1: x0s[col] + colW * frac, v, line: i })+ if (r === heights[i] - 1) ends[i] = { u: x0s[col] + colW * frac + 0.01, v }+ v += rowH+ }+ }+ v += rowH * 0.6+ }+ aboutBars = { bars, ends }+ }+ function aboutFrom(i) {+ // Where the line sits on the glass, from the panel's own layout when you stand at the window.+ const r = aboutRects?.[i]+ if (r && aboutOpacity > 0.5 && !arrival) {+ const d = camZ - ABOUT_Z+ return { x: cam.x + (r.x - OX) * d / F, y: cam.y - (r.y - OY) * d / F, z: ABOUT_Z }+ }+ return aboutPoint(i)+ }+ function aboutPoint(i) {+ const e = aboutBars?.ends[i] ?? { u: 0.5, v: 0.5 }+ return { x: -AHW + 2 * AHW * e.u, y: FLOOR + AH * (1 - e.v), z: ABOUT_Z }+ }++ function drawAbout(T) {+ const od = plane(ABOUT_Z)+ const a = arrival ? 0 : clamp((od - 0.28) / 0.45)+ const want = mode === 'about' && !arrival ? clamp(1 - Math.abs(cam.k - STATION) / 0.9) : 0+ setAboutOpacity(want)+ if (a < 0.01) return+ const sc = F / od+ ps(-AHW, FLOOR); const ax = PX, ay = PY+ ps(AHW, FLOOR + AH); const bx = PX, by = PY+ ctx.globalCompositeOperation = 'source-over'+ // Glass: a little darker than the corridor behind it.+ ctx.globalAlpha = a * 0.35+ ctx.fillStyle = '#050506'+ ctx.fillRect(ax, by, bx - ax, ay - by)+ ctx.strokeStyle = `rgb(${GOLD})`+ ctx.lineWidth = clamp(sc * 0.0025, 0.6, 2)+ ctx.globalAlpha = a * 0.55+ ctx.strokeRect(ax, by, bx - ax, ay - by)+ const inset = 0.028 * sc+ ctx.globalAlpha = a * 0.22+ ctx.strokeRect(ax + inset, by + inset, bx - ax - inset * 2, ay - by - inset * 2)+ // Corner joints.+ ctx.globalAlpha = a * 0.8+ const cl = 0.07 * sc+ ctx.beginPath()+ for (const [x, y, dx, dy] of [[ax, by, 1, 1], [bx, by, -1, 1], [ax, ay, 1, -1], [bx, ay, -1, -1]]) {+ ctx.moveTo(x + dx * cl, y); ctx.lineTo(x, y); ctx.lineTo(x, y + dy * cl)+ }+ ctx.stroke()+ // Writing on the glass, seen from afar (the readable text is the DOM panel when you stand here).+ const textA = a * (1 - aboutOpacity)+ if (textA > 0.02 && aboutBars) {+ ctx.globalAlpha = textA * 0.5+ ctx.lineWidth = clamp(sc * 0.006, 0.6, 3)+ ctx.lineCap = 'round'+ ctx.beginPath()+ ctx.strokeStyle = `rgb(${WARM})`+ for (const b of aboutBars.bars) {+ if (b.head) continue+ ps(-AHW + 2 * AHW * b.u0, FLOOR + AH * (1 - b.v)); ctx.moveTo(PX, PY)+ ps(-AHW + 2 * AHW * b.u1, FLOOR + AH * (1 - b.v)); ctx.lineTo(PX, PY)+ }+ ctx.stroke()+ ctx.strokeStyle = `rgb(${GOLD})`+ ctx.globalAlpha = textA * 0.7+ ctx.beginPath()+ for (const b of aboutBars.bars) {+ if (!b.head) continue+ ps(-AHW + 2 * AHW * b.u0, FLOOR + AH * (1 - b.v)); ctx.moveTo(PX, PY)+ ps(-AHW + 2 * AHW * b.u1, FLOOR + AH * (1 - b.v)); ctx.lineTo(PX, PY)+ }+ ctx.stroke()+ ctx.lineCap = 'butt'+ const size = clamp(sc * 0.05, 0, 18)+ if (size > 6) {+ ctx.font = `${size.toFixed(1)}px ${MONO}`+ ctx.textAlign = 'left'; ctx.textBaseline = 'bottom'+ ctx.fillStyle = `rgb(${GOLD})`; ctx.globalAlpha = textA * 0.9+ ps(-AHW + 2 * AHW * 0.04, FLOOR + AH * (1 - 0.075))+ ctx.fillText('A B O U T Y O U', PX, PY)+ }+ }+ // Along the sill: every day of the corridor as one horizon, the rhythm About You was built from.+ drawHorizon(a)+ // Threads from each belief back into the corridor, to the memories it stands on.+ drawBeliefThreads(T, a)+ }++ function drawHorizon(a) {+ const n = M.maxK+ if (n < 2) return+ const u0 = 0.035, u1 = 0.965, base = 0.955, amp = 0.085+ const at = (k, lift) => ps(-AHW + 2 * AHW * (u0 + (u1 - u0) * (1 - k / n)), FLOOR + AH * (1 - base) + AH * amp * lift)+ ctx.globalCompositeOperation = 'lighter'+ ctx.beginPath()+ at(n, 0); ctx.moveTo(PX, PY)+ for (let k = n; k >= 0; k--) { at(k, M.days[k].quiet ? 0 : 0.08 + 0.92 * M.days[k].bright); ctx.lineTo(PX, PY) }+ at(0, 0); ctx.lineTo(PX, PY); ctx.closePath()+ ctx.fillStyle = `rgb(${GOLD})`; ctx.globalAlpha = a * 0.07; ctx.fill()+ ctx.strokeStyle = `rgb(${GOLD})`; ctx.globalAlpha = a * 0.45; ctx.lineWidth = 1; ctx.stroke()+ // Months under the horizon, and a mark where you stand.+ ctx.globalCompositeOperation = 'source-over'+ at(0, 0); const size = clamp((F / PD) * 0.022, 0, 10)+ if (size >= 7) {+ ctx.font = `${size.toFixed(1)}px ${MONO}`; ctx.textAlign = 'left'; ctx.textBaseline = 'top'+ ctx.fillStyle = `rgb(${WARM})`; ctx.globalAlpha = a * 0.45+ for (const day of M.days) {+ if (day.dom !== 1 || day.k < n * 0.06) continue+ at(day.k, 0); ctx.fillRect(PX, PY, 1, 4); ctx.fillText(MON[day.month].toUpperCase(), PX + 3, PY + 2)+ }+ at(0, 0); ctx.textAlign = 'right'; ctx.fillStyle = `rgb(${GOLD})`; ctx.globalAlpha = a * 0.7+ ctx.fillText('TODAY', PX, PY + 2)+ }+ }++ function drawBeliefThreads(T, a) {+ if (!aboutBars || !M.aboutLines.length) return+ ctx.globalCompositeOperation = 'lighter'+ const useDom = aboutOpacity > 0.5 && aboutRects+ for (const row of M.aboutLines) {+ if (!row.cited.length) continue+ const sel = mode === 'about' && row.i === aboutSel+ let sx, sy+ if (useDom) { const r = aboutRects[row.i]; if (!r) continue; sx = r.x; sy = r.y } else {+ const p = aboutPoint(row.i)+ if (!p3(p.x, p.y, p.z)) continue+ sx = PX; sy = PY+ }+ for (const mem of row.cited) {+ const pt = anchorPoint(mem)+ if (!p3(pt.x, pt.y, zOf(mem.k, T))) continue+ const fog = Math.exp(-Math.max(0, mem.k - cam.k) / FOG)+ ctx.strokeStyle = sel ? `rgb(${GOLD})` : `rgb(${WARM})`+ ctx.globalAlpha = a * (sel ? 0.75 : mode === 'about' ? 0.09 : 0.05) * (0.4 + 0.6 * fog)+ ctx.lineWidth = sel ? 1.3 : 0.8+ const cx = lerp(sx, OX, 0.55), cy = lerp(sy, OY, 0.2)+ ctx.beginPath(); ctx.moveTo(sx, sy); ctx.quadraticCurveTo(cx, cy, PX, PY); ctx.stroke()+ if (sel) { ctx.globalAlpha = a * 0.9; ctx.fillStyle = `rgb(${GOLD})`; ctx.beginPath(); ctx.arc(PX, PY, 2.2, 0, Math.PI * 2); ctx.fill() }+ }+ }+ ctx.globalCompositeOperation = 'source-over'+ }++ function buildAboutPanel() {+ const box = ui.about+ box.replaceChildren()+ const head = el('div', 'ah')+ head.append(el('h1', null, 'About you'))+ const intro = M.about?.intro || (M.about ? '' : 'About You has not been built yet.')+ if (intro) head.append(el('span', 'intro', intro))+ box.append(head)+ const scroll = el('div', 'scroll')+ const cols = el('div', 'cols')+ let sec = null, name = null+ for (const row of M.aboutLines) {+ if (row.line.section !== name) {+ name = row.line.section+ sec = el('div', 'sec')+ sec.append(el('h3', null, name || ''))+ cols.append(sec)+ }+ const line = el('div', 'line')+ line.dataset.i = String(row.i)+ line.append(el('span', 't', row.line.text))+ const cites = el('span', 'c')+ for (const mem of row.cited.slice(0, 6)) { const d = el('span', 'dot'); d.style.background = mem.color; cites.append(d) }+ if (row.asksRef) cites.append(el('span', null, ` ${row.asksRef >= 1000 ? (row.asksRef / 1000).toFixed(1) + 'k' : row.asksRef}`))+ line.append(cites)+ line.addEventListener('click', () => { aboutSel = row.i; markAboutSel(); kick() })+ line.addEventListener('dblclick', () => { aboutSel = row.i; openCard({ type: 'about', row }) })+ sec.append(line)+ }+ scroll.append(cols)+ scroll.addEventListener('scroll', () => { aboutRects = null; aboutBox = ''; kick() })+ box.append(scroll)+ }+ function markAboutSel() {+ for (const node of ui.about.querySelectorAll('.line')) node.classList.toggle('sel', Number(node.dataset.i) === aboutSel)+ const sel = ui.about.querySelector('.line.sel')+ if (sel) sel.scrollIntoView({ block: 'nearest' })+ aboutRects = null+ updateHud()+ }+ function setAboutOpacity(v) {+ if (Math.abs(v - aboutOpacity) < 0.01 && (v === 0 || aboutBox)) { if (v > 0) placeAbout(); return }+ aboutOpacity = v+ if (v <= 0.01) { if (!ui.about.hidden) { ui.about.hidden = true; aboutBox = '' } return }+ if (ui.about.hidden) { ui.about.hidden = false; markAboutSel() }+ ui.about.style.opacity = String(v)+ placeAbout()+ }+ function placeAbout() {+ plane(ABOUT_Z)+ ps(-AHW, FLOOR); const ax = PX, ay = PY+ ps(AHW, FLOOR + AH); const bx = PX, by = PY+ const box = `${Math.round(ax)},${Math.round(by)},${Math.round(bx - ax)},${Math.round(ay - by)}`+ if (box === aboutBox && aboutRects) return+ aboutBox = box+ const s = ui.about.style+ // The glass text stops above the sill, where the horizon of your days runs.+ s.left = `${Math.round(ax)}px`; s.top = `${Math.round(by)}px`; s.width = `${Math.round(bx - ax)}px`; s.height = `${Math.round((ay - by) * 0.855)}px`+ ui.about.classList.toggle('small', bx - ax < 900)+ ui.about.classList.toggle('narrow', bx - ax < 560)+ aboutRects = []+ const view = (ui.about.querySelector('.scroll') ?? ui.about).getBoundingClientRect()+ for (const node of ui.about.querySelectorAll('.line')) {+ const r = node.getBoundingClientRect()+ const t = node.querySelector('.c') ?? node+ const rc = t.getBoundingClientRect()+ const visible = r.bottom > view.top + 4 && r.top < view.bottom - 4+ aboutRects[Number(node.dataset.i)] = visible ? { x: rc.right + 3, y: rc.top + rc.height / 2 } : null+ }+ }++ // ── camera and the loop ───────────────────────────────────────────────────────────────────────────++ function flyTo(k) {+ const dist = Math.abs(k - cam.k)+ const chained = fly.active+ fly.from = cam.k; fly.to = k; fly.t0 = nowS(); fly.active = dist > 0.0005+ fly.dur = reduced ? 0 : clamp(0.24 + 0.2 * Math.log2(1 + dist), 0.24, 1.35)+ fly.ease = dist > 4 && !chained ? easeInOut : easeOut+ kick()+ }++ function step(T, dt) {+ let busy = false+ if (arrival) {+ const t = T - arrival.t0+ const p = easeInOut(clamp((t - 1.55) / 2.6))+ cam.k = lerp(-1.6, 0, p)+ const side = 1 - p+ cam.x = 1.0 * side; cam.y = 0.38 * side; cam.yaw = -0.46 * side; cam.pitch = -0.11 * side+ if (t >= arrival.dur) endArrival()+ busy = true+ } else {+ if (fly.active) {+ const p = fly.dur ? clamp((T - fly.t0) / fly.dur) : 1+ cam.k = lerp(fly.from, fly.to, fly.ease(p))+ if (p >= 1) fly.active = false+ busy = true+ }+ const tx = reduced ? 0 : mouse.x * 0.05, ty = reduced ? 0 : -mouse.y * 0.035+ const ex = tx - cam.x, ey = ty - cam.y+ if (Math.abs(ex) + Math.abs(ey) > 0.0003) { const f = 1 - Math.exp(-dt * 5); cam.x += ex * f; cam.y += ey * f; busy = true }+ cam.yaw = 0; cam.pitch = 0+ }+ speed = dt > 0 ? Math.abs(cam.k - prevK) / dt : 0+ prevK = cam.k+ camZ = -cam.k * S + D+ cY = Math.cos(cam.yaw); sY = Math.sin(cam.yaw); cP = Math.cos(cam.pitch); sP = Math.sin(cam.pitch)+ F = F0 * (reduced ? 1 : 1 - Math.min(0.13, speed / 900))+ if (speed > 0.01) busy = true+ if (pulled && !reduced) busy = true // the string keeps a faint shimmer+ if (pulled && !reduced && T - pulled.t0 < 0.4 + (M.maxK + 8) / WAVE) busy = true+ if (recallOn() && !reduced && T - recall.t0 < 3) busy = true+ return busy+ }++ function kick() { if (!raf && !document.hidden) raf = requestAnimationFrame(tick) }+ function tick(ts) {+ raf = 0+ const T = ts / 1000+ const dt = lastT ? Math.min(0.05, T - lastT) : 1 / 60+ lastT = T+ const busy = step(T, dt)+ render(T)+ if (busy) kick(); else lastT = 0+ }+ document.addEventListener('visibilitychange', () => { if (!document.hidden) { lastT = 0; kick() } })++ function resize() {+ dpr = Math.min(2, window.devicePixelRatio || 1)+ vw = window.innerWidth; vh = window.innerHeight+ canvas.width = Math.round(vw * dpr); canvas.height = Math.round(vh * dpr)+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)+ OX = vw / 2; OY = vh * 0.47+ F0 = Math.min(0.6 * vw / (2 * HW), 0.54 * vh / 1.12) * D+ F = F0+ aboutBox = ''; aboutRects = null+ updateHint()+ kick()+ }+ window.addEventListener('resize', resize)++ // ── arrival ───────────────────────────────────────────────────────────────────────────────────────++ function startArrival() {+ if (reduced) { endArrival(); return }+ arrival = { t0: nowS(), dur: 4.4, stagger: Math.min(0.011, 1.5 / Math.max(1, M.maxK)) }+ document.body.classList.add('arriving')+ updateHint()+ kick()+ }+ function endArrival() {+ arrival = null+ cam.k = 0; cam.x = 0; cam.y = 0; cam.yaw = 0; cam.pitch = 0+ fly.active = false+ document.body.classList.remove('arriving')+ goDay(0, { instant: true })+ updateHint()+ kick()+ }++ // ── focus and travel ──────────────────────────────────────────────────────────────────────────────++ function pickItem(day) {+ let best = null, bd = Infinity+ for (const it of day.items) {+ const d = Math.abs(it.u - focus.u) + (it.lane === focus.lane ? 0 : 0.35)+ if (d < bd) { bd = d; best = it }+ }+ return best+ }+ function goDay(k, opts = {}) {+ if (!M) return+ k = clamp(Math.round(k), 0, M.maxK)+ if (mode !== 'corridor') mode = 'corridor'+ focus.k = k+ focus.item = opts.item !== undefined ? opts.item : pickItem(M.days[k])+ if (opts.item && opts.item.u != null) { focus.lane = opts.item.lane; focus.u = opts.item.u }+ if (opts.instant) { cam.k = k; fly.active = false } else flyTo(k)+ updateHud()+ kick()+ }+ function setFocus(it) {+ focus.item = it+ if (it) { focus.lane = it.lane; focus.u = it.u }+ updateHud(); kick()+ }+ function stepItem(dir) {+ const items = M.days[focus.k].items+ if (!items.length) return+ let i = focus.item ? items.indexOf(focus.item) : -1+ if (i < 0) {+ i = dir > 0 ? items.findIndex((it) => it.u >= focus.u) : findLast(items, (it) => it.u <= focus.u)+ if (i < 0) i = dir > 0 ? items.length - 1 : 0+ } else i = clamp(i + dir, 0, items.length - 1)+ setFocus(items[i])+ }+ function stepLane(dir) {+ const from = focus.item ? focus.item.lane : focus.lane+ const to = clamp(from + dir, 0, M.lanes.length - 1)+ const a = M.lanes[from], b = M.lanes[to]+ const rel = clamp((focus.u - a.u0) / Math.max(1e-6, a.u1 - a.u0))+ focus.lane = to+ focus.u = b.u0 + (b.u1 - b.u0) * rel+ const mine = M.days[focus.k].items.filter((it) => it.lane === to)+ let best = null, bd = Infinity+ for (const it of mine) { const d = Math.abs(it.u - focus.u); if (d < bd) { bd = d; best = it } }+ focus.item = best+ updateHud(); kick()+ }+ function findLast(list, fn) { for (let i = list.length - 1; i >= 0; i--) if (fn(list[i])) return i; return -1 }++ function enterAbout() {+ if (!M) return+ mode = 'about'+ flyTo(STATION)+ updateHud(); kick()+ }++ function tabNext(dir) {+ if (recallOn() && recall.hits.length) return jumpHit(dir)+ if (pulled && pulled.order.length) return jumpLit(dir)+ if (mode === 'corridor') stepItem(dir)+ }+ function jumpLit(dir) {+ const order = pulled.order+ const here = mode === 'about' ? -1 : focus.k+ let k = dir > 0 ? order.find((x) => x > here) : findLastVal(order, (x) => x < here)+ if (k == null) k = dir > 0 ? order[0] : order[order.length - 1]+ goDay(k, { item: pulled.anchors.get(k) ?? null })+ }+ function findLastVal(list, fn) { for (let i = list.length - 1; i >= 0; i--) if (fn(list[i])) return list[i]; return undefined }+ function jumpHit(dir) {+ const hits = recall.hits+ let i = hits.indexOf(focus.item)+ if (i < 0 || mode === 'about') {+ const here = mode === 'about' ? -1 : focus.k+ const tod = focus.item ? focus.item.tod : 1+ i = dir > 0 ? hits.findIndex((h) => h.k > here || (h.k === here && h.tod < tod)) : findLast(hits, (h) => h.k < here || (h.k === here && h.tod > tod))+ if (i < 0) i = dir > 0 ? 0 : hits.length - 1+ } else i = (i + dir + hits.length) % hits.length+ const h = hits[i]+ if (h.k !== focus.k || mode !== 'corridor') goDay(h.k, { item: h }); else setFocus(h)+ }++ function pull(source) {+ if (!source) return+ pulled = buildString(source)+ updateHud(); kick()+ }+ function release() { pulled = null; updateHud(); kick() }++ // ── recall ────────────────────────────────────────────────────────────────────────────────────────++ function setQuery(q) {+ recall.q = q+ recall.terms = queryTerms(q)+ recall.t0 = nowS()+ recall.origin = mode === 'about' ? 0 : focus.k+ clearExtras()+ recall.hits = []; recall.set = new Set(); recall.byDay = new Map(); recall.mems = 0+ if (recallOn() && recall.terms.length) {+ const terms = recall.terms+ for (const it of M.askItems) if (terms.every((t) => it.lower.includes(t))) recall.hits.push(it)+ for (const it of M.memItems) if (terms.every((t) => it.lower.includes(t))) { recall.hits.push(it); recall.mems++ }+ finishHits()+ clearTimeout(recall.timer)+ const seq = ++recall.seq+ recall.timer = setTimeout(() => remoteSearch(q, seq), 160)+ }+ updateHud(); kick()+ }+ function finishHits() {+ recall.hits.sort((a, b) => a.k - b.k || b.tod - a.tod)+ recall.set = new Set(recall.hits)+ recall.byDay = new Map()+ for (const it of recall.hits) recall.byDay.set(it.k, (recall.byDay.get(it.k) ?? 0) + 1)+ }+ async function remoteSearch(q, seq) {+ let hits = []+ try { hits = await MemoryData.search(q) } catch { return }+ if (seq !== recall.seq || q !== recall.q) return+ let added = 0+ for (const h of hits ?? []) {+ if (!h || !h.at) continue+ const known = M.byAskKey.get(`${h.sessionId}@${h.at}`)+ if (known) { if (!recall.set.has(known)) { recall.hits.push(known); added++ } continue }+ const k = M.kOf(h.at)+ if (k < 0 || k > M.maxK) continue+ const day = M.days[k]+ const lane = M.laneFor(M.laneOfCwd(h.cwd) ?? NONE)+ const tod = clamp((h.at - day.t) / DAY, 0, 0.9999)+ const item = { type: 'hit', h, k, lane, tod, color: M.agentOf(h.engine).color, hang: 0.55, extra: true }+ item.u = M.uOf(lane, tod); item.x = -HW + 2 * HW * item.u+ day.items.push(item); day.items.sort((a, b) => a.lane - b.lane || a.tod - b.tod)+ recall.extras.push(item); recall.hits.push(item); added+++ }+ if (added) { finishHits(); updateHud(); kick() }+ }+ function clearExtras() {+ if (!recall.extras.length) return+ const gone = new Set(recall.extras)+ const touched = new Set(recall.extras.map((it) => it.k))+ for (const k of touched) M.days[k].items = M.days[k].items.filter((it) => !gone.has(it))+ if (gone.has(focus.item)) focus.item = pickItem(M.days[focus.k])+ recall.extras = []+ }+ function closeRecall() {+ clearTimeout(recall.timer)+ recall.seq+++ recall.open = false+ setQuery('')+ }++ // ── the HUD ───────────────────────────────────────────────────────────────────────────────────────++ function fmtTime(t) { const d = new Date(t); return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}` }+ function fmtDate(t) { const d = new Date(t); return `${WD[d.getDay()]} ${d.getDate()} ${MON[d.getMonth()]} ${d.getFullYear()}` }+ function ago(k) {+ if (k <= 0) return 'today'+ if (k === 1) return 'yesterday'+ if (k < 14) return `${k} days ago`+ if (k < 60) return `${Math.round(k / 7)} weeks ago`+ return `${Math.round(k / 30.4)} months ago`+ }+ function isoWeek(d) {+ const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()))+ const wd = t.getUTCDay() || 7+ t.setUTCDate(t.getUTCDate() + 4 - wd)+ const y0 = new Date(Date.UTC(t.getUTCFullYear(), 0, 1))+ return Math.ceil(((t - y0) / DAY + 1) / 7)+ }+ const oneLine = (s) => String(s ?? '').replace(/\s+/g, ' ').trim()+ function itemTime(it) { return it.type === 'ask' ? it.a.at : it.type === 'mem' ? it.m.modified : it.h.at }+ function itemEngine(it) { return it.type === 'ask' ? it.a.engine : it.type === 'mem' ? it.m.agent : it.h.engine }+ function itemText(it) {+ if (it.type === 'ask') return oneLine(it.a.text)+ if (it.type === 'mem') return oneLine(`${it.m.title ?? ''}${it.m.description ? ' — ' + it.m.description : ''}`)+ return oneLine(String(it.h.snippet ?? ''))+ }++ // Text with recall terms underlined: plain text nodes and <mark> elements only.+ function appendMarked(node, text, terms) {+ if (!terms?.length) { node.append(document.createTextNode(text)); return }+ const lower = text.toLowerCase()+ let i = 0+ while (i < text.length) {+ let best = -1, len = 0+ for (const t of terms) { const j = lower.indexOf(t, i); if (j >= 0 && (best < 0 || j < best)) { best = j; len = t.length } }+ if (best < 0) { node.append(document.createTextNode(text.slice(i))); break }+ if (best > i) node.append(document.createTextNode(text.slice(i, best)))+ node.append(el('mark', null, text.slice(best, best + len)))+ i = best + len+ }+ }+ function appendSnippet(node, snippet) {+ const parts = String(snippet ?? '').replace(/\s+/g, ' ').split(/(\u0002[^\u0003]*\u0003)/)+ for (const p of parts) {+ if (p.startsWith('\u0002')) node.append(el('mark', null, p.slice(1, -1)))+ else if (p) node.append(document.createTextNode(p))+ }+ }++ function updateHud() {+ if (!M) return+ document.body.classList.toggle('reading', !!reading)+ ui.source.textContent = M.real ? 'your memories · this computer' : 'an invented person'+ if (mode === 'about') {+ ui.day.style.visibility = 'hidden'; ui.ticker.style.visibility = 'hidden'+ const row = M.aboutLines[aboutSel]+ ui.lane.replaceChildren()+ if (row) ui.lane.append(document.createTextNode(row.cited.length ? `cites ${plural(row.cited.length, 'memory', 'memories')}` : row.asksRef ? `from ${plural(row.asksRef, 'message')}` : ''))+ updateStatus(); updateHint()+ return+ }+ ui.day.style.visibility = ''; ui.ticker.style.visibility = ''+ const day = M.days[focus.k]+ ui.date.textContent = fmtDate(day.t)+ ui.ago.textContent = `${ago(day.k)} · week ${isoWeek(day.date)}`+ const parts = []+ const msgs = day.asks + day.ghostN+ parts.push(msgs ? plural(msgs, 'message') : 'no messages')+ if (day.mems) parts.push(`${plural(day.mems, 'memory', 'memories')} written`)+ ui.counts.textContent = parts.join(' · ')+ ui.chips.replaceChildren()+ const engines = {}+ for (const [e, n] of Object.entries(day.by)) engines[e] = (engines[e] ?? 0) + n+ for (const [e, n] of Object.entries(day.ghostBy)) engines[e] = (engines[e] ?? 0) + n+ for (const [e, n] of Object.entries(engines).sort((a, b) => b[1] - a[1])) {+ const ag = M.agentOf(e)+ const chip = el('span')+ const dot = el('span', 'dot'); dot.style.background = ag.color+ chip.append(dot, document.createTextNode(`${ag.name} ${n}`))+ ui.chips.append(chip)+ }+ let note = ''+ if (day.quiet) {+ const st = M.stretches.find((s) => day.k >= s.from && day.k <= s.to)+ note = st ? `a quiet stretch: ${st.n} days without a message` : day.dow === 0 || day.dow === 6 ? 'a quiet weekend day' : 'a quiet day'+ } else if (day.ghostN && !day.asks) note = `older than the messages loaded here; type to recall them`+ else if (day.ghostN) note = `${plural(day.ghostN, 'more message')} older than the loaded window`+ ui.daynote.textContent = note+ // Lane, top right.+ const laneI = focus.item ? focus.item.lane : focus.lane+ ui.lane.replaceChildren()+ const lane = M.lanes[laneI]+ if (lane) {+ ui.lane.append(document.createTextNode('lane '))+ ui.lane.append(el('b', null, lane.name))+ ui.lane.append(document.createTextNode(` ${laneI + 1}/${M.lanes.length}`))+ }+ updateTicker(day)+ updateStatus()+ updateHint()+ }++ function updateTicker(day) {+ const box = ui.ticker+ box.replaceChildren()+ const items = day.items+ const terms = recallOn() ? recall.terms : null+ if (!items.length) {+ box.append(el('div', 'row quiet', day.ghostN ? `${plural(day.ghostN, 'message')} this day, older than the loaded window`+ : day.k === 0 ? 'nothing yet today' : day.quiet ? 'nothing was said this day' : ''))+ return+ }+ let i = focus.item ? items.indexOf(focus.item) : -1+ const center = i >= 0 ? i : Math.max(0, items.findIndex((it) => it.u >= focus.u))+ const rows = 5+ let from = Math.max(0, center - 2)+ from = Math.max(0, Math.min(from, items.length - rows))+ for (let j = from; j < Math.min(items.length, from + rows); j++) {+ const it = items[j]+ const row = el('div', `row${it.type === 'mem' ? ' mem' : ''}${j === i ? ' sel' : ''}${pulled && pulled.set.has(it) ? ' lit' : ''}`)+ row.append(el('span', 'time', fmtTime(itemTime(it))))+ const ag = M.agentOf(itemEngine(it))+ const who = el('span', 'who')+ const dot = el('span', 'dot'); dot.style.background = ag.color+ who.append(dot, document.createTextNode(ag.name))+ row.append(who)+ row.append(el('span', 'where', M.lanes[it.lane]?.name ?? ''))+ const text = el('span', 'text')+ if (it.type === 'hit') appendSnippet(text, it.h.snippet)+ else appendMarked(text, itemText(it), terms)+ row.append(text)+ row.addEventListener('click', () => setFocus(it))+ row.addEventListener('dblclick', () => openCard(it))+ box.append(row)+ }+ }++ function updateStatus() {+ const box = ui.status+ box.replaceChildren()+ if (recall.open || recall.q) {+ box.append(el('span', 'k', '› '))+ box.append(el('span', 'q', recall.q))+ if (recallOn()) {+ const days = recall.byDay.size+ const msgs = recall.hits.length - recall.mems+ const bits = []+ if (msgs) bits.push(plural(msgs, 'message'))+ if (recall.mems) bits.push(plural(recall.mems, 'memory', 'memories'))+ box.append(document.createTextNode(recall.hits.length ? ` ${bits.join(' · ')} on ${plural(days, 'day')}` : ' nothing comes back'))+ if (recall.hits.length) box.append(el('span', 'k', ' ⇥ next ⇧⇥ back esc clear'))+ } else box.append(el('span', 'k', ' keep typing'))+ return+ }+ if (pulled) {+ box.append(el('span', 'pulled', '◆ '))+ box.append(el('span', 'pulled', `“${pulled.label.length > 64 ? pulled.label.slice(0, 63) + '…' : pulled.label}”`))+ const n = pulled.order.length+ box.append(document.createTextNode(n > 1 ? ` came up on ${plural(n, 'day')}` : ' came up on no other day'))+ box.append(el('span', 'k', n > 1 ? ' ⇥ follow ⇧⇥ back esc let go' : ' esc let go'))+ }+ }++ function updateHint() {+ const box = ui.hint+ box.replaceChildren()+ const wide = vw >= 1180+ let keys+ if (arrival) keys = [['any key', 'skips']]+ else if (reading) keys = [['esc', 'back'], ['←→', 'neighbours'], ['↑↓', 'scroll'], ['␣', 'pull its string']]+ else if (mode === 'about') keys = [['↑↓', 'lines'], ['⏎', 'sources'], ['␣', 'pull string'], ['⇥', 'follow into time'], ['G', 'today']]+ else if (recall.open || recall.q) keys = [['type', 'recall'], ['⇥', 'next hit'], ['⏎', 'read'], ['↑↓', 'days'], ['esc', 'clear']]+ else if (wide) keys = [['↑↓', 'days'], ['⇧↑↓', 'weeks'], ['←→', 'messages'], ['⇧←→', 'lanes'], ['g G', 'start · today'], ['⏎', 'read'], ['␣', 'pull string'], ['⇥', 'next'], ['type', 'recall'], ['~', 'about you']]+ else keys = [['↑↓', 'days'], ['⇧', 'weeks'], ['←→ ⇧←→', 'msgs · lanes'], ['g G', ''], ['⏎', 'read'], ['␣', 'pull'], ['⇥', 'next'], ['type', 'recall'], ['~', 'you']]+ keys.forEach(([k, what], i) => {+ if (i) box.append(document.createTextNode(' '))+ box.append(el('b', null, k))+ if (what) box.append(document.createTextNode(` ${what}`))+ })+ }++ // ── the reading card ──────────────────────────────────────────────────────────────────────────────++ function openCard(it) {+ if (!it) return+ reading = it+ const box = ui.card+ box.replaceChildren()+ const kick_ = el('div', 'kick')+ const addAgent = (id) => {+ const ag = M.agentOf(id)+ const s = el('span'); const d = el('span', 'dot'); d.style.background = ag.color+ s.append(d, document.createTextNode(ag.name)); kick_.append(s)+ }+ if (it.type === 'about') {+ const row = it.row+ kick_.append(el('span', 'tag', 'About you'), el('span', null, row.line.section || ''))+ box.append(kick_)+ box.append(el('h2', null, row.line.text))+ const ul = el('ul')+ for (const mem of row.cited) {+ const li = el('li')+ const d = el('span', 'dot'); d.style.background = mem.color+ li.append(d, el('span', null, mem.m.title || mem.m.description || 'a memory'), el('span', 'when', `${M.agentOf(mem.m.agent).name} · ${ago(mem.k)}`))+ ul.append(li)+ }+ if (row.cited.length) { box.append(el('div', 'desc', `Held up by ${plural(row.cited.length, 'memory', 'memories')}:`)); box.append(ul) }+ if (row.asksRef) box.append(el('div', 'meta', `Drawn from ${row.asksRef.toLocaleString('en-US')} of your messages.`))+ if (row.sessionRef) box.append(el('div', 'meta', 'Drawn from a conversation.'))+ const foot = el('div', 'foot'); foot.append(el('b', null, '␣'), document.createTextNode(' pull its string through time esc back'))+ box.append(foot)+ } else if (it.type === 'mem') {+ const m = it.m+ addAgent(m.agent)+ if (m.project?.name) kick_.append(el('span', null, m.project.name))+ kick_.append(el('span', null, m.type || m.kind || ''))+ kick_.append(el('span', null, `written ${fmtDate(m.modified)}, ${fmtTime(m.modified)} · ${ago(it.k)}`))+ box.append(kick_)+ box.append(el('h2', null, m.title || 'Untitled memory'))+ if (m.description && m.description !== m.title) box.append(el('div', 'desc', m.description))+ box.append(el('pre', 'body', String(m.body ?? '')))+ if (m.path) box.append(el('div', 'meta', m.path))+ const s = buildString(it)+ const foot = el('div', 'foot')+ foot.append(document.createTextNode(s.order.length > 1 ? `came up on ${plural(s.order.length, 'day')} · ` : ''), el('b', null, '␣'), document.createTextNode(' pull its string ←→ neighbours esc back'))+ box.append(foot)+ } else {+ const isAsk = it.type === 'ask'+ const src = isAsk ? it.a : it.h+ addAgent(src.engine)+ kick_.append(el('span', null, M.lanes[it.lane]?.name ?? ''))+ kick_.append(el('span', null, `${fmtDate(src.at)}, ${fmtTime(src.at)} · ${ago(it.k)}`))+ box.append(kick_)+ box.append(el('h2', null, src.title ? src.title : 'Untitled conversation'))+ const body = el('pre', 'body')+ if (isAsk) appendMarked(body, String(src.text ?? ''), recallOn() ? recall.terms : null)+ else appendSnippet(body, src.snippet)+ box.append(body)+ const meta = []+ if (isAsk && src.turn >= 0) meta.push(`message ${src.turn + 1} in this conversation`)+ if (isAsk && it.len > String(src.text ?? '').length) meta.push(`first ${String(src.text).length} of ${it.len.toLocaleString('en-US')} characters`)+ if (!isAsk) meta.push('found by recall; older than the messages loaded here')+ if (src.cwd) meta.push(src.cwd)+ if (meta.length) box.append(el('div', 'meta', meta.join(' · ')))+ const foot = el('div', 'foot')+ foot.append(el('b', null, '␣'), document.createTextNode(' pull its string ←→ neighbours esc back'))+ box.append(foot)+ }+ box.hidden = false+ box.scrollTop = 0+ updateHud(); kick()+ }+ function closeCard() { reading = null; ui.card.hidden = true; updateHud(); kick() }++ // ── keys ──────────────────────────────────────────────────────────────────────────────────────────++ function onKey(e) {+ if (!M) return+ if (e.metaKey || e.ctrlKey || e.altKey) return+ const key = e.key+ if (arrival) { e.preventDefault(); endArrival(); return }++ if (reading) {+ if (key === 'Escape' || key === 'Enter' || key === 'Backspace') { e.preventDefault(); closeCard(); return }+ if (key === ' ') { e.preventDefault(); const it = reading; closeCard(); pull(it); return }+ if (key === 'ArrowDown' || key === 'j') { e.preventDefault(); ui.card.scrollBy(0, 60); return }+ if (key === 'ArrowUp' || key === 'k') { e.preventDefault(); ui.card.scrollBy(0, -60); return }+ if ((key === 'ArrowLeft' || key === 'ArrowRight') && reading.type !== 'about') {+ e.preventDefault()+ stepItem(key === 'ArrowLeft' ? -1 : 1)+ if (focus.item) openCard(focus.item)+ return+ }+ if (key === 'Tab') { e.preventDefault(); return }+ return+ }++ const typing = recall.open || recall.q.length > 0+ if (key === 'Escape') {+ e.preventDefault()+ if (typing) closeRecall()+ else if (pulled) release()+ else if (mode === 'about') goDay(0)+ return+ }+ if (key === 'Tab') { e.preventDefault(); tabNext(e.shiftKey ? -1 : 1); return }++ if (mode === 'about' && !typing) {+ const n = M.aboutLines.length+ if (key === 'ArrowDown' || key === 'j') { e.preventDefault(); if (n) { aboutSel = Math.min(n - 1, aboutSel + 1); markAboutSel(); kick() } return }+ if (key === 'ArrowUp' || key === 'k') {+ e.preventDefault()+ if (aboutSel <= 0 || !n) goDay(0); else { aboutSel--; markAboutSel(); kick() }+ return+ }+ if (key === 'Enter') { e.preventDefault(); const row = M.aboutLines[aboutSel]; if (row) openCard({ type: 'about', row }); return }+ if (key === ' ') { e.preventDefault(); const row = M.aboutLines[aboutSel]; if (row) pull({ type: 'about', row }); return }+ if (key === 'G' || key === 'g' || key === '~') { e.preventDefault(); goDay(key === 'g' ? M.maxK : 0); return }+ }++ // Travel works while typing too.+ const big = e.shiftKey ? 7 : 1+ if (key === 'ArrowUp' || (!typing && (key === 'k' || key === 'K'))) {+ e.preventDefault()+ if (mode === 'about') { goDay(0); return }+ goDay(focus.k + (key === 'K' ? 7 : big)); return+ }+ if (key === 'ArrowDown' || (!typing && (key === 'j' || key === 'J'))) {+ e.preventDefault()+ if (mode === 'about') return+ if (focus.k === 0 && big === 1) { enterAbout(); return }+ goDay(focus.k - (key === 'J' ? 7 : big)); return+ }+ if (key === 'ArrowLeft' || key === 'ArrowRight') {+ e.preventDefault()+ if (mode === 'about') return+ const dir = key === 'ArrowLeft' ? -1 : 1+ if (e.shiftKey) stepLane(dir); else stepItem(dir)+ return+ }+ if (key === 'PageUp' || key === 'PageDown') { e.preventDefault(); goDay(focus.k + (key === 'PageUp' ? 7 : -7)); return }+ if (key === 'Home') { e.preventDefault(); goDay(M.maxK); return }+ if (key === 'End') { e.preventDefault(); goDay(0); return }+ if (key === 'Enter') { e.preventDefault(); if (mode === 'corridor' && focus.item) openCard(focus.item); return }++ if (!typing) {+ if (key === 'g') { e.preventDefault(); goDay(M.maxK); return }+ if (key === 'G') { e.preventDefault(); goDay(0); return }+ if (key === '~') { e.preventDefault(); enterAbout(); return }+ if (key === ' ') { e.preventDefault(); if (mode === 'corridor' && focus.item) pull(focus.item); return }+ if (key === '/') { e.preventDefault(); recall.open = true; setQuery(''); return }+ }+ if (key === 'Backspace') {+ e.preventDefault()+ if (!recall.q) { closeRecall(); return }+ setQuery(recall.q.slice(0, -1))+ return+ }+ if (key.length === 1 && key !== '\u0000') {+ if (!typing && key === ' ') return+ e.preventDefault()+ recall.open = true+ if (recall.q.length < 80) setQuery(recall.q + key)+ }+ }+ window.addEventListener('keydown', onKey)++ // ── pointer: optional, for the curious ───────────────────────────────────────────────────────────++ window.addEventListener('mousemove', (e) => {+ mouse.x = (e.clientX / Math.max(1, vw)) * 2 - 1+ mouse.y = (e.clientY / Math.max(1, vh)) * 2 - 1+ kick()+ })+ window.addEventListener('wheel', (e) => {+ if (!M || arrival || reading) return+ if (e.target.closest && (e.target.closest('#about') || e.target.closest('#card'))) return+ e.preventDefault()+ wheelAcc += e.deltaY+ const steps = Math.trunc(wheelAcc / 60)+ if (!steps) return+ wheelAcc -= steps * 60+ if (mode === 'about') { if (steps > 0) goDay(0); return }+ if (focus.k + steps < 0) { enterAbout(); return }+ goDay(focus.k + steps)+ }, { passive: false })+ canvas.addEventListener('click', (e) => {+ if (!M || arrival || reading || mode !== 'corridor') return+ const it = pickAt(e.clientX, e.clientY)+ if (it) { if (it.k !== focus.k) goDay(it.k, { item: it }); else setFocus(it) }+ })+ canvas.addEventListener('dblclick', (e) => {+ if (!M || arrival || reading || mode !== 'corridor') return+ const it = pickAt(e.clientX, e.clientY)+ if (it) openCard(it)+ })+ function pickAt(x, y) {+ const T = nowS()+ let best = null, bd = 9+ for (let k = focus.k; k <= Math.min(M.maxK, focus.k + 3); k++) {+ const day = M.days[k]+ if (plane(zOf(k, T)) < NEAR * 2) continue+ const top = FLOOR + day.h+ for (const it of day.items) {+ if (it.type === 'mem') {+ ps(it.x, FLOOR + BOOK_H / 2)+ const d = Math.hypot(PX - x, (PY - y) * 0.4)+ if (d < bd) { bd = d; best = it }+ continue+ }+ ps(it.x, top); const y0 = PY, x0 = PX+ ps(it.x, top - (it.hang ?? 0.3) * day.h * 0.86)+ if (y < y0 - 3 || y > PY + 3) continue+ const d = Math.abs(x0 - x)+ if (d < bd) { bd = d; best = it }+ }+ if (best) break+ }+ return best+ }++ // ── start ─────────────────────────────────────────────────────────────────────────────────────────++ window.__tesseract = {+ state: () => ({ mode, k: focus.k, item: focus.item ? focus.item.type : null, lane: focus.item ? M.lanes[focus.item.lane].name : M?.lanes[focus.lane]?.name,+ pulled: pulled ? { label: pulled.label, days: pulled.order.length } : null, hits: recall.hits.length, hitDays: recall.byDay.size, q: recall.q,+ reading: reading ? reading.type : null, arrival: !!arrival, maxK: M?.maxK, lanes: M?.lanes.length, camK: cam.k }),+ perf: () => ({ frames: perf.frames, avg: perf.frames ? perf.ms / perf.frames : 0, worst: perf.worst }),+ resetPerf: () => { perf.frames = 0; perf.ms = 0; perf.worst = 0 },+ }++ resize()+ MemoryData.load().then((loaded) => {+ M = build(loaded)+ focus.lane = Math.max(0, M.lanes.findIndex((l) => l.name !== NONE))+ layoutAboutBars()+ buildAboutPanel()+ ui.load.remove()+ updateHud()+ startArrival()+ canvas.focus({ preventScroll: true })+ }).catch((error) => {+ ui.load.textContent = `Could not read memories: ${String(error?.message ?? error)}`+ })+})()diff --git a/docs/research/2026-10-10-memory-brain/tesseract.png b/docs/research/2026-10-10-memory-brain/tesseract.pngnew file mode 100644index 000000000..9ee4b7076Binary files /dev/null and b/docs/research/2026-10-10-memory-brain/tesseract.png differ