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
Merge branch 'main' into fix/cg-thpag
Mohd Kaifa0e7e9a1c941
diff --cc pyproject.tomlindex 1e03d95f,1c0f4181..5a9eb64f--- a/pyproject.toml+++ b/pyproject.toml@@@ -213,7 -213,7 +213,8 @@@ explorer-lite =# Everythingall = [+ "semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,explorer]"+ "semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,explorer]","semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,agno]"]diff --cc semantica/explorer/app.pyindex ba797d75,0d189165..a3d37ec0--- a/semantica/explorer/app.py+++ b/semantica/explorer/app.py@@@ -11,7 -10,7 +11,8 @@@ from contextlib import asynccontextmanafrom pathlib import Pathfrom typing import Optional+from fastapi import FastAPI, Request+ from fastapi import FastAPI, HTTPException, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse@@@ -73,10 -68,14 +74,18 @@@ def create_app(session: Optional[GraphS@app.exception_handler(Exception)async def generic_error_handler(request: Request, exc: Exception):+ tb = traceback.format_exc()+ return JSONResponse(+ status_code=500,+ content={"detail": f"Internal Server Error: {exc}", "traceback": tb},+ # Let FastAPI's built-in HTTPException handler take precedence so that+ # responses from dependency injection (e.g. 503 from get_session) are+ # not swallowed and converted to 500.+ if isinstance(exc, HTTPException):+ raise exc+ return JSONResponse(+ status_code=500,+ content={"detail": "Internal Server Error"},)from .routes.graph import router as graph_router@@@ -122,10 -118,9 +131,14 @@@"status": "active",}++ static_dir = Path(__file__).resolve().parent.parent / "static"+ if static_dir.is_dir():+ from fastapi.staticfiles import StaticFiles+ app.mount("/", StaticFiles(directory=str(static_dir), html=True), name="static")+ static_dir = Path(__file__).resolve().parent.parent / "static"+ static_dir.mkdir(parents=True, exist_ok=True)+ from fastapi.staticfiles import StaticFiles+ app.mount("/", StaticFiles(directory=str(static_dir), html=True), name="static")return appdiff --cc semantica/explorer/dependencies.pyindex b59c72d9,5e29f07e..abca55d8--- a/semantica/explorer/dependencies.py+++ b/semantica/explorer/dependencies.py@@@ -5,7 -5,7 +5,8 @@@ Provides ``Depends()``-compatible callacurrent ``GraphSession`` and ``ConnectionManager`` into route handlers."""+from fastapi import Request+ from fastapi import Request, HTTPException, statusfrom .session import GraphSessionfrom .ws import ConnectionManagerdiff --cc semantica/explorer/routes/analytics.pyindex dc7c584e,92917a4e..2458a0af--- a/semantica/explorer/routes/analytics.py+++ b/semantica/explorer/routes/analytics.py@@@ -42,7 -24,7 +42,8 @@@ async def get_analytics):"""Compute graph analytics (centrality, community, connectivity)."""requested = set((metrics or "centrality,community,connectivity").split(","))+ graph_dict = await asyncio.to_thread(_build_graph_dict, session)+ graph_dict = await asyncio.to_thread(session.build_graph_dict)result: dict = {}if "centrality" in requested and session.centrality is not None:@@@ -84,7 -66,7 +85,8 @@@ async def validate_graphif validator is None:return ValidationReportResponse(valid=True, error_count=0, warning_count=0, issues=[])+ graph_dict = await asyncio.to_thread(_build_graph_dict, session)+ graph_dict = await asyncio.to_thread(session.build_graph_dict)try:report = await asyncio.to_thread(validator.validate, graph_dict)diff --cc semantica/explorer/routes/annotations.pyindex 35dd2a30,c189a89f..b224a15f--- a/semantica/explorer/routes/annotations.py+++ b/semantica/explorer/routes/annotations.py@@@ -38,21 -38,9 +38,24 @@@ async def create_annotationraise KeyError(body.node_id)ann_data = body.model_dump()+ ann_id = await asyncio.to_thread(session.add_annotation, ann_data)+++ anns = await asyncio.to_thread(session.get_annotations)+ for a in anns:+ if a.get("annotation_id") == ann_id:+ return AnnotationResponse(**a)++ return AnnotationResponse(+ annotation_id=ann_id,+ node_id=body.node_id,+ content=body.content,+ tags=body.tags,+ visibility=body.visibility,+ )+ # add_annotation mutates ann_data in-place, adding annotation_id and created_at.+ await asyncio.to_thread(session.add_annotation, ann_data)+ return AnnotationResponse(**ann_data)@router.delete("/{annotation_id}", status_code=204)diff --cc semantica/explorer/routes/decisions.pyindex 7d502d5c,71c9b0a6..293b5443--- a/semantica/explorer/routes/decisions.py+++ b/semantica/explorer/routes/decisions.py@@@ -149,20 -149,34 +149,45 @@@ async def check_compliance"""Check policy compliance for a decision.+ Returns a stub result when no PolicyEngine is wired up.+ Inspects edges of type ``violates``, ``non_compliant``, or ``breaches``+ originating from the decision node. Returns ``compliant=True`` when no+ such edges are found, which is the correct result for graphs that have+ no policy-violation edges defined."""node = await asyncio.to_thread(session.get_node, decision_id)if node is None:raise KeyError(decision_id)++ try:+ from ...context.policy_engine import PolicyEngine+ except ImportError:+ pass++ return ComplianceResponse(+ decision_id=decision_id,+ compliant=True,+ violations=[],+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)++ _VIOLATION_TYPES = {"violates", "non_compliant", "breaches"}+ violation_edges = [+ e for e in edges+ if e.get("source") == decision_id and e.get("type") in _VIOLATION_TYPES+ ]++ violations = [+ {+ "policy_id": e.get("target"),+ "type": e.get("type"),+ "metadata": e.get("metadata", {}),+ }+ for e in violation_edges+ ]++ return ComplianceResponse(+ decision_id=decision_id,+ compliant=len(violations) == 0,+ violations=violations,)diff --cc semantica/explorer/routes/enrich.pyindex 86eb2892,91fff7ca..936b3a6d--- a/semantica/explorer/routes/enrich.py+++ b/semantica/explorer/routes/enrich.py@@@ -65,29 -65,43 +65,66 @@@ async def predict_linksif node is None:raise KeyError(body.node_id)+ # Build graph dict+ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)+ graph_dict = {+ "entities": [{"id": n.get("id"), "type": n.get("type", "entity")} for n in nodes],+ "relationships": [+ {"source": e.get("source"), "target": e.get("target"),+ "type": e.get("type", "related_to")}+ for e in edges+ ],+ }++ try:+ predictions = await asyncio.to_thread(+ predictor.predict_links, graph_dict, body.node_id, top_n=body.top_n+ )+ pred_list = predictions if isinstance(predictions, list) else []+ return LinkPredictionResponse(+ node_id=body.node_id,+ predictions=[_safe_dict(p) for p in pred_list],+ )+ except Exception as exc:+ raise ValueError(f"Link prediction failed: {exc}")+ # Get all nodes and edges to build candidate pairs manually,+ # because ContextGraph.nodes is a dict (not callable) and is incompatible+ # with LinkPredictor._get_all_nodes which requires nodes() or get_all_nodes().+ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)++ # Pre-compute already-connected node IDs so we skip them.+ # (LinkPredictor._edge_exists returns False for ContextGraph since it has no+ # has_edge/get_edge method, so we handle exclusion here instead.)+ existing_neighbours = {+ e.get("target") for e in edges if e.get("source") == body.node_id+ } | {+ e.get("source") for e in edges if e.get("target") == body.node_id+ }++ # Score each candidate via score_link (which works with ContextGraph because+ # it falls back to has_node / get_neighbors).+ scored = []+ for n in nodes:+ candidate = n.get("id")+ if not candidate or candidate == body.node_id or candidate in existing_neighbours:+ continue+ try:+ score = predictor.score_link(session.graph, body.node_id, candidate)+ if score > 0:+ scored.append(+ {"target": candidate, "score": score, "type": n.get("type", "entity")}+ )+ except Exception:+ continue++ scored.sort(key=lambda x: x["score"], reverse=True)++ return LinkPredictionResponse(+ node_id=body.node_id,+ predictions=scored[: body.top_n],+ )@router.post("/api/enrich/dedup", response_model=DedupResponse)@@@ -100,11 -114,16 +137,21 @@@ async def detect_duplicatesfrom ...deduplication import DuplicateDetectordetector = DuplicateDetector()+ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)++ entities = [+ {"id": n.get("id"), "text": n.get("content", n.get("id", "")),+ "type": n.get("type", "entity")}+ # Use asyncio.to_thread — get_nodes acquires an RLock and must not block+ # the event loop.+ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)++ entities = [+ {+ "id": n.get("id"),+ "text": n.get("content", n.get("id", "")),+ "type": n.get("type", "entity"),+ }for n in nodes]diff --cc semantica/explorer/routes/export_import.pyindex c326515d,11062275..587afa56--- a/semantica/explorer/routes/export_import.py+++ b/semantica/explorer/routes/export_import.py@@@ -3,8 -3,8 +3,10 @@@ Export & import routes"""import asyncio+import io+import json+ import json+ import osimport tempfilefrom typing import Optional@@@ -84,8 -51,7 +86,9 @@@ async def export_graphfunc_name, content_type, ext = _FORMAT_MAP[fmt]+ kg = await asyncio.to_thread(_build_kg_dict, session, body.node_ids)++ kg = await asyncio.to_thread(session.build_graph_dict, body.node_ids)try:from ...export.methods import (@@@ -106,20 -72,21 +109,35 @@@if export_fn is None:raise ValueError(f"Export function {func_name} not found.")+ # Write to a temp file, read back content.+ with tempfile.NamedTemporaryFile(suffix=ext, delete=False, mode="w") as tmp:+ tmp_path = tmp.name++ await asyncio.to_thread(export_fn, kg, tmp_path)++ with open(tmp_path, "r", encoding="utf-8", errors="replace") as fh:+ content = fh.read()++ import os+ os.unlink(tmp_path)++ except ImportError:++ # Write to a temp file; always clean up even if export or read fails.+ tmp_path = None+ try:+ with tempfile.NamedTemporaryFile(suffix=ext, delete=False, mode="w") as tmp:+ tmp_path = tmp.name++ await asyncio.to_thread(export_fn, kg, tmp_path)++ with open(tmp_path, "r", encoding="utf-8", errors="replace") as fh:+ content = fh.read()+ finally:+ if tmp_path and os.path.exists(tmp_path):+ os.unlink(tmp_path)++ except ImportError:content = json.dumps(kg, indent=2, default=str)content_type = "application/json"ext = ".json"@@@ -151,43 -118,14 +169,51 @@@ async def import_filetry:if filename.endswith(".json") or filename.endswith(".jsonld"):data = json.loads(content)+++ raw_nodes = data.get("nodes", data.get("entities", []))+ raw_edges = data.get("edges", data.get("relationships", []))+++ # KG export uses {id, type, text, metadata}+ # ContextGraph.add_nodes expects {id, type, properties: {content, ...}}+ nodes = []+ for n in raw_nodes:+ if "properties" in n:+ nodes.append(n)+ else:+ nodes.append({+ "id": n.get("id"),+ "type": n.get("type", "entity"),+ "properties": {+ "content": n.get("text", n.get("content", n.get("id", ""))),+ **(n.get("metadata") or {}),+ },+ })++ # KG export uses {source, target, type, metadata}+ # ContextGraph.add_edges expects {source_id, target_id, type, weight, properties}+ edges = []+ for r in raw_edges:+ src = r.get("source_id", r.get("source"))+ tgt = r.get("target_id", r.get("target"))+ if not src or not tgt:+ continue+ edges.append({+ "source_id": src,+ "target_id": tgt,+ "type": r.get("type", "related_to"),+ "weight": r.get("weight", 1.0),+ "properties": r.get("metadata") or r.get("properties") or {},+ })+ nodes = data.get("nodes", data.get("entities", []))+ edges = data.get("edges", data.get("relationships", []))++ for edge in edges:+ if "source" in edge and "source_id" not in edge:+ edge["source_id"] = edge["source"]+ if "target" in edge and "target_id" not in edge:+ edge["target_id"] = edge["target"]added_nodes = await asyncio.to_thread(session.add_nodes, nodes)added_edges = await asyncio.to_thread(session.add_edges, edges)diff --cc semantica/explorer/routes/graph.pyindex 3b6a0a77,468e9712..b0b8bd4c--- a/semantica/explorer/routes/graph.py+++ b/semantica/explorer/routes/graph.py@@@ -138,13 -138,17 +138,24 @@@ async def find_pathif pf is None:raise ValueError("PathFinder not available — KG extras may not be installed.")+ graph_data = await asyncio.to_thread(_build_graph_dict, session)++ result = await asyncio.to_thread(+ pf.find_shortest_path, graph_data, node_id, target+ )++ path_nodes = result.get("path", []) if isinstance(result, dict) else []+ graph_data = await asyncio.to_thread(session.build_graph_dict)++ # Select algorithm: dijkstra for weighted shortest path, bfs otherwise.+ if algorithm.lower() == "dijkstra":+ path_fn = pf.dijkstra_shortest_path+ else:+ path_fn = pf.bfs_shortest_path++ result = await asyncio.to_thread(path_fn, graph_data, node_id, target)++ path_nodes = result.get("path", []) if isinstance(result, dict) else (result or [])total_weight = result.get("total_weight", 0.0) if isinstance(result, dict) else 0.0return PathResponse(diff --cc semantica/explorer/routes/temporal.pyindex 844b9221,d0ac0149..5753e143--- a/semantica/explorer/routes/temporal.py+++ b/semantica/explorer/routes/temporal.py@@@ -103,8 -103,8 +103,10 @@@ async def temporal_patternsdetector = TemporalPatternDetector()+ nodes, _ = session.get_nodes(skip=0, limit=999_999)+ edges, _ = session.get_edges(skip=0, limit=999_999)+ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)graph_dict = {"entities": [{"id": n.get("id"), "type": n.get("type"), "metadata": n.get("metadata", {})}@@@ -121,5 -121,10 +123,11 @@@if isinstance(patterns, dict):patterns = patterns.get("patterns", [])return TemporalPatternResponse(patterns=patterns if isinstance(patterns, list) else [])+ except Exception:+ except ImportError:+ # TemporalPatternDetector is an optional KG extra; return empty gracefully.+ return TemporalPatternResponse(patterns=[])+ except Exception as exc:+ import logging+ logging.getLogger(__name__).warning("temporal_patterns failed: %s", exc, exc_info=True)return TemporalPatternResponse(patterns=[])diff --cc semantica/explorer/session.pyindex 4ca15333,191442d9..e5f90465--- a/semantica/explorer/session.py+++ b/semantica/explorer/session.py@@@ -36,17 -36,16 +36,21 @@@ class GraphSessionThread safety: all mutations to the graph or the annotations storemust go through methods on this class, which are protected by an+ ``RLock``.+ ``RLock``. Lazy analytics properties are also initialised under the+ same lock to prevent double-instantiation under concurrent requests."""def __init__(self, graph: ContextGraph) -> None:self.graph = graphself._lock = threading.RLock()++ self.annotations: Dict[str, Dict[str, Any]] = {}+++ self.annotations: Dict[str, Dict[str, Any]] = {}+self._centrality: Any = Noneself._community: Any = Noneself._connectivity: Any = None@@@ -64,55 -62,69 +68,118 @@@graph.load_from_file(path)return cls(graph)++ @property+ def centrality(self) -> Any:+ if self._centrality is None and _KG_AVAILABLE:+ self._centrality = CentralityCalculator()+ return self._centrality++ @property+ def community(self) -> Any:+ if self._community is None and _KG_AVAILABLE:+ self._community = CommunityDetector()+ return self._community++ @property+ def connectivity(self) -> Any:+ if self._connectivity is None and _KG_AVAILABLE:+ self._connectivity = ConnectivityAnalyzer()+ return self._connectivity++ @property+ def path_finder(self) -> Any:+ if self._path_finder is None and _KG_AVAILABLE:+ self._path_finder = PathFinder()+ return self._path_finder++ @property+ def node_embedder(self) -> Any:+ if self._node_embedder is None and _KG_AVAILABLE:+ self._node_embedder = NodeEmbedder()+ return self._node_embedder++ @property+ def similarity(self) -> Any:+ if self._similarity is None and _KG_AVAILABLE:+ self._similarity = SimilarityCalculator()+ return self._similarity++ @property+ def link_predictor(self) -> Any:+ if self._link_predictor is None and _KG_AVAILABLE:+ self._link_predictor = LinkPredictor()+ return self._link_predictor++ @property+ def validator(self) -> Any:+ if self._validator is None and _KG_AVAILABLE:+ self._validator = GraphValidator()+ return self._validator++ # ------------------------------------------------------------------+ # Lazy analytics properties (thread-safe double-checked locking)+ # ------------------------------------------------------------------++ @property+ def centrality(self) -> Any:+ with self._lock:+ if self._centrality is None and _KG_AVAILABLE:+ self._centrality = CentralityCalculator()+ return self._centrality++ @property+ def community(self) -> Any:+ with self._lock:+ if self._community is None and _KG_AVAILABLE:+ self._community = CommunityDetector()+ return self._community++ @property+ def connectivity(self) -> Any:+ with self._lock:+ if self._connectivity is None and _KG_AVAILABLE:+ self._connectivity = ConnectivityAnalyzer()+ return self._connectivity++ @property+ def path_finder(self) -> Any:+ with self._lock:+ if self._path_finder is None and _KG_AVAILABLE:+ self._path_finder = PathFinder()+ return self._path_finder++ @property+ def node_embedder(self) -> Any:+ with self._lock:+ if self._node_embedder is None and _KG_AVAILABLE:+ self._node_embedder = NodeEmbedder()+ return self._node_embedder++ @property+ def similarity(self) -> Any:+ with self._lock:+ if self._similarity is None and _KG_AVAILABLE:+ self._similarity = SimilarityCalculator()+ return self._similarity++ @property+ def link_predictor(self) -> Any:+ with self._lock:+ if self._link_predictor is None and _KG_AVAILABLE:+ self._link_predictor = LinkPredictor()+ return self._link_predictor++ @property+ def validator(self) -> Any:+ with self._lock:+ if self._validator is None and _KG_AVAILABLE:+ self._validator = GraphValidator()+ return self._validator++ # ------------------------------------------------------------------+ # Graph read helpers+ # ------------------------------------------------------------------def get_node(self, node_id: str) -> Optional[Dict[str, Any]]:"""Get a single node by ID, or ``None``."""@@@ -128,23 -140,20 +195,37 @@@) -> tuple[list[dict[str, Any]], int]:"""Return a paginated slice of nodes and the total count."""with self._lock:+ # We fetch all nodes if there is a search filter as we need to filter them in memory,+ # otherwise we let the context graph handle the pagination natively.+ if search:+ all_nodes = self.graph.find_nodes(node_type=node_type)+ search_lower = search.lower()+ all_nodes = [+ n for n in all_nodes+ if search_lower in n.get("id", "").lower()+ or search_lower in n.get("content", "").lower()+ or search_lower in str(n.get("metadata", {})).lower()+ ]+ total = len(all_nodes)+ page = all_nodes[skip: skip + limit]+ else:+ total = self.graph.stats().get("node_types", {}).get(node_type, 0) if node_type else self.graph.stats().get("node_count", 0)+ page = self.graph.find_nodes(node_type=node_type, skip=skip, limit=limit)++ all_nodes = self.graph.find_nodes(node_type=node_type)++ # Optional keyword filter+ if search:+ search_lower = search.lower()+ all_nodes = [+ n for n in all_nodes+ if search_lower in n.get("id", "").lower()+ or search_lower in n.get("content", "").lower()+ or search_lower in str(n.get("metadata", {})).lower()+ ]++ total = len(all_nodes)+ page = all_nodes[skip: skip + limit]return page, totaldef get_edges(@@@ -157,18 -166,15 +238,27 @@@) -> tuple[list[dict[str, Any]], int]:"""Return a paginated slice of edges and the total count."""with self._lock:+ if source or target:+ all_edges = self.graph.find_edges(edge_type=edge_type)+ if source:+ all_edges = [e for e in all_edges if e.get("source") == source]+ if target:+ all_edges = [e for e in all_edges if e.get("target") == target]+ total = len(all_edges)+ page = all_edges[skip: skip + limit]+ else:+ total = self.graph.stats().get("edge_types", {}).get(edge_type, 0) if edge_type else self.graph.stats().get("edge_count", 0)+ page = self.graph.find_edges(edge_type=edge_type, skip=skip, limit=limit)++ all_edges = self.graph.find_edges(edge_type=edge_type)++ if source:+ all_edges = [e for e in all_edges if e.get("source") == source]+ if target:+ all_edges = [e for e in all_edges if e.get("target") == target]++ total = len(all_edges)+ page = all_edges[skip: skip + limit]return page, totaldef get_neighbors(self, node_id: str, depth: int = 1) -> List[Dict[str, Any]]:@@@ -193,9 -199,12 +283,15 @@@with self._lock:return self.graph.find_active_nodes(node_type=node_type, at_time=at_time)++ def add_annotation(self, annotation: Dict[str, Any]) -> str:+ """Add an annotation and return its ID."""+ # ------------------------------------------------------------------+ # Annotation CRUD+ # ------------------------------------------------------------------++ def add_annotation(self, annotation: Dict[str, Any]) -> str:+ """Add an annotation (mutates the dict in-place) and return its ID."""ann_id = str(uuid.uuid4())annotation["annotation_id"] = ann_idannotation["created_at"] = datetime.utcnow().isoformat()diff --cc tests/explorer/test_explorer_api.pyindex e47f9661,d8047a0d..d03c8433--- a/tests/explorer/test_explorer_api.py+++ b/tests/explorer/test_explorer_api.py@@@ -72,8 -74,12 +75,14 @@@ class TestHealthInfobody = r.json()assert body["name"] == "Semantica Knowledge Explorer"assert "version" in body+++ assert body["status"] == "active"+++ # ---------------------------------------------------------------------------+ # Graph — Nodes+ # ---------------------------------------------------------------------------class TestGraphNodes:def test_list_nodes(self, client):@@@ -121,9 -132,19 +135,22 @@@assert len(body) >= 1ids = [nb["id"] for nb in body]assert "ml" in ids or "web_dev" in ids++++ # Each neighbour must have required fields+ for nb in body:+ assert "id" in nb and "type" in nb and "hop" in nb++ def test_get_neighbors_depth(self, client):+ r = client.get("/api/graph/node/python/neighbors?depth=2")+ assert r.status_code == 200+ assert isinstance(r.json(), list)+++ # ---------------------------------------------------------------------------+ # Graph — Edges+ # ---------------------------------------------------------------------------class TestGraphEdges:def test_list_edges(self, client):@@@ -142,10 -166,19 +172,23 @@@r = client.get("/api/graph/edges?source=python")assert r.status_code == 200body = r.json()+ assert all(e["source"] == "python" for e in body["edges"])++++ assert len(body["edges"]) >= 1+ assert all(e["source"] == "python" for e in body["edges"])++ def test_list_edges_filter_target(self, client):+ r = client.get("/api/graph/edges?target=ml")+ assert r.status_code == 200+ body = r.json()+ assert all(e["target"] == "ml" for e in body["edges"])+++ # ---------------------------------------------------------------------------+ # Search & Stats+ # ---------------------------------------------------------------------------class TestSearchStats:def test_search(self, client):@@@ -162,7 -204,13 +214,14 @@@assert body["node_count"] >= 5assert body["edge_count"] >= 3assert "density" in body++ assert "node_types" in body and "edge_types" in body+ assert body["density"] >= 0.0+++ # ---------------------------------------------------------------------------+ # Decisions+ # ---------------------------------------------------------------------------class TestDecisions:def test_list_decisions(self, client):@@@ -181,7 -232,9 +243,10 @@@def test_get_decision(self, client):r = client.get("/api/decisions/decision_1")assert r.status_code == 200+ assert r.json()["decision_id"] == "decision_1"+ body = r.json()+ assert body["decision_id"] == "decision_1"+ assert body["outcome"] == "approved"def test_get_decision_not_found(self, client):r = client.get("/api/decisions/nope")@@@ -197,16 -250,43 +262,53 @@@def test_precedents(self, client):r = client.get("/api/decisions/decision_1/precedents")assert r.status_code == 200+ assert isinstance(r.json(), list)++ def test_compliance(self, client):+ r = client.get("/api/decisions/decision_1/compliance")+ assert r.status_code == 200+ body = r.json()+ assert "compliant" in body++++ body = r.json()+ assert isinstance(body, list)+ # decision_2 shares category "tech" so should appear+ ids = [d["decision_id"] for d in body]+ assert "decision_2" in ids++ def test_compliance_no_violations(self, client):+ """Graph has no violation edges so compliance must be True."""+ r = client.get("/api/decisions/decision_1/compliance")+ assert r.status_code == 200+ body = r.json()+ assert "compliant" in body and "violations" in body+ assert body["compliant"] is True+ assert isinstance(body["violations"], list)++ def test_compliance_with_violation(self, client):+ """Add a violation edge then check compliance detects it."""+ # Add a policy node and a violates edge directly on the underlying graph+ session = GraphSession(client.app.state.session.graph)+ session.graph.add_node("policy_1", node_type="policy", content="Data policy")+ session.graph.add_edge("decision_1", "policy_1", edge_type="violates")++ r = client.get("/api/decisions/decision_1/compliance")+ assert r.status_code == 200+ body = r.json()+ assert body["compliant"] is False+ assert len(body["violations"]) >= 1+ assert body["violations"][0]["policy_id"] == "policy_1"++ # Clean up — remove the test edge so other tests are not affected+ # (ContextGraph doesn't expose edge removal; re-create the session fixture+ # to isolate: this test intentionally runs after all other decision tests)+++ # ---------------------------------------------------------------------------+ # Temporal+ # ---------------------------------------------------------------------------class TestTemporal:def test_snapshot_now(self, client):@@@ -214,8 -294,10 +316,12 @@@assert r.status_code == 200body = r.json()assert "active_node_count" in body++ def test_snapshot_at(self, client):+ assert "timestamp" in body+ assert isinstance(body["active_nodes"], list)++ def test_snapshot_at_includes_temporal_node(self, client):r = client.get("/api/temporal/snapshot?at=2025-06-15T00:00:00")assert r.status_code == 200body = r.json()@@@ -230,27 -319,53 +343,68 @@@)assert r.status_code == 200body = r.json()+ assert "added_nodes" in body+ assert "removed_nodes" in body+++++class TestAnalytics:+ def test_analytics(self, client):+ r = client.get("/api/analytics")+ assert r.status_code == 200+ assert "added_nodes" in body and "removed_nodes" in body+ # temporal_node became active between t1 and t2+ assert "temporal_node" in body["added_nodes"]++ def test_patterns(self, client):+ r = client.get("/api/temporal/patterns")+ assert r.status_code == 200+ body = r.json()+ assert "patterns" in body+ assert isinstance(body["patterns"], list)+++ # ---------------------------------------------------------------------------+ # Analytics+ # ---------------------------------------------------------------------------++ class TestAnalytics:+ def test_analytics_response_shape(self, client):+ r = client.get("/api/analytics")+ assert r.status_code == 200+ body = r.json()+ # At least one analytics key must be present (or all None when KG extras absent)+ assert set(body.keys()) >= {"centrality", "community", "connectivity"} or \+ all(v is None for v in body.values())++ def test_analytics_select_metric(self, client):+ r = client.get("/api/analytics?metrics=centrality")+ assert r.status_code == 200+ # When KG extras are absent the key is still present but None; otherwise a dict+ body = r.json()+ assert "centrality" in bodydef test_validation(self, client):r = client.get("/api/analytics/validation")assert r.status_code == 200body = r.json()assert "valid" in body++++class TestReasoning:+ def test_reason(self, client):+ assert "error_count" in body and "warning_count" in body+ assert isinstance(body["issues"], list)+++ # ---------------------------------------------------------------------------+ # Reasoning+ # ---------------------------------------------------------------------------++ class TestReasoning:+ def test_reason_forward(self, client):r = client.post("/api/reason",json={@@@ -259,14 -374,107 +413,115 @@@"mode": "forward",},)+ assert r.status_code in (200, 422)+++++class TestAnnotations:+ def test_create_and_list(self, client):++ # 200 when reasoning module is available; 422 when it's not installed.+ # Either is acceptable — the endpoint must not 500.+ assert r.status_code in (200, 422), (+ f"Unexpected status {r.status_code}: {r.text}"+ )+ if r.status_code == 200:+ body = r.json()+ assert "inferred_facts" in body+ assert "rules_fired" in body+ assert isinstance(body["inferred_facts"], list)+ assert isinstance(body["rules_fired"], int)++ def test_reason_empty_rules(self, client):+ r = client.post(+ "/api/reason",+ json={"facts": ["Person(Alice)"], "rules": [], "mode": "forward"},+ )+ assert r.status_code in (200, 422)+ if r.status_code == 200:+ assert r.json()["rules_fired"] == 0+++ # ---------------------------------------------------------------------------+ # Enrichment — Extract+ # ---------------------------------------------------------------------------++ class TestEnrichExtract:+ def test_extract_returns_structure(self, client):+ r = client.post(+ "/api/enrich/extract",+ json={"text": "Alice works at Acme Corp in New York."},+ )+ # 200 when spacy/transformers available; 422 otherwise+ assert r.status_code in (200, 422), (+ f"Unexpected status {r.status_code}: {r.text}"+ )+ if r.status_code == 200:+ body = r.json()+ assert "entities" in body and "relations" in body+ assert isinstance(body["entities"], list)+ assert isinstance(body["relations"], list)++ def test_extract_empty_text(self, client):+ r = client.post("/api/enrich/extract", json={"text": ""})+ assert r.status_code in (200, 422)+++ # ---------------------------------------------------------------------------+ # Enrichment — Link Prediction+ # ---------------------------------------------------------------------------++ class TestLinkPrediction:+ def test_predict_links_known_node(self, client):+ r = client.post(+ "/api/enrich/links",+ json={"node_id": "python", "top_n": 5},+ )+ # 200 when KG extras available; 422 otherwise+ assert r.status_code in (200, 422), (+ f"Unexpected status {r.status_code}: {r.text}"+ )+ if r.status_code == 200:+ body = r.json()+ assert body["node_id"] == "python"+ assert isinstance(body["predictions"], list)+ # Must not include existing neighbours+ neighbour_ids = {"ml", "web_dev"}+ for pred in body["predictions"]:+ assert pred.get("target") not in neighbour_ids++ def test_predict_links_unknown_node(self, client):+ r = client.post(+ "/api/enrich/links",+ json={"node_id": "does_not_exist", "top_n": 5},+ )+ assert r.status_code == 404+++ # ---------------------------------------------------------------------------+ # Enrichment — Deduplication+ # ---------------------------------------------------------------------------++ class TestDedup:+ def test_dedup_returns_structure(self, client):+ r = client.post("/api/enrich/dedup", json={"threshold": 0.8})+ assert r.status_code in (200, 422), (+ f"Unexpected status {r.status_code}: {r.text}"+ )+ if r.status_code == 200:+ body = r.json()+ assert "duplicates" in body and "total_flagged" in body+ assert isinstance(body["duplicates"], list)+ assert body["total_flagged"] == len(body["duplicates"])+++ # ---------------------------------------------------------------------------+ # Annotations+ # ---------------------------------------------------------------------------++ class TestAnnotations:+ def test_create_and_list(self, client):r = client.post("/api/annotations",json={"node_id": "python", "content": "Great language!", "tags": ["fav"]},@@@ -307,14 -525,28 +572,30 @@@ class TestExportdef test_export_json(self, client):r = client.post("/api/export", json={"format": "json"})assert r.status_code == 200+ assert "json" in r.headers.get("content-type", "").lower() or len(r.content) > 0+ ct = r.headers.get("content-type", "")+ assert "json" in ct.lower()+ # Payload must be valid JSON with entities and relationships+ data = r.json()+ assert "entities" in data and "relationships" in data+ assert len(data["entities"]) >= 5++ def test_export_json_subset(self, client):+ r = client.post("/api/export", json={"format": "json", "node_ids": ["python", "ml"]})+ assert r.status_code == 200+ data = r.json()+ ids = [e["id"] for e in data["entities"]]+ assert set(ids) == {"python", "ml"}def test_export_unsupported(self, client):r = client.post("/api/export", json={"format": "pdf"})assert r.status_code == 422++ # ---------------------------------------------------------------------------+ # Import+ # ---------------------------------------------------------------------------class TestImport:def test_import_json(self, client):@@@ -333,5 -565,34 +614,36 @@@assert body["status"] == "success"assert body["nodes_added"] >= 1+ r2 = client.get("/api/graph/node/imported_node")+ assert r2.status_code == 200+ # Verify the node is now in the graph+ r2 = client.get("/api/graph/node/imported_node")+ assert r2.status_code == 200+ assert r2.json()["id"] == "imported_node"++ def test_import_with_edges(self, client):+ payload = json.dumps({+ "nodes": [+ {"id": "import_src", "type": "test", "properties": {"content": "src"}},+ {"id": "import_tgt", "type": "test", "properties": {"content": "tgt"}},+ ],+ "edges": [+ {"source": "import_src", "target": "import_tgt", "type": "links_to"}+ ],+ })+ r = client.post(+ "/api/import",+ files={"file": ("import2.json", payload, "application/json")},+ )+ assert r.status_code == 200+ body = r.json()+ assert body["status"] == "success"+ assert body["nodes_added"] >= 2++ def test_import_unsupported_format(self, client):+ r = client.post(+ "/api/import",+ files={"file": ("data.csv", b"a,b,c", "text/csv")},+ )+ assert r.status_code == 200+ assert r.json()["status"] == "unsupported"