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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(second-brain): THE MAP — a bounded knowledge graph + cross-type link detectors
xerj-org213cfcd39a1a
diff --git a/docs/design/SECOND_BRAIN_SPEC.md b/docs/design/SECOND_BRAIN_SPEC.mdindex f48b52713..e4916724c 100644--- a/docs/design/SECOND_BRAIN_SPEC.md+++ b/docs/design/SECOND_BRAIN_SPEC.md@@ -112,6 +112,8 @@ per crate; keep byte-identical):"confidence": { "type": "float" },"schema_version": { "type": "integer" },"src_file": { "type": "keyword" },+ "src_format": { "type": "keyword" },+ "dst_format": { "type": "keyword" },"evidence": {"properties": {"quote": { "type": "text" },@@ -143,6 +145,12 @@ ships NO column for that segment. Therefore every edge writer MUST emit:`null_bitmap`, which is exactly the "still valid" signal the hop reads.- `evidence` — JSON object. Objects produce no doc-values column (by design);evidence is read only on hydration paths, never on the hop.+- `src_format` / `dst_format` — JSON **string** when the writer knows the+ endpoint file types (autoindex stamps `CorpusFile.format`: lowercase+ extension, else sniffed family), **key omitted entirely when unknown**+ (API-asserted edges about arbitrary node ids carry neither). Additive+ optional fields — they do NOT bump `schema_version`; both writers stamp the+ same mapping and `1`.- `schema_version` — the integer `1` for every edge this contract produces.Every edge document's **`_id` is exactly its `edge_id` field value**. This is@@ -552,7 +560,8 @@ bi-temporal pair; both are set on the same call.Query params:| param | type | default | notes ||---|---|---|---|-| `node` | string | REQUIRED | 400 if missing/empty |+| `node` | string | — | exactly one of `node`/`nodes` required (400 otherwise); `node` is the 1-seed case |+| `nodes` | comma-list | — | multi-seed frontier, mutually exclusive with `node`; deduped, then clamped to 64 seeds with the clip counted in `not_shown.frontier_clipped` || `hops` | int | 1 | 1 or 2; >2 → 400 with §4.6 wording || `direction` | `out`\|`in`\|`both` | `both` | || `types` | comma-list | all | |@@ -564,7 +573,9 @@ Query params:| `include_evidence` | bool | true | hydrate evidence for RETURNED edges |Handler: brain/index existence check (404) → `graph_expand` with-`frontier = [node]`, `max_result_edges = limit` → post-traversal hydration:+`frontier = <seeds>` (the engine expands a whole frontier at+frontier-size-independent cost), `max_result_edges = limit` → post-traversal+hydration:- `include_evidence`: ONE `es_compat::search` on the edges index with`{"query": {"ids": {"values": [<returned edge_ids>]}}, "size": <n>}`(bounded ≤1000; rides the existing `build_ids_prefilter_cached` fast path,@@ -580,6 +591,7 @@ Response (fixture-exact instance in §8.5):"brain": "notes","contract": "xerj-second-brain/1","node": "note-alpha",+ "seeds": ["note-alpha"],"as_of": 1753700000000,"hops": 1,"direction": "both",@@ -595,7 +607,7 @@ Response (fixture-exact instance in §8.5):"neighbors": [{ "id": "note-gamma", "hop": 1, "via_edge": "<edge_id of first sorted edge that reached it>" }],- "nodes": { "note-beta": { "title": "…", "preview": "…", "index": ".xerj-memory-notes" } },+ "nodes": { "note-beta": { "title": "…", "preview": "…", "path": "notes/beta.md", "index": ".xerj-memory-notes" } },"not_shown": {"edges_clipped": 0,"frontier_clipped": 0,@@ -610,13 +622,17 @@ Response (fixture-exact instance in §8.5):```Rules: `edges` in the §3.2 stable order, each annotated with`direction: "out"|"in"` relative to the expansion (an edge admitted by both-scans reports `"out"`); `neighbors` excludes `node` itself, first-discovery-order; `edge.invalid_at` is `null` in JSON when unset (response-side null is-fine — §2.2's omit-rule binds stored docs, not responses); `nodes` present-only when `include_nodes=true` — summary = `{title, preview, index}` where-`title` = `_source.title` if string else null, `preview` = first 160 chars of-`_source.text` else `_source.body` else null, `index` = the index the doc was-found in. `not_shown` maps `GraphExpandStats` 1:1 plus the dangling fields;+scans reports `"out"`; with multi-seed, "out" means src is one of the seeds);+`seeds` echoes the ADMITTED seed list (post-dedupe, post-clamp) and `node` is+present only when there is exactly one seed; `neighbors` excludes every seed,+first-discovery order; `edge.invalid_at` is `null` in JSON when unset+(response-side null is fine — §2.2's omit-rule binds stored docs, not+responses); `nodes` present only when `include_nodes=true` — summary =+`{title, preview, path, index}` where `title` = `_source.title` if string else+null, `preview` = first 160 chars of `_source.text` else `_source.body` else+null, `path` = `_source.ax_path` if string else null (never guessed), `index`+= the index the doc was found in. `not_shown` maps `GraphExpandStats` 1:1+(handler-clipped seeds fold into `frontier_clipped`) plus the dangling fields;`segments_scanned`/`memtable_docs_scanned` ride along as cost honesty.### 4.4 GET /_graph/{brain}/overview — brain-level stats (dashboard feed)@@ -634,6 +650,10 @@ Handler composes exactly three `es_compat::search` calls on the edges index3. timeline: `exists src` with`{"created": {"date_histogram": {"field": "created_at", "calendar_interval": "<interval>"}}}`.+Plus one size-0 `match_all` count on `nodes_index` → `nodes.total` (0 when+that index does not exist yet — a brain fed through the link API alone+truthfully has no stored notes).+Response:```json{@@ -642,6 +662,7 @@ Response:"exists": true,"as_of": 1753700000000,"nodes_index": ".xerj-memory-notes",+ "nodes": { "total": 0 },"embedder": "lexical-feature-hash","edges": { "total": 8, "live": 8, "invalidated": 0 },"types": [ { "type": "wikilink", "live": 4 }, { "type": "same_dir", "live": 4 } ],@@ -792,33 +813,60 @@ engine/crates/xerj-autoindex/src/detect/wikilink.rs // [[target]] type "wikilink" w 1.0 conf 0.95mdlink.rs // [text](relative/path.md) type "mdlink" w 0.9 conf 0.9href.rs // <a href="relative-or-corpus-url">type "href" w 0.7 conf 0.85- sequence.rs // section s_i -> s_{i+1}, same file type "sequence" w 0.8 conf 0.99+ pathcite.rs // bare path token in prose type "pathcite" w 0.6 conf 0.7+ cratecite.rs // crate-dir name in prose type "cratecite" w 0.5 conf 0.6+ sequence.rs // card → s_0, s_i -> s_{i+1} type "sequence" w 0.8 conf 0.99samedir.rs // chain over sorted files per dir type "same_dir" w 0.3 conf 0.4```+Detector tags as of the cross-file-type revision: `wikilink@2`, `mdlink@2`,+`href@2`, `pathcite@1`, `cratecite@1`, `sequence@2`, `samedir@2`. The @2 bumps+record two behavior changes (per the "bump on ANY behavior change" rule):+every file-level endpoint moved from the target's `s0` section to its+**file-card node**, and edges gained `src_format`/`dst_format`. Edges written+by @1 detectors remain in place, attributable, and time-travelable.+### 6.3 Detector trait (exact shape)```rust/// Edge-schema version stamped into every emitted edge (`schema_version`).pub const EDGE_SCHEMA_VERSION: u32 = 1;+/// Locator of the per-file card node (see §6.6.2a). Cannot collide with+/// content locators — extractor locators are letter+digit shaped.+pub const FILE_CARD_LOCATOR: &str = "file";+/// Corpus-wide resolution table, built once after Phase A (plan assignment):-/// every indexed file's rel path → identity + the doc id of its first section.+/// every indexed file's rel path → identity + its file-card node id.pub struct CorpusIndex {/// key: root-relative path with forward slashes (`FileEntry.rel`).pub files: std::collections::BTreeMap<String, CorpusFile>,/// lowercase file-stem → rel paths bearing it (wikilink resolution;/// BTreeMap so ambiguity resolution below is deterministic).pub by_stem: std::collections::BTreeMap<String, Vec<String>>,+ /// exact file NAME (final segment, case-sensitive) → rel paths bearing it+ /// (pathcite suffix resolution).+ pub by_name: std::collections::BTreeMap<String, Vec<String>>,+ /// crate-directory basename → rels of `Cargo.toml` files directly inside a+ /// directory of that name (cratecite table; DIRECTORY name, contents never+ /// read).+ pub crate_dirs: std::collections::BTreeMap<String, Vec<String>>,}pub struct CorpusFile {pub rel: String,pub file_key: String, // ids::file_key outputpub dataset_slug: String,- /// ids::doc_id(dataset_slug, file_key, "s0") — the file's anchor node.+ /// ids::doc_id(dataset_slug, file_key, FILE_CARD_LOCATOR) — the file's+ /// CARD node, a real emitted doc (§6.6.2a). Every file-level edge lands+ /// here. (Pre-@2 this was the `s0` section id, which does not exist for+ /// row/line/page families — links to a CSV or PDF pointed at a ghost.)pub anchor_doc_id: String,pub mtime_ms: i64,pub dir: String, // parent dir rel path, "" for root+ pub family: String, // sniffed Family::as_str from the frozen plan+ /// File-type label stamped as src_format/dst_format: lowercase extension+ /// when the name has one ("md", "rs", "pdf"), else `family`.+ pub format: String,}/// One detected edge before identity/envelope assembly.@@ -832,6 +880,8 @@ pub struct EdgeDraft {pub src_file: String, // rel path that taught this edge (top-level keyword)pub quote: String, // evidence.quote (≤240 chars, trimmed)pub offset: u64, // evidence.offset (byte offset in section text; 0 for structural)+ pub src_format: String, // CorpusFile.format of the endpoints; "" = unknown,+ pub dst_format: String, // stored key omitted (§2.2)}/// Per-section textual context. `text` is the exact section string that became@@ -839,7 +889,13 @@ pub struct EdgeDraft {pub struct SectionCtx<'a> {pub corpus: &'a CorpusIndex,pub file: &'a CorpusFile,- pub section_ordinal: u32,+ /// Human label from the locator ("section 3", "page 2 section 0") —+ /// §6.6.2's `section_label`. Used verbatim in sequence rationales.+ pub section_label: &'a str,+ /// (doc id, label) of the previously STAGED section of the same file,+ /// None for the first. Stream-order truth — the only source that can name+ /// a PDF page boundary's predecessor.+ pub prev_section: Option<(&'a str, &'a str)>,pub section_doc_id: &'a str,pub text: &'a str,}@@ -858,7 +914,8 @@ pub trait EdgeDetector: Sync {/// The registry. Order is normative (fixture edge ordering depends on it only/// via edge sort, so this is cosmetic — but keep it).-pub fn default_detectors() -> Vec<Box<dyn EdgeDetector>>; // wikilink, mdlink, href, sequence, samedir+pub fn default_detectors() -> Vec<Box<dyn EdgeDetector>>;+// wikilink, mdlink, href, pathcite, cratecite, sequence, samedir```### 6.4 Determinism + edge identity rules@@ -874,7 +931,11 @@ pub fn default_detectors() -> Vec<Box<dyn EdgeDetector>>; // wikilink, mdlink,### 6.5 Per-detector emission rules (normative)-- **wikilink@1**: scan section text for `[[target]]` / `[[target|alias]]`+All detectors stamp `src_format` = the containing file's `CorpusFile.format`+and `dst_format` = the target file's; every `anchor_doc_id` below is the+target's FILE CARD (§6.6.2a).++- **wikilink@2**: scan section text for `[[target]]` / `[[target|alias]]`(target = text before `|`, trimmed). Resolve: exact rel-path match first(with or without extension), else `by_stem[target.to_lowercase()]`; ifmultiple candidates, pick the lexicographically smallest rel (deterministic;@@ -882,19 +943,46 @@ pub fn default_detectors() -> Vec<Box<dyn EdgeDetector>>; // wikilink, mdlink,no edge, count `edges_unresolved`. src = section doc id; dst = target's`anchor_doc_id`; quote = the full trimmed line containing the link (≤240chars); offset = byte offset of the `[[` within the section text.-- **mdlink@1**: `[text](url)` where url has no scheme and no leading `//`;+- **mdlink@2**: `[text](url)` where url has no scheme and no leading `//`;strip fragment/query; resolve relative to the containing file's dir, then asroot-relative; must resolve to a corpus file. Same evidence rules (offset ofthe `[`).-- **href@1**: `<a href="…">` (html-extracted files only, case-insensitive+- **href@2**: `<a href="…">` (html-extracted files only, case-insensitiveattr); same scheme-less resolution as mdlink. Offset = offset of the `href`attribute value start in the section text (best effort; 0 when the extractorlost byte positions).-- **sequence@1** (structural per file, emitted from `detect_text` on section- i>0 to avoid a second pass): for each multi-section file, edge- `section s_{i-1} doc id → section s_i doc id`, quote =- `"section {i-1} precedes section {i} of {rel}"`, offset 0.-- **samedir@1** (structural): per directory with ≥2 indexed files, sort files+- **pathcite@1**: bare path tokens in section text — maximal+ `[A-Za-z0-9_./-]` runs ending `\.[A-Za-z0-9_]+`, leading `/` `./` `../`+ stripped (a trailing `:line` never enters the token; `:` is outside the+ class). Resolve: exact rel-path match; else, for tokens with ≥2 path+ segments, path-SUFFIX match at a `/` boundary (several candidates →+ smallest rel + `edges_ambiguous`; none → `edges_unresolved`). Bare+ one-segment names (`index.rs`) are NEVER suffix-matched: if any corpus file+ bears the name the mention counts as ambiguous, otherwise it is ignored as+ prose noise (not counted — "e.g", domains, version numbers are not+ citations). Self-citations are skipped silently. src = section doc id;+ dst = target's `anchor_doc_id`; quote = full trimmed line; offset = byte+ offset of the (stripped) token. UI name: **"cites file"**.+- **cratecite@1**: whole-word occurrences of a `crate_dirs` key (a corpus+ directory directly containing `Cargo.toml`, keyed by directory basename) in+ section text. Only names containing `-` or `_` are citable (a crate dir+ named `server` would turn ordinary English into edges). Word boundaries+ exclude `[A-Za-z0-9_\-./]`, except a trailing sentence period (`.` not+ followed by an alphanumeric) which does not suppress the match. Underscore+ import spellings (`xerj_fts`) are NOT matched — that equivalence cannot be+ verified without reading manifests. >1 dirs sharing a basename → smallest+ rel + `edges_ambiguous`. dst = that `Cargo.toml`'s `anchor_doc_id`; quote =+ full trimmed line; offset = byte offset of the mention. UI name:+ **"cites crate"**.+- **sequence@2** (structural per file, emitted from `detect_text` to avoid a+ second pass): the file's FIRST staged section gets+ `anchor_doc_id → section doc id`, quote = `"{label} opens {rel}"`; every+ later section gets `prev section doc id → section doc id`, quote =+ `"{prev_label} precedes {label} of {rel}"`; offset 0. Labels per §6.6.2.+ The opener is what connects a file's card (where citations land) to its+ content — without it a cited file's text would be unreachable from the+ ego of its own card.+- **samedir@2** (structural): per directory with ≥2 indexed files, sort filesby rel; emit a CHAIN — one edge per consecutive pair(`left.anchor_doc_id → right.anchor_doc_id`). A chain, not a clique: cliquesare O(n²) and would drown real signal; chain keeps directory cohesion@@ -911,12 +999,35 @@ All hooks live in `lib.rs::run_index`:with the §2.1 mapping; `create` the §2.5 meta doc with `nodes_index` =comma-list of this run's dataset index names (e.g. `"ax-notes-docs"`);bulk-write structural edges (§6.7).-2. **Inside the Phase B per-file sink** (lib.rs ~917, the closure that stages- each `RawRecord`): after the node action is staged for a text-family record,+2. **Inside the Phase B per-file sink** (the closure that stages each+ `RawRecord`): after the node action is staged for a text-section record,run `detect_text` for each detector with the section text- (`fields["body"]`), section ordinal (parsed from `rec.locator` `"s{i}"`),- and the just-computed node `id`. Append resulting edge actions to a- per-worker edge buffer (NOT the node staging file — different target index).+ (`fields["body"]`), the section label, the previously staged section's+ (doc id, label), and the just-computed node `id`. Append resulting edge+ actions to a per-worker edge buffer (NOT the node staging file — different+ target index).++ **Text-section locators** (`lib.rs::section_label`) are exactly two forms:+ `s{i}` (from `emit_document` — md/txt/html/docx prose) and `p{page}-s{sec}`+ (from the PDF extractor — page-major, so stream order IS the lexicographic+ (page, sec) reading order). Any other locator (row/line/byte/table) is not+ a text section and never reaches `detect_text`. Labels: `s3` → "section 3";+ `p2-s0` → "page 2 section 0". The pipeline tracks the previously staged+ section per file in stream order; that predecessor — not locator+ arithmetic — feeds sequence@2, which is what lets PDF sections chain+ across page boundaries.++2a. **File-card node** (before extraction, once per Phase-B file): stage one+ card doc to the file's dataset index at `_id = anchor_doc_id`+ (`ids::doc_id(slug, file_key, FILE_CARD_LOCATOR)`), fields:+ `title` = filename, `ax_path`, `ax_paths`, `ax_file`,+ `ax_locator = "file"`, `ax_dataset`, `ax_run`, `ax_format`. No body — it+ is anchor infrastructure, not content, and is not counted as an extracted+ record. This is the node that makes every file-level edge hydratable+ (row/line/page families have no `s0` doc; pre-@2 their anchors were+ ghosts). Replacement safety: the card carries `ax_file`, so the existing+ delete-before-replace `delete_by_query` removes and the re-run re-stages+ it under the same deterministic id.3. **Replacement invalidation** (same site as the existing`delete_by_query(index, {"term": {"ax_file": key}})` cleanup, lib.rs ~1000):when a file is being replaced, soft-invalidate its prior edges FIRST:@@ -946,11 +1057,13 @@ converges, and readers surface dangling honestly (§4.3).### 6.8 Autoindex tests`detect/mod.rs` unit tests: the §2.3 pin vector; wikilink/mdlink resolution-incl. ambiguity determinism; samedir chain (not clique) on the §8 fixture-folder; sequence on a 3-section file. Integration (behind the existing-live-server test pattern): index the §8.1 folder twice, assert the edge set is-byte-identical across runs and matches §8.3's (src, dst, type, detector)-tuples with autoindex-derived node ids.+incl. ambiguity determinism; pathcite exact/suffix/bare-refusal/noise rules;+cratecite whole-word + citability rules; samedir chain (not clique) on the §8+fixture folder; sequence opener + chaining (incl. a PDF page boundary).+Integration (behind the existing mock-ES test pattern): index the §8.1 folder+twice, assert the edge set is byte-identical across runs and matches §8.3's+(src, dst, type, detector) tuples with autoindex-derived node ids per the+§8.3a delta (file cards, @2 tags, sequence openers).---@@ -1006,6 +1119,23 @@ zeros — the panel exists to prove absence). The subtitle under `edgeTimeline`must carry the embedder honesty string when `overview.embedder` is`"lexical-feature-hash"`: `"recall is lexical (feature hashing) — not neural"`.+Amendment (map + statistics revision, 2026-07-30): the dashboard now renders+SIX additional panels around the nine above, in this page order —+`controls` (12, brain switcher · trail · FIND), `map` (12, mount point for+`ux/brain-map.js`; the panel body owns only the mount + the permanent+"GROUPED BY LINK STRUCTURE — CITATIONS AND FOLDER NEIGHBORHOOD, NOT MEANING"+disclosure), `scrub` (12, the ONE belief-time caret for the whole page,+hoisted out of `ego`), then after `edgeTimeline`: `notes` (4, note total ++by-file-type tally the page itself ran), `crossings` (4, links across file+types from the §2.1 `src_format`/`dst_format` stamps; brains indexed before+stamping show the REINDEX message, never a guess), `reads` (4, the page's own+attributed fetch log — what/how much/why — plus the server's per-index search+counters framed as since-boot). The original nine keep their ids/kinds/cols;+`ego` remains the terminal evidence surface (the anti-hairball rationale in+`ux/ego-ledger.js` stands). §7.4's seed skeleton stays at the nine v1 panels+on purpose — the SPA registry is the render truth and absent ids are created+on boot, so the seed is a durable skeleton, not the composition.+### 7.2 registry.js (exact edits)```js@@ -1112,6 +1242,21 @@ alpha.md, etc. — src_file = evidence.source for all fixture edges. Note edges#1 and #5 share (src,dst) but differ in type → distinct edge_ids: paralleledges of different types are legal and expected.)+### 8.3a Autoindex-output delta (cross-file-type revision)++The table above is the API-seeded fixture (abstract `note-*` ids, @1 tags) and+stays normative for §8.4–§8.6 — those edge_ids are pinned. **Autoindex output+over the same folder now differs in exactly three ways** (asserted by the+`detect/e2e.rs` suite):++1. Detector tags are `wikilink@2` / `samedir@2` (and node-id derivation is+ autoindex's, as before): wikilink src = the s0 SECTION doc (where the+ evidence lives), wikilink dst and both samedir endpoints = FILE CARDS.+2. Five additional `sequence@2` opener edges, one per file:+ `card → s0`, quote `"section 0 opens {rel}"`, weight 0.8, conf 0.99.+ Total fixture edge count: 13 (4 wikilink + 4 samedir + 5 sequence).+3. Every edge carries `src_format: "md"`, `dst_format: "md"`.+### 8.4 Expected `graph_expand` (engine-level)Request: `frontier=["note-alpha"], hops=1, direction=Both, types=None,@@ -1146,6 +1291,7 @@ direction both, limit 100, include_evidence true, include_nodes false):"brain": "notes","contract": "xerj-second-brain/1","node": "note-alpha",+ "seeds": ["note-alpha"],"as_of": 1753700000000,"hops": 1,"direction": "both",diff --git a/docs/design/second_brain_finish_wf.js b/docs/design/second_brain_finish_wf.jsnew file mode 100644index 000000000..4a9ba9c3e--- /dev/null+++ b/docs/design/second_brain_finish_wf.js@@ -0,0 +1,418 @@+export const meta = {+ name: 'second-brain-finish',+ description: 'Recover the unfinished second-brain use case, verify it against its contract, redesign the UX from fresh research, implement, and prove it live end to end',+ phases: [+ { title: 'Recover', detail: 'build + test + spec-conformance ground truth — what actually works today' },+ { title: 'Research', detail: 'fresh landscape, agent-memory, UX and honest-differentiation research in parallel' },+ { title: 'Design', detail: 'synthesize research into one concrete design decision set' },+ { title: 'Implement', detail: 'close the gaps and build the redesigned UX + demo corpus' },+ { title: 'Verify', detail: 'live end-to-end xerj brain run + UX render + spec conformance' },+ { title: 'Ship', detail: 'case study + website page from what was actually proven' },+ ],+}++const REPO = '/home/claude/ai/xerj'+const SPEC = `${REPO}/docs/design/SECOND_BRAIN_SPEC.md`+const SCRATCH = '/tmp/claude-1001/-home-claude-ai-xerj/e36b8c4c-3a94-4a76-80f1-2119380319c6/scratchpad'++const GROUND = `+## Where this work stopped (recovered state — verified, do not re-derive)++The XERJ "second brain" use case was built across three parallel streams and then+ABANDONED MID-VERIFICATION when an earlier workflow's integrate agent died on an API+500. Recovery finding: **integration and shipping already completed in earlier+sessions; the VERIFY phase never ran.** So the code exists but has never been proven+to build, run, or match its contract.++- Branch: \`feat/second-brain\` in the MAIN repo at ${REPO} (already checked out there).+ 14 commits ahead of main, **42 files, +10,528 lines**. Do NOT switch branches.+- The CONTRACT (authoritative, 1,217 lines): ${SPEC}. It is normative — exact index+ mappings, exact edge_id computation, exact endpoint shapes, exact UX panel ids.+ Read it before touching anything. Where code and spec disagree, the spec wins+ unless the spec is demonstrably wrong (say so loudly if it is).+- What exists on the branch (line counts verified):+ * \`engine/crates/xerj-engine/src/graph.rs\` (641) — graph traversal/expansion+ * \`engine/crates/xerj-api/src/graph_api.rs\` (1,662) — the HTTP half:+ POST /_graph/{brain}/link, DELETE .../link/{edge_id}, GET .../ego, GET .../overview+ * \`engine/crates/xerj-server/src/brain.rs\` (690) — the \`xerj brain <folder>\` one-command CLI+ * \`engine/crates/xerj-autoindex/src/detect/\` — link detectors (wikilink, mdlink, href, samedir, sequence, e2e)+ * \`xerj-ux/src/ux/ego-ledger.js\` (871), \`xerj-ux/src/data/second-brain-api.js\` (698),+ \`xerj-ux/src/dashboards/second-brain.js\` (64)+ * tests: \`engine/crates/xerj-engine/tests/graph_expand.rs\` (494),+ \`engine/crates/xerj-server/tests/brain_cli.rs\` (334)+- No TODO/unimplemented markers remain. The UX is written to hit the real API and+ explicitly NEVER falls back to mock data.+- Unrelated: \`git stash@{0}\` holds a prior session's debug PROBE. LEAVE IT ALONE.++## What the feature is (the story it must tell)++\`xerj brain <folder>\` points one binary at a folder of notes and turns it into a+queryable, **bi-temporal, provenance-carrying knowledge graph** — then a console+dashboard shows what your notes believe. The three claims that make it different:+ 1. **Every link has a quote.** An edge is not an assertion, it is evidence — the+ detector records the exact text that justified the link.+ 2. **Replayable at any moment.** Bi-temporal (\`valid_at\` / \`as_of\`): you can ask+ what the brain believed last Tuesday. Retired links are invalidated, never deleted.+ 3. **One binary, zero config.** No graph database, no ETL, no embedding service.+LANGUAGE RULE (binding, from the spec): every human-visible surface says+"link / believed since / retired / what taught this" — NEVER schema vocabulary+(\`edge\`, \`src\`, \`dst\`, \`valid_at\`, \`as_of\`) in the UI.+HONESTY RULE (binding): XERJ is **not** a graph database and must never be presented+as one. It is a search engine with a graph-shaped index over its own documents.++## Build & run discipline (hard rules — violating these is a failed task)++- Cargo workspace is ${REPO}/engine. Build ONLY scoped:+ \`cargo build --release -j 32 -p <crate>\`. NEVER workspace-wide. NEVER \`cargo clean\`.+ The chain is xerj-engine → xerj-api → xerj-autoindex → xerj-console-api → xerj-server.+- \`cargo fmt\` + \`cargo clippy -D warnings\` clean on every crate you touch.+- Booting the server in this sandbox: foreground boots are REAPED (exit 144). Use the+ Bash tool's \`run_in_background: true\`, then poll readiness with+ \`until curl -s -o /dev/null -w '%{http_code}' localhost:PORT/ | grep -q 200; do sleep 2; done\`.+ Config is a TOML with \`[server] es_compat_port / rest_port / data_dir\`.+ **USE PORTS 9330-9345** and data dirs under ${SCRATCH} — other work may hold 9200/9310.+- Commits authored \`xerj-org <[email protected]>\`. NEVER a Claude co-author trailer. Never+ mention ctrl-frk. Do NOT push. Do NOT commit to main. Commit on \`feat/second-brain\`.++## Honesty rules (this becomes a public case study)++- Every claim traces to something you RAN. If you did not run it, say "not measured".+- If the build is broken, that is the headline — fix it, and say it was broken.+- "The feature does not work yet" is a valid, valuable finding. Never paper over it.+- Do not invent benchmark numbers. Measure both sides or omit the comparison.+`++phase('Recover')++const RECOVER_SCHEMA = {+ type: 'object', additionalProperties: false,+ required: ['builds', 'build_errors_fixed', 'tests', 'spec_conformance', 'works_end_to_end', 'gaps', 'summary'],+ properties: {+ builds: { type: 'boolean' },+ build_errors_fixed: { type: 'string', description: 'what was broken and what you changed; "none" if it built clean' },+ tests: { type: 'string', description: 'exact test results per crate' },+ spec_conformance: {+ type: 'array',+ items: {+ type: 'object', additionalProperties: false,+ required: ['area', 'conforms', 'detail'],+ properties: {+ area: { type: 'string', description: 'e.g. edge schema, edge_id, POST link, GET ego, GET overview, recall blend, detectors, UX panels' },+ conforms: { type: 'string', enum: ['yes', 'partial', 'no', 'untested'] },+ detail: { type: 'string' },+ },+ },+ },+ works_end_to_end: { type: 'string', description: 'did `xerj brain <folder>` actually run and produce a queryable graph? exact evidence' },+ gaps: { type: 'array', items: { type: 'string' } },+ summary: { type: 'string' },+ },+}++const recovered = await agent(+`PHASE 1 — RECOVER. Establish the ground truth: does this feature actually work?++${GROUND}++An earlier build of the crate chain was already kicked off; assume nothing about it —+verify yourself.++Do this, in order:+1. **Build** the chain scoped: xerj-engine, xerj-api, xerj-autoindex, xerj-console-api,+ xerj-server. If it does not compile, FIX IT (minimally — the goal is a working+ baseline, not a redesign) and report exactly what was broken.+2. **Test**: run the second-brain tests — \`cargo test --release -j 32 -p xerj-engine --test graph_expand\`+ and \`-p xerj-server --test brain_cli\`, plus the crates' lib tests. Report real numbers.+3. **Spec-conformance audit**: read ${SPEC} and check the implementation against it —+ the edge index mapping (§2.1), the stored-document type discipline (§2.2), edge_id+ computation (§2.3), each endpoint's exact shape (§4.1-4.4), the recall graph modes+ (§5), the detector emission rules (§6.5), and the UX panel contract (§7.1). For each+ area say conforms yes/partial/no/untested with the evidence.+4. **End-to-end**: actually run it. Build a small notes folder (or use ${REPO}/docs —+ real markdown with real wikilinks/relative links), boot the server on port 9330 with+ a data dir under ${SCRATCH}, run \`xerj brain <folder>\`, then curl the graph endpoints+ (\`/_graph/{brain}/overview\`, \`/_graph/{brain}/ego?...\`) and show real JSON output.+ Does it produce a real graph with real quotes on the edges?+5. If the UX can be rendered/exercised headlessly (it is plain JS + a console API), check+ whether the dashboard's data contract matches what the API actually returns.++Return the structured result. Be blunt: if this thing is broken or hollow, say so with+evidence. That is the most valuable outcome of this phase.`,+ { label: 'recover-and-verify', phase: 'Recover', model: 'fable', effort: 'high', schema: RECOVER_SCHEMA }+)++phase('Research')++const RESEARCH = [+ {+ key: 'landscape',+ title: 'The second-brain / PKM landscape and what actually makes one valuable',+ brief: `Research the personal-knowledge-management and "second brain" landscape as it+stands now: Obsidian (+ its graph view and Bases), Logseq, Roam, Reflect, mem.ai, Notion+AI, Tana, Capacities, and the note-graph research tradition. Use WebSearch/WebFetch for+current facts — do not rely on memory. Answer concretely:+- What do users actually get value from, and what is famously *pretty but useless*+ (the "graph view is a hairball nobody uses" critique is well documented — get the real+ substance of it, and what the successful alternatives to a hairball are).+- Which of these tools carry PROVENANCE (why does this link exist?) and which carry+ TIME (what did I believe last month)? Be specific about who does and does not.+- What is the actual job-to-be-done: retrieval? rediscovery? writing? agent grounding?+Return findings with sources (URLs), and a blunt list of design traps to avoid.`,+ },+ {+ key: 'agent-memory',+ title: 'Agent-native memory: how AI agents actually consume a knowledge graph',+ brief: `XERJ's stated positioning is AI-native — the agent is the primary customer.+Research how AI agents actually use long-term memory and knowledge graphs today: MCP+(Model Context Protocol) memory servers, GraphRAG and its critiques, agentic-memory+patterns (episodic vs semantic), temporal knowledge graphs (e.g. Zep/Graphiti), and+retrieval-augmented approaches that use structure rather than pure embeddings. Use+WebSearch/WebFetch for current facts.+Answer: what interface does an agent WANT (tools? a query language? an ego query?), what+does bi-temporality buy an agent concretely, and what does provenance-per-edge buy it+(citation, trust, contradiction detection)? Note that this repo already has an MCP crate+(\`engine/crates/xerj-mcp\`) — read it and say whether the second brain should expose+itself through MCP, and exactly what tools it should expose.`,+ },+ {+ key: 'ux-design',+ title: 'Designing a knowledge-graph UX that is genuinely useful, not a hairball',+ brief: `Research and then DESIGN the visual/interaction language for this dashboard.+Read the existing implementation first — \`xerj-ux/src/ux/ego-ledger.js\` (871 lines),+\`xerj-ux/src/dashboards/second-brain.js\`, \`xerj-ux/src/data/second-brain-api.js\` — and+${SPEC} §7. Then research what actually works for graph/temporal/provenance UI: ego-network+views vs force-directed hairballs, timeline/time-travel controls, evidence-first+("show me the quote") interfaces, and dense-information dashboard patterns.+Also read the repo's own design language: ${REPO}/xerj-ux/assets/base.css and an existing+dashboard module for the house style, and ${REPO}/docs/case-studies/wordpress-security-audit/README.md+for the honesty tone.+Deliver a concrete design: what panels, what interactions, what the ego-ledger should+look and feel like, how time-travel is expressed, how a quote is surfaced. Be specific+enough to implement. Call out anything in the current implementation that should CHANGE.`,+ },+ {+ key: 'differentiation',+ title: 'Honest differentiation: what XERJ genuinely does that others do not',+ brief: `Adversarial, honesty-first analysis. Read ${SPEC} and the implementation, then+determine what this second brain ACTUALLY offers that a user cannot get elsewhere — and+what it does not. Use WebSearch to check the competition's real current capabilities.+Specifically pressure-test the three claims: (1) every link has a quote/provenance,+(2) bi-temporal replay, (3) one binary zero config. For each: is it true in the code, is+it genuinely rare in the market, and does a user actually care?+Then be brutal about the weaknesses: the detectors are lexical (wikilinks, relative+links, same-dir, sequence) — that is *structural* link extraction, NOT semantic+understanding. Does that undercut the "second brain" claim? What is the honest framing?+Also: XERJ is NOT a graph database (a binding rule) — so what happens at scale, and what+queries can it genuinely not answer? Return the honest positioning + the claims we must+NOT make.`,+ },+]++const research = await parallel(RESEARCH.map((r) => () =>+ agent(+`RESEARCH — ${r.title}++${GROUND}++## Recovered ground truth (what actually works today)+${JSON.stringify(recovered).slice(0, 6000)}++## Your assignment+${r.brief}++Use WebSearch and WebFetch for anything about the outside world — this must be current,+not recalled. Cite URLs. Read the real code in ${REPO} for anything about XERJ itself.+Be concrete and opinionated; a list of vague "considerations" is a failed result. Return+a thorough written report.`,+ { label: `research:${r.key}`, phase: 'Research', model: 'fable', effort: 'high' }+ )+))++phase('Design')++const design = await agent(+`PHASE 3 — DESIGN. Turn four research streams into ONE decision set an implementer can execute.++${GROUND}++## Recovered ground truth+${JSON.stringify(recovered).slice(0, 5000)}++## Research: landscape / what makes a second brain valuable+${String(research[0] || '').slice(0, 14000)}++## Research: agent-native memory + MCP+${String(research[1] || '').slice(0, 14000)}++## Research: UX design+${String(research[2] || '').slice(0, 14000)}++## Research: honest differentiation+${String(research[3] || '').slice(0, 12000)}++## Your job++Produce **the design**, as decisions, not options. Constraints:+- The working substrate (graph engine, HTTP API, CLI, detectors) is 10.5k lines that+ already exist and largely work. This is an EVOLUTION, not a rewrite. Justify every+ change to existing behavior; prefer additive.+- ${SPEC} is the contract. If your design changes it, write the exact spec amendment and+ say why the original was wrong.+- Everything must be buildable in this session by a handful of implement agents.++Decide and specify precisely:+1. **The use-case narrative** — the single story this feature tells, in the user's words.+ What is the demo? What does someone see in 60 seconds that makes it click?+2. **The UX** — final panel set, the ego-ledger interaction, how time-travel is expressed,+ how provenance/quotes are surfaced. Reference exact files to change and what the new+ render output must look like. Keep the binding LANGUAGE RULE.+3. **Agent surface** — should the second brain expose MCP tools? If yes, exactly which+ tools with which signatures (read \`engine/crates/xerj-mcp\` first). If no, say why not.+4. **Gap closure** — from the recover phase, which gaps MUST be fixed for the demo to be+ honest, ranked.+5. **The honest framing** — the claims we make and the claims we explicitly refuse to make.+6. **A work breakdown** into 4-6 independent implementation tasks with crisp acceptance+ criteria, each touching a disjoint file set (they will run in parallel).++Return the design as a detailed written document. It IS the implementation brief.`,+ { label: 'design', phase: 'Design', model: 'fable', effort: 'high' }+)++phase('Implement')++const TASKS = [+ { key: 'ux-dashboard', title: 'The dashboard + ego-ledger UX', hint: 'xerj-ux/src/dashboards/second-brain.js, xerj-ux/src/ux/ego-ledger.js, xerj-ux/src/data/second-brain-api.js, assets/base.css' },+ { key: 'api-gaps', title: 'Engine/API gap closure', hint: 'engine/crates/xerj-engine/src/graph.rs, engine/crates/xerj-api/src/graph_api.rs, memory recall graph modes' },+ { key: 'cli-demo', title: 'The `xerj brain` CLI path + a real demo corpus', hint: 'engine/crates/xerj-server/src/brain.rs, engine/crates/xerj-autoindex/src/detect/, a demo notes folder' },+ { key: 'agent-surface', title: 'The agent-facing surface (MCP tools / recipes)', hint: 'engine/crates/xerj-mcp, docs/recipes' },+]++const implemented = await pipeline(+ TASKS,+ (t) => agent(+`IMPLEMENT — ${t.title}++${GROUND}++## THE DESIGN (this is your brief — follow it)+${String(design).slice(0, 22000)}++## Recovered ground truth (what already works — do not break it)+${JSON.stringify(recovered).slice(0, 4000)}++## Your slice+${t.title}. Primary files: ${t.hint}. Other agents are working the other slices IN+PARALLEL in the same tree — stay inside your file set, and if you must touch a shared+file make the smallest possible edit.++Rules:+- Implement only what the design specifies for your slice. If the design is silent or+ wrong on a detail, use the spec (${SPEC}), and note the judgement call in your return.+- Rust: scoped release builds only, fmt + clippy -D warnings clean, add/extend tests.+- JS: no build step in this repo — plain ES modules. Match the house style of the+ existing dashboards exactly.+- Do NOT commit (the ship phase commits once, coherently). Do NOT push.+- VERIFY YOUR OWN WORK before returning: build it, test it, and where possible run it+ against a live server (ports 9330-9345, data dir under ${SCRATCH}).++Return: files changed, what you implemented, your build/test evidence, judgement calls,+and anything you could NOT do (honestly).`,+ { label: `impl:${t.key}`, phase: 'Implement', model: 'fable', effort: 'high' }+ ),+ (result, t) => agent(+`REVIEW the implementation slice "${t.title}" — adversarially, then FIX what is wrong.++${GROUND}++## What the implementer claims+${String(result).slice(0, 12000)}++Your job:+1. Verify the claims. Build it. Run the tests. Read the actual diff (\`git diff\` in ${REPO}).+ If a claim is not true, that is your finding.+2. Check it against ${SPEC} and the binding LANGUAGE + HONESTY rules (no schema vocabulary+ in UI text; never call XERJ a graph database).+3. Fix defects you find, minimally and carefully. Do not redesign.+4. Confirm fmt + clippy clean for any Rust touched.+Return: what you verified, what was wrong, what you fixed, and the final state.`,+ { label: `review:${t.key}`, phase: 'Implement', model: 'fable', effort: 'high' }+ )+)++phase('Verify')++const verified = await agent(+`PHASE 5 — LIVE END-TO-END VERIFICATION. Prove the whole thing works, or prove it does not.++${GROUND}++## The design that was implemented+${String(design).slice(0, 8000)}++## Implementation + review results+${JSON.stringify(implemented).slice(0, 14000)}++Do a full, honest, end-to-end run:+1. Build the whole chain scoped and clean. Report any breakage.+2. Run every second-brain test (graph_expand, brain_cli, engine/api/console lib tests) and+ the ES-YAML conformance gate if it is quick — report exact numbers.+3. **The real run**: pick a REAL folder of notes (e.g. ${REPO}/docs — real markdown with+ real links; or build a richer demo corpus if the implement phase made one), boot the+ server on port 9340 with a fresh data dir under ${SCRATCH}, and run+ \`xerj brain <folder>\` exactly as a user would. Capture the real terminal output.+4. Then interrogate the result over HTTP and show REAL JSON: overview stats, an ego query+ on a real note, and — critically — prove the two headline claims:+ * **every link has a quote**: show an edge carrying its evidence text.+ * **replayable at any moment**: assert a link, invalidate it, and show that a+ time-travel query still returns the earlier belief. If this does not work, SAY SO.+5. Check the UX data contract against the live API responses: does what the dashboard+ expects match what the server returns, field for field?+6. Report token/time/size economics only if you actually measured them.++Return a detailed verdict: what is PROVEN working (with the evidence inline), what is+partial, and what is broken. This report gates the case study — do not flatter it.`,+ { label: 'live-verify', phase: 'Verify', model: 'fable', effort: 'high' }+)++phase('Ship')++const shipped = await agent(+`PHASE 6 — SHIP. Write the use case from what was actually proven, and commit.++${GROUND}++## The design+${String(design).slice(0, 10000)}++## LIVE VERIFICATION (this is your source of truth — publish only what it proves)+${String(verified).slice(0, 18000)}++Write:+1. \`${REPO}/docs/usecases/second-brain/README.md\` — the use case: the story, what it does,+ the real terminal output of \`xerj brain <folder>\`, the real API responses, the two+ headline claims with their evidence, and an explicit "what this does NOT do" section+ (the detectors are structural/lexical, XERJ is not a graph database, scale limits).+2. \`${REPO}/docs/usecases/second-brain/REPRODUCE.md\` — every step to reproduce, exactly.+3. A website page \`${REPO}/landing/use-cases/second-brain.html\` — mirror the structure and+ house style of \`${REPO}/landing/use-cases/code-security-audit.html\` (read it first).+ Use the site's existing CSS classes; do not invent new ones. Do NOT add it to any+ subnav/index yet — the human will decide placement.+4. Commit everything from this whole workflow on \`feat/second-brain\`, authored+ \`xerj-org <[email protected]>\`, no Claude co-author trailer, ONE coherent commit (or a+ small number of logical ones). Do NOT push.++Rules: if verification showed something is broken or unproven, the docs must say so+plainly — a case study that overclaims is worse than none. No invented numbers.++Return: files written, the commit sha, the headline claims you published, and everything+you deliberately refused to claim.`,+ { label: 'ship', phase: 'Ship', model: 'fable', effort: 'high' }+)++return {+ recovered,+ design_summary: String(design).slice(0, 3000),+ implemented_slices: TASKS.map((t) => t.key),+ verified: String(verified).slice(0, 6000),+ shipped: String(shipped).slice(0, 4000),+}diff --git a/docs/design/second_brain_graph_wf.js b/docs/design/second_brain_graph_wf.jsnew file mode 100644index 000000000..d36886952--- /dev/null+++ b/docs/design/second_brain_graph_wf.js@@ -0,0 +1,452 @@+export const meta = {+ name: 'second-brain-graph-ux',+ description: 'Research and rebuild the second-brain UX as an all-in-one visual knowledge graph with a helicopter default view, make the dashboard appear only after a brain exists, prove it on the whole repo (code+PDF+docs), and add a screencast scene',+ phases: [+ { title: 'Research', detail: 'Obsidian + the hairball literature + the existing ledger rationale' },+ { title: 'Design', detail: 'one decision set: helicopter view, drill-down, stats, cross-type relations' },+ { title: 'Build', detail: 'graph view, LOD/clustering, stats panel, conditional dashboard appearance' },+ { title: 'Corpus', detail: 'index the whole repo — 430 PDFs, 208 crates-worth of Rust, 6.6k markdown' },+ { title: 'Prove', detail: 'scale + drill-down + cross-type relations verified on that corpus' },+ { title: 'Screencast', detail: 'add a second-brain scene to AISE without breaking the existing demo' },+ ],+}++const REPO = '/home/claude/ai/xerj'+const AISE = '/home/claude/ai/aise'+const SPEC = `${REPO}/docs/design/SECOND_BRAIN_SPEC.md`+const SCRATCH = '/tmp/claude-1001/-home-claude-ai-xerj/e36b8c4c-3a94-4a76-80f1-2119380319c6/scratchpad'++const GROUND = `+## The mission++Make XERJ's second brain a knowledge-graph UX people LOVE: an all-in-one visual graph+that is never overwhelming no matter how big the corpus, proven on this repo's own+heterogeneous content (code + PDFs + docs), and captured as a screencast.++## Where things stand (verified today — do not re-derive)++- Branch \`feat/second-brain\` in the MAIN repo at ${REPO} (already checked out). The+ feature WORKS end-to-end and is spec-conformant: \`xerj brain <folder>\` indexes a folder+ into a bi-temporal, evidence-carrying link graph; HTTP API is+ \`POST/DELETE /_graph/{brain}/link\`, \`GET /_graph/{brain}/ego\`, \`GET /_graph/{brain}/overview\`.+ Contract: ${SPEC} (normative). Live-verified: 10 notes → 25 links in 0.1s; the repo's+ \`docs/\` → 364 links in 0.7s.+- **The current UX is a text LEDGER, not a node-link graph — deliberately.**+ \`xerj-ux/src/ux/ego-ledger.js\` (~1,100 lines) opens with: *"The graph view is a LEDGER,+ not a hairball. A global force-directed [layout is rejected]"*. READ THAT FILE AND ITS+ RATIONALE FIRST. It is well-reasoned and its evidence-first design (every link shows the+ quote that created it) is the product's best idea. You are not deleting it — you are+ ADDING the visual graph the user asked for, and reconciling it with that rationale.+- Panels/dashboard: \`xerj-ux/src/dashboards/second-brain.js\`, data layer+ \`xerj-ux/src/data/second-brain-api.js\`, registry \`xerj-ux/src/dashboards/registry.js\`,+ console seed \`engine/crates/xerj-console-api/src/seed.rs\`.++## What the user asked for, precisely (these are the acceptance criteria)++1. **An all-in-one visual knowledge-graph view** — a real graph, plus statistics: which+ data was used / read / searched **and why**, and relations between objects across+ different files and file types.+2. **SUCCESS CRITERION (the hard one):** the graph must NOT look overcomplicated or+ oversized *regardless of the size, depth and complexity of the data* — because the+ default is an **auto "helicopter" view** that always auto-selects the largest+ topics/connections at the start — **and** drill-down to the deepest level exists and+ works **smoothly**.+3. **The dashboard must appear only AFTER a brain has been indexed.** Today it is+ hardcoded into the registry and console seed, so a user who never ran \`xerj brain\`+ still sees an empty "Second Brain" dashboard — confusing. Make its presence conditional+ on at least one brain existing.+4. **Really test on a large, heterogeneous corpus** — this repo has **430 PDFs**, 208+ Rust files, ~6,662 markdown files, 75 JS files, plus gtm/ marketing papers. The point is+ to see how a PDF/marketing paper actually relates to crates and functions in the code.+5. **Screencast**: add a second-brain scene to the AISE demo engine. **DO NOT break or+ remove the existing demo scenes** — add to them.++## Binding product rules (violating these is a defect)++- **LANGUAGE RULE:** every human-visible surface says "link / believed since / retired /+ what taught this". NEVER schema vocabulary (\`edge\`, \`src\`, \`dst\`, \`valid_at\`, \`as_of\`)+ in UI text.+- **HONESTY RULE:** XERJ is **not a graph database** and must never be presented as one.+ Traversal is capped at 2 hops per call (\`hops>2\` returns a 400 saying exactly this);+ deeper drill-down must be built by iterating from the response's reachable set, not by+ pretending the engine does variable-depth traversal.+- **Detectors are structural/lexical** (wiki-links, markdown links, hrefs, folder+ adjacency, section sequence) — there is no semantic understanding and no LLM. The+ embedder is \`lexical-feature-hash\`. Any "relates to" claim in the UI must be truthful+ about which detector produced it.+- Keep evidence-first: a link's quote is the product's best idea; the visual graph must+ not lose it.++## Build & run discipline (hard rules)++- Cargo workspace ${REPO}/engine. Scoped builds ONLY: \`cargo build --release -j 32 -p <crate>\`.+ NEVER workspace-wide, NEVER \`cargo clean\`. fmt + clippy -D warnings clean on touched crates.+- JS: no build step — plain ES modules, match the house style of the existing dashboards.+ The console CSP/offline context blocks CDNs: **no external libraries** (no d3, no cytoscape).+ Write the graph yourself; prefer **Canvas 2D** for node/edge rendering at scale.+- Server boots: foreground boots are REAPED (exit 144). Use the Bash tool's+ \`run_in_background: true\`, then poll+ \`until curl -s -o /dev/null -w '%{http_code}' localhost:PORT/ | grep -q 200; do sleep 2; done\`.+- **WebAuthn gotcha (cost an hour today):** the console's relying party is hardcoded to+ \`http://localhost:9200\` (\`xerj-console-api/src/state.rs\` RpConfig default). Passkey+ enrollment ONLY works when the console is served on **port 9200** and browsed via+ **localhost** (not 127.0.0.1 — Chrome rejects raw IPs as an RP). Use 9200 for any+ browser work; use 9330-9345 for headless API-only servers.+- Headless browser IS available: \`puppeteer\` resolves from ${REPO}/node_modules (run node+ from ${REPO}), Chrome at /usr/bin/google-chrome. Enrollment works via a CDP virtual+ authenticator: \`WebAuthn.enable\` + \`WebAuthn.addVirtualAuthenticator({protocol:'ctap2',+ transport:'internal', hasResidentKey:true, hasUserVerification:true, isUserVerified:true,+ automaticPresenceSimulation:true})\`, then claim via the setup magic-link the server prints+ at first boot. A working reference script is ${REPO}/sb_capture.mjs.+- \`xerj brain\` gotcha: a stale resume journal in \`~/.xerj/autoindex\` makes re-runs skip+ detection. Use \`--fresh\` (or clear it) for clean runs.+- Commits authored \`xerj-org <[email protected]>\`, NO Claude co-author trailer, never mention+ ctrl-frk. Do NOT push. Commit on \`feat/second-brain\`.++## Honesty rules (a public demo comes out of this)++- Every number you publish must come from something you RAN. Never estimate silently.+- If the graph IS a hairball at 430-PDF scale, say so and fix it — do not ship a+ screenshot of the one corpus where it looked fine.+- "This does not work yet" is a valuable result. Overclaiming is the only failure mode+ that matters.+`++phase('Research')++const RESEARCH = [+ {+ key: 'obsidian',+ title: 'Obsidian graph view (and its peers) — what it does, and where it fails',+ brief: `Research Obsidian's graph view in depth using WebSearch/WebFetch (current facts,+not memory): the global graph vs the LOCAL graph, depth setting, filters/search-in-graph,+groups + colour rules, forces (centre/repel/link), "orphans", and the Canvas feature. Then+the honest part: the widely-documented criticism that the global graph is a pretty hairball+nobody uses. Find what people ACTUALLY find useful (local graph at depth 1-2, filtered+subgraphs, colour groups) and what they abandon.+Also survey the peers for scale techniques: Logseq, Roam, Kumu, Gephi, and the research+tradition — community detection / clustering for overview, level-of-detail, semantic zoom,+focus+context, degree-of-interest filtering, edge bundling, "overview first, zoom and+filter, details on demand" (Shneiderman).+Deliver: a concrete list of what to copy, what to avoid, and specifically HOW tools keep a+graph readable as N grows into the thousands. Cite URLs.`,+ },+ {+ key: 'helicopter',+ title: 'The helicopter view: how to auto-summarise a large graph so it is never a hairball',+ brief: `This is the user's hard success criterion, so treat it as an engineering problem.+Research and then specify concrete algorithms that run in plain JS on Canvas with no+libraries, over a graph of up to ~50k links:+- **Clustering / community detection** cheap enough for the browser (label propagation,+ Louvain-lite, or connected-components + degree ranking). How do we pick "the largest+ topics" automatically?+- **Level of detail / semantic zoom**: what is drawn at helicopter altitude (clusters as+ super-nodes sized by membership) vs mid vs leaf level, and how the transition stays smooth.+- **Layout without a global force simulation**: deterministic seeded placement, radial/ring+ layouts per cluster, or a coarse force run on the CLUSTER graph only (a few dozen nodes)+ rather than all N. Remember the existing ledger explicitly rejected a global force sim —+ respect the reason (jitter, non-determinism, hairball) while still giving a graph.+- **Drill-down**: how expanding a cluster stays smooth (animated, bounded work per frame),+ and how it composes with the engine's 2-hop cap (you iterate ego calls from the reachable+ set — you must NOT claim variable-depth traversal).+- **Budgets**: hard caps on nodes/edges drawn per frame, and what the UI honestly says when+ it is showing a summary rather than everything.+Deliver precise algorithm choices with complexity, the data the API must supply, and the+draw budget. Be concrete enough to implement.`,+ },+ {+ key: 'ledger-and-api',+ title: 'What the existing UX and API can already give us',+ brief: `Read the real code, not docs: \`xerj-ux/src/ux/ego-ledger.js\` (all of it — the+rationale comment at the top is important), \`xerj-ux/src/dashboards/second-brain.js\`,+\`xerj-ux/src/data/second-brain-api.js\`, \`xerj-ux/src/ux/panel-render.js\` ++\`charts*.js\` (the house viz primitives you must match), \`xerj-ux/assets/base.css\` (the+design tokens/house style), and \`xerj-ux/src/dashboards/registry.js\`.+Then the server side: \`engine/crates/xerj-api/src/graph_api.rs\` — exactly what+\`/ego\` and \`/overview\` return today (fields, caps, \`not_shown\` accounting), and+\`engine/crates/xerj-console-api/src/seed.rs\` for how dashboards are seeded.+Answer: (a) what does the graph view need that the API does NOT return today (e.g. a+whole-brain node+edge dump for layout, cluster hints, per-node degree, file-type facets)?+Specify the exact new/extended endpoint shape needed, honouring the spec's conventions.+(b) How is the dashboard currently registered, and what is the cleanest way to make it+appear only when ≥1 brain exists — list the exact files/functions to change.+(c) Which house primitives should the graph reuse so it looks native.`,+ },+ {+ key: 'stats-and-crosstype',+ title: 'The statistics story and cross-file-type relations',+ brief: `The user wants "statistics which data used/read/search and why" and "relations+between objects from different files" — including how a PDF or marketing paper relates to+crates and functions in code.+Investigate what is TRULY available: read \`engine/crates/xerj-autoindex/src/detect/\`+(all detectors: wikilink, mdlink, href, samedir, sequence, e2e) and the extractors+(\`extract/\` — including the PDF path). Determine honestly which cross-file-type links+this system can actually produce over this repo: can a PDF in \`landing/resources/\` or+\`gtm/\` ever link to a Rust crate? Through what mechanism (an href? a filename mention? a+same-directory rule? nothing at all)?+If the answer is "structurally, almost never", say so plainly and propose what WOULD create+honest cross-type relations (e.g. a detector that links a document to a code file when it+cites the path/crate name — and what its evidence quote would be). Any new detector must+follow the spec's determinism + evidence rules (${SPEC} §6).+Also specify the statistics panel: what counts are real and available (per detector, per+file type, per node degree, ingest/read counts if the engine exposes them), and what is NOT+available and must therefore not be shown. "Which data was searched and why" must map to+something real — say what.`,+ },+]++const research = await parallel(RESEARCH.map((r) => () =>+ agent(+`RESEARCH — ${r.title}++${GROUND}++## Your assignment+${r.brief}++Use WebSearch/WebFetch for anything about the outside world; read the REAL code in ${REPO}+for anything about XERJ. Be concrete and opinionated — a list of vague considerations is a+failed result. Return a thorough report.`,+ { label: `research:${r.key}`, phase: 'Research', model: 'fable', effort: 'high' }+ )+))++phase('Design')++const design = await agent(+`DESIGN — turn the research into ONE decision set an implementer can execute.++${GROUND}++## Research: Obsidian + peers+${String(research[0] || '').slice(0, 15000)}++## Research: helicopter view algorithms+${String(research[1] || '').slice(0, 15000)}++## Research: existing UX + API+${String(research[2] || '').slice(0, 15000)}++## Research: statistics + cross-type relations+${String(research[3] || '').slice(0, 13000)}++Produce THE DESIGN, as decisions not options:++1. **The view.** The all-in-one second-brain screen: what is on it, in what order, and what+ the visual graph looks like at helicopter altitude vs drilled in. Reconcile explicitly+ with the existing ledger's anti-hairball rationale — say what the graph adds, what the+ ledger keeps, and how a user moves between them. The evidence quote must survive.+2. **The helicopter algorithm.** Exact clustering + layout + LOD choices, draw budgets, and+ the interaction model for drill-down (including how it composes with the 2-hop API cap+ without lying about traversal depth). State the target: readable at 25 links AND at+ 50,000 links.+3. **The API delta.** Exact new/extended endpoint(s) with request/response shapes, honouring+ ${SPEC} conventions (contract string, \`not_shown\` accounting, caps). Keep it minimal.+4. **Conditional appearance.** Exact mechanism + files so the dashboard only shows when ≥1+ brain exists, including what a user with no brain sees instead (an honest empty/CTA state+ somewhere sensible, or nothing at all — decide).+5. **Statistics panel.** Only real, available numbers — list them, and list what you refuse+ to show because the data does not exist.+6. **Cross-type relations.** The honest answer for PDF↔code, and if a new detector is+ warranted, its exact spec-conformant definition (tag, weight, confidence, evidence rule,+ determinism).+7. **Work breakdown** into 4-6 parallel implementation tasks with disjoint file sets and+ crisp acceptance criteria.++Return a detailed written document — it IS the implementation brief.`,+ { label: 'design', phase: 'Design', model: 'fable', effort: 'high' }+)++phase('Build')++const TASKS = [+ { key: 'graph-view', title: 'The Canvas knowledge-graph view + helicopter LOD + drill-down',+ files: 'xerj-ux/src/ux/ (new graph module), xerj-ux/assets/base.css' },+ { key: 'api-delta', title: 'The API delta the graph needs (whole-brain summary / cluster feed)',+ files: 'engine/crates/xerj-api/src/graph_api.rs, engine/crates/xerj-engine/src/graph.rs' },+ { key: 'dashboard-stats', title: 'Dashboard composition + the statistics panel + ledger integration',+ files: 'xerj-ux/src/dashboards/second-brain.js, xerj-ux/src/data/second-brain-api.js, xerj-ux/src/ux/ego-ledger.js' },+ { key: 'conditional', title: 'Conditional dashboard appearance (only after a brain exists)',+ files: 'xerj-ux/src/dashboards/registry.js, xerj-ux/src/app.js, engine/crates/xerj-console-api/src/seed.rs' },+ { key: 'crosstype', title: 'Cross-file-type relations (detector work, if the design calls for it)',+ files: 'engine/crates/xerj-autoindex/src/detect/, docs/design/SECOND_BRAIN_SPEC.md amendment' },+]++const built = await pipeline(+ TASKS,+ (t) => agent(+`BUILD — ${t.title}++${GROUND}++## THE DESIGN (your brief — follow it)+${String(design).slice(0, 24000)}++## Your slice+${t.title}. Primary files: ${t.files}. Other agents work the other slices IN PARALLEL in+the same tree — stay in your file set; if you must touch a shared file, make the smallest+possible edit.++Rules:+- No external JS libraries (CSP + offline). Canvas 2D for the graph. Plain ES modules.+- Match the house style exactly (base.css tokens, the existing dashboards' idiom).+- Rust: scoped release builds, fmt + clippy -D warnings clean, extend the tests.+- Honour the LANGUAGE and HONESTY rules in every string you write.+- Do NOT commit. Do NOT push.+- VERIFY YOUR OWN WORK: build it; where it is JS, exercise it headlessly in node or in+ puppeteer against a live server (port 9200 for browser work — see the WebAuthn note).+Return: files changed, what you built, your verification evidence, judgement calls, and+anything you could not do.`,+ { label: `build:${t.key}`, phase: 'Build', model: 'fable', effort: 'high' }+ ),+ (result, t) => agent(+`REVIEW the slice "${t.title}" adversarially, then FIX what is wrong.++${GROUND}++## What the implementer claims+${String(result).slice(0, 12000)}++1. Verify every claim — read the real diff (\`git diff\` in ${REPO}), build it, run it.+ A claim that is not true is your finding.+2. Check the LANGUAGE rule (no schema vocabulary in UI text) and the HONESTY rule (never+ "graph database"; no fake traversal depth) on every user-visible string.+3. Check it against ${SPEC} where relevant.+4. Fix defects minimally. Do not redesign.+Return what you verified, what was wrong, what you fixed, and the final state.`,+ { label: `review:${t.key}`, phase: 'Build', model: 'fable', effort: 'high' }+ )+)++phase('Corpus')++const corpus = await agent(+`INDEX THE WHOLE REPO — the large heterogeneous corpus test.++${GROUND}++## What was built+${JSON.stringify(built).slice(0, 12000)}++This repo contains **430 PDFs** (landing/resources, gtm/, gtm/competitors/**), **208 Rust+files**, **~6,662 markdown files**, 75 JS files. That is the corpus.++Do this:+1. Build the chain scoped and clean first.+2. Boot a server on **port 9200** (browser work later needs that port), fresh data dir under+ ${SCRATCH}, and clear \`~/.xerj/autoindex\` so nothing resumes stale.+3. Run \`xerj brain\` over the repo. Start with a large but sane scope and grow — e.g.+ \`docs/\` + \`gtm/\` + \`landing/\` + \`engine/crates/\`. Capture the REAL terminal output and+ timings at each scale. If it is slow or falls over, that is a finding — report it with+ numbers, then work out whether it is a real limit or a config issue.+4. Report the true shape of the result: how many files, how many links, per-detector+ breakdown, per-file-type breakdown, the biggest hubs, and how many links are AUTHORED vs+ STRUCTURAL.+5. **The cross-type question:** find real examples of a PDF or marketing paper related to a+ crate/code file. Show the actual link with its evidence. If cross-type links essentially+ do not form, SAY SO with the numbers — that is the honest answer and the design should+ have predicted it.+6. Leave the server RUNNING on 9200 with the corpus indexed — the next phase needs it. State+ the brain name(s) clearly.++Return: exact commands, real output, the measured numbers, the cross-type findings (with+evidence), and any failure or limit you hit.`,+ { label: 'index-large-corpus', phase: 'Corpus', model: 'fable', effort: 'high' }+)++phase('Prove')++const proof = await agent(+`PROVE THE SUCCESS CRITERION — visually, at scale, headlessly.++${GROUND}++## The design+${String(design).slice(0, 8000)}++## What was built+${JSON.stringify(built).slice(0, 8000)}++## The indexed corpus (server should be live on 9200)+${String(corpus).slice(0, 10000)}++The user's criterion: **the graph must not look overcomplicated or oversized regardless of+size/depth/complexity — the helicopter default auto-selects the largest topics — and+drill-down to the deepest level works smoothly.**++Do this:+1. Drive the REAL console in puppeteer (port 9200, virtual WebAuthn authenticator — see+ ${REPO}/sb_capture.mjs for a working claim flow). Screenshot the second-brain view on the+ LARGE corpus at: (a) helicopter default, (b) one drill-down step, (c) deepest drill-down,+ (d) the statistics panel, (e) an evidence quote open.+ Save PNGs under ${SCRATCH}/graphshots/.+2. **Judge it honestly against the criterion.** Is the default view readable, or is it a+ hairball? Count the drawn nodes/edges at each level. Measure frame/interaction time if you+ can. If it fails the criterion, FIX IT and re-shoot — that is the job, not a caveat.+3. Verify the conditional appearance: with a brain present the dashboard shows; point the+ console at a fresh empty server (different port/data dir) and confirm it does NOT appear+ (or shows the designed empty state). Screenshot both.+4. Verify the honesty rules survived on real rendered text: no schema vocabulary, no+ "graph database", no fake traversal-depth claim.+Return: the screenshot paths, the counts/timings, a blunt verdict on the success criterion,+and what you fixed to meet it.`,+ { label: 'prove-at-scale', phase: 'Prove', model: 'fable', effort: 'high' }+)++phase('Screencast')++const screencast = await agent(+`SCREENCAST — add a second-brain scene to the AISE demo engine.++${GROUND}++## The proven UX+${String(proof).slice(0, 10000)}++AISE lives at ${AISE} (no git — be careful, there is no undo). It records the Xerj demo:+puppeteer drives scenes, \`src/lib/recorder.js\` captures CDP frames into a constant-fps mp4+so video-time == wall-clock, and \`src/lib/voice.js\` (edge-tts) muxes narration at each+tooltip's \`start_ms\`. Existing scenes: \`src/scenes/01-boot.js\`, \`02-show-data.js\`,+\`03-bulk-ingest.js\`, \`04-verify.js\`, \`05-open-xerj-console.js\`, \`06-walk-spa.js\`,+wired in \`src/orchestrator.js\` (~line 200).++**DO NOT modify or remove the existing scenes or the existing demo flow.** ADD a new scene+(e.g. \`07-second-brain.js\`) and wire it in after the console walk, so the existing demo+still runs exactly as before.++The user's standing requirements for these videos (binding):+- **No usernames or home paths on screen** — everything under \`/tmp/xerj\`, never \`/home/<user>\`.+- Narration never speaks the eyebrow label ("SCENE 7"), never spells out code punctuation+ (say "POST bulk", not "slash underscore bulk"), no spaced-thousands (voice code-switches).+- **No large silent gaps** — narration plays OVER the action, not after it.+- Interactions must show the product WORKING, not just navigation.+- Console/WebAuthn must be on **:9200** (rp_origin).+- Pre-warm the voice cache before recording, else edge-tts latency stalls the run.++The scene should tell the second-brain story: one command over a real folder → the graph+appears at helicopter altitude → drill into a cluster → open a link's evidence quote →+(if it works) the retire/replay beat.++Running the recorder needs Chrome + port binds: use the Bash tool's \`run_in_background\`+(a plain foreground run dies exit 144). A full render takes ~5-8 minutes.++Do this:+1. Write the scene, following the house patterns of the existing scenes exactly (read+ \`06-walk-spa.js\` and \`src/lib/stage.js\` first).+2. Wire it into the orchestrator additively.+3. Stage whatever the scene needs (a notes/corpus folder under /tmp/xerj, the built binary).+4. **Try to actually render an mp4.** If the full pipeline runs, report the output path and+ verify sync (there is a \`review.py\`). If the environment blocks a full render, say so+ honestly and leave a single documented command that produces it.+Return: files added/changed (and confirmation the existing scenes are untouched), the mp4+path if produced, and anything that blocked you.`,+ { label: 'screencast', phase: 'Screencast', model: 'fable', effort: 'high' }+)++return {+ design_summary: String(design).slice(0, 3000),+ built: TASKS.map((t) => t.key),+ corpus: String(corpus).slice(0, 6000),+ proof: String(proof).slice(0, 8000),+ screencast: String(screencast).slice(0, 5000),+}diff --git a/engine/crates/xerj-api/src/graph_api.rs b/engine/crates/xerj-api/src/graph_api.rsindex 3cc9b03c8..19b53f8bd 100644--- a/engine/crates/xerj-api/src/graph_api.rs+++ b/engine/crates/xerj-api/src/graph_api.rs@@ -18,7 +18,8 @@//! ```text//! POST /_graph/{brain}/link assert an edge (lazy index create)//! DELETE /_graph/{brain}/link/{edge_id} soft-invalidate (bi-temporal; never removes)-//! GET /_graph/{brain}/ego neighborhood of one node (+ hydration)+//! GET /_graph/{brain}/ego neighborhood of one node — or up to+//! 64 via `nodes=` (+ hydration)//! GET /_graph/{brain}/overview brain-level stats (dashboard feed)//! ```//!@@ -72,6 +73,13 @@ const BRAIN_META_ID: &str = "__xerj-brain-meta";/// Max returned edges for `ego` (`limit` clamp ceiling).const MAX_EGO_LIMIT: usize = 1000;+/// Max seed ids accepted by `ego`'s `nodes=` param (multi-seed expansion).+/// Excess seeds are dropped and counted into `not_shown.frontier_clipped` —+/// the same honesty channel the engine uses for its own frontier clip. Deeper+/// exploration composes by iterating: expand again from a slice of the+/// previous response's `reachable` ids.+const EGO_SEEDS_CAP: usize = 64;+/// Max dangling node ids listed verbatim in `not_shown.dangling_ids`.const MAX_DANGLING_LISTED: usize = 50;@@ -164,6 +172,8 @@ fn edge_index_mapping() -> Value {"confidence": { "type": "float" },"schema_version": { "type": "integer" },"src_file": { "type": "keyword" },+ "src_format": { "type": "keyword" },+ "dst_format": { "type": "keyword" },"evidence": {"properties": {"quote": { "type": "text" },@@ -595,9 +605,16 @@ pub async fn unlink(/// Query params for `GET /_graph/{brain}/ego` (SECOND_BRAIN_SPEC §4.3).#[derive(Debug, Default, Deserialize)]pub struct EgoParams {- /// REQUIRED — the node to expand from.+ /// The node to expand from. Exactly one of `node`/`nodes` is required.#[serde(default)]pub node: Option<String>,+ /// Comma-separated seed ids for multi-seed expansion (mutually exclusive+ /// with `node`; `node` is the 1-element case). Deduped; clamped to+ /// [`EGO_SEEDS_CAP`] with the clip counted in+ /// `not_shown.frontier_clipped`. This is the sanctioned drill-down+ /// iterator: feed a slice of the previous response's `reachable` back in.+ #[serde(default)]+ pub nodes: Option<String>,/// 1 (default) or 2; anything else is a 400 with the not-a-graph-database/// wording.#[serde(default)]@@ -629,9 +646,12 @@ pub struct EgoParams {pub include_evidence: Option<bool>,}-/// `GET /_graph/{brain}/ego` — the bounded neighborhood of one node.-/// Traversal reads doc-values columns only; evidence and node summaries are-/// hydrated AFTER traversal, on the bounded result set, via `ids` queries.+/// `GET /_graph/{brain}/ego` — the bounded neighborhood of one node, or of up+/// to [`EGO_SEEDS_CAP`] seeds via `nodes=` (the engine expands a whole+/// frontier at frontier-size-independent cost, so multi-seed is the same one+/// bounded read). Traversal reads doc-values columns only; evidence and node+/// summaries are hydrated AFTER traversal, on the bounded result set, via+/// `ids` queries.pub async fn ego(State(state): State<AppState>,Path(brain): Path<String>,@@ -640,15 +660,45 @@ pub async fn ego(if let Err(reason) = validate_brain(&brain) {return error_response(StatusCode::BAD_REQUEST, reason);}- let node = match params.node.as_deref() {- Some(n) if !n.is_empty() => n.to_string(),- _ => {- return error_response(- StatusCode::BAD_REQUEST,- "`node` is required: the node id to expand from",- );- }+ if params.node.is_some() && params.nodes.is_some() {+ return error_response(+ StatusCode::BAD_REQUEST,+ "`node` and `nodes` are mutually exclusive — `nodes` is the multi-seed form",+ );+ }+ // Seed list: `node` is the 1-element case of `nodes`. Deduped preserving+ // order (the order is part of the `reachable` contract), then clamped to+ // EGO_SEEDS_CAP with the clip counted — never silent.+ let raw_seeds: Vec<String> = match (params.node.as_deref(), params.nodes.as_deref()) {+ (Some(n), None) if !n.is_empty() => vec![n.to_string()],+ (None, Some(ns)) => ns+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(String::from)+ .collect(),+ _ => Vec::new(),};+ let mut seeds: Vec<String> = Vec::with_capacity(raw_seeds.len());+ {+ let mut seen: HashSet<&str> = HashSet::with_capacity(raw_seeds.len());+ for id in &raw_seeds {+ if seen.insert(id.as_str()) {+ seeds.push(id.clone());+ }+ }+ }+ if seeds.is_empty() {+ return error_response(+ StatusCode::BAD_REQUEST,+ "`node` (or comma-separated `nodes`) is required: the node id(s) to expand from",+ );+ }+ let mut seeds_clipped = 0u64;+ if seeds.len() > EGO_SEEDS_CAP {+ seeds_clipped = (seeds.len() - EGO_SEEDS_CAP) as u64;+ seeds.truncate(EGO_SEEDS_CAP);+ }let hops = params.hops.unwrap_or(1);if hops == 0 || hops > 2 {return error_response(StatusCode::BAD_REQUEST, GRAPH_HOPS_CAP_REASON);@@ -699,7 +749,7 @@ pub async fn ego(};let req = GraphExpandRequest {- frontier: vec![node.clone()],+ frontier: seeds.clone(),hops: hops as u8,direction,types,@@ -714,10 +764,9 @@ pub async fn ego(// Per-edge direction relative to the expansion: an edge discovered at hop// h is "out" iff its src was in hop h's frontier (an edge admitted by both- // scans reports "out"). The hop-1 frontier is the ego node; the hop-2+ // scans reports "out"). The hop-1 frontier is the seed set; the hop-2// frontier is every endpoint hop 1 discovered.- let mut frontier1: HashSet<&str> = HashSet::new();- frontier1.insert(node.as_str());+ let frontier1: HashSet<&str> = seeds.iter().map(String::as_str).collect();let mut frontier2: HashSet<&str> = HashSet::new();for e in result.edges.iter().filter(|e| e.hop == 1) {for id in [e.src.as_str(), e.dst.as_str()] {@@ -814,6 +863,14 @@ pub async fn ego(}).map(|t| Value::from(t.chars().take(160).collect::<String>())).unwrap_or(Value::Null);+ // Truthful file label for the map/ledger: the autoindex+ // writer stamps `ax_path` on every note; null when absent+ // (manually-written nodes) — never fabricated.+ let path = src+ .and_then(|s| s.get("ax_path"))+ .and_then(Value::as_str)+ .map(Value::from)+ .unwrap_or(Value::Null);let hit_index = h.get("_index").cloned()@@ -821,7 +878,7 @@ pub async fn ego(found.insert(id.to_string());nodes_obj.insert(id.to_string(),- json!({ "title": title, "preview": preview, "index": hit_index }),+ json!({ "title": title, "preview": preview, "path": path, "index": hit_index }),);}}@@ -878,11 +935,10 @@ pub async fn ego(.collect();// Neighbors: first-discovery order following the sorted edge list,- // excluding the ego node; `via_edge` is the first sorted edge that+ // excluding the seed nodes; `via_edge` is the first sorted edge that// reached each one.let mut neighbors: Vec<Value> = Vec::new();- let mut seen: HashSet<&str> = HashSet::new();- seen.insert(node.as_str());+ let mut seen: HashSet<&str> = seeds.iter().map(String::as_str).collect();for e in &result.edges {for id in [e.src.as_str(), e.dst.as_str()] {if seen.insert(id) {@@ -891,10 +947,15 @@ pub async fn ego(}}+ // `seeds` echoes the ADMITTED seed list (post-dedupe, post-clamp) so the+ // caller can bookkeep exactly what was expanded; `node` stays on the+ // response whenever there is exactly one seed (the 1-element case keeps+ // its historical shape). Handler-clipped seeds fold into the same+ // `frontier_clipped` counter the engine uses — one honesty channel.let mut resp = json!({"brain": brain,"contract": GRAPH_CONTRACT,- "node": node,+ "seeds": seeds,"as_of": as_of,"hops": hops,"direction": direction_str,@@ -902,7 +963,7 @@ pub async fn ego("neighbors": neighbors,"not_shown": {"edges_clipped": result.stats.edges_clipped,- "frontier_clipped": result.stats.frontier_clipped,+ "frontier_clipped": result.stats.frontier_clipped + seeds_clipped,"expired_excluded": result.stats.expired_excluded,"type_filtered": result.stats.type_filtered,"segments_without_columns": result.stats.segments_without_columns,@@ -911,6 +972,21 @@ pub async fn ego("dangling_ids": dangling_ids,}});+ if let [only] = resp["seeds"].as_array().map(Vec::as_slice).unwrap_or(&[]) {+ // §8.5 is a normative instance including key order: `node` sits+ // between `contract` and `seeds`, so rebuild in place rather than+ // appending (which would serialize `node` last).+ let only = only.clone();+ let old = std::mem::take(resp.as_object_mut().expect("ego response is an object"));+ let mut ordered = serde_json::Map::with_capacity(old.len() + 1);+ for (k, v) in old {+ if k == "seeds" {+ ordered.insert("node".to_string(), only.clone());+ }+ ordered.insert(k, v);+ }+ resp = Value::Object(ordered);+ }if include_nodes {resp["nodes"] = Value::Object(nodes_obj);}@@ -1006,8 +1082,9 @@ fn embedder_id(state: &AppState) -> String {}/// `GET /_graph/{brain}/overview` — totals, live slice (types/detectors/-/// hubs), and the created-over-time histogram. Exactly three composed-/// searches; every top-N tail is reported in `not_shown`.+/// hubs), the created-over-time histogram, and the notes total. Exactly three+/// composed searches on the edges index plus one size-0 count on the nodes+/// index; every top-N tail is reported in `not_shown`.pub async fn overview(State(state): State<AppState>,Path(brain): Path<String>,@@ -1134,12 +1211,36 @@ pub async fn overview(.unwrap_or_default();let nodes_index = resolve_nodes_index(&state, &brain, &index).await;++ // 4. Notes total: one size-0 count on the nodes index. A brain whose+ // nodes index was never created (edges asserted through the API alone)+ // truthfully has 0 stored notes — reported as such, not a 404 and never+ // fabricated from edge endpoints.+ let nodes_total = if index_exists(&state, &nodes_index) {+ let count_body = EsSearchBody {+ query: Some(json!({ "match_all": {} })),+ size: 0,+ track_total_hits: Some(json!(true)),+ ..Default::default()+ };+ match overview_search(&state, &nodes_index, count_body).await {+ Ok(v) => v+ .pointer("/hits/total/value")+ .and_then(Value::as_u64)+ .unwrap_or(0),+ Err(r) => return r,+ }+ } else {+ 0+ };+Json(json!({"brain": brain,"contract": GRAPH_CONTRACT,"exists": true,"as_of": as_of,"nodes_index": nodes_index,+ "nodes": { "total": nodes_total },"embedder": embedder_id(&state),"edges": {"total": total,@@ -1393,10 +1494,36 @@ mod tests {);got["not_shown"]["memtable_docs_scanned"] = json!(0);+ // §8.5 is normative INCLUDING top-level key order: `node` sits between+ // `contract` and `seeds` on the wire (Value equality alone can't see+ // an order regression).+ let keys: Vec<&str> = got+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect();+ assert_eq!(+ keys,+ [+ "brain",+ "contract",+ "node",+ "seeds",+ "as_of",+ "hops",+ "direction",+ "edges",+ "neighbors",+ "not_shown"+ ]+ );+let expected = json!({"brain": "notes","contract": "xerj-second-brain/1","node": "note-alpha",+ "seeds": ["note-alpha"],"as_of": 1753700000000i64,"hops": 1,"direction": "both",@@ -1579,6 +1706,8 @@ mod tests {assert_eq!(b["exists"], json!(true));assert_eq!(b["nodes_index"], json!(".xerj-memory-notes"));assert_eq!(b["embedder"], json!("lexical-feature-hash"));+ // No nodes index exists for this brain yet → 0 stored notes, honestly.+ assert_eq!(b["nodes"], json!({ "total": 0 }));assert_eq!(b["edges"],json!({ "total": 8, "live": 8, "invalidated": 0 })@@ -1659,4 +1788,222 @@ mod tests {json!({ "brain": "nope", "contract": GRAPH_CONTRACT, "exists": false }));}++ /// The wire-level contract for multi-seed: `?nodes=a,b` arrives through+ /// the real axum `Query` extractor as ONE comma-separated string (the+ /// urlencoded parser does not split on commas) — this pins that.+ #[test]+ fn ego_params_parse_from_a_real_query_string() {+ let uri: axum::http::Uri =+ "/_graph/notes/ego?nodes=note-beta,note-epsilon&hops=2&as_of=1753700000000"+ .parse()+ .unwrap();+ let Query(p) = Query::<EgoParams>::try_from_uri(&uri).unwrap();+ assert_eq!(p.nodes.as_deref(), Some("note-beta,note-epsilon"));+ assert_eq!(p.node, None);+ assert_eq!(p.hops, Some(2));+ assert_eq!(p.as_of.as_deref(), Some("1753700000000"));+ }++ /// Multi-seed ego (`nodes=`): the union of the seed neighborhoods in the+ /// §3.2 stable order, directions relative to the seed SET, neighbors+ /// excluding every seed, `seeds` echoed, `node` absent (>1 seed).+ #[tokio::test]+ async fn ego_multi_seed_unions_neighborhoods() {+ let state = test_state();+ link_fixture(&state).await;++ let p = EgoParams {+ nodes: Some("note-beta,note-epsilon".into()),+ as_of: Some(AS_OF.to_string()),+ ..Default::default()+ };+ let (s, b) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::OK, "{b}");+ assert_eq!(b["seeds"], json!(["note-beta", "note-epsilon"]));+ assert!(+ b.get("node").is_none(),+ "multi-seed response must not carry a single `node`: {b}"+ );++ // beta touches fixture edges 0/2/4/5; epsilon touches 6/7 — six edges+ // in (hop asc, weight desc, edge_id asc) order, direction "out" iff+ // the edge's src is one of the seeds.+ let got: Vec<(&str, &str)> = b["edges"]+ .as_array()+ .unwrap()+ .iter()+ .map(|e| {+ (+ e["edge_id"].as_str().unwrap(),+ e["direction"].as_str().unwrap(),+ )+ })+ .collect();+ assert_eq!(+ got,+ vec![+ (FIXTURE_IDS[2], "out"), // beta → gamma (wikilink)+ (FIXTURE_IDS[0], "in"), // alpha → beta (wikilink)+ (FIXTURE_IDS[6], "in"), // delta → epsilon (same_dir)+ (FIXTURE_IDS[4], "in"), // alpha → beta (same_dir)+ (FIXTURE_IDS[7], "out"), // epsilon → gamma (same_dir)+ (FIXTURE_IDS[5], "out"), // beta → delta (same_dir)+ ]+ );+ let neighbor_ids: Vec<&str> = b["neighbors"]+ .as_array()+ .unwrap()+ .iter()+ .map(|n| n["id"].as_str().unwrap())+ .collect();+ assert_eq!(neighbor_ids, vec!["note-gamma", "note-alpha", "note-delta"]);+ assert_eq!(b["not_shown"]["frontier_clipped"], json!(0));++ // node+nodes together → 400 (mutually exclusive).+ let p = EgoParams {+ node: Some("note-alpha".into()),+ nodes: Some("note-beta".into()),+ as_of: Some(AS_OF.to_string()),+ ..Default::default()+ };+ let (s, b) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ assert!(b["error"]["reason"]+ .as_str()+ .unwrap()+ .contains("mutually exclusive"));++ // An all-empty seed list → the same 400 as a missing `node`.+ let p = EgoParams {+ nodes: Some(", ,".into()),+ ..Default::default()+ };+ let (s, _) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);++ // A 1-element `nodes` IS the `node` case: `node` stays on the shape.+ let p = EgoParams {+ nodes: Some("note-alpha".into()),+ as_of: Some(AS_OF.to_string()),+ ..Default::default()+ };+ let (s, b) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(b["node"], json!("note-alpha"));+ assert_eq!(b["seeds"], json!(["note-alpha"]));+ }++ /// A seed list beyond EGO_SEEDS_CAP is clipped — never silently — into+ /// the same `frontier_clipped` counter the engine uses; duplicates dedupe+ /// before the cap so they cost nothing.+ #[tokio::test]+ async fn ego_seed_cap_is_counted() {+ let state = test_state();+ link_fixture(&state).await;++ // 70 distinct seeds (note-alpha first + 69 unknowns) → 64 kept, 6+ // clipped; input order preserved so note-alpha survives the clamp.+ let mut ids: Vec<String> = vec!["note-alpha".into()];+ ids.extend((0..69).map(|i| format!("ghost-{i:02}")));+ let p = EgoParams {+ nodes: Some(ids.join(",")),+ as_of: Some(AS_OF.to_string()),+ ..Default::default()+ };+ let (s, b) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::OK, "{b}");+ assert_eq!(b["seeds"].as_array().unwrap().len(), 64);+ assert_eq!(b["seeds"][0], json!("note-alpha"));+ assert_eq!(b["not_shown"]["frontier_clipped"], json!(6));+ assert_eq!(b["edges"].as_array().unwrap().len(), 4);++ // 100 copies of one id are one seed — dedupe precedes the cap.+ let p = EgoParams {+ nodes: Some(vec!["note-alpha"; 100].join(",")),+ as_of: Some(AS_OF.to_string()),+ ..Default::default()+ };+ let (s, b) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(b["seeds"], json!(["note-alpha"]));+ assert_eq!(b["not_shown"]["frontier_clipped"], json!(0));+ }++ /// A2 + A3: `overview.nodes.total` counts stored notes once the nodes+ /// index exists (0, honestly, before that), and ego node hydration+ /// carries `path` from `ax_path` (null when the note has none).+ #[tokio::test]+ async fn overview_nodes_total_and_hydrated_path() {+ let state = test_state();+ link_fixture(&state).await;++ async fn put_node(state: &AppState, id: &str, doc: Value) {+ let resp = es_compat::index_doc(+ State(state.clone()),+ Path((".xerj-memory-notes".to_string(), id.to_string())),+ Query(IndexDocParams::default()),+ Json(doc),+ )+ .await+ .into_response();+ let (s, b) = drain_json(resp).await;+ assert!(s.is_success(), "storing node {id} failed: {b}");+ }+ async fn ov(state: &AppState) -> Value {+ let resp = overview(+ State(state.clone()),+ Path("notes".to_string()),+ Query(OverviewParams {+ as_of: Some(AS_OF.to_string()),+ ..Default::default()+ }),+ )+ .await;+ drain_json(resp).await.1+ }++ // Before any node doc exists: total 0 (no nodes index — not a 404).+ assert_eq!(ov(&state).await["nodes"], json!({ "total": 0 }));++ put_node(+ &state,+ "note-alpha",+ json!({+ "title": "Alpha", "text": "Alpha is the hub note.",+ "ax_path": "notes/alpha.md", "ax_format": "md"+ }),+ )+ .await;+ put_node(+ &state,+ "note-beta",+ json!({ "title": "Beta", "body": "Beta continues the thread." }),+ )+ .await;++ assert_eq!(ov(&state).await["nodes"], json!({ "total": 2 }));++ let mut p = ego_params("note-alpha", AS_OF);+ p.include_nodes = Some(true);+ let (s, b) = do_ego(&state, "notes", p).await;+ assert_eq!(s, StatusCode::OK, "{b}");+ assert_eq!(+ b["nodes"]["note-alpha"],+ json!({+ "title": "Alpha",+ "preview": "Alpha is the hub note.",+ "path": "notes/alpha.md",+ "index": ".xerj-memory-notes"+ })+ );+ // No ax_path on beta → null, never guessed.+ assert_eq!(b["nodes"]["note-beta"]["path"], json!(null));+ // gamma + delta still dangle — counted and listed.+ assert_eq!(b["not_shown"]["dangling_nodes"], json!(2));+ assert_eq!(+ b["not_shown"]["dangling_ids"],+ json!(["note-delta", "note-gamma"])+ );+ }}diff --git a/engine/crates/xerj-autoindex/src/detect/cratecite.rs b/engine/crates/xerj-autoindex/src/detect/cratecite.rsnew file mode 100644index 000000000..3b2a9ad11--- /dev/null+++ b/engine/crates/xerj-autoindex/src/detect/cratecite.rs@@ -0,0 +1,203 @@+//! cratecite@1 — a crate directory named in prose ("BM25 (xerj-fts)") links+//! to that crate's `Cargo.toml` file card.+//!+//! The cross-type bridge for doc/PDF → code: marketing papers and design docs+//! name crates, not file paths. The crate table is deterministic Phase-A+//! structure — every corpus directory that directly contains a `Cargo.toml`,+//! keyed by the DIRECTORY basename (contents are never read, so this is+//! honestly "the folder named xerj-fts", not the `[package] name`, and the+//! module says so). Weight 0.5 / confidence 0.6 — a name-drop in prose is+//! authored but the least targeted citation in the ladder.+//!+//! Only crate names containing `-` or `_` are citable: a crate directory+//! named `server` would otherwise turn every English use of the word into an+//! edge. On multi-word names ("xerj-fts") a whole-word match is a real+//! reference with near-zero false-positive surface. Word boundaries exclude+//! `[A-Za-z0-9_\-./]` so `xerj-fts-extra` and path contexts+//! (`crates/xerj-fts/src/…`) do NOT match — path mentions are pathcite's job.+//! Underscore spellings (`xerj_fts`) are NOT matched — that is the import+//! name, not the directory name, and guessing the equivalence would be a+//! resolution rule this detector cannot verify.++use super::{line_at, DetectorCounters, EdgeDetector, EdgeDraft, SectionCtx};+use std::sync::atomic::{AtomicU64, Ordering};++pub const TAG: &str = "cratecite@1";+pub const EDGE_TYPE: &str = "cratecite";+pub const WEIGHT: f32 = 0.5;+pub const CONFIDENCE: f32 = 0.6;++#[derive(Default)]+pub struct Cratecite {+ ambiguous: AtomicU64,+}++fn is_word(c: char) -> bool {+ c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/')+}++/// Right-side boundary: a following `.` only breaks the match when it starts+/// an extension-like continuation ("xerj-fts.txt") — a sentence-final period+/// ("…feeds xerj-fts.") is ordinary prose and must not suppress the citation.+fn boundary_after(rest: &str) -> bool {+ let mut it = rest.chars();+ match it.next() {+ None => true,+ Some('.') => !it+ .next()+ .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'),+ Some(c) => !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '/')),+ }+}++fn citable(name: &str) -> bool {+ name.contains('-') || name.contains('_')+}++impl EdgeDetector for Cratecite {+ fn tag(&self) -> &'static str {+ TAG+ }++ fn detect_text(&self, ctx: &SectionCtx<'_>, out: &mut Vec<EdgeDraft>) {+ for (name, rels) in &ctx.corpus.crate_dirs {+ if !citable(name) {+ continue;+ }+ let mut from = 0usize;+ while let Some(found) = ctx.text[from..].find(name.as_str()) {+ let pos = from + found;+ from = pos + name.len();+ let before_ok = ctx.text[..pos]+ .chars()+ .next_back()+ .is_none_or(|c| !is_word(c));+ let after_ok = boundary_after(&ctx.text[pos + name.len()..]);+ if !before_ok || !after_ok {+ continue;+ }+ // rels is sorted: the first IS the smallest; >1 dirs sharing a+ // basename is counted, never silently guessed.+ if rels.len() > 1 {+ self.ambiguous.fetch_add(1, Ordering::Relaxed);+ }+ let target = &ctx.corpus.files[&rels[0]];+ if target.rel == ctx.file.rel {+ continue;+ }+ out.push(EdgeDraft {+ src: ctx.section_doc_id.to_string(),+ dst: target.anchor_doc_id.clone(),+ edge_type: EDGE_TYPE,+ weight: WEIGHT,+ confidence: CONFIDENCE,+ valid_at_ms: ctx.file.mtime_ms,+ src_file: ctx.file.rel.clone(),+ quote: line_at(ctx.text, pos),+ offset: pos as u64,+ src_format: ctx.file.format.clone(),+ dst_format: target.format.clone(),+ });+ }+ }+ }++ fn counters(&self) -> DetectorCounters {+ DetectorCounters {+ unresolved: 0,+ ambiguous: self.ambiguous.load(Ordering::Relaxed),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::super::{corpus_file, CorpusIndex, SectionCtx};+ use super::*;++ fn corpus() -> CorpusIndex {+ CorpusIndex::build(vec![+ corpus_file("gtm/brief.pdf", "k0", "d", "pdf", 10),+ corpus_file(+ "engine/crates/xerj-fts/Cargo.toml",+ "k1",+ "d",+ "txt-lines",+ 10,+ ),+ corpus_file(+ "engine/crates/xerj-engine/Cargo.toml",+ "k2",+ "d",+ "txt-lines",+ 10,+ ),+ corpus_file("engine/Cargo.toml", "k3", "d", "txt-lines", 10),+ ])+ }++ fn run(corpus: &CorpusIndex, text: &str) -> (Vec<EdgeDraft>, DetectorCounters) {+ let det = Cratecite::default();+ let ctx = SectionCtx {+ corpus,+ file: &corpus.files["gtm/brief.pdf"],+ section_label: "page 1 section 0",+ prev_section: None,+ section_doc_id: "sec0",+ text,+ };+ let mut out = Vec::new();+ det.detect_text(&ctx, &mut out);+ (out, det.counters())+ }++ #[test]+ fn prose_mention_links_the_crates_cargo_toml_card() {+ let corpus = corpus();+ let (out, c) = run(+ &corpus,+ "Ranking is classic BM25 (xerj-fts) under the hood.",+ );+ assert_eq!(out.len(), 1);+ assert_eq!(+ out[0].dst,+ corpus.files["engine/crates/xerj-fts/Cargo.toml"].anchor_doc_id+ );+ assert_eq!(+ out[0].quote,+ "Ranking is classic BM25 (xerj-fts) under the hood."+ );+ assert_eq!(out[0].offset, 25);+ assert_eq!(out[0].src_format, "pdf");+ assert_eq!(out[0].dst_format, "toml");+ assert_eq!(c.ambiguous, 0);+ }++ #[test]+ fn word_boundaries_exclude_longer_names_and_path_contexts() {+ let corpus = corpus();+ let (out, _) = run(+ &corpus,+ "xerj-fts-extra is not it; engine/crates/xerj-fts/src/lib.rs is a path; xerj-fts wins",+ );+ assert_eq!(out.len(), 1, "only the standalone whole-word mention");+ assert_eq!(out[0].offset, 71);+ }++ #[test]+ fn single_word_crate_dirs_are_not_citable() {+ // "engine" contains Cargo.toml but is a dictionary word — matching it+ // in prose would fabricate edges out of ordinary English.+ let corpus = corpus();+ let (out, _) = run(&corpus, "the engine restarts nightly");+ assert!(out.is_empty());+ assert!(corpus.crate_dirs.contains_key("engine"));+ }++ #[test]+ fn multiple_mentions_each_emit() {+ let corpus = corpus();+ let (out, _) = run(&corpus, "xerj-fts feeds xerj-engine.\nxerj-fts again.");+ assert_eq!(out.len(), 3);+ }+}diff --git a/engine/crates/xerj-autoindex/src/detect/e2e.rs b/engine/crates/xerj-autoindex/src/detect/e2e.rsindex dac17f39c..159293b80 100644--- a/engine/crates/xerj-autoindex/src/detect/e2e.rs+++ b/engine/crates/xerj-autoindex/src/detect/e2e.rs@@ -62,16 +62,18 @@ impl MockEs {.unwrap_or_default()}- /// rel path → anchor node `_id`, straight from the published node docs so- /// the expectation uses exactly the ids the pipeline derived.- fn anchors(&self) -> HashMap<String, String> {+ /// rel path → node `_id` for one locator, straight from the published+ /// node docs so expectations use exactly the ids the pipeline derived.+ /// `"file"` = the per-file card (anchor of every file-level edge);+ /// `"s0"` = the first text section.+ fn nodes_at(&self, locator: &str) -> HashMap<String, String> {let mut out = HashMap::new();for (index, docs) in self.docs.lock().unwrap().iter() {if index.starts_with('.') {continue; // catalog + edges indices are not node datasets}for (id, source) in docs {- if source.get("ax_locator").and_then(Value::as_str) == Some("s0") {+ if source.get("ax_locator").and_then(Value::as_str) == Some(locator) {if let Some(rel) = source.get("ax_path").and_then(Value::as_str) {out.insert(rel.to_string(), id.clone());}@@ -80,6 +82,10 @@ impl MockEs {}out}++ fn anchors(&self) -> HashMap<String, String> {+ self.nodes_at(detect::FILE_CARD_LOCATOR)+ }}impl Drop for MockEs {@@ -315,6 +321,8 @@ struct EdgeKey {src_file: String,quote: String,offset: u64,+ src_format: String,+ dst_format: String,}fn edge_keys(edges: &BTreeMap<String, Value>) -> Vec<EdgeKey> {@@ -344,6 +352,8 @@ fn edge_keys(edges: &BTreeMap<String, Value>) -> Vec<EdgeKey> {src_file: s["src_file"].as_str().unwrap().into(),quote: s["evidence"]["quote"].as_str().unwrap().into(),offset: s["evidence"]["offset"].as_u64().unwrap(),+ src_format: s["src_format"].as_str().unwrap_or("").into(),+ dst_format: s["dst_format"].as_str().unwrap_or("").into(),}}).collect();@@ -351,9 +361,13 @@ fn edge_keys(edges: &BTreeMap<String, Value>) -> Vec<EdgeKey> {out}+/// `src_map`/`dst_map` pick the endpoint node per edge semantics: authored+/// text edges (wikilink) START at the section holding the evidence and LAND on+/// the target's file card; structural samedir edges connect card to card.#[allow(clippy::too_many_arguments)]fn expect(- anchors: &HashMap<String, String>,+ src_map: &HashMap<String, String>,+ dst_map: &HashMap<String, String>,src_rel: &str,dst_rel: &str,edge_type: &str,@@ -364,8 +378,8 @@ fn expect(offset: u64,) -> EdgeKey {EdgeKey {- src: anchors[src_rel].clone(),- dst: anchors[dst_rel].clone(),+ src: src_map[src_rel].clone(),+ dst: dst_map[dst_rel].clone(),edge_type: edge_type.into(),detector: detector.into(),weight: weight.into(),@@ -373,6 +387,29 @@ fn expect(src_file: src_rel.into(),quote: quote.into(),offset,+ src_format: "md".into(),+ dst_format: "md".into(),+ }+}++/// The @2 opening edge of every text file's reading chain: card → section 0.+fn expect_opener(+ anchors: &HashMap<String, String>,+ sections: &HashMap<String, String>,+ rel: &str,+) -> EdgeKey {+ EdgeKey {+ src: anchors[rel].clone(),+ dst: sections[rel].clone(),+ edge_type: "sequence".into(),+ detector: "sequence@2".into(),+ weight: "0.8".into(),+ confidence: "0.99".into(),+ src_file: rel.into(),+ quote: format!("section 0 opens {rel}"),+ offset: 0,+ src_format: "md".into(),+ dst_format: "md".into(),}}@@ -389,7 +426,15 @@ fn fixture_folder_end_to_end_matches_the_contract_edge_set() {);let anchors = es.anchors();- assert_eq!(anchors.len(), 5, "five single-section note anchors");+ assert_eq!(anchors.len(), 5, "five file-card anchor nodes");+ let sections = es.nodes_at("s0");+ assert_eq!(sections.len(), 5, "five s0 section nodes");+ for rel in anchors.keys() {+ assert_ne!(+ anchors[rel], sections[rel],+ "card and first section are distinct nodes"+ );+ }let edges = es.index(EDGES_INDEX);assert!(edges.contains_key(detect::BRAIN_META_ID),@@ -404,44 +449,48 @@ fn fixture_folder_end_to_end_matches_the_contract_edge_set() {let mut expected = vec![// §8.2/§8.3 wikilink edges — exact quotes and byte offsets.expect(+ §ions,&anchors,"alpha.md","beta.md","wikilink",- "wikilink@1",+ "wikilink@2","1.0","0.95",alpha_line,35,),expect(+ §ions,&anchors,"alpha.md","gamma.md","wikilink",- "wikilink@1",+ "wikilink@2","1.0","0.95",alpha_line,48,),expect(+ §ions,&anchors,"beta.md","gamma.md","wikilink",- "wikilink@1",+ "wikilink@2","1.0","0.95","Beta continues the thread and references [[gamma]].",41,),expect(+ §ions,&anchors,"delta.md","alpha.md","wikilink",- "wikilink@1",+ "wikilink@2","1.0","0.95","Delta cites [[alpha]] as its source.",@@ -449,57 +498,69 @@ fn fixture_folder_end_to_end_matches_the_contract_edge_set() {),// §8.3 samedir chain over rel-sorted files — 4 edges, not a clique.expect(+ &anchors,&anchors,"alpha.md","beta.md","same_dir",- "samedir@1",+ "samedir@2","0.3","0.4","alpha.md and beta.md share directory .",0,),expect(+ &anchors,&anchors,"beta.md","delta.md","same_dir",- "samedir@1",+ "samedir@2","0.3","0.4","beta.md and delta.md share directory .",0,),expect(+ &anchors,&anchors,"delta.md","epsilon.md","same_dir",- "samedir@1",+ "samedir@2","0.3","0.4","delta.md and epsilon.md share directory .",0,),expect(+ &anchors,&anchors,"epsilon.md","gamma.md","same_dir",- "samedir@1",+ "samedir@2","0.3","0.4","epsilon.md and gamma.md share directory .",0,),+ // sequence@2 opening edges: every file's card starts its reading+ // chain (single-section notes have exactly the opener).+ expect_opener(&anchors, §ions, "alpha.md"),+ expect_opener(&anchors, §ions, "beta.md"),+ expect_opener(&anchors, §ions, "delta.md"),+ expect_opener(&anchors, §ions, "epsilon.md"),+ expect_opener(&anchors, §ions, "gamma.md"),];expected.sort();assert_eq!(edge_keys(&edges), expected, "the exact §8.3 edge set");let g = journal_graph_summary(state.path());- assert_eq!(g["edges_written"], json!(8));- assert_eq!(g["by_detector"]["wikilink@1"], json!(4));- assert_eq!(g["by_detector"]["samedir@1"], json!(4));+ assert_eq!(g["edges_written"], json!(13));+ assert_eq!(g["by_detector"]["wikilink@2"], json!(4));+ assert_eq!(g["by_detector"]["samedir@2"], json!(4));+ assert_eq!(g["by_detector"]["sequence@2"], json!(5));assert_eq!(g["edges_unresolved"], json!(0));assert_eq!(g["edges_ambiguous"], json!(0));assert_eq!(g["edges_self_dropped"], json!(0));@@ -550,20 +611,26 @@ fn dangling_wikilink_is_counted_not_silently_dropped() {let edges = es.index(EDGES_INDEX);let keys = edge_keys(&edges);- let types: Vec<(&str, &str)> = keys- .iter()- .map(|k| (k.edge_type.as_str(), k.detector.as_str()))- .collect();- // One resolved wikilink + one samedir chain edge; [[nowhere]] must not- // fabricate an edge…+ let mut by_type: BTreeMap<(&str, &str), u64> = BTreeMap::new();+ for k in &keys {+ *by_type+ .entry((k.edge_type.as_str(), k.detector.as_str()))+ .or_default() += 1;+ }+ // One resolved wikilink + one samedir chain edge + two sequence openers+ // (card → s0, one per file); [[nowhere]] must not fabricate an edge…assert_eq!(- types,- vec![("same_dir", "samedir@1"), ("wikilink", "wikilink@1")]+ by_type,+ BTreeMap::from([+ (("same_dir", "samedir@2"), 1),+ (("sequence", "sequence@2"), 2),+ (("wikilink", "wikilink@2"), 1),+ ]));// …but it must not vanish either: it is a dangling-link fact of record.let g = journal_graph_summary(state.path());assert_eq!(g["edges_unresolved"], json!(1));- assert_eq!(g["edges_written"], json!(2));+ assert_eq!(g["edges_written"], json!(4));}#[test]diff --git a/engine/crates/xerj-autoindex/src/detect/href.rs b/engine/crates/xerj-autoindex/src/detect/href.rsindex ef9a44026..7214aeeab 100644--- a/engine/crates/xerj-autoindex/src/detect/href.rs+++ b/engine/crates/xerj-autoindex/src/detect/href.rs@@ -1,9 +1,13 @@-//! href@1 — `<a href="…">` to a corpus file, html-extracted files only.+//! href@2 — `<a href="…">` to a corpus file, html-extracted files only.//!//! Weight 0.7: an HTML anchor is authored intent, but exported HTML (wikis,//! doc generators) also mass-produces navigation links, so one anchor says//! less than one hand-written markdown link.//!+//! @2: dst moved from the target's `s0` section to its file-card node (the+//! raw pass's SRC is the file card too) and edges carry+//! `src_format`/`dst_format`.+//!//! ## Why there is a raw-source pass//! The HTML extractor strips markup before sectioning — an `<a>` tag never//! survives into section text, so `detect_text` alone would make this@@ -22,7 +26,7 @@ use super::{use std::sync::atomic::{AtomicU64, Ordering};use std::sync::OnceLock;-pub const TAG: &str = "href@1";+pub const TAG: &str = "href@2";pub const EDGE_TYPE: &str = "href";pub const WEIGHT: f32 = 0.7;pub const CONFIDENCE: f32 = 0.85;@@ -73,6 +77,8 @@ fn draft(src_file: file.rel.clone(),quote,offset,+ src_format: file.format.clone(),+ dst_format: target.format.clone(),}}@@ -194,7 +200,8 @@ mod tests {let ctx = SectionCtx {corpus: &corpus,file: &corpus.files["notes.md"],- section_ordinal: 0,+ section_label: "section 0",+ prev_section: None,section_doc_id: "sec0",text: "<a href=\"site/about.html\">x</a>",};@@ -211,7 +218,8 @@ mod tests {let ctx = SectionCtx {corpus: &corpus,file: &corpus.files["site/index.html"],- section_ordinal: 0,+ section_label: "section 0",+ prev_section: None,section_doc_id: "sec0",text,};diff --git a/engine/crates/xerj-autoindex/src/detect/mdlink.rs b/engine/crates/xerj-autoindex/src/detect/mdlink.rsindex c8a524769..830c2803d 100644--- a/engine/crates/xerj-autoindex/src/detect/mdlink.rs+++ b/engine/crates/xerj-autoindex/src/detect/mdlink.rs@@ -1,16 +1,19 @@-//! mdlink@1 — `[text](relative/path.md)` where the target is a corpus file.+//! mdlink@2 — `[text](relative/path.md)` where the target is a corpus file.//!//! Slightly below wikilink (weight 0.9): an inline markdown link is still an//! explicit authorial act, but it is also how people cite external material,//! so a resolved local target carries marginally less "these notes belong//! together" intent than a `[[wiki link]]`.+//!+//! @2: dst moved from the target's `s0` section to its file-card node and+//! edges carry `src_format`/`dst_format`.use super::{line_at, resolve_local, DetectorCounters, EdgeDetector, EdgeDraft, LinkTarget, SectionCtx,};use std::sync::atomic::{AtomicU64, Ordering};-pub const TAG: &str = "mdlink@1";+pub const TAG: &str = "mdlink@2";pub const EDGE_TYPE: &str = "mdlink";pub const WEIGHT: f32 = 0.9;pub const CONFIDENCE: f32 = 0.9;@@ -71,6 +74,8 @@ impl EdgeDetector for Mdlink {src_file: ctx.file.rel.clone(),quote: line_at(ctx.text, open),offset: open as u64,+ src_format: ctx.file.format.clone(),+ dst_format: target.format.clone(),}),// External links are what markdown links are FOR — skipping// them silently is correct, only local misses are dangling.@@ -108,7 +113,8 @@ mod tests {let ctx = SectionCtx {corpus,file,- section_ordinal: 0,+ section_label: "section 0",+ prev_section: None,section_doc_id: "sec0",text,};diff --git a/engine/crates/xerj-autoindex/src/detect/mod.rs b/engine/crates/xerj-autoindex/src/detect/mod.rsindex 79fc9f87d..a0437ecf1 100644--- a/engine/crates/xerj-autoindex/src/detect/mod.rs+++ b/engine/crates/xerj-autoindex/src/detect/mod.rs@@ -16,8 +16,10 @@//! WAL → memtable → segment path and are soft-invalidated (never deleted) so//! "what did it believe last Tuesday" stays answerable.+pub mod cratecite;pub mod href;pub mod mdlink;+pub mod pathcite;pub mod samedir;pub mod sequence;pub mod wikilink;@@ -113,6 +115,8 @@ pub fn edge_index_mapping() -> Value {"confidence": { "type": "float" },"schema_version": { "type": "integer" },"src_file": { "type": "keyword" },+ "src_format": { "type": "keyword" },+ "dst_format": { "type": "keyword" },"evidence": {"properties": {"quote": { "type": "text" },@@ -135,6 +139,16 @@ pub struct CorpusIndex {/// lowercase file-stem → rel paths bearing it (wikilink resolution;/// BTreeMap + sorted values so ambiguity resolution is deterministic).pub by_stem: BTreeMap<String, Vec<String>>,+ /// exact file NAME (final path segment, case-sensitive) → rel paths+ /// bearing it. pathcite's suffix resolution: a token's last segment keys+ /// this table, then candidates are filtered by full-suffix match — O(log n)+ /// instead of scanning every rel per token.+ pub by_name: BTreeMap<String, Vec<String>>,+ /// crate-directory basename → rels of the `Cargo.toml` files directly+ /// inside a directory of that name (cratecite's Phase-A crate table). Keyed+ /// by DIRECTORY name, not `[package] name` — CorpusIndex never reads file+ /// contents, and saying otherwise would overclaim.+ pub crate_dirs: BTreeMap<String, Vec<String>>,}pub struct CorpusFile {@@ -142,16 +156,27 @@ pub struct CorpusFile {/// `ids::file_key` output.pub file_key: String,pub dataset_slug: String,- /// `ids::doc_id(dataset_slug, file_key, "s0")` — the file's anchor node.+ /// `ids::doc_id(dataset_slug, file_key, "file")` — the file's CARD node.+ /// Every file-level edge terminates here. Historically this was the `s0`+ /// section doc id, which does not exist for row/line/page-locator families+ /// (CSV, JSONL, PDF…) — incoming links then pointed at a ghost. The card+ /// is a real emitted node for EVERY indexed file (lib.rs stages it before+ /// the file's records), so anchors are always hydratable and focusable.pub anchor_doc_id: String,pub mtime_ms: i64,/// Parent dir rel path, "" for root.pub dir: String,/// Sniffed format family (`Family::as_str`), from the frozen plan — NOT- /// guessed from the extension. href@1 gates on this: the contract scopes+ /// guessed from the extension. href@2 gates on this: the contract scopes/// anchor detection to html-extracted files, and an `.html` extension is/// not proof of that (sniffing decides the family).pub family: String,+ /// File-type label stamped into edges as `src_format`/`dst_format`:+ /// lowercase extension when the name has one ("md", "rs", "pdf"), else the+ /// sniffed family. Extension-level truth is what makes the dashboard's+ /// cross-type counts (md→rs, md→pdf) sayable at all — two txt-prose+ /// families would hide exactly the crossings the map exists to show.+ pub format: String,}/// Build one [`CorpusFile`], deriving the anchor node id and parent dir from@@ -168,13 +193,38 @@ pub fn corpus_file(rel: rel.to_string(),file_key: file_key.to_string(),dataset_slug: dataset_slug.to_string(),- anchor_doc_id: crate::ids::doc_id(dataset_slug, file_key, "s0"),+ anchor_doc_id: crate::ids::doc_id(dataset_slug, file_key, FILE_CARD_LOCATOR),mtime_ms,dir: rel.rsplit_once('/').map(|(d, _)| d.to_string()).unwrap_or_default(),family: family.to_string(),+ format: format_of(rel, family),+ }+}++/// Locator of the per-file card node. Cannot collide with content locators —+/// every extractor's locators are letter+digit shaped (`s3`, `p2-s0`, `b1024`,+/// `row7`, table/row pairs), never the bare word `file`.+pub const FILE_CARD_LOCATOR: &str = "file";++/// Lowercase extension of the final path segment, falling back to the sniffed+/// family for extension-less names and dotfiles. Extensions longer than 12+/// chars or with non-alphanumerics are treated as not-an-extension (version+/// suffixes, minified-name noise).+pub(crate) fn format_of(rel: &str, family: &str) -> String {+ let name = rel.rsplit('/').next().unwrap_or(rel);+ match name.rsplit_once('.') {+ Some((stem, ext))+ if !stem.is_empty()+ && !ext.is_empty()+ && ext.len() <= 12+ && ext.bytes().all(|b| b.is_ascii_alphanumeric()) =>+ {+ ext.to_ascii_lowercase()+ }+ _ => family.to_string(),}}@@ -182,20 +232,46 @@ impl CorpusIndex {pub fn build(files: Vec<CorpusFile>) -> Self {let mut map: BTreeMap<String, CorpusFile> = BTreeMap::new();let mut by_stem: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut by_name: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut crate_dirs: BTreeMap<String, Vec<String>> = BTreeMap::new();for f in files {by_stem.entry(stem_of(&f.rel).to_ascii_lowercase()).or_default().push(f.rel.clone());+ let name = f.rel.rsplit('/').next().unwrap_or(&f.rel);+ by_name+ .entry(name.to_string())+ .or_default()+ .push(f.rel.clone());+ if let Some(dir) = f.rel.strip_suffix("/Cargo.toml") {+ let dir_name = dir.rsplit('/').next().unwrap_or(dir);+ if !dir_name.is_empty() {+ crate_dirs+ .entry(dir_name.to_string())+ .or_default()+ .push(f.rel.clone());+ }+ }map.insert(f.rel.clone(), f);}for rels in by_stem.values_mut() {rels.sort();rels.dedup();}+ for rels in by_name.values_mut() {+ rels.sort();+ rels.dedup();+ }+ for rels in crate_dirs.values_mut() {+ rels.sort();+ rels.dedup();+ }CorpusIndex {files: map,by_stem,+ by_name,+ crate_dirs,}}}@@ -248,6 +324,11 @@ pub struct EdgeDraft {pub quote: String,/// evidence.offset (byte offset in section text; 0 for structural).pub offset: u64,+ /// File-type labels of the two endpoints (`CorpusFile.format`), stored as+ /// `src_format`/`dst_format`. Empty string = unknown → key omitted from+ /// the stored doc (same omission discipline as `invalid_at`).+ pub src_format: String,+ pub dst_format: String,}/// Per-section textual context. `text` is the exact section string that became@@ -255,7 +336,16 @@ pub struct EdgeDraft {pub struct SectionCtx<'a> {pub corpus: &'a CorpusIndex,pub file: &'a CorpusFile,- pub section_ordinal: u32,+ /// Human label of this section within its file, derived from the locator+ /// by `lib.rs::section_label`: "section 3" for `s3`, "page 2 section 0"+ /// for `p2-s0`. Used verbatim in sequence evidence rationales.+ pub section_label: &'a str,+ /// (doc id, label) of the previously staged section of the SAME file;+ /// None for the file's first section. Tracked by the pipeline in stream+ /// order — the only way to know a page boundary's predecessor (`p2-s0`'s+ /// predecessor is the LAST section of page 1, which the locator alone+ /// cannot name).+ pub prev_section: Option<(&'a str, &'a str)>,pub section_doc_id: &'a str,pub text: &'a str,}@@ -295,6 +385,8 @@ pub fn default_detectors() -> Vec<Box<dyn EdgeDetector>> {Box::new(wikilink::Wikilink::default()),Box::new(mdlink::Mdlink::default()),Box::new(href::Href::default()),+ Box::new(pathcite::Pathcite::default()),+ Box::new(cratecite::Cratecite::default()),Box::new(sequence::Sequence),Box::new(samedir::SameDir),]@@ -308,6 +400,8 @@ pub fn detector_tag_for(edge_type: &str) -> &'static str {wikilink::EDGE_TYPE => wikilink::TAG,mdlink::EDGE_TYPE => mdlink::TAG,href::EDGE_TYPE => href::TAG,+ pathcite::EDGE_TYPE => pathcite::TAG,+ cratecite::EDGE_TYPE => cratecite::TAG,sequence::EDGE_TYPE => sequence::TAG,samedir::EDGE_TYPE => samedir::TAG,_ => "unknown@0",@@ -461,7 +555,7 @@ pub fn assemble(drafts: &[EdgeDraft], edges_index: &str, created_at_ms: i64) ->let id = edge_id(&d.src, d.edge_type, &d.dst, d.valid_at_ms);let tag = detector_tag_for(d.edge_type);let action = json!({"index": {"_index": edges_index, "_id": id}});- let doc = json!({+ let mut doc = json!({"edge_id": id,"src": d.src,"dst": d.dst,@@ -479,6 +573,17 @@ pub fn assemble(drafts: &[EdgeDraft], edges_index: &str, created_at_ms: i64) ->"offset": d.offset,}});+ // Endpoint file-type labels: omitted (not null) when unknown, same+ // discipline as invalid_at — the API stream's hand-asserted edges+ // carry neither, and that absence must stay a null_bitmap fact.+ if let Some(obj) = doc.as_object_mut() {+ if !d.src_format.is_empty() {+ obj.insert("src_format".into(), json!(d.src_format));+ }+ if !d.dst_format.is_empty() {+ obj.insert("dst_format".into(), json!(d.dst_format));+ }+ }let mut ndjson = action.to_string().into_bytes();ndjson.push(b'\n');ndjson.extend_from_slice(doc.to_string().as_bytes());@@ -648,6 +753,8 @@ mod tests {src_file: "a.md".into(),quote: "self".into(),offset: 0,+ src_format: "md".into(),+ dst_format: "md".into(),},EdgeDraft {src: "n1".into(),@@ -659,6 +766,8 @@ mod tests {src_file: "a.md".into(),quote: "a.md and b.md share directory .".into(),offset: 0,+ src_format: "md".into(),+ dst_format: "md".into(),},];let out = assemble(&drafts, ".xerj-memory-t-edges", 99);@@ -680,9 +789,92 @@ mod tests {doc.get("invalid_at").is_none(),"unset keys must be omitted");+ assert_eq!(doc["src_format"], json!("md"));+ assert_eq!(doc["dst_format"], json!("md"));assert_eq!(doc["edge_id"], json!(out.edges[0].edge_id));}+ #[test]+ fn unknown_endpoint_formats_are_omitted_not_null() {+ let draft = EdgeDraft {+ src: "n1".into(),+ dst: "n2".into(),+ edge_type: wikilink::EDGE_TYPE,+ weight: 1.0,+ confidence: 0.95,+ valid_at_ms: 5,+ src_file: "a.md".into(),+ quote: "q".into(),+ offset: 0,+ src_format: String::new(),+ dst_format: String::new(),+ };+ let out = assemble(std::slice::from_ref(&draft), "i", 7);+ let lines: Vec<&str> = std::str::from_utf8(&out.edges[0].ndjson)+ .unwrap()+ .lines()+ .collect();+ let doc: Value = serde_json::from_str(lines[1]).unwrap();+ assert!(doc.get("src_format").is_none());+ assert!(doc.get("dst_format").is_none());+ }++ #[test]+ fn format_labels_prefer_extension_and_fall_back_to_family() {+ assert_eq!(format_of("docs/a.md", "txt-prose"), "md");+ assert_eq!(format_of("src/lib.rs", "txt-lines"), "rs");+ assert_eq!(format_of("gtm/brief.PDF", "pdf"), "pdf");+ assert_eq!(format_of("Makefile", "txt-lines"), "txt-lines");+ assert_eq!(format_of(".env", "txt-lines"), "txt-lines");+ assert_eq!(+ format_of("x.tar.reallylongextension", "binary"),+ "binary",+ "over-long extensions are not extensions"+ );+ }++ #[test]+ fn corpus_index_builds_name_and_crate_tables() {+ let corpus = CorpusIndex::build(vec![+ corpus_file(+ "engine/crates/xerj-fts/Cargo.toml",+ "k1",+ "d",+ "txt-lines",+ 1,+ ),+ corpus_file(+ "engine/crates/xerj-fts/src/lib.rs",+ "k2",+ "d",+ "txt-lines",+ 1,+ ),+ corpus_file(+ "engine/crates/xerj-api/src/lib.rs",+ "k3",+ "d",+ "txt-lines",+ 1,+ ),+ corpus_file("Cargo.toml", "k4", "d", "txt-lines", 1),+ ]);+ assert_eq!(+ corpus.by_name["lib.rs"],+ vec![+ "engine/crates/xerj-api/src/lib.rs",+ "engine/crates/xerj-fts/src/lib.rs"+ ]+ );+ // Crate table keys on the containing directory's basename; the root+ // Cargo.toml has no containing directory name and must not register.+ assert_eq!(+ corpus.crate_dirs.get("xerj-fts"),+ Some(&vec!["engine/crates/xerj-fts/Cargo.toml".to_string()])+ );+ assert_eq!(corpus.crate_dirs.len(), 1);+ }+#[test]fn assembly_is_deterministic_for_a_fixed_created_at() {let draft = EdgeDraft {@@ -695,6 +887,8 @@ mod tests {src_file: "a.md".into(),quote: "q".into(),offset: 3,+ src_format: "md".into(),+ dst_format: "md".into(),};let a = assemble(std::slice::from_ref(&draft), "i", 7);let b = assemble(std::slice::from_ref(&draft), "i", 7);diff --git a/engine/crates/xerj-autoindex/src/detect/pathcite.rs b/engine/crates/xerj-autoindex/src/detect/pathcite.rsnew file mode 100644index 000000000..f676cf833--- /dev/null+++ b/engine/crates/xerj-autoindex/src/detect/pathcite.rs@@ -0,0 +1,286 @@+//! pathcite@1 — a file path mentioned in prose ("see `src/index.rs:123`")+//! that resolves to a corpus file.+//!+//! Why it exists: on a real repository almost no doc→code citation is a+//! markdown link — authors write bare paths. Measured on this repository,+//! mdlink caught 2 of ~944 doc→code path mentions; pathcite is the detector+//! for the other 99.8%. Weight 0.6 / confidence 0.7 — an authored citation,+//! but resolved by string matching against the corpus tree, one rung less+//! deliberate than a link the author formatted as a link.+//!+//! ## Resolution (deterministic, never guessed)+//! Tokens are maximal `[A-Za-z0-9_./-]` runs ending in `.<alnum ext>`, with+//! any leading `/`, `./`, `../` stripped (a trailing `:line` never enters the+//! token — `:` is outside the class). Then:+//! 1. exact rel-path match wins outright;+//! 2. tokens with ≥ 2 path segments may match as a path SUFFIX+//! (`xerj-engine/src/index.rs` matches `engine/crates/xerj-engine/src/index.rs`);+//! several candidates → lexicographically smallest rel, counted ambiguous;+//! 3. bare one-segment names (`index.rs`) are NEVER suffix-matched — if any+//! corpus file bears the name, the mention is counted ambiguous, not+//! linked. A bare filename is too weakly targeted to assert a belief over.+//!+//! Multi-segment tokens that match nothing are counted unresolved (a dangling+//! path citation is a fact worth surfacing); bare tokens that match nothing+//! are ignored — dotted prose ("e.g", domains, version numbers) is not a+//! citation and would flood the honesty counters with non-facts.+//!+//! A file citing itself is skipped silently: "cites file" pointing at the+//! file it appears in tells a reader nothing.+//!+//! Known overlap: the target of a markdown link is also a path token, so a+//! `[guide](docs/guide.md)` line yields both an mdlink and a pathcite edge.+//! Parallel edges of different types are legal (spec §2.3) and each carries+//! its own honest detector attribution; deduplicating would hide that the+//! mdlink signal is the stronger one.++use super::{+ line_at, CorpusFile, CorpusIndex, DetectorCounters, EdgeDetector, EdgeDraft, SectionCtx,+};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::OnceLock;++pub const TAG: &str = "pathcite@1";+pub const EDGE_TYPE: &str = "pathcite";+pub const WEIGHT: f32 = 0.6;+pub const CONFIDENCE: f32 = 0.7;++#[derive(Default)]+pub struct Pathcite {+ unresolved: AtomicU64,+ ambiguous: AtomicU64,+}++fn token_re() -> &'static regex::Regex {+ static RE: OnceLock<regex::Regex> = OnceLock::new();+ RE.get_or_init(|| {+ regex::Regex::new(r"[A-Za-z0-9_./\-]+\.[A-Za-z0-9_]+").expect("static path-token regex")+ })+}++enum Resolved<'a> {+ Hit(&'a CorpusFile),+ Ambiguous(&'a CorpusFile),+ /// ≥2 segments, no corpus match — a dangling path citation, counted.+ Miss,+ /// One bare segment naming ≥1 corpus file — refused, counted ambiguous.+ BareRefused,+ /// Not recognizably a path citation at all — ignored, not counted.+ Noise,+}++fn resolve<'a>(corpus: &'a CorpusIndex, token: &str) -> Resolved<'a> {+ if let Some(f) = corpus.files.get(token) {+ return Resolved::Hit(f);+ }+ let segments = token.split('/').filter(|s| !s.is_empty()).count();+ let name = token.rsplit('/').next().unwrap_or(token);+ let candidates = corpus.by_name.get(name);+ if segments >= 2 {+ let suffix = format!("/{token}");+ let mut hits = candidates+ .into_iter()+ .flatten()+ .filter(|rel| rel.ends_with(&suffix));+ return match (hits.next(), hits.next()) {+ // Sorted vec ⇒ the first suffix hit IS the smallest rel.+ (Some(rel), None) => Resolved::Hit(&corpus.files[rel]),+ (Some(rel), Some(_)) => Resolved::Ambiguous(&corpus.files[rel]),+ (None, _) => Resolved::Miss,+ };+ }+ match candidates {+ Some(rels) if !rels.is_empty() => Resolved::BareRefused,+ _ => Resolved::Noise,+ }+}++impl EdgeDetector for Pathcite {+ fn tag(&self) -> &'static str {+ TAG+ }++ fn detect_text(&self, ctx: &SectionCtx<'_>, out: &mut Vec<EdgeDraft>) {+ for m in token_re().find_iter(ctx.text) {+ let mut token = m.as_str();+ loop {+ let trimmed = token+ .trim_start_matches('/')+ .trim_start_matches("./")+ .trim_start_matches("../");+ if trimmed.len() == token.len() {+ break;+ }+ token = trimmed;+ }+ if token.is_empty() {+ continue;+ }+ let offset = (m.start() + (m.as_str().len() - token.len())) as u64;+ let target = match resolve(ctx.corpus, token) {+ Resolved::Hit(f) => f,+ Resolved::Ambiguous(f) => {+ self.ambiguous.fetch_add(1, Ordering::Relaxed);+ f+ }+ Resolved::Miss => {+ self.unresolved.fetch_add(1, Ordering::Relaxed);+ continue;+ }+ Resolved::BareRefused => {+ self.ambiguous.fetch_add(1, Ordering::Relaxed);+ continue;+ }+ Resolved::Noise => continue,+ };+ if target.rel == ctx.file.rel {+ continue; // self-citation says nothing+ }+ out.push(EdgeDraft {+ src: ctx.section_doc_id.to_string(),+ dst: target.anchor_doc_id.clone(),+ edge_type: EDGE_TYPE,+ weight: WEIGHT,+ confidence: CONFIDENCE,+ valid_at_ms: ctx.file.mtime_ms,+ src_file: ctx.file.rel.clone(),+ quote: line_at(ctx.text, m.start()),+ offset,+ src_format: ctx.file.format.clone(),+ dst_format: target.format.clone(),+ });+ }+ }++ fn counters(&self) -> DetectorCounters {+ DetectorCounters {+ unresolved: self.unresolved.load(Ordering::Relaxed),+ ambiguous: self.ambiguous.load(Ordering::Relaxed),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::super::{corpus_file, CorpusIndex, SectionCtx};+ use super::*;++ fn corpus() -> CorpusIndex {+ CorpusIndex::build(vec![+ corpus_file("docs/notes.md", "k0", "d", "txt-prose", 10),+ corpus_file(+ "engine/crates/xerj-engine/src/index.rs",+ "k1",+ "d",+ "txt-lines",+ 10,+ ),+ corpus_file(+ "engine/crates/xerj-fts/src/index.rs",+ "k2",+ "d",+ "txt-lines",+ 10,+ ),+ corpus_file(+ "engine/crates/xerj-fts/src/lib.rs",+ "k3",+ "d",+ "txt-lines",+ 10,+ ),+ ])+ }++ fn run(corpus: &CorpusIndex, text: &str) -> (Vec<EdgeDraft>, DetectorCounters) {+ let det = Pathcite::default();+ let ctx = SectionCtx {+ corpus,+ file: &corpus.files["docs/notes.md"],+ section_label: "section 0",+ prev_section: None,+ section_doc_id: "sec0",+ text,+ };+ let mut out = Vec::new();+ det.detect_text(&ctx, &mut out);+ (out, det.counters())+ }++ #[test]+ fn exact_and_suffix_paths_resolve_with_line_stripped() {+ let corpus = corpus();+ let (out, c) = run(+ &corpus,+ "See engine/crates/xerj-fts/src/lib.rs:42 and xerj-engine/src/index.rs for details.",+ );+ assert_eq!(out.len(), 2);+ assert_eq!(+ out[0].dst,+ corpus.files["engine/crates/xerj-fts/src/lib.rs"].anchor_doc_id+ );+ assert_eq!(out[0].offset, 4);+ assert_eq!(+ out[1].dst, corpus.files["engine/crates/xerj-engine/src/index.rs"].anchor_doc_id,+ "multi-segment suffix match"+ );+ assert_eq!(out[0].src_format, "md");+ assert_eq!(out[0].dst_format, "rs");+ assert_eq!(c.unresolved, 0);+ assert_eq!(c.ambiguous, 0);+ }++ #[test]+ fn bare_filenames_are_refused_and_counted_never_guessed() {+ let corpus = corpus();+ // index.rs names TWO corpus files; lib.rs names one — both are bare+ // single-segment mentions and neither may become an edge.+ let (out, c) = run(&corpus, "open index.rs then lib.rs");+ assert!(out.is_empty());+ assert_eq!(c.ambiguous, 2);+ assert_eq!(c.unresolved, 0);+ }++ #[test]+ fn ambiguous_suffix_takes_smallest_rel_and_counts() {+ let corpus = corpus();+ let (out, c) = run(&corpus, "grep src/index.rs for the loop");+ assert_eq!(out.len(), 1);+ assert_eq!(+ out[0].dst, corpus.files["engine/crates/xerj-engine/src/index.rs"].anchor_doc_id,+ "lexicographically smallest rel wins deterministically"+ );+ assert_eq!(c.ambiguous, 1);+ }++ #[test]+ fn dangling_multi_segment_counts_and_prose_noise_is_ignored() {+ let corpus = corpus();+ let (out, c) = run(+ &corpus,+ "e.g. version 1.2.3 at https://example.com/missing/file.md — gone/nowhere.rs too",+ );+ assert!(out.is_empty());+ // example.com/missing/file.md and gone/nowhere.rs are dangling path+ // citations; "e.g", "1.2.3", "https" fragments are noise, not counted.+ assert_eq!(c.unresolved, 2);+ assert_eq!(c.ambiguous, 0);+ }++ #[test]+ fn self_citations_emit_nothing() {+ let corpus = corpus();+ let (out, c) = run(&corpus, "this file is docs/notes.md in the tree");+ assert!(out.is_empty());+ assert_eq!(c.unresolved, 0);+ assert_eq!(c.ambiguous, 0);+ }++ #[test]+ fn leading_dot_and_slash_prefixes_resolve() {+ let corpus = corpus();+ let (out, _) = run(&corpus, "run ./engine/crates/xerj-fts/src/lib.rs first");+ assert_eq!(out.len(), 1);+ assert_eq!(out[0].offset, 6, "offset points at the path, not the ./");+ }+}diff --git a/engine/crates/xerj-autoindex/src/detect/samedir.rs b/engine/crates/xerj-autoindex/src/detect/samedir.rsindex 69ea155a4..f7c5f4b10 100644--- a/engine/crates/xerj-autoindex/src/detect/samedir.rs+++ b/engine/crates/xerj-autoindex/src/detect/samedir.rs@@ -1,4 +1,6 @@-//! samedir@1 — files sharing a directory, chained, never a clique.+//! samedir@2 — files sharing a directory, chained, never a clique.+//! (@2: endpoints moved from `s0` sections to file-card nodes; edges carry+//! `src_format`/`dst_format`.)//!//! Directory co-location is weak evidence (weight 0.3, confidence 0.4 — the//! floor of the detector set): it often means "same topic", but it is the@@ -17,7 +19,7 @@use super::{CorpusIndex, EdgeDetector, EdgeDraft};-pub const TAG: &str = "samedir@1";+pub const TAG: &str = "samedir@2";pub const EDGE_TYPE: &str = "same_dir";pub const WEIGHT: f32 = 0.3;pub const CONFIDENCE: f32 = 0.4;@@ -51,6 +53,8 @@ impl EdgeDetector for SameDir {src_file: left.rel.clone(),quote: format!("{} and {} share directory {shown_dir}", left.rel, right.rel),offset: 0,+ src_format: left.format.clone(),+ dst_format: right.format.clone(),});}}diff --git a/engine/crates/xerj-autoindex/src/detect/sequence.rs b/engine/crates/xerj-autoindex/src/detect/sequence.rsindex d6dd1b451..b74beb4fa 100644--- a/engine/crates/xerj-autoindex/src/detect/sequence.rs+++ b/engine/crates/xerj-autoindex/src/detect/sequence.rs@@ -1,20 +1,30 @@-//! sequence@1 — section s_{i-1} → s_i within one file.+//! sequence@2 — the file card opens the chain, then each section precedes+//! the next within one file.//!//! The natural ordering edge: autoindex splits long documents into//! retrieval-sized sections, and without these edges the split would DESTROY//! the document's own narrative adjacency (a hop from "the answer" to "the//! paragraph after it" is exactly what an agent wants when a section ends//! mid-thought). Weight 0.8 — structural but almost certainly meaningful;-//! confidence 0.99 because the extractor's own ordering cannot be wrong about-//! itself.+//! confidence 0.99 because the pipeline's own staging order cannot be wrong+//! about itself.//!-//! Emitted from `detect_text` on section i>0 (the contract's trick to avoid a-//! second pass): every section after the first knows its predecessor's doc id-//! deterministically from (slug, file_key, "s{i-1}").+//! ## @2 — what changed and why+//! - **The chain starts at the file card** (`CorpusFile::anchor_doc_id`):+//! the first section of every text-family file gets a+//! `card → first section` edge. Without it the card — where every incoming+//! citation lands — would float disconnected from the document's own+//! content, and a 2-hop look around a cited file could never reach what the+//! file says.+//! - **Predecessor comes from the pipeline's stream order**+//! (`SectionCtx::prev_section`), not from arithmetic on the locator. That+//! is what lets PDF sections (`p{page}-s{sec}` locators) chain across page+//! boundaries: `p2-s0`'s predecessor is the LAST section of page 1, which+//! no locator computation can name. `s{i}` files chain exactly as @1 did.use super::{EdgeDetector, EdgeDraft, SectionCtx};-pub const TAG: &str = "sequence@1";+pub const TAG: &str = "sequence@2";pub const EDGE_TYPE: &str = "sequence";pub const WEIGHT: f32 = 0.8;pub const CONFIDENCE: f32 = 0.99;@@ -27,28 +37,31 @@ impl EdgeDetector for Sequence {}fn detect_text(&self, ctx: &SectionCtx<'_>, out: &mut Vec<EdgeDraft>) {- if ctx.section_ordinal == 0 {- return;- }- let prev_ordinal = ctx.section_ordinal - 1;- let prev_doc_id = crate::ids::doc_id(- &ctx.file.dataset_slug,- &ctx.file.file_key,- &format!("s{prev_ordinal}"),- );+ let (src, quote) = match ctx.prev_section {+ Some((prev_id, prev_label)) => (+ prev_id.to_string(),+ format!(+ "{prev_label} precedes {} of {}",+ ctx.section_label, ctx.file.rel+ ),+ ),+ None => (+ ctx.file.anchor_doc_id.clone(),+ format!("{} opens {}", ctx.section_label, ctx.file.rel),+ ),+ };out.push(EdgeDraft {- src: prev_doc_id,+ src,dst: ctx.section_doc_id.to_string(),edge_type: EDGE_TYPE,weight: WEIGHT,confidence: CONFIDENCE,valid_at_ms: ctx.file.mtime_ms,src_file: ctx.file.rel.clone(),- quote: format!(- "section {prev_ordinal} precedes section {} of {}",- ctx.section_ordinal, ctx.file.rel- ),+ quote,offset: 0,+ src_format: ctx.file.format.clone(),+ dst_format: ctx.file.format.clone(),});}}@@ -58,32 +71,72 @@ mod tests {use super::super::{corpus_file, CorpusIndex, SectionCtx};use super::*;- /// A 3-section file yields exactly the two adjacency edges, chained- /// through the deterministic section doc ids.+ /// A 3-section file yields the opening card→s0 edge plus the two+ /// adjacency edges, chained through the deterministic section doc ids.#[test]- fn three_sections_chain_two_edges() {+ fn three_sections_chain_from_the_file_card() {let corpus = CorpusIndex::build(vec![corpus_file("big.md", "kb", "docs", "txt-prose", 7)]);let file = &corpus.files["big.md"];let det = Sequence;let mut out = Vec::new();- for ordinal in 0..3u32 {- let doc_id = crate::ids::doc_id("docs", "kb", &format!("s{ordinal}"));+ let ids: Vec<String> = (0..3u32)+ .map(|i| crate::ids::doc_id("docs", "kb", &format!("s{i}")))+ .collect();+ let labels: Vec<String> = (0..3u32).map(|i| format!("section {i}")).collect();+ let mut prev: Option<(usize, usize)> = None;+ for ordinal in 0..3usize {let ctx = SectionCtx {corpus: &corpus,file,- section_ordinal: ordinal,- section_doc_id: &doc_id,+ section_label: &labels[ordinal],+ prev_section: prev.map(|(i, l)| (ids[i].as_str(), labels[l].as_str())),+ section_doc_id: &ids[ordinal],text: "…",};det.detect_text(&ctx, &mut out);+ prev = Some((ordinal, ordinal));}- assert_eq!(out.len(), 2);- assert_eq!(out[0].src, crate::ids::doc_id("docs", "kb", "s0"));- assert_eq!(out[0].dst, crate::ids::doc_id("docs", "kb", "s1"));- assert_eq!(out[1].src, crate::ids::doc_id("docs", "kb", "s1"));- assert_eq!(out[1].dst, crate::ids::doc_id("docs", "kb", "s2"));- assert_eq!(out[0].quote, "section 0 precedes section 1 of big.md");+ assert_eq!(out.len(), 3);+ assert_eq!(out[0].src, file.anchor_doc_id, "chain opens at the card");+ assert_eq!(out[0].dst, ids[0]);+ assert_eq!(out[0].quote, "section 0 opens big.md");+ assert_eq!(out[1].src, ids[0]);+ assert_eq!(out[1].dst, ids[1]);+ assert_eq!(out[1].quote, "section 0 precedes section 1 of big.md");+ assert_eq!(out[2].quote, "section 1 precedes section 2 of big.md");assert_eq!(out[0].offset, 0);assert_eq!(out[0].valid_at_ms, 7);+ assert_eq!(out[0].src_format, "md");+ assert_eq!(out[0].dst_format, "md");+ }++ /// PDF page-boundary chaining: with stream-order predecessors, page 2's+ /// first section links back to page 1's LAST section — the edge the+ /// locator arithmetic of @1 could never produce.+ #[test]+ fn pdf_sections_chain_across_page_boundaries() {+ let corpus = CorpusIndex::build(vec![corpus_file("brief.pdf", "kp", "docs", "pdf", 9)]);+ let file = &corpus.files["brief.pdf"];+ let det = Sequence;+ let mut out = Vec::new();+ let p1s1 = crate::ids::doc_id("docs", "kp", "p1-s1");+ let p2s0 = crate::ids::doc_id("docs", "kp", "p2-s0");+ let ctx = SectionCtx {+ corpus: &corpus,+ file,+ section_label: "page 2 section 0",+ prev_section: Some((p1s1.as_str(), "page 1 section 1")),+ section_doc_id: &p2s0,+ text: "…",+ };+ det.detect_text(&ctx, &mut out);+ assert_eq!(out.len(), 1);+ assert_eq!(out[0].src, p1s1);+ assert_eq!(out[0].dst, p2s0);+ assert_eq!(+ out[0].quote,+ "page 1 section 1 precedes page 2 section 0 of brief.pdf"+ );+ assert_eq!(out[0].src_format, "pdf");}}diff --git a/engine/crates/xerj-autoindex/src/detect/wikilink.rs b/engine/crates/xerj-autoindex/src/detect/wikilink.rsindex 06dd9f35e..be2e9d899 100644--- a/engine/crates/xerj-autoindex/src/detect/wikilink.rs+++ b/engine/crates/xerj-autoindex/src/detect/wikilink.rs@@ -1,16 +1,19 @@-//! wikilink@1 — `[[Target]]` / `[[Target|alias]]` in section text.+//! wikilink@2 — `[[Target]]` / `[[Target|alias]]` in section text.//!//! The strongest signal the detectors have: a human deliberately named//! another note. Hence weight 1.0; confidence 0.95 rather than 1.0 because//! resolution is by name, and a corpus can hold two files answering to the//! same stem (the ambiguity is counted, never hidden).+//!+//! @2: dst moved from the target's `s0` section to its file-card node+//! (`FILE_CARD_LOCATOR`) and edges carry `src_format`/`dst_format`.use super::{line_at, CorpusFile, CorpusIndex, DetectorCounters, EdgeDetector, EdgeDraft, SectionCtx,};use std::sync::atomic::{AtomicU64, Ordering};-pub const TAG: &str = "wikilink@1";+pub const TAG: &str = "wikilink@2";pub const EDGE_TYPE: &str = "wikilink";pub const WEIGHT: f32 = 1.0;pub const CONFIDENCE: f32 = 0.95;@@ -104,6 +107,8 @@ impl EdgeDetector for Wikilink {src_file: ctx.file.rel.clone(),quote: line_at(text, open),offset: open as u64,+ src_format: ctx.file.format.clone(),+ dst_format: file.format.clone(),});}}@@ -135,7 +140,8 @@ mod tests {let ctx = SectionCtx {corpus,file,- section_ordinal: 0,+ section_label: "section 0",+ prev_section: None,section_doc_id: "sec0",text,};diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rsindex b31d36752..64b803afa 100644--- a/engine/crates/xerj-autoindex/src/lib.rs+++ b/engine/crates/xerj-autoindex/src/lib.rs@@ -155,14 +155,22 @@ struct GraphRt {invalidated: u64,}-/// `emit_document` section locators are `s{i}`; everything else (row/line/-/// table locators) is not a text section and must not reach `detect_text`.-fn section_ordinal(locator: &str) -> Option<u32> {- let rest = locator.strip_prefix('s')?;- if rest.is_empty() || !rest.bytes().all(|b| b.is_ascii_digit()) {- return None;- }- rest.parse().ok()+/// Text-section locator → human label ("section 3", "page 2 section 0").+/// `emit_document` section locators are `s{i}`; PDF sections are+/// `p{page}-s{sec}` (extract/pdf.rs — page-major, so stream order IS the+/// lexicographic (page, sec) reading order). Everything else (row/line/byte/+/// table locators) is not a text section, returns None, and must not reach+/// `detect_text`. The label is used verbatim in sequence evidence rationales.+fn section_label(locator: &str) -> Option<String> {+ fn digits(s: &str) -> bool {+ !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())+ }+ if let Some(rest) = locator.strip_prefix('s') {+ return digits(rest).then(|| format!("section {rest}"));+ }+ let rest = locator.strip_prefix('p')?;+ let (page, sec) = rest.split_once("-s")?;+ (digits(page) && digits(sec)).then(|| format!("page {page} section {sec}"))}// ─── Phase A: per-file scan (sniff + bounded sampling) ───────────────────@@ -1106,6 +1114,11 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// staging file (different target index) and sent only// after the node bulks are accepted (§6.7).let mut edge_drafts: Vec<detect::EdgeDraft> = Vec::new();+ // (doc id, label) of the last staged text section — the+ // sequence detector's predecessor. Stream order is the+ // only source that can name a PDF page boundary's+ // predecessor (p2-s0 follows the LAST section of page 1).+ let mut prev_section: Option<(String, String)> = None;let mut staged = match tempfile::Builder::new().prefix(".autoindex-stage-").tempfile_in(&state_dir)@@ -1129,6 +1142,62 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {}continue;}+ // File-card anchor node (§6.6.2a): one card doc per corpus+ // file, staged BEFORE the file's records. Its+ // deterministic id is `CorpusFile.anchor_doc_id` — the+ // node every file-level edge (wikilink/mdlink/href/+ // pathcite/cratecite/samedir dst, sequence opener src)+ // terminates at. Row/line/page families have no `s0`+ // section doc, so without the card those edges pointed at+ // ghosts. Not counted as an extracted record: it is+ // derived anchor infrastructure, not file content.+ if let Some(gr) = graph.as_ref() {+ if let Some(cf) = gr.corpus.files.get(&f.rel) {+ if let Some(rt) = ds_rt.get(&cf.dataset_slug) {+ let name = f.rel.rsplit('/').next().unwrap_or(&f.rel);+ let mut fields = Map::new();+ fields.insert("title".into(), Value::String(name.to_string()));+ fields.insert("ax_path".into(), Value::String(f.rel.clone()));+ fields.insert(+ "ax_paths".into(),+ Value::Array(+ paths_by_key+ .get(key)+ .into_iter()+ .flatten()+ .cloned()+ .map(Value::String)+ .collect(),+ ),+ );+ fields.insert("ax_file".into(), Value::String(key.clone()));+ fields.insert(+ "ax_locator".into(),+ Value::String(detect::FILE_CARD_LOCATOR.into()),+ );+ fields.insert(+ "ax_dataset".into(),+ Value::String(cf.dataset_slug.clone()),+ );+ fields.insert("ax_run".into(), Value::String(run_id.clone()));+ fields.insert(+ "ax_format".into(),+ Value::String(format_str(Some(&sn))),+ );+ let action = json!({"index": {+ "_index": rt.index, "_id": cf.anchor_doc_id}});+ if let Err(error) = writeln!(+ staged.as_file_mut(),+ "{}\n{}",+ action,+ Value::Object(fields)+ ) {+ send_err =+ Some(format!("stage file card for {}: {error}", f.rel));+ }+ }+ }+ }{let mut sink = |rec: extract::RawRecord| -> bool {let Some(slug) = asg.get(&rec.group).or_else(|| asg.get(&None)) else {@@ -1182,7 +1251,7 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {// string the node doc carries, and `id` is the// section node the evidence lives in.if let Some(gr) = graph.as_ref() {- if let Some(ordinal) = section_ordinal(&rec.locator) {+ if let Some(label) = section_label(&rec.locator) {if let (Some(cf), Some(body)) = (gr.corpus.files.get(&f.rel),doc.get("body").and_then(Value::as_str),@@ -1190,13 +1259,17 @@ pub fn run_index_report(cfg: IndexCfg) -> Result<(i32, Option<Value>)> {let ctx = detect::SectionCtx {corpus: &gr.corpus,file: cf,- section_ordinal: ordinal,+ section_label: &label,+ prev_section: prev_section+ .as_ref()+ .map(|(pid, pl)| (pid.as_str(), pl.as_str())),section_doc_id: &id,text: body,};for det in &gr.detectors {det.detect_text(&ctx, &mut edge_drafts);}+ prev_section = Some((id.clone(), label));}}}@@ -2057,6 +2130,31 @@ fn run_status(cfg: StatusCfg) -> Result<i32> {Ok(0)}+#[cfg(test)]+mod section_label_tests {+ use super::section_label;++ /// The two text-section locator grammars (§6.6.2) and their labels; every+ /// other locator shape must be None so row/line/byte records never reach+ /// `detect_text`.+ #[test]+ fn labels_only_text_section_locators() {+ assert_eq!(section_label("s0").as_deref(), Some("section 0"));+ assert_eq!(section_label("s17").as_deref(), Some("section 17"));+ assert_eq!(section_label("p1-s0").as_deref(), Some("page 1 section 0"));+ assert_eq!(+ section_label("p12-s3").as_deref(),+ Some("page 12 section 3")+ );+ for not_a_section in [+ "s", "sx", "s1x", "p1", "p1-s", "p-s1", "px-s1", "b1024", "row7", "file", "line3",+ "p1-s2-x",+ ] {+ assert_eq!(section_label(not_a_section), None, "{not_a_section}");+ }+ }+}+#[cfg(test)]mod duplicate_integration_tests {use super::*;diff --git a/engine/crates/xerj-autoindex/src/sniff.rs b/engine/crates/xerj-autoindex/src/sniff.rsindex 559b0d187..b43438732 100644--- a/engine/crates/xerj-autoindex/src/sniff.rs+++ b/engine/crates/xerj-autoindex/src/sniff.rs@@ -212,8 +212,23 @@ pub fn decode_text(bytes: &[u8]) -> (String, &'static str) {fn classify_text(text: &str, nonblank: &[&str]) -> Family {let trimmed = text.trim_start();+ // A lone `[section]` opening line that does not parse as JSON is a+ // TOML/INI table header (`[package]` in Cargo.toml, `[Unit]` in a+ // systemd unit), not a JSON array. Without this guard every such file+ // fell into the JSON branch below (any '['-opener passes+ // `looks_like_json_start`), reached the JSON extractor, and was junked+ // — which, for Cargo.toml, also silently disabled the cratecite+ // detector on every real repository (its crate table only holds+ // indexed files). Live-verified 2026-07-30: three Cargo.tomls junked+ // as "json candidate family" before this guard, indexed after.+ let ini_table_header = nonblank.first().is_some_and(|l| {+ let t = l.trim();+ t.starts_with('[')+ && t.ends_with(']')+ && serde_json::from_str::<serde_json::Value>(t).is_err()+ });// JSON / JSONL- if trimmed.starts_with('{') || trimmed.starts_with('[') {+ if !ini_table_header && (trimmed.starts_with('{') || trimmed.starts_with('[')) {if nonblank.len() >= 2 {let parse_ok = nonblank.iter()@@ -508,6 +523,28 @@ mod tests {);}+ /// `[package]`-style openers are TOML/INI table headers, not JSON+ /// arrays. Before the guard, Cargo.toml sniffed as Json, the JSON+ /// extractor junked it, and cratecite's crate table stayed empty on+ /// every real repository (its dst must be an INDEXED Cargo.toml).+ #[test]+ fn toml_table_header_is_not_json() {+ let cargo = "[package]\nname = \"xerj-fts\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\+ [dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\n\+ serde_json = \"1\"\nanyhow = \"1\"\n";+ assert_eq!(classify(cargo), Family::TxtLines);+ let ini = "[Unit]\nDescription=demo\nAfter=network.target\n\n\+ [Service]\nExecStart=/bin/true\nRestart=always\n\n\+ [Install]\nWantedBy=multi-user.target\n";+ assert_eq!(classify(ini), Family::TxtLines);+ // …while real JSON arrays keep their family.+ assert_eq!(classify("[1, 2, 3]\n"), Family::Json);+ assert_eq!(+ classify("[\n {\"a\": 1},\n {\"a\": 2}\n]\n"),+ Family::Json+ );+ }+#[test]fn csv_dialect_semicolon_decimal_comma() {let lines = vec![diff --git a/engine/crates/xerj-console-api/src/seed.rs b/engine/crates/xerj-console-api/src/seed.rsindex 817707004..9534348d0 100644--- a/engine/crates/xerj-console-api/src/seed.rs+++ b/engine/crates/xerj-console-api/src/seed.rs@@ -280,6 +280,13 @@ fn seed_specs() -> Vec<DashboardSpec> {// structure. NOTE (module-doc contract): adding this id needs// NO `SEED_REVISION` bump — absent ids are created on every// boot; the revision only migrates *changed* skeletons.+ //+ // NAV PRESENCE IS NOT SEEDED FROM HERE: `visibility:"default"`+ // docs are skipped by the SPA's dashboard-store hydrate, and+ // the SPA hides this dashboard from the nav until the engine+ // holds ≥ 1 brain (registry `requiresLive:'brains'` ++ // data/brains-probe.js). Deep links and MANAGE still resolve+ // it — this seed stays the durable skeleton either way.registry_id: "second-brain",name: "Second Brain",section: Some("dashboards"),diff --git a/xerj-ux/assets/base.css b/xerj-ux/assets/base.cssindex d83943f55..c23354583 100644--- a/xerj-ux/assets/base.css+++ b/xerj-ux/assets/base.css@@ -2142,9 +2142,135 @@ button.sb-grouphead { width: 100%; }white-space: nowrap;}+/* ---- Second Brain · map mount + statistics row ------------- */+/* The map panel body is a MOUNT POINT (ux/brain-map.js draws into+ it); the disclosure line below it is permanent and DOM-rendered so+ it survives whatever the canvas does. */+.sb-map { position: relative; }+.sb-map-mount { min-height: 140px; position: relative; }+.sb-map-disclosure {+ margin-top: 6px;+ font-size: var(--fs-11);+ letter-spacing: 0.04em;+}+/* Once the map is live its stage carries the same disclosure in the+ corner — one copy of the sentence at a time. */+[data-sb-map-live] .sb-map-disclosure { display: none; }++/* The page's own attributed read log: what — how much — why · when. */+.sb-reads { font-size: var(--fs-13); }+.sb-readrow {+ display: flex;+ gap: var(--sp-2);+ align-items: baseline;+ font-family: var(--font-data);+ padding: 3px 0;+ border-bottom: 1px solid var(--z-faint);+ min-width: 0;+}+.sb-readrow:last-of-type { border-bottom: none; }+.sb-readwhat { color: var(--z-ink); font-weight: 700; white-space: nowrap; }+.sb-readhow { color: var(--z-mute); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.sb-readwhy {+ color: var(--z-mute);+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ text-align: right;+}+.sb-readat { color: var(--z-mute); opacity: 0.7; white-space: nowrap; }++/* ---- Second Brain · THE MAP (canvas + rail, ux/brain-map.js) ----+ Once mounted (`data-sb-map-live`), the mount becomes stage + rail.+ The canvas draws 1px strokes and text only — all color comes from+ the tokens, read at draw time, so theme flips restyle on redraw. */+[data-sb-map-live] .sb-map-mount {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 300px;+ gap: var(--sp-3);+ align-items: start;+}+.sb-map-stage {+ position: relative;+ height: 55vh;+ min-height: 420px;+ border: 1px solid var(--z-faint);+ overflow: hidden;+}+.sb-map-canvas { display: block; width: 100%; height: 100%; touch-action: none; }+.sb-map-status {+ position: absolute;+ top: var(--sp-1);+ left: var(--sp-1);+ font-size: var(--fs-11);+ letter-spacing: 0.04em;+ pointer-events: none;+}+.sb-map-tools {+ position: absolute;+ top: var(--sp-1);+ right: var(--sp-1);+ display: flex;+ gap: var(--sp-2);+ font-size: var(--fs-11);+}+.sb-map-rail {+ max-height: max(55vh, 420px);+ overflow-y: auto;+ font-size: var(--fs-13);+ min-width: 0;+}+.sb-map-selname {+ font-family: var(--font-data);+ font-weight: 700;+ font-size: var(--fs-16);+ margin-bottom: var(--sp-1);+ overflow-wrap: anywhere;+}+.sb-map-note { font-size: var(--fs-11); letter-spacing: 0.04em; margin: 6px 0; }+.sb-map-act {+ display: block;+ text-align: left;+ margin: var(--sp-1) 0;+ border-left: 1px solid var(--z-accent);+ padding-left: var(--sp-1);+}+.sb-map-act[disabled] { color: var(--z-mute); border-left-color: var(--z-faint); cursor: default; }+.sb-map-evlist { margin-top: var(--sp-1); }+.sb-map-evrow {+ display: block;+ width: 100%;+ text-align: left;+ padding: 5px 0;+ border-bottom: 1px solid var(--z-faint);+ font-family: var(--font-data);+ font-size: var(--fs-11);+}+.sb-map-evrow:hover .sb-map-evline,+.sb-map-evrow:focus-visible .sb-map-evline { color: var(--z-accent); }+.sb-map-evline { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.sb-map-evrow.sb-expired .sb-map-evline { text-decoration: line-through; color: var(--z-mute); }+.sb-map-evmeta { display: block; margin-top: 2px; }+.sb-map-satlist { display: flex; flex-direction: column; gap: 2px; margin-top: var(--sp-1); }+.sb-map-satrow {+ text-align: left;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ padding: 2px 0;+}+@media (max-width: 1100px) {+ [data-sb-map-live] .sb-map-mount { grid-template-columns: 1fr; }+ .sb-map-stage { height: 46vh; min-height: 320px; }+ .sb-map-rail { max-height: none; }+}+/* 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); }.sb-rail { display: none; }.sb-focuscard { order: -1; }+ .sb-readhow { display: none; } /* what + why survive; the how is a detail */}diff --git a/xerj-ux/src/app.js b/xerj-ux/src/app.jsindex d838b7936..02c72fd3d 100644--- a/xerj-ux/src/app.js+++ b/xerj-ux/src/app.js@@ -23,6 +23,8 @@ import {listClusters, listIndices, listFields, listClustersSync,defaultClusterId, setDefaultCluster,} from './data/data-sources.js';+import { sbBrainsPresent } from './data/brains-probe.js';+import { activeBackendId, backendBaseUrl } from './data/backends/index.js';// ---------- state -----------------------------------------const LS = {@@ -88,6 +90,11 @@ const state = {};})(),_focusSelector: null, // set by handlers that need focus restored+ // Live-gated features: a dashboard whose registry entry sets+ // `requiresLive: '<key>'` only appears in the NAV once the matching+ // key here is true (fed by a probe against the live engine). Routes+ // and MANAGE are never filtered — a deep link must always resolve.+ liveFeatures: { brains: false },};// Merge any URL-seeded filters into the current dashboard's filter set.if (_urlState.filters) {@@ -259,11 +266,38 @@ function setRefreshInterval(ms) {if (state.refreshTimer) { clearInterval(state.refreshTimer); state.refreshTimer = null; }if (ms > 0) {state.refreshTimer = setInterval(() => {+ probeLiveFeatures();if (state.section === 'dashboards' || state.section === 'discover') render();}, ms);}}+// ---------- live-feature probes ---------------------------+// Some dashboards only earn a nav entry once the engine actually has+// data for them (registry `requiresLive` flag). This asks the probes,+// updates `state.liveFeatures`, and re-renders on a change so the nav+// entry appears/disappears without a reload. The probe module caches+// per baseUrl (~30 s), so calling this on every refresh tick is cheap,+// and a backend/base-URL change naturally re-probes the new target.+let _probingLive = false;+async function probeLiveFeatures() {+ if (_probingLive) return;+ _probingLive = true;+ try {+ const brains = await sbBrainsPresent(backendBaseUrl(activeBackendId()));+ if (brains !== state.liveFeatures.brains) {+ state.liveFeatures.brains = brains;+ // Same guards as the store/panel re-render hooks: never nuke an+ // in-flight drag gesture or steal focus from a form field.+ const ae = document.activeElement;+ const typing = ae && (ae.tagName === 'INPUT' || ae.tagName === 'SELECT' || ae.isContentEditable);+ if (!geomDrag && !typing) render();+ }+ } finally {+ _probingLive = false;+ }+}+// ---------- saved views -----------------------------------// A saved view is a snapshot of (dashId, time, cluster, filters).// Click it to land on that dashboard with the same context.@@ -869,7 +903,13 @@ async function render() {const dash = allDash.find((d) => d.id === state.route)|| dashboardsInSection(state.section, allDash)[0]|| registry['ai-overview'];- const navDash = mergedDashboards(defaults);+ // NAV list only: hide live-gated dashboards until their probe says+ // the engine has data for them (e.g. Second Brain before any+ // `xerj brain` run). `allDash` above is deliberately NOT filtered —+ // the deep link a fresh `xerj brain` prints must resolve instantly;+ // the nav catches up on the next probe tick.+ const navDash = mergedDashboards(defaults)+ .filter((d) => !d.requiresLive || state.liveFeatures[d.requiresLive]);const dashboardsForSection = dashboardsInSection('dashboards', navDash);// For the SEARCH dashboard, eagerly run the search so panels see hits.@@ -1917,12 +1957,23 @@ window.addEventListener('hashchange', () => {saveFilters(state.route);}writeUrlState();+ // Route changes also re-ask the live-feature probes (cached ~30 s):+ // with the auto-refresh interval off, this is what lets the nav+ // catch up after a `xerj brain` run — e.g. when the user opens the+ // deep link the CLI printed.+ probeLiveFeatures();render();});// Boot the refresh interval if the user had one saved.if (state.refresh > 0) setRefreshInterval(state.refresh);+// Probe live-gated features once at boot (re-render happens inside on+// change, same pattern as the setOnChange hook below). Re-probes ride+// the refresh interval; the probe's per-baseUrl cache handles a+// backend/base-URL change without an explicit invalidation hook.+probeLiveFeatures();+// Restore mobile preview class if it was active.if (state.mobile) document.documentElement.classList.add('mobile-preview');diff --git a/xerj-ux/src/dashboards/registry.js b/xerj-ux/src/dashboards/registry.jsindex 9defad6ae..a19374f0e 100644--- a/xerj-ux/src/dashboards/registry.js+++ b/xerj-ux/src/dashboards/registry.js@@ -49,6 +49,13 @@ for (const d of [aiOverview, ragQuality, vectorIndex, agentMemory, secondBrain,d.section = 'dashboards';d.group = DEFAULT_GROUP[d.id] || 'other';}+// Second Brain only earns a NAV entry once the engine holds at least+// one brain (someone ran `xerj brain <folder>`). Generic flag: the+// shell (app.js) filters the nav list on `state.liveFeatures[key]`,+// fed by data/brains-probe.js — no dashboard id is hardcoded there.+// Routing, MANAGE, and deep links (`#/dashboards/second-brain?...`)+// always resolve; only nav presence is gated.+secondBrain.requiresLive = 'brains';// Search-discover gets tagged as the DISCOVER section (promoted out of the dashboards list).searchDiscover.section = 'discover';diff --git a/xerj-ux/src/dashboards/second-brain.js b/xerj-ux/src/dashboards/second-brain.jsindex 378e9fa69..9230546a9 100644--- a/xerj-ux/src/dashboards/second-brain.js+++ b/xerj-ux/src/dashboards/second-brain.js@@ -4,11 +4,23 @@// The relationship layer over documents that already exist: edges are// ordinary XERJ documents, bi-temporal and soft-delete-only, asserted// by deterministic detectors (or by hand) with the exact source quote-// as evidence. This dashboard is an EGO LEDGER — inbound edges left,-// the focus memory centre, outbound edges right — with a belief-time-// scrubber to replay what the brain believed at any moment. A global-// force-directed graph was rejected by design (non-deterministic-// layout, collapses past ~200 nodes); see ux/ego-ledger.js.+// as evidence.+//+// Composition, top to bottom (the decided §1.1 order):+// controls brain switcher · trail crumbs · FIND+// map THE MAP — bounded, deterministic overview (mounted by+// ux/brain-map.js; this dashboard renders the mount point)+// scrub ONE belief-time caret for the whole page — the map+// restyles and the ledger restates from the same drag+// stats counts, kinds, teachers, file types, crossings, and the+// page's own attributed read log — ran numbers only+// ego THE LEDGER — the leaf view; every link's evidence+// hubs/honesty+//+// The ledger is still the terminal surface: a global force-directed+// hairball stays rejected (see ux/ego-ledger.js). The map above it is+// bounded by construction and routes every terminal click back into+// the ledger.//// LIVE DATA ONLY. data/backends/xerj.js routes this dashboard to// data/second-brain-api.js, which reads /_graph/{brain}/overview and@@ -29,8 +41,8 @@ export const secondBrain = {id: 'second-brain',name: 'Second Brain',render: ({ data, time }) => {- // Traces (the 1px focus→group lines) need real layout; schedule a- // post-paint measure+draw pass. No-op outside a browser.+ // Traces + the map mount need real layout; schedule a post-paint+ // measure+draw pass. No-op outside a browser.sbAfterRender();return {title: 'SECOND BRAIN',@@ -44,6 +56,12 @@ export const secondBrain = {// Schema vocabulary (edge, src/dst, as-of) stays in the API and// in the evidence paper-trail, never in a panel title.panels: [+ { id: 'controls', eyebrow: 'YOU ARE HERE · BRAIN, FOCUS, FIND', cols: 12, type: 'controls',+ render: () => body('controls', data) },+ { id: 'map', eyebrow: 'THE MAP · THE WHOLE BRAIN AT A GLANCE', cols: 12, type: 'map',+ render: () => body('map', data) },+ { id: 'scrub', eyebrow: 'BELIEF TIME · ONE CARET DRIVES THE WHOLE PAGE', cols: 12, type: 'scrub',+ render: () => body('scrub', data) },{ id: 'edgesLive', eyebrow: 'BELIEVED AT THIS MOMENT', cols: 3, type: 'metric',render: () => body('edgesLive', data) },{ id: 'edgesTotal', eyebrow: 'EVER ASSERTED', cols: 3, type: 'metric',@@ -56,6 +74,12 @@ export const secondBrain = {render: () => body('typeDist', data) },{ id: 'edgeTimeline', eyebrow: 'NEW LINKS PER DAY', cols: 6, type: 'series',render: () => body('edgeTimeline', data) },+ { id: 'notes', eyebrow: 'WHAT THIS BRAIN HOLDS', cols: 4, type: 'notes',+ render: () => body('notes', data) },+ { id: 'crossings', eyebrow: 'LINKS ACROSS FILE TYPES', cols: 4, type: 'crossings',+ render: () => body('crossings', data) },+ { id: 'reads', eyebrow: 'WHAT THIS VIEW READ · AND WHY', cols: 4, type: 'reads',+ render: () => body('reads', data) },{ id: 'ego', eyebrow: 'THE LEDGER · ONE NOTE, EVERYTHING IT TOUCHES', cols: 12, type: 'ego',render: () => body('ego', data) },{ id: 'hubs', eyebrow: 'CENTERS OF GRAVITY', cols: 6, type: 'topn',diff --git a/xerj-ux/src/data/brains-probe.js b/xerj-ux/src/data/brains-probe.jsnew file mode 100644index 000000000..be37c63bc--- /dev/null+++ b/xerj-ux/src/data/brains-probe.js@@ -0,0 +1,94 @@+// ============================================================+// Xerj Console — "does at least one brain exist?" probe+//+// The Second Brain dashboard only earns a nav entry once the engine+// actually holds a brain — a console pointed at an engine nobody ever+// ran `xerj brain <folder>` against should not advertise an empty+// dashboard. This module answers exactly that yes/no question.+//+// It wraps the same discovery pattern second-brain-api.js uses+// (`_cat/indices/.xerj-memory-*` — PREFIX wildcard only: this+// engine's index-pattern matcher silently returns empty for an infix+// wildcard like `.xerj-memory-*-edges`, live-verified 2026-07-30, so+// the `-edges` cut happens client-side).+//+// Honesty stance: `false` on ANY transport failure. An unreachable+// engine means we cannot claim a brain exists, so the nav entry stays+// hidden — the deep-link route still resolves (app.js never filters+// the route table, only the nav list), so nothing is lost.+//+// Results are cached per baseUrl with a short TTL, so:+// - the boot probe + periodic re-probes don't hammer `_cat`,+// - switching backend/base-URL naturally misses the cache and+// re-probes the new target without an explicit invalidation hook.+// ============================================================++const TTL_MS = 30_000;++/** baseUrl → { at: epoch-ms, value: boolean } */+const cache = new Map();++/** Drop all cached answers (e.g. right after `xerj brain` finishes,+ * or when settings change under us). Safe to call any time. */+export function invalidateBrainsProbe() {+ cache.clear();+}++/**+ * True iff the engine at `baseUrl` holds at least one brain+ * (a reserved `.xerj-memory-{brain}-edges` index).+ *+ * Never throws; returns false on transport failure, non-OK status,+ * or an empty/absent baseUrl.+ */+export async function sbBrainsPresent(baseUrl, signal) {+ const base = (baseUrl || '').replace(/\/+$/, '');+ if (!base) return false;++ const hit = cache.get(base);+ if (hit && Date.now() - hit.at < TTL_MS) return hit.value;++ let present = false;+ try {+ const r = await fetch(`${base}/_cat/indices/.xerj-memory-*`, {+ signal,+ headers: { accept: 'text/plain, application/json' },+ });+ // A wildcard matching nothing is 200 with an EMPTY body on this+ // engine (live-verified; only a concrete name 404s), which parses+ // to zero brains below. Any non-OK status (404 from an older build+ // without the pattern route, 5xx, auth) is treated as "cannot+ // prove a brain exists", so we do not claim one.+ if (r.ok) {+ const text = await r.text();+ present = parseBrainIndices(text).length > 0;+ }+ } catch {+ present = false; // engine down / CORS / abort — no claim+ }++ cache.set(base, { at: Date.now(), value: present });+ return present;+}++/**+ * Parse a `_cat/indices` body into the list of brain names. `_cat` on+ * this engine emits plain text lines (`health status NAME uuid …`);+ * tolerate a JSON array in case a later build adds format=json.+ * Exported for the node self-test.+ */+export function parseBrainIndices(text) {+ const trimmed = (text || '').trim();+ let names = [];+ if (trimmed.startsWith('[')) {+ try { names = JSON.parse(trimmed).map((i) => i.index).filter(Boolean); } catch { names = []; }+ } else if (trimmed) {+ names = trimmed.split('\n')+ .map((l) => l.trim().split(/\s+/)[2])+ .filter(Boolean);+ }+ return names+ .filter((n) => n.startsWith('.xerj-memory-') && n.endsWith('-edges'))+ .map((n) => n.slice('.xerj-memory-'.length, -'-edges'.length))+ .filter((b) => b.length > 0);+}diff --git a/xerj-ux/src/data/second-brain-api.js b/xerj-ux/src/data/second-brain-api.jsindex 4d6da8274..939864878 100644--- a/xerj-ux/src/data/second-brain-api.js+++ b/xerj-ux/src/data/second-brain-api.js@@ -21,6 +21,15 @@// ux/ego-ledger.js#renderPanelBody. Scrub previews are client-side// over already-fetched edges; RELEASING the caret re-queries the// server with `as_of` — the server owns the bi-temporal cut.+//+// Two additions ride along:+// READ LOG — every fetch this page makes records what/how much/why+// (the reads panel is the only honest "which data was read and why";+// the engine does not record other callers' intentions).+// MAP SEAM — ux/brain-map.js is dynamic-imported and mounted into+// the map panel's `[data-sb-map-mount]`; it talks back through+// sbRefocus/sbLogRead/sbPublishMapStats/sbSnapshot and hears the+// shared belief caret as sb:asof-preview / sb:asof-commit events.// ============================================================import {@@ -29,10 +38,14 @@ import {} from '../ux/ego-ledger.js';/** Panel ids of the second-brain dashboard, in render order. The- * controller patches exactly these after an interaction. */+ * controller patches exactly these after an interaction — except a+ * LIVE map body, which is the one panel that owns its own DOM (a+ * canvas is not re-renderable from an HTML string; see patchPanels). */export const SB_PANEL_IDS = [+ 'controls', 'map', 'scrub','edgesLive', 'edgesTotal', 'invalidated', 'detectors',- 'typeDist', 'edgeTimeline', 'ego', 'hubs', 'notShown',+ 'typeDist', 'edgeTimeline', 'notes', 'crossings', 'reads',+ 'ego', 'hubs', 'notShown',];/** Returned edge budget for the belief query. Hops=2 so neighbour rows@@ -76,8 +89,57 @@ const S = {collapsed: new Set(), // folded link-kind groups ("side:type"), per-brainrecentRetired: null, // three most recently retired links (RetiredPanel)lastShift: null, // what the last time-travel changed (scrubber readout)+ // ---- statistics row state ----------------------------------------+ nodeStats: null, // { total, formats:[{format,count}], otherFormats } | { error }+ crossings: null, // { total, crossCount, pairs:[{src,dst,count}], otherPairs } | { error }+ serverReads: null, // { rows:[{index,count}] } | { error } — /v1/metrics counters+ reads: [], // the page's own attributed fetch log (capped)+ readsTotal: 0, // reads ever logged this session (survives the cap)+ mapStats: null, // published by ux/brain-map.js via sbPublishMapStats};+// ----- the page's own read log --------------------------------------+//+// Every fetch this dashboard makes records WHAT it read, HOW MUCH, and+// WHY — the only honest answer to "which data was read and why". The+// engine records neither other callers' whys nor per-note read counts;+// the reads panel says so instead of inventing them.++const READS_CAP = 48;++function logRead(surface, detail, reason) {+ const last = S.reads[S.reads.length - 1];+ S.readsTotal += 1;+ if (last && last.surface === surface && last.detail === detail && last.reason === reason) {+ // The same read repeating back-to-back (render loops, re-probes)+ // collapses into one row with a ×count — the log stays a record,+ // not a scroll of noise.+ last.n += 1;+ last.t = Date.now();+ } else {+ S.reads.push({ t: Date.now(), surface, detail, reason, n: 1 });+ if (S.reads.length > READS_CAP) S.reads = S.reads.slice(-READS_CAP);+ }+ scheduleReadsPatch();+}++/** The map module (and any other in-page reader) logs its reads+ * through the same front door: sbLogRead('links index', '10 pages',+ * 'building the map'). */+export const sbLogRead = logRead;++let readsRaf = 0;+/** Repaint just the reads panel after a log entry — logs land mid-+ * flight (FIND keystrokes, map pages) when no full patch will run. */+function scheduleReadsPatch() {+ if (typeof requestAnimationFrame === 'undefined' || readsRaf) return;+ readsRaf = requestAnimationFrame(() => {+ readsRaf = 0;+ const el = document.querySelector('[data-sb-body="reads"]');+ if (el) el.innerHTML = renderPanelBody('reads', assemble());+ });+}+/*** 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@@ -220,13 +282,16 @@ async function hydrateNames(signal) {const want = [...ids].filter((id) => !(id in S.names)).slice(0, 40);if (!want.length) return;try {+ logRead('notes index', `${want.length} note name${want.length === 1 ? '' : 's'}`, 'turning ids into titles');const r = await fetch(`${S.baseUrl}/${enc(o.nodes_index)}/_search`, {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({query: { ids: { values: want } },size: want.length,- _source: ['title', 'text', 'body'],+ // ax_path/path: the real file behind a note — a truthful label+ // for the focus card and the map, never derived from the id.+ _source: ['title', 'text', 'body', 'ax_path', 'path'],}),signal,});@@ -239,7 +304,10 @@ async function hydrateNames(signal) {: (typeof src.text === 'string' && src.text.trim()? src.text.trim().slice(0, 60): (typeof src.body === 'string' && src.body.trim() ? src.body.trim().slice(0, 60) : null));- if (title) S.names[h._id] = { title };+ const path = (typeof src.ax_path === 'string' && src.ax_path.trim())+ ? src.ax_path.trim()+ : (typeof src.path === 'string' && src.path.trim() ? src.path.trim() : null);+ if (title || path) S.names[h._id] = { title, path };}} catch { /* names are sugar; the ids remain the truth */ }}@@ -247,9 +315,18 @@ async function hydrateNames(signal) {function fetchOverview(signal) {const qs = new URLSearchParams({ top: '10', histogram_interval: 'day' });if (S.asOf != null) qs.set('as_of', String(S.asOf));+ logRead('link counts', 'one overview read', 'the tiles on this page');return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/overview?${qs}`, signal);}+/** The focus note's display name for the read log — hydrated title if+ * the console knows one, else the (shortened) id. Never a guess. */+function focusLabel() {+ const n = S.focus && S.names[S.focus] && S.names[S.focus].title;+ const raw = n || String(S.focus || '');+ return raw.length > 28 ? `${raw.slice(0, 27)}…` : raw;+}+/*** The RETIRED panel's churn rows: the three most recently retired* links, one bounded ordinary search on the edges index. Deliberately@@ -263,6 +340,7 @@ async function fetchRecentRetired(signal) {&& S.overview.edges && S.overview.edges.invalidated > 0;if (!inval) { S.recentRetired = []; return; }try {+ logRead('links index', 'three newest retirements', 'the retired tile');const r = await fetch(`${S.baseUrl}/${enc(`.xerj-memory-${S.brain}-edges`)}/_search`, {method: 'POST',headers: { 'content-type': 'application/json' },@@ -294,6 +372,7 @@ function fetchBelief(signal) {include_expired: 'true', include_nodes: 'true', include_evidence: 'true',});if (S.asOf != null) qs.set('as_of', String(S.asOf));+ logRead('the ledger', `one 2-hop walk from “${focusLabel()}”`, 'you focused this note');return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/ego?${qs}`, signal);}@@ -308,9 +387,140 @@ function fetchTimeline(signal) {limit: String(EGO_LIMIT),include_expired: 'true', include_evidence: 'false',});+ logRead('belief strip', `one 1-hop walk from “${focusLabel()}”`, 'drawing every link’s lifetime');return getJson(`${S.baseUrl}/_graph/${enc(S.brain)}/ego?${qs}`, signal);}+// ----- statistics-row fetches (all best-effort, never throw) --------++/**+ * Notes total + by-file-type tally: one size-0 search over the brain's+ * nodes indices. The total is the search's own hit count — a ran+ * number; the panel prefers it and falls back to overview.nodes.total+ * only when this tally failed (see NotesPanel's rationale).+ */+async function fetchNodeStats(signal) {+ const o = S.overview;+ if (!o || o.exists === false || !o.nodes_index) { S.nodeStats = null; return; }+ try {+ logRead('notes index', 'one tally by file type', 'the notes tile');+ const r = await fetch(`${S.baseUrl}/${enc(o.nodes_index)}/_search`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ size: 0,+ // Exact, not the engine's 10,000 'gte' floor: the tile's+ // headline is the note count, and this brain's own per-type+ // rows summed to 2.1M under a "10,000 NOTES" headline before+ // this flag (live-caught on `repo`, 2026-07-30).+ track_total_hits: true,+ aggs: { formats: { terms: { field: 'ax_format', size: 12 } } },+ }),+ signal,+ });+ if (!r.ok) { S.nodeStats = { error: `HTTP ${r.status}` }; return; }+ const j = await r.json();+ const t = j.hits && j.hits.total;+ let total = t == null ? null : (typeof t === 'object' ? t.value : t);+ // A 'gte' floor is not a count — refuse it rather than print it.+ if (t && typeof t === 'object' && t.relation === 'gte') total = null;+ const agg = (j.aggregations && j.aggregations.formats) || {};+ S.nodeStats = {+ total: Number.isFinite(total) ? total : null,+ formats: (agg.buckets || []).map((b) => ({ format: b.key, count: b.doc_count })),+ otherFormats: agg.sum_other_doc_count || 0,+ };+ } catch (e) {+ if (e && e.name === 'AbortError') return;+ S.nodeStats = { error: String((e && e.message) || e) };+ }+}++/**+ * File-type crossings: which file types link to which, from the+ * src_format/dst_format stamps on the links index. Brains indexed+ * before stamping return zero stamped links — the panel then says+ * REINDEX TO SEE FILE-TYPE CROSSINGS instead of guessing from ids.+ */+async function fetchCrossings(signal) {+ if (!S.brain) { S.crossings = null; return; }+ try {+ logRead('links index', 'one file-type crossing tally', 'the crossings tile');+ const r = await fetch(`${S.baseUrl}/${enc(`.xerj-memory-${S.brain}-edges`)}/_search`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ size: 0,+ // Exact, not the engine's 10,000 'gte' floor — the tile prints+ // this as "N stamped links tallied" and a floor there is a+ // false number (live-caught at 20,930 links, 2026-07-30).+ track_total_hits: true,+ query: { exists: { field: 'src_format' } },+ aggs: {+ src: {+ terms: { field: 'src_format', size: 20 },+ aggs: { dst: { terms: { field: 'dst_format', size: 20 } } },+ },+ },+ }),+ signal,+ });+ if (!r.ok) { S.crossings = { error: `HTTP ${r.status}` }; return; }+ const j = await r.json();+ const t = j.hits && j.hits.total;+ const total = (t == null ? 0 : (typeof t === 'object' ? t.value : t)) || 0;+ const srcAgg = (j.aggregations && j.aggregations.src) || {};+ const pairs = [];+ let otherPairs = 0;+ for (const sb of srcAgg.buckets || []) {+ const dstAgg = sb.dst || {};+ for (const db of dstAgg.buckets || []) {+ pairs.push({ src: sb.key, dst: db.key, count: db.doc_count });+ }+ if (dstAgg.sum_other_doc_count > 0) otherPairs += 1;+ }+ if (srcAgg.sum_other_doc_count > 0) otherPairs += 1;+ // Deterministic order: count desc, then label asc.+ pairs.sort((a, b) => b.count - a.count+ || (a.src < b.src ? -1 : a.src > b.src ? 1 : 0)+ || (a.dst < b.dst ? -1 : a.dst > b.dst ? 1 : 0));+ const crossCount = pairs.reduce((n, p) => n + (p.src !== p.dst ? p.count : 0), 0);+ const sameCount = pairs.reduce((n, p) => n + (p.src === p.dst ? p.count : 0), 0);+ // Bucket caps can hide pairs; when they did, every derived count+ // is a floor and the tile must say so.+ const truncated = otherPairs > 0;+ S.crossings = { total, crossCount, sameCount, truncated, pairs, otherPairs };+ } catch (e) {+ if (e && e.name === 'AbortError') return;+ S.crossings = { error: String((e && e.message) || e) };+ }+}++/**+ * Per-index search counters from the server's own metrics — framed+ * exactly as what they are: since server start, reset at boot. If the+ * metrics endpoint refuses the console's credentials, the panel shows+ * the refusal rather than a stale or invented number.+ */+async function fetchServerReads(signal) {+ try {+ logRead('server counters', 'one metrics read', 'searches per index');+ const r = await fetch(`${S.baseUrl}/v1/metrics`, { signal });+ if (!r.ok) { S.serverReads = { error: `HTTP ${r.status}` }; return; }+ const text = await r.text();+ const rows = [];+ for (const line of text.split('\n')) {+ const m = line.match(/^xerj_queries_by_index_total\{index="([^"]*)"\}\s+(\d+)/);+ if (m) rows.push({ index: m[1], count: Number(m[2]) });+ }+ rows.sort((a, b) => b.count - a.count || (a.index < b.index ? -1 : 1));+ S.serverReads = { rows };+ } catch (e) {+ if (e && e.name === 'AbortError') return;+ S.serverReads = { error: String((e && e.message) || e) };+ }+}+// ----- data assembly (§7.3 shape, extras under `sb`) ---------------function assemble() {@@ -357,6 +567,12 @@ function assemble() {collapsed: S.collapsed,recentRetired: S.recentRetired,lastShift: S.lastShift,+ nodeStats: S.nodeStats,+ crossings: S.crossings,+ serverReads: S.serverReads,+ reads: S.reads,+ readsTotal: S.readsTotal,+ mapStats: S.mapStats,},};}@@ -377,6 +593,7 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {S.baseUrl = (baseUrl || '').replace(/\/+$/, '');S.uiError = null;try {+ logRead('brain list', 'one index listing', 'finding your brains');S.brains = await discoverBrains(S.baseUrl, signal);S.connected = true;S.error = null;@@ -441,15 +658,21 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {&& S.overview.edges && S.overview.edges.total > 0;if (!hasEdges) {S.ego = null; S.timeline = null;+ // A brain can hold notes before it holds links — count them anyway.+ await Promise.all([fetchNodeStats(signal), fetchServerReads(signal)]);return assemble();}if (!S.focus) S.focus = defaultFocus();+ const statJobs = [ // best-effort, never throw+ fetchNodeStats(signal), fetchCrossings(signal), fetchServerReads(signal),+ ];if (S.focus) {try {const [belief, timeline] = await Promise.all([fetchBelief(signal), fetchTimeline(signal),fetchRecentRetired(signal), // best-effort, never throws+ ...statJobs,]);S.ego = belief;S.timeline = timeline;@@ -459,7 +682,7 @@ export async function liveSecondBrain(baseUrl, _ctx, signal) {}} else {S.ego = null; S.timeline = null;- await fetchRecentRetired(signal);+ await Promise.all([fetchRecentRetired(signal), ...statJobs]);}await hydrateNames(signal);saveBrainState();@@ -494,6 +717,13 @@ function patchPanels() {: null;const data = assemble();for (const id of SB_PANEL_IDS) {+ if (id === 'map') {+ // A LIVE map owns its DOM — a mounted canvas cannot be re-created+ // from an HTML string. Skip the innerHTML swap and let the map+ // module restyle itself from state (syncBrainMap below).+ const mapEl = document.querySelector('[data-sb-map]');+ if (mapEl && mapEl.hasAttribute('data-sb-map-live')) continue;+ }const el = document.querySelector(`[data-sb-body="${id}"]`);if (el) el.innerHTML = renderPanelBody(id, data);}@@ -504,6 +734,8 @@ function patchPanels() {showUiError();scheduleTraces();flashFlipped();+ ensureMap();+ syncMap();}/** One-shot outline flash on every ledger row whose belief state the@@ -550,11 +782,102 @@ function scheduleTraces() {*/export function sbAfterRender() {scheduleTraces();+ ensureMap();+}++// ----- THE MAP seam -------------------------------------------------+//+// The map lives in ux/brain-map.js (its own slice). This controller+// only (1) loads it, (2) hands it a mount point (`[data-sb-map-mount]`+// drawn by the map panel body), (3) keeps panel patching from eating+// its canvas, and (4) speaks to it through the narrow API below plus+// two document events: `sb:asof-preview` / `sb:asof-commit`+// (detail.ms = epoch-ms | null for NOW). Expected module exports:+// mountBrainMap() idempotent; finds the mount, draws, and sets+// `data-sb-map-live` on [data-sb-map]+// syncBrainMap() restyle from current state after a panel patch++let mapMod; // undefined = not tried · null = not in this build+let mapModLoading = null;++/** The controller calls this from render() while the dashboard is+ * still assembling HTML strings — the mount point may not be in the+ * DOM yet. Without a post-paint retry the first (often only) data-+ * carrying render never mounts the map: ensureMapNow bails on the+ * missing mount, nothing re-arms it, and the panel shows its waiting+ * placeholder forever (live-caught on the 19k-link `repo` brain,+ * 2026-07-30). Same rAF pattern mountBrainMap uses for its own+ * pre-commit calls. */+let ensureMapRaf = 0;+function ensureMap() {+ if (typeof document === 'undefined') return;+ if (typeof requestAnimationFrame !== 'undefined' && !ensureMapRaf) {+ ensureMapRaf = requestAnimationFrame(() => { ensureMapRaf = 0; ensureMapNow(); });+ }+ ensureMapNow();+}++function ensureMapNow() {+ if (!document.querySelector('[data-sb-map-mount]')) return;+ if (mapMod === null) { markMapMissing(); return; }+ if (mapMod) { try { mapMod.mountBrainMap && mapMod.mountBrainMap(); } catch { /* map draws best-effort */ } return; }+ if (!mapModLoading) {+ mapModLoading = import('../ux/brain-map.js')+ .then((m) => { mapMod = m; ensureMap(); })+ .catch(() => { mapMod = null; markMapMissing(); });+ }+}++/** No ux/brain-map.js in this build: say so — never a spinner that+ * promises a map that cannot arrive. */+function markMapMissing() {+ const el = document.querySelector('[data-sb-map-mount]');+ if (el && el.querySelector('[data-sb-map-waiting]')) {+ el.innerHTML = '<div class="panel-empty mono faint">THE MAP IS NOT IN THIS BUILD · THE LEDGER BELOW SHOWS EVERY LINK</div>';+ }+}++function syncMap() {+ if (mapMod && mapMod.syncBrainMap) {+ try { mapMod.syncBrainMap(); } catch { /* the map never takes the page down */ }+ }+}++/** Map → ledger routing: every terminal click on the map lands in the+ * ledger (the leaf view), scrolled into sight. */+export function sbRefocus(id) {+ refocus(id);+ const ego = document.querySelector('[data-sb-body="ego"]');+ if (ego && ego.scrollIntoView) ego.scrollIntoView({ behavior: 'smooth', block: 'start' });+}++/**+ * The map publishes what it actually read and derived so the+ * statistics row can state it: { orphansFloor, orphansIsFloor,+ * edgesFetched, edgesTotal, … } — every field optional, every consumer+ * renders only what is present.+ */+export function sbPublishMapStats(stats) {+ S.mapStats = stats && typeof stats === 'object' ? stats : null;+ if (typeof document === 'undefined') return;+ const data = assemble();+ for (const id of ['notes', 'crossings']) {+ const el = document.querySelector(`[data-sb-body="${id}"]`);+ if (el) el.innerHTML = renderPanelBody(id, data);+ }+}++/** Read-only view state for the map module. */+export function sbSnapshot() {+ return {+ baseUrl: S.baseUrl, brain: S.brain, focus: S.focus, asOf: S.asOf,+ overview: S.overview, names: S.names,+ };}// ----- interaction ops -----------------------------------------------async function refetch({ overview = false, belief = false, timeline = false }) {+async function refetch({ overview = false, belief = false, timeline = false, stats = false }) {abortInflight();inflight = typeof AbortController !== 'undefined' ? new AbortController() : null;const signal = inflight && inflight.signal;@@ -562,10 +885,24 @@ async function refetch({ overview = false, belief = false, timeline = false }) {S.uiError = null;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+ const ovJob = overview+ ? fetchOverview(signal).then((r) => { S.overview = r; S.overviewError = null; })+ : null;+ if (ovJob) jobs.push(ovJob, fetchRecentRetired(signal)); // retired rides along; never throwsif (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; }));+ if (stats) {+ // Truth-now tallies (notes, crossings, server counters):+ // refreshed on brain switch / retry, deliberately NOT on every+ // as-of commit — they are statements about the record, not about+ // the caret. They need the overview's index names, so they wait+ // for it when one is in flight (and stand down if it failed —+ // the error state owns the page then).+ const run = () => Promise.all([+ fetchNodeStats(signal), fetchCrossings(signal), fetchServerReads(signal),+ ]);+ jobs.push(ovJob ? ovJob.then(run, () => {}) : run());+ }await Promise.all(jobs);await hydrateNames(signal);} catch (e) {@@ -593,6 +930,12 @@ function refocus(id) {// time-travel readout belong to the note that had them.S.openEvidence = new Set();S.lastShift = null;+ // Announce the change for any in-page listener. (The map does NOT+ // subscribe today — it re-reads focus via sbSnapshot on the sync+ // that follows patchPanels; this event is a seam, not a claim.)+ if (typeof document !== 'undefined') {+ document.dispatchEvent(new CustomEvent('sb:refocus', { detail: { id } }));+ }writeMoment();patchPanels(); // immediate: focus card swaps to the new node idrefetch({ belief: true, timeline: true });@@ -604,11 +947,13 @@ function switchBrain(name) {S.brain = name;S.overview = null; S.ego = null; S.timeline = null;S.recentRetired = null; S.openEvidence = new Set(); S.lastShift = null;+ // Another brain is another record: its tallies and its map stats.+ S.nodeStats = null; S.crossings = null; S.mapStats = null;loadBrainState();writeMoment();patchPanels();(async () => {- await refetch({ overview: true });+ await refetch({ overview: true, stats: true });if (!S.focus) S.focus = defaultFocus();if (S.focus) await refetch({ belief: true, timeline: true });})();@@ -651,6 +996,11 @@ function computeShift(prevMs, nextMs) {function commitAsOf(ms) {S.lastShift = computeShift(S.asOf, ms);S.asOf = ms;+ // One caret, whole page: the map restyles its live/retired states+ // from the same commit the ledger re-queries on.+ if (typeof document !== 'undefined') {+ document.dispatchEvent(new CustomEvent('sb:asof-commit', { detail: { ms } }));+ }writeMoment();refetch({ overview: true, belief: true });}@@ -714,6 +1064,8 @@ function previewAsOf(scrub, ms) {label.classList.toggle('sb-cl-right', caretAlignClass(lp) === 'sb-cl-right');}const t = atNow ? null : ms;+ // Mid-drag, the map previews the same moment the ledger rows do.+ document.dispatchEvent(new CustomEvent('sb:asof-preview', { detail: { ms: t } }));const counter = scrub.querySelector('[data-sb-livecount]');const steps = scrub.getAttribute('data-sb-steps');if (steps) {@@ -837,7 +1189,7 @@ function onClick(e) {if (t.closest('[data-sb-now]')) { commitAsOf(null); return; }if (t.closest('[data-sb-retry]')) {- refetch({ overview: true, belief: true, timeline: true });+ refetch({ overview: true, belief: true, timeline: true, stats: true });return;}@@ -950,6 +1302,7 @@ async function runFind(q) {if (!o || o.exists === false || !o.nodes_index) return;const seq = ++findSeq;try {+ logRead('notes index', `one text search “${q.slice(0, 24)}${q.length > 24 ? '…' : ''}”`, 'you typed in FIND');const r = await fetch(`${S.baseUrl}/${enc(o.nodes_index)}/_search`, {method: 'POST',headers: { 'content-type': 'application/json' },diff --git a/xerj-ux/src/ux/brain-map-pipeline.js b/xerj-ux/src/ux/brain-map-pipeline.jsnew file mode 100644index 000000000..0c26762bf--- /dev/null+++ b/xerj-ux/src/ux/brain-map-pipeline.js@@ -0,0 +1,636 @@+// ============================================================+// XERJ.ai — SECOND BRAIN · THE MAP — pipeline (pure, deterministic)+//+// Turns a weight-ranked bulk fetch of a brain's links into a bounded+// picture: intern → contract reading-order chains → connected+// components → pinned-order weighted label propagation → rank. The+// output is ≤ MAP_TOP_CLUSTERS named groups + one "everything else"+// body — the node count on screen is bounded BY CONSTRUCTION, never by+// corpus luck.+//+// Determinism is a product requirement (the same brain must always+// draw the same picture):+// - every stage's processing order is pinned (degree desc, interned+// id asc — never hash-map iteration order);+// - the only randomness is init jitter from mulberry32 seeded by the+// brain's name;+// - layout is a fixed 300-iteration relaxation run synchronously at+// build time — a pure function of the link set, frozen after.+// There is NO live simulation anywhere.+//+// This module is pure (no DOM, no fetch) so it runs headless under+// node for verification. The canvas view lives in brain-map.js.+// ============================================================++// ----- normative constants (the design brief, §2.1) -----------------++export const MAP_PAGE = 5_000; // per _search page+export const MAP_EDGE_BUDGET = 50_000; // hard cap — 10 pages max+export const MAP_TOP_CLUSTERS = 12; // + 1 "everything else" = ≤ 13+export const MAP_SMALL_DIRECT = 40; // ≤ this many file-nodes → no clustering+export const MAP_EXPAND_CAP = 150; // members drawn on expand+export const MAP_PERCOLATION_MAX = 0.35; // cluster > 35% of component → re-split+export const MAP_LPA_SWEEPS = 10;+export const MAP_LAYOUT_ITERS = 300;++// ----- seeded rng ---------------------------------------------------++/** FNV-1a over a string → uint32 seed. */+export function hashStr(s) {+ let h = 0x811c9dc5;+ const str = String(s || '');+ for (let i = 0; i < str.length; i++) {+ h ^= str.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return h >>> 0;+}++/** mulberry32 — tiny deterministic PRNG. */+export function mulberry32(seed) {+ let a = seed >>> 0;+ return function () {+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++// ----- stage 0: intern ----------------------------------------------++/**+ * Raw fetched links → dense typed arrays. Input order (weight desc,+ * link id asc — the server sort) is the interning order, so the same+ * fetch always produces the same dense ids.+ *+ * rows: [{ id, src, dst, type, weight, validAt, invalidAt|null, srcFile }]+ */+export function internEdges(rows) {+ const idOf = new Map();+ const ids = [];+ const intern = (s) => {+ let i = idOf.get(s);+ if (i === undefined) { i = ids.length; ids.push(s); idOf.set(s, i); }+ return i;+ };+ const n = rows.length;+ const srcI = new Uint32Array(n);+ const dstI = new Uint32Array(n);+ const weight = new Float32Array(n);+ const typeOrd = new Uint8Array(n);+ const validAt = new Float64Array(n);+ const invalidAt = new Float64Array(n); // NaN = still believed+ const edgeIds = new Array(n);+ const srcFile = new Array(n);+ const typeNames = [];+ const typeIdx = new Map();+ for (let i = 0; i < n; i++) {+ const r = rows[i];+ srcI[i] = intern(r.src);+ dstI[i] = intern(r.dst);+ weight[i] = Number.isFinite(r.weight) ? r.weight : 1;+ let t = typeIdx.get(r.type);+ if (t === undefined) { t = typeNames.length; typeNames.push(String(r.type || 'link')); typeIdx.set(r.type, t); }+ typeOrd[i] = t;+ validAt[i] = Number(r.validAt) || 0;+ invalidAt[i] = r.invalidAt == null ? NaN : Number(r.invalidAt);+ edgeIds[i] = r.id;+ srcFile[i] = r.srcFile || '';+ }+ return { n, ids, srcI, dstI, weight, typeOrd, typeNames, validAt, invalidAt, edgeIds, srcFile };+}++/** 'live' | 'expired' | 'future' for interned edge i at as-of t. */+export function edgeStateAtI(g, i, t) {+ const at = t == null ? Date.now() : t;+ if (g.validAt[i] > at) return 'future';+ const inv = g.invalidAt[i];+ if (!Number.isNaN(inv) && inv <= at) return 'expired';+ return 'live';+}++// ----- union-find (union-by-min-root — deterministic) ---------------++function ufMake(n) { const p = new Int32Array(n); for (let i = 0; i < n; i++) p[i] = i; return p; }+function ufFind(p, x) {+ let r = x;+ while (p[r] !== r) r = p[r];+ while (p[x] !== r) { const nx = p[x]; p[x] = r; x = nx; }+ return r;+}+function ufUnion(p, a, b) {+ const ra = ufFind(p, a); const rb = ufFind(p, b);+ if (ra === rb) return;+ if (ra < rb) p[rb] = ra; else p[ra] = rb;+}++// ----- stage 1: contract reading-order chains -----------------------++/**+ * Sections of one document are one document: union over `sequence`+ * links only, then remap every link onto file-nodes. Parallel links+ * between the same file pair merge (summed weight, per-kind counts,+ * constituent list kept for the bundle inspector). Links inside one+ * document leave the picture but are counted.+ */+export function contractSequence(g) {+ const seqOrd = g.typeNames.indexOf('sequence');+ const p = ufMake(g.ids.length);+ if (seqOrd >= 0) {+ for (let i = 0; i < g.n; i++) {+ if (g.typeOrd[i] === seqOrd) ufUnion(p, g.srcI[i], g.dstI[i]);+ }+ }+ // Dense file ids in root order (root = min member ⇒ deterministic).+ const fileOfRoot = new Map();+ const fileOf = new Int32Array(g.ids.length);+ const fileRep = []; // representative ORIGINAL interned id per file-node+ const fileSize = []; // notes (original nodes) per file-node+ for (let v = 0; v < g.ids.length; v++) {+ const r = ufFind(p, v);+ let f = fileOfRoot.get(r);+ if (f === undefined) { f = fileRep.length; fileOfRoot.set(r, f); fileRep.push(r); fileSize.push(0); }+ fileOf[v] = f;+ fileSize[f] += 1;+ }+ const F = fileRep.length;+ // Merge parallel links between file pairs (undirected).+ const pairIdx = new Map(); // key a*F+b (a<b) → merged idx+ const fa = []; const fb = []; const fWeight = []; const fCount = [];+ const fKind = []; // per merged edge: Map(typeOrd → count) — insertion order deterministic+ const fEdges = []; // constituent original edge indices+ let selfLoops = 0;+ for (let i = 0; i < g.n; i++) {+ if (seqOrd >= 0 && g.typeOrd[i] === seqOrd) {+ // Contracted away — but COUNTED: every reading-order link lives+ // inside one document by construction, and the "links inside+ // single documents" honesty row must reconcile with the fetch+ // total (fetched = Σ merged-link constituents + selfLoops).+ selfLoops += 1;+ continue;+ }+ let a = fileOf[g.srcI[i]]; let b = fileOf[g.dstI[i]];+ if (a === b) { selfLoops += 1; continue; }+ if (a > b) { const t = a; a = b; b = t; }+ const key = a * F + b;+ let m = pairIdx.get(key);+ if (m === undefined) {+ m = fa.length;+ pairIdx.set(key, m);+ fa.push(a); fb.push(b); fWeight.push(0); fCount.push(0);+ fKind.push(new Map()); fEdges.push([]);+ }+ fWeight[m] += g.weight[i];+ fCount[m] += 1;+ fKind[m].set(g.typeOrd[i], (fKind[m].get(g.typeOrd[i]) || 0) + 1);+ fEdges[m].push(i);+ }+ return { F, fileOf, fileRep, fileSize, fa, fb, fWeight, fCount, fKind, fEdges, selfLoops, seqOrd };+}++// ----- stage 2: connected components --------------------------------++export function components(fg) {+ const p = ufMake(fg.F);+ for (let m = 0; m < fg.fa.length; m++) ufUnion(p, fg.fa[m], fg.fb[m]);+ const compOf = new Int32Array(fg.F);+ const sizeOfRoot = new Map();+ for (let f = 0; f < fg.F; f++) {+ const r = ufFind(p, f);+ compOf[f] = r;+ sizeOfRoot.set(r, (sizeOfRoot.get(r) || 0) + 1);+ }+ return { compOf, sizeOfRoot };+}++// ----- CSR adjacency over merged file edges -------------------------++function buildCsr(fg, edgeKeep) {+ const F = fg.F;+ const deg = new Uint32Array(F);+ const M = fg.fa.length;+ for (let m = 0; m < M; m++) {+ if (edgeKeep && !edgeKeep(m)) continue;+ deg[fg.fa[m]] += 1; deg[fg.fb[m]] += 1;+ }+ const off = new Uint32Array(F + 1);+ for (let f = 0; f < F; f++) off[f + 1] = off[f] + deg[f];+ const nbr = new Uint32Array(off[F]);+ const nbrW = new Float64Array(off[F]);+ const cursor = off.slice(0, F);+ for (let m = 0; m < M; m++) {+ if (edgeKeep && !edgeKeep(m)) continue;+ const a = fg.fa[m]; const b = fg.fb[m]; const w = fg.fWeight[m];+ nbr[cursor[a]] = b; nbrW[cursor[a]] = w; cursor[a] += 1;+ nbr[cursor[b]] = a; nbrW[cursor[b]] = w; cursor[b] += 1;+ }+ return { off, nbr, nbrW, deg };+}++// ----- stage 3: pinned-order weighted label propagation -------------++/**+ * Per component of ≥ 3 file-nodes. Labels init to self; nodes+ * processed in (degree desc, id asc) order; each node adopts the+ * neighbour label with the largest incident weight, ties → smallest+ * label; ≤ MAP_LPA_SWEEPS sweeps or < 0.5% churn. The detector weight+ * ladder (authored links weigh 2–3× folder adjacency) makes citations+ * dominate community formation without any semantic claim.+ *+ * Percolation guard: a cluster > MAP_PERCOLATION_MAX of its component+ * re-runs once with folder-neighbour-only links excluded; nodes losing+ * every incident link keep their parent label; if the giant survives+ * that, it is accepted — some corpora genuinely have one big topic and+ * faking a split would be a lie.+ */+export function labelProp(fg, comps) {+ const F = fg.F;+ const run = (edgeKeep, initLabels) => {+ const csr = buildCsr(fg, edgeKeep);+ const labels = initLabels ? initLabels.slice() : (() => { const l = new Int32Array(F); for (let f = 0; f < F; f++) l[f] = f; return l; })();+ const order = [];+ for (let f = 0; f < F; f++) order.push(f);+ order.sort((a, b) => (csr.deg[b] - csr.deg[a]) || (a - b));+ const tally = new Float64Array(F);+ const touched = [];+ for (let sweep = 0; sweep < MAP_LPA_SWEEPS; sweep++) {+ let churn = 0;+ for (const f of order) {+ const s = csr.off[f]; const e = csr.off[f + 1];+ if (s === e) continue; // no incident links → keeps its label+ for (let k = s; k < e; k++) {+ const lab = labels[csr.nbr[k]];+ if (tally[lab] === 0) touched.push(lab);+ tally[lab] += csr.nbrW[k];+ }+ let best = labels[f]; let bestW = tally[best] || 0;+ for (const lab of touched) {+ const w = tally[lab];+ if (w > bestW || (w === bestW && lab < best)) { best = lab; bestW = w; }+ }+ for (const lab of touched) tally[lab] = 0;+ touched.length = 0;+ if (best !== labels[f]) { labels[f] = best; churn += 1; }+ }+ if (churn / Math.max(1, F) < 0.005) break;+ }+ return labels;+ };++ let labels = run(null, null);++ // Percolation guard per component.+ const compSize = comps.sizeOfRoot;+ const clusterSize = new Map();+ for (let f = 0; f < F; f++) {+ const key = `${comps.compOf[f]}:${labels[f]}`;+ clusterSize.set(key, (clusterSize.get(key) || 0) + 1);+ }+ let needResplit = false;+ for (const [key, size] of clusterSize) {+ const comp = Number(key.split(':')[0]);+ const cs = compSize.get(comp) || 1;+ if (cs >= 3 && size / cs > MAP_PERCOLATION_MAX && size > 3) { needResplit = true; break; }+ }+ if (needResplit) {+ // Exclude merged links that are ONLY folder adjacency (same_dir).+ // A merged link keeping any authored/sequence-adjacent weight stays.+ const sameDirOnly = (m) => {+ const kinds = fg.fKind[m];+ if (kinds.size !== 1) return false;+ const [ord] = kinds.keys();+ return fg.typeNamesRef ? fg.typeNamesRef[ord] === 'same_dir' : false;+ };+ labels = run((m) => !sameDirOnly(m), labels);+ }+ return labels;+}++// ----- stage 4+5: rank + name inputs --------------------------------++/**+ * Clusters ranked by Σ weight of internal links live at `asOf`. Top+ * MAP_TOP_CLUSTERS become bodies; the rest — plus components < 3+ * file-nodes — pool into "everything else". Naming stays honest: a+ * cluster is labelled by its dominant folder prefix when ≥ 60% of its+ * links come from one, else by its busiest member's title (hydrated+ * by the caller — this stage only nominates the id).+ */+export function rankClusters(g, fg, comps, labels, asOf) {+ const F = fg.F;+ // Group file-nodes: key = component root + label; pool small comps.+ const groups = new Map(); // key → { files: [] }+ for (let f = 0; f < F; f++) {+ const comp = comps.compOf[f];+ const cs = comps.sizeOfRoot.get(comp) || 1;+ const key = cs < 3 ? '__else' : `${comp}:${labels[f]}`;+ let grp = groups.get(key);+ if (!grp) { grp = { key, files: [] }; groups.set(key, grp); }+ grp.files.push(f);+ }+ // Cluster of each file for internal/external classification (prelim).+ const groupOf = new Int32Array(F).fill(-1);+ const groupList = [...groups.values()];+ groupList.forEach((grp, gi) => { for (const f of grp.files) groupOf[f] = gi; });++ // Internal live-weight score per group + link counts, over ORIGINAL+ // links (excluding contracted reading-order ones).+ const score = new Float64Array(groupList.length);+ const linkTotal = new Uint32Array(groupList.length);+ const linkLive = new Uint32Array(groupList.length);+ for (let m = 0; m < fg.fa.length; m++) {+ const ga = groupOf[fg.fa[m]]; const gb = groupOf[fg.fb[m]];+ if (ga !== gb) continue;+ for (const i of fg.fEdges[m]) {+ linkTotal[ga] += 1;+ if (edgeStateAtI(g, i, asOf) === 'live') { linkLive[ga] += 1; score[ga] += g.weight[i]; }+ }+ }++ // Rank: score desc, then smallest member file id asc (stable).+ const order = groupList.map((grp, gi) => gi)+ .filter((gi) => groupList[gi].key !== '__else')+ .sort((a, b) => (score[b] - score[a]) || (Math.min(...groupList[a].files) - Math.min(...groupList[b].files)));++ const top = order.slice(0, MAP_TOP_CLUSTERS);+ const pooled = order.slice(MAP_TOP_CLUSTERS);+ const elseGi = groupList.findIndex((grp) => grp.key === '__else');++ // Build final clusters: 0..k-1 real, k = "everything else" (if any).+ const clusters = [];+ const clusterOfFile = new Int32Array(F).fill(-1);+ for (const gi of top) {+ const files = groupList[gi].files.slice().sort((a, b) => a - b);+ const ci = clusters.length;+ for (const f of files) clusterOfFile[f] = ci;+ clusters.push({+ files, isElse: false,+ score: score[gi], linkTotal: linkTotal[gi], linkLive: linkLive[gi],+ noteCount: files.reduce((acc, f) => acc + fg.fileSize[f], 0),+ });+ }+ const elseFiles = [];+ for (const gi of pooled) elseFiles.push(...groupList[gi].files);+ if (elseGi >= 0) elseFiles.push(...groupList[elseGi].files);+ if (elseFiles.length) {+ elseFiles.sort((a, b) => a - b);+ const ci = clusters.length;+ for (const f of elseFiles) clusterOfFile[f] = ci;+ // Count internal links of the pooled body (recompute over membership).+ let lt = 0; let ll = 0; let sc = 0;+ for (let m = 0; m < fg.fa.length; m++) {+ if (clusterOfFile[fg.fa[m]] !== ci || clusterOfFile[fg.fb[m]] !== ci) continue;+ for (const i of fg.fEdges[m]) {+ lt += 1;+ if (edgeStateAtI(g, i, asOf) === 'live') { ll += 1; sc += g.weight[i]; }+ }+ }+ clusters.push({+ files: elseFiles, isElse: true,+ score: sc, linkTotal: lt, linkLive: ll,+ noteCount: elseFiles.reduce((acc, f) => acc + fg.fileSize[f], 0),+ });+ }++ // Naming inputs per cluster.+ for (let ci = 0; ci < clusters.length; ci++) {+ const c = clusters[ci];+ // Dominant folder over internal links' source files: the DEEPEST+ // directory prefix that still covers ≥ 60% of them. Depth matters —+ // on a corpus that lives entirely under one root, the first path+ // segment names every cluster identically and says nothing.+ const prefixCount = new Map(); // 'a/b' → count; '' = top level+ let total = 0;+ for (let m = 0; m < fg.fa.length; m++) {+ const ca = clusterOfFile[fg.fa[m]]; const cb = clusterOfFile[fg.fb[m]];+ if (ca !== ci || cb !== ci) continue;+ for (const i of fg.fEdges[m]) {+ const sf = g.srcFile[i];+ const segs = sf.split('/');+ segs.pop(); // filename off+ for (let d = 0; d <= segs.length; d++) {+ const p = segs.slice(0, d).join('/');+ prefixCount.set(p, (prefixCount.get(p) || 0) + 1);+ }+ total += 1;+ }+ }+ let bestDir = null; let bestDepth = -1;+ for (const [p, cnt] of prefixCount) {+ if (total === 0 || cnt / total < 0.6) continue;+ const depth = p === '' ? 0 : p.split('/').length;+ if (depth > bestDepth || (depth === bestDepth && bestDir != null && p < bestDir)) {+ bestDir = p; bestDepth = depth;+ }+ }+ c.dirLabel = bestDir == null ? null : (bestDir === '' ? '(top level)' : `${bestDir}/`);+ // Busiest member (live merged degree desc, id asc) → hub nominee.+ const degLive = new Map();+ for (let m = 0; m < fg.fa.length; m++) {+ let live = 0;+ for (const i of fg.fEdges[m]) if (edgeStateAtI(g, i, asOf) === 'live') live += 1;+ if (!live) continue;+ degLive.set(fg.fa[m], (degLive.get(fg.fa[m]) || 0) + live);+ degLive.set(fg.fb[m], (degLive.get(fg.fb[m]) || 0) + live);+ }+ c.hubFile = c.files.slice().sort((a, b) => ((degLive.get(b) || 0) - (degLive.get(a) || 0)) || (a - b))[0];+ c.degLive = degLive; // reused for member ordering on expand+ }++ // Two clusters can honestly share a folder name (both ≥ 60% inside+ // engine/, no deeper prefix dominant) — mark the duplicates so the+ // view can add each one's busiest note and the reader can tell them+ // apart (live-seen on the repo brain: engine/ ×2, (top level) ×2).+ const labelCount = new Map();+ for (const c of clusters) if (c.dirLabel) labelCount.set(c.dirLabel, (labelCount.get(c.dirLabel) || 0) + 1);+ for (const c of clusters) c.dirDupe = !!(c.dirLabel && labelCount.get(c.dirLabel) > 1);++ return { clusters, clusterOfFile };+}++// ----- bundles between bodies ---------------------------------------++/** Aggregate merged file links crossing cluster boundaries into ≤+ * C·(C−1)/2 bundles (78 worst case at 13 bodies). */+export function buildBundles(fg, clusterOfFile, nClusters) {+ const idx = new Map();+ const bundles = [];+ for (let m = 0; m < fg.fa.length; m++) {+ let a = clusterOfFile[fg.fa[m]]; let b = clusterOfFile[fg.fb[m]];+ if (a < 0 || b < 0 || a === b) continue;+ if (a > b) { const t = a; a = b; b = t; }+ const key = a * nClusters + b;+ let bi = idx.get(key);+ if (bi === undefined) {+ bi = bundles.length;+ idx.set(key, bi);+ bundles.push({ a, b, count: 0, weight: 0, merged: [] });+ }+ const bu = bundles[bi];+ bu.count += fg.fCount[m];+ bu.weight += fg.fWeight[m];+ bu.merged.push(m);+ }+ return bundles;+}++/** Live constituent count of a bundle at as-of. */+export function bundleLiveAt(g, fg, bundle, asOf) {+ let live = 0;+ for (const m of bundle.merged) {+ for (const i of fg.fEdges[m]) if (edgeStateAtI(g, i, asOf) === 'live') live += 1;+ }+ return live;+}++// ----- layout: seeded relaxation (NOT a live simulation) ------------++/**+ * Place `nb` bodies in the unit square: init on a circle in rank+ * order + seeded jitter, then exactly MAP_LAYOUT_ITERS iterations of+ * Fruchterman–Reingold arithmetic, run synchronously, output frozen.+ * A pure function of (edges, seed): same brain → same picture.+ */+export function relaxLayout(nb, links, seedStr) {+ const rng = mulberry32(hashStr(seedStr));+ const px = new Float64Array(nb);+ const py = new Float64Array(nb);+ const R = 0.35;+ for (let i = 0; i < nb; i++) {+ const th = (i / Math.max(1, nb)) * 2 * Math.PI - Math.PI / 2;+ px[i] = 0.5 + R * Math.cos(th) + (rng() - 0.5) * 0.02;+ py[i] = 0.5 + R * Math.sin(th) + (rng() - 0.5) * 0.02;+ }+ if (nb <= 1) return { px, py };+ const k = Math.sqrt(1 / nb) * 0.9;+ const maxW = links.reduce((a, l) => Math.max(a, l.w), 0) || 1;+ const dx = new Float64Array(nb);+ const dy = new Float64Array(nb);+ for (let iter = 0; iter < MAP_LAYOUT_ITERS; iter++) {+ dx.fill(0); dy.fill(0);+ for (let i = 0; i < nb; i++) {+ for (let j = i + 1; j < nb; j++) {+ let ddx = px[i] - px[j]; let ddy = py[i] - py[j];+ let d2 = ddx * ddx + ddy * ddy;+ if (d2 < 1e-8) { ddx = 1e-4 * ((i + 1) % 3 - 1); ddy = 1e-4; d2 = ddx * ddx + ddy * ddy; }+ const rep = (k * k) / d2;+ dx[i] += ddx * rep; dy[i] += ddy * rep;+ dx[j] -= ddx * rep; dy[j] -= ddy * rep;+ }+ }+ for (const l of links) {+ const ddx = px[l.a] - px[l.b]; const ddy = py[l.a] - py[l.b];+ const d = Math.sqrt(ddx * ddx + ddy * ddy) || 1e-6;+ const att = (d * d / k) * (0.3 + 0.7 * (l.w / maxW));+ const ux = (ddx / d) * att; const uy = (ddy / d) * att;+ dx[l.a] -= ux; dy[l.a] -= uy;+ dx[l.b] += ux; dy[l.b] += uy;+ }+ // Center gravity: sparsely-bundled bodies must drift inward, not+ // pin to the walls — without it pure repulsion shoves every+ // disconnected body into the clamp corners. Factor swept on the+ // repo's own docs/ brain (13 bodies, 5 bundles): 10k → 0 of 13+ // wall-pinned, min pair distance 0.21 of the unit square.+ // (Gravity swept again after the post-layout spread rescale landed:+ // 10k crushed 13 cross-linked bodies into a third of the frame; 4k+ // keeps disconnected bodies off the walls — the rescale below now+ // guarantees frame fill — while letting linked bodies breathe.)+ for (let i = 0; i < nb; i++) {+ dx[i] -= (px[i] - 0.5) * k * 4;+ dy[i] -= (py[i] - 0.5) * k * 4;+ }+ const temp = 0.1 * (1 - iter / MAP_LAYOUT_ITERS) + 0.002;+ for (let i = 0; i < nb; i++) {+ const d = Math.sqrt(dx[i] * dx[i] + dy[i] * dy[i]) || 1e-9;+ const step = Math.min(d, temp);+ px[i] += (dx[i] / d) * step;+ py[i] += (dy[i] / d) * step;+ px[i] = Math.max(0.03, Math.min(0.97, px[i]));+ py[i] = Math.max(0.03, Math.min(0.97, py[i]));+ }+ }+ // Fill the frame: the center gravity that keeps disconnected bodies+ // off the walls also compresses the finished picture into the middle+ // of the unit square (live-seen on the 19k-link repo brain — 13+ // bodies crowded into ~a third of the canvas). Affine per-axis+ // spread, capped at 3× so a genuinely tight pair is not flung to the+ // corners. Pure arithmetic on the frozen positions — determinism+ // holds: same positions in, same positions out.+ let xmin = Infinity; let xmax = -Infinity; let ymin = Infinity; let ymax = -Infinity;+ for (let i = 0; i < nb; i++) {+ xmin = Math.min(xmin, px[i]); xmax = Math.max(xmax, px[i]);+ ymin = Math.min(ymin, py[i]); ymax = Math.max(ymax, py[i]);+ }+ const target = 0.88; // world span between the 0.06 margins+ const fx = xmax - xmin > 1e-6 ? Math.min(target / (xmax - xmin), 3) : 0;+ const fy = ymax - ymin > 1e-6 ? Math.min(target / (ymax - ymin), 3) : 0;+ const cx0 = (xmin + xmax) / 2; const cy0 = (ymin + ymax) / 2;+ for (let i = 0; i < nb; i++) {+ px[i] = 0.5 + (fx ? (px[i] - cx0) * fx : 0);+ py[i] = 0.5 + (fy ? (py[i] - cy0) * fy : 0);+ }+ return { px, py };+}++/** Golden-angle spiral: member slot i around a frozen centroid.+ * O(n), zero iterations, zero occlusion, deterministic. */+export function phyllotaxis(i, cx, cy, c) {+ const th = i * 137.507 * (Math.PI / 180);+ const r = c * Math.sqrt(i);+ return [cx + r * Math.cos(th), cy + r * Math.sin(th)];+}++// ----- the whole pipeline -------------------------------------------++/**+ * rows (fetched, weight-desc) + brainName + asOf → the frozen model.+ * mode 'direct' (≤ MAP_SMALL_DIRECT file-nodes: the real graph, named+ * per file) or 'clustered' (≤ 13 bodies).+ */+export function buildMap(rows, { brainName, asOf = null } = {}) {+ const g = internEdges(rows);+ const fg = contractSequence(g);+ fg.typeNamesRef = g.typeNames; // for the percolation guard's same_dir test+ const distinctNotes = g.ids.length;++ if (fg.F <= MAP_SMALL_DIRECT) {+ // Small corpus: no clustering theatre — the real file graph.+ const links = fg.fa.map((a, m) => ({ a, b: fg.fb[m], w: fg.fWeight[m] }));+ const { px, py } = relaxLayout(fg.F, links, brainName);+ return { mode: 'direct', g, fg, distinctNotes, px, py };+ }++ const comps = components(fg);+ const labels = labelProp(fg, comps);+ const { clusters, clusterOfFile } = rankClusters(g, fg, comps, labels, asOf);+ const bundles = buildBundles(fg, clusterOfFile, clusters.length);+ const links = bundles.map((bu) => ({ a: bu.a, b: bu.b, w: bu.weight }));+ const { px, py } = relaxLayout(clusters.length, links, brainName);+ return { mode: 'clustered', g, fg, distinctNotes, clusters, clusterOfFile, bundles, px, py };+}++/** Recompute the as-of-dependent numbers (scores, live counts) after a+ * belief-time commit. Membership and layout NEVER change here. */+export function restateAt(model, asOf) {+ if (model.mode !== 'clustered') return;+ const { g, fg, clusters, clusterOfFile } = model;+ for (const c of clusters) { c.linkLive = 0; c.score = 0; }+ for (let m = 0; m < fg.fa.length; m++) {+ const ca = clusterOfFile[fg.fa[m]]; const cb = clusterOfFile[fg.fb[m]];+ if (ca < 0 || ca !== cb) continue;+ for (const i of fg.fEdges[m]) {+ if (edgeStateAtI(g, i, asOf) === 'live') {+ clusters[ca].linkLive += 1;+ clusters[ca].score += g.weight[i];+ }+ }+ }+}++/** Members of a cluster in draw order (live merged degree desc, file+ * id asc), capped by MAP_EXPAND_CAP by the caller. */+export function memberOrder(cluster) {+ const deg = cluster.degLive || new Map();+ return cluster.files.slice().sort((a, b) => ((deg.get(b) || 0) - (deg.get(a) || 0)) || (a - b));+}diff --git a/xerj-ux/src/ux/brain-map.js b/xerj-ux/src/ux/brain-map.jsnew file mode 100644index 000000000..07494998c--- /dev/null+++ b/xerj-ux/src/ux/brain-map.js@@ -0,0 +1,1475 @@+// ============================================================+// XERJ.ai — SECOND BRAIN · THE MAP — canvas view + controller+//+// The all-in-one picture above the ego ledger. The ledger's anti-+// hairball rationale (ego-ledger.js header) is answered, not ignored:+//+// - node count is bounded BY CONSTRUCTION (≤ 13 grouped bodies at+// helicopter altitude; worst case ever drawn = 13 bodies + 150+// expanded members + 1 satellite), never by corpus luck;+// - there is NO live simulation: layout is a frozen pure function of+// the link set (brain-map-pipeline.js), same brain → same picture;+// - the map is a navigation instrument: every terminal click lands+// in the ledger below, which stays the only evidence surface.+//+// Altitudes: helicopter (grouped bodies) → ONE expanded group at a+// time (golden-angle spiral of members) → the ledger (leaf). Depth+// beyond that is explored by repeated 2-hop walks — the engine caps+// each walk at 2 hops and this view says so, never pretending+// variable-depth traversal.+//+// SEAM (owned by data/second-brain-api.js, honoured here exactly):+// exports mountBrainMap() — idempotent; draws into+// `[data-sb-map-mount]`, sets `data-sb-map-live`+// syncBrainMap() — restyle from state after a panel patch+// imports sbRefocus / sbLogRead / sbPublishMapStats / sbSnapshot+// hears `sb:asof-preview` / `sb:asof-commit` document events+// (detail.ms = epoch-ms | null for NOW) — ONE belief caret+// drives the whole page.+//+// LANGUAGE RULE: user words only — link / believed / retired / what+// taught this. HONESTY RULE: every cap is stated in place; every+// number on the rail comes from a call this view made and logged.+//+// House chart law: 1px strokes + text only — a grouped body is a TEXT+// BLOCK (name + count line), never a filled bubble.+// ============================================================++import { esc, num } from './text.js';+import { typeName, detectorName, evidenceKind, displayId } from './ego-ledger.js';+import { sbRefocus, sbLogRead, sbPublishMapStats, sbSnapshot } from '../data/second-brain-api.js';+import {+ buildMap, restateAt, memberOrder, bundleLiveAt, phyllotaxis, edgeStateAtI,+ MAP_PAGE, MAP_EDGE_BUDGET, MAP_EXPAND_CAP,+} from './brain-map-pipeline.js';++// Draw caps this view applies on top of the pipeline's (each is said+// on the rail whenever it bites).+const MAP_INTRA_EDGE_DRAW = 600; // member↔member links drawn on expand+const MAP_BUNDLE_INSPECT = 100; // constituent links listed per line+const MAP_SATELLITE_LIST = 100; // satellite members listed in the rail+const MAP_EXPLORE_SEEDS = 64; // starting notes per 2-hop walk (server clamp)++const enc = encodeURIComponent;++// ----- module state -------------------------------------------------++const M = {+ baseUrl: '', brain: null, asOf: null, overview: null,+ status: 'idle', // idle | loading | ready | error+ statusLine: '', error: null,+ gen: 0, // fetch generation guard+ model: null,+ idIndex: null, // note id → interned index+ serverTotal: 0, // hits.total at fetch time (for the budget sentence)+ nodesTotal: null, // note count (overview or own size-0 tally)+ edgeSig: '', // brain + edge counts — reload key+ names: new Map(), // note id → { title, path, format }+ expanded: -1,+ memberDraw: null, // { ci, files, px, py, satellite, satX, satY, total }+ sel: null, // { kind: 'cluster'|'member'|'bundle'|'satellite', ... }+ hover: null,+ cam: { x: 0.5, y: 0.5, s: 1 },+ anim: null,+ spread: 0, // 0 = members folded into the body, 1 = fully spiralled+ previewT: undefined, // mid-drag caret (undefined = none, null = NOW)+ highlightFiles: null, // Set(file idx) from FIND+ highlightMiss: 0, // FIND matches with no links (not on the map)+ explore: null, // { from, hops, reached, reachedFiles, calls, error }+ canvas: null, ctx: null, ro: null,+ drag: null,+ hits: [], // screen-space hit targets, rebuilt every draw+};++// ----- mount + sync (the seam) --------------------------------------++const SHELL = `+ <div class="sb-map-stage" data-sb-map-stage>+ <canvas class="sb-map-canvas" data-sb-map-canvas aria-label="The map — this brain's topics and the links between them, grouped by link structure"></canvas>+ <div class="sb-map-status mono faint" data-sb-map-status>READING THE LINK GRAPH…</div>+ <div class="sb-map-tools mono" data-sb-map-tools>+ <button type="button" class="text-btn" data-sb-map-fit title="Fit the whole map">FIT</button>+ <button type="button" class="text-btn" data-sb-map-collapse hidden title="Fold the open group away">FOLD AWAY</button>+ </div>+ </div>+ <div class="sb-map-rail mono" data-sb-map-rail></div>`;++/** Idempotent: called after every render/patch by the controller.+ * The controller may call this BEFORE a whole-page re-render commits+ * its new DOM (render() builds strings first) — so every call also+ * queues one post-paint re-run, which lands on the final DOM. */+let mountRaf = 0;+export function mountBrainMap() {+ if (typeof document === 'undefined') return;+ if (typeof requestAnimationFrame !== 'undefined' && !mountRaf) {+ mountRaf = requestAnimationFrame(() => { mountRaf = 0; mountNow(); });+ }+ mountNow();+}++function mountNow() {+ const mapEl = document.querySelector('[data-sb-map]');+ const mount = document.querySelector('[data-sb-map-mount]');+ if (!mapEl || !mount) return;+ const snap = sbSnapshot();+ const o = snap.overview && snap.overview.exists !== false ? snap.overview : null;+ const hasEdges = !!(o && o.edges && o.edges.total > 0);+ if (!hasEdges) {+ // The panel body's own honest empty state stays; nothing to mount.+ M.canvas = null;+ mapEl.removeAttribute('data-sb-map-live');+ return;+ }+ if (!mount.querySelector('[data-sb-map-canvas]')) {+ mount.innerHTML = SHELL;+ M.canvas = null; // fresh DOM — remount below+ }+ mapEl.setAttribute('data-sb-map-live', '');+ wireOnce();+ mountCanvas(mount);+ watchFind();+ applySnapshot(snap);+}++/** Restyle from current state after a panel patch (same entry). */+export function syncBrainMap() {+ mountBrainMap();+}++/** Read-only introspection for headless verification (and honest bug+ * reports): what the map believes it has drawn. Never mutates. */+export function sbMapState() {+ return {+ status: M.status,+ error: M.error,+ statusLine: M.statusLine,+ mode: M.model ? M.model.mode : null,+ fileNodes: M.model ? M.model.fg.F : 0,+ clusters: M.model && M.model.clusters ? M.model.clusters.length : 0,+ bundles: M.model && M.model.bundles ? M.model.bundles.length : 0,+ expanded: M.expanded,+ spread: M.spread,+ sel: M.sel ? { kind: M.sel.kind, ci: M.sel.ci, file: M.sel.file, bi: M.sel.bi, rows: M.sel.rows ? M.sel.rows.length : null } : null,+ hits: M.hits.map((h) => ({ kind: h.kind, ci: h.ci, file: h.file, bi: h.bi, x: h.x, y: h.y, w: h.w, h: h.h, seg: h.seg })),+ };+}++function applySnapshot(snap) {+ M.baseUrl = (snap.baseUrl || M.baseUrl || '').replace(/\/+$/, '');+ M.overview = snap.overview && snap.overview.exists !== false ? snap.overview : null;+ const ed = (M.overview && M.overview.edges) || { total: 0, invalidated: 0 };+ const sig = `${snap.brain}|${ed.total}|${ed.invalidated}`;+ const asOfChanged = (snap.asOf ?? null) !== M.asOf;+ M.brain = snap.brain || null;+ M.asOf = snap.asOf ?? null;++ if (sig !== M.edgeSig) {+ M.edgeSig = sig;+ if (ed.total > 0) load();+ return;+ }+ if (M.status === 'ready' && M.model) {+ if (asOfChanged) {+ M.previewT = undefined;+ restateAt(M.model, M.asOf);+ renderRail();+ }+ scheduleDraw();+ } else if (M.status !== 'loading') {+ setStatus(M.status === 'error'+ ? `COULD NOT READ THE LINK GRAPH · ${String(M.error).slice(0, 80)}`+ : M.statusLine);+ renderRail();+ }+}++// ----- one-time wiring ----------------------------------------------++let wired = false;+function wireOnce() {+ if (wired) return;+ wired = true;+ // ONE belief caret drives the whole page: previews restyle the+ // canvas mid-drag; the commit lands via the controller's re-render+ // (patch → syncBrainMap → restateAt) — positions never move.+ document.addEventListener('sb:asof-preview', (e) => {+ if (!M.model || M.status !== 'ready') return;+ M.previewT = e.detail ? e.detail.ms : null;+ scheduleDraw();+ });+ document.addEventListener('sb:asof-commit', () => {+ M.previewT = undefined;+ scheduleDraw();+ });+ document.addEventListener('click', (e) => {+ const t = e.target;+ if (!t || !t.closest) return;+ if (t.closest('[data-sb-map-fit]')) {+ if (M.expanded >= 0) collapseCluster();+ else { animateTo({ x: 0.5, y: 0.5, s: 1 }, M.spread); }+ return;+ }+ if (t.closest('[data-sb-map-collapse]')) { collapseCluster(); return; }+ if (t.closest('[data-sb-map-explore]')) { exploreStep(); return; }+ const open = t.closest('[data-sb-map-open]');+ if (open) sbRefocus(open.getAttribute('data-sb-map-open'));+ });+}++// ----- FIND → map highlight -----------------------------------------+//+// The FIND strip is owned by the controller; its rendered results+// (`[data-sb-findresults]` rows carrying `data-sb-focus` ids) are the+// contract. A childList observer maps every visible hit onto the map+// and dims everything else; clearing FIND clears the light.++const observedSlots = new WeakSet();+function watchFind() {+ if (typeof MutationObserver === 'undefined') return;+ const slot = document.querySelector('[data-sb-findresults]');+ if (!slot || observedSlots.has(slot)) return;+ observedSlots.add(slot);+ const apply = () => {+ const ids = [...slot.querySelectorAll('[data-sb-focus]')]+ .map((b) => b.getAttribute('data-sb-focus')).filter(Boolean);+ highlightNotes(slot.hidden ? [] : ids);+ };+ M.findApply = apply; // re-run after a late model load (see load())+ new MutationObserver(apply).observe(slot, { childList: true, subtree: true, attributes: true, attributeFilter: ['hidden'] });+ apply(); // results rendered before the map mounted still light up+}++function highlightNotes(ids) {+ if (!M.model || M.status !== 'ready') { M.highlightFiles = null; return; }+ if (!ids || !ids.length) {+ if (!M.highlightFiles) return;+ M.highlightFiles = null; M.highlightMiss = 0;+ scheduleDraw(); renderRail();+ return;+ }+ const { fg } = M.model;+ const files = new Set();+ let miss = 0;+ for (const id of ids) {+ const oi = M.idIndex.get(id);+ if (oi === undefined) { miss += 1; continue; }+ files.add(fg.fileOf[oi]);+ }+ M.highlightFiles = files;+ M.highlightMiss = miss;+ scheduleDraw();+ renderRail();+}++// ----- data plumbing ------------------------------------------------++async function fetchEdgePages(gen) {+ const rows = [];+ let after = null;+ let total = 0;+ let totalIsFloor = false;+ let exhausted = false;+ let pages = 0;+ const idx = enc(`.xerj-memory-${M.brain}-edges`);+ while (rows.length < MAP_EDGE_BUDGET) {+ const body = {+ query: { exists: { field: 'src' } },+ sort: [{ weight: 'desc' }, { edge_id: 'asc' }],+ size: Math.min(MAP_PAGE, MAP_EDGE_BUDGET - rows.length),+ _source: ['src', 'dst', 'type', 'weight', 'valid_at', 'invalid_at', 'src_file'],+ };+ if (after) body.search_after = after;+ const r = await fetch(`${M.baseUrl}/${idx}/_search`, {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!r.ok) throw new Error(`link list read failed · HTTP ${r.status}`);+ if (gen !== M.gen) return null; // superseded+ const j = await r.json();+ const hits = (j.hits && j.hits.hits) || [];+ if (!pages) {+ // hits.total may itself be a capped floor ('gte') — treat it as+ // one, never as an exact count (live-verified at 10k links).+ const tot = j.hits && j.hits.total;+ total = (tot && typeof tot === 'object' ? tot.value : tot) || hits.length;+ totalIsFloor = !!(tot && typeof tot === 'object' && tot.relation === 'gte');+ }+ pages += 1;+ for (const h of hits) {+ const s = h._source || {};+ rows.push({+ id: h._id, src: s.src, dst: s.dst, type: s.type, weight: s.weight,+ validAt: s.valid_at, invalidAt: s.invalid_at ?? null, srcFile: s.src_file,+ });+ }+ setStatus(`READING EVERY LINK · PAGE ${pages} · ${num(rows.length)} SO FAR`);+ if (hits.length < MAP_PAGE) { exhausted = true; break; }+ after = hits[hits.length - 1].sort;+ }+ sbLogRead('links index', `${num(rows.length)} links · ${pages} page${pages === 1 ? '' : 's'}, strongest first`, 'building the map');+ // capped = the BUDGET stopped us, not the data. The reported total+ // can undercount (floor); the fetched count is a hard lower bound.+ return {+ rows,+ total: Math.max(total, rows.length),+ totalIsFloor: totalIsFloor || (!exhausted && total <= rows.length),+ capped: !exhausted,+ };+}++/** Bounded ids → titles/paths. Best-effort and honest: an id that+ * resolves nowhere keeps rendering shortened — never guessed. Misses+ * are cached as empty (so the render→hydrate→render chain terminates+ * even on ids the notes index has never heard of). Returns how many+ * ids were newly settled — 0 means a re-render would learn nothing. */+async function hydrateNames(ids, why) {+ const want = [...new Set(ids)].filter((id) => id && !M.names.has(id)).slice(0, 200);+ if (!want.length || !M.overview || !M.overview.nodes_index) return 0;+ try {+ const r = await fetch(`${M.baseUrl}/${enc(M.overview.nodes_index)}/_search`, {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ query: { ids: { values: want } }, size: want.length,+ _source: ['title', 'text', 'body', 'ax_path', 'ax_format', 'path'],+ }),+ });+ if (!r.ok) return 0;+ const j = await r.json();+ for (const h of (j.hits && j.hits.hits) || []) {+ const s = h._source || {};+ const path = typeof s.ax_path === 'string' ? s.ax_path : (typeof s.path === 'string' ? s.path : null);+ let title = typeof s.title === 'string' && s.title.trim() ? s.title.trim()+ : (typeof s.text === 'string' && s.text.trim() ? s.text.trim().slice(0, 60)+ : (typeof s.body === 'string' && s.body.trim() ? s.body.trim().slice(0, 60) : null));+ if (title) title = title.replace(/^#+\s*/, '');+ M.names.set(h._id, { title, path, format: s.ax_format || null });+ }+ // Negative-cache the misses: rendering falls through to the+ // shortened id, and the next hydrate pass is a true no-op.+ for (const id of want) if (!M.names.has(id)) M.names.set(id, { title: null, path: null, format: null });+ sbLogRead('notes index', `${num(want.length)} names`, why);+ return want.length;+ } catch { return 0; /* names are sugar; the ids remain the truth */ }+}++/** Note total: one size-0 tally over the brain's nodes indices — a+ * ran number, never a guess. The map's own count outranks+ * `overview.nodes.total` (fallback only) because the server field is+ * live-verified to return 0 when `nodes_index` is a comma-list+ * (multi-dataset brains), and a false total here would print a false+ * "notes with no links: 0" on two surfaces. */+async function countNotes() {+ const o = M.overview;+ // The overview field is only trusted for single-index brains (it is+ // live-verified to be a false 0 on comma-list brains), and only as a+ // fallback when our own tally cannot run.+ const singleIndex = !!(o && o.nodes_index && !o.nodes_index.includes(','));+ const fallback = singleIndex && o.nodes && Number.isFinite(o.nodes.total) ? o.nodes.total : null;+ if (!o || !o.nodes_index) { M.nodesTotal = fallback; return; }+ try {+ const r = await fetch(`${M.baseUrl}/${enc(o.nodes_index)}/_search`, {+ method: 'POST', headers: { 'content-type': 'application/json' },+ // track_total_hits: without it the engine caps the count at a+ // 10,000 'gte' floor — and a FLOOR minus the linked-note count+ // printed "notes with no links: 0" on a 2.1M-note brain+ // (live-caught on `repo`, 2026-07-30). Exact or nothing.+ body: JSON.stringify({ size: 0, track_total_hits: true }),+ });+ if (!r.ok) { M.nodesTotal = fallback; return; }+ const j = await r.json();+ const t = j.hits && j.hits.total;+ const own = t == null ? null : (typeof t === 'object' ? t.value : t);+ const isFloor = !!(t && typeof t === 'object' && t.relation === 'gte');+ // A floor would understate orphans as far as 0 — refuse it; the+ // rail then says "could not be counted" instead of a false number.+ M.nodesTotal = Number.isFinite(own) && !isFloor ? own : fallback;+ if (M.nodesTotal != null) sbLogRead('notes index', 'one size-0 count', 'counting notes with no links');+ } catch { M.nodesTotal = fallback; }+}++function setStatus(text) {+ M.statusLine = text;+ const el = document.querySelector('[data-sb-map-status]');+ if (el) el.textContent = text;+}++// ----- names for bodies ---------------------------------------------++function fileRepId(f) {+ const { g, fg } = M.model;+ return g.ids[fg.fileRep[f]];+}++function fileLabel(f, max = 22) {+ const meta = M.names.get(fileRepId(f));+ let s;+ if (meta && meta.path) s = meta.path.split('/').pop();+ else if (meta && meta.title) s = meta.title;+ else s = displayId(fileRepId(f));+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;+}++function clusterName(ci) {+ const c = M.model.clusters[ci];+ if (c.isElse) return '…and everything else';+ if (c.dirLabel) {+ // Two groups can honestly share a folder name — tell them apart by+ // each one's busiest note (folder name alone said nothing).+ if (c.dirDupe) {+ const meta = M.names.get(fileRepId(c.hubFile));+ const hub = meta && meta.path ? meta.path.split('/').pop() : (meta && meta.title) || null;+ if (hub) return `${c.dirLabel} ${hub.length > 16 ? `${hub.slice(0, 15)}…` : hub}`;+ }+ return c.dirLabel;+ }+ const meta = M.names.get(fileRepId(c.hubFile));+ if (meta && (meta.title || meta.path)) {+ const t = meta.path ? meta.path.split('/').pop() : meta.title;+ return `around: ${t.length > 24 ? `${t.slice(0, 23)}…` : t}`;+ }+ return `around: ${displayId(fileRepId(c.hubFile))}`;+}++// ----- as-of aware counts -------------------------------------------++const caretT = () => (M.previewT !== undefined ? M.previewT : M.asOf);++function clusterLiveAt(ci, t) {+ const { g, fg, clusterOfFile } = M.model;+ let live = 0;+ for (let m = 0; m < fg.fa.length; m++) {+ if (clusterOfFile[fg.fa[m]] !== ci || clusterOfFile[fg.fb[m]] !== ci) continue;+ for (const i of fg.fEdges[m]) if (edgeStateAtI(g, i, t) === 'live') live += 1;+ }+ return live;+}++// ----- load orchestration -------------------------------------------++async function load() {+ const gen = ++M.gen;+ M.status = 'loading';+ M.model = null; M.expanded = -1; M.sel = null; M.memberDraw = null;+ M.explore = null; M.spread = 0; M.cam = { x: 0.5, y: 0.5, s: 1 };+ renderRail();+ try {+ const res = await fetchEdgePages(gen);+ if (!res || gen !== M.gen) return;+ M.serverTotal = res.total;+ M.serverTotalIsFloor = res.totalIsFloor;+ M.capped = res.capped;+ const t0 = performance.now();+ M.model = buildMap(res.rows, { brainName: M.brain, asOf: M.asOf });+ M.idIndex = new Map(M.model.g.ids.map((id, i) => [id, i]));+ const buildMs = performance.now() - t0;+ M.status = 'ready';+ // Names: every document in direct mode; hub nominees when grouped.+ if (M.model.mode === 'direct') {+ const ids = [];+ for (let f = 0; f < M.model.fg.F; f++) ids.push(fileRepId(f));+ await hydrateNames(ids, 'naming the notes you see');+ } else {+ const ids = M.model.clusters.filter((c) => !c.isElse && (!c.dirLabel || c.dirDupe))+ .map((c) => fileRepId(c.hubFile)).slice(0, 26);+ if (ids.length) await hydrateNames(ids, 'naming the groups');+ }+ await countNotes();+ if (gen !== M.gen) return;+ setStatus(M.capped+ ? `MAP BUILT FROM THE ${num(M.model.g.n)} STRONGEST LINKS OF ${M.serverTotalIsFloor ? '≥ ' : ''}${num(M.serverTotal)}`+ : `${num(M.model.g.n)} LINKS · ${num(M.model.fg.F)} DOCUMENTS${M.model.mode === 'clustered' ? ` · GROUPED INTO ${num(M.model.clusters.length)}` : ''} · BUILT IN ${buildMs < 1 ? '<1' : num(Math.round(buildMs))}MS`);+ // Publish what the map actually read/derived for the stats row.+ const orphansFloor = M.nodesTotal != null+ ? Math.max(0, M.nodesTotal - M.model.distinctNotes) : null;+ sbPublishMapStats({+ edgesFetched: M.model.g.n,+ edgesTotal: M.serverTotal,+ edgesTotalIsFloor: M.serverTotalIsFloor,+ linkedNotes: M.model.distinctNotes,+ documents: M.model.fg.F,+ groups: M.model.mode === 'clustered' ? M.model.clusters.length : null,+ mode: M.model.mode,+ ...(orphansFloor != null ? { orphansFloor, orphansIsFloor: M.capped } : {}),+ });+ scheduleDraw();+ renderRail();+ toolsState();+ // FIND results that arrived while links were still loading were+ // dropped by highlightNotes' not-ready guard — apply them now.+ if (M.findApply) M.findApply();+ } catch (e) {+ if (gen !== M.gen) return;+ M.status = 'error';+ M.error = String((e && e.message) || e);+ setStatus(`COULD NOT READ THE LINK GRAPH · ${M.error.slice(0, 80)}`);+ renderRail();+ }+}++// ----- canvas mount / camera ----------------------------------------++function mountCanvas(mount) {+ const canvas = mount.querySelector('[data-sb-map-canvas]');+ if (!canvas || canvas === M.canvas) return;+ M.canvas = canvas;+ M.ctx = canvas.getContext('2d');+ resizeCanvas();+ if (M.ro) M.ro.disconnect();+ if (typeof ResizeObserver !== 'undefined') {+ M.ro = new ResizeObserver(() => { resizeCanvas(); scheduleDraw(); });+ M.ro.observe(canvas.parentElement);+ }+ canvas.addEventListener('pointerdown', onCanvasDown);+ canvas.addEventListener('pointermove', onCanvasMove);+ canvas.addEventListener('pointerup', onCanvasUp);+ canvas.addEventListener('pointerleave', () => { M.hover = null; scheduleDraw(); });+ canvas.addEventListener('wheel', onWheel, { passive: false });+ canvas.style.cursor = 'grab';+ if (M.status === 'ready') { scheduleDraw(); renderRail(); toolsState(); }+ else setStatus(M.statusLine || 'READING THE LINK GRAPH…');+}++function resizeCanvas() {+ const c = M.canvas;+ if (!c || !c.parentElement) return;+ const r = c.parentElement.getBoundingClientRect();+ const dpr = (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1;+ c.width = Math.max(1, Math.round(r.width * dpr));+ c.height = Math.max(1, Math.round(r.height * dpr));+ c.style.width = `${r.width}px`;+ c.style.height = `${r.height}px`;+}++function view() {+ const dpr = (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1;+ const w = M.canvas.width / dpr;+ const h = M.canvas.height / dpr;+ // Per-axis base: the unit world square maps to the WHOLE canvas, not+ // to a centered min(w,h) square — a wide panel earns a wide picture+ // (live-seen: half the canvas empty while labels crowded the middle).+ // Everything drawn in world space is either a cluster position or a+ // member offset pre-divided by these same factors (expandCluster),+ // so member spirals stay circular on screen.+ const bx = w * 0.92;+ const by = h * 0.92;+ return { w, h, bx, by, dpr };+}++function toScreen(x, y, v) {+ return [+ (x - M.cam.x) * v.bx * M.cam.s + v.w / 2,+ (y - M.cam.y) * v.by * M.cam.s + v.h / 2,+ ];+}++function toWorld(sx, sy, v) {+ return [+ (sx - v.w / 2) / (v.bx * M.cam.s) + M.cam.x,+ (sy - v.h / 2) / (v.by * M.cam.s) + M.cam.y,+ ];+}++// ----- drawing ------------------------------------------------------++let drawRaf = 0;+function scheduleDraw() {+ if (typeof requestAnimationFrame === 'undefined') { draw(); return; }+ if (drawRaf) return;+ drawRaf = requestAnimationFrame(() => { drawRaf = 0; draw(); });+}++function cssVar(name) {+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();+}++function bodyFont(px, weight = 700) {+ return `${weight} ${px}px ${cssVar('--font-data') || 'monospace'}`;+}++/** Rank → font-size step within the house 7-size scale. */+function rankFontPx(rank) {+ return rank === 0 ? 20 : rank <= 2 ? 16 : rank <= 6 ? 13 : 11;+}++function elbow(ctx, x1, y1, x2, y2) {+ // 1px orthogonal trace — pixel-snapped like the ledger rails.+ const mx = Math.round((x1 + x2) / 2) + 0.5;+ const sy1 = Math.round(y1) + 0.5;+ const sy2 = Math.round(y2) + 0.5;+ ctx.beginPath();+ ctx.moveTo(x1, sy1);+ ctx.lineTo(mx, sy1);+ ctx.lineTo(mx, sy2);+ ctx.lineTo(x2, sy2);+ ctx.stroke();+ return [mx, Math.round((sy1 + sy2) / 2)];+}++function draw() {+ if (!M.canvas || !M.ctx || !M.model || M.status !== 'ready') return;+ if (!M.canvas.isConnected) return; // stale canvas from a replaced render+ const v = view();+ const ctx = M.ctx;+ ctx.setTransform(v.dpr, 0, 0, v.dpr, 0, 0);+ ctx.clearRect(0, 0, v.w, v.h);+ const colors = {+ ink: cssVar('--z-ink') || '#e0e0e0',+ mute: cssVar('--z-mute') || '#555',+ accent: cssVar('--z-accent') || '#eebb00',+ cmp: cssVar('--z-cmp') || '#7f93aa',+ };+ M.hits = [];+ const t = caretT();+ const dimAll = !!M.highlightFiles;++ if (M.model.mode === 'direct') drawDirect(ctx, v, t, colors, dimAll);+ else drawClustered(ctx, v, t, colors, dimAll);++ if (M.anim) stepAnim();+}++function bundleStyle(ctx, live, count, cmax, colors) {+ if (live === 0) {+ ctx.strokeStyle = colors.cmp;+ ctx.setLineDash([3, 2]);+ ctx.globalAlpha = 0.5;+ } else {+ ctx.strokeStyle = colors.ink;+ ctx.setLineDash([]);+ ctx.globalAlpha = 0.18 + 0.55 * (Math.log2(count + 1) / Math.log2(cmax + 1));+ }+ ctx.lineWidth = 1;+}++function labelBlock(ctx, x, y, name, countLine, px, color, alpha, hitRef) {+ ctx.textAlign = 'center';+ ctx.textBaseline = 'alphabetic';+ // Knockout: text owns its pixels — a paper-colored rect under each+ // label keeps the 1px bundle traces from running through the words+ // (the traces are drawn first, so they visibly pass BEHIND a group).+ ctx.font = bodyFont(px);+ const kw1 = ctx.measureText(name).width;+ ctx.font = bodyFont(11, 400);+ const kw = Math.max(kw1, countLine ? ctx.measureText(countLine).width : 0) + 8;+ const kh = (countLine ? 14 : 0) + px + 8;+ ctx.globalAlpha = 1;+ ctx.fillStyle = cssVar('--z-paper') || '#0d0d0d';+ ctx.fillRect(x - kw / 2, y - px - 3, kw, kh);+ ctx.globalAlpha = alpha;+ ctx.fillStyle = color;+ ctx.font = bodyFont(px);+ ctx.fillText(name, x, y);+ const w1 = ctx.measureText(name).width;+ let w2 = 0;+ if (countLine) {+ ctx.font = bodyFont(11, 400);+ ctx.globalAlpha = Math.min(1, alpha * 0.9);+ ctx.fillText(countLine, x, y + 14);+ w2 = ctx.measureText(countLine).width;+ }+ ctx.globalAlpha = 1;+ const w = Math.max(w1, w2) + 10;+ const h = (countLine ? 14 : 0) + px + 8;+ if (hitRef) M.hits.push({ ...hitRef, x: x - w / 2, y: y - px - 4, w, h });+}++/**+ * Label layout for the grouped bodies: measure every text block, then+ * run a fixed number of deterministic pairwise separation passes+ * (vertical push-apart, fixed pair order) so body labels never overlap+ * — same data + same viewport ⇒ same nudges. The expanded group's+ * label moves above its member spiral instead of sitting on it.+ */+function layoutBodyLabels(ctx, v, t) {+ const { clusters, px, py } = M.model;+ const ex = M.expanded;+ const out = clusters.map((c, ci) => {+ let [x, y] = toScreen(px[ci], py[ci], v);+ if (ex === ci && M.memberDraw && M.spread > 0.01) {+ // Above the spiral, clear of the members.+ y -= M.memberDraw.radWorldY * v.by * M.cam.s * M.spread + 26;+ }+ const fpx = c.isElse ? 13 : rankFontPx(ci); // clusters arrive rank-ordered+ const live = M.previewT !== undefined ? clusterLiveAt(ci, t) : c.linkLive;+ const countLine = `${num(c.noteCount)} notes · ${num(live)} link${live === 1 ? '' : 's'}`;+ const name = ex === ci ? `▾ ${clusterName(ci)}` : clusterName(ci);+ ctx.font = bodyFont(fpx);+ const w1 = ctx.measureText(name).width;+ ctx.font = bodyFont(11, 400);+ const w = Math.max(w1, ctx.measureText(countLine).width) + 12;+ const h = fpx + 14 + 10;+ return { ci, x, y, w, h, fpx, name, countLine };+ });+ for (let pass = 0; pass < 24; pass++) {+ let moved = false;+ for (let i = 0; i < out.length; i++) {+ for (let j = i + 1; j < out.length; j++) {+ const a = out[i];+ const b = out[j];+ const ox = Math.min(a.x + a.w / 2, b.x + b.w / 2) - Math.max(a.x - a.w / 2, b.x - b.w / 2);+ const oy = Math.min(a.y + 10, b.y + 10) - Math.max(a.y - a.h + 10, b.y - b.h + 10);+ if (ox <= 0 || oy <= 0) continue;+ const push = (oy / 2) + 1;+ if (a.y <= b.y) { a.y -= push; b.y += push; } else { a.y += push; b.y -= push; }+ moved = true;+ }+ }+ if (!moved) break;+ }+ // At the default camera no label may clip the canvas edge (a body at+ // world 0.06 could otherwise hang half its name off-screen). Only at+ // rest — a user who pans a label off the edge meant to.+ if (M.cam.s === 1 && M.cam.x === 0.5 && M.cam.y === 0.5) {+ for (const L of out) {+ L.x = Math.max(L.w / 2 + 4, Math.min(v.w - L.w / 2 - 4, L.x));+ L.y = Math.max(L.h + 4, Math.min(v.h - 8, L.y));+ }+ }+ return out;+}++function drawClustered(ctx, v, t, colors, dimAll) {+ const { clusters, bundles } = M.model;+ const cmax = bundles.reduce((a, b) => Math.max(a, b.count), 0) || 1;+ const ex = M.expanded;++ const hlClusters = new Set();+ if (M.highlightFiles) {+ for (const f of M.highlightFiles) hlClusters.add(M.model.clusterOfFile[f]);+ }++ // Nudged label positions first — bundles anchor to the nudged+ // centers so a trace always meets the words it belongs to.+ const labels = layoutBodyLabels(ctx, v, t);+ const cxOf = (ci) => labels[ci].x;+ const cyOf = (ci) => labels[ci].y - labels[ci].fpx / 2;+ const bodyRectsEarly = labels.map((L) => ({ x: L.x - L.w / 2, y: L.y - L.h + 10, w: L.w, h: L.h }));+ const countRects = []; // placed bundle-count labels (collision-skipped)++ // -- bundles between bodies (1px orthogonal elbows) --+ for (let bi = 0; bi < bundles.length; bi++) {+ const bu = bundles[bi];+ const live = bundleLiveAt(M.model.g, M.model.fg, bu, t);+ const x1 = cxOf(bu.a);+ const y1 = cyOf(bu.a);+ const x2 = cxOf(bu.b);+ const y2 = cyOf(bu.b);+ bundleStyle(ctx, live, bu.count, cmax, colors);+ if (dimAll && !(hlClusters.has(bu.a) && hlClusters.has(bu.b))) ctx.globalAlpha *= 0.15;+ const hovered = M.hover && M.hover.kind === 'bundle' && M.hover.bi === bi;+ if (hovered) { ctx.strokeStyle = colors.accent; ctx.globalAlpha = 0.9; }+ const [mx, my] = elbow(ctx, x1, y1, x2, y2);+ ctx.setLineDash([]);+ if (bundles.length <= 20 || hovered) {+ // The count label yields to text that already owns the spot —+ // hover always shows it (drawn last, in accent).+ ctx.font = bodyFont(11, 400);+ const label = `${num(live)} link${live === 1 ? '' : 's'}`;+ const lw = ctx.measureText(label).width;+ const rect = { x: mx - lw / 2, y: my - 15, w: lw, h: 14 };+ const blocked = [...bodyRectsEarly, ...countRects].some((r) =>+ rect.x < r.x + r.w && r.x < rect.x + rect.w && rect.y < r.y + r.h && r.y < rect.y + rect.h);+ if (!blocked || hovered) {+ countRects.push(rect);+ ctx.fillStyle = hovered ? colors.accent : colors.mute;+ ctx.globalAlpha = hovered ? 1 : 0.8;+ ctx.textAlign = 'center';+ ctx.fillText(label, mx, my - 4);+ ctx.globalAlpha = 1;+ }+ }+ M.hits.push({ kind: 'bundle', bi, seg: [x1, y1, x2, y2] });+ }++ // -- expanded members (under the body labels) --+ if (ex >= 0 && M.memberDraw && M.spread > 0.01) drawMembers(ctx, v, t, colors, bodyRectsEarly);++ // -- grouped bodies: TEXT blocks, never bubbles --+ const maxScore = clusters.reduce((a, c) => Math.max(a, c.score), 0) || 1;+ for (const L of labels) {+ const c = clusters[L.ci];+ const selected = M.sel && M.sel.kind === 'cluster' && M.sel.ci === L.ci;+ const hovered = M.hover && M.hover.kind === 'cluster' && M.hover.ci === L.ci;+ let alpha = c.isElse ? 0.75 : 0.35 + 0.65 * Math.sqrt(c.score / maxScore);+ if (dimAll && !hlClusters.has(L.ci)) alpha = 0.15;+ const color = selected || hovered || (dimAll && hlClusters.has(L.ci))+ ? colors.accent+ : c.isElse ? colors.mute : colors.ink;+ labelBlock(ctx, L.x, L.y, L.name, L.countLine, L.fpx, color, alpha, { kind: 'cluster', ci: L.ci });+ }+}++function drawMembers(ctx, v, t, colors, bodyRects) {+ const md = M.memberDraw;+ const { g, fg, clusterOfFile, px, py } = M.model;+ const ci = md.ci;+ const spread = M.spread;+ const [ccx, ccy] = [px[ci], py[ci]];++ const pos = md.files.map((f, i) => toScreen(+ ccx + (md.px[i] - ccx) * spread,+ ccy + (md.py[i] - ccy) * spread, v));+ const fileSlot = new Map();+ md.files.forEach((f, i) => fileSlot.set(f, i));++ // -- member↔member links (strongest first, capped-and-said) --+ const intra = [];+ for (let m = 0; m < fg.fa.length; m++) {+ const sa = fileSlot.get(fg.fa[m]);+ const sb = fileSlot.get(fg.fb[m]);+ if (sa === undefined || sb === undefined) continue;+ intra.push([fg.fWeight[m], sa, sb, m]);+ }+ intra.sort((a, b) => b[0] - a[0] || a[3] - b[3]);+ md.intraTotal = intra.length;+ ctx.lineWidth = 1;+ for (const [, sa, sb, m] of intra.slice(0, MAP_INTRA_EDGE_DRAW)) {+ let live = 0;+ for (const i of fg.fEdges[m]) if (edgeStateAtI(g, i, t) === 'live') live += 1;+ ctx.strokeStyle = live ? colors.ink : colors.cmp;+ ctx.setLineDash(live ? [] : [3, 2]);+ ctx.globalAlpha = 0.16 * spread;+ ctx.beginPath();+ ctx.moveTo(pos[sa][0], pos[sa][1]);+ ctx.lineTo(pos[sb][0], pos[sb][1]);+ ctx.stroke();+ }+ ctx.setLineDash([]);++ // -- external links: member → the OTHER group's body, aggregated --+ const C = M.model.clusters.length;+ const extAgg = new Set();+ for (let m = 0; m < fg.fa.length; m++) {+ const ca = clusterOfFile[fg.fa[m]];+ const cb = clusterOfFile[fg.fb[m]];+ if ((ca === ci) === (cb === ci)) continue;+ const inFile = ca === ci ? fg.fa[m] : fg.fb[m];+ const other = ca === ci ? cb : ca;+ const slot = fileSlot.get(inFile);+ if (slot === undefined || other < 0) continue;+ extAgg.add(slot * C + other);+ }+ ctx.strokeStyle = colors.ink;+ ctx.globalAlpha = 0.22 * spread;+ for (const key of extAgg) {+ const slot = Math.floor(key / C);+ const other = key % C;+ const [ox, oy] = toScreen(px[other], py[other], v);+ elbow(ctx, pos[slot][0], pos[slot][1], ox, oy);+ }+ ctx.globalAlpha = 1;++ // -- member marks + collision-aware labels (text, never dots) --+ // Body labels claim their space first: a member name never prints+ // through a group name.+ const placed = (bodyRects || []).slice();+ const deg = M.model.clusters[ci].degLive || new Map();+ md.files.forEach((f, i) => {+ const [sx, sy] = pos[i];+ const selected = M.sel && M.sel.kind === 'member' && M.sel.file === f;+ const hovered = M.hover && M.hover.kind === 'member' && M.hover.file === f;+ const hl = M.highlightFiles && M.highlightFiles.has(f);+ const reached = M.explore && M.explore.reachedFiles && M.explore.reachedFiles.has(f);+ ctx.strokeStyle = selected || hovered || hl || reached ? colors.accent : colors.ink;+ ctx.globalAlpha = (M.highlightFiles && !hl ? 0.2 : 0.9) * spread;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(sx - 3, sy); ctx.lineTo(sx + 3, sy);+ ctx.moveTo(sx, sy - 3); ctx.lineTo(sx, sy + 3);+ ctx.stroke();+ if (reached) { // explore frontier — a 1px ring stroke+ ctx.beginPath();+ ctx.arc(sx, sy, 6, 0, 2 * Math.PI);+ ctx.stroke();+ }+ M.hits.push({ kind: 'member', file: f, x: sx - 6, y: sy - 6, w: 12, h: 12 });+ if (spread > 0.85) {+ const name = fileLabel(f, 18);+ ctx.font = bodyFont(11, selected || hovered ? 700 : 400);+ const tw = ctx.measureText(name).width;+ const rect = { x: sx + 6, y: sy - 7, w: tw + 4, h: 14 };+ const collides = placed.some((r) =>+ rect.x < r.x + r.w && r.x < rect.x + rect.w && rect.y < r.y + r.h && r.y < rect.y + rect.h);+ if (!collides || selected || hovered) {+ placed.push(rect);+ ctx.fillStyle = selected || hovered || hl || reached ? colors.accent : colors.ink;+ ctx.globalAlpha = M.highlightFiles && !hl ? 0.25 : ((deg.get(f) || 0) > 0 ? 0.95 : 0.6);+ ctx.textAlign = 'left';+ ctx.fillText(name, sx + 6, sy + 4);+ ctx.globalAlpha = 1;+ M.hits.push({ kind: 'member', file: f, ...rect });+ }+ }+ });+ md.labelled = placed.length - (bodyRects ? bodyRects.length : 0);++ // -- the satellite: everything past the expand cap, as text --+ if (md.satellite > 0 && spread > 0.85) {+ const [sx, sy] = toScreen(md.satX, md.satY, v);+ const selected = M.sel && M.sel.kind === 'satellite';+ labelBlock(ctx, sx, sy, `+ ${num(md.satellite)} MORE NOTES`, null, 13,+ selected ? colors.accent : colors.mute, 0.9, { kind: 'satellite' });+ }+ ctx.globalAlpha = 1;+}++function drawDirect(ctx, v, t, colors, dimAll) {+ const { g, fg, px, py } = M.model;+ const cmax = fg.fCount.reduce((a, c) => Math.max(a, c), 0) || 1;+ const degLive = new Map();+ const liveOf = [];+ for (let m = 0; m < fg.fa.length; m++) {+ let live = 0;+ for (const i of fg.fEdges[m]) if (edgeStateAtI(g, i, t) === 'live') live += 1;+ liveOf.push(live);+ if (!live) continue;+ degLive.set(fg.fa[m], (degLive.get(fg.fa[m]) || 0) + live);+ degLive.set(fg.fb[m], (degLive.get(fg.fb[m]) || 0) + live);+ }+ const maxDeg = Math.max(...degLive.values(), 1);+ // Same deterministic separation pass as the grouped view: labels+ // measure themselves, then push apart vertically in fixed order.+ const labels = [];+ for (let f = 0; f < fg.F; f++) {+ const [x, y] = toScreen(px[f], py[f], v);+ const d = degLive.get(f) || 0;+ const fpx = d >= maxDeg * 0.8 ? 16 : d > 0 ? 13 : 11;+ const notes = fg.fileSize[f];+ const countLine = notes > 1+ ? `${num(notes)} notes · ${num(d)} link${d === 1 ? '' : 's'}`+ : `${num(d)} link${d === 1 ? '' : 's'}`;+ const name = fileLabel(f);+ ctx.font = bodyFont(fpx);+ const w1 = ctx.measureText(name).width;+ ctx.font = bodyFont(11, 400);+ const w = Math.max(w1, ctx.measureText(countLine).width) + 12;+ labels.push({ f, x, y, w, h: fpx + 14 + 10, fpx, name, countLine, d });+ }+ for (let pass = 0; pass < 24; pass++) {+ let moved = false;+ for (let i = 0; i < labels.length; i++) {+ for (let j = i + 1; j < labels.length; j++) {+ const a = labels[i];+ const b = labels[j];+ const ox = Math.min(a.x + a.w / 2, b.x + b.w / 2) - Math.max(a.x - a.w / 2, b.x - b.w / 2);+ const oy = Math.min(a.y + 10, b.y + 10) - Math.max(a.y - a.h + 10, b.y - b.h + 10);+ if (ox <= 0 || oy <= 0) continue;+ const push = (oy / 2) + 1;+ if (a.y <= b.y) { a.y -= push; b.y += push; } else { a.y += push; b.y -= push; }+ moved = true;+ }+ }+ if (!moved) break;+ }+ const cxOf = new Map(labels.map((L) => [L.f, L.x]));+ const cyOf = new Map(labels.map((L) => [L.f, L.y - L.fpx / 2]));+ for (let m = 0; m < fg.fa.length; m++) {+ const x1 = cxOf.get(fg.fa[m]);+ const y1 = cyOf.get(fg.fa[m]);+ const x2 = cxOf.get(fg.fb[m]);+ const y2 = cyOf.get(fg.fb[m]);+ bundleStyle(ctx, liveOf[m], fg.fCount[m], cmax, colors);+ if (dimAll && !(M.highlightFiles.has(fg.fa[m]) || M.highlightFiles.has(fg.fb[m]))) ctx.globalAlpha *= 0.15;+ const hovered = M.hover && M.hover.kind === 'bundle' && M.hover.bi === m;+ if (hovered) { ctx.strokeStyle = colors.accent; ctx.globalAlpha = 0.9; }+ elbow(ctx, x1, y1, x2, y2);+ ctx.setLineDash([]);+ M.hits.push({ kind: 'bundle', bi: m, seg: [x1, y1, x2, y2] });+ }+ for (const L of labels) {+ const selected = M.sel && M.sel.kind === 'member' && M.sel.file === L.f;+ const hovered = M.hover && M.hover.kind === 'member' && M.hover.file === L.f;+ const hl = M.highlightFiles && M.highlightFiles.has(L.f);+ const reached = M.explore && M.explore.reachedFiles && M.explore.reachedFiles.has(L.f);+ let alpha = L.d > 0 ? 0.55 + 0.45 * (L.d / maxDeg) : 0.45;+ if (dimAll && !hl) alpha = 0.15;+ labelBlock(ctx, L.x, L.y, L.name, L.countLine, L.fpx,+ selected || hovered || hl || reached ? colors.accent : colors.ink, alpha, { kind: 'member', file: L.f });+ }+}++// ----- animation (240ms ease-out, positions precomputed) ------------++const easeOut = (u) => 1 - Math.pow(1 - u, 3);++function stepAnim() {+ const a = M.anim;+ if (!a) return;+ const u = Math.min(1, (performance.now() - a.t0) / a.dur);+ const e = easeOut(u);+ M.spread = a.spreadFrom + (a.spreadTo - a.spreadFrom) * e;+ M.cam = {+ x: a.camFrom.x + (a.camTo.x - a.camFrom.x) * e,+ y: a.camFrom.y + (a.camTo.y - a.camFrom.y) * e,+ s: a.camFrom.s + (a.camTo.s - a.camFrom.s) * e,+ };+ if (u >= 1) {+ M.anim = null;+ if (a.then) a.then();+ }+ scheduleDraw();+}++function animateTo(camTo, spreadTo, then) {+ M.anim = {+ t0: performance.now(), dur: 240,+ camFrom: { ...M.cam }, camTo,+ spreadFrom: M.spread, spreadTo,+ then,+ };+ scheduleDraw();+}++// ----- expand / collapse --------------------------------------------++function expandCluster(ci) {+ const model = M.model;+ if (!model || model.mode !== 'clustered' || M.expanded === ci) return;+ const c = model.clusters[ci];+ const order = memberOrder(c);+ const files = order.slice(0, MAP_EXPAND_CAP);+ const satellite = order.length - files.length;+ const v = view();+ // Spiral sized so neighbouring notes sit ~20px apart on screen at+ // the target camera (a Vogel spiral's nearest-neighbour distance ≈+ // its constant): 150 members → ~245px screen radius, always fits.+ const targetS = 2.2;+ // Per-axis world step (the view maps x and y through different+ // scales): dividing a 20px screen step by each axis' own scale keeps+ // the spiral circular on screen.+ const cWx = 20 / (v.bx * targetS);+ const cWy = 20 / (v.by * targetS);+ const cx = model.px[ci];+ const cy = model.py[ci];+ const mpx = [];+ const mpy = [];+ files.forEach((f, i) => {+ const [ox, oy] = phyllotaxis(i + 1, 0, 0, 1);+ mpx.push(cx + ox * cWx); mpy.push(cy + oy * cWy);+ });+ const radY = cWy * Math.sqrt(files.length + 1);+ M.memberDraw = {+ ci, files, px: mpx, py: mpy, satellite,+ satX: cx, satY: cy + radY + cWy * 2,+ total: order.length, radWorldY: radY,+ };+ M.expanded = ci;+ M.sel = { kind: 'cluster', ci };+ M.spread = 0;+ animateTo({ x: cx, y: cy, s: targetS }, 1);+ hydrateNames(files.map(fileRepId), 'naming the notes you spread open')+ .then(() => { scheduleDraw(); renderRail(); });+ toolsState();+ renderRail();+}++function collapseCluster() {+ if (M.expanded < 0) return;+ M.sel = null;+ M.explore = null;+ animateTo({ x: 0.5, y: 0.5, s: 1 }, 0, () => {+ M.expanded = -1;+ M.memberDraw = null;+ renderRail();+ toolsState();+ });+ renderRail();+}++function toolsState() {+ const btn = document.querySelector('[data-sb-map-collapse]');+ if (btn) btn.hidden = M.expanded < 0;+}++// ----- pointer interaction ------------------------------------------++function hitTest(sx, sy) {+ // Text blocks first (topmost), line traces after.+ for (let i = M.hits.length - 1; i >= 0; i--) {+ const h = M.hits[i];+ if (h.seg) continue;+ if (sx >= h.x && sx <= h.x + h.w && sy >= h.y && sy <= h.y + h.h) return h;+ }+ for (let i = M.hits.length - 1; i >= 0; i--) {+ const h = M.hits[i];+ if (!h.seg) continue;+ const [x1, y1, x2, y2] = h.seg;+ const mx = (x1 + x2) / 2;+ if (ptSeg(sx, sy, x1, y1, mx, y1) < 5 || ptSeg(sx, sy, mx, y1, mx, y2) < 5+ || ptSeg(sx, sy, mx, y2, x2, y2) < 5) return h;+ }+ return null;+}++function ptSeg(qx, qy, x1, y1, x2, y2) {+ const dx = x2 - x1;+ const dy = y2 - y1;+ const l2 = dx * dx + dy * dy;+ const u = l2 ? Math.max(0, Math.min(1, ((qx - x1) * dx + (qy - y1) * dy) / l2)) : 0;+ return Math.hypot(qx - (x1 + u * dx), qy - (y1 + u * dy));+}++function canvasXY(e) {+ const r = M.canvas.getBoundingClientRect();+ return [e.clientX - r.left, e.clientY - r.top];+}++function onCanvasDown(e) {+ if (!M.model || M.status !== 'ready') return;+ const [sx, sy] = canvasXY(e);+ const hit = hitTest(sx, sy);+ M.drag = { sx, sy, cam: { ...M.cam }, moved: false, hit };+ if (!hit) {+ try { M.canvas.setPointerCapture(e.pointerId); } catch { /* older engines */ }+ }+}++function onCanvasMove(e) {+ if (!M.model || M.status !== 'ready') return;+ const [sx, sy] = canvasXY(e);+ if (M.drag) {+ const ddx = sx - M.drag.sx;+ const ddy = sy - M.drag.sy;+ if (Math.abs(ddx) + Math.abs(ddy) > 4) M.drag.moved = true;+ if (M.drag.moved && !M.drag.hit) {+ const v = view();+ M.cam.x = M.drag.cam.x - ddx / (v.bx * M.cam.s);+ M.cam.y = M.drag.cam.y - ddy / (v.by * M.cam.s);+ scheduleDraw();+ }+ return;+ }+ const hit = hitTest(sx, sy);+ const key = (h) => (h ? `${h.kind}:${h.ci ?? ''}:${h.file ?? ''}:${h.bi ?? ''}` : '');+ const changed = key(hit) !== key(M.hover);+ M.hover = hit;+ M.canvas.style.cursor = hit ? 'pointer' : 'grab';+ if (changed) scheduleDraw();+}++function onCanvasUp() {+ const d = M.drag;+ M.drag = null;+ if (!d || d.moved) return;+ const hit = d.hit;+ if (!hit) { // background click clears selection, keeps altitude+ M.sel = null;+ renderRail();+ scheduleDraw();+ return;+ }+ if (hit.kind === 'cluster') {+ if (M.expanded === hit.ci) collapseCluster();+ else expandCluster(hit.ci);+ return;+ }+ if (hit.kind === 'member') {+ M.sel = { kind: 'member', file: hit.file };+ M.explore = null;+ hydrateNames([fileRepId(hit.file)], 'naming the note you selected').then(renderRail);+ renderRail();+ scheduleDraw();+ return;+ }+ if (hit.kind === 'satellite') {+ M.sel = { kind: 'satellite' };+ renderRail();+ scheduleDraw();+ return;+ }+ if (hit.kind === 'bundle') {+ M.sel = { kind: 'bundle', bi: hit.bi };+ inspectBundle(hit.bi);+ }+}++function onWheel(e) {+ if (!M.model || M.status !== 'ready') return;+ e.preventDefault();+ const v = view();+ const [sx, sy] = canvasXY(e);+ const [wx, wy] = toWorld(sx, sy, v);+ const s = Math.max(0.4, Math.min(6, M.cam.s * Math.exp(-e.deltaY * 0.0015)));+ M.cam.x = wx - (sx - v.w / 2) / (v.bx * s);+ M.cam.y = wy - (sy - v.h / 2) / (v.by * s);+ M.cam.s = s;+ scheduleDraw();+}++// ----- bundle inspection / explore ----------------------------------++async function inspectBundle(bi) {+ const model = M.model;+ const merged = model.mode === 'direct' ? [bi] : model.bundles[bi].merged;+ const idxs = [];+ for (const m of merged) for (const i of model.fg.fEdges[m]) idxs.push(i);+ idxs.sort((a, b) => (model.g.weight[b] - model.g.weight[a]) || (a - b));+ const top = idxs.slice(0, MAP_BUNDLE_INSPECT);+ M.sel = { kind: 'bundle', bi, total: idxs.length, rows: null };+ renderRail();+ scheduleDraw();+ try {+ const ids = top.map((i) => model.g.edgeIds[i]);+ const r = await fetch(`${M.baseUrl}/${enc(`.xerj-memory-${M.brain}-edges`)}/_search`, {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ query: { ids: { values: ids } }, size: ids.length,+ _source: ['src', 'dst', 'type', 'detector', 'evidence', 'weight', 'valid_at', 'invalid_at', 'src_file'],+ }),+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const j = await r.json();+ sbLogRead('links index', `${num(ids.length)} of ${num(idxs.length)} links, with their evidence`, 'the line you opened');+ const byId = new Map();+ for (const h of (j.hits && j.hits.hits) || []) byId.set(h._id, { edge_id: h._id, ...(h._source || {}) });+ if (M.sel && M.sel.kind === 'bundle' && M.sel.bi === bi) {+ M.sel.rows = ids.map((id) => byId.get(id)).filter(Boolean);+ renderRail();+ }+ } catch (e) {+ if (M.sel && M.sel.kind === 'bundle' && M.sel.bi === bi) {+ M.sel.rows = [];+ M.sel.error = String((e && e.message) || e);+ renderRail();+ }+ }+}++/**+ * Drill-down past the map, honestly: each click is ONE walk of ≤ 2+ * hops from the seeds (the engine's cap — never a depth slider). The+ * next click seeds from what the last walk reached — the iteration the+ * engine's cap prescribes. The HTTP response spells the reached set as+ * `seeds` (admitted) + `neighbors[].id` (everything new — the spec's+ * §4.3 shape; there is no `reachable` field on the wire). Reached+ * notes light up wherever the map draws them.+ */+async function exploreStep() {+ const sel = M.sel;+ if (!sel || sel.kind !== 'member') return;+ const startId = fileRepId(sel.file);+ if (!M.explore) {+ M.explore = {+ from: sel.file, hops: 0, calls: 0, error: null, running: false,+ reached: new Set([startId]), reachedFiles: new Set([sel.file]), clipped: 0,+ };+ }+ const ex = M.explore;+ if (ex.running) return;+ ex.running = true;+ ex.error = null;+ renderRail();+ const seeds = [...ex.reached].slice(0, MAP_EXPLORE_SEEDS);+ const clipped = ex.reached.size - seeds.length;+ try {+ const qs = new URLSearchParams({+ hops: '2', direction: 'both', limit: '1000',+ include_expired: 'false', include_nodes: 'false', include_evidence: 'false',+ });+ if (M.asOf != null) qs.set('as_of', String(M.asOf));+ if (seeds.length === 1) qs.set('node', seeds[0]);+ else qs.set('nodes', seeds.join(','));+ const r = await fetch(`${M.baseUrl}/_graph/${enc(M.brain)}/ego?${qs}`);+ const j = await r.json().catch(() => null);+ if (!r.ok) {+ throw new Error(j && j.error && j.error.reason ? j.error.reason : `HTTP ${r.status}`);+ }+ ex.calls += 1;+ ex.hops += 2;+ ex.clipped = clipped;+ // Reached = admitted seeds + every newly discovered neighbor.+ for (const s of j.seeds || []) if (typeof s === 'string') ex.reached.add(s);+ for (const nb of j.neighbors || []) if (nb && typeof nb.id === 'string') ex.reached.add(nb.id);+ const { fg } = M.model;+ ex.reachedFiles = new Set();+ for (const id of ex.reached) {+ const oi = M.idIndex.get(id);+ if (oi !== undefined) ex.reachedFiles.add(fg.fileOf[oi]);+ }+ sbLogRead('graph walk', `2 hops from ${num(seeds.length)} note${seeds.length === 1 ? '' : 's'} · ${num(ex.reached.size)} reached so far`, 'you asked to explore further');+ } catch (e) {+ ex.error = String((e && e.message) || e);+ } finally {+ ex.running = false;+ renderRail();+ scheduleDraw();+ }+}++// ----- the rail -----------------------------------------------------++function railEl() {+ return document.querySelector('[data-sb-map-rail]');+}++const railRow = (k, v) => `<div class="sb-hrow"><span class="sb-hk">${esc(k)}</span><span class="sb-hv">${esc(v)}</span></div>`;++function kindChip(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>';+}++/** The open-in-ledger affordance: routed through sbRefocus so every+ * terminal click lands in the ledger, scrolled into sight. */+const openBtn = (id, label) =>+ `<button type="button" class="text-btn sb-map-act" data-sb-map-open="${esc(id)}">${esc(label)}</button>`;++function railHome() {+ const model = M.model;+ if (M.status === 'loading') return `<div class="panel-empty mono faint">READING EVERY LINK…</div>`;+ if (M.status === 'error') return `<div class="panel-empty mono faint">COULD NOT READ THE LINK GRAPH · ${esc(String(M.error).slice(0, 90))}</div>`;+ if (!model) return '';+ const capped = !!M.capped;+ const orphanRow = M.nodesTotal != null+ ? railRow('notes with no links', `${capped ? '≥ ' : ''}${num(Math.max(0, M.nodesTotal - model.distinctNotes))}`)+ : railRow('notes with no links', 'could not be counted');+ const hl = M.highlightFiles+ ? `<div class="sb-map-note accent">FIND: ${num(M.highlightFiles.size)} document${M.highlightFiles.size === 1 ? '' : 's'} lit up${M.highlightMiss ? ` · ${num(M.highlightMiss)} match${M.highlightMiss === 1 ? '' : 'es'} have no links — not on the map` : ''}</div>`+ : '';+ return `+ ${hl}+ <div class="sb-hgroup key">WHAT THE MAP DID NOT SHOW</div>+ ${railRow('links beyond the map budget', capped ? `${M.serverTotalIsFloor ? '≥ ' : ''}${num(Math.max(0, M.serverTotal - model.g.n))}` : '0')}+ ${railRow('links inside single documents', num(model.fg.selfLoops))}+ ${orphanRow}+ ${railRow('notes drawn per opened group', `≤ ${num(MAP_EXPAND_CAP)} — the rest wait in a satellite`)}+ <div class="sb-hgroup key">HOW TO READ IT</div>+ <div class="sb-map-note faint">each name is a group of documents that cite each other or share a folder · line thickness is how many links cross · click a group to spread it · click a line to see the quotes that taught those links · click a note to open its ledger below</div>`;+}++function railCluster(ci) {+ const model = M.model;+ const c = model.clusters[ci];+ const t = caretT();+ const live = M.previewT !== undefined ? clusterLiveAt(ci, t) : c.linkLive;+ const notNow = c.linkTotal - live; // retired or not yet believed at the caret+ const kindCount = new Map();+ for (let m = 0; m < model.fg.fa.length; m++) {+ if (model.clusterOfFile[model.fg.fa[m]] !== ci || model.clusterOfFile[model.fg.fb[m]] !== ci) continue;+ for (const [ord, n] of model.fg.fKind[m]) kindCount.set(ord, (kindCount.get(ord) || 0) + n);+ }+ const domKind = [...kindCount.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0];+ const md = M.memberDraw && M.memberDraw.ci === ci ? M.memberDraw : null;+ const capNote = md && md.satellite > 0+ ? `<div class="sb-map-note">TOP ${num(md.files.length)} OF ${num(md.total)} DOCUMENTS DRAWN · the satellite holds the other ${num(md.satellite)}</div>` : '';+ const intraNote = md && md.intraTotal > MAP_INTRA_EDGE_DRAW+ ? railRow('links drawn inside this group', `strongest ${num(MAP_INTRA_EDGE_DRAW)} of ${num(md.intraTotal)}`) : '';+ return `+ <div class="sb-map-selname">${esc(clusterName(ci))}</div>+ ${railRow('notes', num(c.noteCount))}+ ${railRow('documents', num(c.files.length))}+ ${railRow('links believed at this moment', num(live))}+ ${notNow > 0 ? railRow('links retired or not yet believed', num(notNow)) : ''}+ ${domKind ? railRow('mostly connected by', typeName(model.g.typeNames[domKind[0]]).toLowerCase()) : ''}+ ${c.isElse+ ? `<div class="sb-map-note faint">small groups and loose notes pooled so the picture stays readable — nothing is hidden, it is all here</div>`+ : (c.dirLabel+ ? railRow('named after its folder', `holds ≥ 60% of its links`)+ : railRow('named after its busiest note', 'no folder holds 60% of its links'))}+ ${capNote}${intraNote}+ ${openBtn(fileRepId(c.hubFile), 'OPEN ITS BUSIEST NOTE IN THE LEDGER')}+ <div class="sb-map-note faint">${M.expanded === ci ? 'click the group name again to fold it away' : 'click the group on the map to spread its notes'}</div>`;+}++function railMember(f) {+ const id = fileRepId(f);+ const meta = M.names.get(id) || {};+ const model = M.model;+ const notes = model.fg.fileSize[f];+ const t = caretT();+ let live = 0;+ let total = 0;+ for (let m = 0; m < model.fg.fa.length; m++) {+ if (model.fg.fa[m] !== f && model.fg.fb[m] !== f) continue;+ for (const i of model.fg.fEdges[m]) {+ total += 1;+ if (edgeStateAtI(model.g, i, t) === 'live') live += 1;+ }+ }+ const ex = M.explore;+ const exploreBlock = ex+ ? (ex.error+ ? `<div class="sb-map-note">COULD NOT WALK FURTHER · ${esc(ex.error.slice(0, 120))}</div>`+ : `<div class="sb-map-note accent">${num(ex.reached.size)} note${ex.reached.size === 1 ? '' : 's'} within ${num(ex.hops)} hop${ex.hops === 1 ? '' : 's'} · ${num(ex.calls)} walk${ex.calls === 1 ? '' : 's'} of 2 hops each${ex.clipped > 0 ? ` · ${num(ex.clipped)} starting notes past the per-walk cap wait for the next walk` : ''}</div>+ <div class="sb-map-note faint">depth comes from repeated 2-hop walks — the engine caps each walk at 2 hops, and this view says so instead of pretending otherwise</div>`)+ : '';+ return `+ <div class="sb-map-selname">${esc(meta.path ? meta.path.split('/').pop() : (meta.title || displayId(id)))}</div>+ ${meta.path ? `<div class="sb-map-note faint">${esc(meta.path)}</div>` : ''}+ ${meta.title && meta.path ? `<div class="sb-map-note">${esc(meta.title.slice(0, 90))}</div>` : ''}+ ${notes > 1 ? railRow('notes inside (reading order)', num(notes)) : ''}+ ${railRow('links believed at this moment', num(live))}+ ${total > live ? railRow('links retired or not yet believed', num(total - live)) : ''}+ ${openBtn(id, 'OPEN THE LEDGER · EVERY LINK, WITH WHAT TAUGHT IT')}+ <button type="button" class="text-btn sb-map-act" data-sb-map-explore${ex && ex.running ? ' disabled' : ''}>${ex ? (ex.running ? 'WALKING…' : 'WALK 2 MORE HOPS') : 'EXPLORE · WALK 2 HOPS FROM HERE'}</button>+ ${exploreBlock}`;+}++function railSatellite() {+ const md = M.memberDraw;+ if (!md || md.satellite <= 0) return railHome();+ const model = M.model;+ const order = memberOrder(model.clusters[md.ci]);+ const rest = order.slice(md.files.length);+ const listed = rest.slice(0, MAP_SATELLITE_LIST);+ // Re-render only when names actually landed; hydrateNames settles+ // every asked-for id (hit or miss) and returns 0 once nothing is+ // new, so the render→hydrate→render chain cannot loop.+ hydrateNames(listed.map(fileRepId), 'naming the notes in the satellite')+ .then((added) => { if (added) renderRail(); });+ const rows = listed.map((f) =>+ `<button type="button" class="sb-clink sb-map-satrow" data-sb-map-open="${esc(fileRepId(f))}">${esc(fileLabel(f, 40))}</button>`).join('');+ return `+ <div class="sb-map-selname">+ ${num(md.satellite)} MORE NOTES</div>+ <div class="sb-map-note">${listed.length < rest.length ? `FIRST ${num(listed.length)} OF ${num(rest.length)} · ` : ''}each opens its ledger below</div>+ <div class="sb-map-satlist">${rows}</div>`;+}++function railBundle() {+ const sel = M.sel;+ const model = M.model;+ let title;+ if (model.mode === 'clustered') {+ const bu = model.bundles[sel.bi];+ title = `${clusterName(bu.a)} ↔ ${clusterName(bu.b)}`;+ } else {+ title = `${fileLabel(model.fg.fa[sel.bi], 18)} ↔ ${fileLabel(model.fg.fb[sel.bi], 18)}`;+ }+ const head = `<div class="sb-map-selname">${esc(title)}</div>+ <div class="sb-map-note">${sel.total > MAP_BUNDLE_INSPECT ? `TOP ${num(MAP_BUNDLE_INSPECT)} OF ${num(sel.total)} · strongest first` : `${num(sel.total)} link${sel.total === 1 ? '' : 's'}`}</div>`;+ if (sel.rows == null) return `${head}<div class="panel-empty mono faint">READING WHAT TAUGHT THESE LINKS…</div>`;+ if (sel.error) return `${head}<div class="panel-empty mono faint">COULD NOT READ THE EVIDENCE · ${esc(sel.error.slice(0, 80))}</div>`;+ const t = caretT();+ const now = t == null ? Date.now() : t;+ const rows = sel.rows.map((e) => {+ const kind = evidenceKind(e);+ const q = e.evidence && e.evidence.quote ? e.evidence.quote : null;+ const retired = e.invalid_at != null && Number(e.invalid_at) <= now;+ const line = kind === 'quote' ? `“${esc(q)}”`+ : kind === 'rationale' ? `WHY — ${esc(q)}`+ : 'no evidence recorded — asserted, not detected';+ return `+ <button type="button" class="sb-map-evrow${retired ? ' sb-expired' : ''}" data-sb-map-open="${esc(e.src)}"+ title="Open the ledger for the note this link starts from">+ <span class="sb-map-evline${kind === 'quote' ? '' : ' faint'}">${line}</span>+ <span class="sb-map-evmeta faint">${kindChip(e)} taught by ${esc(detectorName(e.detector).toLowerCase())}${e.src_file ? ` · from ${esc(e.src_file)}` : ''}${retired ? ' · RETIRED AT THIS MOMENT' : ''}</span>+ </button>`;+ }).join('');+ return `${head}<div class="sb-map-evlist">${rows}</div>`;+}++function renderRail() {+ const el = railEl();+ if (!el) return;+ const sel = M.sel;+ let html;+ if (!sel) html = railHome();+ else if (sel.kind === 'cluster') html = railCluster(sel.ci);+ else if (sel.kind === 'member') html = railMember(sel.file);+ else if (sel.kind === 'satellite') html = railSatellite();+ else if (sel.kind === 'bundle') html = railBundle();+ else html = railHome();+ el.innerHTML = html;+}diff --git a/xerj-ux/src/ux/ego-ledger.js b/xerj-ux/src/ux/ego-ledger.jsindex 4f0cad0b8..e5ce92d98 100644--- a/xerj-ux/src/ux/ego-ledger.js+++ b/xerj-ux/src/ux/ego-ledger.js@@ -18,6 +18,13 @@// nodes. The signature interaction is the BELIEF-TIME strip: every// link's lifetime on one time axis with a draggable as-of caret.//+// THE MAP (ux/brain-map.js) sits ABOVE this ledger and does not repeal+// the rationale: it draws a BOUNDED number of structure-derived groups+// with a deterministic seeded layout (no live simulation), and every+// terminal click lands back HERE — the ledger stays the leaf view and+// the only evidence surface. This file also renders the mount point,+// the shared scrubber panel, and the statistics row.+//// LANGUAGE RULE: this surface speaks user words — "link", "believed// since", "retired", "what taught this". Schema names (src/dst/// valid_at/edge_id) appear ONLY inside the evidence paper-trail, which@@ -53,6 +60,8 @@ const TYPE_WORDS = {wikilink: 'WIKI-LINKS',mdlink: 'MARKDOWN LINKS',href: 'HTML LINKS',+ pathcite: 'CITES FILE',+ cratecite: 'CITES CRATE',sequence: 'READING ORDER',same_dir: 'SAME FOLDER',manual: 'HAND-ASSERTED',@@ -68,6 +77,8 @@ const DETECTOR_WORDS = {wikilink: 'WIKI-LINKS',mdlink: 'MARKDOWN LINKS',href: 'HTML LINKS',+ pathcite: 'CITES FILE',+ cratecite: 'CITES CRATE',sequence: 'READING ORDER',samedir: 'FOLDER NEIGHBORS',manual: 'HAND-ASSERTED',@@ -90,7 +101,9 @@ export const detectorName = (tag) => {// 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']);+// pathcite/cratecite quote the author's actual line (a real citation the+// author typed, resolved structurally) — authored, quote-rendered.+const AUTHORED_DETECTORS = new Set(['wikilink', 'mdlink', 'href', 'pathcite', 'cratecite']);const STRUCTURAL_DETECTORS = new Set(['samedir', 'sequence']);const detectorBase = (tag) => String(tag || '').split('@')[0];@@ -352,6 +365,10 @@ const FocusCard = ({ ego, nodes, names, brain, asOf }) => {const preview = meta && meta.preview? `<p class="sb-ftext">${esc(meta.preview)}</p>`: '';+ // The real file behind the note, when the engine (or the console's+ // name cache) knows it — a truthful label, never derived from the id.+ const path = (meta && typeof meta.path === 'string' && meta.path)+ || (names && names[id] && names[id].path) || null;const dangling = !meta && ego.not_shown&& Array.isArray(ego.not_shown.dangling_ids)&& ego.not_shown.dangling_ids.includes(id);@@ -367,7 +384,7 @@ const FocusCard = ({ ego, nodes, names, brain, asOf }) => {${nRetired > 0 ? `<span class="sb-fret">+${num(nRetired)} RETIRED</span>` : ''}</div><div class="sb-fprov mono faint">- ${esc(meta && meta.index ? meta.index : `brain ${brain}`)} · id ${esc(id)}${dangling ? ' · NO DOCUMENT BEHIND THIS ID' : ''}${earliest != null ? ` · in this brain since ${esc(fmtDay(earliest))}` : ''}+ ${esc(meta && meta.index ? meta.index : `brain ${brain}`)}${path ? ` · ${esc(path)}` : ''} · id ${esc(id)}${dangling ? ' · NO DOCUMENT BEHIND THIS ID' : ''}${earliest != null ? ` · in this brain since ${esc(fmtDay(earliest))}` : ''}</div></div>`;};@@ -605,18 +622,21 @@ const sideCol = (groups, side, ctx, caption, emptyLabel) => {</div>`;};-/** The three-column ego ledger + rails + scrubber. */+/**+ * The three-column ego ledger + rails. The brain/focus/FIND controls+ * and the belief-time scrubber used to render inside this panel; they+ * are now panels of their own (`controls` at the top of the page, and+ * `scrub` between the map and the statistics row) so ONE caret drives+ * both the map and the ledger — same module state, same commit path.+ */export const EgoLedger = ({ data }) => {const sb = data.sb || {};const ego = data.ego;const asOf = sb.asOf ?? null;const names = sb.names || {};if (!ego) {- // Controls stay up even without a belief response so the user can- // switch brain / reset the caret out of a dead end.return `- ${EgoControls({ brain: data.brain, brains: sb.brains, focus: sb.focus, asOf, trail: sb.trail, names })}- <div class="panel-empty mono faint">${sb.focus ? 'READING WHAT THE BRAIN BELIEVES ABOUT ' + esc(String(sb.focus).toUpperCase()) + '…' : 'NO NOTE IN FOCUS · CLICK ANY NOTE BELOW TO OPEN ITS LEDGER'}</div>`;+ <div class="panel-empty mono faint">${sb.focus ? 'READING WHAT THE BRAIN BELIEVES ABOUT ' + esc(String(sb.focus).toUpperCase()) + '…' : 'NO NOTE IN FOCUS · CLICK ANY NOTE ON THIS PAGE TO OPEN ITS LEDGER'}</div>`;}const nodes = ego.nodes || {};const clipped = !!(ego.not_shown && ego.not_shown.edges_clipped > 0);@@ -649,10 +669,7 @@ export const EgoLedger = ({ data }) => {</div><div class="panel-empty mono faint">NO LINKS TOUCH THIS NOTE AT THIS MOMENT · DRAG BELIEF TIME BACK TO NOW, OR CLICK ANOTHER NOTE BELOW</div>`;- return `- ${EgoControls({ brain: data.brain, brains: sb.brains, focus: ego.node, asOf, trail: sb.trail, names, nodes })}- ${body}- ${BeliefScrubber({ timeline: sb.timeline, asOf, shift: sb.lastShift })}`;+ return body;};// ----- honesty panel ------------------------------------------------@@ -942,6 +959,225 @@ export const EmptyBrainNote = ({ brain, connected, error }) => {</div>`;};+// ----- composition panels: controls / map / scrub -------------------++/**+ * The header strip — brain switcher, trail crumbs, FIND — hoisted out+ * of the ledger so it sits at the top of the page and survives no+ * matter which panel below is empty or broken.+ */+const ControlsPanel = ({ data }) => {+ const sb = data.sb || {};+ if (!data.brain) {+ return `<div class="panel-empty mono faint">NO BRAIN ON THIS ENGINE YET · THE LEDGER PANEL BELOW HAS THE ONE COMMAND THAT MAKES ONE</div>`;+ }+ const nodes = (data.ego && data.ego.nodes) || {};+ return EgoControls({+ brain: data.brain, brains: sb.brains, focus: sb.focus,+ asOf: sb.asOf ?? null, trail: sb.trail, names: sb.names || {}, nodes,+ });+};++/**+ * THE MAP panel body — a MOUNT POINT, not the map itself.+ *+ * Seam contract with ux/brain-map.js (built as its own slice):+ * - this renderer draws `[data-sb-map] > [data-sb-map-mount]` plus+ * the permanent structural-honesty disclosure;+ * - data/second-brain-api.js dynamic-imports ux/brain-map.js and+ * calls its `mountBrainMap()` (idempotent) after every render;+ * - once mounted, the module sets `data-sb-map-live` on+ * `[data-sb-map]`; panel patching then SKIPS this body (so the+ * canvas is never destroyed) and calls `syncBrainMap()` instead;+ * - the module may import { sbRefocus, sbLogRead, sbPublishMapStats,+ * sbSnapshot } from data/second-brain-api.js, and hears belief-+ * time moves as `sb:asof-preview` / `sb:asof-commit` document+ * events (detail.ms — epoch-ms, or null for NOW).+ */+const MapPanel = ({ data }) => {+ const hasEdges = !!(data.overview && data.overview.exists !== false+ && data.overview.edges && data.overview.edges.total > 0);+ const inner = hasEdges+ ? `<div class="panel-empty mono faint" data-sb-map-waiting>THE MAP DRAWS HERE</div>`+ : `<div class="panel-empty mono faint">THE MAP DRAWS ONCE THIS BRAIN HAS LINKS</div>`;+ return `+ <div class="sb-map" data-sb-map>+ <div class="sb-map-mount" data-sb-map-mount>${inner}</div>+ <div class="sb-map-disclosure mono faint">GROUPED BY LINK STRUCTURE — CITATIONS AND FOLDER NEIGHBORHOOD, NOT MEANING</div>+ </div>`;+};++/** The shared belief-time scrubber: ONE caret for the whole page — the+ * map restyles and the ledger rows restate from the same drag. */+const ScrubPanel = ({ data }) => {+ const sb = data.sb || {};+ return BeliefScrubber({ timeline: sb.timeline, asOf: sb.asOf ?? null, shift: sb.lastShift });+};++// ----- statistics row -----------------------------------------------+//+// Every number in these panels comes from a call THIS page made and can+// name. What the engine does not record (per-note read counts, other+// callers' whys, semantic similarity) is refused in as many words —+// never approximated.++/** ax_format values → short honest labels. Raw-ish on purpose: the+ * format tag is the detector's truth, not marketing copy. */+const fmtFormat = (f) => String(f || 'unknown').replace(/[_-]+/g, ' ').toUpperCase();++/** 1px identity+magnitude row, TaughtByPanel style. */+const statRow = (label, count, max, title) => `+ <div class="sb-det">+ <span class="sb-detname"${title ? ` title="${esc(title)}"` : ''}>${esc(label)}</span>+ <span class="sb-detn">${esc(num(count))}</span>+ <svg class="chart sb-hubbar" height="6" viewBox="0 0 100 6" preserveAspectRatio="none" aria-hidden="true">+ <line x1="0" y1="5" x2="${((count / Math.max(max, 1)) * 100).toFixed(1)}" y2="5" stroke="currentColor" stroke-width="1"/>+ </svg>+ </div>`;++/**+ * WHAT THIS BRAIN HOLDS — notes total + by file type + the no-links+ * floor. Total is the size-0 tally this page ran over exactly the+ * indices whose file types are listed below it (so the headline can+ * never contradict its own rows); the overview's nodes.total is the+ * fallback when that tally failed. Both are numbers something+ * returned, never an estimate. (Live-verified 2026-07-30: on a+ * multi-index brain the overview field returns 0 while the same+ * engine counts 634 by search — preferring the tally is what keeps+ * this tile truthful until that server field handles index lists.)+ */+const NotesPanel = ({ data }) => {+ const o = data.overview || {};+ const sb = data.sb || {};+ const st = sb.nodeStats || null;+ // overview.nodes.total is live-verified to be a false 0 when the+ // brain spans several notes indices (comma-list) — only fall back to+ // it for single-index brains.+ const singleIndex = !!(o.nodes_index && !String(o.nodes_index).includes(','));+ const total = (st && Number.isFinite(st.total)) ? st.total+ : (singleIndex && o.nodes && Number.isFinite(o.nodes.total) ? o.nodes.total : null);+ if (total == null) {+ return st && st.error+ ? `<div class="panel-empty mono faint">COULD NOT COUNT THE NOTES · ${esc(String(st.error).slice(0, 60))}</div>`+ : `<div class="panel-empty mono faint">NOT COUNTED YET</div>`;+ }+ const formats = (st && st.formats) || [];+ const max = Math.max(...formats.map((f) => f.count), 1);+ const rows = formats.map((f) => statRow(fmtFormat(f.format), f.count, max)).join('');+ const other = st && st.otherFormats > 0+ ? `<div class="hint">+ ${num(st.otherFormats)} notes in file types beyond this list</div>` : '';+ // Notes with no links: the map computes it (distinct linked notes out+ // of its weight-ranked fetch), so it is a floor whenever that fetch+ // was budget-truncated — say which.+ const ms = sb.mapStats || null;+ const orphans = ms && Number.isFinite(ms.orphansFloor)+ ? `<div class="hint" style="margin-top:6px;">notes with no links: ${ms.orphansIsFloor ? '≥ ' : ''}${num(ms.orphansFloor)}${ms.orphansIsFloor ? ' — a floor; the map read the strongest links, not all of them' : ''}</div>`+ : `<div class="hint" style="margin-top:6px;">notes with no links: counted once the map has read the links</div>`;+ return `+ ${Num({ value: num(total), unit: 'notes', hint: 'each file counts once, and its sections count as their own notes', emphasis: false })}+ <div class="sb-dets" style="margin-top:var(--sp-1);">${rows}</div>+ ${other}${orphans}`;+};++/**+ * LINKS ACROSS FILE TYPES — how many links leave one file type for+ * another (md → rs, md → pdf …), from a file-type tally on the links+ * index. Brains indexed before links carried file-type stamps have+ * nothing to tally — that is a fact about the record, said plainly,+ * never guessed around.+ */+const CrossingsPanel = ({ data }) => {+ const o = data.overview || {};+ const sb = data.sb || {};+ const c = sb.crossings || null;+ // §0 invariant 8: no surface may imply the links mean anything —+ // they are citations and structure found by deterministic detectors.+ const embed = o.embedder+ ? `<div class="hint" style="margin-top:var(--sp-1);">LINKS COME FROM STRUCTURE AND CITATIONS, NOT MEANING — embedder: ${esc(o.embedder)}</div>`+ : '';+ if (!c) return `<div class="panel-empty mono faint">NOT TALLIED YET</div>${embed}`;+ if (c.error) return `<div class="panel-empty mono faint">COULD NOT TALLY · ${esc(String(c.error).slice(0, 60))}</div>${embed}`;+ if (!c.total) {+ return `+ <div class="panel-empty mono faint">REINDEX TO SEE FILE-TYPE CROSSINGS</div>+ <div class="hint">links in this brain carry no file-type stamp on their ends — run <span class="mono">xerj brain</span> on the folder again to stamp them</div>${embed}`;+ }+ // The headline of this panel is CROSSINGS — so the list shows the+ // pairs that actually cross (md → rs, html → pdf …). Same-type pairs+ // dominate every real corpus and would drown the 8 rows this tile+ // can hold; they get one summary line instead of the whole list.+ const crossPairs = c.pairs.filter((p) => p.src !== p.dst).slice(0, 8);+ const max = Math.max(...crossPairs.map((p) => p.count), 1);+ const rows = crossPairs.map((p) => statRow(+ `${fmtFormat(p.src)} → ${fmtFormat(p.dst)}`, p.count, max,+ 'links that cross from one file type to another',+ )).join('');+ const beyondCross = c.pairs.filter((p) => p.src !== p.dst).length - crossPairs.length + (c.otherPairs || 0);+ const floor = c.truncated ? '≥ ' : '';+ const tail = beyondCross > 0 ? `<div class="hint">+ ${num(beyondCross)} more pairings beyond this list</div>` : '';+ const same = c.sameCount > 0+ ? `<div class="hint">${floor}${num(c.sameCount)} more links join files of the SAME type — not listed here</div>` : '';+ return `+ ${Num({ value: `${floor}${num(c.crossCount)}`, unit: 'crossings', hint: `links joining two DIFFERENT file types · ${num(c.total)} stamped links tallied`, emphasis: false })}+ <div class="sb-dets" style="margin-top:var(--sp-1);">${rows}</div>+ ${tail}${same}${embed}`;+};++/** HH:MM:SS (UTC) for the read log — the strip's fmtTs stops at minutes. */+const fmtClock = (ms) => new Date(Number(ms)).toISOString().slice(11, 19);++/**+ * WHAT THIS VIEW READ · AND WHY — the dashboard's own attributed fetch+ * log (every call it made: what, how much, why), then the server's+ * per-index search counters. The log is the ONLY honest answer to+ * "which data was read and why": the engine does not record other+ * callers' intentions, and this panel says so instead of inventing.+ */+const ReadsPanel = ({ data }) => {+ const sb = data.sb || {};+ const reads = sb.reads || [];+ const latest = reads.slice(-10).reverse();+ const logRows = latest.map((r) => `+ <div class="sb-readrow">+ <span class="sb-readwhat">${esc(r.surface)}</span>+ <span class="sb-readhow">${esc(r.detail)}</span>+ <span class="sb-readwhy">${esc(r.reason)}</span>+ <span class="sb-readat">${r.n > 1 ? `×${num(r.n)} · ` : ''}${esc(fmtClock(r.t))}</span>+ </div>`).join('');+ const logCap = reads.length > latest.length+ ? `<div class="hint">latest ${num(latest.length)} of ${num(sb.readsTotal || reads.length)} reads this page made this session</div>`+ : (reads.length ? `<div class="hint">${num(sb.readsTotal || reads.length)} read${(sb.readsTotal || reads.length) === 1 ? '' : 's'} this page made this session</div>` : '');+ const log = reads.length+ ? `${logRows}${logCap}`+ : `<div class="panel-empty mono faint">EVERY CALL THIS PAGE MAKES LOGS ITSELF HERE</div>`;++ // The reserved links index renders in user words (raw name on+ // hover) — the LANGUAGE RULE covers identifiers we can translate.+ const idxLabel = (ix) => {+ const m = String(ix).match(/^\.xerj-memory-(.+)-edges$/);+ return m ? `links of brain “${m[1]}”` : String(ix);+ };+ const srv = sb.serverReads || null;+ let srvRows;+ if (!srv) srvRows = `<div class="panel-empty mono faint">NOT READ YET</div>`;+ else if (srv.error) srvRows = `<div class="panel-empty mono faint">SERVER COUNTERS UNREADABLE · ${esc(String(srv.error).slice(0, 40))}</div>`;+ else if (!srv.rows.length) srvRows = `<div class="panel-empty mono faint">NO SEARCHES COUNTED YET</div>`;+ else {+ const top = srv.rows.slice(0, 6);+ const max = Math.max(...top.map((r) => r.count), 1);+ srvRows = top.map((r) => statRow(idxLabel(r.index), r.count, max, `index: ${r.index}`)).join('')+ + (srv.rows.length > 6 ? `<div class="hint">+ ${num(srv.rows.length - 6)} more indices</div>` : '');+ }+ return `+ <div class="sb-reads">+ <div class="key">THIS PAGE'S OWN READS · WHAT — HOW MUCH — WHY</div>+ ${log}+ <div class="key" style="margin-top:var(--sp-2);">SEARCHES PER INDEX · SINCE SERVER START (COUNTERS RESET AT BOOT)</div>+ ${srvRows}+ <div class="hint" style="margin-top:6px;">who else read what, and why, is not recorded by the engine — showing it would be invention</div>+ </div>`;+};+// ----- panel dispatcher ---------------------------------------------//// One function renders the INNER body of every second-brain panel so@@ -962,6 +1198,10 @@ export function renderPanelBody(id, data) {switch (id) {case 'ego': return BrainErrorNote({ brain: data.brain, reason: sb.overviewError });case 'notShown': return HonestyList({ data });+ // The way OUT of a dead end is switching brains — keep the+ // controls up; the read log stays honest about what was tried.+ case 'controls': return ControlsPanel({ data });+ case 'reads': return ReadsPanel({ data });default: return `<div class="panel-empty mono faint">COULD NOT READ THIS BRAIN · SEE THE LEDGER PANEL</div>`;}}@@ -972,6 +1212,25 @@ export function renderPanelBody(id, data) {const offNote = `<div class="panel-empty mono faint">ENGINE UNREACHABLE · SEE THE LEDGER PANEL</div>`;switch (id) {+ case 'controls':+ if (offline) return offNote;+ return ControlsPanel({ data });+ case 'map':+ if (offline) return offNote;+ return hasBrain ? MapPanel({ data }) : `<div class="panel-empty mono faint">THE MAP DRAWS ONCE A BRAIN EXISTS · SEE THE LEDGER PANEL BELOW</div>`;+ case 'scrub':+ if (offline) return offNote;+ return hasEdges ? ScrubPanel({ data }) : `<div class="panel-empty mono faint">NOTHING TO REPLAY YET · EVERY LINK WILL DRAW ITS LIFETIME HERE</div>`;+ case 'notes':+ if (offline) return offNote;+ return hasBrain ? NotesPanel({ data }) : `<div class="panel-empty mono faint">—</div>`;+ case 'crossings':+ if (offline) return offNote;+ return hasEdges ? CrossingsPanel({ data }) : `<div class="panel-empty mono faint">HOW LINKS CROSS FILE TYPES RANKS HERE · MD → RS, MD → PDF…</div>`;+ case 'reads':+ // Renders even offline — failed calls were still reads this page+ // made, and the log is the record of trying.+ return ReadsPanel({ data });case 'edgesLive':if (offline) return offNote;return hasBrain ? BelievedPanel({ data }) : `<div class="panel-empty mono faint">NO BRAIN YET · SEE BELOW</div>`;@@ -987,15 +1246,11 @@ export function renderPanelBody(id, data) {case 'edgeTimeline':if (offline) return offNote;return hasEdges ? TimelinePanel({ data }) : `<div class="panel-empty mono faint">EACH DAY’S NEW LINKS WILL DRAW HERE</div>`;- case 'ego': {+ case 'ego':+ // An empty brain is not a dead end: the controls panel at the top+ // keeps the brain switcher up; this panel teaches the one command.if (hasEdges) return EgoLedger({ data });- // An empty brain must not be a dead end when OTHER brains have- // data: keep the brain-switcher controls above the teaching copy.- const switcher = sb.connected && Array.isArray(sb.brains) && sb.brains.length > 1- ? EgoControls({ brain: data.brain, brains: sb.brains, focus: null, asOf: null, trail: [], names: sb.names || {} })- : '';- return switcher + EmptyBrainNote({ brain: data.brain, connected: sb.connected, error: sb.error });- }+ return EmptyBrainNote({ brain: data.brain, connected: sb.connected, error: sb.error });case 'hubs':if (offline) return offNote;return hasEdges ? HubsPanel({ data }) : `<div class="panel-empty mono faint">YOUR MOST-CITED NOTES WILL RANK HERE</div>`;