Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(memory): rebuild the Memory section as a linked, path-addressed vault reader (#678)

Ruben Lütkeffa8768f8e8b
diff --git a/docs/authoring/public-docs-manifest.yaml b/docs/authoring/public-docs-manifest.yaml
index a77852fd19..c648f297e8 100644
--- a/docs/authoring/public-docs-manifest.yaml
+++ b/docs/authoring/public-docs-manifest.yaml
@@ -471,7 +471,9 @@ pages:
diataxis: explanation
summary: Understand what Dodaios can remember, how the Wiki connects ideas, and how memory supports chats, contacts, and agents.
authoritative_sources:
- - jarvis/ui/web/frontend/src/views/WikiView.tsx
+ - jarvis/ui/web/frontend/src/views/MemoryView.tsx
+ - jarvis/ui/web/memory_vault_routes.py
+ - jarvis/memory/wiki/vault_model.py
- jarvis/ui/web/wiki_routes.py
- jarvis/memory/wiki/integration.py
- jarvis/memory/wiki/curator.py
diff --git a/docs/product/knowledge-and-sharing/wiki-and-memory.md b/docs/product/knowledge-and-sharing/wiki-and-memory.md
index 01680886ff..e52b2e7b90 100644
--- a/docs/product/knowledge-and-sharing/wiki-and-memory.md
+++ b/docs/product/knowledge-and-sharing/wiki-and-memory.md
@@ -8,7 +8,7 @@ order: 1
diataxis: explanation
status: active
owner: maintainers
-last_reviewed: 2026-07-21
+last_reviewed: 2026-10-14
phase: "-"
audience: end-user
tags: [wiki, memory, context, profile, contacts, privacy]
@@ -41,33 +41,44 @@ history, and links to other subjects.
## Explore the Wiki
-1. **Open Wiki from the sidebar.** The view opens on **Wiki · Memory Map** and
- shows the number of pages and links currently available.
-
-2. **Read the health strips.** They show whether the vault is available,
- whether a write succeeded or failed, whether candidate facts are pending,
- and whether the search index needs rebuilding. **No writes recorded yet**
- means that the current process and candidate journal have no write result to
- show. It does not mean that an existing vault is empty.
-
-3. **Browse by subject.** Expand **entities**, **concepts**, **projects**, or
- **sessions** in the Vault list, then choose a page. The tree also shows
- other visible Markdown folders, such as **people** for contact companion
- pages. Session pages are summaries rather than full transcripts, but the
- current default does not create them from activity episodes.
-
-4. **Use the Memory Map.** Select a node to open its page. A connection means
- that one page contains a Wiki link to another; it does not prove that the
- relationship is current or correct.
-
-5. **Follow links and backlinks.** A link inside a page opens the referenced
- subject. **Backlinks** show pages that point to the page you are reading.
- A broken link points to a page that does not currently exist.
-
-The in-app Wiki is a reader. To edit the underlying notes yourself, connect an
-optional Markdown editor through [Connect Obsidian](connect-obsidian). Dodaios
-works without Obsidian because the files remain ordinary Markdown on your
-computer.
+1. **Open Wiki from the sidebar.** The Memory section opens on an overview:
+ how many pages hold content, how many links and mentions connect them, what
+ changed recently, the most connected pages, and a feed of recent writes.
+
+2. **Check the health indicator.** The dot at the top right shows whether
+ writes land and whether the search index is current. Select it for the
+ reason and for **Rebuild search index**.
+
+3. **Browse by area.** **People & things**, **Projects**, **Concepts**, and
+ **Journal** list pages with their first sentence, how connected they are,
+ and when they changed. Pages without content are folded away until you show
+ them. **Agents** lists each agent's two notebooks (what it learned about its
+ work, and what it knows about you) and its reports, under the agent's
+ current name. Notebooks of deleted or unknown agents are folded away, and
+ empty ones can be moved to the vault's `_archive` folder with **Tidy up
+ empty notebooks**; nothing is deleted.
+
+4. **Read a page and its connections.** The side rail lists the pages that
+ link here, the pages this one links to, pages that mention it by name
+ without linking it, and related pages that share a connection. A dashed
+ link points to a page that does not exist yet; select it to create one.
+
+5. **Use the Map.** Pages with content are dots, links are solid lines and
+ mentions dashed ones. Select a dot to open its page, or use **Show on the
+ map** from a page. A connection means that one page refers to another; it
+ does not prove that the relationship is current or correct.
+
+6. **Search with Ctrl+K** (Cmd+K on macOS). Titles match as you type, text
+ and, when switched on, similar meaning follow, and a name that has no page
+ yet can become one.
+
+You can create, edit, rename, and archive knowledge pages in the app. Editing
+saves the page body and keeps its frontmatter, refuses to overwrite a page
+that changed since you opened it, and renaming updates every link that
+pointed to the old name. Agent notebooks are kept by their agents and are
+read-only here. The files remain ordinary Markdown on your computer, so you
+can also edit them with an optional editor through
+[Connect Obsidian](connect-obsidian).
## Save Something Deliberately
@@ -80,8 +91,7 @@ written summaries.`
Dodaios acknowledges that the write has started, then reports whether it was
saved or failed. Wait for that completion result before relying on the note.
Open **Wiki** and inspect the page named in the result when the detail matters.
-The Wiki view has no note editor or save form; the explicit chat or voice
-request is the in-app manual write path.
+You can also write or correct a page yourself in the Wiki view.
> [!warning] Never ask your assistant to remember a password, credential, recovery
> code, or access token. The write guard blocks common secret shapes, but the
@@ -101,7 +111,7 @@ request is the in-app manual write path.
text through the guarded curator and announces success only after at least
one page was written. Unsupported, duplicate, sensitive, malformed, or
conflicting content can still result in no write.
-- **Index repair does not create knowledge.** **Rebuild index** refreshes the
+- **Index repair does not create knowledge.** **Rebuild search index** refreshes the
derived full-text search data from the Markdown vault. It does not extract a
fact or change a note.
- **Advanced backfill is opt-in.** The `jarvis wiki backfill` command can
@@ -157,10 +167,10 @@ Markdown vault when needed.
written.
3. **The curator updates local notes.** Approved changes pass through guarded
- writes, backups, validation, and a local full-text search index. The tree,
+ writes, backups, validation, and a local full-text search index. The page list,
page, graph, and backlink views read the Markdown files directly. The index
supports search and later recall. The file watcher normally updates it after
- manual Markdown edits; the health strip marks it stale if an update is
+ manual Markdown edits; the health indicator marks it stale if an update is
missed. A slow or missing automatic lookup is skipped rather than holding up
the reply.
@@ -168,7 +178,7 @@ Markdown vault when needed.
Profile directly supplies response preferences. Contacts keep full contact
details. Saving a contact creates or refreshes a **people** page with the
contact's name, aliases, relationship, and note while excluding phone,
- email, and street address. These companion pages appear in the Wiki tree,
+ email, and street address. These companion pages appear in the Wiki,
but you should edit the authoritative record in **Contacts**.
5. **Dodaios-Agents use a short-lived supervisor grant.** A mission can receive
@@ -196,7 +206,7 @@ personal information.
summaries.`
2. Wait for Dodaios to report a successful save. A message that it is still
writing is not the final result.
-3. Open **Wiki** and confirm that the health strip reports a successful last
+3. Open **Wiki** and confirm that the health indicator reports a successful last
write rather than a pending or failed one.
4. Open the page named in the completion result and confirm that the statement
appears in the right context.
@@ -213,10 +223,10 @@ preference.
| The Wiki is empty after ordinary conversations | No durable candidate has passed both review stages, or the Wiki has not completed its first write | Make one explicit, non-sensitive Wiki save request and wait for the completion result |
| **Facts are waiting to be written** | Review work is queued, the app closed before consolidation, or a provider is temporarily unavailable | Keep the app running, check the Wiki provider status, and wait before repeating the same note |
| **Chain failure** or **Last write failed** | Every eligible Wiki provider failed, timed out, or returned unusable output | Open **API Keys > Advanced > Wiki (long-term memory)**, connect or choose a working provider, then retry a harmless test note |
-| **Search index** shows fewer indexed pages than vault pages | The Markdown files and the derived local index are out of sync | Select **Rebuild index**, then reopen the affected page |
+| **Search index** shows fewer indexed pages than vault pages | The Markdown files and the derived local index are out of sync | Select **Rebuild search index**, then reopen the affected page |
| A saved contact has no companion page under **people** | Contact-to-Wiki synchronization has not completed, the Wiki is unavailable, or a recent manual edit temporarily blocked the write | Keep **Contacts** as the authoritative record, reopen Wiki after synchronization, then check Wiki health and vault permissions if the page is still missing |
| The **sessions** folder is empty | Activity-to-Wiki session-page writing is disabled by default; normal conversation capture stores durable facts on subject pages instead | Use Chats or Sessions for transcripts and run an approved Realtime backfill only when you deliberately want to review recent voice sessions |
-| **No writes recorded yet** appears even though pages exist | The status has no current-process or journaled write result to display, which can happen after a restart or for manually added files | Treat the Markdown page as the source of truth; use **Rebuild index** only if search is also stale |
+| The health indicator says **Not checked** even though pages exist | The memory writer has no write result from this run to report yet, which can happen after a restart or for manually added files | Treat the Markdown page as the source of truth; use **Rebuild search index** only if search is also stale |
| A linked page cannot be opened | The target page is missing, invalid, or the page list has not refreshed | Reopen Wiki, rebuild the index if it is stale, and correct the link in the Markdown vault if the target truly does not exist |
## Next Steps
diff --git a/jarvis/memory/learning/notebook.py b/jarvis/memory/learning/notebook.py
index 237ee29dd2..a79bc0c5f0 100644
--- a/jarvis/memory/learning/notebook.py
+++ b/jarvis/memory/learning/notebook.py
@@ -410,6 +410,9 @@ class JarvisNotebook:
}
ledger = self.folder / LEDGER_NAME
try:
+ # Reading the notebooks no longer creates their folder, and a soul
+ # change lands in SOUL.md elsewhere, so the ledger makes its own.
+ self.folder.mkdir(parents=True, exist_ok=True)
if ledger.is_file() and ledger.stat().st_size > _LEDGER_MAX_BYTES:
os.replace(ledger, ledger.with_name(LEDGER_NAME + ".1"))
with ledger.open("a", encoding="utf-8", newline="\n") as handle:
diff --git a/jarvis/memory/wiki/curator.py b/jarvis/memory/wiki/curator.py
index 2ac1c50d7c..3662440572 100644
--- a/jarvis/memory/wiki/curator.py
+++ b/jarvis/memory/wiki/curator.py
@@ -188,6 +188,7 @@ class WikiCurator:
source_label: str,
verb: str = "merge",
all_or_nothing: bool = False,
+ keep_unresolved_links: bool = False,
) -> WriteResult:
"""Apply pre-built updates through the full guarded write pipeline.
@@ -200,6 +201,9 @@ class WikiCurator:
use ``merge``). ``all_or_nothing=True`` makes this call one write
transaction: a lock conflict, secret block, write failure, or schema
failure leaves every page in its pre-call state.
+ ``keep_unresolved_links=True`` is for a person editing a page by hand:
+ a ``[[link]]`` to a page that does not exist yet is their intent (the
+ reader offers to create it), not model noise to demote.
"""
# The LLM is taught (via schema.md) to emit vault-relative targets
# like "entities/ruben.md". Python's Path() treats that as a
@@ -217,7 +221,8 @@ class WikiCurator:
# (or no page created in THIS same batch) must be demoted to plain
# text, never left dangling. Deterministic, regex only, no LLM,
# no I/O — mirrors the session-rollup post-pass.
- updates = self._demote_dangling_links(updates)
+ if not keep_unresolved_links:
+ updates = self._demote_dangling_links(updates)
# ----- 1c. canonicalise Sources citations ----------------------
# Deterministic tidy of the ## Sources section (dedupe, drop
diff --git a/jarvis/memory/wiki/self_doc.py b/jarvis/memory/wiki/self_doc.py
index 5edb76409b..537bae2f21 100644
--- a/jarvis/memory/wiki/self_doc.py
+++ b/jarvis/memory/wiki/self_doc.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import datetime as _dt
import logging
+import re
from pathlib import Path
from typing import TYPE_CHECKING
@@ -134,6 +135,14 @@ def _recently_updated(vault_root: Path, *, limit: int) -> list[str]:
return [rel for _, rel in candidates[:limit]]
+_TIMESTAMP_LINE = re.compile(r"^(?:updated: .*|- Last refreshed: .*)$", re.MULTILINE)
+
+
+def _without_timestamps(text: str) -> str:
+ """The page with its refresh clock removed, for an is-anything-new check."""
+ return _TIMESTAMP_LINE.sub("", text.replace("\r\n", "\n")).strip()
+
+
async def refresh_memory_page(
*,
curator: WikiCurator,
@@ -163,7 +172,19 @@ async def refresh_memory_page(
backlog_count=backlog,
telemetry_snapshot=telemetry.snapshot(),
)
- exists = (vault_root / PAGE_NAME).is_file()
+ page_path = vault_root / PAGE_NAME
+ exists = page_path.is_file()
+ if exists:
+ try:
+ current = await asyncio.to_thread(page_path.read_text, encoding="utf-8")
+ except OSError as exc:
+ log.debug("self_doc: could not read the current page: %s", exc)
+ current = ""
+ if _without_timestamps(current) == _without_timestamps(body):
+ # Only the clock moved. Rewriting would add a log.md entry
+ # per boot and per consolidator run: 1,833 of 2,100 entries
+ # were exactly that, and the activity feed drowned in them.
+ return False
update = PageUpdate(
target_path=Path(PAGE_NAME),
operation="update" if exists else "create",
diff --git a/jarvis/memory/wiki/vault_model.py b/jarvis/memory/wiki/vault_model.py
new file mode 100644
index 0000000000..c5a17ad2b5
--- /dev/null
+++ b/jarvis/memory/wiki/vault_model.py
@@ -0,0 +1,727 @@
+"""A linked, path-addressed model of the whole vault for the Memory section.
+
+The older slug-addressed routes treat ``path.stem`` as a page's identity.
+That breaks as soon as two files share a name, and the vault has 100+ agent
+notebooks that are all called ``MEMORY.md`` and ``USER.md``: every one of
+them resolved to the first match. This model keys every page by its
+vault-relative POSIX path instead and keeps the slug only as a link target.
+
+It is built from pages the route layer has already scanned and parsed, so
+it does no I/O of its own. Everything is deterministic: link resolution,
+mentions, related pages and empty-page detection are plain text work, never
+a model call (AP-9/AP-11), so building it costs no key.
+"""
+from __future__ import annotations
+
+import math
+import re
+from collections import defaultdict
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+from typing import Any
+
+import yaml
+
+from jarvis.memory.wiki.wikilink import SEARCHABLE_DIRS, extract_wikilinks
+
+#: Root pages that document or log the memory itself rather than hold
+#: knowledge. They stay readable but never count as links or graph nodes:
+#: ``log.md`` alone used to contribute ~2,100 of 2,244 "links".
+SYSTEM_ROOT_PAGES: frozenset[str] = frozenset({"log.md", "memory.md", "schema.md", "index.md"})
+TEMPLATE_DIRS: frozenset[str] = frozenset({"templates", "_templates", "99-templates"})
+SOCIETY_DIR = "society"
+NOTEBOOK_FILES: dict[str, str] = {"memory.md": "memory", "user.md": "profile"}
+
+_DIR_KINDS: dict[str, str] = {
+ "entities": "entity",
+ "concepts": "concept",
+ "projects": "project",
+ "sessions": "session",
+ "people": "person",
+}
+_TYPE_KINDS: dict[str, str] = {
+ "entity": "entity",
+ "concept": "concept",
+ "project": "project",
+ "session": "session",
+ "person": "person",
+}
+
+_FRONTMATTER_RE = re.compile(r"\A?---\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL)
+_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
+_HEADING_RE = re.compile(r"^\s{0,3}#{1,6}\s+(.*)$")
+_RULE_RE = re.compile(r"^\s{0,3}(?:[-*_]\s*){3,}$")
+_EMPTY_BULLET_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s*(?:\[[ xX]?\]\s*)?$")
+_WORD_RE = re.compile(r"\w", re.UNICODE)
+_LINK_TOKEN_RE = re.compile(r"(?<!\\)!?\[\[([^\]\n]+)\]\]")
+_MD_LINK_RE = re.compile(r"\[([^\]]*)\]\([^)]*\)")
+_SNIPPET_RADIUS = 90
+_SUMMARY_MAX = 220
+#: Shortest title a plain-text mention may match. Shorter names ("AI", "Lea")
+#: collide with ordinary words far too often to be worth a link.
+_MENTION_MIN_CHARS = 4
+_RELATED_LIMIT = 8
+
+
+# ---------------------------------------------------------------- frontmatter
+
+
+def read_properties(raw: str) -> dict[str, Any]:
+ """Parse a page's YAML frontmatter into plain JSON-safe values.
+
+ The page parser keeps frontmatter as ``key: value`` strings, which turns
+ block lists (``aliases:`` followed by ``- the user``) into empty strings.
+ Properties shown to a reader need the real values, so this parses the
+ block with a YAML loader and falls back to the flat strings on bad YAML.
+ """
+ match = _FRONTMATTER_RE.match(raw)
+ if not match:
+ return {}
+ block = match.group(1)
+ try:
+ loaded = yaml.safe_load(block)
+ except yaml.YAMLError: # silent-ok: hand-edited YAML falls back to the flat key: value read
+ loaded = None
+ if not isinstance(loaded, dict):
+ flat: dict[str, Any] = {}
+ for line in block.splitlines():
+ key, sep, value = line.partition(":")
+ if sep and key.strip() and not line.startswith((" ", "-")):
+ flat[key.strip()] = value.strip()
+ return flat
+ return {str(key): _json_safe(value) for key, value in loaded.items()}
+
+
+def _json_safe(value: Any) -> Any:
+ if value is None or isinstance(value, (bool, int, float, str)):
+ return value
+ if isinstance(value, (list, tuple, set)):
+ return [_json_safe(item) for item in value]
+ if isinstance(value, dict):
+ return {str(k): _json_safe(v) for k, v in value.items()}
+ return str(value)
+
+
+def _string_list(value: Any) -> tuple[str, ...]:
+ if isinstance(value, str):
+ value = [part for part in re.split(r"[,\n]", value.strip("[] ")) if part.strip()]
+ if not isinstance(value, list):
+ return ()
+ return tuple(str(item).strip().strip("'\"") for item in value if str(item).strip())
+
+
+# --------------------------------------------------------------------- input
+
+
+@dataclass(frozen=True, slots=True)
+class SourcePage:
+ """One scanned page as the route layer hands it in."""
+
+ path: str
+ body: str
+ properties: Mapping[str, Any]
+ page_type: str
+ mtime: float
+ size: int
+
+
+@dataclass(frozen=True, slots=True)
+class AgentInfo:
+ """What the roster knows about an agent that owns a notebook folder."""
+
+ agent_id: str
+ name: str
+ state: str # active | archived | orphan
+
+
+# -------------------------------------------------------------------- output
+
+
+@dataclass(slots=True)
+class PageRecord:
+ path: str
+ slug: str
+ title: str
+ kind: str
+ group: str
+ folder: str
+ agent_id: str | None
+ mtime: float
+ size: int
+ words: int
+ empty: bool
+ summary: str
+ aliases: tuple[str, ...]
+ tags: tuple[str, ...]
+ body: str = field(repr=False)
+ properties: Mapping[str, Any] = field(repr=False)
+
+ def summary_dict(self) -> dict[str, Any]:
+ return {
+ "path": self.path,
+ "slug": self.slug,
+ "title": self.title,
+ "kind": self.kind,
+ "group": self.group,
+ "folder": self.folder,
+ "agent_id": self.agent_id,
+ "mtime": self.mtime,
+ "words": self.words,
+ "empty": self.empty,
+ "summary": self.summary,
+ "tags": list(self.tags),
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class Link:
+ source: str
+ target: str | None
+ raw: str
+ kind: str # link | mention
+ context: str
+
+
+@dataclass(slots=True)
+class VaultModel:
+ pages: dict[str, PageRecord]
+ links: list[Link]
+ agents: dict[str, AgentInfo]
+ outgoing: dict[str, list[Link]]
+ incoming: dict[str, list[Link]]
+ resolver: _Resolver = field(repr=False)
+
+ # ------------------------------------------------------------- queries
+
+ def resolve(self, raw: str, source_path: str) -> str | None:
+ """Which page a ``[[raw]]`` link written on ``source_path`` opens."""
+ source = self.pages.get(source_path)
+ if source is None:
+ return None
+ return self.resolver.resolve(raw, source)
+
+ def rewrite_links(
+ self, source_path: str, old_path: str, new_target: str, *, body: str | None = None
+ ) -> tuple[str, int]:
+ """``source_path``'s body with every link to ``old_path`` pointed at ``new_target``.
+
+ ``body`` is the text to rewrite when the caller has a fresher copy than
+ the model's; links resolve as they would on ``source_path``.
+
+ ``new_target`` is the renamed page's vault path without ``.md``. A
+ link written as a bare name stays a bare name; one with a folder
+ keeps the folder form. Aliases (``|label``) and heading anchors
+ (``#part``) survive untouched.
+ """
+ source = self.pages[source_path]
+ count = 0
+
+ def _swap(match: re.Match[str]) -> str:
+ nonlocal count
+ inner = match.group(1)
+ if self.resolver.resolve(inner, source) != old_path:
+ return match.group(0)
+ target, bar, alias = inner.partition("|")
+ name, hash_, anchor = target.partition("#")
+ replacement = new_target if "/" in name else new_target.rsplit("/", 1)[-1]
+ count += 1
+ embed = "!" if match.group(0).startswith("!") else ""
+ return f"{embed}[[{replacement}{hash_}{anchor}{bar}{alias}]]"
+
+ return _LINK_TOKEN_RE.sub(_swap, source.body if body is None else body), count
+
+ def stats(self) -> dict[str, int]:
+ content = [p for p in self.pages.values() if p.group != "system"]
+ resolved = [link for link in self.links if link.kind == "link" and link.target]
+ return {
+ "pages": len(content),
+ "content_pages": sum(1 for p in content if not p.empty),
+ "empty_pages": sum(1 for p in content if p.empty),
+ "links": len(resolved),
+ "mentions": sum(1 for link in self.links if link.kind == "mention"),
+ "broken_links": sum(
+ 1 for link in self.links if link.kind == "link" and not link.target
+ ),
+ }
+
+ def degree(self, path: str) -> int:
+ return len({link.target for link in self.outgoing.get(path, []) if link.target}) + len(
+ {link.source for link in self.incoming.get(path, [])}
+ )
+
+ def related(self, path: str, *, limit: int = _RELATED_LIMIT) -> list[dict[str, Any]]:
+ """Pages two steps away through a shared neighbour, best first.
+
+ A neighbour with many connections (a hub everyone links) says little
+ about two pages that both touch it, so each shared neighbour adds
+ ``1 / log(2 + degree)``.
+ """
+ direct = self._neighbours(path)
+ scores: dict[str, float] = defaultdict(float)
+ via: dict[str, str] = {}
+ for neighbour in direct:
+ weight = 1.0 / math.log(2 + self.degree(neighbour))
+ for candidate in self._neighbours(neighbour):
+ if candidate == path or candidate in direct:
+ continue
+ record = self.pages.get(candidate)
+ if record is None or record.empty or record.group == "system":
+ continue
+ scores[candidate] += weight
+ if candidate not in via or weight > scores[candidate] - weight:
+ via[candidate] = neighbour
+ ranked = sorted(scores.items(), key=lambda item: (-item[1], self.pages[item[0]].title))
+ return [
+ {
+ **self._ref(candidate),
+ "score": round(score, 3),
+ "via": self._ref(via[candidate]) if via.get(candidate) in self.pages else None,
+ }
+ for candidate, score in ranked[:limit]
+ ]
+
+ def page_links(self, path: str) -> dict[str, list[dict[str, Any]]]:
+ """The four link lists the reader's side rail shows for one page."""
+ outgoing: list[dict[str, Any]] = []
+ mentions: list[dict[str, Any]] = []
+ seen_out: set[tuple[str | None, str]] = set()
+ for link in self.outgoing.get(path, []):
+ # ``raw`` is kept per spelling so the reader can map every
+ # ``[[written form]]`` in the body to the page it opens.
+ key = (link.target, link.raw)
+ if key in seen_out:
+ continue
+ seen_out.add(key)
+ if link.kind == "mention":
+ if any(m["path"] == link.target for m in mentions):
+ continue
+ mentions.append({**self._ref(link.target or ""), "context": link.context})
+ elif link.target:
+ outgoing.append({**self._ref(link.target), "broken": False, "raw": link.raw})
+ else:
+ outgoing.append(
+ {
+ "path": None,
+ "title": _display_raw(link.raw),
+ "kind": None,
+ "broken": True,
+ "raw": link.raw,
+ }
+ )
+ backlinks: list[dict[str, Any]] = []
+ mentioned_in: list[dict[str, Any]] = []
+ seen_in: set[tuple[str, str]] = set()
+ for link in self.incoming.get(path, []):
+ key = (link.source, link.kind)
+ if key in seen_in or link.source == path:
+ continue
+ seen_in.add(key)
+ target = backlinks if link.kind == "link" else mentioned_in
+ target.append({**self._ref(link.source), "context": link.context})
+ backlinks.sort(key=lambda item: -self.pages[item["path"]].mtime)
+ mentioned_in.sort(key=lambda item: -self.pages[item["path"]].mtime)
+ return {
+ "outgoing": outgoing,
+ "backlinks": backlinks,
+ "mentions": mentions,
+ "mentioned_in": mentioned_in,
+ }
+
+ def graph(self, *, include_agents: bool = True) -> dict[str, Any]:
+ visible = {
+ path
+ for path, record in self.pages.items()
+ if record.group != "system"
+ and not record.empty
+ and (include_agents or record.group != "agents")
+ }
+ edges: dict[tuple[str, str], str] = {}
+ for link in self.links:
+ if link.target is None or link.source not in visible or link.target not in visible:
+ continue
+ if link.source == link.target:
+ continue
+ key = (link.source, link.target)
+ # A real link outranks a plain-text mention of the same pair.
+ if edges.get(key) != "link":
+ edges[key] = link.kind
+ degree: dict[str, int] = defaultdict(int)
+ for source, target in edges:
+ degree[source] += 1
+ degree[target] += 1
+ nodes = [
+ {
+ "id": path,
+ "title": self.pages[path].title,
+ "kind": self.pages[path].kind,
+ "group": self.pages[path].group,
+ "agent_id": self.pages[path].agent_id,
+ "degree": degree.get(path, 0),
+ }
+ for path in sorted(visible)
+ ]
+ return {
+ "nodes": nodes,
+ "edges": [
+ {"source": source, "target": target, "kind": kind}
+ for (source, target), kind in sorted(edges.items())
+ ],
+ }
+
+ # ------------------------------------------------------------ internals
+
+ def _neighbours(self, path: str) -> set[str]:
+ out = {link.target for link in self.outgoing.get(path, []) if link.target}
+ inc = {link.source for link in self.incoming.get(path, [])}
+ return {p for p in (out | inc) if p != path and p in self.pages}
+
+ def _ref(self, path: str) -> dict[str, Any]:
+ record = self.pages.get(path)
+ if record is None:
+ return {"path": path, "title": path, "kind": None, "group": None, "empty": True}
+ return {
+ "path": record.path,
+ "title": record.title,
+ "kind": record.kind,
+ "group": record.group,
+ "empty": record.empty,
+ "agent_id": record.agent_id,
+ }
+
+
+# ------------------------------------------------------------------ building
+
+
+def build_model(
+ sources: Iterable[SourcePage], agents: Mapping[str, AgentInfo] | None = None
+) -> VaultModel:
+ """Classify, title and interlink every page of one scan."""
+ known_agents = dict(agents or {})
+ pages: dict[str, PageRecord] = {}
+ folder_agents: dict[str, AgentInfo] = {}
+ for source in sources:
+ record = _record(source, known_agents)
+ pages[record.path] = record
+ if record.agent_id and (
+ record.agent_id not in folder_agents
+ or folder_agents[record.agent_id].name == _humanise(record.agent_id)
+ ):
+ folder_agents[record.agent_id] = known_agents.get(record.agent_id) or AgentInfo(
+ agent_id=record.agent_id,
+ name=_notebook_owner(record) or _humanise(record.agent_id),
+ state="orphan",
+ )
+ for record in pages.values():
+ if record.agent_id and record.kind in ("memory", "profile"):
+ info = folder_agents[record.agent_id]
+ record.title = f"{info.name} · {'Memory' if record.kind == 'memory' else 'Profile'}"
+
+ resolver = _Resolver(pages)
+ links: list[Link] = []
+ for record in pages.values():
+ if record.group == "system":
+ continue
+ linked_targets: set[str] = set()
+ for raw in extract_wikilinks(record.body):
+ target = resolver.resolve(raw, record)
+ if target == record.path:
+ continue
+ if target:
+ linked_targets.add(target)
+ links.append(
+ Link(
+ source=record.path,
+ target=target,
+ raw=raw,
+ kind="link",
+ context=_context(record.body, f"[[{raw}"),
+ )
+ )
+ for target, needle in resolver.mentions(record, linked_targets):
+ links.append(
+ Link(
+ source=record.path,
+ target=target,
+ raw=needle,
+ kind="mention",
+ context=_context(record.body, needle),
+ )
+ )
+
+ outgoing: dict[str, list[Link]] = defaultdict(list)
+ incoming: dict[str, list[Link]] = defaultdict(list)
+ for link in links:
+ outgoing[link.source].append(link)
+ if link.target:
+ incoming[link.target].append(link)
+ return VaultModel(
+ pages=pages,
+ links=links,
+ agents=folder_agents,
+ outgoing=dict(outgoing),
+ incoming=dict(incoming),
+ resolver=resolver,
+ )
+
+
+def _record(source: SourcePage, agents: Mapping[str, AgentInfo]) -> PageRecord:
+ rel = PurePosixPath(source.path)
+ parts = rel.parts
+ top = parts[0].casefold() if len(parts) > 1 else ""
+ name = rel.name
+ folder = rel.parent.as_posix() if len(parts) > 1 else ""
+ properties = dict(source.properties)
+ agent_id: str | None = None
+
+ if not top and name.casefold() in SYSTEM_ROOT_PAGES:
+ group, kind = "system", "system"
+ elif top in TEMPLATE_DIRS:
+ group, kind = "system", "template"
+ elif top == SOCIETY_DIR and len(parts) >= 3 and parts[1].casefold() != "shared":
+ group = "agents"
+ agent_id = parts[1]
+ kind = NOTEBOOK_FILES.get(name.casefold(), "note") if len(parts) == 3 else "note"
+ elif top == SOCIETY_DIR:
+ group, kind = "agents", "shared"
+ elif top == "sessions":
+ group, kind = "journal", "session"
+ else:
+ group = "knowledge"
+ kind = (
+ _TYPE_KINDS.get(str(properties.get("type") or source.page_type or ""))
+ or _DIR_KINDS.get(top)
+ or "note"
+ )
+
+ body = source.body
+ clean = readable_body(body)
+ words = len(clean.split())
+ title = _title(properties, body, rel.stem)
+ aliases = _string_list(properties.get("aliases"))
+ tags = _string_list(properties.get("tags"))
+ return PageRecord(
+ path=rel.as_posix(),
+ slug=rel.stem,
+ title=title,
+ kind=kind,
+ group=group,
+ folder=folder,
+ agent_id=agent_id,
+ mtime=source.mtime,
+ size=source.size,
+ words=words,
+ empty=is_empty_body(body),
+ summary=_summary(clean),
+ aliases=aliases,
+ tags=tags,
+ body=body,
+ properties=properties,
+ )
+
+
+def readable_body(body: str) -> str:
+ """The body without HTML comments (entry bookkeeping) and blank runs."""
+ text = _COMMENT_RE.sub("", body)
+ return re.sub(r"\n{3,}", "\n\n", text).strip()
+
+
+def is_empty_body(body: str) -> bool:
+ """True when a body has no prose: only headings, rules, comments, blanks.
+
+ Frontmatter-only stubs and profile skeletons (headings with nothing under
+ them) count as empty; a single real sentence does not.
+ """
+ for line in _COMMENT_RE.sub("", body).splitlines():
+ stripped = line.strip()
+ if not stripped or _HEADING_RE.match(line) or _RULE_RE.match(line):
+ continue
+ if _EMPTY_BULLET_RE.match(line):
+ continue
+ if _WORD_RE.search(stripped):
+ return False
+ return True
+
+
+def _title(properties: Mapping[str, Any], body: str, stem: str) -> str:
+ candidates = [str(properties.get("title") or "")]
+ for line in body.splitlines():
+ match = _HEADING_RE.match(line)
+ if match and line.lstrip().startswith("# "):
+ candidates.append(match.group(1))
+ break
+ for candidate in candidates:
+ candidate = candidate.strip().strip("\"'")
+ if candidate and "{{" not in candidate:
+ return candidate
+ return _humanise(stem)
+
+
+def _notebook_owner(record: PageRecord) -> str:
+ """The agent name a notebook's own title recorded (``"Vega — memory"``).
+
+ The roster forgets agents that were removed outright; their notebooks
+ still carry the name they were created under.
+ """
+ if record.kind not in ("memory", "profile"):
+ return ""
+ title = str(record.properties.get("title") or "").strip().strip("\"'")
+ for suffix in (" — memory", " — user profile", " - memory", " - user profile"):
+ if title.casefold().endswith(suffix):
+ return title[: -len(suffix)].strip()
+ return ""
+
+
+def _humanise(stem: str) -> str:
+ text = stem.replace("-", " ").replace("_", " ").strip()
+ return text[:1].upper() + text[1:] if text else stem
+
+
+def _summary(clean: str) -> str:
+ """First prose paragraph, flattened, without Markdown decoration."""
+ for block in re.split(r"\n\s*\n", clean):
+ lines = [
+ line
+ for line in block.splitlines()
+ if line.strip() and not _HEADING_RE.match(line) and not _RULE_RE.match(line)
+ ]
+ if not lines:
+ continue
+ text = " ".join(line.strip().lstrip("-*+> ").strip() for line in lines)
+ text = _LINK_TOKEN_RE.sub(lambda m: _display_raw(m.group(1)), text)
+ text = _MD_LINK_RE.sub(r"\1", text)
+ text = re.sub(r"[*_`]+", "", text)
+ text = " ".join(text.split())
+ if not _WORD_RE.search(text):
+ continue
+ if len(text) > _SUMMARY_MAX:
+ text = text[:_SUMMARY_MAX].rsplit(" ", 1)[0] + "…"
+ return text
+ return ""
+
+
+def _display_raw(raw: str) -> str:
+ target, _, alias = raw.partition("|")
+ if alias.strip():
+ return alias.strip()
+ return target.strip().split("#", 1)[0].rsplit("/", 1)[-1].removesuffix(".md")
+
+
+def _context(body: str, needle: str) -> str:
+ # Comments go first, whole: cut mid-way by the window, notebook entry
+ # markers would otherwise leak into the snippet as raw JSON.
+ body = _COMMENT_RE.sub(" ", body)
+ idx = body.find(needle)
+ if idx < 0:
+ idx = body.casefold().find(needle.casefold())
+ if idx < 0:
+ return ""
+ start = max(0, idx - _SNIPPET_RADIUS)
+ end = min(len(body), idx + len(needle) + _SNIPPET_RADIUS)
+ text = body[start:end]
+ text = _LINK_TOKEN_RE.sub(lambda m: _display_raw(m.group(1)), text)
+ text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE)
+ text = " ".join(text.split())
+ if start > 0:
+ text = "…" + text
+ if end < len(body):
+ text += "…"
+ return text
+
+
+class _Resolver:
+ """Obsidian-style link resolution over path, file name, title and alias."""
+
+ def __init__(self, pages: Mapping[str, PageRecord]) -> None:
+ self._pages = pages
+ self._by_path: dict[str, str] = {}
+ self._by_stem: dict[str, list[str]] = defaultdict(list)
+ self._by_name: dict[str, list[str]] = defaultdict(list)
+ for path, record in pages.items():
+ self._by_path[path.casefold().removesuffix(".md")] = path
+ self._by_stem[record.slug.casefold()].append(path)
+ if record.group == "knowledge":
+ for name in (record.title, *record.aliases):
+ key = name.strip().casefold()
+ if key:
+ self._by_name[key].append(path)
+ self._mention_index = self._build_mentions()
+
+ def resolve(self, raw: str, source: PageRecord) -> str | None:
+ target = raw.split("|", 1)[0].split("#", 1)[0].strip().replace("\\", "/")
+ target = target.removesuffix(".md").strip("/")
+ if not target:
+ return None
+ key = target.casefold()
+ if "/" in key:
+ if key in self._by_path:
+ return self._by_path[key]
+ key = key.rsplit("/", 1)[-1]
+ candidates = self._by_stem.get(key) or self._by_name.get(key) or []
+ if not candidates:
+ return None
+ if len(candidates) == 1:
+ return candidates[0]
+ return min(candidates, key=lambda path: self._rank(path, source))
+
+ def _rank(self, path: str, source: PageRecord) -> tuple[int, int, str]:
+ record = self._pages[path]
+ same_folder = 0 if record.folder == source.folder else 1
+ top = path.split("/", 1)[0] if "/" in path else ""
+ dir_rank = SEARCHABLE_DIRS.index(top) if top in SEARCHABLE_DIRS else len(SEARCHABLE_DIRS)
+ return same_folder, dir_rank, path
+
+ def _build_mentions(self) -> list[tuple[re.Pattern[str], str, str]]:
+ """One pattern per knowledge name that is distinctive enough to match.
+
+ Multi-word names match case-insensitively; a single word only as
+ written, so the person "Ruben" links while the word "memory" in
+ running text does not pull in a page titled "Memory".
+ """
+ names: dict[str, set[str]] = defaultdict(set)
+ for path, record in self._pages.items():
+ if record.group != "knowledge" or record.empty:
+ continue
+ for name in (record.title, *record.aliases):
+ name = name.strip()
+ if len(name) >= _MENTION_MIN_CHARS and _WORD_RE.search(name):
+ names[name].add(path)
+ out: list[tuple[re.Pattern[str], str, str]] = []
+ for name, paths in names.items():
+ if len(paths) != 1:
+ continue # ambiguous plain text is not a link
+ flags = re.IGNORECASE if " " in name else 0
+ pattern = re.compile(rf"(?<![\w\[/]){re.escape(name)}(?![\w\]])", flags)
+ out.append((pattern, name, next(iter(paths))))
+ out.sort(key=lambda item: -len(item[1]))
+ return out
+
+ def mentions(
+ self, record: PageRecord, already_linked: set[str]
+ ) -> list[tuple[str, str]]:
+ if record.empty or record.group == "system":
+ return []
+ text = _LINK_TOKEN_RE.sub(" ", _COMMENT_RE.sub(" ", record.body))
+ found: list[tuple[str, str]] = []
+ seen = set(already_linked) | {record.path}
+ for pattern, _name, target in self._mention_index:
+ if target in seen:
+ continue
+ match = pattern.search(text)
+ if match:
+ seen.add(target)
+ found.append((target, match.group(0)))
+ return found
+
+
+__all__ = [
+ "AgentInfo",
+ "Link",
+ "PageRecord",
+ "SourcePage",
+ "VaultModel",
+ "build_model",
+ "is_empty_body",
+ "read_properties",
+ "readable_body",
+]
diff --git a/jarvis/society/memory.py b/jarvis/society/memory.py
index a99af3cefd..45f7ccf044 100644
--- a/jarvis/society/memory.py
+++ b/jarvis/society/memory.py
@@ -530,7 +530,10 @@ class SocietyMemory:
if not query:
return []
vault = self.root(root)
- self.books(agent, root=vault)
+ from .memory_books import has_books
+
+ if has_books(vault, agent):
+ self.books(agent, root=vault) # finish an interrupted migration first
qtokens = _tokens(query)
hits: list[MemoryHit] = []
for page in self._pages(vault, agent_id=agent.agent_id):
diff --git a/jarvis/society/memory_books.py b/jarvis/society/memory_books.py
index a9d451a129..37e1635bae 100644
--- a/jarvis/society/memory_books.py
+++ b/jarvis/society/memory_books.py
@@ -186,7 +186,25 @@ def ensure_books(vault: Path, agent: Any) -> dict[str, Path]:
return {target: folder / name for target, name in FILES.items()}
+def has_books(vault: Path, agent: Any) -> bool:
+ """True when the agent's folder holds a notebook or a pending migration.
+
+ Reads must not create files: every agent the roster ever listed used to
+ get two frontmatter-only notebooks the first time anything looked at it,
+ which filled the vault with 170 empty pages.
+ """
+ folder = folder_for(vault, agent.agent_id)
+ if not folder.is_dir():
+ return False
+ return any(
+ path.name.lower() in {"memory.md", "user.md", ".memory-layout.pending.json"}
+ for path in folder.iterdir()
+ )
+
+
def read_books(vault: Path, agent: Any) -> dict[str, list[Entry]]:
+ if not has_books(vault, agent):
+ return {target: [] for target in FILES}
paths = ensure_books(vault, agent)
with FileLock(str(paths["memory"].parent / ".memory-books.lock"), timeout=2):
return {target: parse(body(_read(path))) for target, path in paths.items()}
diff --git a/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts b/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts
index c75bfdce8c..887d4a115b 100644
--- a/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts
+++ b/jarvis/ui/web/frontend/src/__tests__/useWikiLive.test.ts
@@ -103,6 +103,7 @@ describe("useWikiLive", () => {
["wiki", "search"],
["wiki", "page"],
["wiki", "backlinks"],
+ ["wiki", "memory"],
]);
});
@@ -139,6 +140,7 @@ describe("useWikiLive", () => {
["wiki", "search"],
["wiki", "page"],
["wiki", "backlinks"],
+ ["wiki", "memory"],
]);
expect(result.current.lastEventAt).not.toBeNull();
});
diff --git a/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx b/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx
index 10e2b6331a..d13e63cb80 100644
--- a/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx
+++ b/jarvis/ui/web/frontend/src/components/deck/DeckWiki.tsx
@@ -25,9 +25,8 @@ import { useT } from "@/i18n";
/**
* The wiki on the deck — the vault's memory map, in space.
*
- * This is the SAME scene the Wiki section draws (`components/wiki/WikiGraph3D`):
- * the same request, the same nodes, colours and size rule, the same ambient
- * orbit. The deck adds three things a front page needs: it fits into a card
+ * The vault drawn as a 3D scene (`components/wiki/WikiGraph3D`) with an
+ * ambient orbit. The deck adds three things a front page needs: it fits into a card
* and keeps working there, it can expand to the whole window on one click,
* and pages that changed this session glow so the newest memory is the one
* the eye lands on.
@@ -59,9 +58,8 @@ export function warmWikiScene(): void {
/* a chunk that fails to preload simply loads later, as it always did */
});
}
-const WikiGraph2D = lazy(() =>
- import("@/components/wiki/WikiGraph").then((m) => ({ default: m.WikiGraph })),
-);
+// Without WebGL the deck falls back to the Memory section's flat map.
+const WikiGraph2D = lazy(() => import("@/components/memory/MemoryMap"));
const GRAPH_QUERY_KEY = ["wiki", "graph"] as const; // shared with the Wiki section's map
@@ -139,7 +137,7 @@ function DeckWikiScene({
linkLabel={linkLabel}
/>
) : (
- <WikiGraph2D onNodeClick={onNodeClick} highlightSlug={highlightSlug} />
+ <WikiGraph2D onOpen={onNodeClick} focus={null} compact />
)}
</Suspense>
)}
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx
index 64941d85fc..ebd01e4d71 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.prefetch.test.tsx
@@ -15,9 +15,9 @@ vi.mock("@/views/society/SocietyView", () => {
loads.push("agents");
return { SocietyView: () => <div>agents ready</div> };
});
-vi.mock("@/views/WikiView", () => {
+vi.mock("@/views/MemoryView", () => {
loads.push("memory");
- return { WikiView: () => null };
+ return { MemoryView: () => null };
});
vi.mock("@/views/PluginsDialog", () => {
loads.push("plugins");
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index ae44381978..8ae1c69ec0 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -77,8 +77,8 @@ const SocietyView = lazyView(["agents"], () =>
default: m.SocietyView,
})),
);
-const WikiView = lazyView(["memory"], () =>
- import("@/views/WikiView").then((m) => ({ default: m.WikiView })),
+const MemoryView = lazyView(["memory"], () =>
+ import("@/views/MemoryView").then((m) => ({ default: m.MemoryView })),
);
type PluginArea = "plugins" | "mcps" | "skills";
const isPluginArea = (section: string): section is PluginArea =>
@@ -366,7 +366,7 @@ function SwitchOnActiveSection({ active }: { active: string }) {
case "board":
return <BoardView />;
case "memory":
- return <WikiView />;
+ return <MemoryView />;
// The merged voice section: Dictation (default landing) + Dictionary +
// Shortcuts + Language + the speech-to-text keys, behind one tab bar. The
// active id doubles as the tab state, so a voice deep-link to any of them
diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
index eafaf64463..5a9401e3e2 100644
--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
@@ -21,7 +21,6 @@ import { IdeSidePanelToggle } from "@/components/agentic/sidePanel/IdeSidePanelT
import { ThreadTerminalToggle } from "@/components/agentic/threads/ThreadTerminalToggle";
import { useIdeSidePanelStore } from "@/store/ideSidePanel";
import { useIdeThreadsStore } from "@/store/ideThreads";
-import { WikiInspectorToggle } from "@/components/wiki/WikiInspectorToggle";
import { useDesktopChrome, WindowControls } from "@/components/layout/WindowControls";
/**
@@ -110,7 +109,6 @@ export function TopBar() {
<div className="flex shrink-0 items-center">
<CodingModeBadge />
<IdeCaptionPanelToggle />
- <WikiCaptionPanelToggle />
{controls === "trailing" && (
<WindowControls controls={controls} maximized={chrome.maximized} onCommand={chrome.command} />
)}
@@ -135,12 +133,6 @@ function IdeCaptionSwitch() {
);
}
-/** The Wiki inspector's open / close button, only on the Wiki section. */
-function WikiCaptionPanelToggle() {
- const onWiki = useEventStore((s) => s.activeSection === "memory");
- return onWiki ? <WikiInspectorToggle /> : null;
-}
-
/**
* The IDE's panel toggles, only on the IDE: the terminal drawer in the thread
* layout (the grid is all terminals already, and a maximized side panel covers
diff --git a/jarvis/ui/web/frontend/src/components/memory/AgentDirectory.tsx b/jarvis/ui/web/frontend/src/components/memory/AgentDirectory.tsx
new file mode 100644
index 0000000000..4aad5d7ebb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/AgentDirectory.tsx
@@ -0,0 +1,147 @@
+/**
+ * Every agent that owns a notebook folder, one card each: what it remembers
+ * about its work and about the person, at a glance. Agents that were deleted
+ * or that the roster never knew are folded away, and empty leftovers can be
+ * archived in one step.
+ */
+import { useMemo, useState } from "react";
+import { Bot, Brain, Sparkles, UserRound } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import type { MemoryAgent, MemoryIndex, MemoryPageSummary } from "@/lib/memoryApi";
+import { countText, relativeAge, visibleAgents } from "@/lib/memoryModel";
+import { EmptyState } from "@/components/ui/empty-state";
+import { Button } from "@/components/ui/button";
+
+export function AgentDirectory({
+ index,
+ language,
+ onOpen,
+ onTidy,
+}: {
+ index: MemoryIndex;
+ language: string;
+ onOpen: (path: string) => void;
+ onTidy: () => void;
+}) {
+ const t = useT();
+ const [showAll, setShowAll] = useState(false);
+ const pagesByPath = useMemo(() => new Map(index.pages.map((page) => [page.path, page])), [index.pages]);
+ const agents = visibleAgents(index.agents, showAll);
+ const hidden = index.agents.length - visibleAgents(index.agents, false).length;
+ const emptyLeftovers = index.agents.filter((agent) => agent.state !== "active" && agent.empty).length;
+
+ return (
+ <div className="mx-auto flex w-full max-w-[980px] flex-col px-8 pb-16 pt-8 lg:px-12" data-testid="memory-agents">
+ <header className="flex flex-wrap items-end justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-semibold tracking-tight text-foreground-strong">{t("memory_view.area_agents")}</h2>
+ <p className="mt-1 max-w-[560px] text-base text-muted-foreground">{t("memory_view.area_agents_hint")}</p>
+ </div>
+ {index.writable && emptyLeftovers > 0 && (
+ <Button variant="outline" size="sm" onClick={onTidy} data-testid="memory-tidy">
+ <Sparkles aria-hidden />
+ {fill(t("memory_view.tidy_button"), { count: emptyLeftovers })}
+ </Button>
+ )}
+ </header>
+
+ {agents.length === 0 ? (
+ <EmptyState icon={<Bot />} title={t("memory_view.agents_empty_title")} description={t("memory_view.agents_empty_body")} className="mt-10" />
+ ) : (
+ <ul className="mt-6 grid gap-3 md:grid-cols-2">
+ {agents.map((agent) => (
+ <li key={agent.agent_id}>
+ <AgentCard agent={agent} pages={agent.pages.map((path) => pagesByPath.get(path)).filter(isPage)} language={language} onOpen={onOpen} />
+ </li>
+ ))}
+ </ul>
+ )}
+ {hidden > 0 && (
+ <button
+ type="button"
+ onClick={() => setShowAll((value) => !value)}
+ className="mt-5 self-start rounded-md px-1 text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
+ >
+ {showAll ? t("memory_view.agents_hide_inactive") : fill(t("memory_view.agents_show_inactive"), { count: hidden })}
+ </button>
+ )}
+ </div>
+ );
+}
+
+function isPage(page: MemoryPageSummary | undefined): page is MemoryPageSummary {
+ return page !== undefined;
+}
+
+function AgentCard({
+ agent,
+ pages,
+ language,
+ onOpen,
+}: {
+ agent: MemoryAgent;
+ pages: MemoryPageSummary[];
+ language: string;
+ onOpen: (path: string) => void;
+}) {
+ const t = useT();
+ const memory = pages.find((page) => page.kind === "memory");
+ const profile = pages.find((page) => page.kind === "profile");
+ const notes = pages.filter((page) => page.kind === "note" && !page.empty).sort((a, b) => b.mtime - a.mtime);
+ const first = memory && !memory.empty ? memory : profile && !profile.empty ? profile : notes[0] ?? memory ?? profile;
+ return (
+ <div
+ className={cn(
+ "flex h-full flex-col rounded-xl border border-border bg-background p-4 transition-colors",
+ agent.state !== "active" && "bg-transparent",
+ )}
+ >
+ <button type="button" onClick={() => first && onOpen(first.path)} className="flex items-center gap-3 text-left" disabled={!first}>
+ <span
+ className={cn(
+ "grid h-9 w-9 shrink-0 place-items-center rounded-lg text-sm font-semibold uppercase",
+ agent.state === "active" ? "bg-surface-raised text-foreground-strong" : "bg-secondary text-muted-foreground",
+ )}
+ aria-hidden
+ >
+ {agent.name.slice(0, 1)}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-base font-medium text-foreground-strong">{agent.name}</span>
+ <span className="block text-xs text-muted-foreground">
+ {agent.state === "active" ? fill(t("memory_view.updated"), { age: relativeAge(agent.updated, language) }) : t(`memory_view.agent_${agent.state}`)}
+ </span>
+ </span>
+ </button>
+ <p className="mt-3 line-clamp-2 min-h-[2.5rem] text-sm leading-5 text-muted-foreground">
+ {memory && !memory.empty ? memory.summary : profile && !profile.empty ? profile.summary : t("memory_view.agent_nothing_yet")}
+ </p>
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ {memory && <Chip onClick={() => onOpen(memory.path)} icon={<Brain aria-hidden />} label={t("memory_view.kind_memory")} empty={memory.empty} />}
+ {profile && <Chip onClick={() => onOpen(profile.path)} icon={<UserRound aria-hidden />} label={t("memory_view.kind_profile")} empty={profile.empty} />}
+ {notes.length > 0 && (
+ <Chip onClick={() => onOpen(notes[0].path)} label={countText(t, "memory_view.notes_count", notes.length)} empty={false} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Chip({ onClick, icon, label, empty }: { onClick: () => void; icon?: JSX.Element; label: string; empty: boolean }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "inline-flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs font-medium transition-colors [&>svg]:h-3.5 [&>svg]:w-3.5",
+ empty
+ ? "border-dashed border-border text-foreground-faint hover:text-muted-foreground"
+ : "border-border text-foreground hover:bg-secondary",
+ )}
+ >
+ {icon}
+ {label}
+ </button>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/KindIcon.tsx b/jarvis/ui/web/frontend/src/components/memory/KindIcon.tsx
new file mode 100644
index 0000000000..c39e43fd6c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/KindIcon.tsx
@@ -0,0 +1,37 @@
+import {
+ BookMarked,
+ Brain,
+ CalendarDays,
+ FileText,
+ FolderKanban,
+ LayoutTemplate,
+ Lightbulb,
+ Settings2,
+ Share2,
+ Shapes,
+ User,
+ UserRound,
+ type LucideIcon,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+import type { MemoryKind } from "@/lib/memoryApi";
+
+const ICONS: Record<MemoryKind, LucideIcon> = {
+ entity: Shapes,
+ person: User,
+ project: FolderKanban,
+ concept: Lightbulb,
+ session: CalendarDays,
+ note: FileText,
+ memory: Brain,
+ profile: UserRound,
+ shared: Share2,
+ system: Settings2,
+ template: LayoutTemplate,
+};
+
+/** One quiet glyph per page kind; colour stays with the surrounding ink. */
+export function KindIcon({ kind, className }: { kind: MemoryKind | null | undefined; className?: string }) {
+ const Icon = (kind && ICONS[kind]) || BookMarked;
+ return <Icon className={cn("h-4 w-4 shrink-0", className)} aria-hidden />;
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/MarkdownBody.tsx b/jarvis/ui/web/frontend/src/components/memory/MarkdownBody.tsx
new file mode 100644
index 0000000000..ee8407dffc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MarkdownBody.tsx
@@ -0,0 +1,131 @@
+/**
+ * A memory page's Markdown, set as a document at the reading measure.
+ *
+ * Wikilinks arrive pre-resolved from `prepareBody`: a link to a page that
+ * exists opens it; a link to a page that does not exist yet is drawn dashed
+ * and offers to create it.
+ */
+import { useMemo } from "react";
+import ReactMarkdown, { type Components } from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { useT } from "@/i18n";
+import { LINK_SCHEME, MISSING_SCHEME } from "@/lib/memoryModel";
+
+export function MarkdownBody({
+ markdown,
+ onOpen,
+ onCreate,
+}: {
+ markdown: string;
+ onOpen: (path: string) => void;
+ onCreate?: (title: string) => void;
+}) {
+ const t = useT();
+ const components = useMemo<Components>(
+ () => ({
+ a: ({ href, children }) => {
+ if (href?.startsWith(LINK_SCHEME)) {
+ const path = decodeURIComponent(href.slice(LINK_SCHEME.length));
+ return (
+ <a
+ href={href}
+ data-memory-link={path}
+ onClick={(event) => {
+ event.preventDefault();
+ onOpen(path);
+ }}
+ className="font-medium text-foreground-strong underline decoration-border-strong decoration-1 underline-offset-[3px] transition-colors hover:decoration-accent"
+ >
+ {children}
+ </a>
+ );
+ }
+ if (href?.startsWith(MISSING_SCHEME)) {
+ const title = decodeURIComponent(href.slice(MISSING_SCHEME.length));
+ return (
+ <a
+ href={href}
+ title={t("memory_view.link_missing")}
+ onClick={(event) => {
+ event.preventDefault();
+ onCreate?.(title);
+ }}
+ className="text-muted-foreground underline decoration-dashed decoration-1 underline-offset-[3px] hover:text-foreground"
+ >
+ {children}
+ </a>
+ );
+ }
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="text-accent underline-offset-[3px] hover:underline"
+ >
+ {children}
+ </a>
+ );
+ },
+ h1: ({ children }) => (
+ <h2 className="mb-3 mt-10 text-2xl font-semibold tracking-tight text-foreground-strong first:mt-0">{children}</h2>
+ ),
+ h2: ({ children }) => (
+ <h2 className="mb-3 mt-9 text-xl font-semibold tracking-tight text-foreground-strong first:mt-0">{children}</h2>
+ ),
+ h3: ({ children }) => (
+ <h3 className="mb-2 mt-7 text-lg font-semibold text-foreground-strong first:mt-0">{children}</h3>
+ ),
+ h4: ({ children }) => (
+ <h4 className="mb-2 mt-6 text-base font-semibold text-foreground-strong first:mt-0">{children}</h4>
+ ),
+ p: ({ children }) => <p className="my-3.5 leading-7 text-foreground">{children}</p>,
+ ul: ({ children }) => (
+ <ul className="my-3.5 list-disc space-y-1.5 pl-5 leading-7 text-foreground marker:text-foreground-faint">
+ {children}
+ </ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="my-3.5 list-decimal space-y-1.5 pl-6 leading-7 text-foreground marker:text-sm marker:tabular-nums marker:text-foreground-faint">
+ {children}
+ </ol>
+ ),
+ li: ({ children }) => <li className="pl-1">{children}</li>,
+ blockquote: ({ children }) => (
+ <blockquote className="my-5 border-l-2 border-border-strong pl-4 text-foreground-secondary">{children}</blockquote>
+ ),
+ hr: () => <hr className="my-8 border-border" />,
+ strong: ({ children }) => <strong className="font-semibold text-foreground-strong">{children}</strong>,
+ table: ({ children }) => (
+ <div className="my-5 overflow-x-auto rounded-lg border border-border">
+ <table className="w-full border-collapse text-sm">{children}</table>
+ </div>
+ ),
+ th: ({ children }) => (
+ <th className="border-b border-border bg-secondary px-3 py-2 text-left font-medium text-foreground">{children}</th>
+ ),
+ td: ({ children }) => (
+ <td className="border-b border-border px-3 py-2 align-top text-foreground-secondary">{children}</td>
+ ),
+ pre: ({ children }) => (
+ <pre className="my-5 overflow-x-auto rounded-lg border border-border bg-secondary p-4 font-mono text-sm leading-6 text-foreground [&>code]:bg-transparent [&>code]:p-0">
+ {children}
+ </pre>
+ ),
+ code: ({ children, node: _node, ...rest }) => (
+ <code {...rest} className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-[0.9em] text-foreground">
+ {children}
+ </code>
+ ),
+ }),
+ [onCreate, onOpen, t],
+ );
+
+ return (
+ <div className="text-reading" data-testid="memory-markdown">
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
+ {markdown}
+ </ReactMarkdown>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/MemoryDialogs.tsx b/jarvis/ui/web/frontend/src/components/memory/MemoryDialogs.tsx
new file mode 100644
index 0000000000..cd745abba6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MemoryDialogs.tsx
@@ -0,0 +1,295 @@
+/**
+ * The Memory section's three small dialogs: create a page, rename one, and
+ * confirm an archive. They share one frame so they look and behave alike.
+ */
+import { useEffect, useState, type FormEvent, type ReactNode } from "react";
+import * as Dialog from "@radix-ui/react-dialog";
+import { Loader2 } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { KindIcon } from "./KindIcon";
+
+function Frame({
+ open,
+ onClose,
+ busy,
+ title,
+ description,
+ children,
+ testId,
+}: {
+ open: boolean;
+ onClose: () => void;
+ busy: boolean;
+ title: string;
+ description?: string;
+ children: ReactNode;
+ testId: string;
+}) {
+ return (
+ <Dialog.Root open={open} onOpenChange={(next) => !next && !busy && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/50 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=open]:fade-in-0" />
+ <Dialog.Content
+ data-testid={testId}
+ className="fixed left-1/2 top-[18%] z-[90] w-[min(460px,calc(100vw-2rem))] -translate-x-1/2 rounded-xl border border-border bg-popover p-5 text-popover-foreground shadow-float data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95"
+ >
+ <Dialog.Title className="text-base font-semibold text-foreground-strong">{title}</Dialog.Title>
+ {description ? (
+ <Dialog.Description className="mt-1 text-sm leading-relaxed text-muted-foreground">
+ {description}
+ </Dialog.Description>
+ ) : (
+ <Dialog.Description className="sr-only">{title}</Dialog.Description>
+ )}
+ {children}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+function ErrorLine({ error }: { error: string | null }) {
+ if (!error) return null;
+ return (
+ <p role="alert" className="mt-3 text-sm text-destructive">
+ {error}
+ </p>
+ );
+}
+
+export type CreatableKind = "entity" | "project" | "concept";
+const KINDS: CreatableKind[] = ["entity", "project", "concept"];
+
+export function NewPageDialog({
+ open,
+ initialTitle,
+ initialKind,
+ onClose,
+ onCreate,
+}: {
+ open: boolean;
+ initialTitle: string;
+ initialKind: CreatableKind;
+ onClose: () => void;
+ onCreate: (kind: CreatableKind, title: string) => Promise<void>;
+}) {
+ const t = useT();
+ const [title, setTitle] = useState(initialTitle);
+ const [kind, setKind] = useState<CreatableKind>(initialKind);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (open) {
+ setTitle(initialTitle);
+ setKind(initialKind);
+ setError(null);
+ }
+ }, [open, initialKind, initialTitle]);
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ if (!title.trim() || busy) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await onCreate(kind, title.trim());
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Frame
+ open={open}
+ onClose={onClose}
+ busy={busy}
+ title={t("memory_view.new_title")}
+ description={t("memory_view.new_description")}
+ testId="memory-new-dialog"
+ >
+ <form onSubmit={submit} className="mt-4 flex flex-col gap-4">
+ <label className="flex flex-col gap-1.5">
+ <span className="text-sm font-medium text-foreground">{t("memory_view.new_name")}</span>
+ <input
+ autoFocus
+ value={title}
+ onChange={(event) => setTitle(event.target.value)}
+ placeholder={t("memory_view.new_name_placeholder")}
+ data-escape-local=""
+ className="h-9 rounded-lg border border-border bg-background px-3 text-base text-foreground outline-none placeholder:text-foreground-faint focus:border-border-strong"
+ />
+ </label>
+ <fieldset className="flex flex-col gap-1.5">
+ <legend className="mb-1.5 text-sm font-medium text-foreground">{t("memory_view.new_kind")}</legend>
+ <div className="grid grid-cols-3 gap-2">
+ {KINDS.map((option) => (
+ <button
+ key={option}
+ type="button"
+ onClick={() => setKind(option)}
+ aria-pressed={kind === option}
+ className={cn(
+ "flex h-9 items-center justify-center gap-2 rounded-lg border text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ kind === option
+ ? "border-border-strong bg-secondary text-foreground-strong"
+ : "border-border text-muted-foreground hover:bg-secondary hover:text-foreground",
+ )}
+ >
+ <KindIcon kind={option} className="h-3.5 w-3.5" />
+ {t(`memory_view.kind_${option}`)}
+ </button>
+ ))}
+ </div>
+ </fieldset>
+ <ErrorLine error={error} />
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" size="sm" onClick={onClose} disabled={busy}>
+ {t("memory_view.cancel")}
+ </Button>
+ <Button type="submit" size="sm" disabled={busy || !title.trim()}>
+ {busy && <Loader2 className="animate-spin" aria-hidden />}
+ {t("memory_view.create")}
+ </Button>
+ </div>
+ </form>
+ </Frame>
+ );
+}
+
+export function RenameDialog({
+ open,
+ currentTitle,
+ onClose,
+ onRename,
+}: {
+ open: boolean;
+ currentTitle: string;
+ onClose: () => void;
+ onRename: (title: string) => Promise<void>;
+}) {
+ const t = useT();
+ const [title, setTitle] = useState(currentTitle);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (open) {
+ setTitle(currentTitle);
+ setError(null);
+ }
+ }, [open, currentTitle]);
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault();
+ if (!title.trim() || busy) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await onRename(title.trim());
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Frame
+ open={open}
+ onClose={onClose}
+ busy={busy}
+ title={t("memory_view.rename_title")}
+ description={t("memory_view.rename_description")}
+ testId="memory-rename-dialog"
+ >
+ <form onSubmit={submit} className="mt-4 flex flex-col gap-4">
+ <input
+ autoFocus
+ value={title}
+ onChange={(event) => setTitle(event.target.value)}
+ aria-label={t("memory_view.new_name")}
+ data-escape-local=""
+ className="h-9 rounded-lg border border-border bg-background px-3 text-base text-foreground outline-none focus:border-border-strong"
+ />
+ <ErrorLine error={error} />
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" size="sm" onClick={onClose} disabled={busy}>
+ {t("memory_view.cancel")}
+ </Button>
+ <Button type="submit" size="sm" disabled={busy || !title.trim() || title.trim() === currentTitle}>
+ {busy && <Loader2 className="animate-spin" aria-hidden />}
+ {t("memory_view.rename")}
+ </Button>
+ </div>
+ </form>
+ </Frame>
+ );
+}
+
+export function ConfirmDialog({
+ open,
+ title,
+ description,
+ confirmLabel,
+ onClose,
+ onConfirm,
+ items,
+}: {
+ open: boolean;
+ title: string;
+ description: string;
+ confirmLabel: string;
+ onClose: () => void;
+ onConfirm: () => Promise<void>;
+ items?: string[];
+}) {
+ const t = useT();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (open) setError(null);
+ }, [open]);
+
+ const confirm = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ await onConfirm();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Frame open={open} onClose={onClose} busy={busy} title={title} description={description} testId="memory-confirm-dialog">
+ {items && items.length > 0 && (
+ <ul className="mt-4 max-h-48 overflow-y-auto rounded-lg border border-border bg-background px-3 py-2 font-mono text-xs leading-6 text-muted-foreground">
+ {items.slice(0, 200).map((item) => (
+ <li key={item} className="truncate">
+ {item}
+ </li>
+ ))}
+ {items.length > 200 && <li>{fill(t("memory_view.and_more"), { count: items.length - 200 })}</li>}
+ </ul>
+ )}
+ <ErrorLine error={error} />
+ <div className="mt-5 flex justify-end gap-2">
+ <Button type="button" variant="ghost" size="sm" onClick={onClose} disabled={busy}>
+ {t("memory_view.cancel")}
+ </Button>
+ <Button type="button" size="sm" onClick={confirm} disabled={busy}>
+ {busy && <Loader2 className="animate-spin" aria-hidden />}
+ {confirmLabel}
+ </Button>
+ </div>
+ </Frame>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/MemoryHealth.tsx b/jarvis/ui/web/frontend/src/components/memory/MemoryHealth.tsx
new file mode 100644
index 0000000000..5cad37ba9d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MemoryHealth.tsx
@@ -0,0 +1,122 @@
+/**
+ * The memory writer's health, honestly: a dot that says whether writes and
+ * the search index work, and a small panel with the reason and the one
+ * repair a person can start from here (rebuilding the search index).
+ */
+import { useEffect, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Loader2, RefreshCw } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { fetchWikiHealth, rebuildWikiIndex, type WikiHealthSnapshot } from "@/lib/wikiApi";
+import { Button } from "@/components/ui/button";
+
+type Visual = "green" | "amber" | "red" | "unknown";
+
+export function classifyHealth(health: WikiHealthSnapshot): Visual {
+ if (health.bootstrap_ok === false || health.last_write?.ok === false || health.last_chain_failure) return "red";
+ if (health.journal_backlog > 0 || health.vault_legacy_conflict || health.index_state === "stale") return "amber";
+ return health.bootstrap_ok ? "green" : "unknown";
+}
+
+const DOT: Record<Visual, string> = {
+ green: "bg-success",
+ amber: "bg-warning",
+ red: "bg-destructive",
+ unknown: "bg-faint-foreground",
+};
+
+export function MemoryHealth() {
+ const t = useT();
+ const queryClient = useQueryClient();
+ const [open, setOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState<string | null>(null);
+ const root = useRef<HTMLDivElement>(null);
+ const health = useQuery({ queryKey: ["wiki", "health"], queryFn: fetchWikiHealth, refetchInterval: 30_000, staleTime: 5_000 });
+ const visual: Visual = health.data ? classifyHealth(health.data) : "unknown";
+
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (event: MouseEvent) => {
+ if (root.current && !root.current.contains(event.target as Node)) setOpen(false);
+ };
+ const onKey = (event: KeyboardEvent) => event.key === "Escape" && setOpen(false);
+ window.addEventListener("mousedown", onDown);
+ window.addEventListener("keydown", onKey);
+ return () => {
+ window.removeEventListener("mousedown", onDown);
+ window.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ const reindex = async () => {
+ setBusy(true);
+ setResult(null);
+ try {
+ const response = await rebuildWikiIndex();
+ setResult(
+ response.ok
+ ? fill(t("memory_view.health_reindexed"), { count: response.indexed_pages ?? 0 })
+ : response.error ?? t("memory_view.health_reindex_failed"),
+ );
+ await queryClient.invalidateQueries({ queryKey: ["wiki"] });
+ } catch (err) {
+ setResult(err instanceof Error ? err.message : t("memory_view.health_reindex_failed"));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const data = health.data;
+ const reason = !data
+ ? t("memory_view.health_checking")
+ : data.bootstrap_ok === false
+ ? data.bootstrap_error ?? t("memory_view.health_writer_off")
+ : data.last_write?.ok === false
+ ? data.last_write.error ?? t("memory_view.health_write_failed")
+ : data.last_chain_failure
+ ? data.last_chain_failure.detail
+ : data.index_state === "stale"
+ ? fill(t("memory_view.health_index_stale"), { indexed: data.indexed_pages, pages: data.vault_pages })
+ : data.journal_backlog > 0
+ ? fill(t("memory_view.health_backlog"), { count: data.journal_backlog })
+ : t("memory_view.health_ok");
+
+ return (
+ <div ref={root} className="relative">
+ <button
+ type="button"
+ onClick={() => setOpen((value) => !value)}
+ aria-expanded={open}
+ data-testid="memory-health"
+ data-visual={visual}
+ className="inline-flex h-8 items-center gap-2 rounded-md px-2.5 text-sm text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ >
+ <span className={cn("h-2 w-2 rounded-full", health.isLoading ? "animate-pulse bg-faint-foreground" : DOT[visual])} aria-hidden />
+ {t(`memory_view.health_${visual}`)}
+ </button>
+ {open && (
+ <div className="absolute right-0 top-10 z-30 w-[300px] rounded-xl border border-border bg-popover p-4 text-sm shadow-float" role="dialog" aria-label={t("memory_view.health_title")}>
+ <p className="font-medium text-foreground-strong">{t("memory_view.health_title")}</p>
+ <p className="mt-1.5 leading-relaxed text-muted-foreground">{reason}</p>
+ {data && (
+ <dl className="mt-3 grid grid-cols-[1fr_auto] gap-x-3 gap-y-1 text-xs">
+ <dt className="text-muted-foreground">{t("memory_view.health_indexed")}</dt>
+ <dd className="text-right tabular-nums text-foreground">
+ {data.indexed_pages} / {data.vault_pages}
+ </dd>
+ <dt className="text-muted-foreground">{t("memory_view.health_queue")}</dt>
+ <dd className="text-right tabular-nums text-foreground">{data.journal_backlog}</dd>
+ </dl>
+ )}
+ <Button variant="outline" size="sm" className="mt-4 w-full" onClick={() => void reindex()} disabled={busy}>
+ {busy ? <Loader2 className="animate-spin" aria-hidden /> : <RefreshCw aria-hidden />}
+ {t("memory_view.health_reindex")}
+ </Button>
+ {result && <p className="mt-2 text-xs text-muted-foreground">{result}</p>}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/MemoryHome.tsx b/jarvis/ui/web/frontend/src/components/memory/MemoryHome.tsx
new file mode 100644
index 0000000000..68a0fc3222
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MemoryHome.tsx
@@ -0,0 +1,223 @@
+/**
+ * The Memory section's front page: what the assistant knows, what changed
+ * lately and what is most connected — each line one click from the page.
+ */
+import { useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { ArrowRight, BookOpen, Plus } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { countText, relativeAge } from "@/lib/memoryModel";
+import { MEMORY_KEYS, fetchMemoryActivity, type MemoryIndex } from "@/lib/memoryApi";
+import { Button } from "@/components/ui/button";
+import { EmptyState } from "@/components/ui/empty-state";
+import { KindIcon } from "./KindIcon";
+import { PageRow } from "./PageList";
+
+export function MemoryHome({
+ index,
+ language,
+ onOpen,
+ onNewPage,
+ onShowAgents,
+}: {
+ index: MemoryIndex;
+ language: string;
+ onOpen: (path: string) => void;
+ onNewPage: () => void;
+ onShowAgents: () => void;
+}) {
+ const t = useT();
+ const activity = useQuery({
+ queryKey: MEMORY_KEYS.activity,
+ queryFn: () => fetchMemoryActivity(12),
+ staleTime: 10_000,
+ });
+
+ const knowledge = useMemo(
+ () => index.pages.filter((page) => page.group === "knowledge" && !page.empty),
+ [index.pages],
+ );
+ const recent = useMemo(
+ () =>
+ index.pages
+ .filter((page) => page.group !== "system" && !page.empty)
+ .sort((a, b) => b.mtime - a.mtime)
+ .slice(0, 7),
+ [index.pages],
+ );
+ const hubs = useMemo(
+ () => [...knowledge].sort((a, b) => b.links_in - a.links_in).filter((page) => page.links_in > 0).slice(0, 6),
+ [knowledge],
+ );
+ const activeAgents = index.agents.filter((agent) => agent.state === "active");
+ const agentsWithMemory = activeAgents.filter((agent) => !agent.empty).length;
+
+ if (index.stats.content_pages === 0) {
+ return (
+ <div className="flex flex-1 items-center justify-center p-8">
+ <EmptyState
+ icon={<BookOpen />}
+ title={t("memory_view.vault_empty_title")}
+ description={t("memory_view.vault_empty_body")}
+ actions={
+ index.writable ? (
+ <Button size="sm" onClick={onNewPage}>
+ <Plus aria-hidden />
+ {t("memory_view.new_page")}
+ </Button>
+ ) : undefined
+ }
+ />
+ </div>
+ );
+ }
+
+ return (
+ <div className="mx-auto flex w-full max-w-[980px] flex-col px-8 pb-16 pt-8 lg:px-12" data-testid="memory-home">
+ <header className="flex flex-wrap items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h2 className="text-2xl font-semibold tracking-tight text-foreground-strong">{t("memory_view.home_title")}</h2>
+ <p className="mt-1 max-w-[600px] text-base text-muted-foreground">{t("memory_view.home_lead")}</p>
+ </div>
+ </header>
+
+ <div className="mt-7 grid grid-cols-2 gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-4" data-testid="memory-stats">
+ <Stat label={t("memory_view.stat_pages")} value={knowledge.length} />
+ <Stat label={t("memory_view.stat_links")} value={index.stats.links} />
+ <Stat label={t("memory_view.stat_mentions")} value={index.stats.mentions} />
+ <Stat
+ label={t("memory_view.stat_agents")}
+ value={agentsWithMemory}
+ suffix={activeAgents.length > 0 ? fill(t("memory_view.stat_of"), { count: activeAgents.length }) : undefined}
+ onClick={onShowAgents}
+ />
+ </div>
+
+ <div className="mt-10 grid gap-10 lg:grid-cols-[minmax(0,1fr)_300px]">
+ <section>
+ <SectionHeading title={t("memory_view.recently_changed")} />
+ <ul className="mt-2 flex flex-col divide-y divide-border border-y border-border">
+ {recent.map((page) => (
+ <li key={page.path}>
+ <PageRow page={page} language={language} onOpen={onOpen} compact />
+ </li>
+ ))}
+ </ul>
+ </section>
+
+ <div className="flex flex-col gap-10">
+ {hubs.length > 0 && (
+ <section>
+ <SectionHeading title={t("memory_view.most_connected")} />
+ <ul className="mt-2 flex flex-col gap-0.5">
+ {hubs.map((page) => (
+ <li key={page.path}>
+ <button
+ type="button"
+ onClick={() => onOpen(page.path)}
+ className="flex h-9 w-full items-center gap-2.5 rounded-lg px-2 text-left text-sm text-foreground transition-colors hover:bg-secondary"
+ >
+ <KindIcon kind={page.kind} className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{page.title}</span>
+ <span className="text-xs tabular-nums text-foreground-faint">
+ {countText(t, "memory_view.backlinks_short", page.links_in)}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ <section>
+ <SectionHeading title={t("memory_view.activity")} />
+ {activity.isLoading ? (
+ <div className="mt-3 space-y-2" role="status" aria-busy="true">
+ {[0, 1, 2].map((key) => (
+ <div key={key} className="h-8 animate-pulse rounded-md bg-secondary" />
+ ))}
+ </div>
+ ) : (activity.data?.items.length ?? 0) === 0 ? (
+ <p className="mt-2 text-sm text-muted-foreground">{t("memory_view.activity_empty")}</p>
+ ) : (
+ <ol className="mt-2 flex flex-col" data-testid="memory-activity">
+ {activity.data?.items.slice(0, 8).map((item, i) => (
+ <li key={`${item.ts}-${i}`} className="relative border-l border-border pb-4 pl-4 last:pb-0">
+ <span className="absolute -left-[3.5px] top-1.5 h-[7px] w-[7px] rounded-full border border-border-strong bg-background" aria-hidden />
+ <p className="text-xs text-foreground-faint">
+ {relativeAge(Date.parse(item.ts.replace(" ", "T")) / 1000, language)} · {verbLabel(t, item.verb)}
+ </p>
+ <div className="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5">
+ {item.pages.slice(0, 3).map((page) => (
+ <button
+ key={page.path}
+ type="button"
+ onClick={() => onOpen(page.path)}
+ className="truncate text-left text-sm text-foreground hover:underline"
+ >
+ {page.title}
+ </button>
+ ))}
+ {item.pages.length > 3 && (
+ <span className="text-sm text-muted-foreground">+{item.pages.length - 3}</span>
+ )}
+ </div>
+ </li>
+ ))}
+ </ol>
+ )}
+ </section>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const VERBS = new Set(["ingest", "update", "create", "merge", "rename", "archive", "delete"]);
+
+function verbLabel(t: (key: string) => string, verb: string): string {
+ return VERBS.has(verb) ? t(`memory_view.verb_${verb}`) : verb;
+}
+
+function SectionHeading({ title, action }: { title: string; action?: { label: string; onClick: () => void } }) {
+ return (
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium text-foreground">{title}</h3>
+ {action && (
+ <button type="button" onClick={action.onClick} className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
+ {action.label}
+ <ArrowRight className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ )}
+ </div>
+ );
+}
+
+function Stat({
+ label,
+ value,
+ suffix,
+ onClick,
+}: {
+ label: string;
+ value: number;
+ suffix?: string;
+ onClick?: () => void;
+}) {
+ const body = (
+ <>
+ <span className="block text-xs text-muted-foreground">{label}</span>
+ <span className="mt-1 flex items-baseline gap-1.5">
+ <span className="text-2xl font-semibold tabular-nums text-foreground-strong">{value.toLocaleString()}</span>
+ {suffix && <span className="text-xs text-foreground-faint">{suffix}</span>}
+ </span>
+ </>
+ );
+ return onClick ? (
+ <button type="button" onClick={onClick} className="bg-background px-4 py-3.5 text-left transition-colors hover:bg-secondary/60">
+ {body}
+ </button>
+ ) : (
+ <div className="bg-background px-4 py-3.5">{body}</div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/MemoryMap.tsx b/jarvis/ui/web/frontend/src/components/memory/MemoryMap.tsx
new file mode 100644
index 0000000000..3a8a83e775
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MemoryMap.tsx
@@ -0,0 +1,354 @@
+/**
+ * The memory map: every page with content as a node, every link (solid) and
+ * plain-text mention (dashed) as an edge.
+ *
+ * Ink only, no hue: knowledge pages in body ink, agent pages one step
+ * quieter, the page in focus and its neighbours in the accent. Size follows
+ * connectedness, names show for the hubs and for whatever the pointer is on.
+ * Colours come from the theme tokens and follow a light/dark switch live.
+ */
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import ForceGraph2D, { type ForceGraphMethods, type LinkObject, type NodeObject } from "react-force-graph-2d";
+import { useQuery } from "@tanstack/react-query";
+import { Maximize, Network } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { MEMORY_KEYS, fetchMemoryMap, type MapEdge, type MapNode } from "@/lib/memoryApi";
+import { EmptyState } from "@/components/ui/empty-state";
+
+type GraphNode = NodeObject<MapNode & { radius: number }>;
+type GraphLink = LinkObject<GraphNode, { kind: MapEdge["kind"] }>;
+
+interface Palette {
+ ink: string;
+ quiet: string;
+ faint: string;
+ edge: string;
+ edgeStrong: string;
+ accent: string;
+ background: string;
+}
+
+function readPalette(): Palette {
+ const style = getComputedStyle(document.documentElement);
+ const token = (name: string, fallback: string) => {
+ const value = style.getPropertyValue(name).trim();
+ return value ? `hsl(${value})` : fallback;
+ };
+ const alpha = (name: string, a: number, fallback: string) => {
+ const value = style.getPropertyValue(name).trim();
+ return value ? `hsl(${value} / ${a})` : fallback;
+ };
+ return {
+ ink: token("--foreground", "#fafafa"),
+ quiet: token("--muted-foreground", "#a1a1a1"),
+ faint: token("--foreground-faint", "#7a7a7a"),
+ edge: alpha("--foreground", 0.22, "rgba(255,255,255,0.22)"),
+ edgeStrong: alpha("--accent", 0.75, "#3d8bff"),
+ accent: token("--accent", "#3d8bff"),
+ background: token("--background", "#0a0a0a"),
+ };
+}
+
+/**
+ * A gentle pull of every node toward the origin. Without it a page with no
+ * links feels only repulsion, drifts to the edge, and fitting the view to it
+ * shrinks the connected part of the vault to a speck.
+ */
+function centringForce(strength: number) {
+ let nodes: GraphNode[] = [];
+ const force = (alpha: number) => {
+ for (const node of nodes) {
+ node.vx = (node.vx ?? 0) - (node.x ?? 0) * strength * alpha;
+ node.vy = (node.vy ?? 0) - (node.y ?? 0) * strength * alpha;
+ }
+ };
+ force.initialize = (next: GraphNode[]) => {
+ nodes = next;
+ };
+ return force;
+}
+
+const fitsConnected = (node: GraphNode) => node.degree > 0;
+
+function usePalette(): Palette {
+ const [palette, setPalette] = useState<Palette>(() => readPalette());
+ useEffect(() => {
+ const observer = new MutationObserver(() => setPalette(readPalette()));
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] });
+ return () => observer.disconnect();
+ }, []);
+ return palette;
+}
+
+function useSize<T extends HTMLElement>() {
+ const ref = useRef<T>(null);
+ const [size, setSize] = useState({ width: 0, height: 0 });
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const observer = new ResizeObserver(([entry]) => {
+ const { width, height } = entry.contentRect;
+ setSize((prev) => (Math.abs(prev.width - width) < 1 && Math.abs(prev.height - height) < 1 ? prev : { width, height }));
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+ return [ref, size] as const;
+}
+
+export function MemoryMap({
+ focus,
+ onOpen,
+ compact = false,
+}: {
+ focus: string | null;
+ onOpen: (path: string) => void;
+ /** No toolbar and no legend: for a card that embeds the map. */
+ compact?: boolean;
+}) {
+ const t = useT();
+ const [includeAgents, setIncludeAgents] = useState(true);
+ const query = useQuery({
+ queryKey: MEMORY_KEYS.map(includeAgents),
+ queryFn: () => fetchMemoryMap(includeAgents),
+ staleTime: 10_000,
+ });
+ const palette = usePalette();
+ const [containerRef, size] = useSize<HTMLDivElement>();
+ const graphRef = useRef<ForceGraphMethods<GraphNode, GraphLink>>();
+ const [hover, setHover] = useState<string | null>(null);
+ const framed = useRef(false);
+
+ const data = useMemo(() => {
+ const nodes: GraphNode[] = (query.data?.nodes ?? []).map((node) => ({
+ ...node,
+ radius: 2.6 + Math.min(Math.sqrt(node.degree), 7) * 1.25,
+ }));
+ const links: GraphLink[] = (query.data?.edges ?? []).map((edge) => ({ ...edge }));
+ return { nodes, links };
+ }, [query.data]);
+
+ const neighbours = useMemo(() => {
+ const map = new Map<string, Set<string>>();
+ for (const edge of query.data?.edges ?? []) {
+ if (!map.has(edge.source)) map.set(edge.source, new Set());
+ if (!map.has(edge.target)) map.set(edge.target, new Set());
+ map.get(edge.source)?.add(edge.target);
+ map.get(edge.target)?.add(edge.source);
+ }
+ return map;
+ }, [query.data]);
+
+ const labelled = useMemo(() => {
+ const ranked = [...(query.data?.nodes ?? [])].sort((a, b) => b.degree - a.degree);
+ return new Set(ranked.slice(0, 14).map((node) => node.id));
+ }, [query.data]);
+
+ const active = hover ?? focus;
+ const activeSet = useMemo(() => {
+ if (!active) return null;
+ return new Set([active, ...(neighbours.get(active) ?? [])]);
+ }, [active, neighbours]);
+
+ // Spread the layout (library defaults pack a few hundred pages into a
+ // ball), then frame it while it settles. The graph only exists once the
+ // container has a size, so this waits for that too.
+ const mounted = size.width > 0 && size.height > 0;
+ useEffect(() => {
+ const graph = graphRef.current;
+ if (!graph || !mounted) return;
+ const charge = graph.d3Force("charge") as unknown as
+ | { strength?: (v: number) => void; distanceMax?: (v: number) => void }
+ | undefined;
+ charge?.strength?.(-70);
+ charge?.distanceMax?.(420);
+ const link = graph.d3Force("link") as unknown as { distance?: (v: number) => void } | undefined;
+ link?.distance?.(46);
+ graph.d3Force("centre", centringForce(0.08) as never);
+ framed.current = false;
+ graph.d3ReheatSimulation();
+ if (focus) return;
+ // Framing an unsettled layout once leaves the cloud growing past the
+ // edges, so frame a few times while it spreads.
+ const timers = [700, 1800, 3500].map((ms) =>
+ window.setTimeout(() => graphRef.current?.zoomToFit(400, 48, fitsConnected), ms),
+ );
+ return () => timers.forEach((id) => window.clearTimeout(id));
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- re-run per data set, not per focus change
+ }, [data, mounted]);
+
+ // Bring the focused page into view once the layout has settled.
+ useEffect(() => {
+ if (!focus) return;
+ const id = window.setTimeout(() => {
+ const node = data.nodes.find((item) => item.id === focus);
+ if (node && typeof node.x === "number" && typeof node.y === "number") {
+ graphRef.current?.centerAt(node.x, node.y, 600);
+ graphRef.current?.zoom(2.4, 600);
+ }
+ }, 900);
+ return () => window.clearTimeout(id);
+ }, [focus, data]);
+
+ const paintNode = useCallback(
+ (node: GraphNode, ctx: CanvasRenderingContext2D, scale: number) => {
+ const x = node.x ?? 0;
+ const y = node.y ?? 0;
+ const isActive = node.id === active;
+ const lit = activeSet?.has(node.id) ?? false;
+ const dimmed = activeSet !== null && !lit;
+ // Zooming in should reveal the structure, not blow discs up: radii grow
+ // with the square root of the zoom only.
+ const radius = (isActive ? node.radius + 1.5 : node.radius) / Math.max(1, Math.sqrt(scale));
+ ctx.beginPath();
+ ctx.arc(x, y, radius, 0, Math.PI * 2);
+ ctx.globalAlpha = dimmed ? 0.18 : 1;
+ if (node.group === "agents") {
+ ctx.fillStyle = palette.background;
+ ctx.fill();
+ ctx.lineWidth = 1.2 / Math.max(scale, 0.6);
+ ctx.strokeStyle = lit ? palette.accent : palette.quiet;
+ ctx.stroke();
+ } else {
+ ctx.fillStyle = isActive || lit ? palette.accent : palette.ink;
+ ctx.fill();
+ }
+ const showLabel = isActive || (lit && activeSet !== null) || (activeSet === null && labelled.has(node.id)) || scale > 4;
+ if (showLabel) {
+ const fontSize = Math.max(11 / scale, 2.4);
+ ctx.font = `${isActive ? 600 : 500} ${fontSize}px Inter, ui-sans-serif, system-ui, sans-serif`;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "top";
+ const label = node.title.length > 36 ? `${node.title.slice(0, 34)}…` : node.title;
+ ctx.lineWidth = 3 / scale;
+ ctx.strokeStyle = palette.background;
+ ctx.strokeText(label, x, y + radius + 2 / scale);
+ ctx.fillStyle = isActive ? palette.ink : node.group === "agents" ? palette.faint : palette.quiet;
+ ctx.fillText(label, x, y + radius + 2 / scale);
+ }
+ ctx.globalAlpha = 1;
+ },
+ [active, activeSet, labelled, palette],
+ );
+
+ const linkColor = useCallback(
+ (link: GraphLink) => {
+ const source = typeof link.source === "object" ? (link.source as GraphNode).id : link.source;
+ const target = typeof link.target === "object" ? (link.target as GraphNode).id : link.target;
+ if (active && (source === active || target === active)) return palette.edgeStrong;
+ return activeSet ? "rgba(0,0,0,0)" : palette.edge;
+ },
+ [active, activeSet, palette],
+ );
+
+ const counts = useMemo(() => {
+ const nodes = query.data?.nodes ?? [];
+ return {
+ knowledge: nodes.filter((node) => node.group !== "agents").length,
+ agents: nodes.filter((node) => node.group === "agents").length,
+ links: (query.data?.edges ?? []).filter((edge) => edge.kind === "link").length,
+ mentions: (query.data?.edges ?? []).filter((edge) => edge.kind === "mention").length,
+ };
+ }, [query.data]);
+
+ return (
+ <div className="relative flex min-h-0 flex-1 flex-col" data-testid="memory-map">
+ {!compact && (
+ <div className="flex h-12 shrink-0 items-center gap-3 border-b border-border px-4">
+ <h2 className="text-base font-semibold text-foreground-strong">{t("memory_view.map")}</h2>
+ <span className="hidden text-sm text-muted-foreground md:inline">
+ {fill(t("memory_view.map_counts"), { pages: counts.knowledge + counts.agents, links: counts.links, mentions: counts.mentions })}
+ </span>
+ <div className="ml-auto flex items-center gap-1">
+ <label className="flex h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground">
+ <input
+ type="checkbox"
+ checked={includeAgents}
+ onChange={(event) => setIncludeAgents(event.target.checked)}
+ className="h-3.5 w-3.5 accent-[hsl(var(--accent))]"
+ />
+ {t("memory_view.map_include_agents")}
+ </label>
+ <button
+ type="button"
+ onClick={() => graphRef.current?.zoomToFit(500, 48, fitsConnected)}
+ className="inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground"
+ >
+ <Maximize className="h-3.5 w-3.5" aria-hidden />
+ {t("memory_view.map_fit")}
+ </button>
+ </div>
+ </div>
+ )}
+
+ <div ref={containerRef} className="relative min-h-0 flex-1 overflow-hidden">
+ {query.isError ? (
+ <div className="flex h-full items-center justify-center">
+ <EmptyState icon={<Network />} title={t("memory_view.map_error")} />
+ </div>
+ ) : !query.isLoading && data.nodes.length === 0 ? (
+ <div className="flex h-full items-center justify-center">
+ <EmptyState icon={<Network />} title={t("memory_view.map_empty_title")} description={t("memory_view.map_empty_body")} />
+ </div>
+ ) : size.width > 0 && size.height > 0 ? (
+ <ForceGraph2D<GraphNode, GraphLink>
+ ref={graphRef}
+ width={size.width}
+ height={size.height}
+ graphData={data}
+ backgroundColor="rgba(0,0,0,0)"
+ nodeId="id"
+ nodeLabel={() => ""}
+ nodeRelSize={1}
+ nodeVal={(node) => node.radius * node.radius}
+ nodeCanvasObject={paintNode}
+ nodePointerAreaPaint={(node, color, ctx) => {
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.arc(node.x ?? 0, node.y ?? 0, node.radius + 3, 0, Math.PI * 2);
+ ctx.fill();
+ }}
+ linkColor={linkColor}
+ linkWidth={(link) => (link.kind === "link" ? 1 : 0.8)}
+ linkLineDash={(link) => (link.kind === "mention" ? [2, 3] : null)}
+ cooldownTicks={140}
+ onEngineStop={() => {
+ if (framed.current) return;
+ framed.current = true;
+ if (!focus) graphRef.current?.zoomToFit(400, 48, fitsConnected);
+ }}
+ onNodeHover={(node) => setHover(node ? String(node.id) : null)}
+ onNodeClick={(node) => onOpen(String(node.id))}
+ onBackgroundClick={() => setHover(null)}
+ />
+ ) : null}
+
+ {!compact && (
+ <div className="pointer-events-none absolute bottom-4 left-4 flex flex-col gap-1.5 rounded-lg border border-border bg-popover/90 px-3 py-2.5 text-xs text-muted-foreground backdrop-blur-sm">
+ <LegendRow swatch={<span className="h-2.5 w-2.5 rounded-full bg-foreground" />} label={fill(t("memory_view.map_legend_knowledge"), { count: counts.knowledge })} />
+ {includeAgents && (
+ <LegendRow
+ swatch={<span className="h-2.5 w-2.5 rounded-full border border-muted-foreground" />}
+ label={fill(t("memory_view.map_legend_agents"), { count: counts.agents })}
+ />
+ )}
+ <LegendRow swatch={<span className="h-px w-4 bg-foreground/50" />} label={t("memory_view.map_legend_link")} />
+ <LegendRow swatch={<span className={cn("w-4 border-t border-dashed border-foreground/50")} />} label={t("memory_view.map_legend_mention")} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function LegendRow({ swatch, label }: { swatch: JSX.Element; label: string }) {
+ return (
+ <span className="flex items-center gap-2">
+ <span className="flex w-4 justify-center">{swatch}</span>
+ {label}
+ </span>
+ );
+}
+
+export default MemoryMap;
diff --git a/jarvis/ui/web/frontend/src/components/memory/MemoryNav.tsx b/jarvis/ui/web/frontend/src/components/memory/MemoryNav.tsx
new file mode 100644
index 0000000000..63577cbcbe
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MemoryNav.tsx
@@ -0,0 +1,209 @@
+/**
+ * The Memory section's navigation column: search, the areas of the vault with
+ * their page counts, and the agents whose notebooks hold something.
+ */
+import { useMemo } from "react";
+import { Bot, Home, Network, Plus, Search, Settings2 } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import type { MemoryIndex } from "@/lib/memoryApi";
+import { KNOWLEDGE_AREAS, SYSTEM_AREA, visibleAgents, type MemoryArea } from "@/lib/memoryModel";
+import { KindIcon } from "./KindIcon";
+
+export type NavTarget =
+ | { view: "home" }
+ | { view: "map" }
+ | { view: "area"; area: MemoryArea }
+ | { view: "agent"; agentId: string };
+
+const ITEM =
+ "flex h-8 w-full min-w-0 items-center gap-2.5 rounded-lg px-2 text-left text-base transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
+
+const AREA_KIND = { entities: "entity", projects: "project", concepts: "concept", journal: "session" } as const;
+
+const IS_MAC = typeof navigator !== "undefined" && /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent);
+
+export function MemoryNav({
+ index,
+ active,
+ activeAgentId,
+ onNavigate,
+ onSearch,
+ onNewPage,
+}: {
+ index: MemoryIndex | undefined;
+ active: NavTarget["view"] | MemoryArea | null;
+ activeAgentId: string | null;
+ onNavigate: (target: NavTarget) => void;
+ onSearch: () => void;
+ onNewPage: () => void;
+}) {
+ const t = useT();
+ const counts = useMemo(() => {
+ const out = new Map<MemoryArea, number>();
+ for (const page of index?.pages ?? []) {
+ if (page.empty) continue;
+ for (const area of [...KNOWLEDGE_AREAS, SYSTEM_AREA]) {
+ if (area.matches(page)) out.set(area.id, (out.get(area.id) ?? 0) + 1);
+ }
+ }
+ return out;
+ }, [index]);
+ // Only live agents get a row here; deleted and unknown ones stay one click
+ // away under "All agents", where they can also be tidied up.
+ const agents = useMemo(
+ () => visibleAgents(index?.agents ?? [], false).filter((agent) => agent.state === "active"),
+ [index],
+ );
+ const areas = KNOWLEDGE_AREAS.filter((area) => area.id !== "journal" || (counts.get("journal") ?? 0) > 0);
+
+ return (
+ <aside className="flex w-[248px] shrink-0 flex-col bg-sidebar" data-testid="memory-nav">
+ <div className="px-4 pb-3 pt-4">
+ <div className="flex items-center justify-between gap-2">
+ <h1 className="text-lg font-semibold text-foreground-strong">{t("memory_view.title")}</h1>
+ {index?.writable && (
+ <button
+ type="button"
+ onClick={onNewPage}
+ aria-label={t("memory_view.new_page")}
+ title={t("memory_view.new_page")}
+ data-testid="memory-new-page"
+ className="grid h-7 w-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Plus className="h-4 w-4" aria-hidden />
+ </button>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={onSearch}
+ data-testid="memory-search-trigger"
+ className="mt-3 flex h-8 w-full items-center gap-2 rounded-lg border border-border bg-background px-2.5 text-sm text-muted-foreground transition-colors hover:border-border-strong hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Search className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span className="flex-1 truncate text-left">{t("memory_view.search")}</span>
+ <kbd className="rounded border border-border px-1 font-sans text-xs leading-4 text-foreground-faint">
+ {IS_MAC ? "⌘K" : "Ctrl K"}
+ </kbd>
+ </button>
+ </div>
+
+ <ScrollArea className="min-h-0 flex-1">
+ <nav aria-label={t("memory_view.title")} className="flex flex-col gap-0.5 px-2 pb-4">
+ <NavItem active={active === "home"} onClick={() => onNavigate({ view: "home" })} icon={<Home aria-hidden />} label={t("memory_view.overview")} />
+ <NavItem active={active === "map"} onClick={() => onNavigate({ view: "map" })} icon={<Network aria-hidden />} label={t("memory_view.map")} />
+
+ <GroupHeading label={t("memory_view.group_knowledge")} />
+ {areas.map((area) => (
+ <NavItem
+ key={area.id}
+ active={active === area.id}
+ onClick={() => onNavigate({ view: "area", area: area.id })}
+ icon={<KindIcon kind={AREA_KIND[area.id as keyof typeof AREA_KIND]} />}
+ label={t(area.labelKey)}
+ count={counts.get(area.id) ?? 0}
+ testId={`memory-nav-${area.id}`}
+ />
+ ))}
+
+ <GroupHeading label={t("memory_view.group_agents")} />
+ <NavItem
+ active={active === "agents" && !activeAgentId}
+ onClick={() => onNavigate({ view: "area", area: "agents" })}
+ icon={<Bot aria-hidden />}
+ label={t("memory_view.all_agents")}
+ count={(index?.agents ?? []).filter((agent) => agent.state === "active").length}
+ testId="memory-nav-agents"
+ />
+ {agents.map((agent) => (
+ <button
+ key={agent.agent_id}
+ type="button"
+ onClick={() => onNavigate({ view: "agent", agentId: agent.agent_id })}
+ aria-current={activeAgentId === agent.agent_id ? "page" : undefined}
+ className={cn(
+ ITEM,
+ "pl-3 text-sm",
+ activeAgentId === agent.agent_id
+ ? "bg-secondary font-medium text-foreground-strong"
+ : "text-muted-foreground hover:bg-secondary hover:text-foreground",
+ )}
+ >
+ <span
+ className={cn(
+ "grid h-5 w-5 shrink-0 place-items-center rounded-md text-[10px] font-semibold uppercase",
+ agent.state === "active" ? "bg-surface-raised text-foreground" : "bg-secondary text-foreground-faint",
+ )}
+ aria-hidden
+ >
+ {agent.name.slice(0, 1)}
+ </span>
+ <span className="min-w-0 flex-1 truncate">{agent.name}</span>
+ {agent.state !== "active" && (
+ <span className="text-xs text-foreground-faint">{t(`memory_view.agent_${agent.state}_short`)}</span>
+ )}
+ </button>
+ ))}
+
+ <GroupHeading label={t("memory_view.group_system")} />
+ <NavItem
+ active={active === "system"}
+ onClick={() => onNavigate({ view: "area", area: "system" })}
+ icon={<Settings2 aria-hidden />}
+ label={t(SYSTEM_AREA.labelKey)}
+ count={counts.get("system") ?? 0}
+ />
+ </nav>
+ </ScrollArea>
+
+ {index && (
+ <p className="border-t border-border px-4 py-3 text-xs leading-5 text-foreground-faint" data-testid="memory-nav-stats">
+ {fill(t("memory_view.nav_stats"), {
+ pages: index.stats.content_pages,
+ links: index.stats.links + index.stats.mentions,
+ })}
+ </p>
+ )}
+ </aside>
+ );
+}
+
+function GroupHeading({ label }: { label: string }) {
+ return <h2 className="px-2 pb-1 pt-5 text-xs font-medium uppercase tracking-wide text-foreground-faint">{label}</h2>;
+}
+
+function NavItem({
+ active,
+ onClick,
+ icon,
+ label,
+ count,
+ testId,
+}: {
+ active: boolean;
+ onClick: () => void;
+ icon: JSX.Element;
+ label: string;
+ count?: number;
+ testId?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-current={active ? "page" : undefined}
+ data-testid={testId}
+ className={cn(
+ ITEM,
+ "[&>svg]:h-4 [&>svg]:w-4 [&>svg]:shrink-0",
+ active ? "bg-secondary font-medium text-foreground-strong" : "text-muted-foreground hover:bg-secondary hover:text-foreground",
+ )}
+ >
+ {icon}
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {count !== undefined && <span className="text-xs tabular-nums text-foreground-faint">{count}</span>}
+ </button>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/MemorySearch.tsx b/jarvis/ui/web/frontend/src/components/memory/MemorySearch.tsx
new file mode 100644
index 0000000000..e8d580ea6e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/MemorySearch.tsx
@@ -0,0 +1,157 @@
+/**
+ * Ctrl/Cmd+K over the whole memory: titles match instantly from the index,
+ * full text (and, when switched on, meaning) follows from the server, and a
+ * title nobody has written yet can become a new page from the same box.
+ */
+import { useEffect, useMemo, useState } from "react";
+import { Command } from "cmdk";
+import { useQuery } from "@tanstack/react-query";
+import { CornerDownLeft, Plus, Search } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { MEMORY_KEYS, searchMemory, type MemoryIndex } from "@/lib/memoryApi";
+import { KindIcon } from "./KindIcon";
+
+const ITEM =
+ "flex min-h-9 cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm text-foreground aria-selected:bg-secondary aria-selected:text-foreground-strong";
+
+export function MemorySearch({
+ open,
+ onOpenChange,
+ index,
+ onOpen,
+ onCreate,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ index: MemoryIndex | undefined;
+ onOpen: (path: string) => void;
+ onCreate: (title: string) => void;
+}) {
+ const t = useT();
+ const [query, setQuery] = useState("");
+ const [debounced, setDebounced] = useState("");
+
+ useEffect(() => {
+ const id = window.setTimeout(() => setDebounced(query.trim()), 180);
+ return () => window.clearTimeout(id);
+ }, [query]);
+
+ useEffect(() => {
+ if (!open) setQuery("");
+ }, [open]);
+
+ const titleHits = useMemo(() => {
+ const needle = query.trim().toLowerCase();
+ const pages = (index?.pages ?? []).filter((page) => page.group !== "system" || needle);
+ if (!needle) {
+ return pages.filter((page) => !page.empty).sort((a, b) => b.mtime - a.mtime).slice(0, 8);
+ }
+ return pages
+ .filter((page) => page.title.toLowerCase().includes(needle) || page.slug.toLowerCase().includes(needle))
+ .sort(
+ (a, b) =>
+ Number(b.title.toLowerCase().startsWith(needle)) - Number(a.title.toLowerCase().startsWith(needle)) ||
+ Number(a.empty) - Number(b.empty) ||
+ b.links_in - a.links_in,
+ )
+ .slice(0, 8);
+ }, [index, query]);
+
+ const textQuery = useQuery({
+ queryKey: MEMORY_KEYS.search(debounced),
+ queryFn: () => searchMemory(debounced),
+ enabled: open && debounced.length >= 2,
+ staleTime: 30_000,
+ });
+ const titlePaths = new Set(titleHits.map((page) => page.path));
+ const byPath = new Map((index?.pages ?? []).map((page) => [page.path, page]));
+ const textHits = (textQuery.data ?? []).filter((hit) => !titlePaths.has(hit.path));
+ const exact = (index?.pages ?? []).some((page) => page.title.toLowerCase() === query.trim().toLowerCase());
+
+ const choose = (path: string) => {
+ onOpenChange(false);
+ onOpen(path);
+ };
+
+ return (
+ <Command.Dialog
+ open={open}
+ onOpenChange={onOpenChange}
+ label={t("memory_view.search")}
+ shouldFilter={false}
+ overlayClassName="fixed inset-0 z-[80] bg-scrim/40"
+ contentClassName="fixed left-1/2 top-[14%] z-[90] w-[min(640px,calc(100vw-2rem))] -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-float"
+ data-testid="memory-search"
+ >
+ <div className="flex items-center gap-2.5 border-b border-border px-4">
+ <Search className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ <Command.Input
+ value={query}
+ onValueChange={setQuery}
+ placeholder={t("memory_view.search_placeholder")}
+ className="h-12 flex-1 bg-transparent text-base text-foreground outline-none placeholder:text-foreground-faint"
+ />
+ </div>
+ <Command.List className="max-h-[min(60vh,480px)] overflow-y-auto p-2">
+ <Command.Empty className="px-3 py-8 text-center text-sm text-muted-foreground">
+ {textQuery.isFetching ? t("memory_view.searching") : t("memory_view.search_no_results")}
+ </Command.Empty>
+
+ {titleHits.length > 0 && (
+ <Command.Group
+ heading={query.trim() ? t("memory_view.search_titles") : t("memory_view.recently_changed")}
+ className="[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:pt-2 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:text-foreground-faint"
+ >
+ {titleHits.map((page) => (
+ <Command.Item key={page.path} value={`title:${page.path}`} onSelect={() => choose(page.path)} className={ITEM}>
+ <KindIcon kind={page.kind} className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{page.title}</span>
+ <span className="max-w-[40%] truncate text-xs text-foreground-faint">
+ {page.empty ? t("memory_view.no_content_yet") : page.folder}
+ </span>
+ </Command.Item>
+ ))}
+ </Command.Group>
+ )}
+
+ {textHits.length > 0 && (
+ <Command.Group
+ heading={t("memory_view.search_text")}
+ className="[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:pt-3 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:text-foreground-faint"
+ >
+ {textHits.map((hit) => {
+ const page = byPath.get(hit.path);
+ return (
+ <Command.Item key={hit.path} value={`text:${hit.path}`} onSelect={() => choose(hit.path)} className={`${ITEM} items-start`}>
+ <KindIcon kind={page?.kind} className="mt-0.5 h-3.5 w-3.5 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{page?.title ?? hit.title}</span>
+ {hit.snippet && <span className="line-clamp-2 text-xs text-muted-foreground">{hit.snippet.replace(/\s+/g, " ")}</span>}
+ </span>
+ {hit.by_meaning && <span className="shrink-0 text-xs text-foreground-faint">{t("memory_view.by_meaning")}</span>}
+ </Command.Item>
+ );
+ })}
+ </Command.Group>
+ )}
+
+ {query.trim() && !exact && index?.writable && (
+ <Command.Group className="mt-1 border-t border-border pt-1">
+ <Command.Item
+ value="create"
+ onSelect={() => {
+ onOpenChange(false);
+ onCreate(query.trim());
+ }}
+ className={ITEM}
+ >
+ <Plus className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
+ <span className="flex-1 truncate">{fill(t("memory_view.search_create"), { title: query.trim() })}</span>
+ <CornerDownLeft className="h-3.5 w-3.5 text-foreground-faint" aria-hidden />
+ </Command.Item>
+ </Command.Group>
+ )}
+ </Command.List>
+ </Command.Dialog>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/PageEditor.tsx b/jarvis/ui/web/frontend/src/components/memory/PageEditor.tsx
new file mode 100644
index 0000000000..e2d82c6733
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/PageEditor.tsx
@@ -0,0 +1,235 @@
+/**
+ * Plain Markdown editing for one page, with `[[` link completion.
+ *
+ * The file on disk stays the source of truth: the editor saves the body only
+ * (frontmatter is kept by the server), refuses to overwrite a page that
+ * changed since it was opened, and Ctrl/Cmd+S saves while Escape cancels.
+ */
+import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { Eye, Loader2, PencilLine } from "lucide-react";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import type { MemoryPageSummary } from "@/lib/memoryApi";
+import { KindIcon } from "./KindIcon";
+
+interface Suggestion {
+ start: number;
+ query: string;
+}
+
+export function PageEditor({
+ initialBody,
+ pages,
+ onSave,
+ onCancel,
+ renderPreview,
+}: {
+ initialBody: string;
+ pages: MemoryPageSummary[];
+ onSave: (body: string) => Promise<void>;
+ onCancel: () => void;
+ renderPreview: (body: string) => JSX.Element;
+}) {
+ const t = useT();
+ const [body, setBody] = useState(initialBody);
+ const [preview, setPreview] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [suggestion, setSuggestion] = useState<Suggestion | null>(null);
+ const [highlight, setHighlight] = useState(0);
+ const area = useRef<HTMLTextAreaElement>(null);
+ const dirty = body !== initialBody;
+
+ const slugCounts = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const page of pages) counts.set(page.slug.toLowerCase(), (counts.get(page.slug.toLowerCase()) ?? 0) + 1);
+ return counts;
+ }, [pages]);
+
+ const matches = useMemo(() => {
+ if (!suggestion) return [];
+ const needle = suggestion.query.toLowerCase();
+ return pages
+ .filter((page) => page.group !== "system" && !page.empty)
+ .filter((page) => !needle || page.title.toLowerCase().includes(needle) || page.slug.includes(needle))
+ .sort((a, b) => Number(b.group === "knowledge") - Number(a.group === "knowledge") || b.links_in - a.links_in)
+ .slice(0, 7);
+ }, [pages, suggestion]);
+
+ useEffect(() => setHighlight(0), [suggestion?.query]);
+
+ const save = async () => {
+ if (busy) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await onSave(body);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const readSuggestion = (value: string, caret: number) => {
+ const before = value.slice(0, caret);
+ const open = before.lastIndexOf("[[");
+ if (open < 0 || before.slice(open).includes("]]") || before.slice(open).includes("\n")) {
+ setSuggestion(null);
+ return;
+ }
+ setSuggestion({ start: open, query: before.slice(open + 2) });
+ };
+
+ const insert = (page: MemoryPageSummary) => {
+ const el = area.current;
+ if (!el || !suggestion) return;
+ const unique = (slugCounts.get(page.slug.toLowerCase()) ?? 0) === 1;
+ const target = unique ? page.slug : page.path.replace(/\.md$/i, "");
+ const label = unique && page.title.toLowerCase() !== page.slug.toLowerCase() ? `|${page.title}` : "";
+ const caret = el.selectionStart;
+ const after = body.slice(caret).startsWith("]]") ? body.slice(caret + 2) : body.slice(caret);
+ const link = `[[${target}${label}]]`;
+ const next = body.slice(0, suggestion.start) + link + after;
+ setBody(next);
+ setSuggestion(null);
+ requestAnimationFrame(() => {
+ el.focus();
+ const position = suggestion.start + link.length;
+ el.setSelectionRange(position, position);
+ });
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
+ event.preventDefault();
+ void save();
+ return;
+ }
+ if (suggestion && matches.length > 0) {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ setHighlight((value) => (value + 1) % matches.length);
+ return;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ setHighlight((value) => (value - 1 + matches.length) % matches.length);
+ return;
+ }
+ if (event.key === "Enter" || event.key === "Tab") {
+ event.preventDefault();
+ insert(matches[highlight]);
+ return;
+ }
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ if (suggestion) setSuggestion(null);
+ else onCancel();
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-3" data-testid="memory-editor">
+ <div className="flex items-center gap-1 rounded-lg border border-border bg-sidebar p-1">
+ <ModeButton active={!preview} onClick={() => setPreview(false)} icon={<PencilLine aria-hidden />} label={t("memory_view.write")} />
+ <ModeButton active={preview} onClick={() => setPreview(true)} icon={<Eye aria-hidden />} label={t("memory_view.preview")} />
+ <span className="ml-auto hidden pr-2 text-xs text-foreground-faint sm:inline">{t("memory_view.editor_hint")}</span>
+ </div>
+
+ {preview ? (
+ <div className="min-h-[320px] rounded-lg border border-border px-6 py-5">{renderPreview(body)}</div>
+ ) : (
+ <div className="relative">
+ <textarea
+ ref={area}
+ autoFocus
+ value={body}
+ data-escape-local=""
+ spellCheck
+ onChange={(event) => {
+ setBody(event.target.value);
+ readSuggestion(event.target.value, event.target.selectionStart);
+ }}
+ onKeyDown={onKeyDown}
+ onClick={(event) => readSuggestion(body, event.currentTarget.selectionStart)}
+ onBlur={() => window.setTimeout(() => setSuggestion(null), 150)}
+ aria-label={t("memory_view.editor_label")}
+ className="block min-h-[420px] w-full resize-y rounded-lg border border-border bg-background px-5 py-4 font-mono text-sm leading-6 text-foreground outline-none focus:border-border-strong"
+ />
+ {suggestion && matches.length > 0 && (
+ <ul
+ role="listbox"
+ aria-label={t("memory_view.link_suggestions")}
+ className="absolute left-0 right-0 top-full z-10 mt-1 overflow-hidden rounded-lg border border-border bg-popover p-1 shadow-float"
+ >
+ {matches.map((page, index) => (
+ <li key={page.path} role="option" aria-selected={index === highlight}>
+ <button
+ type="button"
+ onMouseDown={(event) => {
+ event.preventDefault();
+ insert(page);
+ }}
+ className={cn(
+ "flex h-8 w-full items-center gap-2 rounded-md px-2 text-left text-sm",
+ index === highlight ? "bg-secondary text-foreground-strong" : "text-foreground hover:bg-secondary",
+ )}
+ >
+ <KindIcon kind={page.kind} className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate">{page.title}</span>
+ <span className="truncate font-mono text-xs text-foreground-faint">{page.folder}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ <div className="flex items-center justify-end gap-2">
+ <Button variant="ghost" size="sm" onClick={onCancel} disabled={busy}>
+ {t("memory_view.cancel")}
+ </Button>
+ <Button size="sm" onClick={() => void save()} disabled={busy || !dirty} data-testid="memory-editor-save">
+ {busy && <Loader2 className="animate-spin" aria-hidden />}
+ {t("memory_view.save")}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function ModeButton({
+ active,
+ onClick,
+ icon,
+ label,
+}: {
+ active: boolean;
+ onClick: () => void;
+ icon: JSX.Element;
+ label: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={active}
+ className={cn(
+ "flex h-7 items-center gap-1.5 rounded-md px-2.5 text-sm font-medium transition-colors [&>svg]:h-3.5 [&>svg]:w-3.5",
+ active ? "bg-background text-foreground-strong shadow-sm" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {icon}
+ {label}
+ </button>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/PageList.tsx b/jarvis/ui/web/frontend/src/components/memory/PageList.tsx
new file mode 100644
index 0000000000..8f172d1245
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/PageList.tsx
@@ -0,0 +1,169 @@
+/**
+ * One area of the vault as a list: each page with its first sentence, how
+ * connected it is and when it last changed. Pages without content are
+ * counted but folded away until asked for.
+ */
+import { useMemo, useState } from "react";
+import { Link2, Search } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import type { MemoryPageSummary } from "@/lib/memoryApi";
+import { matchesQuery, relativeAge, sortPages, type SortKey } from "@/lib/memoryModel";
+import { EmptyState } from "@/components/ui/empty-state";
+import { KindIcon } from "./KindIcon";
+
+export function PageList({
+ title,
+ description,
+ pages,
+ language,
+ onOpen,
+ emptyIcon,
+ emptyTitle,
+ emptyBody,
+ actions,
+}: {
+ title: string;
+ description: string;
+ pages: MemoryPageSummary[];
+ language: string;
+ onOpen: (path: string) => void;
+ emptyIcon: JSX.Element;
+ emptyTitle: string;
+ emptyBody: string;
+ actions?: JSX.Element;
+}) {
+ const t = useT();
+ const [query, setQuery] = useState("");
+ const [sort, setSort] = useState<SortKey>("recent");
+ const [showEmpty, setShowEmpty] = useState(false);
+
+ const withContent = pages.filter((page) => !page.empty);
+ const emptyCount = pages.length - withContent.length;
+ const shown = useMemo(
+ () => sortPages((showEmpty ? pages : withContent).filter((page) => matchesQuery(page, query)), sort),
+ [pages, query, showEmpty, sort, withContent],
+ );
+
+ return (
+ <div className="mx-auto flex w-full max-w-[980px] flex-col px-8 pb-16 pt-8 lg:px-12" data-testid="memory-page-list">
+ <header className="flex flex-wrap items-end justify-between gap-4">
+ <div className="min-w-0">
+ <h2 className="text-2xl font-semibold tracking-tight text-foreground-strong">{title}</h2>
+ <p className="mt-1 max-w-[560px] text-base text-muted-foreground">{description}</p>
+ </div>
+ {actions}
+ </header>
+
+ {pages.length === 0 ? (
+ <EmptyState icon={emptyIcon} title={emptyTitle} description={emptyBody} className="mt-10" />
+ ) : (
+ <>
+ <div className="mt-6 flex flex-wrap items-center gap-2">
+ <label className="flex h-8 min-w-[220px] flex-1 items-center gap-2 rounded-lg border border-border bg-background px-2.5 focus-within:border-border-strong">
+ <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ <input
+ type="search"
+ value={query}
+ data-escape-local=""
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") setQuery("");
+ }}
+ placeholder={t("memory_view.filter")}
+ aria-label={t("memory_view.filter")}
+ className="h-full min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-foreground-faint [&::-webkit-search-cancel-button]:hidden"
+ />
+ </label>
+ <div className="flex items-center rounded-lg border border-border p-0.5" role="group" aria-label={t("memory_view.sort")}>
+ {(["recent", "name", "links"] as const).map((key) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setSort(key)}
+ aria-pressed={sort === key}
+ className={cn(
+ "h-7 rounded-md px-2.5 text-sm transition-colors",
+ sort === key ? "bg-secondary font-medium text-foreground-strong" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {t(`memory_view.sort_${key}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <ul className="mt-4 flex flex-col divide-y divide-border border-y border-border" data-testid="memory-page-rows">
+ {shown.map((page) => (
+ <li key={page.path}>
+ <PageRow page={page} language={language} onOpen={onOpen} />
+ </li>
+ ))}
+ </ul>
+ {shown.length === 0 && (
+ <p className="py-8 text-center text-sm text-muted-foreground">{t("memory_view.filter_no_match")}</p>
+ )}
+ {emptyCount > 0 && (
+ <button
+ type="button"
+ onClick={() => setShowEmpty((value) => !value)}
+ className="mt-4 self-start rounded-md px-1 text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
+ data-testid="memory-toggle-empty"
+ >
+ {showEmpty
+ ? t("memory_view.hide_empty")
+ : fill(t("memory_view.show_empty"), { count: emptyCount })}
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
+
+export function PageRow({
+ page,
+ language,
+ onOpen,
+ compact = false,
+}: {
+ page: MemoryPageSummary;
+ language: string;
+ onOpen: (path: string) => void;
+ compact?: boolean;
+}) {
+ const t = useT();
+ const links = page.links_in + page.links_out;
+ return (
+ <button
+ type="button"
+ onClick={() => onOpen(page.path)}
+ data-memory-row={page.path}
+ className={cn(
+ "group flex w-full items-start gap-3 px-2 text-left transition-colors hover:bg-secondary/60 focus-visible:bg-secondary focus-visible:outline-none",
+ compact ? "py-2.5" : "py-3.5",
+ )}
+ >
+ <KindIcon kind={page.kind} className="mt-0.5 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="flex min-w-0 items-baseline gap-3">
+ <span className={cn("truncate text-base font-medium", page.empty ? "text-muted-foreground" : "text-foreground-strong")}>
+ {page.title}
+ </span>
+ </span>
+ <span className="mt-0.5 line-clamp-1 text-sm text-muted-foreground">
+ {page.empty ? t("memory_view.no_content_yet") : page.summary || " "}
+ </span>
+ </span>
+ <span className="flex shrink-0 items-center gap-3 pt-0.5 text-xs tabular-nums text-foreground-faint">
+ {links > 0 && (
+ <span className="inline-flex items-center gap-1" title={fill(t("memory_view.links_title"), { inbound: page.links_in, outbound: page.links_out })}>
+ <Link2 className="h-3 w-3" aria-hidden />
+ {links}
+ </span>
+ )}
+ <span className="w-[86px] text-right">{relativeAge(page.mtime, language)}</span>
+ </span>
+ </button>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/memory/PageReader.tsx b/jarvis/ui/web/frontend/src/components/memory/PageReader.tsx
new file mode 100644
index 0000000000..9f452e5e23
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/memory/PageReader.tsx
@@ -0,0 +1,633 @@
+/**
+ * One memory page: a document column and a rail of everything it connects to.
+ *
+ * ┌──────────────────────────────────────────┬─────────────────┐
+ * │ Area › Title actions │ Linked from │
+ * │ Title │ Links to │
+ * │ kind · updated · words │ Mentioned in │
+ * │ │ Related │
+ * │ body / notebook entries / empty state │ Properties │
+ * └──────────────────────────────────────────┴─────────────────┘
+ *
+ * Agent notebooks render as their entries, with the agent's other pages one
+ * click away; a page without a sentence of content says so instead of
+ * showing an empty sheet.
+ */
+import { useCallback, useMemo, useState, type ReactNode } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import {
+ Archive,
+ ChevronRight,
+ Copy,
+ ExternalLink,
+ FileQuestion,
+ Network,
+ PencilLine,
+ TextCursorInput,
+} from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { buildObsidianUrl } from "@/lib/obsidian";
+import {
+ MEMORY_KEYS,
+ archiveMemoryPage,
+ renameMemoryPage,
+ saveMemoryPage,
+ useMemoryPage,
+ type LinkRef,
+ type MemoryIndex,
+ type MemoryPage,
+ type NotebookEntry,
+ type PageRef,
+} from "@/lib/memoryApi";
+import {
+ GROUP_LABEL_KEY,
+ HIDDEN_PROPERTIES,
+ KIND_LABEL_KEY,
+ areaOf,
+ formatProperty,
+ countText,
+ prepareBody,
+ relativeAge,
+ type MemoryArea,
+} from "@/lib/memoryModel";
+import { EmptyState } from "@/components/ui/empty-state";
+import { Button } from "@/components/ui/button";
+import { KindIcon } from "./KindIcon";
+import { MarkdownBody } from "./MarkdownBody";
+import { PageEditor } from "./PageEditor";
+import { ConfirmDialog, RenameDialog } from "./MemoryDialogs";
+
+export function PageReader({
+ path,
+ index,
+ language,
+ onOpen,
+ onArea,
+ onShowOnMap,
+ onCreate,
+ onArchived,
+ notify,
+}: {
+ path: string;
+ index: MemoryIndex | undefined;
+ language: string;
+ onOpen: (path: string) => void;
+ onArea: (area: MemoryArea) => void;
+ onShowOnMap: (path: string) => void;
+ onCreate: (title: string) => void;
+ onArchived: () => void;
+ notify: (message: string) => void;
+}) {
+ const t = useT();
+ const queryClient = useQueryClient();
+ const pageQuery = useMemoryPage(path);
+ const page = pageQuery.data;
+ const [editing, setEditing] = useState(false);
+ const [renaming, setRenaming] = useState(false);
+ const [archiving, setArchiving] = useState(false);
+
+ const refresh = useCallback(
+ () => queryClient.invalidateQueries({ queryKey: MEMORY_KEYS.all }),
+ [queryClient],
+ );
+
+ if (pageQuery.isLoading) return <ReaderSkeleton />;
+ if (pageQuery.isError || !page) {
+ return (
+ <div className="flex flex-1 items-center justify-center p-8">
+ <EmptyState
+ icon={<FileQuestion />}
+ title={t("memory_view.page_missing_title")}
+ description={pageQuery.error instanceof Error ? pageQuery.error.message : t("memory_view.page_missing_body")}
+ />
+ </div>
+ );
+ }
+
+ const area = areaOf(page);
+ const agentPages = page.agent_id
+ ? (index?.pages ?? []).filter((item) => item.agent_id === page.agent_id)
+ : [];
+
+ return (
+ <div className="flex min-h-0 flex-1" data-testid="memory-reader" data-path={page.path}>
+ <div className="min-w-0 flex-1 overflow-y-auto">
+ <article className="mx-auto w-full max-w-[760px] px-8 pb-24 pt-6 lg:px-12">
+ <nav aria-label={t("memory_view.breadcrumb")} className="flex min-w-0 items-center gap-1 text-sm text-muted-foreground">
+ <button type="button" onClick={() => onArea(area)} className="truncate rounded px-1 py-0.5 hover:bg-secondary hover:text-foreground">
+ {area === "agents" ? t("memory_view.area_agents") : t(`memory_view.area_${area}`)}
+ </button>
+ {page.agent && (
+ <>
+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-foreground-faint" aria-hidden />
+ <span className="truncate px-1">{page.agent.name}</span>
+ </>
+ )}
+ </nav>
+
+ <header className="mt-5">
+ <div className="flex items-start gap-4">
+ <h1 className="min-w-0 flex-1 text-[28px] font-semibold leading-tight tracking-tight text-foreground-strong" data-testid="memory-page-title">
+ {page.title}
+ </h1>
+ <PageActions
+ page={page}
+ vaultRoot={index?.vault_root ?? ""}
+ writable={index?.writable ?? false}
+ onEdit={() => setEditing(true)}
+ onRename={() => setRenaming(true)}
+ onArchive={() => setArchiving(true)}
+ onShowOnMap={() => onShowOnMap(page.path)}
+ notify={notify}
+ />
+ </div>
+ <MetaLine page={page} language={language} />
+ {(page.aliases.length > 0 || page.tags.length > 0) && (
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ {page.aliases.map((alias) => (
+ <span key={`a-${alias}`} className="rounded-md bg-secondary px-2 py-0.5 text-xs text-foreground-secondary">
+ {alias}
+ </span>
+ ))}
+ {page.tags.map((tag) => (
+ <span key={`t-${tag}`} className="rounded-md border border-border px-2 py-0.5 text-xs text-muted-foreground">
+ #{tag}
+ </span>
+ ))}
+ </div>
+ )}
+ </header>
+
+ {agentPages.length > 1 && (
+ <AgentTabs current={page.path} pages={agentPages} onOpen={onOpen} />
+ )}
+
+ <div className="mt-8">
+ {editing ? (
+ <PageEditor
+ initialBody={page.body_md.replace(/^\s+/, "")}
+ pages={index?.pages ?? []}
+ onCancel={() => setEditing(false)}
+ onSave={async (body) => {
+ await saveMemoryPage(page.path, body, page.mtime);
+ await refresh();
+ setEditing(false);
+ notify(t("memory_view.saved"));
+ }}
+ renderPreview={(body) => (
+ <MarkdownBody markdown={prepareBody(body, page.title, page.outgoing)} onOpen={onOpen} onCreate={onCreate} />
+ )}
+ />
+ ) : (
+ <PageBody page={page} onOpen={onOpen} onCreate={onCreate} onEdit={() => setEditing(true)} writable={Boolean(index?.writable)} />
+ )}
+ </div>
+ {!editing && <ConnectionsRail page={page} onOpen={onOpen} inline />}
+ </article>
+ </div>
+
+ <ConnectionsRail page={page} onOpen={onOpen} />
+
+ <RenameDialog
+ open={renaming}
+ currentTitle={page.title}
+ onClose={() => setRenaming(false)}
+ onRename={async (title) => {
+ const result = await renameMemoryPage(page.path, title);
+ await refresh();
+ setRenaming(false);
+ const done =
+ result.links_rewritten > 0
+ ? fill(t("memory_view.renamed_links"), { count: result.links_rewritten })
+ : t("memory_view.renamed");
+ notify(
+ result.links_unrewritten > 0
+ ? `${done} ${fill(t("memory_view.renamed_unrewritten"), { count: result.links_unrewritten })}`
+ : done,
+ );
+ if (result.path !== page.path) onOpen(result.path);
+ }}
+ />
+ <ConfirmDialog
+ open={archiving}
+ title={fill(t("memory_view.archive_title"), { title: page.title })}
+ description={t("memory_view.archive_body")}
+ confirmLabel={t("memory_view.archive")}
+ onClose={() => setArchiving(false)}
+ onConfirm={async () => {
+ await archiveMemoryPage(page.path);
+ await refresh();
+ setArchiving(false);
+ notify(t("memory_view.archived"));
+ onArchived();
+ }}
+ />
+ </div>
+ );
+}
+
+function MetaLine({ page, language }: { page: MemoryPage; language: string }) {
+ const t = useT();
+ const parts: ReactNode[] = [
+ <span key="kind" className="inline-flex items-center gap-1.5">
+ <KindIcon kind={page.kind} className="h-3.5 w-3.5" />
+ {t(KIND_LABEL_KEY[page.kind])}
+ </span>,
+ ];
+ if (page.agent && page.agent.state !== "active") {
+ parts.push(
+ <span key="state" className="rounded bg-secondary px-1.5 py-px text-xs text-muted-foreground">
+ {t(`memory_view.agent_${page.agent.state}`)}
+ </span>,
+ );
+ }
+ const age = relativeAge(page.mtime, language);
+ if (age) parts.push(<span key="age">{fill(t("memory_view.updated"), { age })}</span>);
+ if (page.entries.length > 0) {
+ parts.push(<span key="entries">{countText(t, "memory_view.entries_count", page.entries.length)}</span>);
+ } else if (page.words > 0) {
+ parts.push(<span key="words">{countText(t, "memory_view.words_count", page.words)}</span>);
+ }
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-x-2.5 gap-y-1 text-sm text-muted-foreground" data-testid="memory-meta">
+ {parts.map((part, i) => (
+ <span key={i} className="inline-flex items-center gap-2.5">
+ {i > 0 && <span className="text-foreground-faint" aria-hidden>·</span>}
+ {part}
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function PageActions({
+ page,
+ vaultRoot,
+ writable,
+ onEdit,
+ onRename,
+ onArchive,
+ onShowOnMap,
+ notify,
+}: {
+ page: MemoryPage;
+ vaultRoot: string;
+ writable: boolean;
+ onEdit: () => void;
+ onRename: () => void;
+ onArchive: () => void;
+ onShowOnMap: () => void;
+ notify: (message: string) => void;
+}) {
+ const t = useT();
+ return (
+ <div className="flex shrink-0 items-center gap-0.5 pt-1">
+ {page.editable && writable && (
+ <Button variant="secondary" size="sm" onClick={onEdit} data-testid="memory-edit">
+ <PencilLine aria-hidden />
+ {t("memory_view.edit")}
+ </Button>
+ )}
+ {!page.empty && <IconAction label={t("memory_view.show_on_map")} onClick={onShowOnMap} icon={<Network />} />}
+ {vaultRoot && (
+ <IconAction
+ label={t("memory_view.open_obsidian")}
+ icon={<ExternalLink />}
+ onClick={() => {
+ window.location.href = buildObsidianUrl(vaultRoot, page.path);
+ }}
+ />
+ )}
+ <IconAction
+ label={t("memory_view.copy_path")}
+ icon={<Copy />}
+ onClick={() => {
+ void navigator.clipboard?.writeText(page.path).then(
+ () => notify(t("memory_view.copied")),
+ () => notify(page.path),
+ );
+ }}
+ />
+ {page.group === "knowledge" && writable && (
+ <IconAction label={t("memory_view.rename")} icon={<TextCursorInput />} onClick={onRename} />
+ )}
+ {page.archivable && writable && <IconAction label={t("memory_view.archive")} icon={<Archive />} onClick={onArchive} />}
+ </div>
+ );
+}
+
+function IconAction({ label, icon, onClick }: { label: string; icon: JSX.Element; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={label}
+ title={label}
+ className="grid h-8 w-8 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:h-4 [&>svg]:w-4"
+ >
+ {icon}
+ </button>
+ );
+}
+
+function AgentTabs({
+ current,
+ pages,
+ onOpen,
+}: {
+ current: string;
+ pages: { path: string; title: string; kind: string; empty: boolean; mtime: number }[];
+ onOpen: (path: string) => void;
+}) {
+ const t = useT();
+ const order = (kind: string) => (kind === "memory" ? 0 : kind === "profile" ? 1 : 2);
+ const sorted = [...pages].sort((a, b) => order(a.kind) - order(b.kind) || b.mtime - a.mtime);
+ return (
+ <div className="mt-6 flex gap-1 overflow-x-auto border-b border-border [scrollbar-width:none]" role="tablist" aria-label={t("memory_view.agent_pages")}>
+ {sorted.map((item) => {
+ const active = item.path === current;
+ const label =
+ item.kind === "memory" ? t("memory_view.kind_memory") : item.kind === "profile" ? t("memory_view.kind_profile") : item.title;
+ return (
+ <button
+ key={item.path}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={() => onOpen(item.path)}
+ className={cn(
+ "-mb-px max-w-[220px] shrink-0 truncate border-b-2 px-3 pb-2 pt-1 text-sm transition-colors",
+ active ? "border-accent font-medium text-foreground-strong" : "border-transparent text-muted-foreground hover:text-foreground",
+ item.empty && !active && "text-foreground-faint",
+ )}
+ >
+ {label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+function PageBody({
+ page,
+ onOpen,
+ onCreate,
+ onEdit,
+ writable,
+}: {
+ page: MemoryPage;
+ onOpen: (path: string) => void;
+ onCreate: (title: string) => void;
+ onEdit: () => void;
+ writable: boolean;
+}) {
+ const t = useT();
+ const markdown = useMemo(() => prepareBody(page.body_md, page.title, page.outgoing), [page]);
+
+ if (page.kind === "memory" || page.kind === "profile") {
+ if (page.entries.length === 0) {
+ return (
+ <EmptyState
+ icon={<KindIcon kind={page.kind} />}
+ title={t(page.kind === "memory" ? "memory_view.notebook_empty_memory" : "memory_view.notebook_empty_profile")}
+ description={fill(t("memory_view.notebook_empty_body"), { agent: page.agent?.name ?? page.title })}
+ />
+ );
+ }
+ return <EntryList entries={page.entries} outgoing={page} onOpen={onOpen} onCreate={onCreate} />;
+ }
+
+ if (page.empty || !markdown) {
+ return (
+ <EmptyState
+ icon={<KindIcon kind={page.kind} />}
+ title={t("memory_view.page_empty_title")}
+ description={t(page.editable ? "memory_view.page_empty_editable" : "memory_view.page_empty_body")}
+ actions={
+ page.editable && writable ? (
+ <Button size="sm" onClick={onEdit}>
+ <PencilLine aria-hidden />
+ {t("memory_view.write_page")}
+ </Button>
+ ) : undefined
+ }
+ />
+ );
+ }
+
+ return <MarkdownBody markdown={markdown} onOpen={onOpen} onCreate={onCreate} />;
+}
+
+const KNOWN_ORIGINS = new Set(["agent", "tool", "user", "review"]);
+
+function EntryList({
+ entries,
+ outgoing,
+ onOpen,
+ onCreate,
+}: {
+ entries: NotebookEntry[];
+ outgoing: MemoryPage;
+ onOpen: (path: string) => void;
+ onCreate: (title: string) => void;
+}) {
+ const t = useT();
+ const sorted = [...entries].sort((a, b) => b.importance - a.importance);
+ return (
+ <ol className="flex flex-col divide-y divide-border rounded-xl border border-border" data-testid="memory-entries">
+ {sorted.map((entry) => (
+ <li key={entry.id} className="px-5 py-4">
+ <div className="mb-1.5 flex items-center gap-2 text-xs text-foreground-faint">
+ {entry.importance >= 8 && (
+ <span className="rounded bg-accent-soft px-1.5 py-px font-medium text-accent">{t("memory_view.important")}</span>
+ )}
+ <span>{KNOWN_ORIGINS.has(entry.origin) ? t(`memory_view.origin_${entry.origin}`) : entry.origin}</span>
+ </div>
+ <div className="[&_p:first-child]:mt-0 [&_p:last-child]:mb-0 [&_p]:my-2 [&_ul]:my-2">
+ <MarkdownBody markdown={prepareBody(entry.text, "", outgoing.outgoing)} onOpen={onOpen} onCreate={onCreate} />
+ </div>
+ </li>
+ ))}
+ </ol>
+ );
+}
+
+// ----------------------------------------------------------------- the rail
+
+function ConnectionsRail({
+ page,
+ onOpen,
+ inline = false,
+}: {
+ page: MemoryPage;
+ onOpen: (path: string) => void;
+ inline?: boolean;
+}) {
+ const t = useT();
+ const outgoing = dedupe(
+ page.outgoing
+ .filter((link) => link.path)
+ .map((link): PageRef => ({ path: link.path as string, title: link.title, kind: link.kind, group: null, empty: false })),
+ );
+ const broken = page.outgoing.filter((link) => link.broken);
+ const properties = Object.entries(page.properties).filter(
+ ([key, value]) => !HIDDEN_PROPERTIES.has(key) && formatProperty(value) !== "",
+ );
+ const total = page.backlinks.length + outgoing.length + page.mentioned_in.length + page.mentions.length + page.related.length;
+
+ return (
+ <aside
+ className={cn(
+ inline
+ ? "mt-12 flex flex-col border-t border-border pt-8 lg:hidden"
+ : "hidden w-[296px] shrink-0 flex-col overflow-y-auto border-l border-border bg-sidebar/60 lg:flex",
+ )}
+ aria-label={t("memory_view.connections")}
+ data-testid={inline ? "memory-rail-inline" : "memory-rail"}
+ >
+ <div className={cn("flex flex-col gap-6", !inline && "px-4 pb-10 pt-6")}>
+ {total === 0 && (
+ <p className="text-sm leading-relaxed text-muted-foreground">{t("memory_view.no_connections")}</p>
+ )}
+ <RailSection title={t("memory_view.linked_from")} items={page.backlinks} onOpen={onOpen} testId="rail-backlinks" />
+ <RailSection title={t("memory_view.links_to")} items={outgoing} onOpen={onOpen} testId="rail-outgoing" />
+ <RailSection
+ title={t("memory_view.mentioned_in")}
+ hint={t("memory_view.mentioned_in_hint")}
+ items={page.mentioned_in}
+ onOpen={onOpen}
+ testId="rail-mentioned-in"
+ />
+ <RailSection title={t("memory_view.mentions")} items={page.mentions} onOpen={onOpen} testId="rail-mentions" />
+ <RailSection
+ title={t("memory_view.related")}
+ hint={t("memory_view.related_hint")}
+ items={page.related.map((item) => ({
+ ...item,
+ context: item.via ? fill(t("memory_view.related_via"), { title: item.via.title }) : "",
+ }))}
+ onOpen={onOpen}
+ testId="rail-related"
+ />
+ {broken.length > 0 && (
+ <section>
+ <RailHeading title={t("memory_view.unresolved_links")} count={broken.length} />
+ <ul className="mt-2 flex flex-wrap gap-1.5">
+ {broken.map((link) => (
+ <li key={link.raw} className="rounded-md border border-dashed border-border px-2 py-0.5 text-xs text-muted-foreground">
+ {link.title}
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+ {properties.length > 0 && (
+ <section>
+ <RailHeading title={t("memory_view.properties")} />
+ <dl className="mt-2 flex flex-col gap-2 text-sm">
+ {properties.map(([key, value]) => (
+ <div key={key} className="grid grid-cols-[96px_1fr] gap-2">
+ <dt className="truncate text-muted-foreground" title={key}>
+ {key}
+ </dt>
+ <dd className="min-w-0 break-words text-foreground">{formatProperty(value)}</dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ )}
+ <section>
+ <RailHeading title={t("memory_view.file")} />
+ <p className="mt-2 break-all font-mono text-xs leading-5 text-muted-foreground">{page.path}</p>
+ <p className="mt-1 text-xs text-foreground-faint">{t(GROUP_LABEL_KEY[page.group])}</p>
+ </section>
+ </div>
+ </aside>
+ );
+}
+
+function dedupe<T extends { path: string }>(items: T[]): T[] {
+ const seen = new Set<string>();
+ return items.filter((item) => (seen.has(item.path) ? false : (seen.add(item.path), true)));
+}
+
+function RailHeading({ title, count }: { title: string; count?: number }) {
+ return (
+ <h3 className="flex items-center justify-between text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ <span>{title}</span>
+ {count !== undefined && <span className="tabular-nums text-foreground-faint">{count}</span>}
+ </h3>
+ );
+}
+
+const RAIL_LIMIT = 8;
+
+function RailSection({
+ title,
+ hint,
+ items,
+ onOpen,
+ testId,
+}: {
+ title: string;
+ hint?: string;
+ items: (PageRef & Partial<Pick<LinkRef, "context">>)[];
+ onOpen: (path: string) => void;
+ testId: string;
+}) {
+ const t = useT();
+ const [expanded, setExpanded] = useState(false);
+ if (items.length === 0) return null;
+ const shown = expanded ? items : items.slice(0, RAIL_LIMIT);
+ return (
+ <section data-testid={testId}>
+ <RailHeading title={title} count={items.length} />
+ {hint && <p className="mt-1 text-xs leading-snug text-foreground-faint">{hint}</p>}
+ <ul className="mt-2 flex flex-col gap-0.5">
+ {shown.map((item) => (
+ <li key={item.path}>
+ <button
+ type="button"
+ onClick={() => onOpen(item.path)}
+ className="group flex w-full flex-col gap-0.5 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-secondary"
+ >
+ <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
+ <KindIcon kind={item.kind} className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className={cn("truncate", item.empty && "text-muted-foreground")}>{item.title}</span>
+ </span>
+ {item.context && (
+ <span className="line-clamp-2 pl-[22px] text-xs leading-snug text-muted-foreground">{item.context}</span>
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ {items.length > RAIL_LIMIT && (
+ <button
+ type="button"
+ onClick={() => setExpanded((value) => !value)}
+ className="mt-1 px-2 text-xs text-muted-foreground hover:text-foreground"
+ >
+ {expanded ? t("memory_view.show_less") : fill(t("memory_view.show_all"), { count: items.length })}
+ </button>
+ )}
+ </section>
+ );
+}
+
+function ReaderSkeleton() {
+ return (
+ <div className="mx-auto w-full max-w-[760px] space-y-4 px-12 pt-12" role="status" aria-busy="true">
+ <div className="h-3 w-32 animate-pulse rounded bg-secondary" />
+ <div className="h-8 w-80 animate-pulse rounded-md bg-secondary" />
+ <div className="h-3 w-56 animate-pulse rounded bg-secondary" />
+ <div className="space-y-3 pt-6">
+ <div className="h-3 w-full animate-pulse rounded bg-secondary" />
+ <div className="h-3 w-5/6 animate-pulse rounded bg-secondary" />
+ <div className="h-3 w-4/6 animate-pulse rounded bg-secondary" />
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx b/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
deleted file mode 100644
index 6b3fafc2f3..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/GraphDimensionToggle.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * The flat/space switch that sits on top of both memory maps.
- *
- * Two segments rather than a checkbox, because "off" is not what the other
- * state is: 2D and 3D are two ways of reading the same network, and a switch
- * labelled only "3D" makes the flat map look like the absence of a feature.
- * Both labels are always visible, so the current state is readable without
- * hovering anything.
- *
- * When the machine cannot give a WebGL context the 3D segment stays visible
- * but disabled and says why. Hiding it would leave the user guessing whether
- * the feature exists; letting them press it would paint a black rectangle.
- */
-import { Box, Square } from "lucide-react";
-
-import { useT } from "@/i18n";
-import { cn } from "@/lib/utils";
-import { useGraphDimension, type GraphDimension } from "@/lib/graphDimension";
-
-export interface GraphDimensionToggleProps {
- /** Placement + surface styling; the host owns where this floats. */
- className?: string;
-}
-
-export function GraphDimensionToggle({
- className,
-}: GraphDimensionToggleProps): JSX.Element {
- const t = useT();
- const { dimension, setDimension, webglSupported, webglState } = useGraphDimension();
-
- const segment = (value: GraphDimension) => {
- const active = dimension === value;
- const blocked = value === "3d" && !webglSupported;
- // Two different "no", two different sentences: a machine that never had a
- // graphics context is not the same as a session that lost one, and the
- // second one a reload can undo.
- const title = blocked
- ? t(
- webglState === "lost"
- ? "wiki_graph.dimension_lost"
- : "wiki_graph.dimension_unavailable",
- )
- : t(value === "3d" ? "wiki_graph.dimension_3d_title" : "wiki_graph.dimension_2d_title");
- const Icon = value === "3d" ? Box : Square;
- return (
- <button
- type="button"
- role="radio"
- aria-checked={active}
- aria-label={title}
- title={title}
- disabled={blocked}
- data-testid={`graph-dimension-${value}`}
- data-active={active ? "true" : "false"}
- onClick={() => setDimension(value)}
- className={cn(
- "inline-flex items-center gap-1 rounded px-2 py-1 text-xs font-medium tabular-nums transition-colors",
- active
- ? "bg-primary/15 text-foreground"
- : "text-muted-foreground hover:text-foreground",
- blocked && "cursor-not-allowed opacity-40 hover:text-muted-foreground",
- )}
- >
- <Icon className="h-3 w-3" aria-hidden />
- {t(value === "3d" ? "wiki_graph.dimension_3d" : "wiki_graph.dimension_2d")}
- </button>
- );
- };
-
- return (
- <div
- role="radiogroup"
- aria-label={t("wiki_graph.dimension_label")}
- data-testid="graph-dimension-toggle"
- data-dimension={dimension}
- data-webgl={webglSupported ? "true" : "false"}
- data-webgl-state={webglState}
- className={cn(
- "inline-flex items-center gap-0.5 rounded-md border border-border bg-card/80 p-0.5 backdrop-blur",
- className,
- )}
- >
- {segment("2d")}
- {segment("3d")}
- </div>
- );
-}
-
-export default GraphDimensionToggle;
diff --git a/jarvis/ui/web/frontend/src/components/wiki/KindGlyph.tsx b/jarvis/ui/web/frontend/src/components/wiki/KindGlyph.tsx
deleted file mode 100644
index 84051ef14b..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/KindGlyph.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { cn } from "@/lib/utils";
-import { GROUP_SHAPE, type KindShape, type WikiGroupId } from "@/lib/wikiModel";
-
-/**
- * The kind of a wiki page as a small shape — the same shape the memory map
- * draws the page as, so a glance at a list row tells you what you will look
- * for on the map. Drawn in `currentColor`; the caller picks the ink.
- */
-export function KindGlyph({
- group,
- className,
- title,
-}: {
- group: WikiGroupId;
- className?: string;
- title?: string;
-}) {
- const shape = GROUP_SHAPE[group];
- return (
- <svg
- viewBox="0 0 16 16"
- aria-hidden={title ? undefined : true}
- role={title ? "img" : undefined}
- className={cn("h-3 w-3 shrink-0", className)}
- data-kind-shape={shape}
- >
- {title && <title>{title}</title>}
- <ShapePath shape={shape} />
- </svg>
- );
-}
-
-function ShapePath({ shape }: { shape: KindShape }) {
- switch (shape) {
- case "square":
- return <rect x="2.5" y="2.5" width="11" height="11" rx="3" fill="currentColor" />;
- case "triangle":
- return <path d="M8 2 L14 13 H2 Z" fill="currentColor" strokeLinejoin="round" />;
- case "hexagon":
- return <path d="M8 1.8 L13.4 4.9 V11.1 L8 14.2 L2.6 11.1 V4.9 Z" fill="currentColor" />;
- case "diamond":
- return <path d="M8 1.5 L14.5 8 L8 14.5 L1.5 8 Z" fill="currentColor" />;
- case "ring":
- return <circle cx="8" cy="8" r="5" fill="none" stroke="currentColor" strokeWidth="2.2" />;
- case "dot":
- return <circle cx="8" cy="8" r="3.5" fill="currentColor" />;
- case "circle":
- default:
- return <circle cx="8" cy="8" r="6" fill="currentColor" />;
- }
-}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx
deleted file mode 100644
index 35b1f87bff..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import { useCallback } from "react";
-import { ExternalLink } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { buildObsidianUrl } from "@/lib/obsidian";
-import { useEventStore } from "@/store/events";
-import { useT } from "@/i18n";
-
-/**
- * Per-page "Open in Obsidian" button.
- *
- * Hands editing off to the real Obsidian desktop app via the
- * `obsidian://open?path=…` URL scheme. There is no reliable way
- * to detect from the browser whether the URL handler is registered, so
- * we fire a fallback toast 800 ms after the click to inform the user
- * what was attempted — if Obsidian launched, they'll see the file open;
- * if not, they at least know why nothing happened.
- *
- * Pass an empty `vaultRelPath` to open the vault root (used by the
- * "Open vault in Obsidian" button in the wiki tab header).
- */
-export interface ObsidianButtonProps {
- /** Absolute configured Jarvis vault root. */
- vaultRoot: string;
- /** Vault-relative POSIX path, e.g. `"entities/harald.md"`. Empty opens the root. */
- vaultRelPath: string;
- /** Use the compact "sm" button size — useful inside dense panels. */
- size?: "default" | "sm";
- /** Optional label override (defaults vary by `vaultRelPath`). */
- label?: string;
-}
-
-/** Delay in ms after click before the fallback toast fires. */
-export const FALLBACK_TOAST_DELAY_MS = 800;
-
-export function ObsidianButton({
- vaultRoot,
- vaultRelPath,
- size = "sm",
- label,
-}: ObsidianButtonProps): JSX.Element {
- const t = useT();
- const pushToast = useEventStore((s) => s.pushToast);
-
- const handleClick = useCallback(() => {
- const url = buildObsidianUrl(vaultRoot, vaultRelPath);
- // Trigger the URL handler. We use `window.location.assign` rather
- // than `window.open` because the latter is blocked by popup blockers
- // and pywebview's window-open hook; `assign` invokes the protocol
- // handler without an intermediate page.
- try {
- window.location.assign(url);
- } catch {
- // Some embeds (jsdom, custom shells) reject the protocol; show
- // the toast immediately in that case.
- pushToast(
- "warning",
- `${t("obsidian_button.trigger_failed")}: ${vaultRelPath || "Vault"}`,
- );
- return;
- }
-
- // 800 ms later: toast the user. We can't detect failure of an
- // `obsidian://` URL from the browser sandbox, so we always show
- // the toast — it doubles as confirmation when Obsidian *did*
- // launch and as a helpful hint when it didn't.
- window.setTimeout(() => {
- if (vaultRelPath) {
- pushToast(
- "info",
- `${t("obsidian_button.handed_over")}: ${vaultRelPath} ${t("obsidian_button.not_installed_hint")}`,
- );
- } else {
- pushToast(
- "info",
- `${t("obsidian_button.vault_handed_over")} ${t("obsidian_button.not_installed_hint")}`,
- );
- }
- }, FALLBACK_TOAST_DELAY_MS);
- }, [pushToast, t, vaultRelPath, vaultRoot]);
-
- const buttonLabel =
- label ?? (vaultRelPath ? t("obsidian_button.open_in_obsidian") : t("obsidian_button.open_vault_in_obsidian"));
-
- return (
- <Button
- type="button"
- variant="outline"
- size={size}
- onClick={handleClick}
- className="gap-1.5"
- title={vaultRelPath || vaultRoot}
- >
- <ExternalLink className="h-3.5 w-3.5" aria-hidden />
- <span>{buttonLabel}</span>
- </Button>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx
deleted file mode 100644
index ddbc007dbd..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * Wiki page header: where the page lives, its title, the one line of facts
- * that matter (kind, last change, length), the frontmatter worth showing, and
- * the hand-off to Obsidian.
- */
-import { lazy, Suspense } from "react";
-
-import { useT } from "@/i18n";
-import { useRunLocale } from "@/components/runs/format";
-import type { WikiKind } from "@/lib/wikiApi";
-import { GROUP_LABEL_KEY, groupOfKind, relativeAge } from "@/lib/wikiModel";
-import { cn } from "@/lib/utils";
-import { KindGlyph } from "@/components/wiki/KindGlyph";
-
-// Lazy so the page body paints before the Obsidian hand-off code arrives.
-const ObsidianButton = lazy(() =>
- import("./ObsidianButton").then((mod) => ({
- default: mod.ObsidianButton,
- })),
-);
-
-interface PageHeaderProps {
- slug: string;
- kind: WikiKind | string;
- title: string;
- frontmatter: Record<string, string | string[]>;
- vaultRoot: string;
- vaultRelPath: string;
- /** Seconds since the epoch of the file's last change, when known. */
- mtime?: number;
- words?: number;
-}
-
-/** Frontmatter field -> i18n key of its pill label. */
-const FRIENDLY_LABELS: Record<string, string> = {
- type: "page_header.field_type",
- entity_kind: "page_header.field_kind",
- status: "page_header.field_status",
- created: "page_header.field_created",
- updated: "page_header.field_updated",
- started: "page_header.field_started",
- last_activity: "page_header.field_last_activity",
-};
-
-const MAX_PILLS = 6;
-
-export function PageHeader({
- slug,
- kind,
- title,
- frontmatter,
- vaultRoot,
- vaultRelPath,
- mtime,
- words,
-}: PageHeaderProps) {
- const t = useT();
- const language = useRunLocale();
- const pills = buildPills(frontmatter);
- const breadcrumb = breadcrumbFromPath(vaultRelPath);
- const group = groupOfKind(kind);
- const changed = mtime ? relativeAge(mtime, language) : "";
-
- return (
- <header className="flex flex-col" data-testid="wiki-page-header" data-slug={slug}>
- <div className="flex items-center justify-between gap-4">
- <nav
- className="flex min-w-0 items-center gap-1.5 text-sm text-foreground-faint"
- data-testid="wiki-page-crumb"
- aria-label={t("wiki_ui.crumb_label")}
- >
- {breadcrumb.map((part, idx) => (
- <span key={idx} className="flex min-w-0 items-center gap-1.5">
- {idx > 0 && <span aria-hidden>/</span>}
- <span className={cn("truncate", idx === breadcrumb.length - 1 && "text-muted-foreground")}>
- {part}
- </span>
- </span>
- ))}
- </nav>
- <Suspense fallback={<ObsidianButtonPlaceholder />}>
- <ObsidianButton vaultRoot={vaultRoot} vaultRelPath={vaultRelPath} size="sm" />
- </Suspense>
- </div>
-
- <h1
- className="mt-5 text-display font-semibold text-foreground-strong"
- data-testid="wiki-page-title"
- >
- {title}
- </h1>
-
- <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground">
- <span className="inline-flex items-center gap-1.5 text-foreground-secondary">
- <KindGlyph group={group} className="h-2.5 w-2.5" />
- {t(GROUP_LABEL_KEY[group])}
- </span>
- {changed && (
- <>
- <span aria-hidden className="text-foreground-faint">·</span>
- <span>{t("wiki_ui.page_changed").replace("{0}", changed)}</span>
- </>
- )}
- {words !== undefined && words > 0 && (
- <>
- <span aria-hidden className="text-foreground-faint">·</span>
- <span>
- {t("wiki_ui.page_words").replace("{0}", new Intl.NumberFormat(language).format(words))}
- </span>
- </>
- )}
- </div>
-
- {/* The page kind used to be painted in one of four hardcoded hues. Hue
- belongs to status and selection only, so the frontmatter facts are
- neutral tags and the kind is told by its shape above. */}
- {pills.length > 0 && (
- <div className="mt-4 flex flex-wrap gap-1.5 text-xs" data-testid="wiki-page-pills">
- {pills.map((p) => (
- <span
- key={p.key}
- className="inline-flex h-6 items-center gap-1 rounded-sm border border-border px-2 text-muted-foreground"
- data-pill-key={p.key}
- >
- <span>{t(p.label)}</span>
- <span className="text-foreground">{p.value}</span>
- </span>
- ))}
- </div>
- )}
- </header>
- );
-}
-
-interface Pill {
- key: string;
- label: string;
- value: string;
-}
-
-function buildPills(fm: Record<string, string | string[]>): Pill[] {
- const out: Pill[] = [];
- for (const [key, raw] of Object.entries(fm)) {
- if (key === "slug" || key === "aliases") continue;
- if (!(key in FRIENDLY_LABELS)) continue;
- const value = Array.isArray(raw) ? raw.join(", ") : raw;
- if (!value || value.trim() === "") continue;
- out.push({ key, label: FRIENDLY_LABELS[key], value });
- if (out.length >= MAX_PILLS) break;
- }
- return out;
-}
-
-function breadcrumbFromPath(relPath: string): string[] {
- // "entities/harald.md" → ["entities", "harald.md"]
- const parts = relPath.split(/[\\/]/).filter(Boolean);
- return parts.length > 0 ? parts : [relPath];
-}
-
-function ObsidianButtonPlaceholder() {
- return <span className="h-8 w-36 shrink-0" data-testid="obsidian-button-placeholder" aria-hidden />;
-}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
deleted file mode 100644
index cb2a0af90f..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
+++ /dev/null
@@ -1,362 +0,0 @@
-/**
- * Render a single wiki page as a document: header (where it lives, title,
- * facts, Obsidian hand-off) over the markdown body, with clickable
- * `[[wikilinks]]`.
- *
- * Wikilink handling: the body markdown is pre-processed before being passed
- * to `react-markdown`. Each `[[X]]`, `[[entities/X]]`, or `[[X|label]]` is
- * rewritten to a regular markdown link with href `#wiki:<slug>`. The
- * `components.a` override of `react-markdown` then intercepts these,
- * rendering a custom `<a>` element that calls `onWikilinkClick(slug)`
- * instead of navigating.
- *
- * Broken wikilinks (target slug not in the cached tree) get the `.broken`
- * class and trigger a toast when clicked.
- *
- * The curator stamps facts with `(as of 2026-08-12)`; those stamps are set as
- * quiet dates beside the fact instead of a parenthesis in the sentence.
- */
-import { Children, cloneElement, isValidElement, useMemo, type ReactNode } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import ReactMarkdown, { type Components } from "react-markdown";
-import remarkGfm from "remark-gfm";
-
-import {
- fetchWikiPage,
- fetchWikiTree,
- type WikiKind,
- type WikiTreeResponse,
-} from "@/lib/wikiApi";
-import { cleanTitle } from "@/lib/wikiModel";
-import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
-import { useRunLocale } from "@/components/runs/format";
-
-import { PageHeader } from "./PageHeader";
-
-interface PageRendererProps {
- slug: string;
- onWikilinkClick: (targetSlug: string) => void;
-}
-
-const WIKILINK_PREFIX = "#wiki:";
-
-// Regex covers `[[slug]]`, `[[entities/slug]]`, `[[slug|label]]`,
-// `[[entities/slug|label]]`. Slugs are kebab-case, optionally folder-prefixed.
-const WIKILINK_RE = /\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]/g;
-
-// `(as of 2026-08-12)` — the curator's freshness stamp on a fact.
-const AS_OF_RE = /\s*\(as of (\d{4}-\d{2}-\d{2})\)/g;
-
-export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {
- const t = useT();
- const language = useRunLocale();
- const qc = useQueryClient();
- const pageQuery = useQuery({
- queryKey: ["wiki", "page", slug],
- queryFn: () => fetchWikiPage(slug),
- staleTime: 5_000,
- });
-
- // Cached tree response — used to determine whether a wikilink resolves
- // to an existing page or is broken.
- const treeQuery = useQuery({
- queryKey: ["wiki", "tree"],
- queryFn: fetchWikiTree,
- staleTime: 5_000,
- });
-
- const knownSlugs = useMemo(
- () => buildKnownSlugSet(treeQuery.data),
- [treeQuery.data],
- );
-
- const page = pageQuery.data;
- const title = cleanTitle(page?.title, slug);
-
- const preprocessedBody = useMemo(() => {
- const raw = pageQuery.data?.body_md ?? "";
- return preprocessWikilinks(stripLeadingTitle(raw, title));
- }, [pageQuery.data?.body_md, title]);
-
- const dateFormat = useMemo(() => {
- try {
- return new Intl.DateTimeFormat(language, { dateStyle: "medium" });
- } catch {
- return null;
- }
- }, [language]);
-
- const components = useMemo<Components>(() => {
- const decorate = (children: ReactNode) => decorateAsOf(children, dateFormat, t("wiki_ui.as_of"));
- return {
- a: ({ href, children, node: _node, ...rest }) => {
- if (typeof href === "string" && href.startsWith(WIKILINK_PREFIX)) {
- const target = href.slice(WIKILINK_PREFIX.length);
- const isBroken = knownSlugs.size > 0 && !knownSlugs.has(target);
- return (
- <a
- {...rest}
- href={href}
- data-target-slug={target}
- title={isBroken ? t("wiki_ui.link_missing") : undefined}
- className={cn(
- "wikilink rounded-sm underline underline-offset-4 transition-colors",
- isBroken
- ? "broken text-muted-foreground decoration-destructive/60 decoration-dashed hover:text-foreground"
- : "text-accent decoration-accent/30 hover:decoration-accent",
- )}
- onClick={(e) => {
- e.preventDefault();
- if (knownSlugs.size > 0 && !knownSlugs.has(target)) {
- // Force a re-fetch of the tree in case the cache is stale,
- // then surface the missing page so the caller can toast.
- qc.invalidateQueries({ queryKey: ["wiki", "tree"] });
- }
- onWikilinkClick(target);
- }}
- >
- {children}
- </a>
- );
- }
- return (
- <a
- {...rest}
- href={href}
- target="_blank"
- rel="noopener noreferrer"
- className="text-accent underline decoration-accent/30 underline-offset-4 transition-colors hover:decoration-accent"
- >
- {children}
- </a>
- );
- },
- h1: ({ children }) => (
- <h2 className="mb-3 mt-10 text-lg font-semibold text-foreground-strong first:mt-0">{children}</h2>
- ),
- h2: ({ children }) => (
- <h2 className="mb-3 mt-10 flex items-center gap-3 text-lg font-semibold text-foreground-strong first:mt-0">
- {children}
- <span aria-hidden className="h-px flex-1 bg-border" />
- </h2>
- ),
- h3: ({ children }) => (
- <h3 className="mb-2 mt-7 text-base font-semibold text-foreground-strong">{children}</h3>
- ),
- h4: ({ children }) => (
- <h4 className="mb-2 mt-6 text-base font-medium text-foreground">{children}</h4>
- ),
- p: ({ children }) => <p className="my-4 text-foreground">{decorate(children)}</p>,
- ul: ({ children }) => (
- <ul className="my-4 space-y-2 pl-5 text-foreground marker:text-foreground-faint [list-style-type:'–__']">
- {children}
- </ul>
- ),
- ol: ({ children }) => (
- <ol className="my-4 list-decimal space-y-2 pl-6 text-foreground marker:text-sm marker:tabular-nums marker:text-foreground-faint">
- {children}
- </ol>
- ),
- li: ({ children }) => <li className="pl-1">{decorate(children)}</li>,
- blockquote: ({ children }) => (
- <blockquote className="my-5 border-l-2 border-border-strong pl-4 text-foreground-secondary">
- {children}
- </blockquote>
- ),
- hr: () => <hr className="my-8 border-border" />,
- strong: ({ children }) => <strong className="font-semibold text-foreground-strong">{children}</strong>,
- table: ({ children }) => (
- <div className="my-5 overflow-x-auto rounded-md border border-border">
- <table className="w-full border-collapse text-sm">{children}</table>
- </div>
- ),
- th: ({ children }) => (
- <th className="border-b border-border bg-secondary px-3 py-2 text-left font-medium text-foreground">
- {children}
- </th>
- ),
- td: ({ children }) => (
- <td className="border-b border-border px-3 py-2 align-top text-foreground-secondary">{children}</td>
- ),
- pre: ({ children }) => (
- <pre className="my-5 overflow-x-auto rounded-md border border-border bg-secondary p-4 font-mono text-sm leading-6 text-foreground [&>code]:bg-transparent [&>code]:p-0">
- {children}
- </pre>
- ),
- code: ({ children, node: _node, ...rest }) => (
- <code
- {...rest}
- className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-sm text-foreground"
- >
- {children}
- </code>
- ),
- };
- }, [dateFormat, knownSlugs, onWikilinkClick, qc, t]);
-
- if (pageQuery.isLoading) {
- return <PageSkeleton />;
- }
-
- if (pageQuery.isError) {
- return (
- <div className="mx-auto w-full max-w-reading px-10 py-10" data-testid="wiki-page-error">
- <p role="alert" className="text-base text-destructive">
- {t("page_renderer.load_error")}
- </p>
- </div>
- );
- }
-
- if (!page || !page.ok) {
- return (
- <div className="mx-auto w-full max-w-reading px-10 py-10" data-testid="wiki-page-error">
- <p role="alert" className="text-base text-destructive">
- {page?.error ?? t("page_renderer.not_found")}
- </p>
- </div>
- );
- }
-
- const kind = (page.kind ?? "entity") as WikiKind;
- const vaultRelPath = page.path ?? `${kind}/${slug}.md`;
- const frontmatter = page.frontmatter ?? {};
-
- return (
- <article
- className="profile-rise mx-auto flex w-full max-w-reading flex-col px-10 pb-24 pt-10"
- data-testid="wiki-page-renderer"
- >
- <PageHeader
- slug={slug}
- kind={kind}
- title={title}
- frontmatter={frontmatter}
- vaultRoot={treeQuery.data?.vault_root ?? ""}
- vaultRelPath={vaultRelPath}
- mtime={page.stats?.mtime}
- words={page.stats?.words}
- />
-
- {/* A wiki page is a document, so it is set at the reading step in full
- ink and bounded to the reading measure, in both themes. */}
- <div
- className="mt-8 border-t border-border pt-8 text-reading text-foreground"
- data-testid="wiki-page-body"
- >
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
- {preprocessedBody}
- </ReactMarkdown>
- </div>
- </article>
- );
-}
-
-/**
- * Convert `[[slug]]`, `[[entities/slug]]`, `[[slug|label]]` markers into
- * regular markdown links pointing at `#wiki:<slug>`. The slug component is
- * the last path segment (so `entities/harald` → `harald`).
- */
-export function preprocessWikilinks(body: string): string {
- return body.replace(WIKILINK_RE, (_match, target: string, label?: string) => {
- const slug = lastSegment(target.trim());
- const text = label ? label.trim() : slug;
- // Escape backslashes first, then `]`, so a label cannot break out of the
- // surrounding markdown link (a trailing `\` would otherwise escape the `]`).
- const safeText = text.replace(/\\/g, "\\\\").replace(/]/g, "\\]");
- return `[${safeText}](${WIKILINK_PREFIX}${slug})`;
- });
-}
-
-/**
- * Pages open with `# <Title>`, which the header already shows. Drop that one
- * heading — and only when it repeats the title — so the title is not printed
- * twice, one above the other.
- */
-export function stripLeadingTitle(body: string, title: string): string {
- const match = /^\s*#\s+(.+?)\s*#*\s*(?:\r?\n|$)/.exec(body);
- if (!match) return body;
- const heading = cleanTitle(match[1]).toLowerCase();
- return heading === cleanTitle(title).toLowerCase() ? body.slice(match[0].length) : body;
-}
-
-/** Replace `(as of YYYY-MM-DD)` in plain-text children with a quiet date. */
-function decorateAsOf(
- children: ReactNode,
- dateFormat: Intl.DateTimeFormat | null,
- label: string,
-): ReactNode {
- return Children.map(children, (child, index) => {
- if (typeof child === "string") {
- if (!AS_OF_RE.test(child)) return child;
- AS_OF_RE.lastIndex = 0;
- const parts: ReactNode[] = [];
- let last = 0;
- for (const match of child.matchAll(AS_OF_RE)) {
- const at = match.index ?? 0;
- if (at > last) parts.push(child.slice(last, at));
- const iso = match[1];
- const date = new Date(`${iso}T12:00:00`);
- const text =
- dateFormat && !Number.isNaN(date.getTime()) ? dateFormat.format(date) : iso;
- parts.push(
- <time
- key={`${index}-${at}`}
- dateTime={iso}
- title={`${label} ${iso}`}
- className="ml-2 inline-flex whitespace-nowrap align-baseline text-sm text-foreground-faint"
- >
- {text}
- </time>,
- );
- last = at + match[0].length;
- }
- if (last < child.length) parts.push(child.slice(last));
- return parts;
- }
- // A paragraph inside a loose list item: decorate one level down too.
- if (isValidElement<{ children?: ReactNode }>(child) && child.type === "p") {
- return cloneElement(child, undefined, decorateAsOf(child.props.children, dateFormat, label));
- }
- return child;
- });
-}
-
-function lastSegment(target: string): string {
- const idx = Math.max(target.lastIndexOf("/"), target.lastIndexOf("\\"));
- return idx >= 0 ? target.slice(idx + 1) : target;
-}
-
-function buildKnownSlugSet(tree: WikiTreeResponse | undefined): Set<string> {
- const out = new Set<string>();
- if (!tree?.folders) return out;
- for (const folder of tree.folders) {
- for (const file of folder.files) {
- out.add(file.slug);
- }
- }
- return out;
-}
-
-function PageSkeleton() {
- return (
- <div
- className="mx-auto w-full max-w-reading space-y-stack px-10 pt-10"
- data-testid="wiki-page-skeleton"
- role="status"
- aria-busy="true"
- >
- <div className="h-3 w-40 animate-pulse rounded-sm bg-foreground/10" />
- <div className="mt-5 h-8 w-72 animate-pulse rounded-md bg-foreground/10" />
- <div className="h-3 w-56 animate-pulse rounded-sm bg-foreground/10" />
- <div className="space-y-stack border-t border-border pt-8">
- <div className="h-3 w-full animate-pulse rounded-sm bg-foreground/10" />
- <div className="h-3 w-5/6 animate-pulse rounded-sm bg-foreground/10" />
- <div className="h-3 w-4/6 animate-pulse rounded-sm bg-foreground/10" />
- </div>
- </div>
- );
-}
-
-export { WIKILINK_PREFIX };
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.contextLoss.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.contextLoss.test.tsx
deleted file mode 100644
index 3b30cf2ea7..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.contextLoss.test.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-/**
- * What the maps do once a graphics context is gone for good.
- *
- * A lost context is not one card's problem: the browser hands them out per
- * page, so a scene that could not get one back is telling every other scene
- * what is about to happen to it. So the flag is shared — one dead surface and
- * every map on screen goes flat, with the switch saying WHY in the user's own
- * language, instead of each of them painting the browser's broken-canvas
- * placeholder in turn.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { PropsWithChildren } from "react";
-
-import { WikiGraph } from "@/components/wiki/WikiGraph";
-import {
- GRAPH_DIMENSION_KEY,
- reportWebglLost,
- resetWebglProbe,
- setGraphDimension,
-} from "@/lib/graphDimension";
-
-vi.mock("react-force-graph-2d", async () => {
- const { forwardRef } = await import("react");
- return {
- default: forwardRef(function ForceGraphMock(_props: Record<string, unknown>, _ref) {
- return <div data-testid="wiki-graph-2d-stub" />;
- }),
- };
-});
-
-vi.mock("@/components/wiki/WikiGraph3D", () => ({
- WikiGraph3D: () => <div data-testid="wiki-graph-3d-stub" />,
-}));
-
-const PAYLOAD = {
- ok: true,
- nodes: [
- { id: "user", kind: "entity", title: "User" },
- { id: "log", kind: "meta", title: "Log" },
- ],
- edges: [{ source: "user", target: "log", context: "wrote" }],
- broken: [],
-};
-
-/** Make the WebGL probe answer yes, the way a real GPU-backed window does. */
-function pretendWebglWorks(): void {
- vi.stubGlobal("WebGLRenderingContext", class {});
- vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
- getExtension: () => null,
- } as unknown as RenderingContext);
- resetWebglProbe();
-}
-
-function Wrapper({ children, client }: PropsWithChildren<{ client: QueryClient }>) {
- return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
-}
-
-function renderGraph() {
- vi.stubGlobal(
- "fetch",
- vi.fn(
- async () =>
- new Response(JSON.stringify(PAYLOAD), {
- status: 200,
- headers: { "content-type": "application/json" },
- }),
- ),
- );
- return render(
- <Wrapper
- client={new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })}
- >
- <WikiGraph onNodeClick={() => {}} />
- </Wrapper>,
- );
-}
-
-beforeEach(() => {
- reportWebglLost(false);
- window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
- setGraphDimension("3d");
- resetWebglProbe();
-});
-
-afterEach(() => {
- cleanup();
- reportWebglLost(false);
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- resetWebglProbe();
- window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
-});
-
-describe("a graphics context lost for good", () => {
- it("takes the map flat instead of leaving a dead canvas on screen", async () => {
- pretendWebglWorks();
- renderGraph();
- // A generous wait: the lazy 3D module resolves on a microtask, and a busy
- // machine running the whole suite at once can be a beat behind.
- await screen.findByTestId("wiki-graph-3d-stub", {}, { timeout: 5_000 });
-
- act(() => reportWebglLost(true));
-
- await waitFor(
- () => {
- expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
- },
- { timeout: 5_000 },
- );
- expect(screen.getByTestId("wiki-graph-2d-stub")).toBeDefined();
- });
-
- it("says a context was lost, not that the machine cannot do 3D", async () => {
- pretendWebglWorks();
- renderGraph();
- // A generous wait: the lazy 3D module resolves on a microtask, and a busy
- // machine running the whole suite at once can be a beat behind.
- await screen.findByTestId("wiki-graph-3d-stub", {}, { timeout: 5_000 });
-
- act(() => reportWebglLost(true));
-
- const segment = (await screen.findByTestId(
- "graph-dimension-3d",
- )) as HTMLButtonElement;
- await waitFor(() => expect(segment.disabled).toBe(true), { timeout: 5_000 });
- expect(segment.getAttribute("title")).toContain("lost its graphics context");
- expect(segment.getAttribute("title")).not.toContain("cannot render 3D");
- expect(
- screen.getByTestId("graph-dimension-toggle").getAttribute("data-webgl-state"),
- ).toBe("lost");
- });
-
- it("keeps the stored preference, so a reload offers the spatial map again", async () => {
- pretendWebglWorks();
- renderGraph();
- // A generous wait: the lazy 3D module resolves on a microtask, and a busy
- // machine running the whole suite at once can be a beat behind.
- await screen.findByTestId("wiki-graph-3d-stub", {}, { timeout: 5_000 });
-
- act(() => reportWebglLost(true));
- await waitFor(
- () => {
- expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
- },
- { timeout: 5_000 },
- );
-
- expect(window.localStorage.getItem(GRAPH_DIMENSION_KEY)).toBe("3d");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.dimension.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.dimension.test.tsx
deleted file mode 100644
index bff08c04cd..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.dimension.test.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * The 2D/3D switch on the Memory Map.
- *
- * Three things have to hold, and the third is the one that keeps the feature
- * honest on machines that are not the developer's:
- *
- * 1. Flat is what you get by default — no WebGL chunk downloaded to read a
- * map that never needed one.
- * 2. Choosing 3D actually swaps the renderer, and the choice is remembered.
- * 3. On a machine with no WebGL context to give, the 3D segment is visibly
- * disabled and the map stays flat — even when a stored preference (say,
- * from a profile synced off a machine that could) asks for 3D.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { PropsWithChildren } from "react";
-
-import { WikiGraph } from "@/components/wiki/WikiGraph";
-import {
- GRAPH_DIMENSION_KEY,
- resetWebglProbe,
- setGraphDimension,
-} from "@/lib/graphDimension";
-
-const { forceGraphProps } = vi.hoisted(() => ({
- forceGraphProps: [] as Array<Record<string, unknown>>,
-}));
-
-vi.mock("react-force-graph-2d", async () => {
- const { forwardRef } = await import("react");
- return {
- default: forwardRef(function ForceGraphMock(
- props: Record<string, unknown>,
- _ref,
- ) {
- forceGraphProps.push(props);
- return <div data-testid="wiki-graph-2d-stub" />;
- }),
- };
-});
-
-// The real 3D component pulls in three.js and asks for a WebGL context, which
-// jsdom cannot give. What this file tests is which renderer gets mounted, so a
-// stand-in is exactly the right amount of 3D.
-vi.mock("@/components/wiki/WikiGraph3D", () => ({
- WikiGraph3D: (props: { width: number; height: number }) => (
- <div
- data-testid="wiki-graph-3d-stub"
- data-width={props.width}
- data-height={props.height}
- />
- ),
-}));
-
-const PAYLOAD = {
- ok: true,
- nodes: [
- { id: "ruben", kind: "entity", title: "Ruben" },
- { id: "harald", kind: "entity", title: "Harald" },
- ],
- edges: [{ source: "ruben", target: "harald", context: "knows" }],
- broken: [],
-};
-
-/** Make the WebGL probe answer yes, the way a real GPU-backed window does. */
-function pretendWebglWorks(): void {
- vi.stubGlobal("WebGLRenderingContext", class {});
- vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
- getExtension: () => null,
- } as unknown as RenderingContext);
- resetWebglProbe();
-}
-
-function makeClient(): QueryClient {
- return new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 0 } },
- });
-}
-
-function Wrapper({ children, client }: PropsWithChildren<{ client: QueryClient }>) {
- return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
-}
-
-function renderGraph() {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(JSON.stringify(PAYLOAD), {
- status: 200,
- headers: { "content-type": "application/json" },
- }),
- ),
- );
- return render(
- <Wrapper client={makeClient()}>
- <WikiGraph onNodeClick={() => {}} />
- </Wrapper>,
- );
-}
-
-beforeEach(() => {
- forceGraphProps.length = 0;
- window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
- setGraphDimension("2d");
- resetWebglProbe();
-});
-
-afterEach(() => {
- cleanup();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
- resetWebglProbe();
- window.localStorage.removeItem(GRAPH_DIMENSION_KEY);
-});
-
-describe("WikiGraph 2D/3D switch", () => {
- it("draws the flat map by default", async () => {
- pretendWebglWorks();
- renderGraph();
-
- expect(await screen.findByTestId("wiki-graph-2d-stub")).toBeDefined();
- expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
- expect(
- screen.getByTestId("graph-dimension-toggle").getAttribute("data-dimension"),
- ).toBe("2d");
- });
-
- it("swaps to the 3D scene when the switch is flipped, and remembers it", async () => {
- pretendWebglWorks();
- renderGraph();
- await screen.findByTestId("wiki-graph-2d-stub");
-
- fireEvent.click(screen.getByTestId("graph-dimension-3d"));
-
- expect(await screen.findByTestId("wiki-graph-3d-stub")).toBeDefined();
- await waitFor(() => {
- expect(screen.queryByTestId("wiki-graph-2d-stub")).toBeNull();
- });
- expect(window.localStorage.getItem(GRAPH_DIMENSION_KEY)).toBe("3d");
- });
-
- it("hands the measured canvas size to the 3D scene", async () => {
- pretendWebglWorks();
- setGraphDimension("3d");
- renderGraph();
-
- const stub = await screen.findByTestId("wiki-graph-3d-stub");
- expect(Number(stub.getAttribute("data-width"))).toBeGreaterThan(0);
- expect(Number(stub.getAttribute("data-height"))).toBeGreaterThan(0);
- });
-
- it("stays flat and disables the 3D segment without a WebGL context", async () => {
- // No WebGL globals stubbed: this is the headless/locked-down machine.
- setGraphDimension("3d");
- renderGraph();
-
- expect(await screen.findByTestId("wiki-graph-2d-stub")).toBeDefined();
- expect(screen.queryByTestId("wiki-graph-3d-stub")).toBeNull();
- const segment = screen.getByTestId("graph-dimension-3d") as HTMLButtonElement;
- expect(segment.disabled).toBe(true);
- expect(segment.getAttribute("title")).toContain("cannot render 3D");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.render.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.render.test.tsx
deleted file mode 100644
index 33921ba2a6..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.render.test.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-/**
- * Render-loop and camera guards for the Memory-Map.
- *
- * `WikiGraph.test.tsx` mocks `react-force-graph-2d` with a prop recorder and
- * no imperative handle, which is enough for data/click behaviour but blind to
- * everything the component does THROUGH the library instance. These tests
- * install a handle so the expensive paths are observable:
- *
- * 1. d3 forces are configured once per data generation, not per engine tick
- * (the tick handler used to re-initialise every force on every frame).
- * 2. a settled engine does not yank the camera back after the user panned.
- * 3. the component's own fit animation is not mistaken for a user pan.
- * 4. the render loop is parked once nothing needs frames any more.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, render, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { PropsWithChildren } from "react";
-
-import { WikiGraph } from "@/components/wiki/WikiGraph";
-
-const { forceGraphProps, handle } = vi.hoisted(() => {
- const chargeForce = { strength: vi.fn(), distanceMax: vi.fn() };
- const linkForce = { distance: vi.fn(), strength: vi.fn() };
- const centerForce = { strength: vi.fn() };
- return {
- forceGraphProps: [] as Array<Record<string, unknown>>,
- handle: {
- chargeForce,
- linkForce,
- centerForce,
- d3Force: vi.fn((name: string) => {
- if (name === "charge") return chargeForce;
- if (name === "link") return linkForce;
- if (name === "center") return centerForce;
- return undefined;
- }),
- zoomToFit: vi.fn(),
- centerAt: vi.fn(),
- zoom: vi.fn(() => 1),
- getGraphBbox: vi.fn(() => ({ x: [-100, 100], y: [-100, 100] })),
- screen2GraphCoords: vi.fn(() => ({ x: 0, y: 0 })),
- pauseAnimation: vi.fn(),
- resumeAnimation: vi.fn(),
- },
- };
-});
-
-vi.mock("react-force-graph-2d", async () => {
- const { forwardRef, useImperativeHandle } = await import("react");
- return {
- default: forwardRef(function ForceGraphMock(
- props: Record<string, unknown>,
- ref,
- ) {
- forceGraphProps.push(props);
- useImperativeHandle(ref, () => handle, []);
- return null;
- }),
- };
-});
-
-const PAYLOAD = {
- ok: true,
- nodes: [
- { id: "ruben", kind: "entity", title: "Ruben" },
- { id: "harald", kind: "entity", title: "Harald" },
- { id: "golf", kind: "concept", title: "Golf" },
- ],
- edges: [{ source: "ruben", target: "harald", context: "knows" }],
- broken: [],
-};
-
-function makeClient(): QueryClient {
- return new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 0 } },
- });
-}
-
-function Wrapper({ children, client }: PropsWithChildren<{ client: QueryClient }>) {
- return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
-}
-
-/** Latest props the component handed to the library. */
-function latest(): Record<string, unknown> {
- return forceGraphProps[forceGraphProps.length - 1];
-}
-
-async function renderGraph() {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(JSON.stringify(PAYLOAD), {
- status: 200,
- headers: { "content-type": "application/json" },
- }),
- ),
- );
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiGraph onNodeClick={() => {}} />
- </Wrapper>,
- );
- await waitFor(() => {
- expect(forceGraphProps.length).toBeGreaterThan(0);
- });
- // Let the pending auto-fit / resize-fit timers settle so each test starts
- // from a quiet camera.
- await act(async () => {
- vi.advanceTimersByTime(3000);
- });
- vi.clearAllMocks();
-}
-
-afterEach(() => {
- cleanup();
- vi.useRealTimers();
- vi.restoreAllMocks();
-});
-
-beforeEach(() => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- forceGraphProps.length = 0;
-});
-
-describe("WikiGraph render loop", () => {
- it("configures the d3 forces once, not on every engine tick", async () => {
- await renderGraph();
- const onEngineTick = latest().onEngineTick as () => void;
-
- await act(async () => {
- for (let i = 0; i < 12; i += 1) onEngineTick();
- });
-
- // Each of these setters walks every node (charge) or every link (link
- // distance) inside d3, so calling them per frame is an O(n) tax on the
- // whole simulation.
- expect(handle.chargeForce.strength).toHaveBeenCalledTimes(1);
- expect(handle.linkForce.distance).toHaveBeenCalledTimes(1);
- expect(handle.centerForce.strength).toHaveBeenCalledTimes(1);
- });
-
- it("re-fits the camera when the engine settles and the user has not panned", async () => {
- await renderGraph();
- const props = latest();
-
- await act(async () => {
- (props.onEngineStop as () => void)();
- });
-
- expect(handle.zoomToFit).toHaveBeenCalled();
- });
-
- it("does not yank the camera back after the user panned", async () => {
- await renderGraph();
- const props = latest();
-
- await act(async () => {
- (props.onZoom as () => void)(); // user drags the canvas
- (props.onEngineStop as () => void)(); // a reheat settles afterwards
- });
-
- expect(handle.zoomToFit).not.toHaveBeenCalled();
- });
-
- it("does not treat its own fit animation as a user pan", async () => {
- await renderGraph();
- const props = latest();
-
- await act(async () => {
- (props.onEngineStop as () => void)();
- });
- expect(handle.zoomToFit).toHaveBeenCalledTimes(1);
-
- // zoomToFit eases over its duration and emits a zoom event per frame.
- // Those are ours; a later settle must still be allowed to re-fit.
- await act(async () => {
- (props.onZoom as () => void)();
- (props.onEngineStop as () => void)();
- });
-
- expect(handle.zoomToFit).toHaveBeenCalledTimes(2);
- });
-
- it("parks the render loop once the layout has settled", async () => {
- await renderGraph();
- const props = latest();
-
- await act(async () => {
- (props.onEngineStop as () => void)();
- });
- // The fit animation still needs frames — pausing is deferred, not skipped.
- expect(handle.pauseAnimation).not.toHaveBeenCalled();
-
- await act(async () => {
- vi.advanceTimersByTime(1500);
- });
-
- expect(handle.pauseAnimation).toHaveBeenCalled();
- });
-
- it("wakes the render loop back up when the pointer returns", async () => {
- await renderGraph();
- const props = latest();
-
- await act(async () => {
- (props.onEngineStop as () => void)();
- vi.advanceTimersByTime(1500);
- });
- expect(handle.pauseAnimation).toHaveBeenCalled();
-
- const wrap = document.querySelector('[data-testid="wiki-graph-wrap"]');
- expect(wrap).not.toBeNull();
- await act(async () => {
- wrap?.dispatchEvent(new Event("pointerenter"));
- });
-
- expect(handle.resumeAnimation).toHaveBeenCalled();
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx
deleted file mode 100644
index d43df6e1a6..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx
+++ /dev/null
@@ -1,246 +0,0 @@
-/**
- * Tests for the WikiGraph force-graph view.
- *
- * `react-force-graph-2d` is canvas-based and jsdom does not implement
- * `<canvas>`, so we mock the library with a thin DOM-only stand-in that
- * exposes node click + nodeVal in a deterministic way. The component itself
- * also keeps a hidden `<ul>` mirror of the nodes so behaviour (radius scaling
- * on `highlightSlug`, click forwarding, empty/error states) is observable
- * without touching the canvas.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { PropsWithChildren } from "react";
-
-import { WikiGraph } from "@/components/wiki/WikiGraph";
-
-const { forceGraphProps } = vi.hoisted(() => ({
- forceGraphProps: [] as Array<Record<string, unknown>>,
-}));
-
-vi.mock("react-force-graph-2d", async () => {
- const { forwardRef } = await import("react");
- return {
- default: forwardRef(function ForceGraphMock(
- props: Record<string, unknown>,
- _ref,
- ) {
- forceGraphProps.push(props);
- return null;
- }),
- };
-});
-
-function makeClient(): QueryClient {
- return new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 0 } },
- });
-}
-
-function Wrapper({ children, client }: PropsWithChildren<{ client: QueryClient }>) {
- return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
-}
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-beforeEach(() => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- forceGraphProps.length = 0;
-});
-
-describe("WikiGraph", () => {
- it("renders empty state when API returns zero nodes", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({ ok: true, nodes: [], edges: [], broken: [] }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiGraph onNodeClick={() => {}} />
- </Wrapper>,
- );
- await waitFor(() => {
- expect(screen.getByTestId("wiki-graph-empty")).toBeDefined();
- });
- expect(screen.getByTestId("wiki-graph-empty").textContent).toContain(
- "Your memory graph is still empty",
- );
- });
-
- it("renders 3 nodes when API returns 3 nodes", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- nodes: [
- { id: "example-parent", kind: "entity", title: "Example Parent" },
- { id: "example-user", kind: "entity", title: "Example User" },
- { id: "pixel-art-editor", kind: "project", title: "Pixel Art Editor" },
- ],
- edges: [
- { source: "example-user", target: "example-parent", context: "Related to" },
- { source: "example-user", target: "pixel-art-editor", context: "Working on" },
- ],
- broken: [],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiGraph onNodeClick={() => {}} />
- </Wrapper>,
- );
- await waitFor(() => {
- expect(screen.getAllByTestId("wiki-graph-node")).toHaveLength(3);
- });
- const ids = screen
- .getAllByTestId("wiki-graph-node")
- .map((el) => el.getAttribute("data-node-id"));
- expect(ids).toEqual(["example-parent", "example-user", "pixel-art-editor"]);
- const edges = screen.getAllByTestId("wiki-graph-edge");
- expect(edges).toHaveLength(2);
- expect(edges[0].textContent).toContain("Example User → Example Parent · Related to");
- expect(edges[1].textContent).toContain(
- "Example User → Pixel Art Editor · Working on",
- );
- });
-
- it("provides directional arrows and safe node and relationship details", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- nodes: [
- { id: "example-parent", kind: "entity", title: "Example Parent" },
- { id: "example-user", kind: "entity", title: "Example User" },
- ],
- edges: [
- {
- source: "example-user",
- target: "example-parent",
- context: "Related <trusted>",
- },
- ],
- broken: [],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiGraph onNodeClick={() => {}} />
- </Wrapper>,
- );
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-graph-edge")).toBeDefined();
- });
- const props = forceGraphProps.at(-1)!;
- const graphData = props.graphData as {
- nodes: Array<Record<string, unknown>>;
- links: Array<Record<string, unknown>>;
- };
- const nodeLabel = props.nodeLabel as (node: Record<string, unknown>) => string;
- const linkLabel = props.linkLabel as (link: Record<string, unknown>) => string;
-
- // Arrows are drawn only on the focused page's links; at rest the map
- // carries none, and the open page's links carry them.
- const arrowLength = props.linkDirectionalArrowLength as (link: unknown) => number;
- expect(arrowLength(graphData.links[0])).toBe(0);
- expect(props.linkDirectionalArrowRelPos).toBe(0.82);
- expect(nodeLabel(graphData.nodes[0])).toContain("Example Parent (entity) · 1 backlink");
- expect(linkLabel(graphData.links[0])).toContain(
- "Example User → Example Parent · Related &lt;trusted&gt;",
- );
- });
-
- it("invokes onNodeClick(slug) when a node is clicked", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- nodes: [{ id: "example-parent", kind: "entity", title: "Example Parent" }],
- edges: [],
- broken: [],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
- const onNodeClick = vi.fn();
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiGraph onNodeClick={onNodeClick} />
- </Wrapper>,
- );
- await waitFor(() => {
- expect(screen.getByTestId("wiki-graph-node")).toBeDefined();
- });
- fireEvent.click(screen.getByRole("button", { name: /Example Parent/i }));
- expect(onNodeClick).toHaveBeenCalledWith("example-parent");
- });
-
- it("renders highlighted node with 1.5x radius", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- nodes: [
- { id: "example-parent", kind: "entity", title: "Example Parent" },
- { id: "example-user", kind: "entity", title: "Example User" },
- ],
- // The parent fixture gets one backlink; the user fixture gets zero.
- edges: [{ source: "example-user", target: "example-parent", context: "Related" }],
- broken: [],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiGraph onNodeClick={() => {}} highlightSlug="example-parent" />
- </Wrapper>,
- );
- await waitFor(() => {
- expect(screen.getAllByTestId("wiki-graph-node")).toHaveLength(2);
- });
- const parentNode = screen
- .getAllByTestId("wiki-graph-node")
- .find((el) => el.getAttribute("data-node-id") === "example-parent");
- const userNode = screen
- .getAllByTestId("wiki-graph-node")
- .find((el) => el.getAttribute("data-node-id") === "example-user");
- expect(parentNode?.getAttribute("data-node-active")).toBe("true");
- expect(userNode?.getAttribute("data-node-active")).toBe("false");
- const parentRadius = Number(parentNode?.getAttribute("data-node-radius"));
- const userRadius = Number(userNode?.getAttribute("data-node-radius"));
- expect(parentRadius).toBe(15);
- expect(userRadius).toBe(8);
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
deleted file mode 100644
index b9446c83bc..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx
+++ /dev/null
@@ -1,1371 +0,0 @@
-// Force-directed graph of the Obsidian-vault wikilink network.
-//
-// Pure view component — it fetches `/api/wiki/graph` via React Query and
-// renders nodes/edges with `react-force-graph-2d`. This is the landing view
-// inside the Wiki section, so the flat map is drawn in the brand's own terms:
-// neutral ink on the room, a page's kind told apart by SHAPE (the same glyphs
-// the library rail uses), and the one accent reserved for what you are looking
-// at. Hovering a page pulls its neighbourhood forward and lets the rest of the
-// vault recede; repeated wikilinks between the same two pages are drawn as one
-// line whose weight says how often they link.
-//
-// This file owns the DATA and the chrome; the projection is a choice. The flat
-// canvas below is the default and lives here; the 3D scene is `WikiGraph3D`,
-// lazily loaded so nobody downloads a WebGL renderer to read a flat map. Both
-// draw the same nodes, the same colours and the same size encoding out of
-// `lib/wikiGraph.ts`, so switching between them changes the projection and
-// nothing else.
-//
-// Visual contract: docs/plans/b3/00-OVERVIEW.md §3. Node colours live in
-// `lib/wikiGraph.ts:NODE_COLOUR` — never hardcoded here.
-import {
- Suspense,
- lazy,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
-import { useQuery } from "@tanstack/react-query";
-import ForceGraph2D from "react-force-graph-2d";
-import type { ForceGraphMethods, NodeObject } from "react-force-graph-2d";
-
-import {
- clampCenterToView,
- NODE_COLOUR,
- edgeDetails,
- endpointId,
- escapeTooltipText,
- nodeDetails,
- nodeSizeScore,
- sizeChanged,
- toGraphData,
- type RenderEdge,
- type RenderNode,
- type WikiGraphPayload,
-} from "@/lib/wikiGraph";
-import {
- GROUP_LABEL_KEY,
- GROUP_SHAPE,
- WIKI_GROUPS,
- cleanTitle,
- degreeOf,
- groupOfKind,
- isHollowShape,
- traceKindShape,
- uniqueEdges,
- type WikiGroupId,
-} from "@/lib/wikiModel";
-import { useGraphDimension } from "@/lib/graphDimension";
-import { GraphDimensionToggle } from "@/components/wiki/GraphDimensionToggle";
-import { KindGlyph } from "@/components/wiki/KindGlyph";
-import { useThemeValue } from "@/hooks/useTheme";
-import { useEventStore } from "@/store/events";
-import { useT, useUiLanguage } from "@/i18n";
-import { cn } from "@/lib/utils";
-import { LocateFixed } from "lucide-react";
-
-// Three.js and the WebGL renderer are by far the heaviest thing this app can
-// pull in. Keeping them behind `lazy` means the chunk is fetched the first
-// time somebody actually asks for the 3D map, and never otherwise.
-const WikiGraph3D = lazy(() =>
- import("@/components/wiki/WikiGraph3D").then((mod) => ({
- default: mod.WikiGraph3D,
- })),
-);
-
-const GRAPH_QUERY_KEY = ["wiki", "graph"] as const;
-
-/** Extra render-loop controls the library exposes but the typings omit. */
-interface RenderControls {
- pauseAnimation?: () => void;
- resumeAnimation?: () => void;
-}
-
-async function fetchGraph(): Promise<WikiGraphPayload> {
- const res = await fetch("/api/wiki/graph");
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
-}
-
-// The tooltip helpers moved to `lib/wikiGraph` — a module that imports
-// nothing — so the deck can use them without dragging this component's graph
-// library into the startup chunk. Re-exported here because this is where every
-// existing caller looks for them.
-export { edgeDetails, escapeTooltipText, nodeDetails } from "@/lib/wikiGraph";
-
-/**
- * Node radius in graph units — shared by the hit area and the label offset.
- * Range 1.0 … 2.6, so with `nodeRelSize=2` a dot is roughly 2.8 px (leaf) to
- * 4.6 px (hub). The scale itself lives in `lib/wikiGraph.ts` so the 3D map
- * sizes its spheres by exactly the same rule.
- */
-function sizeOf(node: RenderNode, isActive: boolean): number {
- return nodeSizeScore(node.backlinkCount ?? 0, isActive);
-}
-
-export interface WikiGraphProps {
- onNodeClick: (slug: string) => void;
- /** When set, render that node enlarged with a glow. */
- highlightSlug?: string;
-}
-
-/**
- * The map's colours, read from the live theme tokens so the canvas follows
- * light and dark exactly as the DOM around it does. Each entry is an HSL
- * triplet (`0 0% 98%`) so an alpha can be appended per use.
- */
-interface GraphPalette {
- ink: string;
- muted: string;
- accent: string;
- room: string;
- rim: string;
- broken: string;
-}
-
-const FALLBACK_PALETTE: Record<"dark" | "light", GraphPalette> = {
- dark: {
- ink: "0 0% 98%",
- muted: "0 0% 63%",
- accent: "212 100% 62%",
- room: "0 0% 4%",
- rim: "0 0% 22%",
- broken: "0 72% 55%",
- },
- light: {
- ink: "0 0% 9%",
- muted: "0 0% 33%",
- accent: "212 92% 45%",
- room: "0 0% 100%",
- rim: "0 0% 74%",
- broken: "0 72% 45%",
- },
-};
-
-function readPalette(theme: "dark" | "light"): GraphPalette {
- const fallback = FALLBACK_PALETTE[theme];
- if (typeof document === "undefined" || !document.body) return fallback;
- const css = getComputedStyle(document.body);
- const token = (name: string, otherwise: string) => {
- const value = css.getPropertyValue(name).trim();
- return /^\d/.test(value) ? value : otherwise;
- };
- return {
- ink: token("--foreground", fallback.ink),
- muted: token("--muted-foreground", fallback.muted),
- accent: token("--accent", fallback.accent),
- room: token("--background", fallback.room),
- rim: token("--border-strong", fallback.rim),
- broken: token("--destructive", fallback.broken),
- };
-}
-
-function hsl(triplet: string, alpha = 1): string {
- return alpha >= 1 ? `hsl(${triplet})` : `hsl(${triplet} / ${alpha})`;
-}
-
-/** The page the map is focused on: the one under the pointer, else the open one. */
-function focusOf(hover: string | null, selected: string | undefined): string | null {
- return hover ?? selected ?? null;
-}
-
-function linkTouches(link: RenderEdge, slug: string): boolean {
- return endpointId(link.source) === slug || endpointId(link.target) === slug;
-}
-
-/** The canvas face of the brand typeface — the bundle names it "Inter Variable". */
-const CANVAS_FONT = "'Inter Variable', Inter, system-ui, sans-serif";
-
-/** Pull of every page towards the middle; see the gravity force. */
-const GRAVITY = 0.035;
-
-/** A page with no links is pulled in harder, so it orbits instead of drifting off. */
-const ORPHAN_GRAVITY = 0.16;
-
-/** Drawn radius in graph units: big enough to see a leaf at a fitted zoom. */
-function drawRadius(node: RenderNode, isActive: boolean): number {
- return nodeSizeScore(node.backlinkCount ?? 0, isActive) * 2.6;
-}
-
-/**
- * The radius a page is actually painted at: its graph size, but never
- * smaller on screen than a dot you can see and point at.
- */
-function paintedRadius(node: RenderNode, isActive: boolean, isHub: boolean, globalScale: number): number {
- const floor = (isHub ? 6 : isActive ? 5 : 3.2) / Math.max(globalScale, 0.01);
- return Math.max(drawRadius(node, isActive), floor);
-}
-
-/** How many of the best-connected pages keep their label at any zoom. */
-const ALWAYS_LABELLED = 10;
-
-/** From this zoom on, every page is labelled — there is room to read them. */
-const LABEL_ALL_ZOOM = 2.4;
-
-const HIDDEN_KINDS_KEY = "jarvis.wiki.map.hiddenKinds";
-
-/**
- * System pages (the append-only log, the memory index) link to nearly every
- * other page; drawn by default they pull the whole vault into one knot. They
- * start hidden — the legend says so and brings them back in one click.
- */
-const DEFAULT_HIDDEN: readonly WikiGroupId[] = ["system"];
-
-function readHiddenKinds(): Set<WikiGroupId> {
- try {
- const raw = window.localStorage.getItem(HIDDEN_KINDS_KEY);
- if (raw) {
- const parsed = JSON.parse(raw) as unknown;
- if (Array.isArray(parsed)) {
- return new Set(
- parsed.filter((value): value is WikiGroupId =>
- (WIKI_GROUPS as readonly string[]).includes(String(value)),
- ),
- );
- }
- }
- } catch {
- // Storage can be blocked (private window, cleared site data); the
- // default below is the right answer then.
- }
- return new Set(DEFAULT_HIDDEN);
-}
-
-function writeHiddenKinds(hidden: ReadonlySet<WikiGroupId>): void {
- try {
- window.localStorage.setItem(HIDDEN_KINDS_KEY, JSON.stringify([...hidden]));
- } catch {
- // Best effort only: the filter still applies for this session.
- }
-}
-
-/**
- * Memory-Map force-graph. Mounts the canvas lazily when the Wiki tab renders
- * (parent owns mounting) and parks the render loop once the layout has
- * settled and the pointer is elsewhere, so an idle Wiki tab stops burning a
- * frame budget it cannot use.
- */
-export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.Element {
- const assistantName = useEventStore((s) => s.assistantName);
- const uiLanguage = useUiLanguage();
- const t = useT();
- // `useT()` returns a FRESH closure on every render, so using it directly in
- // a dependency array silently defeats every memo below — and this component
- // re-renders on each canvas measurement. Keep a stable callable whose
- // identity only changes when the language or the assistant name changes.
- const tRef = useRef(t);
- tRef.current = t;
- const tStable = useCallback(
- (key: string) => tRef.current(key),
- // eslint-disable-next-line react-hooks/exhaustive-deps -- identity is
- // deliberately pinned to what actually changes the translation output.
- [uiLanguage, assistantName],
- );
-
- // Same reasoning for the click handler: the parent re-creates it on every
- // one of ITS renders, which would invalidate the node-list memo each time.
- const onNodeClickRef = useRef(onNodeClick);
- onNodeClickRef.current = onNodeClick;
- const selectNode = useCallback((slug: string) => {
- if (slug) onNodeClickRef.current(slug);
- }, []);
-
- // Flat canvas or WebGL scene, and already
- // degraded back to flat on a machine that cannot render 3D at all.
- const { dimension } = useGraphDimension();
- const isSpatial = dimension === "3d";
- // The Center button drives two very different cameras. The flat one is reset
- // imperatively below; the 3D scene watches this counter and re-frames itself.
- const [resetTick, setResetTick] = useState(0);
-
- const { data, isLoading, isError } = useQuery({
- queryKey: GRAPH_QUERY_KEY,
- queryFn: fetchGraph,
- staleTime: 30_000,
- });
-
- const [hiddenKinds, setHiddenKinds] = useState<Set<WikiGroupId>>(readHiddenKinds);
- const toggleKind = useCallback((group: WikiGroupId) => {
- setHiddenKinds((prev) => {
- const next = new Set(prev);
- if (next.has(group)) next.delete(group);
- else next.add(group);
- writeHiddenKinds(next);
- return next;
- });
- }, []);
-
- // How many pages of each kind the vault holds, before any filter — the
- // legend's counts, and the list of kinds it offers at all.
- const kindCounts = useMemo(() => {
- const counts = new Map<WikiGroupId, number>();
- for (const node of data?.ok ? data.nodes : []) {
- const group = groupOfKind(node.kind);
- counts.set(group, (counts.get(group) ?? 0) + 1);
- }
- return counts;
- }, [data]);
-
- const graphData = useMemo(() => {
- if (!data?.ok) return { nodes: [] as RenderNode[], links: [] as RenderEdge[] };
- // One edge per linked pair, and only between pages whose kind is shown.
- const shown = data.nodes.filter((node) => !hiddenKinds.has(groupOfKind(node.kind)));
- const shownIds = new Set(shown.map((node) => node.id));
- const edges = uniqueEdges(data.edges).filter(
- (edge) => shownIds.has(edge.source) && shownIds.has(edge.target),
- );
- const weights = new Map(edges.map((edge) => [`${edge.source}\u0000${edge.target}`, edge.weight]));
- const out = toGraphData({
- ...data,
- nodes: shown.map((node) => ({ ...node, title: cleanTitle(node.title, node.id) })),
- edges,
- broken: (data.broken ?? []).filter((edge) => shownIds.has(edge.source)),
- });
- for (const link of out.links) {
- (link as RenderEdge & { weight?: number }).weight =
- weights.get(`${link.source}\u0000${link.target}`) ?? 1;
- }
- // CRITICAL — pre-spread initial positions on a tight circle so
- // force-graph-2d's simulation has direction vectors from frame 1.
- // Tight radius (60) means the graph fits inside the viewport even
- // when the canvas dimensions are still stale on first paint.
- const radius = 60;
- out.nodes.forEach((node, idx) => {
- const angle = (idx / Math.max(1, out.nodes.length)) * Math.PI * 2;
- // Use deterministic angles plus a small jitter so identical runs
- // produce identical layouts (helps tests) while still avoiding
- // perfect-circle artefacts in the settled graph.
- const jitter = ((idx * 31) % 13) - 6;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const n = node as any;
- n.x = Math.cos(angle) * (radius + jitter);
- n.y = Math.sin(angle) * (radius + jitter);
- });
- return out;
- }, [data]);
-
- const nodeTitles = useMemo(
- () => new Map(graphData.nodes.map((node) => [node.id, node.title])),
- [graphData.nodes],
- );
-
- // Who neighbours whom, how connected each page is, and which pages keep a
- // label at rest. All derived once per data generation; the canvas callbacks
- // read them through a ref so they stay stable for the library.
- const structure = useMemo(() => {
- const neighbours = new Map<string, Set<string>>();
- const link = (a: string, b: string) => {
- const set = neighbours.get(a) ?? new Set<string>();
- set.add(b);
- neighbours.set(a, set);
- };
- for (const edge of graphData.links) {
- const source = endpointId(edge.source);
- const target = endpointId(edge.target);
- link(source, target);
- link(target, source);
- }
- const degree = degreeOf(
- graphData.links.map((edge) => ({
- source: endpointId(edge.source),
- target: endpointId(edge.target),
- })),
- );
- const labelled = new Set(
- [...degree.entries()]
- .sort((a, b) => b[1] - a[1])
- .slice(0, ALWAYS_LABELLED)
- .map(([id]) => id),
- );
- const groups = new Map(graphData.nodes.map((node) => [node.id, groupOfKind(node.kind)]));
- const maxDegree = Math.max(1, ...degree.values());
- return { neighbours, degree, labelled, groups, maxDegree };
- }, [graphData]);
- const structureRef = useRef(structure);
- structureRef.current = structure;
- const graphDataRef = useRef(graphData);
- graphDataRef.current = graphData;
-
- const hubSlug = data?.hub ?? null;
- const hubRef = useRef(hubSlug);
- hubRef.current = hubSlug;
-
- const theme = useThemeValue();
- const paletteRef = useRef<GraphPalette>(FALLBACK_PALETTE[theme]);
- useEffect(() => {
- paletteRef.current = readPalette(theme);
- }, [theme]);
-
- // The page under the pointer. State, not only a ref: the travelling lights
- // along its links are a library prop that has to change when it does.
- const [hoverSlug, setHoverSlug] = useState<string | null>(null);
- const hoverRef = useRef<string | null>(null);
-
- const graphRef = useRef<ForceGraphMethods<RenderNode, RenderEdge> | undefined>(undefined);
- const wrapRef = useRef<HTMLDivElement | null>(null);
-
- // The canvas draw callbacks read the highlight through a ref so a selection
- // change does not have to swap the prop functions on the library (which
- // makes it re-ingest every accessor); the next painted frame just reads the
- // new value.
- const highlightRef = useRef(highlightSlug);
- highlightRef.current = highlightSlug;
-
- // Canvas dimensions match the wrap container EXACTLY so the graph's
- // (0,0) origin lands at the centre of the visible area.
- //
- // Measurement strategy that finally works:
- // 1. Initial state seeded with a sensible default (window minus
- // sidebar+backlinks ~= window - 600).
- // 2. RAF-driven polling loop that re-measures on every frame.
- // Stops once we get a positive measurement, then re-subscribes
- // to ResizeObserver for live updates. The continuous polling
- // phase exists because some layout passes report clientWidth=0
- // for several frames after mount, and a single ResizeObserver
- // registration doesn't fire if the size never changes.
- const [winSize, setWinSize] = useState<{ w: number; h: number }>(() => ({
- w: typeof window !== "undefined" ? Math.max(800, window.innerWidth - 600) : 800,
- h: typeof window !== "undefined" ? Math.max(600, window.innerHeight - 120) : 600,
- }));
- useEffect(() => {
- let rafId: number | null = null;
- let observer: ResizeObserver | null = null;
- let stopped = false;
- const apply = (w: number, h: number) => {
- // Absorb sub-pixel jitter (scrollbar flicker, DPI rounding) so a noisy
- // ResizeObserver stream doesn't churn React state for no visible change.
- setWinSize((prev) => (sizeChanged(prev, { w, h }) ? { w, h } : prev));
- };
- const poll = () => {
- if (stopped) return;
- const el = wrapRef.current;
- if (el) {
- const r = el.getBoundingClientRect();
- if (r.width > 0 && r.height > 0) {
- apply(Math.floor(r.width), Math.floor(r.height));
- // Once we have a real size, switch from polling to observer.
- if (!observer) {
- observer = new ResizeObserver(() => {
- const rr = el.getBoundingClientRect();
- if (rr.width > 0 && rr.height > 0) {
- apply(Math.floor(rr.width), Math.floor(rr.height));
- }
- });
- observer.observe(el);
- }
- return; // stop polling
- }
- }
- rafId = window.requestAnimationFrame(poll);
- };
- poll();
- return () => {
- stopped = true;
- if (rafId !== null) window.cancelAnimationFrame(rafId);
- observer?.disconnect();
- };
- }, []);
-
- // Auto-fit ONCE, ~2.5 s after the graph data lands. We deliberately
- // do NOT keep firing zoomToFit on a schedule — that destroyed the
- // user's pan: as soon as they dragged the canvas, a pending fit
- // would yank everything back to centre. One initial fit is enough
- // for landing the graph in the viewport; after that the user owns
- // the view. The Zentrieren button is still there for an explicit
- // reset. We also bail out of the auto-fit if the user has already
- // touched the canvas (panInteracted ref).
- const panInteractedRef = useRef(false);
- // Guards the programmatic centerAt() inside onZoomEnd from re-entering itself:
- // centerAt re-emits zoom events, which would otherwise re-fire the boundary
- // clamp in a feedback loop.
- const correctingRef = useRef(false);
- // Wall-clock deadline while OUR OWN camera animation is running. zoomToFit
- // eases over its whole duration and emits a zoom event per frame; without
- // this the very first auto-fit marked the view as "the user panned" and
- // suppressed every later auto-fit (including the one after a resize).
- const programmaticUntilRef = useRef(0);
- // Render-loop bookkeeping. `renderingRef` mirrors the library's animation
- // state; the others decide when parking it is safe.
- const renderingRef = useRef(true);
- const engineRunningRef = useRef(true);
- const pointerInsideRef = useRef(false);
- const pointerDownRef = useRef(false);
- const pauseTimerRef = useRef<number | null>(null);
- // Forces are applied once per data generation, never per tick (see below).
- const forcesConfiguredRef = useRef(false);
-
- const renderControls = (): RenderControls | undefined =>
- graphRef.current as RenderControls | undefined;
-
- const resumeRender = useCallback((): void => {
- if (pauseTimerRef.current !== null) {
- window.clearTimeout(pauseTimerRef.current);
- pauseTimerRef.current = null;
- }
- if (renderingRef.current) return;
- renderingRef.current = true;
- renderControls()?.resumeAnimation?.();
- }, []);
-
- /**
- * Park the render loop — but only when nothing on screen still needs
- * frames. Pausing mid-simulation would freeze a half-settled layout, and
- * pausing during a camera tween would strand it mid-flight, so both defer
- * instead of cancelling.
- */
- const pauseRenderIfIdle = useCallback(function pauseIfIdle(): void {
- if (pauseTimerRef.current !== null) {
- window.clearTimeout(pauseTimerRef.current);
- pauseTimerRef.current = null;
- }
- if (!renderingRef.current) return;
- if (engineRunningRef.current) return;
- if (pointerInsideRef.current || pointerDownRef.current) return;
- const pending = programmaticUntilRef.current - Date.now();
- if (pending > 0) {
- pauseTimerRef.current = window.setTimeout(pauseIfIdle, pending + 30);
- return;
- }
- renderingRef.current = false;
- renderControls()?.pauseAnimation?.();
- }, []);
-
- /** Fit the graph into view, flagged as OUR camera move, not the user's. */
- const fitToView = useCallback(
- (duration: number, padding: number): void => {
- const ref = graphRef.current;
- if (!ref) return;
- programmaticUntilRef.current = Date.now() + duration + 120;
- // A tween needs frames; make sure the loop is not parked.
- resumeRender();
- ref.zoomToFit(duration, padding);
- },
- [resumeRender],
- );
-
- useEffect(() => {
- if (graphData.nodes.length === 0) return;
- const timer = window.setTimeout(() => {
- if (!panInteractedRef.current) {
- fitToView(400, 120);
- }
- }, 2500);
- return () => window.clearTimeout(timer);
- }, [graphData.nodes.length, fitToView]);
-
- // Re-frame after a resize. Now that the canvas resizes in place (no remount),
- // the settled graph keeps its positions but can sit off-centre in the new
- // viewport — so once the size stops changing we fit it back into view. The
- // 220 ms debounce collapses a whole window-drag into a single fit at the end
- // instead of one per intermediate size. A resize is an explicit layout
- // change, so this re-fit intentionally overrides a prior manual pan.
- useEffect(() => {
- if (graphData.nodes.length === 0) return;
- const timer = window.setTimeout(() => {
- panInteractedRef.current = false;
- fitToView(400, 80);
- }, 220);
- return () => window.clearTimeout(timer);
- }, [winSize.w, winSize.h, graphData.nodes.length, fitToView]);
-
- // New data reheats the simulation, so the loop must be running to show it —
- // and the forces have to be re-applied to the new node/link set.
- useEffect(() => {
- if (graphData.nodes.length === 0) return;
- forcesConfiguredRef.current = false;
- engineRunningRef.current = true;
- resumeRender();
- }, [graphData, resumeRender]);
-
- // A selection or theme change only needs a repaint, not a reheat: run a few
- // frames, then go back to idle.
- useEffect(() => {
- if (graphData.nodes.length === 0) return;
- resumeRender();
- const timer = window.setTimeout(() => pauseRenderIfIdle(), 400);
- return () => window.clearTimeout(timer);
- }, [highlightSlug, theme, graphData.nodes.length, resumeRender, pauseRenderIfIdle]);
-
- // Pointer presence drives the idle parking: while the cursor is over the
- // canvas the user can hover, drag and wheel-zoom, all of which need frames.
- //
- // `hasGraph` is a real dependency, not decoration: the first render of this
- // component is always the loading placeholder, so the wrapper does not exist
- // yet and an attach-on-mount effect would bind to nothing and never retry.
- const hasGraph = graphData.nodes.length > 0;
- useEffect(() => {
- const el = wrapRef.current;
- if (!el || !hasGraph) return;
- const onEnter = () => {
- pointerInsideRef.current = true;
- resumeRender();
- };
- const onLeave = () => {
- pointerInsideRef.current = false;
- pauseRenderIfIdle();
- };
- const onDown = () => {
- pointerDownRef.current = true;
- resumeRender();
- };
- const onUp = () => {
- pointerDownRef.current = false;
- };
- el.addEventListener("pointerenter", onEnter);
- el.addEventListener("pointerleave", onLeave);
- el.addEventListener("pointerdown", onDown);
- window.addEventListener("pointerup", onUp);
- el.addEventListener("wheel", resumeRender, { passive: true });
- return () => {
- el.removeEventListener("pointerenter", onEnter);
- el.removeEventListener("pointerleave", onLeave);
- el.removeEventListener("pointerdown", onDown);
- window.removeEventListener("pointerup", onUp);
- el.removeEventListener("wheel", resumeRender);
- };
- }, [hasGraph, resumeRender, pauseRenderIfIdle]);
-
- useEffect(
- () => () => {
- if (pauseTimerRef.current !== null) window.clearTimeout(pauseTimerRef.current);
- },
- [],
- );
-
- const handleResetView = useCallback((): void => {
- // Bumped FIRST, because everything below is flat-canvas work that bails
- // out the moment the 3D scene is the one on screen. The scene re-frames
- // its own camera off this counter.
- setResetTick((tick) => tick + 1);
- const ref = graphRef.current;
- if (!ref) return;
- // User explicitly asked for centring → clear the pan-touched flag
- // so the post-reheat zoomToFit actually fires.
- panInteractedRef.current = false;
- // Two-stage reset: first re-spread nodes onto a fresh circle and
- // reheat the simulation (alpha=1), then zoomToFit after the layout
- // has had a chance to spread out. Without the reheat step a
- // collapsed graph (all nodes at one pixel) stays collapsed after
- // zoomToFit because the math is "fit a 1px-wide bounding box into
- // the viewport" -> infinite zoom.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const anyRef = ref as any;
- const radius = Math.max(180, graphData.nodes.length * 28);
- graphData.nodes.forEach((node, idx) => {
- const angle = (idx / Math.max(1, graphData.nodes.length)) * Math.PI * 2;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const n = node as any;
- n.x = Math.cos(angle) * radius;
- n.y = Math.sin(angle) * radius;
- // Clear pinned positions + velocity so the reheat starts cleanly.
- // These are d3-internals not in the RenderNode TS type but they
- // exist at runtime on every node force-graph-2d touches.
- n.fx = null;
- n.fy = null;
- n.vx = 0;
- n.vy = 0;
- });
- // The reheat needs frames, and it will run the engine again.
- engineRunningRef.current = true;
- resumeRender();
- const sim = anyRef.d3Force?.("simulation");
- if (sim?.alpha && sim?.restart) {
- sim.alpha(1).restart();
- }
- // Give the sim ~1.5 s to spread, then fit.
- window.setTimeout(() => fitToView(600, 100), 1500);
- }, [graphData.nodes, fitToView, resumeRender]);
-
- // Keep the graph from being panned/zoomed entirely out of view.
- //
- // react-force-graph allows unbounded background panning, and a pure pan does
- // NOT reheat the simulation — so the onEngineStop re-fit can never rescue a
- // graph the user dragged off-screen. That was the reported bug: drag the
- // network toward an edge and it vanishes ("the right wall disappears"), with
- // no way back except the Zentrieren button. Here we re-clamp the camera on
- // every pan/zoom tick so the graph "sticks" at the viewport edge (a slice
- // always stays visible; the whole graph stays visible when it is smaller than
- // the viewport — see clampCenterToView).
- //
- // The correction is IMMEDIATE (duration 0). A transitioned centerAt is
- // unreliable here: force-graph's tween is driven by its render loop, which
- // throttles once the simulation freezes, so an eased correction stalls
- // mid-flight (verified live). A synchronous set holds. The guard absorbs the
- // nested zoom event that translateTo re-emits, so this can't loop.
- const clampViewToBounds = useCallback((): void => {
- if (correctingRef.current) return;
- const ref = graphRef.current;
- if (!ref) return;
- const bbox = ref.getGraphBbox();
- if (!bbox) return;
- const center = ref.screen2GraphCoords(winSize.w / 2, winSize.h / 2);
- const target = clampCenterToView(center, ref.zoom(), bbox, {
- w: winSize.w,
- h: winSize.h,
- });
- if (Math.abs(target.x - center.x) > 0.5 || Math.abs(target.y - center.y) > 0.5) {
- correctingRef.current = true;
- ref.centerAt(target.x, target.y, 0);
- correctingRef.current = false;
- }
- }, [winSize.w, winSize.h]);
-
- const handleZoom = useCallback((): void => {
- // Our own fit animation emits zoom events too — those are not a user pan,
- // and the fit is in-bounds by construction, so leave both flags alone.
- if (Date.now() < programmaticUntilRef.current) return;
- // Any user-driven zoom/pan cancels future auto-fits. Without
- // this, the 2.5 s pending fit would yank the canvas back to
- // centre right after the user finished dragging.
- panInteractedRef.current = true;
- // Live wall — keep the graph reachable WHILE the user drags, so it
- // sticks at the edge instead of sliding off and vanishing.
- clampViewToBounds();
- }, [clampViewToBounds]);
-
- const handleZoomEnd = useCallback((): void => {
- // Safety net for any pan/zoom that slipped past the live clamp
- // (e.g. a wheel-zoom that shifts the centre).
- if (Date.now() < programmaticUntilRef.current) return;
- clampViewToBounds();
- }, [clampViewToBounds]);
-
- const handleNodeDrag = useCallback((): void => {
- panInteractedRef.current = true;
- }, []);
-
- const handleBackgroundClick = useCallback(
- (event: MouseEvent): void => {
- // Double-click on empty canvas re-centres the view.
- // Cheaper than reaching for the Zentrieren button.
- if (event.detail >= 2) {
- panInteractedRef.current = false;
- handleResetView();
- }
- },
- [handleResetView],
- );
-
- // Force-sim tuning for dense graphs (~10+ edges per node), applied ONCE per
- // data generation.
- //
- // This used to run on EVERY engine tick. d3's setters are not free: each
- // `charge.strength()` re-initialises the force over all nodes and each
- // `link.distance()` recomputes the distance of every link — so a 60 fps
- // simulation paid an extra O(nodes + links) pass per frame purely to
- // re-assign constants that never changed. On a dense vault that is exactly
- // the stutter users felt while the graph settled and while dragging.
- const configureForces = useCallback((): void => {
- engineRunningRef.current = true;
- if (forcesConfiguredRef.current) return;
- const ref = graphRef.current;
- if (!ref) return;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const anyRef = ref as any;
- // Repulsion: every pair pushes apart, reaching far enough (460 graph
- // units) that the leaves of one hub keep clear of the next hub's, so the
- // vault settles into readable constellations instead of one knot.
- const chargeForce = anyRef.d3Force?.("charge");
- if (chargeForce && typeof chargeForce.strength === "function") {
- chargeForce.strength(-210);
- if (typeof chargeForce.distanceMax === "function") {
- chargeForce.distanceMax(460);
- }
- }
- // Links stay short so a page sits beside what it links to, and loose
- // enough that a hub with ninety links does not crush its leaves together.
- const linkForce = anyRef.d3Force?.("link");
- if (linkForce && typeof linkForce.distance === "function") {
- linkForce.distance(56);
- if (typeof linkForce.strength === "function") {
- linkForce.strength(0.5);
- }
- }
- // Soft centering: every node feels a gentle pull towards (0,0) — this
- // replaces the hard bounding box. Strength 0.08 keeps the cluster from
- // drifting infinitely, but is gentle enough that the user can drag a node
- // far away and it stays where they dropped it. Higher values (0.3-0.5)
- // caused dragged nodes to spring back to the centre, which felt broken
- // when the user wanted to lay the graph out manually.
- const centerForce = anyRef.d3Force?.("center");
- if (centerForce && typeof centerForce.strength === "function") {
- centerForce.strength(0.08);
- }
- // Gentle gravity towards the middle. forceCenter only re-centres the
- // whole cloud; a page with no links feels nothing else, so the charge
- // alone pushed every orphan to the far edge and the camera had to zoom
- // out until the real network was a speck.
- let gravityNodes: Array<{ id?: string | number; x?: number; y?: number; vx?: number; vy?: number }> = [];
- const gravity = Object.assign(
- (alpha: number) => {
- const { degree } = structureRef.current;
- for (const node of gravityNodes) {
- const k = (degree.get(String(node.id ?? "")) ?? 0) > 0 ? GRAVITY : ORPHAN_GRAVITY;
- node.vx = (node.vx ?? 0) - (node.x ?? 0) * k * alpha;
- node.vy = (node.vy ?? 0) - (node.y ?? 0) * k * alpha;
- }
- },
- {
- initialize: (nodes: typeof gravityNodes) => {
- gravityNodes = nodes;
- },
- },
- );
- anyRef.d3Force?.("gravity", gravity);
- forcesConfiguredRef.current = true;
- }, []);
-
- const handleEngineStop = useCallback((): void => {
- engineRunningRef.current = false;
- // First chance the simulation finished spreading — fit the bounding box
- // of the settled nodes into the viewport. 80px padding leaves room for
- // labels at all four edges. Skipped once the user has taken over the
- // camera: a reheat (node drag, reset) ends here too, and yanking the view
- // back every time a drag settles was its own reported bug.
- if (!panInteractedRef.current) {
- fitToView(500, 80);
- }
- // Nothing left to animate — park the loop until the user comes back.
- pauseRenderIfIdle();
- }, [fitToView, pauseRenderIfIdle]);
-
- const nodeLabel = useCallback(
- (node: NodeObject<RenderNode>) =>
- escapeTooltipText(nodeDetails(node as RenderNode, tStable)),
- [tStable],
- );
-
- const linkLabel = useCallback(
- (link: RenderEdge) => escapeTooltipText(edgeDetails(link as RenderEdge, nodeTitles)),
- [nodeTitles],
- );
-
- const nodeVal = useCallback(
- (node: NodeObject<RenderNode>) =>
- sizeOf(node as RenderNode, node.id === highlightRef.current),
- [],
- );
-
- const nodeColor = useCallback(
- (node: NodeObject<RenderNode>) => node.colour ?? NODE_COLOUR.entity ?? "#8b95a7",
- [],
- );
-
- const nodeCanvasObjectMode = useCallback(() => "replace" as const, []);
-
- // The hit area follows the drawn shape (plus a little slack), so a leaf is
- // as easy to hover as it is to see.
- const nodePointerAreaPaint = useCallback(
- (node: NodeObject<RenderNode>, colour: string, ctx: CanvasRenderingContext2D): void => {
- ctx.beginPath();
- ctx.arc(
- node.x ?? 0,
- node.y ?? 0,
- drawRadius(node as RenderNode, node.id === highlightRef.current) + 2.5,
- 0,
- Math.PI * 2,
- );
- ctx.fillStyle = colour;
- ctx.fill();
- },
- [],
- );
-
- const nodeCanvasObject = useCallback(
- (
- node: NodeObject<RenderNode>,
- ctx: CanvasRenderingContext2D,
- globalScale: number,
- ): void => {
- const x = node.x ?? 0;
- const y = node.y ?? 0;
- const id = String(node.id ?? "");
- const palette = paletteRef.current;
- const { neighbours, degree, groups, maxDegree } = structureRef.current;
- const isActive = id === highlightRef.current;
- const isHover = id === hoverRef.current;
- const isHub = id === hubRef.current;
- const focus = focusOf(hoverRef.current, highlightRef.current);
- const isNeighbour = focus !== null && (neighbours.get(focus)?.has(id) ?? false);
- const inFocus = focus === null || id === focus || isNeighbour;
- const group = groups.get(id) ?? "other";
- const isBroken = (node as RenderNode).kind === "broken";
- const shape = isBroken ? "dot" : GROUP_SHAPE[group];
- // Match the nodeVal calculation so the hit area and the drawn shape agree.
- const radius = paintedRadius(node as RenderNode, isActive, isHub, globalScale);
- // Ink weight follows connectedness: leaves are quiet, hubs read first.
- const weight = Math.min(1, (degree.get(id) ?? 0) / Math.max(4, maxDegree * 0.35));
- const alpha = inFocus ? 0.5 + weight * 0.5 : 0.12;
- const lit = isActive || isHover || (hoverRef.current !== null && isNeighbour);
-
- ctx.save();
- // The user's own page wears a faint accent orbit — the map's centre of gravity.
- if (isHub && inFocus) {
- ctx.beginPath();
- ctx.arc(x, y, radius + 2 + 5 / globalScale, 0, Math.PI * 2);
- ctx.strokeStyle = hsl(palette.accent, 0.4);
- ctx.lineWidth = 1 / globalScale;
- ctx.setLineDash([2 / globalScale, 2.5 / globalScale]);
- ctx.stroke();
- ctx.setLineDash([]);
- }
- // The open or hovered page gets a soft accent halo, findable without reading.
- if (isActive || isHover) {
- ctx.beginPath();
- ctx.arc(x, y, radius + 4.5, 0, Math.PI * 2);
- ctx.fillStyle = hsl(palette.accent, isActive ? 0.22 : 0.14);
- ctx.fill();
- }
-
- traceKindShape(ctx, shape, x, y, radius);
- const colour = isBroken
- ? hsl(palette.broken, inFocus ? 0.9 : 0.2)
- : lit || isHub
- ? hsl(palette.accent, inFocus ? 1 : 0.25)
- : hsl(palette.ink, alpha);
- if (isHollowShape(shape)) {
- ctx.strokeStyle = colour;
- ctx.lineWidth = Math.max(1.2, radius * 0.45);
- ctx.stroke();
- } else {
- ctx.fillStyle = colour;
- ctx.fill();
- // A hairline in the room colour keeps touching shapes apart.
- ctx.strokeStyle = hsl(palette.room, 0.9);
- ctx.lineWidth = 0.8 / globalScale;
- ctx.stroke();
- }
-
- ctx.restore();
- },
- [],
- );
-
- /**
- * Labels are drawn after every shape, once per frame, most important first:
- * the open and hovered page, the user's own page, the hovered page's
- * neighbours, then by how connected a page is. A label that would collide
- * with one already placed is left out — a crowded hub shows the names that
- * matter instead of a pile of overprinted text. Zooming in makes room, so
- * more of them appear.
- */
- const drawLabels = useCallback((ctx: CanvasRenderingContext2D, globalScale: number): void => {
- const palette = paletteRef.current;
- const { neighbours, degree, labelled } = structureRef.current;
- const hover = hoverRef.current;
- const selected = highlightRef.current;
- const focus = focusOf(hover, selected);
- const focusNeighbours = focus !== null ? neighbours.get(focus) : undefined;
-
- type Candidate = { node: RenderNode; rank: number; text: string };
- const candidates: Candidate[] = [];
- for (const node of graphDataRef.current.nodes) {
- const id = String(node.id ?? "");
- const isActive = id === selected;
- const isHover = id === hover;
- const isHub = id === hubRef.current;
- const isNeighbour = focusNeighbours?.has(id) ?? false;
- const inFocus = focus === null || id === focus || isNeighbour;
- if (!inFocus) continue;
- let rank: number;
- if (isActive || isHover) rank = 0;
- else if (isHub) rank = 1;
- else if (isNeighbour) rank = 2;
- else if (labelled.has(id)) rank = 3;
- else if (globalScale >= LABEL_ALL_ZOOM) rank = 4;
- else continue;
- const text = node.title ?? id;
- if (text) candidates.push({ node, rank, text });
- }
- candidates.sort(
- (a, b) =>
- a.rank - b.rank ||
- (degree.get(String(b.node.id)) ?? 0) - (degree.get(String(a.node.id)) ?? 0),
- );
-
- const placed: Array<[number, number, number, number]> = [];
- const pad = 3 / globalScale;
- ctx.save();
- ctx.textAlign = "center";
- ctx.textBaseline = "top";
- ctx.lineJoin = "round";
- for (const { node, rank, text } of candidates) {
- const x = node.x ?? 0;
- const y = node.y ?? 0;
- const id = String(node.id ?? "");
- const strong = rank <= 1 || labelled.has(id);
- const fontSize = (strong ? 12 : 11) / globalScale;
- ctx.font = `${strong ? 500 : 400} ${fontSize}px ${CANVAS_FONT}`;
- const radius = paintedRadius(node, id === selected, id === hubRef.current, globalScale);
- const ty = y + radius + 4 / globalScale;
- const width = ctx.measureText(text).width;
- const box: [number, number, number, number] = [
- x - width / 2 - pad,
- ty - pad,
- x + width / 2 + pad,
- ty + fontSize * 1.2 + pad,
- ];
- const collides = placed.some(
- ([l, t, r, b]) => box[0] < r && box[2] > l && box[1] < b && box[3] > t,
- );
- // The open and hovered page always get their name, even over others.
- if (collides && rank > 0) continue;
- placed.push(box);
- // A halo in the room colour instead of a drop shadow: legible over
- // crossing lines in both themes, and no glow.
- ctx.lineWidth = 3.5 / globalScale;
- ctx.strokeStyle = hsl(palette.room, 0.92);
- ctx.strokeText(text, x, ty);
- ctx.fillStyle =
- rank === 0 ? hsl(palette.ink) : strong ? hsl(palette.ink, 0.88) : hsl(palette.muted, 0.95);
- ctx.fillText(text, x, ty);
- }
- ctx.restore();
- }, []);
-
- const linkColor = useCallback((link: RenderEdge) => {
- const palette = paletteRef.current;
- if ((link as RenderEdge).broken) return hsl(palette.broken, 0.5);
- const focus = focusOf(hoverRef.current, highlightRef.current);
- if (focus === null) return hsl(palette.ink, 0.14);
- return linkTouches(link, focus) ? hsl(palette.accent, 0.75) : hsl(palette.ink, 0.04);
- }, []);
-
- const linkWidth = useCallback((link: RenderEdge) => {
- const weight = (link as RenderEdge & { weight?: number }).weight ?? 1;
- const base = 0.6 + Math.min(Math.log2(weight), 4) * 0.35;
- const focus = focusOf(hoverRef.current, highlightRef.current);
- return focus !== null && linkTouches(link, focus) ? base + 0.6 : base;
- }, []);
-
- const linkLineDash = useCallback(
- (link: RenderEdge) => ((link as RenderEdge).broken ? [4, 4] : null),
- [],
- );
-
- // Arrows only where they carry meaning: on the links of the focused page.
- const linkArrowLength = useCallback((link: RenderEdge) => {
- const focus = focusOf(hoverRef.current, highlightRef.current);
- return focus !== null && linkTouches(link, focus) ? 4 : 0;
- }, []);
-
- const linkArrowColor = useCallback((link: RenderEdge) => {
- const palette = paletteRef.current;
- return (link as RenderEdge).broken ? hsl(palette.broken, 0.7) : hsl(palette.accent, 0.9);
- }, []);
-
- // Light travels along the hovered page's links — the map shows which way
- // a page's knowledge flows. Swapped per hover so the library re-seeds it.
- const linkParticles = useCallback(
- (link: RenderEdge) => (hoverSlug !== null && linkTouches(link, hoverSlug) ? 2 : 0),
- [hoverSlug],
- );
-
- const linkParticleColor = useCallback(() => hsl(paletteRef.current.accent), []);
-
- const handleNodeHover = useCallback(
- (node: NodeObject<RenderNode> | null): void => {
- const id = node ? String(node.id ?? "") : null;
- if (hoverRef.current === id) return;
- hoverRef.current = id;
- setHoverSlug(id);
- if (wrapRef.current) wrapRef.current.style.cursor = id ? "pointer" : "";
- resumeRender();
- },
- [resumeRender],
- );
-
- const handleNodeClick = useCallback(
- (node: NodeObject<RenderNode>): void => {
- selectNode((node.id as string | undefined) ?? "");
- },
- [selectNode],
- );
-
- // Hidden DOM mirror — keeps the canvas-based graph testable without a full
- // canvas mock. The visible canvas remains the source of truth for users;
- // this list is purely a behaviour anchor for RTL + a11y readers.
- //
- // Memoised because it is the single largest render cost in this component:
- // one <li> plus a formatted label per node AND per edge. Rebuilding all of
- // that on every canvas measurement (the ResizeObserver fires a burst per
- // window drag) is what made resizing the window feel like the graph froze.
- const nodeListItems = useMemo(
- () =>
- graphData.nodes.map((node) => {
- const isActive = node.id === highlightSlug;
- const renderRadius = isActive ? node.radius * 1.5 : node.radius;
- return (
- <li
- key={node.id}
- data-testid="wiki-graph-node"
- data-node-id={node.id}
- data-node-kind={node.kind}
- data-node-radius={renderRadius}
- data-node-active={isActive ? "true" : "false"}
- >
- <button
- type="button"
- onClick={() => selectNode(node.id)}
- aria-label={nodeDetails(node, tStable)}
- >
- {node.title}
- </button>
- </li>
- );
- }),
- [graphData.nodes, highlightSlug, selectNode, tStable],
- );
-
- const edgeListItems = useMemo(
- () =>
- graphData.links.map((edge, index) => {
- const source = endpointId(edge.source);
- const target = endpointId(edge.target);
- return (
- <li
- key={`${source}:${target}:${index}`}
- data-testid="wiki-graph-edge"
- data-edge-source={source}
- data-edge-target={target}
- data-edge-broken={edge.broken ? "true" : "false"}
- >
- {edgeDetails(edge, nodeTitles)}
- {edge.broken ? ` · ${tStable("wiki_graph.unresolved")}` : ""}
- </li>
- );
- }),
- [graphData.links, nodeTitles, tStable],
- );
-
- if (isLoading) {
- return (
- <div
- data-testid="wiki-graph-loading"
- className="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.loading")}
- </div>
- );
- }
-
- if (isError || !data?.ok) {
- return (
- <div
- data-testid="wiki-graph-error"
- className="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.load_error")}
- </div>
- );
- }
-
- if ((data.nodes ?? []).length === 0) {
- return (
- <div
- data-testid="wiki-graph-empty"
- className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.empty_prefix")}
- {assistantName}
- {t("wiki_graph.empty_suffix")}
- </div>
- );
- }
-
- const legendGroups = WIKI_GROUPS.filter((group) => (kindCounts.get(group) ?? 0) > 0);
- const connectionCount = graphData.links.filter((link) => !link.broken).length;
-
- return (
- <div
- ref={wrapRef}
- data-testid="wiki-graph-wrap"
- className={cn(
- "relative h-full w-full overflow-hidden",
- // A faint dot grid: the map reads as a surface you can move across,
- // not as a void. Drawn from the ink token, so it inverts with the theme.
- "[background-image:radial-gradient(hsl(var(--foreground)/0.07)_1px,transparent_1px)] [background-size:24px_24px]",
- )}
- role="group"
- aria-label={t("wiki_graph.relationship_graph")}
- onPointerLeave={() => handleNodeHover(null)}
- >
- {/* Legend and filter in one: every kind the vault holds, drawn in the
- shape the map uses for it. A click hides or shows that kind. */}
- <div
- className="absolute left-3 top-3 z-10 w-[188px] rounded-lg border border-border bg-popover/85 p-1.5 backdrop-blur"
- data-testid="wiki-graph-legend"
- role="group"
- aria-label={t("wiki_ui.legend_label")}
- >
- {legendGroups.map((group) => {
- const hidden = hiddenKinds.has(group);
- return (
- <button
- key={group}
- type="button"
- onClick={() => toggleKind(group)}
- aria-pressed={!hidden}
- title={t(hidden ? "wiki_ui.legend_show" : "wiki_ui.legend_hide")}
- data-testid={`wiki-graph-legend-${group}`}
- className={cn(
- "flex h-7 w-full items-center gap-2 rounded-md px-2 text-sm transition-colors hover:bg-secondary",
- hidden ? "text-foreground-faint" : "text-foreground",
- )}
- >
- <KindGlyph
- group={group}
- className={cn("h-2.5 w-2.5", hidden ? "opacity-40" : "text-foreground")}
- />
- <span className={cn("min-w-0 flex-1 truncate text-left", hidden && "line-through decoration-foreground-faint/60")}>
- {t(GROUP_LABEL_KEY[group])}
- </span>
- <span className="tabular-nums text-foreground-faint">{kindCounts.get(group) ?? 0}</span>
- </button>
- );
- })}
- <div className="mt-1 flex items-center gap-2 border-t border-border px-2 pb-0.5 pt-2 text-xs text-foreground-faint">
- <span className="h-px w-4 bg-foreground/40" aria-hidden />
- <span className="tabular-nums">
- {t("wiki_ui.legend_connections").replace("{0}", String(connectionCount))}
- </span>
- </div>
- </div>
-
- <div className="absolute bottom-3 right-3 z-10 flex items-center gap-2">
- <GraphDimensionToggle className="h-8 bg-popover/85" />
- <button
- type="button"
- onClick={handleResetView}
- data-testid="wiki-graph-reset-view"
- className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border bg-popover/85 px-2.5 text-sm font-medium text-muted-foreground backdrop-blur transition-colors hover:bg-secondary hover:text-foreground"
- title={t("wiki_graph.reset_view_title")}
- >
- <LocateFixed className="h-3.5 w-3.5" aria-hidden />
- {t("wiki_graph.center")}
- </button>
- </div>
-
- <p className="pointer-events-none absolute bottom-5 left-4 z-10 hidden whitespace-nowrap text-xs text-foreground-faint 2xl:block">
- {t("wiki_ui.map_hint")}
- </p>
-
- {graphData.nodes.length === 0 && (
- <div
- className="absolute inset-0 z-[5] flex items-center justify-center px-8 text-center text-sm text-muted-foreground"
- data-testid="wiki-graph-all-hidden"
- >
- {t("wiki_ui.map_all_hidden")}
- </div>
- )}
-
- <ul data-testid="wiki-graph-node-list" className="sr-only">
- {nodeListItems}
- </ul>
- <ul data-testid="wiki-graph-edge-list" className="sr-only">
- {edgeListItems}
- </ul>
-
- {isSpatial ? (
- <Suspense
- fallback={
- <div
- data-testid="wiki-graph-3d-loading"
- className="flex h-full items-center justify-center text-sm text-muted-foreground"
- >
- {t("wiki_graph.loading_3d")}
- </div>
- }
- >
- <WikiGraph3D
- graphData={graphData}
- width={winSize.w}
- height={winSize.h}
- highlightSlug={highlightSlug}
- pivotSlug={data?.hub ?? null}
- onNodeClick={selectNode}
- resetSignal={resetTick}
- nodeLabel={nodeLabel}
- linkLabel={linkLabel}
- />
- </Suspense>
- ) : (
- <ForceGraph2D<RenderNode, RenderEdge>
- // NO remount key. react-force-graph-2d (via react-kapsule) maps the
- // width/height props onto live `.width()/.height()` calls that resize
- // the canvas WITHOUT restarting the simulation, so node positions
- // survive a resize. A `key={WxH}` here used to unmount+remount the
- // whole graph on every pixel of size change, restarting the force sim
- // from scratch — so any stream of resize events (window drag/maximise,
- // DPI rounding, scrollbar flicker) made the network flail and fly off
- // screen. The settled layout is preserved now; a debounced zoomToFit
- // (see the winSize effect above) just re-frames it after a real resize.
- //
- // Every accessor below is a STABLE callback (the particle count alone
- // changes with the hovered page). Passing fresh closures made the
- // library re-ingest its whole accessor set on each of this
- // component's renders, for values that never changed.
- ref={graphRef}
- graphData={graphData}
- width={winSize.w}
- height={winSize.h}
- backgroundColor="rgba(0,0,0,0)"
- nodeId="id"
- nodeLabel={nodeLabel}
- // Pan + zoom + drag — all interactions enabled so the user
- // can move freely. NO bounding box — the previous bounding
- // box implementation created an "invisible wall" the user
- // could hit and we removed it deliberately.
- enablePanInteraction={true}
- enableZoomInteraction={true}
- enableNodeDrag={true}
- minZoom={0.1}
- maxZoom={8}
- onZoom={handleZoom}
- onZoomEnd={handleZoomEnd}
- onNodeDrag={handleNodeDrag}
- onBackgroundClick={handleBackgroundClick}
- onNodeHover={handleNodeHover}
- // The focus styling reads refs, so the library must paint every
- // frame while its loop runs; the loop itself is parked when idle
- // (see pauseRenderIfIdle), which is what keeps an idle map free.
- autoPauseRedraw={false}
- nodeRelSize={2}
- nodeVal={nodeVal}
- nodeColor={nodeColor}
- nodeCanvasObjectMode={nodeCanvasObjectMode}
- nodeCanvasObject={nodeCanvasObject}
- nodePointerAreaPaint={nodePointerAreaPaint}
- onRenderFramePost={drawLabels}
- linkLabel={linkLabel}
- linkColor={linkColor}
- linkWidth={linkWidth}
- linkLineDash={linkLineDash}
- linkDirectionalArrowLength={linkArrowLength}
- linkDirectionalArrowRelPos={0.82}
- linkDirectionalArrowColor={linkArrowColor}
- linkDirectionalParticles={linkParticles}
- linkDirectionalParticleSpeed={0.006}
- linkDirectionalParticleWidth={2.4}
- linkDirectionalParticleColor={linkParticleColor}
- // - velocityDecay 0.6: damp oscillation in dense graphs
- // - alphaDecay 0.04: settle time ~4s
- // - cooldownTicks 200: matches alphaDecay
- // - warmupTicks 40: enough pre-paint settling that the first
- // visible frame is already mostly in shape
- cooldownTicks={200}
- d3VelocityDecay={0.6}
- d3AlphaDecay={0.04}
- warmupTicks={40}
- onEngineTick={configureForces}
- onEngineStop={handleEngineStop}
- onNodeClick={handleNodeClick}
- />
- )}
- </div>
- );
-}
-
-export default WikiGraph;
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiInspector.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiInspector.tsx
deleted file mode 100644
index 86b10c557b..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiInspector.tsx
+++ /dev/null
@@ -1,701 +0,0 @@
-/**
- * The Wiki section's right rail.
- *
- * With no page open it answers "is my memory working, and what is in it":
- * the subsystem's health in one sentence, the last day's capture as a flow
- * from conversations reviewed to facts written, and the pages everything
- * else hangs off. With a page open it answers "where does this page sit":
- * what links to it, what it links to, and its vital facts.
- *
- * "Honest, not silent" still holds — a failed bootstrap, a failed write, a
- * backlog or a stale index is stated here in words, with the fix beside it.
- */
-import { useMemo, type ReactNode } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { Activity, ArrowUpRight, FileText, RefreshCw } from "lucide-react";
-
-import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
-import { useRunLocale } from "@/components/runs/format";
-import {
- fetchWikiBacklinks,
- fetchWikiGraph,
- fetchWikiPage,
- type WikiCaptureFunnel,
- type WikiHealthSnapshot,
-} from "@/lib/wikiApi";
-import {
- GROUP_LABEL_KEY,
- cleanTitle,
- degreeOf,
- groupOfKind,
- readableSnippet,
- relativeAge,
- uniqueEdges,
- type LibraryItem,
-} from "@/lib/wikiModel";
-import { KindGlyph } from "@/components/wiki/KindGlyph";
-import { WIKI_INSPECTOR_ID } from "@/store/wikiPanel";
-
-export type WikiHealthVisual = "green" | "amber" | "red" | "unknown";
-
-// The three status hues and nothing else. "unknown" is the ONLY state allowed
-// to be neutral — an "ok" that renders dimmer than an "unknown" inverts the ramp.
-export const HEALTH_DOT_STYLE: Record<WikiHealthVisual, string> = {
- green: "bg-success",
- amber: "bg-warning",
- red: "bg-destructive",
- unknown: "bg-faint-foreground",
-};
-
-export const HEALTH_LABEL_KEY: Record<WikiHealthVisual, string> = {
- green: "wiki_ui.health_green",
- amber: "wiki_ui.health_amber",
- red: "wiki_ui.health_red",
- unknown: "wiki_ui.health_unknown",
-};
-
-export function classifyWikiHealth(health: WikiHealthSnapshot): WikiHealthVisual {
- if (
- health.bootstrap_ok === false ||
- health.last_write?.ok === false ||
- health.last_chain_failure
- ) {
- return "red";
- }
- if (
- health.journal_backlog > 0 ||
- health.vault_legacy_conflict ||
- health.index_state === "stale"
- ) {
- return "amber";
- }
- // `last_write?.ok === false` and `last_chain_failure` are both ruled out
- // above, so the remaining green condition collapses to `bootstrap_ok`.
- if (health.bootstrap_ok) {
- return "green";
- }
- // bootstrap_ok is null (never run yet) and nothing else flagged a problem —
- // neither a clean pass nor a known failure, so stay neutral rather than
- // claim "green" for a state we haven't actually verified.
- return "unknown";
-}
-
-function describeWikiWriteStatus(
- health: WikiHealthSnapshot,
- t: (key: string) => string,
-): string {
- if (health.bootstrap_ok === false) {
- return health.bootstrap_error
- ? t("wiki_health.bootstrap_failed").replace("{0}", health.bootstrap_error)
- : t("wiki_health.bootstrap_failed_unknown");
- }
- if (health.last_chain_failure) {
- return t("wiki_health.chain_failure").replace("{0}", health.last_chain_failure.detail);
- }
- if (health.last_write?.ok === false) {
- return health.last_write.error
- ? t("wiki_health.last_write_failed").replace("{0}", health.last_write.error)
- : t("wiki_health.last_write_failed_unknown");
- }
- if (health.last_write?.ok) {
- const page = health.last_write.pages.join(", ") || health.last_write.source;
- return t("wiki_health.last_write_ok").replace("{0}", page);
- }
- if (health.journal_backlog > 0) {
- return t("wiki_health.pending_writes").replace("{0}", String(health.journal_backlog));
- }
- return t("wiki_health.no_writes_yet");
-}
-
-export interface WikiInspectorProps {
- selectedSlug: string | null;
- itemsBySlug: ReadonlyMap<string, LibraryItem>;
- health: WikiHealthSnapshot | null | undefined;
- healthLoading: boolean;
- isReindexing: boolean;
- reindexError: string | null;
- onReindex: () => void;
- onSelect: (slug: string) => void;
-}
-
-export function WikiInspector(props: WikiInspectorProps) {
- const t = useT();
- const onPage = Boolean(props.selectedSlug);
- const HeadIcon = onPage ? FileText : Activity;
- // The Agentic IDE's side panel, in the Wiki: one step lighter than the
- // stage, a rule on its left edge, and a 44 px head that lines up with the
- // stage's own tab bar so the two read as one row.
- return (
- <aside
- id={WIKI_INSPECTOR_ID}
- className="flex h-full min-h-0 w-[300px] shrink-0 flex-col border-l border-border bg-card/40"
- data-testid={onPage ? "wiki-inspector-page" : "wiki-backlinks-placeholder"}
- aria-label={t("wiki_ui.inspector_label")}
- >
- <div className="flex h-11 shrink-0 items-center gap-2 border-b border-border px-4 text-sm font-medium text-foreground">
- <HeadIcon className="h-4 w-4 text-muted-foreground" aria-hidden />
- {t(onPage ? "wiki_ui.inspector_page" : "wiki_ui.inspector_overview")}
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto">
- {props.selectedSlug ? (
- <PageContext
- slug={props.selectedSlug}
- itemsBySlug={props.itemsBySlug}
- onSelect={props.onSelect}
- />
- ) : (
- <Overview {...props} />
- )}
- </div>
- </aside>
- );
-}
-
-/* ------------------------------------------------------------------------ */
-/* Overview */
-/* ------------------------------------------------------------------------ */
-
-function Overview({
- health,
- healthLoading,
- isReindexing,
- reindexError,
- onReindex,
- onSelect,
- itemsBySlug,
-}: WikiInspectorProps) {
- return (
- <div className="flex flex-col">
- <HealthBlock
- health={health}
- isLoading={healthLoading}
- isReindexing={isReindexing}
- reindexError={reindexError}
- onReindex={onReindex}
- />
- {health?.capture_funnel && (
- <CaptureFlow funnel={health.capture_funnel} error={health.capture_error} />
- )}
- <HubsBlock onSelect={onSelect} itemsBySlug={itemsBySlug} />
- </div>
- );
-}
-
-function Block({
- title,
- aside,
- children,
- testId,
- ariaLabel,
-}: {
- title: string;
- aside?: ReactNode;
- children: ReactNode;
- testId?: string;
- ariaLabel?: string;
-}) {
- return (
- <section
- className="border-b border-border px-5 py-5 last:border-b-0"
- data-testid={testId}
- aria-label={ariaLabel}
- >
- <header className="mb-3 flex items-baseline justify-between gap-3">
- <h2 className="text-base font-semibold text-foreground-strong">{title}</h2>
- {aside && <div className="shrink-0 whitespace-nowrap text-sm text-foreground-faint">{aside}</div>}
- </header>
- {children}
- </section>
- );
-}
-
-function HealthBlock({
- health,
- isLoading,
- isReindexing,
- reindexError,
- onReindex,
-}: {
- health: WikiHealthSnapshot | null | undefined;
- isLoading: boolean;
- isReindexing: boolean;
- reindexError: string | null;
- onReindex: () => void;
-}) {
- const t = useT();
-
- if (isLoading) {
- return (
- <Block title={t("wiki_ui.health_title")} testId="wiki-health-strip">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <span
- className="h-2 w-2 shrink-0 animate-pulse rounded-full bg-faint-foreground"
- data-testid="wiki-health-dot"
- data-visual="loading"
- aria-hidden
- />
- <span data-testid="wiki-health-checking">{t("wiki_health.checking")}</span>
- </div>
- </Block>
- );
- }
-
- if (!health) {
- return (
- <Block title={t("wiki_ui.health_title")} testId="wiki-health-strip">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <span
- className="h-2 w-2 shrink-0 rounded-full bg-faint-foreground"
- data-testid="wiki-health-dot"
- data-visual="unknown"
- aria-hidden
- />
- <span data-testid="wiki-health-unavailable">{t("wiki_health.unavailable")}</span>
- </div>
- </Block>
- );
- }
-
- const visual = classifyWikiHealth(health);
- const vaultText = health.vault_root
- ? t("wiki_health.vault_prefix").replace("{0}", health.vault_root)
- : t("wiki_health.vault_unknown");
-
- return (
- <Block title={t("wiki_ui.health_title")} testId="wiki-health-strip">
- <div className="flex items-center gap-2">
- <span className="relative flex h-2 w-2 shrink-0" aria-hidden>
- {visual === "green" && (
- <span className="absolute inset-0 animate-ping rounded-full bg-success opacity-40 motion-reduce:hidden" />
- )}
- <span
- className={cn("relative h-2 w-2 rounded-full", HEALTH_DOT_STYLE[visual])}
- data-testid="wiki-health-dot"
- data-visual={visual}
- />
- </span>
- <span className="text-base font-medium text-foreground">{t(HEALTH_LABEL_KEY[visual])}</span>
- </div>
- <p
- data-testid="wiki-health-write"
- className={cn(
- "mt-2 break-words text-sm",
- visual === "red" ? "text-destructive" : "text-muted-foreground",
- )}
- >
- {describeWikiWriteStatus(health, t)}
- </p>
-
- {(health.journal_backlog > 0 ||
- health.index_state === "stale" ||
- health.vault_legacy_conflict) && (
- <div className="mt-3 flex flex-wrap items-center gap-2 text-sm">
- {health.journal_backlog > 0 && (
- <Badge testId="wiki-health-backlog">
- {t("wiki_health.backlog_count").replace("{0}", String(health.journal_backlog))}
- </Badge>
- )}
- {health.index_state === "stale" && (
- <>
- <Badge testId="wiki-health-index-stale">
- {t("wiki_health.index_stale")
- .replace("{0}", String(health.indexed_pages))
- .replace("{1}", String(health.vault_pages))}
- </Badge>
- <button
- type="button"
- onClick={onReindex}
- disabled={isReindexing}
- data-testid="wiki-health-reindex"
- className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border-strong px-2.5 text-sm font-medium text-foreground transition-colors hover:bg-secondary disabled:opacity-50"
- >
- <RefreshCw className={cn("h-3 w-3", isReindexing && "animate-spin")} aria-hidden />
- {t(isReindexing ? "wiki_health.reindexing" : "wiki_health.reindex")}
- </button>
- </>
- )}
- {health.vault_legacy_conflict && (
- <Badge testId="wiki-health-legacy-conflict">{t("wiki_health.legacy_conflict")}</Badge>
- )}
- </div>
- )}
- {reindexError && (
- <p role="alert" data-testid="wiki-health-reindex-error" className="mt-2 text-sm text-destructive">
- {t("wiki_health.reindex_failed_detail").replace("{0}", reindexError)}
- </p>
- )}
-
- <p
- data-testid="wiki-health-vault"
- className="mt-3 truncate font-mono text-xs text-foreground-faint"
- title={vaultText}
- >
- {vaultText}
- </p>
- </Block>
- );
-}
-
-function Badge({ children, testId }: { children: ReactNode; testId: string }) {
- return (
- <span
- data-testid={testId}
- className="inline-flex h-6 items-center rounded-sm bg-warning/10 px-2 text-xs font-medium text-warning"
- >
- {children}
- </span>
- );
-}
-
-/**
- * The last day's capture as a flow: each stage a bar measured against the
- * conversations reviewed, so the drop-off between "looked at" and "written"
- * is visible at a glance. The quieter outcomes follow as a ledger.
- */
-function CaptureFlow({
- funnel,
- error,
-}: {
- funnel: WikiCaptureFunnel;
- error: string | null | undefined;
-}) {
- const t = useT();
- const windowHours = Math.max(1, Math.round(funnel.window_hours));
- const stages = [
- ["reviewed", t("wiki_health.capture_reviewed"), funnel.total],
- ["candidate-reviews", t("wiki_health.capture_candidate_reviews"), funnel.candidates],
- ["candidate-facts", t("wiki_health.capture_candidate_facts"), funnel.facts],
- ["writes", t("wiki_health.capture_writes"), funnel.writes],
- ] as const;
- const ledger = [
- ["noop", t("wiki_health.capture_noop"), funnel.stage2_noop],
- ["rejected", t("wiki_health.capture_rejected"), funnel.stage2_rejected],
- ["skipped", t("wiki_health.capture_skipped"), funnel.stage2_skipped],
- ["pending", t("wiki_health.capture_pending"), funnel.stage2_pending],
- ["filtered", t("wiki_health.capture_filtered"), funnel.filtered],
- ["empty", t("wiki_health.capture_empty"), funnel.empty],
- ["failed", t("wiki_health.capture_failed"), funnel.failed],
- ["in-progress", t("wiki_health.capture_in_progress"), funnel.started],
- ["session-sweeps", t("wiki_health.capture_session_sweeps"), funnel.sessions_swept],
- ] as const;
- const scale = Math.max(1, ...stages.map(([, , value]) => value));
- const errorText =
- error === "capture_store_unavailable"
- ? t("wiki_health.capture_store_unavailable")
- : error
- ? t("wiki_health.capture_store_error").replace("{0}", error)
- : null;
- const quiet = !error && funnel.total === 0 && funnel.started === 0;
-
- return (
- <Block
- title={t("wiki_ui.capture_title")}
- aside={t("wiki_ui.capture_window").replace("{0}", String(windowHours))}
- testId="wiki-capture-funnel"
- ariaLabel={t("wiki_health.capture_aria").replace("{0}", String(windowHours))}
- >
- {errorText && (
- <p className="mb-3 text-sm text-destructive" data-testid="wiki-capture-error" role="alert">
- {errorText}
- </p>
- )}
- {!error && funnel.failed > 0 && (
- <p className="mb-3 text-sm text-destructive" data-testid="wiki-capture-failed-detail" role="status">
- {t("wiki_health.capture_failed_detail").replace("{0}", String(funnel.failed))}
- </p>
- )}
- {quiet && (
- <p className="mb-3 text-sm text-muted-foreground" data-testid="wiki-capture-quiet">
- {t("wiki_ui.capture_quiet")}
- </p>
- )}
-
- <ol className="space-y-2.5">
- {stages.map(([key, label, value], index) => {
- const last = index === stages.length - 1;
- return (
- <li key={key} data-testid={`wiki-capture-${key}`}>
- <div className="flex items-baseline justify-between gap-3 text-sm">
- <span className="text-muted-foreground">{label}</span>
- <span className="tabular-nums text-foreground">{value}</span>
- </div>
- <div className="mt-1 h-1 overflow-hidden rounded-full bg-foreground/10">
- <div
- className={cn(
- "h-full rounded-full transition-[width] duration-500",
- last ? "bg-accent" : "bg-foreground/45",
- )}
- style={{ width: `${value > 0 ? Math.max(2, (value / scale) * 100) : 0}%` }}
- />
- </div>
- </li>
- );
- })}
- </ol>
-
- <dl className="mt-4 space-y-1 border-t border-border pt-3 text-sm">
- {ledger.map(([key, label, value]) => {
- const alarm = key === "failed" && value > 0;
- return (
- <div
- key={key}
- className={cn("flex items-baseline gap-2", alarm && "text-destructive")}
- data-testid={`wiki-capture-${key}`}
- >
- <dt className={alarm ? undefined : "text-muted-foreground"}>{label}</dt>
- <span aria-hidden className="mb-1 min-w-4 flex-1 border-b border-dotted border-border-strong" />
- <dd className={cn("tabular-nums", alarm ? "text-destructive" : value > 0 ? "text-foreground" : "text-foreground-faint")}>
- {value}
- </dd>
- </div>
- );
- })}
- </dl>
- </Block>
- );
-}
-
-/** The pages most others hang off — the vault's load-bearing pages. */
-function HubsBlock({
- onSelect,
- itemsBySlug,
-}: {
- onSelect: (slug: string) => void;
- itemsBySlug: ReadonlyMap<string, LibraryItem>;
-}) {
- const t = useT();
- const { data, isLoading } = useQuery({
- queryKey: ["wiki", "graph"],
- queryFn: fetchWikiGraph,
- staleTime: 30_000,
- });
-
- const hubs = useMemo(() => {
- if (!data?.ok || !data.nodes) return [];
- const degree = degreeOf(uniqueEdges(data.edges ?? []));
- return data.nodes
- .map((node) => ({
- slug: node.id,
- title: cleanTitle(node.title, node.id),
- group: groupOfKind(node.kind),
- degree: degree.get(node.id) ?? 0,
- }))
- .filter((node) => node.degree > 0)
- .sort((a, b) => b.degree - a.degree)
- .slice(0, 6);
- }, [data]);
-
- if (!isLoading && hubs.length === 0) return null;
- const top = hubs[0]?.degree ?? 1;
-
- return (
- <Block title={t("wiki_ui.hubs_title")} testId="wiki-inspector-hubs">
- {isLoading ? (
- <div className="space-y-2" aria-busy="true">
- {[80, 64, 52].map((w) => (
- <div key={w} className="h-4 animate-pulse rounded-sm bg-foreground/10" style={{ width: `${w}%` }} />
- ))}
- </div>
- ) : (
- <ul className="-mx-2 space-y-px">
- {hubs.map((hub) => (
- <li key={hub.slug}>
- <button
- type="button"
- onClick={() => onSelect(hub.slug)}
- className="group flex w-full flex-col gap-1 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-secondary"
- data-testid="wiki-hub-item"
- >
- <span className="flex w-full items-center gap-2 text-sm">
- <KindGlyph group={itemsBySlug.get(hub.slug)?.group ?? hub.group} className="h-2.5 w-2.5 text-foreground-faint" />
- <span className="min-w-0 flex-1 truncate text-foreground">{hub.title}</span>
- <span className="tabular-nums text-foreground-faint">{hub.degree}</span>
- </span>
- <span className="ml-[18px] block h-0.5 overflow-hidden rounded-full bg-foreground/[0.06]">
- <span
- className="block h-full rounded-full bg-foreground/30 transition-colors group-hover:bg-accent"
- style={{ width: `${(hub.degree / top) * 100}%` }}
- />
- </span>
- </button>
- </li>
- ))}
- </ul>
- )}
- </Block>
- );
-}
-
-/* ------------------------------------------------------------------------ */
-/* Page context */
-/* ------------------------------------------------------------------------ */
-
-function PageContext({
- slug,
- itemsBySlug,
- onSelect,
-}: {
- slug: string;
- itemsBySlug: ReadonlyMap<string, LibraryItem>;
- onSelect: (slug: string) => void;
-}) {
- const t = useT();
- const language = useRunLocale();
- const backlinksQuery = useQuery({
- queryKey: ["wiki", "backlinks", slug],
- queryFn: () => fetchWikiBacklinks(slug),
- staleTime: 5_000,
- });
- const pageQuery = useQuery({
- queryKey: ["wiki", "page", slug],
- queryFn: () => fetchWikiPage(slug),
- staleTime: 5_000,
- });
-
- const backlinks = (backlinksQuery.data?.backlinks ?? []).filter((bl) => bl.slug !== slug);
- const outgoing = useMemo(() => {
- const seen = new Set<string>();
- const out: string[] = [];
- for (const link of pageQuery.data?.wikilinks ?? []) {
- if (!link || link === slug || seen.has(link)) continue;
- seen.add(link);
- out.push(link);
- }
- return out;
- }, [pageQuery.data?.wikilinks, slug]);
-
- const page = pageQuery.data?.ok ? pageQuery.data : null;
- const item = itemsBySlug.get(slug);
- const facts: Array<[string, string]> = [];
- if (page) {
- facts.push([t("wiki_ui.fact_kind"), t(GROUP_LABEL_KEY[item?.group ?? groupOfKind(page.kind)])]);
- if (item?.folder) facts.push([t("wiki_ui.fact_folder"), item.folder]);
- if (page.stats?.words !== undefined)
- facts.push([t("wiki_ui.fact_words"), new Intl.NumberFormat(language).format(page.stats.words)]);
- if (page.stats?.mtime) facts.push([t("wiki_ui.fact_changed"), relativeAge(page.stats.mtime, language)]);
- }
-
- return (
- <div className="flex flex-col">
- <Block
- title={t("wiki_ui.linked_from")}
- aside={backlinksQuery.isLoading ? undefined : String(backlinks.length)}
- testId="wiki-backlinks-panel"
- >
- {backlinksQuery.isLoading && <LineSkeleton />}
- {backlinksQuery.isError && (
- <p role="alert" className="text-sm text-destructive">
- {t("backlinks_panel.load_error")}
- </p>
- )}
- {!backlinksQuery.isLoading && !backlinksQuery.isError && backlinks.length === 0 && (
- <p className="text-sm text-muted-foreground" data-testid="wiki-backlinks-empty">
- {t("wiki_ui.linked_from_empty")}
- </p>
- )}
- {backlinks.length > 0 && (
- <ul className="-mx-2 space-y-px">
- {backlinks.map((bl) => {
- const snippet = bl.snippet ? readableSnippet(bl.snippet) : "";
- return (
- <li key={bl.slug}>
- <button
- type="button"
- onClick={() => onSelect(bl.slug)}
- className="flex w-full items-start gap-2.5 rounded-md px-2 py-2 text-left transition-colors hover:bg-secondary"
- data-testid="wiki-backlink-item"
- data-target-slug={bl.slug}
- >
- <KindGlyph
- group={itemsBySlug.get(bl.slug)?.group ?? "other"}
- className="mt-1 h-2.5 w-2.5 text-foreground-faint"
- />
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm text-foreground">
- {cleanTitle(bl.title, bl.slug)}
- </span>
- {snippet && (
- <span className="mt-0.5 line-clamp-2 block text-xs leading-4 text-muted-foreground">
- {snippet}
- </span>
- )}
- </span>
- </button>
- </li>
- );
- })}
- </ul>
- )}
- </Block>
-
- <Block
- title={t("wiki_ui.links_to")}
- aside={pageQuery.isLoading ? undefined : String(outgoing.length)}
- testId="wiki-outgoing-panel"
- >
- {pageQuery.isLoading && <LineSkeleton />}
- {!pageQuery.isLoading && outgoing.length === 0 && (
- <p className="text-sm text-muted-foreground">{t("wiki_ui.links_to_empty")}</p>
- )}
- {outgoing.length > 0 && (
- <ul className="-mx-2 space-y-px">
- {outgoing.map((target) => {
- const known = itemsBySlug.get(target);
- return (
- <li key={target}>
- {known ? (
- <button
- type="button"
- onClick={() => onSelect(target)}
- className="group flex h-8 w-full items-center gap-2.5 rounded-md px-2 text-left text-sm text-foreground transition-colors hover:bg-secondary"
- data-testid="wiki-outgoing-item"
- >
- <KindGlyph group={known.group} className="h-2.5 w-2.5 text-foreground-faint" />
- <span className="min-w-0 flex-1 truncate">{known.title}</span>
- <ArrowUpRight className="h-3 w-3 shrink-0 text-foreground-faint opacity-0 transition-opacity group-hover:opacity-100" aria-hidden />
- </button>
- ) : (
- <span
- className="flex h-8 items-center gap-2.5 px-2 text-sm text-foreground-faint"
- title={t("wiki_ui.link_missing")}
- data-testid="wiki-outgoing-missing"
- >
- <span className="h-2.5 w-2.5 shrink-0 rounded-full border border-dashed border-current" aria-hidden />
- <span className="min-w-0 flex-1 truncate line-through decoration-foreground-faint/60">{target}</span>
- </span>
- )}
- </li>
- );
- })}
- </ul>
- )}
- </Block>
-
- {facts.length > 0 && (
- <Block title={t("wiki_ui.facts_title")} testId="wiki-page-facts">
- <dl className="space-y-1.5 text-sm">
- {facts.map(([label, value]) => (
- <div key={label} className="flex items-baseline gap-2">
- <dt className="text-muted-foreground">{label}</dt>
- <span aria-hidden className="mb-1 min-w-4 flex-1 border-b border-dotted border-border-strong" />
- <dd className="max-w-[60%] truncate text-foreground" title={value}>
- {value}
- </dd>
- </div>
- ))}
- </dl>
- </Block>
- )}
- </div>
- );
-}
-
-function LineSkeleton() {
- return (
- <div className="space-y-2" aria-busy="true">
- <div className="h-4 w-3/4 animate-pulse rounded-sm bg-foreground/10" />
- <div className="h-4 w-1/2 animate-pulse rounded-sm bg-foreground/10" />
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiInspectorToggle.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiInspectorToggle.tsx
deleted file mode 100644
index 99b14bf8e4..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiInspectorToggle.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { PanelRightClose, PanelRightOpen } from "lucide-react";
-
-import { useT } from "@/i18n";
-import { cn } from "@/lib/utils";
-import { WIKI_INSPECTOR_ID, useWikiPanelStore } from "@/store/wikiPanel";
-
-/**
- * Opens and shuts the Wiki section's right-hand inspector from the window
- * caption — the same place and the same glyph as the Agentic IDE's side-panel
- * toggle, so the two sections share one habit. Kept free of the Wiki's own
- * modules: the caption is in the startup chunk.
- */
-export function WikiInspectorToggle({ className }: { className?: string }) {
- const t = useT();
- const open = useWikiPanelStore((state) => state.open);
- const setOpen = useWikiPanelStore((state) => state.setOpen);
- const label = t(open ? "wiki_ui.inspector_collapse" : "wiki_ui.inspector_expand");
- const Icon = open ? PanelRightClose : PanelRightOpen;
- return (
- <button
- type="button"
- onClick={() => setOpen(!open)}
- title={label}
- aria-label={label}
- aria-expanded={open}
- aria-controls={WIKI_INSPECTOR_ID}
- data-testid="wiki-inspector-toggle"
- className={cn(
- "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md",
- "text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- open && "text-foreground",
- className,
- )}
- >
- <Icon aria-hidden className="h-4 w-4" />
- </button>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiLibrary.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiLibrary.tsx
deleted file mode 100644
index 21ab913f5a..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiLibrary.tsx
+++ /dev/null
@@ -1,266 +0,0 @@
-/**
- * The Wiki section's left rail: every page in the vault, findable in one
- * glance.
- *
- * A filter field on top narrows every group at once as you type. With no
- * filter, the five most recently changed pages lead — what the assistant
- * learned last is usually what you came to look at. Below them the vault's
- * folders are regrouped by what a page IS (people and things, projects,
- * agents' notebooks, system pages), each with the shape the memory map draws
- * it as, so the list and the map share one visual vocabulary.
- */
-import { useMemo, useState, type ReactNode } from "react";
-import { ChevronRight, Search, X } from "lucide-react";
-
-import { cn } from "@/lib/utils";
-import { useRunLocale } from "@/components/runs/format";
-import { useT } from "@/i18n";
-import type { WikiTreeFolder } from "@/lib/wikiApi";
-import {
- GROUP_LABEL_KEY,
- compactAge,
- libraryGroups,
- libraryItems,
- matchesFilter,
- recentItems,
- type LibraryItem,
- type WikiGroupId,
-} from "@/lib/wikiModel";
-import { KindGlyph } from "@/components/wiki/KindGlyph";
-
-const DEFAULT_OPEN: ReadonlySet<WikiGroupId> = new Set(["entity", "project", "concept"]);
-
-export interface WikiLibraryProps {
- folders: readonly WikiTreeFolder[];
- isLoading: boolean;
- isError: boolean;
- selectedSlug: string | null;
- onSelect: (slug: string) => void;
- /** Drawn above the filter: the section's title, stats and search. */
- header?: ReactNode;
-}
-
-export function WikiLibrary({
- folders,
- isLoading,
- isError,
- selectedSlug,
- onSelect,
- header,
-}: WikiLibraryProps) {
- const t = useT();
- const language = useRunLocale();
- const [query, setQuery] = useState("");
- const [openGroups, setOpenGroups] = useState<Set<WikiGroupId>>(() => new Set(DEFAULT_OPEN));
-
- const items = useMemo(() => libraryItems(folders), [folders]);
- const filtered = useMemo(
- () => (query.trim() ? items.filter((item) => matchesFilter(item, query)) : items),
- [items, query],
- );
- const groups = useMemo(() => libraryGroups(filtered), [filtered]);
- const recent = useMemo(() => recentItems(items, 5), [items]);
- const filtering = query.trim().length > 0;
- // One clock per render of the list, so every row ages against the same now.
- const now = Date.now();
-
- const toggle = (id: WikiGroupId) =>
- setOpenGroups((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
-
- return (
- <aside
- className="flex h-full min-h-0 w-[264px] shrink-0 flex-col"
- data-testid="wiki-tree-sidebar"
- aria-label={t("wiki_ui.library_label")}
- >
- {header}
- <div className="shrink-0 px-3 pb-2">
- <div className="relative">
- <Search
- className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-faint"
- aria-hidden
- />
- <input
- type="search"
- value={query}
- onChange={(event) => setQuery(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === "Escape") setQuery("");
- }}
- placeholder={t("wiki_ui.filter_placeholder")}
- aria-label={t("wiki_ui.filter_placeholder")}
- data-testid="wiki-library-filter"
- className={cn(
- "h-8 w-full rounded-lg border border-transparent bg-transparent pl-8 pr-7 text-sm text-foreground hover:bg-secondary/60",
- "placeholder:text-foreground-faint [&::-webkit-search-cancel-button]:hidden",
- "transition-colors focus-visible:border-border focus-visible:bg-input focus-visible:outline-none",
- )}
- />
- {filtering && (
- <button
- type="button"
- onClick={() => setQuery("")}
- aria-label={t("wiki_ui.filter_clear")}
- className="absolute right-1.5 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-sm text-foreground-faint hover:bg-secondary hover:text-foreground"
- >
- <X className="h-3 w-3" aria-hidden />
- </button>
- )}
- </div>
- </div>
-
- <nav className="min-h-0 flex-1 overflow-y-auto px-2 pb-3" data-testid="wiki-library-list">
- {isLoading && <LibrarySkeleton />}
- {isError && (
- <p role="alert" className="px-2 py-2 text-sm text-destructive">
- {t("tree_sidebar.load_error")}
- </p>
- )}
-
- {!isLoading && !isError && (
- <>
- {!filtering && recent.length > 0 && (
- <Section label={t("wiki_ui.recent")} testId="wiki-library-recent">
- {recent.map((item) => (
- <Row
- key={`recent:${item.folder}/${item.slug}`}
- item={item}
- age={compactAge(item.mtime, language, now)}
- active={item.slug === selectedSlug}
- onSelect={onSelect}
- testId="wiki-library-recent-item"
- />
- ))}
- </Section>
- )}
-
- {groups.map((group) => {
- const open = filtering || openGroups.has(group.id);
- return (
- <div key={group.id} className="mt-3 first:mt-0" data-folder={group.id}>
- <button
- type="button"
- onClick={() => toggle(group.id)}
- disabled={filtering}
- aria-expanded={open}
- data-open={open ? "true" : "false"}
- className={cn(
- "group flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-sm font-medium text-foreground-faint transition-colors",
- !filtering && "hover:text-foreground",
- )}
- >
- <ChevronRight
- className={cn("h-3 w-3 shrink-0 transition-transform", open && "rotate-90")}
- aria-hidden
- />
- <span className="flex-1 truncate text-left">{t(GROUP_LABEL_KEY[group.id])}</span>
- <span className="tabular-nums">{group.items.length}</span>
- </button>
- {open && (
- <ul className="mt-0.5 space-y-px" data-testid={`wiki-folder-${group.id}`}>
- {group.items.map((item) => (
- <li key={`${item.folder}/${item.slug}`}>
- <Row
- item={item}
- age={compactAge(item.mtime, language, now)}
- active={item.slug === selectedSlug}
- onSelect={onSelect}
- />
- </li>
- ))}
- </ul>
- )}
- </div>
- );
- })}
-
- {filtering && groups.length === 0 && (
- <p className="px-2 py-6 text-center text-sm text-muted-foreground" data-testid="wiki-library-no-match">
- {t("wiki_ui.filter_no_match")}
- </p>
- )}
- </>
- )}
- </nav>
- </aside>
- );
-}
-
-function Section({
- label,
- testId,
- children,
-}: {
- label: string;
- testId: string;
- children: ReactNode;
-}) {
- return (
- <div className="mb-1" data-testid={testId}>
- <div className="flex h-7 items-center px-2 text-sm font-medium text-foreground-faint">
- {label}
- </div>
- <div className="space-y-px">{children}</div>
- </div>
- );
-}
-
-function Row({
- item,
- age,
- active,
- onSelect,
- testId,
-}: {
- item: LibraryItem;
- age: string;
- active: boolean;
- onSelect: (slug: string) => void;
- testId?: string;
-}) {
- return (
- <button
- type="button"
- onClick={() => onSelect(item.slug)}
- data-slug={item.slug}
- data-active={active ? "true" : "false"}
- data-testid={testId}
- title={item.title}
- className={cn(
- "flex h-8 w-full items-center gap-2.5 rounded-lg px-2 text-left text-base transition-colors",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- active
- ? "bg-secondary text-foreground-strong"
- : "text-foreground-secondary hover:bg-secondary hover:text-foreground",
- )}
- >
- <KindGlyph
- group={item.group}
- className={cn("h-2.5 w-2.5", active ? "text-accent" : "text-foreground-faint")}
- />
- <span className="min-w-0 flex-1 truncate">{item.title}</span>
- {age && (
- <span className="shrink-0 text-xs tabular-nums text-foreground-faint">{age}</span>
- )}
- </button>
- );
-}
-
-function LibrarySkeleton() {
- return (
- <div className="space-y-2 px-2 py-2" data-testid="wiki-tree-skeleton" aria-busy="true">
- {[72, 56, 64, 48, 60, 52].map((width, i) => (
- <div
- key={i}
- className="h-4 animate-pulse rounded-sm bg-foreground/10"
- style={{ width: `${width}%` }}
- />
- ))}
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx
deleted file mode 100644
index 6ea37febbd..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx
+++ /dev/null
@@ -1,352 +0,0 @@
-/**
- * Tests for the WikiSearch Ctrl-K command palette.
- *
- * Behaviour anchors:
- * 1. Ctrl-K opens the dialog.
- * 2. Typing fires a debounced fetch.
- * 3. Empty query shows the "Recent" section seeded from the tree cache.
- * 4. Clicking a result calls `onResultClick(slug)` and closes the dialog.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import type { PropsWithChildren } from "react";
-
-// jsdom does not ship `ResizeObserver`, but Radix Dialog (cmdk's underlying
-// Dialog) calls it on mount. Provide a no-op polyfill before importing the
-// component so the dialog can render under test.
-class ResizeObserverPolyfill {
- observe() {}
- unobserve() {}
- disconnect() {}
-}
-if (typeof (globalThis as { ResizeObserver?: unknown }).ResizeObserver === "undefined") {
- (globalThis as unknown as { ResizeObserver: typeof ResizeObserverPolyfill }).ResizeObserver =
- ResizeObserverPolyfill;
-}
-// Radix Dialog also uses `hasPointerCapture` / `scrollIntoView` which jsdom
-// lacks on Element.prototype.
-if (typeof Element !== "undefined") {
- if (!("hasPointerCapture" in Element.prototype)) {
- // @ts-expect-error -- jsdom shim
- Element.prototype.hasPointerCapture = () => false;
- }
- if (!("scrollIntoView" in Element.prototype)) {
- // @ts-expect-error -- jsdom shim
- Element.prototype.scrollIntoView = () => {};
- }
-}
-
-import { WikiSearch } from "@/components/wiki/WikiSearch";
-
-function makeClient(): QueryClient {
- return new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 0 } },
- });
-}
-
-function seedTreeCache(client: QueryClient) {
- client.setQueryData(["wiki", "tree"], {
- ok: true,
- vault_root: "wiki/obsidian-vault",
- folders: [
- {
- name: "entities",
- kind: "entity",
- count: 2,
- files: [
- { slug: "ruben", title: "Ruben", mtime: 2000, size: 412 },
- { slug: "harald", title: "Harald", mtime: 1000, size: 289 },
- ],
- },
- ],
- });
-}
-
-function Wrapper({ children, client }: PropsWithChildren<{ client: QueryClient }>) {
- return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
-}
-
-afterEach(() => {
- cleanup();
- vi.useRealTimers();
- vi.restoreAllMocks();
-});
-
-beforeEach(() => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
-});
-
-describe("WikiSearch", () => {
- it("opens the palette when Ctrl-K is pressed", async () => {
- const client = makeClient();
- seedTreeCache(client);
- render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={() => {}} />
- </Wrapper>,
- );
- expect(screen.queryByTestId("wiki-search-input")).toBeNull();
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- await waitFor(() => {
- expect(screen.getByTestId("wiki-search-input")).toBeDefined();
- });
- });
-
- it("typing fires a debounced fetch (200ms)", async () => {
- const fetchMock = vi.fn(async () =>
- new Response(
- JSON.stringify({ ok: true, query: "pizza", hits: [] }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- );
- vi.stubGlobal("fetch", fetchMock);
-
- const client = makeClient();
- seedTreeCache(client);
- render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={() => {}} />
- </Wrapper>,
- );
-
- // Open the palette.
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- const input = await screen.findByTestId("wiki-search-input");
-
- // Type rapidly: 'p', 'pi', 'pizza'.
- await act(async () => {
- fireEvent.change(input, { target: { value: "p" } });
- fireEvent.change(input, { target: { value: "pi" } });
- fireEvent.change(input, { target: { value: "pizza" } });
- });
-
- // Before debounce window expires, no fetch yet.
- expect(fetchMock).not.toHaveBeenCalled();
-
- // Advance past the 200 ms debounce.
- await act(async () => {
- vi.advanceTimersByTime(250);
- });
-
- await waitFor(() => {
- expect(fetchMock).toHaveBeenCalledTimes(1);
- });
- const firstCall = fetchMock.mock.calls[0] as unknown as [string | URL];
- const calledUrl = String(firstCall[0]);
- expect(calledUrl).toContain("/api/wiki/search");
- expect(calledUrl).toContain("q=pizza");
- });
-
- it("shows the Recent section seeded from the tree cache when query is empty", async () => {
- const client = makeClient();
- seedTreeCache(client);
- render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={() => {}} />
- </Wrapper>,
- );
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- await waitFor(() => {
- expect(screen.getByTestId("wiki-search-recent")).toBeDefined();
- });
- const items = screen.getAllByTestId("wiki-search-recent-item");
- expect(items).toHaveLength(2);
- // Sorted by mtime desc — ruben first (mtime=2000), harald second.
- expect(items[0].getAttribute("data-slug")).toBe("ruben");
- expect(items[1].getAttribute("data-slug")).toBe("harald");
- });
-
- it("renders every server hit, even when the slug does not match the query", async () => {
- // Regression: the palette let cmdk re-filter the results a second time,
- // scoring the query against the item value (`hit:<slug>`) instead of the
- // page text the backend actually matched. A multi-word search therefore
- // returned hits over the API and showed an empty list to the user.
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- query: "birthday party",
- hits: [
- {
- slug: "harald",
- title: "Harald",
- path: "entities/harald.md",
- snippet: "Plans the birthday party every year.",
- score: 1,
- },
- ],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
-
- const client = makeClient();
- seedTreeCache(client);
- render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={() => {}} />
- </Wrapper>,
- );
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- const input = await screen.findByTestId("wiki-search-input");
- await act(async () => {
- fireEvent.change(input, { target: { value: "birthday party" } });
- });
- await act(async () => {
- vi.advanceTimersByTime(250);
- });
-
- await waitFor(() => {
- const hits = screen.getAllByTestId("wiki-search-hit");
- expect(hits).toHaveLength(1);
- expect(hits[0].getAttribute("data-slug")).toBe("harald");
- });
- });
-
- it("labels a hit that semantic search found, and only that one", async () => {
- // Such a hit shares no word with the query, so nothing in its snippet is
- // highlighted; the label is what tells the reader why it is in the list.
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- query: "sister birthday",
- hits: [
- {
- slug: "party",
- title: "Party",
- path: "projects/party.md",
- snippet: "The birthday party is in May.",
- score: 0.8,
- by_meaning: false,
- },
- {
- slug: "anna",
- title: "Anna",
- path: "entities/anna.md",
- snippet: "Meine Schwester, Geburtstag am 4. Mai.",
- score: 0.7,
- by_meaning: true,
- },
- ],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
-
- const client = makeClient();
- render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={() => {}} />
- </Wrapper>,
- );
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- const input = await screen.findByTestId("wiki-search-input");
- await act(async () => {
- fireEvent.change(input, { target: { value: "sister birthday" } });
- });
- await act(async () => {
- vi.advanceTimersByTime(250);
- });
-
- await waitFor(() => expect(screen.getAllByTestId("wiki-search-hit")).toHaveLength(2));
- const labels = screen.getAllByTestId("wiki-search-by-meaning");
- expect(labels).toHaveLength(1);
- expect(labels[0].closest('[data-testid="wiki-search-hit"]')?.getAttribute("data-slug")).toBe(
- "anna",
- );
- });
-
- it("marks every occurrence of the query term in a snippet", async () => {
- // Regression: highlighting used `pattern.test(part)` with a /g regex,
- // whose `lastIndex` carried over between calls — so it alternated
- // true/false and marked plain words while leaving real matches plain.
- vi.stubGlobal(
- "fetch",
- vi.fn(async () =>
- new Response(
- JSON.stringify({
- ok: true,
- query: "pizza",
- hits: [
- {
- slug: "pizza",
- title: "Pizza",
- path: "concepts/pizza.md",
- snippet: "pizza on Friday and pizza on Sunday",
- score: 1,
- },
- ],
- }),
- { status: 200, headers: { "content-type": "application/json" } },
- ),
- ),
- );
-
- const client = makeClient();
- seedTreeCache(client);
- const { container } = render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={() => {}} />
- </Wrapper>,
- );
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- const input = await screen.findByTestId("wiki-search-input");
- await act(async () => {
- fireEvent.change(input, { target: { value: "pizza" } });
- });
- await act(async () => {
- vi.advanceTimersByTime(250);
- });
-
- await waitFor(() => {
- expect(screen.getAllByTestId("wiki-search-hit")).toHaveLength(1);
- });
- // cmdk renders the palette in a portal, so query the document body.
- const marks = Array.from(
- (container.ownerDocument ?? document).querySelectorAll("mark"),
- );
- expect(marks.map((m) => m.textContent)).toEqual(["pizza", "pizza"]);
- });
-
- it("clicking a result calls onResultClick(slug)", async () => {
- const client = makeClient();
- seedTreeCache(client);
- const onResultClick = vi.fn();
- render(
- <Wrapper client={client}>
- <WikiSearch onResultClick={onResultClick} />
- </Wrapper>,
- );
- await act(async () => {
- fireEvent.keyDown(window, { key: "k", ctrlKey: true });
- });
- await waitFor(() => {
- expect(screen.getByTestId("wiki-search-recent")).toBeDefined();
- });
- const items = screen.getAllByTestId("wiki-search-recent-item");
- await act(async () => {
- fireEvent.click(items[0]);
- });
- expect(onResultClick).toHaveBeenCalledWith("ruben");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
deleted file mode 100644
index 176c510b40..0000000000
--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx
+++ /dev/null
@@ -1,392 +0,0 @@
-// Ctrl-K command palette for the Wiki tab.
-//
-// Owned by Agent C of Phase B3. Wraps the `cmdk` command palette inside a
-// modal Dialog. Behaviour spec lives in docs/plans/b3/AGENT-C-graph-and-search.md
-// §5.
-//
-// * Ctrl-K (or Cmd-K on Mac) opens the palette globally while the Wiki tab
-// is mounted.
-// * Forward-ref exposes `open()` so the header search box (Agent B) can
-// trigger the palette on click.
-// * Empty query → "Recent" section listing the 5 most-recently-modified
-// pages from the existing `tree` query cache.
-// * Typing fires `/api/wiki/search?q=…&k=8` debounced 200 ms.
-// * Enter or click → `onResultClick(slug)` and closes the dialog.
-import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
-import { Command } from "cmdk";
-import { keepPreviousData, useQuery } from "@tanstack/react-query";
-
-import { Search } from "lucide-react";
-
-import { cleanTitle, groupOfKind, readableSnippet, type WikiGroupId } from "@/lib/wikiModel";
-import { KindGlyph } from "@/components/wiki/KindGlyph";
-import { useT } from "@/i18n";
-
-const SEARCH_DEBOUNCE_MS = 200;
-const SEARCH_LIMIT = 8;
-const RECENT_LIMIT = 5;
-
-interface SearchHit {
- slug: string;
- title: string;
- path: string;
- snippet: string;
- score: number;
- /** Found by semantic search, so the snippet has no query word to highlight. */
- by_meaning?: boolean;
-}
-
-interface SearchResponse {
- ok: boolean;
- query: string;
- hits: SearchHit[];
- error?: string;
-}
-
-interface TreeFile {
- slug: string;
- title: string;
- mtime: number;
- size: number;
-}
-
-interface TreeFolder {
- name: string;
- kind: string;
- count: number;
- files: TreeFile[];
-}
-
-interface TreeResponse {
- ok: boolean;
- vault_root: string;
- folders: TreeFolder[];
-}
-
-interface RecentEntry {
- slug: string;
- title: string;
- path: string;
- kind: string;
- mtime: number;
-}
-
-/** A search hit carries only its vault path; its top folder names the kind. */
-function groupOfPath(path: string): WikiGroupId {
- const top = path.split(/[\\/]/)[0] ?? "";
- if (top === "entities") return "entity";
- if (top === "projects") return "project";
- if (top === "concepts") return "concept";
- if (top === "sessions") return "session";
- if (top === "society") return "agent";
- return path.includes("/") ? "other" : "system";
-}
-
-async function fetchSearch(query: string): Promise<SearchResponse> {
- const url = `/api/wiki/search?q=${encodeURIComponent(query)}&k=${SEARCH_LIMIT}`;
- const res = await fetch(url);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
-}
-
-/**
- * Pull recent pages out of the existing tree cache so the empty-query state
- * shows something useful without firing another network request.
- */
-function selectRecentPages(tree: TreeResponse | undefined): RecentEntry[] {
- if (!tree?.ok) return [];
- const flat: RecentEntry[] = [];
- for (const folder of tree.folders) {
- for (const file of folder.files) {
- flat.push({
- slug: file.slug,
- title: file.title,
- path: `${folder.name}/${file.slug}.md`,
- kind: folder.kind,
- mtime: file.mtime,
- });
- }
- }
- flat.sort((a, b) => b.mtime - a.mtime);
- return flat.slice(0, RECENT_LIMIT);
-}
-
-/**
- * Build the highlight matcher for one query. Returns `null` when there is
- * nothing to highlight. Built once per query in the component rather than
- * once per snippet per render.
- */
-function buildHighlightPattern(query: string): RegExp | null {
- const trimmed = query.trim();
- if (!trimmed) return null;
- const terms = trimmed
- .split(/\s+/)
- .filter(Boolean)
- .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
- if (terms.length === 0) return null;
- return new RegExp(`(${terms.join("|")})`, "ig");
-}
-
-/**
- * Render a snippet with `<mark>` highlight wrapping for the matched terms.
- * Best-effort: case-insensitive word match; React escapes the text for us.
- */
-function highlightSnippet(snippet: string, pattern: RegExp | null): JSX.Element {
- if (!pattern || !snippet) return <>{snippet}</>;
- // `String.split` with exactly ONE capture group puts every captured
- // delimiter — i.e. every match — at an ODD index. Deriving the highlight
- // from the index is exact and free.
- //
- // It replaces a `pattern.test(part)` check that was quietly wrong: `test()`
- // on a /g regex advances `lastIndex` and resumes from there on the next
- // call, so consecutive calls alternated true/false. Real matches were left
- // unhighlighted and plain words got marked instead.
- const parts = snippet.split(pattern);
- return (
- <>
- {parts.map((part, idx) =>
- idx % 2 === 1 ? (
- <mark key={idx} className="rounded-sm bg-accent-soft text-foreground">
- {part}
- </mark>
- ) : (
- <span key={idx}>{part}</span>
- ),
- )}
- </>
- );
-}
-
-export interface WikiSearchProps {
- onResultClick: (slug: string) => void;
-}
-
-export interface WikiSearchHandle {
- open: () => void;
-}
-
-export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function WikiSearch(
- { onResultClick },
- ref,
-): JSX.Element {
- const t = useT();
- const [open, setOpen] = useState(false);
- const [rawQuery, setRawQuery] = useState("");
- const [debouncedQuery, setDebouncedQuery] = useState("");
-
- useImperativeHandle(ref, () => ({ open: () => setOpen(true) }), []);
-
- // Ctrl-K / Cmd-K global trigger.
- useEffect(() => {
- function onKeyDown(event: KeyboardEvent) {
- const isOpenCombo =
- event.key.toLowerCase() === "k" && (event.ctrlKey || event.metaKey);
- if (isOpenCombo) {
- event.preventDefault();
- setOpen((prev) => !prev);
- }
- }
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, []);
-
- // Debounce input → query that actually fires the fetch.
- useEffect(() => {
- const handle = window.setTimeout(() => setDebouncedQuery(rawQuery.trim()), SEARCH_DEBOUNCE_MS);
- return () => window.clearTimeout(handle);
- }, [rawQuery]);
-
- // Reset on close so the next open starts fresh.
- useEffect(() => {
- if (!open) {
- setRawQuery("");
- setDebouncedQuery("");
- }
- }, [open]);
-
- const enabled = open && debouncedQuery.length > 0;
- const { data, isFetching, isError, refetch } = useQuery({
- queryKey: ["wiki", "search", debouncedQuery],
- queryFn: () => fetchSearch(debouncedQuery),
- enabled,
- staleTime: 10_000,
- // Keep the previous query's hits on screen while the next one is in
- // flight. Without this every keystroke tore the list down to a
- // "Searching…" placeholder and rebuilt it, which read as typing lag even
- // though the request itself was fast.
- placeholderData: keepPreviousData,
- });
-
- const highlightPattern = useMemo(
- () => buildHighlightPattern(debouncedQuery),
- [debouncedQuery],
- );
-
- // Read the tree through the query cache rather than `getQueryData` so the
- // palette re-renders when the tree lands. `enabled: false` means this
- // component never triggers the (expensive) vault walk itself — it only
- // shows the recents once some other view has fetched the tree.
- const { data: tree } = useQuery<TreeResponse>({
- queryKey: ["wiki", "tree"],
- queryFn: async () => {
- const res = await fetch("/api/wiki/tree");
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
- },
- enabled: false,
- });
- const recent = useMemo(() => selectRecentPages(tree), [tree]);
-
- // The palette's own selection. cmdk picks its first row only when it does
- // the filtering itself; with the backend ranking the hits it would leave
- // nothing selected, so Enter right after typing did nothing.
- const [selectedValue, setSelectedValue] = useState("");
- const firstValue =
- debouncedQuery.length === 0
- ? recent[0]
- ? `recent:${recent[0].slug}`
- : ""
- : data?.ok && data.hits[0]
- ? `hit:${data.hits[0].slug}`
- : "";
- useEffect(() => {
- setSelectedValue(firstValue);
- }, [firstValue]);
-
- const handlePick = useCallback(
- (slug: string) => {
- onResultClick(slug);
- setOpen(false);
- },
- [onResultClick],
- );
-
- // Render the modal even when closed so the imperative `open()` and Ctrl-K
- // shortcut produce a single Dialog mount across the lifetime of the tab.
- return (
- <Command.Dialog
- open={open}
- onOpenChange={setOpen}
- value={selectedValue}
- onValueChange={setSelectedValue}
- label={t("wiki_search.dialog_label")}
- // The backend already ranked these hits (FTS5/BM25 over full page
- // bodies). cmdk's built-in filter would score them a SECOND time
- // against the item `value` — which is `hit:<slug>`, not the page text —
- // and hide every hit whose slug does not contain the query as a
- // subsequence. That is why a multi-word search looked broken: the API
- // returned results and the palette showed an empty list.
- shouldFilter={false}
- data-testid="wiki-search-dialog"
- contentClassName="fixed left-1/2 top-[18vh] z-50 w-[min(640px,90vw)] -translate-x-1/2 overflow-hidden rounded-lg bg-popover shadow-float"
- overlayClassName="fixed inset-0 z-40 bg-scrim/40 backdrop-blur-sm"
- >
- {/* Screen-reader-only title and description — required by Radix Dialog's
- a11y contract; visually hidden so the palette UI stays clean. */}
- <h2 className="sr-only">{t("wiki_search.dialog_label")}</h2>
- <p className="sr-only" id="wiki-search-description">
- {t("wiki_search.dialog_description")}
- </p>
- <div className="flex h-12 items-center gap-3 border-b border-border px-4">
- <Search className="h-4 w-4 shrink-0 text-foreground-faint" aria-hidden />
- <Command.Input
- value={rawQuery}
- onValueChange={setRawQuery}
- placeholder={t("wiki_search.input_placeholder")}
- data-testid="wiki-search-input"
- className="flex-1 bg-transparent text-base text-foreground outline-none placeholder:text-foreground-faint"
- autoFocus
- />
- <kbd className="rounded-sm border border-border px-1.5 py-0.5 font-mono text-xs text-foreground-faint">
- Esc
- </kbd>
- </div>
-
- <Command.List
- data-testid="wiki-search-list"
- className="max-h-[60vh] overflow-y-auto p-2 text-base [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:pt-2 [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-foreground-faint"
- >
- {debouncedQuery.length === 0 ? (
- <Command.Group heading={t("wiki_search.recent_heading")} data-testid="wiki-search-recent">
- {recent.length === 0 ? (
- <div className="px-2 py-3 text-muted-foreground" data-testid="wiki-search-recent-empty">
- {t("wiki_search.no_pages")}
- </div>
- ) : (
- recent.map((entry) => (
- <Command.Item
- key={entry.slug}
- value={`recent:${entry.slug}`}
- onSelect={() => handlePick(entry.slug)}
- data-testid="wiki-search-recent-item"
- data-slug={entry.slug}
- className="flex h-9 cursor-pointer items-center gap-2.5 rounded-md px-2 text-foreground aria-selected:bg-secondary"
- >
- <KindGlyph group={groupOfKind(entry.kind)} className="h-2.5 w-2.5 text-foreground-faint" />
- <span className="truncate">{cleanTitle(entry.title, entry.slug)}</span>
- <span className="ml-auto truncate text-sm text-foreground-faint">{entry.path}</span>
- </Command.Item>
- ))
- )}
- </Command.Group>
- ) : isFetching && !data ? (
- // Only the very first search shows a placeholder. Later keystrokes
- // keep the previous hits visible until the new ones arrive.
- <div className="px-2 py-3 text-muted-foreground" data-testid="wiki-search-loading">
- {t("wiki_search.searching")}
- </div>
- ) : isError || !data?.ok ? (
- <div
- className="flex flex-col items-start gap-2 px-2 py-3 text-muted-foreground"
- data-testid="wiki-search-error"
- >
- <span>{t("wiki_search.unavailable")}</span>
- <button
- type="button"
- onClick={() => refetch()}
- className="text-xs underline hover:text-foreground"
- >
- {t("common.retry")}
- </button>
- </div>
- ) : data.hits.length === 0 ? (
- <Command.Empty data-testid="wiki-search-empty">
- {t("wiki_search.no_hits_prefix")}&quot;{debouncedQuery}&quot;{t("wiki_search.no_hits_suffix")}
- </Command.Empty>
- ) : (
- <Command.Group heading={t("wiki_search.hits_heading")} data-testid="wiki-search-hits">
- {data.hits.map((hit) => (
- <Command.Item
- key={hit.slug}
- value={`hit:${hit.slug}`}
- onSelect={() => handlePick(hit.slug)}
- data-testid="wiki-search-hit"
- data-slug={hit.slug}
- className="flex cursor-pointer flex-col gap-1 rounded-md px-2 py-2 aria-selected:bg-secondary"
- >
- <span className="flex items-center gap-2.5">
- <KindGlyph group={groupOfPath(hit.path)} className="h-2.5 w-2.5 text-foreground-faint" />
- <span className="truncate text-foreground">{cleanTitle(hit.title, hit.slug)}</span>
- {hit.by_meaning ? (
- <span
- data-testid="wiki-search-by-meaning"
- className="shrink-0 rounded-sm border border-border px-1.5 text-xs text-muted-foreground"
- >
- {t("wiki_search.by_meaning")}
- </span>
- ) : null}
- <span className="ml-auto truncate text-sm text-foreground-faint">{hit.path}</span>
- </span>
- <span className="line-clamp-2 pl-5 text-sm text-muted-foreground">
- {highlightSnippet(readableSnippet(hit.snippet), highlightPattern)}
- </span>
- </Command.Item>
- ))}
- </Command.Group>
- )}
- </Command.List>
- </Command.Dialog>
- );
-});
-
-export default WikiSearch;
diff --git a/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts b/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts
index c2cd420586..930aaa809c 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWikiLive.ts
@@ -9,7 +9,7 @@ import { WSClient } from "@/lib/ws";
* React Query caches that project vault state every time the server connects
* or pushes a `page_changed` message.
*
- * Mount this hook once at the WikiView level. Switching away from the wiki
+ * Mount this hook once at the MemoryView level. Switching away from the wiki
* tab unmounts the hook and closes the socket, so no background connection
* remains while the user is on another tab.
*
@@ -69,6 +69,8 @@ export function useWikiLive(): UseWikiLiveResult {
["wiki", "search"],
["wiki", "page"],
["wiki", "backlinks"],
+ // The Memory section's path-addressed index, pages, map and activity.
+ ["wiki", "memory"],
]) {
void queryClient.invalidateQueries({ queryKey });
}
diff --git a/jarvis/ui/web/frontend/src/hooks/useWikiProvider.ts b/jarvis/ui/web/frontend/src/hooks/useWikiProvider.ts
deleted file mode 100644
index 185ee4cd97..0000000000
--- a/jarvis/ui/web/frontend/src/hooks/useWikiProvider.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useCallback, useEffect, useState } from "react";
-
-/**
- * Dedicated Wiki-curator provider/model selection.
- *
- * Reads/writes `GET/PUT /api/settings/wiki-provider`, which exposes the
- * `[memory.wiki.curator].provider` / `.model` config pair. An empty provider
- * means "follow brain.primary"; an empty model means "use that provider's
- * cheap/fast model" (the ack-brain follow_brain pattern). `available` lists the
- * Brain providers the backend will accept as objects carrying each provider's
- * id plus its selectable model ids; the empty "follow primary" / "cheap
- * default" sentinels are rendered by the UI as dedicated options.
- */
-export interface WikiProviderOption {
- provider: string;
- models: string[];
- /** "agent" = OAuth-CLI Jarvis-Agent provider (Codex/Antigravity), "api" otherwise. */
- kind?: "api" | "agent";
- /** Whether the wiki fallback chain sees a usable credential for this provider. */
- ready?: boolean;
-}
-
-/**
- * What the NEXT maintenance run will actually use — resolved by the backend
- * through the same helper the runtime uses, so this is fact, not a guess.
- * `ready: false` means the key-aware chain will cross to another provider.
- */
-export interface WikiResolvedState {
- provider: string;
- model: string;
- ready: boolean;
-}
-
-export interface WikiProviderState {
- provider: string;
- model: string;
- available: WikiProviderOption[];
- resolved?: WikiResolvedState;
- brain_primary?: string;
- // PUT-only echo fields (the save response reuses this shape).
- persisted?: boolean;
- applied_live?: boolean;
- restart_required?: boolean;
-}
-
-const ENDPOINT = "/api/settings/wiki-provider";
-
-export function useWikiProvider() {
- const [data, setData] = useState<WikiProviderState | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- const refetch = useCallback(async () => {
- setError(null);
- try {
- const res = await fetch(ENDPOINT);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const body: WikiProviderState = await res.json();
- setData(body);
- } catch (e) {
- setError((e as Error).message);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => {
- void refetch();
- }, [refetch]);
-
- return { data, loading, error, refetch };
-}
-
-/**
- * Persists the Wiki curator provider/model. Empty strings are valid and mean
- * "follow brain.primary" (provider) / "cheap default" (model). Returns the
- * server's resolved state so the UI reflects what the backend actually applied.
- */
-export async function saveWikiProvider(
- provider: string,
- model: string,
-): Promise<WikiProviderState> {
- const res = await fetch(ENDPOINT, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider, model }),
- });
- const body = await res.json().catch(() => ({}));
- if (!res.ok) {
- throw new Error((body as { detail?: string }).detail ?? `HTTP ${res.status}`);
- }
- return body as WikiProviderState;
-}
diff --git a/jarvis/ui/web/frontend/src/i18n/index.ts b/jarvis/ui/web/frontend/src/i18n/index.ts
index 8f5b06819a..a7c2bd87cb 100644
--- a/jarvis/ui/web/frontend/src/i18n/index.ts
+++ b/jarvis/ui/web/frontend/src/i18n/index.ts
@@ -121,7 +121,8 @@ export type LocaleChunk =
| "onboarding"
| "appshot_editor"
| "providers"
- | "pane_review";
+ | "pane_review"
+ | "memory";
const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknown>>> = {
marketplace: {
@@ -184,6 +185,14 @@ const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknow
zh: () => import("./locales/pane_review/zh.json"),
pt: () => import("./locales/pane_review/pt.json"),
},
+ // The Memory section (the vault reader, map and editor).
+ memory: {
+ en: () => import("./locales/memory/en.json"),
+ de: () => import("./locales/memory/de.json"),
+ es: () => import("./locales/memory/es.json"),
+ zh: () => import("./locales/memory/zh.json"),
+ pt: () => import("./locales/memory/pt.json"),
+ },
};
const EXTRA: Record<UiLanguage, Record<string, unknown>[]> = { en: [], de: [], es: [], zh: [], pt: [] };
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/memory/de.json b/jarvis/ui/web/frontend/src/i18n/locales/memory/de.json
new file mode 100644
index 0000000000..af9161167e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/memory/de.json
@@ -0,0 +1,199 @@
+{
+ "memory_view": {
+ "title": "Gedächtnis",
+ "overview": "Übersicht",
+ "map": "Karte",
+ "search": "Gedächtnis durchsuchen",
+ "search_placeholder": "Seiten, Personen, Projekte suchen…",
+ "search_titles": "Seiten",
+ "search_text": "Im Text",
+ "search_no_results": "Nichts gefunden.",
+ "search_create": "Seite „{title}“ anlegen",
+ "searching": "Suche läuft…",
+ "by_meaning": "ähnliche Bedeutung",
+ "new_page": "Neue Seite",
+ "back": "Zurück",
+ "loading": "Gedächtnis wird geladen…",
+ "load_error_title": "Das Gedächtnis konnte nicht geladen werden",
+ "load_error_body": "Der Vault antwortet nicht. Prüfe in den Einstellungen, ob das Wiki eingeschaltet ist.",
+ "nav_stats": "{pages} Seiten mit Inhalt · {links} Verbindungen",
+ "all_agents": "Alle Agenten",
+ "group_knowledge": "Wissen",
+ "group_agents": "Agenten",
+ "group_journal": "Journal",
+ "group_system": "System",
+ "area_entities": "Personen & Dinge",
+ "area_entities_hint": "Personen, Tools, Orte und alles andere, wozu {name} sich Fakten merkt.",
+ "area_entities_empty": "Sobald {name} etwas über eine Person oder ein Ding lernt, erscheint hier die Seite dazu.",
+ "area_projects": "Projekte",
+ "area_projects_hint": "Woran du arbeitest: Ziele, Stand, offene Punkte.",
+ "area_projects_empty": "Projekte, von denen {name} erfährt, bekommen hier eine Seite.",
+ "area_concepts": "Konzepte",
+ "area_concepts_hint": "Ideen, Definitionen und Methoden, die du behalten willst.",
+ "area_concepts_empty": "Noch keine Konzepte. Lege eines für eine Idee an, die {name} sich merken soll.",
+ "area_journal": "Journal",
+ "area_journal_hint": "Zusammenfassungen vergangener Sitzungen.",
+ "area_journal_empty": "Sitzungszusammenfassungen erscheinen hier, sobald sie geschrieben sind.",
+ "area_system": "Systemseiten",
+ "area_system_hint": "Wie das Gedächtnis funktioniert, sein Schema und das Protokoll aller Änderungen.",
+ "area_system_empty": "Keine Systemseiten.",
+ "area_agents": "Agenten",
+ "area_agents_hint": "Jeder Agent führt zwei Notizbücher: was er über seine Arbeit gelernt hat und was er über dich weiß.",
+ "area_empty_title": "Hier ist noch nichts",
+ "home_title": "Woran sich {name} erinnert",
+ "home_lead": "Verlinkte Markdown-Seiten in deinem Obsidian-Vault. Sie wachsen aus Gesprächen und den eigenen Notizen der Agenten, und du kannst sie hier lesen, bearbeiten und verbinden.",
+ "stat_pages": "Wissensseiten",
+ "stat_links": "Links",
+ "stat_mentions": "Erwähnungen",
+ "stat_agents": "Agenten mit Notizen",
+ "stat_of": "von {count}",
+ "recently_changed": "Zuletzt geändert",
+ "most_connected": "Am stärksten vernetzt",
+ "backlinks_short": "{count} Links",
+ "activity": "Aktivität",
+ "activity_empty": "Noch keine Änderungen aufgezeichnet.",
+ "verb_ingest": "gelernt",
+ "verb_update": "aktualisiert",
+ "verb_create": "erstellt",
+ "verb_merge": "zusammengeführt",
+ "verb_rename": "umbenannt",
+ "verb_archive": "archiviert",
+ "verb_delete": "gelöscht",
+ "vault_empty_title": "Noch nichts gemerkt",
+ "vault_empty_body": "Hier erscheinen Seiten, sobald {name} Personen, Projekte und deine Vorlieben kennenlernt. Du kannst auch selbst die erste schreiben.",
+ "filter": "Liste filtern",
+ "filter_no_match": "Keine Seite passt zum Filter.",
+ "sort": "Sortieren",
+ "sort_recent": "Neueste",
+ "sort_name": "Name",
+ "sort_links": "Verbindungen",
+ "show_empty": "{count} Seiten ohne Inhalt anzeigen",
+ "hide_empty": "Seiten ohne Inhalt ausblenden",
+ "no_content_yet": "Noch kein Inhalt",
+ "links_title": "{inbound} Seiten verlinken hierher, diese Seite verlinkt auf {outbound}",
+ "updated": "aktualisiert {age}",
+ "words_count": "{count} Wörter",
+ "entries_count": "{count} Einträge",
+ "notes_count": "{count} Notizen",
+ "agent_active": "Aktiv",
+ "agent_archived": "Gelöschter Agent",
+ "agent_orphan": "Unbekannter Agent",
+ "agent_archived_short": "gelöscht",
+ "agent_orphan_short": "unbekannt",
+ "agent_nothing_yet": "Hat noch nichts notiert.",
+ "agent_pages": "Seiten dieses Agenten",
+ "agents_empty_title": "Keine Agenten-Notizbücher",
+ "agents_empty_body": "Sobald sich ein Agent etwas merkt, erscheint hier sein Notizbuch.",
+ "agents_show_inactive": "{count} gelöschte oder unbekannte Agenten anzeigen",
+ "agents_hide_inactive": "Gelöschte und unbekannte Agenten ausblenden",
+ "tidy_button": "Leere Notizbücher aufräumen",
+ "tidy_title": "{count} leere Notizbücher archivieren?",
+ "tidy_body": "Diese Notizbücher gehören gelöschten oder unbekannten Agenten und sind leer. Sie wandern in den Ordner _archive des Vaults; gelöscht wird nichts.",
+ "tidy_confirm": "Archivieren",
+ "tidy_done": "{count} leere Notizbücher archiviert.",
+ "tidy_nothing": "Es gibt nichts aufzuräumen.",
+ "and_more": "und {count} weitere",
+ "breadcrumb": "Pfad",
+ "kind_entity": "Objekt",
+ "kind_person": "Person",
+ "kind_project": "Projekt",
+ "kind_concept": "Konzept",
+ "kind_session": "Sitzung",
+ "kind_note": "Notiz",
+ "kind_memory": "Erinnerung",
+ "kind_profile": "Profil",
+ "kind_shared": "Geteilte Notiz",
+ "kind_system": "Systemseite",
+ "kind_template": "Vorlage",
+ "edit": "Bearbeiten",
+ "write": "Schreiben",
+ "preview": "Vorschau",
+ "save": "Speichern",
+ "saved": "Gespeichert.",
+ "cancel": "Abbrechen",
+ "editor_label": "Seitentext in Markdown",
+ "editor_hint": "[[ verlinkt eine Seite · Ctrl S speichert · Esc bricht ab",
+ "link_suggestions": "Seiten zum Verlinken",
+ "show_on_map": "Auf der Karte zeigen",
+ "open_obsidian": "In Obsidian öffnen",
+ "copy_path": "Dateipfad kopieren",
+ "copied": "Pfad kopiert.",
+ "rename": "Umbenennen",
+ "rename_title": "Seite umbenennen",
+ "rename_description": "Jeder Link auf diese Seite wird auf den neuen Namen aktualisiert.",
+ "renamed": "Umbenannt.",
+ "renamed_links": "Umbenannt. {count} Links wurden aktualisiert.",
+ "archive": "Archivieren",
+ "archive_title": "„{title}“ archivieren?",
+ "archive_body": "Die Seite wandert in den Ordner _archive des Vaults und verlässt das Gedächtnis. Du kannst sie dort in Obsidian wiederherstellen.",
+ "archived": "Archiviert.",
+ "new_title": "Neue Seite",
+ "new_description": "Lege eine Seite für eine Person, ein Projekt oder eine Idee an. Von anderen Seiten aus verlinkst du sie mit [[ihr Name]].",
+ "new_name": "Name",
+ "new_name_placeholder": "z. B. Maria Weber",
+ "new_kind": "Art",
+ "create": "Anlegen",
+ "created": "„{title}“ angelegt.",
+ "page_missing_title": "Diese Seite gibt es nicht mehr",
+ "page_missing_body": "Sie wurde im Vault umbenannt, archiviert oder entfernt.",
+ "page_empty_title": "Diese Seite hat noch keinen Inhalt",
+ "page_empty_body": "Sie existiert im Vault, aber es wurde nichts darin geschrieben.",
+ "page_empty_editable": "Schreib hier auf, was gemerkt werden soll, und verlinke verwandte Seiten mit [[ihr Name]].",
+ "write_page": "Diese Seite schreiben",
+ "notebook_empty_memory": "Noch keine Erinnerungen",
+ "notebook_empty_profile": "Noch nichts über dich bekannt",
+ "notebook_empty_body": "{agent} hat in dieses Notizbuch noch nichts geschrieben. Einträge erscheinen hier, sobald es sich etwas merkt.",
+ "important": "Wichtig",
+ "origin_agent": "Vom Agenten notiert",
+ "origin_tool": "Aus einem Tool-Ergebnis",
+ "origin_user": "Das hast du gesagt",
+ "origin_review": "Aus einer Prüfung",
+ "link_missing": "Diese Seite existiert noch nicht. Klicke, um sie anzulegen.",
+ "connections": "Verbindungen",
+ "no_connections": "Diese Seite ist noch mit keiner anderen Seite verbunden.",
+ "linked_from": "Verlinkt von",
+ "links_to": "Verlinkt auf",
+ "mentioned_in": "Erwähnt in",
+ "mentioned_in_hint": "Seiten, die diese hier nennen, ohne sie zu verlinken.",
+ "mentions": "Erwähnungen",
+ "related": "Verwandt",
+ "related_hint": "Haben eine Verbindung mit dieser Seite gemeinsam.",
+ "related_via": "über {title}",
+ "unresolved_links": "Links auf fehlende Seiten",
+ "properties": "Eigenschaften",
+ "file": "Datei",
+ "show_all": "Alle {count} anzeigen",
+ "show_less": "Weniger anzeigen",
+ "map_counts": "{pages} Seiten · {links} Links · {mentions} Erwähnungen",
+ "map_include_agents": "Agenten-Notizbücher",
+ "map_fit": "Einpassen",
+ "map_error": "Die Karte konnte nicht geladen werden.",
+ "map_empty_title": "Noch nichts zu zeichnen",
+ "map_empty_body": "Die Karte zeigt Seiten mit Inhalt und wie sie verlinkt sind. Sie füllt sich, wenn das Gedächtnis wächst.",
+ "map_legend_knowledge": "Wissen ({count})",
+ "map_legend_agents": "Agentenseiten ({count})",
+ "map_legend_link": "Link",
+ "map_legend_mention": "Erwähnung",
+ "health_title": "Gedächtnis-Schreiber",
+ "health_green": "In Ordnung",
+ "health_amber": "Braucht Aufmerksamkeit",
+ "health_red": "Funktioniert nicht",
+ "health_unknown": "Nicht geprüft",
+ "health_checking": "Prüfe…",
+ "health_ok": "Schreibvorgänge kommen an und der Suchindex ist aktuell.",
+ "health_writer_off": "Der Gedächtnis-Schreiber wurde nicht gestartet.",
+ "health_write_failed": "Der letzte Schreibvorgang ist fehlgeschlagen.",
+ "health_index_stale": "Der Suchindex enthält {indexed} von {pages} Seiten. Baue ihn neu auf, um alles zu finden.",
+ "health_backlog": "{count} gelernte Fakten warten darauf, geschrieben zu werden.",
+ "health_indexed": "Seiten im Suchindex",
+ "health_queue": "Wartende Fakten",
+ "health_reindex": "Suchindex neu aufbauen",
+ "health_reindexed": "Suchindex neu aufgebaut: {count} Seiten.",
+ "health_reindex_failed": "Der Suchindex konnte nicht neu aufgebaut werden.",
+ "entries_count_one": "1 Eintrag",
+ "words_count_one": "1 Wort",
+ "notes_count_one": "1 Notiz",
+ "backlinks_short_one": "1 Link",
+ "renamed_unrewritten": "{count} Agenten-Notizbücher verlinken noch den alten Namen; die pflegen ihre Agenten selbst."
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/memory/en.json b/jarvis/ui/web/frontend/src/i18n/locales/memory/en.json
new file mode 100644
index 0000000000..e0aa65d641
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/memory/en.json
@@ -0,0 +1,199 @@
+{
+ "memory_view": {
+ "title": "Memory",
+ "overview": "Overview",
+ "map": "Map",
+ "search": "Search memory",
+ "search_placeholder": "Search pages, people, projects…",
+ "search_titles": "Pages",
+ "search_text": "In the text",
+ "search_no_results": "Nothing found.",
+ "search_create": "Create page “{title}”",
+ "searching": "Searching…",
+ "by_meaning": "similar meaning",
+ "new_page": "New page",
+ "back": "Back",
+ "loading": "Loading memory…",
+ "load_error_title": "The memory could not be loaded",
+ "load_error_body": "The vault did not answer. Check that the wiki is switched on in Settings.",
+ "nav_stats": "{pages} pages with content · {links} connections",
+ "all_agents": "All agents",
+ "group_knowledge": "Knowledge",
+ "group_agents": "Agents",
+ "group_journal": "Journal",
+ "group_system": "System",
+ "area_entities": "People & things",
+ "area_entities_hint": "People, tools, places and everything else {name} keeps facts about.",
+ "area_entities_empty": "When {name} learns about a person or a thing, its page appears here.",
+ "area_projects": "Projects",
+ "area_projects_hint": "What you are working on: goals, status, open threads.",
+ "area_projects_empty": "Projects {name} hears about get a page here.",
+ "area_concepts": "Concepts",
+ "area_concepts_hint": "Ideas, definitions and methods worth keeping.",
+ "area_concepts_empty": "No concepts yet. Create one for an idea you want {name} to remember.",
+ "area_journal": "Journal",
+ "area_journal_hint": "Summaries of past sessions.",
+ "area_journal_empty": "Session summaries appear here once they are written.",
+ "area_system": "System pages",
+ "area_system_hint": "How the memory works, its schema and the log of every change.",
+ "area_system_empty": "No system pages.",
+ "area_agents": "Agents",
+ "area_agents_hint": "Each agent keeps two notebooks: what it learned about its work, and what it knows about you.",
+ "area_empty_title": "Nothing here yet",
+ "home_title": "What {name} remembers",
+ "home_lead": "Linked Markdown pages in your Obsidian vault. They grow from conversations and from the agents' own notes, and you can read, edit and connect them here.",
+ "stat_pages": "Knowledge pages",
+ "stat_links": "Links",
+ "stat_mentions": "Mentions",
+ "stat_agents": "Agents with notes",
+ "stat_of": "of {count}",
+ "recently_changed": "Recently changed",
+ "most_connected": "Most connected",
+ "backlinks_short": "{count} links",
+ "activity": "Activity",
+ "activity_empty": "No changes recorded yet.",
+ "verb_ingest": "learned",
+ "verb_update": "updated",
+ "verb_create": "created",
+ "verb_merge": "merged",
+ "verb_rename": "renamed",
+ "verb_archive": "archived",
+ "verb_delete": "deleted",
+ "vault_empty_title": "Nothing remembered yet",
+ "vault_empty_body": "Pages appear here as {name} learns about people, projects and your preferences. You can also write the first one yourself.",
+ "filter": "Filter this list",
+ "filter_no_match": "No page matches the filter.",
+ "sort": "Sort",
+ "sort_recent": "Recent",
+ "sort_name": "Name",
+ "sort_links": "Connections",
+ "show_empty": "Show {count} pages without content",
+ "hide_empty": "Hide pages without content",
+ "no_content_yet": "No content yet",
+ "links_title": "{inbound} pages link here, this page links to {outbound}",
+ "updated": "updated {age}",
+ "words_count": "{count} words",
+ "entries_count": "{count} entries",
+ "notes_count": "{count} notes",
+ "agent_active": "Active",
+ "agent_archived": "Deleted agent",
+ "agent_orphan": "Unknown agent",
+ "agent_archived_short": "deleted",
+ "agent_orphan_short": "unknown",
+ "agent_nothing_yet": "Has not written anything down yet.",
+ "agent_pages": "This agent's pages",
+ "agents_empty_title": "No agent notebooks",
+ "agents_empty_body": "When an agent remembers something, its notebook appears here.",
+ "agents_show_inactive": "Show {count} deleted or unknown agents",
+ "agents_hide_inactive": "Hide deleted and unknown agents",
+ "tidy_button": "Tidy up empty notebooks",
+ "tidy_title": "Archive {count} empty notebooks?",
+ "tidy_body": "These notebooks belong to deleted or unknown agents and contain nothing. They move to the vault's _archive folder; nothing is deleted.",
+ "tidy_confirm": "Archive",
+ "tidy_done": "{count} empty notebooks archived.",
+ "tidy_nothing": "There is nothing to tidy up.",
+ "and_more": "and {count} more",
+ "breadcrumb": "Location",
+ "kind_entity": "Entity",
+ "kind_person": "Person",
+ "kind_project": "Project",
+ "kind_concept": "Concept",
+ "kind_session": "Session",
+ "kind_note": "Note",
+ "kind_memory": "Memory",
+ "kind_profile": "Profile",
+ "kind_shared": "Shared note",
+ "kind_system": "System page",
+ "kind_template": "Template",
+ "edit": "Edit",
+ "write": "Write",
+ "preview": "Preview",
+ "save": "Save",
+ "saved": "Saved.",
+ "cancel": "Cancel",
+ "editor_label": "Page text in Markdown",
+ "editor_hint": "[[ links a page · Ctrl S saves · Esc cancels",
+ "link_suggestions": "Pages to link",
+ "show_on_map": "Show on the map",
+ "open_obsidian": "Open in Obsidian",
+ "copy_path": "Copy file path",
+ "copied": "Path copied.",
+ "rename": "Rename",
+ "rename_title": "Rename page",
+ "rename_description": "Every link to this page is updated to the new name.",
+ "renamed": "Renamed.",
+ "renamed_links": "Renamed. {count} links were updated.",
+ "archive": "Archive",
+ "archive_title": "Archive “{title}”?",
+ "archive_body": "The page moves to the vault's _archive folder and leaves the memory. You can restore it from there in Obsidian.",
+ "archived": "Archived.",
+ "new_title": "New page",
+ "new_description": "Start a page for a person, a project or an idea. You can link it from other pages with [[its name]].",
+ "new_name": "Name",
+ "new_name_placeholder": "e.g. Maria Weber",
+ "new_kind": "Kind",
+ "create": "Create",
+ "created": "“{title}” created.",
+ "page_missing_title": "This page no longer exists",
+ "page_missing_body": "It was renamed, archived or removed in the vault.",
+ "page_empty_title": "This page has no content yet",
+ "page_empty_body": "It exists in the vault but nothing has been written to it.",
+ "page_empty_editable": "Write what should be remembered here, and link related pages with [[their name]].",
+ "write_page": "Write this page",
+ "notebook_empty_memory": "No memories yet",
+ "notebook_empty_profile": "Nothing known about you yet",
+ "notebook_empty_body": "{agent} has not written to this notebook. Entries appear here as soon as it remembers something.",
+ "important": "Important",
+ "origin_agent": "Noted by the agent",
+ "origin_tool": "From a tool result",
+ "origin_user": "You said this",
+ "origin_review": "From a review",
+ "link_missing": "This page does not exist yet. Click to create it.",
+ "connections": "Connections",
+ "no_connections": "This page is not connected to any other page yet.",
+ "linked_from": "Linked from",
+ "links_to": "Links to",
+ "mentioned_in": "Mentioned in",
+ "mentioned_in_hint": "Pages that name this one without linking it.",
+ "mentions": "Mentions",
+ "related": "Related",
+ "related_hint": "Share a connection with this page.",
+ "related_via": "via {title}",
+ "unresolved_links": "Links to missing pages",
+ "properties": "Properties",
+ "file": "File",
+ "show_all": "Show all {count}",
+ "show_less": "Show less",
+ "map_counts": "{pages} pages · {links} links · {mentions} mentions",
+ "map_include_agents": "Agent notebooks",
+ "map_fit": "Fit",
+ "map_error": "The map could not be loaded.",
+ "map_empty_title": "Nothing to draw yet",
+ "map_empty_body": "The map shows pages with content and how they link. It fills as the memory grows.",
+ "map_legend_knowledge": "Knowledge ({count})",
+ "map_legend_agents": "Agent pages ({count})",
+ "map_legend_link": "Link",
+ "map_legend_mention": "Mention",
+ "health_title": "Memory writer",
+ "health_green": "Healthy",
+ "health_amber": "Needs attention",
+ "health_red": "Not working",
+ "health_unknown": "Not checked",
+ "health_checking": "Checking…",
+ "health_ok": "Writes land and the search index is up to date.",
+ "health_writer_off": "The memory writer did not start.",
+ "health_write_failed": "The last write failed.",
+ "health_index_stale": "The search index has {indexed} of {pages} pages. Rebuild it to find everything.",
+ "health_backlog": "{count} learned facts are waiting to be written.",
+ "health_indexed": "Pages in the search index",
+ "health_queue": "Facts waiting",
+ "health_reindex": "Rebuild search index",
+ "health_reindexed": "Search index rebuilt: {count} pages.",
+ "health_reindex_failed": "The search index could not be rebuilt.",
+ "entries_count_one": "1 entry",
+ "words_count_one": "1 word",
+ "notes_count_one": "1 note",
+ "backlinks_short_one": "1 link",
+ "renamed_unrewritten": "{count} agent notebooks still link the old name; their agents keep them."
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/memory/es.json b/jarvis/ui/web/frontend/src/i18n/locales/memory/es.json
new file mode 100644
index 0000000000..d65efd19f3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/memory/es.json
@@ -0,0 +1,199 @@
+{
+ "memory_view": {
+ "title": "Memoria",
+ "overview": "Resumen",
+ "map": "Mapa",
+ "search": "Buscar en la memoria",
+ "search_placeholder": "Busca páginas, personas, proyectos…",
+ "search_titles": "Páginas",
+ "search_text": "En el texto",
+ "search_no_results": "No se encontró nada.",
+ "search_create": "Crear la página “{title}”",
+ "searching": "Buscando…",
+ "by_meaning": "significado similar",
+ "new_page": "Nueva página",
+ "back": "Atrás",
+ "loading": "Cargando la memoria…",
+ "load_error_title": "No se pudo cargar la memoria",
+ "load_error_body": "El vault no responde. Comprueba en Ajustes que la wiki esté activada.",
+ "nav_stats": "{pages} páginas con contenido · {links} conexiones",
+ "all_agents": "Todos los agentes",
+ "group_knowledge": "Conocimiento",
+ "group_agents": "Agentes",
+ "group_journal": "Diario",
+ "group_system": "Sistema",
+ "area_entities": "Personas y cosas",
+ "area_entities_hint": "Personas, herramientas, lugares y todo lo demás sobre lo que {name} guarda datos.",
+ "area_entities_empty": "Cuando {name} aprenda sobre una persona o una cosa, su página aparecerá aquí.",
+ "area_projects": "Proyectos",
+ "area_projects_hint": "En qué trabajas: objetivos, estado, asuntos pendientes.",
+ "area_projects_empty": "Los proyectos de los que {name} se entere tendrán aquí su página.",
+ "area_concepts": "Conceptos",
+ "area_concepts_hint": "Ideas, definiciones y métodos que merece la pena conservar.",
+ "area_concepts_empty": "Aún no hay conceptos. Crea uno para una idea que quieras que {name} recuerde.",
+ "area_journal": "Diario",
+ "area_journal_hint": "Resúmenes de sesiones pasadas.",
+ "area_journal_empty": "Los resúmenes de sesión aparecerán aquí cuando se escriban.",
+ "area_system": "Páginas del sistema",
+ "area_system_hint": "Cómo funciona la memoria, su esquema y el registro de cada cambio.",
+ "area_system_empty": "No hay páginas del sistema.",
+ "area_agents": "Agentes",
+ "area_agents_hint": "Cada agente lleva dos cuadernos: lo que aprendió sobre su trabajo y lo que sabe de ti.",
+ "area_empty_title": "Aún no hay nada",
+ "home_title": "Lo que recuerda {name}",
+ "home_lead": "Páginas Markdown enlazadas en tu vault de Obsidian. Surgen de las conversaciones y de las notas propias de los agentes, y aquí puedes leerlas, editarlas y conectarlas.",
+ "stat_pages": "Páginas de conocimiento",
+ "stat_links": "Enlaces",
+ "stat_mentions": "Menciones",
+ "stat_agents": "Agentes con notas",
+ "stat_of": "de {count}",
+ "recently_changed": "Cambiadas hace poco",
+ "most_connected": "Más conectadas",
+ "backlinks_short": "{count} enlaces",
+ "activity": "Actividad",
+ "activity_empty": "Aún no hay cambios registrados.",
+ "verb_ingest": "aprendió",
+ "verb_update": "actualizó",
+ "verb_create": "creó",
+ "verb_merge": "fusionó",
+ "verb_rename": "renombró",
+ "verb_archive": "archivó",
+ "verb_delete": "eliminó",
+ "vault_empty_title": "Aún no se ha recordado nada",
+ "vault_empty_body": "Las páginas aparecen aquí a medida que {name} conoce personas, proyectos y tus preferencias. También puedes escribir la primera tú mismo.",
+ "filter": "Filtrar esta lista",
+ "filter_no_match": "Ninguna página coincide con el filtro.",
+ "sort": "Ordenar",
+ "sort_recent": "Recientes",
+ "sort_name": "Nombre",
+ "sort_links": "Conexiones",
+ "show_empty": "Mostrar {count} páginas sin contenido",
+ "hide_empty": "Ocultar páginas sin contenido",
+ "no_content_yet": "Aún sin contenido",
+ "links_title": "{inbound} páginas enlazan aquí, esta página enlaza a {outbound}",
+ "updated": "actualizada {age}",
+ "words_count": "{count} palabras",
+ "entries_count": "{count} entradas",
+ "notes_count": "{count} notas",
+ "agent_active": "Activo",
+ "agent_archived": "Agente eliminado",
+ "agent_orphan": "Agente desconocido",
+ "agent_archived_short": "eliminado",
+ "agent_orphan_short": "desconocido",
+ "agent_nothing_yet": "Todavía no ha anotado nada.",
+ "agent_pages": "Páginas de este agente",
+ "agents_empty_title": "No hay cuadernos de agentes",
+ "agents_empty_body": "Cuando un agente recuerde algo, su cuaderno aparecerá aquí.",
+ "agents_show_inactive": "Mostrar {count} agentes eliminados o desconocidos",
+ "agents_hide_inactive": "Ocultar agentes eliminados y desconocidos",
+ "tidy_button": "Ordenar cuadernos vacíos",
+ "tidy_title": "¿Archivar {count} cuadernos vacíos?",
+ "tidy_body": "Estos cuadernos pertenecen a agentes eliminados o desconocidos y están vacíos. Pasan a la carpeta _archive del vault; no se elimina nada.",
+ "tidy_confirm": "Archivar",
+ "tidy_done": "{count} cuadernos vacíos archivados.",
+ "tidy_nothing": "No hay nada que ordenar.",
+ "and_more": "y {count} más",
+ "breadcrumb": "Ubicación",
+ "kind_entity": "Entidad",
+ "kind_person": "Persona",
+ "kind_project": "Proyecto",
+ "kind_concept": "Concepto",
+ "kind_session": "Sesión",
+ "kind_note": "Nota",
+ "kind_memory": "Recuerdo",
+ "kind_profile": "Perfil",
+ "kind_shared": "Nota compartida",
+ "kind_system": "Página del sistema",
+ "kind_template": "Plantilla",
+ "edit": "Editar",
+ "write": "Escribir",
+ "preview": "Vista previa",
+ "save": "Guardar",
+ "saved": "Guardado.",
+ "cancel": "Cancelar",
+ "editor_label": "Texto de la página en Markdown",
+ "editor_hint": "[[ enlaza una página · Ctrl S guarda · Esc cancela",
+ "link_suggestions": "Páginas para enlazar",
+ "show_on_map": "Mostrar en el mapa",
+ "open_obsidian": "Abrir en Obsidian",
+ "copy_path": "Copiar ruta del archivo",
+ "copied": "Ruta copiada.",
+ "rename": "Renombrar",
+ "rename_title": "Renombrar página",
+ "rename_description": "Todos los enlaces a esta página se actualizan al nuevo nombre.",
+ "renamed": "Renombrada.",
+ "renamed_links": "Renombrada. Se actualizaron {count} enlaces.",
+ "archive": "Archivar",
+ "archive_title": "¿Archivar “{title}”?",
+ "archive_body": "La página pasa a la carpeta _archive del vault y sale de la memoria. Puedes restaurarla desde allí en Obsidian.",
+ "archived": "Archivada.",
+ "new_title": "Nueva página",
+ "new_description": "Crea una página para una persona, un proyecto o una idea. Puedes enlazarla desde otras páginas con [[su nombre]].",
+ "new_name": "Nombre",
+ "new_name_placeholder": "p. ej. María Weber",
+ "new_kind": "Tipo",
+ "create": "Crear",
+ "created": "“{title}” creada.",
+ "page_missing_title": "Esta página ya no existe",
+ "page_missing_body": "Se renombró, archivó o eliminó en el vault.",
+ "page_empty_title": "Esta página aún no tiene contenido",
+ "page_empty_body": "Existe en el vault, pero no se ha escrito nada en ella.",
+ "page_empty_editable": "Escribe aquí lo que debe recordarse y enlaza las páginas relacionadas con [[su nombre]].",
+ "write_page": "Escribir esta página",
+ "notebook_empty_memory": "Aún no hay recuerdos",
+ "notebook_empty_profile": "Aún no se sabe nada de ti",
+ "notebook_empty_body": "{agent} no ha escrito en este cuaderno. Las entradas aparecerán aquí en cuanto recuerde algo.",
+ "important": "Importante",
+ "origin_agent": "Anotado por el agente",
+ "origin_tool": "De un resultado de herramienta",
+ "origin_user": "Lo dijiste tú",
+ "origin_review": "De una revisión",
+ "link_missing": "Esta página aún no existe. Haz clic para crearla.",
+ "connections": "Conexiones",
+ "no_connections": "Esta página aún no está conectada con ninguna otra.",
+ "linked_from": "Enlazada desde",
+ "links_to": "Enlaza a",
+ "mentioned_in": "Mencionada en",
+ "mentioned_in_hint": "Páginas que nombran esta sin enlazarla.",
+ "mentions": "Menciones",
+ "related": "Relacionadas",
+ "related_hint": "Comparten una conexión con esta página.",
+ "related_via": "vía {title}",
+ "unresolved_links": "Enlaces a páginas inexistentes",
+ "properties": "Propiedades",
+ "file": "Archivo",
+ "show_all": "Mostrar las {count}",
+ "show_less": "Mostrar menos",
+ "map_counts": "{pages} páginas · {links} enlaces · {mentions} menciones",
+ "map_include_agents": "Cuadernos de agentes",
+ "map_fit": "Ajustar",
+ "map_error": "No se pudo cargar el mapa.",
+ "map_empty_title": "Aún no hay nada que dibujar",
+ "map_empty_body": "El mapa muestra las páginas con contenido y cómo se enlazan. Se llena a medida que crece la memoria.",
+ "map_legend_knowledge": "Conocimiento ({count})",
+ "map_legend_agents": "Páginas de agentes ({count})",
+ "map_legend_link": "Enlace",
+ "map_legend_mention": "Mención",
+ "health_title": "Escritor de memoria",
+ "health_green": "Correcto",
+ "health_amber": "Requiere atención",
+ "health_red": "No funciona",
+ "health_unknown": "Sin comprobar",
+ "health_checking": "Comprobando…",
+ "health_ok": "Las escrituras se guardan y el índice de búsqueda está al día.",
+ "health_writer_off": "El escritor de memoria no se inició.",
+ "health_write_failed": "La última escritura falló.",
+ "health_index_stale": "El índice de búsqueda tiene {indexed} de {pages} páginas. Reconstrúyelo para encontrarlo todo.",
+ "health_backlog": "{count} datos aprendidos esperan a ser escritos.",
+ "health_indexed": "Páginas en el índice de búsqueda",
+ "health_queue": "Datos en espera",
+ "health_reindex": "Reconstruir índice de búsqueda",
+ "health_reindexed": "Índice de búsqueda reconstruido: {count} páginas.",
+ "health_reindex_failed": "No se pudo reconstruir el índice de búsqueda.",
+ "entries_count_one": "1 entrada",
+ "words_count_one": "1 palabra",
+ "notes_count_one": "1 nota",
+ "backlinks_short_one": "1 enlace",
+ "renamed_unrewritten": "{count} cuadernos de agentes aún enlazan el nombre anterior; los mantienen sus agentes."
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/memory/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/memory/pt.json
new file mode 100644
index 0000000000..db7dc34d1b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/memory/pt.json
@@ -0,0 +1,199 @@
+{
+ "memory_view": {
+ "title": "Memória",
+ "overview": "Visão geral",
+ "map": "Mapa",
+ "search": "Pesquisar na memória",
+ "search_placeholder": "Pesquise páginas, pessoas, projetos…",
+ "search_titles": "Páginas",
+ "search_text": "No texto",
+ "search_no_results": "Nada encontrado.",
+ "search_create": "Criar a página “{title}”",
+ "searching": "Pesquisando…",
+ "by_meaning": "significado semelhante",
+ "new_page": "Nova página",
+ "back": "Voltar",
+ "loading": "Carregando a memória…",
+ "load_error_title": "Não foi possível carregar a memória",
+ "load_error_body": "O vault não respondeu. Verifique nas Configurações se a wiki está ativada.",
+ "nav_stats": "{pages} páginas com conteúdo · {links} conexões",
+ "all_agents": "Todos os agentes",
+ "group_knowledge": "Conhecimento",
+ "group_agents": "Agentes",
+ "group_journal": "Diário",
+ "group_system": "Sistema",
+ "area_entities": "Pessoas e coisas",
+ "area_entities_hint": "Pessoas, ferramentas, lugares e tudo mais sobre o que {name} guarda fatos.",
+ "area_entities_empty": "Quando {name} aprender sobre uma pessoa ou uma coisa, a página dela aparecerá aqui.",
+ "area_projects": "Projetos",
+ "area_projects_hint": "No que você está trabalhando: metas, andamento, pendências.",
+ "area_projects_empty": "Os projetos de que {name} tomar conhecimento ganham uma página aqui.",
+ "area_concepts": "Conceitos",
+ "area_concepts_hint": "Ideias, definições e métodos que valem a pena guardar.",
+ "area_concepts_empty": "Ainda não há conceitos. Crie um para uma ideia que você quer que {name} lembre.",
+ "area_journal": "Diário",
+ "area_journal_hint": "Resumos de sessões anteriores.",
+ "area_journal_empty": "Os resumos de sessão aparecem aqui depois de escritos.",
+ "area_system": "Páginas do sistema",
+ "area_system_hint": "Como a memória funciona, seu esquema e o registro de cada alteração.",
+ "area_system_empty": "Nenhuma página do sistema.",
+ "area_agents": "Agentes",
+ "area_agents_hint": "Cada agente mantém dois cadernos: o que aprendeu sobre o seu trabalho e o que sabe sobre você.",
+ "area_empty_title": "Ainda não há nada aqui",
+ "home_title": "O que {name} lembra",
+ "home_lead": "Páginas Markdown vinculadas no seu vault do Obsidian. Elas crescem a partir das conversas e das anotações dos próprios agentes, e você pode ler, editar e conectar tudo aqui.",
+ "stat_pages": "Páginas de conhecimento",
+ "stat_links": "Links",
+ "stat_mentions": "Menções",
+ "stat_agents": "Agentes com anotações",
+ "stat_of": "de {count}",
+ "recently_changed": "Alteradas recentemente",
+ "most_connected": "Mais conectadas",
+ "backlinks_short": "{count} links",
+ "activity": "Atividade",
+ "activity_empty": "Nenhuma alteração registrada ainda.",
+ "verb_ingest": "aprendeu",
+ "verb_update": "atualizou",
+ "verb_create": "criou",
+ "verb_merge": "mesclou",
+ "verb_rename": "renomeou",
+ "verb_archive": "arquivou",
+ "verb_delete": "excluiu",
+ "vault_empty_title": "Nada lembrado ainda",
+ "vault_empty_body": "As páginas aparecem aqui conforme {name} conhece pessoas, projetos e suas preferências. Você também pode escrever a primeira.",
+ "filter": "Filtrar esta lista",
+ "filter_no_match": "Nenhuma página corresponde ao filtro.",
+ "sort": "Ordenar",
+ "sort_recent": "Recentes",
+ "sort_name": "Nome",
+ "sort_links": "Conexões",
+ "show_empty": "Mostrar {count} páginas sem conteúdo",
+ "hide_empty": "Ocultar páginas sem conteúdo",
+ "no_content_yet": "Ainda sem conteúdo",
+ "links_title": "{inbound} páginas apontam para cá, esta página aponta para {outbound}",
+ "updated": "atualizada {age}",
+ "words_count": "{count} palavras",
+ "entries_count": "{count} entradas",
+ "notes_count": "{count} anotações",
+ "agent_active": "Ativo",
+ "agent_archived": "Agente excluído",
+ "agent_orphan": "Agente desconhecido",
+ "agent_archived_short": "excluído",
+ "agent_orphan_short": "desconhecido",
+ "agent_nothing_yet": "Ainda não anotou nada.",
+ "agent_pages": "Páginas deste agente",
+ "agents_empty_title": "Nenhum caderno de agente",
+ "agents_empty_body": "Quando um agente lembrar de algo, o caderno dele aparecerá aqui.",
+ "agents_show_inactive": "Mostrar {count} agentes excluídos ou desconhecidos",
+ "agents_hide_inactive": "Ocultar agentes excluídos e desconhecidos",
+ "tidy_button": "Organizar cadernos vazios",
+ "tidy_title": "Arquivar {count} cadernos vazios?",
+ "tidy_body": "Estes cadernos pertencem a agentes excluídos ou desconhecidos e estão vazios. Eles vão para a pasta _archive do vault; nada é excluído.",
+ "tidy_confirm": "Arquivar",
+ "tidy_done": "{count} cadernos vazios arquivados.",
+ "tidy_nothing": "Não há nada para organizar.",
+ "and_more": "e mais {count}",
+ "breadcrumb": "Local",
+ "kind_entity": "Entidade",
+ "kind_person": "Pessoa",
+ "kind_project": "Projeto",
+ "kind_concept": "Conceito",
+ "kind_session": "Sessão",
+ "kind_note": "Anotação",
+ "kind_memory": "Memória",
+ "kind_profile": "Perfil",
+ "kind_shared": "Anotação compartilhada",
+ "kind_system": "Página do sistema",
+ "kind_template": "Modelo",
+ "edit": "Editar",
+ "write": "Escrever",
+ "preview": "Pré-visualizar",
+ "save": "Salvar",
+ "saved": "Salvo.",
+ "cancel": "Cancelar",
+ "editor_label": "Texto da página em Markdown",
+ "editor_hint": "[[ vincula uma página · Ctrl S salva · Esc cancela",
+ "link_suggestions": "Páginas para vincular",
+ "show_on_map": "Mostrar no mapa",
+ "open_obsidian": "Abrir no Obsidian",
+ "copy_path": "Copiar caminho do arquivo",
+ "copied": "Caminho copiado.",
+ "rename": "Renomear",
+ "rename_title": "Renomear página",
+ "rename_description": "Todos os links para esta página são atualizados para o novo nome.",
+ "renamed": "Renomeada.",
+ "renamed_links": "Renomeada. {count} links foram atualizados.",
+ "archive": "Arquivar",
+ "archive_title": "Arquivar “{title}”?",
+ "archive_body": "A página vai para a pasta _archive do vault e sai da memória. Você pode restaurá-la de lá no Obsidian.",
+ "archived": "Arquivada.",
+ "new_title": "Nova página",
+ "new_description": "Comece uma página para uma pessoa, um projeto ou uma ideia. Você pode vinculá-la a partir de outras páginas com [[o nome dela]].",
+ "new_name": "Nome",
+ "new_name_placeholder": "p. ex. Maria Weber",
+ "new_kind": "Tipo",
+ "create": "Criar",
+ "created": "“{title}” criada.",
+ "page_missing_title": "Esta página não existe mais",
+ "page_missing_body": "Ela foi renomeada, arquivada ou removida no vault.",
+ "page_empty_title": "Esta página ainda não tem conteúdo",
+ "page_empty_body": "Ela existe no vault, mas nada foi escrito nela.",
+ "page_empty_editable": "Escreva aqui o que deve ser lembrado e vincule páginas relacionadas com [[o nome delas]].",
+ "write_page": "Escrever esta página",
+ "notebook_empty_memory": "Ainda não há memórias",
+ "notebook_empty_profile": "Ainda não se sabe nada sobre você",
+ "notebook_empty_body": "{agent} não escreveu neste caderno. As entradas aparecem aqui assim que ele lembrar de algo.",
+ "important": "Importante",
+ "origin_agent": "Anotado pelo agente",
+ "origin_tool": "De um resultado de ferramenta",
+ "origin_user": "Você disse isto",
+ "origin_review": "De uma revisão",
+ "link_missing": "Esta página ainda não existe. Clique para criá-la.",
+ "connections": "Conexões",
+ "no_connections": "Esta página ainda não está conectada a nenhuma outra.",
+ "linked_from": "Vinculada a partir de",
+ "links_to": "Aponta para",
+ "mentioned_in": "Mencionada em",
+ "mentioned_in_hint": "Páginas que citam esta sem vinculá-la.",
+ "mentions": "Menções",
+ "related": "Relacionadas",
+ "related_hint": "Compartilham uma conexão com esta página.",
+ "related_via": "via {title}",
+ "unresolved_links": "Links para páginas inexistentes",
+ "properties": "Propriedades",
+ "file": "Arquivo",
+ "show_all": "Mostrar todas as {count}",
+ "show_less": "Mostrar menos",
+ "map_counts": "{pages} páginas · {links} links · {mentions} menções",
+ "map_include_agents": "Cadernos de agentes",
+ "map_fit": "Ajustar",
+ "map_error": "Não foi possível carregar o mapa.",
+ "map_empty_title": "Ainda não há nada para desenhar",
+ "map_empty_body": "O mapa mostra as páginas com conteúdo e como elas se vinculam. Ele se preenche conforme a memória cresce.",
+ "map_legend_knowledge": "Conhecimento ({count})",
+ "map_legend_agents": "Páginas de agentes ({count})",
+ "map_legend_link": "Link",
+ "map_legend_mention": "Menção",
+ "health_title": "Gravador da memória",
+ "health_green": "Saudável",
+ "health_amber": "Precisa de atenção",
+ "health_red": "Não funciona",
+ "health_unknown": "Não verificado",
+ "health_checking": "Verificando…",
+ "health_ok": "As gravações chegam ao destino e o índice de busca está atualizado.",
+ "health_writer_off": "O gravador da memória não iniciou.",
+ "health_write_failed": "A última gravação falhou.",
+ "health_index_stale": "O índice de busca tem {indexed} de {pages} páginas. Reconstrua-o para encontrar tudo.",
+ "health_backlog": "{count} fatos aprendidos aguardam gravação.",
+ "health_indexed": "Páginas no índice de busca",
+ "health_queue": "Fatos em espera",
+ "health_reindex": "Reconstruir índice de busca",
+ "health_reindexed": "Índice de busca reconstruído: {count} páginas.",
+ "health_reindex_failed": "Não foi possível reconstruir o índice de busca.",
+ "entries_count_one": "1 entrada",
+ "words_count_one": "1 palavra",
+ "notes_count_one": "1 nota",
+ "backlinks_short_one": "1 link",
+ "renamed_unrewritten": "{count} cadernos de agentes ainda apontam para o nome antigo; os próprios agentes cuidam deles."
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/memory/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/memory/zh.json
new file mode 100644
index 0000000000..16cbe6561b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/i18n/locales/memory/zh.json
@@ -0,0 +1,199 @@
+{
+ "memory_view": {
+ "title": "记忆",
+ "overview": "概览",
+ "map": "图谱",
+ "search": "搜索记忆",
+ "search_placeholder": "搜索页面、人物、项目…",
+ "search_titles": "页面",
+ "search_text": "正文",
+ "search_no_results": "未找到任何内容。",
+ "search_create": "创建页面“{title}”",
+ "searching": "搜索中…",
+ "by_meaning": "语义相近",
+ "new_page": "新建页面",
+ "back": "返回",
+ "loading": "正在加载记忆…",
+ "load_error_title": "无法加载记忆",
+ "load_error_body": "知识库没有响应。请在设置中确认 wiki 已开启。",
+ "nav_stats": "{pages} 个有内容的页面 · {links} 个连接",
+ "all_agents": "所有智能体",
+ "group_knowledge": "知识",
+ "group_agents": "智能体",
+ "group_journal": "日志",
+ "group_system": "系统",
+ "area_entities": "人物与事物",
+ "area_entities_hint": "人物、工具、地点,以及 {name} 记录了事实的其他一切。",
+ "area_entities_empty": "当 {name} 了解到某个人或某件事物时,它的页面会显示在这里。",
+ "area_projects": "项目",
+ "area_projects_hint": "你正在做的事:目标、进展、未完成的事项。",
+ "area_projects_empty": "{name} 了解到的项目会在这里有一个页面。",
+ "area_concepts": "概念",
+ "area_concepts_hint": "值得保留的想法、定义和方法。",
+ "area_concepts_empty": "还没有概念。为你想让 {name} 记住的想法创建一个吧。",
+ "area_journal": "日志",
+ "area_journal_hint": "过往会话的摘要。",
+ "area_journal_empty": "会话摘要写好后会显示在这里。",
+ "area_system": "系统页面",
+ "area_system_hint": "记忆的运作方式、结构,以及每次更改的记录。",
+ "area_system_empty": "没有系统页面。",
+ "area_agents": "智能体",
+ "area_agents_hint": "每个智能体有两本笔记:它在工作中学到的,以及它对你的了解。",
+ "area_empty_title": "这里还没有内容",
+ "home_title": "{name} 记得的内容",
+ "home_lead": "你的 Obsidian 知识库中互相链接的 Markdown 页面。它们来自对话和智能体自己的笔记,你可以在这里阅读、编辑并建立连接。",
+ "stat_pages": "知识页面",
+ "stat_links": "链接",
+ "stat_mentions": "提及",
+ "stat_agents": "有笔记的智能体",
+ "stat_of": "共 {count}",
+ "recently_changed": "最近更改",
+ "most_connected": "连接最多",
+ "backlinks_short": "{count} 个链接",
+ "activity": "动态",
+ "activity_empty": "尚无更改记录。",
+ "verb_ingest": "已学习",
+ "verb_update": "已更新",
+ "verb_create": "已创建",
+ "verb_merge": "已合并",
+ "verb_rename": "已重命名",
+ "verb_archive": "已归档",
+ "verb_delete": "已删除",
+ "vault_empty_title": "还没有记住任何内容",
+ "vault_empty_body": "随着 {name} 了解人物、项目和你的偏好,页面会出现在这里。你也可以自己写第一页。",
+ "filter": "筛选此列表",
+ "filter_no_match": "没有页面符合筛选条件。",
+ "sort": "排序",
+ "sort_recent": "最近",
+ "sort_name": "名称",
+ "sort_links": "连接数",
+ "show_empty": "显示 {count} 个无内容页面",
+ "hide_empty": "隐藏无内容页面",
+ "no_content_yet": "暂无内容",
+ "links_title": "{inbound} 个页面链接到这里,本页链接到 {outbound} 个页面",
+ "updated": "更新于{age}",
+ "words_count": "{count} 字",
+ "entries_count": "{count} 条记录",
+ "notes_count": "{count} 条笔记",
+ "agent_active": "活跃",
+ "agent_archived": "已删除的智能体",
+ "agent_orphan": "未知智能体",
+ "agent_archived_short": "已删除",
+ "agent_orphan_short": "未知",
+ "agent_nothing_yet": "还没有记录任何内容。",
+ "agent_pages": "此智能体的页面",
+ "agents_empty_title": "没有智能体笔记",
+ "agents_empty_body": "当智能体记住某件事时,它的笔记会显示在这里。",
+ "agents_show_inactive": "显示 {count} 个已删除或未知的智能体",
+ "agents_hide_inactive": "隐藏已删除和未知的智能体",
+ "tidy_button": "整理空笔记",
+ "tidy_title": "归档 {count} 本空笔记?",
+ "tidy_body": "这些笔记属于已删除或未知的智能体,且内容为空。它们会移到知识库的 _archive 文件夹,不会被删除。",
+ "tidy_confirm": "归档",
+ "tidy_done": "已归档 {count} 本空笔记。",
+ "tidy_nothing": "没有需要整理的内容。",
+ "and_more": "以及另外 {count} 个",
+ "breadcrumb": "位置",
+ "kind_entity": "实体",
+ "kind_person": "人物",
+ "kind_project": "项目",
+ "kind_concept": "概念",
+ "kind_session": "会话",
+ "kind_note": "笔记",
+ "kind_memory": "记忆",
+ "kind_profile": "档案",
+ "kind_shared": "共享笔记",
+ "kind_system": "系统页面",
+ "kind_template": "模板",
+ "edit": "编辑",
+ "write": "编写",
+ "preview": "预览",
+ "save": "保存",
+ "saved": "已保存。",
+ "cancel": "取消",
+ "editor_label": "Markdown 页面正文",
+ "editor_hint": "[[ 链接页面 · Ctrl S 保存 · Esc 取消",
+ "link_suggestions": "可链接的页面",
+ "show_on_map": "在图谱中显示",
+ "open_obsidian": "在 Obsidian 中打开",
+ "copy_path": "复制文件路径",
+ "copied": "路径已复制。",
+ "rename": "重命名",
+ "rename_title": "重命名页面",
+ "rename_description": "指向此页面的所有链接都会更新为新名称。",
+ "renamed": "已重命名。",
+ "renamed_links": "已重命名。更新了 {count} 个链接。",
+ "archive": "归档",
+ "archive_title": "归档“{title}”?",
+ "archive_body": "该页面会移到知识库的 _archive 文件夹,并从记忆中移除。你可以在 Obsidian 中从那里恢复它。",
+ "archived": "已归档。",
+ "new_title": "新建页面",
+ "new_description": "为一个人、一个项目或一个想法新建页面。你可以在其他页面中用 [[页面名称]] 链接到它。",
+ "new_name": "名称",
+ "new_name_placeholder": "例如:玛丽亚·韦伯",
+ "new_kind": "类型",
+ "create": "创建",
+ "created": "已创建“{title}”。",
+ "page_missing_title": "此页面已不存在",
+ "page_missing_body": "它已在知识库中被重命名、归档或移除。",
+ "page_empty_title": "此页面还没有内容",
+ "page_empty_body": "它存在于知识库中,但尚未写入任何内容。",
+ "page_empty_editable": "在这里写下需要记住的内容,并用 [[页面名称]] 链接相关页面。",
+ "write_page": "编写此页面",
+ "notebook_empty_memory": "还没有记忆",
+ "notebook_empty_profile": "还不了解你的任何信息",
+ "notebook_empty_body": "{agent} 还没有在这本笔记里写入内容。它一旦记住某件事,条目就会显示在这里。",
+ "important": "重要",
+ "origin_agent": "由智能体记录",
+ "origin_tool": "来自工具结果",
+ "origin_user": "你说过的",
+ "origin_review": "来自复盘",
+ "link_missing": "此页面尚不存在。点击即可创建。",
+ "connections": "连接",
+ "no_connections": "此页面尚未与任何其他页面连接。",
+ "linked_from": "被以下页面链接",
+ "links_to": "链接到",
+ "mentioned_in": "被提及于",
+ "mentioned_in_hint": "提到了此页面但没有链接的页面。",
+ "mentions": "提及",
+ "related": "相关",
+ "related_hint": "与此页面有共同连接。",
+ "related_via": "经由 {title}",
+ "unresolved_links": "指向缺失页面的链接",
+ "properties": "属性",
+ "file": "文件",
+ "show_all": "显示全部 {count} 个",
+ "show_less": "收起",
+ "map_counts": "{pages} 个页面 · {links} 个链接 · {mentions} 个提及",
+ "map_include_agents": "智能体笔记",
+ "map_fit": "适应窗口",
+ "map_error": "无法加载图谱。",
+ "map_empty_title": "暂无可绘制的内容",
+ "map_empty_body": "图谱显示有内容的页面及其相互链接。随着记忆增长,它会逐渐丰富。",
+ "map_legend_knowledge": "知识({count})",
+ "map_legend_agents": "智能体页面({count})",
+ "map_legend_link": "链接",
+ "map_legend_mention": "提及",
+ "health_title": "记忆写入器",
+ "health_green": "正常",
+ "health_amber": "需要关注",
+ "health_red": "无法工作",
+ "health_unknown": "未检查",
+ "health_checking": "检查中…",
+ "health_ok": "写入正常,搜索索引是最新的。",
+ "health_writer_off": "记忆写入器未启动。",
+ "health_write_failed": "上一次写入失败。",
+ "health_index_stale": "搜索索引仅包含 {pages} 个页面中的 {indexed} 个。请重建索引以便找到全部内容。",
+ "health_backlog": "有 {count} 条已学习的事实等待写入。",
+ "health_indexed": "搜索索引中的页面",
+ "health_queue": "等待中的事实",
+ "health_reindex": "重建搜索索引",
+ "health_reindexed": "搜索索引已重建:{count} 个页面。",
+ "health_reindex_failed": "无法重建搜索索引。",
+ "entries_count_one": "1 条记录",
+ "words_count_one": "1 个词",
+ "notes_count_one": "1 条笔记",
+ "backlinks_short_one": "1 个链接",
+ "renamed_unrewritten": "还有 {count} 个智能体笔记本链接到旧名称;由各自的智能体维护。"
+ }
+}
diff --git a/jarvis/ui/web/frontend/src/lib/memoryApi.ts b/jarvis/ui/web/frontend/src/lib/memoryApi.ts
new file mode 100644
index 0000000000..f1ebce4f4c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/memoryApi.ts
@@ -0,0 +1,259 @@
+/**
+ * Client for the path-addressed Memory API (`jarvis/ui/web/memory_vault_routes.py`).
+ *
+ * Every page is identified by its vault-relative path (`entities/ruben.md`,
+ * `society/<agent>/MEMORY.md`), never by its file name: a hundred agent
+ * notebooks share the name `MEMORY.md`.
+ */
+import { useQuery } from "@tanstack/react-query";
+
+export type MemoryGroup = "knowledge" | "agents" | "journal" | "system";
+export type MemoryKind =
+ | "entity"
+ | "person"
+ | "project"
+ | "concept"
+ | "session"
+ | "note"
+ | "memory"
+ | "profile"
+ | "shared"
+ | "system"
+ | "template";
+export type AgentState = "active" | "archived" | "orphan";
+
+export interface MemoryPageSummary {
+ path: string;
+ slug: string;
+ title: string;
+ kind: MemoryKind;
+ group: MemoryGroup;
+ folder: string;
+ agent_id: string | null;
+ mtime: number;
+ words: number;
+ empty: boolean;
+ summary: string;
+ tags: string[];
+ links_in: number;
+ links_out: number;
+}
+
+export interface MemoryAgent {
+ agent_id: string;
+ name: string;
+ state: AgentState;
+ empty: boolean;
+ updated: number;
+ pages: string[];
+}
+
+export interface MemoryStats {
+ pages: number;
+ content_pages: number;
+ empty_pages: number;
+ links: number;
+ mentions: number;
+ broken_links: number;
+}
+
+export interface MemoryIndex {
+ ok: true;
+ vault_root: string;
+ stats: MemoryStats;
+ pages: MemoryPageSummary[];
+ agents: MemoryAgent[];
+ writable: boolean;
+}
+
+export interface PageRef {
+ path: string;
+ title: string;
+ kind: MemoryKind | null;
+ group: MemoryGroup | null;
+ empty: boolean;
+ agent_id?: string | null;
+}
+
+export interface LinkRef extends PageRef {
+ context: string;
+}
+
+export interface OutgoingRef {
+ path: string | null;
+ title: string;
+ kind: MemoryKind | null;
+ broken: boolean;
+ raw: string;
+}
+
+export interface RelatedRef extends PageRef {
+ score: number;
+ via: PageRef | null;
+}
+
+export interface NotebookEntry {
+ id: string;
+ text: string;
+ importance: number;
+ origin: string;
+}
+
+export interface MemoryPage extends Omit<MemoryPageSummary, "links_in" | "links_out"> {
+ ok: true;
+ properties: Record<string, unknown>;
+ aliases: string[];
+ body_md: string;
+ size: number;
+ editable: boolean;
+ archivable: boolean;
+ agent: { agent_id: string; name: string; state: AgentState } | null;
+ entries: NotebookEntry[];
+ outgoing: OutgoingRef[];
+ backlinks: LinkRef[];
+ mentions: LinkRef[];
+ mentioned_in: LinkRef[];
+ related: RelatedRef[];
+}
+
+export interface MapNode {
+ id: string;
+ title: string;
+ kind: MemoryKind;
+ group: MemoryGroup;
+ agent_id: string | null;
+ degree: number;
+}
+
+export interface MapEdge {
+ source: string;
+ target: string;
+ kind: "link" | "mention";
+}
+
+export interface MemoryMap {
+ ok: true;
+ nodes: MapNode[];
+ edges: MapEdge[];
+}
+
+export interface ActivityItem {
+ ts: string;
+ verb: string;
+ source: string;
+ summary: string;
+ pages: { path: string; title: string; kind: MemoryKind }[];
+}
+
+export interface TidyResult {
+ ok: true;
+ dry_run: boolean;
+ count: number;
+ paths: string[];
+}
+
+export interface SearchHit {
+ path: string;
+ title: string;
+ snippet: string;
+ by_meaning: boolean;
+}
+
+/** An API refusal with the server's own sentence, ready to show. */
+export class MemoryApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+}
+
+async function request<T>(url: string, init?: RequestInit): Promise<T> {
+ const response = await fetch(url, {
+ ...init,
+ headers: init?.body ? { "Content-Type": "application/json", ...init.headers } : init?.headers,
+ });
+ let payload: unknown = null;
+ try {
+ payload = await response.json();
+ } catch {
+ payload = null;
+ }
+ if (!response.ok) {
+ const detail = (payload as { detail?: unknown } | null)?.detail;
+ const message = typeof detail === "string" ? detail : `HTTP ${response.status}`;
+ throw new MemoryApiError(message, response.status);
+ }
+ return payload as T;
+}
+
+export const MEMORY_KEYS = {
+ all: ["wiki", "memory"] as const,
+ index: ["wiki", "memory", "index"] as const,
+ page: (path: string) => ["wiki", "memory", "read", path] as const,
+ map: (agents: boolean) => ["wiki", "memory", "map", agents] as const,
+ activity: ["wiki", "memory", "activity"] as const,
+ search: (query: string) => ["wiki", "memory", "search", query] as const,
+};
+
+export const fetchMemoryIndex = () => request<MemoryIndex>("/api/wiki/index");
+export const fetchMemoryPage = (path: string) =>
+ request<MemoryPage>(`/api/wiki/read?path=${encodeURIComponent(path)}`);
+export const fetchMemoryMap = (agents: boolean) =>
+ request<MemoryMap>(`/api/wiki/map?agents=${agents ? "true" : "false"}`);
+export const fetchMemoryActivity = (limit = 30) =>
+ request<{ ok: true; items: ActivityItem[] }>(`/api/wiki/activity?limit=${limit}`);
+
+export async function searchMemory(query: string): Promise<SearchHit[]> {
+ const result = await request<{
+ ok: boolean;
+ hits?: { path: string; title: string; snippet: string; by_meaning?: boolean }[];
+ }>(`/api/wiki/search?q=${encodeURIComponent(query)}&k=12`);
+ return (result.hits ?? []).map((hit) => ({
+ path: hit.path,
+ title: hit.title,
+ snippet: hit.snippet,
+ by_meaning: Boolean(hit.by_meaning),
+ }));
+}
+
+export const createMemoryPage = (kind: "entity" | "project" | "concept", title: string, body_md = "") =>
+ request<{ ok: true; path: string }>("/api/wiki/pages", {
+ method: "POST",
+ body: JSON.stringify({ kind, title, body_md }),
+ });
+
+export const saveMemoryPage = (path: string, body_md: string, base_mtime: number | null) =>
+ request<{ ok: true; path: string; mtime: number }>("/api/wiki/pages", {
+ method: "PUT",
+ body: JSON.stringify({ path, body_md, base_mtime }),
+ });
+
+export const renameMemoryPage = (path: string, title: string) =>
+ request<{ ok: true; path: string; links_rewritten: number; links_unrewritten: number }>("/api/wiki/pages/rename", {
+ method: "POST",
+ body: JSON.stringify({ path, title }),
+ });
+
+export const archiveMemoryPage = (path: string) =>
+ request<{ ok: true; path: string }>("/api/wiki/pages/archive", {
+ method: "POST",
+ body: JSON.stringify({ path }),
+ });
+
+export const tidyMemory = (dry_run: boolean) =>
+ request<TidyResult>("/api/wiki/tidy", { method: "POST", body: JSON.stringify({ dry_run }) });
+
+export function useMemoryIndex() {
+ return useQuery({ queryKey: MEMORY_KEYS.index, queryFn: fetchMemoryIndex, staleTime: 5_000 });
+}
+
+export function useMemoryPage(path: string | null) {
+ return useQuery({
+ queryKey: MEMORY_KEYS.page(path ?? ""),
+ queryFn: () => fetchMemoryPage(path ?? ""),
+ enabled: Boolean(path),
+ staleTime: 5_000,
+ });
+}
diff --git a/jarvis/ui/web/frontend/src/lib/memoryModel.test.ts b/jarvis/ui/web/frontend/src/lib/memoryModel.test.ts
new file mode 100644
index 0000000000..e215de1a64
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/memoryModel.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+
+import type { MemoryAgent, OutgoingRef } from "@/lib/memoryApi";
+import {
+ LINK_SCHEME,
+ MISSING_SCHEME,
+ plainText,
+ prepareBody,
+ pruneEmptySections,
+ relativeAge,
+ stripComments,
+ stripLeadingTitle,
+ visibleAgents,
+} from "@/lib/memoryModel";
+
+const OUT: OutgoingRef[] = [
+ { path: "projects/magenta-ide.md", title: "Magenta IDE", kind: "project", broken: false, raw: "projects/magenta-ide" },
+ { path: null, title: "Nowhere", kind: null, broken: true, raw: "Nowhere" },
+];
+
+describe("memoryModel", () => {
+ it("routes resolved links to their path and missing ones to the create offer", () => {
+ const body = prepareBody("Works on [[projects/magenta-ide|the IDE]] and [[Nowhere]].", "Ruben", OUT);
+ expect(body).toBe(
+ `Works on [the IDE](${LINK_SCHEME}${encodeURIComponent("projects/magenta-ide.md")}) and ` +
+ `[Nowhere](${MISSING_SCHEME}Nowhere).`,
+ );
+ });
+
+ it("drops entry bookkeeping and a leading title that repeats the page title", () => {
+ const body = prepareBody('\n# Ruben\n<!-- memory-entry: {"id": "x"} -->\nPrefers short answers.\n', "Ruben", []);
+ expect(body).toBe("Prefers short answers.");
+ expect(stripLeadingTitle("# Other\nbody", "Ruben")).toBe("# Other\nbody");
+ });
+
+ it("removes headings with nothing under them, parents included", () => {
+ const skeleton = "## Summary\nThe owner.\n\n## Preferences\n\n### Food\n- \n\n## Facts\n";
+ expect(pruneEmptySections(skeleton).trim()).toBe("## Summary\nThe owner.");
+ });
+
+ it("keeps a heading whose only content sits in a sub-section", () => {
+ const body = "## Work\n### Projects\n- Magenta\n";
+ expect(pruneEmptySections(body)).toBe(body);
+ });
+
+ it("removes nested and unclosed comment openers completely", () => {
+ expect(stripComments("a <!<!-- x -->-- y --> b")).toBe("a b");
+ expect(stripComments("text <!-- never closed")).toBe("text never closed");
+ });
+
+ it("flattens Markdown for a one-line preview", () => {
+ expect(plainText("**Bold** [[entities/ruben|Ruben]] and [a link](https://x.y)")).toBe("Bold Ruben and a link");
+ });
+
+ it("lists live agents and those with notes, hides empty leftovers", () => {
+ const agents: MemoryAgent[] = [
+ { agent_id: "a", name: "Ada", state: "orphan", empty: true, updated: 0, pages: [] },
+ { agent_id: "b", name: "Bea", state: "archived", empty: false, updated: 0, pages: [] },
+ { agent_id: "c", name: "Cal", state: "active", empty: true, updated: 0, pages: [] },
+ ];
+ expect(visibleAgents(agents, false).map((agent) => agent.name)).toEqual(["Cal", "Bea"]);
+ expect(visibleAgents(agents, true)).toHaveLength(3);
+ });
+
+ it("formats a relative age", () => {
+ const now = 1_000_000 * 1000;
+ expect(relativeAge(1_000_000 - 2 * 86400, "en", now)).toBe("2 days ago");
+ expect(relativeAge(0, "en", now)).toBe("");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/lib/memoryModel.ts b/jarvis/ui/web/frontend/src/lib/memoryModel.ts
new file mode 100644
index 0000000000..b7afc09d54
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/memoryModel.ts
@@ -0,0 +1,298 @@
+/**
+ * Pure helpers for the Memory section: what each area lists, how a page
+ * body becomes readable Markdown, and how wikilinks become clickable.
+ */
+import type {
+ MemoryAgent,
+ MemoryGroup,
+ MemoryKind,
+ MemoryPageSummary,
+ OutgoingRef,
+} from "@/lib/memoryApi";
+
+export type MemoryArea = "entities" | "projects" | "concepts" | "journal" | "agents" | "system";
+
+export interface AreaDef {
+ id: MemoryArea;
+ labelKey: string;
+ descriptionKey: string;
+ matches: (page: MemoryPageSummary) => boolean;
+}
+
+export const KNOWLEDGE_AREAS: AreaDef[] = [
+ {
+ id: "entities",
+ labelKey: "memory_view.area_entities",
+ descriptionKey: "memory_view.area_entities_hint",
+ matches: (p) => p.group === "knowledge" && (p.kind === "entity" || p.kind === "person" || p.kind === "note"),
+ },
+ {
+ id: "projects",
+ labelKey: "memory_view.area_projects",
+ descriptionKey: "memory_view.area_projects_hint",
+ matches: (p) => p.group === "knowledge" && p.kind === "project",
+ },
+ {
+ id: "concepts",
+ labelKey: "memory_view.area_concepts",
+ descriptionKey: "memory_view.area_concepts_hint",
+ matches: (p) => p.group === "knowledge" && p.kind === "concept",
+ },
+ {
+ id: "journal",
+ labelKey: "memory_view.area_journal",
+ descriptionKey: "memory_view.area_journal_hint",
+ matches: (p) => p.group === "journal",
+ },
+];
+
+export const SYSTEM_AREA: AreaDef = {
+ id: "system",
+ labelKey: "memory_view.area_system",
+ descriptionKey: "memory_view.area_system_hint",
+ matches: (p) => p.group === "system",
+};
+
+export function areaOf(page: Pick<MemoryPageSummary, "group" | "kind">): MemoryArea {
+ if (page.group === "agents") return "agents";
+ if (page.group === "system") return "system";
+ for (const area of KNOWLEDGE_AREAS) {
+ if (area.matches(page as MemoryPageSummary)) return area.id;
+ }
+ return "entities";
+}
+
+export const KIND_LABEL_KEY: Record<MemoryKind, string> = {
+ entity: "memory_view.kind_entity",
+ person: "memory_view.kind_person",
+ project: "memory_view.kind_project",
+ concept: "memory_view.kind_concept",
+ session: "memory_view.kind_session",
+ note: "memory_view.kind_note",
+ memory: "memory_view.kind_memory",
+ profile: "memory_view.kind_profile",
+ shared: "memory_view.kind_shared",
+ system: "memory_view.kind_system",
+ template: "memory_view.kind_template",
+};
+
+export const GROUP_LABEL_KEY: Record<MemoryGroup, string> = {
+ knowledge: "memory_view.group_knowledge",
+ agents: "memory_view.group_agents",
+ journal: "memory_view.group_journal",
+ system: "memory_view.group_system",
+};
+
+export type SortKey = "recent" | "name" | "links";
+
+export function sortPages(pages: MemoryPageSummary[], key: SortKey): MemoryPageSummary[] {
+ const out = [...pages];
+ if (key === "name") out.sort((a, b) => a.title.localeCompare(b.title));
+ else if (key === "links")
+ out.sort((a, b) => b.links_in + b.links_out - (a.links_in + a.links_out) || b.mtime - a.mtime);
+ else out.sort((a, b) => b.mtime - a.mtime);
+ return out;
+}
+
+export function matchesQuery(page: Pick<MemoryPageSummary, "title" | "summary" | "path">, query: string): boolean {
+ const needle = query.trim().toLowerCase();
+ if (!needle) return true;
+ return (
+ page.title.toLowerCase().includes(needle) ||
+ page.summary.toLowerCase().includes(needle) ||
+ page.path.toLowerCase().includes(needle)
+ );
+}
+
+/** Agents the reader lists by default: live ones, and any that left real notes. */
+export function visibleAgents(agents: MemoryAgent[], showAll: boolean): MemoryAgent[] {
+ const ranked = [...agents].sort(
+ (a, b) =>
+ Number(b.state === "active") - Number(a.state === "active") ||
+ Number(a.empty) - Number(b.empty) ||
+ a.name.localeCompare(b.name),
+ );
+ return showAll ? ranked : ranked.filter((agent) => agent.state === "active" || !agent.empty);
+}
+
+// ------------------------------------------------------------------ markdown
+
+export const LINK_SCHEME = "#memory:";
+export const MISSING_SCHEME = "#memory-missing:";
+
+const WIKILINK_RE = /(!?)\[\[([^\]\n|]+)(?:\|([^\]\n]+))?\]\]/g;
+const COMMENT_RE = /<!--[\s\S]*?-->/g;
+
+/**
+ * Remove HTML comments (notebook entry bookkeeping) completely.
+ *
+ * One pass can leave a comment opener behind when comments are nested or
+ * split (`<!<!-- -->-- x -->`), so this repeats until nothing changes and then
+ * drops any opener that never closed. The renderer shows no raw HTML anyway;
+ * this keeps the text itself clean.
+ */
+export function stripComments(text: string, replacement = ""): string {
+ let current = text;
+ for (;;) {
+ const next = current.replace(COMMENT_RE, replacement);
+ if (next === current) break;
+ current = next;
+ }
+ return current.split("<!--").join(replacement);
+}
+const HEADING_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
+const FENCE_RE = /^\s{0,3}(```|~~~)/;
+const EMPTY_BULLET_RE = /^\s*(?:[-*+]|\d+[.)])\s*(?:\[[ xX]?\]\s*)?$/;
+
+function linkKey(raw: string): string {
+ return raw.split("|")[0].split("#")[0].trim().replace(/\\/g, "/").replace(/\.md$/i, "").toLowerCase();
+}
+
+function displayOf(raw: string): string {
+ const target = raw.split("#")[0].trim();
+ const last = target.split("/").pop() ?? target;
+ return last.replace(/\.md$/i, "");
+}
+
+/**
+ * The page body as the reader should see it:
+ *
+ * - HTML comments (notebook entry bookkeeping) removed;
+ * - a leading `# Title` that repeats the page title dropped;
+ * - headings with nothing under them removed, so a skeleton of empty
+ * sections does not read as content;
+ * - `[[wikilinks]]` turned into Markdown links the renderer can route.
+ */
+export function prepareBody(body: string, title: string, outgoing: OutgoingRef[]): string {
+ const resolved = new Map<string, OutgoingRef>();
+ for (const link of outgoing) resolved.set(linkKey(link.raw), link);
+
+ let text = stripComments(body).replace(/\r\n/g, "\n");
+ text = stripLeadingTitle(text, title);
+ text = pruneEmptySections(text);
+ // An embed (`![[page]]`) reads as a plain link here: the reader shows one
+ // page at a time.
+ return text.replace(WIKILINK_RE, (_match, _embed: string, target: string, alias?: string) => {
+ const link = resolved.get(linkKey(target));
+ const path = link?.path ?? null;
+ // Without an alias a resolved link reads as the page's title, not its file name.
+ const text = alias ?? (path && link ? link.title : displayOf(target));
+ const label = text.replace(/\\/g, "\\\\").replace(/([[\]])/g, "\\$1");
+ const href = path
+ ? `${LINK_SCHEME}${encodeURIComponent(path)}`
+ : `${MISSING_SCHEME}${encodeURIComponent(displayOf(target))}`;
+ return `[${label}](${href})`;
+ }).trim();
+}
+
+export function stripLeadingTitle(body: string, title: string): string {
+ const match = /^\s*#\s+(.+?)\s*#*\s*(?:\n|$)/.exec(body);
+ if (!match) return body;
+ const normalise = (value: string) => value.replace(/[*_`"]/g, "").trim().toLowerCase();
+ return normalise(match[1]) === normalise(title) ? body.slice(match[0].length) : body;
+}
+
+/** Remove headings whose section (up to the next heading of any level) is blank. */
+export function pruneEmptySections(body: string): string {
+ const lines = body.split("\n");
+ const keep = new Array<boolean>(lines.length).fill(true);
+ let inFence = false;
+ const headings: { index: number; level: number }[] = [];
+ lines.forEach((line, index) => {
+ if (FENCE_RE.test(line)) inFence = !inFence;
+ if (inFence) return;
+ // A bullet with no text is a placeholder, not content.
+ if (EMPTY_BULLET_RE.test(line)) keep[index] = false;
+ const match = HEADING_RE.exec(line);
+ if (match) headings.push({ index, level: match[1].length });
+ });
+ // Walk bottom-up so a parent whose only children were empty goes too.
+ const hasContent = new Map<number, boolean>();
+ for (let h = headings.length - 1; h >= 0; h -= 1) {
+ const { index, level } = headings[h];
+ let end = lines.length;
+ for (let n = h + 1; n < headings.length; n += 1) {
+ if (headings[n].level <= level) {
+ end = headings[n].index;
+ break;
+ }
+ }
+ let content = false;
+ for (let i = index + 1; i < end && !content; i += 1) {
+ const sub = headings.find((item) => item.index === i);
+ if (sub) {
+ content = hasContent.get(i) ?? false;
+ continue;
+ }
+ const stripped = lines[i].trim();
+ if (stripped && !EMPTY_BULLET_RE.test(stripped) && !/^(?:[-*_]\s*){3,}$/.test(stripped)) {
+ content = true;
+ }
+ }
+ hasContent.set(index, content);
+ if (!content) keep[index] = false;
+ }
+ return lines
+ .filter((_, index) => keep[index])
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n");
+}
+
+/** Notebook entries keep their own Markdown; this flattens one for a list row. */
+export function plainText(markdown: string, max = 200): string {
+ const text = stripComments(markdown, " ")
+ .replace(WIKILINK_RE, (_m, _e, target: string, alias?: string) => alias ?? displayOf(target))
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
+ .replace(/[#*_`>]+/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+ return text.length > max ? `${text.slice(0, max).replace(/\s+\S*$/, "")}…` : text;
+}
+
+/** A counted label: `<key>_one` for exactly one, `<key>` with `{count}` otherwise. */
+export function countText(t: (key: string) => string, key: string, count: number): string {
+ return (count === 1 ? t(`${key}_one`) : t(key)).replace("{count}", String(count));
+}
+
+/** "3 days ago" in the reader's language, from a POSIX mtime in seconds. */
+export function relativeAge(mtimeSeconds: number, language: string, nowMs = Date.now()): string {
+ if (!Number.isFinite(mtimeSeconds) || mtimeSeconds <= 0) return "";
+ const diff = mtimeSeconds - nowMs / 1000;
+ const abs = Math.abs(diff);
+ const steps: [number, Intl.RelativeTimeFormatUnit][] = [
+ [60 * 60 * 24 * 365, "year"],
+ [60 * 60 * 24 * 30, "month"],
+ [60 * 60 * 24 * 7, "week"],
+ [60 * 60 * 24, "day"],
+ [60 * 60, "hour"],
+ [60, "minute"],
+ ];
+ try {
+ const format = new Intl.RelativeTimeFormat(language, { numeric: "auto" });
+ for (const [size, unit] of steps) {
+ if (abs >= size) return format.format(Math.round(diff / size), unit);
+ }
+ return format.format(0, "minute");
+ } catch {
+ return "";
+ }
+}
+
+/** Frontmatter keys the header already shows, or that are bookkeeping only. */
+export const HIDDEN_PROPERTIES = new Set([
+ "title",
+ "slug",
+ "type",
+ "aliases",
+ "search_aliases",
+ "tags",
+ "trace",
+ "purpose",
+]);
+
+export function formatProperty(value: unknown): string {
+ if (value === null || value === undefined) return "";
+ if (Array.isArray(value)) return value.map(formatProperty).filter(Boolean).join(", ");
+ if (typeof value === "object") return JSON.stringify(value);
+ return String(value);
+}
diff --git a/jarvis/ui/web/frontend/src/lib/wikiApi.ts b/jarvis/ui/web/frontend/src/lib/wikiApi.ts
index 5f87b87f0f..b4697a6285 100644
--- a/jarvis/ui/web/frontend/src/lib/wikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/wikiApi.ts
@@ -201,7 +201,7 @@ export async function fetchWikiSearch(
* write outcome, journal backlog). Unlike the other fetchers here, this one
* swallows both HTTP-level and network-level failures and returns `null`
* instead of throwing — it is polled on a timer by `WikiHealthStrip`
- * (`WikiView.tsx`), and a transient network blip during polling must not
+ * (`MemoryView.tsx`), and a transient network blip during polling must not
* surface as an unhandled rejection. Callers treat `null` as "unknown", the
* same way the status strip treats a not-yet-resolved health check.
*/
diff --git a/jarvis/ui/web/frontend/src/lib/wikiModel.test.ts b/jarvis/ui/web/frontend/src/lib/wikiModel.test.ts
deleted file mode 100644
index 65bb2dde50..0000000000
--- a/jarvis/ui/web/frontend/src/lib/wikiModel.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- cleanTitle,
- compactAge,
- degreeOf,
- groupOfKind,
- libraryGroups,
- libraryItems,
- matchesFilter,
- readableSnippet,
- recentItems,
- uniqueEdges,
-} from "@/lib/wikiModel";
-import { stripLeadingTitle } from "@/components/wiki/PageRenderer";
-
-const FOLDERS = [
- {
- name: "entities",
- kind: "entity",
- count: 2,
- files: [
- { slug: "zoe", title: "Zoë", mtime: 10, size: 1 },
- { slug: "ada", title: "Ada", mtime: 30, size: 1 },
- ],
- },
- { name: "concepts", kind: "concept", count: 0, files: [] },
- {
- name: "society/ada",
- kind: "society",
- count: 1,
- files: [{ slug: "MEMORY", title: '"Ada — memory"', mtime: 20, size: 1 }],
- },
-];
-
-describe("wikiModel", () => {
- it("strips YAML quotes from titles and falls back to the slug", () => {
- expect(cleanTitle('"Ada — memory"')).toBe("Ada — memory");
- expect(cleanTitle("", "fallback")).toBe("fallback");
- });
-
- it("maps backend kinds onto library groups", () => {
- expect(groupOfKind("society")).toBe("agent");
- expect(groupOfKind("meta")).toBe("system");
- expect(groupOfKind("project")).toBe("project");
- expect(groupOfKind("whatever")).toBe("other");
- });
-
- it("groups pages by kind, drops empty groups and sorts by title", () => {
- const groups = libraryGroups(libraryItems(FOLDERS));
- expect(groups.map((g) => g.id)).toEqual(["entity", "agent"]);
- expect(groups[0].items.map((i) => i.title)).toEqual(["Ada", "Zoë"]);
- expect(groups[1].items[0].title).toBe("Ada — memory");
- });
-
- it("lists the newest pages first and filters accent-insensitively", () => {
- const items = libraryItems(FOLDERS);
- expect(recentItems(items, 2).map((i) => i.slug)).toEqual(["ada", "MEMORY"]);
- expect(items.filter((i) => matchesFilter(i, "zoe")).map((i) => i.slug)).toEqual(["zoe"]);
- });
-
- it("collapses repeated wikilinks into one weighted edge", () => {
- const edges = uniqueEdges([
- { source: "log", target: "memory", context: "" },
- { source: "log", target: "memory", context: "merge" },
- { source: "log", target: "memory", context: "" },
- { source: "a", target: "a", context: "" },
- { source: "a", target: "b", context: "x" },
- ]);
- expect(edges).toHaveLength(2);
- expect(edges[0]).toMatchObject({ source: "log", target: "memory", weight: 3, context: "merge" });
- expect(degreeOf(edges).get("a")).toBe(1);
- });
-
- it("formats a compact age", () => {
- const now = 1_000_000 * 1000;
- expect(compactAge(1_000_000 - 3 * 3600, "en", now)).toBe("3h");
- expect(compactAge(1_000_000 - 2 * 86400, "en", now)).toBe("2d");
- expect(compactAge(0, "en", now)).toBe("");
- });
-
- it("turns markdown snippets into words", () => {
- expect(readableSnippet("# GitHub ## Summary see [[entities/ruben]] and [[x|the label]] **now**")).toBe(
- "GitHub Summary see ruben and the label now",
- );
- });
-
- it("drops a leading H1 only when it repeats the title", () => {
- expect(stripLeadingTitle("\n# Ruben\n\n## Summary\n", "Ruben")).toBe("## Summary\n");
- expect(stripLeadingTitle("# Other\nbody", "Ruben")).toBe("# Other\nbody");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/lib/wikiModel.ts b/jarvis/ui/web/frontend/src/lib/wikiModel.ts
deleted file mode 100644
index edea309fbf..0000000000
--- a/jarvis/ui/web/frontend/src/lib/wikiModel.ts
+++ /dev/null
@@ -1,351 +0,0 @@
-// Pure view model for the Wiki section: how the vault's folders become the
-// library's groups, how a page kind is drawn, and the small formatting rules
-// every wiki surface shares. No React, no DOM — the rail, the inspector, the
-// search palette and the map canvas all read the same answers from here.
-
-import type { WikiTreeFolder } from "@/lib/wikiApi";
-
-/**
- * The groups the library shows, in display order. A vault folder maps onto
- * exactly one of them by its `kind` (see `groupOfKind`).
- */
-export const WIKI_GROUPS = [
- "entity",
- "project",
- "concept",
- "session",
- "agent",
- "system",
- "other",
-] as const;
-
-export type WikiGroupId = (typeof WIKI_GROUPS)[number];
-
-/** i18n key of each group's label, under `wiki_ui`. */
-export const GROUP_LABEL_KEY: Record<WikiGroupId, string> = {
- entity: "wiki_ui.group_entity",
- project: "wiki_ui.group_project",
- concept: "wiki_ui.group_concept",
- session: "wiki_ui.group_session",
- agent: "wiki_ui.group_agent",
- system: "wiki_ui.group_system",
- other: "wiki_ui.group_other",
-};
-
-/** Map a backend folder / node kind onto a library group. */
-export function groupOfKind(kind: string | undefined | null): WikiGroupId {
- switch (kind) {
- case "entity":
- case "concept":
- case "project":
- case "session":
- return kind;
- case "society":
- return "agent";
- case "meta":
- return "system";
- default:
- return "other";
- }
-}
-
-/**
- * Titles written by older curator runs keep the YAML quotes
- * (`"Ada — memory"`); a title is never meant to be shown quoted.
- */
-export function cleanTitle(title: string | null | undefined, fallback = ""): string {
- const raw = (title ?? "").trim();
- const unquoted = raw.replace(/^["'\p{Pi}\p{Pf}]+|["'\p{Pi}\p{Pf}]+$/gu, "").trim();
- return unquoted || fallback;
-}
-
-export interface LibraryItem {
- slug: string;
- title: string;
- /** Seconds since the epoch, as the tree reports it. */
- mtime: number;
- folder: string;
- group: WikiGroupId;
-}
-
-export interface LibraryGroup {
- id: WikiGroupId;
- items: LibraryItem[];
-}
-
-/** Flatten the tree into display items, one per page file. */
-export function libraryItems(folders: readonly WikiTreeFolder[]): LibraryItem[] {
- const out: LibraryItem[] = [];
- for (const folder of folders) {
- const group = groupOfKind(folder.kind);
- for (const file of folder.files) {
- out.push({
- slug: file.slug,
- title: cleanTitle(file.title, file.slug),
- mtime: file.mtime,
- folder: folder.name,
- group,
- });
- }
- }
- return out;
-}
-
-/**
- * Group the items for the library, alphabetically inside a group, and drop
- * groups that have nothing in them — an empty "Concepts" heading is noise.
- */
-export function libraryGroups(items: readonly LibraryItem[]): LibraryGroup[] {
- const byGroup = new Map<WikiGroupId, LibraryItem[]>();
- for (const item of items) {
- const list = byGroup.get(item.group) ?? [];
- list.push(item);
- byGroup.set(item.group, list);
- }
- const collator = new Intl.Collator(undefined, { sensitivity: "base", numeric: true });
- return WIKI_GROUPS.filter((id) => (byGroup.get(id)?.length ?? 0) > 0).map((id) => ({
- id,
- items: [...(byGroup.get(id) ?? [])].sort((a, b) => collator.compare(a.title, b.title)),
- }));
-}
-
-/** The `limit` most recently changed pages, newest first. */
-export function recentItems(items: readonly LibraryItem[], limit = 5): LibraryItem[] {
- return [...items].sort((a, b) => b.mtime - a.mtime).slice(0, limit);
-}
-
-/** Case- and accent-insensitive title/slug match for the rail filter. */
-export function matchesFilter(item: LibraryItem, query: string): boolean {
- const q = normalise(query);
- if (!q) return true;
- return normalise(item.title).includes(q) || normalise(item.slug).includes(q);
-}
-
-function normalise(value: string): string {
- return value
- .normalize("NFD")
- .replace(/\p{M}/gu, "")
- .toLowerCase()
- .trim();
-}
-
-/**
- * A compact age for a list row: `now`, `5m`, `3h`, `2d`, `4w`, `7mo`, `2y`
- * in English, the locale's narrow units elsewhere. `mtime` is in seconds.
- */
-export function compactAge(mtimeSeconds: number, language: string, nowMs = Date.now()): string {
- if (!Number.isFinite(mtimeSeconds) || mtimeSeconds <= 0) return "";
- const seconds = Math.max(0, nowMs / 1000 - mtimeSeconds);
- const steps: Array<[number, Intl.NumberFormatOptions["unit"]]> = [
- [60 * 60 * 24 * 365, "year"],
- [60 * 60 * 24 * 30, "month"],
- [60 * 60 * 24 * 7, "week"],
- [60 * 60 * 24, "day"],
- [60 * 60, "hour"],
- [60, "minute"],
- ];
- for (const [size, unit] of steps) {
- if (seconds >= size) {
- const value = Math.floor(seconds / size);
- try {
- return new Intl.NumberFormat(language, {
- style: "unit",
- unit,
- unitDisplay: "narrow",
- }).format(value);
- } catch {
- return `${value}${String(unit).charAt(0)}`;
- }
- }
- }
- try {
- return new Intl.RelativeTimeFormat(language, { numeric: "auto" }).format(0, "second");
- } catch {
- return "now";
- }
-}
-
-/** A full, localised relative time ("2 days ago") for facts and headers. */
-export function relativeAge(mtimeSeconds: number, language: string, nowMs = Date.now()): string {
- if (!Number.isFinite(mtimeSeconds) || mtimeSeconds <= 0) return "";
- const diff = mtimeSeconds - nowMs / 1000;
- const abs = Math.abs(diff);
- const steps: Array<[number, Intl.RelativeTimeFormatUnit]> = [
- [60 * 60 * 24 * 365, "year"],
- [60 * 60 * 24 * 30, "month"],
- [60 * 60 * 24 * 7, "week"],
- [60 * 60 * 24, "day"],
- [60 * 60, "hour"],
- [60, "minute"],
- [1, "second"],
- ];
- for (const [size, unit] of steps) {
- if (abs >= size || unit === "second") {
- try {
- return new Intl.RelativeTimeFormat(language, { numeric: "auto" }).format(
- Math.round(diff / size),
- unit,
- );
- } catch {
- return "";
- }
- }
- }
- return "";
-}
-
-export interface WeightedEdge {
- source: string;
- target: string;
- /** How many wikilinks this one pair carries. */
- weight: number;
- context: string;
-}
-
-/**
- * Collapse repeated wikilinks into one edge per (source, target) pair.
- *
- * An append-only log page links the same page hundreds of times; drawn
- * literally, that is a thousand overlapping arrows on a single line and the
- * map reads as a hairball. The first non-empty context is kept as the label.
- */
-export function uniqueEdges(
- edges: ReadonlyArray<{ source: string; target: string; context?: string }>,
-): WeightedEdge[] {
- const byPair = new Map<string, WeightedEdge>();
- for (const edge of edges) {
- if (edge.source === edge.target) continue;
- const key = `${edge.source}\u0000${edge.target}`;
- const existing = byPair.get(key);
- if (existing) {
- existing.weight += 1;
- if (!existing.context && edge.context) existing.context = edge.context;
- } else {
- byPair.set(key, {
- source: edge.source,
- target: edge.target,
- weight: 1,
- context: edge.context ?? "",
- });
- }
- }
- return [...byPair.values()];
-}
-
-/** Distinct neighbours per node (in either direction). */
-export function degreeOf(edges: ReadonlyArray<{ source: string; target: string }>): Map<string, number> {
- const neighbours = new Map<string, Set<string>>();
- const add = (a: string, b: string) => {
- const set = neighbours.get(a) ?? new Set<string>();
- set.add(b);
- neighbours.set(a, set);
- };
- for (const edge of edges) {
- if (edge.source === edge.target) continue;
- add(edge.source, edge.target);
- add(edge.target, edge.source);
- }
- return new Map([...neighbours].map(([id, set]) => [id, set.size]));
-}
-
-/**
- * The shape each group is drawn as — on the map canvas and as the glyph in
- * every list. Kind is told apart by SHAPE, not hue: hue in this app means
- * status or "selected", and a page's kind is neither.
- */
-export type KindShape = "circle" | "square" | "triangle" | "hexagon" | "ring" | "diamond" | "dot";
-
-export const GROUP_SHAPE: Record<WikiGroupId, KindShape> = {
- entity: "circle",
- project: "square",
- concept: "triangle",
- session: "hexagon",
- agent: "ring",
- system: "diamond",
- other: "dot",
-};
-
-/** Trace (not fill) one kind shape centred on (x, y) with radius r. */
-export function traceKindShape(
- ctx: CanvasRenderingContext2D,
- shape: KindShape,
- x: number,
- y: number,
- r: number,
-): void {
- ctx.beginPath();
- switch (shape) {
- case "square": {
- const s = r * 0.9;
- const k = s * 0.35;
- ctx.moveTo(x - s + k, y - s);
- ctx.arcTo(x + s, y - s, x + s, y + s, k);
- ctx.arcTo(x + s, y + s, x - s, y + s, k);
- ctx.arcTo(x - s, y + s, x - s, y - s, k);
- ctx.arcTo(x - s, y - s, x + s, y - s, k);
- ctx.closePath();
- break;
- }
- case "triangle": {
- const s = r * 1.15;
- ctx.moveTo(x, y - s);
- ctx.lineTo(x + s * 0.92, y + s * 0.62);
- ctx.lineTo(x - s * 0.92, y + s * 0.62);
- ctx.closePath();
- break;
- }
- case "hexagon": {
- for (let i = 0; i < 6; i += 1) {
- const a = (Math.PI / 3) * i + Math.PI / 6;
- const px = x + Math.cos(a) * r;
- const py = y + Math.sin(a) * r;
- if (i === 0) ctx.moveTo(px, py);
- else ctx.lineTo(px, py);
- }
- ctx.closePath();
- break;
- }
- case "diamond": {
- const s = r * 1.2;
- ctx.moveTo(x, y - s);
- ctx.lineTo(x + s, y);
- ctx.lineTo(x, y + s);
- ctx.lineTo(x - s, y);
- ctx.closePath();
- break;
- }
- case "dot":
- ctx.arc(x, y, r * 0.7, 0, Math.PI * 2);
- break;
- case "ring":
- case "circle":
- default:
- ctx.arc(x, y, r, 0, Math.PI * 2);
- break;
- }
-}
-
-/** Shapes drawn hollow — a ring is a circle with its middle left open. */
-export function isHollowShape(shape: KindShape): boolean {
- return shape === "ring";
-}
-
-const SNIPPET_LINK_RE = /\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]/g;
-
-/**
- * Search and backlink snippets arrive as raw Markdown — `## Goal`, `**x**`,
- * `[[target|label]]`. Show the words only.
- */
-export function readableSnippet(snippet: string): string {
- return snippet
- .replace(SNIPPET_LINK_RE, (_m, target: string, label?: string) => {
- if (label) return label.trim();
- const text = target.trim();
- const idx = Math.max(text.lastIndexOf("/"), text.lastIndexOf("\\"));
- return idx >= 0 ? text.slice(idx + 1) : text;
- })
- .replace(/(^|\s)#{1,6}\s+/g, "$1")
- .replace(/\*+|__|`/g, "")
- .replace(/\s+/g, " ")
- .trim();
-}
diff --git a/jarvis/ui/web/frontend/src/store/wikiPanel.ts b/jarvis/ui/web/frontend/src/store/wikiPanel.ts
deleted file mode 100644
index eccff45d64..0000000000
--- a/jarvis/ui/web/frontend/src/store/wikiPanel.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { create } from "zustand";
-
-/**
- * Whether the Wiki section's right-hand inspector is open.
- *
- * The toggle lives in the window caption (like the Agentic IDE's side panel)
- * and the section reads it, so the answer is one small store. It survives a
- * reload through localStorage, which may be unavailable (private window,
- * blocked storage) — then the panel simply starts open.
- */
-const OPEN_KEY = "jarvis.wiki.inspector.open.v1";
-
-function readOpen(): boolean {
- try {
- return localStorage.getItem(OPEN_KEY) !== "0";
- } catch {
- return true;
- }
-}
-
-interface WikiPanelState {
- open: boolean;
- setOpen: (open: boolean) => void;
-}
-
-export const useWikiPanelStore = create<WikiPanelState>((set) => ({
- open: readOpen(),
- setOpen: (open) => {
- try {
- localStorage.setItem(OPEN_KEY, open ? "1" : "0");
- } catch {
- // Storage unavailable: the choice holds for this session only.
- }
- set({ open });
- },
-}));
-
-/** DOM id of the inspector, for the caption toggle's aria-controls. */
-export const WIKI_INSPECTOR_ID = "wiki-inspector";
diff --git a/jarvis/ui/web/frontend/src/views/MemoryView.tsx b/jarvis/ui/web/frontend/src/views/MemoryView.tsx
new file mode 100644
index 0000000000..aa12315efd
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/MemoryView.tsx
@@ -0,0 +1,396 @@
+/**
+ * The Memory section: what the assistant and its agents remember, as linked
+ * Markdown pages in the Obsidian vault.
+ *
+ * ┌────────────┬────────────────────────────────────────────────┐
+ * │ navigation │ toolbar: back · title health · vault │
+ * │ search ├────────────────────────────────────────────────┤
+ * │ areas │ overview | area list | agents | page | map │
+ * │ agents │ │
+ * └────────────┴────────────────────────────────────────────────┘
+ *
+ * Pages are addressed by vault path everywhere (`/api/wiki/index`, `/read`,
+ * `/map`), so two files that share a name are never confused again.
+ */
+import { Suspense, lazy, useCallback, useEffect, useMemo, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { ArrowLeft, BookOpen, FileText, FolderKanban, Lightbulb, Settings2, Shapes } from "lucide-react";
+import { fill, useLocaleChunk, useT } from "@/i18n";
+import { useRunLocale } from "@/components/runs/format";
+import { useEventStore } from "@/store/events";
+import { useWikiLive } from "@/hooks/useWikiLive";
+import {
+ MEMORY_KEYS,
+ createMemoryPage,
+ tidyMemory,
+ useMemoryIndex,
+ type MemoryPageSummary,
+} from "@/lib/memoryApi";
+import { KNOWLEDGE_AREAS, SYSTEM_AREA, type MemoryArea } from "@/lib/memoryModel";
+import { EmptyState } from "@/components/ui/empty-state";
+import { MemoryNav, type NavTarget } from "@/components/memory/MemoryNav";
+import { MemoryHome } from "@/components/memory/MemoryHome";
+import { PageList } from "@/components/memory/PageList";
+import { AgentDirectory } from "@/components/memory/AgentDirectory";
+import { PageReader } from "@/components/memory/PageReader";
+import { MemorySearch } from "@/components/memory/MemorySearch";
+import { MemoryHealth } from "@/components/memory/MemoryHealth";
+import { ConfirmDialog, NewPageDialog, type CreatableKind } from "@/components/memory/MemoryDialogs";
+import { ObsidianStatus } from "@/components/wiki/ObsidianStatus";
+import { ObsidianSetupDialog } from "@/components/wiki/ObsidianSetupDialog";
+import type { ObsidianStatus as ObsidianStatusType } from "@/types/setup";
+
+// The force-directed map pulls in its own canvas engine; load it on first use.
+const MemoryMap = lazy(() => import("@/components/memory/MemoryMap"));
+
+type Route =
+ | { view: "home" }
+ | { view: "map"; focus: string | null }
+ | { view: "area"; area: MemoryArea }
+ | { view: "page"; path: string };
+
+const AREA_ICONS: Record<string, JSX.Element> = {
+ entities: <Shapes />,
+ projects: <FolderKanban />,
+ concepts: <Lightbulb />,
+ journal: <FileText />,
+ system: <Settings2 />,
+};
+
+function sameRoute(a: Route, b: Route): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+export function MemoryView(): JSX.Element {
+ const t = useT();
+ useLocaleChunk("memory");
+ const language = useRunLocale();
+ useWikiLive();
+ const queryClient = useQueryClient();
+ const indexQuery = useMemoryIndex();
+ const index = indexQuery.data;
+
+ const [history, setHistory] = useState<Route[]>([{ view: "home" }]);
+ const route = history[history.length - 1];
+ const [searchOpen, setSearchOpen] = useState(false);
+ const [creating, setCreating] = useState<{ title: string; kind: CreatableKind } | null>(null);
+ const [tidy, setTidy] = useState<string[] | null>(null);
+ const [toast, setToast] = useState<string | null>(null);
+ const [setupHint, setSetupHint] = useState<ObsidianStatusType | null>(null);
+
+ const go = useCallback((next: Route) => {
+ setHistory((stack) => (sameRoute(stack[stack.length - 1], next) ? stack : [...stack.slice(-30), next]));
+ }, []);
+ const back = useCallback(() => setHistory((stack) => (stack.length > 1 ? stack.slice(0, -1) : stack)), []);
+ const openPage = useCallback((path: string) => go({ view: "page", path }), [go]);
+
+ const notify = useCallback((message: string) => {
+ setToast(message);
+ window.setTimeout(() => setToast((current) => (current === message ? null : current)), 3200);
+ }, []);
+
+ // Ctrl/Cmd+K opens search while the section is on screen.
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
+ event.preventDefault();
+ setSearchOpen((value) => !value);
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ // Another section asked for a page by name (a contact's wiki link, say).
+ const pageRequest = useEventStore((s) => s.wikiPageRequest);
+ useEffect(() => {
+ if (!pageRequest || !index) return;
+ const wanted = pageRequest.slug.replace(/\\/g, "/").replace(/\.md$/i, "").toLowerCase();
+ const match =
+ index.pages.find((page) => page.path.replace(/\.md$/i, "").toLowerCase() === wanted) ??
+ index.pages.find((page) => page.group === "knowledge" && page.slug.toLowerCase() === wanted.split("/").pop()) ??
+ index.pages.find((page) => page.slug.toLowerCase() === wanted.split("/").pop());
+ if (match) openPage(match.path);
+ else notify(t("memory_view.page_missing_title"));
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- answer each request once, when the index is there
+ }, [pageRequest?.seq, Boolean(index)]);
+
+ // First visit: walk through the Obsidian setup when it still needs a step.
+ useEffect(() => {
+ const controller = new AbortController();
+ (async () => {
+ try {
+ const [statusResp, stateResp] = await Promise.all([
+ fetch("/api/setup/obsidian/status", { signal: controller.signal }),
+ fetch("/api/setup/state", { signal: controller.signal }),
+ ]);
+ if (!statusResp.ok || !stateResp.ok) return;
+ const status = (await statusResp.json()) as ObsidianStatusType;
+ const state = (await stateResp.json()) as { obsidian_setup_seen: boolean };
+ if (state.obsidian_setup_seen === false && status.recommended_action !== "ok") setSetupHint(status);
+ } catch (err) {
+ if ((err as { name?: string })?.name !== "AbortError") console.debug("[MemoryView] setup probe failed:", err);
+ }
+ })();
+ return () => controller.abort();
+ }, []);
+
+ const navigate = useCallback(
+ (target: NavTarget) => {
+ if (target.view === "home") go({ view: "home" });
+ else if (target.view === "map") go({ view: "map", focus: null });
+ else if (target.view === "area") go({ view: "area", area: target.area });
+ else {
+ const agent = index?.agents.find((item) => item.agent_id === target.agentId);
+ const pages = (agent?.pages ?? [])
+ .map((path) => index?.pages.find((page) => page.path === path))
+ .filter((page): page is MemoryPageSummary => Boolean(page));
+ const first =
+ pages.find((page) => page.kind === "memory" && !page.empty) ??
+ pages.find((page) => page.kind === "profile" && !page.empty) ??
+ pages.find((page) => !page.empty) ??
+ pages[0];
+ if (first) openPage(first.path);
+ }
+ },
+ [go, index, openPage],
+ );
+
+ const createPage = useCallback(
+ async (kind: CreatableKind, title: string) => {
+ const result = await createMemoryPage(kind, title);
+ await queryClient.invalidateQueries({ queryKey: MEMORY_KEYS.all });
+ setCreating(null);
+ notify(fill(t("memory_view.created"), { title }));
+ openPage(result.path);
+ },
+ [notify, openPage, queryClient, t],
+ );
+
+ const startTidy = useCallback(async () => {
+ try {
+ const preview = await tidyMemory(true);
+ if (preview.count === 0) notify(t("memory_view.tidy_nothing"));
+ else setTidy(preview.paths);
+ } catch (err) {
+ notify(err instanceof Error ? err.message : String(err));
+ }
+ }, [notify, t]);
+
+ const currentPage = route.view === "page" ? index?.pages.find((page) => page.path === route.path) : undefined;
+ const activeNav: NavTarget["view"] | MemoryArea | null =
+ route.view === "page"
+ ? currentPage?.group === "agents"
+ ? "agents"
+ : null
+ : route.view === "area"
+ ? route.area
+ : route.view;
+
+ const obsidian = useMemo(
+ () => <ObsidianStatus onOpenSetup={(status) => setSetupHint(status)} />,
+ [],
+ );
+
+ const toolbarTitle =
+ route.view === "page"
+ ? currentPage?.title ?? ""
+ : route.view === "area"
+ ? route.area === "agents"
+ ? t("memory_view.area_agents")
+ : t(`memory_view.area_${route.area}`)
+ : route.view === "map"
+ ? t("memory_view.map")
+ : t("memory_view.overview");
+
+ return (
+ <div className="flex h-full min-h-0 bg-sidebar" data-testid="memory-view">
+ <MemoryNav
+ index={index}
+ active={activeNav}
+ activeAgentId={currentPage?.agent_id ?? null}
+ onNavigate={navigate}
+ onSearch={() => setSearchOpen(true)}
+ onNewPage={() => setCreating({ title: "", kind: "entity" })}
+ />
+
+ <main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-tl-xl border-l border-t border-border bg-background">
+ <div className="flex h-11 shrink-0 items-center gap-2 border-b border-border px-3">
+ <button
+ type="button"
+ onClick={back}
+ disabled={history.length < 2}
+ aria-label={t("memory_view.back")}
+ title={t("memory_view.back")}
+ className="grid h-8 w-8 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground disabled:pointer-events-none disabled:opacity-30"
+ >
+ <ArrowLeft className="h-4 w-4" aria-hidden />
+ </button>
+ <span className="min-w-0 truncate text-sm font-medium text-foreground" data-testid="memory-toolbar-title">
+ {toolbarTitle}
+ </span>
+ <div className="ml-auto flex items-center gap-1">
+ <MemoryHealth />
+ {obsidian}
+ </div>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
+ {indexQuery.isLoading ? (
+ <div className="flex flex-1 items-center justify-center text-sm text-muted-foreground" role="status">
+ {t("memory_view.loading")}
+ </div>
+ ) : indexQuery.isError || !index ? (
+ <div className="flex flex-1 items-center justify-center p-8">
+ <EmptyState
+ icon={<BookOpen />}
+ title={t("memory_view.load_error_title")}
+ description={indexQuery.error instanceof Error ? indexQuery.error.message : t("memory_view.load_error_body")}
+ />
+ </div>
+ ) : route.view === "page" ? (
+ <PageReader
+ key={route.path}
+ path={route.path}
+ index={index}
+ language={language}
+ onOpen={openPage}
+ onArea={(area) => go({ view: "area", area })}
+ onShowOnMap={(path) => go({ view: "map", focus: path })}
+ onCreate={(title) => setCreating({ title, kind: "entity" })}
+ onArchived={back}
+ notify={notify}
+ />
+ ) : route.view === "map" ? (
+ <Suspense fallback={<div className="flex-1" />}>
+ <MemoryMap focus={route.focus} onOpen={openPage} />
+ </Suspense>
+ ) : (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ {route.view === "home" ? (
+ <MemoryHome
+ index={index}
+ language={language}
+ onOpen={openPage}
+ onNewPage={() => setCreating({ title: "", kind: "entity" })}
+ onShowAgents={() => go({ view: "area", area: "agents" })}
+ />
+ ) : route.area === "agents" ? (
+ <AgentDirectory index={index} language={language} onOpen={openPage} onTidy={() => void startTidy()} />
+ ) : (
+ <AreaList
+ area={route.area}
+ pages={index.pages}
+ language={language}
+ onOpen={openPage}
+ onNew={
+ index.writable && route.area !== "system" && route.area !== "journal"
+ ? () =>
+ setCreating({
+ title: "",
+ kind: route.area === "projects" ? "project" : route.area === "concepts" ? "concept" : "entity",
+ })
+ : undefined
+ }
+ />
+ )}
+ </div>
+ )}
+ </div>
+ </main>
+
+ <MemorySearch
+ open={searchOpen}
+ onOpenChange={setSearchOpen}
+ index={index}
+ onOpen={openPage}
+ onCreate={(title) => setCreating({ title, kind: "entity" })}
+ />
+ <NewPageDialog
+ open={creating !== null}
+ initialTitle={creating?.title ?? ""}
+ initialKind={creating?.kind ?? "entity"}
+ onClose={() => setCreating(null)}
+ onCreate={createPage}
+ />
+ <ConfirmDialog
+ open={tidy !== null}
+ title={fill(t("memory_view.tidy_title"), { count: tidy?.length ?? 0 })}
+ description={t("memory_view.tidy_body")}
+ confirmLabel={t("memory_view.tidy_confirm")}
+ items={tidy ?? []}
+ onClose={() => setTidy(null)}
+ onConfirm={async () => {
+ const result = await tidyMemory(false);
+ await queryClient.invalidateQueries({ queryKey: MEMORY_KEYS.all });
+ setTidy(null);
+ notify(fill(t("memory_view.tidy_done"), { count: result.count }));
+ }}
+ />
+ {setupHint && (
+ <ObsidianSetupDialog
+ open
+ onClose={() => setSetupHint(null)}
+ initialStatus={setupHint}
+ onComplete={async () => {
+ try {
+ await fetch("/api/setup/state/obsidian-seen", { method: "POST" });
+ } catch (err) {
+ console.debug("[MemoryView] mark-obsidian-seen failed:", err);
+ }
+ }}
+ />
+ )}
+ {toast && (
+ <div
+ role="status"
+ data-testid="memory-toast"
+ className="pointer-events-none fixed bottom-10 right-6 z-[110] max-w-sm rounded-lg border border-border bg-popover px-4 py-3 text-sm text-foreground shadow-float"
+ >
+ {toast}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function AreaList({
+ area,
+ pages,
+ language,
+ onOpen,
+ onNew,
+}: {
+ area: MemoryArea;
+ pages: MemoryPageSummary[];
+ language: string;
+ onOpen: (path: string) => void;
+ onNew?: () => void;
+}) {
+ const t = useT();
+ const def = [...KNOWLEDGE_AREAS, SYSTEM_AREA].find((item) => item.id === area) ?? KNOWLEDGE_AREAS[0];
+ const inArea = pages.filter((page) => def.matches(page));
+ return (
+ <PageList
+ title={t(def.labelKey)}
+ description={t(def.descriptionKey)}
+ pages={inArea}
+ language={language}
+ onOpen={onOpen}
+ emptyIcon={AREA_ICONS[area] ?? <BookOpen />}
+ emptyTitle={t("memory_view.area_empty_title")}
+ emptyBody={t(`memory_view.area_${area}_empty`)}
+ actions={
+ onNew ? (
+ <button
+ type="button"
+ onClick={onNew}
+ className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-3 text-sm font-medium text-foreground transition-colors hover:bg-secondary"
+ >
+ {t("memory_view.new_page")}
+ </button>
+ ) : undefined
+ }
+ />
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
deleted file mode 100644
index 041cfebb52..0000000000
--- a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
+++ /dev/null
@@ -1,655 +0,0 @@
-/**
- * Component tests for WikiView and its sub-components.
- *
- * Mocks the fetch surface defined in `src/lib/wikiApi.ts`. The contract is
- * documented in `docs/plans/b3/00-OVERVIEW.md` §3.1 — these tests pin the
- * client-side projection of that contract.
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-
-import { WikiView } from "@/views/WikiView";
-import { useWikiPanelStore } from "@/store/wikiPanel";
-import { PageRenderer, preprocessWikilinks } from "@/components/wiki/PageRenderer";
-import { PageHeader } from "@/components/wiki/PageHeader";
-import type {
- WikiPageResponse,
- WikiTreeResponse,
- WikiBacklinksResponse,
- WikiHealthSnapshot,
-} from "@/lib/wikiApi";
-
-const { useWikiLiveMock } = vi.hoisted(() => ({
- useWikiLiveMock: vi.fn(() => ({ connected: true, lastEventAt: null })),
-}));
-
-vi.mock("@/hooks/useWikiLive", () => ({
- useWikiLive: useWikiLiveMock,
-}));
-
-vi.mock("@/components/wiki/WikiGraph", () => ({
- WikiGraph: ({ onNodeClick }: { onNodeClick: (slug: string) => void }) => (
- <button type="button" onClick={() => onNodeClick("example-parent")}>
- Example Parent graph node
- </button>
- ),
-}));
-
-function freshClient(): QueryClient {
- return new QueryClient({
- defaultOptions: {
- queries: { retry: false, gcTime: 0, staleTime: 0 },
- },
- });
-}
-
-function renderWithClient(node: React.ReactNode) {
- const client = freshClient();
- return render(
- <QueryClientProvider client={client}>{node}</QueryClientProvider>,
- );
-}
-
-/**
- * Install a mock for global `fetch` that returns whatever JSON the mapping
- * function provides for each URL prefix. Unknown URLs throw, so we notice
- * accidental network calls in tests.
- */
-function installFetchMock(
- routes: Record<string, () => unknown>,
-): ReturnType<typeof vi.fn> {
- const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url.startsWith("/api/setup/obsidian/status")) {
- return {
- ok: true,
- status: 200,
- statusText: "OK",
- json: async () => ({
- installed: true,
- config_exists: true,
- vault_registered: true,
- recommended_action: "ok",
- }),
- } as Response;
- }
- if (url.startsWith("/api/setup/state")) {
- return {
- ok: true,
- status: 200,
- statusText: "OK",
- json: async () => ({
- completed: true,
- }),
- } as Response;
- }
- for (const prefix of Object.keys(routes)) {
- if (url.startsWith(prefix)) {
- const body = routes[prefix]();
- return {
- ok: true,
- status: 200,
- statusText: "OK",
- json: async () => body,
- } as Response;
- }
- }
- throw new Error(`unexpected fetch ${url}`);
- });
- // jsdom may not have a typed fetch by default; cast through `unknown` to
- // satisfy TS while still ensuring the runtime override happens.
- (globalThis as unknown as { fetch: typeof fetch }).fetch =
- fetchMock as unknown as typeof fetch;
- return fetchMock;
-}
-
-const EMPTY_TREE: WikiTreeResponse = {
- ok: true,
- vault_root: "wiki/obsidian-vault",
- folders: [
- { name: "entities", kind: "entity", count: 0, files: [] },
- { name: "concepts", kind: "concept", count: 0, files: [] },
- { name: "projects", kind: "project", count: 0, files: [] },
- { name: "sessions", kind: "session", count: 0, files: [] },
- ],
- stats: { total_pages: 0, total_links: 0, last_curator_run: null },
-};
-
-const POPULATED_TREE: WikiTreeResponse = {
- ok: true,
- vault_root: "wiki/obsidian-vault",
- folders: [
- {
- name: "entities",
- kind: "entity",
- count: 2,
- files: [
- { slug: "example-user", title: "Example User", mtime: 1, size: 100 },
- { slug: "example-parent", title: "Example Parent", mtime: 2, size: 200 },
- ],
- },
- { name: "concepts", kind: "concept", count: 0, files: [] },
- {
- name: "projects",
- kind: "project",
- count: 1,
- files: [
- { slug: "pixel-art-editor", title: "Pixel Art Editor", mtime: 3, size: 50 },
- ],
- },
- { name: "sessions", kind: "session", count: 0, files: [] },
- ],
- stats: { total_pages: 3, total_links: 8, last_curator_run: "2026-05-13T13:59:00" },
-};
-
-const EXAMPLE_PARENT_PAGE: WikiPageResponse = {
- ok: true,
- slug: "example-parent",
- kind: "entity",
- title: "Example Parent",
- path: "entities/example-parent.md",
- frontmatter: {
- type: "entity",
- entity_kind: "person",
- slug: "example-parent",
- aliases: [],
- created: "2026-05-13",
- updated: "2026-05-13",
- },
- body_md: "# Example Parent\n\n## Relationships\n\nRelated to [[example-user]] in this synthetic fixture.\n",
- wikilinks: ["example-user"],
- stats: { words: 17, bytes: 289, mtime: 1 },
-};
-
-const EXAMPLE_PARENT_BACKLINKS: WikiBacklinksResponse = {
- ok: true,
- slug: "example-parent",
- backlinks: [
- {
- slug: "example-user",
- title: "Example User",
- snippet: "...Related to [[example-parent]] in this synthetic fixture...",
- },
- ],
-};
-
-afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
-});
-
-beforeEach(() => {
- useWikiLiveMock.mockClear();
-});
-
-describe("WikiView — empty state", () => {
- it("renders the empty-state card when the tree returns 0 pages", async () => {
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- });
- renderWithClient(<WikiView />);
- expect(useWikiLiveMock).toHaveBeenCalledTimes(1);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-empty-state")).toBeDefined();
- });
- expect(screen.getByText(/Your wiki is still empty/i)).toBeDefined();
- });
-});
-
-describe("WikiView — populated tree", () => {
- beforeEach(() => {
- installFetchMock({
- "/api/wiki/tree": () => POPULATED_TREE,
- "/api/wiki/page/": () => EXAMPLE_PARENT_PAGE,
- "/api/wiki/backlinks/": () => EXAMPLE_PARENT_BACKLINKS,
- });
- });
-
- it("renders folder counts and visible leaves for non-empty folders", async () => {
- renderWithClient(<WikiView />);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-tree-sidebar")).toBeDefined();
- });
-
- // People and projects open by default, listed by title, not file name.
- await waitFor(() => {
- const entities = screen.getByTestId("wiki-folder-entity");
- expect(within(entities).getByText("Example User")).toBeDefined();
- expect(within(entities).getByText("Example Parent")).toBeDefined();
- const projects = screen.getByTestId("wiki-folder-project");
- expect(within(projects).getByText("Pixel Art Editor")).toBeDefined();
- });
-
- // The group heading carries the count; an empty folder is no group at all.
- expect(document.querySelector("[data-folder='entity']")!.textContent).toContain("2");
- expect(document.querySelector("[data-folder='concept']")).toBeNull();
-
- // The most recently changed page leads the rail.
- const recent = screen.getAllByTestId("wiki-library-recent-item");
- expect(recent[0].getAttribute("data-slug")).toBe("pixel-art-editor");
- });
-
- it("narrows every group as the filter is typed", async () => {
- renderWithClient(<WikiView />);
- const filter = await screen.findByTestId("wiki-library-filter");
- await screen.findByTestId("wiki-folder-entity");
-
- fireEvent.change(filter, { target: { value: "pixel" } });
-
- expect(screen.queryByTestId("wiki-folder-entity")).toBeNull();
- expect(within(screen.getByTestId("wiki-folder-project")).getByText("Pixel Art Editor")).toBeDefined();
- expect(screen.queryByTestId("wiki-library-recent")).toBeNull();
- });
-
- it("expands the Memory Map across the wiki workspace and restores the side panels", async () => {
- renderWithClient(<WikiView />);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-tree-sidebar")).toBeDefined();
- });
-
- const workspace = screen.getByTestId("wiki-workspace");
- const expandButton = screen.getByRole("button", {
- name: "Expand the Memory Map",
- });
- expect(workspace.getAttribute("data-graph-expanded")).toBe("false");
- expect(expandButton.getAttribute("aria-controls")).toBe("wiki-workspace");
- expect(expandButton.getAttribute("aria-expanded")).toBe("false");
- expect(screen.queryByTestId("wiki-backlinks-placeholder")).not.toBeNull();
-
- fireEvent.click(expandButton);
-
- expect(workspace.getAttribute("data-graph-expanded")).toBe("true");
- expect(workspace.classList.contains("z-[100]")).toBe(true);
- expect(screen.queryByTestId("wiki-tree-sidebar")).toBeNull();
- expect(screen.queryByTestId("wiki-backlinks-placeholder")).toBeNull();
-
- const restoreButton = screen.getByRole("button", {
- name: "Restore the standard wiki layout",
- });
- expect(restoreButton.getAttribute("aria-expanded")).toBe("true");
- fireEvent.click(restoreButton);
-
- expect(workspace.getAttribute("data-graph-expanded")).toBe("false");
- expect(screen.queryByTestId("wiki-tree-sidebar")).not.toBeNull();
- expect(screen.queryByTestId("wiki-backlinks-placeholder")).not.toBeNull();
- });
-
- it("hides the side panel when the caption toggle closes it", async () => {
- useWikiPanelStore.setState({ open: false });
- try {
- renderWithClient(<WikiView />);
- await screen.findByTestId("wiki-folder-entity");
- expect(screen.queryByTestId("wiki-backlinks-placeholder")).toBeNull();
- act(() => useWikiPanelStore.getState().setOpen(true));
- expect(screen.queryByTestId("wiki-backlinks-placeholder")).not.toBeNull();
- } finally {
- useWikiPanelStore.setState({ open: true });
- }
- });
-
- it("clicking a leaf in the tree switches to the page tab and loads the page", async () => {
- renderWithClient(<WikiView />);
-
- const entities = await screen.findByTestId("wiki-folder-entity");
- fireEvent.click(within(entities).getByText("Example Parent"));
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-page-renderer")).toBeDefined();
- });
- expect(screen.getByTestId("wiki-page-title").textContent).toBe("Example Parent");
- }, 10_000);
-
- it("clicking the already-selected graph node returns to its page", async () => {
- renderWithClient(<WikiView />);
-
- const entities = await screen.findByTestId("wiki-folder-entity");
- fireEvent.click(within(entities).getByText("Example Parent"));
- await screen.findByTestId("wiki-page-renderer");
- fireEvent.click(screen.getByTestId("wiki-tab-graph"));
- fireEvent.click(await screen.findByRole("button", {
- name: "Example Parent graph node",
- }));
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-page-renderer")).toBeDefined();
- });
- });
-});
-
-describe("WikiView — health strip", () => {
- const HEALTHY_HEALTH: WikiHealthSnapshot = {
- bootstrap_ok: true,
- bootstrap_error: null,
- vault_root: "wiki/obsidian-vault",
- vault_root_source: "config",
- vault_legacy_conflict: false,
- last_write: {
- ts: 1750000000,
- ok: true,
- pages: ["example-user"],
- error: null,
- source: "curator",
- },
- last_chain_failure: null,
- journal_backlog: 0,
- indexed_pages: 1,
- vault_pages: 1,
- index_state: "ok",
- capture_funnel: {
- window_hours: 24,
- total: 107,
- started: 1,
- filtered: 30,
- empty: 46,
- candidates: 31,
- failed: 2,
- facts: 44,
- sessions_swept: 3,
- stage2_pending: 4,
- stage2_add: 4,
- stage2_update: 5,
- stage2_noop: 8,
- stage2_invalidate: 1,
- stage2_rejected: 2,
- stage2_skipped: 1,
- writes: 9,
- },
- capture_error: null,
- };
-
- const FAILED_HEALTH: WikiHealthSnapshot = {
- bootstrap_ok: true,
- bootstrap_error: null,
- vault_root: "wiki/obsidian-vault",
- vault_root_source: "config",
- vault_legacy_conflict: false,
- last_write: {
- ts: 1750000000,
- ok: false,
- pages: [],
- error: "Permission denied writing entities/example-user.md",
- source: "curator",
- },
- last_chain_failure: null,
- journal_backlog: 3,
- indexed_pages: 0,
- vault_pages: 1,
- index_state: "stale",
- capture_funnel: {
- window_hours: 24,
- total: 0,
- started: 0,
- filtered: 0,
- empty: 0,
- candidates: 0,
- failed: 0,
- facts: 0,
- sessions_swept: 0,
- stage2_pending: 0,
- stage2_add: 0,
- stage2_update: 0,
- stage2_noop: 0,
- stage2_invalidate: 0,
- stage2_rejected: 0,
- stage2_skipped: 0,
- writes: 0,
- },
- capture_error: null,
- };
-
- it("renders the vault path for a healthy snapshot", async () => {
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({ ok: true, health: HEALTHY_HEALTH }),
- });
- renderWithClient(<WikiView />);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-health-strip")).toBeDefined();
- });
- await waitFor(() => {
- expect(screen.getByTestId("wiki-health-vault").textContent).toContain(
- "wiki/obsidian-vault",
- );
- });
- expect(
- screen.getByTestId("wiki-health-dot").getAttribute("data-visual"),
- ).toBe("green");
- expect(screen.getByTestId("wiki-capture-funnel").textContent).toContain(
- "last 24 h",
- );
- expect(screen.getByTestId("wiki-capture-reviewed").textContent).toContain("107");
- expect(screen.getByTestId("wiki-capture-candidate-reviews").textContent).toContain(
- "31",
- );
- expect(screen.getByTestId("wiki-capture-candidate-facts").textContent).toContain(
- "44",
- );
- expect(screen.getByTestId("wiki-capture-writes").textContent).toContain("9");
- expect(screen.getByTestId("wiki-capture-session-sweeps").textContent).toContain("3");
- expect(screen.getByTestId("wiki-capture-failed-detail").textContent).toContain(
- "2",
- );
- });
-
- it("renders the error text for a failed last write, and the backlog count", async () => {
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({ ok: true, health: FAILED_HEALTH }),
- });
- renderWithClient(<WikiView />);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-health-write").textContent).toContain(
- "Permission denied writing entities/example-user.md",
- );
- });
- expect(
- screen.getByTestId("wiki-health-dot").getAttribute("data-visual"),
- ).toBe("red");
- expect(screen.getByTestId("wiki-health-backlog").textContent).toContain("3");
- });
-
- it("rebuilds a stale search index from the health strip", async () => {
- const stale = { ...HEALTHY_HEALTH, indexed_pages: 0, index_state: "stale" as const };
- const fetchMock = installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({ ok: true, health: stale }),
- "/api/wiki/reindex": () => ({ ok: true, indexed_pages: 1, vault_pages: 1 }),
- });
- renderWithClient(<WikiView />);
-
- const button = await screen.findByTestId("wiki-health-reindex");
- fireEvent.click(button);
-
- await waitFor(() => {
- expect(fetchMock).toHaveBeenCalledWith(
- "/api/wiki/reindex",
- { method: "POST" },
- );
- });
- });
-
- it("keeps the reindex failure detail visible beside the retry action", async () => {
- const stale = { ...HEALTHY_HEALTH, indexed_pages: 0, index_state: "stale" as const };
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({ ok: true, health: stale }),
- "/api/wiki/reindex": () => ({ ok: false, error: "FTS database is locked" }),
- });
- renderWithClient(<WikiView />);
-
- fireEvent.click(await screen.findByTestId("wiki-health-reindex"));
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-health-reindex-error").textContent).toContain(
- "FTS database is locked",
- );
- });
- });
-
- it("localises a reindex failure without a backend detail", async () => {
- const stale = { ...HEALTHY_HEALTH, indexed_pages: 0, index_state: "stale" as const };
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({ ok: true, health: stale }),
- "/api/wiki/reindex": () => ({ ok: false }),
- });
- renderWithClient(<WikiView />);
-
- fireEvent.click(await screen.findByTestId("wiki-health-reindex"));
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-health-reindex-error").textContent).toContain(
- "The wiki search index could not be rebuilt.",
- );
- });
- expect(screen.getByTestId("wiki-health-reindex-error").textContent).not.toContain(
- "index rebuild failed",
- );
- });
-
- it("shows the capture-store error detail instead of a generic badge", async () => {
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({
- ok: true,
- health: { ...HEALTHY_HEALTH, capture_error: "capture database is locked" },
- }),
- });
- renderWithClient(<WikiView />);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-capture-error").textContent).toContain(
- "capture database is locked",
- );
- });
- });
-
- it("localises the capture-store sentinel returned by the health API", async () => {
- installFetchMock({
- "/api/wiki/tree": () => EMPTY_TREE,
- "/api/wiki/health": () => ({
- ok: true,
- health: { ...HEALTHY_HEALTH, capture_error: "capture_store_unavailable" },
- }),
- });
- renderWithClient(<WikiView />);
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-capture-error").textContent).toBe(
- "Capture store unavailable",
- );
- });
- expect(screen.getByTestId("wiki-capture-error").textContent).not.toContain(
- "capture_store_unavailable",
- );
- });
-});
-
-describe("PageRenderer — wikilink behaviour", () => {
- it("preprocessWikilinks rewrites [[slug]] / [[folder/slug]] / [[slug|label]]", () => {
- expect(preprocessWikilinks("see [[example-user]] here")).toBe(
- "see [example-user](#wiki:example-user) here",
- );
- expect(preprocessWikilinks("see [[entities/example-user]] here")).toBe(
- "see [example-user](#wiki:example-user) here",
- );
- expect(preprocessWikilinks("see [[example-user|the related entity]] here")).toBe(
- "see [the related entity](#wiki:example-user) here",
- );
- });
-
- it("preprocessWikilinks escapes backslashes in labels", () => {
- expect(preprocessWikilinks("[[example-user|a\\b]]")).toBe(
- "[a\\\\b](#wiki:example-user)",
- );
- expect(preprocessWikilinks("[[example-user|trail\\]]")).toBe(
- "[trail\\\\](#wiki:example-user)",
- );
- });
-
- it("clicking a wikilink fires onWikilinkClick with the target slug", async () => {
- installFetchMock({
- "/api/wiki/tree": () => POPULATED_TREE,
- "/api/wiki/page/example-parent": () => EXAMPLE_PARENT_PAGE,
- });
- const onClick = vi.fn();
- renderWithClient(
- <PageRenderer slug="example-parent" onWikilinkClick={onClick} />,
- );
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-page-renderer")).toBeDefined();
- });
-
- const link = document.querySelector(
- "a.wikilink[data-target-slug='example-user']",
- ) as HTMLAnchorElement | null;
- expect(link).not.toBeNull();
- fireEvent.click(link!);
- expect(onClick).toHaveBeenCalledWith("example-user");
- });
-
- it("renders a broken wikilink with the `.broken` class when the slug is unknown", async () => {
- const brokenPage: WikiPageResponse = {
- ...EXAMPLE_PARENT_PAGE,
- body_md: "Refers to [[nonexistent-slug]] which doesn't exist.\n",
- wikilinks: ["nonexistent-slug"],
- };
- installFetchMock({
- "/api/wiki/tree": () => POPULATED_TREE,
- "/api/wiki/page/example-parent": () => brokenPage,
- });
- renderWithClient(
- <PageRenderer slug="example-parent" onWikilinkClick={vi.fn()} />,
- );
-
- await waitFor(() => {
- expect(screen.getByTestId("wiki-page-renderer")).toBeDefined();
- });
-
- const link = document.querySelector(
- "a.wikilink[data-target-slug='nonexistent-slug']",
- ) as HTMLAnchorElement | null;
- expect(link).not.toBeNull();
- expect(link!.className).toContain("broken");
- });
-});
-
-describe("PageHeader — frontmatter pills", () => {
- it("renders pills for known frontmatter keys and skips slug + aliases", () => {
- render(
- <PageHeader
- slug="example-parent"
- kind="entity"
- title="Example Parent"
- frontmatter={{
- type: "entity",
- entity_kind: "person",
- slug: "example-parent",
- aliases: ["herry", "h"],
- created: "2026-05-13",
- updated: "2026-05-13",
- }}
- vaultRoot="C:/vault/Jarvis"
- vaultRelPath="entities/example-parent.md"
- />,
- );
-
- const pills = document.querySelectorAll("[data-pill-key]");
- const keys = Array.from(pills).map((el) =>
- el.getAttribute("data-pill-key"),
- );
- expect(keys).toContain("type");
- expect(keys).toContain("entity_kind");
- expect(keys).toContain("created");
- expect(keys).toContain("updated");
- expect(keys).not.toContain("slug");
- expect(keys).not.toContain("aliases");
- });
-});
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.tsx b/jarvis/ui/web/frontend/src/views/WikiView.tsx
deleted file mode 100644
index 4dc9d3f76a..0000000000
--- a/jarvis/ui/web/frontend/src/views/WikiView.tsx
+++ /dev/null
@@ -1,562 +0,0 @@
-/**
- * The Wiki section: the assistant's long-term memory, as the Obsidian vault
- * on disk holds it.
- *
- * Read-only — writes happen via the wiki curator or the user editing Markdown
- * files in Obsidian. This view is a projection of the vault exposed through
- * the `/api/wiki/*` endpoints.
- *
- * One viewport, three regions, nothing below the fold:
- *
- * ┌───────────┬──────────────────────────────┬────────────┐
- * │ library │ stage: memory map | page │ inspector │
- * │ 264 px │ (fills the rest) │ 300 px │
- * └───────────┴──────────────────────────────┴────────────┘
- *
- * The library finds a page, the stage shows it (or the whole vault as a
- * map), and the inspector tells you how it connects — or, with nothing open,
- * whether the memory is healthy and what it took in today.
- */
-import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { BookOpen, Maximize2, Minimize2, Network, Search, X } from "lucide-react";
-import { useQuery } from "@tanstack/react-query";
-
-import { cn } from "@/lib/utils";
-import { useT } from "@/i18n";
-import { useRunLocale } from "@/components/runs/format";
-import { useEventStore } from "@/store/events";
-import { useWikiPanelStore } from "@/store/wikiPanel";
-import {
- fetchWikiHealth,
- fetchWikiTree,
- rebuildWikiIndex,
-} from "@/lib/wikiApi";
-import { cleanTitle, libraryItems, relativeAge, type LibraryItem } from "@/lib/wikiModel";
-import { useWikiLive } from "@/hooks/useWikiLive";
-
-import { EmptyState } from "@/components/ui/empty-state";
-import { WikiLibrary } from "@/components/wiki/WikiLibrary";
-import { PageRenderer } from "@/components/wiki/PageRenderer";
-import {
- HEALTH_DOT_STYLE,
- HEALTH_LABEL_KEY,
- WikiInspector,
- classifyWikiHealth,
-} from "@/components/wiki/WikiInspector";
-import { WikiSearch, type WikiSearchHandle } from "@/components/wiki/WikiSearch";
-import { ObsidianStatus } from "@/components/wiki/ObsidianStatus";
-import { ObsidianSetupDialog } from "@/components/wiki/ObsidianSetupDialog";
-import type { ObsidianStatus as ObsidianStatusType } from "@/types/setup";
-
-// The graph bundle (~120 KB minified) only loads when the Wiki section mounts.
-const WikiGraph = lazy(() =>
- import("@/components/wiki/WikiGraph").then((mod) => ({
- default: mod.WikiGraph,
- })),
-);
-
-type CentreTab = "graph" | "page";
-
-interface WikiToast {
- message: string;
- id: number;
-}
-
-const IS_MAC =
- typeof navigator !== "undefined" && /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent);
-
-export function WikiView(): JSX.Element {
- const t = useT();
- const language = useRunLocale();
- useWikiLive();
- const [selectedSlug, setSelectedSlug] = useState<string | null>(null);
- const [centreTab, setCentreTab] = useState<CentreTab>("graph");
- const [isGraphExpanded, setIsGraphExpanded] = useState(false);
- const [toast, setToast] = useState<WikiToast | null>(null);
- // The setup walkthrough opens with the status payload the pill last saw.
- // The hint object also reseeds whenever the user reopens the dialog so
- // step-2-vs-step-3 starts from the most recent reality.
- const [setupHint, setSetupHint] = useState<ObsidianStatusType | null>(null);
- const [dialogOpen, setDialogOpen] = useState(false);
- const [isReindexing, setIsReindexing] = useState(false);
- const [reindexError, setReindexError] = useState<string | null>(null);
- const searchRef = useRef<WikiSearchHandle>(null);
- const inspectorOpen = useWikiPanelStore((s) => s.open);
- const setInspectorOpen = useWikiPanelStore((s) => s.setOpen);
-
- // A staged "open this page" request from another section (e.g. the Contacts
- // detail's wiki link). `seq` bumps on every request, so re-opening the same
- // slug still fires.
- const wikiPageRequest = useEventStore((s) => s.wikiPageRequest);
- useEffect(() => {
- if (wikiPageRequest) setSelectedSlug(wikiPageRequest.slug);
- }, [wikiPageRequest]);
-
- const treeQuery = useQuery({
- queryKey: ["wiki", "tree"],
- queryFn: fetchWikiTree,
- staleTime: 5_000,
- });
-
- const stats = treeQuery.data?.stats;
- const totalPages = stats?.total_pages ?? 0;
- const totalLinks = stats?.total_links ?? 0;
- const folders = useMemo(() => treeQuery.data?.folders ?? [], [treeQuery.data?.folders]);
- const items = useMemo(() => libraryItems(folders), [folders]);
- const itemsBySlug = useMemo(() => {
- const map = new Map<string, LibraryItem>();
- for (const item of items) if (!map.has(item.slug)) map.set(item.slug, item);
- return map;
- }, [items]);
-
- // Wiki subsystem health: polled on mount + every 30 s so the "honest, not
- // silent" status stays live without a manual refresh.
- const healthQuery = useQuery({
- queryKey: ["wiki", "health"],
- queryFn: fetchWikiHealth,
- refetchInterval: 30_000,
- staleTime: 5_000,
- });
-
- // Selecting a page (tree, graph, wikilink, search) swaps to the page tab.
- useEffect(() => {
- if (selectedSlug) {
- setCentreTab("page");
- setIsGraphExpanded(false);
- }
- }, [selectedSlug]);
-
- // Escape leaves the full-window map. With the nav rail covered it is the
- // reflex people reach for first.
- useEffect(() => {
- if (!isGraphExpanded) return;
- const onKey = (event: KeyboardEvent) => {
- if (event.key === "Escape") setIsGraphExpanded(false);
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [isGraphExpanded]);
-
- // On the first visit, auto-open the Obsidian setup walkthrough — but only
- // if the user never marked it completed AND the status says action is
- // required. AbortController cancels both requests on unmount.
- useEffect(() => {
- const controller = new AbortController();
- let cancelled = false;
-
- (async () => {
- try {
- const [statusResp, stateResp] = await Promise.all([
- fetch("/api/setup/obsidian/status", { signal: controller.signal }),
- fetch("/api/setup/state", { signal: controller.signal }),
- ]);
- if (cancelled || !statusResp.ok || !stateResp.ok) return;
-
- const status = (await statusResp.json()) as ObsidianStatusType;
- const state = (await stateResp.json()) as { obsidian_setup_seen: boolean };
-
- if (cancelled) return;
- if (state.obsidian_setup_seen === false && status.recommended_action !== "ok") {
- setSetupHint(status);
- setDialogOpen(true);
- }
- } catch (err) {
- // AbortError is expected on unmount; anything else is only logged —
- // the Obsidian pill in the header still gives the user a manual entry.
- if ((err as { name?: string })?.name !== "AbortError") {
- console.debug("[WikiView] first-run setup probe failed:", err);
- }
- }
- })();
-
- return () => {
- cancelled = true;
- controller.abort();
- };
- }, []);
-
- const showToast = useCallback((message: string) => {
- const id = Date.now();
- setToast({ message, id });
- window.setTimeout(() => {
- setToast((prev) => (prev?.id === id ? null : prev));
- }, 3000);
- }, []);
-
- const handleReindex = useCallback(async () => {
- setIsReindexing(true);
- setReindexError(null);
- try {
- const result = await rebuildWikiIndex();
- if (!result.ok) {
- throw new Error(result.error ?? t("wiki_health.reindex_failed"));
- }
- await Promise.all([healthQuery.refetch(), treeQuery.refetch()]);
- } catch (error) {
- setReindexError(error instanceof Error ? error.message : t("wiki_health.reindex_failed"));
- showToast(t("wiki_health.reindex_failed"));
- } finally {
- setIsReindexing(false);
- }
- }, [healthQuery, showToast, t, treeQuery]);
-
- const handleSelect = useCallback(
- (slug: string) => {
- if (itemsBySlug.size > 0 && !itemsBySlug.has(slug)) {
- showToast(t("wiki_view.page_not_found"));
- return;
- }
- setIsGraphExpanded(false);
- // Selecting the already-open page from the graph does not change the
- // slug, so the selectedSlug effect cannot switch tabs in that case.
- setCentreTab("page");
- setSelectedSlug(slug);
- },
- [itemsBySlug, showToast, t],
- );
-
- const closePage = useCallback(() => {
- setSelectedSlug(null);
- setCentreTab("graph");
- }, []);
-
- const health = healthQuery.data;
- const healthVisual = health ? classifyWikiHealth(health) : "unknown";
- const curated = stats?.last_curator_run
- ? relativeAge(Date.parse(stats.last_curator_run) / 1000, language)
- : "";
-
- const subtitle = treeQuery.isLoading
- ? t("wiki_view.loading_vault")
- : totalPages === 0
- ? t("wiki_view.vault_empty")
- : [
- t("wiki_ui.subtitle_pages").replace("{0}", formatCount(totalPages, language)),
- t("wiki_ui.subtitle_links").replace("{0}", formatCount(totalLinks, language)),
- ]
- .filter(Boolean)
- .join(" · ");
-
- const selectedTitle = selectedSlug
- ? itemsBySlug.get(selectedSlug)?.title ?? cleanTitle(selectedSlug)
- : "";
-
- const inspector = (
- <WikiInspector
- selectedSlug={selectedSlug}
- itemsBySlug={itemsBySlug}
- health={health}
- healthLoading={healthQuery.isLoading}
- isReindexing={isReindexing}
- reindexError={reindexError}
- onReindex={handleReindex}
- onSelect={handleSelect}
- />
- );
-
- const healthChip = (
- <button
- type="button"
- onClick={() => {
- closePage();
- setInspectorOpen(true);
- }}
- data-testid="wiki-health-chip"
- data-visual={healthQuery.isLoading ? "loading" : healthVisual}
- title={t("wiki_ui.health_chip_title")}
- className="inline-flex h-8 items-center gap-2 rounded-md px-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- >
- <span
- className={cn(
- "h-2 w-2 rounded-full",
- healthQuery.isLoading ? "animate-pulse bg-faint-foreground" : HEALTH_DOT_STYLE[healthVisual],
- )}
- aria-hidden
- />
- {healthQuery.isLoading ? t("wiki_health.checking") : t(HEALTH_LABEL_KEY[healthVisual])}
- </button>
- );
-
- // The section is drawn the way the Agentic IDE is: the window's gray ground
- // carries the navigation column (title, search, the page library), and the
- // working surface is one sheet in the room colour with a hairline rim and a
- // rounded top-left corner. Inside the sheet the stage and the inspector are
- // separated by a rule, and the inspector sits one step lighter — the IDE's
- // side panel. Every region has an edge; nothing bleeds into its neighbour.
- return (
- <div className="flex h-full min-h-0 bg-sidebar" data-testid="wiki-view">
- {dialogOpen && setupHint && (
- <ObsidianSetupDialog
- open={dialogOpen}
- onClose={() => setDialogOpen(false)}
- initialStatus={setupHint}
- onComplete={async () => {
- // Only when the user explicitly confirms that setup worked;
- // never on Escape or an outside click. A failed mark only means
- // the wizard reopens on the next visit, so it is logged, not shown.
- try {
- await fetch("/api/setup/state/obsidian-seen", { method: "POST" });
- } catch (err) {
- console.debug("[WikiView] mark-obsidian-seen failed:", err);
- }
- }}
- />
- )}
-
- <WikiSearch ref={searchRef} onResultClick={handleSelect} />
-
- {!isGraphExpanded && (
- <WikiLibrary
- folders={folders}
- isLoading={treeQuery.isLoading}
- isError={treeQuery.isError}
- selectedSlug={selectedSlug}
- onSelect={handleSelect}
- header={
- <div className="px-4 pb-3 pt-3">
- <div className="flex items-center gap-2.5">
- <BookOpen className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
- <h1 className="truncate text-lg font-semibold text-foreground-strong">{t("wiki_ui.title")}</h1>
- </div>
- <p className="mt-1 truncate text-sm text-muted-foreground" title={subtitle} data-testid="wiki-subtitle">
- {subtitle}
- </p>
- {curated && totalPages > 0 && (
- <p className="truncate text-sm text-foreground-faint">
- {t("wiki_ui.subtitle_curated").replace("{0}", curated)}
- </p>
- )}
- <button
- type="button"
- onClick={() => searchRef.current?.open()}
- data-testid="wiki-search-trigger"
- className="mt-4 flex h-8 w-full items-center gap-2 rounded-lg border border-border bg-input px-2.5 text-sm text-muted-foreground transition-colors hover:border-border-strong hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <Search className="h-3.5 w-3.5 shrink-0" aria-hidden />
- <span className="flex-1 truncate text-left">{t("wiki_ui.search_placeholder")}</span>
- <span className="flex shrink-0 items-center gap-0.5" aria-hidden>
- {(IS_MAC ? ["⌘", "K"] : ["Ctrl", "K"]).map((key) => (
- <kbd key={key} className="rounded border border-border bg-background px-1 font-sans text-xs leading-4 text-muted-foreground">
- {key}
- </kbd>
- ))}
- </span>
- </button>
- </div>
- }
- />
- )}
-
- <div
- id="wiki-workspace"
- className={cn(
- "flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background",
- isGraphExpanded
- ? // Expanded means the whole window: the map is the one thing in
- // this app that gets better the more room it has.
- "fixed inset-0 z-[100]"
- : "rounded-tl-xl border-l border-t border-border",
- )}
- data-testid="wiki-workspace"
- data-graph-expanded={isGraphExpanded ? "true" : "false"}
- >
- {treeQuery.isError ? (
- <div className="flex flex-1 items-center justify-center p-6">
- <p role="alert" className="max-w-reading text-base text-destructive" data-testid="wiki-tree-error">
- {t("wiki_view.load_error")}
- </p>
- </div>
- ) : !treeQuery.isLoading && totalPages === 0 ? (
- // An empty vault can itself be a symptom (a failed bootstrap writes
- // nothing), so the health rail stays beside the empty state.
- <div className="flex min-h-0 flex-1">
- <div className="flex min-w-0 flex-1 items-center justify-center p-6">
- <WikiEmptyState />
- </div>
- {inspectorOpen && inspector}
- </div>
- ) : (
- <div className="flex min-h-0 flex-1">
- <section className="flex min-w-0 flex-1 flex-col" aria-label={t("wiki_ui.stage_label")}>
- <div className="flex h-11 shrink-0 items-stretch gap-1 border-b border-border px-3">
- <StageTab
- active={centreTab === "graph"}
- onClick={() => setCentreTab("graph")}
- icon={<Network className="h-3.5 w-3.5" aria-hidden />}
- label={t("wiki_ui.tab_map")}
- testId="wiki-tab-graph"
- />
- {selectedSlug && (
- <StageTab
- active={centreTab === "page"}
- onClick={() => {
- setCentreTab("page");
- setIsGraphExpanded(false);
- }}
- label={selectedTitle}
- testId="wiki-tab-page"
- onClose={closePage}
- closeLabel={t("wiki_ui.close_page")}
- />
- )}
- <div className="ml-auto flex items-center gap-1 self-center">
- {healthChip}
- <ObsidianStatus
- onOpenSetup={(s) => {
- setSetupHint(s);
- setDialogOpen(true);
- }}
- />
- {centreTab === "graph" && (
- <button
- type="button"
- className="inline-flex h-8 items-center gap-1.5 rounded-md px-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- onClick={() => setIsGraphExpanded((expanded) => !expanded)}
- aria-controls="wiki-workspace"
- aria-expanded={isGraphExpanded}
- aria-label={t(
- isGraphExpanded ? "wiki_graph.restore_view_title" : "wiki_graph.expand_view_title",
- )}
- title={t(
- isGraphExpanded ? "wiki_graph.restore_view_title" : "wiki_graph.expand_view_title",
- )}
- data-testid="wiki-graph-expand-toggle"
- >
- {isGraphExpanded ? (
- <Minimize2 className="h-3.5 w-3.5" aria-hidden />
- ) : (
- <Maximize2 className="h-3.5 w-3.5" aria-hidden />
- )}
- <span>{t(isGraphExpanded ? "wiki_graph.restore" : "wiki_graph.expand")}</span>
- </button>
- )}
- </div>
- </div>
-
- <div
- className={cn(
- "relative min-h-0 flex-1",
- centreTab === "page" ? "overflow-y-auto" : "overflow-hidden",
- )}
- >
- {centreTab === "graph" && (
- <Suspense fallback={<GraphSkeleton />}>
- <WikiGraph onNodeClick={handleSelect} highlightSlug={selectedSlug ?? undefined} />
- </Suspense>
- )}
- {centreTab === "page" && selectedSlug && (
- <PageRenderer key={selectedSlug} slug={selectedSlug} onWikilinkClick={handleSelect} />
- )}
- </div>
- </section>
-
- {!isGraphExpanded && inspectorOpen && inspector}
- </div>
- )}
- </div>
-
- {toast && (
- <div
- className="pointer-events-none fixed bottom-12 right-6 z-[110] max-w-sm rounded-lg bg-popover px-4 py-3 text-base text-foreground shadow-float"
- data-testid="wiki-toast"
- role="status"
- >
- {toast.message}
- </div>
- )}
- </div>
- );
-}
-
-function formatCount(value: number, language: string): string {
- try {
- return new Intl.NumberFormat(language).format(value);
- } catch {
- return String(value);
- }
-}
-
-function StageTab({
- active,
- onClick,
- icon,
- label,
- testId,
- onClose,
- closeLabel,
-}: {
- active: boolean;
- onClick: () => void;
- icon?: React.ReactNode;
- label: string;
- testId: string;
- onClose?: () => void;
- closeLabel?: string;
-}) {
- return (
- <div
- className={cn(
- "relative -mb-px flex min-w-0 items-center border-b-2 transition-colors",
- active ? "border-accent" : "border-transparent",
- )}
- >
- <button
- type="button"
- onClick={onClick}
- aria-current={active ? "page" : undefined}
- data-active={active ? "true" : "false"}
- data-testid={testId}
- className={cn(
- "flex h-full min-w-0 max-w-[280px] items-center gap-2 px-2 text-base font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
- active ? "text-foreground-strong" : "text-muted-foreground hover:text-foreground",
- )}
- >
- {icon}
- <span className="truncate">{label}</span>
- </button>
- {onClose && (
- <button
- type="button"
- onClick={onClose}
- aria-label={closeLabel}
- title={closeLabel}
- data-testid={`${testId}-close`}
- className="mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-foreground-faint transition-colors hover:bg-secondary hover:text-foreground"
- >
- <X className="h-3 w-3" aria-hidden />
- </button>
- )}
- </div>
- );
-}
-
-function WikiEmptyState() {
- const t = useT();
- const assistantName = useEventStore((s) => s.assistantName);
- return (
- <div data-testid="wiki-empty-state">
- <EmptyState
- icon={<BookOpen />}
- title={t("wiki_view.empty_title")}
- description={`${t("wiki_view.empty_body_a")} ${assistantName} ${t("wiki_view.empty_body_b")}`}
- />
- <p className="mx-auto -mt-6 max-w-[420px] text-center text-sm text-foreground-faint">
- {t("wiki_view.manual_a")}{" "}
- <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-xs text-foreground">.md</code>
- {t("wiki_view.manual_b")}{" "}
- <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-xs text-foreground">
- wiki/obsidian-vault/entities/
- </code>{" "}
- {t("wiki_view.manual_c")}
- </p>
- </div>
- );
-}
-
-function GraphSkeleton() {
- return (
- <div className="flex h-full items-center justify-center p-6" data-testid="wiki-graph-skeleton">
- <div className="h-24 w-24 animate-pulse rounded-full bg-foreground/10" />
- </div>
- );
-}
diff --git a/jarvis/ui/web/memory_vault_routes.py b/jarvis/ui/web/memory_vault_routes.py
new file mode 100644
index 0000000000..498c1d0d13
--- /dev/null
+++ b/jarvis/ui/web/memory_vault_routes.py
@@ -0,0 +1,597 @@
+"""Path-addressed read and write API behind the desktop Memory section.
+
+The slug routes in :mod:`jarvis.ui.web.wiki_routes` stay for the CLI and
+older callers. They address a page by file name, which cannot work for a
+vault where 100+ agent notebooks are all called ``MEMORY.md``. These routes
+address every page by its vault-relative path and serve the linked model
+from :mod:`jarvis.memory.wiki.vault_model`:
+
+* ``GET /api/wiki/index`` every page, grouped, with agent owners.
+* ``GET /api/wiki/read?path=`` one page with links, backlinks, mentions,
+ related pages and notebook entries.
+* ``GET /api/wiki/map`` nodes and edges for the memory map.
+* ``GET /api/wiki/activity`` what changed recently, from ``log.md``.
+* ``POST /api/wiki/pages`` create a knowledge page.
+* ``PUT /api/wiki/pages`` save an edited body.
+* ``POST /api/wiki/pages/rename`` rename and repoint every link to it.
+* ``POST /api/wiki/pages/archive`` move a page to ``_archive/``.
+* ``POST /api/wiki/tidy`` archive empty notebooks of agents that
+ are no longer active.
+
+Every write goes through the running ``WikiCurator`` and so through the
+guarded ``AtomicWriter`` (backup, secret refusal, schema validation,
+rollback, search index update, ``log.md`` entry, live event). Nothing here
+calls a model, so none of it can bill a key.
+"""
+from __future__ import annotations
+
+import asyncio
+import datetime as _dt
+import logging
+import re
+import threading
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query, Request
+from pydantic import BaseModel, Field
+
+from jarvis.memory.wiki.integration import get_running_curator
+from jarvis.memory.wiki.protocols import PageUpdate
+from jarvis.memory.wiki.session_links import slugify
+from jarvis.memory.wiki.vault_model import (
+ AgentInfo,
+ SourcePage,
+ VaultModel,
+ build_model,
+)
+from jarvis.ui.web.wiki_routes import _resolve_vault_root, _scan_visible_pages
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/wiki", tags=["wiki"])
+
+#: Kinds a person can create from the Memory section, and where they live.
+CREATABLE_KINDS: dict[str, str] = {
+ "entity": "entities",
+ "project": "projects",
+ "concept": "concepts",
+}
+#: Groups whose pages a person edits by hand. Agent notebooks are written by
+#: their agent through entry markers; the reader shows them, the agent's own
+#: memory panel edits them.
+_EDITABLE_GROUPS = frozenset({"knowledge", "journal"})
+_ARCHIVABLE_GROUPS = frozenset({"knowledge", "journal", "agents"})
+_ROSTER_TIMEOUT_S = 3.0
+_LOG_ENTRY_RE = re.compile(
+ r"^## \[(?P<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2})\] (?P<verb>[\w-]+) \| (?P<subject>.+?)\s*$"
+)
+_LOG_LINK_RE = re.compile(r"\[\[([^\]|#]+)")
+_FM_BLOCK_RE = re.compile(r"\A(?---\r?\n.*?\r?\n---[ \t]*)(?:\r?\n|\Z)", re.DOTALL)
+_UPDATED_RE = re.compile(r"^updated:.*$", re.MULTILINE)
+
+
+# ------------------------------------------------------------------ bodies
+
+
+class CreatePageBody(BaseModel):
+ kind: str = Field(pattern=r"^(entity|project|concept)$")
+ title: str = Field(min_length=1, max_length=160)
+ body_md: str = Field(default="", max_length=200_000)
+
+
+class SavePageBody(BaseModel):
+ path: str = Field(min_length=1, max_length=512)
+ body_md: str = Field(max_length=200_000)
+ #: The page's mtime when the editor opened it; a newer file on disk
+ #: means someone (an agent, Obsidian) changed it meanwhile.
+ base_mtime: float
+
+
+class RenamePageBody(BaseModel):
+ path: str = Field(min_length=1, max_length=512)
+ title: str = Field(min_length=1, max_length=160)
+
+
+class ArchivePageBody(BaseModel):
+ path: str = Field(min_length=1, max_length=512)
+
+
+class TidyBody(BaseModel):
+ dry_run: bool = True
+
+
+# ------------------------------------------------------------------- model
+
+_MODEL_LOCK = threading.Lock()
+_MODEL_CACHE: dict[str, tuple[tuple[Any, ...], VaultModel]] = {}
+
+
+async def _agents(request: Request) -> dict[str, AgentInfo] | None:
+ """Roster names and states, or ``None`` when the society is unavailable.
+
+ A notebook folder whose agent the roster no longer knows is an orphan;
+ the reader groups those apart instead of listing them as live agents.
+ """
+ try:
+ from jarvis.society.display_name import display_name
+ from jarvis.ui.web.society_routes import _runtime
+
+ runtime = await asyncio.wait_for(_runtime(request), timeout=_ROSTER_TIMEOUT_S)
+ records = await asyncio.wait_for(
+ runtime.roster.list(include_archived=True), timeout=_ROSTER_TIMEOUT_S
+ )
+ except Exception as exc: # noqa: BLE001 - the vault reads fine without agent names
+ log.info("memory vault: roster unavailable, agent names fall back to ids: %s", exc)
+ return None
+ out: dict[str, AgentInfo] = {}
+ for record in records:
+ state = "archived" if str(record.state).endswith("archived") else "active"
+ out[record.agent_id] = AgentInfo(record.agent_id, display_name(record), state)
+ return out
+
+
+async def _model(request: Request, *, require_roster: bool = False) -> tuple[Path, VaultModel]:
+ """The linked model of the vault, rebuilt only when a file or the roster changed.
+
+ ``require_roster`` is for actions that depend on agent states: without the
+ roster every notebook folder would read as orphaned, live agents included.
+ """
+ vault_root = _resolve_vault_root(request)
+ if vault_root is None or not vault_root.is_dir():
+ raise HTTPException(404, "The memory vault is not set up yet.")
+ visible, roster = await asyncio.gather(_scan_visible_pages(vault_root), _agents(request))
+ if roster is None and require_roster:
+ raise HTTPException(
+ 503, "The agent list is not available right now, so nothing was changed. Try again."
+ )
+ agents = roster or {}
+ signature = (
+ tuple((v.relative_path.as_posix(), v.mtime, v.size) for v in visible),
+ tuple(sorted((a.agent_id, a.name, a.state) for a in agents.values())),
+ )
+ key = str(vault_root)
+ with _MODEL_LOCK:
+ cached = _MODEL_CACHE.get(key)
+ if cached is not None and cached[0] == signature:
+ return vault_root, cached[1]
+ sources = [
+ SourcePage(
+ path=v.relative_path.as_posix(),
+ body=v.page.body,
+ properties=v.properties,
+ page_type=v.page.page_type,
+ mtime=v.mtime,
+ size=v.size,
+ )
+ for v in visible
+ ]
+ model = await asyncio.to_thread(build_model, sources, agents)
+ with _MODEL_LOCK:
+ _MODEL_CACHE[key] = (signature, model)
+ return vault_root, model
+
+
+def _require_page(model: VaultModel, path: str) -> Any:
+ record = model.pages.get(path)
+ if record is None:
+ raise HTTPException(404, "No page at that path.")
+ return record
+
+
+def _require_curator() -> Any:
+ curator = get_running_curator()
+ if curator is None:
+ raise HTTPException(
+ 503,
+ "The memory writer is not running. Turn on the wiki in Settings, then try again.",
+ )
+ return curator
+
+
+def _today() -> str:
+ return _dt.date.today().isoformat()
+
+
+# ------------------------------------------------------------------- reads
+
+
+async def get_index(request: Request) -> dict[str, Any]:
+ """Every page once, grouped, plus the agents that own notebook folders."""
+ vault_root, model = await _model(request)
+ agents = []
+ for agent_id, info in sorted(model.agents.items(), key=lambda item: item[1].name.casefold()):
+ pages = [p for p in model.pages.values() if p.agent_id == agent_id]
+ agents.append(
+ {
+ "agent_id": agent_id,
+ "name": info.name,
+ "state": info.state,
+ "empty": all(p.empty for p in pages),
+ "updated": max((p.mtime for p in pages), default=0.0),
+ "pages": [p.path for p in sorted(pages, key=lambda p: (p.kind, -p.mtime))],
+ }
+ )
+ pages = []
+ for record in model.pages.values():
+ summary = record.summary_dict()
+ summary["links_in"] = len({link.source for link in model.incoming.get(record.path, [])})
+ summary["links_out"] = len(
+ {link.target for link in model.outgoing.get(record.path, []) if link.target}
+ )
+ pages.append(summary)
+ pages.sort(key=lambda p: -p["mtime"])
+ return {
+ "ok": True,
+ "vault_root": str(vault_root),
+ "stats": model.stats(),
+ "pages": pages,
+ "agents": agents,
+ "writable": get_running_curator() is not None,
+ }
+
+
+async def read_page(request: Request, path: str = Query(min_length=1)) -> dict[str, Any]:
+ """One page, its links in both directions, and what it relates to."""
+ _, model = await _model(request)
+ record = _require_page(model, path)
+ entries: list[dict[str, Any]] = []
+ if record.kind in ("memory", "profile"):
+ from jarvis.society.notebook import parse
+
+ try:
+ entries = [
+ {
+ "id": entry.id,
+ "text": entry.text,
+ "importance": entry.importance,
+ "origin": entry.origin,
+ }
+ for entry in parse(record.body)
+ if entry.text.strip()
+ ]
+ except (ValueError, KeyError) as exc:
+ log.warning("memory vault: notebook %s has unreadable entries: %s", path, exc)
+ agent = model.agents.get(record.agent_id or "")
+ return {
+ "ok": True,
+ **record.summary_dict(),
+ "properties": dict(record.properties),
+ "aliases": list(record.aliases),
+ "body_md": record.body,
+ "size": record.size,
+ "editable": record.group in _EDITABLE_GROUPS,
+ "archivable": record.group in _ARCHIVABLE_GROUPS,
+ "agent": (
+ {"agent_id": agent.agent_id, "name": agent.name, "state": agent.state}
+ if agent
+ else None
+ ),
+ "entries": entries,
+ **model.page_links(path),
+ "related": model.related(path),
+ }
+
+
+async def get_map(request: Request, agents: bool = Query(default=True)) -> dict[str, Any]:
+ """The memory map: pages with content as nodes, links and mentions as edges."""
+ _, model = await _model(request)
+ return {"ok": True, **model.graph(include_agents=agents)}
+
+
[email protected]("/activity")
+async def get_activity(
+ request: Request, limit: int = Query(default=40, ge=1, le=200)
+) -> dict[str, Any]:
+ """Recent writes from ``log.md``, newest first, without self-doc refreshes."""
+ vault_root, model = await _model(request)
+ log_path = vault_root / "log.md"
+ try:
+ text = await asyncio.to_thread(log_path.read_text, encoding="utf-8", errors="replace")
+ except OSError as exc:
+ log.info("memory vault: activity feed empty, log.md unreadable: %s", exc)
+ text = ""
+ return {"ok": True, "items": _parse_activity(text, model, limit)}
+
+
+def _parse_activity(text: str, model: VaultModel, limit: int) -> list[dict[str, Any]]:
+ by_stem: dict[str, str] = {}
+ for path in model.pages:
+ by_stem.setdefault(path.removesuffix(".md").casefold(), path)
+ by_stem.setdefault(Path(path).stem.casefold(), path)
+ items: list[dict[str, Any]] = []
+ current: dict[str, Any] | None = None
+ for line in text.splitlines():
+ match = _LOG_ENTRY_RE.match(line)
+ if match:
+ if current is not None:
+ items.append(current)
+ current = {
+ "ts": match["ts"],
+ "verb": match["verb"],
+ "source": match["subject"],
+ "summary": "",
+ "pages": [],
+ }
+ continue
+ if current is None:
+ continue
+ stripped = line.strip()
+ if stripped.startswith("- pages touched:"):
+ for raw in _LOG_LINK_RE.findall(stripped):
+ path = by_stem.get(raw.strip().casefold())
+ if path and path not in current["pages"]:
+ current["pages"].append(path)
+ elif stripped.startswith("- summary:"):
+ current["summary"] = stripped.removeprefix("- summary:").strip()
+ if current is not None:
+ items.append(current)
+ meaningful = [
+ item
+ for item in items
+ if not item["source"].startswith("self-doc") and item["pages"]
+ ]
+ meaningful.reverse()
+ out = []
+ for item in meaningful[:limit]:
+ item["pages"] = [
+ {"path": p, "title": model.pages[p].title, "kind": model.pages[p].kind}
+ for p in item["pages"]
+ ]
+ out.append(item)
+ return out
+
+
+# ------------------------------------------------------------------ writes
+
+
+def _write_failure(result: Any) -> HTTPException | None:
+ if result.applied:
+ return None
+ if result.blocked_pii:
+ return HTTPException(
+ 422, "Not saved: the text looks like it contains a password or key."
+ )
+ if result.skipped_due_to_recent_edit:
+ return HTTPException(
+ 409, "Not saved: the page changed somewhere else a moment ago. Reload it first."
+ )
+ if result.failed_validation:
+ return HTTPException(422, "Not saved: the page did not pass the vault's schema check.")
+ return HTTPException(500, "Not saved.")
+
+
+async def _apply(updates: list[PageUpdate], *, label: str, verb: str) -> Any:
+ curator = _require_curator()
+ result = await curator.apply_external_updates(
+ updates,
+ source_label=label,
+ verb=verb,
+ all_or_nothing=len(updates) > 1,
+ keep_unresolved_links=True,
+ )
+ failure = _write_failure(result)
+ if failure is not None:
+ raise failure
+ return result
+
+
+def _frontmatter_for(kind: str, slug: str, title: str) -> str:
+ today = _today()
+ lines = ["---", f"type: {kind}", f"slug: {slug}", f"title: {_yaml_text(title)}"]
+ if kind == "project":
+ lines.append("status: active")
+ lines += [f"created: {today}", f"updated: {today}", "---"]
+ return "\n".join(lines)
+
+
+def _yaml_text(text: str) -> str:
+ clean = " ".join(text.split())
+ escaped = clean.replace("\\", "\\\\").replace('"', '\\"')
+ return f'"{escaped}"'
+
+
[email protected]("/pages", openapi_extra={"x-jarvis-risk-tier": "monitor"})
+async def create_page(payload: CreatePageBody, request: Request) -> dict[str, Any]:
+ """Create a new entity, project or concept page."""
+ vault_root, model = await _model(request)
+ title = " ".join(payload.title.split())
+ slug = slugify(title)
+ if not slug:
+ raise HTTPException(422, "Give the page a title with at least one letter or digit.")
+ folder = CREATABLE_KINDS[payload.kind]
+ path = f"{folder}/{slug}.md"
+ if path in model.pages or (vault_root / path).exists():
+ raise HTTPException(409, f"A page called {title} already exists.")
+ body = payload.body_md.strip()
+ content = f"{_frontmatter_for(payload.kind, slug, title)}\n\n# {title}\n"
+ if body:
+ content += f"\n{body}\n"
+ await _apply(
+ [PageUpdate(Path(path), "create", content, reason="created in the Memory section")],
+ label="user:memory-section",
+ verb="create",
+ )
+ return {"ok": True, "path": path}
+
+
[email protected]("/pages", openapi_extra={"x-jarvis-risk-tier": "monitor"})
+async def save_page(payload: SavePageBody, request: Request) -> dict[str, Any]:
+ """Replace a page's body; its frontmatter stays as it was."""
+ vault_root, model = await _model(request)
+ record = _require_page(model, payload.path)
+ if record.group not in _EDITABLE_GROUPS:
+ raise HTTPException(
+ 403, "Agent notebooks are kept by their agent. Edit them in the agent's memory panel."
+ )
+ target = vault_root / record.path
+ # The file on disk, not the cached model, decides whether it is stale.
+ current = await asyncio.to_thread(target.stat)
+ if max(record.mtime, current.st_mtime) > payload.base_mtime + 0.001:
+ raise HTTPException(409, "This page changed since you opened it. Reload it first.")
+ raw = await asyncio.to_thread(target.read_text, encoding="utf-8")
+ match = _FM_BLOCK_RE.match(raw)
+ head = match.group(1) if match else ""
+ if head and _UPDATED_RE.search(head):
+ head = _UPDATED_RE.sub(f"updated: {_today()}", head, count=1)
+ body = payload.body_md.replace("\r\n", "\n").strip("\n")
+ content = f"{head}\n\n{body}\n" if head else f"{body}\n"
+ await _apply(
+ [PageUpdate(Path(payload.path), "update", content, reason="edited in the Memory section")],
+ label="user:memory-section",
+ verb="update",
+ )
+ stat = await asyncio.to_thread(target.stat)
+ return {"ok": True, "path": payload.path, "mtime": stat.st_mtime}
+
+
[email protected]("/pages/rename", openapi_extra={"x-jarvis-risk-tier": "monitor"})
+async def rename_page(payload: RenamePageBody, request: Request) -> dict[str, Any]:
+ """Rename a knowledge page and repoint every link that opened it."""
+ vault_root, model = await _model(request)
+ record = _require_page(model, payload.path)
+ if record.group != "knowledge":
+ raise HTTPException(403, "Only knowledge pages can be renamed here.")
+ title = " ".join(payload.title.split())
+ slug = slugify(title)
+ if not slug:
+ raise HTTPException(422, "Give the page a title with at least one letter or digit.")
+ folder = record.folder
+ new_path = f"{folder}/{slug}.md" if folder else f"{slug}.md"
+ if new_path != record.path and (new_path in model.pages or (vault_root / new_path).exists()):
+ raise HTTPException(409, f"A page called {title} already exists.")
+
+ raw = await asyncio.to_thread((vault_root / record.path).read_text, encoding="utf-8")
+ head, fresh_body = _split_head(raw)
+ if head:
+ head = re.sub(r"^slug:.*$", f"slug: {slug}", head, count=1, flags=re.MULTILINE)
+ if re.search(r"^title:", head, flags=re.MULTILINE):
+ head = re.sub(
+ r"^title:.*$", f"title: {_yaml_text(title)}", head, count=1, flags=re.MULTILINE
+ )
+ body = re.sub(
+ rf"^# {re.escape(record.title)}\s*$", f"# {title}", fresh_body, count=1, flags=re.MULTILINE
+ )
+ content = f"{head}\n{body}\n" if head else f"{body}\n"
+ new_target = new_path.removesuffix(".md")
+ updates: list[PageUpdate] = []
+ if new_path == record.path:
+ updates.append(PageUpdate(Path(record.path), "update", content, reason="renamed"))
+ else:
+ updates.append(
+ PageUpdate(
+ Path(new_path),
+ "rename",
+ content,
+ rename_from=Path(record.path),
+ reason="renamed in the Memory section",
+ )
+ )
+ rewritten = 0
+ # Agent notebooks are written by their agents through entry markers, so
+ # their links are reported rather than rewritten behind the agent's back.
+ unrewritten = 0
+ linking = {
+ link.source
+ for link in model.incoming.get(record.path, [])
+ if link.kind == "link" and link.source != record.path
+ }
+ for source in sorted(linking):
+ if model.pages[source].group not in _EDITABLE_GROUPS:
+ unrewritten += 1
+ continue
+ # Rewrite the file as it is now, not as the cached model saw it.
+ source_raw = await asyncio.to_thread((vault_root / source).read_text, encoding="utf-8")
+ source_head, source_body = _split_head(source_raw)
+ new_body, count = model.rewrite_links(source, record.path, new_target, body=source_body)
+ if not count:
+ continue
+ prefix = f"{source_head}\n" if source_head else ""
+ updates.append(
+ PageUpdate(Path(source), "update", f"{prefix}{new_body}\n", reason="link renamed")
+ )
+ rewritten += count
+ await _apply(updates, label="user:memory-section", verb="rename")
+ return {
+ "ok": True,
+ "path": new_path,
+ "links_rewritten": rewritten,
+ "links_unrewritten": unrewritten,
+ }
+
+
[email protected]("/pages/archive", openapi_extra={"x-jarvis-risk-tier": "monitor"})
+async def archive_page(payload: ArchivePageBody, request: Request) -> dict[str, Any]:
+ """Move a page into ``_archive/``; nothing is deleted."""
+ _, model = await _model(request)
+ record = _require_page(model, payload.path)
+ if record.group not in _ARCHIVABLE_GROUPS:
+ raise HTTPException(403, "System pages cannot be archived.")
+ await _apply(
+ [PageUpdate(Path(record.path), "archive", "", reason="archived in the Memory section")],
+ label="user:memory-section",
+ verb="archive",
+ )
+ return {"ok": True, "path": record.path}
+
+
[email protected]("/tidy", openapi_extra={"x-jarvis-risk-tier": "monitor"})
+async def tidy_vault(payload: TidyBody, request: Request) -> dict[str, Any]:
+ """Archive empty notebooks that belong to archived or unknown agents.
+
+ Only pages without a single sentence of content qualify, and they move to
+ ``_archive/`` rather than being deleted. ``dry_run`` (the default) lists
+ what would move.
+ """
+ # Without a roster answer every folder would read as orphaned, live
+ # agents included, so this refuses instead of guessing.
+ vault_root, model = await _model(request, require_roster=True)
+ candidates = [
+ record.path
+ for record in model.pages.values()
+ if record.group == "agents"
+ and record.kind in ("memory", "profile")
+ and record.empty
+ and model.agents.get(record.agent_id or "", AgentInfo("", "", "orphan")).state != "active"
+ ]
+ candidates.sort()
+ if payload.dry_run or not candidates:
+ return {"ok": True, "dry_run": True, "count": len(candidates), "paths": candidates}
+ curator = _require_curator()
+ moved: list[str] = []
+ # Batches keep one backup snapshot per call small and each call fast.
+ for start in range(0, len(candidates), 25):
+ batch = candidates[start : start + 25]
+ result = await curator.apply_external_updates(
+ [PageUpdate(Path(p), "archive", "", reason="empty notebook tidied") for p in batch],
+ source_label="user:memory-tidy",
+ verb="archive",
+ )
+ moved += [_relative(Path(p), vault_root) for p in result.applied]
+ skipped = len(candidates) - len(moved)
+ if skipped:
+ log.warning(
+ "memory tidy: %d of %d empty notebooks were not archived", skipped, len(candidates)
+ )
+ return {"ok": True, "dry_run": False, "count": len(moved), "skipped": skipped, "paths": moved}
+
+
+def _relative(path: Path, vault_root: Path) -> str:
+ try:
+ return path.resolve().relative_to(vault_root.resolve()).as_posix()
+ except ValueError: # silent-ok: the writer only applies in-vault paths; this is display only
+ return path.as_posix()
+
+
+def _split_head(raw: str) -> tuple[str, str]:
+ """``(frontmatter block, body)`` of a page file; the block is ``""`` when absent."""
+ match = _FM_BLOCK_RE.match(raw)
+ if not match:
+ return "", raw
+ return match.group(1), raw[match.end() :]
+
+
+__all__ = ["router"]
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 876ca6b0e4..78cbe2d664 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -527,6 +527,7 @@ class WebServer:
from .marketplace_publish_routes import router as marketplace_publish_router
from .marketplace_routes import router as marketplace_router
from .mcp_routes import router as mcp_router
+ from .memory_vault_routes import router as memory_vault_router
from .mission_billing_routes import router as mission_billing_router
from .missions_auth import router as missions_auth_router
from .missions_pty_routes import router as missions_pty_router
@@ -823,6 +824,8 @@ class WebServer:
app.include_router(onboarding_router)
# Phase B3 — Wiki view (read-only REST API over the Obsidian vault).
app.include_router(wiki_router)
+ # Path-addressed Memory section API (index, reader, map, edits).
+ app.include_router(memory_vault_router)
# Phase B3 — Desktop wiki view live-reload WS endpoint.
# Forwards WikiPageChanged events from the shared EventBus to
# subscribed UI clients. WikiWatcher is started in start().
diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.py
index 516a86cae0..79571b0082 100644
--- a/jarvis/ui/web/wiki_routes.py
+++ b/jarvis/ui/web/wiki_routes.py
@@ -35,7 +35,7 @@ import logging
import os
import threading
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import UTC
from pathlib import Path
from typing import Any
@@ -60,6 +60,7 @@ from jarvis.memory.wiki.protocols import WikiPage
from jarvis.memory.wiki.search import VaultSearch
from jarvis.memory.wiki.semantic_search import with_semantic_hits
from jarvis.memory.wiki.telemetry import telemetry as _telemetry
+from jarvis.memory.wiki.vault_model import read_properties
from jarvis.memory.wiki.vault_root import resolve_vault_root
from jarvis.memory.wiki.wikilink import (
_canonicalise as _canonicalise_link, # type: ignore[attr-defined]
@@ -236,6 +237,8 @@ class _VisiblePage:
relative_path: Path
mtime: float
size: int
+ #: Real YAML frontmatter values (lists included) for the Memory reader.
+ properties: dict[str, Any] = field(default_factory=dict)
def _visible_path_sort_key(relative_path: Path) -> tuple[int, str]:
@@ -374,6 +377,7 @@ def _scan_visible_pages_sync(vault_root: Path) -> list[_VisiblePage]:
relative_path=relative,
mtime=stat.st_mtime,
size=stat.st_size,
+ properties=read_properties(raw),
)
fresh[rel_key] = (*signature, entry)
visible.append(entry)
diff --git a/tests/unit/memory/wiki/test_self_doc_noop.py b/tests/unit/memory/wiki/test_self_doc_noop.py
new file mode 100644
index 0000000000..7f6bd12829
--- /dev/null
+++ b/tests/unit/memory/wiki/test_self_doc_noop.py
@@ -0,0 +1,54 @@
+"""A self-doc refresh that would only move the clock writes nothing.
+
+Each write adds a ``log.md`` entry; refreshing on every boot and every
+consolidator run once made 1,833 of 2,100 log entries say nothing.
+"""
+from __future__ import annotations
+
+import asyncio
+import datetime as dt
+from pathlib import Path
+from types import SimpleNamespace
+
+from jarvis.memory.wiki import self_doc
+
+
+class _RecordingCurator:
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+
+ async def apply_external_updates(self, updates, *, source_label: str, verb: str): # noqa: ANN001
+ self.calls.append(source_label)
+ return SimpleNamespace(applied=[update.target_path for update in updates])
+
+
+def test_refresh_skips_a_page_whose_only_change_is_the_timestamp(tmp_path: Path) -> None:
+ (tmp_path / "entities").mkdir()
+ curator = _RecordingCurator()
+ current = self_doc.render_memory_page(
+ vault_root=tmp_path,
+ backlog_count=0,
+ telemetry_snapshot={},
+ now=dt.datetime(2026, 1, 1, 9, 0),
+ )
+ (tmp_path / self_doc.PAGE_NAME).write_text(current, encoding="utf-8")
+
+ wrote = asyncio.run(
+ self_doc.refresh_memory_page(curator=curator, vault_root=tmp_path, journal=None)
+ )
+
+ assert wrote is False
+ assert curator.calls == []
+
+
+def test_refresh_writes_when_the_status_really_changed(tmp_path: Path) -> None:
+ (tmp_path / "entities").mkdir()
+ curator = _RecordingCurator()
+ (tmp_path / self_doc.PAGE_NAME).write_text("---\ntype: meta\n---\n# Old\n", encoding="utf-8")
+
+ wrote = asyncio.run(
+ self_doc.refresh_memory_page(curator=curator, vault_root=tmp_path, journal=None)
+ )
+
+ assert wrote is True
+ assert curator.calls == ["self-doc:memory.md"]
diff --git a/tests/unit/memory/wiki/test_vault_model.py b/tests/unit/memory/wiki/test_vault_model.py
new file mode 100644
index 0000000000..f406795f25
--- /dev/null
+++ b/tests/unit/memory/wiki/test_vault_model.py
@@ -0,0 +1,195 @@
+"""The path-addressed vault model behind the Memory section.
+
+Pure tests: pages are handed in as ``SourcePage`` values, nothing touches
+disk. They pin the behaviours the old slug-addressed routes got wrong.
+"""
+
+from __future__ import annotations
+
+from jarvis.memory.wiki.vault_model import (
+ AgentInfo,
+ SourcePage,
+ build_model,
+ is_empty_body,
+ read_properties,
+)
+
+
+def _page(path: str, body: str, **properties: object) -> SourcePage:
+ return SourcePage(
+ path=path,
+ body=body,
+ properties=properties,
+ page_type=str(properties.get("type", "")),
+ mtime=1_000.0,
+ size=len(body),
+ )
+
+
+def _notebook(agent_id: str, text: str = "") -> list[SourcePage]:
+ entry = (
+ f'<!-- memory-entry: {{"id": "{agent_id}1", "importance": 5}} -->\n{text}\n' if text else ""
+ )
+ return [
+ _page(f"society/{agent_id}/MEMORY.md", f"\n{entry}", type="society"),
+ _page(f"society/{agent_id}/USER.md", "\n", type="society"),
+ ]
+
+
+def test_files_with_the_same_name_stay_separate_pages() -> None:
+ model = build_model(
+ [
+ *_notebook("ada", "Ada remembers the deploy steps."),
+ *_notebook("vega", "Vega knows SQL."),
+ ],
+ {"vega": AgentInfo("vega", "Vega", "active")},
+ )
+
+ assert set(model.pages) == {
+ "society/ada/MEMORY.md",
+ "society/ada/USER.md",
+ "society/vega/MEMORY.md",
+ "society/vega/USER.md",
+ }
+ vega = model.pages["society/vega/MEMORY.md"]
+ assert vega.title == "Vega · Memory"
+ assert vega.kind == "memory"
+ assert vega.summary == "Vega knows SQL."
+ assert model.agents["vega"].state == "active"
+ # An agent the roster does not know is an orphan, named after its folder.
+ assert model.agents["ada"].state == "orphan"
+ assert model.pages["society/ada/MEMORY.md"].title == "Ada · Memory"
+
+
+def test_frontmatter_only_pages_and_skeletons_count_as_empty() -> None:
+ assert is_empty_body("")
+ assert is_empty_body("\n<!-- memory-entry: {} -->\n")
+ assert is_empty_body("# Ruben\n\n## Summary\n\n## Facts\n- \n---\n")
+ assert not is_empty_body("# Ruben\n\nPrefers short answers.")
+
+ model = build_model(_notebook("ada"))
+ assert model.pages["society/ada/MEMORY.md"].empty
+ stats = model.stats()
+ assert stats["empty_pages"] == 2
+ assert stats["content_pages"] == 0
+
+
+def test_links_resolve_by_path_name_and_alias_and_report_broken_ones() -> None:
+ model = build_model(
+ [
+ _page(
+ "entities/ruben.md",
+ "# Ruben\n\nWorks on [[projects/magenta-ide]] and [[Dodaios]].",
+ type="entity",
+ aliases=["the user"],
+ ),
+ _page(
+ "projects/magenta-ide.md", "# Magenta IDE\n\nBy [[the user|Ruben]].", type="project"
+ ),
+ _page(
+ "entities/dodaios.md", "# Dodaios\n\nAn agent OS.", type="entity", title="Dodaios"
+ ),
+ _page("projects/other.md", "# Other\n\nSee [[nowhere]].", type="project"),
+ ]
+ )
+
+ links = model.page_links("entities/ruben.md")
+ assert {item["path"] for item in links["outgoing"]} == {
+ "projects/magenta-ide.md",
+ "entities/dodaios.md",
+ }
+ assert [item["path"] for item in links["backlinks"]] == ["projects/magenta-ide.md"]
+ broken = model.page_links("projects/other.md")["outgoing"]
+ assert broken == [
+ {"path": None, "title": "nowhere", "kind": None, "broken": True, "raw": "nowhere"}
+ ]
+ assert model.stats()["broken_links"] == 1
+
+
+def test_short_links_prefer_the_page_in_the_same_folder() -> None:
+ model = build_model(
+ [
+ _page("entities/bugatti-divo.md", "# Bugatti Divo (car)\n\nA car.", type="entity"),
+ _page(
+ "projects/bugatti-divo.md", "# Bugatti Divo build\n\nA model kit.", type="project"
+ ),
+ _page("projects/garage.md", "# Garage\n\nNext up: [[bugatti-divo]].", type="project"),
+ ]
+ )
+ assert model.resolve("bugatti-divo", "projects/garage.md") == "projects/bugatti-divo.md"
+
+
+def test_plain_text_mentions_link_distinctive_names_only() -> None:
+ model = build_model(
+ [
+ _page("entities/ruben.md", "# Ruben\n\nThe owner.", type="entity"),
+ _page("entities/memory.md", "# Memory\n\nA concept page.", type="entity"),
+ _page("entities/san-francisco.md", "# San Francisco\n\nA city.", type="entity"),
+ *_notebook("ada", "Ruben moved to san francisco; memory is cheap."),
+ ]
+ )
+
+ mentions = model.page_links("society/ada/MEMORY.md")["mentions"]
+ # "Ruben" as written and the multi-word city in any case; the plain
+ # word "memory" does not pull in the page titled "Memory".
+ assert {item["path"] for item in mentions} == {
+ "entities/ruben.md",
+ "entities/san-francisco.md",
+ }
+ mentioned_in = model.page_links("entities/ruben.md")["mentioned_in"]
+ assert [item["path"] for item in mentioned_in] == ["society/ada/MEMORY.md"]
+
+
+def test_system_pages_never_count_as_links_or_map_nodes() -> None:
+ model = build_model(
+ [
+ _page("log.md", "- pages touched: [[entities/ruben]]\n" * 50),
+ _page("memory.md", "# My Memory\n\n- [[entities/ruben]]", type="meta"),
+ _page("entities/ruben.md", "# Ruben\n\nThe owner.", type="entity"),
+ ]
+ )
+ assert model.stats()["links"] == 0
+ assert model.page_links("entities/ruben.md")["backlinks"] == []
+ assert [node["id"] for node in model.graph()["nodes"]] == ["entities/ruben.md"]
+
+
+def test_related_pages_share_a_neighbour() -> None:
+ model = build_model(
+ [
+ _page("entities/a.md", "# A\n\nKnows [[hub]].", type="entity"),
+ _page("entities/b.md", "# B\n\nAlso knows [[hub]].", type="entity"),
+ _page("entities/hub.md", "# Hub\n\nThe centre.", type="entity"),
+ ]
+ )
+ related = model.related("entities/a.md")
+ assert [item["path"] for item in related] == ["entities/b.md"]
+ assert related[0]["via"]["path"] == "entities/hub.md"
+
+
+def test_rewrite_links_keeps_form_alias_and_anchor() -> None:
+ model = build_model(
+ [
+ _page("entities/old-name.md", "# Old name\n\nA page.", type="entity"),
+ _page(
+ "projects/p.md",
+ "# P\n\n[[old-name]], [[entities/old-name|label]], [[old-name#Facts]], [[other]]",
+ type="project",
+ ),
+ ]
+ )
+ body, count = model.rewrite_links("projects/p.md", "entities/old-name.md", "entities/new-name")
+ assert count == 3
+ assert "[[new-name]]" in body
+ assert "[[entities/new-name|label]]" in body
+ assert "[[new-name#Facts]]" in body
+ assert "[[other]]" in body
+
+
+def test_read_properties_keeps_yaml_lists() -> None:
+ raw = "---\ntype: entity\naliases:\n- the user\n- Ruben\ncreated: 2026-10-02\n---\n# Ruben\n"
+ properties = read_properties(raw)
+ assert properties["aliases"] == ["the user", "Ruben"]
+ assert properties["created"] == "2026-10-02"
+ assert read_properties("# no frontmatter") == {}
+ # Broken YAML falls back to flat key/value pairs instead of failing.
+ assert read_properties("---\ntitle: a: b: [\nslug: x\n---\n")["slug"] == "x"
diff --git a/tests/unit/society/test_memory_books_reads.py b/tests/unit/society/test_memory_books_reads.py
new file mode 100644
index 0000000000..75a21009cf
--- /dev/null
+++ b/tests/unit/society/test_memory_books_reads.py
@@ -0,0 +1,30 @@
+"""Reading an agent's notebooks never creates them.
+
+Every agent the roster ever listed used to get two frontmatter-only files the
+first time anything read its memory, which left 170 empty pages in one vault.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from jarvis.society.memory_books import edit_book, has_books, read_books
+
+
+def _agent(agent_id: str = "vega") -> SimpleNamespace:
+ return SimpleNamespace(agent_id=agent_id, name="Vega")
+
+
+def test_reading_an_agent_without_notebooks_writes_nothing(tmp_path: Path) -> None:
+ agent = _agent()
+ assert read_books(tmp_path, agent) == {"memory": [], "user": []}
+ assert not (tmp_path / "society").exists()
+ assert not has_books(tmp_path, agent)
+
+
+def test_the_first_write_creates_the_notebooks_and_reads_find_it(tmp_path: Path) -> None:
+ agent = _agent()
+ edit_book(tmp_path, agent, "Deploys run on Fridays.", target="memory")
+ assert has_books(tmp_path, agent)
+ books = read_books(tmp_path, agent)
+ assert [entry.text for entry in books["memory"]] == ["Deploys run on Fridays."]
diff --git a/tests/unit/ui/web/test_memory_vault_routes.py b/tests/unit/ui/web/test_memory_vault_routes.py
new file mode 100644
index 0000000000..e955061acd
--- /dev/null
+++ b/tests/unit/ui/web/test_memory_vault_routes.py
@@ -0,0 +1,276 @@
+"""The path-addressed Memory section API (``memory_vault_routes``).
+
+Real files in ``tmp_path`` and a real ``WikiCurator`` + ``AtomicWriter`` for
+the write routes, so every write goes through the same guarded pipeline the
+app uses. The society runtime is absent here, so every agent folder reads
+as an orphan.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from collections.abc import Iterator
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.memory.wiki import integration
+from jarvis.memory.wiki.atomic_writer import AtomicWriter
+from jarvis.memory.wiki.curator import WikiCurator
+from jarvis.memory.wiki.curator_llm import WikiCuratorLLM
+from jarvis.memory.wiki.log_writer import LogWriter
+from jarvis.memory.wiki.page import MarkdownPageRepository
+from jarvis.memory.wiki.vault_index import VaultIndex
+from jarvis.ui.web.memory_vault_routes import router as memory_router
+from jarvis.ui.web.wiki_routes import invalidate_visible_page_cache
+
+_OLD = time.time() - 3_600
+
+
+def _write(vault: Path, rel: str, text: str) -> Path:
+ path = vault / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ # Older than the writer's 30 s concurrent-edit window.
+ os.utime(path, (_OLD, _OLD))
+ return path
+
+
+def vault(tmp_path: Path) -> Path:
+ root = tmp_path / "vault"
+ _write(
+ root,
+ "entities/ruben.md",
+ "---\ntype: entity\nslug: ruben\naliases:\n- the user\n---\n\n# Ruben\n\n"
+ "Owns [[projects/magenta]].\n",
+ )
+ _write(
+ root,
+ "projects/magenta.md",
+ "---\ntype: project\nslug: magenta\nstatus: active\n---\n\n"
+ "# Magenta\n\nBuilt by [[ruben]].\n",
+ )
+ _write(
+ root,
+ "society/ada/MEMORY.md",
+ '---\ntype: society\ntitle: "Ada — memory"\n---\n\n'
+ '<!-- memory-entry: {"id": "a1", "importance": 8, "origin": "tool"} -->\n'
+ "Ruben deploys on Fridays.\n",
+ )
+ _write(root, "society/ada/USER.md", '---\ntype: society\ntitle: "Ada — user profile"\n---\n')
+ _write(root, "society/vega/MEMORY.md", '---\ntype: society\ntitle: "Vega — memory"\n---\n')
+ _write(root, "society/vega/USER.md", '---\ntype: society\ntitle: "Vega — user profile"\n---\n')
+ _write(
+ root,
+ "log.md",
+ "# Wiki Log\n\n## [2026-10-01 10:00] create | journal-batch:1\n\n"
+ "- pages touched: [[entities/ruben]]\n- summary: Applied 1 create.\n\n"
+ "## [2026-10-02 10:00] update | self-doc:memory.md\n\n"
+ "- pages touched: [[memory]]\n- summary: Applied 1 update.\n",
+ )
+ invalidate_visible_page_cache()
+ return root
+
+
+class _EmptyRoster:
+ async def list(self, *, include_archived: bool = False) -> list[object]: # noqa: A003
+ return []
+
+
+class _EmptySociety:
+ roster = _EmptyRoster()
+
+ async def ensure_started(self) -> None:
+ return None
+
+
+def client(vault: Path, tmp_path: Path) -> Iterator[TestClient]:
+ app = FastAPI()
+ app.include_router(memory_router)
+ app.state.config = SimpleNamespace(
+ wiki_integration=SimpleNamespace(vault_root=vault),
+ memory=SimpleNamespace(data_dir=tmp_path / "data"),
+ )
+ # A roster that answers and knows none of the vault's agent folders.
+ app.state.society = _EmptySociety()
+ repo = MarkdownPageRepository()
+ curator = WikiCurator(
+ repo=repo,
+ vault=VaultIndex(repo=repo),
+ writer=AtomicWriter(vault_root=vault, backup_dir=tmp_path / "backups"),
+ llm=WikiCuratorLLM.__new__(WikiCuratorLLM),
+ log_writer=LogWriter(log_path=vault / "log.md"),
+ vault_root=vault,
+ )
+ integration._set_running_curator(curator)
+ try:
+ with TestClient(app) as test_client:
+ yield test_client
+ finally:
+ integration._set_running_curator(None)
+ invalidate_visible_page_cache()
+
+
+def test_index_lists_every_notebook_once_and_flags_empty_pages(client: TestClient) -> None:
+ body = client.get("/api/wiki/index").json()
+
+ paths = {page["path"]: page for page in body["pages"]}
+ assert "society/ada/MEMORY.md" in paths and "society/vega/MEMORY.md" in paths
+ assert paths["society/ada/MEMORY.md"]["empty"] is False
+ assert paths["society/vega/MEMORY.md"]["empty"] is True
+ assert paths["log.md"]["group"] == "system"
+ assert {agent["agent_id"]: agent["state"] for agent in body["agents"]} == {
+ "ada": "orphan",
+ "vega": "orphan",
+ }
+ assert body["stats"]["links"] == 2
+ assert body["writable"] is True
+
+
+def test_read_returns_the_requested_notebook_not_the_first_with_that_name(
+ client: TestClient,
+) -> None:
+ vega = client.get("/api/wiki/read", params={"path": "society/vega/MEMORY.md"}).json()
+ ada = client.get("/api/wiki/read", params={"path": "society/ada/MEMORY.md"}).json()
+
+ assert vega["path"] == "society/vega/MEMORY.md"
+ assert vega["empty"] is True and vega["entries"] == []
+ assert ada["entries"] == [
+ {"id": "a1", "text": "Ruben deploys on Fridays.", "importance": 8, "origin": "tool"}
+ ]
+ assert ada["editable"] is False
+ assert [item["path"] for item in ada["mentions"]] == ["entities/ruben.md"]
+
+
+def test_read_links_both_ways(client: TestClient) -> None:
+ ruben = client.get("/api/wiki/read", params={"path": "entities/ruben.md"}).json()
+ assert [item["path"] for item in ruben["outgoing"]] == ["projects/magenta.md"]
+ assert [item["path"] for item in ruben["backlinks"]] == ["projects/magenta.md"]
+ assert [item["path"] for item in ruben["mentioned_in"]] == ["society/ada/MEMORY.md"]
+ assert ruben["properties"]["aliases"] == ["the user"]
+
+
+def test_unknown_path_is_404(client: TestClient) -> None:
+ response = client.get("/api/wiki/read", params={"path": "../secrets.md"})
+ assert response.status_code == 404
+
+
+def test_map_has_content_pages_only(client: TestClient) -> None:
+ body = client.get("/api/wiki/map").json()
+ ids = {node["id"] for node in body["nodes"]}
+ assert ids == {"entities/ruben.md", "projects/magenta.md", "society/ada/MEMORY.md"}
+ without_agents = client.get("/api/wiki/map", params={"agents": "false"}).json()
+ assert {node["id"] for node in without_agents["nodes"]} == {
+ "entities/ruben.md",
+ "projects/magenta.md",
+ }
+
+
+def test_activity_skips_self_doc_refreshes(client: TestClient) -> None:
+ items = client.get("/api/wiki/activity").json()["items"]
+ assert [(item["verb"], [p["path"] for p in item["pages"]]) for item in items] == [
+ ("create", ["entities/ruben.md"])
+ ]
+
+
+def test_create_save_rename_and_archive_round_trip(client: TestClient, vault: Path) -> None:
+ created = client.post(
+ "/api/wiki/pages", json={"kind": "entity", "title": "Maria Weber", "body_md": ""}
+ )
+ assert created.status_code == 200, created.text
+ assert created.json()["path"] == "entities/maria-weber.md"
+ text = (vault / "entities/maria-weber.md").read_text(encoding="utf-8")
+ assert "slug: maria-weber" in text and "# Maria Weber" in text
+
+ duplicate = client.post("/api/wiki/pages", json={"kind": "entity", "title": "Maria Weber"})
+ assert duplicate.status_code == 409
+
+ ruben = client.get("/api/wiki/read", params={"path": "entities/ruben.md"}).json()
+ saved = client.put(
+ "/api/wiki/pages",
+ json={
+ "path": "entities/ruben.md",
+ "body_md": "# Ruben\n\nWorks with [[Someone New]] on [[projects/magenta]].",
+ "base_mtime": ruben["mtime"],
+ },
+ )
+ assert saved.status_code == 200, saved.text
+ on_disk = (vault / "entities/ruben.md").read_text(encoding="utf-8")
+ assert on_disk.startswith("---\ntype: entity\nslug: ruben\n")
+ # A person's link to a page that does not exist yet is kept, not demoted.
+ assert "[[Someone New]]" in on_disk
+
+ renamed = client.post(
+ "/api/wiki/pages/rename", json={"path": "projects/magenta.md", "title": "Magenta IDE"}
+ )
+ assert renamed.status_code == 200, renamed.text
+ assert renamed.json() == {
+ "ok": True,
+ "path": "projects/magenta-ide.md",
+ "links_rewritten": 1,
+ "links_unrewritten": 0,
+ }
+ assert not (vault / "projects/magenta.md").exists()
+ assert "[[projects/magenta-ide]]" in (vault / "entities/ruben.md").read_text(encoding="utf-8")
+ assert "slug: magenta-ide" in (vault / "projects/magenta-ide.md").read_text(encoding="utf-8")
+
+ archived = client.post("/api/wiki/pages/archive", json={"path": "entities/maria-weber.md"})
+ assert archived.status_code == 200, archived.text
+ assert not (vault / "entities/maria-weber.md").exists()
+ assert list((vault / "_archive").rglob("maria-weber*.md"))
+
+
+def test_save_refuses_a_stale_editor_and_agent_notebooks(client: TestClient) -> None:
+ stale = client.put(
+ "/api/wiki/pages",
+ json={"path": "entities/ruben.md", "body_md": "x", "base_mtime": _OLD - 100},
+ )
+ assert stale.status_code == 409
+
+ notebook = client.put(
+ "/api/wiki/pages",
+ json={"path": "society/ada/MEMORY.md", "body_md": "x", "base_mtime": time.time()},
+ )
+ assert notebook.status_code == 403
+ # Without the editor's base version there is no stale-write guard.
+ unguarded = client.put("/api/wiki/pages", json={"path": "entities/ruben.md", "body_md": "x"})
+ assert unguarded.status_code == 422
+
+
+def test_tidy_previews_then_archives_only_empty_notebooks(client: TestClient, vault: Path) -> None:
+ preview = client.post("/api/wiki/tidy", json={"dry_run": True}).json()
+ assert preview["paths"] == [
+ "society/ada/USER.md",
+ "society/vega/MEMORY.md",
+ "society/vega/USER.md",
+ ]
+ assert (vault / "society/vega/MEMORY.md").exists()
+
+ done = client.post("/api/wiki/tidy", json={"dry_run": False}).json()
+ assert done["count"] == 3
+ assert not (vault / "society/vega/MEMORY.md").exists()
+ assert (vault / "society/ada/MEMORY.md").exists()
+
+
+def test_tidy_refuses_when_the_roster_does_not_answer(client: TestClient, vault: Path) -> None:
+ # Without the roster every folder would look orphaned, live agents too.
+ client.app.state.society = None # type: ignore[attr-defined]
+ response = client.post("/api/wiki/tidy", json={"dry_run": False})
+ assert response.status_code == 503
+ assert (vault / "society/vega/MEMORY.md").exists()
+ # Reading still works; agents just fall back to their folder names.
+ assert client.get("/api/wiki/index").status_code == 200
+
+
+def test_writes_without_a_running_curator_say_why(client: TestClient) -> None:
+ integration._set_running_curator(None)
+ response = client.post("/api/wiki/pages", json={"kind": "concept", "title": "Idea"})
+ assert response.status_code == 503
+ assert "memory writer" in response.json()["detail"]
+ assert client.get("/api/wiki/index").json()["writable"] is False