Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(explorer): add deterministic rendering E2E example and test (#1037) (#1041)
Alex Smolyad3183d0ab3c3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4ea31ff8..cafe3074 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -33,15 +33,29 @@ jobs:- name: Install Explorer frontend dependenciesworking-directory: explorerrun: npm ci+ - name: Install Playwright Chromium+ working-directory: explorer+ run: npx playwright install --with-deps chromium- name: Test Explorer frontendworking-directory: explorerrun: |npm run test:graph-storenpm run test:graph-workspacenpm run test:plugin-registry+ npm run test:deterministic-e2e- name: Build Explorer frontendworking-directory: explorerrun: npm run build+ - name: Install Explorer backend test dependencies+ run: |+ # Run the deterministic backend path before the all-extras CI+ # environment is installed. The Explorer extra supplies the+ # production API dependencies without importing optional vector+ # providers such as Pinecone during test collection.+ pip install -e ".[explorer]" pytest==9.1.1+ - name: Test deterministic Explorer backend path+ run: |+ pytest -q tests/explorer/test_explorer_deterministic_rendering_e2e.py- name: Install pinned Python dependenciesrun: |pip install -r requirements-ci.txtdiff --git a/examples/explorer_deterministic_rendering_example.py b/examples/explorer_deterministic_rendering_example.pynew file mode 100644index 00000000..f4bd9ca3--- /dev/null+++ b/examples/explorer_deterministic_rendering_example.py@@ -0,0 +1,195 @@+"""+Deterministic Explorer Rendering E2E Example.++Demonstrates building, serializing, and reloading a deterministic 4-node,+3-edge knowledge graph baseline for visual inspection in Semantica Explorer (#1037).++Graph topology:+ Alice (Person, #63E6FF) --WORKS_AT--> Acme (Organization, #A78BFA)+ Bob (Person, #63E6FF) --KNOWS--> Alice (Person, #63E6FF)+ Acme (Organization, #A78BFA) --LOCATED_IN--> New York (Location, #34D399)++Clean Checkout Prerequisites:+ 1. Python backend dependencies:+ pip install -e ".[explorer]"+ 2. Frontend workspace dependencies:+ cd explorer && npm install && cd ..++Usage:+ # 1. Generate the deterministic graph baseline:+ python examples/explorer_deterministic_rendering_example.py++ # 2. Launch Explorer with local dev authentication (Option A - Dev mode):+ # Terminal 1 (Backend API):+ SEMANTICA_ALLOW_ANONYMOUS=true python -m semantica.explorer --graph explorer_e2e_test_graph.json --port 8000 --no-browser+ # Terminal 2 (Frontend UI):+ cd explorer && npm run dev+ # Open http://localhost:5173++ # 2. Launch Explorer (Option B - Standalone CLI server):+ SEMANTICA_ALLOW_ANONYMOUS=true python -m semantica.explorer --graph explorer_e2e_test_graph.json --port 8000+ # Open http://localhost:8000++ # Secure authentication alternative:+ export SEMANTICA_API_KEY="your-secret-api-key"+ python -m semantica.explorer --graph explorer_e2e_test_graph.json --port 8000+ # Send HTTP header: X-API-Key: your-secret-api-key++Verification Checklist:+ - Exactly 4 nodes visible on canvas:+ * Alice (Person, #63E6FF)+ * Bob (Person, #63E6FF)+ * Acme (Organization, #A78BFA)+ * New York (Location, #34D399)+ - Exactly 3 directed edges with canonical relationship labels:+ * Alice -> Acme (WORKS_AT)+ * Bob -> Alice (KNOWS)+ * Acme -> New York (LOCATED_IN)+ - Zoom behavior:+ * Zoom in to Inspection tier (ratio <= 0.5): directional arrows and node labels scale clearly.+ * Zoom out to Overview tier (ratio > 1.2): layout remains stable and non-colliding.+ - Hover & Selection interactions:+ * Hover over 'Alice': node halo triggers; incident edges (WORKS_AT, KNOWS) highlight in local context.+ * Click an edge: Inspector panel confirms edgeType ('WORKS_AT', 'KNOWS', or 'LOCATED_IN').+"""++from __future__ import annotations++import json+from pathlib import Path++from semantica.context.context_graph import ContextGraph+from semantica.explorer.session import GraphSession+++def build_deterministic_graph() -> ContextGraph:+ """Build the exact 4-node, 3-edge graph specified in #1037."""+ graph = ContextGraph(advanced_analytics=False)++ # 1. Add exactly 4 nodes+ graph.add_node(+ "alice",+ node_type="Person",+ content="Alice",+ color="#63E6FF",+ )+ graph.add_node(+ "bob",+ node_type="Person",+ content="Bob",+ color="#63E6FF",+ )+ graph.add_node(+ "acme",+ node_type="Organization",+ content="Acme",+ color="#A78BFA",+ )+ graph.add_node(+ "new_york",+ node_type="Location",+ content="New York",+ color="#34D399",+ )++ # 2. Add exactly 3 directed edges+ graph.add_edge("alice", "acme", edge_type="WORKS_AT", weight=1.0)+ graph.add_edge("bob", "alice", edge_type="KNOWS", weight=1.0)+ graph.add_edge("acme", "new_york", edge_type="LOCATED_IN", weight=1.0)++ return graph+++def main() -> None:+ print("=" * 75)+ print("Semantica Explorer Deterministic Graph Generator (#1037)")+ print("=" * 75)++ print("1. Building deterministic ContextGraph...")+ graph = build_deterministic_graph()+ print(+ f" ✓ Graph built with {len(graph.nodes)} nodes "+ f"and {len(graph.edges)} edges."+ )++ output_path = Path("explorer_e2e_test_graph.json").resolve()+ print(f"2. Persisting graph to '{output_path.name}'...")+ graph.save_to_file(str(output_path))+ print(f" ✓ Graph saved to {output_path}")++ # Verify JSON format+ with open(output_path, "r", encoding="utf-8") as f:+ data = json.load(f)+ assert len(data.get("nodes", [])) == 4+ assert len(data.get("edges", [])) == 3++ print("3. Verifying reload via GraphSession.from_file()...")+ session = GraphSession.from_file(str(output_path))+ stats = session.get_stats()+ nodes, total_nodes = session.get_nodes()+ edges, total_edges = session.get_edges()++ assert stats["node_count"] == 4+ assert stats["edge_count"] == 3+ assert total_nodes == 4+ assert total_edges == 3++ print(+ f" ✓ Graph reloaded successfully without mutation "+ f"(nodes: {total_nodes}, edges: {total_edges}).\n"+ )++ print("=" * 75)+ print("Clean Checkout Prerequisites:")+ print("=" * 75)+ print(" pip install -e '.[explorer]'")+ print(" cd explorer && npm install && cd ..\n")++ print("=" * 75)+ print("Reproduction instructions to view in Semantica Explorer:")+ print("=" * 75)+ print("Option A (Frontend dev server + API backend — recommended for development):")+ print(+ f" 1. Backend: SEMANTICA_ALLOW_ANONYMOUS=true python -m semantica.explorer "+ f"--graph {output_path} --port 8000 --no-browser"+ )+ print(" 2. Frontend: cd explorer && npm run dev")+ print(" 3. Open http://localhost:5173 to inspect the graph canvas.\n")++ print("Option B (Standalone Explorer CLI server):")+ print(+ f" SEMANTICA_ALLOW_ANONYMOUS=true python -m semantica.explorer "+ f"--graph {output_path} --port 8000"+ )+ print(" Open http://localhost:8000\n")++ print("Secure Authentication Alternative:")+ print(" export SEMANTICA_API_KEY='your-secret-api-key'")+ print(+ f" python -m semantica.explorer --graph {output_path} --port 8000"+ )+ print(" Send header: 'X-API-Key: your-secret-api-key'\n")++ print("=" * 75)+ print("Verification Checklist:")+ print("=" * 75)+ print(" 1. Nodes (4 total):")+ print(" - Alice (Person, #63E6FF)")+ print(" - Bob (Person, #63E6FF)")+ print(" - Acme (Organization, #A78BFA)")+ print(" - New York (Location, #34D399)")+ print(" 2. Directed Edges & Canonical Labels (3 total):")+ print(" - Alice -> Acme [WORKS_AT]")+ print(" - Bob -> Alice [KNOWS]")+ print(" - Acme -> New York [LOCATED_IN]")+ print(" 3. Zoom Interactions:")+ print(" - Inspection tier (zoom in): directional arrows & labels remain legible.")+ print(" - Overview tier (zoom out): nodes and edges maintain layout integrity.")+ print(" 4. Hover & Selection Interactions:")+ print(" - Hover Alice: node halo triggers and incident edges (WORKS_AT, KNOWS) highlight.")+ print(" - Click edge: Inspector panel displays edgeType label ('WORKS_AT', 'KNOWS', 'LOCATED_IN').")+ print("=" * 75)+++if __name__ == "__main__":+ main()diff --git a/explorer/package.json b/explorer/package.jsonindex fbd0b202..540bf0ca 100644--- a/explorer/package.json+++ b/explorer/package.json@@ -9,7 +9,8 @@"lint": "eslint .","preview": "vite preview","test:graph-store": "node --test tests/graphStore.multi-edge.test.mjs",- "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts",+ "test:graph-workspace": "node --import tsx --test tests/markdownContentViewer.test.ts tests/graphSceneState.display.test.ts tests/temporalLifecycle.test.ts tests/deterministicExplorerRendering.test.ts",+ "test:deterministic-e2e": "node --import tsx --test tests/deterministicExplorerRendering.e2e.ts","test:plugin-registry": "node --import tsx --test tests/pluginRegistry.temporal.test.mjs"},"dependencies": {diff --git a/explorer/tests/deterministicExplorerRendering.e2e.ts b/explorer/tests/deterministicExplorerRendering.e2e.tsnew file mode 100644index 00000000..df13541b--- /dev/null+++ b/explorer/tests/deterministicExplorerRendering.e2e.ts@@ -0,0 +1,103 @@+import assert from "node:assert/strict";+import { spawn, type ChildProcess } from "node:child_process";+import { existsSync } from "node:fs";+import { setTimeout as delay } from "node:timers/promises";+import test from "node:test";+import { chromium, type Page } from "playwright";++const PORT = 4173;+const BASE_URL = `http://127.0.0.1:${PORT}`;++const nodes = [+ { id: "alice", type: "Person", content: "Alice", properties: {} },+ { id: "bob", type: "Person", content: "Bob", properties: {} },+ { id: "acme", type: "Organization", content: "Acme", properties: {} },+ { id: "new_york", type: "Location", content: "New York", properties: {} },+];++const edges = [+ { id: "edge_alice_acme", familyId: "edge_alice_acme", source: "alice", target: "acme", type: "WORKS_AT", weight: 1, properties: {} },+ { id: "edge_bob_alice", familyId: "edge_bob_alice", source: "bob", target: "alice", type: "KNOWS", weight: 1, properties: {} },+ { id: "edge_acme_new_york", familyId: "edge_acme_new_york", source: "acme", target: "new_york", type: "LOCATED_IN", weight: 1, properties: {} },+];++let server: ChildProcess | undefined;++async function startVite(): Promise<void> {+ server = spawn("npm", ["run", "dev", "--", "--host", "127.0.0.1", "--port", String(PORT)], {+ cwd: process.cwd(),+ stdio: "ignore",+ });++ for (let attempt = 0; attempt < 50; attempt += 1) {+ try {+ const response = await fetch(BASE_URL);+ if (response.ok) return;+ } catch {+ // Vite is still starting.+ }+ await delay(100);+ }+ throw new Error("Vite did not become ready");+}++async function installApiFixture(page: Page): Promise<void> {+ await page.route("**/api/graph/**", async (route) => {+ const pathname = new URL(route.request().url()).pathname;+ if (pathname === "/api/graph/stats") {+ await route.fulfill({ json: { node_count: 4, edge_count: 3 } });+ } else if (pathname === "/api/graph/nodes") {+ await route.fulfill({ json: { nodes, total: nodes.length, skip: 0, limit: 1000, next_cursor: null } });+ } else if (pathname === "/api/graph/edges") {+ await route.fulfill({ json: { edges, total: edges.length, skip: 0, limit: 1000, next_cursor: null } });+ } else {+ await route.continue();+ }+ });+}++test("real Explorer loading path hydrates and renders API edge labels", async (t) => {+ await startVite();+ t.after(async () => {+ server?.kill();+ });++ const browser = await chromium.launch({+ headless: true,+ executablePath: process.env.CHROMIUM_PATH || (existsSync("/usr/bin/chromium") ? "/usr/bin/chromium" : undefined),+ });+ t.after(() => browser.close());+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });++ await page.addInitScript(() => {+ const captured = (window as Window & { __capturedCanvasText?: string[] }).__capturedCanvasText = [];+ const originalFillText = CanvasRenderingContext2D.prototype.fillText;+ CanvasRenderingContext2D.prototype.fillText = function (text: string, ...args: [number, number, number?, number?]) {+ captured.push(String(text));+ return originalFillText.call(this, text, ...args);+ };+ });+ await installApiFixture(page);+ await page.goto(BASE_URL);+ await page.getByRole("button", { name: /Open Semantica Explorer/ }).click();++ await page.locator("canvas").nth(0).waitFor({ state: "attached" });+ await page.waitForFunction(() => document.querySelectorAll("canvas").length >= 2);+ await page.waitForFunction(() => {+ const labels = (window as Window & { __capturedCanvasText?: string[] }).__capturedCanvasText ?? [];+ return ["WORKS_AT", "KNOWS", "LOCATED_IN"].every((label) => labels.includes(label));+ }, undefined, { timeout: 10_000 });++ const capturedLabels = await page.evaluate(() => (window as Window & { __capturedCanvasText?: string[] }).__capturedCanvasText ?? []);+ for (const label of ["WORKS_AT", "KNOWS", "LOCATED_IN"]) {+ assert.ok(capturedLabels.includes(label), `Expected rendered edge label ${label}`);+ }+ assert.ok(capturedLabels.includes("Alice"));++ await page.getByRole("button", { name: "Zoom In" }).click();+ await page.waitForTimeout(250);+ const labelsAfterZoom = await page.evaluate(() => (window as Window & { __capturedCanvasText?: string[] }).__capturedCanvasText ?? []);+ for (const label of ["WORKS_AT", "KNOWS", "LOCATED_IN"]) {+ assert.ok(labelsAfterZoom.includes(label), `Expected edge label ${label} after zoom`);+ }+});diff --git a/explorer/tests/deterministicExplorerRendering.test.ts b/explorer/tests/deterministicExplorerRendering.test.tsnew file mode 100644index 00000000..42b62033--- /dev/null+++ b/explorer/tests/deterministicExplorerRendering.test.ts@@ -0,0 +1,508 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ batchMergeEdges,+ batchMergeNodes,+ clearGraph,+ graph,+} from "../src/store/graphStore.ts";+import {+ buildStructuralDistanceSnapshot,+ classifyFullGraphEdge,+ resolveDisplayGraph,+ resolveEdgeElementStyle,+ resolveEdgeVisualState,+ resolveNodeElementStyle,+ resolveNodeVisualState,+ shouldForceNodeLabel,+} from "../src/workspaces/GraphWorkspace/graphSceneState.ts";+import { GRAPH_THEME, type GraphZoomTier } from "../src/workspaces/GraphWorkspace/graphTheme.ts";++test.beforeEach(() => {+ clearGraph();+});++test.after(() => {+ clearGraph();+});++/**+ * Loads the canonical 4-node, 3-edge deterministic test graph (Semantica #1037).+ *+ * Graph structure:+ * Alice (Person) --WORKS_AT--> Acme (Organization)+ * Bob (Person) --KNOWS--> Alice (Person)+ * Acme (Organization) --LOCATED_IN--> New York (Location)+ */+function loadDeterministicTestGraph() {+ batchMergeNodes([+ {+ id: "alice",+ attributes: {+ label: "Alice",+ content: "Alice",+ x: 0,+ y: 0,+ size: 8,+ color: "#63E6FF",+ baseColor: "#63E6FF",+ nodeType: "Person",+ semanticGroup: "Person",+ properties: {},+ },+ },+ {+ id: "bob",+ attributes: {+ label: "Bob",+ content: "Bob",+ x: -50,+ y: 0,+ size: 8,+ color: "#63E6FF",+ baseColor: "#63E6FF",+ nodeType: "Person",+ semanticGroup: "Person",+ properties: {},+ },+ },+ {+ id: "acme",+ attributes: {+ label: "Acme",+ content: "Acme",+ x: 50,+ y: 0,+ size: 8,+ color: "#A78BFA",+ baseColor: "#A78BFA",+ nodeType: "Organization",+ semanticGroup: "Organization",+ properties: {},+ },+ },+ {+ id: "new_york",+ attributes: {+ label: "New York",+ content: "New York",+ x: 100,+ y: 0,+ size: 8,+ color: "#34D399",+ baseColor: "#34D399",+ nodeType: "Location",+ semanticGroup: "Location",+ properties: {},+ },+ },+ ]);++ batchMergeEdges([+ {+ id: "edge_alice_acme",+ source: "alice",+ target: "acme",+ attributes: {+ edgeId: "edge_alice_acme",+ edgeType: "WORKS_AT",+ weight: 1.0,+ visualPriority: 0.8,+ baseSize: 0.8,+ properties: {},+ },+ },+ {+ id: "edge_bob_alice",+ source: "bob",+ target: "alice",+ attributes: {+ edgeId: "edge_bob_alice",+ edgeType: "KNOWS",+ weight: 1.0,+ visualPriority: 0.8,+ baseSize: 0.8,+ properties: {},+ },+ },+ {+ id: "edge_acme_new_york",+ source: "acme",+ target: "new_york",+ attributes: {+ edgeId: "edge_acme_new_york",+ edgeType: "LOCATED_IN",+ weight: 1.0,+ visualPriority: 0.8,+ baseSize: 0.8,+ properties: {},+ },+ },+ ]);+}++test("deterministic graph contains exactly 4 nodes and 3 edges in store", () => {+ loadDeterministicTestGraph();++ assert.equal(graph.order, 4, "Expected exactly 4 nodes");+ assert.equal(graph.size, 3, "Expected exactly 3 edges");++ // Verify node identities and labels+ const alice = graph.getNodeAttributes("alice");+ const bob = graph.getNodeAttributes("bob");+ const acme = graph.getNodeAttributes("acme");+ const newYork = graph.getNodeAttributes("new_york");++ assert.equal(alice.label, "Alice");+ assert.equal(alice.nodeType, "Person");+ assert.equal(alice.color, "#63E6FF");++ assert.equal(bob.label, "Bob");+ assert.equal(bob.nodeType, "Person");+ assert.equal(bob.color, "#63E6FF");++ assert.equal(acme.label, "Acme");+ assert.equal(acme.nodeType, "Organization");+ assert.equal(acme.color, "#A78BFA");++ assert.equal(newYork.label, "New York");+ assert.equal(newYork.nodeType, "Location");+ assert.equal(newYork.color, "#34D399");++ // Verify edge connectivity and canonical edgeType labels+ const edgeAliceAcme = graph.getEdgeAttributes("edge_alice_acme");+ const edgeBobAlice = graph.getEdgeAttributes("edge_bob_alice");+ const edgeAcmeNewYork = graph.getEdgeAttributes("edge_acme_new_york");++ assert.equal(edgeAliceAcme.edgeType, "WORKS_AT");+ assert.equal(graph.source("edge_alice_acme"), "alice");+ assert.equal(graph.target("edge_alice_acme"), "acme");++ assert.equal(edgeBobAlice.edgeType, "KNOWS");+ assert.equal(graph.source("edge_bob_alice"), "bob");+ assert.equal(graph.target("edge_bob_alice"), "alice");++ assert.equal(edgeAcmeNewYork.edgeType, "LOCATED_IN");+ assert.equal(graph.source("edge_acme_new_york"), "acme");+ assert.equal(graph.target("edge_acme_new_york"), "new_york");+});++test("display graph resolution preserves all 4 nodes and 3 edges in full view", () => {+ loadDeterministicTestGraph();++ const { graph: displayGraph } = resolveDisplayGraph("", [], [], "full", { aggregationEnabled: false });++ assert.equal(displayGraph.order, 4);+ assert.equal(displayGraph.size, 3);+ assert.ok(displayGraph.hasNode("alice"));+ assert.ok(displayGraph.hasNode("bob"));+ assert.ok(displayGraph.hasNode("acme"));+ assert.ok(displayGraph.hasNode("new_york"));+ assert.ok(displayGraph.hasEdge("edge_alice_acme"));+ assert.ok(displayGraph.hasEdge("edge_bob_alice"));+ assert.ok(displayGraph.hasEdge("edge_acme_new_york"));+});++test("structural distance calculation resolves correct hop counts across the 3-edge chain", () => {+ loadDeterministicTestGraph();++ // From Bob: Bob (0) -> Alice (1) -> Acme (2) -> New York (3)+ const distances = buildStructuralDistanceSnapshot(graph, "bob", 3);++ assert.equal(distances.bob, 0);+ assert.equal(distances.alice, 1);+ assert.equal(distances.acme, 2);+ assert.equal(distances.new_york, 3);+});++test("edge rendering and canonical edge labels remain legible across zoom tiers and inspection modes", () => {+ loadDeterministicTestGraph();++ const canonicalEdges = [+ { id: "edge_alice_acme", source: "alice", target: "acme", label: "WORKS_AT" },+ { id: "edge_bob_alice", source: "bob", target: "alice", label: "KNOWS" },+ { id: "edge_acme_new_york", source: "acme", target: "new_york", label: "LOCATED_IN" },+ ];++ // 1. Edge attributes preserve canonical edgeType labels in graph store:+ for (const item of canonicalEdges) {+ const attrs = graph.getEdgeAttributes(item.id);+ assert.equal(attrs.edgeType, item.label, `Edge ${item.id} must have edgeType ${item.label}`);+ assert.equal(graph.source(item.id), item.source);+ assert.equal(graph.target(item.id), item.target);+ }++ // 2. In active context / neighbor state across all zoom tiers (overview, structure, inspection):+ const allTiers: GraphZoomTier[] = ["overview", "structure", "inspection"];+ for (const tier of allTiers) {+ for (const item of canonicalEdges) {+ const attrs = graph.getEdgeAttributes(item.id);+ const contextStyle = resolveEdgeElementStyle(+ GRAPH_THEME,+ tier,+ "neighbor",+ attrs,+ item.source,+ item.target,+ "full",+ item.id,+ );++ assert.equal(+ contextStyle.hidden,+ false,+ `Edge ${item.id} (${item.label}) in context state 'neighbor' must be visible in zoom tier '${tier}'`,+ );+ assert.ok(+ contextStyle.size !== undefined && contextStyle.size > 0,+ `Edge ${item.id} (${item.label}) must have positive render size in zoom tier '${tier}'`,+ );+ }+ }++ // 3. In selected state in inspection zoom tier (close examination of edge details and label):+ for (const item of canonicalEdges) {+ const attrs = graph.getEdgeAttributes(item.id);+ const selectedStyle = resolveEdgeElementStyle(+ GRAPH_THEME,+ "inspection",+ "selected",+ attrs,+ item.source,+ item.target,+ "full",+ item.id,+ "selected",+ );++ assert.equal(+ selectedStyle.hidden,+ false,+ `Selected edge ${item.id} (${item.label}) must be visible in inspection zoom tier`,+ );+ assert.ok(+ selectedStyle.size !== undefined && selectedStyle.size > 0,+ `Selected edge ${item.id} (${item.label}) must have positive render size`,+ );+ }++ // 4. Verify inspection zoom tier camera and arrow rendering settings+ assert.equal(GRAPH_THEME.zoomTiers.inspection.showContextualArrows, true);+ assert.equal(GRAPH_THEME.zoomTiers.inspection.showCurves, true);+});++test("node hover interaction preserves edge visibility and highlights canonical incident edge types", () => {+ loadDeterministicTestGraph();++ // Scenario 1: Hover Alice+ // Incident edges: Alice -> Acme (WORKS_AT) and Bob -> Alice (KNOWS)+ const aliceAttrs = graph.getNodeAttributes("alice");+ const aliceVisual = resolveNodeVisualState("alice", "structure", "alice", "", "", new Set(), new Set(), new Set());+ assert.equal(aliceVisual, "hovered");++ const aliceStyle = resolveNodeElementStyle(GRAPH_THEME, "structure", "hovered", aliceAttrs, "Alice");+ assert.equal(aliceStyle.forceLabel, true, "Hovered Alice must force-render label");+ assert.equal(aliceStyle.label, "Alice");+ assert.equal(aliceStyle.showHalo, true, "Hovered Alice must show interactive halo");++ const aliceIncidentEdges = new Set(["edge_alice_acme", "edge_bob_alice"]);++ // Edge Alice -> Acme (WORKS_AT) under Alice hover+ const aliceAcmeAttrs = graph.getEdgeAttributes("edge_alice_acme");+ assert.equal(aliceAcmeAttrs.edgeType, "WORKS_AT");+ const aliceAcmeState = resolveEdgeVisualState(+ "edge_alice_acme",+ "alice",+ "acme",+ "structure",+ "alice",+ "",+ "",+ new Set(),+ new Set(),+ aliceIncidentEdges,+ );+ assert.equal(aliceAcmeState, "hovered");+ const aliceAcmeStyle = resolveEdgeElementStyle(+ GRAPH_THEME,+ "structure",+ "hovered",+ aliceAcmeAttrs,+ "alice",+ "acme",+ "full",+ "edge_alice_acme",+ );+ assert.equal(aliceAcmeStyle.hidden, false, "Incident edge WORKS_AT must remain visible on hover");+ assert.ok(aliceAcmeStyle.size !== undefined && aliceAcmeStyle.size > 0);++ // Edge Bob -> Alice (KNOWS) under Alice hover+ const bobAliceAttrs = graph.getEdgeAttributes("edge_bob_alice");+ assert.equal(bobAliceAttrs.edgeType, "KNOWS");+ const bobAliceState = resolveEdgeVisualState(+ "edge_bob_alice",+ "bob",+ "alice",+ "structure",+ "alice",+ "",+ "",+ new Set(),+ new Set(),+ aliceIncidentEdges,+ );+ assert.equal(bobAliceState, "hovered");+ const bobAliceStyle = resolveEdgeElementStyle(+ GRAPH_THEME,+ "structure",+ "hovered",+ bobAliceAttrs,+ "bob",+ "alice",+ "full",+ "edge_bob_alice",+ );+ assert.equal(bobAliceStyle.hidden, false, "Incident edge KNOWS must remain visible on hover");++ // Non-incident edge Acme -> New York (LOCATED_IN) under Alice hover+ const acmeNyAttrs = graph.getEdgeAttributes("edge_acme_new_york");+ assert.equal(acmeNyAttrs.edgeType, "LOCATED_IN");+ const acmeNyState = resolveEdgeVisualState(+ "edge_acme_new_york",+ "acme",+ "new_york",+ "structure",+ "alice",+ "",+ "",+ new Set(),+ new Set(),+ aliceIncidentEdges,+ );+ assert.equal(acmeNyState, "muted");++ // Scenario 2: Hover Acme+ // Incident edges: Alice -> Acme (WORKS_AT) and Acme -> New York (LOCATED_IN)+ const acmeAttrs = graph.getNodeAttributes("acme");+ const acmeStyle = resolveNodeElementStyle(GRAPH_THEME, "structure", "hovered", acmeAttrs, "Acme");+ assert.equal(acmeStyle.forceLabel, true);+ assert.equal(acmeStyle.label, "Acme");++ const acmeIncidentEdges = new Set(["edge_alice_acme", "edge_acme_new_york"]);+ const acmeNyHoverState = resolveEdgeVisualState(+ "edge_acme_new_york",+ "acme",+ "new_york",+ "structure",+ "acme",+ "",+ "",+ new Set(),+ new Set(),+ acmeIncidentEdges,+ );+ assert.equal(acmeNyHoverState, "hovered");+ const acmeNyHoverStyle = resolveEdgeElementStyle(+ GRAPH_THEME,+ "structure",+ "hovered",+ acmeNyAttrs,+ "acme",+ "new_york",+ "full",+ "edge_acme_new_york",+ );+ assert.equal(acmeNyHoverStyle.hidden, false, "Incident edge LOCATED_IN must remain visible on hover");++ // Scenario 3: Hover Bob+ // Incident edge: Bob -> Alice (KNOWS)+ const bobAttrs = graph.getNodeAttributes("bob");+ const bobStyle = resolveNodeElementStyle(GRAPH_THEME, "structure", "hovered", bobAttrs, "Bob");+ assert.equal(bobStyle.forceLabel, true);+ assert.equal(bobStyle.label, "Bob");++ const bobIncidentEdges = new Set(["edge_bob_alice"]);+ const bobAliceHoverState = resolveEdgeVisualState(+ "edge_bob_alice",+ "bob",+ "alice",+ "structure",+ "bob",+ "",+ "",+ new Set(),+ new Set(),+ bobIncidentEdges,+ );+ assert.equal(bobAliceHoverState, "hovered");+});++test("edge selection maintains canonical edge type labels and active visual state", () => {+ loadDeterministicTestGraph();++ const edgeCases = [+ { id: "edge_alice_acme", source: "alice", target: "acme", label: "WORKS_AT" },+ { id: "edge_bob_alice", source: "bob", target: "alice", label: "KNOWS" },+ { id: "edge_acme_new_york", source: "acme", target: "new_york", label: "LOCATED_IN" },+ ];++ for (const { id, source, target, label } of edgeCases) {+ const attrs = graph.getEdgeAttributes(id);+ assert.equal(attrs.edgeType, label);++ const visualState = resolveEdgeVisualState(+ id,+ source,+ target,+ "inspection",+ null,+ "",+ id, // selected edge+ new Set(),+ new Set(),+ );+ assert.equal(visualState, "selected", `Selected edge ${id} must resolve to 'selected' state`);++ const style = resolveEdgeElementStyle(+ GRAPH_THEME,+ "inspection",+ "selected",+ attrs,+ source,+ target,+ "full",+ id,+ "selected",+ );++ assert.equal(style.hidden, false, `Selected edge ${id} (${label}) must not be hidden`);+ assert.ok(+ style.size !== undefined && style.size > 0,+ `Selected edge ${id} (${label}) must have positive render size`,+ );+ }+});++test("node labels remain forced visible during hover, selection, and inspection zoom tier", () => {+ loadDeterministicTestGraph();++ const nodes = ["alice", "bob", "acme", "new_york"];++ for (const nid of nodes) {+ const attrs = graph.getNodeAttributes(nid);++ // Hover state forces label visibility+ const hoverForcesLabel = shouldForceNodeLabel(GRAPH_THEME, "structure", "hovered", attrs, 0);+ assert.equal(hoverForcesLabel, true, `Node ${nid} label must force visible on hover`);++ // Selected state forces label visibility+ const selectForcesLabel = shouldForceNodeLabel(GRAPH_THEME, "structure", "selected", attrs, 0);+ assert.equal(selectForcesLabel, true, `Node ${nid} label must force visible on selection`);++ // Resolved style emits actual string label+ const style = resolveNodeElementStyle(GRAPH_THEME, "inspection", "hovered", attrs, attrs.label);+ assert.equal(style.forceLabel, true);+ assert.equal(style.label, attrs.label);+ }+});diff --git a/tests/explorer/test_explorer_deterministic_rendering_e2e.py b/tests/explorer/test_explorer_deterministic_rendering_e2e.pynew file mode 100644index 00000000..b4b99c3c--- /dev/null+++ b/tests/explorer/test_explorer_deterministic_rendering_e2e.py@@ -0,0 +1,219 @@+"""+End-to-end integration test for deterministic Explorer rendering (Issue #1037).++Validates:+1. Building the canonical 4-node, 3-edge graph using ContextGraph.+2. Serialization via save_to_file().+3. Reloading via load_from_file() and GraphSession.from_file() without mutation.+4. Explorer HTTP API serving exact nodes, edges, edge types, and connectivity.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from semantica.context.context_graph import ContextGraph+from semantica.explorer.app import create_app+from semantica.explorer.session import GraphSession++try:+ from starlette.testclient import TestClient+except ImportError:+ pytest.skip(+ "starlette TestClient required. Install semantica[explorer].",+ allow_module_level=True,+ )+++def _build_deterministic_graph() -> ContextGraph:+ """Build the exact graph requested in Semantica #1037."""+ graph = ContextGraph(advanced_analytics=False)++ graph.add_node("alice", "Person", content="Alice")+ graph.add_node("bob", "Person", content="Bob")+ graph.add_node("acme", "Organization", content="Acme")+ graph.add_node("new_york", "Location", content="New York")++ graph.add_edge("alice", "acme", edge_type="WORKS_AT")+ graph.add_edge("bob", "alice", edge_type="KNOWS")+ graph.add_edge("acme", "new_york", edge_type="LOCATED_IN")++ return graph+++class TestExplorerDeterministicRenderingE2E:+ """E2E suite for deterministic graph rendering and session loading."""++ def test_build_and_in_memory_structure(self):+ graph = _build_deterministic_graph()++ assert len(graph.nodes) == 4+ assert len(graph.edges) == 3++ node_map = {+ nid: (node.node_type, node.content) for nid, node in graph.nodes.items()+ }+ assert node_map["alice"] == ("Person", "Alice")+ assert node_map["bob"] == ("Person", "Bob")+ assert node_map["acme"] == ("Organization", "Acme")+ assert node_map["new_york"] == ("Location", "New York")++ edge_tuples = {(e.source_id, e.target_id, e.edge_type) for e in graph.edges}+ assert edge_tuples == {+ ("alice", "acme", "WORKS_AT"),+ ("bob", "alice", "KNOWS"),+ ("acme", "new_york", "LOCATED_IN"),+ }++ def test_serialization_and_deserialization(self, tmp_path: Path):+ graph = _build_deterministic_graph()+ output_file = tmp_path / "explorer_deterministic_graph.json"++ graph.save_to_file(str(output_file))+ assert output_file.exists()++ # Validate JSON structure+ with open(output_file, "r", encoding="utf-8") as f:+ raw_data = json.load(f)++ assert "nodes" in raw_data+ assert "edges" in raw_data+ assert len(raw_data["nodes"]) == 4+ assert len(raw_data["edges"]) == 3++ # Reload with ContextGraph.load_from_file+ reloaded_graph = ContextGraph(advanced_analytics=False)+ reloaded_graph.load_from_file(str(output_file))++ assert len(reloaded_graph.nodes) == 4+ assert len(reloaded_graph.edges) == 3+ reloaded_nodes = {+ nid: (node.node_type, node.content)+ for nid, node in reloaded_graph.nodes.items()+ }+ assert reloaded_nodes["alice"] == ("Person", "Alice")+ assert reloaded_nodes["bob"] == ("Person", "Bob")+ assert reloaded_nodes["acme"] == ("Organization", "Acme")+ assert reloaded_nodes["new_york"] == ("Location", "New York")++ reloaded_edges = {+ (e.source_id, e.target_id, e.edge_type) for e in reloaded_graph.edges+ }+ assert reloaded_edges == {+ ("alice", "acme", "WORKS_AT"),+ ("bob", "alice", "KNOWS"),+ ("acme", "new_york", "LOCATED_IN"),+ }++ def test_session_loading_and_stats(self, tmp_path: Path):+ graph = _build_deterministic_graph()+ output_file = tmp_path / "explorer_deterministic_graph.json"+ graph.save_to_file(str(output_file))++ session = GraphSession.from_file(str(output_file))+ stats = session.get_stats()++ assert stats["node_count"] == 4+ assert stats["edge_count"] == 3++ def test_explorer_api_endpoints_with_deterministic_graph(self, tmp_path: Path):+ graph = _build_deterministic_graph()+ output_file = tmp_path / "explorer_deterministic_graph.json"+ graph.save_to_file(str(output_file))++ session = GraphSession.from_file(str(output_file))+ app = create_app(session=session)++ with TestClient(app) as client:+ # 1. Health & Info+ health = client.get("/api/health")+ assert health.status_code == 200+ assert health.json() == {"status": "ok"}++ info = client.get("/api/info")+ assert info.status_code == 200+ assert info.json()["status"] == "active"++ # 2. Stats+ stats = client.get("/api/graph/stats")+ assert stats.status_code == 200+ stats_data = stats.json()+ assert stats_data["node_count"] == 4+ assert stats_data["edge_count"] == 3++ # 3. Nodes endpoint+ nodes_res = client.get("/api/graph/nodes")+ assert nodes_res.status_code == 200+ nodes_data = nodes_res.json()+ assert nodes_data["total"] == 4+ assert len(nodes_data["nodes"]) == 4++ returned_nodes = {+ n["id"]: (n["type"], n["content"]) for n in nodes_data["nodes"]+ }+ assert returned_nodes["alice"] == ("Person", "Alice")+ assert returned_nodes["bob"] == ("Person", "Bob")+ assert returned_nodes["acme"] == ("Organization", "Acme")+ assert returned_nodes["new_york"] == ("Location", "New York")++ # 4. Individual node lookups+ for node_id in ["alice", "bob", "acme", "new_york"]:+ node_res = client.get(f"/api/graph/node/{node_id}")+ assert node_res.status_code == 200+ assert node_res.json()["id"] == node_id++ # 5. Edges endpoint+ edges_res = client.get("/api/graph/edges")+ assert edges_res.status_code == 200+ edges_data = edges_res.json()+ assert edges_data["total"] == 3+ assert len(edges_data["edges"]) == 3++ returned_edges = {+ (e["source"], e["target"], e["type"]) for e in edges_data["edges"]+ }+ assert returned_edges == {+ ("alice", "acme", "WORKS_AT"),+ ("bob", "alice", "KNOWS"),+ ("acme", "new_york", "LOCATED_IN"),+ }++ def test_deterministic_graph_auth_enforcement(self, tmp_path: Path, monkeypatch):+ graph = _build_deterministic_graph()+ output_file = tmp_path / "explorer_deterministic_graph.json"+ graph.save_to_file(str(output_file))++ session = GraphSession.from_file(str(output_file))+ app = create_app(session=session)++ with TestClient(app) as client:+ # 1. Unconfigured auth (no SEMANTICA_ALLOW_ANONYMOUS, no SEMANTICA_API_KEY) -> 503+ monkeypatch.delenv("SEMANTICA_ALLOW_ANONYMOUS", raising=False)+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)+ unconfigured_res = client.get("/api/graph/stats")+ assert unconfigured_res.status_code == 503++ # 2. Configured SEMANTICA_API_KEY without header -> 401+ test_key = "secret-test-key-1037"+ monkeypatch.setenv("SEMANTICA_API_KEY", test_key)+ unauthorized_res = client.get("/api/graph/nodes")+ assert unauthorized_res.status_code == 401++ # 3. Configured SEMANTICA_API_KEY with valid X-API-Key header -> 200+ authorized_res = client.get(+ "/api/graph/nodes",+ headers={"X-API-Key": test_key},+ )+ assert authorized_res.status_code == 200+ assert authorized_res.json()["total"] == 4++ # 4. Explicit local development opt-in: SEMANTICA_ALLOW_ANONYMOUS=true -> 200 without header+ monkeypatch.setenv("SEMANTICA_ALLOW_ANONYMOUS", "true")+ monkeypatch.delenv("SEMANTICA_API_KEY", raising=False)+ anon_res = client.get("/api/graph/edges")+ assert anon_res.status_code == 200+ assert anon_res.json()["total"] == 3+