Python
fix(memhub): keep revoked-source memories on the memory map
alvinfei545b7d38bfe6
diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.pyindex a674d7e..342cd67 100644--- a/memhub/apps/core/src/one_memory/api.py+++ b/memhub/apps/core/src/one_memory/api.py@@ -2978,12 +2978,6 @@ def create_app((`hy_graph_projection`, the visualization exception). Shape matchesthe legacy map so the same view draws both."""- revoked_sources = await asyncio.to_thread(- _read_access(app).revoked_source_ids,- user_id="local",- )- if source in revoked_sources:- raise HTTPException(status_code=409, detail="memory_source_revoked")try:client = await _sdk_client_handle(app).client()# The map visualizes the active source scope, independently of the@@ -3004,16 +2998,9 @@ def create_app(_log_skipped_sdk_memories(skipped)except Exception as error:raise _sdk_http_error(error, "hy_memory_list_failed") from None- revoked_sources = await asyncio.to_thread(- _read_access(app).revoked_source_ids,- user_id="local",- )- if source in revoked_sources:- raise HTTPException(status_code=409, detail="memory_source_revoked")vdb = raw.get("vdb") if isinstance(raw, dict) else Nonetotal = vdb.get("total") if isinstance(vdb, dict) else None- visible = [memory for memory in page.memories if memory.layer != "l1_raw"]- memories = [memory for memory in visible if memory.source not in revoked_sources]+ memories = [memory for memory in page.memories if memory.layer != "l1_raw"]catalog = await asyncio.to_thread(_source_catalog, app)nodes: dict[str, MemoryGraphNode] = {}edges: list[MemoryGraphEdge] = []@@ -3106,18 +3093,8 @@ def create_app(origin="hy_relation",))- final_revoked_sources = await asyncio.to_thread(- _read_access(app).revoked_source_ids,- user_id="local",- )- if final_revoked_sources != revoked_sources:- raise HTTPException(status_code=409, detail="memory_source_access_changed")return MemoryGraphResponse(- total_memories=(- total- if isinstance(total, int) and not revoked_sources- else len(memories)- ),+ total_memories=total if isinstance(total, int) else len(memories),projected_memories=len(memories),nodes=tuple(nodes.values()),edges=tuple(edges),diff --git a/memhub/apps/core/src/one_memory/source_read_access.py b/memhub/apps/core/src/one_memory/source_read_access.pyindex c523a78..19103fc 100644--- a/memhub/apps/core/src/one_memory/source_read_access.py+++ b/memhub/apps/core/src/one_memory/source_read_access.py@@ -135,14 +135,3 @@ class SourceReadAccess:).fetchone()is not None)-- def revoked_source_ids(self, *, user_id: str) -> frozenset[str]:- with main_database(self.database_path).read() as db:- return frozenset(- str(row[0])- for row in db.execute(- "SELECT source_id FROM source_grants "- "WHERE user_id=? AND revoked_at IS NOT NULL",- (user_id,),- )- )diff --git a/memhub/apps/core/tests/test_sdk_data_plane_migration.py b/memhub/apps/core/tests/test_sdk_data_plane_migration.pyindex e098376..810faa3 100644--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py@@ -1325,17 +1325,6 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -"source": "default",}for memory_id in ("c", "d")- ] + [- {- "memory_id": "revoked",- "content": "must not be returned",- "layer": "l2_fact",- "status": "active",- "user_id": "local",- "agent_id": "all-apps",- "session_id": "revoked-session",- "source": "workbuddy",- }]listed = []@@ -1363,15 +1352,6 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -):original = app.state.sdk_client_handleapp.state.sdk_client_handle = Handle()- database = app.state.settings.data_dir / "one-memory.sqlite3"- with sqlite3.connect(database) as db:- db.execute(- "INSERT INTO source_grants "- "(user_id,source_id,root_path,requested_path,root_identity,"- "candidate_kind,granted_at,revoked_at,revision) VALUES "- "('local','workbuddy','/fixture','/fixture','fixture','default',"- "'2026-10-01T00:00:00Z','2026-10-02T00:00:00Z',1)"- )async def graph_snapshot(*, limit):del limit@@ -1389,14 +1369,8 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -"/api/v2/memories/graph",params={"source": "cursor", "offset": 100, "limit": 100},)- revoked = await client.get(- "/api/v2/memories/graph",- params={"source": "workbuddy", "limit": 100},- )app.state.sdk_client_handle = originalassert response.status_code == 200- assert revoked.status_code == 409- assert revoked.json()["detail"] == "memory_source_revoked"return response.json()graph = asyncio.run(scenario())@@ -1404,15 +1378,15 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -assert listed[0]["scene"] == "all"assert listed[0]["statuses"] == ["active"]assert (listed[0]["offset"], listed[0]["limit"]) == (100, 100)- assert (graph["total_memories"], graph["projected_memories"]) == (4, 4)+ assert (graph["total_memories"], graph["projected_memories"]) == (7, 4)assert {node["node_id"] for node in graph["nodes"]} == {"memory:a","memory:b","memory:c","memory:d","source:cursor",+ "hy:t1",}- assert "memory:revoked" not in {node["node_id"] for node in graph["nodes"]}# "default_session" is the SDK's filler, not a conversation.assert [(edge["source_node_id"], edge["target_node_id"])@@ -1422,33 +1396,27 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -assert {edge["relation"] for edge in graph["edges"]} == {"evidence_source","same_conversation",+ "derived_from",}- assert graph["hy_graph_available"] is False+ assert graph["hy_graph_available"] is True@pytest.mark.integration@pytest.mark.fresh_sdk-def test_sdk_memory_graph_rechecks_revocation_after_the_sdk_read(tmp_path) -> None:+def test_sdk_memory_map_still_draws_memories_from_a_revoked_source(tmp_path) -> None:+ # Revoking a source stops new reads from it; memories already distilled+ # from it stay visible, so the map agrees with the list.async def scenario():app = create_app(_app_settings(tmp_path), secret_store=InMemorySecretStore())- database = app.state.settings.data_dir / "one-memory.sqlite3"class Client:def list_memories(self, **_kwargs):- with sqlite3.connect(database) as db:- db.execute(- "INSERT INTO source_grants "- "(user_id,source_id,root_path,requested_path,root_identity,"- "candidate_kind,granted_at,revoked_at,revision) VALUES "- "('local','cursor','/fixture','/fixture','fixture','default',"- "'2026-10-01T00:00:00Z','2026-10-02T00:00:00Z',1)"- )return {"vdb": {"memories": [{- "memory_id": "revoked-during-read",- "content": "must not escape",+ "memory_id": "kept",+ "content": "distilled before revocation","layer": "l2_fact","status": "active","user_id": "local",@@ -1477,14 +1445,25 @@ def test_sdk_memory_graph_rechecks_revocation_after_the_sdk_read(tmp_path) -> No) as client,):app.state.sdk_client_handle = Handle()+ database = app.state.settings.data_dir / "one-memory.sqlite3"+ with sqlite3.connect(database) as db:+ db.execute(+ "INSERT INTO source_grants "+ "(user_id,source_id,root_path,requested_path,root_identity,"+ "candidate_kind,granted_at,revoked_at,revision) VALUES "+ "('local','cursor','/fixture','/fixture','fixture','default',"+ "'2026-10-01T00:00:00Z','2026-10-02T00:00:00Z',1)"+ )response = await client.get("/api/v2/memories/graph",params={"source": "cursor", "limit": 100},)- assert response.status_code == 409- assert response.json()["detail"] == "memory_source_revoked"+ assert response.status_code == 200+ return response.json()- asyncio.run(scenario())+ graph = asyncio.run(scenario())+ assert (graph["total_memories"], graph["projected_memories"]) == (1, 1)+ assert "memory:kept" in {node["node_id"] for node in graph["nodes"]}def test_a_completed_sdk_write_does_not_touch_retired_evidence(store) -> None:diff --git a/memhub/apps/web/src/memory-map-model.test.ts b/memhub/apps/web/src/memory-map-model.test.tsindex 7fd7991..5889d4e 100644--- a/memhub/apps/web/src/memory-map-model.test.ts+++ b/memhub/apps/web/src/memory-map-model.test.ts@@ -7,7 +7,6 @@ import type {import { describe, expect, it } from "vitest";import {mapGroups,- omitRevokedSourceGraph,projectMap,projectPagedSourceMap,} from "./memory-map-model";@@ -96,18 +95,6 @@ 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 --git a/memhub/apps/web/src/memory-map-model.ts b/memhub/apps/web/src/memory-map-model.tsindex a84308f..fe14c26 100644--- a/memhub/apps/web/src/memory-map-model.ts+++ b/memhub/apps/web/src/memory-map-model.ts@@ -15,85 +15,6 @@ 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.