Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
chore(studio): delete the vendor-hiding feature; resolve dead code left by the pivot
FABIOTESS8d2a60bc2477
diff --git a/studio/src-tauri/sidecars/agent/acl.test.ts b/studio/src-tauri/sidecars/agent/acl.test.tsdeleted file mode 100644index 362e39d4..00000000--- a/studio/src-tauri/sidecars/agent/acl.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { describe, it, expect } from 'vitest';-import { ROLES, roleById, isUnrestricted, docFilter, summarise, type Role } from './acl.js';-import type { McpClient } from './mcp.js';--/**- * `acl.ts` is the layer that actually enforces access control (the sidecar- * queries the graph through it); `studio/src/lib/roles.ts` is only a- * frontend display mirror. A regression here reaches production undetected- * unless this file catches it, so these tests exercise `roleById`,- * `docFilter` and `summarise` directly rather than relying on the mirror's- * coverage.- *- * The same four documents used by `roles.test.ts`'s fixtures, restated here- * in the `onto_query` row shape `summarise` actually parses (one row per- * doc, groups comma-joined by GROUP_CONCAT).- */-const DOC_ROWS = [- { doc: 'DCAT-001', cls: 'Dataset', groups: 'public' },- { doc: 'DCAT-002', cls: 'Dataset', groups: 'compliance' },- { doc: 'DCAT-003', cls: 'Dataset', groups: 'public,compliance' },- { doc: 'DCAT-004', cls: 'Dataset', groups: 'editor' },-];-const ALL_DOCS = DOC_ROWS.map(r => r.doc).sort();--function mockMcp(rows: Array<Record<string, string>>): McpClient {- return {- callTool: async () => JSON.stringify({ results: rows }),- } as unknown as McpClient;-}--const reader = ROLES.find(r => r.id === 'reader')!;-const unrestricted = ROLES.find(r => r.id === 'all')!;--describe('roleById', () => {- it('resolves an unknown role id to a denied role, not the unrestricted one', () => {- const role = roleById('does-not-exist');- expect(role.unrestricted).toBe(false);- expect(isUnrestricted(role)).toBe(false);- });-- it('resolves undefined (no selection made) to the unrestricted role', () => {- const role = roleById(undefined);- expect(role.id).toBe('all');- expect(isUnrestricted(role)).toBe(true);- });-- it('resolves a known id to the matching role', () => {- expect(roleById('reader').id).toBe('reader');- });-});--describe('docFilter', () => {- it('returns no restriction for the unrestricted role', () => {- expect(docFilter(unrestricted)).toBe('');- });-- it('returns an unsatisfiable VALUES clause for a denied (unknown) role', () => {- const denied = roleById('does-not-exist');- expect(docFilter(denied)).toBe('?d <https://w3id.org/dcat-us-demo#aclGroup> ?__g . VALUES ?__g { }');- });-- it('returns an unsatisfiable VALUES clause for a role with an empty grant list', () => {- const emptyGrantRole: Role = {- id: 'unassigned',- label: 'Unassigned',- groups: [],- unrestricted: false,- description: 'Awaiting a group assignment.',- };- expect(docFilter(emptyGrantRole)).toBe('?d <https://w3id.org/dcat-us-demo#aclGroup> ?__g . VALUES ?__g { }');- });-- it('returns a VALUES clause naming the granted groups for a subset role', () => {- expect(docFilter(reader)).toBe('?d <https://w3id.org/dcat-us-demo#aclGroup> ?__g . VALUES ?__g { "public" }');- });-});--describe('summarise', () => {- it('an unknown role identifier resolves to a denied role and yields no visible documents', async () => {- const denied = roleById('does-not-exist');- const result = await summarise(mockMcp(DOC_ROWS), denied);- expect(result.visible).toEqual([]);- expect(result.withheld).toEqual(ALL_DOCS);- });-- it('a role with an empty grant list yields no visible documents', async () => {- const emptyGrantRole: Role = {- id: 'unassigned',- label: 'Unassigned',- groups: [],- unrestricted: false,- description: 'Awaiting a group assignment.',- };- const result = await summarise(mockMcp(DOC_ROWS), emptyGrantRole);- expect(result.visible).toEqual([]);- expect(result.withheld).toEqual(ALL_DOCS);- });-- it('a role with a subset grant yields exactly that subset and withholds the rest', async () => {- // 'reader' holds only the 'public' group.- const result = await summarise(mockMcp(DOC_ROWS), reader);- expect(result.visible).toEqual(['DCAT-001', 'DCAT-003']);- expect(result.withheld).toEqual(['DCAT-002', 'DCAT-004']);- });-- it('an explicitly unrestricted role sees everything', async () => {- const result = await summarise(mockMcp(DOC_ROWS), unrestricted);- expect(result.visible).toEqual(ALL_DOCS);- expect(result.withheld).toEqual([]);- });-});diff --git a/studio/src-tauri/sidecars/agent/acl.ts b/studio/src-tauri/sidecars/agent/acl.tsdeleted file mode 100644index 1cfc2fa9..00000000--- a/studio/src-tauri/sidecars/agent/acl.ts+++ /dev/null@@ -1,219 +0,0 @@-/**- * Access control over retrieval.- *- * The corpus documents carry their own access metadata: every header states a- * Classification and an Acl Group, and `demo/acl_normalise.py` lifts those into- * one flat `:aclGroup` triple per document per group. This module is the half- * that enforces them.- *- * Enforcement is at RETRIEVAL time, not at presentation time. A document the- * viewer's role cannot reach never enters the subgraph, so it cannot reach the- * model, cannot be paraphrased into an answer, and cannot leak through a- * citation. Filtering after generation would be theatre: the model would- * already have seen the text.- *- * The consequence is deliberate and worth showing rather than hiding. Two- * roles asking the same question can receive different answers, and a role- * that can see only one side of a disputed fact receives a confident answer- * that the full corpus would contradict. That is not a defect of the method;- * it is what access control means, made visible.- *- * DENY BY DEFAULT. Two failure modes matter more than the happy path:- * - An unrecognised role id must be denied, not treated as unrestricted.- * - A role with an empty `groups` list must see nothing, not everything.- * Only the single sentinel role explicitly marked `unrestricted: true` (see- * `ROLES[0]` below) bypasses filtering; that must never be inferred from an- * empty group list, because every other role's default state IS an empty- * group list before someone assigns it access.- */--import type { McpClient } from './mcp.js';--const NS = process.env.ONTO_NS ?? 'https://w3id.org/dcat-us-demo#';--export interface Role {- id: string;- label: string;- groups: string[];- /**- * True only for the one role that deliberately bypasses access control.- * Never derive this from `groups.length === 0`: a role awaiting a group- * assignment and a role that has opted out of filtering are different- * things, and conflating them is what makes an access-control layer fail- * open.- */- unrestricted: boolean;- /** Shown in the UI so a viewer understands what this role is meant to be. */- description: string;-}--/**- * Roles as the corpus defines them. The groups are not invented: they are the- * exact values found in the document headers, so a role either matches real- * documents or matches nothing.- */-export const ROLES: Role[] = [- {- id: 'all',- label: 'Unrestricted',- groups: [],- unrestricted: true,- description: 'No access control applied. Every document is retrievable.',- },- {- id: 'editor',- label: 'Catalogue Editor',- groups: ['editor'],- unrestricted: false,- description: 'Sees every dataset and distribution record, published or still in draft.',- },- {- id: 'reader',- label: 'Public Reader',- groups: ['public'],- unrestricted: false,- description: 'Sees only records marked published; drafts and internal review notes are withheld.',- },- {- id: 'compliance',- label: 'Compliance Reviewer',- groups: ['compliance'],- unrestricted: false,- description: 'Sees the conformance and licence-review records used to check DCAT-US compliance.',- },- {- id: 'publisher-ops',- label: 'Publisher Operations',- groups: ['publisher-ops'],- unrestricted: false,- description: 'Sees the publisher and distribution records for datasets under active curation.',- },-];--/**- * A denial sentinel for a role id this list does not recognise.- *- * Returned in place of a lookup failure rather than defaulting to `ROLES[0]`- * (the unrestricted role). Falling back to full access on an unrecognised- * name is the exact failure mode this module exists to prevent: it would- * look like access control was applied, when in fact nothing was withheld.- */-const DENIED_ROLE: Role = {- id: '__denied__',- label: 'Access Denied',- groups: [],- unrestricted: false,- description: 'Unrecognised role: no documents are visible.',-};--/**- * Resolve a role id.- *- * `undefined` means "no role was selected", the legitimate default state of a- * fresh session, and resolves to the unrestricted role, matching the UI's own- * default. Any OTHER string that does not match a known id is treated as a- * bad or spoofed value, not a missing selection, and is denied rather than- * silently granted the unrestricted role.- */-export function roleById(id: string | undefined): Role {- if (id === undefined) return ROLES[0];- return ROLES.find(r => r.id === id) ?? DENIED_ROLE;-}--/** True when this role applies no restriction at all. */-export function isUnrestricted(role: Role): boolean {- return role.unrestricted === true;-}--/**- * A SPARQL fragment constraining `?doc` to documents the role can reach.- *- * Returns an empty string for the unrestricted role so the caller's query is- * unchanged rather than wrapped in a tautology, which keeps the unrestricted- * path byte-identical to the behaviour before access control existed. Every- * other role, including one with an empty `groups` list, gets a `VALUES`- * clause; an empty `VALUES {}` matches nothing, which is what denies a role- * that has not been assigned to any group.- */-export function docFilter(role: Role, docVar = '?d'): string {- if (isUnrestricted(role)) return '';- const values = role.groups.map(g => `"${g}"`).join(' ');- return `${docVar} <${NS}aclGroup> ?__g . VALUES ?__g { ${values} }`;-}--export interface AclSummary {- role: string;- roleLabel: string;- visible: string[];- withheld: string[];- classifications: Record<string, string>;-}--/**- * Which documents this role can and cannot reach.- *- * Both halves are returned because the withheld list is the honest part: an- * answer built from a filtered corpus should be able to say how much it could- * not see, rather than presenting a partial view as a complete one.- */-export async function summarise(mcp: McpClient, role: Role): Promise<AclSummary> {- const rows = await query(- mcp,- `PREFIX dcus: <${NS}>- SELECT ?doc ?cls (GROUP_CONCAT(?g; separator=",") AS ?groups) WHERE {- ?d dcus:docId ?doc .- OPTIONAL { ?d dcus:classification ?cls }- OPTIONAL { ?d dcus:aclGroup ?g }- } GROUP BY ?doc ?cls`,- );-- const visible: string[] = [];- const withheld: string[] = [];- const classifications: Record<string, string> = {};-- for (const r of rows) {- const doc = r.doc;- if (!doc) continue;- classifications[doc] = r.cls ?? 'Unclassified';- const groups = (r.groups ?? '').split(',').map(s => s.trim()).filter(Boolean);- // Deny by default: an unrestricted role reaches everything, and every- // other role reaches a document only when a group it actually holds is- // named on that document. A role holding no groups at all reaches- // nothing, because `groups.some(...)` over an empty array is false.- const reachable = isUnrestricted(role) || groups.some(g => role.groups.includes(g));- (reachable ? visible : withheld).push(doc);- }-- visible.sort();- withheld.sort();- return { role: role.id, roleLabel: role.label, visible, withheld, classifications };-}--async function query(mcp: McpClient, sparql: string): Promise<Array<Record<string, string>>> {- try {- const raw = await mcp.callTool('onto_query', { query: sparql.replace(/\s+/g, ' ') });- const rows = JSON.parse(raw)?.results ?? [];- return rows.map((row: Record<string, string>) => {- const out: Record<string, string> = {};- for (const [k, v] of Object.entries(row)) out[k] = literal(v);- return out;- });- } catch {- return [];- }-}--/** Strip Turtle literal decoration; the engine returns values as written. */-function literal(v: string): string {- if (!v) return v;- if (v.startsWith('<') && v.endsWith('>')) return v.slice(1, -1).split('#').pop() ?? v;- if (v.startsWith('"')) {- const body = v.slice(1);- for (const cut of ['"^^', '"@', '"']) {- const i = body.indexOf(cut);- if (i >= 0) return body.slice(0, i);- }- return body;- }- return v;-}diff --git a/studio/src-tauri/sidecars/agent/baseline.ts b/studio/src-tauri/sidecars/agent/baseline.tsindex 928f2432..729abf9d 100644--- a/studio/src-tauri/sidecars/agent/baseline.ts+++ b/studio/src-tauri/sidecars/agent/baseline.ts@@ -16,6 +16,16 @@* module docstring), and nothing here manufactures it. Callers that want the* comparison surface, not just this one side of it, combine this module's* output with graphrag.ts's own, and leave the verdict to a person.+ *+ * NOT CURRENTLY WIRED. index.ts's stdin/stdout protocol has no message type+ * that calls this, and studio/src/lib/compare-source.ts's live+ * getCompareSource() throws rather than reaching it ("No live comparison is+ * implemented for..."). That is an intentional, disclosed capability gap,+ * not an oversight discovered here: wiring this in would mean adding a+ * request type to the sidecar protocol and a matching Tauri command, real+ * cross-process plumbing this module alone does not decide. Until that+ * lands, this stays a correct, unit-tested implementation with no caller,+ * exercised only by baseline.test.ts.*/const STOP = new Set(diff --git a/studio/src-tauri/sidecars/agent/providers/alias.ts b/studio/src-tauri/sidecars/agent/providers/alias.tsindex 318dd9fc..663de9d5 100644--- a/studio/src-tauri/sidecars/agent/providers/alias.ts+++ b/studio/src-tauri/sidecars/agent/providers/alias.ts@@ -1,18 +1,6 @@/**- * Model display aliasing and provider selection.- *- * What the UI shows about which model is serving a request is a presentation- * decision, not a technical one. In a client setting the specific vendor and- * weights are often not what the conversation should be about, and naming them- * invites a debate that is beside the point.- *- * Set ONTO_MODEL_LABEL to display a codename instead of the real identifier.- * Nothing about routing changes: this affects the label only.+ * Provider selection.*/-export function displayModel(real: string): string {- const label = process.env.ONTO_MODEL_LABEL;- return label && label.trim() ? label.trim() : real;-}import type { Provider } from './types.js';import { AnthropicProvider } from './anthropic.js';diff --git a/studio/src-tauri/sidecars/agent/providers/anthropic.ts b/studio/src-tauri/sidecars/agent/providers/anthropic.tsindex b5fe6b5a..c737363c 100644--- a/studio/src-tauri/sidecars/agent/providers/anthropic.ts+++ b/studio/src-tauri/sidecars/agent/providers/anthropic.ts@@ -17,7 +17,6 @@import Anthropic from '@anthropic-ai/sdk';import type { Provider, ToolSpec, ToolCall, ToolOutcome, TurnResult } from './types.js';-import { displayModel } from './alias.js';/** Default model. Override with ONTO_LLM_MODEL. */const DEFAULT_MODEL = 'claude-opus-5';@@ -58,7 +57,7 @@ export class AnthropicProvider implements Provider {}async describe(): Promise<string> {- return displayModel(this.model);+ return this.model;}setSystem(system: string): void {diff --git a/studio/src-tauri/sidecars/agent/providers/claudecli.ts b/studio/src-tauri/sidecars/agent/providers/claudecli.tsindex 6a68109c..727a315b 100644--- a/studio/src-tauri/sidecars/agent/providers/claudecli.ts+++ b/studio/src-tauri/sidecars/agent/providers/claudecli.ts@@ -14,7 +14,6 @@import { spawn } from 'child_process';import type { Provider, ToolSpec, ToolOutcome, TurnResult } from './types.js';-import { displayModel } from './alias.js';export class ClaudeCliProvider implements Provider {readonly name = 'claude-cli';@@ -31,7 +30,7 @@ export class ClaudeCliProvider implements Provider {}async describe(): Promise<string> {- return displayModel(this.model ?? 'claude-cli');+ return this.model ?? 'claude-cli';}setSystem(system: string): void {diff --git a/studio/src-tauri/sidecars/agent/providers/openai.ts b/studio/src-tauri/sidecars/agent/providers/openai.tsindex a7785849..42e4e31e 100644--- a/studio/src-tauri/sidecars/agent/providers/openai.ts+++ b/studio/src-tauri/sidecars/agent/providers/openai.ts@@ -11,7 +11,6 @@*/import type { Provider, ToolSpec, ToolCall, ToolOutcome, TurnResult } from './types.js';-import { displayModel } from './alias.js';interface ChatMessage {role: 'system' | 'user' | 'assistant' | 'tool';@@ -59,7 +58,7 @@ export class OpenAICompatibleProvider implements Provider {}async describe(): Promise<string> {- return displayModel(await this.resolveModel());+ return this.resolveModel();}setSystem(system: string): void {diff --git a/studio/src/components/AddClassDialog.tsx b/studio/src/components/AddClassDialog.tsxdeleted file mode 100644index c07224d0..00000000--- a/studio/src/components/AddClassDialog.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { useState, useRef, useEffect } from 'react';--interface AddClassDialogProps {- position: { x: number; y: number };- onSubmit: (className: string) => void;- onCancel: () => void;-}--export function AddClassDialog({ position, onSubmit, onCancel }: AddClassDialogProps) {- const [value, setValue] = useState('');- const inputRef = useRef<HTMLInputElement>(null);-- useEffect(() => {- inputRef.current?.focus();- }, []);-- function handleKeyDown(e: React.KeyboardEvent) {- if (e.key === 'Enter' && value.trim()) {- e.preventDefault();- onSubmit(value.trim());- } else if (e.key === 'Escape') {- e.preventDefault();- onCancel();- }- }-- return (- <div- className="absolute z-50 flex flex-col gap-1"- style={{- left: position.x,- top: position.y,- }}- >- <input- ref={inputRef}- type="text"- placeholder="Class name..."- value={value}- onChange={(e) => setValue(e.target.value)}- onKeyDown={handleKeyDown}- onBlur={onCancel}- className="px-3 py-1.5 rounded text-sm outline-none"- style={{- background: 'var(--bg-panel)',- color: 'var(--text-primary)',- border: '1px solid var(--accent)',- minWidth: '180px',- }}- />- <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>- Enter to create · Esc to cancel- </span>- </div>- );-}diff --git a/studio/src/components/GovernancePanel.tsx b/studio/src/components/GovernancePanel.tsxindex a248852c..0598fa5a 100644--- a/studio/src/components/GovernancePanel.tsx+++ b/studio/src/components/GovernancePanel.tsx@@ -30,7 +30,12 @@ interface TokenKind {count: number;}-const VAULT_PROVIDER = 'Skyflow';+// demo/tokenisation.py's ONTO_VAULT defaults to "local" (LocalVault, a JSON+// file under demo/derived/_vault.json), not a hosted vendor: this must match+// that default, not the swappable options it also supports (Skyflow,+// Databunker), or this panel would name a provider this demonstration never+// actually runs.+const VAULT_PROVIDER = 'Local JSON (demo only)';const NS = 'https://w3id.org/dcat-us-demo#';export function GovernancePanel() {diff --git a/studio/src/components/GraphCanvas.tsx b/studio/src/components/GraphCanvas.tsxdeleted file mode 100644index 2feacde2..00000000--- a/studio/src/components/GraphCanvas.tsx+++ /dev/null@@ -1,427 +0,0 @@-import { useRef, useEffect, useState, useCallback } from 'react';-import ForceGraph3D from '3d-force-graph';-import * as THREE from 'three';-import * as mcp from '../lib/mcp-client';-import { useEngine } from '../hooks/useEngine';-import { AddClassDialog } from './AddClassDialog';--interface SelectedNode {- id: string;- label: string;- uri: string;-}--interface GraphCanvasProps {- onNodeSelect: (node: SelectedNode | null) => void;- dagMode?: boolean;-}--interface SparqlBinding {- [key: string]: { type: string; value: string };-}--interface GraphNode {- id: string;- label: string;- uri: string;- x?: number;- y?: number;- z?: number;-}--interface GraphLink {- source: string;- target: string;- type?: 'subclass' | 'property';- label?: string;-}--// --- Helpers -----function parseSparqlResults(text: string): SparqlBinding[] {- try {- const parsed = JSON.parse(text);- const rows: Record<string, string>[] = parsed?.results ?? [];- return rows.map(row => {- const binding: SparqlBinding = {};- for (const [key, val] of Object.entries(row)) {- const s = String(val);- if (s.startsWith('<') && s.endsWith('>')) {- binding[key] = { type: 'uri', value: s.slice(1, -1) };- } else {- const unquoted = s.replace(/^"(.*)"(@\w+)?(\^\^.*)?$/, '$1').replace(/\\"/g, '"');- binding[key] = { type: 'literal', value: unquoted };- }- }- return binding;- });- } catch {- return [];- }-}--function shortUri(uri: string): string {- const hash = uri.lastIndexOf('#');- if (hash >= 0) return uri.slice(hash + 1);- const slash = uri.lastIndexOf('/');- if (slash >= 0) return uri.slice(slash + 1);- return uri;-}--const ONTO_NS = 'http://example.org/ontology#';--const CLASSES_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>-PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>-SELECT ?c ?label WHERE {- { ?c a owl:Class } UNION { ?c a rdfs:Class }- OPTIONAL { ?c rdfs:label ?label }- FILTER(!isBlank(?c))-}`;--const EDGES_QUERY = `PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>-PREFIX owl: <http://www.w3.org/2002/07/owl#>-SELECT ?sub ?parent WHERE {- ?sub rdfs:subClassOf ?parent .- { ?sub a owl:Class } UNION { ?sub a rdfs:Class }- FILTER(!isBlank(?sub) && !isBlank(?parent))-}`;--const PROPERTY_EDGES_QUERY = `PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>-PREFIX owl: <http://www.w3.org/2002/07/owl#>-PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>-SELECT ?prop ?propLabel ?domain ?range WHERE {- { ?prop a owl:ObjectProperty } UNION { ?prop a rdf:Property }- ?prop rdfs:domain ?domain .- ?prop rdfs:range ?range .- OPTIONAL { ?prop rdfs:label ?propLabel }- FILTER(!isBlank(?domain) && !isBlank(?range))-}`;--// --- Component -----export function GraphCanvas({ onNodeSelect, dagMode }: GraphCanvasProps) {- const containerRef = useRef<HTMLDivElement>(null);- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const graphRef = useRef<any>(null);- const { status, refreshStats } = useEngine();-- const [addDialog, setAddDialog] = useState<{ x: number; y: number } | null>(null);- const [toast, setToast] = useState<string | null>(null);- const [selectedId, setSelectedId] = useState<string | null>(null);-- const showToast = useCallback((msg: string) => {- setToast(msg);- setTimeout(() => setToast(null), 4000);- }, []);-- // --- Load graph data ---- const loadGraph = useCallback(async () => {- const g = graphRef.current;- if (!g) return;-- try {- const [classesText, edgesText, propEdgesText] = await Promise.all([- mcp.sparqlQuery(CLASSES_QUERY),- mcp.sparqlQuery(EDGES_QUERY),- mcp.sparqlQuery(PROPERTY_EDGES_QUERY),- ]);-- const classBindings = parseSparqlResults(classesText);- const edgeBindings = parseSparqlResults(edgesText);- const propEdgeBindings = parseSparqlResults(propEdgesText);-- const nodeMap = new Map<string, GraphNode>();-- for (const b of classBindings) {- const uri = b.c?.value;- if (!uri) continue;- const id = shortUri(uri);- if (!nodeMap.has(id)) {- nodeMap.set(id, { id, label: b.label?.value || id, uri });- }- }-- // Add parent nodes missing from classes query- for (const b of edgeBindings) {- const parentUri = b.parent?.value;- if (!parentUri) continue;- const pid = shortUri(parentUri);- if (!nodeMap.has(pid)) {- nodeMap.set(pid, { id: pid, label: pid, uri: parentUri });- }- }-- const edgeSet = new Set<string>();- const links: GraphLink[] = [];- for (const b of edgeBindings) {- const subUri = b.sub?.value;- const parentUri = b.parent?.value;- if (!subUri || !parentUri) continue;- const sid = shortUri(subUri);- const pid = shortUri(parentUri);- const eid = `${sid}→${pid}`;- if (nodeMap.has(sid) && nodeMap.has(pid) && !edgeSet.has(eid)) {- edgeSet.add(eid);- links.push({ source: sid, target: pid, type: 'subclass' });- }- }-- // Object property edges (domain → range)- for (const b of propEdgeBindings) {- const domainUri = b.domain?.value;- const rangeUri = b.range?.value;- if (!domainUri || !rangeUri) continue;- const did = shortUri(domainUri);- const rid = shortUri(rangeUri);- const propLabel = b.propLabel?.value || shortUri(b.prop?.value || '');- const eid = `${did}→${rid}:${propLabel}`;- if (nodeMap.has(did) && nodeMap.has(rid) && !edgeSet.has(eid)) {- edgeSet.add(eid);- links.push({ source: did, target: rid, type: 'property', label: propLabel });- }- }-- // Connect all root nodes (no parent) to a virtual hub so the graph is one connected component- const hasParent = new Set<string>();- for (const l of links) {- if (l.type === 'subclass') hasParent.add(l.source as string);- }- const rootIds: string[] = [];- for (const id of nodeMap.keys()) {- if (!hasParent.has(id)) rootIds.push(id);- }- if (rootIds.length > 1) {- const hub: GraphNode = { id: '__root__', label: 'Ontology', uri: '' };- nodeMap.set('__root__', hub);- for (const rid of rootIds) {- links.push({ source: rid, target: '__root__', type: 'subclass' });- }- }-- g.graphData({ nodes: Array.from(nodeMap.values()), links });- refreshStats();- } catch (e) {- console.error('Failed to load graph:', e);- showToast('Failed to load graph from engine');- }- }, [showToast, refreshStats]);-- // --- Initialize 3D graph ---- useEffect(() => {- const el = containerRef.current;- if (!el) return;-- const graph = new (ForceGraph3D as any)()(el)- .backgroundColor('#1e1e2e')- .nodeLabel('label')- .nodeColor((node: object) => {- const n = node as GraphNode;- if (n.id === selectedId) return '#f9e2af';- if (n.id === '__root__') return '#f38ba8';- return '#89b4fa';- })- .nodeOpacity(0.95)- .nodeResolution(16)- .linkColor((link: object) => {- const l = link as GraphLink;- return l.type === 'property' ? '#f9e2af' : '#585b70';- })- .linkOpacity(0.6)- .linkWidth((link: object) => {- const l = link as GraphLink;- return l.type === 'property' ? 2 : 1.5;- })- .linkDirectionalArrowLength(6)- .linkDirectionalArrowRelPos(1)- .linkDirectionalArrowColor((link: object) => {- const l = link as GraphLink;- return l.type === 'property' ? '#f9e2af' : '#89b4fa';- })- .linkLabel((link: object) => {- const l = link as GraphLink;- return l.type === 'property' ? (l.label || '') : '';- })- .nodeThreeObject((node: object) => {- const n = node as GraphNode;- const group = new THREE.Group();-- // Sphere- const isRoot = n.id === '__root__';- const sphere = new THREE.Mesh(- new THREE.SphereGeometry(isRoot ? 8 : 5, 16, 16),- new THREE.MeshLambertMaterial({ color: n.id === selectedId ? 0xf9e2af : isRoot ? 0xf38ba8 : 0x89b4fa })- );- group.add(sphere);-- // Label sprite- const canvas = document.createElement('canvas');- canvas.width = 256;- canvas.height = 64;- const ctx = canvas.getContext('2d')!;- ctx.font = 'bold 24px sans-serif';- ctx.fillStyle = '#cdd6f4';- ctx.textAlign = 'center';- ctx.fillText(n.label.slice(0, 20), 128, 40);- const tex = new THREE.CanvasTexture(canvas);- const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthWrite: false }));- sprite.scale.set(40, 12, 1);- sprite.position.set(0, 12, 0);- group.add(sprite);-- return group;- })- .onNodeClick((node: object) => {- const n = node as GraphNode;- if (n.id === '__root__') return; // virtual hub not selectable- setSelectedId(n.id);- onNodeSelect({ id: n.id, label: n.label, uri: n.uri });- // Fly camera toward node- const dist = 80;- const distRatio = 1 + dist / Math.hypot(n.x ?? 0, n.y ?? 0, n.z ?? 0);- graph.cameraPosition(- { x: (n.x ?? 0) * distRatio, y: (n.y ?? 0) * distRatio, z: (n.z ?? 0) * distRatio },- { x: n.x ?? 0, y: n.y ?? 0, z: n.z ?? 0 },- 800- );- })- .onBackgroundClick(() => {- setSelectedId(null);- onNodeSelect(null);- });-- // Spring-based force tuning- graph.d3Force('link')?.distance(30).strength(0.7);- graph.d3Force('charge')?.strength(-120);-- // DAG mode: top-down tree layout in 3D- if (dagMode) {- graph.dagMode('td');- graph.dagLevelDistance(40);- }-- // Warm lighting- const scene = graph.scene() as THREE.Scene;- scene.add(new THREE.AmbientLight(0xffffff, 0.6));- const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);- dirLight.position.set(100, 200, 100);- scene.add(dirLight);-- graphRef.current = graph;-- // Size to container- const ro = new ResizeObserver(() => {- graph.width(el.offsetWidth).height(el.offsetHeight);- });- ro.observe(el);- graph.width(el.offsetWidth).height(el.offsetHeight);-- (window as unknown as Record<string, unknown>).__refreshGraph = loadGraph;-- return () => {- ro.disconnect();- graph._destructor?.();- graphRef.current = null;- delete (window as unknown as Record<string, unknown>).__refreshGraph;- };- }, [onNodeSelect, loadGraph]);-- // Refresh node colors when selection changes- useEffect(() => {- graphRef.current?.nodeThreeObjectExtend(false);- graphRef.current?.refresh?.();- }, [selectedId]);-- // Auto-load when connected- useEffect(() => {- if (status === 'connected') loadGraph();- }, [status, loadGraph]);-- // Delete key handler- useEffect(() => {- async function handleKeyDown(e: KeyboardEvent) {- if (e.key !== 'Delete' && e.key !== 'Backspace') return;- const tag = (e.target as HTMLElement)?.tagName;- if (tag === 'INPUT' || tag === 'TEXTAREA') return;- if (!selectedId) return;-- // Find the selected node's URI from current graph data- const data = graphRef.current?.graphData();- const node = data?.nodes?.find((n: GraphNode) => n.id === selectedId) as GraphNode | undefined;- if (!node?.uri) return;-- try {- await mcp.sparqlUpdate(`DELETE WHERE { <${node.uri}> ?p ?o }`);- await mcp.sparqlUpdate(`DELETE WHERE { ?s ?p <${node.uri}> }`);- await mcp.saveGraphToFile();- setSelectedId(null);- onNodeSelect(null);- await loadGraph();- showToast(`Deleted: ${node.label}`);- } catch (ex) {- showToast(`Delete failed: ${ex instanceof Error ? ex.message : String(ex)}`);- }- }- document.addEventListener('keydown', handleKeyDown);- return () => document.removeEventListener('keydown', handleKeyDown);- }, [selectedId, loadGraph, onNodeSelect, showToast]);-- // Right-click on canvas = add class- function handleContextMenu(e: React.MouseEvent) {- e.preventDefault();- setAddDialog({ x: e.clientX, y: e.clientY });- }-- async function handleAddClass(className: string) {- setAddDialog(null);- const localName = className.split(/\s+/).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('');- const turtle = `@prefix owl: <http://www.w3.org/2002/07/owl#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n<${ONTO_NS}${localName}> a owl:Class ; rdfs:label "${className}" .`;- try {- const v = await mcp.validate(turtle);- if (v.toLowerCase().includes('error')) { showToast(`Validation error: ${v}`); return; }- await mcp.loadTurtle(turtle);- await mcp.saveGraphToFile();- await loadGraph();- showToast(`Created: ${className}`);- } catch (ex) {- showToast(`Failed: ${ex instanceof Error ? ex.message : String(ex)}`);- }- }-- return (- <div className="absolute inset-0" onContextMenu={handleContextMenu}>- <div ref={containerRef} className="w-full h-full" />-- {addDialog && (- <AddClassDialog- position={addDialog}- onSubmit={handleAddClass}- onCancel={() => setAddDialog(null)}- />- )}-- {toast && (- <div className="absolute bottom-4 left-1/2 -translate-x-1/2 px-4 py-2 rounded text-sm max-w-md text-center"- style={{- background: toast.toLowerCase().includes('error') || toast.toLowerCase().includes('fail')- ? 'var(--error)' : 'var(--bg-panel)',- color: toast.toLowerCase().includes('error') || toast.toLowerCase().includes('fail')- ? '#1e1e2e' : 'var(--text-primary)',- border: '1px solid var(--border)',- }}>- {toast}- </div>- )}-- {status !== 'connected' && (- <div className="absolute inset-0 flex items-center justify-center"- style={{ color: 'var(--text-secondary)' }}>- {status === 'connecting' ? 'Connecting to engine...' : 'Engine not connected'}- </div>- )}-- <div className="absolute bottom-4 right-4 text-xs" style={{ color: 'var(--text-secondary)' }}>- Drag to orbit · Scroll to zoom · Click node to inspect · Right-click to add- </div>- </div>- );-}diff --git a/studio/src/components/LiveChrome.tsx b/studio/src/components/LiveChrome.tsxindex 97ea4ae4..f475e2f8 100644--- a/studio/src/components/LiveChrome.tsx+++ b/studio/src/components/LiveChrome.tsx@@ -6,6 +6,7 @@ import { Graph3D } from './Graph3D';import { ChatPanel } from './ChatPanel';import { PropertyInspector } from './PropertyInspector';import { LineagePanel } from './LineagePanel';+import { GovernancePanel } from './GovernancePanel';import * as mcp from '../lib/mcp-client';/**@@ -27,6 +28,7 @@ export function LiveChrome({ children }: { children: React.ReactNode }) {const [graphMode, setGraphMode] = useState<'2d' | '3d'>('2d');const [showInspector, setShowInspector] = useState(false);const [showLineage, setShowLineage] = useState(false);+ const [showGovernance, setShowGovernance] = useState(false);const [selectedNode, setSelectedNode] = useState<{ id: string; label: string; uri: string } | null>(null);const [projectName, setProjectName] = useState('studio-live');const [savingAs, setSavingAs] = useState(false);@@ -181,6 +183,12 @@ export function LiveChrome({ children }: { children: React.ReactNode }) {color: showLineage ? 'var(--bg-primary)' : 'var(--text-secondary)' }}>Lineage</button>+ <button onClick={() => setShowGovernance(g => !g)}+ className="text-xs px-2 py-1 rounded"+ style={{ background: showGovernance ? 'var(--accent)' : 'var(--bg-panel)',+ color: showGovernance ? 'var(--bg-primary)' : 'var(--text-secondary)' }}>+ Governance+ </button></div></div>@@ -205,6 +213,13 @@ export function LiveChrome({ children }: { children: React.ReactNode }) {</div>)}+ {showGovernance && (+ <div className="w-72 border-l overflow-hidden"+ style={{ borderColor: 'var(--border)', background: 'var(--bg-panel)' }}>+ <GovernancePanel />+ </div>+ )}+{/* The shared demonstration body (corpus / findings / resolution /compare), the same tree the replay build renders. */}<div className="w-96 border-l overflow-hidden flex flex-col"diff --git a/studio/src/lib/roles.ts b/studio/src/lib/roles.tsindex e88584be..c7972f4b 100644--- a/studio/src/lib/roles.ts+++ b/studio/src/lib/roles.ts@@ -1,19 +1,22 @@/*** Viewer roles offered in the UI.*- * These mirror `src-tauri/sidecars/agent/acl.ts`, which is the component that- * actually enforces them. The duplication is deliberate: the frontend and the- * sidecar are separate processes with separate build graphs, and a shared- * module between them would mean bundling sidecar code into the web build.+ * Nothing in the sidecar's live chat loop currently enforces these: the+ * agent sidecar's retrieval path (graphrag.ts) takes no role parameter, so a+ * live chat session is not filtered by role today. This module and+ * `GovernancePanel.tsx` (which renders it) show what access control WOULD+ * withhold, computed live from the corpus's own :aclGroup / :classification+ * triples via `resolveVisibility` below, not a claim that retrieval is+ * currently gated by it. An earlier version of this module's docstring+ * claimed a sidecar module (`acl.ts`) enforced these roles; nothing imported+ * that module except its own test, so nothing actually enforced anything,+ * and it has been removed rather than left as a claim this codebase could+ * not back up.*- * DENY BY DEFAULT, on both sides of that duplication. An id sent from here- * that the sidecar does not recognise must be denied there, not treated as- * unrestricted, and this module's own `resolveVisibility` below must fail the- * same way: an unrecognised role id or an empty group list withholds every- * document, so the two lists cannot silently drift into one filtering and the- * other not. Defaulting either side to full access on a mismatch would still- * "work" in the sense of not crashing, which is exactly what makes it- * dangerous: it would visibly stop filtering while looking like it was.+ * DENY BY DEFAULT regardless: an unrecognised role id or an empty group list+ * withholds every document rather than defaulting to full access, because a+ * silent fallback to "everything visible" would look identical to filtering+ * having run, which is exactly what makes it dangerous.*/export interface RoleOption {@@ -118,8 +121,10 @@ export interface StoreOption {available: boolean;}+// 'aws-semantic' / 'AWS semantic platform' has been removed: it named no+// real hosted product. Amazon Neptune is AWS's actual graph/RDF offering and+// stays as a genuinely disclosed-but-unavailable option.export const STORE_OPTIONS: StoreOption[] = [{ id: 'embedded', label: 'Embedded engine', available: true },{ id: 'neptune', label: 'Amazon Neptune', available: false },- { id: 'aws-semantic', label: 'AWS semantic platform', available: false },];