Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: implement Knowledge Explorer API backend

ZohaibHassan1699a4db3ece4d
diff --git a/pyproject.toml b/pyproject.toml
index a6abe1fc..858b7875 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -196,9 +196,21 @@ dev = [
"ipykernel>=6.15.0"
]
-# ---- Everything ----
+# Explorer Dashboard
+explorer = [
+ "fastapi>=0.100.0",
+ "uvicorn[standard]>=0.22.0",
+ "websockets>=11.0",
+ "python-multipart>=0.0.6"
+]
+explorer-lite = [
+ "streamlit>=1.25.0",
+ "streamlit-agraph>=0.0.45"
+]
+
+# Everything
all = [
- "semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling]"
+ "semantica[dev,viz,gpu,infra,cloud,monitoring,llm-all,models-huggingface,split-all,graph-all,vectorstore-all,parse-docling,explorer]"
]
# ---------------- ENTRYPOINTS ----------------
@@ -206,6 +218,7 @@ all = [
semantica = "semantica.cli:main"
semantica-server = "semantica.server:main"
semantica-worker = "semantica.worker:main"
+semantica-explorer = "semantica.explorer:main"
# ---------------- TOOLING ----------------
[tool.setuptools.packages.find]
diff --git a/semantica/explorer/__init__.py b/semantica/explorer/__init__.py
new file mode 100644
index 00000000..f52ef0ff
--- /dev/null
+++ b/semantica/explorer/__init__.py
@@ -0,0 +1,91 @@
+"""
+Semantica Knowledge Explorer : CLI Entry Point
+
+Provides the ``semantica-explorer`` command that loads a graph from a
+JSON file, starts a FastAPI server, and optionally opens the browser.
+
+Usage::
+
+ semantica-explorer --graph my_graph.json --port 8000
+ python -m semantica.explorer --graph my_graph.json
+"""
+
+import argparse
+import sys
+import webbrowser
+
+
+def main(argv=None):
+ """CLI entry point for the Knowledge Explorer server."""
+ parser = argparse.ArgumentParser(
+ prog="semantica-explorer",
+ description="Semantica Knowledge Explorer — interactive dashboard for KG exploration",
+ )
+ parser.add_argument(
+ "--graph", "-g",
+ required=True,
+ help="Path to a ContextGraph JSON file to load.",
+ )
+ parser.add_argument(
+ "--port", "-p",
+ type=int,
+ default=8000,
+ help="Port to bind the server to (default: 8000).",
+ )
+ parser.add_argument(
+ "--host",
+ default="127.0.0.1",
+ help="Host to bind the server to (default: 127.0.0.1).",
+ )
+ parser.add_argument(
+ "--no-browser",
+ action="store_true",
+ help="Do not open the browser automatically.",
+ )
+ args = parser.parse_args(argv)
+
+
+ import os
+ if not os.path.isfile(args.graph):
+ print(f"Error: graph file not found: {args.graph}", file=sys.stderr)
+ sys.exit(1)
+
+ try:
+ import uvicorn
+ except ImportError:
+ print(
+ "Error: uvicorn is required. Install with:\n"
+ " pip install semantica[explorer]",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+ from .session import GraphSession
+ from .app import create_app
+
+ print(f"Loading graph from {args.graph} ...")
+ session = GraphSession.from_file(args.graph)
+ stats = session.get_stats()
+ print(
+ f"Graph loaded — {stats.get('node_count', 0)} nodes, "
+ f"{stats.get('edge_count', 0)} edges"
+ )
+
+
+ app = create_app(session=session)
+
+
+ url = f"http://{args.host}:{args.port}"
+ if not args.no_browser:
+ import threading
+ threading.Timer(1.5, lambda: webbrowser.open(url)).start()
+
+ print(f"Starting explorer at {url}")
+ print(f" API docs: {url}/docs")
+ print(f" Health: {url}/api/health")
+
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/semantica/explorer/app.py b/semantica/explorer/app.py
new file mode 100644
index 00000000..ba797d75
--- /dev/null
+++ b/semantica/explorer/app.py
@@ -0,0 +1,131 @@
+"""
+Semantica Explorer — FastAPI Application Factory
+
+Creates and configures the FastAPI app with CORS, error handling,
+static file serving, route registration, and WebSocket support.
+"""
+
+import os
+import traceback
+from contextlib import asynccontextmanager
+from pathlib import Path
+from typing import Optional
+
+from fastapi import FastAPI, Request
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import JSONResponse
+
+from .. import __version__
+from .session import GraphSession
+from .ws import ConnectionManager
+
+
+def create_app(session: Optional[GraphSession] = None) -> FastAPI:
+ """
+ Build a fully-configured FastAPI application.
+
+ Args:
+ session: Pre-built ``GraphSession``. If ``None`` the caller must
+ attach one to ``app.state.session`` before the first
+ request arrives.
+ """
+
+ @asynccontextmanager
+ async def lifespan(app: FastAPI):
+
+ if session is not None:
+ app.state.session = session
+ app.state.ws_manager = ConnectionManager()
+ yield
+
+
+ app = FastAPI(
+ title="Semantica Knowledge Explorer",
+ description="Interactive dashboard API for exploring Semantica knowledge graphs.",
+ version=__version__,
+ lifespan=lifespan,
+ )
+
+
+ cors_origins = os.environ.get("EXPLORER_CORS_ORIGINS", "*")
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=cors_origins.split(","),
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+ )
+
+
+ @app.exception_handler(KeyError)
+ async def key_error_handler(request: Request, exc: KeyError):
+ return JSONResponse(
+ status_code=404,
+ content={"detail": f"Not found: {exc}"},
+ )
+
+ @app.exception_handler(ValueError)
+ async def value_error_handler(request: Request, exc: ValueError):
+ return JSONResponse(
+ status_code=422,
+ content={"detail": str(exc)},
+ )
+
+ @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},
+ )
+
+ from .routes.graph import router as graph_router
+ from .routes.analytics import router as analytics_router
+ from .routes.decisions import router as decisions_router
+ from .routes.temporal import router as temporal_router
+ from .routes.enrich import router as enrich_router
+ from .routes.export_import import router as export_import_router
+ from .routes.annotations import router as annotations_router
+
+ app.include_router(graph_router)
+ app.include_router(analytics_router)
+ app.include_router(decisions_router)
+ app.include_router(temporal_router)
+ app.include_router(enrich_router)
+ app.include_router(export_import_router)
+ app.include_router(annotations_router)
+
+
+ from fastapi import WebSocket, WebSocketDisconnect
+
+ @app.websocket("/ws/graph-updates")
+ async def websocket_endpoint(websocket: WebSocket):
+ manager: ConnectionManager = app.state.ws_manager
+ await manager.connect(websocket)
+ try:
+ while True:
+
+ await websocket.receive_text()
+ except WebSocketDisconnect:
+ manager.disconnect(websocket)
+
+
+ @app.get("/api/health")
+ async def health():
+ return {"status": "healthy"}
+
+ @app.get("/api/info")
+ async def info():
+ return {
+ "name": "Semantica Knowledge Explorer",
+ "version": __version__,
+ "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")
+
+ return app
diff --git a/semantica/explorer/dependencies.py b/semantica/explorer/dependencies.py
new file mode 100644
index 00000000..b59c72d9
--- /dev/null
+++ b/semantica/explorer/dependencies.py
@@ -0,0 +1,21 @@
+"""
+Semantica Explorer : FastAPI Dependencies
+
+Provides ``Depends()``-compatible callables for injecting the
+current ``GraphSession`` and ``ConnectionManager`` into route handlers.
+"""
+
+from fastapi import Request
+
+from .session import GraphSession
+from .ws import ConnectionManager
+
+
+def get_session(request: Request) -> GraphSession:
+ """Retrieve the GraphSession stored on ``app.state``."""
+ return request.app.state.session
+
+
+def get_ws_manager(request: Request) -> ConnectionManager:
+ """Retrieve the ConnectionManager stored on ``app.state``."""
+ return request.app.state.ws_manager
diff --git a/semantica/explorer/routes/__init__.py b/semantica/explorer/routes/__init__.py
new file mode 100644
index 00000000..dd489a6b
--- /dev/null
+++ b/semantica/explorer/routes/__init__.py
@@ -0,0 +1 @@
+"""Route package for the Semantica Knowledge Explorer API."""
diff --git a/semantica/explorer/routes/analytics.py b/semantica/explorer/routes/analytics.py
new file mode 100644
index 00000000..dc7c584e
--- /dev/null
+++ b/semantica/explorer/routes/analytics.py
@@ -0,0 +1,121 @@
+"""
+Analytics routes : centrality, community, connectivity, validation.
+"""
+
+import asyncio
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query
+
+from ..dependencies import get_session
+from ..schemas import AnalyticsResponse, ValidationIssue, ValidationReportResponse
+from ..session import GraphSession
+
+router = APIRouter(prefix="/api/analytics", tags=["Analytics"])
+
+
+def _build_graph_dict(session: GraphSession) -> dict:
+ """Build the entity/relationship dict expected by KG analysers."""
+ nodes, _ = session.get_nodes(skip=0, limit=999_999)
+ edges, _ = session.get_edges(skip=0, limit=999_999)
+ return {
+ "entities": [
+ {"id": n.get("id"), "type": n.get("type", "entity"),
+ "text": n.get("content", n.get("id", "")), "metadata": n.get("metadata", {})}
+ for n in nodes
+ ],
+ "relationships": [
+ {"source": e.get("source"), "target": e.get("target"),
+ "type": e.get("type", "related_to"), "metadata": e.get("metadata", {})}
+ for e in edges
+ ],
+ }
+
+
[email protected]("", response_model=AnalyticsResponse)
+async def get_analytics(
+ metrics: Optional[str] = Query(
+ None,
+ description="Comma-separated metrics to compute: centrality,community,connectivity",
+ ),
+ session: GraphSession = Depends(get_session),
+):
+ """Compute graph analytics (centrality, community, connectivity)."""
+ requested = set((metrics or "centrality,community,connectivity").split(","))
+ graph_dict = await asyncio.to_thread(_build_graph_dict, session)
+ result: dict = {}
+
+ if "centrality" in requested and session.centrality is not None:
+ try:
+ centrality = await asyncio.to_thread(
+ session.centrality.calculate_degree_centrality, graph_dict
+ )
+ result["centrality"] = centrality
+ except Exception as exc:
+ result["centrality"] = {"error": str(exc)}
+
+ if "community" in requested and session.community is not None:
+ try:
+ community = await asyncio.to_thread(
+ session.community.detect_communities, graph_dict
+ )
+ result["community"] = community
+ except Exception as exc:
+ result["community"] = {"error": str(exc)}
+
+ if "connectivity" in requested and session.connectivity is not None:
+ try:
+ connectivity = await asyncio.to_thread(
+ session.connectivity.analyze_connectivity, graph_dict
+ )
+ result["connectivity"] = connectivity
+ except Exception as exc:
+ result["connectivity"] = {"error": str(exc)}
+
+ return AnalyticsResponse(**result)
+
+
[email protected]("/validation", response_model=ValidationReportResponse)
+async def validate_graph(
+ session: GraphSession = Depends(get_session),
+):
+ """Run graph validation and return a pass/fail report."""
+ validator = session.validator
+ if validator is None:
+ return ValidationReportResponse(valid=True, error_count=0, warning_count=0, issues=[])
+
+ graph_dict = await asyncio.to_thread(_build_graph_dict, session)
+
+ try:
+ report = await asyncio.to_thread(validator.validate, graph_dict)
+ except Exception as exc:
+ return ValidationReportResponse(
+ valid=False,
+ error_count=1,
+ issues=[ValidationIssue(severity="error", message=str(exc))],
+ )
+
+
+ if isinstance(report, dict):
+ valid = report.get("valid", True)
+ errors = report.get("errors", [])
+ warnings = report.get("warnings", [])
+ else:
+ valid = getattr(report, "valid", True)
+ errors = getattr(report, "errors", [])
+ warnings = getattr(report, "warnings", [])
+
+ issues = []
+ for e in (errors or []):
+ msg = e if isinstance(e, str) else str(e)
+ issues.append(ValidationIssue(severity="error", message=msg))
+ for w in (warnings or []):
+ msg = w if isinstance(w, str) else str(w)
+ issues.append(ValidationIssue(severity="warning", message=msg))
+
+ return ValidationReportResponse(
+ valid=valid,
+ error_count=len(errors or []),
+ warning_count=len(warnings or []),
+ issues=issues,
+ )
diff --git a/semantica/explorer/routes/annotations.py b/semantica/explorer/routes/annotations.py
new file mode 100644
index 00000000..35dd2a30
--- /dev/null
+++ b/semantica/explorer/routes/annotations.py
@@ -0,0 +1,67 @@
+"""
+Annotation routes — CRUD for collaborative annotations on graph nodes.
+
+Annotations are stored in-memory on the ``GraphSession`` and do not
+modify Semantica core.
+"""
+
+import asyncio
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query
+
+from ..dependencies import get_session
+from ..schemas import AnnotationCreate, AnnotationResponse
+from ..session import GraphSession
+
+router = APIRouter(prefix="/api/annotations", tags=["Annotations"])
+
+
[email protected]("", response_model=list[AnnotationResponse])
+async def list_annotations(
+ node_id: Optional[str] = Query(None, description="Filter by node ID"),
+ session: GraphSession = Depends(get_session),
+):
+ """List annotations, optionally filtered by node_id."""
+ anns = await asyncio.to_thread(session.get_annotations, node_id)
+ return [AnnotationResponse(**a) for a in anns]
+
+
[email protected]("", response_model=AnnotationResponse, status_code=201)
+async def create_annotation(
+ body: AnnotationCreate,
+ session: GraphSession = Depends(get_session),
+):
+ """Create a new annotation on a node."""
+ node = await asyncio.to_thread(session.get_node, body.node_id)
+ if node is None:
+ raise 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,
+ )
+
+
[email protected]("/{annotation_id}", status_code=204)
+async def delete_annotation(
+ annotation_id: str,
+ session: GraphSession = Depends(get_session),
+):
+ """Delete an annotation by ID."""
+ deleted = await asyncio.to_thread(session.delete_annotation, annotation_id)
+ if not deleted:
+ raise KeyError(annotation_id)
+ return None
diff --git a/semantica/explorer/routes/decisions.py b/semantica/explorer/routes/decisions.py
new file mode 100644
index 00000000..7d502d5c
--- /dev/null
+++ b/semantica/explorer/routes/decisions.py
@@ -0,0 +1,168 @@
+"""
+Decision routes : decision listing, causal chains, precedents, compliance.
+
+Uses ContextGraph-native queries so it works without a Neo4j/FalkorDB backend.
+"""
+
+import asyncio
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query
+
+from ..dependencies import get_session
+from ..schemas import (
+ CausalChainResponse,
+ ComplianceResponse,
+ DecisionResponse,
+)
+from ..session import GraphSession
+
+router = APIRouter(prefix="/api/decisions", tags=["Decisions"])
+
+
+def _node_to_decision(n: dict) -> DecisionResponse:
+ """Map a ContextGraph node dict to a DecisionResponse."""
+ meta = n.get("metadata", {})
+ return DecisionResponse(
+ decision_id=n.get("id", ""),
+ category=meta.get("category", ""),
+ scenario=meta.get("scenario", ""),
+ reasoning=meta.get("reasoning", ""),
+ outcome=meta.get("outcome", ""),
+ confidence=float(meta.get("confidence", 0.0)),
+ timestamp=meta.get("timestamp"),
+ metadata=meta,
+ )
+
+
[email protected]("", response_model=list[DecisionResponse])
+async def list_decisions(
+ category: Optional[str] = Query(None),
+ skip: int = Query(0, ge=0),
+ limit: int = Query(50, ge=1, le=500),
+ session: GraphSession = Depends(get_session),
+):
+ """List decision nodes (type='decision') with optional category filter."""
+ nodes, _ = await asyncio.to_thread(
+ session.get_nodes, node_type="decision", skip=0, limit=999_999
+ )
+
+ if category:
+ nodes = [
+ n for n in nodes
+ if n.get("metadata", {}).get("category", "").lower() == category.lower()
+ ]
+
+ page = nodes[skip: skip + limit]
+ return [_node_to_decision(n) for n in page]
+
+
[email protected]("/{decision_id}", response_model=DecisionResponse)
+async def get_decision(
+ decision_id: str,
+ session: GraphSession = Depends(get_session),
+):
+ """Get a single decision by ID."""
+ node = await asyncio.to_thread(session.get_node, decision_id)
+ if node is None:
+ raise KeyError(decision_id)
+ return _node_to_decision(node)
+
+
[email protected]("/{decision_id}/chain", response_model=CausalChainResponse)
+async def get_causal_chain(
+ decision_id: str,
+ session: GraphSession = Depends(get_session),
+):
+ """
+ Trace the causal chain for a decision.
+
+ Uses BFS neighbour traversal over ``caused_by`` / ``influences``
+ relationship types as a lightweight, backend-agnostic fallback.
+ """
+ node = await asyncio.to_thread(session.get_node, decision_id)
+ if node is None:
+ raise KeyError(decision_id)
+
+ # Walk outbound causal edges (up to 5 hops)
+ neighbors = await asyncio.to_thread(session.get_neighbors, decision_id, depth=5)
+ chain = [
+ {
+ "id": nb.get("id"),
+ "type": nb.get("type"),
+ "relationship": nb.get("relationship"),
+ "hop": nb.get("hop"),
+ "content": nb.get("content", ""),
+ }
+ for nb in neighbors
+ ]
+ return CausalChainResponse(decision_id=decision_id, chain=chain)
+
+
[email protected]("/{decision_id}/precedents", response_model=list[DecisionResponse])
+async def get_precedents(
+ decision_id: str,
+ limit: int = Query(10, ge=1, le=100),
+ session: GraphSession = Depends(get_session),
+):
+ """
+ Find precedent decisions similar to the given decision.
+
+ Lightweight: looks for other decision-type nodes and ranks by shared
+ category and keyword overlap.
+ """
+ node = await asyncio.to_thread(session.get_node, decision_id)
+ if node is None:
+ raise KeyError(decision_id)
+
+ meta = node.get("metadata", {})
+ category = meta.get("category", "")
+ scenario_words = set(meta.get("scenario", "").lower().split())
+
+ all_decisions, _ = await asyncio.to_thread(
+ session.get_nodes, node_type="decision", skip=0, limit=999_999
+ )
+
+ scored = []
+ for d in all_decisions:
+ if d.get("id") == decision_id:
+ continue
+ d_meta = d.get("metadata", {})
+ score = 0.0
+ if d_meta.get("category", "").lower() == category.lower() and category:
+ score += 0.5
+ d_words = set(d_meta.get("scenario", "").lower().split())
+ if scenario_words and d_words:
+ overlap = len(scenario_words & d_words) / max(len(scenario_words | d_words), 1)
+ score += 0.5 * overlap
+ scored.append((score, d))
+
+ scored.sort(key=lambda x: x[0], reverse=True)
+ return [_node_to_decision(d) for _, d in scored[:limit]]
+
+
[email protected]("/{decision_id}/compliance", response_model=ComplianceResponse)
+async def check_compliance(
+ decision_id: str,
+ session: GraphSession = Depends(get_session),
+):
+ """
+ Check policy compliance for a decision.
+
+ Returns a stub result when no PolicyEngine is wired up.
+ """
+ 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=[],
+ )
diff --git a/semantica/explorer/routes/enrich.py b/semantica/explorer/routes/enrich.py
new file mode 100644
index 00000000..606130fe
--- /dev/null
+++ b/semantica/explorer/routes/enrich.py
@@ -0,0 +1,156 @@
+"""
+Enrichment & reasoning routes — extraction, link prediction, dedup, reasoning.
+"""
+
+import asyncio
+
+from fastapi import APIRouter, Depends
+
+from ..dependencies import get_session
+from ..schemas import (
+ DedupRequest,
+ DedupResponse,
+ EnrichExtractRequest,
+ EnrichExtractResponse,
+ LinkPredictionRequest,
+ LinkPredictionResponse,
+ ReasoningRequest,
+ ReasoningResponse,
+)
+from ..session import GraphSession
+
+router = APIRouter(tags=["Enrichment"])
+
+
[email protected]("/api/enrich/extract", response_model=EnrichExtractResponse)
+async def extract_entities(
+ body: EnrichExtractRequest,
+ session: GraphSession = Depends(get_session),
+):
+ """Extract entities and relations from free text."""
+ try:
+ from ...semantic_extract.methods import extract_entities as _extract_entities
+ from ...semantic_extract.methods import extract_relations as _extract_relations
+
+ entities = await asyncio.to_thread(_extract_entities, body.text)
+ relations = await asyncio.to_thread(_extract_relations, body.text)
+
+ ent_list = entities if isinstance(entities, list) else getattr(entities, "entities", [])
+ rel_list = relations if isinstance(relations, list) else getattr(relations, "relations", [])
+
+ return EnrichExtractResponse(
+ entities=[_safe_dict(e) for e in ent_list],
+ relations=[_safe_dict(r) for r in rel_list],
+ )
+ except ImportError:
+ raise ValueError(
+ "semantic_extract module not available. "
+ "Ensure spacy and transformers are installed."
+ )
+ except Exception as exc:
+ raise ValueError(f"Extraction failed: {exc}")
+
+
[email protected]("/api/enrich/links", response_model=LinkPredictionResponse)
+async def predict_links(
+ body: LinkPredictionRequest,
+ session: GraphSession = Depends(get_session),
+):
+ """Predict likely new edges for a node."""
+ predictor = session.link_predictor
+ if predictor is None:
+ raise ValueError("LinkPredictor not available — KG extras may not be installed.")
+
+ node = await asyncio.to_thread(session.get_node, body.node_id)
+ if node is None:
+ raise KeyError(body.node_id)
+
+ # Build graph dict
+ nodes, _ = session.get_nodes(skip=0, limit=999_999)
+ edges, _ = 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}")
+
+
[email protected]("/api/enrich/dedup", response_model=DedupResponse)
+async def detect_duplicates(
+ body: DedupRequest,
+ session: GraphSession = Depends(get_session),
+):
+ """Run a deduplication scan over graph entities."""
+ try:
+ from ...deduplication import DuplicateDetector
+
+ detector = DuplicateDetector()
+ nodes, _ = 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
+ ]
+
+ dups = await asyncio.to_thread(
+ detector.detect_duplicates, entities, threshold=body.threshold
+ )
+ dup_list = dups if isinstance(dups, list) else getattr(dups, "duplicates", [])
+ return DedupResponse(
+ duplicates=[_safe_dict(d) for d in dup_list],
+ total_flagged=len(dup_list),
+ )
+ except ImportError:
+ raise ValueError("Deduplication module not available.")
+ except Exception as exc:
+ raise ValueError(f"Dedup scan failed: {exc}")
+
+
[email protected]("/api/reason", response_model=ReasoningResponse)
+async def run_reasoning(
+ body: ReasoningRequest,
+ session: GraphSession = Depends(get_session),
+):
+ """Run inference rules over facts."""
+ try:
+ from ...reasoning.reasoner import Reasoner
+
+ reasoner = Reasoner()
+ inferred = await asyncio.to_thread(
+ reasoner.infer_facts, body.facts, body.rules
+ )
+
+ return ReasoningResponse(
+ inferred_facts=inferred if isinstance(inferred, list) else [],
+ rules_fired=len(inferred) if isinstance(inferred, list) else 0,
+ )
+ except ImportError:
+ raise ValueError("Reasoning module not available.")
+ except Exception as exc:
+ raise ValueError(f"Reasoning failed: {exc}")
+
+
+
+def _safe_dict(obj) -> dict:
+ """Convert an object to a JSON-safe dict."""
+ if isinstance(obj, dict):
+ return obj
+ if hasattr(obj, "__dict__"):
+ return {k: v for k, v in obj.__dict__.items() if not k.startswith("_")}
+ return {"value": str(obj)}
diff --git a/semantica/explorer/routes/export_import.py b/semantica/explorer/routes/export_import.py
new file mode 100644
index 00000000..608db5ff
--- /dev/null
+++ b/semantica/explorer/routes/export_import.py
@@ -0,0 +1,174 @@
+"""
+Export & import routes.
+"""
+
+import asyncio
+import io
+import json
+import tempfile
+from typing import Optional
+
+from fastapi import APIRouter, Depends, File, UploadFile
+from fastapi.responses import Response
+
+from ..dependencies import get_session, get_ws_manager
+from ..schemas import ExportRequest
+from ..session import GraphSession
+from ..ws import ConnectionManager
+
+router = APIRouter(tags=["Export / Import"])
+
+
+_FORMAT_MAP = {
+ "json": ("export_json", "application/json", ".json"),
+ "json-ld": ("export_json", "application/ld+json", ".jsonld"),
+ "turtle": ("export_rdf", "text/turtle", ".ttl"),
+ "rdf-xml": ("export_rdf", "application/rdf+xml", ".rdf"),
+ "n-triples": ("export_rdf", "application/n-triples", ".nt"),
+ "csv": ("export_csv", "text/csv", ".csv"),
+ "graphml": ("export_graph", "application/xml", ".graphml"),
+ "gexf": ("export_graph", "application/xml", ".gexf"),
+ "owl": ("export_owl", "application/rdf+xml", ".owl"),
+ "cypher": ("export_lpg", "text/plain", ".cypher"),
+ "aql": ("export_arango", "text/plain", ".aql"),
+ "yaml": ("export_yaml", "text/yaml", ".yaml"),
+}
+
+
+def _build_kg_dict(session: GraphSession, node_ids: Optional[list] = None) -> dict:
+ """Build the knowledge-graph dict that exporters expect."""
+ nodes, _ = session.get_nodes(skip=0, limit=999_999)
+ edges, _ = session.get_edges(skip=0, limit=999_999)
+
+ if node_ids:
+ id_set = set(node_ids)
+ nodes = [n for n in nodes if n.get("id") in id_set]
+ edges = [
+ e for e in edges
+ if e.get("source") in id_set and e.get("target") in id_set
+ ]
+
+ return {
+ "entities": [
+ {
+ "id": n.get("id"),
+ "type": n.get("type", "entity"),
+ "text": n.get("content", n.get("id", "")),
+ "metadata": n.get("metadata", {}),
+ }
+ for n in nodes
+ ],
+ "relationships": [
+ {
+ "source": e.get("source"),
+ "target": e.get("target"),
+ "type": e.get("type", "related_to"),
+ "metadata": e.get("metadata", {}),
+ }
+ for e in edges
+ ],
+ }
+
+
[email protected]("/api/export")
+async def export_graph(
+ body: ExportRequest,
+ session: GraphSession = Depends(get_session),
+):
+ """Export the current graph in the requested format."""
+ fmt = body.format.lower()
+ if fmt not in _FORMAT_MAP:
+ raise ValueError(
+ f"Unsupported format '{fmt}'. Supported: {', '.join(sorted(_FORMAT_MAP))}"
+ )
+
+ func_name, content_type, ext = _FORMAT_MAP[fmt]
+
+ kg = await asyncio.to_thread(_build_kg_dict, session, body.node_ids)
+
+
+ try:
+ from ...export.methods import (
+ export_json, export_rdf, export_csv, export_graph as export_graph_fn,
+ export_owl, export_lpg, export_arango, export_yaml,
+ )
+ fn_map = {
+ "export_json": export_json,
+ "export_rdf": export_rdf,
+ "export_csv": export_csv,
+ "export_graph": export_graph_fn,
+ "export_owl": export_owl,
+ "export_lpg": export_lpg,
+ "export_arango": export_arango,
+ "export_yaml": export_yaml,
+ }
+ export_fn = fn_map.get(func_name)
+ 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:
+
+ content = json.dumps(kg, indent=2, default=str)
+ content_type = "application/json"
+ ext = ".json"
+
+ filename = f"semantica_export{ext}"
+ return Response(
+ content=content,
+ media_type=content_type,
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
+ )
+
+
[email protected]("/api/import")
+async def import_file(
+ file: UploadFile = File(...),
+ session: GraphSession = Depends(get_session),
+ ws: ConnectionManager = Depends(get_ws_manager),
+):
+ """
+ Import entities from an uploaded file (JSON or CSV).
+
+ For JSON files the expected shape is ``{"nodes": [...], "edges": [...]}``.
+ """
+ content = await file.read()
+ filename = file.filename or "upload"
+
+ await ws.broadcast("import_started", {"filename": filename})
+
+ try:
+ if filename.endswith(".json") or filename.endswith(".jsonld"):
+ data = json.loads(content)
+ nodes = data.get("nodes", data.get("entities", []))
+ edges = data.get("edges", data.get("relationships", []))
+
+ added_nodes = await asyncio.to_thread(session.graph.add_nodes, nodes)
+ added_edges = await asyncio.to_thread(session.graph.add_edges, edges)
+
+ result = {
+ "status": "success",
+ "nodes_added": added_nodes,
+ "edges_added": added_edges,
+ }
+ else:
+ result = {
+ "status": "unsupported",
+ "detail": f"File type not supported yet: {filename}",
+ }
+ except Exception as exc:
+ result = {"status": "error", "detail": str(exc)}
+
+ await ws.broadcast("import_completed", result)
+ return result
diff --git a/semantica/explorer/routes/graph.py b/semantica/explorer/routes/graph.py
new file mode 100644
index 00000000..3b6a0a77
--- /dev/null
+++ b/semantica/explorer/routes/graph.py
@@ -0,0 +1,211 @@
+"""
+Graph routes — node / edge / path / search endpoints.
+"""
+
+import asyncio
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query
+
+from ..dependencies import get_session
+from ..schemas import (
+ EdgeListResponse,
+ EdgeResponse,
+ GraphStatsResponse,
+ NeighborResponse,
+ NodeListResponse,
+ NodeResponse,
+ PathResponse,
+ SearchRequest,
+ SearchResultItem,
+ SearchResultResponse,
+)
+from ..session import GraphSession
+
+router = APIRouter(prefix="/api/graph", tags=["Graph"])
+
+
+def _node_dict_to_response(n: dict) -> NodeResponse:
+ """Convert a ContextGraph node dict to a NodeResponse."""
+ meta = n.get("metadata", {})
+ return NodeResponse(
+ id=n.get("id", ""),
+ type=n.get("type", "entity"),
+ content=n.get("content", meta.get("content", "")),
+ properties=meta,
+ valid_from=meta.get("valid_from"),
+ valid_until=meta.get("valid_until"),
+ )
+
+
+
[email protected]("/nodes", response_model=NodeListResponse)
+async def list_nodes(
+ type: Optional[str] = Query(None, description="Filter by node type"),
+ search: Optional[str] = Query(None, description="Keyword search over node content"),
+ skip: int = Query(0, ge=0),
+ limit: int = Query(100, ge=1, le=1000),
+ session: GraphSession = Depends(get_session),
+):
+ """List nodes with optional filtering and pagination."""
+ nodes, total = await asyncio.to_thread(
+ session.get_nodes, node_type=type, search=search, skip=skip, limit=limit
+ )
+ return NodeListResponse(
+ nodes=[_node_dict_to_response(n) for n in nodes],
+ total=total,
+ skip=skip,
+ limit=limit,
+ )
+
+
[email protected]("/node/{node_id}", response_model=NodeResponse)
+async def get_node(
+ node_id: str,
+ session: GraphSession = Depends(get_session),
+):
+ """Get a single node by ID."""
+ node = await asyncio.to_thread(session.get_node, node_id)
+ if node is None:
+ raise KeyError(node_id)
+ return _node_dict_to_response(node)
+
+
[email protected]("/node/{node_id}/neighbors", response_model=list[NeighborResponse])
+async def get_neighbors(
+ node_id: str,
+ depth: int = Query(1, ge=1, le=5),
+ session: GraphSession = Depends(get_session),
+):
+ """Get neighbours of a node via BFS traversal."""
+ neighbors = await asyncio.to_thread(session.get_neighbors, node_id, depth)
+ return [
+ NeighborResponse(
+ id=nb.get("id", ""),
+ type=nb.get("type", ""),
+ content=nb.get("content", ""),
+ relationship=nb.get("relationship", ""),
+ weight=nb.get("weight", 1.0),
+ hop=nb.get("hop", 1),
+ )
+ for nb in neighbors
+ ]
+
+
+
+
[email protected]("/edges", response_model=EdgeListResponse)
+async def list_edges(
+ type: Optional[str] = Query(None, description="Filter by edge type"),
+ source: Optional[str] = Query(None, description="Filter by source node ID"),
+ target: Optional[str] = Query(None, description="Filter by target node ID"),
+ skip: int = Query(0, ge=0),
+ limit: int = Query(100, ge=1, le=1000),
+ session: GraphSession = Depends(get_session),
+):
+ """List edges with optional filtering and pagination."""
+ edges, total = await asyncio.to_thread(
+ session.get_edges, edge_type=type, source=source, target=target, skip=skip, limit=limit
+ )
+ return EdgeListResponse(
+ edges=[
+ EdgeResponse(
+ source=e.get("source", ""),
+ target=e.get("target", ""),
+ type=e.get("type", ""),
+ weight=e.get("weight", 1.0),
+ properties=e.get("metadata", {}),
+ )
+ for e in edges
+ ],
+ total=total,
+ skip=skip,
+ limit=limit,
+ )
+
+
+
+
[email protected]("/node/{node_id}/path", response_model=PathResponse)
+async def find_path(
+ node_id: str,
+ target: str = Query(..., description="Target node ID"),
+ algorithm: str = Query("bfs", description="Algorithm: bfs, dijkstra"),
+ session: GraphSession = Depends(get_session),
+):
+ """Find a path between two nodes."""
+ pf = session.path_finder
+ if 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 []
+ total_weight = result.get("total_weight", 0.0) if isinstance(result, dict) else 0.0
+
+ return PathResponse(
+ source=node_id,
+ target=target,
+ algorithm=algorithm,
+ path=path_nodes,
+ total_weight=total_weight,
+ )
+
+
+
[email protected]("/search", response_model=SearchResultResponse)
+async def search_nodes(
+ body: SearchRequest,
+ session: GraphSession = Depends(get_session),
+):
+ """Keyword search over graph nodes."""
+ results = await asyncio.to_thread(session.search, body.query, body.limit)
+ items = [
+ SearchResultItem(
+ node=_node_dict_to_response(r.get("node", {})),
+ score=r.get("score", 0.0),
+ )
+ for r in results
+ ]
+ return SearchResultResponse(results=items, total=len(items), query=body.query)
+
+
+
[email protected]("/stats", response_model=GraphStatsResponse)
+async def graph_stats(
+ session: GraphSession = Depends(get_session),
+):
+ """Get graph-level statistics."""
+ stats = await asyncio.to_thread(session.get_stats)
+ return GraphStatsResponse(**stats)
+
+
+
+def _build_graph_dict(session: GraphSession) -> dict:
+ """Build a graph dict for analytics helpers (entities + relationships)."""
+ nodes, _ = session.get_nodes(skip=0, limit=999_999)
+ edges, _ = session.get_edges(skip=0, limit=999_999)
+ return {
+ "entities": [
+ {
+ "id": n.get("id"),
+ "type": n.get("type", "entity"),
+ "text": n.get("content", n.get("id", "")),
+ "metadata": n.get("metadata", {}),
+ }
+ for n in nodes
+ ],
+ "relationships": [
+ {
+ "source": e.get("source"),
+ "target": e.get("target"),
+ "type": e.get("type", "related_to"),
+ "metadata": e.get("metadata", {}),
+ }
+ for e in edges
+ ],
+ }
diff --git a/semantica/explorer/routes/temporal.py b/semantica/explorer/routes/temporal.py
new file mode 100644
index 00000000..844b9221
--- /dev/null
+++ b/semantica/explorer/routes/temporal.py
@@ -0,0 +1,125 @@
+"""
+Temporal routes — snapshot, diff, patterns.
+"""
+
+import asyncio
+from datetime import datetime, timezone
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Query
+
+from ..dependencies import get_session
+from ..schemas import (
+ NodeResponse,
+ TemporalDiffResponse,
+ TemporalPatternResponse,
+ TemporalSnapshotResponse,
+)
+from ..session import GraphSession
+
+router = APIRouter(prefix="/api/temporal", tags=["Temporal"])
+
+
+def _node_dict_to_response(n: dict) -> NodeResponse:
+ meta = n.get("metadata", {})
+ return NodeResponse(
+ id=n.get("id", ""),
+ type=n.get("type", "entity"),
+ content=n.get("content", meta.get("content", "")),
+ properties=meta,
+ valid_from=meta.get("valid_from"),
+ valid_until=meta.get("valid_until"),
+ )
+
+
[email protected]("/snapshot", response_model=TemporalSnapshotResponse)
+async def temporal_snapshot(
+ at: Optional[str] = Query(
+ None, description="ISO-8601 datetime; defaults to now."
+ ),
+ session: GraphSession = Depends(get_session),
+):
+ """
+ Return the graph as it existed at a given timestamp.
+
+ Only nodes whose ``valid_from`` / ``valid_until`` window includes
+ the requested time are returned.
+ """
+ if at:
+ ts_str = at.replace("Z", "+00:00")
+ at_time = datetime.fromisoformat(ts_str)
+ else:
+ at_time = datetime.now(timezone.utc)
+
+ active = await asyncio.to_thread(session.get_active_nodes, at_time=at_time)
+ return TemporalSnapshotResponse(
+ timestamp=at_time.isoformat(),
+ active_nodes=[_node_dict_to_response(n) for n in active],
+ active_node_count=len(active),
+ )
+
+
[email protected]("/diff", response_model=TemporalDiffResponse)
+async def temporal_diff(
+ from_time: str = Query(..., description="Start ISO-8601 datetime"),
+ to_time: str = Query(..., description="End ISO-8601 datetime"),
+ session: GraphSession = Depends(get_session),
+):
+ """
+ Diff the graph between two points in time.
+
+ Returns node IDs that were added (active at ``to_time`` but not
+ ``from_time``) and removed (active at ``from_time`` but not
+ ``to_time``).
+ """
+ t1 = datetime.fromisoformat(from_time.replace("Z", "+00:00"))
+ t2 = datetime.fromisoformat(to_time.replace("Z", "+00:00"))
+
+ active_t1 = await asyncio.to_thread(session.get_active_nodes, at_time=t1)
+ active_t2 = await asyncio.to_thread(session.get_active_nodes, at_time=t2)
+
+ ids_t1 = {n.get("id") for n in active_t1}
+ ids_t2 = {n.get("id") for n in active_t2}
+
+ return TemporalDiffResponse(
+ from_time=t1.isoformat(),
+ to_time=t2.isoformat(),
+ added_nodes=sorted(ids_t2 - ids_t1),
+ removed_nodes=sorted(ids_t1 - ids_t2),
+ )
+
+
[email protected]("/patterns", response_model=TemporalPatternResponse)
+async def temporal_patterns(
+ session: GraphSession = Depends(get_session),
+):
+ """
+ Detect temporal patterns (trends, cycles, anomalies).
+
+ Falls back to a stub when ``TemporalPatternDetector`` is not available.
+ """
+ try:
+ from ...kg import TemporalPatternDetector
+ detector = TemporalPatternDetector()
+
+
+ nodes, _ = session.get_nodes(skip=0, limit=999_999)
+ edges, _ = session.get_edges(skip=0, limit=999_999)
+ graph_dict = {
+ "entities": [
+ {"id": n.get("id"), "type": n.get("type"), "metadata": n.get("metadata", {})}
+ for n in nodes
+ ],
+ "relationships": [
+ {"source": e.get("source"), "target": e.get("target"),
+ "type": e.get("type"), "metadata": e.get("metadata", {})}
+ for e in edges
+ ],
+ }
+
+ patterns = await asyncio.to_thread(detector.detect_patterns, graph_dict)
+ if isinstance(patterns, dict):
+ patterns = patterns.get("patterns", [])
+ return TemporalPatternResponse(patterns=patterns if isinstance(patterns, list) else [])
+ except Exception:
+ return TemporalPatternResponse(patterns=[])
diff --git a/semantica/explorer/schemas.py b/semantica/explorer/schemas.py
new file mode 100644
index 00000000..3e63ab14
--- /dev/null
+++ b/semantica/explorer/schemas.py
@@ -0,0 +1,257 @@
+"""
+Semantica Explorer : Pydantic Schemas
+
+All request/response models for the Knowledge Explorer REST API.
+"""
+
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Union
+
+from pydantic import BaseModel, Field
+
+
+
+class ErrorResponse(BaseModel):
+ """Standard error envelope."""
+ detail: str
+ status_code: int = 500
+
+
+
+class NodeResponse(BaseModel):
+ """Single node representation."""
+ id: str
+ type: str
+ content: str = ""
+ properties: Dict[str, Any] = Field(default_factory=dict)
+ valid_from: Optional[str] = None
+ valid_until: Optional[str] = None
+
+
+class EdgeResponse(BaseModel):
+ """Single edge representation."""
+ source: str
+ target: str
+ type: str
+ weight: float = 1.0
+ properties: Dict[str, Any] = Field(default_factory=dict)
+
+
+class NodeListResponse(BaseModel):
+ """Paginated node list."""
+ nodes: List[NodeResponse]
+ total: int
+ skip: int = 0
+ limit: int = 100
+
+
+class EdgeListResponse(BaseModel):
+ """Paginated edge list."""
+ edges: List[EdgeResponse]
+ total: int
+ skip: int = 0
+ limit: int = 100
+
+
+class NeighborResponse(BaseModel):
+ """Neighbor node with relationship info."""
+ id: str
+ type: str
+ content: str = ""
+ relationship: str = ""
+ weight: float = 1.0
+ hop: int = 1
+
+
+class PathResponse(BaseModel):
+ """Path between two nodes."""
+ source: str
+ target: str
+ algorithm: str
+ path: List[str]
+ total_weight: float = 0.0
+
+
+class GraphStatsResponse(BaseModel):
+ """Graph-level statistics."""
+ node_count: int
+ edge_count: int
+ node_types: Dict[str, int] = Field(default_factory=dict)
+ edge_types: Dict[str, int] = Field(default_factory=dict)
+ density: float = 0.0
+
+
+class SearchRequest(BaseModel):
+ """Search request body."""
+ query: str
+ filters: Optional[Dict[str, Any]] = None
+ limit: int = 20
+
+
+class SearchResultItem(BaseModel):
+ """Single search result."""
+ node: NodeResponse
+ score: float = 0.0
+
+
+class SearchResultResponse(BaseModel):
+ """Search results."""
+ results: List[SearchResultItem]
+ total: int
+ query: str
+
+
+
+
+class AnalyticsResponse(BaseModel):
+ """Analytics results."""
+ centrality: Optional[Dict[str, Any]] = None
+ community: Optional[Dict[str, Any]] = None
+ connectivity: Optional[Dict[str, Any]] = None
+
+
+class ValidationIssue(BaseModel):
+ """Single validation error or warning."""
+ severity: str # "error" or "warning"
+ message: str
+ node_id: Optional[str] = None
+ edge_source: Optional[str] = None
+ edge_target: Optional[str] = None
+
+
+class ValidationReportResponse(BaseModel):
+ """Graph validation report."""
+ valid: bool
+ error_count: int = 0
+ warning_count: int = 0
+ issues: List[ValidationIssue] = Field(default_factory=list)
+
+
+
+class DecisionResponse(BaseModel):
+ """Single decision."""
+ decision_id: str
+ category: str = ""
+ scenario: str = ""
+ reasoning: str = ""
+ outcome: str = ""
+ confidence: float = 0.0
+ timestamp: Optional[str] = None
+ metadata: Dict[str, Any] = Field(default_factory=dict)
+
+
+class CausalChainResponse(BaseModel):
+ """Causal chain for a decision."""
+ decision_id: str
+ chain: List[Dict[str, Any]] = Field(default_factory=list)
+
+
+class ComplianceResponse(BaseModel):
+ """Policy compliance check result."""
+ decision_id: str
+ compliant: bool = True
+ violations: List[Dict[str, Any]] = Field(default_factory=list)
+
+
+
+class TemporalSnapshotResponse(BaseModel):
+ """Graph state at a point in time."""
+ timestamp: str
+ active_nodes: List[NodeResponse]
+ active_node_count: int
+
+
+class TemporalDiffResponse(BaseModel):
+ """Diff between two temporal snapshots."""
+ from_time: str
+ to_time: str
+ added_nodes: List[str] = Field(default_factory=list)
+ removed_nodes: List[str] = Field(default_factory=list)
+
+
+class TemporalPatternResponse(BaseModel):
+ """Detected temporal patterns."""
+ patterns: List[Dict[str, Any]] = Field(default_factory=list)
+
+
+class EnrichExtractRequest(BaseModel):
+ """Entity/relation extraction from text."""
+ text: str
+
+
+class EnrichExtractResponse(BaseModel):
+ """Extraction results."""
+ entities: List[Dict[str, Any]] = Field(default_factory=list)
+ relations: List[Dict[str, Any]] = Field(default_factory=list)
+
+
+class LinkPredictionRequest(BaseModel):
+ """Link prediction request."""
+ node_id: str
+ top_n: int = 10
+
+
+class LinkPredictionResponse(BaseModel):
+ """Link prediction results."""
+ node_id: str
+ predictions: List[Dict[str, Any]] = Field(default_factory=list)
+
+
+class DedupRequest(BaseModel):
+ """Deduplication scan request."""
+ threshold: float = 0.8
+
+
+class DedupResponse(BaseModel):
+ """Deduplication results."""
+ duplicates: List[Dict[str, Any]] = Field(default_factory=list)
+ total_flagged: int = 0
+
+
+class ReasoningRequest(BaseModel):
+ """Reasoning request."""
+ facts: List[str]
+ rules: List[str]
+ mode: str = "forward" # forward, backward, rete
+
+
+class ReasoningResponse(BaseModel):
+ """Reasoning results."""
+ inferred_facts: List[str] = Field(default_factory=list)
+ rules_fired: int = 0
+
+
+
+
+class ExportRequest(BaseModel):
+ """Export request."""
+ format: str = "json"
+ node_ids: Optional[List[str]] = None
+
+
+class ExportResponse(BaseModel):
+ """Export result metadata."""
+ format: str
+ content_type: str
+ filename: str
+ size_bytes: int = 0
+
+
+
+
+class AnnotationCreate(BaseModel):
+ """Create an annotation."""
+ node_id: str
+ content: str
+ tags: List[str] = Field(default_factory=list)
+ visibility: str = "public"
+
+
+class AnnotationResponse(BaseModel):
+ """Single annotation."""
+ annotation_id: str
+ node_id: str
+ content: str
+ tags: List[str] = Field(default_factory=list)
+ visibility: str = "public"
+ created_at: str = ""
diff --git a/semantica/explorer/session.py b/semantica/explorer/session.py
new file mode 100644
index 00000000..de0ff3b2
--- /dev/null
+++ b/semantica/explorer/session.py
@@ -0,0 +1,211 @@
+"""
+Semantica Explorer : Graph Session
+
+Holds a loaded ContextGraph together with lazily-initialized analytics
+components. One session is created at server startup and shared across
+all API requests via FastAPI's dependency injection.
+"""
+
+import threading
+import uuid
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+from ..context.context_graph import ContextGraph
+
+_KG_AVAILABLE = False
+try:
+ from ..kg import (
+ CentralityCalculator,
+ CommunityDetector,
+ ConnectivityAnalyzer,
+ GraphValidator,
+ LinkPredictor,
+ NodeEmbedder,
+ PathFinder,
+ SimilarityCalculator,
+ )
+ _KG_AVAILABLE = True
+except ImportError:
+ pass
+
+
+class GraphSession:
+ """
+ Holds a loaded graph and its associated analytics components.
+
+ Thread safety: all mutations to the graph or the annotations store
+ must go through methods on this class, which are protected by an
+ ``RLock``.
+ """
+
+ def __init__(self, graph: ContextGraph) -> None:
+ self.graph = graph
+ self._lock = threading.RLock()
+
+
+ self.annotations: Dict[str, Dict[str, Any]] = {}
+
+
+ self._centrality: Any = None
+ self._community: Any = None
+ self._connectivity: Any = None
+ self._path_finder: Any = None
+ self._node_embedder: Any = None
+ self._similarity: Any = None
+ self._link_predictor: Any = None
+ self._validator: Any = None
+
+
+ @classmethod
+ def from_file(cls, path: str) -> "GraphSession":
+ """Load a ContextGraph from a JSON file and wrap it in a session."""
+ graph = ContextGraph()
+ 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
+
+
+ def get_node(self, node_id: str) -> Optional[Dict[str, Any]]:
+ """Get a single node by ID, or ``None``."""
+ with self._lock:
+ return self.graph.find_node(node_id)
+
+ def get_nodes(
+ self,
+ node_type: Optional[str] = None,
+ search: Optional[str] = None,
+ skip: int = 0,
+ limit: int = 100,
+ ) -> tuple[list[dict[str, Any]], int]:
+ """Return a paginated slice of nodes and the total count."""
+ with self._lock:
+ 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, total
+
+ def get_edges(
+ self,
+ edge_type: Optional[str] = None,
+ source: Optional[str] = None,
+ target: Optional[str] = None,
+ skip: int = 0,
+ limit: int = 100,
+ ) -> tuple[list[dict[str, Any]], int]:
+ """Return a paginated slice of edges and the total count."""
+ with self._lock:
+ 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, total
+
+ def get_neighbors(self, node_id: str, depth: int = 1) -> List[Dict[str, Any]]:
+ """Get neighbours for a node (BFS). Returns [] for unknown nodes."""
+ with self._lock:
+ return self.graph.get_neighbors(node_id, hops=depth)
+
+ def search(self, query: str, limit: int = 20) -> List[Dict[str, Any]]:
+ """Keyword search across node content."""
+ with self._lock:
+ return self.graph.query(query)[:limit]
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Graph-level statistics."""
+ with self._lock:
+ return self.graph.stats()
+
+ def get_active_nodes(
+ self, at_time: Optional[datetime] = None, node_type: Optional[str] = None
+ ) -> List[Dict[str, Any]]:
+ """Nodes active at a given point in time."""
+ 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."""
+ ann_id = str(uuid.uuid4())
+ annotation["annotation_id"] = ann_id
+ annotation["created_at"] = datetime.utcnow().isoformat()
+ with self._lock:
+ self.annotations[ann_id] = annotation
+ return ann_id
+
+ def get_annotations(self, node_id: Optional[str] = None) -> List[Dict[str, Any]]:
+ """List annotations, optionally filtered by node_id."""
+ with self._lock:
+ anns = list(self.annotations.values())
+ if node_id:
+ anns = [a for a in anns if a.get("node_id") == node_id]
+ return anns
+
+ def delete_annotation(self, annotation_id: str) -> bool:
+ """Delete an annotation. Returns True if found and deleted."""
+ with self._lock:
+ return self.annotations.pop(annotation_id, None) is not None
diff --git a/semantica/explorer/ws.py b/semantica/explorer/ws.py
new file mode 100644
index 00000000..f71dfab3
--- /dev/null
+++ b/semantica/explorer/ws.py
@@ -0,0 +1,91 @@
+"""
+Semantica Explorer : WebSocket Connection Manager
+
+Manages WebSocket connections for real-time graph updates,
+import progress events, and mutation broadcasts.
+"""
+
+import asyncio
+import json
+import threading
+from datetime import datetime, timezone
+from typing import Any, Dict, Set
+
+from fastapi import WebSocket
+
+
+class ConnectionManager:
+ """
+ Thread-safe WebSocket connection manager.
+
+ Maintains a set of active WebSocket connections and provides
+ methods to broadcast events to all connected clients.
+ """
+
+ def __init__(self):
+ self._active_connections: Set[WebSocket] = set()
+ self._lock = threading.Lock()
+
+ async def connect(self, websocket: WebSocket) -> None:
+ """Accept a WebSocket connection and add it to the active set."""
+ await websocket.accept()
+ with self._lock:
+ self._active_connections.add(websocket)
+
+ def disconnect(self, websocket: WebSocket) -> None:
+ """Remove a WebSocket connection from the active set."""
+ with self._lock:
+ self._active_connections.discard(websocket)
+
+ @property
+ def active_count(self) -> int:
+ """Number of active connections."""
+ with self._lock:
+ return len(self._active_connections)
+
+ async def broadcast(self, event_type: str, data: Any = None) -> None:
+ """
+ Broadcast a JSON message to all connected clients.
+
+ Args:
+ event_type: Event type string (e.g., "node_added", "import_progress").
+ data: Arbitrary JSON-serialisable payload.
+ """
+ message = json.dumps(
+ {
+ "event": event_type,
+ "data": data,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ },
+ default=str,
+ )
+
+ with self._lock:
+ connections = set(self._active_connections)
+
+
+ disconnected: list[WebSocket] = []
+ for ws in connections:
+ try:
+ await ws.send_text(message)
+ except Exception:
+ disconnected.append(ws)
+
+ if disconnected:
+ with self._lock:
+ for ws in disconnected:
+ self._active_connections.discard(ws)
+
+ async def send_personal(
+ self, websocket: WebSocket, event_type: str, data: Any = None
+ ) -> None:
+ """Send a message to a single client."""
+ message = json.dumps(
+ {
+ "event": event_type,
+ "data": data,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ },
+ default=str,
+ )
+ await websocket.send_text(message)
diff --git a/tests/explorer/__init__.py b/tests/explorer/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/tests/explorer/test_explorer_api.py b/tests/explorer/test_explorer_api.py
new file mode 100644
index 00000000..e47f9661
--- /dev/null
+++ b/tests/explorer/test_explorer_api.py
@@ -0,0 +1,337 @@
+"""
+Integration tests for the Semantica Knowledge Explorer API.
+
+Uses FastAPI's TestClient (from starlette.testclient).
+"""
+
+import json
+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) is required for explorer tests. "
+ "Install with: pip install semantica[explorer]",
+ allow_module_level=True,
+ )
+
+
+
+def _build_sample_graph() -> ContextGraph:
+ """Create a small ContextGraph with a handful of nodes and edges."""
+ g = ContextGraph(advanced_analytics=False)
+
+ g.add_node("python", node_type="language", content="Python programming language",
+ popularity="high")
+ g.add_node("javascript", node_type="language", content="JavaScript programming language")
+ g.add_node("web_dev", node_type="concept", content="Web Development")
+ g.add_node("ml", node_type="concept", content="Machine Learning")
+ g.add_node("decision_1", node_type="decision", content="Approve ML framework",
+ category="tech", scenario="Choosing ML framework", outcome="approved",
+ confidence="0.9", reasoning="Best performance")
+ g.add_node("decision_2", node_type="decision", content="Reject legacy stack",
+ category="tech", scenario="Choosing ML framework alternative",
+ outcome="rejected", confidence="0.4", reasoning="Outdated")
+ g.add_node("temporal_node", node_type="event", content="Conference talk",
+ valid_from="2025-01-01T00:00:00", valid_until="2025-12-31T23:59:59")
+
+ g.add_edge("python", "ml", edge_type="used_in", weight=0.9)
+ g.add_edge("javascript", "web_dev", edge_type="used_in", weight=0.8)
+ g.add_edge("python", "web_dev", edge_type="used_in", weight=0.5)
+ g.add_edge("decision_1", "ml", edge_type="about")
+
+ return g
+
+
[email protected](scope="module")
+def client():
+ """FastAPI TestClient backed by a sample graph."""
+ graph = _build_sample_graph()
+ session = GraphSession(graph)
+ app = create_app(session=session)
+ with TestClient(app) as c:
+ yield c
+
+
+
+class TestHealthInfo:
+ def test_health(self, client):
+ r = client.get("/api/health")
+ assert r.status_code == 200
+ assert r.json()["status"] == "healthy"
+
+ def test_info(self, client):
+ r = client.get("/api/info")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["name"] == "Semantica Knowledge Explorer"
+ assert "version" in body
+
+
+
+class TestGraphNodes:
+ def test_list_nodes(self, client):
+ r = client.get("/api/graph/nodes")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["total"] >= 5
+ assert len(body["nodes"]) <= body["total"]
+
+ def test_list_nodes_pagination(self, client):
+ r = client.get("/api/graph/nodes?skip=0&limit=2")
+ assert r.status_code == 200
+ body = r.json()
+ assert len(body["nodes"]) == 2
+ assert body["limit"] == 2
+
+ def test_list_nodes_filter_type(self, client):
+ r = client.get("/api/graph/nodes?type=language")
+ assert r.status_code == 200
+ body = r.json()
+ assert all(n["type"] == "language" for n in body["nodes"])
+
+ def test_list_nodes_search(self, client):
+ r = client.get("/api/graph/nodes?search=python")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["total"] >= 1
+
+ def test_get_node(self, client):
+ r = client.get("/api/graph/node/python")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["id"] == "python"
+ assert body["type"] == "language"
+
+ def test_get_node_not_found(self, client):
+ r = client.get("/api/graph/node/nonexistent_xyz")
+ assert r.status_code == 404
+
+ def test_get_neighbors(self, client):
+ r = client.get("/api/graph/node/python/neighbors")
+ assert r.status_code == 200
+ body = r.json()
+ assert isinstance(body, list)
+ assert len(body) >= 1
+ ids = [nb["id"] for nb in body]
+ assert "ml" in ids or "web_dev" in ids
+
+
+
+
+class TestGraphEdges:
+ def test_list_edges(self, client):
+ r = client.get("/api/graph/edges")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["total"] >= 3
+
+ def test_list_edges_filter_type(self, client):
+ r = client.get("/api/graph/edges?type=used_in")
+ assert r.status_code == 200
+ body = r.json()
+ assert all(e["type"] == "used_in" for e in body["edges"])
+
+ def test_list_edges_filter_source(self, client):
+ r = client.get("/api/graph/edges?source=python")
+ assert r.status_code == 200
+ body = r.json()
+ assert all(e["source"] == "python" for e in body["edges"])
+
+
+
+
+class TestSearchStats:
+ def test_search(self, client):
+ r = client.post("/api/graph/search", json={"query": "programming", "limit": 5})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["query"] == "programming"
+ assert len(body["results"]) >= 1
+
+ def test_stats(self, client):
+ r = client.get("/api/graph/stats")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["node_count"] >= 5
+ assert body["edge_count"] >= 3
+ assert "density" in body
+
+
+class TestDecisions:
+ def test_list_decisions(self, client):
+ r = client.get("/api/decisions")
+ assert r.status_code == 200
+ body = r.json()
+ assert isinstance(body, list)
+ assert len(body) >= 1
+
+ def test_list_decisions_category(self, client):
+ r = client.get("/api/decisions?category=tech")
+ assert r.status_code == 200
+ body = r.json()
+ assert all(d["category"] == "tech" for d in body)
+
+ 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"
+
+ def test_get_decision_not_found(self, client):
+ r = client.get("/api/decisions/nope")
+ assert r.status_code == 404
+
+ def test_causal_chain(self, client):
+ r = client.get("/api/decisions/decision_1/chain")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["decision_id"] == "decision_1"
+ assert isinstance(body["chain"], list)
+
+ 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
+
+
+
+
+class TestTemporal:
+ def test_snapshot_now(self, client):
+ r = client.get("/api/temporal/snapshot")
+ assert r.status_code == 200
+ body = r.json()
+ assert "active_node_count" in body
+
+ def test_snapshot_at(self, client):
+ r = client.get("/api/temporal/snapshot?at=2025-06-15T00:00:00")
+ assert r.status_code == 200
+ body = r.json()
+ ids = [n["id"] for n in body["active_nodes"]]
+ assert "temporal_node" in ids
+
+ def test_diff(self, client):
+ r = client.get(
+ "/api/temporal/diff"
+ "?from_time=2024-01-01T00:00:00"
+ "&to_time=2025-06-15T00:00:00"
+ )
+ assert r.status_code == 200
+ body = 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
+
+ def test_validation(self, client):
+ r = client.get("/api/analytics/validation")
+ assert r.status_code == 200
+ body = r.json()
+ assert "valid" in body
+
+
+
+class TestReasoning:
+ def test_reason(self, client):
+ r = client.post(
+ "/api/reason",
+ json={
+ "facts": ["Person(Alice)", "Knows(Alice, Bob)"],
+ "rules": ["IF Knows(?x, ?y) THEN Connected(?x, ?y)"],
+ "mode": "forward",
+ },
+ )
+ assert r.status_code in (200, 422)
+
+
+
+
+class TestAnnotations:
+ def test_create_and_list(self, client):
+
+ r = client.post(
+ "/api/annotations",
+ json={"node_id": "python", "content": "Great language!", "tags": ["fav"]},
+ )
+ assert r.status_code == 201
+ ann = r.json()
+ assert ann["node_id"] == "python"
+ ann_id = ann["annotation_id"]
+
+ # List all
+ r = client.get("/api/annotations")
+ assert r.status_code == 200
+ assert any(a["annotation_id"] == ann_id for a in r.json())
+
+ # List filtered by node
+ r = client.get("/api/annotations?node_id=python")
+ assert r.status_code == 200
+ assert all(a["node_id"] == "python" for a in r.json())
+
+ # Delete
+ r = client.delete(f"/api/annotations/{ann_id}")
+ assert r.status_code == 204
+
+ def test_create_annotation_bad_node(self, client):
+ r = client.post(
+ "/api/annotations",
+ json={"node_id": "nonexistent", "content": "oops"},
+ )
+ assert r.status_code == 404
+
+ def test_delete_annotation_not_found(self, client):
+ r = client.delete("/api/annotations/no_such_id")
+ assert r.status_code == 404
+
+
+
+class TestExport:
+ def 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
+
+ def test_export_unsupported(self, client):
+ r = client.post("/api/export", json={"format": "pdf"})
+ assert r.status_code == 422
+
+
+
+
+class TestImport:
+ def test_import_json(self, client):
+ payload = json.dumps({
+ "nodes": [
+ {"id": "imported_node", "type": "test", "properties": {"content": "hello"}}
+ ],
+ "edges": [],
+ })
+ r = client.post(
+ "/api/import",
+ files={"file": ("import.json", payload, "application/json")},
+ )
+ assert r.status_code == 200
+ body = r.json()
+ assert body["status"] == "success"
+ assert body["nodes_added"] >= 1
+
+ r2 = client.get("/api/graph/node/imported_node")
+ assert r2.status_code == 200