Python
Merge remote-tracking branch 'origin/main' into fix/memory-source-filter-sync
kristinhecbcc50f35e9a
diff --cc memhub/apps/web/src/MemoryMap.test.tsxindex 6cd12a3,e28a3e1..5feaf65--- a/memhub/apps/web/src/MemoryMap.test.tsx+++ b/memhub/apps/web/src/MemoryMap.test.tsx@@@ -1275,18 -1143,121 +1306,122 @@@ it("closing the compact source inspectoaddEventListener() {},removeEventListener() {},}));- sourceReceipt.mockResolvedValue(importedReceipt);- render(<Host items={[]} sources={importedSources} />);- await openSourceReceipt();- await screen.findByText(importedReceipt.examples[0].excerpt);+ const page = {+ items: memories,+ total: 2,+ offset: 0,+ limit: 20,+ source_ids_by_memory: { m0: ["codex"], m1: ["codex"] },+ };+ const view = render(+ <Host simplified sources={importedSources} libraryView={pagedView(page)} />,+ );+ await act(async () => {});+ await userEvent.click(screen.getByRole("button", { name: "图中选择 Codex" }));await userEvent.click(screen.getByRole("button", { name: "关闭记忆详情" }));- expect(document.querySelector(".source-import-receipt")).toBeNull();++ view.rerender(+ <Host+ simplified+ sources={importedSources}+ libraryView={{+ ...pagedView(page),+ source: "codex",+ settledSource: "codex",+ }}+ />,+ );+ expect(screen.queryByRole("dialog", { name: "记忆与原文" })).toBeNull();+ expect(screen.queryByRole("heading", { name: "第一条" })).toBeNull();+ });++ it("keeps the source selection and offers retry when its page fails", async () => {+ const onRetry = vi.fn();+ const page = {+ items: memories,+ total: 2,+ offset: 0,+ limit: 20,+ source_ids_by_memory: { m0: ["codex"], m1: ["codex"] },+ };+ const view = render(+ <Host simplified sources={importedSources} libraryView={pagedView(page)} />,+ );+ await act(async () => {});+ await userEvent.click(screen.getByRole("button", { name: "图中选择 Codex" }));+ view.rerender(+ <Host+ simplified+ sources={importedSources}+ libraryView={{+ ...pagedView(page),+ source: "codex",+ settledSource: "codex",+ failed: true,+ onRetry,+ }}+ />,+ );+ expect(+ screen+ .getAllByRole("alert")+ .some((node) => node.textContent === "记忆暂时无法读取"),+ ).toBe(true);+ await userEvent.click(screen.getByRole("button", { name: "重试" }));+ expect(onRetry).toHaveBeenCalledOnce();+ });++ it("drops a pending source selection when that source is revoked", async () => {+ const page = {+ items: memories,+ total: 2,+ offset: 0,+ limit: 20,+ source_ids_by_memory: { m0: ["codex"], m1: ["codex"] },+ };+ const view = render(+ <Host+ simplified+ sources={[importedSources[0]]}+ libraryView={pagedView(page)}+ />,+ );+ await act(async () => {});+ await userEvent.click(screen.getByRole("button", { name: "图中选择 Codex" }));expect(screen.getByTestId("canvas").dataset.selected).toBe("source:codex");- await userEvent.click(- screen.getByRole("button", { name: "查看选中来源原文" }),++ view.rerender(+ <Host+ simplified+ sources={[{ ...importedSources[0], authorized: false }]}+ libraryView={{+ ...pagedView(page),+ source: "codex",+ settledSource: "codex",+ }}+ />,+ );+ expect(screen.queryByRole("button", { name: "图中选择 Codex" })).toBeNull();- expect(screen.getByTestId("canvas").dataset.selected).not.toBe(- "source:codex",- );++ expect(screen.queryByTestId("canvas")).toBeNull();++ expect(++ screen.getByRole("list", { name: "地图记忆列表" }).children,++ ).toHaveLength(0);+ expect(screen.queryByText("正在读取记忆详情…")).toBeNull();++ view.rerender(+ <Host+ simplified+ sources={[importedSources[0]]}+ libraryView={{+ ...pagedView(page),+ source: "codex",+ settledSource: "codex",+ }}+ />,+ );+ expect(screen.getByTestId("canvas").dataset.selected).not.toBe(+ "source:codex",);- expect(screen.getByRole("dialog", { name: "记忆与原文" })).toBeTruthy();- expect(screen.getByText("查看已读内容")).toBeTruthy();});it("REV09: first governed memories replace fallback without remounting the graph or breaking memory IDs", async () => {diff --cc memhub/apps/web/src/MemoryMap.tsxindex 4f897cd,2a708d8..cf5ae56--- a/memhub/apps/web/src/MemoryMap.tsx+++ b/memhub/apps/web/src/MemoryMap.tsx@@@ -42,6 -42,6 +42,7 @@@ import { memoryText, useMemoryLanguageimport {type MapAxis,mapGroups,++ omitRevokedSourceGraph,projectMap,projectPagedSourceMap,} from "./memory-map-model";@@@ -96,8 -95,9 +96,10 @@@ type Props =page: MemoryLibraryPage | null;loading: boolean;failed: boolean;+ graphFailed?: boolean;stale: boolean;+ settledSource?: string;+ settledQuery?: string;/** The source id the SDK uses for "no source given" (shown as 未识别来源). */unattributedSource?: string;onQuery(value: string): void;@@@ -179,20 -183,20 +185,24 @@@ export function MemoryMap(props: Propsconst library = props.libraryView;const serverPaged = library !== undefined;const unattributedLabel = text("未识别来源");++ const authorizedBaseGraph = useMemo(++ () => omitRevokedSourceGraph(baseGraph, sources),++ [baseGraph, sources],++ );const graph = useMemo(() =>serverPaged? projectPagedSourceMap(-- baseGraph,++ authorizedBaseGraph,library?.page ?? null,sources,library?.unattributedSource? { [library.unattributedSource]: unattributedLabel }: undefined,)-- : baseGraph,++ : authorizedBaseGraph,[-- baseGraph,++ authorizedBaseGraph,serverPaged,library?.page,library?.unattributedSource,@@@ -231,10 -238,10 +244,18 @@@? `source:${library.source}`: "": groupKey;-- const active = useMemo(-- () => memories.filter((m) => m.status !== "deleted"),-- [memories],-- );++ const active = useMemo(() => {++ const revoked = new Set(++ sources++ .filter((source) => source.authorized === false)++ .map((source) => source.source_id),++ );++ return memories.filter((memory) => {++ if (memory.status === "deleted") return false;++ const sourceIds = library?.page?.source_ids_by_memory?.[memory.memory_id];++ return !sourceIds?.some((sourceId) => revoked.has(sourceId));++ });++ }, [library?.page?.source_ids_by_memory, memories, sources]);const arrival = resolveMemoryArrival({arrival: props.arrival,processing: props.processing,@@@ -309,29 -316,6 +330,29 @@@[active, group, search, serverPaged, axis, groupKey],);const projection = useMemo(() => {+ if (serverPaged && (library?.stale || library?.graphFailed))+ return {+ total_memories: library.page?.total ?? 0,+ projected_memories: 0,+ hy_graph_available: false,+ nodes: [],+ edges: [],+ };+ // Source filtering owns the graph scope, while pagination owns only the+ // left-hand list window. Projecting the graph back down to the current+ // 20-row page made "All applications" look like whichever source happened+ // to dominate that page. Keyword search is intentionally page-scoped.+ if (serverPaged && !library?.query) {+ return (- baseGraph ??++ authorizedBaseGraph ??+ projectMap(+ graph,+ active,+ axis,+ filtered.map((m) => m.memory_id),+ )+ );+ }const result = projectMap(graph,active,@@@ -363,21 -347,7 +384,21 @@@confidence: null,})),};- }, [graph, axis, filtered, active, groupKey, search, sources, serverPaged]);+ }, [- baseGraph,++ authorizedBaseGraph,+ graph,+ axis,+ filtered,+ active,+ groupKey,+ search,+ sources,+ serverPaged,+ library?.query,+ library?.stale,+ library?.graphFailed,+ library?.page?.total,+ ]);const visibleGroupNode = groupNode? (projection.nodes.find((node) =>diff --cc memhub/apps/web/src/MemorySpace.tsxindex 9381265,14e442e..5c57097--- a/memhub/apps/web/src/MemorySpace.tsx+++ b/memhub/apps/web/src/MemorySpace.tsx@@@ -1044,8 -1026,9 +1044,10 @@@ export function MemorySpace(page: sdkLibrary.page,loading: sdkLibrary.loading,failed: sdkLibrary.failed,- stale: false,+ graphFailed: sdkGraphFailed,+ stale: !sdkGraphSettled,+ settledSource: sdkLibrary.settledSource,+ settledQuery: sdkLibrary.settledQuery,unattributedSource: UNATTRIBUTED_SOURCE_ID,onQuery: setSdkLibraryQuery,onSource: setSdkLibrarySource,diff --cc memhub/apps/web/src/memory-map-model.test.tsindex 5889d4e,5889d4e..7fd7991--- a/memhub/apps/web/src/memory-map-model.test.ts+++ b/memhub/apps/web/src/memory-map-model.test.ts@@@ -7,6 -7,6 +7,7 @@@ import typeimport { describe, expect, it } from "vitest";import {mapGroups,++ omitRevokedSourceGraph,projectMap,projectPagedSourceMap,} from "./memory-map-model";@@@ -95,6 -95,6 +96,18 @@@ describe("memory map membership", () =expect(result.nodes.map((n) => n.node_id)).not.toContain("memory:c");expect(result.edges).toHaveLength(2);});++ it("removes revoked source subgraphs while retaining authorized ones", () => {++ const result = omitRevokedSourceGraph(graph, [++ { source_id: "codex", authorized: false },++ { source_id: "cursor", authorized: true },++ ] as SourceResponse[]);++ expect(result?.nodes.map((node) => node.node_id)).toEqual([++ "memory:c",++ "source:cursor",++ ]);++ expect(result?.edges.map((edge) => edge.edge_id)).toEqual(["c"]);++ expect(result?.projected_memories).toBe(1);++ });it("builds topic edges only from actual tags, without creating new facts", () => {const result = projectMap(graph, memories, "topic", ["a", "b"]);expect(result.nodes.filter((n) => n.node_type === "memory")).toHaveLength(diff --cc memhub/apps/web/src/memory-map-model.tsindex fe14c26,fe14c26..a84308f--- a/memhub/apps/web/src/memory-map-model.ts+++ b/memhub/apps/web/src/memory-map-model.ts@@@ -15,6 -15,6 +15,85 @@@ export type MapGroup =sourceCount: number;};++/** Remove every graph fact that depends on an explicitly revoked source.++ * Unknown source IDs remain visible because they are not an authorization denial.++ */++export function omitRevokedSourceGraph(++ graph: MemoryGraphResponse | null,++ sources: SourceResponse[],++): MemoryGraphResponse | null {++ if (!graph) return null;++ const revoked = new Set(++ sources++ .filter((source) => source.authorized === false)++ .map((source) => source.source_id),++ );++ if (!revoked.size) return graph;++++ const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));++ const blocked = new Set(++ graph.nodes++ .filter(++ (node) =>++ node.node_type === "source" &&++ !!node.source_id &&++ revoked.has(node.source_id),++ )++ .map((node) => node.node_id),++ );++ for (const edge of graph.edges) {++ if (edge.origin !== "provenance") continue;++ const ends = [edge.source_node_id, edge.target_node_id];++ if (!ends.some((id) => blocked.has(id))) continue;++ for (const id of ends) {++ if (nodes.get(id)?.node_type === "memory") blocked.add(id);++ }++ }++++ const candidateEdges = graph.edges.filter(++ (edge) =>++ !blocked.has(edge.source_node_id) && !blocked.has(edge.target_node_id),++ );++ const retained = new Set(++ graph.nodes++ .filter(++ (node) => node.node_type === "memory" && !blocked.has(node.node_id),++ )++ .map((node) => node.node_id),++ );++ let changed = true;++ while (changed) {++ changed = false;++ for (const edge of candidateEdges) {++ if (++ retained.has(edge.source_node_id) &&++ !retained.has(edge.target_node_id)++ ) {++ retained.add(edge.target_node_id);++ changed = true;++ } else if (++ retained.has(edge.target_node_id) &&++ !retained.has(edge.source_node_id)++ ) {++ retained.add(edge.source_node_id);++ changed = true;++ }++ }++ }++ const retainedNodes = graph.nodes.filter((node) => retained.has(node.node_id));++ return {++ ...graph,++ projected_memories: retainedNodes.filter(++ (node) => node.node_type === "memory",++ ).length,++ nodes: retainedNodes,++ edges: candidateEdges.filter(++ (edge) =>++ retained.has(edge.source_node_id) && retained.has(edge.target_node_id),++ ),++ };++}++/** The current authorized page owns provenance; the global graph may be truncated.* Callers must pass null while page authority is stale. Catalog metadata names* sources and can veto revoked ones, but never invents evidence membership.