Add Cortex Portal — web visualization for knowledge graph
Express API server wrapping existing store/graph core with REST endpoints for nodes, edges, graph, and search. React + Vite portal with React Flow for interactive graph visualization, Tailwind CSS styling, and full CRUD UI (sidebar, node panel, add/link modals, search bar, toast notifications).
This commit is contained in:
918
package-lock.json
generated
918
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,8 @@
|
|||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"dev": "tsc --watch"
|
"dev": "tsc --watch",
|
||||||
|
"serve": "node dist/server/index.js"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
@@ -17,10 +18,14 @@
|
|||||||
"better-sqlite3": "^12.6.2",
|
"better-sqlite3": "^12.6.2",
|
||||||
"chalk": "^4.1.2",
|
"chalk": "^4.1.2",
|
||||||
"commander": "^14.0.3",
|
"commander": "^14.0.3",
|
||||||
|
"cors": "^2.8.6",
|
||||||
|
"express": "^5.2.1",
|
||||||
"uuid": "^13.0.0"
|
"uuid": "^13.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/better-sqlite3": "^7.6.13",
|
"@types/better-sqlite3": "^7.6.13",
|
||||||
|
"@types/cors": "^2.8.19",
|
||||||
|
"@types/express": "^5.0.6",
|
||||||
"@types/node": "^25.2.0",
|
"@types/node": "^25.2.0",
|
||||||
"@types/uuid": "^10.0.0",
|
"@types/uuid": "^10.0.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
|
|||||||
12
portal/index.html
Normal file
12
portal/index.html
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Cortex Portal</title>
|
||||||
|
</head>
|
||||||
|
<body class="bg-gray-950 text-gray-100">
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
2681
portal/package-lock.json
generated
Normal file
2681
portal/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
26
portal/package.json
Normal file
26
portal/package.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "cortex-portal",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tanstack/react-query": "^5.62.0",
|
||||||
|
"@xyflow/react": "^12.4.0",
|
||||||
|
"react": "^19.0.0",
|
||||||
|
"react-dom": "^19.0.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.0.0",
|
||||||
|
"@types/react": "^19.0.0",
|
||||||
|
"@types/react-dom": "^19.0.0",
|
||||||
|
"tailwindcss": "^4.0.0",
|
||||||
|
"typescript": "^5.9.0",
|
||||||
|
"vite": "^6.0.0",
|
||||||
|
"@vitejs/plugin-react": "^4.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
62
portal/src/App.tsx
Normal file
62
portal/src/App.tsx
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
|
import GraphView from './components/GraphView';
|
||||||
|
import Sidebar from './components/Sidebar';
|
||||||
|
import NodePanel from './components/NodePanel';
|
||||||
|
import AddNodeModal from './components/AddNodeModal';
|
||||||
|
import LinkModal from './components/LinkModal';
|
||||||
|
import Toast from './components/Toast';
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
|
const [showAddNode, setShowAddNode] = useState(false);
|
||||||
|
const [linkFromId, setLinkFromId] = useState<string | null>(null);
|
||||||
|
const [toast, setToast] = useState<string | null>(null);
|
||||||
|
const qc = useQueryClient();
|
||||||
|
|
||||||
|
const refresh = useCallback(() => {
|
||||||
|
qc.invalidateQueries({ queryKey: ['graph'] });
|
||||||
|
qc.invalidateQueries({ queryKey: ['nodes'] });
|
||||||
|
}, [qc]);
|
||||||
|
|
||||||
|
const notify = useCallback((msg: string) => {
|
||||||
|
setToast(msg);
|
||||||
|
setTimeout(() => setToast(null), 3000);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen w-screen overflow-hidden">
|
||||||
|
<Sidebar
|
||||||
|
selectedId={selectedId}
|
||||||
|
onSelect={setSelectedId}
|
||||||
|
onAddNode={() => setShowAddNode(true)}
|
||||||
|
/>
|
||||||
|
<div className="flex-1 relative">
|
||||||
|
<GraphView selectedId={selectedId} onSelect={setSelectedId} />
|
||||||
|
</div>
|
||||||
|
{selectedId && (
|
||||||
|
<NodePanel
|
||||||
|
nodeId={selectedId}
|
||||||
|
onClose={() => setSelectedId(null)}
|
||||||
|
onLink={(id) => setLinkFromId(id)}
|
||||||
|
onRefresh={refresh}
|
||||||
|
onNotify={notify}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{showAddNode && (
|
||||||
|
<AddNodeModal
|
||||||
|
onClose={() => setShowAddNode(false)}
|
||||||
|
onCreated={() => { refresh(); notify('Node created'); }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{linkFromId && (
|
||||||
|
<LinkModal
|
||||||
|
fromId={linkFromId}
|
||||||
|
onClose={() => setLinkFromId(null)}
|
||||||
|
onCreated={() => { refresh(); notify('Edge created'); }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{toast && <Toast message={toast} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
44
portal/src/api.ts
Normal file
44
portal/src/api.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import type { CortexNode, CortexEdge, GraphData, NodeWithConnections, SearchResult, NodeKind, EdgeType } from './types';
|
||||||
|
|
||||||
|
const BASE = '/api';
|
||||||
|
|
||||||
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
...init,
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(body.error || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
listNodes: (params?: { kind?: string; status?: string; tags?: string }) =>
|
||||||
|
request<CortexNode[]>(`/nodes?${new URLSearchParams(params as any || {})}`),
|
||||||
|
|
||||||
|
getNode: (id: string) =>
|
||||||
|
request<NodeWithConnections>(`/nodes/${id}`),
|
||||||
|
|
||||||
|
addNode: (body: { kind: NodeKind; title: string; content?: string; status?: string; tags?: string[] }) =>
|
||||||
|
request<CortexNode>('/nodes', { method: 'POST', body: JSON.stringify(body) }),
|
||||||
|
|
||||||
|
updateNode: (id: string, body: Record<string, any>) =>
|
||||||
|
request<CortexNode>(`/nodes/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||||
|
|
||||||
|
deleteNode: (id: string, hard = false) =>
|
||||||
|
request<{ ok: boolean }>(`/nodes/${id}?hard=${hard}`, { method: 'DELETE' }),
|
||||||
|
|
||||||
|
addEdge: (body: { fromId: string; toId: string; type: EdgeType }) =>
|
||||||
|
request<CortexEdge>('/edges', { method: 'POST', body: JSON.stringify(body) }),
|
||||||
|
|
||||||
|
deleteEdge: (id: string) =>
|
||||||
|
request<{ ok: boolean }>(`/edges/${id}`, { method: 'DELETE' }),
|
||||||
|
|
||||||
|
getGraph: () =>
|
||||||
|
request<GraphData>('/graph'),
|
||||||
|
|
||||||
|
search: (text: string, options?: Record<string, any>) =>
|
||||||
|
request<SearchResult[]>('/search', { method: 'POST', body: JSON.stringify({ text, options }) }),
|
||||||
|
};
|
||||||
2
portal/src/app.css
Normal file
2
portal/src/app.css
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@import "@xyflow/react/dist/style.css";
|
||||||
84
portal/src/components/AddNodeModal.tsx
Normal file
84
portal/src/components/AddNodeModal.tsx
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { api } from '../api';
|
||||||
|
import type { NodeKind } from '../types';
|
||||||
|
|
||||||
|
const KINDS: NodeKind[] = ['memory', 'component', 'task', 'decision'];
|
||||||
|
|
||||||
|
export default function AddNodeModal({
|
||||||
|
onClose,
|
||||||
|
onCreated,
|
||||||
|
}: {
|
||||||
|
onClose: () => void;
|
||||||
|
onCreated: () => void;
|
||||||
|
}) {
|
||||||
|
const [kind, setKind] = useState<NodeKind>('task');
|
||||||
|
const [title, setTitle] = useState('');
|
||||||
|
const [content, setContent] = useState('');
|
||||||
|
const [status, setStatus] = useState('');
|
||||||
|
const [tags, setTags] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
if (!title.trim()) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
await api.addNode({
|
||||||
|
kind,
|
||||||
|
title,
|
||||||
|
content: content || undefined,
|
||||||
|
status: status || undefined,
|
||||||
|
tags: tags ? tags.split(',').map(t => t.trim()) : undefined,
|
||||||
|
});
|
||||||
|
onCreated();
|
||||||
|
onClose();
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
|
||||||
|
<div className="bg-gray-900 border border-gray-700 rounded-lg p-6 w-96" onClick={e => e.stopPropagation()}>
|
||||||
|
<h2 className="text-lg font-semibold text-white mb-4">Add Node</h2>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Kind</label>
|
||||||
|
<div className="flex gap-2 mt-1">
|
||||||
|
{KINDS.map(k => (
|
||||||
|
<button
|
||||||
|
key={k}
|
||||||
|
onClick={() => setKind(k)}
|
||||||
|
className={`px-3 py-1 text-xs rounded ${kind === k ? 'bg-indigo-600 text-white' : 'bg-gray-800 text-gray-400'}`}
|
||||||
|
>
|
||||||
|
{k}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Title</label>
|
||||||
|
<input value={title} onChange={e => setTitle(e.target.value)} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Content</label>
|
||||||
|
<textarea value={content} onChange={e => setContent(e.target.value)} rows={3} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1 resize-none" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Status</label>
|
||||||
|
<input value={status} onChange={e => setStatus(e.target.value)} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1" placeholder="e.g. todo, in-progress, done" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Tags (comma-separated)</label>
|
||||||
|
<input value={tags} onChange={e => setTags(e.target.value)} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 mt-5">
|
||||||
|
<button onClick={onClose} className="flex-1 py-2 bg-gray-800 text-gray-400 rounded text-sm">Cancel</button>
|
||||||
|
<button onClick={submit} disabled={loading || !title.trim()} className="flex-1 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded text-sm font-medium">
|
||||||
|
{loading ? 'Creating...' : 'Create'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
107
portal/src/components/GraphView.tsx
Normal file
107
portal/src/components/GraphView.tsx
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
import { useMemo, useCallback } from 'react';
|
||||||
|
import {
|
||||||
|
ReactFlow,
|
||||||
|
MiniMap,
|
||||||
|
Controls,
|
||||||
|
Background,
|
||||||
|
useNodesState,
|
||||||
|
useEdgesState,
|
||||||
|
type Node as FlowNode,
|
||||||
|
type Edge as FlowEdge,
|
||||||
|
} from '@xyflow/react';
|
||||||
|
import { useGraph } from '../hooks/useGraph';
|
||||||
|
import type { CortexNode } from '../types';
|
||||||
|
|
||||||
|
const KIND_COLORS: Record<string, string> = {
|
||||||
|
memory: '#6366f1',
|
||||||
|
component: '#22c55e',
|
||||||
|
task: '#f59e0b',
|
||||||
|
decision: '#ef4444',
|
||||||
|
};
|
||||||
|
|
||||||
|
function layoutNodes(nodes: CortexNode[]): FlowNode[] {
|
||||||
|
const cols = Math.max(Math.ceil(Math.sqrt(nodes.length)), 1);
|
||||||
|
return nodes.map((n, i) => ({
|
||||||
|
id: n.id,
|
||||||
|
position: { x: (i % cols) * 280 + 50, y: Math.floor(i / cols) * 140 + 50 },
|
||||||
|
data: { label: n.title, kind: n.kind, status: n.status },
|
||||||
|
style: {
|
||||||
|
background: KIND_COLORS[n.kind] || '#6b7280',
|
||||||
|
color: '#fff',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: '12px 16px',
|
||||||
|
fontSize: 13,
|
||||||
|
fontWeight: 500,
|
||||||
|
minWidth: 160,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function GraphView({
|
||||||
|
selectedId,
|
||||||
|
onSelect,
|
||||||
|
}: {
|
||||||
|
selectedId: string | null;
|
||||||
|
onSelect: (id: string) => void;
|
||||||
|
}) {
|
||||||
|
const { data, isLoading } = useGraph();
|
||||||
|
|
||||||
|
const initialNodes = useMemo(() => (data ? layoutNodes(data.nodes) : []), [data]);
|
||||||
|
const initialEdges = useMemo<FlowEdge[]>(
|
||||||
|
() =>
|
||||||
|
data
|
||||||
|
? data.edges.map((e) => ({
|
||||||
|
id: e.id,
|
||||||
|
source: e.fromId,
|
||||||
|
target: e.toId,
|
||||||
|
label: e.type,
|
||||||
|
animated: e.type === 'blocked_by',
|
||||||
|
style: { stroke: '#64748b' },
|
||||||
|
labelStyle: { fill: '#94a3b8', fontSize: 11 },
|
||||||
|
}))
|
||||||
|
: [],
|
||||||
|
[data],
|
||||||
|
);
|
||||||
|
|
||||||
|
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
|
||||||
|
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
|
||||||
|
|
||||||
|
// Sync when data changes
|
||||||
|
useMemo(() => {
|
||||||
|
setNodes(initialNodes);
|
||||||
|
setEdges(initialEdges);
|
||||||
|
}, [initialNodes, initialEdges, setNodes, setEdges]);
|
||||||
|
|
||||||
|
const onNodeClick = useCallback(
|
||||||
|
(_: any, node: FlowNode) => onSelect(node.id),
|
||||||
|
[onSelect],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-full text-gray-400">
|
||||||
|
Loading graph...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ReactFlow
|
||||||
|
nodes={nodes}
|
||||||
|
edges={edges}
|
||||||
|
onNodesChange={onNodesChange}
|
||||||
|
onEdgesChange={onEdgesChange}
|
||||||
|
onNodeClick={onNodeClick}
|
||||||
|
fitView
|
||||||
|
className="bg-gray-950"
|
||||||
|
>
|
||||||
|
<Background color="#334155" gap={20} />
|
||||||
|
<Controls className="!bg-gray-800 !border-gray-700 [&>button]:!bg-gray-800 [&>button]:!border-gray-700 [&>button]:!text-gray-300" />
|
||||||
|
<MiniMap
|
||||||
|
nodeColor={(n) => KIND_COLORS[(n.data as any)?.kind] || '#6b7280'}
|
||||||
|
className="!bg-gray-900 !border-gray-700"
|
||||||
|
/>
|
||||||
|
</ReactFlow>
|
||||||
|
);
|
||||||
|
}
|
||||||
77
portal/src/components/LinkModal.tsx
Normal file
77
portal/src/components/LinkModal.tsx
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { api } from '../api';
|
||||||
|
import { useNodes } from '../hooks/useNodes';
|
||||||
|
import type { EdgeType } from '../types';
|
||||||
|
|
||||||
|
const EDGE_TYPES: EdgeType[] = [
|
||||||
|
'depends_on', 'contains', 'implements', 'blocked_by',
|
||||||
|
'subtask_of', 'relates_to', 'supersedes', 'about',
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function LinkModal({
|
||||||
|
fromId,
|
||||||
|
onClose,
|
||||||
|
onCreated,
|
||||||
|
}: {
|
||||||
|
fromId: string;
|
||||||
|
onClose: () => void;
|
||||||
|
onCreated: () => void;
|
||||||
|
}) {
|
||||||
|
const { data: nodes } = useNodes();
|
||||||
|
const [toId, setToId] = useState('');
|
||||||
|
const [type, setType] = useState<EdgeType>('relates_to');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
if (!toId) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
await api.addEdge({ fromId, toId, type });
|
||||||
|
onCreated();
|
||||||
|
onClose();
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const targets = nodes?.filter(n => n.id !== fromId) || [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
|
||||||
|
<div className="bg-gray-900 border border-gray-700 rounded-lg p-6 w-96" onClick={e => e.stopPropagation()}>
|
||||||
|
<h2 className="text-lg font-semibold text-white mb-4">Create Link</h2>
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Edge Type</label>
|
||||||
|
<select
|
||||||
|
value={type}
|
||||||
|
onChange={e => setType(e.target.value as EdgeType)}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1"
|
||||||
|
>
|
||||||
|
{EDGE_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-400">Target Node</label>
|
||||||
|
<select
|
||||||
|
value={toId}
|
||||||
|
onChange={e => setToId(e.target.value)}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1"
|
||||||
|
>
|
||||||
|
<option value="">Select a node...</option>
|
||||||
|
{targets.map(n => (
|
||||||
|
<option key={n.id} value={n.id}>[{n.kind}] {n.title}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 mt-5">
|
||||||
|
<button onClick={onClose} className="flex-1 py-2 bg-gray-800 text-gray-400 rounded text-sm">Cancel</button>
|
||||||
|
<button onClick={submit} disabled={loading || !toId} className="flex-1 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded text-sm font-medium">
|
||||||
|
{loading ? 'Linking...' : 'Create Link'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
135
portal/src/components/NodePanel.tsx
Normal file
135
portal/src/components/NodePanel.tsx
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { api } from '../api';
|
||||||
|
import type { NodeWithConnections } from '../types';
|
||||||
|
|
||||||
|
export default function NodePanel({
|
||||||
|
nodeId,
|
||||||
|
onClose,
|
||||||
|
onLink,
|
||||||
|
onRefresh,
|
||||||
|
onNotify,
|
||||||
|
}: {
|
||||||
|
nodeId: string;
|
||||||
|
onClose: () => void;
|
||||||
|
onLink: (id: string) => void;
|
||||||
|
onRefresh: () => void;
|
||||||
|
onNotify: (msg: string) => void;
|
||||||
|
}) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const { data: node, isLoading } = useQuery({
|
||||||
|
queryKey: ['node', nodeId],
|
||||||
|
queryFn: () => api.getNode(nodeId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const [editing, setEditing] = useState<string | null>(null);
|
||||||
|
const [editValue, setEditValue] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
|
||||||
|
window.addEventListener('keydown', handler);
|
||||||
|
return () => window.removeEventListener('keydown', handler);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
if (isLoading || !node) {
|
||||||
|
return (
|
||||||
|
<div className="w-80 bg-gray-900 border-l border-gray-800 p-4 text-gray-400">
|
||||||
|
Loading...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const save = async (field: string, value: string) => {
|
||||||
|
const body: any = {};
|
||||||
|
if (field === 'tags') body.tags = value.split(',').map(t => t.trim()).filter(Boolean);
|
||||||
|
else body[field] = value;
|
||||||
|
await api.updateNode(nodeId, body);
|
||||||
|
qc.invalidateQueries({ queryKey: ['node', nodeId] });
|
||||||
|
onRefresh();
|
||||||
|
setEditing(null);
|
||||||
|
onNotify(`Updated ${field}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!confirm('Delete this node?')) return;
|
||||||
|
await api.deleteNode(nodeId, true);
|
||||||
|
onRefresh();
|
||||||
|
onClose();
|
||||||
|
onNotify('Node deleted');
|
||||||
|
};
|
||||||
|
|
||||||
|
const Field = ({ label, field, value }: { label: string; field: string; value: string }) => (
|
||||||
|
<div className="mb-3">
|
||||||
|
<label className="text-[10px] uppercase tracking-wide text-gray-500">{label}</label>
|
||||||
|
{editing === field ? (
|
||||||
|
<div className="flex gap-1 mt-1">
|
||||||
|
<input
|
||||||
|
value={editValue}
|
||||||
|
onChange={(e) => setEditValue(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && save(field, editValue)}
|
||||||
|
className="flex-1 bg-gray-800 border border-gray-600 rounded px-2 py-1 text-sm text-white"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<button onClick={() => save(field, editValue)} className="text-xs text-indigo-400">Save</button>
|
||||||
|
<button onClick={() => setEditing(null)} className="text-xs text-gray-500">Cancel</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
onClick={() => { setEditing(field); setEditValue(value); }}
|
||||||
|
className="text-sm text-gray-300 mt-0.5 cursor-pointer hover:text-white min-h-[20px]"
|
||||||
|
>
|
||||||
|
{value || <span className="text-gray-600 italic">empty</span>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="w-80 bg-gray-900 border-l border-gray-800 flex flex-col h-full overflow-y-auto">
|
||||||
|
<div className="p-4 border-b border-gray-800 flex justify-between items-start">
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] uppercase tracking-wide text-gray-500">{node.kind}</span>
|
||||||
|
<h2 className="text-base font-semibold text-white">{node.title}</h2>
|
||||||
|
<span className="text-[10px] text-gray-600">{node.id.slice(0, 8)}</span>
|
||||||
|
</div>
|
||||||
|
<button onClick={onClose} className="text-gray-500 hover:text-white text-lg">×</button>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 flex-1">
|
||||||
|
<Field label="Status" field="status" value={node.status || ''} />
|
||||||
|
<Field label="Content" field="content" value={node.content} />
|
||||||
|
<Field label="Tags" field="tags" value={node.tags.join(', ')} />
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<label className="text-[10px] uppercase tracking-wide text-gray-500">Connections</label>
|
||||||
|
{node.connections.outgoing.length === 0 && node.connections.incoming.length === 0 && (
|
||||||
|
<p className="text-sm text-gray-600 mt-1">No connections</p>
|
||||||
|
)}
|
||||||
|
{node.connections.outgoing.map((c) => (
|
||||||
|
<div key={c.id} className="text-sm text-gray-400 mt-1">
|
||||||
|
<span className="text-gray-500">→ {c.type}</span> {c.node.title}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{node.connections.incoming.map((c) => (
|
||||||
|
<div key={c.id} className="text-sm text-gray-400 mt-1">
|
||||||
|
<span className="text-gray-500">← {c.type}</span> {c.node.title}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 border-t border-gray-800 flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => onLink(nodeId)}
|
||||||
|
className="flex-1 py-1.5 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded text-sm"
|
||||||
|
>
|
||||||
|
Link to...
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleDelete}
|
||||||
|
className="flex-1 py-1.5 bg-red-900/50 hover:bg-red-800 text-red-300 rounded text-sm"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
portal/src/components/SearchBar.tsx
Normal file
51
portal/src/components/SearchBar.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { api } from '../api';
|
||||||
|
import type { SearchResult } from '../types';
|
||||||
|
|
||||||
|
export default function SearchBar({ onSelect }: { onSelect: (id: string) => void }) {
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [results, setResults] = useState<SearchResult[]>([]);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
const search = async () => {
|
||||||
|
if (!query.trim()) return;
|
||||||
|
const res = await api.search(query);
|
||||||
|
setResults(res);
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && search()}
|
||||||
|
placeholder="Search nodes..."
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-indigo-500"
|
||||||
|
/>
|
||||||
|
{open && results.length > 0 && (
|
||||||
|
<div className="absolute top-full left-0 right-0 mt-1 bg-gray-800 border border-gray-700 rounded shadow-lg z-50 max-h-60 overflow-y-auto">
|
||||||
|
{results.map((r) => (
|
||||||
|
<button
|
||||||
|
key={r.node.id}
|
||||||
|
onClick={() => { onSelect(r.node.id); setOpen(false); setQuery(''); }}
|
||||||
|
className="w-full text-left p-2 hover:bg-gray-700 text-sm text-gray-300 border-b border-gray-700 last:border-0"
|
||||||
|
>
|
||||||
|
<span className="text-[10px] text-gray-500 uppercase">{r.node.kind}</span>
|
||||||
|
<div className="truncate">{r.node.title}</div>
|
||||||
|
<span className="text-[10px] text-gray-500">score: {r.score.toFixed(2)}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{open && results.length === 0 && (
|
||||||
|
<div className="absolute top-full left-0 right-0 mt-1 bg-gray-800 border border-gray-700 rounded p-2 text-sm text-gray-500 z-50">
|
||||||
|
No results
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{open && (
|
||||||
|
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
69
portal/src/components/Sidebar.tsx
Normal file
69
portal/src/components/Sidebar.tsx
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useNodes } from '../hooks/useNodes';
|
||||||
|
import SearchBar from './SearchBar';
|
||||||
|
import type { NodeKind } from '../types';
|
||||||
|
|
||||||
|
const KINDS: (NodeKind | '')[] = ['', 'memory', 'component', 'task', 'decision'];
|
||||||
|
|
||||||
|
export default function Sidebar({
|
||||||
|
selectedId,
|
||||||
|
onSelect,
|
||||||
|
onAddNode,
|
||||||
|
}: {
|
||||||
|
selectedId: string | null;
|
||||||
|
onSelect: (id: string) => void;
|
||||||
|
onAddNode: () => void;
|
||||||
|
}) {
|
||||||
|
const [kindFilter, setKindFilter] = useState('');
|
||||||
|
const { data: nodes, isLoading } = useNodes(kindFilter ? { kind: kindFilter } : undefined);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="w-72 bg-gray-900 border-r border-gray-800 flex flex-col h-full">
|
||||||
|
<div className="p-4 border-b border-gray-800">
|
||||||
|
<h1 className="text-lg font-bold text-white mb-3">Cortex Portal</h1>
|
||||||
|
<SearchBar onSelect={onSelect} />
|
||||||
|
<div className="flex gap-1 mt-3 flex-wrap">
|
||||||
|
{KINDS.map((k) => (
|
||||||
|
<button
|
||||||
|
key={k}
|
||||||
|
onClick={() => setKindFilter(k)}
|
||||||
|
className={`px-2 py-0.5 text-xs rounded ${
|
||||||
|
kindFilter === k
|
||||||
|
? 'bg-indigo-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-400 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{k || 'All'}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 overflow-y-auto p-2">
|
||||||
|
{isLoading && <p className="text-gray-500 text-sm p-2">Loading...</p>}
|
||||||
|
{nodes?.map((n) => (
|
||||||
|
<button
|
||||||
|
key={n.id}
|
||||||
|
onClick={() => onSelect(n.id)}
|
||||||
|
className={`w-full text-left p-2 rounded mb-1 text-sm ${
|
||||||
|
selectedId === n.id
|
||||||
|
? 'bg-indigo-600/30 text-white'
|
||||||
|
: 'hover:bg-gray-800 text-gray-300'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="text-[10px] uppercase tracking-wide text-gray-500">{n.kind}</span>
|
||||||
|
<div className="truncate">{n.title}</div>
|
||||||
|
{n.status && <span className="text-[10px] text-gray-500">{n.status}</span>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="p-3 border-t border-gray-800">
|
||||||
|
<button
|
||||||
|
onClick={onAddNode}
|
||||||
|
className="w-full py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded text-sm font-medium"
|
||||||
|
>
|
||||||
|
+ Add Node
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
7
portal/src/components/Toast.tsx
Normal file
7
portal/src/components/Toast.tsx
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
export default function Toast({ message }: { message: string }) {
|
||||||
|
return (
|
||||||
|
<div className="fixed bottom-6 right-6 bg-green-600 text-white px-4 py-2 rounded-lg shadow-lg z-50 animate-fade-in">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
9
portal/src/hooks/useGraph.ts
Normal file
9
portal/src/hooks/useGraph.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { api } from '../api';
|
||||||
|
|
||||||
|
export function useGraph() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['graph'],
|
||||||
|
queryFn: api.getGraph,
|
||||||
|
});
|
||||||
|
}
|
||||||
9
portal/src/hooks/useNodes.ts
Normal file
9
portal/src/hooks/useNodes.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { api } from '../api';
|
||||||
|
|
||||||
|
export function useNodes(params?: { kind?: string; status?: string }) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['nodes', params],
|
||||||
|
queryFn: () => api.listNodes(params),
|
||||||
|
});
|
||||||
|
}
|
||||||
17
portal/src/main.tsx
Normal file
17
portal/src/main.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import './app.css';
|
||||||
|
import { StrictMode } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
|
import App from './App';
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: { queries: { refetchOnWindowFocus: false } },
|
||||||
|
});
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<App />
|
||||||
|
</QueryClientProvider>
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
44
portal/src/types.ts
Normal file
44
portal/src/types.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
export type NodeKind = 'memory' | 'component' | 'task' | 'decision';
|
||||||
|
|
||||||
|
export type EdgeType =
|
||||||
|
| 'depends_on' | 'contains' | 'implements' | 'blocked_by'
|
||||||
|
| 'subtask_of' | 'relates_to' | 'supersedes' | 'about';
|
||||||
|
|
||||||
|
export interface CortexNode {
|
||||||
|
id: string;
|
||||||
|
kind: NodeKind;
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
status?: string;
|
||||||
|
tags: string[];
|
||||||
|
metadata: Record<string, any>;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
isStale?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CortexEdge {
|
||||||
|
id: string;
|
||||||
|
fromId: string;
|
||||||
|
toId: string;
|
||||||
|
type: EdgeType;
|
||||||
|
metadata: Record<string, any>;
|
||||||
|
createdAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GraphData {
|
||||||
|
nodes: CortexNode[];
|
||||||
|
edges: CortexEdge[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NodeWithConnections extends CortexNode {
|
||||||
|
connections: {
|
||||||
|
incoming: (CortexEdge & { node: CortexNode })[];
|
||||||
|
outgoing: (CortexEdge & { node: CortexNode })[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SearchResult {
|
||||||
|
node: CortexNode;
|
||||||
|
score: number;
|
||||||
|
}
|
||||||
14
portal/tsconfig.json
Normal file
14
portal/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"outDir": "./dist"
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
16
portal/vite.config.ts
Normal file
16
portal/vite.config.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), tailwindcss()],
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:3100',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
build: {
|
||||||
|
outDir: 'dist',
|
||||||
|
},
|
||||||
|
});
|
||||||
9
src/cli/commands/serve.ts
Normal file
9
src/cli/commands/serve.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
|
||||||
|
export const serveCommand = new Command('serve')
|
||||||
|
.description('Start the Cortex Portal web server')
|
||||||
|
.option('-p, --port <number>', 'Port number', '3100')
|
||||||
|
.action((opts) => {
|
||||||
|
process.env.PORT = opts.port;
|
||||||
|
require('../../server/index');
|
||||||
|
});
|
||||||
@@ -8,6 +8,7 @@ import { listCommand } from './commands/list';
|
|||||||
import { updateCommand } from './commands/update';
|
import { updateCommand } from './commands/update';
|
||||||
import { removeCommand } from './commands/remove';
|
import { removeCommand } from './commands/remove';
|
||||||
import { graphCommand } from './commands/graph';
|
import { graphCommand } from './commands/graph';
|
||||||
|
import { serveCommand } from './commands/serve';
|
||||||
import { closeDb } from '../core/db';
|
import { closeDb } from '../core/db';
|
||||||
|
|
||||||
const program = new Command();
|
const program = new Command();
|
||||||
@@ -25,6 +26,7 @@ program.addCommand(listCommand);
|
|||||||
program.addCommand(updateCommand);
|
program.addCommand(updateCommand);
|
||||||
program.addCommand(removeCommand);
|
program.addCommand(removeCommand);
|
||||||
program.addCommand(graphCommand);
|
program.addCommand(graphCommand);
|
||||||
|
program.addCommand(serveCommand);
|
||||||
|
|
||||||
program.hook('postAction', () => {
|
program.hook('postAction', () => {
|
||||||
closeDb();
|
closeDb();
|
||||||
|
|||||||
29
src/server/index.ts
Normal file
29
src/server/index.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import path from 'path';
|
||||||
|
import routes from './routes';
|
||||||
|
import { closeDb } from '../core/db';
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const PORT = parseInt(process.env.PORT || '3100');
|
||||||
|
|
||||||
|
app.use(cors());
|
||||||
|
app.use(express.json());
|
||||||
|
app.use('/api', routes);
|
||||||
|
|
||||||
|
// Serve portal static files in production
|
||||||
|
const portalDist = path.join(__dirname, '../../portal/dist');
|
||||||
|
app.use(express.static(portalDist));
|
||||||
|
app.get('{*path}', (_req, res) => {
|
||||||
|
res.sendFile(path.join(portalDist, 'index.html'));
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = app.listen(PORT, () => {
|
||||||
|
console.log(`Cortex Portal running at http://localhost:${PORT}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
closeDb();
|
||||||
|
server.close();
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
136
src/server/routes.ts
Normal file
136
src/server/routes.ts
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
import { Router, Request, Response } from 'express';
|
||||||
|
import { addNode, getNode, listNodes, updateNode, removeNode, addEdge, removeEdge, query } from '../core/store';
|
||||||
|
import { getConnections, buildTree } from '../core/graph';
|
||||||
|
import { getDb } from '../core/db';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
function param(req: Request, name: string): string {
|
||||||
|
const v = req.params[name];
|
||||||
|
return Array.isArray(v) ? v[0] : v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// List nodes
|
||||||
|
router.get('/nodes', (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const options: any = {};
|
||||||
|
if (req.query.kind) options.kind = req.query.kind as string;
|
||||||
|
if (req.query.status) options.status = req.query.status as string;
|
||||||
|
if (req.query.tags) options.tags = (req.query.tags as string).split(',');
|
||||||
|
if (req.query.limit) options.limit = parseInt(req.query.limit as string);
|
||||||
|
if (req.query.includeStale === 'true') options.includeStale = true;
|
||||||
|
const nodes = listNodes(options);
|
||||||
|
res.json(nodes.map(n => ({ ...n, embedding: undefined })));
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get single node + connections
|
||||||
|
router.get('/nodes/:id', (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const node = getNode(param(req, 'id'));
|
||||||
|
if (!node) return res.status(404).json({ error: 'Node not found' });
|
||||||
|
const connections = getConnections(param(req, 'id'));
|
||||||
|
res.json({ ...node, embedding: undefined, connections });
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add node
|
||||||
|
router.post('/nodes', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const node = await addNode(req.body);
|
||||||
|
res.status(201).json({ ...node, embedding: undefined });
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(400).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update node
|
||||||
|
router.patch('/nodes/:id', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const node = await updateNode(param(req, 'id'), req.body);
|
||||||
|
if (!node) return res.status(404).json({ error: 'Node not found' });
|
||||||
|
res.json({ ...node, embedding: undefined });
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(400).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete node
|
||||||
|
router.delete('/nodes/:id', (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const hard = req.query.hard === 'true';
|
||||||
|
const ok = removeNode(param(req, 'id'), hard);
|
||||||
|
if (!ok) return res.status(404).json({ error: 'Node not found' });
|
||||||
|
res.json({ ok: true });
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add edge
|
||||||
|
router.post('/edges', (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { fromId, toId, type, metadata } = req.body;
|
||||||
|
const edge = addEdge(fromId, toId, type, metadata);
|
||||||
|
res.status(201).json(edge);
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(400).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete edge
|
||||||
|
router.delete('/edges/:id', (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const ok = removeEdge(param(req, 'id'));
|
||||||
|
if (!ok) return res.status(404).json({ error: 'Edge not found' });
|
||||||
|
res.json({ ok: true });
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Graph — returns nodes + edges for React Flow
|
||||||
|
router.get('/graph', (_req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const db = getDb();
|
||||||
|
const nodes = (db.prepare('SELECT * FROM nodes WHERE is_stale = 0').all() as any[]).map(row => ({
|
||||||
|
id: row.id,
|
||||||
|
kind: row.kind,
|
||||||
|
title: row.title,
|
||||||
|
content: row.content,
|
||||||
|
status: row.status,
|
||||||
|
tags: JSON.parse(row.tags || '[]'),
|
||||||
|
metadata: JSON.parse(row.metadata || '{}'),
|
||||||
|
createdAt: row.created_at,
|
||||||
|
updatedAt: row.updated_at,
|
||||||
|
}));
|
||||||
|
const edges = (db.prepare('SELECT * FROM edges').all() as any[]).map(row => ({
|
||||||
|
id: row.id,
|
||||||
|
fromId: row.from_id,
|
||||||
|
toId: row.to_id,
|
||||||
|
type: row.type,
|
||||||
|
metadata: JSON.parse(row.metadata || '{}'),
|
||||||
|
createdAt: row.created_at,
|
||||||
|
}));
|
||||||
|
res.json({ nodes, edges });
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Search
|
||||||
|
router.post('/search', async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { text, options } = req.body;
|
||||||
|
const results = await query(text, options || {});
|
||||||
|
res.json(results.map(r => ({ ...r, node: { ...r.node, embedding: undefined } })));
|
||||||
|
} catch (err: any) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
Reference in New Issue
Block a user