Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: brain model semantics foundation - typed preference relations, memory labels, dry-run backfill (#51)

Sol Aitken14d1ee177d5d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 1e02d946..7ccc86cb 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.23.0",
+ "version": "0.24.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 8de71fe1..042d6fe3 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.23.0",
+ "version": "0.24.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d53d9d80..4535a61c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,33 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.24.0] - 2026-05-30
+
+Brain model semantics foundation. Preferences can now carry explicit typed
+relationship metadata, memory-layer labels, and branch labels while preserving
+the existing Markdown-first source of truth and deterministic dream behavior.
+
+### Added
+
+- Preference-oriented relation vocabulary (`depends_on`, `refines`) layered on
+ the existing typed graph semantics boundary. Brain backlinks and the explorer
+ now surface typed preference relations without introducing a parallel graph.
+- Optional preference frontmatter metadata: `memory_layer: L0|L1|L2|L3`,
+ `memory_branch: <slug>`, and typed relation fields such as `depends_on:` /
+ `refines:` / `contradicts:`. Absent fields remain byte-identical for legacy
+ preferences.
+- Deterministic dry-run semantics backfill planner plus
+ `o2b brain semantics-backfill --json`, currently previewing missing inverse
+ `superseded_by` pointers when an active preference already declares
+ `supersedes` against a retired one.
+
+### Notes
+
+- Full branch isolation, selective branch pick mutation, and per-layer dream /
+ retention policy are intentionally deferred behind the ADR in
+ `docs/brainstorm/brain-model-semantics-foundation/adr.md`.
+- Full suite green on merge: 2854 tests passing.
+
## [0.23.0] - 2026-05-30
Agent capability and CLI integration. MCP servers can now narrow the advertised
@@ -2132,7 +2159,7 @@ with `source_type: inline`, the source-file wikilink in `source`,
and a `dedup_hash`over the normalised payload. After capture
the source line is annotated`@osb✓ [[sig-...]]`(inline form)
or the info-string flips to`osb-checked`with a`<!-- @osb✓
- [[sig-...]] -->`comment line (block form), making re-runs
+ [[sig-...]] -->`comment line (block form), making re-runs
idempotent. Default ignore set covers`Brain/`, `.git`,
`node_modules`, `.obsidian`, `.trash`, `.stversions`,
`.open-second-brain`; additional excludes via `--exclude`,
diff --git a/README.md b/README.md
index c3aa28a7..de2f22cd 100644
--- a/README.md
+++ b/README.md
@@ -106,7 +106,7 @@ The capabilities you actually feel day to day:
| 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows; `brain_agent_query` and `brain_agent_diff` let you inspect which agent contributed what. |
| 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osb✓` checkmark so re-runs skip it. |
| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` / `monthly` summarise what changed; `o2b brain intent-review` previews whether signal clusters are ready before the next `dream`; `o2b brain retention` recommends keep/improve/park/prune actions without deleting anything. |
-| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Double-click a node — Obsidian opens the underlying note. |
+| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Preference files can now declare typed relationships such as `depends_on:` and `refines:`, plus `memory_layer` / `memory_branch` labels, and the explorer surfaces those semantics without changing the Markdown source of truth. Double-click a node — Obsidian opens the underlying note. |
| 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. |
| 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |
| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` — SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |
@@ -129,6 +129,7 @@ o2b brain audit pref-foo --json # Full mutation trail for one preference
o2b brain morning-brief --json # Session-start summary (prefs, open questions, notes)
o2b brain sources --json # Per-source signal dashboard
o2b brain graph-export --out graph.json # Export the vault knowledge graph
+o2b brain semantics-backfill --json # Dry-run typed preference-edge repair proposals
o2b vault profile switch work # Activate a named multi-vault profile
o2b brain agent-query --agent claude --json # Source-agent provenance query
o2b brain agent-diff --mode diff --agent claude --agent codex
diff --git a/docs/brainstorm/brain-model-semantics-foundation/adr.md b/docs/brainstorm/brain-model-semantics-foundation/adr.md
new file mode 100644
index 00000000..f19e8330
--- /dev/null
+++ b/docs/brainstorm/brain-model-semantics-foundation/adr.md
@@ -0,0 +1,31 @@
+# ADR: Brain Model Semantics Foundation
+
+**Status:** accepted for this PR
+**Date:** 2026-05-30
+**Scope:** `t_965212be`, `t_f373499d`, `t_09dc93c1`
+
+## Context
+
+The selected upstream tasks point toward three related but differently sized ideas: typed memory edges, selective branch picks, and L0-L3 memory layers. Open Second Brain already has typed graph semantics for arbitrary vault pages, a Brain backlink index, a deterministic preference writer/parser, and pairwise merge/retire behavior. The safest foundation is to extend those existing boundaries rather than introduce a second graph or rewrite the Brain lifecycle.
+
+## Decision
+
+Open Second Brain will add a narrow, frontmatter-native semantics foundation for preferences:
+
+- Preference typed edges use the existing relation vocabulary boundary.
+- Preference files may carry optional top-level typed relation fields such as `depends_on:` and `refines:`.
+- Preference files may carry optional inert metadata labels: `memory_layer: L0|L1|L2|L3` and `memory_branch` as a validated slug value.
+- The Brain explorer and backlink index project these fields as read-only semantics.
+- A deterministic dry-run planner can propose high-confidence supersession-edge backfill from existing `supersedes` / `superseded_by` evidence.
+
+## Consequences
+
+This PR creates a stable source-of-truth shape for future model semantics while preserving existing Brain behavior. It does not create isolated branch state, does not implement selective pick mutation, and does not change `dream` retention or confidence policies per layer. Those behaviors need separate ADRs because they affect snapshots, audit, rollback, query semantics, conflict handling, and user expectations.
+
+## Deferred decisions
+
+- Where branch state lives if Open Second Brain later supports copy-on-write Brain branches.
+- How selective pick resolves conflicts between preference revisions and content hashes.
+- Whether L0-L3 layers should influence `dream`, active digest rendering, search ranking, or retention.
+- Whether semantic backfill should gain an apply mode, and which audit/snapshot guard it must use before writes.
+- Whether relation tokens beyond `depends_on` and `refines` should be added.
diff --git a/docs/brainstorm/brain-model-semantics-foundation/cli-output/claude.md b/docs/brainstorm/brain-model-semantics-foundation/cli-output/claude.md
new file mode 100644
index 00000000..f23a754a
--- /dev/null
+++ b/docs/brainstorm/brain-model-semantics-foundation/cli-output/claude.md
@@ -0,0 +1,41 @@
+### Variant 1: Frontmatter-native vocabulary extension
+
+- **Approach**: Lay the foundation entirely in the source-of-truth Markdown by extending the existing `relation-vocab.ts` vocabulary with the preference-specific relation types the upstream tasks imply (`depends_on`, `refines`, plus the already-present `contradicts`/`superseded_by`), and adding optional `relation`-shaped frontmatter fields and a single optional `layer` tag to the preference parser. The explorer projects these through `ExplorerEdge.kind` so typed edges and layer become visible without any new storage. Branching is represented only as an optional `branch` string label on a preference (a soft namespace), with no copy-on-write machinery - selective pick remains a future merge-side concern.
+- **Trade-offs**:
+ - Pro: Maximally aligned with constraints - reuses the single validation boundary, no parallel subsystem, byte-identical default (fields absent unless supplied).
+ - Pro: Deterministic and LLM-free; edges/layers live in the plain files the README promises to own.
+ - Pro: Smallest test surface - extends `explorer.test.ts` and `backlinks-relation.test.ts` rather than adding suites.
+ - Con: Branching is only a label, not isolation - defers the hardest upstream feature almost entirely.
+ - Con: Layer is a flat tag with no per-layer lifecycle, so L0-L3 retention policies are not yet expressible.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant 2: Unified semantics descriptor with deterministic backfill
+
+- **Approach**: Introduce one cohesive optional "semantics" block on the preference model in `types.ts` that carries all three concepts together - typed edges (validated against `relation-vocab`), a `layer` enum (L0-L3), and a `branch` label - parsed and written through `preference.ts`. Pair it with a dry-run-default backfill tool (mirroring ContextLattice's `memory-edge-backfill`) that deterministically derives high-confidence `same-session`/`exact-topic` edges from existing `evidenced_by` and topic slugs. The descriptor is the shared foundation all three future layers build on.
+- **Trade-offs**:
+ - Pro: Treats the three tasks as one coherent model layer, avoiding three disjoint half-features.
+ - Pro: The backfill-with-dry-run pattern is directly reusable by existing merge/scan operations and is fully deterministic.
+ - Pro: Single descriptor gives every future layer (branch isolation, per-layer lifecycle) a stable home.
+ - Con: Larger schema footprint up front; risk of speculative fields that stay empty if branching/layering never land.
+ - Con: A `layer` enum baked into the core preference type nudges toward the L0-L3 restructure the constraints explicitly say not to do in one PR.
+ - Con: Backfill tooling adds a CLI surface and its own test suite.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Derived projection and index layer
+
+- **Approach**: Keep preference files essentially untouched and compute typed semantics on the read side - `explorer.ts` and a deterministic derivation step infer edges (`depends_on`/`refines`/`contradicts`) and a layer classification from existing signals (`evidenced_by`, topic slugs, confidence, session adapters) into a derived, regenerable index rather than stored frontmatter. Branching and selective pick are modeled as alternate derivation views over the same vault, not stored state.
+- **Trade-offs**:
+ - Pro: Zero schema change to the source of truth; default install is trivially byte-identical and nothing is written unless regenerated.
+ - Pro: Edges and layers stay always-consistent with their sources because they are recomputed, never hand-maintained.
+ - Pro: Naturally fits the existing derived-artifact pattern (active.md is already auto-generated).
+ - Con: Operator cannot author an explicit relationship (e.g. "pref-a depends-on pref-b") - only inferred edges exist, contradicting the upstream "first-class typed edge" intent.
+ - Con: A derivation/index step risks becoming the parallel graph subsystem the constraints forbid.
+ - Con: Heuristic layer classification is fragile and hardest to test deterministically.
+- **Complexity**: medium
+- **Risk**: high
+
+### Recommended: Variant 1
+
+**Rationale**: It is the only variant that satisfies every hard constraint at once - additive, deterministic, schema-compatible, byte-identical by default, and built strictly on the existing `relation-vocab`/`backlink`/`explorer` surfaces rather than a new subsystem. The task is explicitly a _foundation_, and the validator comments require an ADR before branching and L0-L3 lifecycle are built, so Variant 1 establishes the typed-edge and layer-tag vocabulary now while deferring copy-on-write branching and per-layer lifecycle exactly as the constraints demand. Variant 2's unified descriptor and Variant 3's derived index both over-commit to mechanisms (a baked-in layer enum, an inference subsystem) that pre-empt decisions the ADRs are meant to make.
diff --git a/docs/brainstorm/brain-model-semantics-foundation/cli-output/prompt.md b/docs/brainstorm/brain-model-semantics-foundation/cli-output/prompt.md
new file mode 100644
index 00000000..565c8183
--- /dev/null
+++ b/docs/brainstorm/brain-model-semantics-foundation/cli-output/prompt.md
@@ -0,0 +1,144 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+Multi-task PR selected by the operator: Brain Model Semantics foundation.
+
+## Task 1: t_965212be - [upstream:contextlattice] Typed memory edges with deterministic backfill
+
+**Source**: https://github.com/sheawinkler/ContextLattice/releases/tag/v3.3.29
+**Repo**: sheawinkler/contextlattice (61 stars)
+**Released**: v3.3.29 (2026-05-29T08:32:54Z)
+
+### What
+
+ContextLattice v3.3.29 introduced first-class typed memory edges in the public gateway. The system supports deterministic retroactive edge backfill with dry-run default, a high-confidence write mode for same-session and exact-topic relationships, and an agent CLI wrapper (scripts/agent/memory-edge-backfill) for automated backfill operations.
+
+### Why useful for OSB
+
+OSB preferences are linked via topic slugs and evidenced_by arrays, but there is no explicit typed edge system between preferences. A typed memory edge system would allow OSB to express richer relationships between preferences (e.g., "pref-a depends-on pref-b", "pref-x refines pref-y", "pref-c contradicts pref-d") beyond the current contradiction-detection in the dream pass. The deterministic backfill pattern with dry-run default is also applicable to OSB's existing merge and scan operations.
+
+### Status in OSB
+
+- Verdict: not_in_osb_useful
+- Codegraph hints: src/core/brain/dream.ts:1462 (computeConfidence - contradiction detection, no typed edges); src/core/brain/merge.ts:83 (mergePreferences - pairwise merge, no edge graph); src/core/brain/preference.ts (preference structure - no edge/relationship fields). OSB has contradiction detection and pairwise merge but no explicit typed relationship graph between preferences.
+
+### Latest validator comment
+
+- sanity: clean
+- cluster: leave: shares the preference-model substrate with t_f373499d (branching) and t_09dc93c1 (layering), but each is a distinct layer of the model with no umbrella parent task; not linked.
+- priority: set to 2. A typed relationship graph between preferences (depends-on/refines/contradicts) is a new data-model concept that needs an ADR before build.
+
+## Task 2: t_f373499d - [upstream:Memoria] Selective branch pick support for memory operations
+
+**Source**: https://github.com/matrixorigin/Memoria/releases/tag/v0.4.0
+**Repo**: matrixorigin/Memoria (259 stars)
+**Released**: v0.4.0 (2026-05-11T10:45:56Z)
+
+### What
+
+Memoria v0.4.0 added explicit branch access for memory operations and selective branch pick support. Users can create branches of the memory state and selectively pick individual memory entries from branches, enabling experimentation with different memory configurations without affecting the main vault. The feature was introduced across commits #193 (selective branch pick) and #203 (explicit branch access).
+
+### Why useful for OSB
+
+OSB preferences use a flat vault structure with mergePreferences for pairwise deduplication (src/core/brain/merge.ts:83). A branching system would allow users to: (a) experiment with preference changes in isolated branches, (b) selectively merge individual preferences between branches rather than the current all-or-nothing merge, (c) maintain alternative configurations (e.g., a "research" branch vs "production" branch of the brain) without duplicating the entire vault. The selective pick operation is finer-grained than OSB's current merge (which keeps one pref and drops the other).
+
+### Status in OSB
+
+- Verdict: not_in_osb_useful
+- Codegraph hints: src/core/brain/merge.ts:83 (mergePreferences - keep/drop pairwise, no branching); src/core/fs-atomic.ts:26 (atomicWriteFileSync - atomic writes, no branch isolation); src/core/brain/preference.ts (preference structure - no branch metadata). OSB has no branching concept - the vault is a single linear state.
+
+### Latest validator comment
+
+- sanity: clean
+- cluster: leave: shares the preference-model substrate with t_965212be (typed edges) and t_09dc93c1 (layering), distinct layer, no umbrella parent; not linked.
+- priority: set to 2. Git-like branching (branch metadata + copy-on-write + cherry-pick + diff) is a large architectural feature that needs an ADR.
+
+## Task 3: t_09dc93c1 - [upstream:TencentDB-Agent-Memory] Multi-layered memory architecture with L0-L3 hierarchy
+
+**Source**: https://github.com/Tencent/TencentDB-Agent-Memory/releases/tag/v1.0.0-beta.1
+**Repo**: Tencent/TencentDB-Agent-Memory (3891 stars)
+**Released**: v1.0.0-beta.1 (2026-05-29T10:27:04Z)
+
+### What
+
+TencentDB Agent Memory v1.0.0-beta.1 evolved from an OpenClaw plugin into a standalone memory service with a four-layer memory architecture: L0 Conversation (add/query/search/delete), L1 Atomic (update/query/search/delete), L2 Scenario (ls/read/write/rm), and L3 Core/Persona (read/write). Each layer has a distinct lifecycle and granularity. The v2 REST API exposes all layers under /v2/ prefix with Bearer token authentication. Standalone local mode runs with zero external dependencies (SQLite + BM25), and official TypeScript and Python SDKs are provided.
+
+### Why useful for OSB
+
+OSB's brain uses a flat preference structure (confirmed/quarantine/retired statuses) with topic-based organization. A layered memory architecture would allow OSB to: (a) separate transient conversation-level context (L0) from durable atomic facts (L1), scenario-specific knowledge (L2), and core persona/identity (L3), (b) apply different retention and confidence policies per layer, (c) scope search relevance by layer (e.g., prefer L3 for identity questions, L0 for recent context). The standalone service model with REST API could also complement OSB's MCP surface for non-MCP agent integrations.
+
+### Status in OSB
+
+- Verdict: not_in_osb_useful
+- Codegraph hints: src/core/brain/preference.ts (single preference model, no layer concept); src/core/brain/dream.ts (dream pass processes all preferences uniformly, no layer-specific logic); src/core/brain/sessions/ (session adapters - no layer tagging). OSB has no memory layering - all preferences share the same schema and lifecycle.
+
+### Latest validator comment
+
+- sanity: clean
+- cluster: leave: shares the preference-model substrate with t_965212be (typed edges) and t_f373499d (branching), distinct layer, no umbrella parent; not linked.
+- priority: set to 2. A four-layer L0-L3 memory architecture with per-layer lifecycle/retention is a fundamental restructure of the flat preference model and needs an ADR.
+
+# Project context
+
+Project: Open Second Brain, TypeScript on Bun. Obsidian-native memory layer. Plain Markdown files under Brain/ are the source of truth. Deterministic core: no LLM in the dream algorithm. Current package version on main: 0.23.0.
+
+Recent commits:
+
+- 3a5d5c3 feat: agent capability CLI integration - runtime MCP capabilities, inherited JSON, completions (#50)
+- a085bfa feat: vault portability + session economy - codec, sources dashboard, vault-map tokens, multi-vault profiles, graph export/import (#49)
+- 73e4a28 feat: brain lifecycle suite - mutation audit, multi-phase dream, reconcile domains, morning brief, temporal extraction, heal enrichment (#48)
+- bd49cd5 feat: recall and ranking quality - Weibull recency, query intent, synonym expansion, recall budgets, query cache, pre-compress pack (#47)
+- cbbe18f feat: typed graph semantics - typed relations, visibility scoping, MCP landscape (#46)
+- 5fa7eb0 feat: MCP context economy - preview budget, artifact fetch, recall hint (#45)
+- 2bd3f48 v0.17.0 - Brain Lifecycle Review Suite: intent review, retention, monthly synthesis, complexity warning (#44)
+- 9b87838 v0.16.0 - Agent boundary control surfaces: pinned context, Markdown links, MCP output contracts (#43)
+- 66980b2 ci: drop bun version floor, track latest only (#42)
+- feca6a7 v0.15.0 - Cross-agent query foundation: source-agent provenance retrieval and comparison (#41)
+- ffde4ac chore(release): v0.14.1 (#40)
+- bc97b38 refactor: add validation toolchain and normalize project formatting (#39)
+
+Related files and existing local design:
+
+- src/core/graph/relation-vocab.ts already defines the typed graph vocabulary for arbitrary vault pages: related, extends, contradicts, superseded_by. It is the single validation boundary and must be reused rather than duplicated.
+- src/core/brain/backlinks.ts already records relation?: string on BacklinkRef when preference/retired frontmatter uses known relation fields.
+- src/core/brain/explorer.ts currently emits ExplorerEdge.kind as only supersedes | wikilink and does not expose relation metadata.
+- src/core/brain/preference.ts is the preference parser/writer. WritePreferenceInput has supersedes and aliases but no general relationship/layer/branch metadata.
+- src/core/brain/merge.ts is pairwise keep/drop merge. It writes superseded_by on retired artifacts and does not implement branch isolation.
+- src/core/brain/types.ts keeps closed status enums and broad typed frontmatter models. Recent suites added audit, lifecycle, tier, confidence, and temporal fields additively.
+- tests/core/brain/backlinks-relation.test.ts already proves frontmatter relation fields tag backlinks.
+- tests/core/brain/explorer.test.ts covers explorer graph nodes/edges and is the likely cheapest surface for typed relation projection tests.
+- docs/brainstorm/typed-graph-semantics/design.md explicitly says preference-domain supersession exists and typed relations are generalized through the shared vocabulary. It rejected a new parallel graph subsystem.
+- README emphasizes plain Markdown ownership, deterministic dream, one vault across agents, and operator-controlled pin/merge/reject/rollback.
+- CHANGELOG v0.23.0 is current; v0.19.0 introduced typed graph semantics; v0.21.0 added audit/morning brief; v0.22.0 added vault portability.
+- No Brain/active.md exists in this repository checkout, so active Brain preferences were unavailable during context gathering.
+
+Constraints:
+
+- Follow SOLID, KISS, DRY.
+- Prefer additive, deterministic, schema-compatible changes.
+- Do not add a parallel graph subsystem if existing relation-vocab/backlink/explorer surfaces can carry the foundation.
+- Do not implement full copy-on-write memory branches or L0-L3 lifecycle rewrite in one PR.
+- Do not add LLM calls to dream or any deterministic core path.
+- Keep default install byte-identical where possible; new fields should be absent unless explicitly supplied or derived.
+- Public artifacts should use "Open Second Brain", not abbreviations.
+- Tests are Bun tests. Project validation uses bun run typecheck, bun run lint, bun run test, bun run sync-version:check.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/brain-model-semantics-foundation/design.md b/docs/brainstorm/brain-model-semantics-foundation/design.md
new file mode 100644
index 00000000..b7493149
--- /dev/null
+++ b/docs/brainstorm/brain-model-semantics-foundation/design.md
@@ -0,0 +1,68 @@
+# Brain Model Semantics Foundation - typed preference semantics without a second graph
+
+**Status:** draft
+**Author:** GitHub Copilot (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain can already store preferences, retire superseded rules, detect contradictions in `dream`, and index typed relationships on arbitrary vault pages. The Brain preference model itself still lacks a small, explicit foundation for user-authored preference relationships, memory-layer labels, and future branch-aware operations. The selected upstream tasks are useful, but their full forms are architectural: typed memory edges, selective memory branch picks, and L0-L3 lifecycle policy should not be built as a destructive rewrite in one release.
+
+## Scope
+
+- Extend the existing relation vocabulary with preference-oriented relation types that can be authored in preference frontmatter and consumed by the current Brain backlink index.
+- Project typed Brain preference edges through the explorer data model while keeping existing `supersedes` and wikilink behavior compatible.
+- Add optional `memory_layer` (`L0`, `L1`, `L2`, `L3`) and `memory_branch` metadata to parsed/written preference files as inert labels, with absent fields preserving legacy byte output.
+- Add a deterministic dry-run supersession backfill planner that proposes high-confidence typed-edge repairs from existing `supersedes` / `superseded_by` evidence without writing by default.
+- Document the ADR decision for what is intentionally deferred from full branch and L0-L3 architecture.
+
+## Out of scope
+
+- Full copy-on-write Brain branches, branch storage roots, or isolated branch query semantics.
+- A `pick` command that mutates one memory branch from another.
+- Per-layer retention, confidence, dream, search-ranking, or lifecycle policy.
+- A new REST service, SDK layer, background daemon, or non-MCP API surface.
+- A parallel graph database or derived index separate from the existing relation vocabulary, backlink index, and explorer projection.
+- Any LLM call inside `dream` or a deterministic core path.
+
+## Chosen approach
+
+Use the consultant's Variant 1: frontmatter-native vocabulary extension. Preference semantics stay in the Markdown source of truth, use the existing `relation-vocab.ts` validation boundary, and flow through the existing Brain backlink and explorer surfaces. Branch and layer support land only as validated labels that future ADR-backed work can consume.
+
+## Design decisions
+
+- **Reuse `relation-vocab.ts`.** New preference relation tokens are added to the same data-driven vocabulary used by vault-page typed graph semantics, so producers and consumers do not hardcode competing relation sets.
+- **Keep relations as top-level frontmatter fields.** A preference can use fields such as `depends_on:` or `refines:` with wikilink targets, matching the existing `related:` / `extends:` / `contradicts:` / `superseded_by:` convention instead of adding a nested object shape that the simple frontmatter writer does not need.
+- **Preserve default byte identity.** `writePreference` emits `memory_layer`, `memory_branch`, and typed relation fields only when callers supply them. Existing dream refreshes and legacy fixtures stay unchanged.
+- **Model layers and branches as labels only.** `memory_layer` and `memory_branch` let future tooling identify intended semantics without silently changing retention, confidence, or query behavior in this release.
+- **Backfill is a plan before a mutation.** The first deterministic backfill surface returns proposals and a stable JSON shape; applying those proposals can be added later once the operator-facing review workflow is clear.
+- **Explorer exposes relation detail without breaking consumers.** Existing edge `kind` remains compatible (`supersedes` / `wikilink`), while a new optional `relation` field carries typed semantics for clients that know how to use it.
+- **Branch pick remains ADR-only.** The selected task's branch idea is acknowledged through `memory_branch`, but real selective pick requires decisions about snapshots, conflicts, audit, and rollback that are larger than this foundation PR.
+
+## File changes
+
+New:
+
+- `docs/brainstorm/brain-model-semantics-foundation/adr.md` - ADR for typed edges, layer labels, branch labels, and deferred full branch/layer behavior.
+- `src/core/brain/semantics-backfill.ts` - pure deterministic planner for typed supersession-edge backfill proposals.
+- `tests/core/brain/semantics-backfill.test.ts` - dry-run planner tests.
+
+Modified:
+
+- `src/core/graph/relation-vocab.ts` - add preference-oriented relation vocabulary tokens.
+- `src/core/brain/types.ts` - add optional `memory_layer`, `memory_branch`, and typed relation metadata types.
+- `src/core/brain/preference.ts` - parse and write optional preference semantics fields, preserving absent-field byte identity.
+- `src/core/brain/backlinks.ts` - rely on the expanded vocabulary and cover the new relation tokens in tests.
+- `src/core/brain/explorer.ts` - include optional edge `relation` and node memory metadata.
+- `templates/brain-explorer.html` - render relation labels and memory metadata when present.
+- `tests/core/brain/backlinks-relation.test.ts` - cover new relation vocabulary tokens.
+- `tests/core/brain/explorer.test.ts` - cover relation projection and memory metadata.
+- `README.md`, `CHANGELOG.md`, and CLI reference docs if a user-facing command or JSON surface is added.
+
+## Risks and open questions
+
+- **Relation vocabulary creep.** Adding `depends_on` and `refines` is useful, but every future token should still pass through the shared vocabulary boundary rather than appear ad hoc in callers.
+- **Frontmatter parser limits.** The existing lightweight YAML parser can mangle wikilink arrays; tests must cover scalar and array forms for new relation fields.
+- **Branch label expectations.** A `memory_branch` field could look like real branch isolation. Documentation must state clearly that it is metadata only until a later ADR-backed branch implementation ships.
+- **Layer label expectations.** `memory_layer` is not a lifecycle policy in this release. It must not alter `dream`, active digest generation, retention, or search ranking yet.
+- **Backfill apply semantics.** The first planner can be dry-run only. If implementation adds `--apply`, it must have snapshot/audit coverage before writing.
diff --git a/docs/brainstorm/brain-model-semantics-foundation/plan.md b/docs/brainstorm/brain-model-semantics-foundation/plan.md
new file mode 100644
index 00000000..e2072beb
--- /dev/null
+++ b/docs/brainstorm/brain-model-semantics-foundation/plan.md
@@ -0,0 +1,48 @@
+# Brain Model Semantics Foundation - implementation plan
+
+## Tasks
+
+### Task 1: Preference relation vocabulary and backlink projection
+
+- **Files**: `src/core/graph/relation-vocab.ts`, `src/core/brain/backlinks.ts`, `tests/core/brain/backlinks-relation.test.ts`
+- **Acceptance**: A Bun test proves `depends_on:` and `refines:` preference frontmatter fields are accepted by the shared vocabulary and appear as `BacklinkRef.relation` values; an unknown field remains untyped.
+- **Depends on**: none
+
+### Task 2: Preference memory metadata parse/write
+
+- **Files**: `src/core/brain/types.ts`, `src/core/brain/preference.ts`, focused preference parser/writer tests
+- **Acceptance**: Tests prove `writePreference` emits `memory_layer` and `memory_branch` only when supplied, `parsePreference` and `parseRetired` round-trip them, invalid `memory_layer` is rejected, and legacy preferences without those fields remain byte-identical.
+- **Depends on**: none
+
+### Task 3: Explorer typed semantics projection
+
+- **Files**: `src/core/brain/explorer.ts`, `templates/brain-explorer.html`, `tests/core/brain/explorer.test.ts`
+- **Acceptance**: A Bun test proves explorer nodes expose `memory_layer` / `memory_branch`, typed relation edges include `relation`, existing `kind` values remain compatible, and the static template renders relation labels without changing graph JSON schema version unless required.
+- **Depends on**: Task 1, Task 2
+
+### Task 4: Deterministic supersession backfill planner
+
+- **Files**: `src/core/brain/semantics-backfill.ts`, `tests/core/brain/semantics-backfill.test.ts`
+- **Acceptance**: Tests prove the planner returns a stable dry-run proposal when an active preference `supersedes` a retired preference that lacks the inverse `superseded_by`, returns no proposal when the inverse already exists, and makes no writes.
+- **Depends on**: Task 1
+
+### Task 5: CLI or documented read surface for backfill preview
+
+- **Files**: `src/cli/main.ts` and adjacent CLI helpers if a command is added; otherwise `docs/cli-reference.md`
+- **Acceptance**: Either `o2b brain semantics-backfill --json` returns the dry-run plan in a stable machine-readable shape, or the implementation explicitly documents that the planner remains internal for this PR and no CLI surface ships.
+- **Depends on**: Task 4
+
+### Task 6: Documentation and release metadata
+
+- **Files**: `README.md`, `CHANGELOG.md`, `docs/cli-reference.md` if CLI changed, `package.json`, lock/version mirrors if version sync requires them
+- **Acceptance**: User-facing docs describe typed preference semantics, memory metadata labels, and dry-run backfill accurately; changelog has one new version entry; `bun run sync-version:check` passes after the version bump.
+- **Depends on**: Tasks 1-5
+
+## Validation plan
+
+- Focused tests after each atomic unit, starting with failing tests.
+- `bun run typecheck`
+- `bun run lint`
+- `bun run test`
+- `bun run sync-version:check`
+- `code_checker` after code edits, per project instructions.
diff --git a/docs/brainstorm/brain-model-semantics-foundation/variants.md b/docs/brainstorm/brain-model-semantics-foundation/variants.md
new file mode 100644
index 00000000..3d5accf8
--- /dev/null
+++ b/docs/brainstorm/brain-model-semantics-foundation/variants.md
@@ -0,0 +1,53 @@
+# Brain Model Semantics foundation - variants
+
+## Consultant output
+
+### Variant 1: Frontmatter-native vocabulary extension
+
+- **Approach**: Lay the foundation entirely in the source-of-truth Markdown by extending the existing `relation-vocab.ts` vocabulary with the preference-specific relation types the upstream tasks imply (`depends_on`, `refines`, plus the already-present `contradicts`/`superseded_by`), and adding optional `relation`-shaped frontmatter fields and a single optional `layer` tag to the preference parser. The explorer projects these through `ExplorerEdge.kind` so typed edges and layer become visible without any new storage. Branching is represented only as an optional `branch` string label on a preference (a soft namespace), with no copy-on-write machinery - selective pick remains a future merge-side concern.
+- **Trade-offs**:
+ - Pro: Maximally aligned with constraints - reuses the single validation boundary, no parallel subsystem, byte-identical default (fields absent unless supplied).
+ - Pro: Deterministic and LLM-free; edges/layers live in the plain files the README promises to own.
+ - Pro: Smallest test surface - extends `explorer.test.ts` and `backlinks-relation.test.ts` rather than adding suites.
+ - Con: Branching is only a label, not isolation - defers the hardest upstream feature almost entirely.
+ - Con: Layer is a flat tag with no per-layer lifecycle, so L0-L3 retention policies are not yet expressible.
+- **Complexity**: small
+- **Risk**: low
+
+### Variant 2: Unified semantics descriptor with deterministic backfill
+
+- **Approach**: Introduce one cohesive optional "semantics" block on the preference model in `types.ts` that carries all three concepts together - typed edges (validated against `relation-vocab`), a `layer` enum (L0-L3), and a `branch` label - parsed and written through `preference.ts`. Pair it with a dry-run-default backfill tool (mirroring ContextLattice's `memory-edge-backfill`) that deterministically derives high-confidence `same-session`/`exact-topic` edges from existing `evidenced_by` and topic slugs. The descriptor is the shared foundation all three future layers build on.
+- **Trade-offs**:
+ - Pro: Treats the three tasks as one coherent model layer, avoiding three disjoint half-features.
+ - Pro: The backfill-with-dry-run pattern is directly reusable by existing merge/scan operations and is fully deterministic.
+ - Pro: Single descriptor gives every future layer (branch isolation, per-layer lifecycle) a stable home.
+ - Con: Larger schema footprint up front; risk of speculative fields that stay empty if branching/layering never land.
+ - Con: A `layer` enum baked into the core preference type nudges toward the L0-L3 restructure the constraints explicitly say not to do in one PR.
+ - Con: Backfill tooling adds a CLI surface and its own test suite.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 3: Derived projection and index layer
+
+- **Approach**: Keep preference files essentially untouched and compute typed semantics on the read side - `explorer.ts` and a deterministic derivation step infer edges (`depends_on`/`refines`/`contradicts`) and a layer classification from existing signals (`evidenced_by`, topic slugs, confidence, session adapters) into a derived, regenerable index rather than stored frontmatter. Branching and selective pick are modeled as alternate derivation views over the same vault, not stored state.
+- **Trade-offs**:
+ - Pro: Zero schema change to the source of truth; default install is trivially byte-identical and nothing is written unless regenerated.
+ - Pro: Edges and layers stay always-consistent with their sources because they are recomputed, never hand-maintained.
+ - Pro: Naturally fits the existing derived-artifact pattern (active.md is already auto-generated).
+ - Con: Operator cannot author an explicit relationship (e.g. "pref-a depends-on pref-b") - only inferred edges exist, contradicting the upstream "first-class typed edge" intent.
+ - Con: A derivation/index step risks becoming the parallel graph subsystem the constraints forbid.
+ - Con: Heuristic layer classification is fragile and hardest to test deterministically.
+- **Complexity**: medium
+- **Risk**: high
+
+### Recommended: Variant 1
+
+**Rationale**: It is the only variant that satisfies every hard constraint at once - additive, deterministic, schema-compatible, byte-identical by default, and built strictly on the existing `relation-vocab`/`backlink`/`explorer` surfaces rather than a new subsystem. The task is explicitly a _foundation_, and the validator comments require an ADR before branching and L0-L3 lifecycle are built, so Variant 1 establishes the typed-edge and layer-tag vocabulary now while deferring copy-on-write branching and per-layer lifecycle exactly as the constraints demand. Variant 2's unified descriptor and Variant 3's derived index both over-commit to mechanisms (a baked-in layer enum, an inference subsystem) that pre-empt decisions the ADRs are meant to make.
+
+## Orchestrator decision
+
+Chosen: Variant 1.
+
+The existing typed graph semantics work already established `src/core/graph/relation-vocab.ts` as the single validation boundary, and the Brain backlink index already consumes known frontmatter relation fields. Reusing that path gives the selected scope a real implementation foundation without introducing speculative branch storage, a second graph, or layer-specific lifecycle policy before the ADR has settled those decisions.
+
+The implementation should therefore ship a narrow additive slice: preference-authored typed edge vocabulary and explorer projection, optional `memory_layer` / `memory_branch` metadata with validation, and a deterministic dry-run planner for supersession-edge backfill. Full copy-on-write branches, selective pick commands, REST service mode, and per-layer retention remain out of scope for this PR.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 46f0061c..dec7d7ea 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -58,6 +58,7 @@ o2b brain sources Read-only dashboard of signals by (agent, source_t
o2b brain graph-export Serialise the vault knowledge graph (pages, wikilinks, typed relations) to a stable graph.json (since v0.22.0): stdout or --out <file>
o2b brain graph-import Reconstruct vault page stubs from a graph.json (since v0.22.0): --mode skip|overwrite|merge; vault-guarded writes
o2b brain backlinks List inbound references to a Brain artifact id
+o2b brain semantics-backfill Dry-run typed preference-edge backfill preview (since v0.24.0): --json returns missing inverse superseded_by proposals; no writes
o2b brain mcp-landscape List MCP servers configured across the vault (since v0.19.0): name, source file, packages, required env-var names (values never read)
o2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yaml
o2b brain import-session Replay signals from a registered agent session .jsonl (or directory)
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 65683fbf..48415216 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.23.0",
+ "version": "0.24.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index ad20c2cd..8266b7e8 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.23.0",
+ "version": "0.24.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index beb7b181..22240117 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.23.0"
+version: "0.24.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 49cc02aa..8c45d9d0 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.23.0",
+ "version": "0.24.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 46d475f0..5887ef89 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.23.0"
+version: "0.24.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index c4ead1e8..03ea8f90 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.23.0"
+version = "0.24.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index b803f9aa..6c253ca8 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -38,6 +38,7 @@ import {
cmdBrainGraphExport,
cmdBrainGraphImport,
cmdBrainBacklinks,
+ cmdBrainSemanticsBackfill,
cmdBrainMcpLandscape,
cmdBrainMerge,
cmdBrainExplorer,
@@ -145,6 +146,8 @@ export async function handleBrainSubcommand(
return await cmdBrainGraphImport(rest);
case "backlinks":
return await cmdBrainBacklinks(rest);
+ case "semantics-backfill":
+ return await cmdBrainSemanticsBackfill(rest);
case "mcp-landscape":
return await cmdBrainMcpLandscape(rest);
case "scan-inline":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index f3971ba4..6179acae 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -45,6 +45,7 @@ Brain verbs (observing memory):
graph-export Serialise the vault knowledge graph to graph.json
graph-import Reconstruct vault pages from graph.json (--mode skip|overwrite|merge)
backlinks List inbound references to a Brain artifact id
+ semantics-backfill Preview deterministic typed preference-edge backfill proposals
mcp-landscape List MCP servers configured across the vault (packages, env names)
scan-inline Capture @osb markers from folders listed under notes.read_paths in _brain.yaml
import-session Replay signals from a registered agent session .jsonl (or directory)
@@ -177,6 +178,11 @@ export const VERB_HELP: Record<string, string> = {
"update / retire / merge) with agent, reason, and revision + content-hash\n" +
"before/after. A ret- or bare-slug argument resolves to the same trail.\n" +
"Read-only.\n",
+ "semantics-backfill":
+ "usage: o2b brain semantics-backfill [--vault <path>] [--json]\n" +
+ "Dry-run only. Previews deterministic typed preference-edge backfill\n" +
+ "proposals, currently the inverse superseded_by edge when an active\n" +
+ "preference supersedes a retired preference that lacks the pointer.\n",
codec:
"usage: o2b brain codec --compress | --expand [--in <file>]\n" +
"Run the deterministic, lossless session codec over stdin (or --in <file>)\n" +
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 9b3e31b0..2cb90c94 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -25,6 +25,7 @@ export { cmdBrainSources } from "./sources.ts";
export { cmdBrainGraphExport } from "./graph-export.ts";
export { cmdBrainGraphImport } from "./graph-import.ts";
export { cmdBrainBacklinks } from "./backlinks.ts";
+export { cmdBrainSemanticsBackfill } from "./semantics-backfill.ts";
export { cmdBrainMcpLandscape } from "./mcp-landscape.ts";
export { cmdBrainMerge } from "./merge.ts";
export { cmdBrainExplorer } from "./explorer.ts";
diff --git a/src/cli/brain/verbs/semantics-backfill.ts b/src/cli/brain/verbs/semantics-backfill.ts
new file mode 100644
index 00000000..ce2f890d
--- /dev/null
+++ b/src/cli/brain/verbs/semantics-backfill.ts
@@ -0,0 +1,33 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { planSemanticsBackfill } from "../../../core/brain/semantics-backfill.ts";
+import { info, okJson, parse, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainSemanticsBackfill(
+ argv: string[],
+): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const plan = planSemanticsBackfill(vault);
+
+ if (flags["json"]) {
+ okJson({
+ dry_run: true,
+ count: plan.proposals.length,
+ proposals: plan.proposals,
+ });
+ return 0;
+ }
+
+ info(`Semantics backfill dry-run proposals: ${plan.proposals.length}`);
+ for (const proposal of plan.proposals) {
+ info(
+ ` ${proposal.source_id} ${proposal.field}: ${proposal.value} ` +
+ `(target ${proposal.target_id}, ${proposal.reason})`,
+ );
+ }
+ return 0;
+}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 8bdeba05..e15a6c1a 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -122,6 +122,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("graph-export", "Export vault graph"),
command("graph-import", "Import vault graph stubs"),
command("backlinks", "List inbound Brain references"),
+ command("semantics-backfill", "Preview Brain semantics backfill"),
command(
"mcp-landscape",
"List MCP servers configured across the vault",
diff --git a/src/core/brain/explorer.ts b/src/core/brain/explorer.ts
index 8e8b9c9c..40e6a938 100644
--- a/src/core/brain/explorer.ts
+++ b/src/core/brain/explorer.ts
@@ -35,7 +35,11 @@ import {
export const EXPLORER_SCHEMA_VERSION = 1 as const;
export type ExplorerNodeKind = "preference" | "retired";
-export type ExplorerNodeStatus = "unconfirmed" | "confirmed" | "quarantine" | "retired";
+export type ExplorerNodeStatus =
+ | "unconfirmed"
+ | "confirmed"
+ | "quarantine"
+ | "retired";
export type ExplorerEdgeKind = "supersedes" | "wikilink";
export interface ExplorerNode {
@@ -53,12 +57,15 @@ export interface ExplorerNode {
readonly retired_reason: string | null;
readonly last_evidence_at: string | null;
readonly backlink_count: number;
+ readonly memory_layer?: BrainPreference["memory_layer"];
+ readonly memory_branch?: string;
}
export interface ExplorerEdge {
readonly source: string;
readonly target: string;
readonly kind: ExplorerEdgeKind;
+ readonly relation?: string;
}
export interface ExplorerGraph {
@@ -89,7 +96,9 @@ export function collectExplorerData(
const knownIds = new Set<string>();
if (existsSync(dirs.preferences)) {
- for (const entry of readdirSync(dirs.preferences, { withFileTypes: true })) {
+ for (const entry of readdirSync(dirs.preferences, {
+ withFileTypes: true,
+ })) {
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
if (!entry.name.startsWith("pref-")) continue;
const path = join(dirs.preferences, entry.name);
@@ -150,7 +159,10 @@ export function collectExplorerData(
});
}
-function nodeFromPreference(pref: BrainPreference, backlinkCount: number): ExplorerNode {
+function nodeFromPreference(
+ pref: BrainPreference,
+ backlinkCount: number,
+): ExplorerNode {
return {
id: pref.id,
kind: "preference",
@@ -166,10 +178,19 @@ function nodeFromPreference(pref: BrainPreference, backlinkCount: number): Explo
retired_reason: null,
last_evidence_at: pref.last_evidence_at,
backlink_count: backlinkCount,
+ ...(pref.memory_layer !== undefined
+ ? { memory_layer: pref.memory_layer }
+ : {}),
+ ...(pref.memory_branch !== undefined
+ ? { memory_branch: pref.memory_branch }
+ : {}),
};
}
-function nodeFromRetired(ret: BrainRetired, backlinkCount: number): ExplorerNode {
+function nodeFromRetired(
+ ret: BrainRetired,
+ backlinkCount: number,
+): ExplorerNode {
return {
id: ret.id,
kind: "retired",
@@ -185,6 +206,12 @@ function nodeFromRetired(ret: BrainRetired, backlinkCount: number): ExplorerNode
retired_reason: ret.retired_reason,
last_evidence_at: ret.last_evidence_at,
backlink_count: backlinkCount,
+ ...(ret.memory_layer !== undefined
+ ? { memory_layer: ret.memory_layer }
+ : {}),
+ ...(ret.memory_branch !== undefined
+ ? { memory_branch: ret.memory_branch }
+ : {}),
};
}
@@ -232,14 +259,19 @@ function loadTemplate(): string {
raw = readFileSync(TEMPLATE_PATH, "utf8");
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- throw new Error(`Failed to load brain-explorer template from ${TEMPLATE_PATH}: ${msg}`, {
- cause: err,
- });
+ throw new Error(
+ `Failed to load brain-explorer template from ${TEMPLATE_PATH}: ${msg}`,
+ {
+ cause: err,
+ },
+ );
}
const first = raw.indexOf(PLACEHOLDER);
const last = raw.lastIndexOf(PLACEHOLDER);
if (first === -1) {
- throw new Error(`brain-explorer.html template is missing the ${PLACEHOLDER} marker`);
+ throw new Error(
+ `brain-explorer.html template is missing the ${PLACEHOLDER} marker`,
+ );
}
if (first !== last) {
throw new Error(
@@ -260,7 +292,10 @@ function loadTemplate(): string {
* / `$1` injection through the JSON body (principle bodies are free
* text and may contain `$`).
*/
-export function renderExportedHtml(graph: ExplorerGraph, vaultPath?: string): string {
+export function renderExportedHtml(
+ graph: ExplorerGraph,
+ vaultPath?: string,
+): string {
const json = JSON.stringify(graph).replace(/[<>&]/g, (c) => {
switch (c) {
case "<":
@@ -350,7 +385,10 @@ export function buildLiveServer(vault: string, port: number): LiveServerHandle {
// ---- Helpers ------------------------------------------------------------
-function deriveEdges(index: BacklinkIndex, knownIds: ReadonlySet<string>): ExplorerEdge[] {
+function deriveEdges(
+ index: BacklinkIndex,
+ knownIds: ReadonlySet<string>,
+): ExplorerEdge[] {
const edges: ExplorerEdge[] = [];
const seen = new Set<string>();
for (const [target, refs] of index) {
@@ -359,11 +397,19 @@ function deriveEdges(index: BacklinkIndex, knownIds: ReadonlySet<string>): Explo
if (!knownIds.has(ref.source)) continue; // logs / signals
if (ref.source === target) continue;
const kind: ExplorerEdgeKind =
- ref.field === "supersedes" || ref.field === "superseded_by" ? "supersedes" : "wikilink";
- const key = `${ref.source}\x00${target}\x00${kind}`;
+ ref.field === "supersedes" || ref.field === "superseded_by"
+ ? "supersedes"
+ : "wikilink";
+ const relation = ref.relation;
+ const key = `${ref.source}\x00${target}\x00${kind}\x00${relation ?? ""}`;
if (seen.has(key)) continue;
seen.add(key);
- edges.push({ source: ref.source, target, kind });
+ edges.push({
+ source: ref.source,
+ target,
+ kind,
+ ...(relation ? { relation } : {}),
+ });
}
}
return edges;
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index a5584b08..6398713b 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -37,18 +37,34 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import type { FrontmatterMap } from "../types.ts";
-import { formatFrontmatter, parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
-import { brainDirs, preferencePath, retiredPath, validateSlug } from "./paths.ts";
+import {
+ formatFrontmatter,
+ parseFrontmatter,
+ writeFrontmatterAtomic,
+} from "../vault.ts";
+import {
+ DEFAULT_RELATION_TYPES,
+ type DefaultRelationType,
+} from "../graph/relation-vocab.ts";
+import {
+ brainDirs,
+ preferencePath,
+ retiredPath,
+ validateSlug,
+} from "./paths.ts";
import {
BRAIN_CONFIDENCE,
+ BRAIN_MEMORY_LAYER,
BRAIN_PREFERENCE_STATUS,
BRAIN_RETIRED_REASON,
type BrainConfidence,
type BrainEvidenceSummary,
+ type BrainMemoryLayer,
type BrainPreference,
type BrainPreferenceStatus,
type BrainRetired,
type BrainRetiredReason,
+ isBrainMemoryLayer,
} from "./types.ts";
import type { PageLifecycle } from "./page-meta/lifecycle.ts";
import type { PageTier } from "./page-meta/tier.ts";
@@ -68,7 +84,12 @@ export class BrainStatusFolderMismatchError extends Error {
readonly status: string;
readonly folder: "preferences" | "retired";
- constructor(message: string, path: string, status: string, folder: "preferences" | "retired") {
+ constructor(
+ message: string,
+ path: string,
+ status: string,
+ folder: "preferences" | "retired",
+ ) {
super(`${message} (path=${path}, status=${status}, folder=${folder})`);
this.name = "BrainStatusFolderMismatchError";
this.path = path;
@@ -134,6 +155,13 @@ export interface WritePreferenceInput {
readonly content_hash?: string;
readonly supersedes?: string;
readonly aliases?: ReadonlyArray<string>;
+ readonly memory_layer?: BrainMemoryLayer;
+ readonly memory_branch?: string;
+ readonly related?: ReadonlyArray<string>;
+ readonly extends?: ReadonlyArray<string>;
+ readonly depends_on?: ReadonlyArray<string>;
+ readonly refines?: ReadonlyArray<string>;
+ readonly contradicts?: ReadonlyArray<string>;
/**
* Brain lifecycle suite (F5). Bi-temporal validity window, filled by
* the dream promotion path from the source signal's ISO temporal
@@ -285,7 +313,10 @@ export function writePreference(
* body. Caller-side cost is negligible compared with the writePref
* + log overhead avoided when the body is up to date.
*/
-export function wouldRewritePreference(vault: string, input: WritePreferenceInput): boolean {
+export function wouldRewritePreference(
+ vault: string,
+ input: WritePreferenceInput,
+): boolean {
const slug = validateSlug(input.slug);
const path = preferencePath(vault, slug);
if (!existsSync(path)) return true;
@@ -303,7 +334,10 @@ export function wouldRewritePreference(vault: string, input: WritePreferenceInpu
}
}
-function preferenceFrontmatter(input: WritePreferenceInput, id: string): FrontmatterMap {
+function preferenceFrontmatter(
+ input: WritePreferenceInput,
+ id: string,
+): FrontmatterMap {
const tags = composePreferenceTags(input);
const confidence = input.confidence ?? BRAIN_CONFIDENCE.low;
const pinned = input.pinned ?? false;
@@ -354,10 +388,27 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma
if (input.revision !== undefined) metadata["_revision"] = input.revision;
if (input.content_hash) metadata["_content_hash"] = input.content_hash;
if (input.scope?.trim()) metadata["scope"] = input.scope.trim();
- if (input.supersedes?.trim()) metadata["supersedes"] = input.supersedes.trim();
+ if (input.supersedes?.trim())
+ metadata["supersedes"] = input.supersedes.trim();
if (input.aliases && input.aliases.length > 0) {
metadata["aliases"] = [...input.aliases];
}
+ if (input.memory_layer !== undefined) {
+ metadata["memory_layer"] = validateMemoryLayer(
+ input.memory_layer,
+ "writePreference",
+ );
+ }
+ if (input.memory_branch?.trim()) {
+ metadata["memory_branch"] = validateMemoryBranch(
+ input.memory_branch,
+ "writePreference",
+ );
+ }
+ for (const field of PREFERENCE_RELATION_FIELDS) {
+ const values = input[field];
+ if (values && values.length > 0) metadata[field] = [...values];
+ }
// `_lifecycle` is emitted only when the caller supplies it. Legacy
// call sites stay byte-identical; new writers (dream refresh pass,
// lint consolidate) opt in by passing the field. Readers fall back
@@ -374,8 +425,10 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma
// supplied (e.g. dream filled it from the source signal's ISO text).
// Reader-side support already exists via readBitemporalSlots; legacy
// callers stay byte-identical.
- if (input.valid_from?.trim()) metadata["valid_from"] = input.valid_from.trim();
- if (input.valid_until?.trim()) metadata["valid_until"] = input.valid_until.trim();
+ if (input.valid_from?.trim())
+ metadata["valid_from"] = input.valid_from.trim();
+ if (input.valid_until?.trim())
+ metadata["valid_until"] = input.valid_until.trim();
return metadata;
}
@@ -430,11 +483,15 @@ function renderPreferenceBody(input: WritePreferenceInput): string {
}
if (input.recentApplied && input.recentApplied.length > 0) {
- sections.push(renderEvidenceSection("Recent applications", input.recentApplied));
+ sections.push(
+ renderEvidenceSection("Recent applications", input.recentApplied),
+ );
}
if (input.recentViolated && input.recentViolated.length > 0) {
- sections.push(renderEvidenceSection("Recent violations", input.recentViolated));
+ sections.push(
+ renderEvidenceSection("Recent violations", input.recentViolated),
+ );
}
const guidance = input.howToApply?.trim();
@@ -446,7 +503,10 @@ function renderPreferenceBody(input: WritePreferenceInput): string {
return sections.join("\n\n");
}
-function renderEvidenceSection(heading: string, rows: ReadonlyArray<BrainEvidenceSummary>): string {
+function renderEvidenceSection(
+ heading: string,
+ rows: ReadonlyArray<BrainEvidenceSummary>,
+): string {
const lines: string[] = [`## ${heading}`, ""];
for (const ev of rows) {
const parts: string[] = [`- ${ev.artifact}`, `— ${ev.timestamp}`];
@@ -492,7 +552,9 @@ export const DERIVED_FIELDS: ReadonlyArray<string> = Object.freeze([
* `meta`; original is untouched. Exported because the backlink
* index and other raw-frontmatter consumers need the same rule.
*/
-export function normalizeDerivedKeys(meta: Record<string, unknown>): Record<string, unknown> {
+export function normalizeDerivedKeys(
+ meta: Record<string, unknown>,
+): Record<string, unknown> {
const out: Record<string, unknown> = { ...meta };
for (const name of DERIVED_FIELDS) {
if (name in out && out[name] !== undefined) {
@@ -541,7 +603,9 @@ export function parsePreference(path: string): BrainPreference {
// `status: "retired"` here because that case is the dedicated
// status-folder-mismatch the parser surfaces below as a typed error
// (doctor downgrades it to a warning) — see §4 of the design doc.
- const statusValues = Object.values(BRAIN_PREFERENCE_STATUS) as ReadonlyArray<string>;
+ const statusValues = Object.values(
+ BRAIN_PREFERENCE_STATUS,
+ ) as ReadonlyArray<string>;
if (!statusValues.includes(status) && status !== "retired") {
throw new Error(
`preference status must be one of ${statusValues.join(", ")}; got ${JSON.stringify(status)} (${path})`,
@@ -590,11 +654,69 @@ export function parsePreference(path: string): BrainPreference {
...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])
? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }
: {}),
+ ...spreadMemorySemantics(meta, path),
...spreadBiTemporal(meta),
};
return Object.freeze(result);
}
+type PreferenceRelationField = Exclude<DefaultRelationType, "superseded_by">;
+
+const PREFERENCE_RELATION_FIELDS = Object.freeze(
+ DEFAULT_RELATION_TYPES.filter(
+ (field): field is PreferenceRelationField => field !== "superseded_by",
+ ),
+);
+
+function spreadMemorySemantics(
+ meta: Record<string, unknown>,
+ path: string,
+): {
+ readonly memory_layer?: BrainMemoryLayer;
+ readonly memory_branch?: string;
+ readonly related?: ReadonlyArray<string>;
+ readonly extends?: ReadonlyArray<string>;
+ readonly depends_on?: ReadonlyArray<string>;
+ readonly refines?: ReadonlyArray<string>;
+ readonly contradicts?: ReadonlyArray<string>;
+} {
+ const out: Record<string, BrainMemoryLayer | string | ReadonlyArray<string>> =
+ {};
+ const memoryLayer = optionalScalarString(meta, "memory_layer");
+ if (memoryLayer !== undefined) {
+ out["memory_layer"] = validateMemoryLayer(memoryLayer, path);
+ }
+ const memoryBranch = optionalScalarString(meta, "memory_branch");
+ if (memoryBranch !== undefined) {
+ out["memory_branch"] = validateMemoryBranch(memoryBranch, path);
+ }
+ for (const field of PREFERENCE_RELATION_FIELDS) {
+ const values = optionalStringList(meta, field);
+ if (values !== undefined) out[field] = values;
+ }
+ return out;
+}
+
+function validateMemoryLayer(value: string, path: string): BrainMemoryLayer {
+ if (isBrainMemoryLayer(value)) return value;
+ const allowed = Object.values(BRAIN_MEMORY_LAYER).join(", ");
+ throw new Error(
+ `preference field 'memory_layer' must be one of ${allowed}; got ${JSON.stringify(value)} (${path})`,
+ );
+}
+
+function validateMemoryBranch(value: string, path: string): string {
+ try {
+ return validateSlug(value);
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ throw new Error(
+ `preference field 'memory_branch' is invalid: ${reason} (${path})`,
+ { cause: err },
+ );
+ }
+}
+
/**
* Read the additive bi-temporal slots (`valid_from`, `valid_until`,
* `recorded_at`) from a frontmatter map. Returns a partial object
@@ -651,7 +773,9 @@ export function parseRetired(path: string): BrainRetired {
const id = requireString(meta, "id", path);
const retired_at = requireString(meta, "retired_at", path);
const reasonStr = requireString(meta, "retired_reason", path);
- const reasonValues = Object.values(BRAIN_RETIRED_REASON) as ReadonlyArray<string>;
+ const reasonValues = Object.values(
+ BRAIN_RETIRED_REASON,
+ ) as ReadonlyArray<string>;
if (!reasonValues.includes(reasonStr)) {
throw new Error(
`retired_reason must be one of ${reasonValues.join(", ")}; got ${JSON.stringify(reasonStr)} (${path})`,
@@ -690,8 +814,14 @@ export function parseRetired(path: string): BrainRetired {
...(meta["aliases"] !== undefined && Array.isArray(meta["aliases"])
? { aliases: [...(meta["aliases"] as ReadonlyArray<string>)] }
: {}),
+ ...spreadMemorySemantics(meta, path),
...(optionalScalarString(meta, "user_rejected_reason") !== undefined
- ? { user_rejected_reason: optionalScalarString(meta, "user_rejected_reason") }
+ ? {
+ user_rejected_reason: optionalScalarString(
+ meta,
+ "user_rejected_reason",
+ ),
+ }
: {}),
...spreadBiTemporal(meta),
};
@@ -731,7 +861,9 @@ export function moveToRetired(
// file: a misrouted call fails fast with no destructive side effect.
const dirs = brainDirs(vault);
if (dirname(prefPath) !== dirs.preferences) {
- throw new Error(`moveToRetired: source path was not under preferences/: ${prefPath}`);
+ throw new Error(
+ `moveToRetired: source path was not under preferences/: ${prefPath}`,
+ );
}
const [meta, body] = parseFrontmatter(prefPath);
@@ -762,14 +894,17 @@ export function moveToRetired(
const newMeta: FrontmatterMap = {};
for (const [k, v] of Object.entries(meta)) {
// Identity keys overwritten below.
- if (k === "kind" || k === "id" || k === "status" || k === "_status") continue;
+ if (k === "kind" || k === "id" || k === "status" || k === "_status")
+ continue;
// Fields that don't apply to retired (drop both shapes per §24).
if (k === "unconfirmed_until") continue;
if (k === "confirmed_at" || k === "_confirmed_at") continue;
if (k === "tags") {
// Replace the `brain/preference` tag with `brain/retired`.
const arr = Array.isArray(v) ? [...v] : [];
- newMeta["tags"] = arr.map((t) => (t === "brain/preference" ? "brain/retired" : t));
+ newMeta["tags"] = arr.map((t) =>
+ t === "brain/preference" ? "brain/retired" : t,
+ );
continue;
}
// Group C derived fields go to disk in the `_`-prefixed shape so
@@ -822,22 +957,27 @@ export function moveToRetired(
unconfirmed_until: requireString(meta, "unconfirmed_until", prefPath),
status: BRAIN_PREFERENCE_STATUS.confirmed, // body render is status-agnostic
evidenced_by: optionalStringArray(meta, "evidenced_by"),
- ...(opts.evidenceApplied !== undefined ? { recentApplied: opts.evidenceApplied } : {}),
- ...(opts.evidenceViolated !== undefined ? { recentViolated: opts.evidenceViolated } : {}),
+ ...(opts.evidenceApplied !== undefined
+ ? { recentApplied: opts.evidenceApplied }
+ : {}),
+ ...(opts.evidenceViolated !== undefined
+ ? { recentViolated: opts.evidenceViolated }
+ : {}),
};
// moveToRetired is also called outside dream (CLI reject) — when the
// caller did not pre-fetch evidence, we collect it here so the
// retired file is the canonical historical snapshot in both paths.
let renderInputWithEvidence: WritePreferenceInput = renderInput;
- if (renderInput.recentApplied === undefined && renderInput.recentViolated === undefined) {
+ if (
+ renderInput.recentApplied === undefined &&
+ renderInput.recentViolated === undefined
+ ) {
// Late-bound import to avoid a cyclic dependency: evidence.ts
// imports nothing from preference.ts at module load time.
// eslint-disable-next-line @typescript-eslint/no-require-imports
- const ev = (require("./evidence.ts") as typeof import("./evidence.ts")).collectEvidenceForSlug(
- vault,
- slug,
- { sinceIso: renderInput.created_at },
- );
+ const ev = (
+ require("./evidence.ts") as typeof import("./evidence.ts")
+ ).collectEvidenceForSlug(vault, slug, { sinceIso: renderInput.created_at });
renderInputWithEvidence = {
...renderInput,
recentApplied: ev.applied,
@@ -856,7 +996,9 @@ export function moveToRetired(
// Confirm the new file actually landed before unlinking the source.
if (!existsSync(newPath)) {
- throw new Error(`moveToRetired: write of ${newPath} reported success but file is absent`);
+ throw new Error(
+ `moveToRetired: write of ${newPath} reported success but file is absent`,
+ );
}
unlinkSync(prefPath);
@@ -866,7 +1008,8 @@ export function moveToRetired(
// always records (the audit's no-op rule only suppresses `update`).
if (opts.audit) {
const principle = requireString(meta, "principle", prefPath);
- const scope = typeof meta["scope"] === "string" ? (meta["scope"] as string) : undefined;
+ const scope =
+ typeof meta["scope"] === "string" ? (meta["scope"] as string) : undefined;
const revRaw = meta["_revision"];
const contentHash = computeContentHash(principle, scope);
appendPrefAudit(
@@ -956,16 +1099,27 @@ function enforceStatusFolderInvariant(
}
}
-function requireField(meta: Record<string, unknown>, field: string, path: string): void {
+function requireField(
+ meta: Record<string, unknown>,
+ field: string,
+ path: string,
+): void {
if (!(field in meta) || meta[field] === undefined || meta[field] === null) {
throw new Error(`preference missing field: ${field} (${path})`);
}
- if (typeof meta[field] === "string" && (meta[field] as string).trim() === "") {
+ if (
+ typeof meta[field] === "string" &&
+ (meta[field] as string).trim() === ""
+ ) {
throw new Error(`preference missing field: ${field} (${path})`);
}
}
-function requireString(meta: Record<string, unknown>, field: string, path: string): string {
+function requireString(
+ meta: Record<string, unknown>,
+ field: string,
+ path: string,
+): string {
requireField(meta, field, path);
const v = meta[field];
if (typeof v !== "string") {
@@ -986,13 +1140,18 @@ function requireStringArray(
}
for (const item of v) {
if (typeof item !== "string") {
- throw new Error(`preference field '${field}' must be an array of strings (${path})`);
+ throw new Error(
+ `preference field '${field}' must be an array of strings (${path})`,
+ );
}
}
return [...(v as ReadonlyArray<string>)];
}
-function optionalStringArray(meta: Record<string, unknown>, field: string): ReadonlyArray<string> {
+function optionalStringArray(
+ meta: Record<string, unknown>,
+ field: string,
+): ReadonlyArray<string> {
const v = meta[field];
if (v === undefined || v === null) return [];
if (!Array.isArray(v)) {
@@ -1000,7 +1159,31 @@ function optionalStringArray(meta: Record<string, unknown>, field: string): Read
}
for (const item of v) {
if (typeof item !== "string") {
- throw new Error(`preference field '${field}' must be an array of strings`);
+ throw new Error(
+ `preference field '${field}' must be an array of strings`,
+ );
+ }
+ }
+ return [...(v as ReadonlyArray<string>)];
+}
+
+function optionalStringList(
+ meta: Record<string, unknown>,
+ field: PreferenceRelationField,
+): ReadonlyArray<string> | undefined {
+ const v = meta[field];
+ if (v === undefined || v === null) return undefined;
+ if (typeof v === "string") return v.trim() ? [v] : [];
+ if (!Array.isArray(v)) {
+ throw new Error(
+ `preference field '${field}' must be a string or array of strings`,
+ );
+ }
+ for (const item of v) {
+ if (typeof item !== "string") {
+ throw new Error(
+ `preference field '${field}' must be a string or array of strings`,
+ );
}
}
return [...(v as ReadonlyArray<string>)];
@@ -1012,7 +1195,10 @@ function optionalStringArray(meta: Record<string, unknown>, field: string): Read
* the on-disk roundtrip survives the simple YAML emitter (which has no
* native null token).
*/
-function optionalNullableString(meta: Record<string, unknown>, field: string): string | null {
+function optionalNullableString(
+ meta: Record<string, unknown>,
+ field: string,
+): string | null {
const v = meta[field];
if (v === undefined || v === null) return null;
if (typeof v !== "string") {
@@ -1023,7 +1209,11 @@ function optionalNullableString(meta: Record<string, unknown>, field: string): s
return v;
}
-function optionalNumber(meta: Record<string, unknown>, field: string, fallback: number): number {
+function optionalNumber(
+ meta: Record<string, unknown>,
+ field: string,
+ fallback: number,
+): number {
const v = meta[field];
if (v === undefined || v === null || v === "") return fallback;
// The simple parser surfaces all values as strings; numerics included.
@@ -1040,7 +1230,10 @@ function optionalNumber(meta: Record<string, unknown>, field: string, fallback:
throw new Error(`preference field '${field}' must be a number`);
}
-function optionalScalarString(meta: Record<string, unknown>, field: string): string | undefined {
+function optionalScalarString(
+ meta: Record<string, unknown>,
+ field: string,
+): string | undefined {
const v = meta[field];
if (v === undefined || v === null) return undefined;
if (typeof v !== "string") return undefined;
@@ -1048,7 +1241,10 @@ function optionalScalarString(meta: Record<string, unknown>, field: string): str
return trimmed === "" ? undefined : v;
}
-function parseConfidence(meta: Record<string, unknown>, path: string): BrainConfidence {
+function parseConfidence(
+ meta: Record<string, unknown>,
+ path: string,
+): BrainConfidence {
const v = meta["confidence"];
if (v === undefined || v === null || v === "") return BRAIN_CONFIDENCE.low;
if (typeof v !== "string") {
@@ -1073,7 +1269,10 @@ function parseConfidence(meta: Record<string, unknown>, path: string): BrainConf
* hard parse error — drifting numeric confidence into `> 1` or
* `NaN` would corrupt every downstream comparison silently.
*/
-function parseConfidenceValue(meta: Record<string, unknown>, path: string): number | null {
+function parseConfidenceValue(
+ meta: Record<string, unknown>,
+ path: string,
+): number | null {
const v = meta["confidence_value"];
if (v === undefined || v === null || v === "" || v === "null") return null;
let n: number | null = null;
diff --git a/src/core/brain/semantics-backfill.ts b/src/core/brain/semantics-backfill.ts
new file mode 100644
index 00000000..d1903b55
--- /dev/null
+++ b/src/core/brain/semantics-backfill.ts
@@ -0,0 +1,98 @@
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "./paths.ts";
+import { parsePreference, parseRetired } from "./preference.ts";
+import { normaliseWikilinkTarget } from "./wikilink.ts";
+import type { BrainPreference, BrainRetired } from "./types.ts";
+
+export interface SemanticsBackfillProposal {
+ readonly source_id: string;
+ readonly target_id: string;
+ readonly relation: "superseded_by";
+ readonly field: "superseded_by";
+ readonly value: string;
+ readonly reason: "active-supersedes-retired-missing-inverse";
+ readonly path: string;
+}
+
+export interface SemanticsBackfillPlan {
+ readonly proposals: ReadonlyArray<SemanticsBackfillProposal>;
+}
+
+interface ParsedPreferenceEntry {
+ readonly path: string;
+ readonly pref: BrainPreference;
+}
+
+interface ParsedRetiredEntry {
+ readonly path: string;
+ readonly retired: BrainRetired;
+}
+
+export function planSemanticsBackfill(vault: string): SemanticsBackfillPlan {
+ const active = readPreferences(vault);
+ const retiredById = new Map(
+ readRetired(vault).map((entry) => [entry.retired.id, entry]),
+ );
+ const proposals: SemanticsBackfillProposal[] = [];
+
+ for (const entry of active) {
+ const supersedes = entry.pref.supersedes;
+ if (!supersedes) continue;
+ const retiredId = normaliseWikilinkTarget(supersedes);
+ if (!retiredId.startsWith("ret-")) continue;
+ const retired = retiredById.get(retiredId);
+ if (!retired) continue;
+ if (retired.retired.superseded_by !== undefined) continue;
+ proposals.push({
+ source_id: retired.retired.id,
+ target_id: entry.pref.id,
+ relation: "superseded_by",
+ field: "superseded_by",
+ value: `[[${entry.pref.id}]]`,
+ reason: "active-supersedes-retired-missing-inverse",
+ path: retired.path,
+ });
+ }
+
+ proposals.sort((a, b) => {
+ const source = a.source_id.localeCompare(b.source_id);
+ if (source !== 0) return source;
+ return a.target_id.localeCompare(b.target_id);
+ });
+
+ return Object.freeze({ proposals: Object.freeze(proposals) });
+}
+
+function readPreferences(vault: string): ReadonlyArray<ParsedPreferenceEntry> {
+ const dir = brainDirs(vault).preferences;
+ if (!existsSync(dir)) return [];
+ const out: ParsedPreferenceEntry[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.startsWith("pref-") || !name.endsWith(".md")) continue;
+ const path = join(dir, name);
+ try {
+ out.push({ path, pref: parsePreference(path) });
+ } catch {
+ continue;
+ }
+ }
+ return out;
+}
+
+function readRetired(vault: string): ReadonlyArray<ParsedRetiredEntry> {
+ const dir = brainDirs(vault).retired;
+ if (!existsSync(dir)) return [];
+ const out: ParsedRetiredEntry[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.startsWith("ret-") || !name.endsWith(".md")) continue;
+ const path = join(dir, name);
+ try {
+ out.push({ path, retired: parseRetired(path) });
+ } catch {
+ continue;
+ }
+ }
+ return out;
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 5086d43f..4466a4ac 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -22,7 +22,8 @@ export const BRAIN_SIGNAL_SIGN = {
positive: "positive",
negative: "negative",
} as const;
-export type BrainSignalSign = (typeof BRAIN_SIGNAL_SIGN)[keyof typeof BRAIN_SIGNAL_SIGN];
+export type BrainSignalSign =
+ (typeof BRAIN_SIGNAL_SIGN)[keyof typeof BRAIN_SIGNAL_SIGN];
/**
* Where the signal came from (§9 / §16 capture extensions). Absent
@@ -47,9 +48,12 @@ const BRAIN_SIGNAL_SOURCE_TYPE_VALUES: ReadonlyArray<BrainSignalSourceType> =
Object.values(BRAIN_SIGNAL_SOURCE_TYPE);
/** Type-guard for the enum union — used by writer + parser. */
-export function isBrainSignalSourceType(v: unknown): v is BrainSignalSourceType {
+export function isBrainSignalSourceType(
+ v: unknown,
+): v is BrainSignalSourceType {
return (
- typeof v === "string" && (BRAIN_SIGNAL_SOURCE_TYPE_VALUES as ReadonlyArray<string>).includes(v)
+ typeof v === "string" &&
+ (BRAIN_SIGNAL_SOURCE_TYPE_VALUES as ReadonlyArray<string>).includes(v)
);
}
@@ -74,7 +78,27 @@ export const BRAIN_CONFIDENCE = {
medium: "medium",
high: "high",
} as const;
-export type BrainConfidence = (typeof BRAIN_CONFIDENCE)[keyof typeof BRAIN_CONFIDENCE];
+export type BrainConfidence =
+ (typeof BRAIN_CONFIDENCE)[keyof typeof BRAIN_CONFIDENCE];
+
+export const BRAIN_MEMORY_LAYER = {
+ L0: "L0",
+ L1: "L1",
+ L2: "L2",
+ L3: "L3",
+} as const;
+export type BrainMemoryLayer =
+ (typeof BRAIN_MEMORY_LAYER)[keyof typeof BRAIN_MEMORY_LAYER];
+
+const BRAIN_MEMORY_LAYER_VALUES: ReadonlyArray<BrainMemoryLayer> =
+ Object.values(BRAIN_MEMORY_LAYER);
+
+export function isBrainMemoryLayer(value: unknown): value is BrainMemoryLayer {
+ return (
+ typeof value === "string" &&
+ BRAIN_MEMORY_LAYER_VALUES.includes(value as BrainMemoryLayer)
+ );
+}
export const BRAIN_RETIRED_REASON = {
staleNoEvidence: "stale-no-evidence",
@@ -99,7 +123,8 @@ export const BRAIN_RETIRED_REASON = {
// no contradiction, the two rules said the same thing.
mergedInto: "merged-into",
} as const;
-export type BrainRetiredReason = (typeof BRAIN_RETIRED_REASON)[keyof typeof BRAIN_RETIRED_REASON];
+export type BrainRetiredReason =
+ (typeof BRAIN_RETIRED_REASON)[keyof typeof BRAIN_RETIRED_REASON];
export const BRAIN_APPLY_RESULT = {
applied: "applied",
@@ -112,7 +137,8 @@ export const BRAIN_APPLY_RESULT = {
// `retain-pinned` log entry instead.
outdated: "outdated",
} as const;
-export type BrainApplyResult = (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];
+export type BrainApplyResult =
+ (typeof BRAIN_APPLY_RESULT)[keyof typeof BRAIN_APPLY_RESULT];
/**
* All possible log event types. `dream` summarises a run; `feedback`
@@ -195,7 +221,8 @@ export const BRAIN_LOG_EVENT_KIND = {
*/
reconcile: "reconcile",
} as const;
-export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
+export type BrainLogEventKind =
+ (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
/**
* Precomputed set of every event-kind string. Both the markdown
@@ -268,7 +295,8 @@ export const RECONCILE_DOMAIN = {
/** Resolvable by recency: one side is materially fresher. */
sourceFreshness: "source-freshness",
} as const;
-export type ReconcileDomain = (typeof RECONCILE_DOMAIN)[keyof typeof RECONCILE_DOMAIN];
+export type ReconcileDomain =
+ (typeof RECONCILE_DOMAIN)[keyof typeof RECONCILE_DOMAIN];
/**
* An unresolved contradiction the reconcile phase surfaced for operator
@@ -422,6 +450,13 @@ export interface BrainPreference {
/** Optional wikilink to a retired pref this one replaces. */
readonly supersedes?: string;
readonly aliases?: ReadonlyArray<string>;
+ readonly memory_layer?: BrainMemoryLayer;
+ readonly memory_branch?: string;
+ readonly related?: ReadonlyArray<string>;
+ readonly extends?: ReadonlyArray<string>;
+ readonly depends_on?: ReadonlyArray<string>;
+ readonly refines?: ReadonlyArray<string>;
+ readonly contradicts?: ReadonlyArray<string>;
/**
* Bi-temporal: event-time start. ISO-8601 UTC timestamp marking
* when the rule was first considered true (independent of when the
@@ -481,6 +516,13 @@ export interface BrainRetired {
readonly confidence_value: number | null;
readonly pinned: boolean;
readonly aliases?: ReadonlyArray<string>;
+ readonly memory_layer?: BrainMemoryLayer;
+ readonly memory_branch?: string;
+ readonly related?: ReadonlyArray<string>;
+ readonly extends?: ReadonlyArray<string>;
+ readonly depends_on?: ReadonlyArray<string>;
+ readonly refines?: ReadonlyArray<string>;
+ readonly contradicts?: ReadonlyArray<string>;
/**
* When the retire transition was driven by `o2b brain reject`, the
* operator-supplied free-form reason is mirrored here so future dream
@@ -612,7 +654,9 @@ export interface BrainSkipCorruptedLogEvent extends BrainLogEventBase {
/** `pin` / `unpin` entry — protected-set change. */
export interface BrainPinLogEvent extends BrainLogEventBase {
- readonly kind: typeof BRAIN_LOG_EVENT_KIND.pin | typeof BRAIN_LOG_EVENT_KIND.unpin;
+ readonly kind:
+ | typeof BRAIN_LOG_EVENT_KIND.pin
+ | typeof BRAIN_LOG_EVENT_KIND.unpin;
readonly preference: string;
}
diff --git a/src/core/graph/relation-vocab.ts b/src/core/graph/relation-vocab.ts
index 865e705a..aa21c3be 100644
--- a/src/core/graph/relation-vocab.ts
+++ b/src/core/graph/relation-vocab.ts
@@ -29,6 +29,8 @@
export const DEFAULT_RELATION_TYPES = Object.freeze([
"related",
"extends",
+ "depends_on",
+ "refines",
"contradicts",
"superseded_by",
] as const);
diff --git a/templates/brain-explorer.html b/templates/brain-explorer.html
index ebc73503..92ccb8c0 100644
--- a/templates/brain-explorer.html
+++ b/templates/brain-explorer.html
@@ -1,763 +1,1132 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8" />
-<title>Open Second Brain — Explorer</title>
-<style>
- :root {
- color-scheme: light dark;
- --bg: #fafafa;
- --panel: #ffffff;
- --border: #e0e0e0;
- --text: #1a1a1a;
- --muted: #666;
- --accent: #4263eb;
- --confirmed: #2f9e44;
- --unconfirmed: #f59f00;
- --quarantine: #e8590c;
- --retired: #868e96;
- --pinned: #f9c74f;
- --edge: #cfcfcf;
- --edge-supersedes: #c92a2a;
- }
- @media (prefers-color-scheme: dark) {
- :root {
- --bg: #1a1a1a;
- --panel: #242424;
- --border: #383838;
- --text: #f0f0f0;
- --muted: #999;
- --edge: #444;
- }
- }
- * { box-sizing: border-box; }
- html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
- body { display: grid; grid-template-columns: 240px 1fr 320px; grid-template-rows: 36px 1fr; }
- header { grid-column: 1 / -1; padding: 0 12px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; background: var(--panel); }
- header .title { font-weight: 600; }
- header .meta { color: var(--muted); font-size: 12px; }
- aside { background: var(--panel); border-right: 1px solid var(--border); padding: 10px 12px; overflow: auto; }
- aside.right { border-right: none; border-left: 1px solid var(--border); }
- aside h3 { margin: 12px 0 6px 0; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); }
- aside h3:first-child { margin-top: 0; }
- aside label { display: block; padding: 2px 0; cursor: pointer; }
- aside input[type="search"] { width: 100%; padding: 6px 8px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--text); }
- main { position: relative; overflow: hidden; background: var(--bg); }
- canvas { display: block; width: 100%; height: 100%; cursor: grab; }
- canvas:active { cursor: grabbing; }
- .legend { display: flex; gap: 8px; flex-wrap: wrap; font-size: 11px; color: var(--muted); }
- .legend .dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; vertical-align: middle; margin-right: 4px; }
- .stats { color: var(--muted); font-size: 12px; }
- .panel-empty { color: var(--muted); font-style: italic; }
- .field { display: flex; gap: 6px; margin: 3px 0; }
- .field .k { color: var(--muted); min-width: 100px; }
- .field .v { word-break: break-word; }
- .principle { padding: 6px 8px; background: var(--bg); border-left: 3px solid var(--accent); margin: 6px 0; }
- .pill { display: inline-block; padding: 1px 6px; border-radius: 10px; font-size: 11px; background: var(--bg); border: 1px solid var(--border); }
- .pill.confirmed { border-color: var(--confirmed); color: var(--confirmed); }
- .pill.unconfirmed { border-color: var(--unconfirmed); color: var(--unconfirmed); }
- .pill.quarantine { border-color: var(--quarantine); color: var(--quarantine); }
- .pill.retired { border-color: var(--retired); color: var(--retired); }
- ul.edge-list { list-style: none; padding-left: 0; margin: 4px 0; }
- ul.edge-list li { padding: 2px 0; }
- ul.edge-list .kind { color: var(--muted); font-size: 11px; }
- button.id-copy { font-size: 11px; padding: 1px 6px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--text); cursor: pointer; }
- /* §14 polish: keyboard-accessible node listbox. The canvas remains
+ <head>
+ <meta charset="utf-8" />
+ <title>Open Second Brain — Explorer</title>
+ <style>
+ :root {
+ color-scheme: light dark;
+ --bg: #fafafa;
+ --panel: #ffffff;
+ --border: #e0e0e0;
+ --text: #1a1a1a;
+ --muted: #666;
+ --accent: #4263eb;
+ --confirmed: #2f9e44;
+ --unconfirmed: #f59f00;
+ --quarantine: #e8590c;
+ --retired: #868e96;
+ --pinned: #f9c74f;
+ --edge: #cfcfcf;
+ --edge-supersedes: #c92a2a;
+ }
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #1a1a1a;
+ --panel: #242424;
+ --border: #383838;
+ --text: #f0f0f0;
+ --muted: #999;
+ --edge: #444;
+ }
+ }
+ * {
+ box-sizing: border-box;
+ }
+ html,
+ body {
+ margin: 0;
+ height: 100%;
+ background: var(--bg);
+ color: var(--text);
+ font:
+ 13px/1.45 system-ui,
+ -apple-system,
+ "Segoe UI",
+ sans-serif;
+ }
+ body {
+ display: grid;
+ grid-template-columns: 240px 1fr 320px;
+ grid-template-rows: 36px 1fr;
+ }
+ header {
+ grid-column: 1 / -1;
+ padding: 0 12px;
+ border-bottom: 1px solid var(--border);
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ background: var(--panel);
+ }
+ header .title {
+ font-weight: 600;
+ }
+ header .meta {
+ color: var(--muted);
+ font-size: 12px;
+ }
+ aside {
+ background: var(--panel);
+ border-right: 1px solid var(--border);
+ padding: 10px 12px;
+ overflow: auto;
+ }
+ aside.right {
+ border-right: none;
+ border-left: 1px solid var(--border);
+ }
+ aside h3 {
+ margin: 12px 0 6px 0;
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--muted);
+ }
+ aside h3:first-child {
+ margin-top: 0;
+ }
+ aside label {
+ display: block;
+ padding: 2px 0;
+ cursor: pointer;
+ }
+ aside input[type="search"] {
+ width: 100%;
+ padding: 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--text);
+ }
+ main {
+ position: relative;
+ overflow: hidden;
+ background: var(--bg);
+ }
+ canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ cursor: grab;
+ }
+ canvas:active {
+ cursor: grabbing;
+ }
+ .legend {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ font-size: 11px;
+ color: var(--muted);
+ }
+ .legend .dot {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ vertical-align: middle;
+ margin-right: 4px;
+ }
+ .stats {
+ color: var(--muted);
+ font-size: 12px;
+ }
+ .panel-empty {
+ color: var(--muted);
+ font-style: italic;
+ }
+ .field {
+ display: flex;
+ gap: 6px;
+ margin: 3px 0;
+ }
+ .field .k {
+ color: var(--muted);
+ min-width: 100px;
+ }
+ .field .v {
+ word-break: break-word;
+ }
+ .principle {
+ padding: 6px 8px;
+ background: var(--bg);
+ border-left: 3px solid var(--accent);
+ margin: 6px 0;
+ }
+ .pill {
+ display: inline-block;
+ padding: 1px 6px;
+ border-radius: 10px;
+ font-size: 11px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ }
+ .pill.confirmed {
+ border-color: var(--confirmed);
+ color: var(--confirmed);
+ }
+ .pill.unconfirmed {
+ border-color: var(--unconfirmed);
+ color: var(--unconfirmed);
+ }
+ .pill.quarantine {
+ border-color: var(--quarantine);
+ color: var(--quarantine);
+ }
+ .pill.retired {
+ border-color: var(--retired);
+ color: var(--retired);
+ }
+ ul.edge-list {
+ list-style: none;
+ padding-left: 0;
+ margin: 4px 0;
+ }
+ ul.edge-list li {
+ padding: 2px 0;
+ }
+ ul.edge-list .kind {
+ color: var(--muted);
+ font-size: 11px;
+ }
+ button.id-copy {
+ font-size: 11px;
+ padding: 1px 6px;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ color: var(--text);
+ cursor: pointer;
+ }
+ /* §14 polish: keyboard-accessible node listbox. The canvas remains
the visual surface; this listbox is the accessible source of
truth so screen readers and keyboard-only operators can
navigate the graph. */
- #node-list { list-style: none; margin: 0 0 6px 0; padding: 0; max-height: 220px; overflow: auto; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); }
- #node-list li { padding: 4px 8px; cursor: pointer; font-size: 12px; border-bottom: 1px solid transparent; }
- #node-list li .topic { color: var(--muted); font-size: 11px; margin-right: 4px; }
- #node-list li[aria-selected="true"] { background: var(--accent); color: #fff; }
- #node-list li[aria-selected="true"] .topic { color: rgba(255,255,255,0.85); }
- #node-list:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
- #node-list-empty { padding: 6px 8px; color: var(--muted); font-style: italic; font-size: 12px; }
-</style>
-</head>
-<body>
-<header>
- <span class="title">Brain Explorer</span>
- <span id="vault-name" class="meta"></span>
- <span id="stats" class="stats"></span>
-</header>
-<aside class="left">
- <h3>Search</h3>
- <input id="search" type="search" placeholder="topic or principle..." />
- <h3>Status</h3>
- <label><input type="checkbox" class="status-filter" value="confirmed" checked /> <span class="legend"><span class="dot" style="background: var(--confirmed)"></span>confirmed</span></label>
- <label><input type="checkbox" class="status-filter" value="unconfirmed" checked /> <span class="legend"><span class="dot" style="background: var(--unconfirmed)"></span>unconfirmed</span></label>
- <label><input type="checkbox" class="status-filter" value="quarantine" checked /> <span class="legend"><span class="dot" style="background: var(--quarantine)"></span>quarantine</span></label>
- <label><input type="checkbox" class="status-filter" value="retired" checked /> <span class="legend"><span class="dot" style="background: var(--retired)"></span>retired</span></label>
- <h3>Legend</h3>
- <div class="stats">
- Node size grows with applied_count.<br />
- Gold ring = pinned.<br />
- Red dashed edge = supersedes.<br />
- Grey edge = wikilink.
- </div>
-</aside>
-<main>
- <canvas id="canvas"></canvas>
-</main>
-<aside id="details" class="right">
- <h3>Nodes</h3>
- <ul
- id="node-list"
- role="listbox"
- tabindex="0"
- aria-label="Brain preferences"
- aria-activedescendant=""
- ></ul>
- <button id="reset-layout" type="button" class="id-copy">Reset layout</button>
- <hr />
- <div id="details-body">
- <p class="panel-empty">Select a node to inspect.</p>
- </div>
-</aside>
-
-<script type="application/json" id="brain-data">__GRAPH_JSON__</script>
-<script>
-"use strict";
-
-(function () {
- const dataEl = document.getElementById("brain-data");
- let graph;
- try {
- graph = JSON.parse(dataEl.textContent);
- } catch (e) {
- document.getElementById("details-body").textContent = "Failed to parse graph data: " + e.message;
- return;
- }
- const VAULT_PATH = "__VAULT_PATH__";
-
- document.getElementById("vault-name").textContent = graph.vault_basename || "(unnamed vault)";
- document.getElementById("stats").textContent =
- graph.nodes.length + " nodes, " + graph.edges.length + " edges";
-
- const canvas = document.getElementById("canvas");
- const ctx = canvas.getContext("2d");
- const COLORS = {
- confirmed: "#2f9e44",
- unconfirmed: "#f59f00",
- quarantine: "#e8590c",
- retired: "#868e96",
- pinned: "#f9c74f",
- edge: "#cfcfcf",
- "edge-supersedes": "#c92a2a",
- };
-
- function showTooltip(text) {
- let tip = document.getElementById("deeplink-tooltip");
- if (!tip) {
- tip = document.createElement("div");
- tip.id = "deeplink-tooltip";
- tip.style.cssText = "position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:#333;color:#fff;padding:8px 16px;border-radius:4px;font-size:12px;z-index:9999;transition:opacity 0.3s;";
- document.body.appendChild(tip);
- }
- tip.textContent = text;
- tip.style.opacity = "1";
- clearTimeout(tip._timer);
- tip._timer = setTimeout(() => { tip.style.opacity = "0"; }, 3000);
- }
-
- // ---- State -------------------------------------------------------------
- const nodes = graph.nodes.map((n) => ({
- ...n,
- x: 0,
- y: 0,
- vx: 0,
- vy: 0,
- radius: Math.max(8, Math.min(40, 8 + Math.sqrt(n.applied_count) * 6)),
- visible: true,
- }));
- const nodeById = new Map(nodes.map((n) => [n.id, n]));
- const edges = graph.edges
- .map((e) => ({ ...e, sNode: nodeById.get(e.source), tNode: nodeById.get(e.target) }))
- .filter((e) => e.sNode && e.tNode);
-
- // Topic centres for soft clustering.
- const topics = new Map();
- for (const n of nodes) {
- if (!topics.has(n.topic)) {
- topics.set(n.topic, { x: 0, y: 0, count: 0 });
- }
- topics.get(n.topic).count++;
- }
-
- // Filter state.
- const statusFilters = new Set(["confirmed", "unconfirmed", "quarantine", "retired"]);
- let searchTerm = "";
-
- // §14 polish: layout + filter persistence (localStorage). Per-vault
- // key so multiple explorer tabs against different vaults stay
- // separate. Stored shape:
- // { schema: 1, positions: { id: [x, y] }, filters: { status: [...], search: string } }
- // Failures (private mode, quota, malformed JSON) degrade silently
- // to a non-persistent session.
- const STORAGE_KEY =
- "osb-explorer-layout:" + (graph.vault_basename || "default");
- const STORAGE_SCHEMA = 1;
- let storedLayout = null;
- try {
- const raw = localStorage.getItem(STORAGE_KEY);
- if (raw !== null) {
- const parsed = JSON.parse(raw);
- if (parsed && parsed.schema === STORAGE_SCHEMA) storedLayout = parsed;
- }
- } catch (e) {
- storedLayout = null;
- }
- if (storedLayout && storedLayout.filters) {
- if (Array.isArray(storedLayout.filters.status)) {
- statusFilters.clear();
- for (const s of storedLayout.filters.status) statusFilters.add(s);
- }
- if (typeof storedLayout.filters.search === "string") {
- searchTerm = storedLayout.filters.search;
- }
- }
-
- // ---- Layout -----------------------------------------------------------
- function placeInitial() {
- const w = canvas.width;
- const h = canvas.height;
- const cx = w / 2;
- const cy = h / 2;
- // Place topic centres on a circle.
- const topicNames = Array.from(topics.keys());
- topicNames.forEach((name, i) => {
- const angle = (i / Math.max(1, topicNames.length)) * Math.PI * 2;
- const r = Math.min(w, h) * 0.25;
- const t = topics.get(name);
- t.x = cx + Math.cos(angle) * r;
- t.y = cy + Math.sin(angle) * r;
- });
- // Place each node near its topic centre with jitter.
- for (const n of nodes) {
- const t = topics.get(n.topic);
- n.x = t.x + (Math.random() - 0.5) * 80;
- n.y = t.y + (Math.random() - 0.5) * 80;
- }
- // Overlay stored positions on top of the topic-based seed. New
- // nodes (no entry in the stored map) keep their topic-anchored
- // placement; previously-seen nodes warm-start to the last
- // observed location so the layout no longer "jumps" between
- // reloads. We zero velocity so the physics relaxes from rest.
- if (storedLayout && storedLayout.positions) {
- for (const n of nodes) {
- const stored = storedLayout.positions[n.id];
- if (Array.isArray(stored) && stored.length === 2
- && Number.isFinite(stored[0]) && Number.isFinite(stored[1])) {
- n.x = stored[0];
- n.y = stored[1];
- n.vx = 0;
- n.vy = 0;
- }
+ #node-list {
+ list-style: none;
+ margin: 0 0 6px 0;
+ padding: 0;
+ max-height: 220px;
+ overflow: auto;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: var(--bg);
+ }
+ #node-list li {
+ padding: 4px 8px;
+ cursor: pointer;
+ font-size: 12px;
+ border-bottom: 1px solid transparent;
}
- }
- }
+ #node-list li .topic {
+ color: var(--muted);
+ font-size: 11px;
+ margin-right: 4px;
+ }
+ #node-list li[aria-selected="true"] {
+ background: var(--accent);
+ color: #fff;
+ }
+ #node-list li[aria-selected="true"] .topic {
+ color: rgba(255, 255, 255, 0.85);
+ }
+ #node-list:focus {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+ }
+ #node-list-empty {
+ padding: 6px 8px;
+ color: var(--muted);
+ font-style: italic;
+ font-size: 12px;
+ }
+ </style>
+ </head>
+ <body>
+ <header>
+ <span class="title">Brain Explorer</span>
+ <span id="vault-name" class="meta"></span>
+ <span id="stats" class="stats"></span>
+ </header>
+ <aside class="left">
+ <h3>Search</h3>
+ <input id="search" type="search" placeholder="topic or principle..." />
+ <h3>Status</h3>
+ <label
+ ><input
+ type="checkbox"
+ class="status-filter"
+ value="confirmed"
+ checked
+ />
+ <span class="legend"
+ ><span class="dot" style="background: var(--confirmed)"></span
+ >confirmed</span
+ ></label
+ >
+ <label
+ ><input
+ type="checkbox"
+ class="status-filter"
+ value="unconfirmed"
+ checked
+ />
+ <span class="legend"
+ ><span class="dot" style="background: var(--unconfirmed)"></span
+ >unconfirmed</span
+ ></label
+ >
+ <label
+ ><input
+ type="checkbox"
+ class="status-filter"
+ value="quarantine"
+ checked
+ />
+ <span class="legend"
+ ><span class="dot" style="background: var(--quarantine)"></span
+ >quarantine</span
+ ></label
+ >
+ <label
+ ><input type="checkbox" class="status-filter" value="retired" checked />
+ <span class="legend"
+ ><span class="dot" style="background: var(--retired)"></span
+ >retired</span
+ ></label
+ >
+ <h3>Legend</h3>
+ <div class="stats">
+ Node size grows with applied_count.<br />
+ Gold ring = pinned.<br />
+ Red dashed edge = supersedes.<br />
+ Grey edge = wikilink.
+ </div>
+ </aside>
+ <main>
+ <canvas id="canvas"></canvas>
+ </main>
+ <aside id="details" class="right">
+ <h3>Nodes</h3>
+ <ul
+ id="node-list"
+ role="listbox"
+ tabindex="0"
+ aria-label="Brain preferences"
+ aria-activedescendant=""
+ ></ul>
+ <button id="reset-layout" type="button" class="id-copy">
+ Reset layout
+ </button>
+ <hr />
+ <div id="details-body">
+ <p class="panel-empty">Select a node to inspect.</p>
+ </div>
+ </aside>
+
+ <script type="application/json" id="brain-data">
+ __GRAPH_JSON__
+ </script>
+ <script>
+ "use strict";
- function saveLayout() {
- try {
- const positions = {};
- for (const n of nodes) {
- if (Number.isFinite(n.x) && Number.isFinite(n.y)) {
- positions[n.id] = [Math.round(n.x * 10) / 10, Math.round(n.y * 10) / 10];
+ (function () {
+ const dataEl = document.getElementById("brain-data");
+ let graph;
+ try {
+ graph = JSON.parse(dataEl.textContent);
+ } catch (e) {
+ document.getElementById("details-body").textContent =
+ "Failed to parse graph data: " + e.message;
+ return;
}
- }
- const payload = {
- schema: STORAGE_SCHEMA,
- positions,
- filters: {
- status: Array.from(statusFilters),
- search: searchTerm,
- },
- };
- localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
- } catch (e) {
- // Quota or disabled storage — non-persistent session.
- }
- }
-
- let saveTimer = null;
- function scheduleSave(delayMs) {
- if (saveTimer !== null) clearTimeout(saveTimer);
- saveTimer = setTimeout(() => {
- saveTimer = null;
- saveLayout();
- }, delayMs);
- }
-
- const K_TOPIC = 0.006;
- const K_CHARGE = 700;
- const K_SPRING = 0.04;
- const DAMPING = 0.85;
- const MAX_V = 12;
-
- function step() {
- const w = canvas.width;
- const h = canvas.height;
- // Topic attraction.
- for (const n of nodes) {
- if (!n.visible) continue;
- const t = topics.get(n.topic);
- n.vx += (t.x - n.x) * K_TOPIC;
- n.vy += (t.y - n.y) * K_TOPIC;
- }
- // Charge repulsion (pairwise — fine for O(N^2) at N ≤ 300).
- for (let i = 0; i < nodes.length; i++) {
- const a = nodes[i];
- if (!a.visible) continue;
- for (let j = i + 1; j < nodes.length; j++) {
- const b = nodes[j];
- if (!b.visible) continue;
- const dx = a.x - b.x;
- const dy = a.y - b.y;
- const d2 = dx * dx + dy * dy + 0.01;
- const f = K_CHARGE / d2;
- const d = Math.sqrt(d2);
- const fx = (dx / d) * f;
- const fy = (dy / d) * f;
- a.vx += fx; a.vy += fy;
- b.vx -= fx; b.vy -= fy;
- }
- }
- // Edge springs.
- for (const e of edges) {
- if (!e.sNode.visible || !e.tNode.visible) continue;
- const dx = e.tNode.x - e.sNode.x;
- const dy = e.tNode.y - e.sNode.y;
- const d = Math.sqrt(dx * dx + dy * dy) + 0.01;
- const rest = e.sNode.radius + e.tNode.radius + 40;
- const f = (d - rest) * K_SPRING;
- const fx = (dx / d) * f;
- const fy = (dy / d) * f;
- e.sNode.vx += fx; e.sNode.vy += fy;
- e.tNode.vx -= fx; e.tNode.vy -= fy;
- }
- // Damping + integrate + clamp.
- for (const n of nodes) {
- if (!n.visible) continue;
- n.vx *= DAMPING;
- n.vy *= DAMPING;
- if (n.vx > MAX_V) n.vx = MAX_V; else if (n.vx < -MAX_V) n.vx = -MAX_V;
- if (n.vy > MAX_V) n.vy = MAX_V; else if (n.vy < -MAX_V) n.vy = -MAX_V;
- n.x += n.vx;
- n.y += n.vy;
- // Soft wall.
- const pad = 30;
- if (n.x < pad) { n.x = pad; n.vx *= -0.3; }
- if (n.x > w - pad) { n.x = w - pad; n.vx *= -0.3; }
- if (n.y < pad) { n.y = pad; n.vy *= -0.3; }
- if (n.y > h - pad) { n.y = h - pad; n.vy *= -0.3; }
- }
- }
-
- // ---- Render -----------------------------------------------------------
- let selectedId = null;
- let hoverId = null;
-
- function render() {
- const w = canvas.width;
- const h = canvas.height;
- ctx.clearRect(0, 0, w, h);
- // Edges.
- ctx.lineWidth = 1;
- for (const e of edges) {
- if (!e.sNode.visible || !e.tNode.visible) continue;
- ctx.beginPath();
- ctx.moveTo(e.sNode.x, e.sNode.y);
- ctx.lineTo(e.tNode.x, e.tNode.y);
- if (e.kind === "supersedes") {
- ctx.strokeStyle = COLORS["edge-supersedes"];
- ctx.setLineDash([4, 4]);
- } else {
- ctx.strokeStyle = COLORS.edge;
- ctx.setLineDash([]);
- }
- ctx.stroke();
- }
- ctx.setLineDash([]);
- // Nodes.
- for (const n of nodes) {
- if (!n.visible) continue;
- ctx.beginPath();
- ctx.arc(n.x, n.y, n.radius, 0, Math.PI * 2);
- ctx.fillStyle = COLORS[n.status] || COLORS.unconfirmed;
- ctx.fill();
- if (n.pinned) {
- ctx.lineWidth = 3;
- ctx.strokeStyle = COLORS.pinned;
- ctx.stroke();
- }
- if (n.id === selectedId || n.id === hoverId) {
- ctx.lineWidth = 2;
- ctx.strokeStyle = "#1a1a1a";
- ctx.stroke();
- }
- }
- // Hover tooltip.
- if (hoverId) {
- const h = nodeById.get(hoverId);
- if (h && h.visible) {
- const label = h.principle.length > 80 ? h.principle.slice(0, 77) + "..." : h.principle;
- ctx.font = "12px system-ui";
- const metrics = ctx.measureText(label);
- const padX = 6, padY = 4;
- const x = h.x + h.radius + 6;
- const y = h.y - h.radius;
- ctx.fillStyle = "rgba(0, 0, 0, 0.78)";
- ctx.fillRect(x, y, metrics.width + padX * 2, 18 + padY);
- ctx.fillStyle = "#fff";
- ctx.fillText(label, x + padX, y + 14);
- }
- }
- }
-
- // ---- Hit test, panel render ------------------------------------------
- function findNode(px, py) {
- for (let i = nodes.length - 1; i >= 0; i--) {
- const n = nodes[i];
- if (!n.visible) continue;
- const dx = px - n.x;
- const dy = py - n.y;
- if (dx * dx + dy * dy <= n.radius * n.radius) return n;
- }
- return null;
- }
-
- function renderPanel(n) {
- const root = document.getElementById("details-body");
- if (!n) {
- root.innerHTML = '<p class="panel-empty">Select a node to inspect.</p>';
- return;
- }
- const inbound = edges.filter((e) => e.target === n.id);
- const outbound = edges.filter((e) => e.source === n.id);
- const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" }[c]));
- const html = [
- '<div class="field"><span class="k">id</span><span class="v"><code>' + esc(n.id) + '</code></span></div>',
- '<div class="principle">' + esc(n.principle) + '</div>',
- '<div class="field"><span class="k">topic</span><span class="v">' + esc(n.topic) + '</span></div>',
- n.scope ? '<div class="field"><span class="k">scope</span><span class="v">' + esc(n.scope) + '</span></div>' : "",
- '<div class="field"><span class="k">status</span><span class="v"><span class="pill ' + n.status + '">' + n.status + '</span>'
- + (n.confidence ? ' <span class="pill">' + n.confidence + (n.confidence_value !== null ? ' (' + n.confidence_value.toFixed(2) + ')' : '') + '</span>' : '')
- + '</span></div>',
- '<div class="field"><span class="k">applied</span><span class="v">' + n.applied_count + '</span></div>',
- '<div class="field"><span class="k">violated</span><span class="v">' + n.violated_count + '</span></div>',
- n.pinned ? '<div class="field"><span class="k">pinned</span><span class="v">yes</span></div>' : "",
- n.last_evidence_at ? '<div class="field"><span class="k">last evidence</span><span class="v">' + esc(n.last_evidence_at) + '</span></div>' : "",
- '<div class="field"><span class="k">backlinks</span><span class="v">' + n.backlink_count + ' inbound</span></div>',
- n.retired_reason ? '<div class="field"><span class="k">retired reason</span><span class="v">' + esc(n.retired_reason) + '</span></div>' : "",
- "<h3>Outbound</h3>",
- outbound.length === 0
- ? '<p class="panel-empty">none</p>'
- : '<ul class="edge-list">' + outbound.map((e) => '<li>' + esc(e.target) + ' <span class="kind">[' + e.kind + ']</span></li>').join("") + '</ul>',
- "<h3>Inbound</h3>",
- inbound.length === 0
- ? '<p class="panel-empty">none</p>'
- : '<ul class="edge-list">' + inbound.map((e) => '<li>' + esc(e.source) + ' <span class="kind">[' + e.kind + ']</span></li>').join("") + '</ul>',
- ].join("");
- root.innerHTML = html;
- }
-
- // ---- Filtering -------------------------------------------------------
- function applyFilters() {
- const term = searchTerm.toLowerCase();
- for (const n of nodes) {
- const statusOk = statusFilters.has(n.status);
- const textOk = !term
- || n.principle.toLowerCase().includes(term)
- || n.topic.toLowerCase().includes(term)
- || n.id.toLowerCase().includes(term);
- n.visible = statusOk && textOk;
- }
- rebuildVisibleSorted();
- scheduleListRender();
- }
-
- // ---- Listbox (keyboard-accessible mirror of the canvas) --------------
- // The visible nodes are also presented as a focusable <ul role="listbox">.
- // Pointer users keep the canvas; keyboard and screen reader users get
- // the listbox. Both surfaces call `selectNode(id)` so state stays in
- // lockstep across input devices.
- // `visibleSortedCache` is rebuilt by `applyFilters` and consumed by
- // `renderNodeList` / `moveListboxFocus` — saves an O(N log N) sort
- // on every Arrow key on large vaults.
- let visibleSortedCache = [];
- let renderNodeListPending = false;
-
- function escHtml(s) {
- return String(s).replace(/[&<>"]/g, (c) => ({
- "&": "&amp;",
- "<": "&lt;",
- ">": "&gt;",
- '"': "&quot;",
- }[c]));
- }
-
- function rebuildVisibleSorted() {
- visibleSortedCache = nodes
- .filter((n) => n.visible)
- .slice()
- .sort((a, b) => {
- const t = a.topic.localeCompare(b.topic);
- return t !== 0 ? t : a.id.localeCompare(b.id);
- });
- }
-
- function renderNodeList() {
- const list = document.getElementById("node-list");
- const visible = visibleSortedCache;
- if (visible.length === 0) {
- list.innerHTML = '<li id="node-list-empty">No matching nodes.</li>';
- list.setAttribute("aria-activedescendant", "");
- return;
- }
- list.innerHTML = visible
- .map((n) => {
- const selected = n.id === selectedId ? ' aria-selected="true"' : ' aria-selected="false"';
- const title = n.principle.length > 80 ? n.principle.slice(0, 77) + "..." : n.principle;
- return (
- '<li role="option" id="node-opt-' + escHtml(n.id) + '"' + selected +
- ' data-node-id="' + escHtml(n.id) + '">' +
- '<span class="topic">' + escHtml(n.topic) + '</span>' +
- escHtml(title) +
- '</li>'
- );
- })
- .join("");
- list.setAttribute(
- "aria-activedescendant",
- selectedId ? "node-opt-" + selectedId : "",
- );
- // Bind per-item click handlers via event delegation (cheap and
- // survives the full re-render above).
- list.onclick = (ev) => {
- const li = ev.target.closest("li[data-node-id]");
- if (!li) return;
- selectNode(li.getAttribute("data-node-id"));
- };
- list.ondblclick = (ev) => {
- if (!VAULT_PATH) return;
- const li = ev.target.closest("li[data-node-id]");
- if (!li) return;
- const nodeId = li.getAttribute("data-node-id");
- const filePath = VAULT_PATH + (nodeId.startsWith("ret-")
- ? "/Brain/retired/" : "/Brain/preferences/") + nodeId + ".md";
- const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
- window.open(uri, "_blank");
- };
- }
-
- // Defer the listbox rebuild to the next animation frame so a held-
- // down filter key only re-renders the <ul> once per paint instead
- // of per keystroke. The canvas-side render is on its own rAF loop
- // and is unaffected.
- function scheduleListRender() {
- if (renderNodeListPending) return;
- renderNodeListPending = true;
- requestAnimationFrame(() => {
- renderNodeListPending = false;
- renderNodeList();
- });
- }
-
- function selectNode(id) {
- selectedId = id || null;
- const n = id ? nodeById.get(id) : null;
- renderPanel(n);
- // Mirror selection into the listbox without rebuilding the full
- // DOM (cheaper, preserves scroll position).
- const list = document.getElementById("node-list");
- for (const li of list.querySelectorAll('li[data-node-id]')) {
- li.setAttribute("aria-selected", li.getAttribute("data-node-id") === id ? "true" : "false");
- }
- list.setAttribute("aria-activedescendant", id ? "node-opt-" + id : "");
- if (id) {
- const focused = list.querySelector('li[data-node-id="' + id + '"]');
- if (focused && focused.scrollIntoView) {
- focused.scrollIntoView({ block: "nearest" });
- }
- }
- }
-
- function moveListboxFocus(delta) {
- const visible = visibleSortedCache;
- if (visible.length === 0) return;
- const cur = selectedId
- ? visible.findIndex((n) => n.id === selectedId)
- : -1;
- let next;
- if (cur === -1) {
- next = delta > 0 ? 0 : visible.length - 1;
- } else {
- next = (cur + delta + visible.length) % visible.length;
- }
- selectNode(visible[next].id);
- }
-
- // ---- Wire up DOM events ----------------------------------------------
- function resizeCanvas() {
- const r = canvas.getBoundingClientRect();
- canvas.width = Math.max(100, Math.floor(r.width));
- canvas.height = Math.max(100, Math.floor(r.height));
- }
- window.addEventListener("resize", resizeCanvas);
-
- canvas.addEventListener("mousemove", (e) => {
- const r = canvas.getBoundingClientRect();
- const x = e.clientX - r.left;
- const y = e.clientY - r.top;
- const n = findNode(x, y);
- hoverId = n ? n.id : null;
- });
- canvas.addEventListener("click", (e) => {
- const r = canvas.getBoundingClientRect();
- const x = e.clientX - r.left;
- const y = e.clientY - r.top;
- const n = findNode(x, y);
- selectNode(n ? n.id : null);
- });
- canvas.addEventListener("dblclick", (e) => {
- if (!VAULT_PATH) return;
- const r = canvas.getBoundingClientRect();
- const x = e.clientX - r.left;
- const y = e.clientY - r.top;
- const n = findNode(x, y);
- if (!n) return;
- const filePath = VAULT_PATH + (n.id.startsWith("ret-")
- ? "/Brain/retired/" : "/Brain/preferences/") + n.id + ".md";
- const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
- const opened = window.open(uri, "_blank");
- if (!opened) {
- navigator.clipboard.writeText(filePath).then(() => {
- showTooltip("Obsidian not detected — path copied to clipboard");
- }).catch(() => {
- showTooltip("Path: " + filePath);
- });
- }
- });
-
- // §14 polish: keyboard handlers on the listbox. The listbox is
- // `tabindex="0"`, so it joins the natural tab order after the
- // search input.
- const nodeList = document.getElementById("node-list");
- nodeList.addEventListener("keydown", (e) => {
- switch (e.key) {
- case "ArrowDown":
- e.preventDefault();
- moveListboxFocus(+1);
- break;
- case "ArrowUp":
- e.preventDefault();
- moveListboxFocus(-1);
- break;
- case "Home":
- e.preventDefault();
- if (visibleSortedCache.length > 0) {
- selectNode(visibleSortedCache[0].id);
+ const VAULT_PATH = "__VAULT_PATH__";
+
+ document.getElementById("vault-name").textContent =
+ graph.vault_basename || "(unnamed vault)";
+ document.getElementById("stats").textContent =
+ graph.nodes.length + " nodes, " + graph.edges.length + " edges";
+
+ const canvas = document.getElementById("canvas");
+ const ctx = canvas.getContext("2d");
+ const COLORS = {
+ confirmed: "#2f9e44",
+ unconfirmed: "#f59f00",
+ quarantine: "#e8590c",
+ retired: "#868e96",
+ pinned: "#f9c74f",
+ edge: "#cfcfcf",
+ "edge-supersedes": "#c92a2a",
+ };
+
+ function showTooltip(text) {
+ let tip = document.getElementById("deeplink-tooltip");
+ if (!tip) {
+ tip = document.createElement("div");
+ tip.id = "deeplink-tooltip";
+ tip.style.cssText =
+ "position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:#333;color:#fff;padding:8px 16px;border-radius:4px;font-size:12px;z-index:9999;transition:opacity 0.3s;";
+ document.body.appendChild(tip);
+ }
+ tip.textContent = text;
+ tip.style.opacity = "1";
+ clearTimeout(tip._timer);
+ tip._timer = setTimeout(() => {
+ tip.style.opacity = "0";
+ }, 3000);
}
- break;
- case "End":
- e.preventDefault();
- if (visibleSortedCache.length > 0) {
- selectNode(visibleSortedCache[visibleSortedCache.length - 1].id);
+
+ // ---- State -------------------------------------------------------------
+ const nodes = graph.nodes.map((n) => ({
+ ...n,
+ x: 0,
+ y: 0,
+ vx: 0,
+ vy: 0,
+ radius: Math.max(8, Math.min(40, 8 + Math.sqrt(n.applied_count) * 6)),
+ visible: true,
+ }));
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
+ const edges = graph.edges
+ .map((e) => ({
+ ...e,
+ sNode: nodeById.get(e.source),
+ tNode: nodeById.get(e.target),
+ }))
+ .filter((e) => e.sNode && e.tNode);
+
+ // Topic centres for soft clustering.
+ const topics = new Map();
+ for (const n of nodes) {
+ if (!topics.has(n.topic)) {
+ topics.set(n.topic, { x: 0, y: 0, count: 0 });
+ }
+ topics.get(n.topic).count++;
+ }
+
+ // Filter state.
+ const statusFilters = new Set([
+ "confirmed",
+ "unconfirmed",
+ "quarantine",
+ "retired",
+ ]);
+ let searchTerm = "";
+
+ // §14 polish: layout + filter persistence (localStorage). Per-vault
+ // key so multiple explorer tabs against different vaults stay
+ // separate. Stored shape:
+ // { schema: 1, positions: { id: [x, y] }, filters: { status: [...], search: string } }
+ // Failures (private mode, quota, malformed JSON) degrade silently
+ // to a non-persistent session.
+ const STORAGE_KEY =
+ "osb-explorer-layout:" + (graph.vault_basename || "default");
+ const STORAGE_SCHEMA = 1;
+ let storedLayout = null;
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (raw !== null) {
+ const parsed = JSON.parse(raw);
+ if (parsed && parsed.schema === STORAGE_SCHEMA)
+ storedLayout = parsed;
+ }
+ } catch (e) {
+ storedLayout = null;
+ }
+ if (storedLayout && storedLayout.filters) {
+ if (Array.isArray(storedLayout.filters.status)) {
+ statusFilters.clear();
+ for (const s of storedLayout.filters.status) statusFilters.add(s);
+ }
+ if (typeof storedLayout.filters.search === "string") {
+ searchTerm = storedLayout.filters.search;
+ }
+ }
+
+ // ---- Layout -----------------------------------------------------------
+ function placeInitial() {
+ const w = canvas.width;
+ const h = canvas.height;
+ const cx = w / 2;
+ const cy = h / 2;
+ // Place topic centres on a circle.
+ const topicNames = Array.from(topics.keys());
+ topicNames.forEach((name, i) => {
+ const angle = (i / Math.max(1, topicNames.length)) * Math.PI * 2;
+ const r = Math.min(w, h) * 0.25;
+ const t = topics.get(name);
+ t.x = cx + Math.cos(angle) * r;
+ t.y = cy + Math.sin(angle) * r;
+ });
+ // Place each node near its topic centre with jitter.
+ for (const n of nodes) {
+ const t = topics.get(n.topic);
+ n.x = t.x + (Math.random() - 0.5) * 80;
+ n.y = t.y + (Math.random() - 0.5) * 80;
+ }
+ // Overlay stored positions on top of the topic-based seed. New
+ // nodes (no entry in the stored map) keep their topic-anchored
+ // placement; previously-seen nodes warm-start to the last
+ // observed location so the layout no longer "jumps" between
+ // reloads. We zero velocity so the physics relaxes from rest.
+ if (storedLayout && storedLayout.positions) {
+ for (const n of nodes) {
+ const stored = storedLayout.positions[n.id];
+ if (
+ Array.isArray(stored) &&
+ stored.length === 2 &&
+ Number.isFinite(stored[0]) &&
+ Number.isFinite(stored[1])
+ ) {
+ n.x = stored[0];
+ n.y = stored[1];
+ n.vx = 0;
+ n.vy = 0;
+ }
+ }
+ }
+ }
+
+ function saveLayout() {
+ try {
+ const positions = {};
+ for (const n of nodes) {
+ if (Number.isFinite(n.x) && Number.isFinite(n.y)) {
+ positions[n.id] = [
+ Math.round(n.x * 10) / 10,
+ Math.round(n.y * 10) / 10,
+ ];
+ }
+ }
+ const payload = {
+ schema: STORAGE_SCHEMA,
+ positions,
+ filters: {
+ status: Array.from(statusFilters),
+ search: searchTerm,
+ },
+ };
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
+ } catch (e) {
+ // Quota or disabled storage — non-persistent session.
+ }
+ }
+
+ let saveTimer = null;
+ function scheduleSave(delayMs) {
+ if (saveTimer !== null) clearTimeout(saveTimer);
+ saveTimer = setTimeout(() => {
+ saveTimer = null;
+ saveLayout();
+ }, delayMs);
+ }
+
+ const K_TOPIC = 0.006;
+ const K_CHARGE = 700;
+ const K_SPRING = 0.04;
+ const DAMPING = 0.85;
+ const MAX_V = 12;
+
+ function step() {
+ const w = canvas.width;
+ const h = canvas.height;
+ // Topic attraction.
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ const t = topics.get(n.topic);
+ n.vx += (t.x - n.x) * K_TOPIC;
+ n.vy += (t.y - n.y) * K_TOPIC;
+ }
+ // Charge repulsion (pairwise — fine for O(N^2) at N ≤ 300).
+ for (let i = 0; i < nodes.length; i++) {
+ const a = nodes[i];
+ if (!a.visible) continue;
+ for (let j = i + 1; j < nodes.length; j++) {
+ const b = nodes[j];
+ if (!b.visible) continue;
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ const d2 = dx * dx + dy * dy + 0.01;
+ const f = K_CHARGE / d2;
+ const d = Math.sqrt(d2);
+ const fx = (dx / d) * f;
+ const fy = (dy / d) * f;
+ a.vx += fx;
+ a.vy += fy;
+ b.vx -= fx;
+ b.vy -= fy;
+ }
+ }
+ // Edge springs.
+ for (const e of edges) {
+ if (!e.sNode.visible || !e.tNode.visible) continue;
+ const dx = e.tNode.x - e.sNode.x;
+ const dy = e.tNode.y - e.sNode.y;
+ const d = Math.sqrt(dx * dx + dy * dy) + 0.01;
+ const rest = e.sNode.radius + e.tNode.radius + 40;
+ const f = (d - rest) * K_SPRING;
+ const fx = (dx / d) * f;
+ const fy = (dy / d) * f;
+ e.sNode.vx += fx;
+ e.sNode.vy += fy;
+ e.tNode.vx -= fx;
+ e.tNode.vy -= fy;
+ }
+ // Damping + integrate + clamp.
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ n.vx *= DAMPING;
+ n.vy *= DAMPING;
+ if (n.vx > MAX_V) n.vx = MAX_V;
+ else if (n.vx < -MAX_V) n.vx = -MAX_V;
+ if (n.vy > MAX_V) n.vy = MAX_V;
+ else if (n.vy < -MAX_V) n.vy = -MAX_V;
+ n.x += n.vx;
+ n.y += n.vy;
+ // Soft wall.
+ const pad = 30;
+ if (n.x < pad) {
+ n.x = pad;
+ n.vx *= -0.3;
+ }
+ if (n.x > w - pad) {
+ n.x = w - pad;
+ n.vx *= -0.3;
+ }
+ if (n.y < pad) {
+ n.y = pad;
+ n.vy *= -0.3;
+ }
+ if (n.y > h - pad) {
+ n.y = h - pad;
+ n.vy *= -0.3;
+ }
+ }
+ }
+
+ // ---- Render -----------------------------------------------------------
+ let selectedId = null;
+ let hoverId = null;
+
+ function render() {
+ const w = canvas.width;
+ const h = canvas.height;
+ ctx.clearRect(0, 0, w, h);
+ // Edges.
+ ctx.lineWidth = 1;
+ for (const e of edges) {
+ if (!e.sNode.visible || !e.tNode.visible) continue;
+ ctx.beginPath();
+ ctx.moveTo(e.sNode.x, e.sNode.y);
+ ctx.lineTo(e.tNode.x, e.tNode.y);
+ if (e.kind === "supersedes") {
+ ctx.strokeStyle = COLORS["edge-supersedes"];
+ ctx.setLineDash([4, 4]);
+ } else {
+ ctx.strokeStyle = COLORS.edge;
+ ctx.setLineDash([]);
+ }
+ ctx.stroke();
+ }
+ ctx.setLineDash([]);
+ // Nodes.
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ ctx.beginPath();
+ ctx.arc(n.x, n.y, n.radius, 0, Math.PI * 2);
+ ctx.fillStyle = COLORS[n.status] || COLORS.unconfirmed;
+ ctx.fill();
+ if (n.pinned) {
+ ctx.lineWidth = 3;
+ ctx.strokeStyle = COLORS.pinned;
+ ctx.stroke();
+ }
+ if (n.id === selectedId || n.id === hoverId) {
+ ctx.lineWidth = 2;
+ ctx.strokeStyle = "#1a1a1a";
+ ctx.stroke();
+ }
+ }
+ // Hover tooltip.
+ if (hoverId) {
+ const h = nodeById.get(hoverId);
+ if (h && h.visible) {
+ const label =
+ h.principle.length > 80
+ ? h.principle.slice(0, 77) + "..."
+ : h.principle;
+ ctx.font = "12px system-ui";
+ const metrics = ctx.measureText(label);
+ const padX = 6,
+ padY = 4;
+ const x = h.x + h.radius + 6;
+ const y = h.y - h.radius;
+ ctx.fillStyle = "rgba(0, 0, 0, 0.78)";
+ ctx.fillRect(x, y, metrics.width + padX * 2, 18 + padY);
+ ctx.fillStyle = "#fff";
+ ctx.fillText(label, x + padX, y + 14);
+ }
+ }
+ }
+
+ // ---- Hit test, panel render ------------------------------------------
+ function findNode(px, py) {
+ for (let i = nodes.length - 1; i >= 0; i--) {
+ const n = nodes[i];
+ if (!n.visible) continue;
+ const dx = px - n.x;
+ const dy = py - n.y;
+ if (dx * dx + dy * dy <= n.radius * n.radius) return n;
+ }
+ return null;
+ }
+
+ function renderPanel(n) {
+ const root = document.getElementById("details-body");
+ if (!n) {
+ root.innerHTML =
+ '<p class="panel-empty">Select a node to inspect.</p>';
+ return;
+ }
+ const inbound = edges.filter((e) => e.target === n.id);
+ const outbound = edges.filter((e) => e.source === n.id);
+ const esc = (s) =>
+ String(s).replace(
+ /[&<>]/g,
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c],
+ );
+ const edgeLabel = (e) => e.relation || e.kind;
+ const html = [
+ '<div class="field"><span class="k">id</span><span class="v"><code>' +
+ esc(n.id) +
+ "</code></span></div>",
+ '<div class="principle">' + esc(n.principle) + "</div>",
+ '<div class="field"><span class="k">topic</span><span class="v">' +
+ esc(n.topic) +
+ "</span></div>",
+ n.scope
+ ? '<div class="field"><span class="k">scope</span><span class="v">' +
+ esc(n.scope) +
+ "</span></div>"
+ : "",
+ n.memory_layer
+ ? '<div class="field"><span class="k">memory layer</span><span class="v">' +
+ esc(n.memory_layer) +
+ "</span></div>"
+ : "",
+ n.memory_branch
+ ? '<div class="field"><span class="k">memory branch</span><span class="v">' +
+ esc(n.memory_branch) +
+ "</span></div>"
+ : "",
+ '<div class="field"><span class="k">status</span><span class="v"><span class="pill ' +
+ n.status +
+ '">' +
+ n.status +
+ "</span>" +
+ (n.confidence
+ ? ' <span class="pill">' +
+ n.confidence +
+ (n.confidence_value !== null
+ ? " (" + n.confidence_value.toFixed(2) + ")"
+ : "") +
+ "</span>"
+ : "") +
+ "</span></div>",
+ '<div class="field"><span class="k">applied</span><span class="v">' +
+ n.applied_count +
+ "</span></div>",
+ '<div class="field"><span class="k">violated</span><span class="v">' +
+ n.violated_count +
+ "</span></div>",
+ n.pinned
+ ? '<div class="field"><span class="k">pinned</span><span class="v">yes</span></div>'
+ : "",
+ n.last_evidence_at
+ ? '<div class="field"><span class="k">last evidence</span><span class="v">' +
+ esc(n.last_evidence_at) +
+ "</span></div>"
+ : "",
+ '<div class="field"><span class="k">backlinks</span><span class="v">' +
+ n.backlink_count +
+ " inbound</span></div>",
+ n.retired_reason
+ ? '<div class="field"><span class="k">retired reason</span><span class="v">' +
+ esc(n.retired_reason) +
+ "</span></div>"
+ : "",
+ "<h3>Outbound</h3>",
+ outbound.length === 0
+ ? '<p class="panel-empty">none</p>'
+ : '<ul class="edge-list">' +
+ outbound
+ .map(
+ (e) =>
+ "<li>" +
+ esc(e.target) +
+ ' <span class="kind">[' +
+ esc(edgeLabel(e)) +
+ "]</span></li>",
+ )
+ .join("") +
+ "</ul>",
+ "<h3>Inbound</h3>",
+ inbound.length === 0
+ ? '<p class="panel-empty">none</p>'
+ : '<ul class="edge-list">' +
+ inbound
+ .map(
+ (e) =>
+ "<li>" +
+ esc(e.source) +
+ ' <span class="kind">[' +
+ esc(edgeLabel(e)) +
+ "]</span></li>",
+ )
+ .join("") +
+ "</ul>",
+ ].join("");
+ root.innerHTML = html;
+ }
+
+ // ---- Filtering -------------------------------------------------------
+ function applyFilters() {
+ const term = searchTerm.toLowerCase();
+ for (const n of nodes) {
+ const statusOk = statusFilters.has(n.status);
+ const textOk =
+ !term ||
+ n.principle.toLowerCase().includes(term) ||
+ n.topic.toLowerCase().includes(term) ||
+ n.id.toLowerCase().includes(term);
+ n.visible = statusOk && textOk;
+ }
+ rebuildVisibleSorted();
+ scheduleListRender();
+ }
+
+ // ---- Listbox (keyboard-accessible mirror of the canvas) --------------
+ // The visible nodes are also presented as a focusable <ul role="listbox">.
+ // Pointer users keep the canvas; keyboard and screen reader users get
+ // the listbox. Both surfaces call `selectNode(id)` so state stays in
+ // lockstep across input devices.
+ // `visibleSortedCache` is rebuilt by `applyFilters` and consumed by
+ // `renderNodeList` / `moveListboxFocus` — saves an O(N log N) sort
+ // on every Arrow key on large vaults.
+ let visibleSortedCache = [];
+ let renderNodeListPending = false;
+
+ function escHtml(s) {
+ return String(s).replace(
+ /[&<>"]/g,
+ (c) =>
+ ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ })[c],
+ );
+ }
+
+ function rebuildVisibleSorted() {
+ visibleSortedCache = nodes
+ .filter((n) => n.visible)
+ .slice()
+ .sort((a, b) => {
+ const t = a.topic.localeCompare(b.topic);
+ return t !== 0 ? t : a.id.localeCompare(b.id);
+ });
+ }
+
+ function renderNodeList() {
+ const list = document.getElementById("node-list");
+ const visible = visibleSortedCache;
+ if (visible.length === 0) {
+ list.innerHTML = '<li id="node-list-empty">No matching nodes.</li>';
+ list.setAttribute("aria-activedescendant", "");
+ return;
+ }
+ list.innerHTML = visible
+ .map((n) => {
+ const selected =
+ n.id === selectedId
+ ? ' aria-selected="true"'
+ : ' aria-selected="false"';
+ const title =
+ n.principle.length > 80
+ ? n.principle.slice(0, 77) + "..."
+ : n.principle;
+ return (
+ '<li role="option" id="node-opt-' +
+ escHtml(n.id) +
+ '"' +
+ selected +
+ ' data-node-id="' +
+ escHtml(n.id) +
+ '">' +
+ '<span class="topic">' +
+ escHtml(n.topic) +
+ "</span>" +
+ escHtml(title) +
+ "</li>"
+ );
+ })
+ .join("");
+ list.setAttribute(
+ "aria-activedescendant",
+ selectedId ? "node-opt-" + selectedId : "",
+ );
+ // Bind per-item click handlers via event delegation (cheap and
+ // survives the full re-render above).
+ list.onclick = (ev) => {
+ const li = ev.target.closest("li[data-node-id]");
+ if (!li) return;
+ selectNode(li.getAttribute("data-node-id"));
+ };
+ list.ondblclick = (ev) => {
+ if (!VAULT_PATH) return;
+ const li = ev.target.closest("li[data-node-id]");
+ if (!li) return;
+ const nodeId = li.getAttribute("data-node-id");
+ const filePath =
+ VAULT_PATH +
+ (nodeId.startsWith("ret-")
+ ? "/Brain/retired/"
+ : "/Brain/preferences/") +
+ nodeId +
+ ".md";
+ const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
+ window.open(uri, "_blank");
+ };
+ }
+
+ // Defer the listbox rebuild to the next animation frame so a held-
+ // down filter key only re-renders the <ul> once per paint instead
+ // of per keystroke. The canvas-side render is on its own rAF loop
+ // and is unaffected.
+ function scheduleListRender() {
+ if (renderNodeListPending) return;
+ renderNodeListPending = true;
+ requestAnimationFrame(() => {
+ renderNodeListPending = false;
+ renderNodeList();
+ });
+ }
+
+ function selectNode(id) {
+ selectedId = id || null;
+ const n = id ? nodeById.get(id) : null;
+ renderPanel(n);
+ // Mirror selection into the listbox without rebuilding the full
+ // DOM (cheaper, preserves scroll position).
+ const list = document.getElementById("node-list");
+ for (const li of list.querySelectorAll("li[data-node-id]")) {
+ li.setAttribute(
+ "aria-selected",
+ li.getAttribute("data-node-id") === id ? "true" : "false",
+ );
+ }
+ list.setAttribute(
+ "aria-activedescendant",
+ id ? "node-opt-" + id : "",
+ );
+ if (id) {
+ const focused = list.querySelector('li[data-node-id="' + id + '"]');
+ if (focused && focused.scrollIntoView) {
+ focused.scrollIntoView({ block: "nearest" });
+ }
+ }
+ }
+
+ function moveListboxFocus(delta) {
+ const visible = visibleSortedCache;
+ if (visible.length === 0) return;
+ const cur = selectedId
+ ? visible.findIndex((n) => n.id === selectedId)
+ : -1;
+ let next;
+ if (cur === -1) {
+ next = delta > 0 ? 0 : visible.length - 1;
+ } else {
+ next = (cur + delta + visible.length) % visible.length;
+ }
+ selectNode(visible[next].id);
+ }
+
+ // ---- Wire up DOM events ----------------------------------------------
+ function resizeCanvas() {
+ const r = canvas.getBoundingClientRect();
+ canvas.width = Math.max(100, Math.floor(r.width));
+ canvas.height = Math.max(100, Math.floor(r.height));
+ }
+ window.addEventListener("resize", resizeCanvas);
+
+ canvas.addEventListener("mousemove", (e) => {
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ hoverId = n ? n.id : null;
+ });
+ canvas.addEventListener("click", (e) => {
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ selectNode(n ? n.id : null);
+ });
+ canvas.addEventListener("dblclick", (e) => {
+ if (!VAULT_PATH) return;
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ if (!n) return;
+ const filePath =
+ VAULT_PATH +
+ (n.id.startsWith("ret-")
+ ? "/Brain/retired/"
+ : "/Brain/preferences/") +
+ n.id +
+ ".md";
+ const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
+ const opened = window.open(uri, "_blank");
+ if (!opened) {
+ navigator.clipboard
+ .writeText(filePath)
+ .then(() => {
+ showTooltip("Obsidian not detected — path copied to clipboard");
+ })
+ .catch(() => {
+ showTooltip("Path: " + filePath);
+ });
+ }
+ });
+
+ // §14 polish: keyboard handlers on the listbox. The listbox is
+ // `tabindex="0"`, so it joins the natural tab order after the
+ // search input.
+ const nodeList = document.getElementById("node-list");
+ nodeList.addEventListener("keydown", (e) => {
+ switch (e.key) {
+ case "ArrowDown":
+ e.preventDefault();
+ moveListboxFocus(+1);
+ break;
+ case "ArrowUp":
+ e.preventDefault();
+ moveListboxFocus(-1);
+ break;
+ case "Home":
+ e.preventDefault();
+ if (visibleSortedCache.length > 0) {
+ selectNode(visibleSortedCache[0].id);
+ }
+ break;
+ case "End":
+ e.preventDefault();
+ if (visibleSortedCache.length > 0) {
+ selectNode(
+ visibleSortedCache[visibleSortedCache.length - 1].id,
+ );
+ }
+ break;
+ case "Enter":
+ case " ":
+ // Enter / Space commit on the currently focused option. The
+ // visual / panel state already follows focus, so this is a
+ // no-op when something is already selected — but we keep the
+ // explicit handler so screen-readers announce the commit.
+ e.preventDefault();
+ if (selectedId) selectNode(selectedId);
+ break;
+ case "Escape":
+ e.preventDefault();
+ selectNode(null);
+ break;
+ default:
+ break;
+ }
+ });
+
+ // Hydrate the search box and status checkboxes from stored filters
+ // before wiring listeners — otherwise the first reload still flashes
+ // the unchecked default.
+ const searchInput = document.getElementById("search");
+ searchInput.value = searchTerm;
+ for (const cb of document.querySelectorAll(".status-filter")) {
+ cb.checked = statusFilters.has(cb.value);
+ }
+
+ searchInput.addEventListener("input", (e) => {
+ searchTerm = e.target.value;
+ applyFilters();
+ scheduleSave(500);
+ });
+ for (const cb of document.querySelectorAll(".status-filter")) {
+ cb.addEventListener("change", (e) => {
+ const v = e.target.value;
+ if (e.target.checked) statusFilters.add(v);
+ else statusFilters.delete(v);
+ applyFilters();
+ scheduleSave(500);
+ });
+ }
+
+ // Reset layout button: clears the persisted state and reloads so
+ // physics seeds from `placeInitial` instead of the stored coords.
+ document
+ .getElementById("reset-layout")
+ .addEventListener("click", () => {
+ try {
+ localStorage.removeItem(STORAGE_KEY);
+ } catch (e) {
+ // No-op: nothing to clear in non-persistent mode.
+ }
+ location.reload();
+ });
+
+ // Flush on tab close / reload. `pagehide` is the cross-browser
+ // best-effort hook; `beforeunload` is intentionally avoided
+ // because it triggers the browser's "leave site?" prompt under
+ // some configurations.
+ window.addEventListener("pagehide", saveLayout);
+
+ // ---- Boot ------------------------------------------------------------
+ resizeCanvas();
+ placeInitial();
+ applyFilters();
+
+ // Persist the layout once after each settle. `unsavedMotion`
+ // latches true whenever any visible node has non-trivial velocity
+ // and resets only after `saveLayout` runs; otherwise an idle graph
+ // would JSON.stringify-and-write every 250 ms forever.
+ let settleSavedAt = -Infinity;
+ let unsavedMotion = true;
+ function frame() {
+ step();
+ render();
+ const now = performance.now();
+ if (now - settleSavedAt > 250) {
+ let totalV = 0;
+ for (const n of nodes) {
+ if (!n.visible) continue;
+ const v = Math.abs(n.vx) + Math.abs(n.vy);
+ if (v > 0.05) unsavedMotion = true;
+ totalV += v;
+ }
+ if (totalV < 0.5 && unsavedMotion) {
+ settleSavedAt = now;
+ unsavedMotion = false;
+ saveLayout();
+ }
+ }
+ requestAnimationFrame(frame);
}
- break;
- case "Enter":
- case " ":
- // Enter / Space commit on the currently focused option. The
- // visual / panel state already follows focus, so this is a
- // no-op when something is already selected — but we keep the
- // explicit handler so screen-readers announce the commit.
- e.preventDefault();
- if (selectedId) selectNode(selectedId);
- break;
- case "Escape":
- e.preventDefault();
- selectNode(null);
- break;
- default:
- break;
- }
- });
-
- // Hydrate the search box and status checkboxes from stored filters
- // before wiring listeners — otherwise the first reload still flashes
- // the unchecked default.
- const searchInput = document.getElementById("search");
- searchInput.value = searchTerm;
- for (const cb of document.querySelectorAll(".status-filter")) {
- cb.checked = statusFilters.has(cb.value);
- }
-
- searchInput.addEventListener("input", (e) => {
- searchTerm = e.target.value;
- applyFilters();
- scheduleSave(500);
- });
- for (const cb of document.querySelectorAll(".status-filter")) {
- cb.addEventListener("change", (e) => {
- const v = e.target.value;
- if (e.target.checked) statusFilters.add(v);
- else statusFilters.delete(v);
- applyFilters();
- scheduleSave(500);
- });
- }
-
- // Reset layout button: clears the persisted state and reloads so
- // physics seeds from `placeInitial` instead of the stored coords.
- document.getElementById("reset-layout").addEventListener("click", () => {
- try {
- localStorage.removeItem(STORAGE_KEY);
- } catch (e) {
- // No-op: nothing to clear in non-persistent mode.
- }
- location.reload();
- });
-
- // Flush on tab close / reload. `pagehide` is the cross-browser
- // best-effort hook; `beforeunload` is intentionally avoided
- // because it triggers the browser's "leave site?" prompt under
- // some configurations.
- window.addEventListener("pagehide", saveLayout);
-
- // ---- Boot ------------------------------------------------------------
- resizeCanvas();
- placeInitial();
- applyFilters();
-
- // Persist the layout once after each settle. `unsavedMotion`
- // latches true whenever any visible node has non-trivial velocity
- // and resets only after `saveLayout` runs; otherwise an idle graph
- // would JSON.stringify-and-write every 250 ms forever.
- let settleSavedAt = -Infinity;
- let unsavedMotion = true;
- function frame() {
- step();
- render();
- const now = performance.now();
- if (now - settleSavedAt > 250) {
- let totalV = 0;
- for (const n of nodes) {
- if (!n.visible) continue;
- const v = Math.abs(n.vx) + Math.abs(n.vy);
- if (v > 0.05) unsavedMotion = true;
- totalV += v;
- }
- if (totalV < 0.5 && unsavedMotion) {
- settleSavedAt = now;
- unsavedMotion = false;
- saveLayout();
- }
- }
- requestAnimationFrame(frame);
- }
- frame();
-})();
-</script>
-</body>
+ frame();
+ })();
+ </script>
+ </body>
</html>
diff --git a/tests/cli/brain-semantics-backfill-cli.test.ts b/tests/cli/brain-semantics-backfill-cli.test.ts
new file mode 100644
index 00000000..8f0450d1
--- /dev/null
+++ b/tests/cli/brain-semantics-backfill-cli.test.ts
@@ -0,0 +1,92 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ moveToRetired,
+ writePreference,
+ type WritePreferenceInput,
+} from "../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+} from "../../src/core/brain/types.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-semantics-cli-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function basePref(
+ slug: string,
+ overrides: Partial<WritePreferenceInput> = {},
+): WritePreferenceInput {
+ return {
+ slug,
+ topic: "writing",
+ principle: `Principle for ${slug}`,
+ created_at: "2026-05-30T12:00:00Z",
+ unconfirmed_until: "2026-06-06T12:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2026-05-30T13:00:00Z",
+ pinned: false,
+ confidence: BRAIN_CONFIDENCE.low,
+ ...overrides,
+ };
+}
+
+async function bootstrap(): Promise<void> {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(init.returncode).toBe(0);
+ const brainInit = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(brainInit.returncode).toBe(0);
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+}
+
+test("brain semantics-backfill --json prints a dry-run proposal plan", async () => {
+ await bootstrap();
+ const old = writePreference(vault, basePref("old"));
+ moveToRetired(vault, old.path, BRAIN_RETIRED_REASON.rebutted, {
+ now: new Date("2026-06-01T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-06-01]]",
+ });
+ writePreference(vault, basePref("new", { supersedes: "[[ret-old]]" }));
+
+ const result = await runCli(
+ ["brain", "semantics-backfill", "--vault", vault, "--json"],
+ {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ },
+ );
+
+ expect(result.returncode).toBe(0);
+ const payload = JSON.parse(result.stdout);
+ expect(payload.ok).toBe(true);
+ expect(payload.dry_run).toBe(true);
+ expect(payload.count).toBe(1);
+ expect(payload.proposals[0]).toMatchObject({
+ source_id: "ret-old",
+ target_id: "pref-new",
+ relation: "superseded_by",
+ field: "superseded_by",
+ value: "[[pref-new]]",
+ });
+});
diff --git a/tests/core/brain/backlinks-relation.test.ts b/tests/core/brain/backlinks-relation.test.ts
index 6476fac3..abc3d9f4 100644
--- a/tests/core/brain/backlinks-relation.test.ts
+++ b/tests/core/brain/backlinks-relation.test.ts
@@ -67,6 +67,36 @@ test("a retired pref's superseded_by ref carries relation 'superseded_by'", () =
expect(superseded?.relation).toBe("superseded_by");
});
+test("preference-specific relation fields carry relation tokens", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-foo.md"),
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-foo",
+ "topic: foo",
+ "_status: confirmed",
+ "principle: example",
+ "depends_on: [[pref-base]]",
+ "refines: [[pref-draft]]",
+ "---",
+ "",
+ "body",
+ ].join("\n"),
+ );
+ const idx = buildBacklinkIndex(vault);
+
+ const depends = idx.get("pref-base") ?? [];
+ expect(depends).toHaveLength(1);
+ expect(depends[0]?.field).toBe("depends_on");
+ expect(depends[0]?.relation).toBe("depends_on");
+
+ const refines = idx.get("pref-draft") ?? [];
+ expect(refines).toHaveLength(1);
+ expect(refines[0]?.field).toBe("refines");
+ expect(refines[0]?.relation).toBe("refines");
+});
+
test("a non-vocabulary field (supersedes) carries no relation", () => {
// `supersedes` is the inverse of `superseded_by` and is deliberately
// NOT part of the relation vocabulary, so its ref must stay untyped.
diff --git a/tests/core/brain/explorer.test.ts b/tests/core/brain/explorer.test.ts
index c7eabade..7a01b529 100644
--- a/tests/core/brain/explorer.test.ts
+++ b/tests/core/brain/explorer.test.ts
@@ -18,7 +18,10 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
-import { buildBacklinkIndex, backlinkCount } from "../../../src/core/brain/backlinks.ts";
+import {
+ buildBacklinkIndex,
+ backlinkCount,
+} from "../../../src/core/brain/backlinks.ts";
import {
collectExplorerData,
EXPLORER_SCHEMA_VERSION,
@@ -150,7 +153,9 @@ describe("collectExplorerData", () => {
const g = collectExplorerData(vault);
const supersedesEdges = g.edges.filter((e) => e.kind === "supersedes");
expect(supersedesEdges.length).toBeGreaterThanOrEqual(1);
- const e = supersedesEdges.find((x) => x.source === "pref-new" && x.target === "ret-old");
+ const e = supersedesEdges.find(
+ (x) => x.source === "pref-new" && x.target === "ret-old",
+ );
expect(e).toBeDefined();
});
@@ -169,7 +174,9 @@ describe("collectExplorerData", () => {
);
const g = collectExplorerData(vault);
const wlEdges = g.edges.filter((e) => e.kind === "wikilink");
- const bToA = wlEdges.find((e) => e.source === "pref-b" && e.target === "pref-a");
+ const bToA = wlEdges.find(
+ (e) => e.source === "pref-b" && e.target === "pref-a",
+ );
expect(bToA).toBeDefined();
// No edge to the signal — sig-foo is not in the node set.
expect(g.edges.find((e) => e.target === "sig-foo")).toBeUndefined();
@@ -177,6 +184,31 @@ describe("collectExplorerData", () => {
expect(g.edges.find((e) => e.target === "pref-nope")).toBeUndefined();
});
+ test("typed semantics metadata projects onto explorer nodes and edges", () => {
+ writePreference(vault, basePref("base"));
+ writePreference(
+ vault,
+ basePref("semantic", {
+ memory_layer: "L2",
+ memory_branch: "research",
+ depends_on: ["[[pref-base]]"],
+ }),
+ );
+
+ const g = collectExplorerData(vault);
+ const node = g.nodes.find((n) => n.id === "pref-semantic");
+ expect(node).toBeDefined();
+ expect(node!.memory_layer).toBe("L2");
+ expect(node!.memory_branch).toBe("research");
+
+ const edge = g.edges.find(
+ (e) => e.source === "pref-semantic" && e.target === "pref-base",
+ );
+ expect(edge).toBeDefined();
+ expect(edge!.kind).toBe("wikilink");
+ expect(edge!.relation).toBe("depends_on");
+ });
+
test("output is byte-identical across two runs (modulo generated_at)", () => {
writePreference(vault, basePref("alpha", { applied_count: 2 }));
writePreference(vault, basePref("beta"));
@@ -210,8 +242,14 @@ describe("collectExplorerData", () => {
writePreference(vault, basePref("target"));
// Two sources, both reaching target via `evidenced_by` (the
// canonical inter-pref reference field).
- writePreference(vault, basePref("source1", { evidenced_by: ["[[pref-target]]"] }));
- writePreference(vault, basePref("source2", { evidenced_by: ["[[pref-target]]"] }));
+ writePreference(
+ vault,
+ basePref("source1", { evidenced_by: ["[[pref-target]]"] }),
+ );
+ writePreference(
+ vault,
+ basePref("source2", { evidenced_by: ["[[pref-target]]"] }),
+ );
const g = collectExplorerData(vault);
const node = g.nodes.find((n) => n.id === "pref-target");
const expected = backlinkCount(buildBacklinkIndex(vault), "pref-target");
@@ -242,7 +280,9 @@ describe("collectExplorerData", () => {
// then retired. Within each kind, ids ascend.
const kinds = g.nodes.map((n) => n.kind);
expect(kinds).toEqual(["preference", "preference", "retired"]);
- const prefIds = g.nodes.filter((n) => n.kind === "preference").map((n) => n.id);
+ const prefIds = g.nodes
+ .filter((n) => n.kind === "preference")
+ .map((n) => n.id);
expect(prefIds).toEqual([...prefIds].toSorted());
});
});
@@ -277,7 +317,9 @@ describe("renderExportedHtml", () => {
/<script type="application\/json" id="brain-data">([\s\S]+?)<\/script>/,
);
const parsed = JSON.parse(match![1]!);
- const node = parsed.nodes.find((n: { id: string }) => n.id === "pref-dollars");
+ const node = parsed.nodes.find(
+ (n: { id: string }) => n.id === "pref-dollars",
+ );
expect(node.principle).toBe("Money is $100 or $$abc — keep this exact");
});
@@ -285,7 +327,8 @@ describe("renderExportedHtml", () => {
writePreference(
vault,
basePref("script-close", {
- principle: "Never let </script><script>bad()</script> split the data block",
+ principle:
+ "Never let </script><script>bad()</script> split the data block",
}),
);
const g = collectExplorerData(vault);
@@ -296,8 +339,12 @@ describe("renderExportedHtml", () => {
);
expect(match).not.toBeNull();
const parsed = JSON.parse(match![1]!);
- const node = parsed.nodes.find((n: { id: string }) => n.id === "pref-script-close");
- expect(node.principle).toBe("Never let </script><script>bad()</script> split the data block");
+ const node = parsed.nodes.find(
+ (n: { id: string }) => n.id === "pref-script-close",
+ );
+ expect(node.principle).toBe(
+ "Never let </script><script>bad()</script> split the data block",
+ );
});
// §14 polish (v0.10.6) — the keyboard-accessible listbox markup and
diff --git a/tests/core/brain/preference-semantics.test.ts b/tests/core/brain/preference-semantics.test.ts
new file mode 100644
index 00000000..a2383e47
--- /dev/null
+++ b/tests/core/brain/preference-semantics.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ moveToRetired,
+ parsePreference,
+ parseRetired,
+ writePreference,
+ type WritePreferenceInput,
+} from "../../../src/core/brain/preference.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pref-semantics-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function basePref(
+ slug: string,
+ overrides: Partial<WritePreferenceInput> = {},
+): WritePreferenceInput {
+ return {
+ slug,
+ topic: "writing",
+ principle: `Principle for ${slug}`,
+ created_at: "2026-05-30T12:00:00Z",
+ unconfirmed_until: "2026-06-06T12:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2026-05-30T13:00:00Z",
+ pinned: false,
+ confidence: BRAIN_CONFIDENCE.low,
+ ...overrides,
+ };
+}
+
+describe("preference memory semantics frontmatter", () => {
+ test("writePreference omits semantics metadata unless supplied", () => {
+ const res = writePreference(vault, basePref("legacy"));
+ const text = readFileSync(res.path, "utf8");
+
+ expect(text).not.toContain("memory_layer:");
+ expect(text).not.toContain("memory_branch:");
+ expect(text).not.toContain("depends_on:");
+ expect(text).not.toContain("refines:");
+ });
+
+ test("writePreference emits supplied layer, branch, and relation fields", () => {
+ const res = writePreference(
+ vault,
+ basePref("semantic", {
+ memory_layer: "L2",
+ memory_branch: "research",
+ depends_on: ["[[pref-base]]"],
+ refines: ["[[pref-draft]]"],
+ } as Partial<WritePreferenceInput>),
+ );
+ const text = readFileSync(res.path, "utf8");
+
+ expect(text).toContain("memory_layer: L2");
+ expect(text).toContain("memory_branch: research");
+ expect(text).toContain('depends_on: ["[[pref-base]]"]');
+ expect(text).toContain('refines: ["[[pref-draft]]"]');
+ });
+
+ test("parsePreference round-trips supplied semantics metadata", () => {
+ const res = writePreference(
+ vault,
+ basePref("roundtrip", {
+ memory_layer: "L3",
+ memory_branch: "persona",
+ depends_on: ["[[pref-base]]"],
+ refines: ["[[pref-draft]]"],
+ contradicts: ["[[pref-old]]"],
+ } as Partial<WritePreferenceInput>),
+ );
+
+ const parsed = parsePreference(res.path);
+ expect(parsed.memory_layer).toBe("L3");
+ expect(parsed.memory_branch).toBe("persona");
+ expect(parsed.depends_on).toEqual(["[[pref-base]]"]);
+ expect(parsed.refines).toEqual(["[[pref-draft]]"]);
+ expect(parsed.contradicts).toEqual(["[[pref-old]]"]);
+ });
+
+ test("parsePreference rejects invalid memory_layer values", () => {
+ const path = join(vault, "Brain", "preferences", "pref-invalid-layer.md");
+ writeFileSync(
+ path,
+ [
+ "---",
+ "kind: brain-preference",
+ "id: pref-invalid-layer",
+ "created_at: 2026-05-30T12:00:00Z",
+ "_confirmed_at: 2026-05-30T13:00:00Z",
+ "unconfirmed_until: 2026-06-06T12:00:00Z",
+ "tags: [brain, brain/preference, brain/topic/writing]",
+ "topic: writing",
+ "_status: confirmed",
+ "principle: invalid layer",
+ "_evidenced_by: []",
+ "_applied_count: 0",
+ "_violated_count: 0",
+ '_last_evidence_at: "null"',
+ "_confidence: low",
+ '_confidence_value: "null"',
+ "pinned: false",
+ "memory_layer: L9",
+ "---",
+ ].join("\n"),
+ "utf8",
+ );
+
+ expect(() => parsePreference(path)).toThrow("memory_layer");
+ });
+
+ test("writePreference rejects invalid memory_branch slugs", () => {
+ expect(() =>
+ writePreference(
+ vault,
+ basePref("bad-branch", {
+ memory_branch: "../research",
+ } as Partial<WritePreferenceInput>),
+ ),
+ ).toThrow("memory_branch");
+ });
+
+ test("moveToRetired preserves memory semantics metadata", () => {
+ const res = writePreference(
+ vault,
+ basePref("retire-me", {
+ memory_layer: "L1",
+ memory_branch: "experiment",
+ depends_on: ["[[pref-base]]"],
+ } as Partial<WritePreferenceInput>),
+ );
+
+ const retired = moveToRetired(
+ vault,
+ res.path,
+ BRAIN_RETIRED_REASON.userRejected,
+ {
+ now: new Date("2026-06-01T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-06-01]]",
+ user_rejected_reason: "test",
+ },
+ );
+
+ const parsed = parseRetired(retired.path);
+ expect(parsed.memory_layer).toBe("L1");
+ expect(parsed.memory_branch).toBe("experiment");
+ expect(parsed.depends_on).toEqual(["[[pref-base]]"]);
+ });
+});
diff --git a/tests/core/brain/semantics-backfill.test.ts b/tests/core/brain/semantics-backfill.test.ts
new file mode 100644
index 00000000..bdac50a5
--- /dev/null
+++ b/tests/core/brain/semantics-backfill.test.ts
@@ -0,0 +1,110 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ moveToRetired,
+ writePreference,
+ type WritePreferenceInput,
+} from "../../../src/core/brain/preference.ts";
+import { planSemanticsBackfill } from "../../../src/core/brain/semantics-backfill.ts";
+import {
+ BRAIN_CONFIDENCE,
+ BRAIN_PREFERENCE_STATUS,
+ BRAIN_RETIRED_REASON,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-semantics-backfill-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function basePref(
+ slug: string,
+ overrides: Partial<WritePreferenceInput> = {},
+): WritePreferenceInput {
+ return {
+ slug,
+ topic: "writing",
+ principle: `Principle for ${slug}`,
+ created_at: "2026-05-30T12:00:00Z",
+ unconfirmed_until: "2026-06-06T12:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2026-05-30T13:00:00Z",
+ pinned: false,
+ confidence: BRAIN_CONFIDENCE.low,
+ ...overrides,
+ };
+}
+
+function retire(slug: string, supersededBy?: string): string {
+ const pref = writePreference(vault, basePref(slug));
+ return moveToRetired(vault, pref.path, BRAIN_RETIRED_REASON.rebutted, {
+ now: new Date("2026-06-01T00:00:00Z"),
+ retired_by: "[[Brain/log/2026-06-01]]",
+ ...(supersededBy !== undefined ? { superseded_by: supersededBy } : {}),
+ }).path;
+}
+
+describe("planSemanticsBackfill", () => {
+ test("proposes inverse superseded_by for active supersedes links", () => {
+ const retiredPath = retire("old");
+ writePreference(
+ vault,
+ basePref("new", {
+ supersedes: "[[ret-old]]",
+ }),
+ );
+
+ const plan = planSemanticsBackfill(vault);
+
+ expect(plan.proposals).toEqual([
+ {
+ source_id: "ret-old",
+ target_id: "pref-new",
+ relation: "superseded_by",
+ field: "superseded_by",
+ value: "[[pref-new]]",
+ reason: "active-supersedes-retired-missing-inverse",
+ path: retiredPath,
+ },
+ ]);
+ expect(readFileSync(retiredPath, "utf8")).not.toContain("superseded_by:");
+ });
+
+ test("does not propose when retired inverse already exists", () => {
+ retire("old", "[[pref-new]]");
+ writePreference(
+ vault,
+ basePref("new", {
+ supersedes: "[[ret-old]]",
+ }),
+ );
+
+ const plan = planSemanticsBackfill(vault);
+
+ expect(plan.proposals).toEqual([]);
+ });
+
+ test("returns proposals in stable source-target order", () => {
+ retire("z-old");
+ retire("a-old");
+ writePreference(vault, basePref("z-new", { supersedes: "[[ret-z-old]]" }));
+ writePreference(vault, basePref("a-new", { supersedes: "[[ret-a-old]]" }));
+
+ const plan = planSemanticsBackfill(vault);
+
+ expect(plan.proposals.map((p) => `${p.source_id}->${p.target_id}`)).toEqual(
+ ["ret-a-old->pref-a-new", "ret-z-old->pref-z-new"],
+ );
+ });
+});
diff --git a/tests/core/graph/relation-vocab.test.ts b/tests/core/graph/relation-vocab.test.ts
index a9e88d3c..c246ff7a 100644
--- a/tests/core/graph/relation-vocab.test.ts
+++ b/tests/core/graph/relation-vocab.test.ts
@@ -15,9 +15,16 @@ import {
relationFromFrontmatterField,
} from "../../../src/core/graph/relation-vocab.ts";
-test("the default vocabulary covers the four declared relation types", () => {
+test("the default vocabulary covers the declared relation types", () => {
const actual: string[] = [...DEFAULT_RELATION_TYPES];
- expect(actual.toSorted()).toEqual(["contradicts", "extends", "related", "superseded_by"]);
+ expect(actual.toSorted()).toEqual([
+ "contradicts",
+ "depends_on",
+ "extends",
+ "refines",
+ "related",
+ "superseded_by",
+ ]);
});
test("normalizeRelation is NFC + trimmed + lower-cased", () => {
@@ -35,6 +42,8 @@ test("isKnownRelation accepts the vocabulary and rejects anything else", () => {
test("relationFromFrontmatterField maps a known relation field to its relation, else null", () => {
expect(relationFromFrontmatterField("contradicts")).toBe("contradicts");
+ expect(relationFromFrontmatterField("Depends_On")).toBe("depends_on");
+ expect(relationFromFrontmatterField("refines")).toBe("refines");
expect(relationFromFrontmatterField("Superseded_By")).toBe("superseded_by");
expect(relationFromFrontmatterField("title")).toBeNull();
expect(relationFromFrontmatterField("aliases")).toBeNull();