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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(wiki): rebuild the Wiki section as library, memory map and inspector
rubenluetke10-beep86b7af247090
diff --git a/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsx b/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsxdeleted file mode 100644index a3a963c30e..0000000000--- a/jarvis/ui/web/frontend/src/components/wiki/BacklinksPanel.tsx+++ /dev/null@@ -1,101 +0,0 @@-/**- * Right-column panel: pages that link back to the currently open page.- *- * Reads `/api/wiki/backlinks/{slug}` and renders each backlink as a clickable- * card. Clicking a backlink invokes `onSelect(targetSlug)` so the caller- * can switch the page view.- */-import { useQuery } from "@tanstack/react-query";-import { FileText } from "lucide-react";--import { useT } from "@/i18n";-import { fetchWikiBacklinks } from "@/lib/wikiApi";--interface BacklinksPanelProps {- slug: string;- onSelect: (targetSlug: string) => void;-}--export function BacklinksPanel({ slug, onSelect }: BacklinksPanelProps) {- const t = useT();- const { data, isLoading, isError } = useQuery({- queryKey: ["wiki", "backlinks", slug],- queryFn: () => fetchWikiBacklinks(slug),- staleTime: 5_000,- enabled: Boolean(slug),- });-- const backlinks = data?.backlinks ?? [];-- return (- <aside- className="flex h-full w-[380px] shrink-0 flex-col overflow-y-auto bg-sidebar p-4"- data-testid="wiki-backlinks-panel"- >- <BacklinksCard title="Backlinks">- {isLoading && <BacklinksSkeleton />}- {isError && (- <div- role="alert"- className="text-meta text-destructive"- >- {t("backlinks_panel.load_error")}- </div>- )}- {!isLoading && !isError && backlinks.length === 0 && (- <p className="text-body text-muted-foreground" data-testid="wiki-backlinks-empty">- {t("backlinks_panel.empty")}- </p>- )}- {!isLoading && !isError &&- backlinks.map((bl) => (- <button- type="button"- key={bl.slug}- onClick={() => onSelect(bl.slug)}- className="flex w-full items-start gap-2 rounded-md px-2 py-2 text-left text-body text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"- data-testid="wiki-backlink-item"- data-target-slug={bl.slug}- >- <FileText className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <div className="truncate text-foreground">{bl.title || bl.slug}</div>- {bl.snippet && (- <div className="mt-0.5 text-meta text-muted-foreground">- {bl.snippet}- </div>- )}- </div>- </button>- ))}- </BacklinksCard>- </aside>- );-}--function BacklinksCard({- title,- children,-}: {- title: string;- children: React.ReactNode;-}) {- return (- // Not a card: a panel the full height of the section is far too wide to- // earn --card, so it takes the rail ground and the heading does the work a- // box used to do badly.- <section className="mb-stack">- <h3 className="mb-3 text-title font-semibold text-foreground-strong">{title}</h3>- <div className="space-y-1">{children}</div>- </section>- );-}--function BacklinksSkeleton() {- return (- <div className="space-y-2" data-testid="wiki-backlinks-skeleton">- <div className="h-4 w-3/4 animate-pulse rounded-full bg-sheen/[0.06]" />- <div className="h-3 w-1/2 animate-pulse rounded-full bg-sheen/[0.06]" />- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/wiki/KindGlyph.tsx b/jarvis/ui/web/frontend/src/components/wiki/KindGlyph.tsxnew file mode 100644index 0000000000..84051ef14b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/wiki/KindGlyph.tsx@@ -0,0 +1,51 @@+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/ObsidianStatus.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsxindex 5015e910bf..8f82adca78 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsx@@ -97,8 +97,8 @@ describe("ObsidianStatus", () => {expect(pill.getAttribute("title")).toContain("1.7.4");// OK pill is non-interactive.expect((pill as HTMLButtonElement).disabled).toBe(true);- // Green colour class present (#5bd4a4).- expect(pill.className).toContain("#5bd4a4");+ // Connected reads quiet: the success hue sits on the icon only.+ expect(pill.className).toContain("text-success");});it("renders 'not installed' when installed=false", async () => {@@ -114,7 +114,7 @@ describe("ObsidianStatus", () => {});const pill = screen.getByTestId("obsidian-status-pill");expect(pill.textContent).toContain("not installed");- expect(pill.className).toContain("#facc15");+ expect(pill.className).toContain("text-warning");expect((pill as HTMLButtonElement).disabled).toBe(false);});@@ -131,7 +131,7 @@ describe("ObsidianStatus", () => {});const pill = screen.getByTestId("obsidian-status-pill");expect(pill.textContent).toContain("not registered");- expect(pill.className).toContain("#ffb84d");+ expect(pill.className).toContain("text-warning");});it("renders 'status unclear' on fetch failure", async () => {@@ -147,7 +147,7 @@ describe("ObsidianStatus", () => {});const pill = screen.getByTestId("obsidian-status-pill");expect(pill.textContent).toContain("status unclear");- expect(pill.className).toContain("#8d94a8");+ expect(pill.className).toContain("text-muted-foreground");});it("renders 'status unclear' when note is set", async () => {diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsxindex 39eca1f5e5..9c0096ffe9 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx@@ -45,19 +45,14 @@ function classify(status: ObsidianStatusType | null, errored: boolean): Visual {return "unclear";}-// Tailwind colour classes mirroring the codebase conventions-// (cf. PageHeader's TYPE_COLOR map and ObsidianButton's outline style).-// Hex fallbacks from the task brief: ok=#5bd4a4 register=#ffb84d install=#facc15 unclear=#8d94a8const VISUAL_STYLE: Record<Visual, string> = {- loading:- "border-border bg-secondary/40 text-muted-foreground cursor-default",- ok: "border-[#5bd4a4]/40 bg-[#5bd4a4]/10 text-[#5bd4a4] cursor-default",- register:- "border-[#ffb84d]/40 bg-[#ffb84d]/10 text-[#ffb84d] cursor-pointer hover:bg-[#ffb84d]/20",- install:- "border-[#facc15]/40 bg-[#facc15]/10 text-[#facc15] cursor-pointer hover:bg-[#facc15]/20",- unclear:- "border-[#8d94a8]/40 bg-[#8d94a8]/10 text-[#8d94a8] cursor-pointer hover:bg-[#8d94a8]/20",+ // Theme tokens only: status hues for status, neutral ink otherwise. The+ // connected state is quiet — a green icon, not a green slab.+ loading: "text-muted-foreground cursor-default",+ ok: "text-muted-foreground cursor-default [&>svg]:text-success",+ register: "text-warning cursor-pointer hover:bg-warning/10",+ install: "text-warning cursor-pointer hover:bg-warning/10",+ unclear: "text-muted-foreground cursor-pointer hover:bg-secondary hover:text-foreground",};function visualLabels(t: (key: string) => string): Record<Visual, string> {@@ -196,7 +191,7 @@ export function ObsidianStatus({data-visual={visual}aria-label={label}className={cn(- "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",+ "inline-flex h-8 items-center gap-1.5 rounded-md px-2.5 text-sm font-medium transition-colors","disabled:opacity-100",VISUAL_STYLE[visual],)}diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsxindex 4606c0b317..2f8f5f57fc 100644--- a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx@@ -1,19 +1,17 @@/**- * Wiki page header: breadcrumb + title + frontmatter pills + Obsidian button.- *- * The Obsidian button itself is owned by Agent D; this header attempts to- * import that component lazily and falls back to a disabled placeholder- * when it does not yet exist (parallel-build contract).+ * 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 { useT, useUiLanguage } from "@/i18n";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 import — Agent D owns the real "Open in Obsidian" button. A-// placeholder file ships in this branch; Agent D's real implementation-// replaces it during Wave 2.+// Lazy so the page body paints before the Obsidian hand-off code arrives.const ObsidianButton = lazy(() =>import("./ObsidianButton").then((mod) => ({default: mod.ObsidianButton,@@ -22,11 +20,14 @@ const ObsidianButton = lazy(() =>interface PageHeaderProps {slug: string;- kind: WikiKind;+ 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;}const FRIENDLY_LABELS: Record<string, string> = {@@ -48,58 +49,83 @@ export function PageHeader({frontmatter,vaultRoot,vaultRelPath,+ mtime,+ words,}: PageHeaderProps) {+ const t = useT();+ const language = useUiLanguage();const pills = buildPills(frontmatter);const breadcrumb = breadcrumbFromPath(vaultRelPath);+ const group = groupOfKind(kind);+ const changed = mtime ? relativeAge(mtime, language) : "";return (- <header- className="flex flex-col gap-3 border-b border-border px-7 py-5 md:flex-row md:items-start md:justify-between"- data-testid="wiki-page-header"- data-slug={slug}- >- <div className="min-w-0 flex-1">- <div className="mb-1.5 text-meta text-muted-foreground" data-testid="wiki-page-crumb">+ <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}>- {idx > 0 && <span className="mx-1.5">/</span>}- {part}+ <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>))}- </div>- <h1- className="text-display font-semibold text-foreground-strong"- data-testid="wiki-page-title"- >- {title}- </h1>- {/* The page kind used to be painted in one of four hardcoded hues.- Hue belongs to life, fault and identity only — a page's kind is- none of those, so it is now simply the first neutral chip. */}- {(pills.length > 0 || kind) && (- <div className="mt-2.5 flex flex-wrap gap-2 text-meta" data-testid="wiki-page-pills">- <span className="rounded-full bg-secondary px-2.5 py-0.5 text-foreground">{kind}</span>- {pills.map((p) => (- <span- key={p.key}- className="rounded-full bg-secondary px-2.5 py-0.5 text-muted-foreground"- data-pill-key={p.key}- >- <span className="mr-1.5">{p.label}:</span>- <span className="text-foreground">{p.value}</span>- </span>- ))}- </div>- )}+ </nav>+ <Suspense fallback={<ObsidianButtonPlaceholder />}>+ <ObsidianButton vaultRoot={vaultRoot} vaultRelPath={vaultRelPath} size="sm" />+ </Suspense></div>- <Suspense- fallback={- <ObsidianButtonPlaceholder vaultRelPath={vaultRelPath} />- }+ <h1+ className="mt-5 text-display font-semibold text-foreground-strong"+ data-testid="wiki-page-title">- <ObsidianButton vaultRoot={vaultRoot} vaultRelPath={vaultRelPath} />- </Suspense>+ {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>{p.label}</span>+ <span className="text-foreground">{p.value}</span>+ </span>+ ))}+ </div>+ )}</header>);}@@ -129,23 +155,6 @@ function breadcrumbFromPath(relPath: string): string[] {return parts.length > 0 ? parts : [relPath];}-function ObsidianButtonPlaceholder({ vaultRelPath: _vaultRelPath }: { vaultRelPath: string }) {- const t = useT();- return (- <button- type="button"- disabled- className={cn(- "inline-flex shrink-0 items-center gap-2 rounded-md bg-secondary",- "px-3.5 py-2 text-body text-faint-foreground",- )}- data-testid="obsidian-button-placeholder"- title={t("page_header.placeholder_title")}- >- <span className="grid h-4 w-4 place-items-center rounded-sm bg-faint-foreground text-micro font-semibold text-background">- O- </span>- {t("page_header.open_in_obsidian")}- </button>- );+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.tsxindex 40f8366366..3df37c4ade 100644--- a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx@@ -1,6 +1,7 @@/**- * Render a single wiki page: header (breadcrumb + pills + Obsidian button)- * plus the markdown body with clickable `[[wikilinks]]`.+ * 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@@ -11,10 +12,14 @@** 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 { useMemo } from "react";+import { Children, cloneElement, isValidElement, useMemo, type ReactNode } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";-import ReactMarkdown from "react-markdown";+import ReactMarkdown, { type Components } from "react-markdown";+import remarkGfm from "remark-gfm";import {fetchWikiPage,@@ -22,8 +27,9 @@ import {type WikiKind,type WikiTreeResponse,} from "@/lib/wikiApi";+import { cleanTitle } from "@/lib/wikiModel";import { cn } from "@/lib/utils";-import { useT } from "@/i18n";+import { useT, useUiLanguage } from "@/i18n";import { PageHeader } from "./PageHeader";@@ -38,8 +44,12 @@ const WIKILINK_PREFIX = "#wiki:";// `[[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 = useUiLanguage();const qc = useQueryClient();const pageQuery = useQuery({queryKey: ["wiki", "page", slug],@@ -60,10 +70,129 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {[treeQuery.data],);+ const page = pageQuery.data;+ const title = cleanTitle(page?.title, slug);+const preprocessedBody = useMemo(() => {const raw = pageQuery.data?.body_md ?? "";- return preprocessWikilinks(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 />;@@ -71,19 +200,18 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {if (pageQuery.isError) {return (- <div className="px-7 py-6" data-testid="wiki-page-error">- <p role="alert" className="text-body text-destructive">+ <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>);}- const page = pageQuery.data;if (!page || !page.ok) {return (- <div className="px-7 py-6" data-testid="wiki-page-error">- <p role="alert" className="text-body text-destructive">+ <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>@@ -92,20 +220,13 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {const kind = (page.kind ?? "entity") as WikiKind;const vaultRelPath = page.path ?? `${kind}/${slug}.md`;- const title = page.title ?? slug;const frontmatter = page.frontmatter ?? {};- const handleClick = (target: string) => {- 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 show a toast.- qc.invalidateQueries({ queryKey: ["wiki", "tree"] });- }- onWikilinkClick(target);- };-return (- <article className="flex flex-col" data-testid="wiki-page-renderer">+ <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"+ ><PageHeaderslug={slug}kind={kind}@@ -113,75 +234,17 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {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. It used to run every- paragraph, list and heading at muted ink under `prose-invert` — a- dark-only class — so a page read as text somebody had disabled, and- light mode got dark-mode typography. */}+ ink and bounded to the reading measure, in both themes. */}<div- className="max-w-reading px-9 py-7 text-reading text-foreground"+ className="mt-8 border-t border-border pt-8 text-reading text-foreground"data-testid="wiki-page-body">- <ReactMarkdown- components={{- a: ({ href, children, ...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}- className={cn("wikilink", isBroken && "broken")}- onClick={(e) => {- e.preventDefault();- handleClick(target);- }}- >- {children}- </a>- );- }- return (- <a {...rest} href={href} target="_blank" rel="noopener noreferrer">- {children}- </a>- );- },- h1: ({ children }) => (- <h2 className="mb-3 mt-group text-title font-semibold text-foreground-strong">- {children}- </h2>- ),- h2: ({ children }) => (- <h2 className="mb-3 mt-group text-title font-semibold text-foreground-strong">- {children}- </h2>- ),- h3: ({ children }) => (- <h3 className="mb-2 mt-block text-title font-semibold text-foreground-strong">- {children}- </h3>- ),- p: ({ children }) => <p className="my-stack text-foreground">{children}</p>,- ul: ({ children }) => (- <ul className="my-stack list-disc pl-5 text-foreground">{children}</ul>- ),- li: ({ children }) => <li className="my-0.5">{children}</li>,- code: ({ children, ...rest }) => (- <code- {...rest}- className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-meta text-foreground"- >- {children}- </code>- ),- }}- >+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>{preprocessedBody}</ReactMarkdown></div>@@ -205,6 +268,60 @@ export function preprocessWikilinks(body: string): string {});}+/**+ * 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;@@ -224,21 +341,18 @@ function buildKnownSlugSet(tree: WikiTreeResponse | undefined): Set<string> {function PageSkeleton() {return (<div- className="max-w-reading space-y-stack px-9 py-7"+ 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-32 animate-pulse rounded-full bg-sheen/[0.06]" />- <div className="h-6 w-64 animate-pulse rounded-md bg-sheen/[0.06]" />- <div className="flex gap-2">- <div className="h-4 w-20 animate-pulse rounded-full bg-sheen/[0.06]" />- <div className="h-4 w-24 animate-pulse rounded-full bg-sheen/[0.06]" />- </div>- <div className="mt-group space-y-stack">- <div className="h-3 w-full animate-pulse rounded-full bg-sheen/[0.06]" />- <div className="h-3 w-5/6 animate-pulse rounded-full bg-sheen/[0.06]" />- <div className="h-3 w-4/6 animate-pulse rounded-full bg-sheen/[0.06]" />+ <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>);diff --git a/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsx b/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsxdeleted file mode 100644index 5640dcd27e..0000000000--- a/jarvis/ui/web/frontend/src/components/wiki/TreeSidebar.tsx+++ /dev/null@@ -1,188 +0,0 @@-/**- * Folder tree for the on-disk Obsidian vault.- *- * Renders the response from `/api/wiki/tree` as a collapsible tree.- * Folder open/closed state lives in local component state — not persisted.- * Folders `entities` and `projects` start open; `concepts`, `sessions`,- * `_archive` start closed (mockup contract).- */-import { useState, useMemo, useEffect } from "react";-import { ChevronRight, FileText } from "lucide-react";-import { useQuery } from "@tanstack/react-query";--import { cn } from "@/lib/utils";-import { fetchWikiTree, type WikiTreeFolder } from "@/lib/wikiApi";-import { useT } from "@/i18n";--interface TreeSidebarProps {- selectedSlug: string | null;- onSelect: (slug: string) => void;-}--const DEFAULT_OPEN = new Set(["entities", "projects"]);--export function TreeSidebar({ selectedSlug, onSelect }: TreeSidebarProps) {- const t = useT();- const { data, isLoading, isError } = useQuery({- queryKey: ["wiki", "tree"],- queryFn: fetchWikiTree,- staleTime: 5_000,- });-- const folders: WikiTreeFolder[] = data?.folders ?? [];- const stats = data?.stats;-- const [openFolders, setOpenFolders] = useState<Set<string>>(- () => new Set(DEFAULT_OPEN),- );-- // Reconcile open state when the tree arrives: non-empty folders that match- // DEFAULT_OPEN remain open; otherwise leave user-controlled state alone.- // Important: return the previous Set reference when no folder needed to be- // added — returning a fresh Set every render triggers an infinite loop in- // React 18 strict mode (and in tests).- useEffect(() => {- setOpenFolders((prev) => {- let changed = false;- const next = new Set(prev);- for (const f of folders) {- if (DEFAULT_OPEN.has(f.name) && f.count > 0 && !next.has(f.name)) {- next.add(f.name);- changed = true;- }- }- return changed ? next : prev;- });- }, [folders]);-- const toggle = (name: string) => {- setOpenFolders((prev) => {- const next = new Set(prev);- if (next.has(name)) {- next.delete(name);- } else {- next.add(name);- }- return next;- });- };-- const lastChangedLabel = useMemo(() => {- if (!stats?.last_curator_run) return "—";- try {- const d = new Date(stats.last_curator_run);- return d.toLocaleString();- } catch {- return "—";- }- }, [stats?.last_curator_run]);-- return (- <aside- className="flex h-full w-[260px] shrink-0 flex-col overflow-y-auto bg-sidebar"- data-testid="wiki-tree-sidebar"- >- <div className="flex items-center justify-between border-b border-border px-3 py-3">- <h2 className="text-title font-semibold text-foreground-strong">Vault</h2>- <span className="text-meta text-muted-foreground">wiki/obsidian-vault/</span>- </div>-- <div className="flex-1 p-2">- {isLoading && <TreeSkeleton />}- {isError && (- <div- role="alert"- className="m-2 text-meta text-destructive"- >- {t("tree_sidebar.load_error")}- </div>- )}-- {!isLoading && !isError &&- folders.map((folder) => {- const isOpen = openFolders.has(folder.name);- return (- <div key={folder.name} className="mb-1">- <button- type="button"- onClick={() => toggle(folder.name)}- className={cn(- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body",- "text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground",- )}- data-folder={folder.name}- data-open={isOpen ? "true" : "false"}- >- <ChevronRight- className={cn(- "h-3 w-3 shrink-0 transition-transform",- isOpen && "rotate-90",- )}- />- <span className="flex-1 text-left">{folder.name}</span>- <span className="text-meta tabular-nums">{folder.count}</span>- </button>-- {isOpen && folder.files.length > 0 && (- <ul className="ml-3 mt-0.5 space-y-0.5" data-testid={`wiki-folder-${folder.name}`}>- {folder.files.map((file) => {- const isActive = file.slug === selectedSlug;- return (- <li key={file.slug}>- <button- type="button"- onClick={() => onSelect(file.slug)}- data-slug={file.slug}- data-active={isActive ? "true" : "false"}- className={cn(- "flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-body transition-colors",- isActive- ? "bg-secondary text-foreground-strong"- : "text-muted-foreground hover:bg-secondary hover:text-foreground",- )}- >- <FileText className="h-3 w-3 shrink-0" />- <span className="truncate">{file.slug}.md</span>- </button>- </li>- );- })}- </ul>- )}- </div>- );- })}- </div>-- {stats && (- <div- className="space-y-1 border-t border-border px-3 py-3 text-meta text-muted-foreground"- data-testid="wiki-tree-meta"- >- <div className="flex justify-between gap-2">- <span>Total pages</span>- <span className="tabular-nums text-foreground">{stats.total_pages}</span>- </div>- <div className="flex justify-between gap-2">- <span>Total links</span>- <span className="tabular-nums text-foreground">{stats.total_links}</span>- </div>- <div className="flex justify-between gap-2">- <span>{t("tree_sidebar.last_change")}</span>- <span className="text-foreground">{lastChangedLabel}</span>- </div>- </div>- )}- </aside>- );-}--function TreeSkeleton() {- return (- <div className="space-y-2 p-2" data-testid="wiki-tree-skeleton">- {[0, 1, 2, 3].map((i) => (- <div key={i} className="h-4 animate-pulse rounded-full bg-sheen/[0.06]" />- ))}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsxindex 3f17483547..d43df6e1a6 100644--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx@@ -162,7 +162,10 @@ describe("WikiGraph", () => {const nodeLabel = props.nodeLabel as (node: Record<string, unknown>) => string;const linkLabel = props.linkLabel as (link: Record<string, unknown>) => string;- expect(props.linkDirectionalArrowLength).toBe(4);+ // 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(diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsxindex 6e2cadcf30..e397875752 100644--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.tsx@@ -1,9 +1,13 @@// Force-directed graph of the Obsidian-vault wikilink network.//-// Owned by Agent C of Phase B3. Pure view component — it fetches-// `/api/wiki/graph` via React Query and renders nodes/edges with-// `react-force-graph-2d`. No filter chips, no custom force tweaks; this is the-// landing view inside the Wiki tab, so it stays minimal and fast.+// 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`,@@ -28,7 +32,6 @@ import ForceGraph2D from "react-force-graph-2d";import type { ForceGraphMethods, NodeObject } from "react-force-graph-2d";import {- BROKEN_EDGE_COLOUR,clampCenterToView,NODE_COLOUR,edgeDetails,@@ -42,10 +45,26 @@ import {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@@ -92,6 +111,116 @@ export interface WikiGraphProps {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";++/** 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@@ -137,9 +266,47 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.EstaleTime: 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[] };- const out = toGraphData(data);+ // 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@@ -164,6 +331,56 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E[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 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);@@ -340,14 +557,14 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.EresumeRender();}, [graphData, resumeRender]);- // A selection change only needs a repaint, not a reheat: run a few frames,- // then go back to idle.+ // 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, graphData.nodes.length, resumeRender, pauseRenderIfIdle]);+ }, [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.@@ -525,22 +742,23 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.Eif (!ref) return;// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst anyRef = ref as any;- // Repulsion: each pair pushes each other away with strength- // -180 if closer than 220 px, then falls off. Settled- // envelope is ~300x300 px.+ // Repulsion: every pair pushes apart, reaching far enough (380 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(-180);+ chargeForce.strength(-150);if (typeof chargeForce.distanceMax === "function") {- chargeForce.distanceMax(220);+ chargeForce.distanceMax(380);}}- // Links stay short so labels stay close enough to read.+ // 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(55);+ linkForce.distance(48);if (typeof linkForce.strength === "function") {- linkForce.strength(0.85);+ linkForce.strength(0.5);}}// Soft centering: every node feels a gentle pull towards (0,0) — this@@ -592,7 +810,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E[],);- const nodeCanvasObjectMode = useCallback(() => "after" as const, []);+ const nodeCanvasObjectMode = useCallback(() => "replace" as const, []);const nodeCanvasObject = useCallback((@@ -602,52 +820,148 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E): void => {const x = node.x ?? 0;const y = node.y ?? 0;- const isActive = node.id === highlightRef.current;- // Match the nodeVal calculation so label distance stays consistent with- // the dot edge across all node sizes.+ const id = String(node.id ?? "");+ const palette = paletteRef.current;+ const { neighbours, degree, labelled, 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 = sizeOf(node as RenderNode, isActive) * 2;- if (isActive) {- ctx.save();+ // 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 + 4, 0, 2 * Math.PI, false);- ctx.fillStyle = "rgba(106, 169, 255, 0.18)";+ 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();- ctx.restore();+ // A hairline in the room colour keeps touching shapes apart.+ ctx.strokeStyle = hsl(palette.room, 0.9);+ ctx.lineWidth = 0.8 / globalScale;+ ctx.stroke();}- // Always-visible labels in screen-space (divide font size by- // globalScale so labels look ~10 px regardless of zoom).- const label = (node as RenderNode).title ?? (node.id as string | undefined) ?? "";- if (label) {- ctx.save();- const fontSize = 10 / globalScale;- ctx.font = `${fontSize}px ui-sans-serif, system-ui, sans-serif`;++ const showLabel =+ inFocus &&+ (isActive ||+ isHover ||+ isHub ||+ (focus !== null && isNeighbour) ||+ labelled.has(id) ||+ globalScale >= LABEL_ALL_ZOOM);+ const label = (node as RenderNode).title ?? id;+ if (showLabel && label) {+ const strong = isActive || isHover || isHub || labelled.has(id);+ const fontSize = (strong ? 12 : 11) / globalScale;+ ctx.font = `${strong ? 500 : 400} ${fontSize}px ${CANVAS_FONT}`;ctx.textAlign = "center";ctx.textBaseline = "top";- ctx.fillStyle = isActive ? "#e6ecf5" : "#a8b0c0";- ctx.shadowColor = "rgba(0,0,0,0.85)";- ctx.shadowBlur = 3 / globalScale;- ctx.fillText(label, x, y + radius + 3 / globalScale);- ctx.restore();+ const ty = y + radius + 4 / globalScale;+ // A halo in the room colour instead of a drop shadow: legible over+ // crossing lines in both themes, and no glow.+ ctx.lineJoin = "round";+ ctx.lineWidth = 3.5 / globalScale;+ ctx.strokeStyle = hsl(palette.room, 0.92);+ ctx.strokeText(label, x, ty);+ ctx.fillStyle =+ isActive || isHover+ ? hsl(palette.ink)+ : strong+ ? hsl(palette.ink, 0.88)+ : hsl(palette.muted, 0.95);+ ctx.fillText(label, x, ty);}+ ctx.restore();},[],);- const linkColor = useCallback(- (link: RenderEdge) =>- (link as RenderEdge).broken ? BROKEN_EDGE_COLOUR : "rgba(106, 169, 255, 0.45)",- [],- );+ 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),[],);- const linkArrowColor = useCallback(- (link: RenderEdge) =>- (link as RenderEdge).broken ? BROKEN_EDGE_COLOUR : "rgba(106, 169, 255, 0.75)",- [],+ // 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(@@ -735,7 +1049,7 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E);}- if (graphData.nodes.length === 0) {+ if ((data.nodes ?? []).length === 0) {return (<divdata-testid="wiki-graph-empty"@@ -748,26 +1062,92 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E);}+ const legendGroups = WIKI_GROUPS.filter((group) => (kindCounts.get(group) ?? 0) > 0);+ const connectionCount = graphData.links.filter((link) => !link.broken).length;+return (<divref={wrapRef}data-testid="wiki-graph-wrap"- className="relative h-full w-full overflow-hidden"+ 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)}>- <div className="absolute top-3 right-3 z-10 flex items-center gap-2">- <GraphDimensionToggle />+ {/* 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-[200px] 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 right-3 top-3 z-10 flex items-center gap-2">+ <GraphDimensionToggle className="h-8 bg-popover/85" /><buttontype="button"onClick={handleResetView}data-testid="wiki-graph-reset-view"- className="rounded-md border border-border bg-card/80 px-3 py-1.5 text-xs text-muted-foreground backdrop-blur transition hover:text-foreground hover:bg-card"+ 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-3 left-1/2 z-10 -translate-x-1/2 whitespace-nowrap text-xs text-foreground-faint">+ {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>@@ -810,8 +1190,9 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.E// 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. Passing fresh closures- // made the library re-ingest its whole accessor set on each of this+ // 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}@@ -833,7 +1214,11 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.EonZoomEnd={handleZoomEnd}onNodeDrag={handleNodeDrag}onBackgroundClick={handleBackgroundClick}- // Compact, Obsidian-like node size.+ 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}@@ -841,11 +1226,15 @@ export function WikiGraph({ onNodeClick, highlightSlug }: WikiGraphProps): JSX.EnodeCanvasObject={nodeCanvasObject}linkLabel={linkLabel}linkColor={linkColor}- linkWidth={1.0}+ linkWidth={linkWidth}linkLineDash={linkLineDash}- linkDirectionalArrowLength={4}+ 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 alphaDecaydiff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiInspector.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiInspector.tsxnew file mode 100644index 0000000000..c9c861def2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiInspector.tsx@@ -0,0 +1,700 @@+/**+ * 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 { ArrowUpRight, RefreshCw } from "lucide-react";++import { cn } from "@/lib/utils";+import { useT, useUiLanguage } from "@/i18n";+import {+ fetchWikiBacklinks,+ fetchWikiGraph,+ fetchWikiPage,+ type WikiCaptureFunnel,+ type WikiHealthSnapshot,+} from "@/lib/wikiApi";+import {+ GROUP_LABEL_KEY,+ cleanTitle,+ degreeOf,+ groupOfKind,+ relativeAge,+ uniqueEdges,+ type LibraryItem,+} from "@/lib/wikiModel";+import { KindGlyph } from "@/components/wiki/KindGlyph";++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();+ return (+ <aside+ className="flex h-full min-h-0 w-[320px] shrink-0 flex-col overflow-y-auto border-l border-border bg-sidebar"+ data-testid={props.selectedSlug ? "wiki-inspector-page" : "wiki-backlinks-placeholder"}+ aria-label={t("wiki_ui.inspector_label")}+ >+ {props.selectedSlug ? (+ <PageContext+ slug={props.selectedSlug}+ itemsBySlug={props.itemsBySlug}+ onSelect={props.onSelect}+ />+ ) : (+ <Overview {...props} />+ )}+ </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="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 */+/* ------------------------------------------------------------------------ */++const SNIPPET_LINK_RE = /\[\[([^\]|\n]+)(?:\|([^\]\n]+))?\]\]/g;++/** Backlink snippets arrive with raw `[[target|label]]` markup; show words. */+export function readableSnippet(snippet: string): string {+ return snippet+ .replace(SNIPPET_LINK_RE, (_m, target: string, label?: string) => {+ const text = (label ?? target).trim();+ const idx = Math.max(text.lastIndexOf("/"), text.lastIndexOf("\\"));+ return idx >= 0 && !label ? text.slice(idx + 1) : text;+ })+ .replace(/\s+/g, " ")+ .trim();+}++function PageContext({+ slug,+ itemsBySlug,+ onSelect,+}: {+ slug: string;+ itemsBySlug: ReadonlyMap<string, LibraryItem>;+ onSelect: (slug: string) => void;+}) {+ const t = useT();+ const language = useUiLanguage();+ 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/WikiLibrary.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiLibrary.tsxnew file mode 100644index 0000000000..04017e2662--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiLibrary.tsx@@ -0,0 +1,261 @@+/**+ * 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 { useT, useUiLanguage } 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;+}++export function WikiLibrary({+ folders,+ isLoading,+ isError,+ selectedSlug,+ onSelect,+}: WikiLibraryProps) {+ const t = useT();+ const language = useUiLanguage();+ 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-[272px] shrink-0 flex-col border-r border-border bg-sidebar"+ data-testid="wiki-tree-sidebar"+ aria-label={t("wiki_ui.library_label")}+ >+ <div className="shrink-0 p-3">+ <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-md border border-border bg-background pl-8 pr-7 text-sm text-foreground",+ "placeholder:text-foreground-faint [&::-webkit-search-cancel-button]:hidden",+ "transition-colors focus-visible:border-accent 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-md px-2 text-left text-base transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ active+ ? "bg-accent-soft 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.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsxindex bd7e92322f..3073c56ee1 100644--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx@@ -16,7 +16,10 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useStimport { Command } from "cmdk";import { keepPreviousData, useQuery } from "@tanstack/react-query";-import { colourForKind } from "@/lib/wikiGraph";+import { Search } from "lucide-react";++import { cleanTitle, groupOfKind, type WikiGroupId } from "@/lib/wikiModel";+import { KindGlyph } from "@/components/wiki/KindGlyph";import { useT } from "@/i18n";const SEARCH_DEBOUNCE_MS = 200;@@ -66,6 +69,17 @@ interface RecentEntry {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);@@ -130,7 +144,7 @@ function highlightSnippet(snippet: string, pattern: RegExp | null): JSX.Element<>{parts.map((part, idx) =>idx % 2 === 1 ? (- <mark key={idx} className="bg-foreground/30 text-foreground">+ <mark key={idx} className="rounded-sm bg-accent-soft text-foreground">{part}</mark>) : (@@ -244,7 +258,7 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function// returned results and the palette showed an empty list.shouldFilter={false}data-testid="wiki-search-dialog"- contentClassName="fixed left-1/2 top-[20vh] z-50 w-[min(640px,90vw)] -translate-x-1/2 rounded-xl border border-border bg-background"+ 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@@ -253,24 +267,24 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function<p className="sr-only" id="wiki-search-description">{t("wiki_search.dialog_description")}</p>- <div className="flex items-center gap-2 border-b border-border px-3 py-2">- <span aria-hidden="true" className="text-muted-foreground">⌕</span>+ <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.Inputvalue={rawQuery}onValueChange={setRawQuery}placeholder={t("wiki_search.input_placeholder")}data-testid="wiki-search-input"- className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"+ className="flex-1 bg-transparent text-base text-foreground outline-none placeholder:text-foreground-faint"autoFocus/>- <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 text-micro text-muted-foreground">+ <kbd className="rounded-sm border border-border px-1.5 py-0.5 font-mono text-xs text-foreground-faint">Esc</kbd></div><Command.Listdata-testid="wiki-search-list"- className="max-h-[60vh] overflow-y-auto p-2 text-sm"+ 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">@@ -286,15 +300,11 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(functiononSelect={() => handlePick(entry.slug)}data-testid="wiki-search-recent-item"data-slug={entry.slug}- className="flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 aria-selected:bg-muted"+ className="flex h-9 cursor-pointer items-center gap-2.5 rounded-md px-2 text-foreground aria-selected:bg-secondary">- <span- aria-hidden="true"- className="inline-block h-2 w-2 rounded-full"- style={{ background: colourForKind(entry.kind) }}- />- <span className="font-medium">{entry.title}</span>- <span className="text-muted-foreground">— {entry.path}</span>+ <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>)))}@@ -332,13 +342,14 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(functiononSelect={() => handlePick(hit.slug)}data-testid="wiki-search-hit"data-slug={hit.slug}- className="flex cursor-pointer flex-col gap-1 rounded px-2 py-1.5 aria-selected:bg-muted"+ 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">- <span className="font-medium">{hit.title}</span>- <span className="text-muted-foreground">— {hit.path}</span>+ <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>+ <span className="ml-auto truncate text-sm text-foreground-faint">{hit.path}</span></span>- <span className="line-clamp-2 text-xs text-muted-foreground">+ <span className="line-clamp-2 pl-5 text-sm text-muted-foreground">{highlightSnippet(hit.snippet, highlightPattern)}</span></Command.Item>diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 7086354819..bf0b7a06ef 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4161,6 +4161,59 @@"backlog_count": "Journal-Rückstand: {0}","legacy_conflict": "Konflikt mit Legacy-Vault erkannt"},+ "wiki_ui": {+ "title": "Wiki",+ "library_label": "Wiki-Seiten",+ "filter_placeholder": "Seiten filtern",+ "filter_clear": "Filter leeren",+ "filter_no_match": "Kein Seitentitel passt. Mit Strg K durchsuchst du den Inhalt.",+ "recent": "Zuletzt geändert",+ "group_entity": "Personen & Dinge",+ "group_project": "Projekte",+ "group_concept": "Konzepte",+ "group_session": "Sitzungen",+ "group_agent": "Notizbücher der Agenten",+ "group_system": "Systemseiten",+ "group_other": "Sonstiges",+ "inspector_label": "Seitendetails und Zustand des Gedächtnisses",+ "health_title": "Zustand des Gedächtnisses",+ "health_green": "Alles in Ordnung",+ "health_amber": "Braucht Aufmerksamkeit",+ "health_red": "Funktioniert nicht",+ "health_unknown": "Noch nicht geprüft",+ "health_chip_title": "Zustand des Gedächtnisses anzeigen",+ "capture_title": "Aus Gesprächen erfasst",+ "capture_window": "letzte {0} Std.",+ "capture_quiet": "In diesem Zeitraum wurde nichts erfasst.",+ "hubs_title": "Am stärksten vernetzt",+ "linked_from": "Verlinkt von",+ "linked_from_empty": "Noch keine andere Seite verlinkt hierher.",+ "links_to": "Verlinkt auf",+ "links_to_empty": "Diese Seite verlinkt auf keine andere Seite.",+ "link_missing": "Diese Seite gibt es noch nicht",+ "facts_title": "Über diese Seite",+ "fact_kind": "Art",+ "fact_folder": "Ordner",+ "fact_words": "Wörter",+ "fact_changed": "Geändert",+ "legend_label": "Seitenarten auf der Karte",+ "legend_show": "Auf der Karte zeigen",+ "legend_hide": "Auf der Karte ausblenden",+ "legend_connections": "{0} Verbindungen",+ "map_hint": "Scrollen zum Zoomen · Ziehen zum Verschieben · Doppelklick zentriert",+ "map_all_hidden": "Alle Seitenarten sind ausgeblendet. Blende in der Legende eine wieder ein.",+ "crumb_label": "Ort im Vault",+ "page_changed": "Geändert {0}",+ "page_words": "{0} Wörter",+ "as_of": "Stand",+ "search_placeholder": "Gedächtnis durchsuchen",+ "subtitle_pages": "{0} Seiten",+ "subtitle_links": "{0} Links",+ "subtitle_curated": "kuratiert {0}",+ "stage_label": "Gedächtniskarte und Seite",+ "tab_map": "Gedächtniskarte",+ "close_page": "Seite schließen"+ },"skill_create_dialog": {"title": "Skill erstellen","subtitle": "Beschreibe, was der Skill tun soll — per KI entwerfen oder das Formular selbst ausfüllen.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f3014b2ed5..d6e0d2936a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4161,6 +4161,59 @@"backlog_count": "Journal backlog: {0}","legacy_conflict": "Legacy vault conflict detected"},+ "wiki_ui": {+ "title": "Wiki",+ "library_label": "Wiki pages",+ "filter_placeholder": "Filter pages",+ "filter_clear": "Clear filter",+ "filter_no_match": "No page title matches. Press Ctrl K to search inside pages.",+ "recent": "Recently changed",+ "group_entity": "People & things",+ "group_project": "Projects",+ "group_concept": "Concepts",+ "group_session": "Sessions",+ "group_agent": "Agent notebooks",+ "group_system": "System pages",+ "group_other": "Other",+ "inspector_label": "Page details and memory health",+ "health_title": "Memory health",+ "health_green": "Healthy",+ "health_amber": "Needs attention",+ "health_red": "Not working",+ "health_unknown": "Not checked yet",+ "health_chip_title": "Show memory health",+ "capture_title": "Captured from conversations",+ "capture_window": "last {0} h",+ "capture_quiet": "Nothing was captured in this window.",+ "hubs_title": "Most connected",+ "linked_from": "Linked from",+ "linked_from_empty": "No other page links here yet.",+ "links_to": "Links to",+ "links_to_empty": "This page links to no other page.",+ "link_missing": "This page does not exist yet",+ "facts_title": "About this page",+ "fact_kind": "Kind",+ "fact_folder": "Folder",+ "fact_words": "Words",+ "fact_changed": "Changed",+ "legend_label": "Page kinds on the map",+ "legend_show": "Show on the map",+ "legend_hide": "Hide from the map",+ "legend_connections": "{0} connections",+ "map_hint": "Scroll to zoom · drag to move · double-click to recenter",+ "map_all_hidden": "Every page kind is hidden. Turn one back on in the legend.",+ "crumb_label": "Location in the vault",+ "page_changed": "Changed {0}",+ "page_words": "{0} words",+ "as_of": "As of",+ "search_placeholder": "Search memory",+ "subtitle_pages": "{0} pages",+ "subtitle_links": "{0} links",+ "subtitle_curated": "curated {0}",+ "stage_label": "Memory map and page",+ "tab_map": "Memory map",+ "close_page": "Close page"+ },"skill_create_dialog": {"title": "Create skill","subtitle": "Describe what the skill should do — draft it with AI or fill the form yourself.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex c9c8be79b8..3be782d896 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4161,6 +4161,59 @@"backlog_count": "Retraso del journal: {0}","legacy_conflict": "Conflicto con la bóveda heredada detectado"},+ "wiki_ui": {+ "title": "Wiki",+ "library_label": "Páginas de la wiki",+ "filter_placeholder": "Filtrar páginas",+ "filter_clear": "Borrar filtro",+ "filter_no_match": "Ningún título coincide. Pulsa Ctrl K para buscar dentro de las páginas.",+ "recent": "Cambiadas recientemente",+ "group_entity": "Personas y cosas",+ "group_project": "Proyectos",+ "group_concept": "Conceptos",+ "group_session": "Sesiones",+ "group_agent": "Cuadernos de agentes",+ "group_system": "Páginas del sistema",+ "group_other": "Otras",+ "inspector_label": "Detalles de la página y estado de la memoria",+ "health_title": "Estado de la memoria",+ "health_green": "Todo en orden",+ "health_amber": "Requiere atención",+ "health_red": "No funciona",+ "health_unknown": "Aún sin comprobar",+ "health_chip_title": "Mostrar el estado de la memoria",+ "capture_title": "Capturado de conversaciones",+ "capture_window": "últimas {0} h",+ "capture_quiet": "No se capturó nada en este periodo.",+ "hubs_title": "Más conectadas",+ "linked_from": "Enlazada desde",+ "linked_from_empty": "Ninguna otra página enlaza aquí todavía.",+ "links_to": "Enlaza a",+ "links_to_empty": "Esta página no enlaza a ninguna otra.",+ "link_missing": "Esta página aún no existe",+ "facts_title": "Sobre esta página",+ "fact_kind": "Tipo",+ "fact_folder": "Carpeta",+ "fact_words": "Palabras",+ "fact_changed": "Cambiada",+ "legend_label": "Tipos de página en el mapa",+ "legend_show": "Mostrar en el mapa",+ "legend_hide": "Ocultar del mapa",+ "legend_connections": "{0} conexiones",+ "map_hint": "Desplaza para hacer zoom · arrastra para mover · doble clic para centrar",+ "map_all_hidden": "Todos los tipos de página están ocultos. Vuelve a activar uno en la leyenda.",+ "crumb_label": "Ubicación en el vault",+ "page_changed": "Cambiada {0}",+ "page_words": "{0} palabras",+ "as_of": "A fecha de",+ "search_placeholder": "Buscar en la memoria",+ "subtitle_pages": "{0} páginas",+ "subtitle_links": "{0} enlaces",+ "subtitle_curated": "curada {0}",+ "stage_label": "Mapa de memoria y página",+ "tab_map": "Mapa de memoria",+ "close_page": "Cerrar página"+ },"skill_create_dialog": {"title": "Crear habilidad","subtitle": "Describe qué debe hacer la habilidad: créala con IA o rellena el formulario tú mismo.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 1929aaa07a..252a9e092e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -4163,6 +4163,59 @@"backlog_count": "日志积压:{0}","legacy_conflict": "检测到旧版资料库冲突"},+ "wiki_ui": {+ "title": "Wiki",+ "library_label": "Wiki 页面",+ "filter_placeholder": "筛选页面",+ "filter_clear": "清除筛选",+ "filter_no_match": "没有匹配的页面标题。按 Ctrl K 搜索页面内容。",+ "recent": "最近更改",+ "group_entity": "人物与事物",+ "group_project": "项目",+ "group_concept": "概念",+ "group_session": "会话",+ "group_agent": "智能体笔记",+ "group_system": "系统页面",+ "group_other": "其他",+ "inspector_label": "页面详情与记忆状态",+ "health_title": "记忆状态",+ "health_green": "运行正常",+ "health_amber": "需要关注",+ "health_red": "无法工作",+ "health_unknown": "尚未检查",+ "health_chip_title": "显示记忆状态",+ "capture_title": "从对话中捕获",+ "capture_window": "最近 {0} 小时",+ "capture_quiet": "此时间段内没有捕获任何内容。",+ "hubs_title": "连接最多",+ "linked_from": "被以下页面链接",+ "linked_from_empty": "还没有其他页面链接到这里。",+ "links_to": "链接到",+ "links_to_empty": "此页面没有链接到其他页面。",+ "link_missing": "此页面尚不存在",+ "facts_title": "关于此页面",+ "fact_kind": "类型",+ "fact_folder": "文件夹",+ "fact_words": "字数",+ "fact_changed": "更改于",+ "legend_label": "地图上的页面类型",+ "legend_show": "在地图上显示",+ "legend_hide": "从地图上隐藏",+ "legend_connections": "{0} 个连接",+ "map_hint": "滚动缩放 · 拖动移动 · 双击居中",+ "map_all_hidden": "所有页面类型都已隐藏。请在图例中重新打开一种。",+ "crumb_label": "在库中的位置",+ "page_changed": "更改于 {0}",+ "page_words": "{0} 字",+ "as_of": "截至",+ "search_placeholder": "搜索记忆",+ "subtitle_pages": "{0} 个页面",+ "subtitle_links": "{0} 个链接",+ "subtitle_curated": "整理于 {0}",+ "stage_label": "记忆地图与页面",+ "tab_map": "记忆地图",+ "close_page": "关闭页面"+ },"skill_create_dialog": {"title": "创建技能","subtitle": "描述这个技能要做什么——用 AI 起草,或自己填写表单。",diff --git a/jarvis/ui/web/frontend/src/lib/wikiModel.ts b/jarvis/ui/web/frontend/src/lib/wikiModel.tsnew file mode 100644index 0000000000..5f5fe6d777--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/wikiModel.ts@@ -0,0 +1,331 @@+// 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(/^["'“‘]+|["'”’]+$/g, "").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(/[̀-ͯ]/g, "")+ .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";+}diff --git a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.test.tsxindex 1e63aa667e..278aa993b9 100644--- a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx@@ -6,7 +6,7 @@* client-side projection of that contract.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { WikiView } from "@/views/WikiView";@@ -213,20 +213,34 @@ describe("WikiView — populated tree", () => {expect(screen.getByTestId("wiki-tree-sidebar")).toBeDefined();});- // Three populated leaves are visible because entities and projects open- // by default (per mockup contract).+ // People and projects open by default, listed by title, not file name.await waitFor(() => {- expect(screen.getByText("example-user.md")).toBeDefined();- expect(screen.getByText("example-parent.md")).toBeDefined();- expect(screen.getByText("pixel-art-editor.md")).toBeDefined();+ 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();});- // Concepts folder shows count "0".- const conceptsButton = document.querySelector(- "[data-folder='concepts']",- );- expect(conceptsButton).not.toBeNull();- expect(conceptsButton!.textContent).toContain("0");+ // 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 () => {@@ -266,11 +280,8 @@ describe("WikiView — populated tree", () => {it("clicking a leaf in the tree switches to the page tab and loads the page", async () => {renderWithClient(<WikiView />);- await waitFor(() => {- expect(screen.getByText("example-parent.md")).toBeDefined();- });-- fireEvent.click(screen.getByText("example-parent.md"));+ const entities = await screen.findByTestId("wiki-folder-entity");+ fireEvent.click(within(entities).getByText("Example Parent"));await waitFor(() => {expect(screen.getByTestId("wiki-page-renderer")).toBeDefined();@@ -281,9 +292,10 @@ describe("WikiView — populated tree", () => {it("clicking the already-selected graph node returns to its page", async () => {renderWithClient(<WikiView />);- fireEvent.click(await screen.findByText("example-parent.md"));+ const entities = await screen.findByTestId("wiki-folder-entity");+ fireEvent.click(within(entities).getByText("Example Parent"));await screen.findByTestId("wiki-page-renderer");- fireEvent.click(screen.getByRole("button", { name: "Memory Map" }));+ fireEvent.click(screen.getByTestId("wiki-tab-graph"));fireEvent.click(await screen.findByRole("button", {name: "Example Parent graph node",}));@@ -394,7 +406,7 @@ describe("WikiView — health strip", () => {screen.getByTestId("wiki-health-dot").getAttribute("data-visual"),).toBe("green");expect(screen.getByTestId("wiki-capture-funnel").textContent).toContain(- "Last 24h capture",+ "last 24 h",);expect(screen.getByTestId("wiki-capture-reviewed").textContent).toContain("107");expect(screen.getByTestId("wiki-capture-candidate-reviews").textContent).toContain(diff --git a/jarvis/ui/web/frontend/src/views/WikiView.tsx b/jarvis/ui/web/frontend/src/views/WikiView.tsxindex f90acfb8fc..e8c5bbe7da 100644--- a/jarvis/ui/web/frontend/src/views/WikiView.tsx+++ b/jarvis/ui/web/frontend/src/views/WikiView.tsx@@ -1,52 +1,53 @@/**- * Desktop view of the on-disk Obsidian vault.+ * The Wiki section: the assistant's long-term memory, as the Obsidian vault+ * on disk holds it.*- * Read-only — writes happen via the WikiCurator (B1) or the user editing- * Markdown files in Obsidian. This component is a pure projection of- * `wiki/obsidian-vault/` exposed through Agent A's `/api/wiki/*` endpoints.+ * 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.*- * Layout (matches docs/plans/b3/00-OVERVIEW.md §4.1):- * ┌──────────┬──────────────────┬────────────┐- * │ tree │ graph | page │ backlinks │- * │ (260 px) │ (centre tabs) │ (380 px) │- * └──────────┴──────────────────┴────────────┘+ * One viewport, three regions, nothing below the fold:*- * Replaces the legacy `MemoryView` (`data/core_memory.json` flat memory).+ * ┌───────────┬──────────────────────────────┬────────────┐+ * │ library │ stage: memory map | page │ inspector │+ * │ 272 px │ (fills the rest) │ 320 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, useState } from "react";-import {- FileText,- Maximize2,- Minimize2,- Network,- Notebook,- RefreshCw,-} from "lucide-react";+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 { ViewHeader } from "@/views/ChatsView";import { cn } from "@/lib/utils";-import { useT } from "@/i18n";+import { useT, useUiLanguage } from "@/i18n";import { useEventStore } from "@/store/events";import {fetchWikiHealth,fetchWikiTree,rebuildWikiIndex,- type WikiCaptureFunnel,- type WikiHealthSnapshot,} from "@/lib/wikiApi";+import { cleanTitle, libraryItems, relativeAge, type LibraryItem } from "@/lib/wikiModel";import { useWikiLive } from "@/hooks/useWikiLive";-import { TreeSidebar } from "@/components/wiki/TreeSidebar";+import { EmptyState } from "@/components/ui/empty-state";+import { WikiLibrary } from "@/components/wiki/WikiLibrary";import { PageRenderer } from "@/components/wiki/PageRenderer";-import { BacklinksPanel } from "@/components/wiki/BacklinksPanel";+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";-// Agent C owns WikiGraph. Lazy import so the graph bundle (~120 KB minified)-// only loads when the Wiki tab is mounted. A placeholder file ships in this-// branch — Agent C's real implementation will replace it during Wave 2.+// 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,@@ -60,8 +61,12 @@ interface WikiToast {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 = useUiLanguage();useWikiLive();const [selectedSlug, setSelectedSlug] = useState<string | null>(null);const [centreTab, setCentreTab] = useState<CentreTab>("graph");@@ -74,17 +79,16 @@ export function WikiView(): JSX.Element {const [dialogOpen, setDialogOpen] = useState(false);const [isReindexing, setIsReindexing] = useState(false);const [reindexError, setReindexError] = useState<string | null>(null);+ const searchRef = useRef<WikiSearchHandle>(null);// A staged "open this page" request from another section (e.g. the Contacts- // detail's wiki link). Same consumption idiom as the Visualization stage:- // `seq` bumps on every request, so re-opening the same slug still fires.+ // 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]);- // Tree query lives both here (for header stats + empty-state detection)- // and inside TreeSidebar (for the list). React Query dedupes them.const treeQuery = useQuery({queryKey: ["wiki", "tree"],queryFn: fetchWikiTree,@@ -94,9 +98,16 @@ export function WikiView(): JSX.Element {const stats = treeQuery.data?.stats;const totalPages = stats?.total_pages ?? 0;const totalLinks = stats?.total_links ?? 0;-- // Wiki subsystem health (spec A5): polled on mount + every 30 s so the- // "honest, not silent" status strip stays live without a manual refresh.+ 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,@@ -104,8 +115,7 @@ export function WikiView(): JSX.Element {staleTime: 5_000,});- // When a slug is selected (via tree click, graph click, or wikilink),- // automatically swap to the page tab.+ // Selecting a page (tree, graph, wikilink, search) swaps to the page tab.useEffect(() => {if (selectedSlug) {setCentreTab("page");@@ -114,8 +124,7 @@ export function WikiView(): JSX.Element {}, [selectedSlug]);// Escape leaves the full-window map. With the nav rail covered it is the- // reflex people reach for first, and the Restore button in the tab bar is- // the only other way out.+ // reflex people reach for first.useEffect(() => {if (!isGraphExpanded) return;const onKey = (event: KeyboardEvent) => {@@ -125,11 +134,9 @@ export function WikiView(): JSX.Element {return () => window.removeEventListener("keydown", onKey);}, [isGraphExpanded]);- // On the first visit to the Wiki tab, auto-open the Obsidian setup- // walkthrough — but only if the user has never marked it as completed- // AND the current status says action is required.- // Both requests run in parallel; AbortController cancels them if the- // component unmounts before the network round trip finishes.+ // 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;@@ -146,16 +153,13 @@ export function WikiView(): JSX.Element {const state = (await stateResp.json()) as { obsidian_setup_seen: boolean };if (cancelled) return;- if (- state.obsidian_setup_seen === false &&- status.recommended_action !== "ok"- ) {+ if (state.obsidian_setup_seen === false && status.recommended_action !== "ok") {setSetupHint(status);setDialogOpen(true);}} catch (err) {- // AbortError is expected on unmount; everything else we silently- // swallow — the status pill still gives the user a manual entry.+ // 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);}@@ -186,25 +190,16 @@ export function WikiView(): JSX.Element {}await Promise.all([healthQuery.refetch(), treeQuery.refetch()]);} catch (error) {- setReindexError(- error instanceof Error ? error.message : t("wiki_health.reindex_failed"),- );+ setReindexError(error instanceof Error ? error.message : t("wiki_health.reindex_failed"));showToast(t("wiki_health.reindex_failed"));} finally {setIsReindexing(false);}}, [healthQuery, showToast, t, treeQuery]);- // Build the known-slug set lazily here too, so we can validate a wikilink- // click before changing the URL. Single source of truth: the tree response.- const knownSlugs = useMemo(- () => collectSlugs(treeQuery.data?.folders ?? []),- [treeQuery.data?.folders],- );-const handleSelect = useCallback((slug: string) => {- if (knownSlugs.size > 0 && !knownSlugs.has(slug)) {+ if (itemsBySlug.size > 0 && !itemsBySlug.has(slug)) {showToast(t("wiki_view.page_not_found"));return;}@@ -214,45 +209,81 @@ export function WikiView(): JSX.Element {setCentreTab("page");setSelectedSlug(slug);},- [knownSlugs, showToast, t],+ [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")- : `${totalPages} ${t("wiki_view.pages")} · ${totalLinks} ${t("wiki_view.wikilinks")}`;+ : [+ t("wiki_ui.subtitle_pages").replace("{0}", formatCount(totalPages, language)),+ t("wiki_ui.subtitle_links").replace("{0}", formatCount(totalLinks, language)),+ curated ? t("wiki_ui.subtitle_curated").replace("{0}", curated) : "",+ ]+ .filter(Boolean)+ .join(" · ");++ const selectedTitle = selectedSlug+ ? itemsBySlug.get(selectedSlug)?.title ?? cleanTitle(selectedSlug)+ : "";return (<div className="flex h-full min-h-0 flex-col" data-testid="wiki-view">- <div className="flex items-start justify-between gap-3 pr-6">- <div className="min-w-0 flex-1">- <ViewHeader- icon={<Notebook className="h-4 w-4" />}- title="Wiki · Memory Map"- subtitle={subtitle}- />- </div>- <div className="flex shrink-0 items-center gap-3 pt-4">- <ObsidianStatus- onOpenSetup={(s) => {- setSetupHint(s);- setDialogOpen(true);- }}- />- </div>- </div>-- <WikiHealthStrip- health={healthQuery.data}- isLoading={healthQuery.isLoading}- isReindexing={isReindexing}- reindexError={reindexError}- onReindex={handleReindex}- />- <WikiCaptureFunnelStrip- error={healthQuery.data?.capture_error}- funnel={healthQuery.data?.capture_funnel}+ <ViewHeader+ icon={<BookOpen className="h-4 w-4" />}+ title={t("wiki_ui.title")}+ subtitle={subtitle}+ right={+ <>+ <button+ type="button"+ onClick={() => searchRef.current?.open()}+ data-testid="wiki-search-trigger"+ className="flex h-8 w-60 items-center gap-2 rounded-md border border-border bg-background px-2.5 text-sm text-foreground-faint transition-colors hover:border-border-strong hover:text-muted-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>+ <kbd className="rounded-sm border border-border px-1.5 font-mono text-xs leading-5">+ {IS_MAC ? "⌘K" : "Ctrl K"}+ </kbd>+ </button>+ <button+ type="button"+ onClick={closePage}+ 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>+ <ObsidianStatus+ onOpenSetup={(s) => {+ setSetupHint(s);+ setDialogOpen(true);+ }}+ />+ </>+ }/>{dialogOpen && setupHint && (@@ -262,13 +293,10 @@ export function WikiView(): JSX.Element {initialStatus={setupHint}onComplete={async () => {// Only when the user explicitly confirms that setup worked;- // never on Escape or an outside click. Fire-and-forget — the- // route never returns a 5xx, and a failed mark only means the- // wizard reopens on the next visit.+ // 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",- });+ await fetch("/api/setup/state/obsidian-seen", { method: "POST" });} catch (err) {console.debug("[WikiView] mark-obsidian-seen failed:", err);}@@ -276,78 +304,88 @@ export function WikiView(): JSX.Element {/>)}+ <WikiSearch ref={searchRef} onResultClick={handleSelect} />+{treeQuery.isError ? (- <div className="flex flex-1 items-center justify-center p-6">- <div- role="alert"- className="max-w-reading text-body text-destructive"- data-testid="wiki-tree-error"- >+ <div className="flex flex-1 items-center justify-center border-t border-border p-6">+ <p role="alert" className="max-w-reading text-base text-destructive" data-testid="wiki-tree-error">{t("wiki_view.load_error")}- </div>+ </p></div>) : !treeQuery.isLoading && totalPages === 0 ? (- <EmptyState />+ // 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 overflow-hidden border-t border-border">+ <div className="flex min-w-0 flex-1 items-center justify-center p-6">+ <WikiEmptyState />+ </div>+ <WikiInspector+ selectedSlug={null}+ itemsBySlug={itemsBySlug}+ health={health}+ healthLoading={healthQuery.isLoading}+ isReindexing={isReindexing}+ reindexError={reindexError}+ onReindex={handleReindex}+ onSelect={handleSelect}+ />+ </div>) : (<divid="wiki-workspace"className={cn(- "flex flex-1 min-h-0 overflow-hidden",- // Expanded means the whole window, not "the middle column, but- // wider". The map is the one thing in this app that gets better- // the more room it has, and leaving the nav rail, the header and- // two status strips around it was most of why it never looked- // like anything. Fixed to the viewport, above everything.- isGraphExpanded && "fixed inset-0 z-[100]",+ "flex min-h-0 flex-1 overflow-hidden border-t border-border",+ // Expanded means the whole window: the map is the one thing in+ // this app that gets better the more room it has.+ isGraphExpanded && "fixed inset-0 z-[100] border-t-0 bg-background",)}data-testid="wiki-workspace"data-graph-expanded={isGraphExpanded ? "true" : "false"}>{!isGraphExpanded && (- <TreeSidebar+ <WikiLibrary+ folders={folders}+ isLoading={treeQuery.isLoading}+ isError={treeQuery.isError}selectedSlug={selectedSlug}onSelect={handleSelect}/>)}- <section className="flex flex-1 min-w-0 flex-col">- <div className="flex items-stretch border-b border-border">- <TabButton+ <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">+ <StageTabactive={centreTab === "graph"}onClick={() => setCentreTab("graph")}- icon={<Network className="h-3.5 w-3.5" />}- label="Memory Map"- />- <TabButton- active={centreTab === "page"}- onClick={() => {- setCentreTab("page");- setIsGraphExpanded(false);- }}- icon={<FileText className="h-3.5 w-3.5" />}- label={- selectedSlug- ? `Page · ${selectedSlug}.md`- : "Page"- }- disabled={!selectedSlug}+ 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")}+ />+ )}{centreTab === "graph" && (<buttontype="button"- className="ml-auto mr-2 my-1.5 inline-flex items-center gap-1.5 self-center rounded-md px-2.5 py-1.5 text-body text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"+ className="ml-auto inline-flex h-8 items-center gap-1.5 self-center 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",+ isGraphExpanded ? "wiki_graph.restore_view_title" : "wiki_graph.expand_view_title",)}title={t(- isGraphExpanded- ? "wiki_graph.restore_view_title"- : "wiki_graph.expand_view_title",+ isGraphExpanded ? "wiki_graph.restore_view_title" : "wiki_graph.expand_view_title",)}data-testid="wiki-graph-expand-toggle">@@ -356,64 +394,46 @@ export function WikiView(): JSX.Element {) : (<Maximize2 className="h-3.5 w-3.5" aria-hidden />)}- <span>- {t(- isGraphExpanded- ? "wiki_graph.restore"- : "wiki_graph.expand",- )}- </span>+ <span>{t(isGraphExpanded ? "wiki_graph.restore" : "wiki_graph.expand")}</span></button>)}</div>- <div className="flex-1 min-h-0 overflow-y-auto">+ <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}- />+ <WikiGraph onNodeClick={handleSelect} highlightSlug={selectedSlug ?? undefined} /></Suspense>)}-- {centreTab === "page" && (- <>- {selectedSlug ? (- <PageRenderer- slug={selectedSlug}- onWikilinkClick={handleSelect}- />- ) : (- <div- className="px-7 py-10 text-center text-body text-muted-foreground"- data-testid="wiki-page-no-selection"- >- {t("wiki_view.no_selection_hint")}- </div>- )}- </>+ {centreTab === "page" && selectedSlug && (+ <PageRenderer key={selectedSlug} slug={selectedSlug} onWikilinkClick={handleSelect} />)}</div></section>- {!isGraphExpanded &&- (selectedSlug ? (- <BacklinksPanel slug={selectedSlug} onSelect={handleSelect} />- ) : (- <aside- className="flex h-full w-[380px] shrink-0 flex-col bg-sidebar p-4"- data-testid="wiki-backlinks-placeholder"- >- <p className="text-body text-muted-foreground">{t("wiki_view.backlinks_hint")}</p>- </aside>- ))}+ {!isGraphExpanded && (+ <WikiInspector+ selectedSlug={selectedSlug}+ itemsBySlug={itemsBySlug}+ health={health}+ healthLoading={healthQuery.isLoading}+ isReindexing={isReindexing}+ reindexError={reindexError}+ onReindex={handleReindex}+ onSelect={handleSelect}+ />+ )}</div>)}{toast && (<div- className="pointer-events-none fixed bottom-12 right-6 z-50 max-w-sm rounded-lg bg-popover px-4 py-3 text-body text-foreground shadow-float"+ 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">@@ -424,389 +444,95 @@ export function WikiView(): JSX.Element {);}-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.-const HEALTH_DOT_STYLE: Record<WikiHealthVisual, string> = {- green: "bg-success",- amber: "bg-warning",- red: "bg-destructive",- unknown: "bg-faint-foreground",-};--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";- }- // At this point `last_write?.ok === false` and `last_chain_failure` are- // both already ruled out by the guard above, so the remaining green- // condition collapses to `bootstrap_ok` alone.- 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");-}--/**- * Compact status strip at the top of the Wiki tab (spec A5). Polled by the- * caller on a timer; this component only renders whatever snapshot it was- * given. "Honest, not silent": a failed bootstrap, a failed write, or a- * growing journal backlog shows up here instead of failing quietly.- */-function WikiHealthStrip({- health,- isLoading,- isReindexing,- reindexError,- onReindex,-}: {- health: WikiHealthSnapshot | null | undefined;- isLoading: boolean;- isReindexing: boolean;- reindexError: string | null;- onReindex: () => void;-}): JSX.Element {- const t = useT();-- if (isLoading) {- return (- <div- className="flex items-center gap-2 border-b border-border px-4 py-2 text-meta text-muted-foreground"- data-testid="wiki-health-strip"- >- <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>- );+function formatCount(value: number, language: string): string {+ try {+ return new Intl.NumberFormat(language).format(value);+ } catch {+ return String(value);}-- if (!health) {- return (- <div- className="flex items-center gap-2 border-b border-border px-4 py-2 text-meta text-muted-foreground"- data-testid="wiki-health-strip"- >- <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>- );- }-- const visual = classifyWikiHealth(health);- const vaultText = health.vault_root- ? t("wiki_health.vault_prefix").replace("{0}", health.vault_root)- : t("wiki_health.vault_unknown");- const writeText = describeWikiWriteStatus(health, t);-- return (- <div- className="flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-4 py-2 text-meta text-muted-foreground"- data-testid="wiki-health-strip"- >- <span- className={cn("h-2 w-2 shrink-0 rounded-full", HEALTH_DOT_STYLE[visual])}- data-testid="wiki-health-dot"- data-visual={visual}- aria-hidden- />- <span data-testid="wiki-health-vault" className="truncate">- {vaultText}- </span>- <span aria-hidden>·</span>- <span- data-testid="wiki-health-write"- className={visual === "red" ? "text-destructive" : undefined}- >- {writeText}- </span>- {health.journal_backlog > 0 && (- <span- data-testid="wiki-health-backlog"- className="rounded-full bg-secondary px-2 py-0.5 text-warning"- >- {t("wiki_health.backlog_count").replace(- "{0}",- String(health.journal_backlog),- )}- </span>- )}- {health.index_state === "stale" && (- <>- <span- data-testid="wiki-health-index-stale"- className="rounded-full bg-secondary px-2 py-0.5 text-warning"- >- {t("wiki_health.index_stale")- .replace("{0}", String(health.indexed_pages))- .replace("{1}", String(health.vault_pages))}- </span>- <button- type="button"- onClick={onReindex}- disabled={isReindexing}- data-testid="wiki-health-reindex"- className="inline-flex items-center gap-1 rounded-md bg-secondary px-2 py-0.5 text-foreground transition-colors hover:bg-popover disabled:opacity-50"- >- <RefreshCw className={cn("h-3 w-3", isReindexing && "animate-spin")} />- {t(isReindexing ? "wiki_health.reindexing" : "wiki_health.reindex")}- </button>- {reindexError && (- <span- role="alert"- data-testid="wiki-health-reindex-error"- className="text-destructive"- >- {t("wiki_health.reindex_failed_detail").replace("{0}", reindexError)}- </span>- )}- </>- )}- {health.vault_legacy_conflict && (- <span- data-testid="wiki-health-legacy-conflict"- className="rounded-full bg-secondary px-2 py-0.5 text-warning"- >- {t("wiki_health.legacy_conflict")}- </span>- )}- </div>- );}-function WikiCaptureFunnelStrip({- error,- funnel,-}: {- error: string | null | undefined;- funnel: WikiCaptureFunnel | undefined;-}): JSX.Element | null {- const t = useT();- if (!funnel) return null;-- const windowHours = Math.max(1, Math.round(funnel.window_hours));- const metrics = [- ["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],- ["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 windowLabel = t("wiki_health.capture_window").replace(- "{0}",- String(windowHours),- );- const errorText =- error === "capture_store_unavailable"- ? t("wiki_health.capture_store_unavailable")- : error- ? t("wiki_health.capture_store_error").replace("{0}", error)- : null;-- return (- <section- aria-label={t("wiki_health.capture_aria").replace("{0}", String(windowHours))}- className="flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-4 py-1.5 text-meta"- data-testid="wiki-capture-funnel"- >- <span className="text-foreground">{windowLabel}</span>- {errorText && (- <span- className="text-destructive"- data-testid="wiki-capture-error"- role="alert"- >- {errorText}- </span>- )}- {!error && funnel.failed > 0 && (- <span- className="text-destructive"- data-testid="wiki-capture-failed-detail"- role="status"- >- {t("wiki_health.capture_failed_detail").replace(- "{0}",- String(funnel.failed),- )}- </span>- )}- <dl className="flex flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground">- {metrics.map(([key, label, value]) => (- <div- className={cn(- "flex items-baseline gap-1",- key === "failed" && value > 0 && "text-destructive",- )}- data-testid={`wiki-capture-${key}`}- key={key}- >- <dt>{label}</dt>- <dd- className={cn(- "tabular-nums",- key === "failed" && value > 0 ? "text-destructive" : "text-foreground",- )}- >- {value}- </dd>- </div>- ))}- </dl>- </section>- );-}--function TabButton({+function StageTab({active,onClick,icon,label,- disabled,+ testId,+ onClose,+ closeLabel,}: {active: boolean;onClick: () => void;- icon: React.ReactNode;+ icon?: React.ReactNode;label: string;- disabled?: boolean;+ testId: string;+ onClose?: () => void;+ closeLabel?: string;}) {return (- <button- type="button"- onClick={onClick}- disabled={disabled}+ <divclassName={cn(- "flex items-center gap-1.5 border-b-2 px-4 py-2.5 text-body transition-colors",- active- ? "border-primary text-foreground-strong"- : "border-transparent text-muted-foreground hover:text-foreground",- disabled && "cursor-not-allowed opacity-50 hover:text-muted-foreground",+ "relative -mb-px flex min-w-0 items-center border-b-2 transition-colors",+ active ? "border-accent" : "border-transparent",)}- data-active={active ? "true" : "false"}- data-testid={`wiki-tab-${label.toLowerCase().replace(/\s+/g, "-")}`}>- {icon}- {label}- </button>+ <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 EmptyState() {+function WikiEmptyState() {const t = useT();const assistantName = useEventStore((s) => s.assistantName);return (- <div className="flex flex-1 items-center justify-center p-6">- <div- className="max-w-form rounded-lg bg-card px-8 py-10 text-center shadow-rim"- data-testid="wiki-empty-state"- >- <Notebook className="mx-auto mb-3 h-8 w-8 text-muted-foreground" />- <h3 className="mb-2 text-page font-semibold text-foreground-strong">- {t("wiki_view.empty_title")}- </h3>- <p className="mb-2 text-reading text-foreground">- {t("wiki_view.empty_body_a")} {assistantName} {t("wiki_view.empty_body_b")}- </p>- <p className="text-reading text-muted-foreground">- {t("wiki_view.manual_a")}{" "}- <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-meta text-foreground">- .md- </code>- {t("wiki_view.manual_b")}{" "}- <code className="rounded-sm bg-secondary px-1 py-0.5 font-mono text-meta text-foreground">- wiki/obsidian-vault/entities/- </code>{" "}- {t("wiki_view.manual_c")}- </p>- </div>+ <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 min-h-[400px] items-center justify-center p-6"- data-testid="wiki-graph-skeleton"- >- <div className="h-full w-full max-w-page animate-pulse rounded-lg bg-sheen/[0.06]" />+ <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>);}--function collectSlugs(- folders: Array<{ files: Array<{ slug: string }> }>,-): Set<string> {- const out = new Set<string>();- for (const folder of folders) {- for (const file of folder.files) {- out.add(file.slug);- }- }- return out;-}