Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

test(second-brain): keep the headless capture + verification harnesses

xerj-orgc585c15d43fa
diff --git a/docs/examples/second-brain-capture/graph_capture.mjs b/docs/examples/second-brain-capture/graph_capture.mjs
new file mode 100644
index 000000000..d8f30fc74
--- /dev/null
+++ b/docs/examples/second-brain-capture/graph_capture.mjs
@@ -0,0 +1,266 @@
+// Judge THE MAP against the success criterion on the large `repo` brain.
+// Drives the REAL console on :9200 (virtual WebAuthn), serves fresh UX
+// assets from the working tree, screenshots every altitude, and measures
+// drawn-element counts + frame timing. Run from /home/claude/ai/xerj.
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const BASE = 'http://localhost:9200';
+const BRAIN = process.argv[2] || 'repo';
+const OUT = process.argv[3] || '/tmp/claude-1001/-home-claude-ai-xerj/e36b8c4c-3a94-4a76-80f1-2119380319c6/scratchpad/graphshots';
+const TOKEN = process.argv[4] || null;
+const UX = '/home/claude/ai/xerj/xerj-ux';
+fs.mkdirSync(OUT, { recursive: true });
+const say = (s) => console.log(s);
+
+const MIME = { '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml' };
+const browser = await puppeteer.launch({
+ headless: 'new', executablePath: '/usr/bin/google-chrome',
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+page.on('pageerror', (e) => say('PAGE EXCEPTION: ' + String(e).slice(0, 300)));
+page.on('console', (m) => { if (m.type() === 'error') say('PAGE ERROR: ' + m.text().slice(0, 200)); });
+page.on('response', (r) => { if (r.status() >= 400) say('HTTP ' + r.status() + ' ' + r.url().slice(0, 140)); });
+
+await page.setRequestInterception(true);
+page.on('request', (req) => {
+ const u = new URL(req.url());
+ if (u.origin === BASE && u.pathname.startsWith('/_xerj-console/') && !u.pathname.startsWith('/_xerj-console/api/')) {
+ let rel = u.pathname.slice('/_xerj-console/'.length);
+ if (rel === '' || rel === 'setup' || rel === 'login') rel = rel ? `${rel}.html` : 'index.html';
+ const file = path.join(UX, rel);
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) {
+ req.respond({ status: 200, headers: { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-cache' }, body: fs.readFileSync(file) });
+ return;
+ }
+ }
+ req.continue();
+});
+
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
+});
+
+const me = await page.goto(`${BASE}/_xerj-console/api/v1/me`, { waitUntil: 'networkidle0' });
+if (me.status() === 401) {
+ if (!TOKEN) { say('NEEDS TOKEN'); process.exit(1); }
+ await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+ await new Promise((r) => setTimeout(r, 1200));
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ el.value = el.type === 'email' || k.includes('email') ? `graph-${Date.now()}@example.com`
+ : (k.includes('passkey') || k.includes('pkname')) ? 'demo-key' : 'Verify';
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ });
+ await page.evaluate(() => {
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+ });
+ await new Promise((r) => setTimeout(r, 5000));
+ if (/setup/.test(page.url())) { say('CLAIM FAILED: ' + (await page.evaluate(() => document.body.innerText.slice(0, 300)))); await browser.close(); process.exit(1); }
+ say('claimed ok → ' + page.url());
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const mapState = () => page.evaluate(async () => (await import('/_xerj-console/src/ux/brain-map.js')).sbMapState());
+const shot = async (n) => { await page.screenshot({ path: `${OUT}/${n}.png` }); say(' shot ' + n); };
+const scrollMap = () => page.evaluate(() => {
+ const el = document.querySelector('[data-sb-map]');
+ el && el.scrollIntoView({ block: 'start' }); window.scrollBy(0, -70);
+});
+const railText = (n = 800) => page.evaluate((k) => {
+ const el = document.querySelector('[data-sb-map-rail]');
+ return el ? el.innerText.slice(0, k) : '(no rail)';
+}, n);
+
+// frame-interval sampler around an interaction
+const startFrames = () => page.evaluate(() => {
+ window.__frames = []; window.__fon = true;
+ let last = performance.now();
+ const tick = (t) => { window.__frames.push(t - last); last = t; if (window.__fon) requestAnimationFrame(tick); };
+ requestAnimationFrame(tick);
+});
+const stopFrames = () => page.evaluate(() => {
+ window.__fon = false;
+ const f = window.__frames.slice(1);
+ if (!f.length) return null;
+ const s = [...f].sort((a, b) => a - b);
+ return { n: f.length, mean: f.reduce((a, b) => a + b, 0) / f.length, p95: s[Math.floor(s.length * 0.95)], max: s[s.length - 1] };
+});
+
+async function clickHit(pred, pick) {
+ const st = await mapState();
+ const cands = st.hits.filter(pred);
+ const hit = pick ? pick(cands, st) : cands[0];
+ if (!hit) { say('NO HIT'); return null; }
+ const box = await (await page.$('[data-sb-map-canvas]')).boundingBox();
+ let x; let y;
+ if (hit.seg) { const [x1, y1, x2, y2] = hit.seg; x = box.x + (x1 + x2) / 2; y = box.y + (y1 + y2) / 2; }
+ else { x = box.x + hit.x + hit.w / 2; y = box.y + hit.y + hit.h / 2; }
+ await page.mouse.click(x, y);
+ return hit;
+}
+
+// ── (a) helicopter default ──
+const t0 = Date.now();
+await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=${BRAIN}`, { waitUntil: 'networkidle0' });
+let readyAt=null;
+for (let i = 0; i < 240; i++) { const st = await mapState().catch(() => null); if (st && st.status === 'ready') { readyAt = Date.now(); break; } await sleep(1000); }
+say('map ready wall-clock: ' + (readyAt ? ((readyAt - t0) + 'ms after navigation') : 'NEVER within 240s'));
+let st = await mapState();
+say(`READY in ~${Date.now() - t0}ms wall: ` + JSON.stringify({ status: st.status, mode: st.mode, fileNodes: st.fileNodes, clusters: st.clusters, bundles: st.bundles, statusLine: st.statusLine, error: st.error }));
+await scrollMap(); await sleep(800);
+st = await mapState();
+say('HELICOPTER drawn hits: ' + JSON.stringify({
+ clusters: st.hits.filter((h) => h.kind === 'cluster').length,
+ bundleTraces: st.hits.filter((h) => h.kind === 'bundle').length,
+ members: st.hits.filter((h) => h.kind === 'member').length,
+}));
+await shot('a-helicopter-default');
+say('HOME RAIL:\n' + await railText(700));
+
+// ── (b) one drill-down step: expand the biggest group ──
+await startFrames();
+await clickHit((h) => h.kind === 'cluster' && h.ci === 0);
+await sleep(1400);
+const fr1 = await stopFrames();
+st = await mapState();
+say('EXPANDED: ' + JSON.stringify({ expanded: st.expanded, spread: st.spread, members: st.hits.filter((h) => h.kind === 'member').length, satellite: st.hits.filter((h) => h.kind === 'satellite').length }));
+say('expand frames: ' + JSON.stringify(fr1));
+await shot('b-drilldown-expanded');
+say('CLUSTER RAIL:\n' + await railText(700));
+
+// ── (c) deepest: member → ledger + explore walks ──
+const mhit = await clickHit((h) => h.kind === 'member' && !h.seg, (cands, s) => {
+ const texts = s.hits.filter((h) => !h.seg && h.kind !== 'member');
+ const free = cands.filter((c) => c.w > 20 && !texts.some((t) => c.x < t.x + t.w && t.x < c.x + c.w && c.y < t.y + t.h && t.y < c.y + c.h));
+ return free[Math.floor(free.length / 2)] || cands[Math.floor(cands.length / 2)];
+});
+await sleep(800);
+say('member sel: ' + JSON.stringify((await mapState()).sel));
+// two explore walks = 4 hops honest depth
+for (let w = 0; w < 2; w++) {
+ const tw = Date.now();
+ const clicked = await page.evaluate(() => {
+ const b = document.querySelector('[data-sb-map-explore]');
+ if (!b) return false;
+ b.click();
+ return true;
+ });
+ if (!clicked) { say('no explore btn'); break; }
+ await sleep(150); // let the WALKING state render
+ for (let i = 0; i < 40; i++) { const r = await railText(2000); if (!/WALKING…/.test(r)) break; await sleep(250); }
+ say(`walk ${w + 1} settled in ~${Date.now() - tw}ms`);
+}
+say('EXPLORE RAIL:\n' + await railText(700));
+await shot('c1-deepest-explore');
+
+// satellite depth: expand the pooled "everything else" group (largest
+// member count) and open its satellite list
+await page.click('[data-sb-map-collapse]').catch(() => {});
+await sleep(900);
+let est = await mapState();
+const lastCi = est.hits.filter((h) => h.kind === 'cluster').length - 1;
+await clickHit((h) => h.kind === 'cluster' && h.ci === lastCi);
+await sleep(1600);
+est = await mapState();
+say('ELSE EXPANDED: ' + JSON.stringify({ expanded: est.expanded, members: est.hits.filter((h) => h.kind === 'member').length, satellite: est.hits.filter((h) => h.kind === 'satellite').length }));
+say('ELSE RAIL:\n' + await railText(500));
+// the satellite hangs below the spiral — pan it into the canvas first
+let satHit = (await mapState()).hits.find((h) => h.kind === 'satellite');
+if (satHit) {
+ const cbox = await (await page.$('[data-sb-map-canvas]')).boundingBox();
+ const cx = satHit.x + satHit.w / 2; const cy = satHit.y + satHit.h / 2;
+ if (cy > cbox.height - 30 || cy < 10 || cx < 10 || cx > cbox.width - 10) {
+ const dx = (cbox.width / 2) - cx; const dy = (cbox.height / 2) - cy;
+ await page.mouse.move(cbox.x + 8, cbox.y + 8);
+ await page.mouse.down();
+ await page.mouse.move(cbox.x + 8 + dx, cbox.y + 8 + dy, { steps: 12 });
+ await page.mouse.up();
+ await sleep(400);
+ }
+}
+const sat = await clickHit((h) => h.kind === 'satellite');
+if (sat) {
+ await sleep(1200);
+ say('SATELLITE RAIL:\n' + await railText(600));
+ await shot('c3-satellite-list');
+} else { say('NO SATELLITE on else-cluster'); await shot('c3-else-expanded'); }
+
+// then the true leaf: open the ledger
+await page.evaluate(() => { const b = document.querySelector('[data-sb-map-open]'); b && b.click(); });
+await sleep(2500);
+await shot('c2-leaf-ledger');
+
+// ── (e) evidence quote open: bundle inspector with quotes ──
+await scrollMap(); await sleep(400);
+await page.click('[data-sb-map-collapse]').catch(() => {});
+await sleep(900);
+await clickHit((h) => h.kind === 'bundle', (cands, s) => {
+ const texts = s.hits.filter((h) => !h.seg);
+ return cands.find((c) => {
+ const [x1, y1, x2, y2] = c.seg;
+ const mx = (x1 + x2) / 2; const my = (y1 + y2) / 2;
+ return !texts.some((t) => mx >= t.x && mx <= t.x + t.w && my >= t.y && my <= t.y + t.h);
+ }) || cands[0];
+});
+await sleep(1500);
+say('BUNDLE RAIL:\n' + await railText(900));
+await shot('e-bundle-evidence-quotes');
+
+// ── (d) statistics row ──
+await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-body="edgesLive"]') || document.querySelector('[data-sb-body="scrub"]');
+ el && el.scrollIntoView({ block: 'start' }); window.scrollBy(0, -60);
+});
+await sleep(600);
+await shot('d-statistics');
+say('READS PANEL:\n' + await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-body="reads"]');
+ return el ? el.innerText.slice(0, 700) : '(none)';
+}));
+say('CROSSINGS PANEL:\n' + await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-body="crossings"]');
+ return el ? el.innerText.slice(0, 500) : '(none)';
+}));
+
+// pan/zoom responsiveness at helicopter altitude
+await scrollMap(); await sleep(300);
+await startFrames();
+const canvasEl = await page.$('[data-sb-map-canvas]');
+if (!canvasEl) { say('NO CANVAS for pan/zoom'); await browser.close(); process.exit(1); }
+const box = await canvasEl.boundingBox();
+await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+for (let i = 0; i < 6; i++) await page.mouse.wheel({ deltaY: -120 });
+await page.mouse.down();
+await page.mouse.move(box.x + box.width / 2 + 200, box.y + box.height / 2 + 80, { steps: 20 });
+await page.mouse.up();
+for (let i = 0; i < 6; i++) await page.mouse.wheel({ deltaY: 120 });
+await sleep(200);
+say('pan/zoom frames: ' + JSON.stringify(await stopFrames()));
+
+// language & honesty audit on real rendered text
+const audit = await page.evaluate(() => {
+ const txt = document.body.innerText;
+ const bad = [];
+ for (const w of [/\bedge\b/i, /\bsrc\b/i, /\bdst\b/i, /valid_at/i, /as_of/i, /\bas-of\b/i, /graph database/i]) {
+ const m = txt.match(w);
+ if (m) {
+ const i = txt.indexOf(m[0]);
+ bad.push({ word: m[0], ctx: txt.slice(Math.max(0, i - 60), i + 60).replace(/\n/g, ' ') });
+ }
+ }
+ return bad;
+});
+say('LANGUAGE AUDIT (rendered text): ' + JSON.stringify(audit, null, 1));
+
+await browser.close();
+say('done');
diff --git a/docs/examples/second-brain-capture/map_browser_test.mjs b/docs/examples/second-brain-capture/map_browser_test.mjs
new file mode 100644
index 000000000..8c958ae1d
--- /dev/null
+++ b/docs/examples/second-brain-capture/map_browser_test.mjs
@@ -0,0 +1,233 @@
+// Browser verification of THE MAP against the live 9200 data plane.
+// The server's embedded console bundle is stale; every /_xerj-console/
+// static asset is intercepted and served from the working tree, so this
+// exercises the REAL new code end-to-end (auth, live graph API, canvas).
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const BASE = 'http://localhost:9200';
+const TOKEN = process.argv[2];
+const EMAIL = process.argv[4] || '[email protected]';
+const OUT = process.argv[3] || '/tmp/mapshots';
+const UX = '/home/claude/ai/xerj/xerj-ux';
+fs.mkdirSync(OUT, { recursive: true });
+const say = (s) => console.log(s);
+
+const MIME = { '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml' };
+
+const browser = await puppeteer.launch({
+ headless: 'new',
+ executablePath: '/usr/bin/google-chrome',
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+page.on('console', (m) => { if (m.type() === 'error') say('PAGE ERROR: ' + m.text().slice(0, 200)); });
+page.on('response', (r) => { if (r.status() >= 400) say('HTTP ' + r.status() + ' ' + r.url()); });
+page.on('pageerror', (e) => say('PAGE EXCEPTION: ' + String(e).slice(0, 300)));
+
+// serve fresh UX from disk
+await page.setRequestInterception(true);
+page.on('request', (req) => {
+ const u = new URL(req.url());
+ if (u.origin === BASE && u.pathname.startsWith('/_xerj-console/') && !u.pathname.startsWith('/_xerj-console/api/')) {
+ let rel = u.pathname.slice('/_xerj-console/'.length);
+ if (rel === '' || rel === 'setup' || rel === 'login') rel = rel ? `${rel}.html` : 'index.html';
+ const file = path.join(UX, rel);
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) {
+ req.respond({
+ status: 200,
+ headers: { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-cache' },
+ body: fs.readFileSync(file),
+ });
+ return;
+ }
+ }
+ req.continue();
+});
+
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true,
+ hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
+});
+
+// ── claim (if needed) ──
+const me = await page.goto(`${BASE}/_xerj-console/api/v1/me`, { waitUntil: 'networkidle0' });
+if (me.status() === 401) {
+ if (!TOKEN) { say('NEEDS TOKEN'); process.exit(1); }
+ await page.evaluateOnNewDocument((em) => { window.__email = em; }, EMAIL);
+ await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+ await new Promise((r) => setTimeout(r, 1200));
+ await page.evaluate(() => {
+ const v = { email: window.__email || '[email protected]', display: 'Verify', pk: 'demo-key' };
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ el.value = el.type === 'email' || k.includes('email') ? v.email
+ : (k.includes('passkey') || k.includes('pkname')) ? v.pk : v.display;
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ });
+ await page.evaluate(() => {
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+ });
+ await new Promise((r) => setTimeout(r, 5000));
+ say('after claim: ' + page.url());
+ if (/setup/.test(page.url())) {
+ say('CLAIM FAILED: ' + (await page.evaluate(() => document.body.innerText.slice(0, 300))));
+ await browser.close(); process.exit(1);
+ }
+}
+
+const mapState = () => page.evaluate(async () => {
+ const m = await import('/_xerj-console/src/ux/brain-map.js');
+ return m.sbMapState();
+});
+const shot = async (n) => { await page.screenshot({ path: `${OUT}/${n}.png` }); say(' shot ' + n); };
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// canvas click helper: hit-rect center in canvas coords → page coords
+async function clickHit(pred, pick) {
+ const st = await mapState();
+ const cands = st.hits.filter(pred);
+ const hit = pick ? pick(cands, st) : cands[0];
+ if (!hit) { say('NO HIT for predicate'); return null; }
+ const box = await (await page.$('[data-sb-map-canvas]')).boundingBox();
+ let x; let y;
+ if (hit.seg) { const [x1, y1, x2, y2] = hit.seg; x = box.x + (x1 + x2) / 2; y = box.y + (y1 + y2) / 2; }
+ else { x = box.x + hit.x + hit.w / 2; y = box.y + hit.y + hit.h / 2; }
+ await page.mouse.click(x, y);
+ return hit;
+}
+
+// ── docs brain: clustered mode ──
+await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=docs`, { waitUntil: 'networkidle0' });
+await sleep(6000);
+const dbg = await page.evaluate(async () => {
+ const m = await import('/_xerj-console/src/ux/brain-map.js');
+ const api = await import('/_xerj-console/src/data/second-brain-api.js');
+ const snap = api.sbSnapshot();
+ let mountErr = null;
+ try { m.mountBrainMap(); } catch (e) { mountErr = String((e && e.stack) || e); }
+ return { snapBrain: snap.brain, hasOv: !!snap.overview, edges: snap.overview && snap.overview.edges, baseUrl: snap.baseUrl, mapEl: !!document.querySelector('[data-sb-map]'), mount: !!document.querySelector('[data-sb-map-mount]'), waiting: !!document.querySelector('[data-sb-map-waiting]'), mountErr };
+});
+say('mount debug: ' + JSON.stringify(dbg));
+await sleep(3000);
+let st = await mapState();
+say('docs map state: ' + JSON.stringify({ status: st.status, mode: st.mode, fileNodes: st.fileNodes, clusters: st.clusters, bundles: st.bundles, statusLine: st.statusLine, error: st.error }));
+await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-map]');
+ el && el.scrollIntoView({ block: 'start' });
+ window.scrollBy(0, -80);
+});
+await sleep(600);
+await shot('m1-helicopter');
+
+// expand the rank-0 cluster
+const chit = await clickHit((h) => h.kind === 'cluster' && h.ci === 0);
+say('clicked cluster: ' + JSON.stringify(chit && { ci: chit.ci }));
+await sleep(900); // 240ms anim + name hydration
+st = await mapState();
+say('after expand: ' + JSON.stringify({ expanded: st.expanded, spread: st.spread, sel: st.sel }));
+await shot('m2-expanded');
+
+// select a member
+const mhit = await clickHit((h) => h.kind === 'member' && !h.seg, (cands, st) => {
+ // farthest labelled member from the expanded centroid, clear of other text
+ const texts = st.hits.filter((h) => !h.seg && h.kind !== 'member');
+ const free = cands.filter((c) => c.w > 20 && !texts.some((t) => c.x < t.x + t.w && t.x < c.x + c.w && c.y < t.y + t.h && t.y < c.y + c.h));
+ return free[free.length - 1] || cands[cands.length - 1];
+});
+await sleep(700);
+st = await mapState();
+say('member sel: ' + JSON.stringify(st.sel));
+await shot('m3-member-rail');
+const railText = await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-map-rail]');
+ return el ? el.innerText.slice(0, 600) : '(no rail)';
+});
+say('RAIL:\n' + railText);
+
+// explore 2 hops
+const expBtn = await page.$('[data-sb-map-explore]');
+if (expBtn) {
+ await expBtn.click();
+ await sleep(1500);
+ say('EXPLORE RAIL:\n' + await page.evaluate(() => document.querySelector('[data-sb-map-rail]').innerText.slice(0, 700)));
+ await shot('m4-explore');
+}
+
+// fold away, then open a bundle line
+await page.click('[data-sb-map-collapse]').catch(() => {});
+await sleep(600);
+const bhit = await clickHit((h) => h.kind === 'bundle', (cands, st) => {
+ const texts = st.hits.filter((h) => !h.seg);
+ return cands.find((c) => {
+ const [x1, y1, , y2] = c.seg;
+ const mx = (x1 + c.seg[2]) / 2; const my = (y1 + y2) / 2;
+ return !texts.some((t) => mx >= t.x && mx <= t.x + t.w && my >= t.y && my <= t.y + t.h);
+ }) || cands[0];
+});
+await sleep(1200);
+st = await mapState();
+say('bundle sel: ' + JSON.stringify(st.sel));
+await shot('m5-bundle-evidence');
+say('BUNDLE RAIL:\n' + await page.evaluate(() => document.querySelector('[data-sb-map-rail]').innerText.slice(0, 800)));
+
+// belief-time preview event (the shared caret contract)
+await page.evaluate(() => {
+ document.dispatchEvent(new CustomEvent('sb:asof-preview', { detail: { ms: Date.now() - 400 * 864e5 } }));
+});
+await sleep(400);
+await shot('m6-asof-preview');
+await page.evaluate(() => {
+ document.dispatchEvent(new CustomEvent('sb:asof-commit', { detail: { ms: null } }));
+});
+
+// FIND highlight
+await page.evaluate(() => {
+ const inp = document.querySelector('[data-sb-find]');
+ if (inp) {
+ inp.value = 'wordpress';
+ inp.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+});
+await sleep(1500);
+await shot('m7-find-highlight');
+
+// ── notes brain: direct mode ──
+await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=notes`, { waitUntil: 'networkidle0' });
+await sleep(5000);
+st = await mapState();
+say('notes map state: ' + JSON.stringify({ status: st.status, mode: st.mode, fileNodes: st.fileNodes, statusLine: st.statusLine }));
+await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-map]');
+ el && el.scrollIntoView({ block: 'start' });
+ window.scrollBy(0, -80);
+});
+await sleep(600);
+await shot('m8-direct-mode');
+
+// ── gtm brain: 10k links, PDF-heavy, 13 groups, retired links ──
+await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=gtm`, { waitUntil: 'networkidle0' });
+await sleep(8000);
+st = await mapState();
+say('gtm map state: ' + JSON.stringify({ status: st.status, mode: st.mode, fileNodes: st.fileNodes, clusters: st.clusters, bundles: st.bundles, statusLine: st.statusLine, error: st.error }));
+await page.evaluate(() => {
+ const el = document.querySelector('[data-sb-map]');
+ el && el.scrollIntoView({ block: 'start' });
+ window.scrollBy(0, -80);
+});
+await sleep(600);
+await shot('m9-gtm-helicopter');
+await clickHit((h) => h.kind === 'cluster' && h.ci === 0);
+await sleep(1200);
+await shot('m10-gtm-expanded');
+say('gtm rail: ' + (await page.evaluate(() => document.querySelector('[data-sb-map-rail]').innerText.slice(0, 400))));
+
+await browser.close();
+say('done');
diff --git a/docs/examples/second-brain-capture/navcheck.mjs b/docs/examples/second-brain-capture/navcheck.mjs
new file mode 100644
index 000000000..cc5c80713
--- /dev/null
+++ b/docs/examples/second-brain-capture/navcheck.mjs
@@ -0,0 +1,80 @@
+// Conditional-nav verification: does "Second Brain" appear in the nav?
+// argv[2] = setup token (only needed on an unclaimed server)
+// argv[3] = screenshot name
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const BASE = 'http://localhost:9200';
+const TOKEN = process.argv[2] && process.argv[2] !== '-' ? process.argv[2] : null;
+const NAME = process.argv[3] || 'navcheck';
+const OUT = '/tmp/claude-1001/-home-claude-ai-xerj/e36b8c4c-3a94-4a76-80f1-2119380319c6/scratchpad/graphshots';
+const UX = '/home/claude/ai/xerj/xerj-ux';
+fs.mkdirSync(OUT, { recursive: true });
+const say = (s) => console.log(s);
+const MIME = { '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml' };
+
+const browser = await puppeteer.launch({
+ headless: 'new', executablePath: '/usr/bin/google-chrome',
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+await page.setRequestInterception(true);
+page.on('request', (req) => {
+ const u = new URL(req.url());
+ if (u.origin === BASE && u.pathname.startsWith('/_xerj-console/') && !u.pathname.startsWith('/_xerj-console/api/')) {
+ let rel = u.pathname.slice('/_xerj-console/'.length);
+ if (rel === '' || rel === 'setup' || rel === 'login') rel = rel ? `${rel}.html` : 'index.html';
+ const file = path.join(UX, rel);
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) {
+ req.respond({ status: 200, headers: { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-cache' }, body: fs.readFileSync(file) });
+ return;
+ }
+ }
+ req.continue();
+});
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
+});
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const me = await page.goto(`${BASE}/_xerj-console/api/v1/me`, { waitUntil: 'networkidle0' });
+if (me.status() === 401) {
+ if (!TOKEN) { say('NEEDS TOKEN'); process.exit(1); }
+ await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+ await sleep(1200);
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ el.value = el.type === 'email' || k.includes('email') ? '[email protected]'
+ : (k.includes('passkey') || k.includes('pkname')) ? 'demo-key' : 'Verify';
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ });
+ await page.evaluate(() => {
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+ });
+ await sleep(5000);
+ if (/setup/.test(page.url())) { say('CLAIM FAILED: ' + (await page.evaluate(() => document.body.innerText.slice(0, 300)))); await browser.close(); process.exit(1); }
+}
+
+await page.goto(`${BASE}/_xerj-console/#/dashboards`, { waitUntil: 'networkidle0' });
+await sleep(6000); // probe tick + potential re-render
+const navText = await page.evaluate(() => document.body.innerText);
+const inNav = /second brain/i.test(navText);
+say('NAV LISTS SECOND BRAIN: ' + inNav);
+await page.screenshot({ path: `${OUT}/${NAME}.png` });
+say('shot ' + NAME);
+// deep-link must still resolve even when nav hides it
+await page.goto(`${BASE}/_xerj-console/#/second-brain`, { waitUntil: 'networkidle0' });
+await sleep(4000);
+const deep = await page.evaluate(() => document.body.innerText.slice(0, 1200));
+say('DEEP LINK BODY HEAD:\n' + deep.slice(0, 600));
+await page.screenshot({ path: `${OUT}/${NAME}-deeplink.png` });
+say('shot ' + NAME + '-deeplink');
+await browser.close();
diff --git a/docs/examples/second-brain-capture/regress_small.mjs b/docs/examples/second-brain-capture/regress_small.mjs
new file mode 100644
index 000000000..0c20849d1
--- /dev/null
+++ b/docs/examples/second-brain-capture/regress_small.mjs
@@ -0,0 +1,62 @@
+// Regression: docs (clustered, 435 links) + notes (direct mode) after
+// the layout/view changes.
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+import path from 'node:path';
+const BASE = 'http://localhost:9200';
+const OUT = '/tmp/claude-1001/-home-claude-ai-xerj/e36b8c4c-3a94-4a76-80f1-2119380319c6/scratchpad/graphshots';
+const UX = '/home/claude/ai/xerj/xerj-ux';
+const say = (s) => console.log(s);
+const MIME = { '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml' };
+const browser = await puppeteer.launch({ headless: 'new', executablePath: '/usr/bin/google-chrome', args: ['--no-sandbox', '--disable-dev-shm-usage'] });
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+await page.setRequestInterception(true);
+page.on('request', (req) => {
+ const u = new URL(req.url());
+ if (u.origin === BASE && u.pathname.startsWith('/_xerj-console/') && !u.pathname.startsWith('/_xerj-console/api/')) {
+ let rel = u.pathname.slice('/_xerj-console/'.length);
+ if (rel === '' || rel === 'setup' || rel === 'login') rel = rel ? `${rel}.html` : 'index.html';
+ const file = path.join(UX, rel);
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) {
+ req.respond({ status: 200, headers: { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-cache' }, body: fs.readFileSync(file) });
+ return;
+ }
+ }
+ req.continue();
+});
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } });
+const TOKEN = process.argv[2];
+const me = await page.goto(`${BASE}/_xerj-console/api/v1/me`, { waitUntil: 'networkidle0' });
+if (me.status() === 401) {
+ await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+ await new Promise((r) => setTimeout(r, 1200));
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ el.value = el.type === 'email' || k.includes('email') ? `rg-${Date.now()}@example.com` : (k.includes('passkey') || k.includes('pkname')) ? 'k' : 'V';
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+ });
+ await new Promise((r) => setTimeout(r, 5000));
+ say('claim → ' + page.url());
+}
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const mapState = () => page.evaluate(async () => (await import('/_xerj-console/src/ux/brain-map.js')).sbMapState());
+for (const brain of ['docs', 'notes']) {
+ await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=${brain}`, { waitUntil: 'networkidle0' });
+ let st = null;
+ for (let i = 0; i < 40; i++) { st = await mapState().catch(() => null); if (st && st.status === 'ready') break; await sleep(1000); }
+ say(`${brain}: ` + JSON.stringify({ status: st && st.status, mode: st && st.mode, fileNodes: st && st.fileNodes, clusters: st && st.clusters, bundles: st && st.bundles, statusLine: st && st.statusLine, error: st && st.error }));
+ await page.evaluate(() => { const el = document.querySelector('[data-sb-map]'); el && el.scrollIntoView({ block: 'start' }); window.scrollBy(0, -70); });
+ await sleep(700);
+ await page.screenshot({ path: `${OUT}/regress-${brain}.png` });
+ say(' shot regress-' + brain);
+}
+await browser.close();
+say('done');
diff --git a/docs/examples/second-brain-capture/sb_capture.mjs b/docs/examples/second-brain-capture/sb_capture.mjs
new file mode 100644
index 000000000..0ace839c5
--- /dev/null
+++ b/docs/examples/second-brain-capture/sb_capture.mjs
@@ -0,0 +1,87 @@
+// One session: claim the console, then capture every second-brain state:
+// dashboard, the ledger, evidence quotes expanded, and time-travel after a retire.
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+
+const BASE = process.argv[2], TOKEN = process.argv[3], OUT = process.argv[4];
+const say = (s) => console.log(s);
+fs.mkdirSync(OUT, { recursive: true });
+
+const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true,
+ hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
+});
+
+// ── claim ──
+await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+await new Promise((r) => setTimeout(r, 1200));
+await page.evaluate(() => {
+ const v = { email: '[email protected]', display: 'Owner', pk: 'demo-key' };
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ el.value = el.type === 'email' || k.includes('email') ? v.email
+ : (k.includes('passkey') || k.includes('pkname')) ? v.pk : v.display;
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+});
+await page.evaluate(() => {
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+});
+await new Promise((r) => setTimeout(r, 5000));
+say('after claim: ' + page.url());
+if (/setup/.test(page.url())) {
+ say('CLAIM FAILED: ' + (await page.evaluate(() => document.body.innerText.slice(0, 300))));
+ await browser.close(); process.exit(1);
+}
+
+const go = async () => {
+ await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=notes`, { waitUntil: 'networkidle0' });
+ await new Promise((r) => setTimeout(r, 6500));
+};
+const shot = async (n, o = {}) => { await page.screenshot({ path: `${OUT}/${n}.png`, ...o }); say(' shot ' + n); };
+const ledgerText = () => page.evaluate(() => {
+ const el = [...document.querySelectorAll('*')].find((n) => (n.innerText || '').includes('THE LEDGER · ONE NOTE'));
+ return el ? el.innerText.slice(0, 2500) : '(not found)';
+});
+
+// ── 1. dashboard top ──
+await go();
+await shot('01-dashboard-top');
+
+// ── 2. the ledger, scrolled into view ──
+await page.evaluate(() => {
+ const el = [...document.querySelectorAll('*')].reverse()
+ .find((n) => (n.innerText || '').includes('THE LEDGER · ONE NOTE') && n.children.length < 40);
+ (el || document.body).scrollIntoView({ block: 'start' });
+ window.scrollBy(0, -60);
+});
+await new Promise((r) => setTimeout(r, 900));
+await shot('02-ledger');
+
+// ── 3. expand evidence quotes ──
+const n = await page.evaluate(() => {
+ const t = [...document.querySelectorAll('button,a,span,div')]
+ .filter((x) => ['QUOTE', 'WHY'].includes((x.innerText || '').trim()) && x.children.length === 0);
+ t.slice(0, 6).forEach((x) => x.click());
+ return t.length;
+});
+say('evidence toggles: ' + n);
+await new Promise((r) => setTimeout(r, 1400));
+await shot('03-evidence');
+fs.writeFileSync(`${OUT}/ledger-evidence.txt`, await ledgerText());
+
+// ── 4. full page (everything) ──
+await shot('04-full', { fullPage: true });
+
+await browser.close();
+say('done');
diff --git a/docs/examples/second-brain-capture/sb_dash_verify.mjs b/docs/examples/second-brain-capture/sb_dash_verify.mjs
new file mode 100644
index 000000000..fb9e76e42
--- /dev/null
+++ b/docs/examples/second-brain-capture/sb_dash_verify.mjs
@@ -0,0 +1,208 @@
+// Live verification of the second-brain dashboard composition +
+// statistics panel + ledger integration, against a running console.
+// node sb_dash_verify.mjs <base> <outdir> [token]
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+
+const BASE = process.argv[2] || 'http://localhost:9200';
+const OUT = process.argv[3] || '/tmp/sbdash';
+const TOKEN = process.argv[4] || '';
+fs.mkdirSync(OUT, { recursive: true });
+const say = (s) => console.log(s);
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true,
+ hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },
+});
+page.on('console', (m) => { if (m.type() === 'error') say(' [console.error] ' + m.text().slice(0, 160)); });
+page.on('pageerror', (e) => say(' [pageerror] ' + String(e).slice(0, 200)));
+
+const go = async () => {
+ await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=docs`, { waitUntil: 'networkidle0' });
+ await sleep(5000);
+};
+
+await go();
+let url = page.url();
+say('landed: ' + url);
+if (/setup|login|claim/i.test(url) && TOKEN) {
+ say('claiming with token…');
+ await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+ await sleep(1200);
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ // Unique per run — enrolment 409s on an email that is already registered.
+ el.value = el.type === 'email' || k.includes('email') ? `verify${Date.now() % 1e7}@example.com`
+ : (k.includes('passkey') || k.includes('pkname')) ? 'verify-key' : 'Owner';
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ });
+ await page.evaluate(() => {
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+ });
+ await sleep(5000);
+ say('after claim: ' + page.url());
+ await go();
+}
+
+const results = [];
+const check = async (label, fn) => {
+ let v;
+ try { v = await fn(); } catch (e) { v = 'THREW ' + String(e).slice(0, 120); }
+ results.push([label, v]);
+ say(`${v === true ? 'PASS' : 'FAIL'} ${label}${v === true ? '' : ' → ' + JSON.stringify(v).slice(0, 220)}`);
+};
+const $text = (sel) => page.evaluate((s) => {
+ const el = document.querySelector(s);
+ return el ? el.innerText : null;
+}, sel);
+const has = (sel) => page.evaluate((s) => !!document.querySelector(s), sel);
+
+// ---- 1. composition: panel order -----------------------------------
+await check('panels present + §1.1 order (controls→map→scrub→stats→ego)', async () => {
+ const ids = await page.evaluate(() =>
+ [...document.querySelectorAll('[data-sb-body]')].map((e) => e.getAttribute('data-sb-body')));
+ const want = ['controls', 'map', 'scrub', 'edgesLive', 'edgesTotal', 'invalidated', 'detectors',
+ 'typeDist', 'edgeTimeline', 'notes', 'crossings', 'reads', 'ego', 'hubs', 'notShown'];
+ return JSON.stringify(ids) === JSON.stringify(want) ? true : ids;
+});
+await check('map mount + permanent structural disclosure', async () => {
+ const t = await $text('[data-sb-body="map"]');
+ return t && t.includes('GROUPED BY LINK STRUCTURE — CITATIONS AND FOLDER NEIGHBORHOOD, NOT MEANING') ? true : t;
+});
+await check('scrubber is its own panel (and not inside the ledger)', async () => {
+ const inScrub = await has('[data-sb-body="scrub"] [data-sb-scrub]');
+ const inEgo = await has('[data-sb-body="ego"] [data-sb-scrub]');
+ return inScrub && !inEgo ? true : { inScrub, inEgo };
+});
+await check('controls hoisted to top (brain/focus/find)', async () => {
+ const inCtl = await has('[data-sb-body="controls"] [data-sb-find]');
+ const inEgo = await has('[data-sb-body="ego"] .sb-controls');
+ return inCtl && !inEgo ? true : { inCtl, inEgo };
+});
+
+// ---- 2. statistics row ---------------------------------------------
+await check('notes tile: total + file types (ran numbers)', async () => {
+ const t = await $text('[data-sb-body="notes"]');
+ return t && /\d/.test(t) && /notes/i.test(t) && /PROSE|LINES|JSON|YAML|MARKDOWN/i.test(t) ? true : t;
+});
+await check('crossings: honest pre-stamp REINDEX message', async () => {
+ const t = await $text('[data-sb-body="crossings"]');
+ return t && (t.includes('REINDEX TO SEE FILE-TYPE CROSSINGS') || t.includes('crossings')) ? true : t;
+});
+await check('embedder disclosure present', async () => {
+ const t = await $text('[data-sb-body="crossings"]');
+ return t && t.includes('NOT MEANING') && t.includes('lexical-feature-hash') ? true : t;
+});
+await check('read log: attributed rows (what — how much — why)', async () => {
+ const t = await $text('[data-sb-body="reads"]');
+ return t && t.includes('one overview read') && t.includes('the tiles on this page')
+ && t.includes('finding your brains') ? true : t;
+});
+await check('read log: 2-hop walk attributed to the focus', async () => {
+ const t = await $text('[data-sb-body="reads"]');
+ return t && t.includes('2-hop walk') && t.includes('you focused this note') ? true : t;
+});
+await check('server counters: since-server-start framing (or honest refusal)', async () => {
+ const t = await $text('[data-sb-body="reads"]');
+ return t && t.includes('SINCE SERVER START')
+ && (t.includes('links of brain') || t.includes('UNREADABLE') || t.includes('NO SEARCHES')) ? true : t;
+});
+await check('read-attribution refusal line present', async () => {
+ const t = await $text('[data-sb-body="reads"]');
+ return t && t.includes('not recorded by the engine') ? true : t;
+});
+
+// ---- 3. ledger integration -----------------------------------------
+await check('ledger renders with focus card + path label', async () => {
+ const t = await $text('[data-sb-body="ego"]');
+ return t && t.includes('FOCUS') ? true : (t || '').slice(0, 150);
+});
+await check('refocus via hub click updates ledger + read log', async () => {
+ const before = await $text('.sb-focuscard .sb-ftitle');
+ const clicked = await page.evaluate(() => {
+ const rows = [...document.querySelectorAll('[data-sb-body="hubs"] .sb-hubrow')];
+ const other = rows.find((r) => !r.classList.contains('sb-hub-active'));
+ if (!other) return false;
+ other.click();
+ return true;
+ });
+ if (!clicked) return 'no non-active hub row';
+ await sleep(2500);
+ const after = await $text('.sb-focuscard .sb-ftitle');
+ const log = await $text('[data-sb-body="reads"]');
+ return after && after !== before && log.includes('2-hop walk') ? true : { before, after };
+});
+await check('belief-time commit from the standalone scrubber', async () => {
+ const strip = await page.$('[data-sb-body="scrub"] [data-sb-strip]');
+ if (!strip) return 'no strip';
+ // The 55vh map sits above the scrubber — bring the strip on-screen
+ // or the synthetic pointer lands outside the viewport (a no-op).
+ await strip.scrollIntoView();
+ await sleep(300);
+ const box = await strip.boundingBox();
+ await page.mouse.click(box.x + box.width * 0.5, box.y + box.height / 2);
+ await sleep(2500);
+ const ctl = await $text('[data-sb-body="controls"]');
+ return ctl && ctl.includes('BACK TO NOW') ? true : ctl && ctl.slice(0, 200);
+});
+await check('ledger rows restate under the committed as-of', async () => {
+ const t = await $text('[data-sb-body="scrub"]');
+ return t && /BELIEVED AT THIS MOMENT/.test(t) ? true : t;
+});
+// back to NOW
+await page.evaluate(() => { const b = document.querySelector('[data-sb-now]'); b && b.click(); });
+await sleep(2000);
+await check('FIND logs its search + returns refocus links', async () => {
+ await page.type('[data-sb-find]', 'security');
+ await sleep(1500);
+ const slotShown = await page.evaluate(() => {
+ const s = document.querySelector('[data-sb-findresults]');
+ return s && !s.hidden && s.innerText.length > 0;
+ });
+ const log = await $text('[data-sb-body="reads"]');
+ return slotShown && log.includes('you typed in FIND') ? true : { slotShown };
+});
+await check('map placeholder honest when module absent (or live map mounted)', async () => {
+ const t = await $text('[data-sb-body="map"]');
+ const live = await has('[data-sb-map][data-sb-map-live]');
+ return live || (t && (t.includes('NOT IN THIS BUILD') || t.includes('THE MAP DRAWS HERE'))) ? true : t;
+});
+await check('live map: canvas mounted, panel patching spared it', async () => {
+ const live = await has('[data-sb-map][data-sb-map-live] [data-sb-map-canvas]');
+ return live ? true : 'no live canvas (fails until the map slice lands — honest state covered above)';
+});
+await check('map fetch attributed in the shared read log', async () => {
+ const t = await $text('[data-sb-body="reads"]');
+ return t && t.includes('building the map') ? true
+ : 'no map read logged (map slice not mounted yet)';
+});
+
+// ---- screenshots (evidence) ----------------------------------------
+await page.evaluate(() => window.scrollTo(0, 0));
+await sleep(400);
+await page.screenshot({ path: `${OUT}/01-top-controls-map-scrub.png` });
+await page.evaluate(() => document.querySelector('[data-sb-body="notes"]')?.scrollIntoView({ block: 'center' }));
+await sleep(400);
+await page.screenshot({ path: `${OUT}/02-statistics-row.png` });
+await page.evaluate(() => document.querySelector('[data-sb-body="ego"]')?.scrollIntoView());
+await sleep(400);
+await page.screenshot({ path: `${OUT}/03-ledger.png` });
+await page.screenshot({ path: `${OUT}/04-full.png`, fullPage: true });
+
+const fails = results.filter(([, v]) => v !== true).length;
+say(fails === 0 ? `ALL ${results.length} CHECKS PASS` : `${fails}/${results.length} CHECKS FAILED`);
+await browser.close();
+process.exit(fails ? 1 : 0);
diff --git a/docs/examples/second-brain-capture/sb_retire.mjs b/docs/examples/second-brain-capture/sb_retire.mjs
new file mode 100644
index 000000000..d232a6ec2
--- /dev/null
+++ b/docs/examples/second-brain-capture/sb_retire.mjs
@@ -0,0 +1,59 @@
+// Retire one link over the API, then screenshot the dashboard so the
+// "RETIRED · KEPT FOR REPLAY" state is visible in the UI (claim 2).
+import puppeteer from 'puppeteer';
+import fs from 'node:fs';
+
+const BASE = process.argv[2], TOKEN = process.argv[3], OUT = process.argv[4];
+const say = (s) => console.log(s);
+fs.mkdirSync(OUT, { recursive: true });
+
+// 1. pick a live edge and retire it (plain HTTP, before the browser work)
+const ov = await (await fetch(`${BASE}/_graph/notes/overview`)).json();
+const hub = ov.hubs.out[0].id;
+const ego = await (await fetch(`${BASE}/_graph/notes/ego?node=${hub}&hops=1`)).json();
+const edge = ego.edges.find((e) => e.evidence && e.evidence.quote) || ego.edges[0];
+const t = Date.now();
+const del = await (await fetch(`${BASE}/_graph/notes/link/${edge.edge_id}?invalid_at=${t}`, { method: 'DELETE' })).json();
+say('retired ' + edge.edge_id + ' -> ' + JSON.stringify(del));
+const after = await (await fetch(`${BASE}/_graph/notes/overview`)).json();
+say('overview now: ' + JSON.stringify(after.edges));
+fs.writeFileSync(`${OUT}/retire.json`, JSON.stringify({ retired: edge.edge_id, del, edges: after.edges, hub }, null, 2));
+
+// 2. claim console + screenshot the retired state
+const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'] });
+const page = await browser.newPage();
+await page.setViewport({ width: 1500, height: 1000, deviceScaleFactor: 1.5 });
+const cdp = await page.createCDPSession();
+await cdp.send('WebAuthn.enable');
+await cdp.send('WebAuthn.addVirtualAuthenticator', {
+ options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true,
+ hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } });
+await page.goto(`${BASE}/_xerj-console/setup#token=${TOKEN}`, { waitUntil: 'networkidle0' });
+await new Promise((r) => setTimeout(r, 1200));
+await page.evaluate(() => {
+ const v = { email: '[email protected]', display: 'Owner', pk: 'demo-key' };
+ for (const el of document.querySelectorAll('input')) {
+ if (['hidden', 'submit', 'button'].includes(el.type)) continue;
+ const k = ((el.name || '') + (el.id || '') + (el.placeholder || '')).toLowerCase();
+ el.value = el.type === 'email' || k.includes('email') ? v.email
+ : (k.includes('passkey') || k.includes('pkname')) ? v.pk : v.display;
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+});
+await page.evaluate(() => {
+ const b = [...document.querySelectorAll('button')].find((x) => /enrol|create|claim/i.test(x.innerText));
+ b && b.click();
+});
+await new Promise((r) => setTimeout(r, 5000));
+if (/setup/.test(page.url())) { say('CLAIM FAILED'); await browser.close(); process.exit(1); }
+
+await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=notes`, { waitUntil: 'networkidle0' });
+await new Promise((r) => setTimeout(r, 6500));
+await page.screenshot({ path: `${OUT}/05-retired-top.png` });
+fs.writeFileSync(`${OUT}/retired.txt`, await page.evaluate(() => document.body.innerText.slice(0, 3000)));
+// focus the node whose edge we retired, include retired rows
+await page.goto(`${BASE}/_xerj-console/#/second-brain?brain=notes&node=${process.argv[5] || ''}`, { waitUntil: 'networkidle0' }).catch(() => {});
+await new Promise((r) => setTimeout(r, 4000));
+await page.screenshot({ path: `${OUT}/06-retired-full.png`, fullPage: true });
+await browser.close();
+say('done');