Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(explorer): implement phase 1: single-server deployment and dockerization
ZohaibHassan1660c00fb5c21a
diff --git a/DockerFile b/DockerFilenew file mode 100644index 00000000..d57e6abf--- /dev/null+++ b/DockerFile@@ -0,0 +1,29 @@+FROM node:20-alpine AS frontend-builder++WORKDIR /app/semantica-explorer+++COPY semantica-explorer/package.json semantica-explorer/package-lock.json* ./+++RUN npm install+++COPY semantica-explorer/ ./+RUN npm run build+++FROM python:3.12-slim AS runtime++WORKDIR /app++COPY pyproject.toml ./+COPY semantica/ ./semantica/++COPY --from=frontend-builder /app/semantica/static ./semantica/static++RUN pip install --no-cache-dir ".[explorer]"++EXPOSE 8000++CMD ["python", "-m", "uvicorn", "semantica.server:app", "--host", "0.0.0.0", "--port", "8000"]\ No newline at end of filediff --git a/semantica-explorer/vite.config.ts b/semantica-explorer/vite.config.tsindex 08d68e69..0d577015 100644--- a/semantica-explorer/vite.config.ts+++ b/semantica-explorer/vite.config.ts@@ -1,6 +1,7 @@import { defineConfig } from 'vite'import react, { reactCompilerPreset } from '@vitejs/plugin-react'import babel from '@rolldown/plugin-babel'+import path from 'path'// https://vite.dev/config/export default defineConfig({@@ -8,6 +9,13 @@ export default defineConfig({react(),babel({ presets: [reactCompilerPreset()] })],++ base: '/',+ build: {++ outDir: path.resolve(__dirname, '../semantica/static'),+ emptyOutDir: true,+ },server: {proxy: {'/api': {diff --git a/semantica/server.py b/semantica/server.pyindex 44ac7176..a5d0befc 100644--- a/semantica/server.py+++ b/semantica/server.py@@ -7,7 +7,10 @@ using FastAPI and uvicorn.import loggingimport uvicorn+from contextlib import asynccontextmanager+from pathlib import Pathfrom fastapi import FastAPI, HTTPException+from fastapi.responses import FileResponsefrom pydantic import BaseModelfrom typing import List, Optional, Dict, Any@@ -15,13 +18,51 @@ from . import __version__from .core.orchestrator import Semanticafrom .utils.logging import setup_logging+try:+ from .context.context_graph import ContextGraph+ from .explorer.session import GraphSession+ from .explorer.ws import ConnectionManager+ EXPLORER_AVAILABLE = True+except ImportError:+ EXPLORER_AVAILABLE = False+# Initialize loggingsetup_logging()+STATIC_DIR = Path(__file__).parent / "static"++@asynccontextmanager+async def lifespan(app: FastAPI):+ """Lifecycle manager for startup and shutdown events."""+ logging.info("Starting up Semantica API...")++ if EXPLORER_AVAILABLE:+ try:+ logging.info("Initializing Graph engine and Database connection...")+ graph = ContextGraph()+ app.state.session = GraphSession(graph)+ app.state.ws_manager = ConnectionManager()+ logging.info("Database Session and WebSockets attached to app state.")+ except Exception as e:+ logging.error(f"Failed to initialize GraphSession: {e}")+ app.state.session = None+ app.state.ws_manager = None+ else:+ app.state.session = None+ app.state.ws_manager = None++ yield++ logging.info("Shutting down Semantica API...")+ if getattr(app.state, "session", None) and hasattr(app.state.session.graph, "close"):+ app.state.session.graph.close()++app = FastAPI(title="Semantica API",description="REST API for the Semantica Framework",- version=__version__+ version=__version__,+ lifespan=lifespan)# Global framework instance@@ -31,7 +72,8 @@ class BuildRequest(BaseModel):sources: List[str]config: Optional[Dict[str, Any]] = None[email protected]("/")+[email protected]("/api/info")async def root():"""Root endpoint returning framework info."""return {@@ -54,44 +96,60 @@ async def build_kb(request: BuildRequest):except Exception as e:raise HTTPException(status_code=500, detail=str(e))--# Explorer API Routers (Loaded gracefully if semantica[explorer] is installed)--try:- from .explorer.routes import (- analytics,- annotations,- decisions,- enrich,- export_import,- graph,- temporal,- )-- app.include_router(analytics.router)- app.include_router(annotations.router)- app.include_router(decisions.router)- app.include_router(enrich.router)- app.include_router(export_import.router)- app.include_router(graph.router)- app.include_router(temporal.router)-- logging.info("Explorer API routes successfully mounted.")--except ImportError as exc:+# -Mount explorer routes+if EXPLORER_AVAILABLE:+ try:+ from .explorer.routes import (+ analytics,+ annotations,+ decisions,+ enrich,+ export_import,+ graph,+ temporal,+ vocabulary+ )++ app.include_router(analytics.router)+ app.include_router(annotations.router)+ app.include_router(decisions.router)+ app.include_router(enrich.router)+ app.include_router(export_import.router)+ app.include_router(graph.router)+ app.include_router(temporal.router)+ app.include_router(vocabulary.router)++ logging.info("Explorer and Vocabulary API routes successfully mounted.")+ except Exception as exc:+ logging.error(f"Failed to mount explorer routes: {exc}")+else:logging.warning(- f"Explorer API routes not mounted. To enable the Knowledge Explorer, "- f"install the required dependencies: pip install semantica[explorer]. "- f"Details: {exc}"+ "Explorer API routes not mounted. To enable the Knowledge Explorer, "+ "install the required dependencies: pip install 'semantica[explorer]'.")-# Vocabulary router — mounted separately; available once PR #421 lands-try:- from .explorer.routes import vocabulary- app.include_router(vocabulary.router)- logging.info("Vocabulary API routes successfully mounted.")-except ImportError:- logging.debug("Vocabulary router not yet available (pending implementation).")+# SPA catch all+[email protected]("/{full_path:path}")+async def serve_spa(full_path: str):+ """+ Catch-all route that serves React assets and index.html for React Router.+ """+ requested_file = STATIC_DIR / full_path+++ if requested_file.is_file():+ return FileResponse(requested_file)+++ index_file = STATIC_DIR / "index.html"+ if index_file.is_file():+ return FileResponse(index_file)++ raise HTTPException(+ status_code=404,+ detail="Frontend not built. Run `npm run build` in semantica-explorer/ first."+ )def main():"""Server entry point."""