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
fix(ontology): address Qodo automated review findings from PR #524
KaifAhmad163acc7a66e81
diff --git a/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx b/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsxindex a0444e4d..8c8475ea 100644--- a/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx+++ b/explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx@@ -1452,12 +1452,16 @@ export function GraphWorkspace({ externalFocusNodeId, externalFocusToken }: Grapif (!graphReady || !graph.hasNode(externalFocusNodeId)) return;lastExternalFocusTokenRef.current = externalFocusToken;+ // Set state directly instead of going through focusNode(), which captures+ // a stale viewMode in its closure. setViewMode is called first so the node+ // is visible in the full graph before the scene pans to it.setViewMode("full");- focusNode(externalFocusNodeId);+ setSelectedNodeId(externalFocusNodeId);+ setSelectedEdgeId("");window.setTimeout(() => {sceneRef.current?.focusNode(externalFocusNodeId);}, 0);- }, [externalFocusNodeId, externalFocusToken, focusNode, graphReady]);+ }, [externalFocusNodeId, externalFocusToken, graphReady]);const handleEdgeSelect = useCallback((edgeId: string) => {setSelectedEdgeId(edgeId);diff --git a/explorer/src/workspaces/OntologyWorkspace/AlignmentsTab.tsx b/explorer/src/workspaces/OntologyWorkspace/AlignmentsTab.tsxindex 88407aa0..36420899 100644--- a/explorer/src/workspaces/OntologyWorkspace/AlignmentsTab.tsx+++ b/explorer/src/workspaces/OntologyWorkspace/AlignmentsTab.tsx@@ -75,6 +75,29 @@ export function AlignmentsTab() {return counts;}, [alignments]);+ // Pairwise matrix: group alignments by (source_ontology, target_ontology) pair.+ const matrix = useMemo(() => {+ function ontologyOfUri(uri: string): string {+ for (const entry of registry) {+ if (uri === entry.uri || uri.startsWith(entry.uri + "#") || uri.startsWith(entry.uri + "/")) {+ return entry.uri;+ }+ }+ const hashIdx = uri.lastIndexOf("#");+ if (hashIdx > 0) return uri.substring(0, hashIdx);+ const slashIdx = uri.lastIndexOf("/");+ return slashIdx > 0 ? uri.substring(0, slashIdx) : uri;+ }+ const cells: Map<string, OntologyAlignment[]> = new Map();+ for (const alignment of alignments) {+ const key = `${ontologyOfUri(alignment.source_uri)}|||${ontologyOfUri(alignment.target_uri)}`;+ const bucket = cells.get(key) ?? [];+ bucket.push(alignment);+ cells.set(key, bucket);+ }+ return { ontologies: registry, cells };+ }, [registry, alignments]);+const handleSave = useCallback(async () => {if (!sourceUri.trim() || !targetUri.trim()) {setError("Provide both source and target entity URIs.");@@ -166,6 +189,61 @@ export function AlignmentsTab() {Export your graph or ontology to preserve recorded mappings.</div>+ {matrix.ontologies.length >= 2 ? (+ <section style={cardStyle}>+ <h3 style={sectionTitleStyle}>Pairwise alignment matrix</h3>+ <div style={{ overflowX: "auto" }}>+ <table style={matrixTableStyle}>+ <thead>+ <tr>+ <th style={matrixCornerStyle} />+ {matrix.ontologies.map((col) => (+ <th key={col.uri} style={matrixColHeaderStyle}>{col.name}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {matrix.ontologies.map((row) => (+ <tr key={row.uri}>+ <td style={matrixRowHeaderStyle}>{row.name}</td>+ {matrix.ontologies.map((col) => {+ const key = `${row.uri}|||${col.uri}`;+ const cellItems = matrix.cells.get(key) ?? [];+ const isDiag = row.uri === col.uri;+ return (+ <td key={col.uri} style={{ ...matrixCellStyle, background: isDiag ? "rgba(255,255,255,0.015)" : undefined }}>+ {isDiag ? <span style={mutedStyle}>—</span> : cellItems.length ? (+ <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>+ {cellItems.map((item) => (+ <span+ key={item.id}+ style={{ ...relationBadgeStyle, color: RELATION_COLORS[item.relation], borderColor: `${RELATION_COLORS[item.relation]}44`, cursor: "pointer", fontSize: 9 }}+ title={`${item.source_label} → ${item.target_label} (${Math.round(item.confidence * 100)}%)`}+ onClick={() => {+ setSourceUri(item.source_uri);+ setTargetUri(item.target_uri);+ setRelation(item.relation);+ setConfidence(item.confidence);+ setProvenance(item.provenance ?? "");+ }}+ >+ {item.relation.split(":")[1]}+ </span>+ ))}+ </div>+ ) : <span style={{ color: "rgba(127,208,255,0.15)", fontSize: 12 }}>·</span>}+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ <p style={{ ...mutedStyle, marginTop: 10 }}>Click a relation badge to load it into the editor below.</p>+ </section>+ ) : null}+<div style={gridStyle}><section style={cardStyle}><h3 style={sectionTitleStyle}>Create or update alignment</h3>@@ -321,3 +399,8 @@ const iconButtonStyle: CSSProperties = { width: 34, height: 34, borderRadius: 10const mutedStyle: CSSProperties = { margin: 0, color: "#6a7f97", fontSize: 13 };const errorStyle: CSSProperties = { padding: 12, borderRadius: 14, color: "#ffb4c2", background: "rgba(255,157,175,0.1)", border: "1px solid rgba(255,157,175,0.18)" };const ephemeralBannerStyle: CSSProperties = { padding: "9px 14px", borderRadius: 12, color: "#f2b66d", background: "rgba(242,182,109,0.08)", border: "1px solid rgba(242,182,109,0.22)", fontSize: 12 };+const matrixTableStyle: CSSProperties = { borderCollapse: "collapse", minWidth: "100%", fontSize: 12 };+const matrixCornerStyle: CSSProperties = { padding: "8px 12px", borderBottom: "1px solid rgba(127,208,255,0.1)" };+const matrixColHeaderStyle: CSSProperties = { padding: "8px 12px", color: "#9ee8d7", fontWeight: 900, borderBottom: "1px solid rgba(127,208,255,0.1)", textAlign: "center", whiteSpace: "nowrap" };+const matrixRowHeaderStyle: CSSProperties = { padding: "8px 12px", color: "#9ee8d7", fontWeight: 900, borderRight: "1px solid rgba(127,208,255,0.1)", whiteSpace: "nowrap" };+const matrixCellStyle: CSSProperties = { padding: "8px 10px", borderBottom: "1px solid rgba(127,208,255,0.06)", borderRight: "1px solid rgba(127,208,255,0.06)", textAlign: "center", verticalAlign: "middle", minWidth: 100 };diff --git a/explorer/src/workspaces/OntologyWorkspace/ShaclStudio.tsx b/explorer/src/workspaces/OntologyWorkspace/ShaclStudio.tsxindex ba110436..a6c0c360 100644--- a/explorer/src/workspaces/OntologyWorkspace/ShaclStudio.tsx+++ b/explorer/src/workspaces/OntologyWorkspace/ShaclStudio.tsx@@ -18,7 +18,9 @@ export function ShaclStudio({ onJumpToNode }: ShaclStudioProps) {const [registry, setRegistry] = useState<OntologyEntry[]>([]);const [selectedUri, setSelectedUri] = useState("");const [shacl, setShacl] = useState("");+ const [fullShacl, setFullShacl] = useState(""); // preserves complete Turtle across shape selectionsconst [shapes, setShapes] = useState<ShaclShapeSummary[]>([]);+ const [selectedShapeId, setSelectedShapeId] = useState<string | null>(null);const [validation, setValidation] = useState<ShaclValidationResponse | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState("");@@ -46,7 +48,10 @@ export function ShaclStudio({ onJumpToNode }: ShaclStudioProps) {try {const data = await loadShaclShapes(uri);setShapes(data.shapes);- setShacl((current) => current || data.shacl_turtle);+ const turtle = data.shacl_turtle;+ setFullShacl(turtle);+ setShacl((current) => current || turtle);+ setSelectedShapeId(null);setValidation(null);} catch (err) {setError(err instanceof Error ? err.message : "Could not load SHACL shapes.");@@ -57,16 +62,20 @@ export function ShaclStudio({ onJumpToNode }: ShaclStudioProps) {useEffect(() => {setShacl("");+ setFullShacl("");+ setSelectedShapeId(null);void loadShapes(selectedUri);}, [selectedUri, loadShapes]);- const handleGenerate = async () => {+ const handleGenerate = useCallback(async () => {if (!selectedUri) return;setLoading(true);setError("");try {const data = await generateShacl(selectedUri, "strict");+ setFullShacl(data.shacl_turtle);setShacl(data.shacl_turtle);+ setSelectedShapeId(null);const shapeData = await loadShaclShapes(selectedUri);setShapes(shapeData.shapes);setValidation(null);@@ -75,7 +84,29 @@ export function ShaclStudio({ onJumpToNode }: ShaclStudioProps) {} finally {setLoading(false);}- };+ }, [selectedUri]);++ const handleSelectShape = useCallback((shapeId: string) => {+ setSelectedShapeId(shapeId);+ // Extract the Turtle block for this shape from the full SHACL so the editor+ // pre-populates with the selected shape's definition.+ const src = fullShacl || shacl;+ const normalised = src.replace(/\r\n/g, "\n");+ // Split on blank lines to isolate statement groups.+ const blocks = normalised.split(/\n{2,}/).filter((b) => b.trim());+ const match = blocks.find((b) => {+ const first = b.trimStart();+ return first.startsWith(shapeId + " ") || first.startsWith(shapeId + "\n") || first.startsWith(shapeId + "\t");+ });+ if (match) {+ setShacl(match.trim());+ }+ }, [fullShacl, shacl]);++ const handleShowAllShapes = useCallback(() => {+ setSelectedShapeId(null);+ setShacl(fullShacl);+ }, [fullShacl]);const handleValidate = async () => {if (!selectedUri || !shacl.trim()) return;@@ -166,25 +197,45 @@ export function ShaclStudio({ onJumpToNode }: ShaclStudioProps) {<section style={cardStyle}><div style={panelHeaderStyle}><h3 style={sectionTitleStyle}>Shape library</h3>- <span style={countBadgeStyle}>{shapes.length} shapes</span>+ <div style={{ display: "flex", gap: 8, alignItems: "center" }}>+ <span style={countBadgeStyle}>{shapes.length} shapes</span>+ {selectedShapeId ? (+ <button style={smallButtonStyle} onClick={handleShowAllShapes}>View all</button>+ ) : null}+ </div></div><div style={shapeListStyle}>{groupedShapes.map(([target, items]) => (<div key={target} style={shapeGroupStyle}><div style={shapeTargetStyle}>{target}</div>- {items.map((shape) => (- <div key={shape.id} style={shapeRowStyle}>- <FileCode2 size={14} color="#9ee8d7" />- <div>- <div style={{ color: "#ebf3ff", fontWeight: 800 }}>{shape.id}</div>- <div style={mutedStyle}>- {shape.constraint_count} constraints- {shape.constraints.length ? ` · ${shape.constraints.join(", ")}` : ""}+ {items.map((shape) => {+ const isSelected = selectedShapeId === shape.id;+ return (+ <button+ key={shape.id}+ style={{+ ...shapeRowStyle,+ cursor: "pointer",+ background: isSelected ? "rgba(124,231,211,0.1)" : "rgba(255,255,255,0.03)",+ border: isSelected ? "1px solid rgba(124,231,211,0.35)" : "1px solid rgba(127,208,255,0.08)",+ textAlign: "left",+ width: "100%",+ }}+ onClick={() => handleSelectShape(shape.id)}+ title="Click to load this shape into the editor"+ >+ <FileCode2 size={14} color={isSelected ? "#7ce7d3" : "#9ee8d7"} />+ <div>+ <div style={{ color: "#ebf3ff", fontWeight: 800 }}>{shape.id}</div>+ <div style={mutedStyle}>+ {shape.constraint_count} constraints+ {shape.constraints.length ? ` · ${shape.constraints.join(", ")}` : ""}+ </div></div>- </div>- <span style={violationBadgeStyle}>{shape.violation_count}</span>- </div>- ))}+ <span style={violationBadgeStyle}>{shape.violation_count}</span>+ </button>+ );+ })}</div>))}{!shapes.length ? <p style={mutedStyle}>No shapes generated yet.</p> : null}@@ -193,7 +244,9 @@ export function ShaclStudio({ onJumpToNode }: ShaclStudioProps) {<section style={editorShellStyle}><div style={panelHeaderStyle}>- <h3 style={sectionTitleStyle}>Turtle shape editor</h3>+ <h3 style={sectionTitleStyle}>+ {selectedShapeId ? selectedShapeId : "Turtle shape editor"}+ </h3><div style={{ display: "flex", gap: 8 }}><button style={secondaryButtonStyle} disabled={loading} onClick={handleGenerate}><Wand2 size={14} /> Generate strict</button><button style={primaryButtonStyle} disabled={loading || !shacl.trim()} onClick={handleValidate}>diff --git a/semantica/explorer/routes/ontology.py b/semantica/explorer/routes/ontology.pyindex 4a6b8da3..6ce9d9ce 100644--- a/semantica/explorer/routes/ontology.py+++ b/semantica/explorer/routes/ontology.py@@ -23,7 +23,8 @@ router = APIRouter(prefix="/api/ontology", tags=["Ontology"])logger = logging.getLogger(__name__)_MAX_FETCH_BYTES = 20 * 1024 * 1024 # 20 MB-_MAX_ANALYSIS_NODES = 5_000 # cap for health/suggest/shacl node scans to avoid OOM+_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",@@ -473,6 +474,36 @@ def _label_similarity(left: str, right: str) -> float:return round(max(sequence, token_score), 4)+def _token_set(label: str) -> frozenset:+ return frozenset(label.lower().replace("_", " ").replace("-", " ").split())+++def _tfidf_embedding_vectors(labels: List[str]) -> Optional[Dict[str, List[float]]]:+ """Build character-ngram TF-IDF vectors from entity labels (sklearn-based, no gensim needed)."""+ if len(labels) < 2:+ return None+ try:+ from sklearn.feature_extraction.text import TfidfVectorizer # type: ignore+ normed = [" ".join(l.lower().replace("_", " ").replace("-", " ").split()) for l in labels]+ vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4), min_df=1)+ matrix = vec.fit_transform(normed)+ return {label: matrix[i].toarray().flatten().tolist() for i, label in enumerate(labels)}+ except Exception:+ return None+++def _cosine_sim(v1: List[float], v2: List[float]) -> float:+ try:+ from ...kg import SimilarityCalculator+ return SimilarityCalculator().cosine_similarity(v1, v2)+ except Exception:+ import math+ dot = sum(a * b for a, b in zip(v1, v2))+ n1 = math.sqrt(sum(a * a for a in v1))+ n2 = math.sqrt(sum(b * b for b in v2))+ return dot / (n1 * n2) if n1 and n2 else 0.0++def _candidate_relation(source: Dict[str, Any], target: Dict[str, Any]) -> AlignmentRelation:source_type = _classify_node_type(source.get("type", ""))target_type = _classify_node_type(target.get("type", ""))@@ -1233,21 +1264,10 @@ async def upsert_alignment(updated_at=now,)store[alignment_id] = alignment-- try:- from ...ontology import OntologyEngine- engine = OntologyEngine()- await asyncio.to_thread(- engine.create_alignment,- body.source_uri,- body.target_uri,- _ALIGNMENT_RELATIONS[body.relation],- confidence=body.confidence,- provenance=body.provenance,- )- except Exception as exc:- logger.debug("OntologyEngine alignment persistence unavailable; using route store: %s", exc)-+ # 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@@ -1279,11 +1299,33 @@ async def suggest_alignments(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:@@ -1292,9 +1334,34 @@ async def suggest_alignments(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)- score = label_score++ 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@@ -1305,10 +1372,10 @@ async def suggest_alignments(target_uri=target_id,target_label=target_label,relation=relation,- score=round(score, 4),+ score=score,label_similarity=label_score,- embedding_similarity=None,- reason="Matched by label similarity; embedding similarity was not required or unavailable.",+ embedding_similarity=embedding_sim,+ reason=reason,))suggestions.sort(key=lambda item: item.score, reverse=True)@@ -1374,15 +1441,12 @@ async def ontology_health(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 any(item.source_uri == node.get("id") for node in assessed)+ item.source_uri for item in alignments if item.source_uri in assessed_ids} | {- item.target_uri- for item in alignments- if any(item.target_uri == node.get("id") for node in assessed)+ item.target_uri for item in alignments if item.target_uri in assessed_ids}alignment_score = (len(aligned_sources) / total) * 100if assessed and not aligned_sources:@@ -1515,16 +1579,29 @@ async def list_shacl_shapes(async def validate_shacl(body: ShaclValidateRequest):if not body.shacl_turtle.strip():raise HTTPException(status_code=422, detail="SHACL Turtle cannot be empty.")- # Live validation requires pySHACL and a wired data graph from OntologyEngine.validate_graph().- # Always return unavailable until that integration is complete — never return a false "conforms"- # result that would mislead users editing shapes.++ # 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=(- "Live graph validation is not yet wired to a data graph. "- "Install semantica[shacl] and connect OntologyEngine.validate_graph() to enable full validation."+ "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=[],)diff --git a/tests/explorer/test_ontology_subissue3.py b/tests/explorer/test_ontology_subissue3.pyindex 671a0256..a95444d5 100644--- a/tests/explorer/test_ontology_subissue3.py+++ b/tests/explorer/test_ontology_subissue3.py@@ -215,3 +215,49 @@ def test_alignment_accepts_external_uri(client):assert response.status_code == 200alignment = response.json()assert alignment["target_label"] == "Person" # derived from URI fragment+++def test_suggest_alignments_returns_embedding_similarity(client):+ response = client.post(+ "/api/ontology/suggest-alignments",+ json={+ "source_ontology_uri": "http://example.org/onto-a",+ "target_ontology_uri": "http://example.org/onto-b",+ "threshold": 0.20,+ "limit": 10,+ },+ )+ assert response.status_code == 200+ suggestions = response.json()+ assert suggestions+ # When sklearn is available, embedding_similarity should be populated.+ top = suggestions[0]+ assert top["embedding_similarity"] is not None, (+ "TF-IDF embedding similarity must be returned when sklearn is installed"+ )+ # Combined score must be a weighted blend, not purely the label score.+ assert top["score"] != top["label_similarity"] or top["embedding_similarity"] == top["label_similarity"]+++def test_shacl_validate_rejects_invalid_turtle_syntax(client):+ response = client.post(+ "/api/ontology/shacl/validate",+ json={+ "uri": "http://example.org/onto-a",+ "shacl_turtle": "this is not valid turtle !!!",+ },+ )+ assert response.status_code == 422+++def test_health_alignment_coverage_uses_set_lookup(client):+ # Create an alignment first so coverage score can be non-zero.+ client.post("/api/ontology/alignments", json={+ "source_uri": "http://example.org/onto-a#Person",+ "target_uri": "http://example.org/onto-b#PersonRecord",+ "relation": "owl:equivalentClass",+ "confidence": 0.9,+ })+ payload = client.get("/api/ontology/health?uri=http%3A%2F%2Fexample.org%2Fonto-a").json()+ alignment_dim = next(d for d in payload["dimensions"] if d["key"] == "alignment")+ assert alignment_dim["score"] > 0.0, "alignment coverage must be non-zero after recording an alignment"