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
chore: resolve merge conflicts with origin/main
KaifAhmad11861ca578cf8
diff --cc explorer/src/workspaces/OntologyWorkspace/index.tsxindex 6ad45525,3e0fd251..d2c69593--- a/explorer/src/workspaces/OntologyWorkspace/index.tsx+++ b/explorer/src/workspaces/OntologyWorkspace/index.tsx@@@ -7,10 -7,9 +7,12 @@@ importShield,Sliders,} from "lucide-react";+import { AlignmentsTab } from "./AlignmentsTab";+import { HealthTab } from "./HealthTab";import { OntologyManager } from "./OntologyManager";+ import { OntologyEditor } from "./OntologyEditor";+import { ShaclStudio } from "./ShaclStudio";+ import { VersionsTab } from "./VersionsTab";export type OntologyHubTab =| "registry"@@@ -107,29 -94,36 +109,15 @@@ export function OntologyWorkspace({ onJcase "registry":return <OntologyManager />;case "editor":- return (- <ComingSoonStub- icon={Sliders}- title="Visual Ontology Editor"- description="Visually edit classes, properties, individuals, restrictions, axioms, and SKOS metadata. Create and propose schema changes through a governed draft workflow."- badge="Subissue 2"- />- );+ return <OntologyEditor />;case "versions":- return (- <ComingSoonStub- icon={Layers}- title="Versions & Change Proposals"- description="View version history, compare schema diffs, submit change proposals, and manage the review-to-publish lifecycle."- badge="Subissue 2"- />- );+ return <VersionsTab />;case "alignments":- return (- <ComingSoonStub- icon={GitMerge}- title="Cross-Ontology Alignments"- description="Manage mappings between ontologies, review suggested alignments from embedding-assisted similarity, and publish alignment sets."- badge="Subissue 3"- />- );+ return <AlignmentsTab />;case "health":- return (- <ComingSoonStub- icon={HeartPulse}- title="Ontology Health Dashboard"- description="Score completeness, consistency, SHACL conformance, alignment coverage, and documentation quality across all loaded ontologies."- badge="Subissue 3"- />- );+ return <HealthTab onFixInEditor={handleFixInEditor} />;case "shacl":- return (- <ComingSoonStub- icon={Shield}- title="SHACL Studio"- description="Generate, edit, and validate SHACL shapes. Preview constraint violations against the active graph before publishing."- badge="Subissue 3"- />- );+ return <ShaclStudio onJumpToNode={onJumpToGraphNode} />;}};diff --cc semantica/explorer/routes/ontology.pyindex 6ce9d9ce,6f4da820..411a6bb4--- a/semantica/explorer/routes/ontology.py+++ b/semantica/explorer/routes/ontology.py@@@ -7,24 -8,30 +8,33 @@@ import ipaddresimport loggingimport socketimport uuid- from datetime import UTC, datetime+ from datetime import datetime, UTC+from difflib import SequenceMatcher- from typing import Any, Dict, List, Literal, Optional+ from typing import Any, Dict, List, Optional, Tuplefrom urllib.parse import urlparse+ from typing_extensions import Literalfrom fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom pydantic import BaseModel, Field- from ..dependencies import get_sessionfrom ..session import GraphSession+ from ..dependencies import get_sessionfrom ..utils.rdf_parser import _safe_parse_rdf+ try:+ from rdflib.namespace import DCT, DC+ except ImportError:+ # Fallback if DCT/DC not available+ DCT = None+ DC = None- router = APIRouter(prefix="/api/ontology", tags=["Ontology"])logger = logging.getLogger(__name__)+ # Create router+ router = APIRouter(prefix="/api/ontology", tags=["ontology"])+_MAX_FETCH_BYTES = 20 * 1024 * 1024 # 20 MB+_MAX_ANALYSIS_NODES = 5_000 # cap for health/suggest/shacl node scans to avoid OOM+_MAX_ENTITIES_PER_SIDE = 500 # per-ontology cap for the O(n²) pairwise suggestion loop_CLASS_TYPES = frozenset({"owl:Class", "rdfs:Class",@@@ -76,16 -83,16 +86,26 @@@ _FORMAT_ALIASES: Dict[str, str] ="json": "json-ld",}+_ALIGNMENT_RELATIONS: Dict[str, str] = {+ "owl:equivalentClass": "http://www.w3.org/2002/07/owl#equivalentClass",+ "owl:equivalentProperty": "http://www.w3.org/2002/07/owl#equivalentProperty",+ "skos:exactMatch": "http://www.w3.org/2004/02/skos/core#exactMatch",+ "skos:closeMatch": "http://www.w3.org/2004/02/skos/core#closeMatch",+ "skos:broadMatch": "http://www.w3.org/2004/02/skos/core#broadMatch",+ "skos:narrowMatch": "http://www.w3.org/2004/02/skos/core#narrowMatch",+ "skos:relatedMatch": "http://www.w3.org/2004/02/skos/core#relatedMatch",+}++ _INGEST_FORMAT_SUFFIXES: Dict[str, str] = {+ "turtle": ".ttl",+ "xml": ".rdf",+ "json-ld": ".jsonld",+ "nt": ".nt",+ "n3": ".n3",+ "trig": ".trig",+ "nquads": ".nq",+ }+# ---------------------------------------------------------------------------# Schemas@@@ -217,141 -229,110 +242,245 @@@ class RefreshResponse(BaseModel)edges_added: int = 0+AlignmentRelation = Literal[+ "owl:equivalentClass",+ "owl:equivalentProperty",+ "skos:exactMatch",+ "skos:closeMatch",+ "skos:broadMatch",+ "skos:narrowMatch",+ "skos:relatedMatch",+]+++class OntologyAlignment(BaseModel):+ id: str+ source_uri: str+ source_label: str = ""+ target_uri: str+ target_label: str = ""+ relation: AlignmentRelation+ predicate_uri: str+ confidence: float = Field(default=1.0, ge=0.0, le=1.0)+ provenance: Optional[str] = None+ source: Optional[str] = None+ reviewer: Optional[str] = None+ created_at: str+ updated_at: str+++class OntologyAlignmentRequest(BaseModel):+ source_uri: str+ source_label: Optional[str] = None # override for external/unloaded URIs+ target_uri: str+ target_label: Optional[str] = None # override for external/unloaded URIs+ relation: AlignmentRelation+ confidence: float = Field(default=1.0, ge=0.0, le=1.0)+ provenance: Optional[str] = None+ source: Optional[str] = None+ reviewer: Optional[str] = None+++class AlignmentSuggestionRequest(BaseModel):+ source_ontology_uri: Optional[str] = None+ target_ontology_uri: Optional[str] = None+ threshold: float = Field(default=0.65, ge=0.0, le=1.0)+ limit: int = Field(default=25, ge=1, le=100)+++class AlignmentSuggestion(BaseModel):+ source_uri: str+ source_label: str+ target_uri: str+ target_label: str+ relation: AlignmentRelation+ score: float+ label_similarity: float+ embedding_similarity: Optional[float] = None+ reason: str+++class HealthDimension(BaseModel):+ key: str+ label: str+ score: float = Field(ge=0.0, le=100.0)+ status: Literal["ok", "warning", "critical", "unavailable"] = "ok"+ detail: str+++class HealthIssue(BaseModel):+ id: str+ severity: Literal["info", "warning", "critical"] = "warning"+ category: str+ entity_uri: Optional[str] = None+ entity_label: Optional[str] = None+ message: str+ action: Optional[str] = None+++class OntologyHealthResponse(BaseModel):+ uri: str+ name: str+ total_score: float = Field(ge=0.0, le=100.0)+ dimensions: List[HealthDimension]+ issues: List[HealthIssue] = Field(default_factory=list)+ generated_at: str+++class ShaclGenerateRequest(BaseModel):+ uri: str+ quality_tier: Literal["standard", "strict"] = "strict"+++class ShaclValidateRequest(BaseModel):+ uri: Optional[str] = None+ shacl_turtle: str+++class ShaclViolation(BaseModel):+ node: Optional[str] = None+ path: Optional[str] = None+ severity: str = "Violation"+ message: str+ focus_node: Optional[str] = None+ source_shape: Optional[str] = None+++class ShaclShapeSummary(BaseModel):+ id: str+ target_class: Optional[str] = None+ constraint_count: int = 0+ constraints: List[str] = Field(default_factory=list)+ violation_count: int = 0+++class ShaclGenerateResponse(BaseModel):+ uri: str+ shacl_turtle: str+ shape_count: int+ generated_at: str+++class ShaclShapesResponse(BaseModel):+ uri: str+ shapes: List[ShaclShapeSummary]+ shacl_turtle: str+ generated_at: str+++class ShaclValidationResponse(BaseModel):+ uri: Optional[str] = None+ conforms: bool+ status: Literal["success", "unavailable", "error"] = "success"+ message: str+ violations: List[ShaclViolation] = Field(default_factory=list)+ report_text: Optional[str] = None+++ # ---------------------------------------------------------------------------+ # Draft, Proposal, and Version Schemas+ # ---------------------------------------------------------------------------++ class DraftDiff(BaseModel):+ added_classes: List[str] = Field(default_factory=list)+ removed_classes: List[str] = Field(default_factory=list)+ modified_classes: Dict[str, Dict[str, Any]] = Field(default_factory=dict)+ added_properties: List[str] = Field(default_factory=list)+ removed_properties: List[str] = Field(default_factory=list)+ modified_properties: Dict[str, Dict[str, Any]] = Field(default_factory=dict)+ added_restrictions: List[Dict[str, Any]] = Field(default_factory=list)+ removed_restrictions: List[Dict[str, Any]] = Field(default_factory=list)+ added_axioms: List[Dict[str, Any]] = Field(default_factory=list)+ removed_axioms: List[Dict[str, Any]] = Field(default_factory=list)+ annotation_changes: Dict[str, Dict[str, Any]] = Field(default_factory=dict)+++ class DraftRequest(BaseModel):+ ontology_uri: str+ diff: DraftDiff+ author: str+ summary: Optional[str] = None+ timestamp: Optional[str] = None+++ class DraftResponse(BaseModel):+ draft_id: str+ ontology_uri: str+ diff: DraftDiff+ author: str+ summary: Optional[str] = None+ created_at: str+ updated_at: str+++ class ProposalState(BaseModel):+ state: Literal["draft", "proposed", "approved", "published", "rejected"]+++ class ProposalRequest(BaseModel):+ draft_id: str+ ontology_uri: str+ summary: str+ reviewer: Optional[str] = None+++ class ProposalResponse(BaseModel):+ proposal_id: str+ draft_id: str+ ontology_uri: str+ summary: str+ author: str+ reviewer: Optional[str] = None+ state: Literal["draft", "proposed", "approved", "published", "rejected"]+ impact_analysis: Dict[str, Any] = Field(default_factory=dict)+ shacl_validation: Dict[str, Any] = Field(default_factory=dict)+ created_at: str+ updated_at: str+ comments: List[Dict[str, Any]] = Field(default_factory=list)+++ class CommentRequest(BaseModel):+ element_uri: str+ text: str+ author: str+++ class VersionEntry(BaseModel):+ version_id: str+ ontology_uri: str+ state: Literal["draft", "published"]+ author: str+ date: str+ diff_summary: Dict[str, Any] = Field(default_factory=dict)+++ class VersionCompareRequest(BaseModel):+ version1: str+ version2: str+++ class VersionCompareResponse(BaseModel):+ version1: str+ version2: str+ metadata_changes: Dict[str, Any] = Field(default_factory=dict)+ class_changes: Dict[str, Any] = Field(default_factory=dict)+ property_changes: Dict[str, Any] = Field(default_factory=dict)+ restriction_changes: Dict[str, Any] = Field(default_factory=dict)+ axiom_changes: Dict[str, Any] = Field(default_factory=dict)+++ class AlignmentRequest(BaseModel):+ source_uri: str+ target_uri: str+ predicate: str+++ class AlignmentResponse(BaseModel):+ source: str+ predicate: str+ target: str++# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------@@@ -362,12 -343,54 +491,54 @@@ def _get_registry(request: Request) ->return request.app.state.ontology_registry+def _get_alignment_store(request: Request) -> Dict[str, OntologyAlignment]:+ if not hasattr(request.app.state, "ontology_alignments"):+ request.app.state.ontology_alignments = {}+ return request.app.state.ontology_alignments+++ def _get_drafts(request: Request) -> Dict[str, DraftResponse]:+ if not hasattr(request.app.state, "ontology_drafts"):+ request.app.state.ontology_drafts = {}+ return request.app.state.ontology_drafts+++ def _get_proposals(request: Request) -> Dict[str, ProposalResponse]:+ if not hasattr(request.app.state, "ontology_proposals"):+ request.app.state.ontology_proposals = {}+ return request.app.state.ontology_proposals+++ def _get_versions(request: Request) -> Dict[str, List[VersionEntry]]:+ if not hasattr(request.app.state, "ontology_versions"):+ request.app.state.ontology_versions = {}+ return request.app.state.ontology_versions++-def _get_alignment_store(request: Request) -> Dict[str, AlignmentResponse]:- if not hasattr(request.app.state, "ontology_alignment_store"):- request.app.state.ontology_alignment_store = {}- return request.app.state.ontology_alignment_store--+ def _alignment_key(source: str, predicate: str, target: str) -> str:+ return f"{source}::{predicate}::{target}"+++ def _coerce_alignment(raw: Any) -> Optional[AlignmentResponse]:+ if isinstance(raw, AlignmentResponse):+ return raw+ if isinstance(raw, dict):+ source = raw.get("source") or raw.get("source_uri")+ target = raw.get("target") or raw.get("target_uri")+ predicate = raw.get("predicate") or raw.get("relation")+ if source and target and predicate:+ return AlignmentResponse(source=source, predicate=predicate, target=target)+ return None+++ def _version_field(version: Any, field: str, default: Any = None) -> Any:+ if isinstance(version, VersionEntry):+ return getattr(version, field)+ if isinstance(version, dict):+ return version.get(field, default)+ return default++def _uri_to_prefix(uri: str) -> str:for base, prefix in _URI_PREFIX_MAP.items():if uri.startswith(base):@@@ -1159,454 -1348,136 +1708,538 @@@ async def get_skos_conceptconcept_uri: str,session: GraphSession = Depends(get_session),):- node = await asyncio.to_thread(session.get_node, concept_uri)- if node is None:- raise HTTPException(status_code=404, detail="Concept not found.")+ """Get SKOS concept detail using OntologyEngine.list_concepts() and search_concepts()."""+ try:+ from ...ontology import OntologyEngine++ # Initialize OntologyEngine with session's graph store+ engine_config = {"store": session.graph.store if hasattr(session.graph, "store") else None}+ engine = OntologyEngine(**engine_config)++ # Try to get scheme_uri from node first+ node = await asyncio.to_thread(session.get_node, concept_uri)+ if node is None:+ raise HTTPException(status_code=404, detail="Concept not found.")++ scheme_uri = node.get("properties", {}).get("scheme_uri")++ # Use OntologyEngine.list_concepts if scheme_uri is known+ if scheme_uri:+ concepts = await asyncio.to_thread(engine.list_concepts, scheme_uri)+ concept_data = next((c for c in concepts if c["uri"] == concept_uri), None)++ if concept_data:+ return SKOSConceptDetail(+ uri=concept_data["uri"],+ pref_label=concept_data["pref_label"],+ alt_labels=concept_data.get("alt_labels", []),+ hidden_labels=[],+ definition=None,+ scope_note=None,+ editorial_note=None,+ broader=[],+ narrower=[],+ related=[],+ exact_match=[],+ close_match=[],+ broad_match=[],+ narrow_match=[],+ scheme_uri=scheme_uri,+ )++ # Fallback to session-based implementation+ props = node.get("properties", {})+ out_edges, _ = await asyncio.to_thread(session.get_edges, source=concept_uri, skip=0, limit=9999)+ in_edges, _ = await asyncio.to_thread(session.get_edges, target=concept_uri, skip=0, limit=9999)++ def collect_out(rel: str) -> List[str]:+ return [e["target"] for e in out_edges if e.get("type") == rel]++ def collect_in(rel: str) -> List[str]:+ return [e["source"] for e in in_edges if e.get("type") == rel]++ pref_label = props.get("pref_label") or props.get("skos:prefLabel") or _node_label(node)+ alt_labels = props.get("alt_labels") or props.get("skos:altLabel") or []+ if isinstance(alt_labels, str):+ alt_labels = [alt_labels]+ hidden_labels = props.get("skos:hiddenLabel") or []+ if isinstance(hidden_labels, str):+ hidden_labels = [hidden_labels]++ if not scheme_uri:+ candidates = collect_out("skos:inScheme") or collect_out("skos:topConceptOf")+ scheme_uri = candidates[0] if candidates else None++ return SKOSConceptDetail(+ uri=concept_uri,+ pref_label=pref_label,+ alt_labels=list(alt_labels),+ hidden_labels=list(hidden_labels),+ definition=props.get("definition") or props.get("skos:definition"),+ scope_note=props.get("skos:scopeNote"),+ editorial_note=props.get("skos:editorialNote"),+ broader=collect_out("skos:broader") + collect_in("skos:narrower"),+ narrower=collect_out("skos:narrower") + collect_in("skos:broader"),+ related=collect_out("skos:related"),+ exact_match=collect_out("skos:exactMatch"),+ close_match=collect_out("skos:closeMatch"),+ broad_match=collect_out("skos:broadMatch"),+ narrow_match=collect_out("skos:narrowMatch"),+ scheme_uri=scheme_uri,+ )+ except HTTPException:+ raise+ except Exception as exc:+ logger.warning(f"OntologyEngine SKOS methods failed, using fallback: {exc}")+ # Fallback to session-based implementation+ node = await asyncio.to_thread(session.get_node, concept_uri)+ if node is None:+ raise HTTPException(status_code=404, detail="Concept not found.")- props = node.get("properties", {})- out_edges, _ = await asyncio.to_thread(session.get_edges, source=concept_uri, skip=0, limit=9999)- in_edges, _ = await asyncio.to_thread(session.get_edges, target=concept_uri, skip=0, limit=9999)-- def collect_out(rel: str) -> List[str]:- return [e["target"] for e in out_edges if e.get("type") == rel]-- def collect_in(rel: str) -> List[str]:- return [e["source"] for e in in_edges if e.get("type") == rel]-- pref_label = props.get("pref_label") or props.get("skos:prefLabel") or _node_label(node)- alt_labels = props.get("alt_labels") or props.get("skos:altLabel") or []- if isinstance(alt_labels, str):- alt_labels = [alt_labels]- hidden_labels = props.get("skos:hiddenLabel") or []- if isinstance(hidden_labels, str):- hidden_labels = [hidden_labels]-- scheme_uri = props.get("scheme_uri")- if not scheme_uri:- candidates = collect_out("skos:inScheme") or collect_out("skos:topConceptOf")- scheme_uri = candidates[0] if candidates else None-- return SKOSConceptDetail(- uri=concept_uri,- pref_label=pref_label,- alt_labels=list(alt_labels),- hidden_labels=list(hidden_labels),- definition=props.get("definition") or props.get("skos:definition"),- scope_note=props.get("skos:scopeNote"),- editorial_note=props.get("skos:editorialNote"),- broader=collect_out("skos:broader") + collect_in("skos:narrower"),- narrower=collect_out("skos:narrower") + collect_in("skos:broader"),- related=collect_out("skos:related"),- exact_match=collect_out("skos:exactMatch"),- close_match=collect_out("skos:closeMatch"),- broad_match=collect_out("skos:broadMatch"),- narrow_match=collect_out("skos:narrowMatch"),- scheme_uri=scheme_uri,- )+ props = node.get("properties", {})+ out_edges, _ = await asyncio.to_thread(session.get_edges, source=concept_uri, skip=0, limit=9999)+ in_edges, _ = await asyncio.to_thread(session.get_edges, target=concept_uri, skip=0, limit=9999)++ def collect_out(rel: str) -> List[str]:+ return [e["target"] for e in out_edges if e.get("type") == rel]++ def collect_in(rel: str) -> List[str]:+ return [e["source"] for e in in_edges if e.get("type") == rel]++ pref_label = props.get("pref_label") or props.get("skos:prefLabel") or _node_label(node)+ alt_labels = props.get("alt_labels") or props.get("skos:altLabel") or []+ if isinstance(alt_labels, str):+ alt_labels = [alt_labels]+ hidden_labels = props.get("skos:hiddenLabel") or []+ if isinstance(hidden_labels, str):+ hidden_labels = [hidden_labels]++ scheme_uri = props.get("scheme_uri")+ if not scheme_uri:+ candidates = collect_out("skos:inScheme") or collect_out("skos:topConceptOf")+ scheme_uri = candidates[0] if candidates else None++ return SKOSConceptDetail(+ uri=concept_uri,+ pref_label=pref_label,+ alt_labels=list(alt_labels),+ hidden_labels=list(hidden_labels),+ definition=props.get("definition") or props.get("skos:definition"),+ scope_note=props.get("skos:scopeNote"),+ editorial_note=props.get("skos:editorialNote"),+ broader=collect_out("skos:broader") + collect_in("skos:narrower"),+ narrower=collect_out("skos:narrower") + collect_in("skos:broader"),+ related=collect_out("skos:related"),+ exact_match=collect_out("skos:exactMatch"),+ close_match=collect_out("skos:closeMatch"),+ broad_match=collect_out("skos:broadMatch"),+ narrow_match=collect_out("skos:narrowMatch"),+ scheme_uri=scheme_uri,+ )+# alignments, health, and SHACL studio++[email protected]("/alignments", response_model=List[OntologyAlignment])+async def list_alignments(+ request: Request,+ uri: Optional[str] = Query(None),+):+ store = _get_alignment_store(request)+ alignments = list(store.values())+ if uri:+ alignments = [+ item for item in alignments+ if item.source_uri.startswith(uri) or item.target_uri.startswith(uri)+ ]+ return sorted(alignments, key=lambda item: (item.source_label, item.target_label, item.relation))++[email protected]("/alignments", response_model=OntologyAlignment)+async def upsert_alignment(+ request: Request,+ body: OntologyAlignmentRequest,+ session: GraphSession = Depends(get_session),+):+ source_node = await asyncio.to_thread(session.get_node, body.source_uri)+ target_node = await asyncio.to_thread(session.get_node, body.target_uri)+ # External vocabulary URIs (e.g. schema.org, DBpedia) are not in the local+ # graph; fall back to a label derived from the URI or the caller-supplied label.+ source_label = (+ body.source_label+ or (_node_label(source_node) if source_node is not None else None)+ or _label_from_uri(body.source_uri)+ )+ target_label = (+ body.target_label+ or (_node_label(target_node) if target_node is not None else None)+ or _label_from_uri(body.target_uri)+ )++ now = datetime.now(UTC).isoformat()+ store = _get_alignment_store(request)+ alignment_id = _alignment_id(body.source_uri, body.relation, body.target_uri)+ existing = store.get(alignment_id)+ alignment = OntologyAlignment(+ id=alignment_id,+ source_uri=body.source_uri,+ source_label=source_label,+ target_uri=body.target_uri,+ target_label=target_label,+ relation=body.relation,+ predicate_uri=_ALIGNMENT_RELATIONS[body.relation],+ confidence=body.confidence,+ provenance=body.provenance,+ source=body.source,+ reviewer=body.reviewer,+ created_at=existing.created_at if existing else now,+ updated_at=now,+ )+ store[alignment_id] = alignment+ # OntologyEngine.create_alignment() requires a TripletStore (e.g. FalkorDB) which is+ # not configured in the explorer deployment. Alignments are intentionally stored only+ # in request.app.state (session memory). The ephemeral-storage banner in the UI+ # communicates this limitation to users.+ return alignment++[email protected]("/alignments")+async def delete_alignment(request: Request, id: str = Query(...)):+ store = _get_alignment_store(request)+ if id not in store:+ raise HTTPException(status_code=404, detail="Alignment not found.")+ del store[id]+ return {"status": "removed", "id": id}++[email protected]("/suggest-alignments", response_model=List[AlignmentSuggestion])+async def suggest_alignments(+ body: AlignmentSuggestionRequest,+ session: GraphSession = Depends(get_session),+):+ nodes, total_count = await asyncio.to_thread(session.get_nodes, skip=0, limit=_MAX_ANALYSIS_NODES)+ if total_count > _MAX_ANALYSIS_NODES:+ logger.warning(+ "suggest-alignments: graph has %d nodes; analysis capped at %d. "+ "Filter by source/target ontology URI for more accurate results.",+ total_count, _MAX_ANALYSIS_NODES,+ )+ source_nodes = _ontology_entities(nodes, body.source_ontology_uri)+ target_nodes = _ontology_entities(nodes, body.target_ontology_uri)+ if not body.source_ontology_uri:+ source_nodes = _ontology_entities(nodes)+ if not body.target_ontology_uri:+ target_nodes = _ontology_entities(nodes)++ # Per-side entity cap to bound the O(n²) comparison loop.+ if len(source_nodes) > _MAX_ENTITIES_PER_SIDE:+ logger.warning("suggest-alignments: source side capped at %d entities.", _MAX_ENTITIES_PER_SIDE)+ source_nodes = source_nodes[:_MAX_ENTITIES_PER_SIDE]+ if len(target_nodes) > _MAX_ENTITIES_PER_SIDE:+ logger.warning("suggest-alignments: target side capped at %d entities.", _MAX_ENTITIES_PER_SIDE)+ target_nodes = target_nodes[:_MAX_ENTITIES_PER_SIDE]++ # Build TF-IDF character-ngram embeddings for all candidate labels.+ all_entities = source_nodes + target_nodes+ all_labels = list({_node_label(n) for n in all_entities if _node_label(n)})+ embeddings: Optional[Dict[str, List[float]]] = await asyncio.to_thread(_tfidf_embedding_vectors, all_labels)+ has_embeddings = embeddings is not None++ # Pre-build token sets for targets to enable O(1) prefiltering (skip zero-overlap pairs).+ target_token_sets: Dict[str, frozenset] = {+ n.get("id", ""): _token_set(_node_label(n)) for n in target_nodes+ }++ suggestions: List[AlignmentSuggestion] = []+ for source_node in source_nodes:+ source_id = source_node.get("id", "")+ source_label = _node_label(source_node)+ source_ontology = _node_source_ontology(source_node)+ source_tokens = _token_set(source_label)+ source_vec = embeddings.get(source_label) if has_embeddings else None++ for target_node in target_nodes:+ target_id = target_node.get("id", "")+ if not source_id or source_id == target_id:+ continue+ target_ontology = _node_source_ontology(target_node)+ if source_ontology and target_ontology and source_ontology == target_ontology:+ continue++ # Token-overlap prefilter: skip pairs with zero shared tokens (Jaccard=0 ⇒ label_sim≈0).+ target_tokens = target_token_sets.get(target_id, frozenset())+ if source_tokens and target_tokens and not (source_tokens & target_tokens):+ continue++ target_label = _node_label(target_node)+ label_score = _label_similarity(source_label, target_label)++ embedding_sim: Optional[float] = None+ if has_embeddings and source_vec is not None:+ target_vec = embeddings.get(target_label)+ if target_vec is not None:+ try:+ embedding_sim = round(_cosine_sim(source_vec, target_vec), 4)+ except Exception:+ embedding_sim = None++ # Combined score: average label and embedding similarity when both are available.+ if embedding_sim is not None:+ score = round(0.4 * label_score + 0.6 * embedding_sim, 4)+ reason = (+ f"Label similarity {label_score:.2f}, embedding cosine similarity {embedding_sim:.2f} "+ f"(TF-IDF character n-gram vectors via SimilarityCalculator)."+ )+ else:+ score = label_score+ reason = f"Label similarity {label_score:.2f}; embedding vectors unavailable."++ if score < body.threshold:+ continue++ relation = _candidate_relation(source_node, target_node)+ suggestions.append(AlignmentSuggestion(+ source_uri=source_id,+ source_label=source_label,+ target_uri=target_id,+ target_label=target_label,+ relation=relation,+ score=score,+ label_similarity=label_score,+ embedding_similarity=embedding_sim,+ reason=reason,+ ))++ suggestions.sort(key=lambda item: item.score, reverse=True)+ return suggestions[:body.limit]++[email protected]("/health", response_model=OntologyHealthResponse)+async def ontology_health(+ request: Request,+ uri: str = Query(...),+ session: GraphSession = Depends(get_session),+):+ registry = {entry.uri: entry for entry in await _registry_entries(request, session)}+ entry = registry.get(uri)+ if entry is None:+ raise HTTPException(status_code=404, detail="Ontology not found in registry.")++ nodes, total_nodes = await asyncio.to_thread(session.get_nodes, skip=0, limit=_MAX_ANALYSIS_NODES)+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=_MAX_ANALYSIS_NODES)+ if total_nodes > _MAX_ANALYSIS_NODES:+ logger.warning("ontology-health: graph has %d nodes; analysis capped at %d.", total_nodes, _MAX_ANALYSIS_NODES)+ entities = _ontology_entities(nodes, uri)+ classes = [node for node in entities if _classify_node_type(node.get("type", "")) == "class"]+ properties = [node for node in entities if _classify_node_type(node.get("type", "")) == "property"]+ assessed = classes + properties++ issues: List[HealthIssue] = []+ total = max(len(assessed), 1)+ with_label = sum(1 for node in assessed if _node_label(node))+ with_comment = sum(1 for node in assessed if _entity_description(node))+ with_definition = sum(1 for node in assessed if _entity_definition(node))+ completeness_score = ((with_label + with_comment + with_definition) / (total * 3)) * 100++ for node in assessed:+ label = _node_label(node)+ if not _entity_description(node):+ issues.append(HealthIssue(+ id=f"doc:{node.get('id')}",+ severity="warning",+ category="Documentation",+ entity_uri=node.get("id"),+ entity_label=label,+ message=f"{label} is missing a comment or definition.",+ action="Add documentation in Editor.",+ ))++ property_range_edges = {+ edge.get("source")+ for edge in edges+ if edge.get("type") == "rdfs:range"+ }+ missing_range = [node for node in properties if node.get("id") not in property_range_edges]+ for node in missing_range[:25]:+ issues.append(HealthIssue(+ id=f"range:{node.get('id')}",+ severity="info",+ category="Consistency",+ entity_uri=node.get("id"),+ entity_label=_node_label(node),+ message="Property has no explicit rdfs:range.",+ action="Review property range in Editor.",+ ))++ consistency_score = max(0.0, 100.0 - (len(missing_range) / max(len(properties), 1)) * 60.0)++ assessed_ids = {node.get("id") for node in assessed if node.get("id")}+ alignments = _get_alignment_store(request).values()+ aligned_sources = {+ item.source_uri for item in alignments if item.source_uri in assessed_ids+ } | {+ item.target_uri for item in alignments if item.target_uri in assessed_ids+ }+ alignment_score = (len(aligned_sources) / total) * 100+ if assessed and not aligned_sources:+ issues.append(HealthIssue(+ id=f"alignment:{uri}",+ severity="warning",+ category="Alignment",+ message="No cross-ontology alignments are recorded for local classes or properties.",+ action="Review suggested alignments.",+ ))++ documentation_score = ((with_comment / total) * 80.0) + (20.0 if entry.version or entry.source_url else 0.0)++ shacl_dimension = HealthDimension(+ key="shacl",+ label="SHACL Conformance",+ score=0.0,+ status="unavailable",+ detail="Live SHACL validation is available in SHACL Studio when optional validation dependencies are installed.",+ )++ dimensions = [+ HealthDimension(+ key="completeness",+ label="Completeness",+ score=round(completeness_score, 1),+ status="ok" if completeness_score >= 80 else "warning",+ detail=f"{with_label}/{total} labeled, {with_comment}/{total} documented, {with_definition}/{total} defined.",+ ),+ HealthDimension(+ key="consistency",+ label="Consistency",+ score=round(consistency_score, 1),+ status="ok" if consistency_score >= 80 else "warning",+ detail=f"{len(missing_range)} properties are missing explicit ranges.",+ ),+ shacl_dimension,+ HealthDimension(+ key="alignment",+ label="Alignment Coverage",+ score=round(alignment_score, 1),+ status="ok" if alignment_score >= 50 else "warning",+ detail=f"{len(aligned_sources)}/{total} classes or properties have an alignment.",+ ),+ HealthDimension(+ key="documentation",+ label="Documentation",+ score=round(documentation_score, 1),+ status="ok" if documentation_score >= 75 else "warning",+ detail="Measures comments plus source/version metadata.",+ ),+ ]+ scoreable = [dim for dim in dimensions if dim.status != "unavailable"]+ total_score = sum(dim.score for dim in scoreable) / max(len(scoreable), 1)++ return OntologyHealthResponse(+ uri=uri,+ name=entry.name,+ total_score=round(total_score, 1),+ dimensions=dimensions,+ issues=issues[:100],+ generated_at=datetime.now(UTC).isoformat(),+ )+++async def _generated_shacl_for_uri(+ request: Request,+ session: GraphSession,+ uri: str,+ quality_tier: str = "strict",+) -> tuple[str, List[ShaclShapeSummary]]:+ registry = {entry.uri: entry for entry in await _registry_entries(request, session)}+ entry = registry.get(uri)+ if entry is None:+ raise HTTPException(status_code=404, detail="Ontology not found in registry.")++ nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=_MAX_ANALYSIS_NODES)+ edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=_MAX_ANALYSIS_NODES)+ entities = _ontology_entities(nodes, uri)+ ontology_dict = _ontology_dict_from_nodes(uri, entry.name, entities, edges)++ try:+ from ...ontology import OntologyEngine+ engine = OntologyEngine()+ shacl_turtle = await asyncio.to_thread(+ engine.to_shacl,+ ontology_dict,+ format="turtle",+ quality_tier=quality_tier,+ validate_output=False,+ )+ except Exception as exc:+ logger.debug("OntologyEngine.to_shacl unavailable; using basic generator: %s", exc)+ shacl_turtle = _basic_shacl_turtle(uri, entry.name, entities)++ return shacl_turtle, _summarize_shapes(shacl_turtle)++[email protected]("/shacl/generate", response_model=ShaclGenerateResponse)+async def generate_shacl(+ request: Request,+ body: ShaclGenerateRequest,+ session: GraphSession = Depends(get_session),+):+ shacl_turtle, shapes = await _generated_shacl_for_uri(request, session, body.uri, body.quality_tier)+ return ShaclGenerateResponse(+ uri=body.uri,+ shacl_turtle=shacl_turtle,+ shape_count=len(shapes),+ generated_at=datetime.now(UTC).isoformat(),+ )++[email protected]("/shacl/shapes", response_model=ShaclShapesResponse)+async def list_shacl_shapes(+ request: Request,+ uri: str = Query(...),+ session: GraphSession = Depends(get_session),+):+ shacl_turtle, shapes = await _generated_shacl_for_uri(request, session, uri)+ return ShaclShapesResponse(+ uri=uri,+ shapes=shapes,+ shacl_turtle=shacl_turtle,+ generated_at=datetime.now(UTC).isoformat(),+ )++[email protected]("/shacl/validate", response_model=ShaclValidationResponse)+async def validate_shacl(body: ShaclValidateRequest):+ if not body.shacl_turtle.strip():+ raise HTTPException(status_code=422, detail="SHACL Turtle cannot be empty.")++ # Syntax-check the submitted Turtle with rdflib before claiming anything about it.+ try:+ import rdflib # type: ignore+ g = rdflib.Graph()+ await asyncio.to_thread(g.parse, data=body.shacl_turtle, format="turtle")+ except ImportError:+ pass # rdflib unavailable; skip syntax check+ except Exception as exc:+ raise HTTPException(+ status_code=422,+ detail=f"Invalid Turtle syntax: {exc}",+ ) from exc++ # Live data-graph validation requires pySHACL wired to OntologyEngine.validate_graph().+ return ShaclValidationResponse(+ uri=body.uri,+ conforms=False,+ status="unavailable",+ message=(+ "Turtle parsed successfully. "+ "Live graph validation is not yet wired to a data graph — "+ "install semantica[shacl] and connect OntologyEngine.validate_graph() to enable full validation."+ ),+ violations=[],+ )++# ---------------------------------------------------------------------------# Wildcard management endpoints (must come after specific routes)# ---------------------------------------------------------------------------