Skip to content
Python

feat(memhub): draw the memory map from SDK memories on SDK authority

alvinfei18046152abb0
diff --git a/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx b/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx
index 73ae594..c82576d 100644
--- a/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx
+++ b/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx
@@ -1,18 +1,34 @@
// @vitest-environment jsdom
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import type {
+ GovernedMemory,
+ MemoryGraphResponse,
+ SdkMemoryRecord,
+} from "@one-memory/contracts";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { MemorySpace } from "./MemorySpace";
+import { sdkMapMemory } from "./sdk-memory-map";
const api = vi.hoisted(() => ({
authority: vi.fn(),
legacyLibrary: vi.fn(),
- graph: vi.fn(),
+ legacyGraph: vi.fn(),
+ sdkLibrary: vi.fn(),
+ sdkGraph: vi.fn(),
}));
vi.mock("./api", () => ({
getMemoryAuthority: api.authority,
getMemoryLibrary: api.legacyLibrary,
getMemories: async () => [],
- getMemoryGraph: api.graph,
+ getMemoryGraph: api.legacyGraph,
+ getSdkMemoryLibrary: api.sdkLibrary,
+ getSdkMemoryGraph: api.sdkGraph,
getMemoryProcessing: async () => null,
getModelProfiles: async () => [],
apiErrorCode: () => null,
@@ -20,50 +36,217 @@ vi.mock("./api", () => ({
vi.mock("./GraphWidthPrompt", () => ({ GraphWidthPrompt: () => null }));
vi.mock("./MemoryNoteComposer", () => ({ MemoryNoteComposer: () => null }));
vi.mock("./MemoryMap", () => ({
- MemoryMap: ({ hidden }: { hidden: boolean }) => (
- <div hidden={hidden} data-testid="legacy-map" />
+ MemoryMap: ({
+ hidden,
+ memories,
+ graph,
+ loaded,
+ onOpenMemory,
+ }: {
+ hidden: boolean;
+ memories: GovernedMemory[];
+ graph: MemoryGraphResponse | null;
+ loaded: boolean;
+ onOpenMemory(id: string): void;
+ }) => (
+ <div hidden={hidden} data-testid="map">
+ <span data-testid="map-memories">
+ {memories.map((m) => `${m.memory_id}:${m.status}`).join(",")}
+ </span>
+ <span data-testid="map-nodes">{graph?.nodes.length ?? "none"}</span>
+ <span data-testid="map-loaded">{String(loaded)}</span>
+ <button type="button" onClick={() => onOpenMemory("a")}>
+ open a
+ </button>
+ </div>
),
}));
vi.mock("./SdkMemoryLibrary", () => ({
- SdkMemoryLibrary: () => <div data-testid="sdk-library" />,
+ SdkMemoryLibrary: ({
+ focusedMemoryId,
+ }: {
+ focusedMemoryId: string | null;
+ }) => <div data-testid="sdk-library">{focusedMemoryId ?? ""}</div>,
}));
vi.mock("./MemoryRecallScope", () => ({
MemoryRecallScope: () => null,
memoryProvenanceLabel: () => "原话",
}));
+const record = (memory_id: string): SdkMemoryRecord => ({
+ memory_id,
+ content: `memory ${memory_id}`,
+ layer: "l2_fact",
+ status: "active",
+ is_latest: true,
+ supersedes: [],
+ superseded_by: [],
+ tags: ["工作"],
+ owner: null,
+ source_raw_ids: [],
+ user_id: "local",
+ agent_id: "all-apps",
+ session_id: "s1",
+ source: "cursor",
+ memory_at: null,
+ gmt_created: 1_761_000_000,
+});
+
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
-it("opens the SDK library on SDK authority instead of a map that cannot load", async () => {
+function sdkAuthority() {
api.authority.mockResolvedValue({ authority: "sdk", migration_id: "m" });
+ api.sdkLibrary.mockResolvedValue({
+ memories: [record("a"), record("b")],
+ total: 3018,
+ limit: 300,
+ offset: 0,
+ });
+ api.sdkGraph.mockResolvedValue({
+ total_memories: 3018,
+ projected_memories: 2,
+ nodes: [
+ { node_id: "memory:a", node_type: "memory", label: "a", memory_id: "a" },
+ { node_id: "memory:b", node_type: "memory", label: "b", memory_id: "b" },
+ { node_id: "source:cursor", node_type: "source", label: "Cursor" },
+ ],
+ edges: [],
+ hy_graph_available: true,
+ });
+}
+
+it("draws the map from SDK memories on SDK authority, without legacy reads", async () => {
+ sdkAuthority();
+
+ render(<MemorySpace simplified active />);
+
+ await waitFor(() =>
+ expect(screen.getByTestId("map-loaded").textContent).toBe("true"),
+ );
+ expect(screen.getByTestId("map").hidden).toBe(false);
+ expect(screen.getByTestId("map-memories").textContent).toBe(
+ "a:confirmed,b:confirmed",
+ );
+ expect(screen.getByTestId("map-nodes").textContent).toBe("3");
+ expect(await screen.findByText(/3,018/)).toBeTruthy();
+ expect(api.sdkLibrary).toHaveBeenCalledWith(
+ { statuses: ["active"], offset: 0, limit: 300 },
+ expect.any(AbortSignal),
+ );
+ expect(api.legacyLibrary).not.toHaveBeenCalled();
+ expect(api.legacyGraph).not.toHaveBeenCalled();
+});
+
+it("opens a memory from the SDK map in the SDK library", async () => {
+ sdkAuthority();
render(<MemorySpace simplified active />);
+ await waitFor(() =>
+ expect(screen.getByTestId("map-loaded").textContent).toBe("true"),
+ );
+ fireEvent.click(screen.getByText("open a"));
const library = await screen.findByTestId("sdk-library");
+ expect(library.textContent).toBe("a");
expect(library.closest("[hidden]")).toBeNull();
- expect(screen.getByTestId("legacy-map").hidden).toBe(true);
- expect(api.legacyLibrary).not.toHaveBeenCalled();
- expect(api.graph).not.toHaveBeenCalled();
- expect(screen.queryByText("正在读取…")).toBeNull();
+ expect(screen.getByTestId("map").hidden).toBe(true);
});
it("keeps asking for the authority until Core answers", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
+ sdkAuthority();
api.authority
.mockRejectedValueOnce(new Error("core_not_ready"))
- .mockRejectedValueOnce(new Error("core_not_ready"))
- .mockResolvedValue({ authority: "sdk", migration_id: "m" });
+ .mockRejectedValueOnce(new Error("core_not_ready"));
render(<MemorySpace simplified active />);
await vi.advanceTimersByTimeAsync(2_000);
await waitFor(() => expect(api.authority).toHaveBeenCalledTimes(3));
- expect(await screen.findByTestId("sdk-library")).toBeTruthy();
+ await waitFor(() =>
+ expect(screen.getByTestId("map-loaded").textContent).toBe("true"),
+ );
} finally {
vi.useRealTimers();
}
});
+
+it("projects SDK records into the fields the map groups by", () => {
+ const coding = sdkMapMemory({ ...record("c"), layer: "coding_experience" });
+ expect(coding).toMatchObject({
+ memory_id: "c",
+ kind: "coding",
+ status: "confirmed",
+ tags: ["工作"],
+ deleted_at: null,
+ });
+ expect(sdkMapMemory({ ...record("s"), layer: "l6_schema" }).kind).toBe(
+ "schema",
+ );
+ expect(sdkMapMemory({ ...record("x"), status: "superseded" }).status).toBe(
+ "superseded",
+ );
+});
+
+const node = (
+ node_id: string,
+ node_type: MemoryGraphResponse["nodes"][number]["node_type"],
+ extra: Partial<MemoryGraphResponse["nodes"][number]> = {},
+): MemoryGraphResponse["nodes"][number] => ({
+ node_id,
+ node_type,
+ label: node_id,
+ memory_id: null,
+ source_id: null,
+ kind: null,
+ status: null,
+ confidence: null,
+ ...extra,
+});
+const provenance = (
+ from: string,
+ to: string,
+): MemoryGraphResponse["edges"][number] => ({
+ edge_id: `${from}->${to}`,
+ source_node_id: from,
+ target_node_id: to,
+ relation: "evidence_source",
+ weight: null,
+ origin: "provenance",
+});
+
+it("groups and draws SDK memories by source with the real map model", async () => {
+ const { mapGroups, projectMap } = await import("./memory-map-model");
+ const memories = [record("a"), record("b")].map(sdkMapMemory);
+ const graph: MemoryGraphResponse = {
+ total_memories: 2,
+ projected_memories: 2,
+ nodes: [
+ node("memory:a", "memory", { memory_id: "a" }),
+ node("memory:b", "memory", { memory_id: "b" }),
+ node("source:cursor", "source", { source_id: "cursor", label: "Cursor" }),
+ node("hy:t1", "topic"),
+ ],
+ edges: [
+ provenance("source:cursor", "memory:a"),
+ provenance("source:cursor", "memory:b"),
+ ],
+ hy_graph_available: true,
+ };
+
+ const groups = mapGroups(memories, graph, "source");
+ expect(groups.map((group) => [group.key, group.memoryIds])).toEqual([
+ ["source:cursor", ["a", "b"]],
+ ]);
+ const drawn = projectMap(graph, memories, "source", ["a", "b"]);
+ expect(
+ drawn.nodes
+ .filter((node) => node.node_type === "memory")
+ .map((n) => n.memory_id),
+ ).toEqual(["a", "b"]);
+ expect(drawn.edges.length).toBeGreaterThan(0);
+});
diff --git a/memhub/apps/web/src/MemorySpace.tsx b/memhub/apps/web/src/MemorySpace.tsx
index 7693dae..0babc10 100644
--- a/memhub/apps/web/src/MemorySpace.tsx
+++ b/memhub/apps/web/src/MemorySpace.tsx
@@ -39,6 +39,8 @@ import {
getMemoryGraph,
getMemoryProcessing,
getModelProfiles,
+ getSdkMemoryGraph,
+ getSdkMemoryLibrary,
manualExtract,
mutateMemory,
retryUnknownMemoryProcessing,
@@ -56,6 +58,7 @@ import { subscribePoll } from "./poll-scheduler";
import { R6Button } from "./R6Controls";
import { SdkMemoryLibrary } from "./SdkMemoryLibrary";
import { SdkRawHistory } from "./SdkRawHistory";
+import { sdkMapMemory } from "./sdk-memory-map";
import { sourceNameOr } from "./source-label";
import { traceUiAction } from "./ui-trace";
import { useMemoryLibrary } from "./use-memory-library";
@@ -159,12 +162,8 @@ export function MemorySpace({
"unknown" | "legacy" | "sdk"
>("unknown");
const [managementOpen, setManagementOpen] = useState(false);
- // On SDK authority the map still reads the legacy library and governed
- // detail, which the API refuses, so it would wait forever. The SDK library
- // lists, opens, edits and deletes through v2; show it until the map reads
- // SDK memories too.
const displayedMode = simplified
- ? managementOpen || memoryAuthority === "sdk"
+ ? managementOpen
? "library"
: "map"
: mode;
@@ -300,6 +299,49 @@ export function MemorySpace({
const [sdkFocusedMemoryId, setSdkFocusedMemoryId] = useState<string | null>(
null,
);
+ // The map on SDK authority. Legacy reads (library page, governed graph)
+ // are refused there, so it draws SDK memories and the v2 graph instead.
+ const [sdkMap, setSdkMap] = useState<{
+ memories: GovernedMemory[];
+ graph: MemoryGraphResponse;
+ } | null>(null);
+ const [sdkMapFailed, setSdkMapFailed] = useState(false);
+ const sdkMapVisible =
+ memoryAuthority === "sdk" &&
+ simplified &&
+ active &&
+ displayedMode === "map";
+ useEffect(() => {
+ if (!sdkMapVisible) return;
+ let cancelled = false;
+ let controller: AbortController | null = null;
+ const read = async () => {
+ controller?.abort();
+ const request = new AbortController();
+ controller = request;
+ try {
+ const [page, graph] = await Promise.all([
+ getSdkMemoryLibrary(
+ { statuses: ["active"], offset: 0, limit: 300 },
+ request.signal,
+ ),
+ getSdkMemoryGraph(request.signal),
+ ]);
+ if (cancelled) return;
+ setSdkMap({ memories: page.memories.map(sdkMapMemory), graph });
+ setSdkMapFailed(false);
+ } catch {
+ if (!cancelled && !request.signal.aborted) setSdkMapFailed(true);
+ }
+ };
+ void read();
+ const timer = setInterval(() => void read(), 30_000);
+ return () => {
+ cancelled = true;
+ clearInterval(timer);
+ controller?.abort();
+ };
+ }, [sdkMapVisible]);
const [draft, setDraft] = useState("");
const [selection, setSelection] = useState<Set<string>>(new Set());
const bulkInFlight = useRef(false);
@@ -1458,35 +1500,50 @@ export function MemorySpace({
{simplified ? t("memory:记忆") : t("memory:记忆空间")}
</h1>
<span className="memory-loaded-count">
- {memoryAuthority === "sdk"
- ? null
- : simplified && !management
- ? mapLibrary.failed
- ? t("memory:记忆读取失败")
- : mapLibrary.stale
- ? t("memory:正在导入历史会话,记忆将陆续出现")
- : mapLibrary.page
- ? tn(
- "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条",
- mapLibrary.page.total,
- {
- filter: settledFilterLabel
- ? t("memory:({filter})", {
- filter: settledFilterLabel,
- })
- : "",
- shown: new Intl.NumberFormat(locale).format(
- mapLibrary.page.items.length,
- ),
- },
- )
- : t("memory:正在读取…")
- : loaded
+ {memoryAuthority === "sdk" && simplified && !management
+ ? sdkMapFailed && !sdkMap
+ ? t("memory:记忆读取失败")
+ : sdkMap
? tn(
- "memory:已加载 {count} 条记忆",
- memories.filter((m) => m.status !== "deleted").length,
+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条",
+ sdkMap.graph.total_memories,
+ {
+ filter: "",
+ shown: new Intl.NumberFormat(locale).format(
+ sdkMap.memories.length,
+ ),
+ },
)
- : t("memory:正在读取…")}
+ : t("memory:正在读取…")
+ : memoryAuthority === "sdk"
+ ? null
+ : simplified && !management
+ ? mapLibrary.failed
+ ? t("memory:记忆读取失败")
+ : mapLibrary.stale
+ ? t("memory:正在导入历史会话,记忆将陆续出现")
+ : mapLibrary.page
+ ? tn(
+ "memory:已沉淀 {count} 条{filter} · 当前展示 {shown} 条",
+ mapLibrary.page.total,
+ {
+ filter: settledFilterLabel
+ ? t("memory:({filter})", {
+ filter: settledFilterLabel,
+ })
+ : "",
+ shown: new Intl.NumberFormat(locale).format(
+ mapLibrary.page.items.length,
+ ),
+ },
+ )
+ : t("memory:正在读取…")
+ : loaded
+ ? tn(
+ "memory:已加载 {count} 条记忆",
+ memories.filter((m) => m.status !== "deleted").length,
+ )
+ : t("memory:正在读取…")}
</span>
</div>
<MemoryNoteComposer
@@ -1830,7 +1887,7 @@ export function MemorySpace({
focusDialogue={focusDialogue}
onFocusDialogueConsumed={onFocusDialogueConsumed}
libraryView={
- simplified
+ simplified && memoryAuthority !== "sdk"
? {
query: mapQuery,
source: mapSource,
@@ -1854,19 +1911,39 @@ export function MemorySpace({
.catch((reason) => setError(message(reason, t)));
}}
hidden={!active || displayedMode !== "map"}
- memories={simplified ? (mapLibrary.page?.items ?? []) : memories}
- graph={simplified && sourceSnapshotStale ? null : graph}
+ memories={
+ memoryAuthority === "sdk"
+ ? (sdkMap?.memories ?? [])
+ : simplified
+ ? (mapLibrary.page?.items ?? [])
+ : memories
+ }
+ graph={
+ memoryAuthority === "sdk"
+ ? (sdkMap?.graph ?? null)
+ : simplified && sourceSnapshotStale
+ ? null
+ : graph
+ }
sources={sources}
processing={processing}
arrival={memoryArrival}
onViewHistory={simplified ? onConnect : () => setMode("history")}
- loaded={simplified ? mapLibrary.page !== null : loaded}
+ loaded={
+ memoryAuthority === "sdk"
+ ? sdkMap !== null
+ : simplified
+ ? mapLibrary.page !== null
+ : loaded
+ }
detail={detail}
detailLoad={detailLoad}
overlayBlocked={
!active ||
deleteCount > 0 ||
- (simplified && (!mapLibrary.page || sourceSnapshotStale))
+ (memoryAuthority === "sdk"
+ ? sdkMap === null
+ : simplified && (!mapLibrary.page || sourceSnapshotStale))
}
draft={draft}
busy={busy || detailReadBlocked}
@@ -1874,6 +1951,14 @@ export function MemorySpace({
streaming={streaming}
onDraft={setDraft}
onOpenMemory={(memoryId) => {
+ if (memoryAuthority === "sdk") {
+ // Governed detail is refused on SDK authority; the SDK library
+ // opens, edits and deletes the same memory through v2.
+ setSdkFocusedMemoryId(memoryId);
+ if (simplified) setManagementOpen(true);
+ else setMode("library");
+ return;
+ }
const recalled = answerMemories.current.find(
(memory) => memory.memory_id === memoryId,
);
diff --git a/memhub/apps/web/src/api.ts b/memhub/apps/web/src/api.ts
index 9eeb7c1..6333ee6 100644
--- a/memhub/apps/web/src/api.ts
+++ b/memhub/apps/web/src/api.ts
@@ -1162,6 +1162,17 @@ export async function getMemory(memoryId: string): Promise<MemoryDetail> {
*/
let pendingMemoryGraph: Promise<MemoryGraphResponse> | null = null;
+/** The memory map on SDK authority: SDK memories plus the graph overlay. */
+export async function getSdkMemoryGraph(
+ signal?: AbortSignal,
+): Promise<MemoryGraphResponse> {
+ const response = await client.get<MemoryGraphResponse>(
+ "/api/v2/memories/graph",
+ { params: { limit: 300 }, signal },
+ );
+ return response.data;
+}
+
export async function getMemoryGraphWith(
transport: { get: typeof client.get } = client,
): Promise<MemoryGraphResponse> {
diff --git a/memhub/apps/web/src/sdk-memory-map.ts b/memhub/apps/web/src/sdk-memory-map.ts
new file mode 100644
index 0000000..ccb337b
--- /dev/null
+++ b/memhub/apps/web/src/sdk-memory-map.ts
@@ -0,0 +1,51 @@
+import type {
+ GovernedMemory,
+ MemoryKind,
+ SdkMemoryRecord,
+} from "@one-memory/contracts";
+
+function kindOf(layer: string): MemoryKind {
+ if (layer === "l6_schema") return "schema";
+ if (layer === "l7_intention") return "intention";
+ if (layer.startsWith("coding")) return "coding";
+ if (layer.startsWith("working")) return "working";
+ return "chat";
+}
+
+function stamp(seconds: number | null | undefined): string {
+ return typeof seconds === "number" && Number.isFinite(seconds)
+ ? new Date(seconds * 1_000).toISOString()
+ : "";
+}
+
+/** An SDK memory in the shape the memory map draws.
+ *
+ * The map groups and labels by id, content, kind, status and tags only. It
+ * never writes through this shape: opening a memory goes to the SDK library,
+ * so the governed-only fields are inert placeholders here.
+ */
+export function sdkMapMemory(record: SdkMemoryRecord): GovernedMemory {
+ const created = stamp(record.gmt_created ?? record.memory_at);
+ return {
+ memory_id: record.memory_id,
+ user_id: record.user_id,
+ kind: kindOf(record.layer),
+ status:
+ record.status === "active"
+ ? "confirmed"
+ : record.status === "superseded"
+ ? "superseded"
+ : "deleted",
+ content: record.content,
+ scopes: [],
+ evidence_ids: [],
+ origin: "extracted",
+ tags: [...record.tags],
+ supersedes: [...record.supersedes],
+ superseded_by: [...record.superseded_by],
+ revision: 1,
+ created_at: created,
+ updated_at: created,
+ deleted_at: null,
+ };
+}