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.

ux(second-brain): verified dashboard + ego-ledger slice — evidence-honesty pass + 3 review fixes

xerj-org0a0d54153a1f
diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.css
index dfd83a765..d83943f55 100644
--- a/xerj-ux/assets/base.css
+++ b/xerj-ux/assets/base.css
@@ -2014,6 +2014,134 @@ html.mobile-preview .nav-sub {
user-select: all; /* one click selects the whole command */
}
+/* Evidence chips — QUOTE (authored text) keeps the ink treatment;
+ WHY (structural rationale) and NO EVIDENCE are muted: they must
+ never carry the same visual promise as a real quote. */
+.sb-eq-why { color: var(--z-mute); }
+.sb-eq-none { color: var(--z-mute); opacity: 0.75; }
+
+/* Structural rationale in the paper trail: data face, mute ink, faint
+ rule — deliberately NOT the quote treatment (prose face, accent
+ rule, quotation marks). The style is the honesty. */
+.sb-evwhy {
+ font-family: var(--font-data);
+ font-size: var(--fs-13);
+ line-height: 1.6;
+ color: var(--z-mute);
+ border-left: 1px solid var(--z-faint);
+ padding-left: var(--sp-2);
+ margin: 4px 0 8px;
+}
+
+/* Floating evidence preview (hover / keyboard focus). Display-only:
+ pointer-events none so it can never steal the click that pins. */
+.sb-evpreview {
+ position: fixed;
+ z-index: 60; /* above the ledger; below nothing it needs to yield to */
+ max-width: 44ch;
+ background: var(--z-paper);
+ border: 1px solid var(--z-faint);
+ padding: var(--sp-2);
+ pointer-events: none;
+}
+.sb-evpreview .sb-evquote,
+.sb-evpreview .sb-evwhy { margin: 0 0 6px; }
+
+/* One-shot flash on rows the last time-travel flipped. */
+@keyframes sb-flipflash {
+ from { outline-color: var(--z-accent); }
+ to { outline-color: transparent; }
+}
+.sb-erow.sb-flip {
+ outline: 1px solid transparent;
+ outline-offset: -1px;
+ animation: sb-flipflash 0.6s ease-out;
+}
+
+/* What-changed readout in the scrubber legend (mid slot, own line). */
+.sb-changeout { display: block; margin-top: 2px; color: var(--z-ink); }
+
+/* Assertion ticks on the belief-count curve — snap targets, muted. */
+.sb-atick { color: var(--z-mute); }
+
+/* FIND — the house frameless-input pattern (.filter-bar .kql),
+ inlined into the controls row. */
+.sb-cfind {
+ display: inline-flex;
+ align-items: baseline;
+ gap: var(--sp-2);
+ flex: 1 1 180px;
+ min-width: 140px;
+}
+.sb-findinput {
+ flex: 1;
+ min-width: 0;
+ background: none;
+ border: 0;
+ border-bottom: 1px solid var(--z-faint);
+ font-family: var(--font-data);
+ font-size: var(--fs-13);
+ color: var(--z-ink);
+ padding: 2px 0;
+ text-transform: none;
+ letter-spacing: 0;
+ outline: none;
+}
+.sb-findinput:focus { border-bottom-color: var(--z-accent); }
+.sb-findinput::placeholder { color: var(--z-mute); opacity: 0.6; }
+.sb-findresults {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: var(--sp-1) var(--sp-2);
+ padding: var(--sp-1) 0 var(--sp-2);
+ border-bottom: 1px solid var(--z-faint);
+ margin-bottom: var(--sp-2);
+ font-size: var(--fs-13);
+}
+.sb-findrow { font-family: var(--font-data); }
+
+/* Group headers are buttons now (client-side fold); the global button
+ reset keeps the look — this only restores full-width flex. */
+button.sb-grouphead { width: 100%; }
+.sb-ghcaret {
+ display: inline-block;
+ width: 12px;
+ font-size: 9px;
+ color: var(--z-mute);
+}
+
+/* RETIRED panel churn rows: dashed — the visual grammar of retirement
+ everywhere on this page — each with the evidence it carried. */
+.sb-retrows { margin-top: var(--sp-2); }
+.sb-retrow {
+ display: block;
+ width: 100%;
+ text-align: left;
+ padding: 4px 0;
+ border-bottom: 1px dashed var(--z-faint);
+ font-family: var(--font-data);
+ font-size: var(--fs-11);
+}
+.sb-retrow:hover .sb-retpair,
+.sb-retrow:focus-visible .sb-retpair { color: var(--z-accent); }
+.sb-retpair {
+ display: block;
+ color: var(--z-ink);
+ text-decoration: line-through;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.sb-retwhen { color: var(--z-accent); }
+.sb-retev {
+ display: block;
+ color: var(--z-mute);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
/* Narrow screens: stack — focus card first, then in, then out. */
@media (max-width: 1100px) {
.sb-ledger { grid-template-columns: 1fr; row-gap: var(--sp-3); }
diff --git a/xerj-ux/src/dashboards/second-brain.js b/xerj-ux/src/dashboards/second-brain.js
index 7438b2f57..378e9fa69 100644
--- a/xerj-ux/src/dashboards/second-brain.js
+++ b/xerj-ux/src/dashboards/second-brain.js
@@ -34,7 +34,11 @@ export const secondBrain = {
sbAfterRender();
return {
title: 'SECOND BRAIN',
- kicker: 'WHAT YOUR NOTES BELIEVE · EVERY LINK HAS A QUOTE · REPLAYABLE AT ANY MOMENT',
+ // "EVERY LINK SHOWS ITS EVIDENCE", not "HAS A QUOTE": manual and
+ // agent-asserted links may carry no quote, and structural links
+ // carry a rationale, not note text. The kicker must not claim
+ // more than the schema enforces (spec §7.1, amended 2026-07-30).
+ kicker: 'WHAT YOUR NOTES BELIEVE · EVERY LINK SHOWS ITS EVIDENCE · REPLAYABLE AT ANY MOMENT',
meta: [time, 'XERJ-GRAPH'],
// Eyebrows speak user words — link / believed / retired / taught.
// Schema vocabulary (edge, src/dst, as-of) stays in the API and
diff --git a/xerj-ux/src/data/second-brain-api.js b/xerj-ux/src/data/second-brain-api.js
index 709f046a8..4d6da8274 100644
--- a/xerj-ux/src/data/second-brain-api.js
+++ b/xerj-ux/src/data/second-brain-api.js
@@ -25,6 +25,7 @@
import {
renderPanelBody, drawLedgerTraces, edgeStateAt, fmtTs, caretAlignClass,
+ EvidencePreview, FindResults, authoredSplit, splitLabel,
} from '../ux/ego-ledger.js';
/** Panel ids of the second-brain dashboard, in render order. The
@@ -59,7 +60,7 @@ const S = {
overviewError: null, // overview read failed on a REAL brain — an error state, never "empty"
brains: [],
brain: null,
- lastHashBrain: null, // last `?brain=` deep-link value already applied
+ lastHashApplied: null, // last deep-link query tail already applied
focus: null,
asOf: null, // epoch-ms | null = NOW
trail: [],
@@ -67,16 +68,54 @@ const S = {
ego: null, // §4.3 body — the belief at the caret
timeline: null, // §4.3 body — hop-1, include_expired, pinned at NOW
names: {}, // node id → { title } — display names for hub ids / crumbs
+ // Pinned paper trails (edge ids). Living here — NOT in the DOM — is
+ // the point: every patchPanels()/scrub commit re-renders rows from
+ // this set, so a pinned quote survives any re-render. Cleared on
+ // refocus (a new ledger is a new reading), never on an as-of commit.
+ openEvidence: new Set(),
+ collapsed: new Set(), // folded link-kind groups ("side:type"), per-brain
+ recentRetired: null, // three most recently retired links (RetiredPanel)
+ lastShift: null, // what the last time-travel changed (scrubber readout)
};
-/** `brain` out of the hash's query tail (`#/second-brain?brain=X`), or
- * null. The router (app.js parseRoute) ignores everything after `?`. */
-function hashBrain() {
+/**
+ * The deep-link query tail (`#/second-brain?brain=X&focus=Y&as_of=Z`),
+ * parsed: a URL that is a MOMENT in a brain's beliefs, not just a
+ * brain. The router (app.js parseRoute) ignores everything after `?`.
+ * `raw` is the verbatim tail so "already applied" is one comparison.
+ */
+function hashMoment() {
const h = location.hash || '';
const q = h.indexOf('?');
if (q < 0) return null;
- const b = (new URLSearchParams(h.slice(q + 1)).get('brain') || '').trim();
- return b || null;
+ const raw = h.slice(q + 1);
+ const p = new URLSearchParams(raw);
+ const brain = (p.get('brain') || '').trim() || null;
+ const focus = (p.get('focus') || '').trim() || null;
+ const asOfN = Number(p.get('as_of'));
+ const asOf = Number.isFinite(asOfN) && asOfN > 0 ? asOfN : null;
+ if (!brain && !focus && asOf == null) return null;
+ return { raw, brain, focus, asOf };
+}
+
+/**
+ * Write the current moment back into the hash (replaceState — no
+ * history spam) so the address bar is always a shareable artifact:
+ * copy it, and the receiver opens the same brain, the same note, the
+ * same point in belief time. Only touches the hash while ON the
+ * second-brain route.
+ */
+function writeMoment() {
+ if (typeof history === 'undefined' || typeof location === 'undefined') return;
+ if (!S.brain) return;
+ const h = location.hash || '';
+ if (!h.startsWith('#/second-brain')) return;
+ const qs = new URLSearchParams({ brain: S.brain });
+ if (S.focus) qs.set('focus', S.focus);
+ if (S.asOf != null) qs.set('as_of', String(S.asOf));
+ const raw = qs.toString();
+ S.lastHashApplied = raw; // our own write is by definition applied
+ try { history.replaceState(null, '', `#/second-brain?${raw}`); } catch { /* sandboxed */ }
}
function loadBrainState() {
@@ -86,8 +125,9 @@ function loadBrainState() {
S.focus = st.focus || null;
S.asOf = Number.isFinite(st.asOf) ? st.asOf : null;
S.trail = Array.isArray(st.trail) ? st.trail : [];
+ S.collapsed = new Set(Array.isArray(st.collapsed) ? st.collapsed : []);
} catch {
- S.focus = null; S.asOf = null; S.trail = [];
+ S.focus = null; S.asOf = null; S.trail = []; S.collapsed = new Set();
}
}
@@ -96,7 +136,10 @@ function saveBrainState() {
if (!S.brain) return;
sessionStorage.setItem(
K.perBrain(S.brain),
- JSON.stringify({ focus: S.focus, asOf: S.asOf, trail: S.trail.slice(-8) }),
+ JSON.stringify({
+ focus: S.focus, asOf: S.asOf, trail: S.trail.slice(-8),
+ collapsed: [...S.collapsed].slice(0, 64),
+ }),
);
} catch { /* storage full/blocked — view still works, just not sticky */ }
}
@@ -126,9 +169,16 @@ async function getJson(url, signal) {
* tolerate a JSON array in case a later build adds it. A wildcard
* matching nothing is an empty 200 — an engine with no brains is a
* normal state, not an error.
+ *
+ * The fetch pattern is `.xerj-memory-*` (prefix only): live-verified
+ * 2026-07-30 that this engine's index-pattern matcher supports a
+ * single leading or trailing `*` but NOT an infix wildcard —
+ * `.xerj-memory-*-edges` returns an empty 200 even when the index
+ * exists. The `-edges` cut happens in the client filter below either
+ * way, so the result set is identical.
*/
async function discoverBrains(baseUrl, signal) {
- const r = await fetch(`${baseUrl}/_cat/indices/.xerj-memory-*-edges`, { signal });
+ const r = await fetch(`${baseUrl}/_cat/indices/.xerj-memory-*`, { signal });
if (r.status === 404) return [];
if (!r.ok) throw new Error(`_cat/indices HTTP ${r.status}`);
const text = await r.text();
@@ -166,6 +216,7 @@ async function hydrateNames(signal) {
for (const h of (o.hubs && o.hubs.out) || []) ids.add(h.id);
for (const t of S.trail) ids.add(t);
if (S.focus) ids.add(S.focus);
+ for (const e of S.recentRetired || []) { ids.add(e.src); ids.add(e.dst); }
const want = [...ids].filter((id) => !(id in S.names)).slice(0, 40);
if (!want.length) return;
try {
@@ -199,6 +250,37 @@ function fetchOverview(signal) {
return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/overview?${qs}`, signal);
}
+/**
+ * The RETIRED panel's churn rows: the three most recently retired
+ * links, one bounded ordinary search on the edges index. Deliberately
+ * truth-now (not as-of-aware): "most recently retired" is a statement
+ * about the record, not about the caret. Best-effort — on any failure
+ * the rows simply don't render; the count above them is the truth
+ * either way.
+ */
+async function fetchRecentRetired(signal) {
+ const inval = S.overview && S.overview.exists !== false
+ && S.overview.edges && S.overview.edges.invalidated > 0;
+ if (!inval) { S.recentRetired = []; return; }
+ try {
+ const r = await fetch(`${S.baseUrl}/${enc(`.xerj-memory-${S.brain}-edges`)}/_search`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ query: { exists: { field: 'invalid_at' } },
+ sort: [{ invalid_at: { order: 'desc' } }],
+ size: 3,
+ _source: ['src', 'dst', 'type', 'detector', 'evidence', 'valid_at', 'invalid_at'],
+ }),
+ signal,
+ });
+ if (!r.ok) { S.recentRetired = null; return; }
+ const j = await r.json();
+ S.recentRetired = (((j.hits && j.hits.hits) || []))
+ .map((h) => ({ edge_id: h._id, ...(h._source || {}) }));
+ } catch { S.recentRetired = null; }
+}
+
/**
* The belief at the caret. `include_expired=true` so an invalidated
* fact comes back struck-through + RETIRED instead of silently gone;
@@ -240,6 +322,12 @@ function assemble() {
// Hints in user words, and as-of-aware: the same tile must say
// WHEN it is true once the belief caret leaves NOW.
const atHint = S.asOf != null ? `at ${fmtTs(S.asOf)} UTC` : 'right now';
+ // The detectors hint carries the authored/structural split — the
+ // honesty device that stops folder position from counting at par
+ // with written citations.
+ const detHint = detectors.length
+ ? splitLabel(authoredSplit(detectors))
+ : 'deterministic, versioned';
return {
brain: S.brain,
overview: S.overview,
@@ -248,7 +336,7 @@ function assemble() {
edgesLive: { formatted: num(ed.live), hint: `held true ${atHint}` },
edgesTotal: { formatted: num(ed.total), hint: 'nothing is ever deleted' },
invalidated: { formatted: num(ed.invalidated), hint: 'drag belief time left to revisit' },
- detectors: { formatted: num(detectors.length) + detTail, hint: 'deterministic, versioned' },
+ detectors: { formatted: num(detectors.length) + detTail, hint: detHint },
},
series: {
created: ((o && o.created_over_time) || []).map((b) => b.count),
@@ -265,6 +353,10 @@ function assemble() {
trail: S.trail.slice(),
timeline: S.timeline,
names: S.names,
+ openEvidence: S.openEvidence,
+ collapsed: S.collapsed,
+ recentRetired: S.recentRetired,
+ lastShift: S.lastShift,
},
};
}
@@ -301,18 +393,23 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
let persisted = null;
try { persisted = localStorage.getItem(K.brain); } catch { /* private mode */ }
- // Deep link: `#/second-brain?brain=X` — the URL `xerj brain` prints and
- // opens. Applied when it CHANGES (pasting a new link switches brains) but
- // never re-asserted on every render, so the in-app picker still wins for
- // the rest of the session.
- const fromHash = hashBrain();
- if (fromHash && fromHash !== S.lastHashBrain) {
- S.lastHashBrain = fromHash;
- if (S.brains.includes(fromHash)) {
- persisted = fromHash;
- try { localStorage.setItem(K.brain, fromHash); } catch { /* private mode */ }
- } else {
- S.uiError = `brain "${fromHash}" not found on this engine`;
+ // Deep link: `#/second-brain?brain=X&focus=Y&as_of=Z` — the URL
+ // `xerj brain` prints, and the shareable-moment URLs this page writes
+ // back on every refocus / time-travel. Applied when it CHANGES
+ // (pasting a new link jumps to that moment) but never re-asserted on
+ // every render, so in-app navigation still wins for the session.
+ const fromHash = hashMoment();
+ let hashFocus = null;
+ let hashAsOf = null;
+ if (fromHash && fromHash.raw !== S.lastHashApplied) {
+ S.lastHashApplied = fromHash.raw;
+ if (fromHash.brain && S.brains.includes(fromHash.brain)) {
+ persisted = fromHash.brain;
+ hashFocus = fromHash.focus;
+ hashAsOf = fromHash.asOf;
+ try { localStorage.setItem(K.brain, fromHash.brain); } catch { /* private mode */ }
+ } else if (fromHash.brain) {
+ S.uiError = `brain "${fromHash.brain}" not found on this engine`;
}
}
S.brain = persisted && S.brains.includes(persisted) ? persisted : (S.brains[0] || null);
@@ -321,6 +418,10 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
return assemble();
}
loadBrainState();
+ // The pasted moment outranks the persisted one — that is what makes
+ // the URL an artifact: the receiver sees the sender's view.
+ if (hashFocus) S.focus = hashFocus;
+ if (hashAsOf != null) S.asOf = hashAsOf;
try {
S.overview = await fetchOverview(signal);
@@ -348,6 +449,7 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
try {
const [belief, timeline] = await Promise.all([
fetchBelief(signal), fetchTimeline(signal),
+ fetchRecentRetired(signal), // best-effort, never throws
]);
S.ego = belief;
S.timeline = timeline;
@@ -357,6 +459,7 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {
}
} else {
S.ego = null; S.timeline = null;
+ await fetchRecentRetired(signal);
}
await hydrateNames(signal);
saveBrainState();
@@ -374,16 +477,48 @@ function abortInflight() {
}
/** Re-render every second-brain panel body currently in the DOM from
- * module state, then redraw the traces post-paint. */
+ * module state, then redraw the traces post-paint. Pinned paper
+ * trails re-render open (S.openEvidence is module state, not DOM
+ * state) — this is what makes a pin survive scrub commits. */
function patchPanels() {
if (typeof document === 'undefined') return;
+ hidePreview();
+ // innerHTML replacement destroys the focused element; without this,
+ // arrow-key time travel dies after its first commit (the second
+ // keypress lands on a detached caret). Remember what held keyboard
+ // focus and restore it on the freshly-rendered twin.
+ const focused = document.activeElement;
+ const refocusSel = focused && focused.matches
+ ? (focused.matches('[data-sb-caret]') ? '[data-sb-caret]'
+ : (focused.matches('[data-sb-find]') ? '[data-sb-find]' : null))
+ : null;
const data = assemble();
for (const id of SB_PANEL_IDS) {
const el = document.querySelector(`[data-sb-body="${id}"]`);
if (el) el.innerHTML = renderPanelBody(id, data);
}
+ if (refocusSel) {
+ const again = document.querySelector(refocusSel);
+ if (again && again.focus) again.focus();
+ }
showUiError();
scheduleTraces();
+ flashFlipped();
+}
+
+/** One-shot outline flash on every ledger row whose belief state the
+ * last time-travel flipped. Runs once per commit, right after the
+ * post-commit re-render; the class removes itself after the fade. */
+function flashFlipped() {
+ const shift = S.lastShift;
+ if (!shift || !shift.flashPending || !shift.flipped || !shift.flipped.length) return;
+ shift.flashPending = false;
+ for (const id of shift.flipped) {
+ for (const row of document.querySelectorAll(`[data-sb-edge="${CSS.escape(id)}"]`)) {
+ row.classList.add('sb-flip');
+ setTimeout(() => row.classList.remove('sb-flip'), 700);
+ }
+ }
}
function showUiError() {
@@ -428,6 +563,7 @@ async function refetch({ overview = false, belief = false, timeline = false }) {
try {
const jobs = [];
if (overview) jobs.push(fetchOverview(signal).then((r) => { S.overview = r; S.overviewError = null; }));
+ if (overview) jobs.push(fetchRecentRetired(signal)); // rides along; never throws
if (belief && S.focus) jobs.push(fetchBelief(signal).then((r) => { S.ego = r; }));
if (timeline && S.focus) jobs.push(fetchTimeline(signal).then((r) => { S.timeline = r; }));
await Promise.all(jobs);
@@ -453,6 +589,11 @@ function refocus(id) {
}
S.focus = id;
S.ego = null; S.timeline = null;
+ // A new ledger is a new reading: pinned paper trails and the last
+ // time-travel readout belong to the note that had them.
+ S.openEvidence = new Set();
+ S.lastShift = null;
+ writeMoment();
patchPanels(); // immediate: focus card swaps to the new node id
refetch({ belief: true, timeline: true });
}
@@ -462,7 +603,9 @@ function switchBrain(name) {
try { localStorage.setItem(K.brain, name); } catch { /* private mode */ }
S.brain = name;
S.overview = null; S.ego = null; S.timeline = null;
+ S.recentRetired = null; S.openEvidence = new Set(); S.lastShift = null;
loadBrainState();
+ writeMoment();
patchPanels();
(async () => {
await refetch({ overview: true });
@@ -471,10 +614,44 @@ function switchBrain(name) {
})();
}
+/**
+ * What did moving the caret change? Diffed over the pinned timeline
+ * set (hop-1, include_expired, fetched at NOW), so scrubbing never has
+ * to guess: appearances = believed-since inside the crossed interval,
+ * retirements = believed-until inside it — counted separately, never
+ * netted (a link that appeared AND retired inside the interval counts
+ * in both — that is the honest reading). `flipped` lists the rows
+ * whose visible state changed, for the one-shot flash.
+ */
+function computeShift(prevMs, nextMs) {
+ const edges = (S.timeline && S.timeline.edges) || [];
+ if (!edges.length) return null;
+ const a = prevMs == null ? Date.now() : prevMs;
+ const b = nextMs == null ? Date.now() : nextMs;
+ if (a === b) return null;
+ const t0 = Math.min(a, b);
+ const t1 = Math.max(a, b);
+ let appeared = 0;
+ let retired = 0;
+ const flipped = [];
+ for (const e of edges) {
+ const va = Number(e.valid_at);
+ const vi = e.invalid_at != null ? Number(e.invalid_at) : null;
+ if (va > t0 && va <= t1) appeared += 1;
+ if (vi != null && vi > t0 && vi <= t1) retired += 1;
+ if (edgeStateAt(e, prevMs) !== edgeStateAt(e, nextMs)) flipped.push(e.edge_id);
+ }
+ return { t0, t1, appeared, retired, flipped, flashPending: true };
+}
+
/** Commit an as-of. `null` = NOW. Overview + belief re-query (both are
- * as-of-dependent); the timeline stays pinned at NOW by design. */
+ * as-of-dependent); the timeline stays pinned at NOW by design.
+ * Pinned paper trails are NOT cleared here — time travel must not
+ * eat an open quote. */
function commitAsOf(ms) {
+ S.lastShift = computeShift(S.asOf, ms);
S.asOf = ms;
+ writeMoment();
refetch({ overview: true, belief: true });
}
@@ -559,7 +736,12 @@ function previewAsOf(scrub, ms) {
seg.classList.remove('sb-l-live', 'sb-l-future', 'sb-l-expired');
seg.classList.add(`sb-l-${state}`);
}
- if (counter) counter.textContent = `${live} OF ${total}`;
+ if (counter) {
+ // Same floor rule as the curve branch: a clipped fetch renders
+ // '≥' on both numbers — the preview must not quietly drop it.
+ const floor = counter.textContent.trimStart().startsWith('≥') ? '≥' : '';
+ counter.textContent = `${floor}${live} OF ${floor}${total}`;
+ }
}
for (const row of document.querySelectorAll('[data-sb-edge][data-va]')) {
const e = { valid_at: Number(row.getAttribute('data-va')), invalid_at: row.hasAttribute('data-vi') ? Number(row.getAttribute('data-vi')) : null };
@@ -605,9 +787,33 @@ function onPointerMove(e) {
previewAsOf(drag.scrub, drag.ms);
}
+/** The strip's belief events (assertions + retirements), ascending.
+ * Snap targets and arrow-key stops — moments where nothing changed
+ * are not interesting places to stand. */
+function stripEvents(scrub) {
+ const attr = scrub.getAttribute('data-sb-events');
+ if (!attr) return [];
+ return attr.split(',').map(Number).filter(Number.isFinite);
+}
+
+/** Within 1.5% of the strip span of a belief event, land ON the event
+ * (an assertion snaps to its believed-since, a retirement to its
+ * believed-until) — pixel-hunting the exact moment is the strip's
+ * job, not the user's. */
+function snapToEvent(scrub, ms, dom) {
+ const events = stripEvents(scrub);
+ if (!events.length) return ms;
+ let best = null;
+ for (const t of events) {
+ if (best == null || Math.abs(t - ms) < Math.abs(best - ms)) best = t;
+ }
+ return best != null && Math.abs(best - ms) <= (dom[1] - dom[0]) * 0.015 ? best : ms;
+}
+
function onPointerUp() {
if (!drag) return;
- const ms = normalizeAsOf(drag.ms, drag.dom);
+ const snapped = snapToEvent(drag.scrub, drag.ms, drag.dom);
+ const ms = normalizeAsOf(snapped, drag.dom);
drag = null;
commitAsOf(ms);
}
@@ -654,9 +860,37 @@ function onClick(e) {
const evBtn = t.closest('[data-sb-evidence]');
if (evBtn) {
+ // Pin / unpin the full paper trail. The pin lives in S.openEvidence
+ // (module state), so it survives every re-render; the direct DOM
+ // toggle here is just the immediate feedback.
+ const id = evBtn.getAttribute('data-sb-evidence');
+ const pin = !S.openEvidence.has(id);
+ if (pin) S.openEvidence.add(id); else S.openEvidence.delete(id);
const row = evBtn.closest('[data-sb-edge]');
const body = row && row.querySelector('[data-sb-evbody]');
- if (body) body.hidden = !body.hidden;
+ if (body) body.hidden = !pin;
+ evBtn.setAttribute('aria-expanded', String(pin));
+ hidePreview();
+ scheduleTraces(); // row heights changed under the rails
+ return;
+ }
+
+ const foldBtn = t.closest('[data-sb-collapse]');
+ if (foldBtn) {
+ // Fold / unfold a link-kind group. Pure client-side: header + count
+ // stay, honesty counters don't move, nothing is refetched. Direct
+ // DOM toggle (not patchPanels) so an open FIND list isn't eaten.
+ const key = foldBtn.getAttribute('data-sb-collapse');
+ const fold = !S.collapsed.has(key);
+ if (fold) S.collapsed.add(key); else S.collapsed.delete(key);
+ const rows = foldBtn.closest('.sb-group');
+ const body = rows && rows.querySelector('[data-sb-grouprows]');
+ if (body) body.hidden = fold;
+ const glyph = foldBtn.querySelector('[data-sb-ghcaret]');
+ if (glyph) glyph.textContent = fold ? '▸' : '▾';
+ foldBtn.setAttribute('aria-expanded', String(!fold));
+ saveBrainState();
+ scheduleTraces(); // group geometry changed under the rails
return;
}
// Strip clicks are handled by the pointer pipeline above (a click is
@@ -667,14 +901,28 @@ let keyCommit = 0;
function onKeyDown(e) {
const caret = e.target && e.target.closest && e.target.closest('[data-sb-caret]');
if (!caret) return;
- if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' && e.key !== 'End') return;
const scrub = caret.closest('[data-sb-scrub]');
const dom = scrub && stripDomain(scrub);
if (!dom) return;
e.preventDefault();
- const step = Math.max(60_000, Math.round((dom[1] - dom[0]) / 100));
const cur = S.asOf == null ? dom[1] : S.asOf;
- const next = Math.max(dom[0], Math.min(dom[1], cur + (e.key === 'ArrowRight' ? step : -step)));
+ let next;
+ if (e.key === 'End') {
+ next = dom[1]; // NOW
+ } else {
+ // Step between belief events — each keypress lands on the previous/
+ // next moment something actually changed, not a blind 1% hop.
+ const events = stripEvents(scrub);
+ if (e.key === 'ArrowRight') {
+ next = events.find((t) => t > cur);
+ if (next == null) next = dom[1];
+ } else {
+ const prevs = events.filter((t) => t < cur);
+ next = prevs.length ? prevs[prevs.length - 1] : dom[0];
+ }
+ next = Math.max(dom[0], Math.min(dom[1], next));
+ }
previewAsOf(scrub, next);
// Debounce the server commit so holding the key doesn't queue queries.
clearTimeout(keyCommit);
@@ -685,6 +933,155 @@ function onResize() {
scheduleTraces();
}
+// ----- FIND — a note by the words in it ------------------------------
+//
+// One bounded query against the brain's nodes index (the same index
+// hydrateNames reads), debounced 250ms, capped at 7 hits. Results are
+// ordinary refocus links; an empty answer says what the brain is.
+
+let findTimer = 0;
+let findSeq = 0; // only the latest keystroke's response may render
+
+async function runFind(q) {
+ const slot = document.querySelector('[data-sb-findresults]');
+ if (!slot) return;
+ if (!q) { slot.hidden = true; slot.innerHTML = ''; return; }
+ const o = S.overview;
+ if (!o || o.exists === false || !o.nodes_index) return;
+ const seq = ++findSeq;
+ try {
+ const r = await fetch(`${S.baseUrl}/${enc(o.nodes_index)}/_search`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ query: {
+ bool: {
+ should: [
+ { match: { title: q } },
+ { match: { text: q } },
+ { match: { body: q } },
+ ],
+ },
+ },
+ size: 7,
+ _source: ['title'],
+ }),
+ });
+ if (seq !== findSeq) return; // a newer keystroke owns the slot
+ if (!r.ok) {
+ slot.innerHTML = `<span class="sb-sidenote mono faint">FIND FAILED · HTTP ${r.status}</span>`;
+ slot.hidden = false;
+ return;
+ }
+ const j = await r.json();
+ const hits = ((j.hits && j.hits.hits) || []).map((h) => ({
+ id: h._id,
+ title: (h._source && typeof h._source.title === 'string' && h._source.title.trim())
+ ? h._source.title.trim() : null,
+ }));
+ slot.innerHTML = FindResults({ hits, names: S.names });
+ slot.hidden = false;
+ } catch (e) {
+ if (seq !== findSeq) return;
+ slot.innerHTML = `<span class="sb-sidenote mono faint">FIND FAILED · ${String((e && e.message) || e).slice(0, 60)}</span>`;
+ slot.hidden = false;
+ }
+}
+
+function onFindInput(e) {
+ const inp = e.target && e.target.closest && e.target.closest('[data-sb-find]');
+ if (!inp) return;
+ clearTimeout(findTimer);
+ const q = inp.value.trim();
+ findTimer = setTimeout(() => runFind(q), 250);
+}
+
+function onFindKey(e) {
+ const inp = e.target && e.target.closest && e.target.closest('[data-sb-find]');
+ if (!inp) return;
+ if (e.key === 'Enter') {
+ // Enter opens the first match — the keyboard path to a refocus.
+ const first = document.querySelector('[data-sb-findresults] .sb-findfirst');
+ if (first) { e.preventDefault(); refocus(first.getAttribute('data-sb-focus')); }
+ } else if (e.key === 'Escape') {
+ inp.value = '';
+ clearTimeout(findTimer);
+ const slot = document.querySelector('[data-sb-findresults]');
+ if (slot) { slot.hidden = true; slot.innerHTML = ''; }
+ }
+}
+
+// ----- evidence hover preview ---------------------------------------
+//
+// Pointer rest (≥300ms) or keyboard focus on a row's meta button
+// floats the quote/rationale up in a small fixed card; clicking pins
+// the full in-flow paper trail instead. The card is display-only
+// (pointer-events none) and never shows raw ids.
+
+let pvTimer = 0;
+let pvEl = null; // the one floating card, if any
+
+function edgeById(id) {
+ for (const e of (S.ego && S.ego.edges) || []) if (e.edge_id === id) return e;
+ for (const e of (S.timeline && S.timeline.edges) || []) if (e.edge_id === id) return e;
+ return null;
+}
+
+function hidePreview() {
+ clearTimeout(pvTimer);
+ pvTimer = 0;
+ if (pvEl && pvEl.parentNode) pvEl.parentNode.removeChild(pvEl);
+ pvEl = null;
+}
+
+function showPreview(btn) {
+ const id = btn.getAttribute('data-sb-evidence');
+ if (S.openEvidence.has(id)) return; // already pinned in-flow — no float
+ const e = edgeById(id);
+ if (!e) return;
+ hidePreview();
+ pvEl = document.createElement('div');
+ pvEl.className = 'sb-evpreview';
+ pvEl.innerHTML = EvidencePreview(e);
+ document.body.appendChild(pvEl);
+ // Float up: above the row when there is room, below it otherwise,
+ // clamped to the viewport either way.
+ const r = btn.getBoundingClientRect();
+ const w = pvEl.offsetWidth;
+ const h = pvEl.offsetHeight;
+ const left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8));
+ const top = r.top - h - 6 >= 4 ? r.top - h - 6 : r.bottom + 6;
+ pvEl.style.left = `${Math.round(left)}px`;
+ pvEl.style.top = `${Math.round(top)}px`;
+}
+
+function onPointerOver(e) {
+ const btn = e.target && e.target.closest && e.target.closest('[data-sb-evidence]');
+ if (!btn) return;
+ clearTimeout(pvTimer);
+ pvTimer = setTimeout(() => showPreview(btn), 300);
+}
+
+function onPointerOut(e) {
+ const btn = e.target && e.target.closest && e.target.closest('[data-sb-evidence]');
+ if (!btn) return;
+ // Still inside the same button (child-to-child move)? Keep the card.
+ if (e.relatedTarget && btn.contains(e.relatedTarget)) return;
+ hidePreview();
+}
+
+function onFocusIn(e) {
+ const btn = e.target && e.target.closest && e.target.closest('[data-sb-evidence]');
+ if (!btn) return;
+ showPreview(btn); // keyboard focus previews immediately — no rest delay
+}
+
+function onFocusOut(e) {
+ const btn = e.target && e.target.closest && e.target.closest('[data-sb-evidence]');
+ if (!btn) return;
+ hidePreview();
+}
+
(function wire() {
if (wired || typeof document === 'undefined') return;
wired = true;
@@ -694,5 +1091,11 @@ function onResize() {
document.addEventListener('pointerup', onPointerUp);
document.addEventListener('pointercancel', onPointerCancel);
document.addEventListener('keydown', onKeyDown);
+ document.addEventListener('input', onFindInput);
+ document.addEventListener('keydown', onFindKey);
+ document.addEventListener('pointerover', onPointerOver);
+ document.addEventListener('pointerout', onPointerOut);
+ document.addEventListener('focusin', onFocusIn);
+ document.addEventListener('focusout', onFocusOut);
window.addEventListener('resize', onResize);
})();
diff --git a/xerj-ux/src/ux/ego-ledger.js b/xerj-ux/src/ux/ego-ledger.js
index ba1ad55f6..4f0cad0b8 100644
--- a/xerj-ux/src/ux/ego-ledger.js
+++ b/xerj-ux/src/ux/ego-ledger.js
@@ -79,6 +79,51 @@ export const detectorName = (tag) => {
return v ? `${w} · v${v}` : w;
};
+// ----- evidence honesty classes -------------------------------------
+//
+// Not every link's evidence is a quote, and saying so is load-bearing:
+// AUTHORED links (wikilink/mdlink/href) carry the exact text the
+// author wrote — a real quote, quoted.
+// STRUCTURAL links (samedir/sequence) carry a detector-generated
+// rationale — real evidence of WHY, but never text from the note,
+// so it must never wear quotation marks.
+// Links with no evidence at all (asserted by hand or agent without a
+// quote) say so — absence is shown, not papered over.
+
+const AUTHORED_DETECTORS = new Set(['wikilink', 'mdlink', 'href']);
+const STRUCTURAL_DETECTORS = new Set(['samedir', 'sequence']);
+const detectorBase = (tag) => String(tag || '').split('@')[0];
+
+/** 'quote' | 'rationale' | 'none' — how this link's evidence renders. */
+export const evidenceKind = (e) => {
+ const q = e && e.evidence && e.evidence.quote;
+ if (!q) return 'none';
+ return STRUCTURAL_DETECTORS.has(detectorBase(e.detector)) ? 'rationale' : 'quote';
+};
+
+/**
+ * Live-link counts split by what kind of teaching stands behind them,
+ * from `overview.detectors`. AUTHORED = a person wrote that link;
+ * STRUCTURAL = folder position / sort order (a prior, not a citation);
+ * anything else (hand- or agent-asserted vocabularies) is counted
+ * apart, never folded in. This split is what keeps a wikilink-free
+ * corpus honest: "0 authored · 214 structural", not a proud 214.
+ */
+export function authoredSplit(detectors) {
+ const s = { authored: 0, structural: 0, asserted: 0 };
+ for (const d of detectors || []) {
+ const b = detectorBase(d.detector);
+ if (AUTHORED_DETECTORS.has(b)) s.authored += d.live || 0;
+ else if (STRUCTURAL_DETECTORS.has(b)) s.structural += d.live || 0;
+ else s.asserted += d.live || 0;
+ }
+ return s;
+}
+
+/** The split as one lowercase hint phrase. */
+export const splitLabel = (s) =>
+ `${num(s.authored)} authored · ${num(s.structural)} structural${s.asserted > 0 ? ` · ${num(s.asserted)} asserted` : ''}`;
+
/** Ids are opaque doc ids — autoindex ones are long hashes. Never make
* a human read 32 hex chars as a name. */
const looksHashy = (id) => /^[0-9a-f]{16,}$/i.test(String(id || ''));
@@ -174,13 +219,22 @@ export function hop2Counts(edges, asOfMs) {
// ----- evidence -----------------------------------------------------
-/** The exact source quote that taught this link, plus its full paper
- * trail. This block is the ONLY place raw ids surface — labelled. */
-const EvidenceBlock = (e) => {
+/** Detector-aware evidence line. A quote is quoted; a structural
+ * rationale is prefixed WHY — and never dressed as text from the
+ * note; no evidence says so in as many words. */
+const evidenceLine = (e) => {
+ const kind = evidenceKind(e);
+ if (kind === 'quote') return `<p class="sb-evquote">“${esc(e.evidence.quote)}”</p>`;
+ if (kind === 'rationale') return `<p class="sb-evwhy">WHY — ${esc(e.evidence.quote)}</p>`;
+ return `<p class="sb-evquote sb-evnone">NO EVIDENCE RECORDED — ASSERTED, NOT DETECTED</p>`;
+};
+
+/** The evidence that taught this link, plus its full paper trail.
+ * This block is the ONLY place raw ids surface — labelled. `pinned`
+ * renders it open in-flow (the pin set lives in module state on the
+ * controller side, so pins survive every re-render). */
+const EvidenceBlock = (e, pinned) => {
const ev = e.evidence || {};
- const quote = ev.quote
- ? `<p class="sb-evquote">“${esc(ev.quote)}”</p>`
- : `<p class="sb-evquote sb-evnone">no source quote was recorded for this link</p>`;
const src = ev.source
? `<span>from ${esc(ev.source)}${ev.offset != null && ev.offset > 0 ? ` · byte ${esc(ev.offset)}` : ''}</span>`
: '';
@@ -190,8 +244,8 @@ const EvidenceBlock = (e) => {
const expired = e.expired_at != null
? ` · retirement recorded ${esc(fmtTs(e.expired_at))}` : '';
return `
- <div class="sb-evbody" data-sb-evbody hidden>
- ${quote}
+ <div class="sb-evbody" data-sb-evbody${pinned ? '' : ' hidden'}>
+ ${evidenceLine(e)}
<div class="sb-evmeta mono faint">
${src}
<span>taught by ${esc(detectorName(e.detector).toLowerCase())} (${esc(e.detector || 'unknown detector')}) · ${esc(fmt(conf * 100, { decimals: 0 }))}% confident · strength ${esc(fmt(e.weight ?? 1, { decimals: 2 }))}</span>
@@ -201,12 +255,36 @@ const EvidenceBlock = (e) => {
</div>`;
};
+/**
+ * Floating hover card: the evidence line + one taught-by sentence. No
+ * raw ids here — the full paper trail is one click (the pin) away.
+ * Rendered into a fixed-position card by the interaction controller.
+ */
+export const EvidencePreview = (e) => {
+ const conf = e.confidence ?? 1;
+ return `
+ ${evidenceLine(e)}
+ <div class="sb-evmeta mono faint">
+ <span>taught by ${esc(detectorName(e.detector).toLowerCase())} · ${esc(fmt(conf * 100, { decimals: 0 }))}% confident · click to pin the paper trail</span>
+ </div>`;
+};
+
// ----- rows + groups ------------------------------------------------
-const edgeRow = (e, side, { counts, asOf, clipped, nodes, names }) => {
+/** The row chip naming what stands behind the link: QUOTE (authored
+ * text), WHY (structural rationale), or NO EVIDENCE. */
+const evidenceChip = (e) => {
+ const kind = evidenceKind(e);
+ if (kind === 'quote') return '<span class="sb-eq">QUOTE</span>';
+ if (kind === 'rationale') return '<span class="sb-eq sb-eq-why">WHY</span>';
+ return '<span class="sb-eq sb-eq-none">NO EVIDENCE</span>';
+};
+
+const edgeRow = (e, side, { counts, asOf, clipped, nodes, names, open }) => {
const id = farEnd(e);
const state = edgeStateAt(e, asOf);
const n = counts.get(id) || 0;
+ const pinned = !!(open && open.has(e.edge_id));
const hop2 = n > 0
? `+${clipped ? '≥' : ''}${num(n)} MORE`
: '';
@@ -217,15 +295,16 @@ const edgeRow = (e, side, { counts, asOf, clipped, nodes, names }) => {
<button type="button" class="sb-ename" data-sb-focus="${esc(id)}"
title="Open the ledger for ${esc(id)}">${esc(nodeName(id, { nodes, names }))}</button>
<button type="button" class="sb-emeta" data-sb-evidence="${esc(e.edge_id)}"
- title="Show the source quote that taught this link">
+ aria-expanded="${pinned}"
+ title="Show what taught this link — click to pin the full paper trail">
<span class="sb-ewin">${esc(fmtWindow(e.valid_at, e.invalid_at))}</span>
- ${(e.evidence && e.evidence.quote) ? '<span class="sb-eq">QUOTE</span>' : ''}
+ ${evidenceChip(e)}
${hop2 ? `<span class="sb-ehop2" title="${esc(num(n))} more link${n === 1 ? '' : 's'} one step beyond — click the name to walk there">${esc(hop2)}</span>` : ''}
<span class="sb-tag sb-tag-retired">RETIRED</span>
<span class="sb-tag sb-tag-notyet">NOT YET</span>
</button>
</div>
- ${EvidenceBlock(e)}
+ ${EvidenceBlock(e, pinned)}
</div>`;
};
@@ -235,13 +314,21 @@ const groupBlock = (g, side, ctx) => {
const countLabel = shown < total
? `TOP ${num(shown)} OF ${num(total)}`
: `${num(total)}`;
+ // Collapse is a client-side fold — header + count stay visible, the
+ // honesty counters never change, nothing is refetched.
+ const key = `${side}:${g.type}`;
+ const collapsed = !!(ctx.collapsed && ctx.collapsed.has(key));
return `
<div class="sb-group">
- <div class="sb-grouphead" data-sb-grouphead="${side}">
- <span class="sb-ghtype">${esc(typeName(g.type))}</span>
+ <button type="button" class="sb-grouphead" data-sb-grouphead="${side}"
+ data-sb-collapse="${esc(key)}" aria-expanded="${!collapsed}"
+ title="${collapsed ? 'Show' : 'Fold away'} these links (nothing is refetched)">
+ <span class="sb-ghtype"><span class="sb-ghcaret" data-sb-ghcaret>${collapsed ? '▸' : '▾'}</span>${esc(typeName(g.type))}</span>
<span class="sb-ghcount">${esc(countLabel)}</span>
+ </button>
+ <div class="sb-grouprows" data-sb-grouprows${collapsed ? ' hidden' : ''}>
+ ${g.list.slice(0, LEDGER_GROUP_CAP).map((e) => edgeRow(e, side, ctx)).join('')}
</div>
- ${g.list.slice(0, LEDGER_GROUP_CAP).map((e) => edgeRow(e, side, ctx)).join('')}
</div>`;
};
@@ -307,8 +394,28 @@ const EgoControls = ({ brain, brains, focus, asOf, trail, names, nodes }) => {
<span><span class="key">BRAIN</span> <span class="sb-cval">${esc(brain || '—')}</span> ${brainSwitch}</span>
<span><span class="key">FOCUS</span> ${trailHtml}<span class="sb-cval">${esc(focus ? crumbName(focus) : '—')}</span></span>
<span><span class="key">VIEWING</span> <span class="sb-cval${asOf != null ? ' accent' : ''}">${asOf != null ? esc(fmtTs(asOf)) + ' UTC' : 'NOW'}</span>${asOf != null ? ` <button type="button" class="sb-clink" data-sb-now>BACK TO NOW</button>` : ''}</span>
+ <span class="sb-cfind"><span class="key">FIND</span><input class="sb-findinput" type="text"
+ data-sb-find spellcheck="false" autocomplete="off"
+ placeholder="a note, by the words in it"
+ aria-label="Find a note in this brain — Enter opens the first match"></span>
<span class="sb-cerr" data-sb-error></span>
- </div>`;
+ </div>
+ <div class="sb-findresults" data-sb-findresults hidden></div>`;
+};
+
+/**
+ * FIND results: a temporary strip of note links under the controls.
+ * Every hit is the same refocus affordance as any other note name; an
+ * empty answer teaches what the brain is (and is not).
+ */
+export const FindResults = ({ hits, names }) => {
+ if (!hits || !hits.length) {
+ return `<span class="sb-sidenote mono faint">NO NOTE MATCHES — THE BRAIN ONLY KNOWS WHAT THE FOLDER TAUGHT IT</span>`;
+ }
+ return hits.map((h, i) =>
+ `<button type="button" class="sb-clink sb-findrow${i === 0 ? ' sb-findfirst' : ''}"
+ data-sb-focus="${esc(h.id)}" title="Open the ledger for ${esc(h.id)}">${esc(h.title || nodeName(h.id, { names }))}</button>`)
+ .join('<span class="faint"> · </span>');
};
// ----- belief-time scrubber ----------------------------------------
@@ -336,7 +443,7 @@ export const caretAlignClass = (pct) =>
* interval set is pinned at NOW with retired links included, so
* scrubbing never removes data from the strip — only states change.
*/
-export const BeliefScrubber = ({ timeline, asOf }) => {
+export const BeliefScrubber = ({ timeline, asOf, shift }) => {
const edges = (timeline && timeline.edges) || [];
if (!edges.length) {
return `<div class="sb-scrub" data-sb-scrub><div class="panel-empty mono faint">NOTHING TO REPLAY YET · EVERY LINK WILL DRAW ITS LIFETIME HERE</div></div>`;
@@ -359,6 +466,17 @@ export const BeliefScrubber = ({ timeline, asOf }) => {
const liveAt = (t) => edges.reduce((a, e) => a + (edgeStateAt(e, t) === 'live' ? 1 : 0), 0);
const liveAtCaret = liveAt(asOf);
+ // Every belief event on the strip (assertions AND retirements),
+ // sorted, deduped: the caret snaps to these on release and the arrow
+ // keys step between them — moments where nothing changed are not
+ // interesting stops.
+ const eventTimes = [...new Set(
+ edges.flatMap((e) => (e.invalid_at != null
+ ? [Number(e.valid_at), Number(e.invalid_at)]
+ : [Number(e.valid_at)])),
+ )].sort((a, b) => a - b);
+ const eventsAttr = ` data-sb-events="${esc(eventTimes.join(','))}"`;
+
const lifetimes = edges.length <= SCRUB_LIFETIME_MAX;
let stripInner = '';
let h = 0;
@@ -419,15 +537,45 @@ export const BeliefScrubber = ({ timeline, asOf }) => {
}
pts += ` ${X},${prevY.toFixed(1)}`;
stepsAttr = ` data-sb-steps="${esc(steps.map(([t, n]) => `${t}:${n}`).join(','))}"`;
+ // Assertion ticks: one 1px mute tick per moment a link started
+ // being believed (deduped at tick resolution) — the snap targets,
+ // made visible on the curve form where individual rows are gone.
+ const seenX = new Set();
+ let ticks = '';
+ for (const e of edges) {
+ const x = xOf(Number(e.valid_at));
+ const xq = Math.round(x);
+ if (seenX.has(xq)) continue;
+ seenX.add(xq);
+ ticks += `<line class="sb-atick" x1="${x.toFixed(1)}" x2="${x.toFixed(1)}" y1="${h - 6}" y2="${h - 1}" stroke="currentColor" stroke-width="1"/>`;
+ }
stripInner = `<svg class="chart sb-striplines" width="100%" height="${h}" viewBox="0 0 ${X} ${h}" preserveAspectRatio="none" aria-hidden="true">
+ ${ticks}
<polyline points="${pts}" fill="none" stroke="currentColor" stroke-width="1"/>
</svg>
<span class="sb-curvemax mono faint">peak ${esc(floor)}${num(maxC)}</span>`;
explain = `THE LINE COUNTS BELIEFS OVER TIME — TOO MANY LINKS (${floor}${num(edges.length)}) TO DRAW ONE PER ROW`;
}
+ // What the last time-travel changed, stated in the legend: counts of
+ // appearances and retirements between the two carets — always named
+ // separately, never netted, '≥' floors when the fetch was clipped.
+ // "THIS MOMENT" must name the caret's end of the crossed interval:
+ // dragging right the caret sits at t1, dragging left it sits at t0 —
+ // the other endpoint is named by its date, never misattributed.
+ const shiftWhen = shift
+ ? (Math.abs(caretMs - shift.t1) <= Math.abs(caretMs - shift.t0)
+ ? `BETWEEN ${esc(fmtDay(shift.t0))} AND THIS MOMENT`
+ : `BETWEEN THIS MOMENT AND ${esc(fmtDay(shift.t1))}`)
+ : '';
+ const shiftHtml = shift
+ ? `<span class="sb-changeout" data-sb-changeout>↳ ${shift.appeared === 0 && shift.retired === 0
+ ? 'NOTHING CHANGED'
+ : `${esc(floor)}${num(shift.appeared)} APPEARED · ${esc(floor)}${num(shift.retired)} RETIRED`} ${shiftWhen}</span>`
+ : '';
+
return `
- <div class="sb-scrub" data-sb-scrub data-d0="${d0}" data-d1="${d1}"${stepsAttr}>
+ <div class="sb-scrub" data-sb-scrub data-d0="${d0}" data-d1="${d1}"${stepsAttr}${eventsAttr}>
<div class="key">BELIEF TIME · DRAG ANYWHERE ON THE STRIP — THE PAGE REPLAYS WHAT THIS BRAIN BELIEVED AT THAT MOMENT</div>
<div class="sb-strip" data-sb-strip style="height:${h}px;">
${stripInner}
@@ -439,7 +587,7 @@ export const BeliefScrubber = ({ timeline, asOf }) => {
</div>
<div class="sb-scrub-legend mono faint">
<span>${esc(fmtDay(d0raw))}</span>
- <span class="mid"><span data-sb-livecount>${esc(floor)}${num(liveAtCaret)} OF ${esc(floor)}${num(edges.length)}</span> BELIEVED AT THIS MOMENT<span class="sb-scrub-explain"> · ${explain}</span></span>
+ <span class="mid"><span data-sb-livecount>${esc(floor)}${num(liveAtCaret)} OF ${esc(floor)}${num(edges.length)}</span> BELIEVED AT THIS MOMENT<span class="sb-scrub-explain"> · ${explain}</span>${shiftHtml}</span>
<span>${asOf != null ? `<button type="button" class="text-btn" data-sb-now>BACK TO NOW</button>` : `TODAY · ${esc(fmtDay(now))}`}</span>
</div>
</div>`;
@@ -473,7 +621,11 @@ export const EgoLedger = ({ data }) => {
const nodes = ego.nodes || {};
const clipped = !!(ego.not_shown && ego.not_shown.edges_clipped > 0);
const counts = hop2Counts(ego.edges, asOf);
- const ctx = { nodes, names, counts, asOf, clipped };
+ const ctx = {
+ nodes, names, counts, asOf, clipped,
+ open: sb.openEvidence, // pinned paper trails — survive re-renders
+ collapsed: sb.collapsed, // folded link-kind groups
+ };
const inGroups = groupEdges(ego.edges, 'in');
const outGroups = groupEdges(ego.edges, 'out');
const hop1 = (ego.edges || []).filter((e) => e.hop === 1);
@@ -500,7 +652,7 @@ export const EgoLedger = ({ data }) => {
return `
${EgoControls({ brain: data.brain, brains: sb.brains, focus: ego.node, asOf, trail: sb.trail, names, nodes })}
${body}
- ${BeliefScrubber({ timeline: sb.timeline, asOf })}`;
+ ${BeliefScrubber({ timeline: sb.timeline, asOf, shift: sb.lastShift })}`;
};
// ----- honesty panel ------------------------------------------------
@@ -647,15 +799,35 @@ const AssertedPanel = ({ data }) => {
return Num({ value: m.formatted, unit: 'links', spark, hint: m.hint, emphasis: false });
};
-/** RETIRED — count + share of everything ever asserted. */
+/** RETIRED — count + share of everything ever asserted + the three
+ * most recently retired links, each with the evidence it carried.
+ * The churn rows are truth-now (most recent retirements on record),
+ * regardless of where the belief caret sits. */
const RetiredPanel = ({ data }) => {
const o = data.overview || {};
+ const sb = data.sb || {};
const ed = o.edges || { total: 0, invalidated: 0 };
const m = (data.metrics && data.metrics.invalidated) || { formatted: num(ed.invalidated || 0), hint: '' };
const share = ed.total > 0 ? `${((100 * ed.invalidated) / ed.total).toFixed(ed.invalidated ? 1 : 0)}% of all links` : '';
+ const names = sb.names || {};
+ const recent = Array.isArray(sb.recentRetired) ? sb.recentRetired : [];
+ const evSnippet = (e) => {
+ const kind = evidenceKind(e);
+ if (kind === 'quote') return `“${e.evidence.quote}”`;
+ if (kind === 'rationale') return `WHY — ${e.evidence.quote}`;
+ return 'no evidence recorded';
+ };
+ const rows = recent.map((e) => `
+ <button type="button" class="sb-retrow" data-sb-focus="${esc(e.src)}"
+ title="Open the ledger for ${esc(e.src)}">
+ <span class="sb-retpair">${esc(nodeName(e.src, { names }))} → ${esc(nodeName(e.dst, { names }))}</span>
+ <span class="sb-retwhen">retired ${esc(fmtDay(e.invalid_at))}</span>
+ <span class="sb-retev">${esc(evSnippet(e))}</span>
+ </button>`).join('');
return `
${Num({ value: m.formatted, unit: 'links', hint: m.hint, emphasis: false })}
- ${share ? `<div class="hint" style="margin-top:6px;">${esc(share)} · never deleted, only retired</div>` : ''}`;
+ ${share ? `<div class="hint" style="margin-top:6px;">${esc(share)} · never deleted, only retired</div>` : ''}
+ ${rows ? `<div class="sb-retrows">${rows}</div>` : ''}`;
};
/** WHAT TAUGHT THIS BRAIN — the detectors as identity + magnitude
@@ -677,8 +849,12 @@ const TaughtByPanel = ({ data }) => {
const notListed = (o.not_shown && o.not_shown.detectors_not_listed) || 0;
const tail = (dets.length > 4 || notListed > 0)
? `<div class="hint">+ ${num(Math.max(0, dets.length - 4) + notListed)} more</div>` : '';
+ // Authored vs structural, always stated: a corpus with no written
+ // links must read "0 authored · N structural", never a proud N.
+ const split = authoredSplit(dets);
return `<div class="sb-dets">${rows}${tail}</div>
- <div class="hint" style="margin-top:6px;">deterministic · versioned · no LLM</div>`;
+ <div class="hint" style="margin-top:6px;">${esc(splitLabel(split))}</div>
+ <div class="hint">deterministic · versioned · no LLM</div>`;
};
const TypeDistPanel = ({ data }) => {
@@ -687,7 +863,11 @@ const TypeDistPanel = ({ data }) => {
if (!types.length) return `<div class="panel-empty mono faint">NO LINKS AT THIS MOMENT</div>`;
const tail = o.not_shown && o.not_shown.types_not_listed > 0
? `<div class="hint">+ ${num(o.not_shown.types_not_listed)} kinds beyond this list</div>` : '';
- return Dist({ segments: types.map((t) => ({ label: typeName(t.type), value: t.live })) }) + tail;
+ // The same authored/structural honesty as the detectors tile: how
+ // much of this distribution is written citation vs folder position.
+ const split = authoredSplit(o.detectors);
+ const splitNote = `<div class="hint" style="margin-top:6px;">${esc(splitLabel(split))} — authored links are written citations; structural ones are folder position and sort order</div>`;
+ return Dist({ segments: types.map((t) => ({ label: typeName(t.type), value: t.live })) }) + tail + splitNote;
};
const TimelinePanel = ({ data }) => {