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
feat: D3 tree view, multi-step ontology builder, connected graph
FABIOTESS8946505a2f9f
diff --git a/Cargo.lock b/Cargo.lockindex a3359f6e..573760ce 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2345,7 +2345,7 @@ dependencies = [[[package]]name = "open-ontologies"-version = "0.1.10"+version = "0.1.11"dependencies = ["anyhow","arrow",diff --git a/studio/package-lock.json b/studio/package-lock.jsonindex 62127383..314b66b3 100644--- a/studio/package-lock.json+++ b/studio/package-lock.json@@ -15,6 +15,7 @@"3d-force-graph": "^1.79.1","cytoscape": "^3.33.1","cytoscape-dagre": "^2.5.0",+ "d3": "^7.9.0","react": "^19.1.0","react-dom": "^19.1.0","react-markdown": "^10.1.0",@@ -25,6 +26,7 @@"devDependencies": {"@tauri-apps/cli": "^2","@types/cytoscape": "^3.21.9",+ "@types/d3": "^7.4.3","@types/react": "^19.1.8","@types/react-dom": "^19.1.6","@vitejs/plugin-react": "^4.6.0",@@ -1676,6 +1678,290 @@"dev": true,"license": "MIT"},+ "node_modules/@types/d3": {+ "version": "7.4.3",+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-array": "*",+ "@types/d3-axis": "*",+ "@types/d3-brush": "*",+ "@types/d3-chord": "*",+ "@types/d3-color": "*",+ "@types/d3-contour": "*",+ "@types/d3-delaunay": "*",+ "@types/d3-dispatch": "*",+ "@types/d3-drag": "*",+ "@types/d3-dsv": "*",+ "@types/d3-ease": "*",+ "@types/d3-fetch": "*",+ "@types/d3-force": "*",+ "@types/d3-format": "*",+ "@types/d3-geo": "*",+ "@types/d3-hierarchy": "*",+ "@types/d3-interpolate": "*",+ "@types/d3-path": "*",+ "@types/d3-polygon": "*",+ "@types/d3-quadtree": "*",+ "@types/d3-random": "*",+ "@types/d3-scale": "*",+ "@types/d3-scale-chromatic": "*",+ "@types/d3-selection": "*",+ "@types/d3-shape": "*",+ "@types/d3-time": "*",+ "@types/d3-time-format": "*",+ "@types/d3-timer": "*",+ "@types/d3-transition": "*",+ "@types/d3-zoom": "*"+ }+ },+ "node_modules/@types/d3-array": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-axis": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-brush": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-chord": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-contour": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-array": "*",+ "@types/geojson": "*"+ }+ },+ "node_modules/@types/d3-delaunay": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",+ "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-dispatch": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",+ "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-drag": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-dsv": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-ease": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-fetch": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-dsv": "*"+ }+ },+ "node_modules/@types/d3-force": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-format": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",+ "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-geo": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",+ "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/geojson": "*"+ }+ },+ "node_modules/@types/d3-hierarchy": {+ "version": "3.1.7",+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-path": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-polygon": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-quadtree": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-random": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",+ "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-scale": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-time": "*"+ }+ },+ "node_modules/@types/d3-scale-chromatic": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-selection": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-shape": {+ "version": "3.1.8",+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",+ "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-path": "*"+ }+ },+ "node_modules/@types/d3-time": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-time-format": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",+ "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-timer": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/d3-transition": {+ "version": "3.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-zoom": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/d3-interpolate": "*",+ "@types/d3-selection": "*"+ }+ },"node_modules/@types/debug": {"version": "4.1.12","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",@@ -1700,6 +1986,13 @@"@types/estree": "*"}},+ "node_modules/@types/geojson": {+ "version": "7946.0.16",+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/hast": {"version": "3.0.4","resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",@@ -1939,6 +2232,15 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/commander": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",+ "license": "MIT",+ "engines": {+ "node": ">= 10"+ }+ },"node_modules/convert-source-map": {"version": "2.0.0","resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",@@ -1973,6 +2275,47 @@"cytoscape": "^3.2.22"}},+ "node_modules/d3": {+ "version": "7.9.0",+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "3",+ "d3-axis": "3",+ "d3-brush": "3",+ "d3-chord": "3",+ "d3-color": "3",+ "d3-contour": "4",+ "d3-delaunay": "6",+ "d3-dispatch": "3",+ "d3-drag": "3",+ "d3-dsv": "3",+ "d3-ease": "3",+ "d3-fetch": "3",+ "d3-force": "3",+ "d3-format": "3",+ "d3-geo": "3",+ "d3-hierarchy": "3",+ "d3-interpolate": "3",+ "d3-path": "3",+ "d3-polygon": "3",+ "d3-quadtree": "3",+ "d3-random": "3",+ "d3-scale": "4",+ "d3-scale-chromatic": "3",+ "d3-selection": "3",+ "d3-shape": "3",+ "d3-time": "3",+ "d3-time-format": "4",+ "d3-timer": "3",+ "d3-transition": "3",+ "d3-zoom": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-array": {"version": "3.2.4","resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",@@ -1985,12 +2328,49 @@"node": ">=12"}},+ "node_modules/d3-axis": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-binarytree": {"version": "1.0.2","resolved": "https://registry.npmjs.org/d3-binarytree/-/d3-binarytree-1.0.2.tgz","integrity": "sha512-cElUNH+sHu95L04m92pG73t2MEJXKu+GeKUN1TJkFsu93E5W8E9Sc3kHEGJKgenGvj19m6upSn2EunvMgMD2Yw==","license": "MIT"},+ "node_modules/d3-brush": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "3",+ "d3-transition": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-chord": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-color": {"version": "3.1.0","resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",@@ -2000,6 +2380,30 @@"node": ">=12"}},+ "node_modules/d3-contour": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "^3.2.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-delaunay": {+ "version": "6.0.4",+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",+ "license": "ISC",+ "dependencies": {+ "delaunator": "5"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-dispatch": {"version": "3.0.1","resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",@@ -2009,6 +2413,79 @@"node": ">=12"}},+ "node_modules/d3-drag": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-selection": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dsv": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",+ "license": "ISC",+ "dependencies": {+ "commander": "7",+ "iconv-lite": "0.6",+ "rw": "1"+ },+ "bin": {+ "csv2json": "bin/dsv2json.js",+ "csv2tsv": "bin/dsv2dsv.js",+ "dsv2dsv": "bin/dsv2dsv.js",+ "dsv2json": "bin/dsv2json.js",+ "json2csv": "bin/json2dsv.js",+ "json2dsv": "bin/json2dsv.js",+ "json2tsv": "bin/json2dsv.js",+ "tsv2csv": "bin/dsv2dsv.js",+ "tsv2json": "bin/dsv2json.js"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-fetch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",+ "license": "ISC",+ "dependencies": {+ "d3-dsv": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-force": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-quadtree": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-force-3d": {"version": "3.0.6","resolved": "https://registry.npmjs.org/d3-force-3d/-/d3-force-3d-3.0.6.tgz",@@ -2034,6 +2511,27 @@"node": ">=12"}},+ "node_modules/d3-geo": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",+ "license": "ISC",+ "dependencies": {+ "d3-array": "2.5.0 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-hierarchy": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-interpolate": {"version": "3.0.1","resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",@@ -2052,6 +2550,24 @@"integrity": "sha512-F8gPlqpP+HwRPMO/8uOu5wjH110+6q4cgJvgJT6vlpy3BEaDIKlTZrgHKZSp/i1InRpVfh4puY/kvL6MxK930A==","license": "MIT"},+ "node_modules/d3-path": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-polygon": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-quadtree": {"version": "3.0.1","resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",@@ -2061,6 +2577,15 @@"node": ">=12"}},+ "node_modules/d3-random": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-scale": {"version": "4.0.2","resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",@@ -2099,6 +2624,18 @@"node": ">=12"}},+ "node_modules/d3-shape": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",+ "license": "ISC",+ "dependencies": {+ "d3-path": "^3.1.0"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/d3-time": {"version": "3.1.0","resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",@@ -2132,6 +2669,41 @@"node": ">=12"}},+ "node_modules/d3-transition": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-dispatch": "1 - 3",+ "d3-ease": "1 - 3",+ "d3-interpolate": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ },+ "peerDependencies": {+ "d3-selection": "2 - 3"+ }+ },+ "node_modules/d3-zoom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-transition": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/dagre": {"version": "0.8.5","resolved": "https://registry.npmjs.org/dagre/-/dagre-0.8.5.tgz",@@ -2184,6 +2756,15 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/delaunator": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",+ "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",+ "license": "ISC",+ "dependencies": {+ "robust-predicates": "^3.0.2"+ }+ },"node_modules/dequal": {"version": "2.0.3","resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",@@ -2422,6 +3003,18 @@"url": "https://opencollective.com/unified"}},+ "node_modules/iconv-lite": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/inline-style-parser": {"version": "0.2.7","resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",@@ -3695,6 +4288,12 @@"url": "https://opencollective.com/unified"}},+ "node_modules/robust-predicates": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",+ "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",+ "license": "Unlicense"+ },"node_modules/rollup": {"version": "4.59.0","resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",@@ -3739,6 +4338,18 @@"fsevents": "~2.3.2"}},+ "node_modules/rw": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",+ "license": "BSD-3-Clause"+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",diff --git a/studio/package.json b/studio/package.jsonindex a2cf4699..2c343117 100644--- a/studio/package.json+++ b/studio/package.json@@ -17,6 +17,7 @@"3d-force-graph": "^1.79.1","cytoscape": "^3.33.1","cytoscape-dagre": "^2.5.0",+ "d3": "^7.9.0","react": "^19.1.0","react-dom": "^19.1.0","react-markdown": "^10.1.0",@@ -27,6 +28,7 @@"devDependencies": {"@tauri-apps/cli": "^2","@types/cytoscape": "^3.21.9",+ "@types/d3": "^7.4.3","@types/react": "^19.1.8","@types/react-dom": "^19.1.6","@vitejs/plugin-react": "^4.6.0",diff --git a/studio/src-tauri/sidecars/agent/dist/index.js b/studio/src-tauri/sidecars/agent/dist/index.jsindex 69ce041c..6f1f233a 100644--- a/studio/src-tauri/sidecars/agent/dist/index.js+++ b/studio/src-tauri/sidecars/agent/dist/index.js@@ -1,217 +1,183 @@import { query } from '@anthropic-ai/claude-agent-sdk';import * as readline from 'readline';-// --- Configuration ---const ENGINE_URL = 'http://localhost:8080/mcp';-const SYSTEM_PROMPT = `You are an ontology engineering assistant with access to the Open Ontologies engine and all 42 of its tools.+const SYSTEM_PROMPT = `You are an ontology engineering assistant with MCP tools for the Open Ontologies engine.-Do not use emoji in your responses. Use plain text and markdown formatting only.+No emoji. Plain text and markdown only.-ALL 42 TOOLS — use whichever are appropriate for the task:+CRITICAL: When asked to build an ontology, you will receive step-by-step instructions. Follow each step EXACTLY. Call the tools specified — do NOT just describe what you would do.-Core:-- onto_clear: Reset the triple store (call FIRST when building from scratch)-- onto_load: Load Turtle RDF into the store (use "turtle" param for inline content)-- onto_save: Export ontology to file-- onto_stats: Get triple/class/property counts-- onto_validate: Check RDF/OWL syntax-- onto_lint: Quality checks — missing labels, domains, ranges-- onto_query: Run SPARQL SELECT queries-- onto_diff: Compare two ontology versions-- onto_convert: Convert between formats (Turtle, N-Triples, RDF/XML, N-Quads, TriG)-- onto_status: Check if server is running--Remote:-- onto_pull: Fetch ontology from a remote URL or SPARQL endpoint-- onto_push: Push ontology to a remote SPARQL endpoint-- onto_import: Resolve and load owl:imports chains from URLs--Schema:-- onto_import_schema: Import a PostgreSQL schema as OWL ontology--Data pipeline:-- onto_map: Generate a mapping config from data file + loaded ontology-- onto_ingest: Parse structured data (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet) into RDF-- onto_shacl: Validate loaded data against SHACL shapes-- onto_extend: Run the full pipeline: ingest + SHACL validate + reason in one call--Versioning:-- onto_version: Save a named snapshot before making changes-- onto_history: List saved version snapshots-- onto_rollback: Restore a previous version--Lifecycle (Terraform-style):-- onto_plan: Preview changes — added/removed classes, blast radius, risk score-- onto_apply: Apply planned changes (safe or migrate mode)-- onto_lock: Protect production IRIs from removal-- onto_drift: Compare versions — rename detection, drift velocity-- onto_enforce: Check design pattern compliance (generic, boro, value_partition)-- onto_monitor: Run SPARQL watchers with threshold alerts-- onto_monitor_clear: Clear blocked state after resolving monitor alerts-- onto_lineage: View the session lineage trail--Alignment:-- onto_align: Detect alignment candidates between two ontologies (7 weighted signals)-- onto_align_feedback: Accept/reject alignment candidates to self-calibrate confidence--Clinical:-- onto_crosswalk: Look up ICD-10 / SNOMED / MeSH terminology mappings-- onto_enrich: Add skos:exactMatch triples linking classes to clinical codes-- onto_validate_clinical: Check class labels against clinical crosswalk terminology--Feedback (self-calibrating):-- onto_lint_feedback: Accept/dismiss a lint issue to suppress future warnings-- onto_enforce_feedback: Accept/dismiss an enforce violation--Embeddings + semantic search:-- onto_embed: Generate text + Poincare structural embeddings for all classes-- onto_search: Find classes by natural language description (requires onto_embed first)-- onto_similarity: Compute embedding similarity between two IRIs--OWL2-DL Reasoning:-- onto_reason: Run RDFS or OWL-RL inference — materializes inferred triples-- onto_dl_explain: Explain why a class is unsatisfiable (DL tableaux clash trace)-- onto_dl_check: Check if one class is subsumed by another (DL tableaux)--CRITICAL RULES:-1. When asked to BUILD, CREATE, or MAKE a new ontology from scratch — call onto_clear FIRST, then onto_load.-2. When asked to EXPAND, ADD TO, or EXTEND an existing ontology — do NOT clear, just onto_load.-3. After any onto_load or mutation, ALWAYS call onto_save with path "~/.open-ontologies/studio-live.ttl" to persist the graph so the UI can display it.-4. After mutations, mention what changed so the UI can refresh the graph.-5. For a thorough build: onto_clear -> onto_load -> onto_stats -> onto_reason -> onto_stats -> onto_lint -> onto_enforce (generic) -> onto_query (verify) -> onto_save -> onto_version.-6. ALWAYS call onto_reason after onto_load — it materializes inferred triples (transitive subclass chains, domain/range propagation). Call onto_stats before and after to show what was inferred.-7. ALWAYS call onto_enforce with rule pack "generic" after onto_lint — it catches design pattern issues that lint misses.-8. ALWAYS call onto_version after onto_save — every save should have a rollback point.-9. For data ingestion: onto_map -> onto_ingest -> onto_shacl -> onto_reason -> onto_save -> onto_version.-10. For alignment: onto_align -> onto_align_feedback -> onto_apply -> onto_save -> onto_version.`;+After any onto_load, always call onto_stats to verify what was loaded.+After all loads are done, always call onto_save with path "~/.open-ontologies/studio-live.ttl".`;const MUTATION_TOOLS = new Set(['onto_load', 'onto_clear', 'onto_apply', 'onto_reason','onto_rollback', 'onto_ingest', 'onto_extend', 'onto_import','onto_pull', 'onto_enrich']);-// --- State ---let sessionId;-// --- stdout Protocol ---function send(msg) {process.stdout.write(JSON.stringify(msg) + '\n');}-// --- Wait for engine to be ready ---async function waitForEngine(maxRetries = 15) {for (let i = 0; i < maxRetries; i++) {try {const resp = await fetch(ENGINE_URL, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Accept': 'application/json, text/event-stream',- },+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream' },body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'initialize',- params: {- protocolVersion: '2025-03-26',- capabilities: {},- clientInfo: { name: 'ontology-agent-probe', version: '1.0.0' },- },+ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'probe', version: '1.0.0' } },}),});if (resp.ok)return true;}- catch {- // Engine not ready yet- }+ catch { /* retry */ }await new Promise(r => setTimeout(r, 1000));}return false;}-// --- Handle a chat message using the Claude Agent SDK ----async function handleMessage(userMessage) {+// --- Run one agent turn within a persistent session ---+async function runTurn(prompt) {let mutated = false;- try {- // Build the prompt with system context prepended- const fullPrompt = userMessage;- const q = query({- prompt: fullPrompt,- options: {- systemPrompt: SYSTEM_PROMPT,- model: 'claude-opus-4-6',- mcpServers: {- 'ontology-engine': {- type: 'http',- url: ENGINE_URL,- },- },- // Allow all MCP tools without prompting- allowedTools: ['mcp__ontology-engine__*'],- // No built-in tools needed - only MCP tools from the engine- tools: [],- // Persist sessions to disk so resume works across turns- // Don't persist to disk — prevents auto-resuming stale sessions after engine restart- persistSession: false,- // Resume in-memory session for multi-turn within same sidecar process- ...(sessionId ? { resume: sessionId } : {}),- // Accept edits mode to avoid permission prompts- permissionMode: 'bypassPermissions',- allowDangerouslySkipPermissions: true,- },- });- for await (const message of q) {- // Capture session ID for multi-turn AND share with frontend for SPARQL queries- if ('session_id' in message && message.session_id && !sessionId) {+ const q = query({+ prompt,+ options: {+ systemPrompt: SYSTEM_PROMPT,+ model: 'claude-opus-4-6',+ mcpServers: { 'ontology-engine': { type: 'http', url: ENGINE_URL } },+ allowedTools: ['mcp__ontology-engine__*'],+ tools: [],+ persistSession: true,+ ...(sessionId ? { resume: sessionId } : {}),+ permissionMode: 'bypassPermissions',+ allowDangerouslySkipPermissions: true,+ maxTurns: 15,+ },+ });+ for await (const message of q) {+ if ('session_id' in message && message.session_id) {+ if (!sessionId) {sessionId = message.session_id;- // Tell the frontend which MCP session to use for graph queriessend({ type: 'session', sessionId: message.session_id });}- switch (message.type) {- case 'assistant': {- // Extract text content from the assistant message- const content = message.message?.content;- if (Array.isArray(content)) {- for (const block of content) {- if (block.type === 'text' && block.text) {- send({ type: 'text', content: block.text });- }- if (block.type === 'tool_use') {- send({ type: 'tool_call', tool: block.name, input: block.input });- // Tool names are namespaced: "mcp__ontology-engine__onto_load"- // Check if the name ends with any known mutation tool- if ([...MUTATION_TOOLS].some(t => block.name === t || block.name.endsWith(`__${t}`))) {- mutated = true;- }+ }+ switch (message.type) {+ case 'assistant': {+ const content = message.message?.content;+ if (Array.isArray(content)) {+ for (const block of content) {+ if (block.type === 'text' && block.text) {+ send({ type: 'text', content: block.text });+ }+ if (block.type === 'tool_use') {+ send({ type: 'tool_call', tool: block.name, input: block.input });+ if ([...MUTATION_TOOLS].some(t => block.name === t || block.name.endsWith(`__${t}`))) {+ mutated = true;}}}- break;- }- case 'result': {- // Final result message- if (message.subtype === 'success') {- // Success - text already sent via assistant messages- }- else {- // Error subtypes: error_during_execution, error_max_turns, etc.- const errors = 'errors' in message ? message.errors : [];- send({ type: 'error', error: (errors && errors.length > 0) ? errors.join('; ') : `Agent error: ${message.subtype}` });- }- break;}- case 'system': {- // System messages (compact boundaries, etc.) - ignore- break;+ break;+ }+ case 'result': {+ if (message.subtype !== 'success') {+ const errors = 'errors' in message ? message.errors : [];+ send({ type: 'error', error: (errors && errors.length > 0) ? errors.join('; ') : `Agent error: ${message.subtype}` });}+ break;}+ case 'system': break;+ }+ }+ return mutated;+}+// --- Build request detection ---+function isBuildRequest(msg) {+ const lower = msg.toLowerCase();+ return (lower.includes('build') || lower.includes('create') || lower.includes('make') || lower.includes('generate'))+ && (lower.includes('ontology') || lower.includes('about'));+}+function extractDomain(msg) {+ const patterns = [+ /(?:about|for|on|of)\s+(.+)/i,+ /(?:build|create|make|generate)\s+(?:a\s+|an\s+|the\s+)?(?:\w+\s+)?(?:ontology\s+)?(?:about|for|on|of)\s+(.+)/i,+ ];+ for (const p of patterns) {+ const m = msg.match(p);+ if (m) {+ const match = m[2] || m[1];+ if (match)+ return match.trim().replace(/[.!?]+$/, '');+ }+ }+ return msg.replace(/^(build|create|make|generate)\s+(an?\s+)?ontology\s*/i, '').trim() || msg;+}+// --- Multi-step build within ONE session ---+async function handleBuild(domain) {+ const ns = domain.toLowerCase().replace(/[^a-z0-9]+/g, '-');+ // Step 1: Clear + load classes+ send({ type: 'text', content: `**Building ontology: ${domain}**\n\n---\n**Step 1/4:** Classes hierarchy...` });+ await runTurn(`Build an ontology about "${domain}". Use namespace @prefix : <http://example.org/${ns}#> .++Step 1: Call onto_clear. Then call onto_load with Turtle containing:+- 80-150 owl:Class declarations organised in a subClassOf hierarchy 5-7 levels deep+- A root class, 5-8 major branches, each with 3-6 sub-branches, each with 2-5 leaves+- Enumerate ALL real-world subtypes exhaustively+- Every class MUST have rdfs:label and rdfs:comment++Call onto_stats after loading to verify. Do NOT call onto_save yet — more content coming.`);+ // Step 2: Properties (SAME session — agent has context)+ send({ type: 'text', content: `\n---\n**Step 2/4:** Properties...` });+ await runTurn(`Now add properties to the ontology. Call onto_load with Turtle using the SAME namespace as before containing:++- 25-40 owl:ObjectProperty declarations, each with rdfs:domain, rdfs:range, rdfs:label, rdfs:comment+- Build rdfs:subPropertyOf hierarchies (e.g., hasParticipant > hasAgent > hasDriver)+- Add owl:inverseOf pairs for bidirectional relationships+- Mark owl:TransitiveProperty (isPartOf), owl:SymmetricProperty (isRelatedTo), owl:FunctionalProperty where appropriate+- 15-20 owl:DatatypeProperty declarations with rdfs:domain, rdfs:range (xsd types), rdfs:label, rdfs:comment++Call onto_stats after loading. Do NOT call onto_save yet.`);+ // Step 3: Axioms + individuals (SAME session)+ send({ type: 'text', content: `\n---\n**Step 3/4:** Axioms + individuals...` });+ await runTurn(`Now add axioms and individuals. Call onto_load with Turtle using the SAME namespace containing:++- owl:disjointWith between ALL sibling classes that cannot overlap+- 15-20 owl:NamedIndividual instances — real-world examples with rdf:type and property values++Call onto_stats after loading. Do NOT call onto_save yet.`);+ // Step 4: Reason + save (SAME session)+ send({ type: 'text', content: `\n---\n**Step 4/4:** Reasoning + save...` });+ await runTurn(`Final step. Run:+1. onto_reason with profile "rdfs"+2. onto_stats — report the final counts+3. onto_save with path "~/.open-ontologies/studio-live.ttl"++Report the final ontology statistics.`);+ send({ type: 'text', content: `\n---\n**Build complete.** Refresh the tree view to see the full graph.` });+}+// --- Handle a chat message ---+async function handleMessage(userMessage) {+ try {+ if (isBuildRequest(userMessage)) {+ const domain = extractDomain(userMessage);+ // Fresh session for each new build+ sessionId = undefined;+ await handleBuild(domain);+ send({ type: 'done', mutated: true });+ }+ else {+ const mutated = await runTurn(userMessage);+ send({ type: 'done', mutated });}- send({ type: 'done', mutated });}catch (e) {send({ type: 'error', error: String(e) });- send({ type: 'done', mutated });+ send({ type: 'done', mutated: false });}}-// --- stdin/stdout Protocol ---+// --- Main ---async function main() {- // Wait for the ontology engine to be readyconst engineReady = await waitForEngine();if (!engineReady) {send({ type: 'error', error: 'Engine not reachable after 15 retries' });diff --git a/studio/src-tauri/sidecars/agent/index.ts b/studio/src-tauri/sidecars/agent/index.tsindex 19e3d77f..28c32560 100644--- a/studio/src-tauri/sidecars/agent/index.ts+++ b/studio/src-tauri/sidecars/agent/index.ts@@ -1,95 +1,17 @@import { query } from '@anthropic-ai/claude-agent-sdk';-import type { Query, SDKMessage } from '@anthropic-ai/claude-agent-sdk';+import type { Query } from '@anthropic-ai/claude-agent-sdk';import * as readline from 'readline';-// --- Configuration ----const ENGINE_URL = 'http://localhost:8080/mcp';-const SYSTEM_PROMPT = `You are an ontology engineering assistant with access to the Open Ontologies engine and all 43 of its tools.--Do not use emoji in your responses. Use plain text and markdown formatting only.--ALL 43 TOOLS — use whichever are appropriate for the task:--Core:-- onto_clear: Reset the triple store (call FIRST when building from scratch)-- onto_load: Load Turtle RDF into the store (use "turtle" param for inline content)-- onto_save: Export ontology to file-- onto_stats: Get triple/class/property counts-- onto_validate: Check RDF/OWL syntax-- onto_lint: Quality checks — missing labels, domains, ranges-- onto_query: Run SPARQL SELECT queries-- onto_diff: Compare two ontology versions-- onto_convert: Convert between formats (Turtle, N-Triples, RDF/XML, N-Quads, TriG)-- onto_status: Check if server is running--Marketplace:-- onto_marketplace: Browse and install standard ontologies from a curated catalogue of 29 W3C/ISO/industry standards (use action "list" or "install" with an id)--Remote:-- onto_pull: Fetch ontology from a remote URL or SPARQL endpoint-- onto_push: Push ontology to a remote SPARQL endpoint-- onto_import: Resolve and load owl:imports chains from URLs--Schema:-- onto_import_schema: Import a PostgreSQL schema as OWL ontology--Data pipeline:-- onto_map: Generate a mapping config from data file + loaded ontology-- onto_ingest: Parse structured data (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet) into RDF-- onto_shacl: Validate loaded data against SHACL shapes-- onto_extend: Run the full pipeline: ingest + SHACL validate + reason in one call--Versioning:-- onto_version: Save a named snapshot before making changes-- onto_history: List saved version snapshots-- onto_rollback: Restore a previous version--Lifecycle (Terraform-style):-- onto_plan: Preview changes — added/removed classes, blast radius, risk score-- onto_apply: Apply planned changes (safe or migrate mode)-- onto_lock: Protect production IRIs from removal-- onto_drift: Compare versions — rename detection, drift velocity-- onto_enforce: Check design pattern compliance (generic, boro, value_partition)-- onto_monitor: Run SPARQL watchers with threshold alerts (supports webhook_url for push notifications)-- onto_monitor_clear: Clear blocked state after resolving monitor alerts-- onto_lineage: View the session lineage trail--Alignment:-- onto_align: Detect alignment candidates between two ontologies (7 weighted signals)-- onto_align_feedback: Accept/reject alignment candidates to self-calibrate confidence--Clinical:-- onto_crosswalk: Look up ICD-10 / SNOMED / MeSH terminology mappings-- onto_enrich: Add skos:exactMatch triples linking classes to clinical codes-- onto_validate_clinical: Check class labels against clinical crosswalk terminology--Feedback (self-calibrating):-- onto_lint_feedback: Accept/dismiss a lint issue to suppress future warnings-- onto_enforce_feedback: Accept/dismiss an enforce violation--Embeddings + semantic search:-- onto_embed: Generate text + Poincare structural embeddings for all classes-- onto_search: Find classes by natural language description (requires onto_embed first)-- onto_similarity: Compute embedding similarity between two IRIs--OWL2-DL Reasoning:-- onto_reason: Run RDFS or OWL-RL inference — materializes inferred triples-- onto_dl_explain: Explain why a class is unsatisfiable (DL tableaux clash trace)-- onto_dl_check: Check if one class is subsumed by another (DL tableaux)--CRITICAL RULES:-1. When asked to BUILD, CREATE, or MAKE a new ontology from scratch — call onto_clear FIRST, then onto_load.-2. When asked to EXPAND, ADD TO, or EXTEND an existing ontology — do NOT clear, just onto_load.-3. After any onto_load or mutation, ALWAYS call onto_save with path "~/.open-ontologies/studio-live.ttl" to persist the graph so the UI can display it.-4. After mutations, mention what changed so the UI can refresh the graph.-5. For a thorough build: onto_clear -> onto_load -> onto_stats -> onto_reason -> onto_stats -> onto_lint -> onto_enforce (generic) -> onto_query (verify) -> onto_save -> onto_version.-6. ALWAYS call onto_reason after onto_load — it materializes inferred triples (transitive subclass chains, domain/range propagation). Call onto_stats before and after to show what was inferred.-7. ALWAYS call onto_enforce with rule pack "generic" after onto_lint — it catches design pattern issues that lint misses.-8. ALWAYS call onto_version after onto_save — every save should have a rollback point.-9. For data ingestion: onto_map -> onto_ingest -> onto_shacl -> onto_reason -> onto_save -> onto_version.-10. For alignment: onto_align -> onto_align_feedback -> onto_apply -> onto_save -> onto_version.`;+const SYSTEM_PROMPT = `You are an ontology engineering assistant with MCP tools for the Open Ontologies engine.++No emoji. Plain text and markdown only.++CRITICAL: When asked to build an ontology, you will receive step-by-step instructions. Follow each step EXACTLY. Call the tools specified — do NOT just describe what you would do.++After any onto_load, always call onto_stats to verify what was loaded.+After all loads are done, always call onto_save with path "~/.open-ontologies/studio-live.ttl".`;const MUTATION_TOOLS = new Set(['onto_load', 'onto_clear', 'onto_apply', 'onto_reason',@@ -97,151 +19,202 @@ const MUTATION_TOOLS = new Set(['onto_pull', 'onto_enrich']);-// --- State ----let sessionId: string | undefined;-// --- stdout Protocol ----function send(msg: Record<string, unknown>): void {process.stdout.write(JSON.stringify(msg) + '\n');}-// --- Wait for engine to be ready ----async function waitForEngine(maxRetries = 15): Promise<boolean> {for (let i = 0; i < maxRetries; i++) {try {const resp = await fetch(ENGINE_URL, {method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'Accept': 'application/json, text/event-stream',- },+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream' },body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'initialize',- params: {- protocolVersion: '2025-03-26',- capabilities: {},- clientInfo: { name: 'ontology-agent-probe', version: '1.0.0' },- },+ jsonrpc: '2.0', id: 1, method: 'initialize',+ params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'probe', version: '1.0.0' } },}),});if (resp.ok) return true;- } catch {- // Engine not ready yet- }+ } catch { /* retry */ }await new Promise(r => setTimeout(r, 1000));}return false;}-// --- Handle a chat message using the Claude Agent SDK ---+// --- Run one agent turn within a persistent session ----async function handleMessage(userMessage: string): Promise<void> {+async function runTurn(prompt: string): Promise<boolean> {let mutated = false;- try {- // Build the prompt with system context prepended- const fullPrompt = userMessage;-- const q: Query = query({- prompt: fullPrompt,- options: {- systemPrompt: SYSTEM_PROMPT,- model: 'claude-opus-4-6',- mcpServers: {- 'ontology-engine': {- type: 'http',- url: ENGINE_URL,- },- },- // Allow all MCP tools without prompting- allowedTools: ['mcp__ontology-engine__*'],- // No built-in tools needed - only MCP tools from the engine- tools: [],- // Persist sessions to disk so resume works across turns- // Don't persist to disk — prevents auto-resuming stale sessions after engine restart- persistSession: false,- // Resume in-memory session for multi-turn within same sidecar process- ...(sessionId ? { resume: sessionId } : {}),- // Accept edits mode to avoid permission prompts- permissionMode: 'bypassPermissions',- allowDangerouslySkipPermissions: true,- },- });-- for await (const message of q) {- // Capture session ID for multi-turn AND share with frontend for SPARQL queries- if ('session_id' in message && message.session_id && !sessionId) {+ const q: Query = query({+ prompt,+ options: {+ systemPrompt: SYSTEM_PROMPT,+ model: 'claude-opus-4-6',+ mcpServers: { 'ontology-engine': { type: 'http', url: ENGINE_URL } },+ allowedTools: ['mcp__ontology-engine__*'],+ tools: [],+ persistSession: true,+ ...(sessionId ? { resume: sessionId } : {}),+ permissionMode: 'bypassPermissions',+ allowDangerouslySkipPermissions: true,+ maxTurns: 15,+ },+ });++ for await (const message of q) {+ if ('session_id' in message && message.session_id) {+ if (!sessionId) {sessionId = message.session_id;- // Tell the frontend which MCP session to use for graph queriessend({ type: 'session', sessionId: message.session_id });}+ }- switch (message.type) {- case 'assistant': {- // Extract text content from the assistant message- const content = message.message?.content;- if (Array.isArray(content)) {- for (const block of content) {- if (block.type === 'text' && block.text) {- send({ type: 'text', content: block.text });- }- if (block.type === 'tool_use') {- send({ type: 'tool_call', tool: block.name, input: block.input });- // Tool names are namespaced: "mcp__ontology-engine__onto_load"- // Check if the name ends with any known mutation tool- if ([...MUTATION_TOOLS].some(t => block.name === t || block.name.endsWith(`__${t}`))) {- mutated = true;- }+ switch (message.type) {+ case 'assistant': {+ const content = message.message?.content;+ if (Array.isArray(content)) {+ for (const block of content) {+ if (block.type === 'text' && block.text) {+ send({ type: 'text', content: block.text });+ }+ if (block.type === 'tool_use') {+ send({ type: 'tool_call', tool: block.name, input: block.input });+ if ([...MUTATION_TOOLS].some(t => block.name === t || block.name.endsWith(`__${t}`))) {+ mutated = true;}}}- break;}-- case 'result': {- // Final result message- if (message.subtype === 'success') {- // Success - text already sent via assistant messages- } else {- // Error subtypes: error_during_execution, error_max_turns, etc.- const errors = 'errors' in message ? (message as { errors?: string[] }).errors : [];- send({ type: 'error', error: (errors && errors.length > 0) ? errors.join('; ') : `Agent error: ${message.subtype}` });- }- break;- }-- case 'system': {- // System messages (compact boundaries, etc.) - ignore- break;+ break;+ }+ case 'result': {+ if (message.subtype !== 'success') {+ const errors = 'errors' in message ? (message as { errors?: string[] }).errors : [];+ send({ type: 'error', error: (errors && errors.length > 0) ? errors.join('; ') : `Agent error: ${message.subtype}` });}+ break;}+ case 'system': break;}+ }++ return mutated;+}++// --- Build request detection ---++function isBuildRequest(msg: string): boolean {+ const lower = msg.toLowerCase();+ return (lower.includes('build') || lower.includes('create') || lower.includes('make') || lower.includes('generate'))+ && (lower.includes('ontology') || lower.includes('about'));+}- send({ type: 'done', mutated });+function extractDomain(msg: string): string {+ const patterns = [+ /(?:about|for|on|of)\s+(.+)/i,+ /(?:build|create|make|generate)\s+(?:a\s+|an\s+|the\s+)?(?:\w+\s+)?(?:ontology\s+)?(?:about|for|on|of)\s+(.+)/i,+ ];+ for (const p of patterns) {+ const m = msg.match(p);+ if (m) {+ const match = m[2] || m[1];+ if (match) return match.trim().replace(/[.!?]+$/, '');+ }+ }+ return msg.replace(/^(build|create|make|generate)\s+(an?\s+)?ontology\s*/i, '').trim() || msg;+}++// --- Multi-step build within ONE session ---++async function handleBuild(domain: string): Promise<void> {+ const ns = domain.toLowerCase().replace(/[^a-z0-9]+/g, '-');++ // Step 1: Clear + load classes+ send({ type: 'text', content: `**Building ontology: ${domain}**\n\n---\n**Step 1/4:** Classes hierarchy...` });+ await runTurn(+ `Build an ontology about "${domain}". Use namespace @prefix : <http://example.org/${ns}#> .++Step 1: Call onto_clear. Then call onto_load with Turtle containing:+- 80-150 owl:Class declarations organised in a subClassOf hierarchy 5-7 levels deep+- A root class, 5-8 major branches, each with 3-6 sub-branches, each with 2-5 leaves+- Enumerate ALL real-world subtypes exhaustively+- Every class MUST have rdfs:label and rdfs:comment++Call onto_stats after loading to verify. Do NOT call onto_save yet — more content coming.`+ );++ // Step 2: Properties (SAME session — agent has context)+ send({ type: 'text', content: `\n---\n**Step 2/4:** Properties...` });+ await runTurn(+ `Now add properties to the ontology. Call onto_load with Turtle using the SAME namespace as before containing:++- 25-40 owl:ObjectProperty declarations, each with rdfs:domain, rdfs:range, rdfs:label, rdfs:comment+- Build rdfs:subPropertyOf hierarchies (e.g., hasParticipant > hasAgent > hasDriver)+- Add owl:inverseOf pairs for bidirectional relationships+- Mark owl:TransitiveProperty (isPartOf), owl:SymmetricProperty (isRelatedTo), owl:FunctionalProperty where appropriate+- 15-20 owl:DatatypeProperty declarations with rdfs:domain, rdfs:range (xsd types), rdfs:label, rdfs:comment++Call onto_stats after loading. Do NOT call onto_save yet.`+ );++ // Step 3: Axioms + individuals (SAME session)+ send({ type: 'text', content: `\n---\n**Step 3/4:** Axioms + individuals...` });+ await runTurn(+ `Now add axioms and individuals. Call onto_load with Turtle using the SAME namespace containing:++- owl:disjointWith between ALL sibling classes that cannot overlap+- 15-20 owl:NamedIndividual instances — real-world examples with rdf:type and property values++Call onto_stats after loading. Do NOT call onto_save yet.`+ );++ // Step 4: Reason + save (SAME session)+ send({ type: 'text', content: `\n---\n**Step 4/4:** Reasoning + save...` });+ await runTurn(+ `Final step. Run:+1. onto_reason with profile "rdfs"+2. onto_stats — report the final counts+3. onto_save with path "~/.open-ontologies/studio-live.ttl"++Report the final ontology statistics.`+ );++ send({ type: 'text', content: `\n---\n**Build complete.** Refresh the tree view to see the full graph.` });+}++// --- Handle a chat message ---++async function handleMessage(userMessage: string): Promise<void> {+ try {+ if (isBuildRequest(userMessage)) {+ const domain = extractDomain(userMessage);+ // Fresh session for each new build+ sessionId = undefined;+ await handleBuild(domain);+ send({ type: 'done', mutated: true });+ } else {+ const mutated = await runTurn(userMessage);+ send({ type: 'done', mutated });+ }} catch (e) {send({ type: 'error', error: String(e) });- send({ type: 'done', mutated });+ send({ type: 'done', mutated: false });}}-// --- stdin/stdout Protocol ---+// --- Main ---async function main(): Promise<void> {- // Wait for the ontology engine to be readyconst engineReady = await waitForEngine();if (!engineReady) {send({ type: 'error', error: 'Engine not reachable after 15 retries' });}-send({ type: 'ready' });const rl = readline.createInterface({ input: process.stdin });-rl.on('line', async (line) => {try {const msg = JSON.parse(line);diff --git a/studio/src/components/ChatPanel.tsx b/studio/src/components/ChatPanel.tsxindex 345d54ab..6e67905a 100644--- a/studio/src/components/ChatPanel.tsx+++ b/studio/src/components/ChatPanel.tsx@@ -3,8 +3,8 @@ import ReactMarkdown from 'react-markdown';import { useChat, ChatMessage } from '../hooks/useChat';const SLASH_COMMANDS = [- { cmd: '/build', description: 'Build a new ontology', prompt: 'Build me an ontology about ' },- { cmd: '/expand', description: 'Expand current ontology', prompt: 'Expand the current ontology with ' },+ { cmd: '/build', description: 'Build a new ontology', prompt: 'Build an ontology about ' },+ { cmd: '/expand', description: 'Expand current ontology', prompt: 'Expand the current ontology with more detail about ' },{ cmd: '/validate', description: 'Run full validation', prompt: 'Run onto_validate and onto_lint on the current ontology and report all issues' },{ cmd: '/reason', description: 'Run OWL reasoning', prompt: 'Run onto_reason with profile owl-rl on the current ontology' },{ cmd: '/enforce', description: 'Check design patterns', prompt: 'Run onto_enforce with the generic rule pack' },@@ -14,8 +14,8 @@ const SLASH_COMMANDS = [];const STARTER_CHIPS = [- { label: 'Build an ontology', prompt: 'Build me an ontology about ' },- { label: 'Expand current', prompt: 'Expand the current ontology with ' },+ { label: 'Build an ontology', prompt: 'Build an ontology about ' },+ { label: 'Expand current', prompt: 'Expand the current ontology with more detail about ' },{ label: 'Validate', prompt: 'Validate the current ontology and report any issues' },{ label: 'Run reasoning', prompt: 'Run OWL reasoning on the current ontology' },{ label: 'Explain structure', prompt: 'Explain the structure of the current ontology' },diff --git a/studio/src/components/GraphCanvas.tsx b/studio/src/components/GraphCanvas.tsxindex 6f65fc61..ba6ba50f 100644--- a/studio/src/components/GraphCanvas.tsx+++ b/studio/src/components/GraphCanvas.tsx@@ -181,6 +181,23 @@ export function GraphCanvas({ onNodeSelect, dagMode }: GraphCanvasProps) {}}+ // 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) {@@ -199,7 +216,9 @@ export function GraphCanvas({ onNodeSelect, dagMode }: GraphCanvasProps) {.nodeLabel('label').nodeColor((node: object) => {const n = node as GraphNode;- return n.id === selectedId ? '#f9e2af' : '#89b4fa';+ if (n.id === selectedId) return '#f9e2af';+ if (n.id === '__root__') return '#f38ba8';+ return '#89b4fa';}).nodeOpacity(0.95).nodeResolution(16)@@ -227,9 +246,10 @@ export function GraphCanvas({ onNodeSelect, dagMode }: GraphCanvasProps) {const group = new THREE.Group();// Sphere+ const isRoot = n.id === '__root__';const sphere = new THREE.Mesh(- new THREE.SphereGeometry(5, 16, 16),- new THREE.MeshLambertMaterial({ color: n.id === selectedId ? 0xf9e2af : 0x89b4fa })+ new THREE.SphereGeometry(isRoot ? 8 : 5, 16, 16),+ new THREE.MeshLambertMaterial({ color: n.id === selectedId ? 0xf9e2af : isRoot ? 0xf38ba8 : 0x89b4fa }));group.add(sphere);@@ -252,6 +272,7 @@ export function GraphCanvas({ onNodeSelect, dagMode }: GraphCanvasProps) {}).onNodeClick((node: object) => {const n = node as GraphNode;+ if (n.id === '__root__') return; // virtual hub not selectablesetSelectedId(n.id);onNodeSelect({ id: n.id, label: n.label, uri: n.uri });// Fly camera toward nodediff --git a/studio/src/components/Layout.tsx b/studio/src/components/Layout.tsxindex b6113ac2..aae4644b 100644--- a/studio/src/components/Layout.tsx+++ b/studio/src/components/Layout.tsx@@ -7,13 +7,13 @@ import { PropertyInspector } from './PropertyInspector';import { LineagePanel } from './LineagePanel';import * as mcp from '../lib/mcp-client';-type ViewMode = '3d' | 'dag' | 'tree';+type ViewMode = '3d' | 'tree';export function Layout() {const [showChat, setShowChat] = useState(true);const [showInspector, setShowInspector] = useState(false);const [showLineage, setShowLineage] = useState(false);- const [viewMode, setViewMode] = useState<ViewMode>('3d');+ const [viewMode, setViewMode] = useState<ViewMode>('tree');const [selectedNode, setSelectedNode] = useState<{ id: string; label: string; uri: string } | null>(null);const [projectName, setProjectName] = useState('studio-live');const [savingAs, setSavingAs] = useState(false);@@ -122,12 +122,12 @@ export function Layout() {<div className="ml-auto flex gap-2">{/* View mode toggle */}- {(['3d', 'dag', 'tree'] as ViewMode[]).map(mode => (+ {(['tree', '3d'] as ViewMode[]).map(mode => (<button key={mode} onClick={() => setViewMode(mode)}className="text-xs px-2 py-1 rounded"style={{ background: viewMode === mode ? 'var(--accent)' : 'var(--bg-panel)',color: viewMode === mode ? 'var(--bg-primary)' : 'var(--text-secondary)' }}>- {mode === '3d' ? '3D' : mode === 'dag' ? 'DAG' : 'Tree'}+ {mode === '3d' ? '3D' : 'Tree'}</button>))}<div className="w-px mx-1" style={{ background: 'var(--border)' }} />@@ -159,7 +159,7 @@ export function Layout() {{viewMode === 'tree' ? (<TreeView onNodeSelect={setSelectedNode} />) : (- <GraphCanvas onNodeSelect={setSelectedNode} dagMode={viewMode === 'dag'} />+ <GraphCanvas onNodeSelect={setSelectedNode} />)}</div>diff --git a/studio/src/components/TreeView.tsx b/studio/src/components/TreeView.tsxindex bfd0bdd1..01cd7b4e 100644--- a/studio/src/components/TreeView.tsx+++ b/studio/src/components/TreeView.tsx@@ -1,18 +1,34 @@-import { useRef, useEffect, useCallback } from 'react';-import cytoscape from 'cytoscape';-// @ts-expect-error dagre layout has no types-import dagre from 'cytoscape-dagre';+import { useRef, useEffect, useCallback, useState } from 'react';+import * as d3 from 'd3';import * as mcp from '../lib/mcp-client';import { useEngine } from '../hooks/useEngine';-cytoscape.use(dagre);+interface TreeViewProps {+ onNodeSelect: (node: { id: string; label: string; uri: string } | null) => void;+}interface SparqlBinding {[key: string]: { type: string; value: string };}-interface TreeViewProps {- onNodeSelect: (node: { id: string; label: string; uri: string } | null) => void;+type NodeType = 'Class' | 'ObjectProperty' | 'DatatypeProperty' | 'AnnotationProperty' | 'Individual' | 'Restriction' | 'Ontology';++interface OntologyNode {+ id: string;+ label: string;+ uri: string;+ nodeType: NodeType;+ children: OntologyNode[];+ _childCount?: number;+ propertyCount?: number; // how many properties reference this class+ connectionCount?: number; // total edges (for sizing)+}++interface CrossLink {+ sourceId: string;+ targetId: string;+ label: string;+ linkType: 'domain' | 'range' | 'equivalentClass' | 'disjointWith' | 'restriction';}function parseSparqlResults(text: string): SparqlBinding[] {@@ -45,21 +61,39 @@ function shortUri(uri: string): string {return uri;}-// Color palette for depth levels — matches brain-in-the-fish style-const DEPTH_COLORS = [- '#f38ba8', // pink — root- '#fab387', // peach — level 1- '#f9e2af', // yellow — level 2- '#a6e3a1', // green — level 3- '#89b4fa', // blue — level 4- '#cba6f7', // mauve — level 5- '#94e2d5', // teal — level 6+-];--function colorForDepth(depth: number): string {- return DEPTH_COLORS[Math.min(depth, DEPTH_COLORS.length - 1)];+// Node type colors (Catppuccin Mocha)+const NODE_TYPE_COLORS: Record<NodeType, string> = {+ Ontology: '#f38ba8', // pink+ Class: '#89b4fa', // blue+ ObjectProperty: '#a6e3a1', // green+ DatatypeProperty: '#f9e2af', // yellow+ AnnotationProperty: '#cba6f7', // mauve+ Individual: '#fab387', // peach+ Restriction: '#94e2d5', // teal+};++const NODE_TYPE_SIZES: Record<NodeType, number> = {+ Ontology: 14,+ Class: 8,+ ObjectProperty: 7,+ DatatypeProperty: 6,+ AnnotationProperty: 5,+ Individual: 6,+ Restriction: 5,+};++function getColor(type: NodeType): string {+ return NODE_TYPE_COLORS[type] ?? '#a6adc8';+}++function getSize(type: NodeType, connectionCount: number): number {+ const base = NODE_TYPE_SIZES[type] ?? 6;+ // Scale up for highly connected nodes+ return base + Math.min(connectionCount * 0.3, 6);}+// ── SPARQL Queries ──────────────────────────────────────────────+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 {@@ -68,7 +102,7 @@ SELECT ?c ?label WHERE {FILTER(!isBlank(?c))}`;-const EDGES_QUERY = `PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>+const SUBCLASS_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 .@@ -76,297 +110,795 @@ SELECT ?sub ?parent WHERE {FILTER(!isBlank(?sub) && !isBlank(?parent))}`;+const OBJ_PROPS_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>+PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>+PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>+SELECT ?p ?label ?domain ?range ?parent WHERE {+ { ?p a owl:ObjectProperty } UNION { ?p a rdf:Property }+ OPTIONAL { ?p rdfs:label ?label }+ OPTIONAL { ?p rdfs:domain ?domain . FILTER(!isBlank(?domain)) }+ OPTIONAL { ?p rdfs:range ?range . FILTER(!isBlank(?range)) }+ OPTIONAL { ?p rdfs:subPropertyOf ?parent . FILTER(!isBlank(?parent)) }+ FILTER(!isBlank(?p))+}`;++const DATA_PROPS_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>+PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>+SELECT ?p ?label ?domain ?parent WHERE {+ ?p a owl:DatatypeProperty .+ OPTIONAL { ?p rdfs:label ?label }+ OPTIONAL { ?p rdfs:domain ?domain . FILTER(!isBlank(?domain)) }+ OPTIONAL { ?p rdfs:subPropertyOf ?parent . FILTER(!isBlank(?parent)) }+ FILTER(!isBlank(?p))+}`;++const ANNOTATION_PROPS_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>+PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>+SELECT ?p ?label WHERE {+ ?p a owl:AnnotationProperty .+ OPTIONAL { ?p rdfs:label ?label }+ FILTER(!isBlank(?p))+}`;++const INDIVIDUALS_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>+PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>+PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>+SELECT ?ind ?label ?type WHERE {+ ?ind a ?type .+ ?type a owl:Class .+ OPTIONAL { ?ind rdfs:label ?label }+ FILTER(!isBlank(?ind) && ?type != owl:Class && ?type != rdfs:Class && ?type != owl:ObjectProperty && ?type != owl:DatatypeProperty && ?type != owl:AnnotationProperty && ?type != owl:NamedIndividual)+} LIMIT 200`;++const EQUIV_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>+SELECT ?a ?b WHERE {+ ?a owl:equivalentClass ?b .+ FILTER(!isBlank(?a) && !isBlank(?b) && ?a != ?b)+}`;++const DISJOINT_QUERY = `PREFIX owl: <http://www.w3.org/2002/07/owl#>+SELECT ?a ?b WHERE {+ ?a owl:disjointWith ?b .+ FILTER(!isBlank(?a) && !isBlank(?b))+}`;++function countDescendants(node: OntologyNode): number {+ if (!node.children || node.children.length === 0) return 0;+ let count = node.children.length;+ for (const c of node.children) count += countDescendants(c);+ return count;+}+export function TreeView({ onNodeSelect }: TreeViewProps) {const containerRef = useRef<HTMLDivElement>(null);- const cyRef = useRef<cytoscape.Core | null>(null);+ const svgRef = useRef<SVGSVGElement | null>(null);+ const gRef = useRef<d3.Selection<SVGGElement, unknown, null, undefined> | null>(null);+ const zoomRef = useRef<d3.ZoomBehavior<SVGSVGElement, unknown> | null>(null);+ const treeDataRef = useRef<OntologyNode | null>(null);+ const crossLinksRef = useRef<CrossLink[]>([]);+ const collapsedRef = useRef<Set<string>>(new Set());+ const hiddenTypesRef = useRef<Set<NodeType>>(new Set());const { status, refreshStats } = useEngine();+ const [stats, setStats] = useState({ classes: 0, properties: 0, individuals: 0, depth: 0, crossLinks: 0 });+ const [hiddenTypes, setHiddenTypes] = useState<Set<NodeType>>(new Set());+ const [typeCounts, setTypeCounts] = useState<Map<NodeType, number>>(new Map());++ const filterTree = useCallback((node: OntologyNode): OntologyNode => {+ const copy = { ...node };+ if (collapsedRef.current.has(node.id)) {+ copy._childCount = countDescendants(node);+ copy.children = [];+ } else if (node.children) {+ copy.children = node.children+ .filter(c => !hiddenTypesRef.current.has(c.nodeType))+ .map(c => filterTree(c));+ }+ return copy;+ }, []);- const loadTree = useCallback(async () => {- const cy = cyRef.current;- if (!cy) return;+ const renderTree = useCallback(() => {+ const svg = svgRef.current;+ const g = gRef.current;+ const treeData = treeDataRef.current;+ if (!svg || !g || !treeData) return;++ g.selectAll('*').remove();++ const filteredData = filterTree(treeData);+ const hierarchy = d3.hierarchy(filteredData, d => d.children);++ const leafCount = hierarchy.leaves().length;+ const rect = containerRef.current?.getBoundingClientRect();+ const viewW = rect?.width ?? 800;+ const viewH = rect?.height ?? 600;++ const treeHeight = Math.max(viewH - 80, leafCount * 24);+ const treeWidth = Math.max(viewW - 300, hierarchy.height * 200);++ const treeLayout = d3.tree<OntologyNode>()+ .size([treeHeight, treeWidth])+ .separation((a, b) => (a.parent === b.parent ? 1 : 1.4));+ treeLayout(hierarchy);++ const xOff = 180;+ const yOff = 40;++ // Build node position map for cross-links+ const nodePositions = new Map<string, { x: number; y: number }>();+ hierarchy.descendants().forEach(d => {+ nodePositions.set(d.data.id, { x: (d.y ?? 0) + xOff, y: (d.x ?? 0) + yOff });+ });++ // Draw tree links+ g.selectAll('.tree-link')+ .data(hierarchy.links())+ .enter().append('path')+ .attr('class', 'tree-link')+ .attr('fill', 'none')+ .attr('stroke', d => getColor(d.target.data.nodeType))+ .attr('stroke-opacity', 0.25)+ .attr('stroke-width', 1.5)+ .attr('d', d3.linkHorizontal<d3.HierarchyPointLink<OntologyNode>, d3.HierarchyPointNode<OntologyNode>>()+ .x(d => d.y + xOff)+ .y(d => d.x + yOff) as unknown as string);++ // Draw cross-links (domain→range, equivalentClass, disjointWith)+ const visibleCrossLinks = crossLinksRef.current.filter(cl => {+ const s = nodePositions.get(cl.sourceId);+ const t = nodePositions.get(cl.targetId);+ return s && t;+ });++ const crossLinkColor: Record<string, string> = {+ domain: '#a6e3a199',+ range: '#f9e2af99',+ equivalentClass: '#cba6f799',+ disjointWith: '#f38ba866',+ restriction: '#94e2d566',+ };++ g.selectAll('.cross-link')+ .data(visibleCrossLinks)+ .enter().append('path')+ .attr('class', 'cross-link')+ .attr('fill', 'none')+ .attr('stroke', d => crossLinkColor[d.linkType] ?? '#585b7044')+ .attr('stroke-opacity', 0.2)+ .attr('stroke-width', 1)+ .attr('stroke-dasharray', d => d.linkType === 'disjointWith' ? '2,4' : '4,4')+ .attr('d', d => {+ const s = nodePositions.get(d.sourceId)!;+ const t = nodePositions.get(d.targetId)!;+ const mx = (s.x + t.x) / 2;+ return `M${s.x},${s.y}C${mx},${s.y},${mx},${t.y},${t.x},${t.y}`;+ });++ // Draw nodes+ const nodes = g.selectAll('.tree-node')+ .data(hierarchy.descendants())+ .enter().append('g')+ .attr('class', d => {+ let cls = 'tree-node';+ if (collapsedRef.current.has(d.data.id)) cls += ' collapsed';+ return cls;+ })+ .attr('transform', d => `translate(${(d.y ?? 0) + xOff},${(d.x ?? 0) + yOff})`)+ .style('cursor', 'pointer')+ .on('click', (event: MouseEvent, d) => {+ event.stopPropagation();+ if (event.shiftKey || event.metaKey) {+ toggleCollapse(d.data.id);+ } else {+ if (d.data.id === '__ontology__') return;+ onNodeSelect({ id: d.data.id, label: d.data.label, uri: d.data.uri });+ }+ })+ .on('dblclick', (event: MouseEvent, d) => {+ event.stopPropagation();+ toggleCollapse(d.data.id);+ })+ .on('mouseover', function(_event: MouseEvent, d) {+ d3.select(this).select('circle')+ .attr('stroke', '#cdd6f4').attr('stroke-width', 3);++ // Highlight path to root+ const ancestors = new Set<string>();+ let current: d3.HierarchyNode<OntologyNode> | null = d;+ while (current) { ancestors.add(current.data.id); current = current.parent; }++ g.selectAll<SVGPathElement, d3.HierarchyPointLink<OntologyNode>>('.tree-link')+ .attr('stroke-opacity', l =>+ ancestors.has(l.source.data.id) && ancestors.has(l.target.data.id) ? 0.8 : 0.08+ )+ .attr('stroke-width', l =>+ ancestors.has(l.source.data.id) && ancestors.has(l.target.data.id) ? 2.5 : 1+ );++ // Highlight connected cross-links+ g.selectAll<SVGPathElement, CrossLink>('.cross-link')+ .attr('stroke-opacity', cl =>+ cl.sourceId === d.data.id || cl.targetId === d.data.id ? 0.6 : 0.05+ )+ .attr('stroke-width', cl =>+ cl.sourceId === d.data.id || cl.targetId === d.data.id ? 2 : 1+ );+ })+ .on('mouseout', function() {+ d3.select(this).select('circle')+ .attr('stroke', '#1e1e2e').attr('stroke-width', 2);+ g.selectAll('.tree-link').attr('stroke-opacity', 0.25).attr('stroke-width', 1.5);+ g.selectAll('.cross-link').attr('stroke-opacity', 0.2).attr('stroke-width', 1);+ });++ // Node circles — different shapes per type+ nodes.append('circle')+ .attr('r', d => getSize(d.data.nodeType, d.data.connectionCount ?? 0))+ .attr('fill', d => getColor(d.data.nodeType))+ .attr('stroke', '#1e1e2e')+ .attr('stroke-width', 2)+ .style('filter', 'drop-shadow(0 0 4px rgba(0,0,0,0.4))');++ // Property nodes get a diamond overlay+ nodes.filter(d => d.data.nodeType === 'ObjectProperty' || d.data.nodeType === 'DatatypeProperty')+ .append('rect')+ .attr('x', d => -getSize(d.data.nodeType, 0) * 0.5)+ .attr('y', d => -getSize(d.data.nodeType, 0) * 0.5)+ .attr('width', d => getSize(d.data.nodeType, 0))+ .attr('height', d => getSize(d.data.nodeType, 0))+ .attr('transform', 'rotate(45)')+ .attr('fill', 'none')+ .attr('stroke', d => getColor(d.data.nodeType))+ .attr('stroke-width', 1)+ .attr('stroke-opacity', 0.4)+ .style('pointer-events', 'none');++ // Collapse indicator+ nodes.filter(d => (d.data.children && d.data.children.length > 0) || (d.data._childCount != null && d.data._childCount > 0))+ .append('text')+ .attr('x', 0).attr('y', 1)+ .attr('text-anchor', 'middle')+ .attr('dominant-baseline', 'central')+ .style('font-size', d => `${getSize(d.data.nodeType, 0) * 1.1}px`)+ .style('fill', '#1e1e2e')+ .style('font-weight', '700')+ .style('pointer-events', 'none')+ .text(d => collapsedRef.current.has(d.data.id) ? '+' : '');++ // Collapsed child count+ nodes.filter(d => d.data._childCount != null && d.data._childCount > 0)+ .append('text')+ .attr('x', d => getSize(d.data.nodeType, 0) + 4)+ .attr('y', -8)+ .attr('text-anchor', 'start')+ .style('font-size', '9px')+ .style('fill', '#6c7086')+ .style('pointer-events', 'none')+ .text(d => `(${d.data._childCount})`);++ // Labels+ nodes.append('text')+ .attr('x', d => getSize(d.data.nodeType, d.data.connectionCount ?? 0) + 8)+ .attr('y', 4)+ .attr('text-anchor', 'start')+ .style('font-size', d => d.data.nodeType === 'Ontology' ? '14px' : d.depth <= 2 ? '12px' : '11px')+ .style('font-weight', d => d.data.children.length > 0 || d.data.nodeType === 'Ontology' ? '600' : '400')+ .style('fill', d => d.data.nodeType === 'Ontology' ? '#cdd6f4' : '#bac2de')+ .style('font-family', '-apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif')+ .style('pointer-events', 'none')+ .text(d => {+ const lbl = d.data.label || d.data.id;+ return lbl.length > 45 ? lbl.substring(0, 45) + '...' : lbl;+ });++ // Property count badge on classes+ nodes.filter(d => d.data.nodeType === 'Class' && d.data.propertyCount != null && d.data.propertyCount > 0)+ .append('text')+ .attr('x', d => {+ const lbl = d.data.label || d.data.id;+ const truncated = lbl.length > 45 ? lbl.substring(0, 45) + '...' : lbl;+ return getSize(d.data.nodeType, d.data.connectionCount ?? 0) + 8 + truncated.length * 6.5;+ })+ .attr('y', 4)+ .attr('text-anchor', 'start')+ .style('font-size', '9px')+ .style('fill', '#585b70')+ .style('pointer-events', 'none')+ .text(d => `[${d.data.propertyCount}p]`);++ }, [filterTree, onNodeSelect]);++ const toggleCollapse = useCallback((id: string) => {+ if (collapsedRef.current.has(id)) collapsedRef.current.delete(id);+ else collapsedRef.current.add(id);+ renderTree();+ }, [renderTree]);++ const fitGraph = useCallback(() => {+ const svg = svgRef.current;+ const g = gRef.current;+ if (!svg || !g) return;+ const gNode = g.node();+ if (!gNode) return;+ const bbox = gNode.getBBox();+ if (bbox.width === 0 || bbox.height === 0) return;++ const rect = containerRef.current?.getBoundingClientRect();+ const w = rect?.width ?? 800;+ const h = rect?.height ?? 600;++ const pad = 60;+ const scale = Math.min(w / (bbox.width + pad * 2), h / (bbox.height + pad * 2), 1.5);+ const transform = d3.zoomIdentity+ .translate(w / 2, h / 2)+ .scale(scale)+ .translate(-(bbox.x + bbox.width / 2), -(bbox.y + bbox.height / 2));++ if (zoomRef.current) {+ d3.select(svg).transition().duration(500).call(zoomRef.current.transform, transform);+ }+ }, []);++ // Load full ontology from SPARQL+ const loadTree = useCallback(async () => {try {- const [classesText, edgesText] = await Promise.all([+ const [classesText, subclassText, objPropsText, dataPropsText, annotPropsText, individualsText, equivText, disjointText] = await Promise.all([mcp.sparqlQuery(CLASSES_QUERY),- mcp.sparqlQuery(EDGES_QUERY),+ mcp.sparqlQuery(SUBCLASS_QUERY),+ mcp.sparqlQuery(OBJ_PROPS_QUERY),+ mcp.sparqlQuery(DATA_PROPS_QUERY),+ mcp.sparqlQuery(ANNOTATION_PROPS_QUERY),+ mcp.sparqlQuery(INDIVIDUALS_QUERY),+ mcp.sparqlQuery(EQUIV_QUERY),+ mcp.sparqlQuery(DISJOINT_QUERY),]);const classBindings = parseSparqlResults(classesText);- const edgeBindings = parseSparqlResults(edgesText);-- const nodeIds = new Set<string>();- const nodeData = new Map<string, { label: string; uri: string }>();- const childToParents = new Map<string, Set<string>>();+ const subclassBindings = parseSparqlResults(subclassText);+ const objPropBindings = parseSparqlResults(objPropsText);+ const dataPropBindings = parseSparqlResults(dataPropsText);+ const annotPropBindings = parseSparqlResults(annotPropsText);+ const individualBindings = parseSparqlResults(individualsText);+ const equivBindings = parseSparqlResults(equivText);+ const disjointBindings = parseSparqlResults(disjointText);++ // ── Build node registry ────────────────────────────────────+ const allNodes = new Map<string, { label: string; uri: string; nodeType: NodeType; connections: number; propertyCount: number }>();+ const parentToChildren = new Map<string, Set<string>>();const hasParent = new Set<string>();+ const crossLinks: CrossLink[] = [];++ // Track property counts per class+ const classPropertyCount = new Map<string, number>();+ // Classesfor (const b of classBindings) {const uri = b.c?.value;if (!uri) continue;const id = shortUri(uri);- if (!nodeIds.has(id)) {- nodeIds.add(id);- nodeData.set(id, { label: b.label?.value || id, uri });+ if (!allNodes.has(id)) {+ allNodes.set(id, { label: b.label?.value || id, uri, nodeType: 'Class', connections: 0, propertyCount: 0 });}}- for (const b of edgeBindings) {+ // SubClass edges (tree structure)+ for (const b of subclassBindings) {const subUri = b.sub?.value;const parentUri = b.parent?.value;if (!subUri || !parentUri) continue;const sid = shortUri(subUri);const pid = shortUri(parentUri);- if (!nodeIds.has(pid)) {- nodeIds.add(pid);- nodeData.set(pid, { label: pid, uri: parentUri });+ if (!allNodes.has(pid)) {+ allNodes.set(pid, { label: pid, uri: parentUri, nodeType: 'Class', connections: 0, propertyCount: 0 });}- if (!childToParents.has(sid)) childToParents.set(sid, new Set());- childToParents.get(sid)!.add(pid);+ if (!parentToChildren.has(pid)) parentToChildren.set(pid, new Set());+ parentToChildren.get(pid)!.add(sid);hasParent.add(sid);++ const pn = allNodes.get(pid)!; pn.connections++;+ const sn = allNodes.get(sid)!; sn.connections++;}- // Find root nodes (no parent) and connect orphans to a virtual root- const roots = new Set<string>();- for (const id of nodeIds) {- if (!hasParent.has(id)) roots.add(id);+ // Object properties — add to tree under a "Properties" branch, create cross-links for domain/range+ const propParentToChildren = new Map<string, Set<string>>();+ const propHasParent = new Set<string>();+ for (const b of objPropBindings) {+ const uri = b.p?.value;+ if (!uri) continue;+ const id = shortUri(uri);+ if (!allNodes.has(id)) {+ allNodes.set(id, { label: b.label?.value || id, uri, nodeType: 'ObjectProperty', connections: 0, propertyCount: 0 });+ }+ // Property hierarchy+ if (b.parent?.value) {+ const pid = shortUri(b.parent.value);+ if (!allNodes.has(pid)) {+ allNodes.set(pid, { label: pid, uri: b.parent.value, nodeType: 'ObjectProperty', connections: 0, propertyCount: 0 });+ }+ if (!propParentToChildren.has(pid)) propParentToChildren.set(pid, new Set());+ propParentToChildren.get(pid)!.add(id);+ propHasParent.add(id);+ }+ // Domain cross-link+ if (b.domain?.value) {+ const did = shortUri(b.domain.value);+ crossLinks.push({ sourceId: id, targetId: did, label: 'domain', linkType: 'domain' });+ const dn = allNodes.get(did);+ if (dn) { dn.connections++; dn.propertyCount++; }+ const pn = allNodes.get(id)!; pn.connections++;+ classPropertyCount.set(did, (classPropertyCount.get(did) ?? 0) + 1);+ }+ // Range cross-link+ if (b.range?.value) {+ const rid = shortUri(b.range.value);+ crossLinks.push({ sourceId: id, targetId: rid, label: 'range', linkType: 'range' });+ const rn = allNodes.get(rid);+ if (rn) rn.connections++;+ const pn = allNodes.get(id)!; pn.connections++;+ }}- // Compute depth for each node (BFS from roots)- const depth = new Map<string, number>();- const parentToChildren = new Map<string, Set<string>>();- for (const [child, parents] of childToParents) {- for (const parent of parents) {- if (!parentToChildren.has(parent)) parentToChildren.set(parent, new Set());- parentToChildren.get(parent)!.add(child);+ // Datatype properties+ for (const b of dataPropBindings) {+ const uri = b.p?.value;+ if (!uri) continue;+ const id = shortUri(uri);+ if (!allNodes.has(id)) {+ allNodes.set(id, { label: b.label?.value || id, uri, nodeType: 'DatatypeProperty', connections: 0, propertyCount: 0 });+ }+ if (b.parent?.value) {+ const pid = shortUri(b.parent.value);+ if (!propParentToChildren.has(pid)) propParentToChildren.set(pid, new Set());+ propParentToChildren.get(pid)!.add(id);+ propHasParent.add(id);+ }+ if (b.domain?.value) {+ const did = shortUri(b.domain.value);+ crossLinks.push({ sourceId: id, targetId: did, label: 'domain', linkType: 'domain' });+ classPropertyCount.set(did, (classPropertyCount.get(did) ?? 0) + 1);}}- // BFS- const queue: string[] = [];- for (const r of roots) {- depth.set(r, 0);- queue.push(r);+ // Annotation properties+ for (const b of annotPropBindings) {+ const uri = b.p?.value;+ if (!uri) continue;+ const id = shortUri(uri);+ if (!allNodes.has(id)) {+ allNodes.set(id, { label: b.label?.value || id, uri, nodeType: 'AnnotationProperty', connections: 0, propertyCount: 0 });+ }}- while (queue.length > 0) {- const node = queue.shift()!;- const d = depth.get(node) ?? 0;- const children = parentToChildren.get(node);- if (children) {- for (const child of children) {- if (!depth.has(child)) {- depth.set(child, d + 1);- queue.push(child);- }- }++ // Individuals+ const individualsByClass = new Map<string, string[]>();+ for (const b of individualBindings) {+ const uri = b.ind?.value;+ const typeUri = b.type?.value;+ if (!uri || !typeUri) continue;+ const id = shortUri(uri);+ const typeId = shortUri(typeUri);+ if (!allNodes.has(id)) {+ allNodes.set(id, { label: b.label?.value || id, uri, nodeType: 'Individual', connections: 0, propertyCount: 0 });}+ if (!individualsByClass.has(typeId)) individualsByClass.set(typeId, []);+ individualsByClass.get(typeId)!.push(id);}- // Build elements- const elements: cytoscape.ElementDefinition[] = [];+ // Equivalent class cross-links+ for (const b of equivBindings) {+ const a = b.a?.value;+ const bv = b.b?.value;+ if (!a || !bv) continue;+ crossLinks.push({ sourceId: shortUri(a), targetId: shortUri(bv), label: 'equivalentClass', linkType: 'equivalentClass' });+ }- // Add virtual root if multiple roots exist- if (roots.size > 1) {- elements.push({- data: { id: '__root__', label: 'Ontology', uri: '', depth: 0 },- });- for (const r of roots) {- elements.push({- data: { id: `__root__->${r}`, source: '__root__', target: r },- });- depth.set(r, 1);+ // Disjoint cross-links+ for (const b of disjointBindings) {+ const a = b.a?.value;+ const bv = b.b?.value;+ if (!a || !bv) continue;+ crossLinks.push({ sourceId: shortUri(a), targetId: shortUri(bv), label: 'disjointWith', linkType: 'disjointWith' });+ }++ // Set property counts on nodes+ for (const [id, count] of classPropertyCount) {+ const node = allNodes.get(id);+ if (node) node.propertyCount = count;+ }++ // ── Build tree hierarchy ───────────────────────────────────+ const visited = new Set<string>();++ function buildClassNode(id: string): OntologyNode {+ visited.add(id);+ const data = allNodes.get(id)!;+ const childIds = parentToChildren.get(id) ?? new Set();+ const children: OntologyNode[] = [];+ for (const cid of childIds) {+ if (!visited.has(cid) && allNodes.has(cid)) {+ children.push(buildClassNode(cid));+ }}- // Recompute depths from virtual root- const q2: string[] = [...roots];- while (q2.length > 0) {- const node = q2.shift()!;- const d = depth.get(node) ?? 1;- const children = parentToChildren.get(node);- if (children) {- for (const child of children) {- depth.set(child, d + 1);- q2.push(child);- }+ // Add individuals as leaf children+ const inds = individualsByClass.get(id) ?? [];+ for (const iid of inds) {+ if (!visited.has(iid) && allNodes.has(iid)) {+ visited.add(iid);+ const idata = allNodes.get(iid)!;+ children.push({ id: iid, label: idata.label, uri: idata.uri, nodeType: 'Individual', children: [], connectionCount: idata.connections, propertyCount: 0 });}}+ children.sort((a, b) => a.label.localeCompare(b.label));+ return { id, label: data.label, uri: data.uri, nodeType: data.nodeType, children, connectionCount: data.connections, propertyCount: data.propertyCount };}- for (const id of nodeIds) {- const data = nodeData.get(id);- if (!data) continue;- const d = depth.get(id) ?? 0;- elements.push({- data: { id, label: data.label, uri: data.uri, depth: d, color: colorForDepth(d) },- });+ function buildPropNode(id: string): OntologyNode {+ visited.add(id);+ const data = allNodes.get(id)!;+ const childIds = propParentToChildren.get(id) ?? new Set();+ const children: OntologyNode[] = [];+ for (const cid of childIds) {+ if (!visited.has(cid) && allNodes.has(cid)) {+ children.push(buildPropNode(cid));+ }+ }+ children.sort((a, b) => a.label.localeCompare(b.label));+ return { id, label: data.label, uri: data.uri, nodeType: data.nodeType, children, connectionCount: data.connections, propertyCount: 0 };}- for (const [child, parents] of childToParents) {- for (const parent of parents) {- if (nodeIds.has(child) && nodeIds.has(parent)) {- elements.push({- data: { id: `${parent}->${child}`, source: parent, target: child },- });- }+ // Class roots+ const classRoots: string[] = [];+ for (const [id, data] of allNodes) {+ if (data.nodeType === 'Class' && !hasParent.has(id)) classRoots.push(id);+ }+ classRoots.sort((a, b) => (allNodes.get(a)!.label).localeCompare(allNodes.get(b)!.label));+ const classBranches = classRoots.map(id => buildClassNode(id));++ // Orphan classes+ for (const [id, data] of allNodes) {+ if (data.nodeType === 'Class' && !visited.has(id)) {+ classBranches.push({ id, label: data.label, uri: data.uri, nodeType: 'Class', children: [], connectionCount: data.connections, propertyCount: data.propertyCount });+ visited.add(id);+ }+ }++ // Property roots+ const propRoots: string[] = [];+ for (const [id, data] of allNodes) {+ if ((data.nodeType === 'ObjectProperty' || data.nodeType === 'DatatypeProperty') && !propHasParent.has(id) && !visited.has(id)) {+ propRoots.push(id);+ }+ }+ propRoots.sort((a, b) => (allNodes.get(a)!.label).localeCompare(allNodes.get(b)!.label));+ const propBranches = propRoots.map(id => buildPropNode(id));++ // Orphan properties+ for (const [id, data] of allNodes) {+ if ((data.nodeType === 'ObjectProperty' || data.nodeType === 'DatatypeProperty') && !visited.has(id)) {+ propBranches.push({ id, label: data.label, uri: data.uri, nodeType: data.nodeType, children: [], connectionCount: data.connections, propertyCount: 0 });+ visited.add(id);}}- cy.elements().remove();- cy.add(elements);+ // Annotation properties+ const annotBranches: OntologyNode[] = [];+ for (const [id, data] of allNodes) {+ if (data.nodeType === 'AnnotationProperty' && !visited.has(id)) {+ visited.add(id);+ annotBranches.push({ id, label: data.label, uri: data.uri, nodeType: 'AnnotationProperty', children: [], connectionCount: 0, propertyCount: 0 });+ }+ }+ annotBranches.sort((a, b) => a.label.localeCompare(b.label));++ // Orphan individuals+ const orphanInds: OntologyNode[] = [];+ for (const [id, data] of allNodes) {+ if (data.nodeType === 'Individual' && !visited.has(id)) {+ visited.add(id);+ orphanInds.push({ id, label: data.label, uri: data.uri, nodeType: 'Individual', children: [], connectionCount: 0, propertyCount: 0 });+ }+ }- cy.layout({- name: 'dagre',- rankDir: 'LR',- nodeSep: 8,- rankSep: 120,- edgeSep: 4,- animate: false,- } as cytoscape.LayoutOptions).run();+ // ── Assemble root ──────────────────────────────────────────+ const rootChildren: OntologyNode[] = [];- cy.fit(undefined, 30);+ if (classBranches.length > 0) {+ rootChildren.push({+ id: '__classes__', label: `Classes (${classBranches.length})`, uri: '',+ nodeType: 'Class', children: classBranches, connectionCount: 0, propertyCount: 0,+ });+ }+ if (propBranches.length > 0) {+ rootChildren.push({+ id: '__properties__', label: `Properties (${propBranches.length})`, uri: '',+ nodeType: 'ObjectProperty', children: propBranches, connectionCount: 0, propertyCount: 0,+ });+ }+ if (annotBranches.length > 0) {+ rootChildren.push({+ id: '__annotations__', label: `Annotations (${annotBranches.length})`, uri: '',+ nodeType: 'AnnotationProperty', children: annotBranches, connectionCount: 0, propertyCount: 0,+ });+ }+ if (orphanInds.length > 0) {+ rootChildren.push({+ id: '__individuals__', label: `Individuals (${orphanInds.length})`, uri: '',+ nodeType: 'Individual', children: orphanInds, connectionCount: 0, propertyCount: 0,+ });+ }++ const root: OntologyNode = {+ id: '__ontology__', label: 'Ontology', uri: '',+ nodeType: 'Ontology', children: rootChildren, connectionCount: 0, propertyCount: 0,+ };++ // Compute stats+ let md = 0;+ function findMaxDepth(node: OntologyNode, d: number) {+ if (d > md) md = d;+ node.children.forEach(c => findMaxDepth(c, d + 1));+ }+ findMaxDepth(root, 0);+ countDescendants(root);++ // Count by type+ const tc = new Map<NodeType, number>();+ for (const data of allNodes.values()) {+ tc.set(data.nodeType, (tc.get(data.nodeType) ?? 0) + 1);+ }+ setTypeCounts(tc);++ const totalClasses = tc.get('Class') ?? 0;+ const totalProps = (tc.get('ObjectProperty') ?? 0) + (tc.get('DatatypeProperty') ?? 0) + (tc.get('AnnotationProperty') ?? 0);+ const totalInds = tc.get('Individual') ?? 0;++ setStats({ classes: totalClasses, properties: totalProps, individuals: totalInds, depth: md, crossLinks: crossLinks.length });+ treeDataRef.current = root;+ crossLinksRef.current = crossLinks;+ collapsedRef.current = new Set();+ renderTree();+ setTimeout(fitGraph, 300);refreshStats();} catch (e) {console.error('Failed to load tree:', e);}- }, [refreshStats]);-+ }, [renderTree, fitGraph, refreshStats]);++ const toggleTypeFilter = useCallback((type: NodeType) => {+ const next = new Set(hiddenTypesRef.current);+ if (next.has(type)) next.delete(type);+ else next.add(type);+ hiddenTypesRef.current = next;+ setHiddenTypes(new Set(next));+ renderTree();+ }, [renderTree]);++ // Initialize SVGuseEffect(() => {const el = containerRef.current;if (!el) return;-- const cy = cytoscape({- container: el,- style: [- {- selector: 'node',- style: {- 'background-color': 'data(color)' as unknown as string,- 'label': 'data(label)',- 'color': '#bac2de',- 'font-size': '9px',- 'font-family': '-apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif',- 'text-valign': 'center',- 'text-halign': 'right',- 'text-margin-x': 8,- 'width': 10,- 'height': 10,- 'border-width': 0,- 'text-max-width': '200px',- 'text-wrap': 'ellipsis',- },- },- {- selector: 'node[id = "__root__"]',- style: {- 'background-color': '#f38ba8',- 'width': 14,- 'height': 14,- 'font-size': '11px',- 'font-weight': 'bold' as unknown as number,- 'color': '#cdd6f4',- },- },- {- selector: 'node:selected',- style: {- 'background-color': '#f9e2af',- 'border-color': '#f9e2af',- 'border-width': 2,- 'width': 14,- 'height': 14,- 'color': '#cdd6f4',- 'font-weight': 'bold' as unknown as number,- },- },- {- selector: 'edge',- style: {- 'line-color': '#45475a',- 'target-arrow-color': '#45475a',- 'target-arrow-shape': 'triangle',- 'curve-style': 'unbundled-bezier',- 'control-point-distances': [20],- 'control-point-weights': [0.5],- 'width': 1,- 'arrow-scale': 0.6,- 'opacity': 0.5,- },- },- {- selector: 'edge[source = "__root__"]',- style: {- 'line-color': '#585b70',- 'target-arrow-color': '#585b70',- 'width': 1.5,- 'opacity': 0.7,- },- },- ],- layout: { name: 'preset' },- wheelSensitivity: 0.2,- minZoom: 0.1,- maxZoom: 4,- pixelRatio: 2,- });-- cy.on('tap', 'node', (evt) => {- const node = evt.target;- if (node.id() === '__root__') return;- onNodeSelect({- id: node.id(),- label: node.data('label'),- uri: node.data('uri'),- });- });-- cy.on('tap', (evt) => {- if (evt.target === cy) {- onNodeSelect(null);- }- });-- // Highlight path on hover- cy.on('mouseover', 'node', (evt) => {- const node = evt.target;- const ancestors = node.predecessors();- const descendants = node.successors();- cy.elements().style('opacity', 0.15);- node.style('opacity', 1);- ancestors.style('opacity', 0.8);- descendants.style('opacity', 0.8);+ const rect = el.getBoundingClientRect();++ const svg = d3.select(el)+ .append('svg')+ .attr('width', rect.width)+ .attr('height', rect.height)+ .style('background', '#1e1e2e')+ .style('display', 'block');++ const g = svg.append('g');++ const zoom = d3.zoom<SVGSVGElement, unknown>()+ .scaleExtent([0.02, 8])+ .on('zoom', (event) => g.attr('transform', event.transform.toString()));+ svg.call(zoom);+ svg.on('click', () => onNodeSelect(null));++ svgRef.current = svg.node();+ gRef.current = g;+ zoomRef.current = zoom;++ const ro = new ResizeObserver(() => {+ const r = el.getBoundingClientRect();+ svg.attr('width', r.width).attr('height', r.height);});+ ro.observe(el);- cy.on('mouseout', 'node', () => {- cy.elements().removeStyle('opacity');- });-- cyRef.current = cy;(window as unknown as Record<string, unknown>).__refreshGraph = loadTree;return () => {- cy.destroy();- cyRef.current = null;+ ro.disconnect(); svg.remove();+ svgRef.current = null; gRef.current = null; zoomRef.current = null;delete (window as unknown as Record<string, unknown>).__refreshGraph;};}, [onNodeSelect, loadTree]);+ // KeyboarduseEffect(() => {- if (status === 'connected') loadTree();- }, [status, loadTree]);+ const handler = (e: KeyboardEvent) => {+ const tag = (e.target as HTMLElement)?.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA') return;+ if (e.key === 'Escape') onNodeSelect(null);+ else if (e.key === 'f' || e.key === 'F') fitGraph();+ else if (e.key === 'r' || e.key === 'R') {+ if (svgRef.current && zoomRef.current) {+ d3.select(svgRef.current).transition().duration(500).call(zoomRef.current.transform, d3.zoomIdentity);+ }+ }+ };+ window.addEventListener('keydown', handler);+ return () => window.removeEventListener('keydown', handler);+ }, [onNodeSelect, fitGraph]);++ useEffect(() => { if (status === 'connected') loadTree(); }, [status, loadTree]);++ const typeOrder: NodeType[] = ['Class', 'ObjectProperty', 'DatatypeProperty', 'AnnotationProperty', 'Individual'];return (- <div className="absolute inset-0">- <div ref={containerRef} className="w-full h-full" style={{ background: '#1e1e2e' }} />- <div className="absolute top-3 left-3 flex gap-2 text-xs" style={{ color: 'var(--text-secondary)' }}>- {DEPTH_COLORS.map((color, i) => (- <span key={i} className="flex items-center gap-1">- <span className="inline-block w-2 h-2 rounded-full" style={{ background: color }} />- {i === 0 ? 'root' : `L${i}`}+ <div className="absolute inset-0" style={{ background: '#1e1e2e' }}>+ <div ref={containerRef} className="w-full h-full" />++ {/* Stats bar */}+ <div className="absolute top-3 left-3 flex items-center gap-2" style={{ zIndex: 10 }}>+ {[+ { label: 'classes', value: stats.classes, color: NODE_TYPE_COLORS.Class },+ { label: 'properties', value: stats.properties, color: NODE_TYPE_COLORS.ObjectProperty },+ { label: 'individuals', value: stats.individuals, color: NODE_TYPE_COLORS.Individual },+ { label: 'cross-links', value: stats.crossLinks, color: '#585b70' },+ { label: 'depth', value: stats.depth, color: '#cdd6f4' },+ ].map(s => (+ <span key={s.label} style={{+ background: '#181825', border: '1px solid #313244', borderRadius: 6,+ padding: '3px 10px', fontSize: 10, color: '#6c7086',+ display: 'flex', alignItems: 'center', gap: 4,+ }}>+ <span style={{ color: s.color, fontWeight: 600 }}>{s.value}</span> {s.label}</span>))}</div>- <div className="absolute bottom-4 right-4 text-xs" style={{ color: 'var(--text-secondary)' }}>- Scroll to zoom · Drag to pan · Hover to trace path · Click to inspect++ {/* Node type legend (clickable filters) */}+ <div className="absolute top-12 left-3 flex flex-col gap-1" style={{ zIndex: 10 }}>+ {typeOrder.filter(t => (typeCounts.get(t) ?? 0) > 0).map(type => (+ <button+ key={type}+ onClick={() => toggleTypeFilter(type)}+ style={{+ background: '#181825',+ border: '1px solid #313244',+ borderRadius: 6,+ padding: '4px 10px',+ fontSize: 11,+ color: hiddenTypes.has(type) ? '#45475a' : '#bac2de',+ display: 'flex', alignItems: 'center', gap: 8,+ cursor: 'pointer',+ textDecoration: hiddenTypes.has(type) ? 'line-through' : 'none',+ opacity: hiddenTypes.has(type) ? 0.5 : 1,+ textAlign: 'left',+ fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif',+ }}+ >+ <span style={{ width: 8, height: 8, borderRadius: '50%', background: getColor(type), display: 'inline-block', flexShrink: 0 }} />+ <span style={{ fontWeight: 600 }}>{type}</span>+ <span style={{ color: '#585b70', fontSize: 10 }}>({typeCounts.get(type) ?? 0})</span>+ </button>+ ))}+ </div>++ {/* Shortcuts */}+ <div className="absolute bottom-3 right-3" style={{ zIndex: 10 }}>+ <span style={{ background: '#181825', border: '1px solid #313244', borderRadius: 6, padding: '4px 10px', fontSize: 10, color: '#45475a' }}>+ Scroll zoom · Drag pan · Click inspect · Shift+click collapse · <b>F</b> fit · <b>R</b> reset · <b>Esc</b> deselect+ </span></div>++ {status !== 'connected' && (+ <div className="absolute inset-0 flex items-center justify-center" style={{ color: '#585b70', zIndex: 5 }}>+ {status === 'connecting' ? 'Connecting to engine...' : 'Engine not connected'}+ </div>+ )}</div>);}