Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(memory-graph): add an owner knowledge graph
Cursor Agent347491027ab5
diff --git a/.env.example b/.env.exampleindex 35fc56cf..30d9f3ab 100644--- a/.env.example+++ b/.env.example@@ -28,6 +28,11 @@ OS_SESSION_SECRET=# where `export …_TOKEN=` lines live — …) are blocked even within# the read roots. Set =1 to lift that denylist (you accept the exposure).# OS_FS_ALLOW_SENSITIVE=1+# Optional markdown vault for the Memory app (/memory, `mso memory-graph`).+# Must sit inside OS_FS_READ_ROOTS. The owner can also type a path in the app.+# ~/vault is on the sensitive-home denylist; use a path such as ~/notes or+# ~/obsidian/vault. Unset scans project knowledge and agent memory only.+# OS_MEMORY_GRAPH_ROOT=# --- Exec safety + audit (optional) ---# Catastrophic shell commands (rm -rf /, mkfs, dd to a block device, fork bomb…)diff --git a/app/api/v1/memory-graph/route.ts b/app/api/v1/memory-graph/route.tsnew file mode 100644index 00000000..e228efb0--- /dev/null+++ b/app/api/v1/memory-graph/route.ts@@ -0,0 +1,22 @@+import { NextRequest, NextResponse } from "next/server";+import { verifyAuth } from "@/lib/agent/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { collectMemoryGraph } from "@/lib/memory-graph/collect";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++export async function GET(req: NextRequest) {+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const context = await getSessionContext();+ if (!context) return NextResponse.json({ error: "unauthorized" }, { status: 401 });+ const root = (req.nextUrl.searchParams.get("root") ?? process.env.OS_MEMORY_GRAPH_ROOT ?? "").trim().slice(0, 500);+ const project = (req.nextUrl.searchParams.get("project") ?? "").trim().slice(0, 200);+ try {+ const graph = await collectMemoryGraph({ root, project, principal: `cli:${context.session.device_id}` });+ return NextResponse.json(graph, { headers: { "Cache-Control": "no-store" } });+ } catch (error) {+ const message = error instanceof Error ? error.message : "memory graph failed";+ return NextResponse.json({ error: message.slice(0, 200) }, { status: 500 });+ }+}diff --git a/bin/mso b/bin/msoindex 3eba1e5d..18e79f05 100755--- a/bin/mso+++ b/bin/mso@@ -74,6 +74,7 @@# org * Organization chart: units, seats, reporting lines, targets# a2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoff# memory * Assistant memories: list | add | rm+# memory-graph [project] Knowledge graph: vault notes, project memory, agent memory# config * Advanced raw AI config compatibility surface# prefs * UI preferences: show | set# federation * Batonly capability federation worker: statusdiff --git a/bin/mso.test.ts b/bin/mso.test.tsindex 5a323b3e..d7171282 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -57,6 +57,10 @@ describe("bin/mso", () => {expect(undocumented).toEqual([]);});+ it("prints memory-graph usage instead of the assistant memory verb", () => {+ expect(run("memory-graph", "--help")).toContain("memory-graph [project]");+ });+it("exits non-zero on an unknown command", () => {expect(() => run("definitely-not-a-verb")).toThrow();});diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 9720f30a..672938aa 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -347,3 +347,7 @@ MSO has a Workflow Graph v2 layer above the existing automation/lifecycle/RASMICTelegram and Discord credentials remain under `lib/infra/*`. Telegram inbound requests require the configured Bot API webhook secret; Discord inbound requests require Ed25519-signed Interactions. Discord Gateway message ingestion is not part of the current capability.Inbound channel events may dispatch into the existing Workflow Graph engine through the `channel_trigger` node. Outbound automation uses `channel_send`, which calls the same Channels send service as the UI/API. This keeps Channels, Integrations, and Workflows as separate authorities without copying credentials or building a second automation engine. See [CHANNELS.md](./CHANNELS.md).++## Memory graph++`frontend/slices/memory-graph/` is the owner-only Memory app at `/memory` (`mso memory-graph`). It draws vault markdown, project `.mso/KNOWLEDGE.md`, repo-local `.agent` memory, the signed-in device's typed agent memory, and assistant memories. Unresolved `[[wikilinks]]` are ghost nodes. Web, radial, and layered layouts plus a local hop neighbourhood are client-side. This surface is inspired by open-silong's memory graph (MIT) and does not depend on Obsidian or Convex. It is not the Workflow session graph. See [`MEMORY-GRAPH.md`](./MEMORY-GRAPH.md).diff --git a/docs/CLI.md b/docs/CLI.mdindex 5bc1abe0..e1e75a56 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -114,6 +114,7 @@ Commands:org * Organization chart: units, seats, reporting lines, targetsa2a * Agent-to-Agent v1: list | discover | add | rm | send | task | cancel | handoffmemory * Assistant memories: list | add | rm+ memory-graph [project] Knowledge graph: vault notes, project memory, agent memoryconfig * Advanced raw AI config compatibility surfaceprefs * UI preferences: show | setfederation * Batonly capability federation worker: statusdiff --git a/docs/MEMORY-GRAPH.md b/docs/MEMORY-GRAPH.mdnew file mode 100644index 00000000..7a88b026--- /dev/null+++ b/docs/MEMORY-GRAPH.md@@ -0,0 +1,34 @@+# Memory graph++Owner-only knowledge graph inside the MSO shell. Open it from Launchpad or Spotlight as **Memory**, at `/memory`, or with `mso memory-graph [project]`.++The graph is built on the server by `GET /api/v1/memory-graph` and rendered in the browser. It does not use Convex, and it does not require Obsidian. Layout ideas — web (force), radial rings, layered hop columns, a local neighbourhood, ghost nodes for unresolved `[[wikilinks]]`, and folder/group color — follow [open-silong](https://github.com/rahmanef63/open-silong) `frontend/slices/memory-graph` (MIT). The implementation is MSO-native.++This is separate from the Workflow session graph.++## What becomes a node++- Markdown notes under an optional vault directory. Set `OS_MEMORY_GRAPH_ROOT`, or type a path in the app. The path must pass the normal read-root jail. `~/vault` is on the sensitive-home denylist; `~/notes` or `~/obsidian/vault` are usable when they sit inside `OS_FS_READ_ROOTS`.+- `.mso/KNOWLEDGE.md` and a bounded set of repo-local `.agent` memory records for a named project. With no vault and no project, the scan includes up to four discovered projects.+- Typed agent memory for the signed-in device (`cli:<device id>`, the same principal Alfa Cockpit uses). Private and restricted claims show as “Private memory”.+- Assistant memories from the owner memory store.++`[[Title]]` links resolve to a note with that title or path. Anything unresolved is a ghost. Relative `.md` links become edges when the target file is in the graph. Folder hubs connect two or more notes in the same top-level folder.++## Using the view++- **Web**, **Radial**, and **Layered** rearrange the same nodes.+- **Local** keeps the selected node and its neighbourhood. Hops are 1–4. With nothing selected, the highest-degree node is the centre.+- **Ghosts**, **Tags**, and **Orphans** toggle those nodes. Group chips hide a color group.+- Click a node to select it. Click it again, double-click it, or press **Open** to open a note that has a file path in Code.+- Drag the background to pan. Scroll to zoom.++The scan is capped (notes, depth, directories, project records) and may report that it truncated. Excerpts are redacted for obvious secrets. The route is owner-only; Viewer and Operator are refused.++## Deploy++Merging to `main` does not rebuild a running MSO service. On the host, update with:++```bash+mso update+```diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 0b52f6f4..1ca1cc1d 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,7 @@+## 2026-09-24 — Add a first-class Memory graph++MSO now has a Memory app (`/memory`, Launchpad and Spotlight “Memory”, CLI `mso memory-graph`) for a navigable knowledge graph. The owner-only `GET /api/v1/memory-graph` builds it from an optional markdown vault (`OS_MEMORY_GRAPH_ROOT` or a path typed in the app, jailed to `OS_FS_READ_ROOTS`), project `.mso/KNOWLEDGE.md`, bounded repo-local `.agent` memory, the signed-in device’s typed agent memory, and assistant memories. Unresolved `[[wikilinks]]` become ghost nodes; folders and projects color groups. The client offers web, radial, and layered layouts plus a local hop neighbourhood, and opens a note in Code on a second click, double-click, or Open. Layout ideas follow open-silong’s memory graph (MIT). This is not the Workflow session graph and does not require Obsidian. Production picks it up with `mso update` after the commit is on `origin/main`; a GitHub merge does not rebuild the systemd service by itself.+## 2026-09-24 — Integrations Variables + native AI Providers tabIntegrations now has metadata-only variables that alias an exact named connection without copying credentials. variable.set / variable.delete are part of the existing integration_manage authority, integration_query view=variables exposes only safe references, rename/delete invariants prevent stale aliases, and an existing pre-variable mcp/jev connection can project a JEV alias without hardcoding a user. Workflow Optimizer Jev mode resolves JEV by default while preserving an explicit diagnostic override; endpoint/token remain private in Integrations.diff --git a/docs/README.md b/docs/README.mdindex 7f97b09d..23676839 100644--- a/docs/README.md+++ b/docs/README.md@@ -25,6 +25,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`COGNITIVE-RUNTIME.md`](./COGNITIVE-RUNTIME.md) | Provider-neutral MCP/session/context/tool-routing runtime and benchmark contract || [`AGENT-BOOTSTRAP.md`](./AGENT-BOOTSTRAP.md) | Canonical first-call sequence and capability-parity matrix across CLI, MCP, and Alfa || [`RASMIC.md`](./RASMIC.md) | Risk-aware orchestration, repo-local memory/evidence, collision detection and recipe/script promotion |+| [`MEMORY-GRAPH.md`](./MEMORY-GRAPH.md) | Owner Memory app: vault notes, project knowledge, agent memory, layouts and limits || [`COMPARISON.md`](./COMPARISON.md) | Generated product comparison methodology, evidence and notes || [`COMPETITIVE-ROADMAP.md`](./COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate specialist boundaries and next investments || [`INSTALL.md`](./INSTALL.md) | Owner installation, TLS, updates, backup and uninstall |diff --git a/docs/SHARED-GRAPH-FOUNDATION.md b/docs/SHARED-GRAPH-FOUNDATION.mdindex a6c989ca..23b5da42 100644--- a/docs/SHARED-GRAPH-FOUNDATION.md+++ b/docs/SHARED-GRAPH-FOUNDATION.md@@ -22,6 +22,7 @@ This document records the current ownership boundary for first-party MSO graph U| Organization persistence | Organization API/actions | owner | — | — | B feature-owned || Workflow persistence / execution / run state | Workflow API/runtime | — | owner | read-only history input | B feature-owned || Session artifacts / terminal / save-as-workflow | `workflow-session-details.tsx` + session APIs | — | — | owner | B feature-owned |+| Memory graph (notes, knowledge, agent memory) | `frontend/slices/memory-graph/` | — | — | — | B feature-owned. Separate from the workflow canvas. || n8n iframe/auth/origin/sandbox | `frontend/slices/n8n/**` | — | — | — | C provider-specific || Legacy Organization projection helper | removed; superseded by shared projection | — | — | — | D obsolete |diff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.mdindex 1c785105..8434daca 100644--- a/docs/SLICE-CATALOG.md+++ b/docs/SLICE-CATALOG.md@@ -3,12 +3,12 @@> **Current reference.** Counts are checked against the directory tree by> `scripts/check-docs.mjs`; the directory remains the final authority.-<!-- slice-catalog: slices=28 appshell-features=10 -->+<!-- slice-catalog: slices=29 appshell-features=10 -->Every application is a vertical slice under `frontend/slices/`. Host-facing slices use theshared API/host seam rather than reaching arbitrary Node host APIs from client code.-## Slices (28)+## Slices (29)| Slug | Purpose ||---|---|@@ -31,6 +31,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c| `n8n` | Dedicated reviewed n8n workspace, isolated from native Workflows and MSO credentials || `media-studio` | Image/media studio surface || `media-viewer` | Preview/Quick Look-style media viewer |+| `memory-graph` | Interactive knowledge and memory graph (vault notes, project knowledge, agent memory) || `os-settings` | MSO Settings || `os-shell` | MSO consumer manifest/capabilities for AppShell || `os-terminal` | Interactive PTY Terminal / Claude Code surface |diff --git a/frontend/slices/memory-graph/app.tsx b/frontend/slices/memory-graph/app.tsxnew file mode 100644index 00000000..6e879a2e--- /dev/null+++ b/frontend/slices/memory-graph/app.tsx@@ -0,0 +1,13 @@+"use client";++import type { AppProps } from "@/features/appshell";+import { AppFrame } from "@/features/appshell";+import { MemoryGraphScreen } from "./components/memory-graph-screen";++export default function MemoryGraphApp(_props: AppProps) {+ return (+ <AppFrame safeArea={false} className="h-full bg-background" bodyClassName="overflow-hidden">+ <MemoryGraphScreen />+ </AppFrame>+ );+}diff --git a/frontend/slices/memory-graph/components/graph-canvas.tsx b/frontend/slices/memory-graph/components/graph-canvas.tsxnew file mode 100644index 00000000..d4454b54--- /dev/null+++ b/frontend/slices/memory-graph/components/graph-canvas.tsx@@ -0,0 +1,95 @@+"use client";++import { useMemo, useRef, useState } from "react";+import type { MemoryGraphEdge, MemoryGraphNode } from "@/lib/memory-graph/types";+import { groupColor, placeNodes, type GraphLayoutName } from "../lib/layout";++export function GraphCanvas({+ nodes, edges, layout, selected, onSelect, onOpen,+}: {+ nodes: MemoryGraphNode[];+ edges: MemoryGraphEdge[];+ layout: GraphLayoutName;+ selected: string | null;+ onSelect: (id: string) => void;+ onOpen: (node: MemoryGraphNode) => void;+}) {+ const points = useMemo(() => placeNodes(nodes, edges, layout), [nodes, edges, layout]);+ const groups = useMemo(() => [...new Set(nodes.map((node) => node.group))], [nodes]);+ const bounds = useMemo(() => {+ const values = [...points.values()];+ if (!values.length) return { x: 0, y: 0, w: 200, h: 200 };+ const xs = values.map((point) => point.x), ys = values.map((point) => point.y);+ const minX = Math.min(...xs) - 80, minY = Math.min(...ys) - 60;+ return { x: minX, y: minY, w: Math.max(...xs) - minX + 160, h: Math.max(...ys) - minY + 140 };+ }, [points]);+ return (+ <GraphStage key={`${layout}:${nodes.map((node) => node.id).join("\n")}`} bounds={bounds} points={points} groups={groups} nodes={nodes} edges={edges} selected={selected} onSelect={onSelect} onOpen={onOpen} />+ );+}++function GraphStage({+ bounds, points, groups, nodes, edges, selected, onSelect, onOpen,+}: {+ bounds: { x: number; y: number; w: number; h: number };+ points: Map<string, { x: number; y: number }>;+ groups: string[];+ nodes: MemoryGraphNode[];+ edges: MemoryGraphEdge[];+ selected: string | null;+ onSelect: (id: string) => void;+ onOpen: (node: MemoryGraphNode) => void;+}) {+ const [view, setView] = useState(bounds);+ const drag = useRef<{ x: number; y: number; vx: number; vy: number } | null>(null);+ return (+ <svg+ className="h-full w-full touch-none bg-background"+ viewBox={`${view.x} ${view.y} ${view.w} ${view.h}`}+ role="application"+ aria-label="Memory graph"+ onPointerDown={(event) => {+ if (event.target !== event.currentTarget) return;+ drag.current = { x: event.clientX, y: event.clientY, vx: view.x, vy: view.y };+ event.currentTarget.setPointerCapture(event.pointerId);+ }}+ onPointerMove={(event) => {+ if (!drag.current) return;+ const rect = event.currentTarget.getBoundingClientRect();+ const scale = view.w / Math.max(rect.width, 1);+ setView((current) => ({ ...current, x: drag.current!.vx - (event.clientX - drag.current!.x) * scale, y: drag.current!.vy - (event.clientY - drag.current!.y) * scale }));+ }}+ onPointerUp={() => { drag.current = null; }}+ onWheel={(event) => {+ event.preventDefault();+ const factor = event.deltaY > 0 ? 1.08 : 0.92;+ setView((current) => ({ ...current, w: current.w * factor, h: current.h * factor }));+ }}+ >+ {edges.map((edge) => {+ const source = points.get(edge.source), target = points.get(edge.target);+ if (!source || !target) return null;+ return <line key={`${edge.kind}:${edge.source}:${edge.target}`} x1={source.x} y1={source.y} x2={target.x} y2={target.y} stroke="var(--muted-foreground)" strokeOpacity={edge.resolved ? 0.55 : 0.35} strokeDasharray={edge.resolved ? undefined : "4 3"} />;+ })}+ {nodes.map((node) => {+ const point = points.get(node.id);+ if (!point) return null;+ const radius = node.kind === "folder" ? 16 : 8 + Math.min(node.degree, 8) * 1.6;+ const fill = node.kind === "ghost" ? "var(--muted-foreground)" : groupColor(node.group, groups);+ return (+ <g key={node.id} transform={`translate(${point.x} ${point.y})`} role="button" tabIndex={0}+ aria-pressed={selected === node.id} aria-label={node.title}+ onClick={() => onSelect(node.id)}+ onDoubleClick={() => onOpen(node)}+ onKeyDown={(event) => { if (event.key === "Enter") onOpen(node); }}+ >+ {node.kind === "folder"+ ? <rect x={-radius} y={-radius} width={radius * 2} height={radius * 2} rx={4} fill={fill} stroke={selected === node.id ? "var(--accent)" : "transparent"} strokeWidth={3} />+ : <circle r={radius} fill={fill} fillOpacity={node.kind === "ghost" ? 0.35 : 0.9} stroke={selected === node.id ? "var(--accent)" : node.kind === "ghost" ? "var(--muted-foreground)" : "transparent"} strokeDasharray={node.kind === "ghost" ? "3 2" : undefined} strokeWidth={selected === node.id ? 3 : 1.5} />}+ <text y={radius + 14} textAnchor="middle" fill="var(--foreground)" fontSize={11}>{node.title.slice(0, 28)}</text>+ </g>+ );+ })}+ </svg>+ );+}diff --git a/frontend/slices/memory-graph/components/graph-inspector.tsx b/frontend/slices/memory-graph/components/graph-inspector.tsxnew file mode 100644index 00000000..f4ac30ff--- /dev/null+++ b/frontend/slices/memory-graph/components/graph-inspector.tsx@@ -0,0 +1,19 @@+"use client";++import { Button } from "@/components/ui/button";+import type { MemoryGraphNode } from "@/lib/memory-graph/types";++export function GraphInspector({ node, onOpen }: { node: MemoryGraphNode | null; onOpen: (node: MemoryGraphNode) => void }) {+ if (!node) {+ return <aside className="p-3 text-xs text-muted-foreground">Select a node. Double-click a note to open it.</aside>;+ }+ return (+ <aside className="flex flex-col gap-2 overflow-auto p-3">+ <h2 className="text-sm font-medium">{node.title}</h2>+ <p className="text-xs text-muted-foreground">{node.kind} · {node.group} · {node.degree} links</p>+ {node.kind === "ghost" ? <p className="text-xs">Unresolved wikilink. No note in this graph uses that title.</p> : null}+ {node.excerpt ? <p className="text-xs leading-relaxed">{node.excerpt}</p> : null}+ {node.path ? <Button size="sm" onClick={() => onOpen(node)}>Open</Button> : null}+ </aside>+ );+}diff --git a/frontend/slices/memory-graph/components/graph-toolbar.tsx b/frontend/slices/memory-graph/components/graph-toolbar.tsxnew file mode 100644index 00000000..6c52bfa2--- /dev/null+++ b/frontend/slices/memory-graph/components/graph-toolbar.tsx@@ -0,0 +1,69 @@+"use client";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { groupColor, type GraphLayoutName } from "../lib/layout";++const LAYOUTS: GraphLayoutName[] = ["web", "radial", "layered"];++export function GraphToolbar({+ root, project, layout, local, depth, showGhosts, showTags, showOrphans, groups, hiddenGroups, busy,+ onRoot, onProject, onLayout, onLocal, onDepth, onGhosts, onTags, onOrphans, onToggleGroup, onReload,+}: {+ root: string;+ project: string;+ layout: GraphLayoutName;+ local: boolean;+ depth: number;+ showGhosts: boolean;+ showTags: boolean;+ showOrphans: boolean;+ groups: string[];+ hiddenGroups: string[];+ busy: boolean;+ onRoot: (value: string) => void;+ onProject: (value: string) => void;+ onLayout: (value: GraphLayoutName) => void;+ onLocal: (value: boolean) => void;+ onDepth: (value: number) => void;+ onGhosts: (value: boolean) => void;+ onTags: (value: boolean) => void;+ onOrphans: (value: boolean) => void;+ onToggleGroup: (group: string) => void;+ onReload: () => void;+}) {+ return (+ <div className="flex flex-wrap items-center gap-2 px-3 py-2">+ <Input aria-label="Vault path" value={root} placeholder="Vault path (optional)" onChange={(event) => onRoot(event.target.value)} className="h-8 w-40 text-xs" />+ <Input aria-label="Project" value={project} placeholder="Project" onChange={(event) => onProject(event.target.value)} className="h-8 w-28 text-xs" />+ <Button size="sm" variant="outline" disabled={busy} onClick={onReload}>Load</Button>+ {LAYOUTS.map((name) => (+ <Button key={name} size="sm" variant={layout === name ? "default" : "outline"} onClick={() => onLayout(name)} className="capitalize">{name}</Button>+ ))}+ <Button size="sm" variant={local ? "default" : "outline"} onClick={() => onLocal(!local)}>Local</Button>+ {local ? (+ <label className="flex items-center gap-1 text-xs text-muted-foreground">+ Hops+ <Input aria-label="Neighbourhood hops" type="number" min={1} max={4} value={depth} onChange={(event) => onDepth(Number(event.target.value) || 1)} className="h-8 w-14 text-xs" />+ </label>+ ) : null}+ <Toggle label="Ghosts" checked={showGhosts} onChange={onGhosts} />+ <Toggle label="Tags" checked={showTags} onChange={onTags} />+ <Toggle label="Orphans" checked={showOrphans} onChange={onOrphans} />+ {groups.slice(0, 12).map((group) => (+ <button key={group} type="button" className="rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground" style={{ borderColor: groupColor(group, groups) }} aria-pressed={!hiddenGroups.includes(group)} onClick={() => onToggleGroup(group)}>+ {group}+ </button>+ ))}+ </div>+ );+}++function Toggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) {+ return (+ <label className="flex items-center gap-1 text-xs text-muted-foreground">+ <input type="checkbox" checked={checked} onChange={(event) => onChange(event.target.checked)} />+ {label}+ </label>+ );+}diff --git a/frontend/slices/memory-graph/components/memory-graph-screen.tsx b/frontend/slices/memory-graph/components/memory-graph-screen.tsxnew file mode 100644index 00000000..4e5f1819--- /dev/null+++ b/frontend/slices/memory-graph/components/memory-graph-screen.tsx@@ -0,0 +1,111 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { openWindow } from "@/features/appshell";+import type { MemoryGraphDocument, MemoryGraphNode } from "@/lib/memory-graph/types";+import { GraphCanvas } from "./graph-canvas";+import { GraphInspector } from "./graph-inspector";+import { GraphToolbar } from "./graph-toolbar";+import type { GraphLayoutName } from "../lib/layout";+import { viewGraph } from "../lib/view-model";++const ROOT_KEY = "mso:memory-graph:root";+const PROJECT_KEY = "mso:memory-graph:project";++function stored(key: string): string {+ if (typeof window === "undefined") return "";+ return localStorage.getItem(key) ?? "";+}++async function loadGraph(root: string, project: string): Promise<MemoryGraphDocument> {+ const params = new URLSearchParams();+ if (root.trim()) params.set("root", root.trim());+ if (project.trim()) params.set("project", project.trim());+ const response = await fetch(`/api/v1/memory-graph?${params}`, { cache: "no-store" });+ const body = await response.json().catch(() => ({}));+ if (!response.ok) throw new Error(typeof body.error === "string" ? body.error : `request failed (${response.status})`);+ return body as MemoryGraphDocument;+}++export function MemoryGraphScreen() {+ const [root, setRoot] = useState(() => stored(ROOT_KEY));+ const [project, setProject] = useState(() => stored(PROJECT_KEY));+ const [applied, setApplied] = useState(() => ({ root: stored(ROOT_KEY), project: stored(PROJECT_KEY), nonce: 0 }));+ const [layout, setLayout] = useState<GraphLayoutName>("web");+ const [local, setLocal] = useState(false);+ const [depth, setDepth] = useState(2);+ const [showGhosts, setShowGhosts] = useState(true);+ const [showTags, setShowTags] = useState(false);+ const [showOrphans, setShowOrphans] = useState(true);+ const [hiddenGroups, setHiddenGroups] = useState<string[]>([]);+ const [query, setQuery] = useState("");+ const [selected, setSelected] = useState<string | null>(null);+ const [result, setResult] = useState<{ key: string; graph: MemoryGraphDocument | null; error: string } | null>(null);+ const requestKey = `${applied.root}\n${applied.project}\n${applied.nonce}`;+ const graph = result?.key === requestKey ? result.graph : null;+ const error = result?.key === requestKey ? result.error : "";+ const busy = result?.key !== requestKey;++ useEffect(() => {+ const key = requestKey;+ let alive = true;+ loadGraph(applied.root, applied.project).then(+ (next) => { if (alive) setResult({ key, graph: next, error: "" }); },+ (cause: unknown) => { if (alive) setResult({ key, graph: null, error: cause instanceof Error ? cause.message : "Could not load the memory graph" }); },+ );+ return () => { alive = false; };+ }, [applied.project, applied.root, requestKey]);++ const visible = useMemo(() => graph ? viewGraph(graph, {+ query, showGhosts, showTags, showOrphans, local, depth: Math.min(4, Math.max(1, depth)), focusId: selected, hiddenGroups,+ }) : null, [graph, query, showGhosts, showTags, showOrphans, local, depth, selected, hiddenGroups]);+ const groups = useMemo(() => [...new Set(graph?.nodes.map((node) => node.group) ?? [])], [graph]);+ const current = visible?.nodes.find((node) => node.id === selected) ?? null;++ const openNode = (node: MemoryGraphNode) => {+ if (!node.path) return;+ openWindow("code-editor", node.title, { w: 860, h: 600 }, { path: node.path });+ };+ const selectNode = (id: string) => {+ if (id === selected) {+ const node = visible?.nodes.find((item) => item.id === id);+ if (node) openNode(node);+ }+ setSelected(id);+ };++ return (+ <div className="flex h-full min-h-0 flex-col">+ <GraphToolbar+ root={root} project={project} layout={layout} local={local} depth={depth}+ showGhosts={showGhosts} showTags={showTags} showOrphans={showOrphans}+ groups={groups} hiddenGroups={hiddenGroups} busy={busy}+ onRoot={setRoot} onProject={setProject} onLayout={setLayout} onLocal={setLocal} onDepth={setDepth}+ onGhosts={setShowGhosts} onTags={setShowTags} onOrphans={setShowOrphans}+ onToggleGroup={(group) => setHiddenGroups((currentGroups) => currentGroups.includes(group) ? currentGroups.filter((item) => item !== group) : [...currentGroups, group])}+ onReload={() => {+ localStorage.setItem(ROOT_KEY, root);+ localStorage.setItem(PROJECT_KEY, project);+ setApplied({ root, project, nonce: applied.nonce + 1 });+ }}+ />+ <div className="flex items-center gap-2 border-b px-3 py-1">+ <input aria-label="Search graph" value={query} placeholder="Search titles" onChange={(event) => setQuery(event.target.value)} className="h-7 w-full bg-transparent text-xs outline-none" />+ <span className="shrink-0 text-[11px] text-muted-foreground">{busy ? "Loading" : `${visible?.nodes.length ?? 0} nodes`}</span>+ </div>+ {error ? <p className="px-3 py-2 text-xs text-destructive">{error}</p> : null}+ {graph?.warnings.length ? <p className="px-3 py-1 text-xs text-muted-foreground">{graph.warnings.join(" · ")}</p> : null}+ {!error && graph && visible && visible.nodes.length === 0 ? (+ <p className="px-3 py-2 text-xs text-muted-foreground">No notes yet. Set a markdown vault inside your read roots, or add project knowledge and agent memory. Optional default: OS_MEMORY_GRAPH_ROOT.</p>+ ) : null}+ <div className="flex min-h-0 flex-1 flex-col @min-[560px]:flex-row">+ <div className="min-h-0 min-w-0 flex-1">+ {visible ? <GraphCanvas nodes={visible.nodes} edges={visible.edges} layout={layout} selected={selected} onSelect={selectNode} onOpen={openNode} /> : null}+ </div>+ <div className="max-h-40 shrink-0 overflow-auto border-t @min-[560px]:max-h-none @min-[560px]:w-64 @min-[560px]:border-t-0 @min-[560px]:border-l">+ <GraphInspector node={current} onOpen={openNode} />+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/slices/memory-graph/index.ts b/frontend/slices/memory-graph/index.tsnew file mode 100644index 00000000..bc19beae--- /dev/null+++ b/frontend/slices/memory-graph/index.ts@@ -0,0 +1,12 @@+import { Waypoints } from "lucide-react";+import type { AppDescriptor } from "@/features/appshell";++// Memory is a first-class shell app. The window bundle stays lazy.+export const memoryGraphApp: AppDescriptor = {+ id: "memory-graph",+ title: "Memory",+ icon: Waypoints,+ gradient: "var(--primary)",+ load: () => import("./app"),+ defaultSize: { w: 1080, h: 720 },+};diff --git a/frontend/slices/memory-graph/lib/layout.ts b/frontend/slices/memory-graph/lib/layout.tsnew file mode 100644index 00000000..062e9d6b--- /dev/null+++ b/frontend/slices/memory-graph/lib/layout.ts@@ -0,0 +1,113 @@+import type { MemoryGraphEdge, MemoryGraphNode } from "@/lib/memory-graph/types";++export type GraphLayoutName = "web" | "radial" | "layered";+export interface Point { x: number; y: number }++function hops(nodes: MemoryGraphNode[], edges: MemoryGraphEdge[]) {+ const adj = new Map<string, string[]>();+ for (const node of nodes) adj.set(node.id, []);+ for (const edge of edges) {+ adj.get(edge.source)?.push(edge.target);+ adj.get(edge.target)?.push(edge.source);+ }+ const pivot = [...nodes].sort((a, b) => b.degree - a.degree || a.id.localeCompare(b.id))[0]?.id ?? null;+ const ring = new Map<string, number>();+ if (pivot) {+ ring.set(pivot, 0);+ const queue = [pivot];+ for (let index = 0; index < queue.length; index++) {+ const nextHop = (ring.get(queue[index]!) ?? 0) + 1;+ for (const neighbor of adj.get(queue[index]!) ?? []) {+ if (ring.has(neighbor)) continue;+ ring.set(neighbor, nextHop);+ queue.push(neighbor);+ }+ }+ }+ let max = 0;+ for (const value of ring.values()) max = Math.max(max, value);+ for (const node of nodes) if (!ring.has(node.id)) ring.set(node.id, max + 1);+ return { pivot, ring };+}++function placeRadial(nodes: MemoryGraphNode[], edges: MemoryGraphEdge[]): Map<string, Point> {+ const { ring } = hops(nodes, edges);+ const buckets = new Map<number, MemoryGraphNode[]>();+ for (const node of [...nodes].sort((a, b) => a.id.localeCompare(b.id))) {+ const hop = ring.get(node.id) ?? 0;+ buckets.set(hop, [...(buckets.get(hop) ?? []), node]);+ }+ const points = new Map<string, Point>();+ for (const [hop, bucket] of buckets) {+ bucket.forEach((node, index) => {+ if (hop === 0) { points.set(node.id, { x: 0, y: 0 }); return; }+ const angle = (Math.PI * 2 * index) / bucket.length - Math.PI / 2;+ points.set(node.id, { x: Math.cos(angle) * hop * 150, y: Math.sin(angle) * hop * 150 });+ });+ }+ return points;+}++function placeLayered(nodes: MemoryGraphNode[], edges: MemoryGraphEdge[]): Map<string, Point> {+ const { ring } = hops(nodes, edges);+ const buckets = new Map<number, MemoryGraphNode[]>();+ for (const node of [...nodes].sort((a, b) => a.id.localeCompare(b.id))) {+ const hop = ring.get(node.id) ?? 0;+ buckets.set(hop, [...(buckets.get(hop) ?? []), node]);+ }+ const points = new Map<string, Point>();+ for (const [hop, bucket] of buckets) {+ bucket.forEach((node, index) => {+ points.set(node.id, { x: hop * 210, y: (index - (bucket.length - 1) / 2) * 68 });+ });+ }+ return points;+}++function placeWeb(nodes: MemoryGraphNode[], edges: MemoryGraphEdge[]): Map<string, Point> {+ const ordered = [...nodes].sort((a, b) => a.id.localeCompare(b.id));+ const pos = ordered.map((node, index) => {+ const angle = (Math.PI * 2 * index) / Math.max(ordered.length, 1);+ const radius = 80 + ordered.length * 4;+ return { id: node.id, x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };+ });+ const indexOf = new Map(pos.map((point, index) => [point.id, index]));+ for (let iter = 0; iter < 60; iter++) {+ for (let i = 0; i < pos.length; i++) {+ for (let j = i + 1; j < pos.length; j++) {+ const a = pos[i]!, b = pos[j]!;+ let dx = a.x - b.x, dy = a.y - b.y;+ let dist = Math.hypot(dx, dy) || 0.01;+ if (dist < 16) { dx = (i - j) || 1; dy = 1; dist = Math.hypot(dx, dy); }+ const force = 900 / (dist * dist);+ const ux = dx / dist, uy = dy / dist;+ a.x += ux * force; a.y += uy * force;+ b.x -= ux * force; b.y -= uy * force;+ }+ }+ for (const edge of edges) {+ const a = pos[indexOf.get(edge.source) ?? -1];+ const b = pos[indexOf.get(edge.target) ?? -1];+ if (!a || !b) continue;+ const dx = b.x - a.x, dy = b.y - a.y;+ const dist = Math.hypot(dx, dy) || 0.01;+ const pull = (dist - 160) * 0.04;+ a.x += (dx / dist) * pull; a.y += (dy / dist) * pull;+ b.x -= (dx / dist) * pull; b.y -= (dy / dist) * pull;+ }+ for (const point of pos) { point.x *= 0.98; point.y *= 0.98; }+ }+ return new Map(pos.map((point) => [point.id, { x: point.x, y: point.y }]));+}++export function placeNodes(nodes: MemoryGraphNode[], edges: MemoryGraphEdge[], layout: GraphLayoutName): Map<string, Point> {+ if (layout === "radial") return placeRadial(nodes, edges);+ if (layout === "layered") return placeLayered(nodes, edges);+ return placeWeb(nodes, edges);+}++export function groupColor(group: string, groups: string[]): string {+ const index = Math.max(0, groups.indexOf(group));+ const mix = 22 + (index % 6) * 12;+ return `color-mix(in srgb, var(--accent) ${mix}%, var(--foreground))`;+}diff --git a/frontend/slices/memory-graph/lib/view-model.ts b/frontend/slices/memory-graph/lib/view-model.tsnew file mode 100644index 00000000..437e5f59--- /dev/null+++ b/frontend/slices/memory-graph/lib/view-model.ts@@ -0,0 +1,56 @@+import { neighbourhood } from "@/lib/memory-graph/assemble";+import type { MemoryGraphDocument, MemoryGraphEdge, MemoryGraphNode } from "@/lib/memory-graph/types";++export interface ViewOptions {+ query: string;+ showGhosts: boolean;+ showTags: boolean;+ showOrphans: boolean;+ local: boolean;+ depth: number;+ focusId: string | null;+ hiddenGroups: string[];+}++function withDegree(nodes: MemoryGraphNode[], edges: MemoryGraphEdge[]): MemoryGraphNode[] {+ const degree = new Map(nodes.map((node) => [node.id, 0]));+ for (const edge of edges) {+ degree.set(edge.source, (degree.get(edge.source) ?? 0) + 1);+ degree.set(edge.target, (degree.get(edge.target) ?? 0) + 1);+ }+ return nodes.map((node) => ({ ...node, degree: degree.get(node.id) ?? 0 }));+}++export function viewGraph(graph: MemoryGraphDocument, options: ViewOptions): MemoryGraphDocument {+ let nodes = graph.nodes.filter((node) => !options.hiddenGroups.includes(node.group));+ if (!options.showGhosts) nodes = nodes.filter((node) => node.kind !== "ghost");+ if (!options.showTags) nodes = nodes.filter((node) => node.kind !== "tag");+ const kept = new Set(nodes.map((node) => node.id));+ let edges = graph.edges.filter((edge) => kept.has(edge.source) && kept.has(edge.target));++ if (options.local && nodes.length) {+ const focus = options.focusId && kept.has(options.focusId)+ ? options.focusId+ : [...nodes].sort((a, b) => b.degree - a.degree || a.id.localeCompare(b.id))[0]!.id;+ const near = neighbourhood(edges, focus, options.depth);+ nodes = nodes.filter((node) => near.has(node.id));+ const ids = new Set(nodes.map((node) => node.id));+ edges = edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target));+ }++ const query = options.query.trim().toLowerCase();+ if (query) {+ nodes = nodes.filter((node) => `${node.title} ${node.group} ${node.excerpt ?? ""}`.toLowerCase().includes(query));+ const ids = new Set(nodes.map((node) => node.id));+ edges = edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target));+ }++ nodes = withDegree(nodes, edges);+ if (!options.showOrphans) {+ nodes = nodes.filter((node) => node.degree > 0 || node.kind === "folder");+ const ids = new Set(nodes.map((node) => node.id));+ edges = edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target));+ nodes = withDegree(nodes, edges);+ }+ return { ...graph, nodes, edges };+}diff --git a/frontend/slices/memory-graph/lib/view.test.ts b/frontend/slices/memory-graph/lib/view.test.tsnew file mode 100644index 00000000..205ab3de--- /dev/null+++ b/frontend/slices/memory-graph/lib/view.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import type { MemoryGraphDocument } from "@/lib/memory-graph/types";+import { placeNodes } from "./layout";+import { viewGraph } from "./view-model";++const graph: MemoryGraphDocument = {+ truncated: false,+ warnings: [],+ root: "/vault",+ counts: { notes: 2, memories: 0, ghosts: 1 },+ nodes: [+ { id: "note:a", title: "Alpha", kind: "note", group: "daily", degree: 2 },+ { id: "note:b", title: "Beta", kind: "note", group: "daily", degree: 1 },+ { id: "ghost:missing", title: "Missing", kind: "ghost", group: "Unresolved", degree: 1 },+ { id: "tag:topic", title: "#topic", kind: "tag", group: "Tags", degree: 1 },+ ],+ edges: [+ { source: "note:a", target: "note:b", kind: "wikilink", resolved: true },+ { source: "note:a", target: "ghost:missing", kind: "wikilink", resolved: false },+ { source: "note:b", target: "tag:topic", kind: "tag", resolved: true },+ ],+};++const base = { query: "", showGhosts: true, showTags: false, showOrphans: true, local: false, depth: 1, focusId: null, hiddenGroups: [] };++describe("memory graph view", () => {+ it("places a radial hub at the origin and layers hops to the right", () => {+ const radial = placeNodes(graph.nodes, graph.edges, "radial");+ expect(radial.get("note:a")).toEqual({ x: 0, y: 0 });+ const layered = placeNodes(graph.nodes, graph.edges, "layered");+ expect(layered.get("note:a")?.x).toBe(0);+ expect(layered.get("note:b")!.x).toBeGreaterThan(layered.get("note:a")!.x);+ const web = placeNodes(graph.nodes, graph.edges, "web");+ expect(placeNodes(graph.nodes, graph.edges, "web")).toEqual(web);+ });++ it("hides ghosts and tags, and keeps a one-hop local neighbourhood", () => {+ const hidden = viewGraph(graph, { ...base, showGhosts: false });+ expect(hidden.nodes.map((node) => node.kind).sort()).toEqual(["note", "note"]);+ const local = viewGraph(graph, { ...base, showGhosts: true, local: true, focusId: "note:b", depth: 1 });+ expect(local.nodes.map((node) => node.id).sort()).toEqual(["note:a", "note:b"]);+ });+});diff --git a/frontend/slices/os-shell/memory-graph-app.test.ts b/frontend/slices/os-shell/memory-graph-app.test.tsnew file mode 100644index 00000000..1d66ab27--- /dev/null+++ b/frontend/slices/os-shell/memory-graph-app.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from "vitest";+import { BUILTIN_APPS } from "./shell.manifest";++describe("Memory graph registration", () => {+ it("keeps Memory addressable without pushing Docs or Settings off the first home page", () => {+ const app = BUILTIN_APPS.find((item) => item.id === "memory-graph");+ expect(app?.slug).toBe("memory");+ expect(app?.title).toBe("Memory");+ const index = (slug: string) => BUILTIN_APPS.findIndex((item) => item.slug === slug);+ expect(index("docs")).toBeLessThan(24);+ expect(index("settings")).toBeLessThan(24);+ expect(index("memory")).toBeGreaterThan(index("links"));+ });+});diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.tsindex a7bcec8d..a05ba57f 100644--- a/frontend/slices/os-shell/shell.manifest.ts+++ b/frontend/slices/os-shell/shell.manifest.ts@@ -25,6 +25,7 @@ import { channelsApp } from "@/features/channels";import { workflowsApp } from "@/features/workflows";import { n8nApp } from "@/features/n8n";import { organizationApp } from "@/features/organization";+import { memoryGraphApp } from "@/features/memory-graph";import { cloudflareApp, dokployApp } from "@/features/infrastructure";import { themeQuickPickerFeature } from "./theme-quick-picker";import { serverConnectionStatusFeature } from "./server-connection-status";@@ -84,6 +85,7 @@ export const BUILTIN_APPS: AppDescriptor[] = [withSlug(withArtwork(docsApp), "docs"),pin(withSlug(withArtwork(osSettingsApp), "settings")),withSlug(withArtwork(quicklinksApp), "links"),+ withSlug(memoryGraphApp, "memory"),];// Shell features — the generic brand-free set now lives INSIDE the appshelldiff --git a/lib/agent/server-role.test.ts b/lib/agent/server-role.test.tsindex 875baf66..7b3b9e23 100644--- a/lib/agent/server-role.test.ts+++ b/lib/agent/server-role.test.ts@@ -14,6 +14,7 @@ describe("host API role policy", () => {"/api/v1/temp-share/abc",]) expect(requiredRoleForRequest(req("GET", path)), path).toBe("viewer");expect(requiredRoleForRequest(req("GET", "/api/v1/future-feature"))).toBe("owner");+ expect(requiredRoleForRequest(req("GET", "/api/v1/memory-graph"))).toBe("owner");expect(requiredRoleForRequest(req("GET", "/api/v1/sys/stats-private"))).toBe("owner");expect(requiredRoleForRequest(req("GET", "/api/v1/sys/services-private"))).toBe("owner");expect(requiredRoleForRequest(req("POST", "/api/v1/future-feature"))).toBe("owner");diff --git a/lib/memory-graph/assemble.test.ts b/lib/memory-graph/assemble.test.tsnew file mode 100644index 00000000..3a3f1062--- /dev/null+++ b/lib/memory-graph/assemble.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import { assembleMemoryGraph, neighbourhood } from "./assemble";+import type { GraphInputNode } from "./types";++const notes: GraphInputNode[] = [+ { id: "note:a/alpha", title: "Alpha", kind: "note", group: "a", text: "See [[Beta]] and [more](beta.md) #topic" },+ { id: "note:a/beta", title: "Beta", kind: "note", group: "a", text: "[[Missing Page]]" },+];++describe("assembleMemoryGraph", () => {+ it("resolves wikilinks and markdown hrefs, and keeps unresolved titles as ghosts", () => {+ const graph = assembleMemoryGraph(notes, []);+ const edge = (kind: string, target: string) => graph.edges.find((item) => item.kind === kind && item.target === target);+ expect(edge("wikilink", "note:a/beta")?.resolved).toBe(true);+ expect(edge("mention", "note:a/beta")?.resolved).toBe(true);+ expect(graph.nodes.find((node) => node.id === "ghost:missing-page")).toMatchObject({ kind: "ghost", group: "Unresolved" });+ expect(graph.nodes.find((node) => node.kind === "tag")?.title).toBe("#topic");+ expect(graph.nodes.some((node) => "text" in node)).toBe(false);+ expect(graph.counts.ghosts).toBe(1);+ });++ it("limits a local neighbourhood to the requested hop depth", () => {+ const graph = assembleMemoryGraph(notes, [+ { source: "note:a/alpha", targetId: "note:a/beta", kind: "contains" },+ ]);+ const near = neighbourhood(graph.edges, "note:a/alpha", 1);+ expect(near.has("note:a/beta")).toBe(true);+ expect(near.has("ghost:missing-page")).toBe(false);+ expect(neighbourhood(graph.edges, "note:a/alpha", 2).has("ghost:missing-page")).toBe(true);+ });+});diff --git a/lib/memory-graph/assemble.ts b/lib/memory-graph/assemble.tsnew file mode 100644index 00000000..c624609c--- /dev/null+++ b/lib/memory-graph/assemble.ts@@ -0,0 +1,175 @@+// Graph assembly inspired by rahmanef63/open-silong memory-graph (MIT):+// unresolved [[wikilinks]] become ghost nodes, and links are undirected for+// neighbourhood queries. MSO supplies the notes; this file does not copy that UI.++import type { GraphInputLink, GraphInputNode, MemoryGraphDocument, MemoryGraphEdge, MemoryGraphNode } from "./types";++const WIKILINK_RE = /\[\[([^\]|#^]+?)(?:\|[^\]]+)?\]\]/g;+const TAG_RE = /(?:^|\s)#([A-Za-z0-9_][A-Za-z0-9_/-]{0,40})/g;+const HREF_RE = /\[[^\]]*]\(([^)\s]+)\)/g;++export function slug(title: string): string {+ return title.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "untitled";+}++export function extractNoteLinks(text: string): { wikilinks: string[]; hrefs: string[]; tags: string[] } {+ const wikilinks: string[] = [];+ const hrefs: string[] = [];+ const tags: string[] = [];+ for (const match of text.matchAll(WIKILINK_RE)) {+ const title = (match[1] ?? "").trim();+ if (title) wikilinks.push(title);+ }+ for (const match of text.matchAll(HREF_RE)) {+ const href = (match[1] ?? "").trim();+ if (href && !/^[a-z]+:/i.test(href)) hrefs.push(href);+ }+ for (const match of text.matchAll(TAG_RE)) if (match[1]) tags.push(match[1]);+ return { wikilinks, hrefs, tags };+}++export function neighbourhood(edges: MemoryGraphEdge[], rootId: string, depth: number): Set<string> {+ const adj = new Map<string, string[]>();+ for (const edge of edges) {+ adj.set(edge.source, [...(adj.get(edge.source) ?? []), edge.target]);+ adj.set(edge.target, [...(adj.get(edge.target) ?? []), edge.source]);+ }+ const seen = new Set<string>([rootId]);+ let frontier = [rootId];+ for (let hop = 0; hop < depth; hop++) {+ const next: string[] = [];+ for (const id of frontier) {+ for (const neighbor of adj.get(id) ?? []) {+ if (seen.has(neighbor)) continue;+ seen.add(neighbor);+ next.push(neighbor);+ }+ }+ frontier = next;+ }+ return seen;+}++function stemOf(id: string): string {+ return id.replace(/^(note|knowledge|memory|agent|folder|project):/, "");+}++function indexes(nodes: GraphInputNode[]) {+ const bySlug = new Map<string, string[]>();+ const byStem = new Map<string, string>();+ const byBase = new Map<string, string[]>();+ for (const node of nodes) {+ const titleSlug = slug(node.title);+ bySlug.set(titleSlug, [...(bySlug.get(titleSlug) ?? []), node.id]);+ const stem = stemOf(node.id).replace(/\.md$/i, "").toLowerCase();+ byStem.set(stem, node.id);+ byStem.set(slug(stem), node.id);+ const base = slug(stem.split("/").pop() ?? stem);+ byBase.set(base, [...(byBase.get(base) ?? []), node.id]);+ }+ return { bySlug, byStem, byBase };+}++function unique(ids: string[] | undefined): string | null {+ return ids && ids.length === 1 ? ids[0] : null;+}++function resolveWikilink(raw: string, index: ReturnType<typeof indexes>): string | null {+ const clean = raw.trim().replace(/\.md$/i, "");+ const key = clean.toLowerCase();+ return index.byStem.get(key) ?? index.byStem.get(slug(clean)) ?? unique(index.byBase.get(slug(clean.split("/").pop() ?? clean))) ?? unique(index.bySlug.get(slug(clean)));+}++function resolveHref(raw: string, source: GraphInputNode, index: ReturnType<typeof indexes>): string | null {+ const noHash = raw.split("#")[0]?.split("?")[0] ?? "";+ if (!noHash.toLowerCase().endsWith(".md")) return null;+ const sourceStem = stemOf(source.id).replace(/\.md$/i, "");+ const dir = sourceStem.includes("/") ? sourceStem.slice(0, sourceStem.lastIndexOf("/")) : "";+ const parts = `${dir}/${noHash}`.split("/");+ const stack: string[] = [];+ for (const part of parts) {+ if (!part || part === ".") continue;+ if (part === "..") stack.pop();+ else stack.push(part);+ }+ const joined = stack.join("/").replace(/\.md$/i, "").toLowerCase();+ return index.byStem.get(joined) ?? null;+}++function pushEdge(edges: MemoryGraphEdge[], seen: Set<string>, edge: MemoryGraphEdge) {+ if (edge.source === edge.target) return;+ const key = `${edge.kind}|${edge.source}|${edge.target}`;+ if (seen.has(key)) return;+ seen.add(key);+ edges.push(edge);+}++export function assembleMemoryGraph(+ inputs: GraphInputNode[],+ links: GraphInputLink[],+ options: { includeGhosts?: boolean; includeTags?: boolean } = {},+): Pick<MemoryGraphDocument, "nodes" | "edges" | "counts"> {+ const includeGhosts = options.includeGhosts ?? true;+ const includeTags = options.includeTags ?? true;+ const index = indexes(inputs);+ const nodes = new Map<string, MemoryGraphNode>();+ for (const input of inputs) {+ const { text: _text, ...rest } = input;+ nodes.set(input.id, { ...rest, degree: 0 });+ }+ const edges: MemoryGraphEdge[] = [];+ const seen = new Set<string>();+ const tagCount = { n: 0 };++ const addTag = (source: string, tag: string) => {+ if (!includeTags || tagCount.n > 40) return;+ const id = `tag:${tag.toLowerCase()}`;+ if (!nodes.has(id)) {+ tagCount.n += 1;+ nodes.set(id, { id, title: `#${tag}`, kind: "tag", group: "Tags", degree: 0 });+ }+ pushEdge(edges, seen, { source, target: id, kind: "tag", resolved: true });+ };++ for (const input of inputs) {+ if (!input.text) continue;+ const extracted = extractNoteLinks(input.text);+ for (const title of extracted.wikilinks) {+ const target = resolveWikilink(title, index);+ if (target) pushEdge(edges, seen, { source: input.id, target, kind: "wikilink", resolved: true });+ else if (includeGhosts) {+ const id = `ghost:${slug(title)}`;+ if (!nodes.has(id)) nodes.set(id, { id, title, kind: "ghost", group: "Unresolved", degree: 0 });+ pushEdge(edges, seen, { source: input.id, target: id, kind: "wikilink", resolved: false });+ }+ }+ for (const href of extracted.hrefs) {+ const target = resolveHref(href, input, index);+ if (target) pushEdge(edges, seen, { source: input.id, target, kind: "mention", resolved: true });+ }+ for (const tag of extracted.tags) addTag(input.id, tag);+ }++ for (const link of links) {+ const target = link.targetId ?? (link.target ? resolveWikilink(link.target, index) : null);+ if (!target || !nodes.has(link.source) || !nodes.has(target)) continue;+ pushEdge(edges, seen, { source: link.source, target, kind: link.kind, resolved: true });+ }++ for (const edge of edges) {+ const source = nodes.get(edge.source);+ const target = nodes.get(edge.target);+ if (source) source.degree += 1;+ if (target) target.degree += 1;+ }+ const nodeList = [...nodes.values()];+ return {+ nodes: nodeList,+ edges,+ counts: {+ notes: nodeList.filter((node) => node.kind === "note" || node.kind === "knowledge").length,+ memories: nodeList.filter((node) => node.kind === "memory" || node.kind === "agent").length,+ ghosts: nodeList.filter((node) => node.kind === "ghost").length,+ },+ };+}diff --git a/lib/memory-graph/collect.test.ts b/lib/memory-graph/collect.test.tsnew file mode 100644index 00000000..12db9484--- /dev/null+++ b/lib/memory-graph/collect.test.ts@@ -0,0 +1,69 @@+import { mkdtemp, mkdir, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@/lib/agent/memory-store", () => ({ queryAgentMemory: vi.fn() }));+vi.mock("@/lib/agent/legacy-owner-memory", () => ({ listMemories: vi.fn() }));+vi.mock("@/lib/host/projects-api", () => ({+ listProjects: vi.fn(),+ resolveProjectHint: vi.fn(),+ readProjectKnowledge: vi.fn(),+}));+vi.mock("@/lib/orchestration/repo-memory", () => ({ listRepoMemoryRecords: vi.fn() }));++import { queryAgentMemory } from "@/lib/agent/memory-store";+import { listMemories } from "@/lib/agent/legacy-owner-memory";+import { readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";+import { listRepoMemoryRecords } from "@/lib/orchestration/repo-memory";+import { collectMemoryGraph } from "./collect";++const agent = vi.mocked(queryAgentMemory);+const memories = vi.mocked(listMemories);+const knowledge = vi.mocked(readProjectKnowledge);+const project = vi.mocked(resolveProjectHint);+const records = vi.mocked(listRepoMemoryRecords);++describe("collectMemoryGraph", () => {+ beforeEach(() => {+ agent.mockReset();+ memories.mockReset();+ knowledge.mockReset();+ project.mockReset();+ records.mockReset();+ });++ it("joins a vault note, project knowledge, and redacts private agent memory", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "mso-memory-collect-"));+ vi.stubEnv("OS_FS_READ_ROOTS", root);+ await mkdir(path.join(root, "daily"), { recursive: true });+ await writeFile(path.join(root, "daily", "Alpha.md"), "# Alpha\n\nHello vault\n");+ project.mockResolvedValue({+ hint: "demo", id: "root/demo", name: "demo", path: "/projects/demo", rootId: "root", root: "/projects", aliases: [], matchedBy: "name",+ });+ knowledge.mockResolvedValue({ exists: true, path: ".mso/KNOWLEDGE.md", content: "Use [[Alpha]]\napi_key=super-secret", bytes: 10, sha256: "abc" });+ records.mockResolvedValue([{+ schemaVersion: 1, id: "rec_1", kind: "decision", status: "active", title: "Ship graph", summary: "See [[Alpha]]",+ source: "agent", confidence: 0.9, importance: 0.5, scope: [], tags: [], supersedes: [], createdAt: "2026-09-01T00:00:00.000Z", updatedAt: "2026-09-01T00:00:00.000Z",+ }]);+ agent.mockResolvedValue({+ at: "2026-09-01T00:00:00.000Z", schemaVersion: 1, total: 1, records: [{+ record: {+ id: "mem_1", document: "MEMORY.md", key: "Token", value: "sk_live_should_not_leak", kind: "semantic",+ confidence: 1, sensitivity: "private", validFrom: "2026-09-01T00:00:00.000Z", createdAt: "2026-09-01T00:00:00.000Z",+ provenance: { authority: "explicit", channel: "cli", observedAt: "2026-09-01T00:00:00.000Z" },+ },+ conflicts: [],+ }],+ });+ memories.mockResolvedValue([]);++ const graph = await collectMemoryGraph({ root, project: "demo", principal: "cli:device" });+ const encoded = JSON.stringify(graph);+ expect(encoded).not.toContain("super-secret");+ expect(encoded).not.toContain("sk_live_should_not_leak");+ expect(graph.nodes.some((node) => node.kind === "note" && node.title === "Alpha")).toBe(true);+ expect(graph.edges.some((edge) => edge.kind === "wikilink" && edge.target.startsWith("note:"))).toBe(true);+ expect(graph.nodes.find((node) => node.id === "agent:mem_1")?.excerpt).toBe("Private memory");+ });+});diff --git a/lib/memory-graph/collect.ts b/lib/memory-graph/collect.tsnew file mode 100644index 00000000..e89ab07f--- /dev/null+++ b/lib/memory-graph/collect.ts@@ -0,0 +1,158 @@+// Owner memory-graph collector. Vault markdown, one project's knowledge and+// repo memory, the signed-in device's typed agent memory, and assistant memories.++import path from "node:path";+import { queryAgentMemory } from "@/lib/agent/memory-store";+import { listMemories } from "@/lib/agent/legacy-owner-memory";+import type { AgentMemoryRecord } from "@/lib/agent/memory-types";+import { listProjects, readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";+import { listRepoMemoryRecords } from "@/lib/orchestration/repo-memory";+import { redactText } from "@/lib/orchestration/redaction";+import { assembleMemoryGraph } from "./assemble";+import type { GraphInputLink, GraphInputNode, MemoryGraphDocument } from "./types";+import { readVaultNotes } from "./vault";++const PROJECT_CAP = 4;+const RECORD_CAP = 12;++export interface CollectInput {+ root: string;+ project: string;+ principal: string;+}++function folderHubs(notes: GraphInputNode[]): { nodes: GraphInputNode[]; links: GraphInputLink[] } {+ const groups = new Map<string, string[]>();+ for (const note of notes) {+ if (note.kind !== "note") continue;+ groups.set(note.group, [...(groups.get(note.group) ?? []), note.id]);+ }+ const nodes: GraphInputNode[] = [];+ const links: GraphInputLink[] = [];+ for (const [group, ids] of groups) {+ if (ids.length < 2) continue;+ const id = `folder:${group}`;+ nodes.push({ id, title: group, kind: "folder", group });+ for (const targetId of ids) links.push({ source: id, targetId, kind: "contains" });+ }+ return { nodes, links };+}++function agentPieces(records: Array<{ record: AgentMemoryRecord }>): { nodes: GraphInputNode[]; links: GraphInputLink[] } {+ const nodes: GraphInputNode[] = [];+ const links: GraphInputLink[] = [];+ const seenDocs = new Set<string>();+ for (const row of records) {+ const record = row.record;+ if (!seenDocs.has(record.document)) {+ seenDocs.add(record.document);+ nodes.push({ id: `agent-doc:${record.document}`, title: record.document, kind: "folder", group: "Agent memory" });+ }+ const priv = record.sensitivity !== "normal";+ nodes.push({+ id: `agent:${record.id}`,+ title: record.key.slice(0, 80),+ kind: "agent",+ group: "Agent memory",+ excerpt: priv ? "Private memory" : redactText(record.value, 160),+ text: priv ? "" : record.value,+ });+ links.push({ source: `agent-doc:${record.document}`, targetId: `agent:${record.id}`, kind: "contains" });+ for (const prior of record.supersedes ?? []) {+ links.push({ source: `agent:${record.id}`, targetId: `agent:${prior}`, kind: "related" });+ }+ }+ return { nodes, links };+}++async function projectPieces(projectPath: string, projectId: string, projectName: string): Promise<{ nodes: GraphInputNode[]; links: GraphInputLink[] }> {+ const nodes: GraphInputNode[] = [];+ const links: GraphInputLink[] = [];+ const hub = `project:${projectId}`;+ nodes.push({ id: hub, title: projectName, kind: "folder", group: projectName });+ const knowledge = await readProjectKnowledge(projectPath).catch(() => null);+ if (knowledge?.exists && knowledge.content.trim()) {+ const id = `knowledge:${projectId}`;+ nodes.push({+ id, title: `${projectName} knowledge`, kind: "knowledge", group: projectName,+ path: path.join(projectPath, knowledge.path),+ excerpt: redactText(knowledge.content, 160),+ text: knowledge.content,+ });+ links.push({ source: hub, targetId: id, kind: "contains" });+ }+ const records = await listRepoMemoryRecords(projectPath, { limit: RECORD_CAP }).catch(() => []);+ for (const record of records) {+ const id = `memory:${projectId}:${record.id}`;+ const summary = redactText(`${record.title}\n${record.summary}`, 160);+ nodes.push({ id, title: record.title.slice(0, 80), kind: "memory", group: projectName, excerpt: summary, text: `${record.title}\n${record.summary}` });+ links.push({ source: hub, targetId: id, kind: "contains" });+ for (const prior of record.supersedes) links.push({ source: id, targetId: `memory:${projectId}:${prior}`, kind: "related" });+ }+ return { nodes, links };+}++export async function collectMemoryGraph(input: CollectInput): Promise<MemoryGraphDocument> {+ const warnings: string[] = [];+ let truncated = false;+ const nodes: GraphInputNode[] = [];+ const links: GraphInputLink[] = [];++ const vault = await readVaultNotes(input.root);+ if (vault.warning) warnings.push(vault.warning);+ truncated = vault.truncated;+ nodes.push(...vault.notes);+ const hubs = folderHubs(vault.notes);+ nodes.push(...hubs.nodes);+ links.push(...hubs.links);++ const projectTargets: Array<{ id: string; name: string; path: string }> = [];+ if (input.project.trim()) {+ const resolved = await resolveProjectHint(input.project.trim()).catch(() => null);+ if (!resolved) warnings.push("Project was not found");+ else projectTargets.push(resolved);+ } else if (!vault.root) {+ const listed = await listProjects({ limit: PROJECT_CAP }).catch((error: unknown) => {+ warnings.push(error instanceof Error ? error.message.slice(0, 160) : "Project scan failed");+ return { projects: [] as Array<{ id: string; name: string; path: string }> };+ });+ projectTargets.push(...listed.projects.slice(0, PROJECT_CAP));+ }++ for (const project of projectTargets) {+ try {+ const piece = await projectPieces(project.path, project.id, project.name);+ nodes.push(...piece.nodes);+ links.push(...piece.links);+ } catch (error) {+ warnings.push(error instanceof Error ? error.message.slice(0, 160) : "Project memory failed");+ }+ }++ try {+ const agent = await queryAgentMemory(input.principal, { limit: 40 });+ const piece = agentPieces(agent.records);+ nodes.push(...piece.nodes);+ links.push(...piece.links);+ } catch (error) {+ warnings.push(error instanceof Error ? error.message.slice(0, 160) : "Agent memory unavailable");+ }++ try {+ for (const memory of (await listMemories()).slice(0, 40)) {+ nodes.push({+ id: `owner:${memory.id}`,+ title: memory.text.split("\n")[0]?.slice(0, 80) || "Memory",+ kind: "memory",+ group: "Assistant memory",+ excerpt: redactText(memory.text, 160),+ text: memory.text,+ });+ }+ } catch (error) {+ warnings.push(error instanceof Error ? error.message.slice(0, 160) : "Assistant memory unavailable");+ }++ const graph = assembleMemoryGraph(nodes, links, { includeGhosts: true, includeTags: true });+ return { ...graph, truncated, warnings, root: vault.root };+}diff --git a/lib/memory-graph/types.ts b/lib/memory-graph/types.tsnew file mode 100644index 00000000..68088563--- /dev/null+++ b/lib/memory-graph/types.ts@@ -0,0 +1,54 @@+// Memory-graph contract shared by the owner API and the Memory app.+// Node/edge ideas (ghosts, wikilinks, groups) follow rahmanef63/open-silong+// frontend/slices/memory-graph (MIT). This file is an MSO-native shape.++export type MemoryNodeKind = "note" | "ghost" | "knowledge" | "memory" | "agent" | "folder" | "tag";+export type MemoryEdgeKind = "wikilink" | "mention" | "contains" | "related" | "tag";++export interface MemoryGraphNode {+ id: string;+ title: string;+ kind: MemoryNodeKind;+ /** Color/group key: vault folder, project, or memory bucket. */+ group: string;+ degree: number;+ /** Host path the Code app can open. Absent for ghosts and private claims. */+ path?: string;+ excerpt?: string;+}++export interface MemoryGraphEdge {+ source: string;+ target: string;+ kind: MemoryEdgeKind;+ resolved: boolean;+}++export interface MemoryGraphDocument {+ nodes: MemoryGraphNode[];+ edges: MemoryGraphEdge[];+ truncated: boolean;+ warnings: string[];+ /** Resolved vault root, when a readable vault was scanned. */+ root: string | null;+ counts: { notes: number; memories: number; ghosts: number };+}++export interface GraphInputNode {+ id: string;+ title: string;+ kind: Exclude<MemoryNodeKind, "ghost" | "tag">;+ group: string;+ path?: string;+ excerpt?: string;+ /** Link source only. Never copied onto the returned node. */+ text?: string;+}++export interface GraphInputLink {+ source: string;+ targetId?: string;+ /** Wikilink title or relative markdown href. */+ target?: string;+ kind: Exclude<MemoryEdgeKind, "tag">;+}diff --git a/lib/memory-graph/vault.test.ts b/lib/memory-graph/vault.test.tsnew file mode 100644index 00000000..9ef951e5--- /dev/null+++ b/lib/memory-graph/vault.test.ts@@ -0,0 +1,39 @@+import { mkdtemp, mkdir, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { readVaultNotes } from "./vault";++const previous = process.env.OS_FS_READ_ROOTS;++afterEach(() => {+ if (previous === undefined) delete process.env.OS_FS_READ_ROOTS;+ else process.env.OS_FS_READ_ROOTS = previous;+});++describe("readVaultNotes", () => {+ it("reads markdown inside the read root and skips hidden tool directories", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "mso-memory-graph-"));+ process.env.OS_FS_READ_ROOTS = root;+ await mkdir(path.join(root, "daily"), { recursive: true });+ await mkdir(path.join(root, ".obsidian"), { recursive: true });+ await writeFile(path.join(root, "daily", "Alpha.md"), "# Alpha\n\nLinked [[Beta]]\n");+ await writeFile(path.join(root, ".obsidian", "Secret.md"), "# Secret\n");+ const scan = await readVaultNotes(root);+ expect(scan.root).toBe(root);+ expect(scan.notes.map((note) => note.title)).toEqual(["Alpha"]);+ expect(scan.notes[0]).toMatchObject({ group: "daily", kind: "note" });+ expect(scan.notes[0]?.text).toContain("[[Beta]]");+ });++ it("refuses a root outside the readable roots", async () => {+ const allowed = await mkdtemp(path.join(os.tmpdir(), "mso-memory-allowed-"));+ const blocked = await mkdtemp(path.join(os.tmpdir(), "mso-memory-blocked-"));+ process.env.OS_FS_READ_ROOTS = allowed;+ vi.stubEnv("OS_FS_READ_ROOTS", allowed);+ const scan = await readVaultNotes(blocked);+ expect(scan.notes).toEqual([]);+ expect(scan.root).toBeNull();+ expect(scan.warning).toMatch(/outside|readable/i);+ });+});diff --git a/lib/memory-graph/vault.ts b/lib/memory-graph/vault.tsnew file mode 100644index 00000000..aa6eaa9b--- /dev/null+++ b/lib/memory-graph/vault.ts@@ -0,0 +1,87 @@+// Bounded markdown vault scan. Every file is re-checked with the host read+// jail (resolveReadable) so a symlink cannot escape OS_FS_READ_ROOTS.++import path from "node:path";+import { promises as fs } from "node:fs";+import { readBoundedRegularFile } from "@/lib/host/bounded-read";+import { resolveReadable } from "@/lib/host/paths";+import type { GraphInputNode } from "./types";++const MAX_FILES = 160;+const MAX_DEPTH = 6;+const MAX_DIRS = 400;+const MAX_BYTES = 48 * 1024;+const SKIP = new Set(["node_modules", ".git", ".obsidian", ".mso", ".agent", "dist", ".next", "coverage"]);++export interface VaultScan {+ notes: GraphInputNode[];+ truncated: boolean;+ root: string | null;+ warning?: string;+}++function titleFrom(body: string, filename: string): string {+ const heading = body.match(/^#\s+(.+)$/m)?.[1]?.trim();+ const title = heading || filename.replace(/\.md$/i, "");+ return title.slice(0, 80) || filename;+}++function excerptFrom(body: string): string {+ const plain = body.replace(/^#\s+.+$/m, "").replace(/\s+/g, " ").trim();+ return plain.slice(0, 160);+}++export async function readVaultNotes(requested: string): Promise<VaultScan> {+ const rootRequest = requested.trim();+ if (!rootRequest) return { notes: [], truncated: false, root: null };+ let root: string;+ try {+ root = await resolveReadable(rootRequest);+ } catch (error) {+ const message = error instanceof Error ? error.message : "unreadable vault";+ return { notes: [], truncated: false, root: null, warning: message.slice(0, 180) };+ }+ const rootStat = await fs.lstat(root).catch(() => null);+ if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) {+ return { notes: [], truncated: false, root: null, warning: "Memory graph root must be a real directory" };+ }++ const notes: GraphInputNode[] = [];+ const queue: Array<{ dir: string; rel: string; depth: number }> = [{ dir: root, rel: "", depth: 0 }];+ let dirs = 0;+ let truncated = false;++ while (queue.length && notes.length < MAX_FILES && dirs < MAX_DIRS) {+ const current = queue.shift()!;+ dirs += 1;+ const entries = await fs.readdir(current.dir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (entry.name.startsWith(".") || SKIP.has(entry.name) || entry.isSymbolicLink()) continue;+ const full = path.join(current.dir, entry.name);+ const rel = current.rel ? `${current.rel}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ if (current.depth < MAX_DEPTH) queue.push({ dir: full, rel, depth: current.depth + 1 });+ continue;+ }+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;+ if (notes.length >= MAX_FILES) { truncated = true; break; }+ let readable: string;+ try { readable = await resolveReadable(full); } catch { continue; }+ const body = await readBoundedRegularFile(readable, MAX_BYTES);+ if (body === null) { truncated = true; continue; }+ const stem = rel.replace(/\.md$/i, "");+ const group = stem.includes("/") ? stem.split("/")[0]! : "Notes";+ notes.push({+ id: `note:${stem}`,+ title: titleFrom(body, entry.name),+ kind: "note",+ group,+ path: readable,+ excerpt: excerptFrom(body),+ text: body,+ });+ }+ }+ if (queue.length) truncated = true;+ return { notes, truncated, root };+}diff --git a/scripts/cli/commands-state.sh b/scripts/cli/commands-state.shindex 33658fe0..52ed5333 100755--- a/scripts/cli/commands-state.sh+++ b/scripts/cli/commands-state.sh@@ -178,6 +178,9 @@ case "$cmd" inrm) jdel "/api/memory?id=$(enc "${2:?id}")" ;;*) die "usage: mso $U_memory" ;;esac ;;+ memory-graph)+ if [ -n "${1-}" ]; then jget "/api/v1/memory-graph?project=$(enc "$1")";+ else jget "/api/v1/memory-graph"; fi ;;config) mso_config_command "$U_config" "$@" ;;federation)case "${1:-status}" indiff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex 8a249186..e084dd1c 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -46,6 +46,7 @@ U_agents="agents list [current-session-id]|send <source-session-id> <target> <meU_org="org flow-custom-nodes|flow-nodes-move|flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete <revision> <JSON with unitId|@file>|show|unit-upsert <revision> <JSON|@file>|seat-upsert <revision> <JSON|@file>|unit-delete <revision> <id>|seat-delete <revision> <id>|replace <revision> <JSON|@file>"U_a2a="a2a list|state|sessions|spawn <source-session> <objective> [title]|inbox <session>|discover <url>|add <url> [alias]|rm <target>|send <target> <message> [--wait]|stream <target> <message>|task <target> <taskId> [history]|cancel <target> <taskId>|handoff <target> <objective> [context] [--wait]|local sessions|local handoff <session> <objective>|local spawn <sourceSession> <objective> [title]|local inbox <session>|auth list [target]|auth add <target> [label] [bearer|api-key|oauth2]|auth use <target> <credentialId|none>|auth rm <credentialId>|inbound list|inbound create [label] [read|write|exec]|inbound rm <tokenId>"U_memory="memory list|add <text>|rm <id>"+U_memory_graph="memory-graph [project]"U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"U_prefs="prefs show|set <json>"U_federation="federation status"@@ -80,7 +81,10 @@ mso_cli_main() {if [ $# -ge 2 ]; thencase "$2" in-h|--help|help)- eval "u=\${U_$1-}"+ # Hyphenated verbs (`memory-graph`) map to U_memory_graph. A raw+ # ${U_memory-graph} expansion is the unrelated `memory` usage string.+ local help_key="${1//-/_}"+ eval "u=\${U_${help_key}-}"[ -n "${u-}" ] && { echo "usage: mso $u"; exit 0; }usage | grep -E "^ +$1( |$)" || usageexit 0 ;;@@ -97,7 +101,7 @@ mso_cli_main() {mso_cmd_host "$cmd" "$@" ;;agent|chat|model|setup|onboard|provider|providers|integrations|channels|flow|workflow|gateway|web|camoufox|apps|mapp|term)mso_cmd_runtime "$cmd" "$@" ;;- ai|cockpit|threads|agent-sessions|agents|org|a2a|memory|config|prefs|federation|models|skills|changelog|stock)+ ai|cockpit|threads|agent-sessions|agents|org|a2a|memory|memory-graph|config|prefs|federation|models|skills|changelog|stock)mso_cmd_state "$cmd" "$@" ;;devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|service|build|deploy|update|reset|uninstall|crud|api|completion)mso_cmd_admin "$cmd" "$@" ;;