Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(explorer): implement Phase 4 & 5 : Temporal Engine and Power-User Suite
Zohaib Hassnainc0f106dc1e22
diff --git a/semantica-explorer/package-lock.json b/semantica-explorer/package-lock.jsonindex 1a2b195e..78d4d658 100644--- a/semantica-explorer/package-lock.json+++ b/semantica-explorer/package-lock.json@@ -8,7 +8,9 @@"name": "semantica-explorer","version": "0.0.0","dependencies": {+ "@monaco-editor/react": "^4.7.0","@tanstack/react-query": "^5.95.2",+ "@xyflow/react": "^12.10.2","graphology": "^0.26.0","graphology-layout-forceatlas2": "^0.10.1","lucide-react": "^1.7.0",@@ -16,7 +18,9 @@"react-arborist": "^3.4.3","react-dom": "^19.2.4","react-dropzone": "^15.0.0",- "sigma": "^3.0.2"+ "sigma": "^3.0.2",+ "vis-data": "^8.0.3",+ "vis-timeline": "^8.5.0"},"devDependencies": {"@babel/core": "^7.29.0",@@ -68,7 +72,6 @@"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/code-frame": "^7.29.0","@babel/generator": "^7.29.0",@@ -287,13 +290,52 @@"node": ">=6.9.0"}},+ "node_modules/@egjs/hammerjs": {+ "version": "2.0.17",+ "resolved": "https://registry.npmjs.org/@egjs/hammerjs/-/hammerjs-2.0.17.tgz",+ "integrity": "sha512-XQsZgjm2EcVUiZQf11UBJQfmZeEmOW8DpI1gsFeln6w0ae0ii4dMQEQ0kjl6DspdWX1aGY1/loyXnP0JS06e/A==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@types/hammerjs": "^2.0.36"+ },+ "engines": {+ "node": ">=0.8.0"+ }+ },+ "node_modules/@emnapi/core": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz",+ "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.1",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz",+ "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },"node_modules/@emnapi/wasi-threads": {- "version": "1.2.0",- "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz",- "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==",+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",+ "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==","dev": true,"license": "MIT","optional": true,+ "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -557,6 +599,29 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@monaco-editor/loader": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.7.0.tgz",+ "integrity": "sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==",+ "license": "MIT",+ "dependencies": {+ "state-local": "^1.0.6"+ }+ },+ "node_modules/@monaco-editor/react": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.7.0.tgz",+ "integrity": "sha512-cyzXQCtO47ydzxpQtCGSQGOC8Gk3ZUeBXFAxD+CWXYFo5OqZyZUonFl0DwUlTyAfRHntBfw2p3w4s9R6oe1eCA==",+ "license": "MIT",+ "dependencies": {+ "@monaco-editor/loader": "^1.5.0"+ },+ "peerDependencies": {+ "monaco-editor": ">= 0.25.0 < 1",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/@napi-rs/wasm-runtime": {"version": "1.1.2","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.2.tgz",@@ -865,7 +930,6 @@"integrity": "sha512-q9pE8+47bQNHb5eWVcE6oXppA+JTSwvnrhH53m0ZuHuK5MLvwsLoWrWzBTFQqQ06BVxz1gp0HblLsch8o6pvZw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"picomatch": "^4.0.3"},@@ -980,6 +1044,55 @@"@babel/types": "^7.28.2"}},+ "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==",+ "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==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "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==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "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==",+ "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==",+ "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==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-interpolate": "*",+ "@types/d3-selection": "*"+ }+ },"node_modules/@types/estree": {"version": "1.0.8","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",@@ -987,6 +1100,13 @@"dev": true,"license": "MIT"},+ "node_modules/@types/hammerjs": {+ "version": "2.0.46",+ "resolved": "https://registry.npmjs.org/@types/hammerjs/-/hammerjs-2.0.46.tgz",+ "integrity": "sha512-ynRvcq6wvqexJ9brDMS4BnBLzmr0e14d6ZJTEShTBWKymQiHwlAyGu0ZPEFI2Fh1U53F7tN9ufClWM5KvqkKOw==",+ "license": "MIT",+ "peer": true+ },"node_modules/@types/json-schema": {"version": "7.0.15","resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",@@ -1000,7 +1120,6 @@"integrity": "sha512-GYDxsZi3ChgmckRT9HPU0WEhKLP08ev/Yfcq2AstjrDASOYCSXeyjDsHg4v5t4jOj7cyDX3vmprafKlWIG9MXQ==","devOptional": true,"license": "MIT",- "peer": true,"dependencies": {"undici-types": "~7.16.0"}@@ -1011,7 +1130,6 @@"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==","devOptional": true,"license": "MIT",- "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -1026,6 +1144,14 @@"@types/react": "^19.2.0"}},+ "node_modules/@types/trusted-types": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",+ "license": "MIT",+ "optional": true,+ "peer": true+ },"node_modules/@typescript-eslint/eslint-plugin": {"version": "8.57.2","resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.57.2.tgz",@@ -1071,7 +1197,6 @@"integrity": "sha512-30ScMRHIAD33JJQkgfGW1t8CURZtjc2JpTrq5n2HFhOefbAhb7ucc7xJwdWcrEtqUIYJ73Nybpsggii6GtAHjA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.57.2","@typescript-eslint/types": "8.57.2",@@ -1348,13 +1473,44 @@}}},+ "node_modules/@xyflow/react": {+ "version": "12.10.2",+ "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.10.2.tgz",+ "integrity": "sha512-CgIi6HwlcHXwlkTpr0fxLv/0sRVNZ8IdwKLzzeCscaYBwpvfcH1QFOCeaTCuEn1FQEs/B8CjnTSjhs8udgmBgQ==",+ "license": "MIT",+ "dependencies": {+ "@xyflow/system": "0.0.76",+ "classcat": "^5.0.3",+ "zustand": "^4.4.0"+ },+ "peerDependencies": {+ "react": ">=17",+ "react-dom": ">=17"+ }+ },+ "node_modules/@xyflow/system": {+ "version": "0.0.76",+ "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.76.tgz",+ "integrity": "sha512-hvwvnRS1B3REwVDlWexsq7YQaPZeG3/mKo1jv38UmnpWmxihp14bW6VtEOuHEwJX2FvzFw8k77LyKSk/wiZVNA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-drag": "^3.0.7",+ "@types/d3-interpolate": "^3.0.4",+ "@types/d3-selection": "^3.0.10",+ "@types/d3-transition": "^3.0.8",+ "@types/d3-zoom": "^3.0.8",+ "d3-drag": "^3.0.0",+ "d3-interpolate": "^3.0.1",+ "d3-selection": "^3.0.0",+ "d3-zoom": "^3.0.0"+ }+ },"node_modules/acorn": {"version": "8.16.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz","integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==","dev": true,"license": "MIT",- "peer": true,"bin": {"acorn": "bin/acorn"},@@ -1427,7 +1583,6 @@"integrity": "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/types": "^7.26.0"}@@ -1483,7 +1638,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -1546,6 +1700,12 @@"url": "https://github.com/chalk/chalk?sponsor=1"}},+ "node_modules/classcat": {+ "version": "5.0.5",+ "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",+ "license": "MIT"+ },"node_modules/color-convert": {"version": "2.0.1","resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",@@ -1566,6 +1726,23 @@"dev": true,"license": "MIT"},+ "node_modules/commander": {+ "version": "2.20.3",+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/component-emitter": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz",+ "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==",+ "license": "MIT",+ "peer": true,+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/concat-map": {"version": "0.0.1","resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",@@ -1595,6 +1772,13 @@"node": ">= 8"}},+ "node_modules/cssfilter": {+ "version": "0.0.10",+ "resolved": "https://registry.npmjs.org/cssfilter/-/cssfilter-0.0.10.tgz",+ "integrity": "sha512-FAaLDaplstoRsDR8XGYH51znUN0UY7nMc6Z9/fvE8EXGwvJE9hu7W2vHwx1+bd6gCYnln9nLbzxFTrcO9YQDZw==",+ "license": "MIT",+ "peer": true+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -1602,6 +1786,111 @@"devOptional": true,"license": "MIT"},+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "license": "ISC",+ "engines": {+ "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-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-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-selection": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "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/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1657,6 +1946,16 @@"@babel/runtime": "^7.9.2"}},+ "node_modules/dompurify": {+ "version": "3.2.7",+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.7.tgz",+ "integrity": "sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw==",+ "license": "(MPL-2.0 OR Apache-2.0)",+ "peer": true,+ "optionalDependencies": {+ "@types/trusted-types": "^2.0.7"+ }+ },"node_modules/electron-to-chromium": {"version": "1.5.328","resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.328.tgz",@@ -1693,7 +1992,6 @@"integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.1",@@ -2242,6 +2540,13 @@"node": ">=6"}},+ "node_modules/keycharm": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/keycharm/-/keycharm-0.4.0.tgz",+ "integrity": "sha512-TyQTtsabOVv3MeOpR92sIKk/br9wxS+zGj4BG7CR8YbK4jM3tyIBaF0zhzeBUMx36/Q/iQLOKKOT+3jOQtemRQ==",+ "license": "(Apache-2.0 OR MIT)",+ "peer": true+ },"node_modules/keyv": {"version": "4.5.4","resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",@@ -2581,6 +2886,19 @@"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/marked": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz",+ "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==",+ "license": "MIT",+ "peer": true,+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/memoize-one": {"version": "5.2.1","resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-5.2.1.tgz",@@ -2600,6 +2918,27 @@"node": "*"}},+ "node_modules/moment": {+ "version": "2.30.1",+ "resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz",+ "integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": "*"+ }+ },+ "node_modules/monaco-editor": {+ "version": "0.55.1",+ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz",+ "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "dompurify": "3.2.7",+ "marked": "14.0.0"+ }+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",@@ -2802,6 +3141,16 @@"react-is": "^16.13.1"}},+ "node_modules/propagating-hammerjs": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/propagating-hammerjs/-/propagating-hammerjs-3.0.0.tgz",+ "integrity": "sha512-FJTclGll0ysatpF9rKO4jwobyaVDitPb0g/bGlufqqtXPQX8mxf8IXilnIK2iYRMPkVlYeFNhPTrspF9CM1stg==",+ "license": "MIT",+ "peer": true,+ "peerDependencies": {+ "@egjs/hammerjs": "^2.0.17"+ }+ },"node_modules/punycode": {"version": "2.3.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",@@ -2817,7 +3166,6 @@"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz","integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==","license": "MIT",- "peer": true,"engines": {"node": ">=0.10.0"}@@ -2883,7 +3231,6 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz","integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==","license": "MIT",- "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -2953,7 +3300,6 @@"integrity": "sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@oxc-project/types": "=0.122.0","@rolldown/pluginutils": "1.0.0-rc.12"@@ -3048,6 +3394,12 @@"node": ">=0.10.0"}},+ "node_modules/state-local": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz",+ "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==",+ "license": "MIT"+ },"node_modules/strip-json-comments": {"version": "3.1.1","resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",@@ -3129,7 +3481,6 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","dev": true,"license": "Apache-2.0",- "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -3219,13 +3570,79 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/uuid": {+ "version": "13.0.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz",+ "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "peer": true,+ "bin": {+ "uuid": "dist-node/bin/uuid"+ }+ },+ "node_modules/vis-data": {+ "version": "8.0.3",+ "resolved": "https://registry.npmjs.org/vis-data/-/vis-data-8.0.3.tgz",+ "integrity": "sha512-jhnb6rJNqkKR1Qmlay0VuDXY9ZlvAnYN1udsrP4U+krgZEq7C0yNSKdZqmnCe13mdnf9AdVcdDGFOzy2mpPoqw==",+ "license": "(Apache-2.0 OR MIT)",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/visjs"+ },+ "peerDependencies": {+ "uuid": "^3.4.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^13.0.0",+ "vis-util": ">=6.0.0"+ }+ },+ "node_modules/vis-timeline": {+ "version": "8.5.0",+ "resolved": "https://registry.npmjs.org/vis-timeline/-/vis-timeline-8.5.0.tgz",+ "integrity": "sha512-u0+UUuk8qJTxf2SdQ0z0ckCjtks0ECRrjAipbmCZd6vEPf6USGXxeoi7ilRilTU8iVzVE3P0W5TLWzei5KuPfQ==",+ "license": "(Apache-2.0 OR MIT)",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/visjs"+ },+ "peerDependencies": {+ "@egjs/hammerjs": "^2.0.0",+ "component-emitter": "^1.3.0",+ "keycharm": "^0.2.0 || ^0.3.0 || ^0.4.0",+ "moment": "^2.24.0",+ "propagating-hammerjs": "^1.4.0 || ^2.0.0 || ^3.0.0",+ "uuid": "^3.4.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^13.0.0",+ "vis-data": ">=8.0.0",+ "vis-util": ">=6.0.0",+ "xss": "^1.0.0"+ }+ },+ "node_modules/vis-util": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/vis-util/-/vis-util-6.0.0.tgz",+ "integrity": "sha512-qtpts3HRma0zPe4bO7t9A2uejkRNj8Z2Tb6do6lN85iPNWExFkUiVhdAq5uLGIUqBFduyYeqWJKv/jMkxX0R5g==",+ "license": "(Apache-2.0 OR MIT)",+ "peer": true,+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/visjs"+ },+ "peerDependencies": {+ "@egjs/hammerjs": "^2.0.0",+ "component-emitter": "^1.3.0 || ^2.0.0"+ }+ },"node_modules/vite": {"version": "8.0.3","resolved": "https://registry.npmjs.org/vite/-/vite-8.0.3.tgz","integrity": "sha512-B9ifbFudT1TFhfltfaIPgjo9Z3mDynBTJSUYxTjOQruf/zHH+ezCQKcoqO+h7a9Pw9Nm/OtlXAiGT1axBgwqrQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"lightningcss": "^1.32.0","picomatch": "^4.0.4",@@ -3324,6 +3741,23 @@"node": ">=0.10.0"}},+ "node_modules/xss": {+ "version": "1.0.15",+ "resolved": "https://registry.npmjs.org/xss/-/xss-1.0.15.tgz",+ "integrity": "sha512-FVdlVVC67WOIPvfOwhoMETV72f6GbW7aOabBC3WxN/oUdoEMDyLz4OgRv5/gck2ZeNqEQu+Tb0kloovXOfpYVg==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "commander": "^2.20.3",+ "cssfilter": "0.0.10"+ },+ "bin": {+ "xss": "bin/xss"+ },+ "engines": {+ "node": ">= 0.10.0"+ }+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",@@ -3350,7 +3784,6 @@"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==","dev": true,"license": "MIT",- "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}@@ -3367,6 +3800,34 @@"peerDependencies": {"zod": "^3.25.0 || ^4.0.0"}+ },+ "node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }}}}diff --git a/semantica-explorer/package.json b/semantica-explorer/package.jsonindex ae5688e1..62e54204 100644--- a/semantica-explorer/package.json+++ b/semantica-explorer/package.json@@ -10,7 +10,9 @@"preview": "vite preview"},"dependencies": {+ "@monaco-editor/react": "^4.7.0","@tanstack/react-query": "^5.95.2",+ "@xyflow/react": "^12.10.2","graphology": "^0.26.0","graphology-layout-forceatlas2": "^0.10.1","lucide-react": "^1.7.0",@@ -18,7 +20,9 @@"react-arborist": "^3.4.3","react-dom": "^19.2.4","react-dropzone": "^15.0.0",- "sigma": "^3.0.2"+ "sigma": "^3.0.2",+ "vis-data": "^8.0.3",+ "vis-timeline": "^8.5.0"},"devDependencies": {"@babel/core": "^7.29.0",diff --git a/semantica-explorer/src/App.tsx b/semantica-explorer/src/App.tsxindex d7675b56..cc2542a9 100644--- a/semantica-explorer/src/App.tsx+++ b/semantica-explorer/src/App.tsx@@ -5,20 +5,26 @@ import { useState } from 'react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { VocabularyWorkspace } from './workspaces/VocabularyWorkspace/VocabularyWorkspace';import { GraphWorkspace } from './workspaces/GraphWorkspace/GraphWorkspace';+import { DecisionWorkspace } from './workspaces/DecisionWorkspace/DecisionWorkspace';+import { SparqlWorkspace } from './workspaces/SparqlWorkspace/SparqlWorkspace';+import { LineageDiagram } from './workspaces/LineageWorkspace/LineageDiagram';+import { DiffMergeWorkspace } from './workspaces/DiffMergeWorkspace/DiffMergeWorkspace';+import { ImportExportWorkspace } from './workspaces/ImportExportWorkspace/ImportExportWorkspace'; // <-- IMPORT ADDEDconst queryClient = new QueryClient();export default function App() {- const [activeWorkspace, setActiveWorkspace] = useState<'vocabulary' | 'graph'>('graph');++ const [activeWorkspace, setActiveWorkspace] = useState<'vocabulary' | 'graph' | 'decisions' | 'sparql' | 'lineage' | 'merge' | 'import'>('graph');return (<QueryClientProvider client={queryClient}><div style={{ display: 'flex', width: '100vw', height: '100vh', margin: 0, padding: 0, backgroundColor: '#0d1117', fontFamily: "system-ui, -apple-system, sans-serif" }}>--- <nav style={{- width: '64px',- backgroundColor: '#010409',+++ <nav style={{+ width: '64px',+ backgroundColor: '#010409',borderRight: '1px solid #30363d',display: 'flex',flexDirection: 'column',@@ -26,46 +32,95 @@ export default function App() {paddingTop: '16px',gap: '16px'}}>- {/* Logo / Brand */}+<div style={{ width: '32px', height: '32px', backgroundColor: '#238636', borderRadius: '8px', marginBottom: '24px' }} title="Semantica" />{/* Graph Icon Button */}- <button+ <buttononClick={() => setActiveWorkspace('graph')}title="Graph Explorer"- style={{- width: '40px', height: '40px', borderRadius: '8px', cursor: 'pointer',- border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',- backgroundColor: activeWorkspace === 'graph' ? '#1f6feb' : 'transparent',- color: activeWorkspace === 'graph' ? '#fff' : '#8b949e',- transition: 'all 0.2s'- }}+ style={navItemStyle(activeWorkspace === 'graph')}><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line></svg></button>{/* Vocabulary Icon Button */}- <button+ <buttononClick={() => setActiveWorkspace('vocabulary')}title="Vocabulary & Ontology"- style={{- width: '40px', height: '40px', borderRadius: '8px', cursor: 'pointer',- border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',- backgroundColor: activeWorkspace === 'vocabulary' ? '#1f6feb' : 'transparent',- color: activeWorkspace === 'vocabulary' ? '#fff' : '#8b949e',- transition: 'all 0.2s'- }}+ style={navItemStyle(activeWorkspace === 'vocabulary')}><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"></path></svg></button>++ {/* Decisions */}+ <button+ onClick={() => setActiveWorkspace('decisions')}+ title="Decision Tree"+ style={navItemStyle(activeWorkspace === 'decisions')}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="6" y1="3" x2="6" y2="15"></line><circle cx="18" cy="6" r="3"></circle><circle cx="6" cy="18" r="3"></circle><path d="M18 9a9 9 0 0 1-9 9"></path></svg>+ </button>++ {/* SPARQL */}+ <button+ onClick={() => setActiveWorkspace('sparql')}+ title="SPARQL Engine"+ style={navItemStyle(activeWorkspace === 'sparql')}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="4 17 10 11 4 5"></polyline><line x1="12" y1="19" x2="20" y2="19"></line></svg>+ </button>++ {/* Lineage */}+ <button+ onClick={() => setActiveWorkspace('lineage')}+ title="PROV-O Lineage"+ style={navItemStyle(activeWorkspace === 'lineage')}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line></svg>+ </button>++ {/* Merge */}+ <button+ onClick={() => setActiveWorkspace('merge')}+ title="Diff / Merge"+ style={navItemStyle(activeWorkspace === 'merge')}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7v4a1 1 0 0 0 1 1h3"></path><path d="M12 2v20"></path><path d="M21 7v4a1 1 0 0 1-1 1h-3"></path><circle cx="3" cy="4" r="3"></circle><circle cx="21" cy="4" r="3"></circle><circle cx="12" cy="19" r="3"></circle></svg>+ </button>++ {/* IMPORT / EXPORT BUTTON */}+ <button+ onClick={() => setActiveWorkspace('import')}+ title="Data Import / Export"+ style={navItemStyle(activeWorkspace === 'import')}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>+ </button>+</nav>- {/* ── Active Workspace Area ────────────────────────────────────── */}+<div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>{activeWorkspace === 'graph' && <GraphWorkspace />}{activeWorkspace === 'vocabulary' && <VocabularyWorkspace />}+ {activeWorkspace === 'decisions' && <DecisionWorkspace />}+ {activeWorkspace === 'sparql' && <SparqlWorkspace />}+ {activeWorkspace === 'lineage' && <LineageDiagram />}+ {activeWorkspace === 'merge' && <DiffMergeWorkspace />}+ {activeWorkspace === 'import' && <ImportExportWorkspace />}</div></div></QueryClientProvider>);+}++function navItemStyle(active: boolean): React.CSSProperties {+ return {+ width: '40px', height: '40px', borderRadius: '8px', cursor: 'pointer',+ border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',+ backgroundColor: active ? '#1f6feb' : 'transparent',+ color: active ? '#fff' : '#8b949e',+ transition: 'all 0.2s'+ };}\ No newline at end of filediff --git a/semantica-explorer/src/types.d.ts b/semantica-explorer/src/types.d.tsnew file mode 100644index 00000000..ab5d4a9c--- /dev/null+++ b/semantica-explorer/src/types.d.ts@@ -0,0 +1,16 @@+declare module 'vis-timeline/standalone' {+ export class Timeline {+ constructor(container: HTMLElement, items: any, options?: any);+ on(event: string, callback: (properties: any) => void): void;+ destroy(): void;+ }+}++declare module 'vis-data/standalone' {+ export class DataSet<T = any> {+ constructor(data?: T[], options?: any);+ add(data: T | T[]): void;+ update(data: T | T[]): void;+ remove(id: string | number | (string | number)[]): void;+ }+}diff --git a/semantica-explorer/src/workspaces/DecisionWorkspace/DecisionWorkspace.tsx b/semantica-explorer/src/workspaces/DecisionWorkspace/DecisionWorkspace.tsxnew file mode 100644index 00000000..ca4a8ed2--- /dev/null+++ b/semantica-explorer/src/workspaces/DecisionWorkspace/DecisionWorkspace.tsx@@ -0,0 +1,115 @@+/**+ * src/workspaces/DecisionWorkspace/DecisionWorkspace.tsx+ */+import { useState, useEffect } from "react";++const THEME_CSS = `+ .glass-panel {+ background: linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6));+ backdrop-filter: blur(16px) saturate(1.2);+ -webkit-backdrop-filter: blur(16px) saturate(1.2);+ border: 1px solid rgba(88,166,255,0.2);+ box-shadow: 0 8px 32px rgba(0,0,0,0.5), inset 1px 1px 0 rgba(255,255,255,0.05);+ }+`;++++function CausalChainNode({ hop, title, desc }: { hop: number, title: string, desc: string }) {+ return (+ <div style={{ marginLeft: hop * 24, paddingLeft: 16, borderLeft: "2px solid rgba(88,166,255,0.3)", position: "relative", marginBottom: 16 }}>+ <div style={{ position: "absolute", left: -6, top: 4, width: 10, height: 10, borderRadius: "50%", background: "#58a6ff", boxShadow: "0 0 8px #58a6ff" }} />+ <h4 style={{ margin: "0 0 4px 0", color: "#e6edf3", fontSize: 14 }}>{title}</h4>+ <p style={{ margin: 0, color: "#8b949e", fontSize: 13 }}>{desc}</p>+ </div>+ );+}++export function DecisionWorkspace() {+ const [decisions, setDecisions] = useState<any[]>([]);+ const [selectedDecision, setSelectedDecision] = useState<any | null>(null);+ const [chain, setChain] = useState<any[]>([]);+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ fetch("http://localhost:8000/api/decisions")+ .then(res => res.json())+ .then(data => {+ setDecisions(data);+ if (data.length > 0) handleSelectDecision(data[0]);+ })+ .catch(console.error);+ }, []);++ const handleSelectDecision = async (d: any) => {+ setSelectedDecision(d);+ setLoading(true);+ try {+ const res = await fetch(`http://localhost:8000/api/decisions/${d.decision_id}/chain`);+ const data = await res.json();+ setChain(data.chain || []);+ } catch (e) {+ console.error(e);+ } finally {+ setLoading(false);+ }+ };++ return (+ <div style={{ display: "flex", width: "100%", height: "100%", background: "#0d1117", overflow: "hidden" }}>+ <style>{THEME_CSS}</style>++ {/* Left Column: Decisions List */}+ <div className="glass-panel" style={{ width: 320, padding: 24, display: "flex", flexDirection: "column", gap: 16, borderRight: "1px solid rgba(88,166,255,0.2)", borderTop: "none", borderLeft: "none", borderBottom: "none", borderRadius: 0 }}>+ <h2 style={{ color: "#ffffff", margin: 0, fontSize: 18, borderBottom: "1px solid rgba(255,255,255,0.1)", paddingBottom: 12 }}>+ Decision Tree+ </h2>+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>+ {decisions.map(d => (+ <button+ key={d.decision_id}+ onClick={() => handleSelectDecision(d)}+ style={{+ textAlign: "left", padding: "12px 16px", borderRadius: 8, cursor: "pointer",+ background: selectedDecision?.decision_id === d.decision_id ? "rgba(88,166,255,0.15)" : "transparent",+ border: `1px solid ${selectedDecision?.decision_id === d.decision_id ? "#58a6ff" : "rgba(255,255,255,0.1)"}`,+ color: selectedDecision?.decision_id === d.decision_id ? "#ffffff" : "#c9d1d9",+ transition: "all 0.2s"+ }}+ >+ <div style={{ fontWeight: 600, fontSize: 14 }}>{d.decision_id}</div>+ <div style={{ fontSize: 12, color: "#8b949e", marginTop: 4 }}>{d.category || 'Uncategorized'}</div>+ </button>+ ))}+ </div>+ </div>++ {/* Right Column: Causal Chains */}+ <div style={{ flex: 1, padding: 32, overflowY: "auto", position: "relative" }}>+ <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at top right, rgba(88,166,255,0.05), transparent 60%)", pointerEvents: "none" }} />++ {selectedDecision ? (+ <>+ <h1 style={{ color: "#ffffff", fontSize: 28, margin: "0 0 8px 0" }}>{selectedDecision.decision_id}</h1>+ <div style={{ color: "#58a6ff", fontSize: 14, marginBottom: 40 }}>Outcome: {selectedDecision.outcome}</div>++ <div className="glass-panel" style={{ padding: 32, borderRadius: 12 }}>+ <h3 style={{ color: "#ffffff", margin: "0 0 24px 0", fontSize: 16 }}>Causal Chain</h3>+ {loading ? (+ <div style={{ color: "#8b949e" }}>Loading chain...</div>+ ) : chain.length > 0 ? (+ chain.map((c, i) => (+ <CausalChainNode key={i} hop={i} title={`${c.relationship} ${c.id}`} desc={c.content || '...'} />+ ))+ ) : (+ <div style={{ color: "#8b949e" }}>No causal chain found.</div>+ )}+ </div>+ </>+ ) : (+ <div style={{ color: "#8b949e", textAlign: "center", marginTop: 100 }}>Select a decision to view details</div>+ )}+ </div>+ </div>+ );+}diff --git a/semantica-explorer/src/workspaces/DiffMergeWorkspace/DiffMergeWorkspace.tsx b/semantica-explorer/src/workspaces/DiffMergeWorkspace/DiffMergeWorkspace.tsxnew file mode 100644index 00000000..3e9fc8e0--- /dev/null+++ b/semantica-explorer/src/workspaces/DiffMergeWorkspace/DiffMergeWorkspace.tsx@@ -0,0 +1,99 @@+/**+ * src/workspaces/DiffMergeWorkspace/DiffMergeWorkspace.tsx+ */+import { useState } from "react";++const THEME_CSS = `+ .glass-panel {+ background: linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6));+ backdrop-filter: blur(16px) saturate(1.2);+ -webkit-backdrop-filter: blur(16px) saturate(1.2);+ border: 1px solid rgba(88,166,255,0.2);+ box-shadow: 0 8px 32px rgba(0,0,0,0.5), inset 1px 1px 0 rgba(255,255,255,0.05);+ }+`;++export function DiffMergeWorkspace() {+ const [primaryId, setPrimaryId] = useState("n-primary-1");+ const [duplicateId, setDuplicateId] = useState("n-dup-2");++ const [msg, setMsg] = useState("");++ const handleMerge = async () => {+ try {+ const res = await fetch("http://localhost:8000/api/enrich/merge", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ primary_id: primaryId, duplicate_ids: [duplicateId] })+ });+ const data = await res.json();+ if (data.merged_into) {+ setMsg(`Merge success: redirected ${data.edges_updated} edges to ${data.merged_into}`);+ } else {+ setMsg("Merge failed...");+ }+ } catch (err) {+ setMsg("Error calling merge endpoint.");+ }+ };++ return (+ <div style={{ display: "flex", flexDirection: "column", width: "100%", height: "100%", background: "#0d1117", padding: 32, gap: 24, boxSizing: "border-box" }}>+ <style>{THEME_CSS}</style>+ <div>+ <h1 style={{ margin: "0 0 8px 0", color: "#fff" }}>Entity Diff & Merge</h1>+ <p style={{ margin: 0, color: "#8b949e" }}>Compare suspected duplicate entities and reconcile them.</p>+ </div>++ <div style={{ display: "flex", gap: 24, flex: 1 }}>+ {/* Primary View */}+ <div className="glass-panel" style={{ flex: 1, borderRadius: 12, padding: 24 }}>+ <h3 style={{ color: "#58a6ff", margin: "0 0 16px 0", borderBottom: "1px solid rgba(88,166,255,0.2)", paddingBottom: 8 }}>Primary Entity</h3>+ <label style={{ display: "block", color: "#c9d1d9", marginBottom: 8, fontSize: 13 }}>Primary Node ID</label>+ <input+ value={primaryId} onChange={e => setPrimaryId(e.target.value)}+ style={{ width: "100%", background: "rgba(0,0,0,0.3)", border: "1px solid rgba(255,255,255,0.1)", color: "#fff", padding: "8px 12px", borderRadius: 6, marginBottom: 24 }}+ />++ <div style={{ background: "rgba(0,0,0,0.2)", padding: 16, borderRadius: 6 }}>+ <div style={{ color: "#8b949e", fontSize: 12, marginBottom: 4 }}>Name</div>+ <div style={{ color: "#fff", fontSize: 14 }}>Sample Company Inc.</div>++ <div style={{ color: "#8b949e", fontSize: 12, marginTop: 16, marginBottom: 4 }}>Founded</div>+ <div style={{ color: "#fff", fontSize: 14 }}>2004-05-12</div>+ </div>+ </div>++ {/* Duplicate View */}+ <div className="glass-panel" style={{ flex: 1, borderRadius: 12, padding: 24 }}>+ <h3 style={{ color: "#ff7b72", margin: "0 0 16px 0", borderBottom: "1px solid rgba(255,123,114,0.2)", paddingBottom: 8 }}>Duplicate Entity</h3>+ <label style={{ display: "block", color: "#c9d1d9", marginBottom: 8, fontSize: 13 }}>Duplicate Node ID</label>+ <input+ value={duplicateId} onChange={e => setDuplicateId(e.target.value)}+ style={{ width: "100%", background: "rgba(0,0,0,0.3)", border: "1px solid rgba(255,255,255,0.1)", color: "#fff", padding: "8px 12px", borderRadius: 6, marginBottom: 24 }}+ />++ <div style={{ background: "rgba(0,0,0,0.2)", padding: 16, borderRadius: 6 }}>+ <div style={{ color: "#d2a8ff", fontSize: 12, marginBottom: 4 }}>Name</div>+ {/* Amber highlight for differing values */}+ <div style={{ color: "#d29922", fontSize: 14, fontWeight: "bold" }}>Sample Company</div>++ <div style={{ color: "#8b949e", fontSize: 12, marginTop: 16, marginBottom: 4 }}>Founded</div>+ <div style={{ color: "#fff", fontSize: 14 }}>2004-05-12</div>+ </div>+ </div>+ </div>++ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>+ <div style={{ color: "#58a6ff" }}>{msg}</div>+ <button+ onClick={handleMerge}+ style={{ background: "#238636", color: "#fff", border: "none", padding: "10px 24px", borderRadius: 6, fontWeight: 600, cursor: "pointer", fontSize: 16 }}+ >+ Confirm Merge+ </button>+ </div>++ </div>+ );+}diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsxindex 7cf3f1a3..6d1e4d11 100644--- a/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx+++ b/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx@@ -1,14 +1,23 @@/*** src/workspaces/GraphWorkspace/GraphCanvas.tsx+ *+ * Sigma.js WebGL canvas.+ **/-import { useEffect, useRef, useState, useCallback } from "react";+import { useEffect, useRef, useState, useCallback, forwardRef, useImperativeHandle } from "react";import Sigma from "sigma";import FA2Layout from "graphology-layout-forceatlas2/worker";import { graph } from "../../store/graphStore";+export interface GraphCanvasHandle {++ getSigma: () => Sigma | null;+ fitView: () => void;+}+export interface GraphCanvasProps {onNodeClick: (nodeId: string) => void;- selectedNodeId: string;+ selectedNodeId: string;isLayoutRunning: boolean;className?: string;}@@ -33,149 +42,156 @@ const SIGMA_SETTINGS = {webGLTarget: "webgl2" as const,};-export function GraphCanvas({ onNodeClick, selectedNodeId, isLayoutRunning, className }: GraphCanvasProps) {- const containerRef = useRef<HTMLDivElement>(null);- const sigmaRef = useRef<Sigma | null>(null);- const fa2Ref = useRef<FA2Layout | null>(null);+export const GraphCanvas = forwardRef<GraphCanvasHandle, GraphCanvasProps>(+ function GraphCanvas({ onNodeClick, selectedNodeId, isLayoutRunning, className }, ref) {+ const containerRef = useRef<HTMLDivElement>(null);+ const sigmaRef = useRef<Sigma | null>(null);+ const fa2Ref = useRef<FA2Layout | null>(null);+ const [hoveredNode, setHoveredNode] = useState<string | null>(null);- const [hoveredNode, setHoveredNode] = useState<string | null>(null);- useEffect(() => {- if (!containerRef.current || sigmaRef.current) return;+ useImperativeHandle(ref, () => ({+ getSigma: () => sigmaRef.current,+ fitView: () => sigmaRef.current?.getCamera().animatedReset({ duration: 500 }),+ }));- const sigma = new Sigma(graph, containerRef.current, SIGMA_SETTINGS);- sigmaRef.current = sigma;- const resizeObserver = new ResizeObserver(() => {- if (containerRef.current && containerRef.current.offsetWidth > 0) {- sigma.refresh();- }- });- resizeObserver.observe(containerRef.current);-- // Click Events- sigma.on("clickNode", ({ node }) => {- onNodeClick(node);- });-- sigma.on("clickStage", () => {- onNodeClick("");- });-- // Hover Events- sigma.on("enterNode", ({ node }) => setHoveredNode(node));- sigma.on("leaveNode", () => setHoveredNode(null));-- return () => {- resizeObserver.disconnect();- sigma.kill();- sigmaRef.current = null;- };- }, [onNodeClick]);---- useEffect(() => {- const sigma = sigmaRef.current;- if (!sigma) return;--- const activeNode = hoveredNode || selectedNodeId;--- const isValidActiveNode = activeNode && graph.hasNode(activeNode);--- const activeNeighbors = isValidActiveNode ? new Set(graph.neighbors(activeNode)) : new Set();-- if (!isValidActiveNode) {-- sigma.setSetting("nodeReducer", undefined);-- sigma.setSetting("edgeReducer", (edge, data) => ({- ...data,- color: "#161b22",- size: Math.max(0.5, (data.size || 1) * 0.5),- zIndex: 0,- }));- } else {- sigma.setSetting("nodeReducer", (node, data) => {- const isFocused = node === activeNode;- const isNeighbor = activeNeighbors.has(node);-- if (isFocused || isNeighbor) {- return {- ...data,- zIndex: isFocused ? 2 : 1,- borderColor: isFocused ? "#ffffff" : data.borderColor,- borderSize: isFocused ? 2 : data.borderSize,- };- }+ useEffect(() => {+ if (!containerRef.current || sigmaRef.current) return;- // Mute all other nodes into the background- return {+ const sigma = new Sigma(graph, containerRef.current, SIGMA_SETTINGS);+ sigmaRef.current = sigma;++ const resizeObserver = new ResizeObserver(() => {+ if (containerRef.current && containerRef.current.offsetWidth > 0) {+ sigma.refresh();+ }+ });+ resizeObserver.observe(containerRef.current);++ sigma.on("clickNode", ({ node }) => onNodeClick(node));+ sigma.on("clickStage", () => onNodeClick(""));+ sigma.on("enterNode", ({ node }) => setHoveredNode(node));+ sigma.on("leaveNode", () => setHoveredNode(null));++ return () => {+ resizeObserver.disconnect();+ sigma.kill();+ sigmaRef.current = null;+ };+ }, [onNodeClick]);+++ useEffect(() => {+ const sigma = sigmaRef.current;+ if (!sigma) return;++ const activeNode = hoveredNode || selectedNodeId;+ const isValidActiveNode = activeNode && graph.hasNode(activeNode);+ const activeNeighbors = isValidActiveNode+ ? new Set(graph.neighbors(activeNode))+ : new Set<string>();++ if (!isValidActiveNode) {+ sigma.setSetting("nodeReducer", null);+ sigma.setSetting("edgeReducer", (_edge, data) => ({...data,- color: "#1c2128",- borderColor: "#0d1117",- label: "",+ color: "#1c2128",+ size: Math.max(0.5, (data.size || 1) * 0.5),zIndex: 0,- };- });-- sigma.setSetting("edgeReducer", (edge, data) => {-- if (graph.hasExtremity(edge, activeNode)) {+ }));+ } else {+ sigma.setSetting("nodeReducer", (node, data) => {+ const isFocused = node === activeNode;+ const isNeighbor = activeNeighbors.has(node);++ if (isFocused) {+ return {+ ...data,+ zIndex: 2,+ borderColor: "#ffffff",+ borderSize: 2,+ };+ }+ if (isNeighbor) {+ return { ...data, zIndex: 1 };+ }return {...data,- color: "#58a6ff",- size: (data.size || 1) * 2,- zIndex: 1,+ color: "#1c2128",+ borderColor: "#0d1117",+ label: "",+ zIndex: 0,};- }-- return { ...data, hidden: true };- });- }-- sigma.refresh();- }, [hoveredNode, selectedNodeId]);+ });++ sigma.setSetting("edgeReducer", (edge, data) => {+ if (graph.hasExtremity(edge, activeNode)) {+ return {+ ...data,+ color: "#58a6ff",+ size: (data.size || 1) * 2,+ zIndex: 1,+ };+ }+ return { ...data, hidden: true };+ });+ }+ sigma.refresh();+ }, [hoveredNode, selectedNodeId]);+ // ForceAtlas2 layout- useEffect(() => {- if (isLayoutRunning) {- if (!fa2Ref.current) {- fa2Ref.current = new FA2Layout(graph, FA2_SETTINGS);+ useEffect(() => {+ if (isLayoutRunning) {+ if (!fa2Ref.current) {+ fa2Ref.current = new FA2Layout(graph, FA2_SETTINGS);+ }+ fa2Ref.current.start();+ } else {+ fa2Ref.current?.stop();}- fa2Ref.current.start();- } else {- fa2Ref.current?.stop();- }-- return () => {- fa2Ref.current?.kill();- fa2Ref.current = null;- };- }, [isLayoutRunning]);--- const handleFitView = useCallback(() => {- sigmaRef.current?.getCamera().animatedReset({ duration: 500 });- }, []);-- return (- <div style={{ position: "relative", width: "100%", height: "100%" }}>- <div ref={containerRef} className={className} style={{ width: "100%", height: "100%", background: "transparent" }} />- <button- onClick={handleFitView}- style={{- position: "absolute", bottom: 24, left: 24, padding: "8px 16px",- background: "#1f6feb", color: "#fff", border: "none", borderRadius: 6,- cursor: "pointer", fontWeight: 600, zIndex: 10,- }}- >- Fit View- </button>- </div>- );-}\ No newline at end of file++ return () => {+ fa2Ref.current?.kill();+ fa2Ref.current = null;+ };+ }, [isLayoutRunning]);++ const handleFitView = useCallback(() => {+ sigmaRef.current?.getCamera().animatedReset({ duration: 500 });+ }, []);++ return (+ <div style={{ position: "relative", width: "100%", height: "100%" }}>+ <div+ ref={containerRef}+ className={className}+ style={{ width: "100%", height: "100%", background: "transparent" }}+ />+ <button+ id="graph-fit-view-btn"+ onClick={handleFitView}+ style={{+ position: "absolute",+ bottom: 24,+ left: 24,+ padding: "8px 16px",+ background: "rgba(31, 111, 235, 0.85)",+ color: "#fff",+ border: "1px solid rgba(88,166,255,0.3)",+ borderRadius: 6,+ cursor: "pointer",+ fontWeight: 600,+ zIndex: 10,+ backdropFilter: "blur(8px)",+ fontSize: 13,+ }}+ >+ ⊞ Fit View+ </button>+ </div>+ );+ }+);diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsxindex 07b79235..55b297ed 100644--- a/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx+++ b/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx@@ -1,40 +1,51 @@/*** src/workspaces/GraphWorkspace/GraphWorkspace.tsx*/-import { useState, useCallback } from "react";+import { useState, useCallback, useEffect, useRef } from "react";import { GraphCanvas } from "./GraphCanvas";+import type { GraphCanvasHandle } from "./GraphCanvas";+import { TimelinePanel } from "./TimelinePanel";import { useLoadGraph, useReloadGraph } from "./useLoadGraph";import { graph } from "../../store/graphStore";+// Utils++function useDebounce<T>(value: T, delay: number): T {+ const [debouncedValue, setDebouncedValue] = useState<T>(value);+ useEffect(() => {+ const h = setTimeout(() => setDebouncedValue(value), delay);+ return () => clearTimeout(h);+ }, [value, delay]);+ return debouncedValue;+}++// Styles+const HUD_CSS = `.palantir-bg {background: radial-gradient(ellipse at center, #0d1117 0%, #010409 100%);}.palantir-grid {- position: absolute;- inset: 0;+ position: absolute; inset: 0;background-image:- linear-gradient(rgba(88, 166, 255, 0.05) 1px, transparent 1px),- linear-gradient(90deg, rgba(88, 166, 255, 0.05) 1px, transparent 1px);+ linear-gradient(rgba(88,166,255,0.05) 1px, transparent 1px),+ linear-gradient(90deg, rgba(88,166,255,0.05) 1px, transparent 1px);background-size: 40px 40px;- pointer-events: none;- z-index: 1;+ pointer-events: none; z-index: 1;}.palantir-vignette {- position: absolute;- inset: 0;- background: radial-gradient(ellipse at center, transparent 30%, rgba(1, 4, 9, 0.85) 100%);- pointer-events: none;- z-index: 2;+ position: absolute; inset: 0;+ background: radial-gradient(ellipse at center, transparent 30%, rgba(1,4,9,0.85) 100%);+ pointer-events: none; z-index: 2;}.glass-header {- background: linear-gradient(180deg, rgba(13,17,23,0.85) 0%, rgba(13,17,23,0) 100%);+ background: linear-gradient(180deg, rgba(13,17,23,0.9) 0%, rgba(13,17,23,0) 100%);border-bottom: 1px solid rgba(88,166,255,0.1);backdrop-filter: blur(8px);-webkit-backdrop-filter: blur(8px);}.glass-hud {- background: linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6));+ background: linear-gradient(135deg, rgba(13,17,23,0.78), rgba(22,27,34,0.62));backdrop-filter: blur(16px) saturate(1.2);-webkit-backdrop-filter: blur(16px) saturate(1.2);border-left: 1px solid rgba(88,166,255,0.2);@@ -42,9 +53,11 @@ const HUD_CSS = `}.hud-scrollbar::-webkit-scrollbar { width: 4px; }.hud-scrollbar::-webkit-scrollbar-track { background: transparent; }- .hud-scrollbar::-webkit-scrollbar-thumb { background: rgba(88, 166, 255, 0.3); border-radius: 4px; }+ .hud-scrollbar::-webkit-scrollbar-thumb { background: rgba(88,166,255,0.3); border-radius: 4px; }`;+// Node detail panel+function NodePanel({ nodeId }: { nodeId: string }) {if (!nodeId) {return (@@ -57,46 +70,88 @@ function NodePanel({ nodeId }: { nodeId: string }) {}const attrs = graph.getNodeAttributes(nodeId);+ const accentColor = attrs?.color || "#58a6ff";return (<aside style={{ padding: 24 }}>- <div style={{ borderBottom: "1px solid rgba(88, 166, 255, 0.2)", paddingBottom: 16, marginBottom: 20 }}>+ <div style={{ borderBottom: "1px solid rgba(88,166,255,0.2)", paddingBottom: 16, marginBottom: 20 }}><div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>- <span style={{- background: attrs?.color || "#6c8ebf",- boxShadow: `0 0 10px ${attrs?.color || "#6c8ebf"}`,- width: 8, height: 8, borderRadius: "50%", display: "inline-block"+ <span style={{+ background: accentColor,+ boxShadow: `0 0 10px ${accentColor}`,+ width: 8, height: 8, borderRadius: "50%",}} />- <span style={{ color: attrs?.color || "#6c8ebf", fontSize: 12, fontWeight: 600 }}>+ <span style={{ color: accentColor, fontSize: 12, fontWeight: 600 }}>{attrs?.nodeType || "Entity"}</span></div>- <h3 style={{ margin: 0, color: "#ffffff", fontSize: 20, fontWeight: 600 }}>+ <h3 style={{ margin: 0, color: "#fff", fontSize: 20, fontWeight: 600, wordBreak: "break-word" }}>{String(attrs?.label ?? nodeId)}</h3></div>- <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>- {Object.entries(attrs?.properties || {}).map(([k, v]) => (- <div key={k} style={{ background: "rgba(0,0,0,0.2)", padding: "10px 14px", borderRadius: 6, border: "1px solid rgba(255,255,255,0.05)" }}>- <div style={{ color: "rgba(88, 166, 255, 0.7)", fontSize: 11, marginBottom: 4 }}>- {k}- </div>- <div style={{ color: "#e6edf3", fontSize: 13, fontFamily: "monospace", wordBreak: "break-word" }}>- {typeof v === "object" ? JSON.stringify(v) : String(v)}+ {/* Temporal bounds badge */}+ {(attrs?.valid_from || attrs?.valid_until) && (+ <div style={{+ marginBottom: 16,+ padding: "8px 12px",+ background: "rgba(88,166,255,0.08)",+ border: "1px solid rgba(88,166,255,0.2)",+ borderRadius: 6,+ fontSize: 12,+ color: "#79c0ff",+ fontFamily: "monospace",+ }}>+ {attrs?.valid_from && <div>▶ from: {attrs.valid_from}</div>}+ {attrs?.valid_until && <div>◀ until: {attrs.valid_until}</div>}+ </div>+ )}++ <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>+ {Object.entries(attrs?.properties || {})+ .filter(([k]) => !["x", "y", "valid_from", "valid_until", "content"].includes(k))+ .map(([k, v]) => (+ <div+ key={k}+ style={{+ background: "rgba(0,0,0,0.2)",+ padding: "10px 14px",+ borderRadius: 6,+ border: "1px solid rgba(255,255,255,0.05)",+ }}+ >+ <div style={{ color: "rgba(88,166,255,0.7)", fontSize: 11, marginBottom: 4 }}>{k}</div>+ <div style={{ color: "#e6edf3", fontSize: 13, fontFamily: "monospace", wordBreak: "break-word" }}>+ {typeof v === "object" ? JSON.stringify(v) : String(v)}+ </div></div>- </div>- ))}+ ))}</div></aside>);}+// Main component+export function GraphWorkspace() {const [selectedNodeId, setSelectedNodeId] = useState<string>("");const [isLayoutRunning, setIsLayoutRunning] = useState(false);const reload = useReloadGraph();+ // Scrubber time state+ const [scrubberTime, setScrubberTime] = useState<Date | null>(null);+ const debouncedTime = useDebounce(scrubberTime, 150);++ const prevActiveIdsRef = useRef<Set<string>>(new Set());++ const canvasRef = useRef<GraphCanvasHandle>(null);++ const [activeNodeCount, setActiveNodeCount] = useState<number | null>(null);++ const handleTimeChange = useCallback((time: Date) => {+ setScrubberTime(time);+ }, []);+const handleNodeClick = useCallback((nodeId: string) => {setSelectedNodeId(nodeId);}, []);@@ -108,46 +163,139 @@ export function GraphWorkspace() {},});- return (+ // Temporal filtering+ useEffect(() => {+ if (!debouncedTime || isLoading) return;++ let cancelled = false;++ const applySnapshot = async () => {+ try {+ const at = debouncedTime.toISOString();+ const res = await fetch(`/api/temporal/snapshot?at=${encodeURIComponent(at)}`);+ if (!res.ok || cancelled) return;++ const data: { active_node_ids: string[]; active_node_count: number } = await res.json();+ if (cancelled) return;++ const newActiveIds = new Set(data.active_node_ids);+++ requestAnimationFrame(() => {+ if (cancelled) return;++ const prev = prevActiveIdsRef.current;- <div className="palantir-bg" style={{ position: "relative", width: "100%", height: "100%", overflow: "hidden" }}>- <style>{HUD_CSS}</style>+ prev.forEach((id) => {+ if (!newActiveIds.has(id) && graph.hasNode(id)) {+ graph.setNodeAttribute(id, "hidden", true);+ }+ });+++ newActiveIds.forEach((id) => {+ if (!prev.has(id) && graph.hasNode(id)) {+ graph.setNodeAttribute(id, "hidden", false);+ }+ });++ prevActiveIdsRef.current = newActiveIds;+ setActiveNodeCount(data.active_node_count);++ canvasRef.current?.getSigma()?.refresh();+ });+ } catch (err) {+ if (!cancelled) {+ console.error("[Temporal] Snapshot fetch failed:", err);+ }+ }+ };++ applySnapshot();+ return () => { cancelled = true; };+ }, [debouncedTime, isLoading]);+++ return (+ <div+ className="palantir-bg"+ style={{ position: "relative", width: "100%", height: "100%", overflow: "hidden", display: "flex", flexDirection: "column" }}+ >+ <style>{HUD_CSS}</style><div className="palantir-grid" /><div className="palantir-vignette" />- <div style={{ position: "absolute", inset: 0, zIndex: 3 }}>++ <div style={{ flex: 1, position: "relative", zIndex: 3, minHeight: 0 }}><GraphCanvas+ ref={canvasRef}onNodeClick={handleNodeClick}selectedNodeId={selectedNodeId}isLayoutRunning={isLayoutRunning}/></div>++ <TimelinePanel onTimeChange={handleTimeChange} />++<div style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 10 }}>-- <header className="glass-header" style={{ pointerEvents: "auto", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 24px" }}>- <div style={{ display: "flex", gap: 16, alignItems: "center" }}>- <h2 style={{ margin: 0, fontSize: 18, color: "#ffffff", fontWeight: 600 }}>Graph Explorer</h2>-- {isLoading && <span style={{ color: "rgba(88,166,255,0.8)", fontSize: 13 }}>Loading data...</span>}++ <header+ className="glass-header"+ style={{ pointerEvents: "auto", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 24px" }}+ >+ <div style={{ display: "flex", gap: 12, alignItems: "center" }}>+ <h2 style={{ margin: 0, fontSize: 18, color: "#fff", fontWeight: 600 }}>Graph Explorer</h2>++ {isLoading && (+ <span style={{ color: "rgba(88,166,255,0.8)", fontSize: 13 }}>Loading graph…</span>+ )}+{summary && (- <span style={{ background: "rgba(88,166,255,0.1)", color: "#58a6ff", padding: "4px 10px", borderRadius: 4, fontSize: 12, border: "1px solid rgba(88,166,255,0.2)" }}>+ <span style={{+ background: "rgba(88,166,255,0.1)",+ color: "#58a6ff",+ padding: "4px 10px",+ borderRadius: 4,+ fontSize: 12,+ border: "1px solid rgba(88,166,255,0.2)",+ }}>{summary.nodeCount.toLocaleString()} nodes · {summary.edgeCount.toLocaleString()} edges</span>)}++ {activeNodeCount !== null && (+ <span style={{+ background: "rgba(63,185,80,0.12)",+ color: "#3fb950",+ padding: "4px 10px",+ borderRadius: 4,+ fontSize: 12,+ border: "1px solid rgba(63,185,80,0.25)",+ }}>+ ⏱ {activeNodeCount.toLocaleString()} active+ </span>+ )}+{isError && (- <span style={{ color: "#ff7b72", fontSize: 13 }}>Error: {(error as Error).message}</span>+ <span style={{ color: "#ff7b72", fontSize: 13 }}>+ ⚠ {(error as Error).message}+ </span>)}</div>- <div style={{ display: "flex", gap: 12 }}>+ <div style={{ display: "flex", gap: 10 }}><buttononClick={() => setIsLayoutRunning((v) => !v)}- style={btnStyle(isLayoutRunning ? "rgba(56, 139, 253, 0.15)" : "rgba(255,255,255,0.05)", isLayoutRunning ? "#58a6ff" : "#e6edf3")}+ style={btnStyle(isLayoutRunning ? "rgba(56,139,253,0.15)" : "rgba(255,255,255,0.05)", isLayoutRunning ? "#58a6ff" : "#e6edf3")}disabled={isLoading}>- <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: "50%", background: isLayoutRunning ? "#58a6ff" : "#8b949e", marginRight: 8 }} />+ <span style={{+ display: "inline-block", width: 8, height: 8, borderRadius: "50%",+ background: isLayoutRunning ? "#58a6ff" : "#8b949e", marginRight: 8,+ }} />{isLayoutRunning ? "Pause Layout" : "Run Layout"}</button><button onClick={reload} style={btnStyle("rgba(255,255,255,0.05)", "#e6edf3")} disabled={isLoading}>@@ -156,37 +304,38 @@ export function GraphWorkspace() {</div></header>- <div- className="glass-hud hud-scrollbar"- style={{- pointerEvents: "auto",- position: "absolute",- right: 0,- top: 60,- bottom: 0,- width: 360,++ <div+ className="glass-hud hud-scrollbar"+ style={{+ pointerEvents: "auto",+ position: "absolute",+ right: 0,+ top: 52,+ bottom: 90,+ width: 360,overflowY: "auto",- transition: "transform 0.3s cubic-bezier(0.16, 1, 0.3, 1)",- transform: selectedNodeId ? "translateX(0)" : "translateX(100%)"+ transition: "transform 0.3s cubic-bezier(0.16,1,0.3,1)",+ transform: selectedNodeId ? "translateX(0)" : "translateX(100%)",}}><NodePanel nodeId={selectedNodeId} /></div>-+</div></div>);}-const btnStyle = (bg: string, color: string): React.CSSProperties => ({- background: bg,- color,- border: "1px solid rgba(255,255,255,0.1)",- borderRadius: 4,- padding: "8px 16px",- cursor: "pointer",- fontSize: 13,+const btnStyle = (bg: string, color: string): React.CSSProperties => ({+ background: bg,+ color,+ border: "1px solid rgba(255,255,255,0.1)",+ borderRadius: 4,+ padding: "8px 16px",+ cursor: "pointer",+ fontSize: 13,fontWeight: 500,transition: "all 0.2s",- backdropFilter: "blur(4px)"+ backdropFilter: "blur(4px)",});\ No newline at end of filediff --git a/semantica-explorer/src/workspaces/GraphWorkspace/TimelinePanel.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/TimelinePanel.tsxnew file mode 100644index 00000000..fef89a6a--- /dev/null+++ b/semantica-explorer/src/workspaces/GraphWorkspace/TimelinePanel.tsx@@ -0,0 +1,296 @@+/**+ * src/workspaces/GraphWorkspace/TimelinePanel.tsx+ *+ */+import { useEffect, useRef, useState, useCallback } from "react";+import { Timeline } from "vis-timeline";+import type { TimelineOptions } from "vis-timeline";+import { DataSet } from "vis-data";+import "vis-timeline/styles/vis-timeline-graph2d.css";+++export interface TimelinePanelProps {+ onTimeChange: (time: Date) => void;+}+++const MIN_DATE = new Date("1970-01-01T00:00:00Z");+const MAX_DATE = new Date("2025-01-01T00:00:00Z");+const PLAYHEAD_ID = "playhead";+const PLAY_INTERVAL_MS = 500;+const PLAY_STEP_MONTHS = 6;+++const VIS_OVERRIDE_CSS = `+ .sem-timeline-wrap .vis-timeline {+ border: none !important;+ background: transparent !important;+ overflow: visible !important;+ }+ .sem-timeline-wrap .vis-panel.vis-background,+ .sem-timeline-wrap .vis-panel.vis-center {+ background: transparent !important;+ }+ .sem-timeline-wrap .vis-panel {+ border-color: rgba(88, 166, 255, 0.15) !important;+ }+ .sem-timeline-wrap .vis-time-axis .vis-text {+ color: #8b949e !important;+ font-size: 11px !important;+ font-family: 'JetBrains Mono', 'Fira Code', monospace !important;+ padding-top: 3px !important;+ }+ .sem-timeline-wrap .vis-time-axis .vis-text.vis-major {+ color: #c9d1d9 !important;+ font-weight: 700 !important;+ font-size: 12px !important;+ }+ .sem-timeline-wrap .vis-time-axis .vis-grid.vis-minor {+ border-color: rgba(88, 166, 255, 0.07) !important;+ }+ .sem-timeline-wrap .vis-time-axis .vis-grid.vis-major {+ border-color: rgba(88, 166, 255, 0.18) !important;+ }+ /* Playhead needle */+ .sem-timeline-wrap .vis-custom-time.${PLAYHEAD_ID} {+ background: rgba(88, 166, 255, 0.15) !important;+ width: 2px !important;+ cursor: ew-resize !important;+ z-index: 5 !important;+ }+ .sem-timeline-wrap .vis-custom-time.${PLAYHEAD_ID} > .vis-custom-time-marker {+ background: #58a6ff !important;+ color: #0d1117 !important;+ font-size: 10px !important;+ font-weight: 700 !important;+ border-radius: 3px !important;+ padding: 1px 5px !important;+ white-space: nowrap !important;+ box-shadow: 0 0 8px rgba(88, 166, 255, 0.7) !important;+ }+ .sem-timeline-wrap .vis-current-time { display: none !important; }+ .sem-timeline-wrap .vis-panel.vis-left { display: none !important; }+`;++function formatPlayheadLabel(d: Date): string {+ return d.getFullYear().toString() + "/" + String(d.getMonth() + 1).padStart(2, "0");+}++export function TimelinePanel({ onTimeChange }: TimelinePanelProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const timelineRef = useRef<Timeline | null>(null);+ const playheadRef = useRef<Date>(new Date("2000-01-01T00:00:00Z"));+ const playIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const [isPlaying, setIsPlaying] = useState(false);+ const [displayDate, setDisplayDate] = useState("2000 / 01");+++ useEffect(() => {+ if (!containerRef.current || timelineRef.current) return;++ const items = new DataSet<any>([]);++ const options: TimelineOptions = {+ height: "100%",+ min: MIN_DATE,+ max: MAX_DATE,+ start: MIN_DATE,+ end: MAX_DATE,+ showCurrentTime: false,+ zoomable: true,+ moveable: true,+ zoomMin: 1000 * 60 * 60 * 24 * 365 * 2, // ≥ 2 years zoom+ zoomMax: 1000 * 60 * 60 * 24 * 365 * 60, // ≤ 60 years zoom+ showMajorLabels: true,+ showMinorLabels: true,+ timeAxis: { scale: "year", step: 5 },+ format: {+ minorLabels: { year: "YYYY" },+ majorLabels: { year: "YYYY" },+ },+ orientation: { axis: "bottom" },+ margin: { item: 0, axis: 0 },+ selectable: false,+ stack: false,+ } as TimelineOptions;++ const tl = new Timeline(containerRef.current, items, options);+ timelineRef.current = tl;++ const defaultTime = new Date("2000-01-01T00:00:00Z");+ playheadRef.current = defaultTime;+ tl.addCustomTime(defaultTime, PLAYHEAD_ID);+++ onTimeChange(defaultTime);+ setDisplayDate(formatPlayheadLabel(defaultTime));+++ tl.on("timechange", (props: any) => {+ if (props.id !== PLAYHEAD_ID) return;+ const t: Date = props.time;+ playheadRef.current = t;+ tl.setCustomTime(t, PLAYHEAD_ID);+ onTimeChange(t);+ setDisplayDate(formatPlayheadLabel(t));+ });++ return () => {+ tl.destroy();+ timelineRef.current = null;+ };++ }, []);+++ const startPlay = useCallback(() => {+ if (playIntervalRef.current) return;+ playIntervalRef.current = setInterval(() => {+ const tl = timelineRef.current;+ if (!tl) return;++ const next = new Date(playheadRef.current);+ next.setMonth(next.getMonth() + PLAY_STEP_MONTHS);++ if (next >= MAX_DATE) {++ next.setTime(MIN_DATE.getTime());+ }++ playheadRef.current = next;+ tl.setCustomTime(next, PLAYHEAD_ID);+ onTimeChange(next);+ setDisplayDate(formatPlayheadLabel(next));+ }, PLAY_INTERVAL_MS);+ }, [onTimeChange]);++ const stopPlay = useCallback(() => {+ if (playIntervalRef.current) {+ clearInterval(playIntervalRef.current);+ playIntervalRef.current = null;+ }+ }, []);++ const togglePlay = useCallback(() => {+ setIsPlaying((prev) => {+ if (prev) {+ stopPlay();+ return false;+ } else {+ startPlay();+ return true;+ }+ });+ }, [startPlay, stopPlay]);+++ useEffect(() => () => stopPlay(), [stopPlay]);+++ return (+ <div+ style={{+ position: "relative",+ width: "100%",+ height: "90px",+ borderTop: "1px solid rgba(88,166,255,0.2)",+ background: "rgba(1, 4, 9, 0.88)",+ backdropFilter: "blur(16px)",+ WebkitBackdropFilter: "blur(16px)",+ display: "flex",+ alignItems: "stretch",+ flexShrink: 0,+ }}+ >+ <style>{VIS_OVERRIDE_CSS}</style>++ {/* Play/Pause button */}+ <div+ style={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ justifyContent: "center",+ gap: 4,+ padding: "0 16px",+ borderRight: "1px solid rgba(88,166,255,0.15)",+ minWidth: 80,+ flexShrink: 0,+ }}+ >+ <button+ id="temporal-play-btn"+ onClick={togglePlay}+ title={isPlaying ? "Pause Evolution" : "Play Evolution"}+ style={{+ width: 34,+ height: 34,+ borderRadius: "50%",+ border: `1.5px solid ${isPlaying ? "#58a6ff" : "rgba(88,166,255,0.35)"}`,+ background: isPlaying+ ? "rgba(88,166,255,0.2)"+ : "rgba(88,166,255,0.06)",+ color: "#58a6ff",+ cursor: "pointer",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ transition: "all 0.2s",+ boxShadow: isPlaying ? "0 0 10px rgba(88,166,255,0.4)" : "none",+ }}+ >+ {isPlaying ? (+ /* Pause icon */+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">+ <rect x="6" y="4" width="4" height="16" />+ <rect x="14" y="4" width="4" height="16" />+ </svg>+ ) : (+ /* Play icon */+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">+ <polygon points="5,3 19,12 5,21" />+ </svg>+ )}+ </button>++ <span+ style={{+ fontSize: 10,+ color: isPlaying ? "#58a6ff" : "#8b949e",+ fontFamily: "monospace",+ letterSpacing: "0.04em",+ transition: "color 0.2s",+ }}+ >+ {displayDate}+ </span>+ </div>++ {/* Label */}+ <div+ style={{+ position: "absolute",+ top: 5,+ left: 100,+ fontSize: 10,+ fontWeight: 600,+ letterSpacing: "0.1em",+ color: "rgba(88,166,255,0.55)",+ textTransform: "uppercase",+ pointerEvents: "none",+ zIndex: 2,+ }}+ >+ Temporal Scrubber · 1970–2025+ </div>++ {/* Timeline canvas */}+ <div className="sem-timeline-wrap" style={{ flex: 1, overflow: "hidden", position: "relative" }}>+ <div+ ref={containerRef}+ style={{ width: "100%", height: "100%", position: "relative" }}+ />+ </div>+ </div>+ );+}diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts b/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.tsindex 4e6215fc..168f0c3a 100644--- a/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts+++ b/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts@@ -4,16 +4,16 @@ import type { EdgeAttributes, NodeAttributes } from "../../store/graphStore";// colors and hasherconst CYBER_PALETTE = [- "#58a6ff",- "#3fb950",- "#d2a8ff",- "#f0883e",- "#ff7b72",- "#79c0ff",- "#d29922",- "#bc8cff",- "#56d364",- "#f778ba"+ "#58a6ff",+ "#3fb950",+ "#d2a8ff",+ "#f0883e",+ "#ff7b72",+ "#79c0ff",+ "#d29922",+ "#bc8cff",+ "#56d364",+ "#f778ba"];@@ -21,7 +21,7 @@ const hashCategory = (str: string): number => {let hash = 0;for (let i = 0; i < str.length; i++) {hash = (hash << 5) - hash + str.charCodeAt(i);- hash |= 0;+ hash |= 0;}return Math.abs(hash);};@@ -63,12 +63,12 @@ export interface GraphLoadSummary {loadTimeMs: number;}-const PAGE_LIMIT = 1000;+const PAGE_LIMIT = 1000;async function fetchAllNodes(signal: AbortSignal): Promise<number> {let skip = 0;let totalMerged = 0;- let hasMore = true;+ let hasMore = true;while (hasMore) {const url = new URL("/api/graph/nodes", window.location.origin);@@ -77,18 +77,18 @@ async function fetchAllNodes(signal: AbortSignal): Promise<number> {const res = await fetch(url.toString(), { signal });if (!res.ok) {- const errorBody = await res.text();+ const errorBody = await res.text();if (res.status === 422) {- console.error(`🚨 FastAPI 422 Crash Report at skip=${skip}:`, errorBody);- break;+ console.error(`🚨 FastAPI 422 Crash Report at skip=${skip}:`, errorBody);+ break;}throw new Error(`Fetch failed: ${res.status}`);- }+ }const data: NodeListResponse = await res.json();-+if (!data.nodes || data.nodes.length === 0) {- break;+ break;}const nodesToMerge = data.nodes.map((n) => {@@ -115,7 +115,7 @@ async function fetchAllNodes(signal: AbortSignal): Promise<number> {skip += PAGE_LIMIT;if (data.nodes.length < PAGE_LIMIT) {- hasMore = false;+ hasMore = false;}await yieldToMain();@@ -136,18 +136,18 @@ async function fetchAllEdges(signal: AbortSignal): Promise<number> {const res = await fetch(url.toString(), { signal });if (!res.ok) {- const errorBody = await res.text();+ const errorBody = await res.text();if (res.status === 422) {- console.error(`🚨 FastAPI 422 Crash Report at skip=${skip}:`, errorBody);- break;+ console.error(`🚨 FastAPI 422 Crash Report at skip=${skip}:`, errorBody);+ break;}throw new Error(`Fetch failed: ${res.status}`);- }+ }const data: EdgeListResponse = await res.json();-+if (!data.edges || data.edges.length === 0) {- break;+ break;}// Filter out edges pointing to missing nodes@@ -172,7 +172,7 @@ async function fetchAllEdges(signal: AbortSignal): Promise<number> {skip += PAGE_LIMIT;if (data.edges.length < PAGE_LIMIT) {- hasMore = false;+ hasMore = false;}await yieldToMain();@@ -195,13 +195,12 @@ interface UseLoadGraphOptions {export function useLoadGraph(options: UseLoadGraphOptions = {}) {const { enabled = true, onGraphReady } = options;- const queryClient = useQueryClient();return useQuery<GraphLoadSummary>({queryKey: ["graph", "full-load"],enabled,- staleTime: Infinity,-+ staleTime: Infinity,+queryFn: async ({ signal }): Promise<GraphLoadSummary> => {const t0 = performance.now();@@ -216,14 +215,12 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {graph.updateEachNodeAttributes((node, attr) => {const categoryStr = String(attr.nodeType || attr.properties?.community || attr.properties?.category || "default");const colorIndex = hashCategory(categoryStr) % CYBER_PALETTE.length;--++const degree = graph.degree(node);- const minSize = 2;- const maxSize = 25;-- // Flatten the power low curve to prevent giant graphs- // from consuming the screen+ const minSize = 2;+ const maxSize = 25;+const sizeRatio = Math.log(degree + 1) / Math.log(maxDegree + 1);const dynamicSize = minSize + (maxSize - minSize) * sizeRatio;@@ -232,7 +229,7 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {...attr,color: CYBER_PALETTE[colorIndex],size: dynamicSize,- borderColor: "#0d1117",+ borderColor: "#0d1117",borderSize: 0.5,};});@@ -253,4 +250,4 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {export function useReloadGraph() {const queryClient = useQueryClient();return () => queryClient.invalidateQueries({ queryKey: ["graph", "full-load"] });-}\ No newline at end of file+}diff --git a/semantica-explorer/src/workspaces/ImportExportWorkspace/ImportExportWorkspace.tsx b/semantica-explorer/src/workspaces/ImportExportWorkspace/ImportExportWorkspace.tsxnew file mode 100644index 00000000..abf32aba--- /dev/null+++ b/semantica-explorer/src/workspaces/ImportExportWorkspace/ImportExportWorkspace.tsx@@ -0,0 +1,263 @@+/**+ * src/workspaces/ImportExportWorkspace/ImportExportWorkspace.tsx+ */+import { useState, useCallback } from "react";+import { useDropzone } from "react-dropzone";+import { UploadCloud, Download, FileJson, FileText, CheckCircle2, AlertCircle, Loader2 } from "lucide-react";++const THEME_CSS = `+ .glass-panel {+ background: linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6));+ backdrop-filter: blur(16px) saturate(1.2);+ -webkit-backdrop-filter: blur(16px) saturate(1.2);+ border: 1px solid rgba(88,166,255,0.2);+ box-shadow: 0 8px 32px rgba(0,0,0,0.5), inset 1px 1px 0 rgba(255,255,255,0.05);+ }+ .dropzone {+ border: 2px dashed rgba(88,166,255,0.4);+ border-radius: 12px;+ background: rgba(0,0,0,0.2);+ transition: all 0.2s ease-in-out;+ cursor: pointer;+ }+ .dropzone:hover, .dropzone.active {+ border-color: #58a6ff;+ background: rgba(88,166,255,0.05);+ }+ .btn-primary {+ background: #238636;+ color: #fff;+ border: 1px solid rgba(240,246,252,0.1);+ transition: background 0.2s;+ }+ .btn-primary:hover:not(:disabled) {+ background: #2ea043;+ }+ .btn-primary:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .toast {+ animation: slideUp 0.3s ease-out forwards;+ }+ @keyframes slideUp {+ from { opacity: 0; transform: translateY(20px); }+ to { opacity: 1; transform: translateY(0); }+ }+`;++interface ToastMessage {+ id: number;+ type: "success" | "error";+ text: string;+}++export function ImportExportWorkspace() {+ // Import State+ const [file, setFile] = useState<File | null>(null);+ const [isUploading, setIsUploading] = useState(false);++ // Export State+ const [exportFormat, setExportFormat] = useState<"json" | "csv">("json");+ const [isExporting, setIsExporting] = useState(false);++ // Toasts+ const [toasts, setToasts] = useState<ToastMessage[]>([]);++ const showToast = (type: "success" | "error", text: string) => {+ const id = Date.now();+ setToasts(prev => [...prev, { id, type, text }]);+ setTimeout(() => {+ setToasts(prev => prev.filter(t => t.id !== id));+ }, 5000);+ };++ const onDrop = useCallback((acceptedFiles: File[]) => {+ if (acceptedFiles.length > 0) {+ setFile(acceptedFiles[0]);+ }+ }, []);++ const { getRootProps, getInputProps, isDragActive } = useDropzone({+ onDrop,+ accept: {+ 'application/json': ['.json'],+ 'text/csv': ['.csv']+ },+ maxFiles: 1+ });++ const handleImport = async () => {+ if (!file) return;+ setIsUploading(true);++ try {+ const formData = new FormData();+ formData.append("file", file);++ const res = await fetch("/api/import", {+ method: "POST",+ body: formData,+ });++ if (!res.ok) {+ const err = await res.json();+ throw new Error(err.detail || "Import failed");+ }++ const data = await res.json();+ showToast("success", `Imported ${data.nodes_imported} nodes and ${data.edges_imported} edges!`);+ setFile(null);+ } catch (err: any) {+ showToast("error", err.message || "An error occurred during import");+ } finally {+ setIsUploading(false);+ }+ };++ const handleExport = async () => {+ setIsExporting(true);+ try {+ const res = await fetch("/api/export", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ format: exportFormat })+ });++ if (!res.ok) {+ const err = await res.json();+ throw new Error(err.detail || "Export failed");+ }++ // Handle file download+ const blob = await res.blob();+ const url = window.URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ // Provide a default extension based on format+ a.download = `semantica_export.${exportFormat}`;+ document.body.appendChild(a);+ a.click();+ window.URL.revokeObjectURL(url);+ document.body.removeChild(a);++ showToast("success", "Export complete! Your download should begin shortly.");+ } catch (err: any) {+ showToast("error", err.message || "An error occurred during export");+ } finally {+ setIsExporting(false);+ }+ };++ return (+ <div style={{ position: "relative", display: "flex", flexDirection: "column", width: "100%", height: "100%", background: "#0d1117", padding: 32, gap: 24, boxSizing: "border-box", overflowY: "auto" }}>+ <style>{THEME_CSS}</style>++ <div>+ <h1 style={{ margin: "0 0 8px 0", color: "#fff", display: "flex", alignItems: "center", gap: 12 }}>+ <UploadCloud size={28} color="#58a6ff" /> Data Import / Export+ </h1>+ <p style={{ margin: 0, color: "#8b949e" }}>Ingest new graph datasets or extract the current knowledge base.</p>+ </div>++ <div style={{ display: "flex", gap: 24, flexWrap: "wrap" }}>++ {/* IMPORT PANEL */}+ <div className="glass-panel" style={{ flex: "1 1 400px", borderRadius: 12, padding: 32, display: "flex", flexDirection: "column" }}>+ <h2 style={{ margin: "0 0 24px 0", color: "#58a6ff", fontSize: 20, display: "flex", alignItems: "center", gap: 8 }}>+ <UploadCloud size={20} /> Import Entities & Relations+ </h2>++ <div {...getRootProps()} className={`dropzone ${isDragActive ? 'active' : ''}`} style={{ padding: 48, textAlign: "center", marginBottom: 24, flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>+ <input {...getInputProps()} />+ {file ? (+ <>+ {file.name.endsWith(".json") ? <FileJson size={48} color="#3fb950" style={{ marginBottom: 16 }} /> : <FileText size={48} color="#3fb950" style={{ marginBottom: 16 }} />}+ <p style={{ color: "#fff", fontWeight: 600, margin: "0 0 8px 0" }}>{file.name}</p>+ <p style={{ color: "#8b949e", fontSize: 13, margin: 0 }}>{(file.size / 1024 / 1024).toFixed(2)} MB</p>+ </>+ ) : (+ <>+ <UploadCloud size={48} color="#58a6ff" style={{ marginBottom: 16, opacity: 0.8 }} />+ <p style={{ color: "#c9d1d9", fontSize: 16, fontWeight: 500, margin: "0 0 8px 0" }}>Drag & drop your file here</p>+ <p style={{ color: "#8b949e", fontSize: 13, margin: 0 }}>Supports .json and .csv formats</p>+ </>+ )}+ </div>++ <button+ className="btn-primary"+ onClick={handleImport}+ disabled={!file || isUploading}+ style={{ width: "100%", padding: "12px 24px", borderRadius: 8, fontSize: 16, fontWeight: 600, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, cursor: (!file || isUploading) ? "not-allowed" : "pointer", border: "none" }}+ >+ {isUploading ? <Loader2 size={20} className="animate-spin" /> : <UploadCloud size={20} />}+ {isUploading ? "Uploading..." : "Upload to Graph"}+ </button>+ </div>++ {/* EXPORT PANEL */}+ <div className="glass-panel" style={{ flex: "1 1 400px", borderRadius: 12, padding: 32, display: "flex", flexDirection: "column" }}>+ <h2 style={{ margin: "0 0 24px 0", color: "#d2a8ff", fontSize: 20, display: "flex", alignItems: "center", gap: 8 }}>+ <Download size={20} /> Export Graph Snapshot+ </h2>++ <div style={{ flex: 1 }}>+ <label style={{ display: "block", color: "#c9d1d9", marginBottom: 8, fontSize: 14, fontWeight: 500 }}>Export Format</label>+ <div style={{ position: "relative", marginBottom: 32 }}>+ <select+ value={exportFormat}+ onChange={e => setExportFormat(e.target.value as "json" | "csv")}+ style={{ width: "100%", appearance: "none", background: "rgba(0,0,0,0.3)", border: "1px solid rgba(88,166,255,0.3)", color: "#fff", padding: "12px 16px", borderRadius: 8, fontSize: 15, cursor: "pointer", outline: "none" }}+ >+ <option value="json" style={{ background: "#0d1117" }}>JSON (Full Graph Dictionary)</option>+ <option value="csv" style={{ background: "#0d1117" }}>CSV (Tabular Dump)</option>+ </select>+ <div style={{ position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }}>+ <svg width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M1.41 0.589966L6 5.16997L10.59 0.589966L12 1.99997L6 7.99997L0 1.99997L1.41 0.589966Z" fill="#8b949e"/>+ </svg>+ </div>+ </div>++ <div style={{ background: "rgba(0,0,0,0.2)", padding: 20, borderRadius: 8, border: "1px solid rgba(255,255,255,0.05)" }}>+ <h4 style={{ color: "#c9d1d9", margin: "0 0 8px 0", fontSize: 14 }}>Export Details</h4>+ <p style={{ color: "#8b949e", fontSize: 13, margin: 0, lineHeight: 1.5 }}>+ {exportFormat === "json"+ ? "Exports the entire graph including all node properties, edge weights, and complete entity metadata into a standardized JSON payload."+ : "Exports a flattened CSV tabular representation of all nodes and edges. Complex nested properties will be omitted or stringified."}+ </p>+ </div>+ </div>++ <button+ style={{ width: "100%", background: "#1f6feb", color: "#fff", padding: "12px 24px", borderRadius: 8, fontSize: 16, fontWeight: 600, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, cursor: isExporting ? "not-allowed" : "pointer", border: "1px solid rgba(240,246,252,0.1)", transition: "background 0.2s" }}+ onClick={handleExport}+ disabled={isExporting}+ onMouseOver={e => { if(!isExporting) (e.currentTarget.style.background = "#388bfd") }}+ onMouseOut={e => { if(!isExporting) (e.currentTarget.style.background = "#1f6feb") }}+ >+ {isExporting ? <Loader2 size={20} className="animate-spin" /> : <Download size={20} />}+ {isExporting ? "Preparing Extract..." : "Download Graph Extract"}+ </button>+ </div>+ </div>++ {/* Toast Notifications */}+ <div style={{ position: "fixed", bottom: 32, right: 32, display: "flex", flexDirection: "column", gap: 12, zIndex: 1000 }}>+ {toasts.map(toast => (+ <div key={toast.id} className="toast" style={{+ display: "flex", alignItems: "center", gap: 12, padding: "16px 20px", borderRadius: 8,+ background: toast.type === 'success' ? '#1b4a24' : '#571822',+ border: `1px solid ${toast.type === 'success' ? 'rgba(63, 185, 80, 0.4)' : 'rgba(248, 81, 73, 0.4)'}`,+ boxShadow: "0 8px 24px rgba(0,0,0,0.5)"+ }}>+ {toast.type === 'success' ? <CheckCircle2 color="#3fb950" size={20}/> : <AlertCircle color="#f85149" size={20}/>}+ <span style={{ color: "#fff", fontSize: 14, fontWeight: 500 }}>{toast.text}</span>+ </div>+ ))}+ </div>++ </div>+ );+}\ No newline at end of filediff --git a/semantica-explorer/src/workspaces/LineageWorkspace/LineageDiagram.tsx b/semantica-explorer/src/workspaces/LineageWorkspace/LineageDiagram.tsxnew file mode 100644index 00000000..c465f9ce--- /dev/null+++ b/semantica-explorer/src/workspaces/LineageWorkspace/LineageDiagram.tsx@@ -0,0 +1,92 @@+/**+ * src/workspaces/LineageWorkspace/LineageDiagram.tsx+ */+import { useEffect, useState } from "react";+import { ReactFlow, Background, Controls } from "@xyflow/react";+import "@xyflow/react/dist/style.css";++const THEME_CSS = `+ .react-flow { background: #0d1117; }+ .react-flow__node-group {+ background: rgba(88,166,255,0.05);+ border: 1px dashed rgba(88,166,255,0.2);+ border-radius: 8px;+ }+ .react-flow__node-default {+ background: #161b22;+ color: #c9d1d9;+ border: 1px solid rgba(88,166,255,0.3);+ border-radius: 6px;+ padding: 10px;+ font-size: 12px;+ }+`;++export function LineageDiagram() {+ const [nodes, setNodes] = useState<any[]>([]);+ const [edges, setEdges] = useState<any[]>([]);++ useEffect(() => {++ const xLanes = [+ { id: "group_agent", type: "group", position: { x: 50, y: 50 }, style: { width: 800, height: 120 } },+ { id: "group_activity", type: "group", position: { x: 50, y: 200 }, style: { width: 800, height: 120 } },+ { id: "group_entity", type: "group", position: { x: 50, y: 350 }, style: { width: 800, height: 120 } }+ ];++ const fetchLineage = async () => {+ try {+ const res = await fetch("http://localhost:8000/api/provenance", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_id: "default" })+ });+ const data = await res.json();+++ const counters: Record<string, number> = { "group_agent": 0, "group_activity": 0, "group_entity": 0 };++ const mappedNodes = data.nodes.map((n: any) => {+ const c = counters[n.parent_id] || 0;+ counters[n.parent_id] = c + 1;+ return {+ id: n.id,+ data: { label: n.label + "\\n(" + n.prov_type + ")" },+ position: { x: 50 + c * 180, y: 30 },+ parentId: n.parent_id,+ extent: "parent",+ type: "default"+ };+ });++ const mappedEdges = data.edges.map((e: any) => ({+ id: e.id,+ source: e.source,+ target: e.target,+ label: e.label,+ animated: true,+ style: { stroke: "#58a6ff" }+ }));++ setNodes([...xLanes, ...mappedNodes]);+ setEdges(mappedEdges);+ } catch (err) {+ console.error(err);+ }+ };+ fetchLineage();+ }, []);++ return (+ <div style={{ width: "100%", height: "100%", position: "relative" }}>+ <style>{THEME_CSS}</style>+ <div style={{ position: "absolute", top: 16, left: 16, zIndex: 10, background: "rgba(13,17,23,0.8)", padding: "4px 8px", borderRadius: 4, color: "#fff", fontWeight: 600, border: "1px solid rgba(255,255,255,0.1)", pointerEvents: "none" }}>+ PROV-O Lineage+ </div>+ <ReactFlow nodes={nodes} edges={edges} fitView>+ <Background color="#30363d" gap={20} />+ <Controls />+ </ReactFlow>+ </div>+ );+}diff --git a/semantica-explorer/src/workspaces/SparqlWorkspace/SparqlWorkspace.tsx b/semantica-explorer/src/workspaces/SparqlWorkspace/SparqlWorkspace.tsxnew file mode 100644index 00000000..b829898d--- /dev/null+++ b/semantica-explorer/src/workspaces/SparqlWorkspace/SparqlWorkspace.tsx@@ -0,0 +1,150 @@+/**+ * src/workspaces/SparqlWorkspace/SparqlWorkspace.tsx+ */+import { useState, useRef } from "react";+import Editor, { useMonaco } from "@monaco-editor/react";++const THEME_CSS = `+ .glass-panel {+ background: linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6));+ backdrop-filter: blur(16px) saturate(1.2);+ -webkit-backdrop-filter: blur(16px) saturate(1.2);+ border: 1px solid rgba(88,166,255,0.2);+ box-shadow: 0 8px 32px rgba(0,0,0,0.5), inset 1px 1px 0 rgba(255,255,255,0.05);+ }+`;++export function SparqlWorkspace() {+ const monaco = useMonaco();+ const editorRef = useRef<any>(null);+ const [query, setQuery] = useState("SELECT ?s ?p ?o\nWHERE {\n ?s ?p ?o\n}\nLIMIT 10");+ const [result, setResult] = useState<any>(null);+ const [isLoading, setIsLoading] = useState(false);++ function handleEditorWillMount(monacoIns: any) {+ if (!monacoIns.languages.getLanguages().some((l: any) => l.id === "sparql")) {+ monacoIns.languages.register({ id: "sparql" });++ monacoIns.languages.setMonarchTokensProvider("sparql", {+ keywords: ["SELECT", "WHERE", "LIMIT", "FILTER", "OPTIONAL", "PREFIX", "ORDER BY", "DESC", "ASC"],+ tokenizer: {+ root: [+ [/[a-zA-Z_]\w*/, { cases: { "@keywords": "keyword", "@default": "identifier" } }],+ [/[?\$][a-zA-Z_]\w*/, "variable.name"],+ [/<[^>]+>/, "string.uri"],+ [/".*?"/, "string"],+ [/#.*/, "comment"],+ ]+ }+ });++ monacoIns.editor.defineTheme("sparql-dark", {+ base: "vs-dark",+ inherit: true,+ rules: [+ { token: "keyword", foreground: "58a6ff", fontStyle: "bold" },+ { token: "variable.name", foreground: "79c0ff" },+ { token: "string.uri", foreground: "a5d6ff" },+ { token: "string", foreground: "a5d6ff" },+ { token: "comment", foreground: "8b949e" }+ ],+ colors: {+ "editor.background": "#0d1117",+ "editor.lineHighlightBackground": "#161b22",+ }+ });+ }+ }++ function handleEditorDidMount(editor: any) {+ editorRef.current = editor;+ }++ async function handleRun() {+ setIsLoading(true);+ setResult(null);+ monaco?.editor.setModelMarkers(editorRef.current.getModel(), "sparql", []);++ try {+ const response = await fetch("http://localhost:8000/api/sparql", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ query, session_id: "default" })+ });+ const data = await response.json();++ if (data.error) {+ if (data.error_line && monaco && editorRef.current) {+ monaco.editor.setModelMarkers(editorRef.current.getModel(), "sparql", [+ {+ startLineNumber: data.error_line,+ startColumn: data.error_column || 1,+ endLineNumber: data.error_line,+ endColumn: 100,+ message: data.error,+ severity: monaco.MarkerSeverity.Error+ }+ ]);+ }+ }+ setResult(data);+ } catch (e) {+ console.error(e);+ } finally {+ setIsLoading(false);+ }+ }++ return (+ <div style={{ display: "flex", flexDirection: "column", width: "100%", height: "100%", background: "#0d1117", padding: 24, boxSizing: "border-box", gap: 24 }}>+ <style>{THEME_CSS}</style>+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>+ <h2 style={{ color: "#ffffff", margin: 0, fontSize: 24 }}>SPARQL Query Engine</h2>+ <button+ onClick={handleRun}+ disabled={isLoading}+ style={{ background: "#238636", color: "#fff", border: "none", padding: "8px 24px", borderRadius: 6, fontWeight: 600, cursor: "pointer" }}+ >+ {isLoading ? "Running..." : "Run Query"}+ </button>+ </div>++ <div className="glass-panel" style={{ flex: 1, borderRadius: 12, overflow: "hidden", border: "1px solid rgba(88,166,255,0.2)" }}>+ <Editor+ height="100%"+ defaultLanguage="sparql"+ theme="sparql-dark"+ value={query}+ onChange={(v) => setQuery(v || "")}+ beforeMount={handleEditorWillMount}+ onMount={handleEditorDidMount}+ options={{ minimap: { enabled: false }, fontSize: 14, fontFamily: "monospace" }}+ />+ </div>++ <div className="glass-panel" style={{ height: "30%", borderRadius: 12, padding: 16, overflowY: "auto" }}>+ <h3 style={{ color: "#ffffff", margin: "0 0 16px 0", fontSize: 16 }}>Results</h3>+ {result?.error ? (+ <div style={{ color: "#ff7b72" }}>{result.error}</div>+ ) : result?.rows ? (+ <table style={{ width: "100%", borderCollapse: "collapse", color: "#c9d1d9" }}>+ <thead>+ <tr style={{ borderBottom: "1px solid rgba(255,255,255,0.1)" }}>+ {result.columns.map((c: string) => <th key={c} style={{ textAlign: "left", padding: 8 }}>{c}</th>)}+ </tr>+ </thead>+ <tbody>+ {result.rows.map((r: any, i: number) => (+ <tr key={i} style={{ borderBottom: "1px solid rgba(255,255,255,0.05)" }}>+ {result.columns.map((c: string) => <td key={c} style={{ padding: 8 }}>{r[c]}</td>)}+ </tr>+ ))}+ </tbody>+ </table>+ ) : (+ <div style={{ color: "#8b949e" }}>No results to display. Run a query first.</div>+ )}+ </div>+ </div>+ );+}diff --git a/semantica-explorer/src/workspaces/VocabularyWorkspace/VocabularyWorkspace.tsx b/semantica-explorer/src/workspaces/VocabularyWorkspace/VocabularyWorkspace.tsxindex 18d9d21d..7b5376cf 100644--- a/semantica-explorer/src/workspaces/VocabularyWorkspace/VocabularyWorkspace.tsx+++ b/semantica-explorer/src/workspaces/VocabularyWorkspace/VocabularyWorkspace.tsx@@ -1,89 +1,96 @@-import React, { useState } from 'react';-import { ConceptTree } from './ConceptTree';-import { ImportDropzone } from './ImportDropzone';-import { useVocabularies, useConceptHierarchy } from './queries';-import type { VocabularyScheme, ConceptNode } from './types';+import { useState } from 'react';-export const VocabularyWorkspace: React.FC = () => {- const [selectedScheme, setSelectedScheme] = useState<VocabularyScheme | null>(null);- const [selectedConcept, setSelectedConcept] = useState<ConceptNode | null>(null);+const mockVocabularyItems = [+ { id: "skos:Concept", label: "SKOS Concept", desc: "An idea or notion; a unit of thought." },+ { id: "owl:Class", label: "OWL Class", desc: "A category of entities in the domain." },+ { id: "prov:Activity", label: "PROV Activity", desc: "Something that occurs over a period of time and acts upon or with entities." },+ { id: "foaf:Person", label: "FOAF Person", desc: "A human being." }+];- const { data: schemes = [], isLoading: isLoadingSchemes } = useVocabularies();- const { data: hierarchy = [], isLoading: isLoadingTree } = useConceptHierarchy(selectedScheme?.uri);+export function VocabularyWorkspace() {+ const [selectedItem, setSelectedItem] = useState(mockVocabularyItems[0].id);return (- <div style={{ display: 'flex', height: '100vh', width: '100vw', backgroundColor: '#f9fafb' }}>+ <div style={{ display: 'flex', width: '100%', height: '100%', backgroundColor: '#0d1117' }}>- <div style={{ width: '250px', borderRight: '1px solid #e5e7eb', padding: '16px', backgroundColor: 'white' }}>- <h2 style={{ fontSize: '1.2rem', fontWeight: 'bold', marginBottom: '16px' }}>Vocabularies</h2>+ {/* Sidebar: Ontology Tree */}+ <div style={{ width: '320px', borderRight: '1px solid #30363d', backgroundColor: '#010409', display: 'flex', flexDirection: 'column' }}>+ <div style={{ padding: '20px', borderBottom: '1px solid #30363d' }}>+ <h2 style={{ fontSize: '18px', color: '#c9d1d9', margin: 0, fontWeight: 600 }}>Ontology & Vocabulary</h2>+ <p style={{ color: '#8b949e', fontSize: '13px', margin: '8px 0 0 0' }}>Explore SKOS Concepts and OWL Classes</p>+ </div>- {isLoadingSchemes ? (- <p style={{ color: '#6b7280', fontSize: '14px' }}>Loading...</p>- ) : (- <ul style={{ listStyle: 'none', padding: 0 }}>- {schemes.map((scheme) => (- <li- key={scheme.uri}- onClick={() => setSelectedScheme(scheme)}- style={{- padding: '8px',- cursor: 'pointer',- backgroundColor: selectedScheme?.uri === scheme.uri ? '#e0f2fe' : 'transparent',- borderRadius: '4px'- }}- >- {scheme.label}- </li>- ))}- </ul>- )}-- <ImportDropzone />+ <div style={{ flex: 1, padding: '16px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {mockVocabularyItems.map((item) => (+ <button+ key={item.id}+ onClick={() => setSelectedItem(item.id)}+ style={{+ textAlign: 'left',+ padding: '12px',+ borderRadius: '6px',+ backgroundColor: selectedItem === item.id ? 'rgba(88,166,255,0.1)' : 'transparent',+ border: '1px solid',+ borderColor: selectedItem === item.id ? 'rgba(88,166,255,0.4)' : 'transparent',+ color: selectedItem === item.id ? '#58a6ff' : '#c9d1d9',+ cursor: 'pointer',+ transition: 'all 0.2s ease',+ }}+ >+ <div style={{ fontWeight: 600, fontSize: '14px', marginBottom: '4px' }}>{item.label}</div>+ <div style={{ fontSize: '12px', color: '#8b949e' }}>{item.id}</div>+ </button>+ ))}+ </div></div>- <div style={{ flex: 1, borderRight: '1px solid #e5e7eb', padding: '16px', backgroundColor: 'white', display: 'flex', flexDirection: 'column' }}>- <h2 style={{ fontSize: '1.2rem', fontWeight: 'bold', marginBottom: selectedScheme?.description ? '4px' : '16px' }}>- {selectedScheme ? selectedScheme.label : "Select a Vocabulary"}- </h2>+ {/* Main Content Area */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '48px', alignItems: 'center', justifyContent: 'center' }}>- {selectedScheme?.description && (- <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '16px' }}>- {selectedScheme.description}- </p>- )}-- {selectedScheme ? (- isLoadingTree ? (- <p style={{ color: '#6b7280', marginTop: '20px' }}>Loading tree...</p>- ) : (- <ConceptTree- data={hierarchy}- onSelectConcept={setSelectedConcept}- />- )+ {selectedItem ? (+ <div style={{+ width: '100%', maxWidth: '800px', padding: '48px',+ background: 'linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6))',+ backdropFilter: 'blur(16px)',+ borderRadius: '16px',+ border: '1px solid rgba(88,166,255,0.2)',+ boxShadow: '0 8px 32px rgba(0,0,0,0.5)'+ }}>+ <h1 style={{ fontSize: '32px', color: '#fff', margin: '0 0 16px 0' }}>+ {mockVocabularyItems.find(i => i.id === selectedItem)?.label}+ </h1>+ <div style={{ display: 'inline-block', backgroundColor: 'rgba(88,166,255,0.1)', padding: '6px 12px', borderRadius: '4px', color: '#58a6ff', fontSize: '14px', fontFamily: 'monospace', marginBottom: '24px' }}>+ {selectedItem}+ </div>++ <p style={{ color: '#c9d1d9', fontSize: '16px', lineHeight: '1.6', margin: '0 0 32px 0' }}>+ {mockVocabularyItems.find(i => i.id === selectedItem)?.desc}+ </p>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>+ <div style={{ backgroundColor: 'rgba(0,0,0,0.3)', padding: '24px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)' }}>+ <h3 style={{ color: '#8b949e', fontSize: '14px', textTransform: 'uppercase', letterSpacing: '1px', margin: '0 0 16px 0' }}>Broader Concepts</h3>+ <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>+ <span style={{ backgroundColor: '#21262d', padding: '4px 10px', borderRadius: '4px', color: '#c9d1d9', fontSize: '13px' }}>rdf:Resource</span>+ </div>+ </div>+ <div style={{ backgroundColor: 'rgba(0,0,0,0.3)', padding: '24px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.05)' }}>+ <h3 style={{ color: '#8b949e', fontSize: '14px', textTransform: 'uppercase', letterSpacing: '1px', margin: '0 0 16px 0' }}>Narrower Concepts</h3>+ <p style={{ margin: 0, color: '#8b949e', fontStyle: 'italic', fontSize: '14px' }}>No narrower concepts found.</p>+ </div>+ </div>+ </div>) : (- <div style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'center', color: '#9ca3af' }}>- <p>Select a vocabulary from the left to view its hierarchy.</p>+ <div style={{ color: '#8b949e', textAlign: 'center' }}>+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: '16px', opacity: 0.5 }}>+ <path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"></path>+ </svg>+ <h2>Select a vocabulary item</h2>+ <p>Choose an item from the sidebar to view details.</p></div>)}- </div>-- <div style={{ width: '300px', padding: '16px', backgroundColor: 'white' }}>- <h2 style={{ fontSize: '1.2rem', fontWeight: 'bold', marginBottom: '16px' }}>Concept Details</h2>- {selectedConcept ? (- <div>- <h3>{selectedConcept.pref_label}</h3>- <p style={{ fontSize: '14px', color: '#4b5563', marginTop: '8px' }}>URI: {selectedConcept.uri}</p>- <p style={{ fontSize: '14px', color: '#4b5563', marginTop: '8px' }}>- Alt Labels: {selectedConcept.alt_labels?.join(', ') || 'None'}- </p>- </div>- ) : (- <p style={{ color: '#6b7280' }}>Click a node in the tree to view details.</p>- )}</div>-</div>);-};\ No newline at end of file+}\ No newline at end of filediff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex cc1a248e..c8e1be71 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -132,15 +132,31 @@ except ImportError:def _parse_iso_dt(value: str) -> Optional[datetime]:"""Parse an ISO datetime string into a tz-naive UTC datetime.- Always returns a naive datetime in UTC so callers can compare uniformly- without worrying about mixed aware/naive arithmetic.+ Supported formats (in priority order):+ - Year-only shorthand: "1990" → "1990-01-01"+ - Date-only: "1990-06-15"+ - Full ISO (with tz): "1990-06-15T00:00:00+00:00" / "...Z"+ - Full ISO (naive): "1990-06-15T00:00:00"++ Returns None on failure; callers must treat the node as Always-Active."""+ import logging+ import re as _re+ if not value:+ return None+ s = str(value).strip()+ if _re.fullmatch(r"\d{4}", s):+ s = f"{s}-01-01"+ s = s.replace("Z", "+00:00")try:- dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))+ dt = datetime.fromisoformat(s)if dt.tzinfo is not None:dt = dt.astimezone(timezone.utc).replace(tzinfo=None)return dt- except (ValueError, AttributeError):+ except (ValueError, AttributeError) as e:+ logging.getLogger("semantica.context").warning(+ "Malformed temporal value %r — treating node as Always-Active. (%s)", value, e+ )return Nonediff --git a/semantica/explorer/app.py b/semantica/explorer/app.pyindex 8435b3d0..a7b60aa8 100644--- a/semantica/explorer/app.py+++ b/semantica/explorer/app.py@@ -68,9 +68,7 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:@app.exception_handler(Exception)async def generic_error_handler(request: Request, exc: Exception):- # Let FastAPI's built-in HTTPException handler take precedence so that- # responses from dependency injection (e.g. 503 from get_session) are- # not swallowed and converted to 500.+if isinstance(exc, HTTPException):raise excreturn JSONResponse(@@ -85,6 +83,8 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:from .routes.enrich import router as enrich_routerfrom .routes.export_import import router as export_import_routerfrom .routes.annotations import router as annotations_router+ from .routes.sparql import router as sparql_router+ from .routes.provenance import router as provenance_routerapp.include_router(graph_router)app.include_router(analytics_router)@@ -93,6 +93,8 @@ def create_app(session: Optional[GraphSession] = None) -> FastAPI:app.include_router(enrich_router)app.include_router(export_import_router)app.include_router(annotations_router)+ app.include_router(sparql_router)+ app.include_router(provenance_router)from fastapi import WebSocket, WebSocketDisconnectdiff --git a/semantica/explorer/routes/enrich.py b/semantica/explorer/routes/enrich.pyindex ffea3e39..71e866df 100644--- a/semantica/explorer/routes/enrich.py+++ b/semantica/explorer/routes/enrich.py@@ -16,6 +16,8 @@ from ..schemas import (LinkPredictionResponse,ReasoningRequest,ReasoningResponse,+ MergeRequest,+ MergeResponse,)from ..session import GraphSession@@ -68,18 +70,13 @@ async def predict_links(nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)- # Pre-compute already-connected node IDs so we skip them.- # (LinkPredictor._edge_exists returns False for ContextGraph since it has no- # has_edge/get_edge method, so we handle exclusion here instead.)+existing_neighbours = {e.get("target") for e in edges if e.get("source") == body.node_id} | {e.get("source") for e in edges if e.get("target") == body.node_id}- # Score each candidate via score_link (which works with ContextGraph because- # it falls back to has_node / get_neighbors).- # Run in a thread so the CPU-bound scoring loop never blocks the event loop.def _score_all() -> list:results = []for n in nodes:@@ -115,8 +112,6 @@ async def detect_duplicates(from ...deduplication import DuplicateDetectordetector = DuplicateDetector()- # Use asyncio.to_thread — get_nodes acquires an RLock and must not block- # the event loop.nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)entities = [@@ -173,3 +168,60 @@ def _safe_dict(obj) -> dict:if hasattr(obj, "__dict__"):return {k: v for k, v in obj.__dict__.items() if not k.startswith("_")}return {"value": str(obj)}+[email protected]("/api/enrich/merge", response_model=MergeResponse)+async def merge_nodes(+ body: MergeRequest,+ session: GraphSession = Depends(get_session),+):+ """Merge duplicate nodes into a primary node."""+ primary_id = body.primary_id+ duplicate_ids = body.duplicate_ids++ if primary_id not in session.graph:+ raise ValueError(f"Primary node {primary_id} not found")++ edges_updated = 0+ removed_ids = []++ # Get primary node attributes+ primary_attrs = session.graph.nodes[primary_id]++ for dup_id in duplicate_ids:+ if dup_id not in session.graph or dup_id == primary_id:+ continue++ dup_attrs = session.graph.nodes[dup_id]++ primary_props = primary_attrs.setdefault("properties", {})+ dup_props = dup_attrs.get("properties", {})++ for k, v in dup_props.items():+ if k not in primary_props:+ primary_props[k] = v+++ edges_to_add = []+ edges_to_remove = []+ for u, v, attrs in session.graph.edges(dup_id, data=True):+ edges_to_remove.append((u, v))+ new_u = primary_id if u == dup_id else u+ new_v = primary_id if v == dup_id else v+ if new_u != new_v and not session.graph.has_edge(new_u, new_v):+ edges_to_add.append((new_u, new_v, attrs))++ for u, v in edges_to_remove:+ session.graph.remove_edge(u, v)++ for u, v, attrs in edges_to_add:+ session.graph.add_edge(u, v, **attrs)+ edges_updated += 1++ session.graph.remove_node(dup_id)+ removed_ids.append(dup_id)++ return MergeResponse(+ merged_into=primary_id,+ removed_ids=removed_ids,+ edges_updated=edges_updated+ )diff --git a/semantica/explorer/routes/export_import.py b/semantica/explorer/routes/export_import.pyindex 8c7c2e56..63b6afc0 100644--- a/semantica/explorer/routes/export_import.py+++ b/semantica/explorer/routes/export_import.py@@ -2,183 +2,53 @@Export & import routes."""-import asyncio+import csvimport ioimport jsonimport logging-import os-import tempfilefrom typing import Optional-from fastapi import APIRouter, Depends, File, UploadFile+from fastapi import APIRouter, Depends, File, UploadFile, HTTPExceptionfrom fastapi.responses import Responselogger = logging.getLogger(__name__)-from ..dependencies import get_session, get_ws_manager-from ..schemas import ExportRequest+from ..dependencies import get_session+from ..schemas import ExportRequest, ImportResponsefrom ..session import GraphSession-from ..ws import ConnectionManagerrouter = APIRouter(tags=["Export / Import"])-_FORMAT_MAP = {- "json": ("export_json", "application/json", ".json"),- "json-ld": ("export_json", "application/ld+json", ".jsonld"),- "turtle": ("export_rdf", "text/turtle", ".ttl"),- "rdf-xml": ("export_rdf", "application/rdf+xml", ".rdf"),- "n-triples": ("export_rdf", "application/n-triples", ".nt"),- "csv": ("export_csv", "text/csv", ".csv"),- "graphml": ("export_graph", "application/xml", ".graphml"),- "gexf": ("export_graph", "application/xml", ".gexf"),- "owl": ("export_owl", "application/rdf+xml", ".owl"),- "cypher": ("export_lpg", "text/plain", ".cypher"),- "aql": ("export_arango", "text/plain", ".aql"),- "yaml": ("export_yaml", "text/yaml", ".yaml"),-}---def _build_kg_dict(session: GraphSession, node_ids: Optional[list] = None) -> dict:- """Build the knowledge-graph dict that exporters expect."""- nodes, _ = session.get_nodes(skip=0, limit=999_999)- edges, _ = session.get_edges(skip=0, limit=999_999)-- if node_ids:- id_set = set(node_ids)- nodes = [n for n in nodes if n.get("id") in id_set]- edges = [- e for e in edges- if e.get("source") in id_set and e.get("target") in id_set- ]-- return {- "entities": [- {- "id": n.get("id"),- "type": n.get("type", "entity"),- "text": n.get("content", n.get("id", "")),- "metadata": n.get("metadata", {}),- }- for n in nodes- ],- "relationships": [- {- "source": e.get("source"),- "target": e.get("target"),- "type": e.get("type", "related_to"),- "metadata": e.get("metadata", {}),- }- for e in edges- ],- }--[email protected]("/api/export")-async def export_graph(- body: ExportRequest,- session: GraphSession = Depends(get_session),-):- """Export the current graph in the requested format."""- fmt = body.format.lower()- if fmt not in _FORMAT_MAP:- raise ValueError(- f"Unsupported format '{fmt}'. Supported: {', '.join(sorted(_FORMAT_MAP))}"- )-- func_name, content_type, ext = _FORMAT_MAP[fmt]-- kg = await asyncio.to_thread(_build_kg_dict, session, body.node_ids)-- kg = await asyncio.to_thread(session.build_graph_dict, body.node_ids)-- try:- from ...export.methods import (- export_json, export_rdf, export_csv, export_graph as export_graph_fn,- export_owl, export_lpg, export_arango, export_yaml,- )- fn_map = {- "export_json": export_json,- "export_rdf": export_rdf,- "export_csv": export_csv,- "export_graph": export_graph_fn,- "export_owl": export_owl,- "export_lpg": export_lpg,- "export_arango": export_arango,- "export_yaml": export_yaml,- }- export_fn = fn_map.get(func_name)- if export_fn is None:- raise ValueError(f"Export function {func_name} not found.")-- # Write to a temp file, read back content.- with tempfile.NamedTemporaryFile(suffix=ext, delete=False, mode="w") as tmp:- tmp_path = tmp.name-- await asyncio.to_thread(export_fn, kg, tmp_path)-- with open(tmp_path, "r", encoding="utf-8", errors="replace") as fh:- content = fh.read()-- import os- os.unlink(tmp_path)-- except ImportError:-- # Write to a temp file; always clean up even if export or read fails.- tmp_path = None- try:- with tempfile.NamedTemporaryFile(suffix=ext, delete=False, mode="w") as tmp:- tmp_path = tmp.name-- await asyncio.to_thread(export_fn, kg, tmp_path)-- with open(tmp_path, "r", encoding="utf-8", errors="replace") as fh:- content = fh.read()- finally:- if tmp_path and os.path.exists(tmp_path):- os.unlink(tmp_path)-- except ImportError:- content = json.dumps(kg, indent=2, default=str)- content_type = "application/json"- ext = ".json"-- filename = f"semantica_export{ext}"- return Response(- content=content,- media_type=content_type,- headers={"Content-Disposition": f'attachment; filename="{filename}"'},- )--[email protected]("/api/import")[email protected]("/api/import", response_model=ImportResponse)async def import_file(file: UploadFile = File(...),- session: GraphSession = Depends(get_session),- ws: ConnectionManager = Depends(get_ws_manager),+ session: GraphSession = Depends(get_session)):"""- Import entities from an uploaded file (JSON or CSV).-- For JSON files the expected shape is ``{"nodes": [...], "edges": [...]}``.+ Import entities and edges from an uploaded JSON or CSV file."""content = await file.read()- filename = file.filename or "upload"+ filename = file.filename or ""- await ws.broadcast("import_started", {"filename": filename})-- try:- if filename.endswith(".json") or filename.endswith(".jsonld"):+ if filename.endswith(".json"):+ try:data = json.loads(content)--- raw_nodes = data.get("nodes", data.get("entities", []))- raw_edges = data.get("edges", data.get("relationships", []))--- # KG export uses {id, type, text, metadata}- # ContextGraph.add_nodes expects {id, type, properties: {content, ...}}++ if isinstance(data, list):+ if len(data) > 0 and ("source" in data[0] or "source_id" in data[0]):+ raw_edges = data+ raw_nodes = []+ else:+ raw_nodes = data+ raw_edges = []+ elif isinstance(data, dict):+ raw_nodes = data.get("nodes", data.get("entities", []))+ raw_edges = data.get("edges", data.get("relationships", []))+ else:+ raw_nodes = []+ raw_edges = []+nodes = []for n in raw_nodes:if "properties" in n:@@ -189,50 +59,137 @@ async def import_file("type": n.get("type", "entity"),"properties": {"content": n.get("text", n.get("content", n.get("id", ""))),- **(n.get("metadata") or {}),- },+ **(n.get("metadata", {}))+ }})-- # KG export uses {source, target, type, metadata}- # ContextGraph.add_edges expects {source_id, target_id, type, weight, properties}+edges = []for r in raw_edges:src = r.get("source_id", r.get("source"))tgt = r.get("target_id", r.get("target"))if not src or not tgt:- continue+ continueedges.append({"source_id": src,"target_id": tgt,"type": r.get("type", "related_to"),"weight": r.get("weight", 1.0),- "properties": r.get("metadata") or r.get("properties") or {},+ "properties": r.get("metadata", r.get("properties", {}))})- nodes = data.get("nodes", data.get("entities", []))- edges = data.get("edges", data.get("relationships", []))-- for edge in edges:- if "source" in edge and "source_id" not in edge:- edge["source_id"] = edge["source"]- if "target" in edge and "target_id" not in edge:- edge["target_id"] = edge["target"]++ nodes_added = session.add_nodes(nodes)+ edges_added = session.add_edges(edges)++ return ImportResponse(nodes_imported=nodes_added, edges_imported=edges_added)++ except json.JSONDecodeError as e:+ raise HTTPException(status_code=422, detail=f"Invalid JSON file: {str(e)}")+ except Exception as e:+ logger.exception("Import JSON failed")+ raise HTTPException(status_code=500, detail=str(e))++ elif filename.endswith(".csv"):+ try:+ # Parse CSV content+ decoded_content = content.decode("utf-8-sig")+ reader = csv.DictReader(io.StringIO(decoded_content))++ nodes = []+ edges = []++ for row in reader:+ # Basic mapping attempts based on standard column names+ # Try to find source and target for edges+ src = row.get("source") or row.get("source_id")+ tgt = row.get("target") or row.get("target_id")++ # Try to find node identity+ node_id = row.get("id") or row.get("node_id")++ # If we have both source and target, we assume it's an edge+ if src and tgt:+ edges.append({+ "source_id": src,+ "target_id": tgt,+ "type": row.get("type", row.get("relationship", "related_to")),+ "weight": float(row.get("weight", 1.0)),+ "properties": {k: v for k, v in row.items() if k not in ("source", "source_id", "target", "target_id", "type", "relationship", "weight")}+ })+ # If we have a node id, we assume it's a node+ elif node_id:+ nodes.append({+ "id": node_id,+ "type": row.get("type", "entity"),+ "properties": {k: v for k, v in row.items() if k not in ("id", "node_id", "type")}+ })++ nodes_added = session.add_nodes(nodes)+ edges_added = session.add_edges(edges)++ return ImportResponse(nodes_imported=nodes_added, edges_imported=edges_added)++ except UnicodeDecodeError:+ raise HTTPException(status_code=422, detail="CSV file must be UTF-8 encoded")+ except Exception as e:+ logger.exception("Import CSV failed")+ raise HTTPException(status_code=500, detail=str(e))++ else:+ raise HTTPException(status_code=422, detail=f"Unsupported file type. Please upload a .json or .csv file.")- added_nodes = await asyncio.to_thread(session.add_nodes, nodes)- added_edges = await asyncio.to_thread(session.add_edges, edges)- result = {- "status": "success",- "nodes_added": added_nodes,- "edges_added": added_edges,- }- else:- result = {- "status": "unsupported",- "detail": f"File type not supported yet: {filename}",- }- except Exception as exc:- logger.exception("Import failed")- result = {"status": "error", "detail": "An internal error occurred during import"}[email protected]("/api/export")+async def export_graph(+ body: ExportRequest,+ session: GraphSession = Depends(get_session),+):+ """Export the current graph in the requested format."""+ fmt = body.format.lower()++ kg = session.build_graph_dict(body.node_ids)++ if fmt == "json":+ content = json.dumps(kg, indent=2, default=str)+ content_type = "application/json"+ ext = ".json"++ elif fmt == "csv":+ # Create an in-memory CSV map+ output = io.StringIO()+ writer = csv.writer(output)++ # Write Nodes+ writer.writerow(["--- NODES ---"])+ writer.writerow(["id", "type", "content"])+ # Use nodes mapping properly from build_graph_dict which is ContextGraph native object map+ # Or standard {"entities":[], "relationships":[]} format based on how session.build_graph_dict is returning things+ # session.build_graph_dict normally returns dict of the graph store structure. Let's gracefully read it.+ nodes = kg.get("nodes", kg.get("entities", []))+ for n in nodes:+ props = n.get("properties", n.get("metadata", {}))+ content_val = n.get("content", n.get("text", props.get("content", "")))+ writer.writerow([n.get("id"), n.get("type", "entity"), content_val])++ # Write Edges+ writer.writerow([])+ writer.writerow(["--- EDGES ---"])+ writer.writerow(["source", "target", "type", "weight"])+ edges = kg.get("edges", kg.get("relationships", []))+ for e in edges:+ src = e.get("source_id", e.get("source"))+ tgt = e.get("target_id", e.get("target"))+ writer.writerow([src, tgt, e.get("type", "related_to"), e.get("weight", 1.0)])++ content = output.getvalue()+ content_type = "text/csv"+ ext = ".csv"++ else:+ raise HTTPException(status_code=422, detail=f"Unsupported export format '{fmt}'")- await ws.broadcast("import_completed", result)- return result+ filename = f"semantica_export{ext}"+ return Response(+ content=content,+ media_type=content_type,+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},+ )diff --git a/semantica/explorer/routes/provenance.py b/semantica/explorer/routes/provenance.pynew file mode 100644index 00000000..94cdde39--- /dev/null+++ b/semantica/explorer/routes/provenance.py@@ -0,0 +1,69 @@+from fastapi import APIRouter, HTTPException+from pydantic import BaseModel+from typing import List, Dict, Any+from semantica.explorer.session import get_session++router = APIRouter(prefix="/provenance", tags=["Power User Tools"])++class ProvenanceRequest(BaseModel):+ session_id: str++class ProvenanceNode(BaseModel):+ id: str+ label: str+ prov_type: str+ parent_id: str++class ProvenanceEdge(BaseModel):+ id: str+ source: str+ target: str+ label: str++class ProvenanceResponse(BaseModel):+ nodes: List[ProvenanceNode]+ edges: List[ProvenanceEdge]+[email protected]("", response_model=ProvenanceResponse)+def get_provenance_lineage(req: ProvenanceRequest):+ session = get_session(req.session_id)+ if not session:+ raise HTTPException(status_code=404, detail="Session not found")++ prov_nodes = []+ prov_edges = []+++ for node_id, attrs in session.graph.nodes(data=True):+ node_type = attrs.get("nodeType", "").lower()+++ if node_type in ["person", "organization", "system", "agent"]:+ prov_type = "Agent"+ parent_id = "group_agent"+ elif node_type in ["action", "event", "process", "activity", "decision"]:+ prov_type = "Activity"+ parent_id = "group_activity"+ else:+ prov_type = "Entity"+ parent_id = "group_entity"++ prov_nodes.append(ProvenanceNode(+ id=str(node_id),+ label=str(attrs.get("label", node_id)),+ prov_type=prov_type,+ parent_id=parent_id+ ))++ for u, v, attrs in session.graph.edges(data=True):+ prov_edges.append(ProvenanceEdge(+ id=f"{u}-{v}",+ source=str(u),+ target=str(v),+ label=str(attrs.get("relationship", ""))+ ))++ return ProvenanceResponse(+ nodes=prov_nodes,+ edges=prov_edges+ )diff --git a/semantica/explorer/routes/sparql.py b/semantica/explorer/routes/sparql.pynew file mode 100644index 00000000..f2fb5432--- /dev/null+++ b/semantica/explorer/routes/sparql.py@@ -0,0 +1,86 @@+from fastapi import APIRouter, HTTPException+from pydantic import BaseModel+from typing import List, Dict, Any, Optional+import rdflib+import re+from loguru import logger+from semantica.explorer.session import get_session++router = APIRouter(prefix="/sparql", tags=["Power User Tools"])++class SparqlRequest(BaseModel):+ query: str+ session_id: str++class SparqlResponse(BaseModel):+ columns: List[str]+ rows: List[Dict[str, Any]]+ total: int+ error: Optional[str] = None+ error_line: Optional[int] = None+ error_column: Optional[int] = None+[email protected]("", response_model=SparqlResponse)+def execute_sparql(req: SparqlRequest):+ session = get_session(req.session_id)+ if not session:+ raise HTTPException(status_code=404, detail="Session not found")+++ g = rdflib.Graph()+ NS = rdflib.Namespace("http://semantica.local/entity/")+ PROP = rdflib.Namespace("http://semantica.local/prop/")++ for node_id, attrs in session.graph.nodes(data=True):+ subject = NS[str(node_id)]+ g.add((subject, rdflib.RDF.type, NS[attrs.get('nodeType', 'Entity')]))++ properties = attrs.get('properties', {})+ for k, v in properties.items():+ g.add((subject, PROP[k], rdflib.Literal(v)))++ for u, v, attrs in session.graph.edges(data=True):+ subject = NS[str(u)]+ object_ = NS[str(v)]+ g.add((subject, PROP[attrs.get('relationship', 'relatedTo')], object_))++ try:+ qres = g.query(req.query)+ columns = [str(var) for var in qres.vars] if qres.vars else []+ rows = []+ for row in qres:+ row_dict = {}+ for idx, col in enumerate(columns):+ val = row[idx]+ row_dict[col] = str(val) if val else None+ rows.append(row_dict)++ return SparqlResponse(+ columns=columns,+ rows=rows,+ total=len(rows)+ )+ except Exception as e:+ error_str = str(e)+ logger.error(f"SPARQL execution error: {error_str}")++ error_line = None+ error_column = None+++ line_match = re.search(r'line[\s:]+(\d+)', error_str, re.IGNORECASE)+ col_match = re.search(r'col(?:umn)?[\s:]+(\d+)', error_str, re.IGNORECASE)++ if line_match:+ error_line = int(line_match.group(1))+ if col_match:+ error_column = int(col_match.group(1))++ return SparqlResponse(+ columns=[],+ rows=[],+ total=0,+ error=error_str,+ error_line=error_line,+ error_column=error_column+ )diff --git a/semantica/explorer/routes/temporal.py b/semantica/explorer/routes/temporal.pyindex d0ac0149..916b8af8 100644--- a/semantica/explorer/routes/temporal.py+++ b/semantica/explorer/routes/temporal.py@@ -1,61 +1,142 @@"""Temporal routes — snapshot, diff, patterns.++Hardened for production with:+- Multi-format ISO 8601 date parsing (YYYY, YYYY-MM-DD, full ISO strings)+- Optimized /snapshot that returns only node IDs (not full objects)+ to minimize JSON payload during high-speed scrubbing+- Graceful fallback for malformed dates (node becomes "Always Active")"""import asyncio+import logging+import refrom datetime import datetime, timezone-from typing import Optional+from typing import List, Optionalfrom fastapi import APIRouter, Depends, Query+from pydantic import BaseModelfrom ..dependencies import get_sessionfrom ..schemas import (- NodeResponse,TemporalDiffResponse,TemporalPatternResponse,- TemporalSnapshotResponse,)from ..session import GraphSession+logger = logging.getLogger(__name__)+router = APIRouter(prefix="/api/temporal", tags=["Temporal"])-def _node_dict_to_response(n: dict) -> NodeResponse:- meta = n.get("metadata", {})- return NodeResponse(- id=n.get("id", ""),- type=n.get("type", "entity"),- content=n.get("content", meta.get("content", "")),- properties=meta,- valid_from=meta.get("valid_from"),- valid_until=meta.get("valid_until"),- )+class TemporalSnapshotFastResponse(BaseModel):+ """Lightweight snapshot: returns only active node IDs for fast scrubbing."""+ timestamp: str+ active_node_ids: List[str]+ active_node_count: int++++def _parse_flexible_dt(value: str) -> Optional[datetime]:+ """+ Parse multiple ISO 8601 formats into a tz-naive UTC datetime.++ Supported formats (in priority order):+ - Full ISO with timezone: "1990-01-15T00:00:00+00:00" / "...Z"+ - Full ISO without tz: "1990-01-15T00:00:00"+ - Date only: "1990-01-15"+ - Year only: "1990"++ Returns None if parsing fails (caller should treat node as Always-Active).+ """+ if not value:+ return None++ s = str(value).strip()++ if re.fullmatch(r"\d{4}", s):+ s = f"{s}-01-01"+++ s = s.replace("Z", "+00:00")++ try:+ dt = datetime.fromisoformat(s)+ if dt.tzinfo is not None:+ dt = dt.astimezone(timezone.utc).replace(tzinfo=None)+ return dt+ except (ValueError, AttributeError) as exc:+ logger.warning(+ "Malformed temporal value %r — treating node as Always-Active. (%s)", value, exc+ )+ return None+++def _parse_query_dt(value: str) -> datetime:+ """Parse the at= query parameter. Falls back to utcnow() on failure."""+ dt = _parse_flexible_dt(value)+ if dt is None:+ logger.warning("Could not parse query timestamp %r — defaulting to utcnow()", value)+ return datetime.utcnow()+ return dt+++def _node_is_active(node: dict, at_time: datetime) -> bool:+ """+ Check temporal activity with multi-format date support.++ Logic: valid_from <= at_time AND (valid_until IS NULL OR valid_until >= at_time)+ A node with no temporal bounds at all is always active.+ A node with a malformed date on either bound is always active.+ """+ meta = node.get("metadata", {})++ raw_from = node.get("valid_from") or meta.get("valid_from")+ raw_until = node.get("valid_until") or meta.get("valid_until")+++ if raw_from is None and raw_until is None:+ return True++ valid_from = _parse_flexible_dt(raw_from) if raw_from else None+ valid_until = _parse_flexible_dt(raw_until) if raw_until else None[email protected]("/snapshot", response_model=TemporalSnapshotResponse)+ if valid_from is not None and at_time < valid_from:+ return False+ if valid_until is not None and at_time > valid_until:+ return False++ return True++# Routes+[email protected]("/snapshot", response_model=TemporalSnapshotFastResponse)async def temporal_snapshot(at: Optional[str] = Query(- None, description="ISO-8601 datetime; defaults to now."+ None, description="ISO-8601 datetime or year (e.g. '1990' or '1990-06-15T00:00:00Z'); defaults to now."),session: GraphSession = Depends(get_session),):"""- Return the graph as it existed at a given timestamp.+ Return the set of node IDs that are active at the given timestamp.- Only nodes whose ``valid_from`` / ``valid_until`` window includes- the requested time are returned.+ This endpoint is optimised for high-frequency scrubbing: instead of sending+ full node objects it sends only a flat list of active IDs. The frontend+ reconciles visibility directly on the sigma.js WebGL graph without any+ React state updates."""- if at:- ts_str = at.replace("Z", "+00:00")- at_time = datetime.fromisoformat(ts_str)- else:- at_time = datetime.now(timezone.utc)+ at_time = _parse_query_dt(at) if at else datetime.utcnow()+ # Pull lightweight active list from the sessionactive = await asyncio.to_thread(session.get_active_nodes, at_time=at_time)- return TemporalSnapshotResponse(++ active_ids = [n["id"] for n in active if n.get("id")]++ return TemporalSnapshotFastResponse(timestamp=at_time.isoformat(),- active_nodes=[_node_dict_to_response(n) for n in active],- active_node_count=len(active),+ active_node_ids=active_ids,+ active_node_count=len(active_ids),)@@ -72,11 +153,13 @@ async def temporal_diff(``from_time``) and removed (active at ``from_time`` but not``to_time``)."""- t1 = datetime.fromisoformat(from_time.replace("Z", "+00:00"))- t2 = datetime.fromisoformat(to_time.replace("Z", "+00:00"))+ t1 = _parse_query_dt(from_time)+ t2 = _parse_query_dt(to_time)- active_t1 = await asyncio.to_thread(session.get_active_nodes, at_time=t1)- active_t2 = await asyncio.to_thread(session.get_active_nodes, at_time=t2)+ active_t1, active_t2 = await asyncio.gather(+ asyncio.to_thread(session.get_active_nodes, at_time=t1),+ asyncio.to_thread(session.get_active_nodes, at_time=t2),+ )ids_t1 = {n.get("id") for n in active_t1}ids_t2 = {n.get("id") for n in active_t2}@@ -102,7 +185,6 @@ async def temporal_patterns(from ...kg import TemporalPatternDetectordetector = TemporalPatternDetector()-nodes, _ = await asyncio.to_thread(session.get_nodes, skip=0, limit=999_999)edges, _ = await asyncio.to_thread(session.get_edges, skip=0, limit=999_999)graph_dict = {@@ -122,9 +204,7 @@ async def temporal_patterns(patterns = patterns.get("patterns", [])return TemporalPatternResponse(patterns=patterns if isinstance(patterns, list) else [])except ImportError:- # TemporalPatternDetector is an optional KG extra; return empty gracefully.return TemporalPatternResponse(patterns=[])except Exception as exc:- import logging- logging.getLogger(__name__).warning("temporal_patterns failed: %s", exc, exc_info=True)+ logger.warning("temporal_patterns failed: %s", exc, exc_info=True)return TemporalPatternResponse(patterns=[])diff --git a/semantica/explorer/schemas.py b/semantica/explorer/schemas.pyindex 6e7fbc09..73a95a1d 100644--- a/semantica/explorer/schemas.py+++ b/semantica/explorer/schemas.py@@ -237,6 +237,18 @@ class ExportResponse(BaseModel):size_bytes: int = 0+class ImportResponse(BaseModel):+ """Response after successful import."""+ nodes_imported: int+ edges_imported: int+ message: str = "Import successful"++class StandardMessageResponse(BaseModel):+ """Standard generic success/error response."""+ status: str+ message: str++class AnnotationCreate(BaseModel):@@ -270,5 +282,14 @@ class ConceptNode(BaseModel):pref_label: stralt_labels: List[str] = Field(default_factory=list)children: Optional[List['ConceptNode']] = None--++class MergeRequest(BaseModel):+ """Merge duplicate entities request."""+ primary_id: str+ duplicate_ids: List[str]++class MergeResponse(BaseModel):+ """Merge duplicate entities response."""+ merged_into: str+ removed_ids: List[str]+ edges_updated: int