Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add LLM Wiki page with browse, search, graph, and maintenance job

Adam Eivydccb5e8f3490
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 73f8a56154..4997ce8211 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,15 @@
- Inline note editor with Cmd+S save, backlinks panel, and frontmatter properties view
- Full-text search with context snippets and relevance ranking
- Link graph endpoint for vault-wide wikilink visualization
+- **LLM Wiki** — a dedicated Wiki page for managing an LLM-maintained knowledge base in Obsidian
+ - Overview tab with page-type stats (sources, entities, concepts, comparisons, synthesis, queries), recent activity feed, and health report display
+ - Browse tab with folder-tree navigation for both wiki pages and raw sources, inline note viewer/editor with metadata sidebar (frontmatter, tags, wikilinks, backlinks)
+ - Full-text search tab with relevance ranking, context snippets, and one-click navigation to results
+ - Interactive knowledge graph tab with color-coded node clusters by page type, zoom/pan, and click-to-navigate
+ - Activity log tab parsing the wiki's chronological log into a structured timeline
+ - Wiki schema (`WIKI.md`) defining page types, frontmatter conventions, and ingest/query/lint workflows
+ - Weekly CoS maintenance job (`job-wiki-maintenance`) that audits the wiki for contradictions, orphans, missing cross-references, outdated claims, and generates a lint report
+ - Obsidian attachment folder auto-configured to `raw/assets/` for Web Clipper image downloads
- **Disk usage monitoring** on dashboard — system health endpoint now reports root filesystem disk usage (total/used/free/percent) with warning at 85% and critical alert at 95%; SystemHealthWidget displays a new Disk card with progress bar alongside Memory, CPU, Processes, and Apps
- **CyberCity v2 improvement plan** — 19 concrete ideas across 3 effort tiers for transforming CyberCity from decorative scene to living systems dashboard, including system health atmosphere, productivity district, goal monuments, chronotype energy overlay, and knowledge district
@@ -32,3 +41,4 @@
- **Broken worktree detection** — worktree cleanup now verifies `rev-parse --show-toplevel` matches the expected worktree path before trusting `git status`; prevents broken worktrees (missing `.git` file) from resolving to a parent repo and incorrectly blocking removal
- **Agent prompt missing commit step** — agent instructions now explicitly include "commit and push" in the numbered steps and the simplify section reinforces committing after review, preventing agents from completing work without pushing changes
- **Memory classifier — LM Studio no-model-loaded failures** — memory classification calls to LM Studio failed with `400 "No models loaded"` when the server had no model in memory. The classifier now discovers downloaded LLMs via `GET /api/v0/models`, auto-loads the configured model (or first available LLM) via `POST /api/v1/models/load`, and retries with the actually-loaded model id — mirroring the existing embedding auto-load path in `memoryEmbeddings.js`
+- **Browser CDP downloads reverting to `~/Downloads`** — `Browser.setDownloadBehavior` is DevTools-session-scoped in Chrome: the instant the WebSocket that issued the command closes, Chrome tears down the session's `BrowserHandler` and the download directory reverts to the profile default. The previous implementation opened a WS, sent the command, and closed it immediately after the ack — so the managed download dir was only in effect for milliseconds and real downloads landed in `~/Downloads`. `browser/server.js` now keeps a persistent keep-alive WebSocket open for the lifetime of the process, with automatic reconnect if Chrome restarts, proper error detection on the command response, and clean teardown on shutdown
diff --git a/browser/server.js b/browser/server.js
index dccae77c83..dcf63e5aef 100644
--- a/browser/server.js
+++ b/browser/server.js
@@ -17,6 +17,10 @@ const CDP_HOST = process.env.CDP_HOST || '127.0.0.1';
let chromeProcess = null;
let headlessMode = true;
+let downloadWs = null;
+let downloadWsReconnectTimer = null;
+let downloadDirCurrent = null;
+let shuttingDown = false;
function getChromePath() {
const os = platform();
@@ -39,40 +43,85 @@ async function checkCdp() {
return res.json();
}
+// Chrome's `Browser.setDownloadBehavior` is DevTools-session-scoped — when the
+// WebSocket that issued the command closes, Chrome tears down the BrowserHandler
+// and the setting reverts to default (`~/Downloads`). We must keep a live CDP
+// connection open for the lifetime of this process so downloads keep landing in
+// our managed directory.
async function configureDownloadBehavior(downloadDir) {
- const version = await checkCdp();
- const wsUrl = version?.webSocketDebuggerUrl;
- if (!wsUrl) return;
+ downloadDirCurrent = downloadDir;
- // CDP requires explicit Browser.setDownloadBehavior — without it headless Chrome silently drops downloads
// WebSocket is a global in Node.js 21+ (project targets Node 22+)
if (typeof WebSocket === 'undefined') {
console.log('⚠️ WebSocket not available — download configuration skipped (requires Node.js 21+)');
return;
}
- await new Promise((resolve) => {
- const ws = new WebSocket(wsUrl);
- const timer = setTimeout(() => { ws.close(); resolve(); }, 5000);
- ws.addEventListener('open', () => {
- ws.send(JSON.stringify({
- id: 1,
- method: 'Browser.setDownloadBehavior',
- params: { behavior: 'allow', downloadPath: downloadDir }
- }));
- });
- ws.addEventListener('message', (event) => {
- const msg = JSON.parse(event.data);
- if (msg.id === 1) {
- console.log(`📥 Downloads configured → ${downloadDir}`);
- clearTimeout(timer);
- ws.close();
- resolve();
+
+ // Tear down any existing keep-alive before opening a new one
+ if (downloadWs) {
+ try { downloadWs.close(); } catch {}
+ downloadWs = null;
+ }
+ if (downloadWsReconnectTimer) {
+ clearTimeout(downloadWsReconnectTimer);
+ downloadWsReconnectTimer = null;
+ }
+
+ const version = await checkCdp();
+ const wsUrl = version?.webSocketDebuggerUrl;
+ if (!wsUrl) {
+ console.log('⚠️ CDP unreachable — cannot configure download behavior');
+ scheduleDownloadReconnect();
+ return;
+ }
+
+ const ws = new WebSocket(wsUrl);
+ downloadWs = ws;
+
+ ws.addEventListener('open', () => {
+ ws.send(JSON.stringify({
+ id: 1,
+ method: 'Browser.setDownloadBehavior',
+ params: { behavior: 'allow', downloadPath: downloadDir }
+ }));
+ });
+
+ ws.addEventListener('message', (event) => {
+ const msg = JSON.parse(event.data);
+ if (msg.id === 1) {
+ if (msg.error) {
+ console.error(`❌ Browser.setDownloadBehavior failed: ${msg.error.message || JSON.stringify(msg.error)}`);
+ } else {
+ console.log(`📥 Downloads configured → ${downloadDir} (keep-alive WS open)`);
}
- });
- ws.addEventListener('error', () => { clearTimeout(timer); resolve(); });
+ }
+ });
+
+ ws.addEventListener('close', () => {
+ if (downloadWs === ws) downloadWs = null;
+ if (shuttingDown) return;
+ console.log('⚠️ Download keep-alive WS closed — will reconnect');
+ scheduleDownloadReconnect();
+ });
+
+ ws.addEventListener('error', (event) => {
+ console.error(`❌ Download keep-alive WS error: ${event?.message || 'unknown'}`);
});
}
+function scheduleDownloadReconnect() {
+ if (shuttingDown || downloadWsReconnectTimer) return;
+ downloadWsReconnectTimer = setTimeout(async () => {
+ downloadWsReconnectTimer = null;
+ if (shuttingDown || !downloadDirCurrent) return;
+ if (await checkCdp()) {
+ await configureDownloadBehavior(downloadDirCurrent);
+ } else {
+ scheduleDownloadReconnect();
+ }
+ }, 2000);
+}
+
async function launchBrowser() {
const config = await loadConfig();
const downloadDir = config.downloadDir || DEFAULT_DOWNLOAD_DIR;
@@ -115,6 +164,10 @@ async function launchBrowser() {
chromeProcess.on('exit', (code) => {
console.log(`⚠️ Chrome exited with code ${code}`);
chromeProcess = null;
+ if (downloadWs) {
+ try { downloadWs.close(); } catch {}
+ downloadWs = null;
+ }
});
// Wait for CDP to become available
@@ -163,6 +216,15 @@ const healthServer = createServer(async (req, res) => {
function shutdown() {
console.log('🛑 Shutting down browser...');
+ shuttingDown = true;
+ if (downloadWsReconnectTimer) {
+ clearTimeout(downloadWsReconnectTimer);
+ downloadWsReconnectTimer = null;
+ }
+ if (downloadWs) {
+ try { downloadWs.close(); } catch {}
+ downloadWs = null;
+ }
if (chromeProcess && !chromeProcess.killed) {
chromeProcess.kill('SIGTERM');
}
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 42bd36eee7..025dcd4770 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -26,6 +26,7 @@ import Post from './pages/Post';
import Review from './pages/Review';
import Loops from './pages/Loops';
import CharacterSheet from './pages/CharacterSheet';
+import Wiki from './pages/Wiki';
// Auto-reload on stale chunk errors (e.g., after a rebuild changes chunk hashes)
// Uses sessionStorage to prevent infinite reload loops (max 1 reload per session)
@@ -143,6 +144,8 @@ export default function App() {
<Route path="city/settings" element={<CyberCity />} />
<Route path="data" element={<DataManager />} />
<Route path="character" element={<CharacterSheet />} />
+ <Route path="wiki" element={<Navigate to="/wiki/overview" replace />} />
+ <Route path="wiki/:tab" element={<Wiki />} />
<Route path="agents" element={<Agents />} />
<Route path="agents/:agentId" element={<Agents />} />
<Route path="agents/:agentId/:tab" element={<Agents />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 17065b928d..4480afe0b9 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -70,7 +70,9 @@ import {
Swords,
Image as ImageIcon,
HardDrive,
- MessagesSquare
+ MessagesSquare,
+ BookOpen,
+ Search
} from 'lucide-react';
/* global __APP_VERSION__ */
import Logo from './Logo';
@@ -236,7 +238,18 @@ const navItems = [
{ to: '/uploads', label: 'Uploads', icon: Upload }
]
},
- { to: '/agents', label: 'Social Agents', icon: Users, single: true }
+ { to: '/agents', label: 'Social Agents', icon: Users, single: true },
+ {
+ label: 'Wiki',
+ icon: BookOpen,
+ children: [
+ { to: '/wiki/overview', label: 'Overview', icon: BarChart3 },
+ { to: '/wiki/browse', label: 'Browse', icon: FileText },
+ { to: '/wiki/graph', label: 'Graph', icon: Network },
+ { to: '/wiki/log', label: 'Log', icon: Activity },
+ { to: '/wiki/search', label: 'Search', icon: Search }
+ ]
+ }
];
const SIDEBAR_KEY = 'portos-sidebar-collapsed';
@@ -695,6 +708,7 @@ export default function Layout() {
location.pathname.startsWith('/messages') ||
location.pathname.startsWith('/post') ||
location.pathname === '/review' ||
+ location.pathname.startsWith('/wiki') ||
location.pathname.startsWith('/agents') ||
location.pathname === '/shell' ||
location.pathname.startsWith('/city') ||
diff --git a/client/src/components/wiki/constants.jsx b/client/src/components/wiki/constants.jsx
new file mode 100644
index 0000000000..90aea4f355
--- /dev/null
+++ b/client/src/components/wiki/constants.jsx
@@ -0,0 +1,18 @@
+import { FileText, Users, Lightbulb, GitCompare, Layers, HelpCircle } from 'lucide-react';
+
+export const WIKI_CATEGORIES = [
+ { key: 'sources', folder: 'wiki/sources', label: 'Sources', icon: FileText, color: 'port-accent', hex: '#3b82f6' },
+ { key: 'entities', folder: 'wiki/entities', label: 'Entities', icon: Users, color: 'port-success', hex: '#22c55e' },
+ { key: 'concepts', folder: 'wiki/concepts', label: 'Concepts', icon: Lightbulb, color: 'port-warning', hex: '#f59e0b' },
+ { key: 'comparisons', folder: 'wiki/comparisons', label: 'Comparisons', icon: GitCompare, color: 'purple-400', hex: '#a855f7' },
+ { key: 'synthesis', folder: 'wiki/synthesis', label: 'Synthesis', icon: Layers, color: 'cyan-400', hex: '#06b6d4' },
+ { key: 'queries', folder: 'wiki/queries', label: 'Queries', icon: HelpCircle, color: 'pink-400', hex: '#ec4899' }
+];
+
+export function PageTypeIcon({ folder }) {
+ const type = folder?.split('/')[1];
+ const cat = WIKI_CATEGORIES.find(c => c.key === type);
+ if (!cat) return <FileText size={14} className="text-gray-500 shrink-0" />;
+ const Icon = cat.icon;
+ return <Icon size={14} className={`text-${cat.color} shrink-0`} />;
+}
diff --git a/client/src/components/wiki/tabs/BrowseTab.jsx b/client/src/components/wiki/tabs/BrowseTab.jsx
new file mode 100644
index 0000000000..49767502c9
--- /dev/null
+++ b/client/src/components/wiki/tabs/BrowseTab.jsx
@@ -0,0 +1,374 @@
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { useLocation } from 'react-router-dom';
+import * as api from '../../../services/api';
+import {
+ FileText, FolderOpen,
+ ChevronDown, ChevronRight, ArrowLeft, Tag, Link2, Edit3, Save,
+ Trash2, X, RefreshCw
+} from 'lucide-react';
+import toast from '../../ui/Toast';
+import { timeAgo, formatBytes } from '../../../utils/formatters';
+import { WIKI_CATEGORIES } from '../constants.jsx';
+
+const WIKI_FOLDERS = WIKI_CATEGORIES.map(c => ({ key: c.folder, label: c.label, icon: c.icon, color: `text-${c.color}` }));
+const RAW_FOLDERS = [{ key: 'raw', label: 'Raw Sources', icon: FolderOpen, color: 'text-gray-400' }];
+
+export default function BrowseTab({ vaultId, notes, rawNotes, allNotes, onRefresh }) {
+ const location = useLocation();
+ const [selectedNote, setSelectedNote] = useState(null);
+ const [noteContent, setNoteContent] = useState('');
+ const [editing, setEditing] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [loadingNote, setLoadingNote] = useState(false);
+ const [expandedFolders, setExpandedFolders] = useState(new Set(['wiki/sources', 'wiki/entities', 'wiki/concepts']));
+ const [activeSection, setActiveSection] = useState('wiki');
+ const [tags, setTags] = useState([]);
+ const [showTags, setShowTags] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(null);
+ const editorRef = useRef(null);
+
+ // Handle deep-link from overview
+ useEffect(() => {
+ if (location.state?.openNote) {
+ handleSelectNote(location.state.openNote);
+ }
+ }, [location.state]);
+
+ const handleSelectNote = async (notePath) => {
+ setLoadingNote(true);
+ setEditing(false);
+ const data = await api.getNote(vaultId, notePath).catch(() => null);
+ if (data && !data.error) {
+ setSelectedNote(data);
+ setNoteContent(data.content);
+ }
+ setLoadingNote(false);
+ };
+
+ const handleSaveNote = async () => {
+ if (!selectedNote) return;
+ setSaving(true);
+ const data = await api.updateNote(vaultId, selectedNote.path, noteContent).catch(() => null);
+ setSaving(false);
+ if (data) {
+ setSelectedNote(data);
+ setEditing(false);
+ toast.success('Note saved');
+ onRefresh();
+ }
+ };
+
+ const handleDeleteNote = async (notePath) => {
+ await api.deleteNote(vaultId, notePath).catch(() => null);
+ toast.success('Note deleted');
+ setConfirmDelete(null);
+ if (selectedNote?.path === notePath) setSelectedNote(null);
+ onRefresh();
+ };
+
+ const loadTags = async () => {
+ const data = await api.getNotesVaultTags(vaultId).catch(() => null);
+ if (data?.tags) setTags(data.tags);
+ };
+
+ const toggleFolder = (folder) => {
+ setExpandedFolders(prev => {
+ const next = new Set(prev);
+ if (next.has(folder)) next.delete(folder);
+ else next.add(folder);
+ return next;
+ });
+ };
+
+ const notesForFolder = useCallback((folderKey) => {
+ if (folderKey === 'raw') return rawNotes;
+ return notes.filter(n => n.folder === folderKey);
+ }, [notes, rawNotes]);
+
+ const folders = activeSection === 'wiki' ? WIKI_FOLDERS : RAW_FOLDERS;
+
+ const rootWikiNotes = activeSection === 'wiki'
+ ? allNotes.filter(n =>
+ (n.folder === 'wiki' || n.path === 'wiki/index.md' || n.path === 'wiki/log.md') &&
+ !WIKI_FOLDERS.some(f => n.folder === f.key)
+ )
+ : [];
+
+ return (
+ <div className="flex -m-4" style={{ height: 'calc(100vh - 220px)' }}>
+ {/* Left panel */}
+ <div className="w-80 border-r border-port-border flex flex-col shrink-0">
+ {/* Section toggle */}
+ <div className="p-3 border-b border-port-border flex items-center gap-2">
+ <button
+ onClick={() => setActiveSection('wiki')}
+ className={`flex-1 px-3 py-1.5 rounded text-sm font-medium transition-colors ${
+ activeSection === 'wiki' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'
+ }`}
+ >
+ Wiki ({notes.length})
+ </button>
+ <button
+ onClick={() => setActiveSection('raw')}
+ className={`flex-1 px-3 py-1.5 rounded text-sm font-medium transition-colors ${
+ activeSection === 'raw' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'
+ }`}
+ >
+ Raw ({rawNotes.length})
+ </button>
+ <button
+ onClick={() => { loadTags(); setShowTags(!showTags); }}
+ className={`p-1.5 rounded ${showTags ? 'text-port-accent' : 'text-gray-500 hover:text-white'}`}
+ title="Tags"
+ >
+ <Tag size={14} />
+ </button>
+ </div>
+
+ {/* Tags */}
+ {showTags && tags.length > 0 && (
+ <div className="px-3 py-2 border-b border-port-border flex flex-wrap gap-1 max-h-24 overflow-auto">
+ {tags.map(t => (
+ <span key={t.tag} className="px-1.5 py-0.5 rounded text-xs bg-port-accent/20 text-port-accent">
+ #{t.tag} <span className="text-gray-500">{t.count}</span>
+ </span>
+ ))}
+ </div>
+ )}
+
+ {/* Folder tree */}
+ <div className="flex-1 overflow-auto">
+ {folders.map(folder => {
+ const folderNotes = notesForFolder(folder.key);
+ const Icon = folder.icon;
+ const expanded = expandedFolders.has(folder.key);
+ return (
+ <div key={folder.key}>
+ <button
+ onClick={() => toggleFolder(folder.key)}
+ className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-400 hover:text-white hover:bg-port-card/50"
+ >
+ {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+ <Icon size={14} className={folder.color} />
+ <span className="flex-1 text-left">{folder.label}</span>
+ <span className="text-xs text-gray-600">{folderNotes.length}</span>
+ </button>
+ {expanded && (
+ <div className="ml-4">
+ {folderNotes.length === 0 ? (
+ <div className="px-3 py-2 text-xs text-gray-600 italic">Empty</div>
+ ) : folderNotes.map(note => (
+ <button
+ key={note.path}
+ onClick={() => handleSelectNote(note.path)}
+ className={`w-full flex items-center gap-2 px-3 py-1.5 text-sm text-left transition-colors ${
+ selectedNote?.path === note.path
+ ? 'bg-port-accent/10 text-port-accent'
+ : 'text-gray-300 hover:text-white hover:bg-port-card/30'
+ }`}
+ >
+ <FileText size={12} className="shrink-0 text-gray-500" />
+ <span className="flex-1 truncate">{note.name}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+
+ {rootWikiNotes.map(note => (
+ <button
+ key={note.path}
+ onClick={() => handleSelectNote(note.path)}
+ className={`w-full flex items-center gap-2 px-3 py-1.5 text-sm text-left transition-colors ${
+ selectedNote?.path === note.path
+ ? 'bg-port-accent/10 text-port-accent'
+ : 'text-gray-300 hover:text-white hover:bg-port-card/30'
+ }`}
+ >
+ <FileText size={12} className="shrink-0 text-gray-500" />
+ <span className="flex-1 truncate">{note.name}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Right panel: note viewer */}
+ <div className="flex-1 flex flex-col min-w-0">
+ {loadingNote ? (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ ) : selectedNote ? (
+ <>
+ {/* Note header */}
+ <div className="px-4 py-3 border-b border-port-border flex items-center gap-3">
+ <div className="flex-1 min-w-0">
+ <h2 className="text-white font-medium truncate">{selectedNote.name}</h2>
+ <div className="flex items-center gap-3 text-xs text-gray-500">
+ {selectedNote.folder && (
+ <span className="flex items-center gap-1">
+ <FolderOpen size={10} />
+ {selectedNote.folder}
+ </span>
+ )}
+ <span>Modified {timeAgo(selectedNote.modifiedAt)}</span>
+ <span>{formatBytes(selectedNote.size)}</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-1">
+ {editing ? (
+ <>
+ <button
+ onClick={handleSaveNote}
+ disabled={saving}
+ className="flex items-center gap-1 px-3 py-1.5 rounded bg-port-accent text-white text-sm hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ <Save size={14} />
+ {saving ? 'Saving...' : 'Save'}
+ </button>
+ <button
+ onClick={() => { setEditing(false); setNoteContent(selectedNote.content); }}
+ className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white"
+ >
+ <X size={16} />
+ </button>
+ </>
+ ) : (
+ <button
+ onClick={() => setEditing(true)}
+ className="flex items-center gap-1 px-3 py-1.5 rounded bg-port-card text-gray-300 text-sm hover:text-white hover:bg-port-border"
+ >
+ <Edit3 size={14} />
+ Edit
+ </button>
+ )}
+ <button
+ onClick={() => setConfirmDelete(selectedNote.path)}
+ className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-port-error"
+ title="Delete note"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+
+ {/* Delete confirmation */}
+ {confirmDelete === selectedNote.path && (
+ <div className="px-4 py-2 bg-port-error/10 border-b border-port-error/30 flex items-center gap-3 text-sm">
+ <span className="text-port-error">Delete this note permanently?</span>
+ <button onClick={() => handleDeleteNote(selectedNote.path)} className="px-2 py-1 rounded bg-port-error text-white text-xs">Delete</button>
+ <button onClick={() => setConfirmDelete(null)} className="px-2 py-1 rounded bg-port-card text-gray-300 text-xs">Cancel</button>
+ </div>
+ )}
+
+ {/* Note content */}
+ <div className="flex-1 overflow-auto flex">
+ <div className="flex-1 min-w-0">
+ {editing ? (
+ <textarea
+ ref={editorRef}
+ value={noteContent}
+ onChange={e => setNoteContent(e.target.value)}
+ className="w-full h-full p-4 bg-port-bg text-gray-200 font-mono text-sm resize-none focus:outline-none"
+ spellCheck={false}
+ onKeyDown={e => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 's') {
+ e.preventDefault();
+ handleSaveNote();
+ }
+ }}
+ />
+ ) : (
+ <div className="p-4 prose prose-invert prose-sm max-w-none">
+ <pre className="whitespace-pre-wrap text-sm text-gray-300 font-mono leading-relaxed">
+ {selectedNote.body || selectedNote.content}
+ </pre>
+ </div>
+ )}
+ </div>
+
+ {/* Sidebar: metadata */}
+ {!editing && (
+ <div className="w-56 border-l border-port-border p-3 space-y-4 shrink-0 overflow-auto hidden lg:block">
+ {selectedNote.frontmatter && Object.keys(selectedNote.frontmatter).length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium text-gray-400 uppercase mb-1">Properties</h4>
+ <div className="space-y-1">
+ {Object.entries(selectedNote.frontmatter).map(([key, val]) => (
+ <div key={key} className="text-xs">
+ <span className="text-gray-500">{key}:</span>{' '}
+ <span className="text-gray-300">{Array.isArray(val) ? val.join(', ') : String(val)}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {selectedNote.tags?.length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium text-gray-400 uppercase mb-1">Tags</h4>
+ <div className="flex flex-wrap gap-1">
+ {selectedNote.tags.map(tag => (
+ <span key={tag} className="px-1.5 py-0.5 rounded text-xs bg-port-accent/20 text-port-accent">#{tag}</span>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {selectedNote.wikilinks?.length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium text-gray-400 uppercase mb-1 flex items-center gap-1">
+ <Link2 size={10} /> Links ({selectedNote.wikilinks.length})
+ </h4>
+ <div className="space-y-0.5">
+ {selectedNote.wikilinks.map(link => (
+ <button
+ key={link}
+ onClick={() => {
+ const match = allNotes.find(n => n.name.toLowerCase() === link.toLowerCase());
+ if (match) handleSelectNote(match.path);
+ else toast.error(`"${link}" not found`);
+ }}
+ className="block w-full text-left text-xs text-port-accent hover:text-white truncate"
+ >
+ {link}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {selectedNote.backlinks?.length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium text-gray-400 uppercase mb-1 flex items-center gap-1">
+ <ArrowLeft size={10} /> Backlinks ({selectedNote.backlinks.length})
+ </h4>
+ <div className="space-y-0.5">
+ {selectedNote.backlinks.map(bl => (
+ <button
+ key={bl.path}
+ onClick={() => handleSelectNote(bl.path)}
+ className="block w-full text-left text-xs text-port-accent hover:text-white truncate"
+ >
+ {bl.name}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="flex flex-col items-center justify-center h-full text-gray-500">
+ <FileText size={48} className="mb-3 opacity-30" />
+ <p className="text-sm">Select a page to view</p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/wiki/tabs/GraphTab.jsx b/client/src/components/wiki/tabs/GraphTab.jsx
new file mode 100644
index 0000000000..23061b0529
--- /dev/null
+++ b/client/src/components/wiki/tabs/GraphTab.jsx
@@ -0,0 +1,252 @@
+import { useState, useEffect, useRef, useCallback } from 'react';
+import { useNavigate } from 'react-router-dom';
+import * as api from '../../../services/api';
+import { RefreshCw, Network, ZoomIn, ZoomOut } from 'lucide-react';
+import { WIKI_CATEGORIES } from '../constants.jsx';
+
+export default function GraphTab({ vaultId }) {
+ const navigate = useNavigate();
+ const canvasRef = useRef(null);
+ const [graphData, setGraphData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [zoom, setZoom] = useState(1);
+ const [offset, setOffset] = useState({ x: 0, y: 0 });
+ const [dragging, setDragging] = useState(false);
+ const [hoveredNode, setHoveredNode] = useState(null);
+ const nodesRef = useRef([]);
+ const connectionCountsRef = useRef(new Map());
+
+ const loadGraph = useCallback(async () => {
+ setLoading(true);
+ const data = await api.getNotesVaultGraph(vaultId).catch(() => null);
+ if (data && !data.error) {
+ setGraphData(data);
+ layoutNodes(data);
+ }
+ setLoading(false);
+ }, [vaultId]);
+
+ useEffect(() => {
+ loadGraph();
+ }, [loadGraph]);
+
+ const layoutNodes = (data) => {
+ const { nodes, edges } = data;
+ if (nodes.length === 0) return;
+
+ // Pre-compute connection counts (O(E) instead of O(N*E) per render)
+ const counts = new Map();
+ for (const edge of edges) {
+ counts.set(edge.source, (counts.get(edge.source) || 0) + 1);
+ counts.set(edge.target, (counts.get(edge.target) || 0) + 1);
+ }
+ connectionCountsRef.current = counts;
+
+ // Group by folder for clustered layout
+ const groups = {};
+ for (const node of nodes) {
+ const group = node.folder?.split('/')[1] || 'root';
+ if (!groups[group]) groups[group] = [];
+ groups[group].push(node);
+ }
+
+ const groupKeys = Object.keys(groups);
+ const centerX = 400;
+ const centerY = 300;
+ const groupRadius = 200;
+ const positioned = [];
+
+ groupKeys.forEach((group, gi) => {
+ const angle = (gi / groupKeys.length) * Math.PI * 2;
+ const gx = centerX + Math.cos(angle) * groupRadius;
+ const gy = centerY + Math.sin(angle) * groupRadius;
+ const items = groups[group];
+ const nodeRadius = Math.min(80, items.length * 15);
+
+ items.forEach((node, ni) => {
+ const na = (ni / items.length) * Math.PI * 2;
+ positioned.push({
+ ...node,
+ x: gx + Math.cos(na) * nodeRadius,
+ y: gy + Math.sin(na) * nodeRadius,
+ group
+ });
+ });
+ });
+
+ nodesRef.current = positioned;
+ };
+
+ // Render graph on canvas
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !graphData || nodesRef.current.length === 0) return;
+
+ const ctx = canvas.getContext('2d');
+ const rect = canvas.parentElement.getBoundingClientRect();
+ canvas.width = rect.width;
+ canvas.height = rect.height;
+
+ const nodes = nodesRef.current;
+ const nodeMap = new Map(nodes.map(n => [n.path, n]));
+
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.save();
+ ctx.translate(offset.x + canvas.width / 2 - 400, offset.y + canvas.height / 2 - 300);
+ ctx.scale(zoom, zoom);
+
+ // Draw edges
+ ctx.strokeStyle = 'rgba(59, 130, 246, 0.15)';
+ ctx.lineWidth = 1;
+ for (const edge of graphData.edges) {
+ const source = nodeMap.get(edge.source);
+ const target = nodeMap.get(edge.target);
+ if (source && target) {
+ ctx.beginPath();
+ ctx.moveTo(source.x, source.y);
+ ctx.lineTo(target.x, target.y);
+ ctx.stroke();
+ }
+ }
+
+ // Draw nodes
+ const colorMap = Object.fromEntries(WIKI_CATEGORIES.map(c => [c.key, c.hex]));
+ colorMap.root = '#6b7280';
+
+ for (const node of nodes) {
+ const isHovered = hoveredNode === node.path;
+ const color = colorMap[node.group] || colorMap.root;
+ const radius = isHovered ? 7 : 5;
+
+ const connections = connectionCountsRef.current.get(node.path) || 0;
+ const nodeRadius = radius + Math.min(connections * 1.5, 6);
+
+ ctx.beginPath();
+ ctx.arc(node.x, node.y, nodeRadius, 0, Math.PI * 2);
+ ctx.fillStyle = isHovered ? color : color + '99';
+ ctx.fill();
+
+ if (isHovered) {
+ ctx.strokeStyle = color;
+ ctx.lineWidth = 2;
+ ctx.stroke();
+ }
+
+ // Label
+ if (isHovered || zoom > 0.8) {
+ ctx.font = `${isHovered ? 'bold ' : ''}${11 / zoom}px system-ui`;
+ ctx.fillStyle = isHovered ? '#ffffff' : '#9ca3af';
+ ctx.textAlign = 'center';
+ ctx.fillText(node.name, node.x, node.y + nodeRadius + 12 / zoom);
+ }
+ }
+
+ ctx.restore();
+ }, [graphData, zoom, offset, hoveredNode]);
+
+ const handleMouseMove = useCallback((e) => {
+ const canvas = canvasRef.current;
+ if (!canvas || nodesRef.current.length === 0) return;
+
+ if (dragging) {
+ setOffset(prev => ({
+ x: prev.x + e.movementX,
+ y: prev.y + e.movementY
+ }));
+ return;
+ }
+
+ const rect = canvas.getBoundingClientRect();
+ const mx = (e.clientX - rect.left - offset.x - canvas.width / 2 + 400) / zoom;
+ const my = (e.clientY - rect.top - offset.y - canvas.height / 2 + 300) / zoom;
+
+ let closest = null;
+ let minDist = 20;
+ for (const node of nodesRef.current) {
+ const dist = Math.hypot(node.x - mx, node.y - my);
+ if (dist < minDist) {
+ minDist = dist;
+ closest = node.path;
+ }
+ }
+ setHoveredNode(closest);
+ canvas.style.cursor = closest ? 'pointer' : dragging ? 'grabbing' : 'grab';
+ }, [dragging, zoom, offset]);
+
+ const handleClick = useCallback(() => {
+ if (hoveredNode) {
+ navigate('/wiki/browse', { state: { openNote: hoveredNode } });
+ }
+ }, [hoveredNode, navigate]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ if (!graphData || graphData.totalNodes === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center h-64 text-gray-500">
+ <Network size={32} className="mb-2 opacity-30" />
+ <p className="text-sm">No pages to graph yet</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="relative -m-4" style={{ height: 'calc(100vh - 220px)' }}>
+ {/* Controls */}
+ <div className="absolute top-4 right-4 z-10 flex items-center gap-2">
+ <span className="text-xs text-gray-500">{graphData.totalNodes} nodes, {graphData.totalEdges} edges</span>
+ <button
+ onClick={() => setZoom(z => Math.min(z + 0.2, 3))}
+ className="p-1.5 rounded bg-port-card border border-port-border text-gray-400 hover:text-white"
+ >
+ <ZoomIn size={14} />
+ </button>
+ <button
+ onClick={() => setZoom(z => Math.max(z - 0.2, 0.3))}
+ className="p-1.5 rounded bg-port-card border border-port-border text-gray-400 hover:text-white"
+ >
+ <ZoomOut size={14} />
+ </button>
+ <button
+ onClick={() => { setZoom(1); setOffset({ x: 0, y: 0 }); }}
+ className="px-2 py-1 rounded bg-port-card border border-port-border text-gray-400 hover:text-white text-xs"
+ >
+ Reset
+ </button>
+ <button onClick={loadGraph} className="p-1.5 rounded bg-port-card border border-port-border text-gray-400 hover:text-white">
+ <RefreshCw size={14} />
+ </button>
+ </div>
+
+ {/* Legend */}
+ <div className="absolute bottom-4 left-4 z-10 bg-port-card/90 border border-port-border rounded-lg p-3 flex flex-wrap gap-3 text-xs">
+ {WIKI_CATEGORIES.map(cat => (
+ <span key={cat.key} className="flex items-center gap-1">
+ <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: cat.hex }} />
+ <span className="text-gray-400">{cat.label}</span>
+ </span>
+ ))}
+ </div>
+
+ <canvas
+ ref={canvasRef}
+ className="w-full h-full"
+ onMouseMove={handleMouseMove}
+ onClick={handleClick}
+ onMouseDown={() => { if (!hoveredNode) setDragging(true); }}
+ onMouseUp={() => setDragging(false)}
+ onMouseLeave={() => { setDragging(false); setHoveredNode(null); }}
+ onWheel={(e) => {
+ e.preventDefault();
+ setZoom(z => Math.max(0.3, Math.min(3, z - e.deltaY * 0.001)));
+ }}
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/wiki/tabs/LogTab.jsx b/client/src/components/wiki/tabs/LogTab.jsx
new file mode 100644
index 0000000000..c894da8886
--- /dev/null
+++ b/client/src/components/wiki/tabs/LogTab.jsx
@@ -0,0 +1,111 @@
+import { useState, useEffect, useMemo } from 'react';
+import * as api from '../../../services/api';
+import { RefreshCw, Clock } from 'lucide-react';
+import { timeAgo } from '../../../utils/formatters';
+
+export default function LogTab({ vaultId, allNotes }) {
+ const [log, setLog] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const logExists = allNotes?.some(n => n.path === 'wiki/log.md');
+
+ useEffect(() => {
+ if (logExists) loadLog();
+ else { setLog(null); setLoading(false); }
+ }, [vaultId, logExists]);
+
+ const loadLog = async () => {
+ setLoading(true);
+ const data = await api.getNote(vaultId, 'wiki/log.md').catch(() => null);
+ setLog(data?.error ? null : data);
+ setLoading(false);
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ if (!log) {
+ return (
+ <div className="flex flex-col items-center justify-center h-64 text-gray-500">
+ <Clock size={32} className="mb-2 opacity-30" />
+ <p className="text-sm">No activity log found</p>
+ <p className="text-xs mt-1">The log is created automatically during wiki operations</p>
+ </div>
+ );
+ }
+
+ const entries = useMemo(() => {
+ const result = [];
+ const lines = (log.body || log.content || '').split('\n');
+ let currentEntry = null;
+
+ for (const line of lines) {
+ const match = line.match(/^## \[(\d{4}-\d{2}-\d{2})\] (\w+) \| (.+)$/);
+ if (match) {
+ if (currentEntry) result.push(currentEntry);
+ currentEntry = {
+ date: match[1],
+ type: match[2],
+ title: match[3],
+ details: []
+ };
+ } else if (currentEntry && line.trim() && !line.startsWith('# ') && !line.startsWith('---')) {
+ currentEntry.details.push(line);
+ }
+ }
+ if (currentEntry) result.push(currentEntry);
+ result.reverse();
+ return result;
+ }, [log]);
+
+ const typeColors = {
+ init: 'text-port-accent',
+ ingest: 'text-port-success',
+ query: 'text-port-warning',
+ lint: 'text-purple-400',
+ update: 'text-cyan-400'
+ };
+
+ return (
+ <div className="max-w-4xl mx-auto">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="text-sm font-medium text-white">Activity Log</h3>
+ <div className="flex items-center gap-2 text-xs text-gray-500">
+ <span>{entries.length} entries</span>
+ {log.modifiedAt && <span>Updated {timeAgo(log.modifiedAt)}</span>}
+ <button onClick={loadLog} className="p-1 rounded hover:bg-port-card text-gray-500 hover:text-white">
+ <RefreshCw size={12} />
+ </button>
+ </div>
+ </div>
+
+ <div className="space-y-3">
+ {entries.length === 0 ? (
+ <div className="text-center py-8 text-gray-500 text-sm">No log entries yet</div>
+ ) : entries.map((entry, i) => (
+ <div key={i} className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-3 mb-2">
+ <span className="text-xs text-gray-500 font-mono">{entry.date}</span>
+ <span className={`px-1.5 py-0.5 rounded text-xs font-medium uppercase ${typeColors[entry.type] || 'text-gray-400'} bg-port-bg`}>
+ {entry.type}
+ </span>
+ <span className="text-sm text-white font-medium">{entry.title}</span>
+ </div>
+ {entry.details.length > 0 && (
+ <div className="text-xs text-gray-400 space-y-0.5 ml-1">
+ {entry.details.map((line, j) => (
+ <div key={j}>{line}</div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/wiki/tabs/OverviewTab.jsx b/client/src/components/wiki/tabs/OverviewTab.jsx
new file mode 100644
index 0000000000..438f79d3d4
--- /dev/null
+++ b/client/src/components/wiki/tabs/OverviewTab.jsx
@@ -0,0 +1,124 @@
+import { useState, useEffect, useMemo } from 'react';
+import { useNavigate } from 'react-router-dom';
+import * as api from '../../../services/api';
+import { FolderOpen, RefreshCw, AlertTriangle } from 'lucide-react';
+import { timeAgo } from '../../../utils/formatters';
+import { WIKI_CATEGORIES, PageTypeIcon } from '../constants.jsx';
+
+export default function OverviewTab({ vaultId, stats, notes, allNotes, onRefresh }) {
+ const navigate = useNavigate();
+ const [lintReport, setLintReport] = useState(null);
+ const [loadingLint, setLoadingLint] = useState(false);
+
+ const lintExists = allNotes?.some(n => n.path === 'wiki/lint-report.md');
+
+ useEffect(() => {
+ if (lintExists) loadLintReport();
+ else setLintReport(null);
+ }, [vaultId, lintExists]);
+
+ const loadLintReport = async () => {
+ setLoadingLint(true);
+ const data = await api.getNote(vaultId, 'wiki/lint-report.md').catch(() => null);
+ setLintReport(data?.error ? null : data);
+ setLoadingLint(false);
+ };
+
+ const recentPages = useMemo(() =>
+ [...notes].sort((a, b) => new Date(b.modifiedAt) - new Date(a.modifiedAt)).slice(0, 10),
+ [notes]
+ );
+
+ return (
+ <div className="space-y-6">
+ {/* Stats grid */}
+ <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
+ <FolderOpen className="w-5 h-5 text-gray-400 mx-auto mb-1" />
+ <div className="text-2xl font-bold text-white">{stats.rawSources}</div>
+ <div className="text-xs text-gray-500">Raw Sources</div>
+ </div>
+ {WIKI_CATEGORIES.map(cat => (
+ <div key={cat.key} className="bg-port-card border border-port-border rounded-lg p-4 text-center">
+ <cat.icon className={`w-5 h-5 text-${cat.color} mx-auto mb-1`} />
+ <div className="text-2xl font-bold text-white">{stats[cat.key]}</div>
+ <div className="text-xs text-gray-500">{cat.label}</div>
+ </div>
+ ))}
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ {/* Recent activity */}
+ <div className="bg-port-card border border-port-border rounded-lg">
+ <div className="px-4 py-3 border-b border-port-border flex items-center justify-between">
+ <h3 className="text-sm font-medium text-white">Recent Activity</h3>
+ <button onClick={onRefresh} className="text-gray-500 hover:text-white">
+ <RefreshCw size={14} />
+ </button>
+ </div>
+ <div className="divide-y divide-port-border/50">
+ {recentPages.length === 0 ? (
+ <div className="p-4 text-center text-gray-500 text-sm">No wiki pages yet</div>
+ ) : recentPages.map(note => (
+ <button
+ key={note.path}
+ onClick={() => navigate('/wiki/browse', { state: { openNote: note.path } })}
+ className="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-port-bg/50 transition-colors"
+ >
+ <PageTypeIcon folder={note.folder} />
+ <div className="flex-1 min-w-0">
+ <div className="text-sm text-white truncate">{note.name}</div>
+ <div className="text-xs text-gray-500">{note.folder}</div>
+ </div>
+ <span className="text-xs text-gray-500 shrink-0">{timeAgo(note.modifiedAt)}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Lint report / health */}
+ <div className="bg-port-card border border-port-border rounded-lg">
+ <div className="px-4 py-3 border-b border-port-border flex items-center justify-between">
+ <h3 className="text-sm font-medium text-white">Health Report</h3>
+ {lintReport && (
+ <span className="text-xs text-gray-500">Updated {timeAgo(lintReport.modifiedAt)}</span>
+ )}
+ </div>
+ <div className="p-4">
+ {loadingLint ? (
+ <div className="flex items-center justify-center h-20">
+ <RefreshCw size={16} className="animate-spin text-port-accent" />
+ </div>
+ ) : lintReport ? (
+ <div className="text-sm text-gray-300 whitespace-pre-wrap max-h-64 overflow-auto font-mono text-xs leading-relaxed">
+ {lintReport.body?.slice(0, 2000) || 'Report empty'}
+ </div>
+ ) : (
+ <div className="text-center py-6">
+ <AlertTriangle size={24} className="text-gray-600 mx-auto mb-2" />
+ <p className="text-sm text-gray-500">No lint report yet</p>
+ <p className="text-xs text-gray-600 mt-1">The weekly wiki maintenance job will generate one, or ask the LLM to lint the wiki</p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Quick actions */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-sm font-medium text-white mb-3">How to Use</h3>
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-gray-400">
+ <div>
+ <span className="text-port-accent font-medium">Ingest:</span> Drop markdown files into <code className="text-gray-300">raw/</code> in Obsidian, then ask Claude to ingest them
+ </div>
+ <div>
+ <span className="text-port-accent font-medium">Query:</span> Ask questions about the wiki content — answers can be filed back as wiki pages
+ </div>
+ <div>
+ <span className="text-port-accent font-medium">Lint:</span> Ask Claude to health-check the wiki, or let the scheduled job handle it
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/wiki/tabs/SearchTab.jsx b/client/src/components/wiki/tabs/SearchTab.jsx
new file mode 100644
index 0000000000..c686a77f3e
--- /dev/null
+++ b/client/src/components/wiki/tabs/SearchTab.jsx
@@ -0,0 +1,111 @@
+import { useState, useCallback, useRef } from 'react';
+import { useNavigate } from 'react-router-dom';
+import * as api from '../../../services/api';
+import { Search, FileText, X, RefreshCw, Tag } from 'lucide-react';
+
+export default function SearchTab({ vaultId }) {
+ const navigate = useNavigate();
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState(null);
+ const [searching, setSearching] = useState(false);
+ const inputRef = useRef(null);
+
+ const handleSearch = useCallback(async () => {
+ if (!query.trim() || !vaultId) return;
+ setSearching(true);
+ const data = await api.searchNotes(vaultId, query.trim(), 50).catch(() => null);
+ setSearching(false);
+ if (data) setResults(data);
+ }, [query, vaultId]);
+
+ const openNote = (notePath) => {
+ navigate('/wiki/browse', { state: { openNote: notePath } });
+ };
+
+ return (
+ <div className="max-w-4xl mx-auto space-y-4">
+ {/* Search bar */}
+ <div className="relative">
+ <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ ref={inputRef}
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ onKeyDown={e => e.key === 'Enter' && handleSearch()}
+ placeholder="Search wiki pages and raw sources..."
+ className="w-full bg-port-card border border-port-border rounded-lg pl-11 pr-20 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ autoFocus
+ />
+ <div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">
+ {query && (
+ <button onClick={() => { setQuery(''); setResults(null); }} className="text-gray-500 hover:text-white">
+ <X size={16} />
+ </button>
+ )}
+ <button
+ onClick={handleSearch}
+ disabled={searching || !query.trim()}
+ className="px-3 py-1 rounded bg-port-accent text-white text-sm disabled:opacity-50"
+ >
+ {searching ? <RefreshCw size={14} className="animate-spin" /> : 'Search'}
+ </button>
+ </div>
+ </div>
+
+ {/* Results */}
+ {results && (
+ <div>
+ <div className="text-sm text-gray-500 mb-3">
+ {results.total} result{results.total !== 1 ? 's' : ''} for &ldquo;{results.query}&rdquo;
+ </div>
+ <div className="space-y-2">
+ {results.results.map(result => (
+ <button
+ key={result.path}
+ onClick={() => openNote(result.path)}
+ className="w-full text-left bg-port-card border border-port-border rounded-lg p-4 hover:border-port-accent/50 transition-colors"
+ >
+ <div className="flex items-center gap-2 mb-1">
+ <FileText size={14} className="text-port-accent shrink-0" />
+ <span className="text-white font-medium">{result.name}</span>
+ {result.titleMatch && (
+ <span className="px-1.5 py-0.5 rounded text-xs bg-port-accent/20 text-port-accent">title match</span>
+ )}
+ {result.folder && (
+ <span className="text-xs text-gray-500">{result.folder}</span>
+ )}
+ </div>
+ {result.snippets?.length > 0 && (
+ <div className="space-y-1 mt-2">
+ {result.snippets.slice(0, 2).map((snippet, i) => (
+ <div key={i} className="text-xs text-gray-400 truncate">
+ <span className="text-gray-600 mr-1">L{snippet.line}:</span>
+ {snippet.text}
+ </div>
+ ))}
+ </div>
+ )}
+ {result.tags?.length > 0 && (
+ <div className="flex items-center gap-1 mt-2">
+ <Tag size={10} className="text-gray-500" />
+ {result.tags.slice(0, 5).map(tag => (
+ <span key={tag} className="text-xs text-port-accent/70">#{tag}</span>
+ ))}
+ </div>
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {!results && (
+ <div className="text-center py-12 text-gray-500">
+ <Search size={32} className="mx-auto mb-3 opacity-30" />
+ <p className="text-sm">Search across all wiki pages and raw sources</p>
+ <p className="text-xs mt-1">Searches titles and content, ranked by relevance</p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/Wiki.jsx b/client/src/pages/Wiki.jsx
new file mode 100644
index 0000000000..d5eeb69461
--- /dev/null
+++ b/client/src/pages/Wiki.jsx
@@ -0,0 +1,178 @@
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import * as api from '../services/api';
+import toast from '../components/ui/Toast';
+import { BookOpen, Search, Network, FileText, BarChart3, RefreshCw, Activity } from 'lucide-react';
+
+import WikiOverviewTab from '../components/wiki/tabs/OverviewTab';
+import WikiBrowseTab from '../components/wiki/tabs/BrowseTab';
+import WikiSearchTab from '../components/wiki/tabs/SearchTab';
+import WikiGraphTab from '../components/wiki/tabs/GraphTab';
+import WikiLogTab from '../components/wiki/tabs/LogTab';
+
+const TABS = [
+ { id: 'overview', label: 'Overview', icon: BarChart3 },
+ { id: 'browse', label: 'Browse', icon: FileText },
+ { id: 'search', label: 'Search', icon: Search },
+ { id: 'graph', label: 'Graph', icon: Network },
+ { id: 'log', label: 'Log', icon: Activity }
+];
+
+export default function Wiki() {
+ const { tab } = useParams();
+ const navigate = useNavigate();
+ const activeTab = tab || 'overview';
+
+ const [vaults, setVaults] = useState([]);
+ const [selectedVaultId, setSelectedVaultId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [notes, setNotes] = useState([]);
+ const [totalNotes, setTotalNotes] = useState(0);
+
+ const loadVaults = useCallback(async () => {
+ const data = await api.getNotesVaults().catch(() => []);
+ setVaults(data);
+ if (data.length > 0) {
+ setSelectedVaultId(prev => prev || data[0].id);
+ }
+ setLoading(false);
+ }, []);
+
+ const loadNotes = useCallback(async () => {
+ if (!selectedVaultId) return;
+ const data = await api.scanNotesVault(selectedVaultId, { limit: 1000 }).catch(() => null);
+ if (data) {
+ setNotes(data.notes);
+ setTotalNotes(data.total);
+ }
+ }, [selectedVaultId]);
+
+ useEffect(() => {
+ loadVaults();
+ }, [loadVaults]);
+
+ useEffect(() => {
+ if (selectedVaultId) loadNotes();
+ }, [selectedVaultId, loadNotes]);
+
+ const wikiNotes = useMemo(() => notes.filter(n => n.folder?.startsWith('wiki')), [notes]);
+ const rawNotes = useMemo(() => notes.filter(n => n.folder?.startsWith('raw') || n.path?.startsWith('raw/')), [notes]);
+
+ const stats = useMemo(() => {
+ const byFolder = {};
+ for (const note of wikiNotes) {
+ const parts = note.folder?.split('/') || [];
+ const category = parts[1] || 'root';
+ byFolder[category] = (byFolder[category] || 0) + 1;
+ }
+ return {
+ total: wikiNotes.length,
+ sources: byFolder.sources || 0,
+ entities: byFolder.entities || 0,
+ concepts: byFolder.concepts || 0,
+ comparisons: byFolder.comparisons || 0,
+ synthesis: byFolder.synthesis || 0,
+ queries: byFolder.queries || 0,
+ rawSources: rawNotes.length
+ };
+ }, [wikiNotes, rawNotes]);
+
+ const handleRefresh = useCallback(() => {
+ loadNotes();
+ }, [loadNotes]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ if (vaults.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center h-full text-gray-500">
+ <BookOpen size={48} className="mb-3 opacity-30" />
+ <p className="text-sm">No Obsidian vaults connected</p>
+ <p className="text-xs mt-1">Go to Brain &gt; Notes to connect a vault first</p>
+ </div>
+ );
+ }
+
+ const renderTabContent = () => {
+ switch (activeTab) {
+ case 'overview':
+ return <WikiOverviewTab vaultId={selectedVaultId} stats={stats} notes={wikiNotes} allNotes={notes} onRefresh={handleRefresh} />;
+ case 'browse':
+ return <WikiBrowseTab vaultId={selectedVaultId} notes={wikiNotes} rawNotes={rawNotes} allNotes={notes} onRefresh={handleRefresh} />;
+ case 'search':
+ return <WikiSearchTab vaultId={selectedVaultId} onRefresh={handleRefresh} />;
+ case 'graph':
+ return <WikiGraphTab vaultId={selectedVaultId} />;
+ case 'log':
+ return <WikiLogTab vaultId={selectedVaultId} allNotes={notes} />;
+ default:
+ return <WikiOverviewTab vaultId={selectedVaultId} stats={stats} notes={wikiNotes} allNotes={notes} onRefresh={handleRefresh} />;
+ }
+ };
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* Header */}
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <div className="flex items-center gap-3">
+ <BookOpen className="w-8 h-8 text-port-accent" />
+ <div>
+ <h1 className="text-xl font-bold text-white">Wiki</h1>
+ <p className="text-sm text-gray-500">LLM-maintained knowledge base</p>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-4 text-sm">
+ <span className="text-gray-500">{stats.total} wiki pages</span>
+ <span className="text-gray-500">{stats.rawSources} sources</span>
+ {vaults.length > 1 && (
+ <select
+ value={selectedVaultId || ''}
+ onChange={e => setSelectedVaultId(e.target.value)}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ {vaults.map(v => (
+ <option key={v.id} value={v.id}>{v.name}</option>
+ ))}
+ </select>
+ )}
+ </div>
+ </div>
+
+ {/* Tab navigation */}
+ <div className="flex border-b border-port-border">
+ {TABS.map((tabItem) => {
+ const Icon = tabItem.icon;
+ const isActive = activeTab === tabItem.id;
+ return (
+ <button
+ key={tabItem.id}
+ onClick={() => navigate(`/wiki/${tabItem.id}`)}
+ className={`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
+ isActive
+ ? 'text-port-accent border-b-2 border-port-accent bg-port-accent/5'
+ : 'text-gray-400 hover:text-white hover:bg-port-card'
+ }`}
+ role="tab"
+ aria-selected={isActive}
+ >
+ <Icon size={16} aria-hidden="true" />
+ {tabItem.label}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Tab content */}
+ <div className="flex-1 overflow-auto p-4">
+ {renderTabContent()}
+ </div>
+ </div>
+ );
+}
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 25d4882a59..63df052b9f 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -369,6 +369,53 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-wiki-maintenance',
+ name: 'Wiki Maintenance',
+ description: 'Audit the LLM Wiki for contradictions, orphan pages, missing cross-references, outdated claims, and structural issues.',
+ category: 'wiki-maintenance',
+ interval: 'weekly',
+ intervalMs: WEEK,
+ scheduledTime: '03:00',
+ cronExpression: '0 3 * * 0',
+ enabled: false,
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ type: 'agent',
+ promptTemplate: `[Autonomous Job] Wiki Maintenance
+
+You are acting as my Chief of Staff, performing a weekly health check on my LLM Wiki.
+
+The wiki lives in an Obsidian vault. Read the schema file first:
+ Read the file at: ~/Library/Mobile Documents/iCloud~md~obsidian/Documents/PortOS/WIKI.md
+
+Then perform a full lint pass:
+
+1. Read wiki/index.md and wiki/log.md to understand current state
+2. Read every file in wiki/ (sources, entities, concepts, comparisons, synthesis, queries)
+3. Read every file in raw/ to check for unprocessed sources
+4. Check for:
+ - Contradictions between wiki pages (conflicting claims about the same topic)
+ - Orphan pages with no inbound wikilinks from other pages
+ - Concepts or entities mentioned repeatedly in text but lacking their own dedicated page
+ - Claims that appear outdated based on newer files in raw/
+ - Missing cross-references (pages that should link to each other but don't)
+ - Raw sources that have no corresponding wiki/sources/ summary page
+ - Broken wikilinks (links to pages that don't exist)
+ - Frontmatter inconsistencies (missing type, dates, sources, tags)
+5. Write the health report to wiki/lint-report.md with:
+ - Summary of findings grouped by severity (critical, warning, suggestion)
+ - Specific fixes for each issue (which file, what to change)
+ - Statistics (total pages, total links, orphan count, coverage %)
+6. Append a log entry to wiki/log.md
+7. Create CoS tasks for any critical issues that need manual attention
+
+Focus on actionable findings. The goal is to keep the wiki healthy as it grows.`,
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
]
let initPromise = null