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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: command palette (⌘K) + shared nav backbone with voice agent
Adam Eivy665da2778141
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..1cc3cebb34--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,12 @@+# Next Release++## Added++- **Global Command Palette (`⌘K`) with shared backbone for the voice agent** — the `CmdK` overlay has been upgraded from a content-search box into a true command palette. Typing fuzzy-matches across every navigable page (Dashboard, Brain, CoS sub-pages, MeatSpace tabs, Settings, etc.) and a curated set of voice-agent actions (Capture to Brain, PM2 status, Today's health summary, Current time, Feed digest, Recent Brain entries, etc.). Enter navigates or runs the action; arrow keys walk the list; Esc closes. The existing Brain/Memory/Apps/History/Health content search is preserved underneath as a second section so nothing regresses. Empty-query state shows a curated shortlist (Dashboard, Brain Inbox, Tasks, Goals, Review Hub, Capture to Brain, time, goal list, today's summary) so `⌘K` + Enter always does something useful.++ - **DRY backbone** — navigation is now defined once in `server/lib/navManifest.js` (`NAV_COMMANDS` + `resolveNavCommand` fuzzy resolver) and consumed by both the voice agent's `ui_navigate` tool and the palette via `GET /api/palette/manifest`. The old hand-synced 140-line `NAV_PAGES` map inside `server/services/voice/tools.js` is gone — adding a page to the manifest now updates both the sidebar's spoken/typed entrypoint AND the palette automatically, eliminating the "keep in sync with Layout.jsx" drift footgun.+ - **Palette-safe action whitelist** — `POST /api/palette/action/:id` dispatches a narrow subset of voice tools (brain/goals/meatspace/pm2/feeds/time/daily-log); DOM-driving tools (`ui_click`, `ui_fill`, `ui_select`, `ui_check`, `ui_navigate`) are intentionally excluded since the palette has no voice-agent DOM context to drive. Action descriptions + JSON Schema parameters are lifted from the same voice-tool registry, so palette hints and voice hints can never drift apart.+ - **Tests** — new `server/lib/navManifest.test.js` (9 tests covering shape invariants + fuzzy-match tiers + alias map) and `server/routes/palette.test.js` (5 tests covering manifest shape, action dispatch, whitelist enforcement). All 30 existing voice-tool tests continue to pass against the refactored resolver.+ - **Keyboard help modal updated** — the `?` shortcut list now advertises "Open command palette" instead of "Open search" and describes Enter as "Go to page, run action, or open result".++ Files: `server/lib/navManifest.js` (new), `server/routes/palette.js` (new), `server/services/voice/tools.js` (refactored), `server/index.js` (mounts `/api/palette`), `client/src/services/apiPalette.js` (new), `client/src/components/CmdKSearch.jsx` (palette behavior), `client/src/components/KeyboardHelp.jsx` (updated copy). Tests: `server/lib/navManifest.test.js`, `server/routes/palette.test.js`.diff --git a/CLAUDE.md b/CLAUDE.mdindex 695e5e24e1..0bfd3f652e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -69,6 +69,32 @@ PortOS depends on `portos-ai-toolkit` as an npm module for AI provider managemen- The toolkit uses spread in `updateProvider()` so existing providers preserve custom fields, but `createProvider()` has an explicit field list- After updating the toolkit, run `npm update portos-ai-toolkit` in PortOS to pull changes+### Command Palette & Voice Nav — shared backbone (`server/lib/navManifest.js`)++PortOS has a single source of truth for navigation: `server/lib/navManifest.js` exports `NAV_COMMANDS` (every navigable page: `{ id, path, label, section, aliases, keywords }`) and `resolveNavCommand()` (the fuzzy resolver). It is consumed by:++- The **`⌘K` Command Palette** (`client/src/components/CmdKSearch.jsx`) via `GET /api/palette/manifest`.+- The **voice agent's `ui_navigate` tool** (`server/services/voice/tools.js`) — so "take me to tasks" resolves through the same map the palette uses.++**When adding a new page, you MUST also add an entry to `NAV_COMMANDS`.** Adding only a `<Route>` in `App.jsx` and a sidebar link in `Layout.jsx` will leave the page unreachable from `⌘K` and un-navigable by voice. Entry shape:++```js+{ id: 'nav.<section>.<slug>', path: '/foo/bar', label: 'Bar', section: 'Foo',+ aliases: ['foo-bar', 'bar'], keywords: ['synonyms', 'context'] }+```++- `id` — stable, dotted (`nav.brain.inbox`). Must be unique.+- `path` — exact route the client router matches; must start with `/`.+- `section` — matches the sidebar group label so the palette and sidebar stay visually aligned.+- `aliases` — short spoken/typed tokens the user is likely to say. The voice agent's fuzzy resolver tries each alias with tiered matching; more aliases = more forgiving voice navigation.+- `keywords` — extra terms used only by the palette's in-UI scorer (synonyms, feature names).++Fail-fast guards at module load catch missing fields, non-slash paths, and duplicate ids — so a bad entry blocks server boot instead of silently breaking palette/voice.++**For NEW voice-tool-style actions that should appear in `⌘K`:** add the tool to `server/services/voice/tools.js` (it's the single source of action schemas), then whitelist its `id` in the `PALETTE_ACTIONS` array in `server/routes/palette.js` with a `section` + `label`. Do not duplicate the tool's description or parameters — the palette route hydrates them from `getToolSpecs()` at request time. DOM-driving tools (`ui_click`, `ui_fill`, etc.) stay off the palette whitelist because the palette has no live DOM context.++**Tests:** `server/lib/navManifest.test.js` asserts shape invariants + alias resolution; `server/routes/palette.test.js` asserts the manifest endpoint + action dispatch + whitelist enforcement. Any new entry is automatically covered by the shape-invariant tests.+### Slashdo Commands (`lib/slashdo`)PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`. This provides slash commands (`/do:review`, `/do:pr`, `/do:push`, `/do:release`, etc.) and shared libraries without requiring a separate global install.@@ -96,6 +122,7 @@ When CoS agents or AI tools work on managed apps outside PortOS, all research, p- **Above the fold** - keep actionable content and info above the fold and design pages for maximum information and access without scrolling- **No hardcoded localhost** - use `window.location.hostname` for URLs; app accessed via Tailscale remotely- **Alphabetical navigation** - sidebar nav items in `Layout.jsx` are alphabetically ordered after the Dashboard+CyberCity top section and separator; children within collapsible sections are also alphabetical+- **Every new page registers in the nav manifest** - when adding a `<Route>` + sidebar link, also add a `NAV_COMMANDS` entry in `server/lib/navManifest.js`. This makes the page reachable via `⌘K` and voice (`ui_navigate`) automatically. See the "Command Palette & Voice Nav" section above for the entry shape.- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback- **Single-line logging** - use emoji prefixes and string interpolation, never log full JSON blobs or arrays```jsdiff --git a/PLAN.md b/PLAN.mdindex 443eb3e7da..710702b52b 100644--- a/PLAN.md+++ b/PLAN.md@@ -8,6 +8,118 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]1. **God file decomposition** — routes/cos.js ✅, routes/scaffold.js ✅, client/api.js ✅, services/digital-twin.js ✅ (split into 10 focused modules), services/subAgentSpawner.js ✅ (split into 9 focused modules). **All god files decomposed.**+## Proposed Features — 2026-04-24++Three high-value work items drawn from an inventory of the current app surface (45+ pages, 50+ services, rich Brain/Memory/Twin/Goals/Calendar systems with no unified conversational surface, static Dashboard, and growing sidebar sprawl).++### 1. Global Command Palette (`Cmd+K` / `Ctrl+K`) ✅ SHIPPED 2026-04-24++> Shared-backbone implementation complete. `server/lib/navManifest.js` is the single source of truth for navigation, consumed by both the palette (`GET /api/palette/manifest`) and the voice agent (`ui_navigate` via `resolveNavCommand`). Palette-safe voice tools dispatch through `POST /api/palette/action/:id`. See CLAUDE.md "Command Palette & Voice Nav" section for the entry shape every new page must register.++**Problem.** The sidebar now carries 45+ pages across 10+ collapsible sections (Brain, Calendar, Character, CoS, Data, DevTools, Digital Twin, MeatSpace, Messages, Settings…). Finding a page is becoming the slowest part of using the app — especially on mobile where the drawer is a finger marathon. The keyboard-shortcut help modal (`?`) already proved that a global overlay paradigm works here.++**What it is.** A single keystroke-triggered overlay with a fuzzy-matched input that unifies four action types into one search surface:++- **Navigate** — every route in `Layout.jsx` nav config, plus deep routes (e.g. `/brain/inbox`, `/cos/schedule`, `/meatspace/alcohol`).+- **Do** — run CoS tasks (`> Run task "sec audit"`), quick-capture a thought to Brain (`> Capture: …`), queue a voice agent prompt, trigger a loop, run an allowlisted shell command.+- **Jump to entity** — fuzzy-pick an app, agent, goal, thought, memory, repo, JIRA issue by title/slug.+- **Recent** — last 5 navigations / last 5 CoS task runs as default results when the palette opens empty.++**Why it's high value.**+- Zero-training UX for power users; instant on mobile as well (drawer is slow on small screens).+- Naturally surfaces features the user hasn't rediscovered yet — a palette exposes the whole app without demanding nav hierarchy be "right".+- Reuses existing data: routes table, CoS task list, Brain capture endpoint, Goals + Apps + Agents lists.++**Approach.**+- `client/src/components/CommandPalette.jsx` — Headless listbox, modal overlay, subscribes to `keydown` for `Cmd+K` / `Ctrl+K`. Follow the existing keyboard-shortcut modal pattern so focus traps + ESC behavior are consistent.+- `client/src/services/commandRegistry.js` — Each nav entry, CoS task type, and quick-action exports a `{ id, label, keywords, section, run() }` record. Registry is assembled at app boot; individual pages can register contextual commands (e.g. Brain page registers "Capture thought").+- Fuzzy ranker: tiny owned implementation (subsequence score + section prefix weight) — no new dependency. ~80 lines.+- Entity search hits existing endpoints (`/api/apps`, `/api/agents`, `/api/goals`, `/api/brain/search`) debounced at 150ms; cache last result in a `Map` keyed by query.+- Keyboard shortcut registered via the existing shortcuts help modal so it shows up there too.++**Size.** Medium. ~1 week. No new deps. Mostly additive.++**Definition of done.**+- `Cmd+K` opens the palette from any page, mobile included.+- Typing `goals` jumps to `/digital-twin/goals` in ≤2 keystrokes.+- Typing `> capture buy milk` records a Brain thought without leaving the current page.+- Escape / outside-click closes cleanly; palette reopens with the last query pre-selected for 30s.++---++### 2. Customizable Dashboard with Saved Layouts++**Problem.** `client/src/pages/Dashboard.jsx` hard-codes the widget list: `BackupWidget`, `SystemHealthWidget`, `CosDashboardWidget`, `GoalProgressWidget`, `UpcomingTasksWidget`, `DecisionLogWidget`, `DeathClockWidget`, `ProactiveAlertsWidget`, `QuickBrainCapture`, `QuickTaskWidget`, `ReviewHubCard`. Every user-visible feature competes for space on the same grid; nothing can be hidden, reordered, or scoped to context. Already called out in `PLAN.md` Future Ideas as "Dashboard Customization — Drag-and-drop widgets, named layouts."++**What it is.** A dashboard with multiple named layouts the user can switch between via dropdown (or `Cmd+K`), each layout storing its own widget selection and order. Starter layouts:++- **Morning Review** — ProactiveAlerts, UpcomingTasks, ReviewHub, GoalProgress, DeathClock.+- **Focus** — QuickTask, CoS activity, UpcomingTasks only. Minimal chrome.+- **Health** — DeathClock, MeatSpace deltas, chronotype energy overlay, recent biomarkers.+- **Ops** — SystemHealth, CoS dashboard, Backup, recent app activity.+- **Everything** — the current all-widgets view, preserved as default.++**Why it's high value.**+- Dashboard is the most-opened page — every quality-of-life gain compounds.+- Context-sensitive layouts ("Focus" hides noise) directly support chronotype-aware work modes already in PortOS's DNA.+- Makes room to add new widgets later without further crowding — the feature scales.++**Approach.**+- `data/dashboard-layouts.json` — array of `{ id, name, widgets: [{ type, w, h, x, y, props? }] }`. Default layout seeded on first run from the current hard-coded order.+- `server/routes/dashboardLayouts.js` — GET/PUT with Zod validation; atomic write via `server/lib/fileUtils.js#atomicWrite` (which the audit backlog already wants extracted — this feature can be the forcing function).+- `client/src/components/DashboardGrid.jsx` — Lightweight 12-column grid. Evaluate: (a) write 150–200 lines of owned grid + drag handlers on top of HTML5 DnD, vs (b) resurrect the deferred `@dnd-kit/*` dep purely for accessibility (keyboard + ARIA). Decide in a brainstorm; lean toward owned code per project dep rules, falling back to `@dnd-kit` only if a11y correctness takes it past the 300-line ceiling.+- Widget registry: each widget exports `{ id, label, defaultSize, Component }`. Dashboard renders from the active layout, not a static import list.+- Layout picker: dropdown in the Dashboard header + palette commands `> Layout: Focus`.++**Size.** Medium–Large. ~1.5 weeks. Either no new deps (owned grid) or one resurrected dep with accessibility justification.++**Definition of done.**+- User can switch layouts from a dropdown and via `Cmd+K`.+- Drag-and-drop reorder persists across reload (keyboard-accessible).+- Hide/show widgets per layout; layouts survive PortOS restart.+- New widgets can be added by dropping a file into `client/src/components/dashboard/widgets/` and registering it — no Dashboard.jsx edit needed.++---++### 3. "Ask Yourself" — Unified Conversational Twin over Brain + Memory + Goals + Identity + Calendar++**Problem.** PortOS has spent many milestones building a rich model of the user: Brain (thoughts, daily log, notes, links), Memory (pgvector + BM25 hybrid retrieval), Digital Twin (identity, autobiography, personality, behavioral feedback), Goals, Calendar, MeatSpace biomarkers. These live on separate pages with separate inputs. There is still no single conversational surface where the user can ask their own system a question like *"What did I decide about my exercise routine in March?"*, *"What's on my plate this afternoon given how I slept?"*, or *"Draft a status update to my team as me."* Without this, the twin is a library nobody borrows from.++**What it is.** A dedicated "Ask" page (and a palette entry / voice intent) that runs a retrieval-augmented, twin-flavored chat:++- **Retrieval.** Every question fans out in parallel across memory semantic search, Brain notes full-text, Goals, Calendar events for the relevant time window, and recent MeatSpace metrics. Hybrid ranker picks top-N per source.+- **Persona.** System prompt injects the user's digital-twin preamble (tone, values, communication style) so answers sound like them — not like a generic assistant. Reuses the "Identity Context Injection" idea already in Future Ideas.+- **Modes.** `Ask` (answer as yourself), `Advise` (answer as a coach who knows you), `Draft` (produce text in your voice for a specified recipient/platform).+- **Trails.** Every answer shows its sources as expandable chips (click to jump to the Brain note / Memory / Goal / Calendar event). Builds trust and surfaces where knowledge is thin.+- **Continuations.** Each turn is saved to a short-lived conversation and can be one-click promoted to a Brain note, CoS task, or Goal update.++**Why it's high value.**+- Highest leverage feature relative to existing investment: nearly zero new data, maximum new utility. Takes the twin from "archive" to "assistant".+- Directly advances three GOALS.md pillars: Personal Knowledge Management, Digital Identity Modeling, Full Digital Autonomy.+- Pairs naturally with the existing voice widget — once text works, the same pipeline is the brain for "talk to yourself."++**Approach.**+- `server/services/askService.js` — Orchestrates: (a) parallel retrieval via existing `memoryEmbeddings` + `brain` + `goals` + `calendarGoogleApiSync` services, (b) source-weighted reranking, (c) prompt assembly with twin preamble from `services/character.js` / `services/identity.js`, (d) streamed completion through `portos-ai-toolkit` with the user's preferred model tier.+- `server/routes/ask.js` — `POST /api/ask` (stream via SSE or existing Socket.IO channel). Zod-validated `{ question, mode, timeWindow?, maxSources? }`.+- `client/src/pages/Ask.jsx` — Chat transcript, source chips, mode switcher, "turn into task/note/goal" actions. Deep-linkable per CLAUDE.md (e.g. `/ask/:conversationId`).+- Voice integration: register an `ask` intent that routes through the same service, so "Hey, what did I decide about X?" works without UI.+- Persistence: conversations live in `data/ask-conversations/` as JSON; auto-expire after 30 days unless promoted. Keeps the data store boring.+- Safety: no cross-user data (it's single-user), but cap retrieval to the user's own stores — never hit external APIs without explicit mode (`Ask web`).++**Size.** Large. ~3–4 weeks real-time. Ships in two slices: (a) text chat + sources (weeks 1–2), (b) voice + promotion actions (weeks 3–4). Each slice is shippable on its own.++**Definition of done (slice a).**+- `/ask` page accepts a question, streams an answer in the twin's voice, shows ≥3 source chips per answer.+- Clicking a source deep-links to the origin (Brain note, Memory item, Goal, Calendar event).+- Conversations persist and are listable at `/ask`.+- `Cmd+K` → typing a question routes into a new conversation.++**Definition of done (slice b).**+- Voice widget can route questions through the same pipeline.+- Each answer shows three 1-click promotions: "Save as Brain note", "Create CoS task", "Attach to Goal…".++---+## Backlog- [ ] **Voice CoS tool expansion** — tools now include the original domain set plus `ui_navigate`, `ui_list_interactables`, `ui_click`, `ui_fill`, `ui_select`, `ui_check` for accessibility-style page driving. Remaining candidates:diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex 1104c0cdf5..48a0542b66 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -1,14 +1,41 @@-import { useState, useEffect, useRef, useCallback } from 'react';+import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { createPortal } from 'react-dom';import { useNavigate } from 'react-router-dom';-import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2 } from 'lucide-react';+import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play } from 'lucide-react';import { useCmdKSearch } from '../hooks/useCmdKSearch';import { useScrollLock } from '../hooks/useScrollLock';-import { search } from '../services/api';+import { search, getPaletteManifest, runPaletteAction } from '../services/api';+import toast from './ui/Toast';import { modKey } from '../utils/platform';const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };+// Cheap subsequence-based fuzzy scorer. No new deps. Ranks:+// 1. exact label match (highest)+// 2. label starts-with+// 3. alias exact match+// 4. keyword contains+// 5. subsequence over label+const scoreCommand = (cmd, q) => {+ if (!q) return 0;+ const label = (cmd.label || '').toLowerCase();+ const aliases = (cmd.aliases || []).map((a) => a.toLowerCase());+ const keywords = (cmd.keywords || []).map((k) => k.toLowerCase());+ const section = (cmd.section || '').toLowerCase();++ if (label === q) return 1000;+ if (label.startsWith(q)) return 800 - (label.length - q.length);+ if (aliases.includes(q)) return 750;+ if (label.includes(q)) return 500;+ if (aliases.some((a) => a.includes(q))) return 400;+ if (keywords.some((k) => k.includes(q))) return 300;+ if (section.includes(q)) return 150;+ // Subsequence fallback: every character in q appears in order inside label.+ let i = 0;+ for (const ch of label) if (ch === q[i]) i += 1;+ return i === q.length ? 100 + i : 0;+};+function Highlight({ text, query }) {if (!query || !text) return <span>{text}</span>;const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');@@ -30,61 +57,104 @@ export default function CmdKSearch() {const inputRef = useRef(null);const [query, setQuery] = useState('');- const [results, setResults] = useState([]);+ const [manifest, setManifest] = useState(null);+ const [searchResults, setSearchResults] = useState([]);const [loading, setLoading] = useState(false);const [focusedIndex, setFocusedIndex] = useState(0);const [expandedSources, setExpandedSources] = useState(new Set());+ const [running, setRunning] = useState(false);const resultRefs = useRef([]);- // Auto-focus input when overlay opensuseEffect(() => {if (open) inputRef.current?.focus();}, [open]);- // Lock body scroll when openuseScrollLock(open);- // Clear state when overlay closesuseEffect(() => {if (!open) {setQuery('');- setResults([]);+ setSearchResults([]);setFocusedIndex(0);setExpandedSources(new Set());}}, [open]);- // Debounced search-as-you-type+ // Lazy-load the palette manifest on first open and cache for the session.+ // The manifest rarely changes; re-fetching on every open wastes a roundtrip.+ useEffect(() => {+ if (!open || manifest) return;+ getPaletteManifest()+ .then((data) => setManifest(data))+ .catch(() => setManifest({ nav: [], actions: [] }));+ }, [open, manifest]);+useEffect(() => {if (query.length < 2) {- setResults([]);+ setSearchResults([]);setLoading(false);return;}setLoading(true);const timer = setTimeout(() => {search(query)- .then(data => {- setResults(data?.sources ?? []);- })+ .then((data) => setSearchResults(data?.sources ?? [])).finally(() => setLoading(false));}, 300);return () => clearTimeout(timer);}, [query]);- // Reset focusedIndex when results changeuseEffect(() => {setFocusedIndex(0);- }, [results]);+ }, [searchResults, query]);++ const { navHits, actionHits } = useMemo(() => {+ if (!manifest) return { navHits: [], actionHits: [] };+ const q = query.trim().toLowerCase();+ if (!q) {+ // Default view: a curated set of "most useful" nav + actions so Enter+ // on empty query has meaning instead of doing nothing.+ const curatedNav = manifest.nav+ .filter((c) => ['nav.dashboard', 'nav.brain.inbox', 'nav.cos.tasks', 'nav.goals', 'nav.review-hub'].includes(c.id));+ const curatedActions = manifest.actions+ .filter((a) => ['brain_capture', 'time_now', 'goal_list', 'meatspace_summary_today'].includes(a.id));+ return { navHits: curatedNav, actionHits: curatedActions };+ }+ const scoredNav = manifest.nav+ .map((c) => ({ cmd: c, score: scoreCommand(c, q) }))+ .filter((x) => x.score > 0)+ .sort((a, b) => b.score - a.score)+ .slice(0, 8)+ .map((x) => x.cmd);+ const scoredActions = manifest.actions+ .map((a) => ({ cmd: a, score: scoreCommand(a, q) }))+ .filter((x) => x.score > 0)+ .sort((a, b) => b.score - a.score)+ .slice(0, 5)+ .map((x) => x.cmd);+ return { navHits: scoredNav, actionHits: scoredActions };+ }, [manifest, query]);++ const flatCommands = useMemo(+ () => [+ ...navHits.map((c) => ({ kind: 'nav', ...c })),+ ...actionHits.map((a) => ({ kind: 'action', ...a })),+ ],+ [navHits, actionHits]+ );++ const flatSearchResults = useMemo(+ () =>+ searchResults.flatMap((source) => {+ const isExpanded = expandedSources.has(source.id);+ const visible = isExpanded ? source.results : source.results.slice(0, 3);+ return visible.map((r) => ({ ...r, kind: 'search', sourceId: source.id }));+ }),+ [searchResults, expandedSources]+ );- // Compute flat result list for keyboard navigation- const flatResults = results.flatMap(source => {- const isExpanded = expandedSources.has(source.id);- const visible = isExpanded ? source.results : source.results.slice(0, 3);- return visible.map(result => ({ ...result, sourceId: source.id }));- });+ const combined = useMemo(() => [...flatCommands, ...flatSearchResults], [flatCommands, flatSearchResults]);- // Scroll focused result into viewuseEffect(() => {const el = resultRefs.current[focusedIndex];if (el) el.scrollIntoView({ block: 'nearest' });@@ -92,21 +162,48 @@ export default function CmdKSearch() {const close = useCallback(() => setOpen(false), [setOpen]);- const handleNavigate = useCallback((url) => {- navigate(url);- close();+ const dispatchCommand = useCallback(async (item) => {+ if (item.kind === 'nav') {+ navigate(item.path);+ close();+ return;+ }+ if (item.kind === 'action') {+ // Actions with required args can't be run blind from the palette — the+ // parameters schema is served with the manifest for future inline arg+ // UIs. For v1, only dispatch tools whose required list is empty. For+ // others, offer a hint toast telling the user to use voice or the+ // relevant page.+ const required = item.parameters?.required || [];+ if (required.length > 0) {+ toast(`${item.label} needs arguments — use voice or open the related page.`);+ return;+ }+ setRunning(true);+ const res = await runPaletteAction(item.id).catch((e) => ({ error: e.message }));+ setRunning(false);+ const summary = res?.result?.summary || res?.error || `${item.label} ran.`;+ if (res?.ok === false || res?.error) toast.error(summary);+ else toast.success(summary);+ close();+ return;+ }+ if (item.kind === 'search') {+ navigate(item.url);+ close();+ }}, [navigate, close]);const handleKeyDown = (e) => {if (e.key === 'ArrowDown') {e.preventDefault();- if (flatResults.length > 0) setFocusedIndex(i => Math.min(i + 1, flatResults.length - 1));+ if (combined.length > 0) setFocusedIndex((i) => Math.min(i + 1, combined.length - 1));} else if (e.key === 'ArrowUp') {e.preventDefault();- if (flatResults.length > 0) setFocusedIndex(i => Math.max(i - 1, 0));+ if (combined.length > 0) setFocusedIndex((i) => Math.max(i - 1, 0));} else if (e.key === 'Enter') {- const item = flatResults[focusedIndex];- if (item) handleNavigate(item.url);+ const item = combined[focusedIndex];+ if (item) dispatchCommand(item);} else if (e.key === 'Escape') {close();}@@ -114,62 +211,112 @@ export default function CmdKSearch() {if (!open) return null;- // Build a flat index counter across sources for focusedIndex mappinglet flatIdx = 0;+ const renderCommandRow = (item, kindLabel) => {+ const currentIdx = flatIdx++;+ const isFocused = focusedIndex === currentIdx;+ const Icon = item.kind === 'nav' ? Navigation : Play;+ const subtitle = item.kind === 'nav'+ ? `${item.section} · ${item.path}`+ : (item.description ? item.description.slice(0, 80) : item.section || '');+ return (+ <div+ key={`${item.kind}:${item.id}`}+ ref={(el) => { resultRefs.current[currentIdx] = el; }}+ onClick={() => dispatchCommand(item)}+ className={`flex items-start gap-3 px-3 py-2 rounded-lg cursor-pointer transition-colors ${+ isFocused ? 'bg-port-accent/10' : 'hover:bg-white/5'+ }`}+ role="option"+ aria-selected={isFocused}+ >+ <Icon size={14} className="shrink-0 mt-0.5 text-gray-400" />+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-white truncate">+ <Highlight text={item.label} query={query} />+ </p>+ {subtitle && (+ <p className="text-xs text-gray-500 truncate mt-0.5">{subtitle}</p>+ )}+ </div>+ <span className="text-[10px] uppercase tracking-wide text-gray-500 shrink-0 mt-1">{kindLabel}</span>+ </div>+ );+ };+const overlay = (<divclassName="fixed inset-0 z-[9999] flex items-start justify-center pt-[10vh]"onKeyDown={handleKeyDown}>- {/* Backdrop */}<divclassName="absolute inset-0 bg-black/60"onClick={close}aria-hidden="true"/>- {/* Modal container */}<div className="relative w-full max-w-3xl mx-4 bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden">-- {/* Search input row */}<div className="flex items-center gap-3 px-4 py-4 border-b border-port-border"><Search size={18} className="text-gray-400 shrink-0" /><inputref={inputRef}type="text"value={query}- onChange={e => setQuery(e.target.value)}- placeholder="Search Brain, Memory, Health..."+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Go to page, run an action, or search Brain / Memory / Apps…"className="flex-1 bg-transparent text-white placeholder-gray-500 outline-hidden text-sm"- aria-label="Search PortOS"+ aria-label="Command palette"/>+ {running && <Loader2 size={14} className="animate-spin text-gray-400 shrink-0" />}<span className="text-xs text-gray-500 border border-port-border rounded px-1.5 py-0.5 shrink-0">{`${modKey}+K`}</span></div>- {/* Results area */}<div className="max-h-96 overflow-y-auto p-2">+ {/* Commands: Navigate */}+ {navHits.length > 0 && (+ <div className="mb-2">+ <div className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400 uppercase tracking-wide">+ <Navigation size={14} />+ <span>Go to</span>+ </div>+ {navHits.map((c) => renderCommandRow({ kind: 'nav', ...c }, 'GO'))}+ </div>+ )}++ {/* Commands: Run */}+ {actionHits.length > 0 && (+ <div className="mb-2">+ <div className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400 uppercase tracking-wide">+ <Play size={14} />+ <span>Run</span>+ </div>+ {actionHits.map((a) => renderCommandRow({ kind: 'action', ...a }, 'RUN'))}+ </div>+ )}++ {/* Content search (lazy — only when query ≥ 2 chars) */}{loading && (- <div className="flex items-center justify-center py-8">- <Loader2 size={20} className="animate-spin text-gray-400" />+ <div className="flex items-center justify-center py-4">+ <Loader2 size={18} className="animate-spin text-gray-400" /></div>)}- {!loading && query.length >= 2 && results.length === 0 && (+ {!loading && query.length >= 2 && searchResults.length === 0 && flatCommands.length === 0 && (<div className="text-center text-sm text-gray-500 py-8">No results for “{query}”</div>)}- {!loading && query.length < 2 && (+ {!loading && !query && flatCommands.length === 0 && (<div className="text-center text-sm text-gray-600 py-8">- Type 2+ characters to search across Brain, Memory, Apps, History, and Health+ Start typing to go to a page, run an action, or search.</div>)}- {!loading && results.map(source => {+ {!loading && searchResults.map((source) => {const SourceIcon = ICON_MAP[source.icon] ?? Search;const isExpanded = expandedSources.has(source.id);const visible = isExpanded ? source.results : source.results.slice(0, 3);@@ -177,23 +324,19 @@ export default function CmdKSearch() {return (<div key={source.id} className="mb-2">- {/* Source header */}<div className="flex items-center gap-2 px-3 py-2 text-xs text-gray-400 uppercase tracking-wide"><SourceIcon size={14} /><span>{source.label}</span></div>- {/* Result rows */}- {visible.map(result => {- const currentIdx = flatIdx;- flatIdx++;+ {visible.map((result) => {+ const currentIdx = flatIdx++;const isFocused = focusedIndex === currentIdx;-return (<divkey={result.id}- ref={el => { resultRefs.current[currentIdx] = el; }}- onClick={() => handleNavigate(result.url)}+ ref={(el) => { resultRefs.current[currentIdx] = el; }}+ onClick={() => dispatchCommand({ kind: 'search', ...result })}className={`flex items-start gap-3 px-3 py-2 rounded-lg cursor-pointer transition-colors ${isFocused ? 'bg-port-accent/10' : 'hover:bg-white/5'}`}@@ -212,10 +355,9 @@ export default function CmdKSearch() {);})}- {/* Show more button */}{hasMore && (<button- onClick={() => setExpandedSources(prev => new Set([...prev, source.id]))}+ onClick={() => setExpandedSources((prev) => new Set([...prev, source.id]))}className="text-xs text-port-accent px-3 py-1 hover:underline">Show {source.results.length - 3} more@@ -225,6 +367,11 @@ export default function CmdKSearch() {);})}</div>++ <div className="flex items-center justify-between gap-2 px-4 py-2 border-t border-port-border text-[11px] text-gray-500">+ <span>↑↓ navigate · ↵ run · Esc close</span>+ <span>Shared backbone with voice agent</span>+ </div></div></div>);diff --git a/client/src/components/KeyboardHelp.jsx b/client/src/components/KeyboardHelp.jsxindex 15f3c996c0..e962948256 100644--- a/client/src/components/KeyboardHelp.jsx+++ b/client/src/components/KeyboardHelp.jsx@@ -9,17 +9,17 @@ const SHORTCUT_SECTIONS = [{title: 'Global',shortcuts: [- { keys: [`${modKey}+K`], description: 'Open search' },+ { keys: [`${modKey}+K`], description: 'Open command palette' },{ keys: ['?'], description: 'Show keyboard shortcuts' },{ keys: ['Esc'], description: 'Close overlays' },],},{- title: 'Search (when open)',+ title: 'Command Palette (when open)',shortcuts: [- { keys: ['\u2191', '\u2193'], description: 'Navigate results' },- { keys: ['Enter'], description: 'Go to selected result' },- { keys: ['Esc'], description: 'Close search' },+ { keys: ['\u2191', '\u2193'], description: 'Navigate commands and results' },+ { keys: ['Enter'], description: 'Go to page, run action, or open result' },+ { keys: ['Esc'], description: 'Close palette' },],},{diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 91844becba..a1ce5e06e1 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -32,6 +32,7 @@ export * from './apiDigitalTwin.js';export * from './apiMeatspace.js';export * from './apiMortalLoom.js';export * from './apiOpenClaw.js';+export * from './apiPalette.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiPalette.js b/client/src/services/apiPalette.jsnew file mode 100644index 0000000000..1069d7e131--- /dev/null+++ b/client/src/services/apiPalette.js@@ -0,0 +1,9 @@+import { request } from './apiCore.js';++export const getPaletteManifest = () => request('/palette/manifest');++export const runPaletteAction = (id, args = {}) =>+ request(`/palette/action/${encodeURIComponent(id)}`, {+ method: 'POST',+ body: JSON.stringify({ args }),+ });diff --git a/server/index.js b/server/index.jsindex f35fa7aac7..1f56bbd1cc 100644--- a/server/index.js+++ b/server/index.js@@ -60,6 +60,7 @@ import autobiographyRoutes from './routes/autobiography.js';import backupRoutes from './routes/backup.js';import databaseRoutes from './routes/database.js';import searchRoutes from './routes/search.js';+import paletteRoutes from './routes/palette.js';import dataSyncRoutes from './routes/dataSync.js';import identityRoutes from './routes/identity.js';import instancesRoutes from './routes/instances.js';@@ -244,6 +245,7 @@ app.use('/api/git', gitRoutes);app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);app.use('/api/search', searchRoutes);+app.use('/api/palette', paletteRoutes);app.use('/api/attachments', attachmentsRoutes);app.use('/api/backup', backupRoutes);app.use('/api/database', databaseRoutes);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsnew file mode 100644index 0000000000..611f98e1d4--- /dev/null+++ b/server/lib/navManifest.js@@ -0,0 +1,217 @@+// Single source of truth for PortOS navigation commands.+//+// Consumed by:+// - server/services/voice/tools.js#ui_navigate (voice agent resolves "take me to tasks")+// - server/routes/palette.js (Cmd+K palette fetches the manifest)+// - client/src/components/CmdKSearch.jsx (renders nav commands in the palette)+//+// Adding a page to the sidebar? Add an entry here first; voice + palette pick it up automatically.+//+// Entry shape:+// { id, path, label, section, aliases?: string[], keywords?: string[] }+//+// - id: stable machine identifier ("nav.brain.inbox"); used by the palette + action dispatch.+// - path: exact route the client router resolves.+// - label: human-readable name shown in the palette.+// - section: grouping label; matches the sidebar section so the palette and sidebar agree on structure.+// - aliases: short spoken/typed tokens the user is likely to say ("inbox", "cos", "twin"). Fuzzy matcher tries exact alias first.+// - keywords: extra terms for the palette's in-UI fuzzy search (synonyms, context words).++export const NAV_COMMANDS = [+ // ── Main (sidebar singletons) ─────────────────────────────────────────+ { id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['dashboard', 'home'], keywords: ['overview', 'start'] },+ { id: 'nav.review-hub', path: '/review', label: 'Review Hub', section: 'Main', aliases: ['review', 'review-hub'] },+ { id: 'nav.cybercity', path: '/city', label: 'CyberCity', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization'] },+ { id: 'nav.character', path: '/character', label: 'Character', section: 'Main', aliases: ['character'] },+ { id: 'nav.data', path: '/data', label: 'Data', section: 'Main', aliases: ['data'] },+ { id: 'nav.goals', path: '/goals/list', label: 'Goals', section: 'Main', aliases: ['goals'] },+ { id: 'nav.insights', path: '/insights/overview', label: 'Insights', section: 'Main', aliases: ['insights'] },+ { id: 'nav.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Main', aliases: ['openclaw'] },+ { id: 'nav.social-agents', path: '/agents', label: 'Social Agents', section: 'Main', aliases: ['social-agents'] },+ { id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },+ { id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Main', aliases: ['shell', 'terminal'] },+ { id: 'nav.browser', path: '/browser', label: 'Browser', section: 'Main', aliases: ['browser'] },+ { id: 'nav.instances', path: '/instances', label: 'Instances', section: 'Main', aliases: ['instances'] },+ { id: 'nav.loops', path: '/loops', label: 'Loops', section: 'Main', aliases: ['loops'] },++ // ── Brain ─────────────────────────────────────────────────────────────+ { id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Inbox', section: 'Brain', aliases: ['brain', 'brain-inbox', 'inbox'] },+ { id: 'nav.brain.config', path: '/brain/config', label: 'Config', section: 'Brain', aliases: ['brain-config'] },+ { id: 'nav.brain.daily-log', path: '/brain/daily-log', label: 'Daily Log', section: 'Brain', aliases: ['daily-log', 'journal'] },+ { id: 'nav.brain.digest', path: '/brain/digest', label: 'Digest', section: 'Brain', aliases: ['brain-digest'] },+ { id: 'nav.brain.graph', path: '/brain/graph', label: 'Graph', section: 'Brain', aliases: ['brain-graph'] },+ { id: 'nav.brain.links', path: '/brain/links', label: 'Links', section: 'Brain', aliases: ['brain-links'] },+ { id: 'nav.brain.memory', path: '/brain/memory', label: 'Memory', section: 'Brain', aliases: ['brain-memory', 'memory'] },+ { id: 'nav.brain.notes', path: '/brain/notes', label: 'Notes', section: 'Brain', aliases: ['brain-notes', 'notes'] },+ { id: 'nav.brain.trust', path: '/brain/trust', label: 'Trust', section: 'Brain', aliases: ['brain-trust'] },++ // ── Calendar ──────────────────────────────────────────────────────────+ { id: 'nav.calendar.agenda', path: '/calendar/agenda', label: 'Agenda', section: 'Calendar', aliases: ['calendar', 'agenda'] },+ { id: 'nav.calendar.config', path: '/calendar/config', label: 'Config', section: 'Calendar', aliases: ['calendar-config'] },+ { id: 'nav.calendar.day', path: '/calendar/day', label: 'Day', section: 'Calendar', aliases: ['calendar-day'] },+ { id: 'nav.calendar.week', path: '/calendar/week', label: 'Week', section: 'Calendar', aliases: ['calendar-week'] },+ { id: 'nav.calendar.month', path: '/calendar/month', label: 'Month', section: 'Calendar', aliases: ['calendar-month'] },+ { id: 'nav.calendar.lifetime', path: '/calendar/lifetime', label: 'Lifetime', section: 'Calendar', aliases: ['calendar-lifetime'] },+ { id: 'nav.calendar.review', path: '/calendar/review', label: 'Review', section: 'Calendar', aliases: ['calendar-review'] },+ { id: 'nav.calendar.sync', path: '/calendar/sync', label: 'Sync', section: 'Calendar', aliases: ['calendar-sync'] },++ // ── Chief of Staff ────────────────────────────────────────────────────+ { id: 'nav.cos.tasks', path: '/cos/tasks', label: 'Tasks', section: 'Chief of Staff', aliases: ['tasks', 'cos', 'cos-tasks', 'chief-of-staff'] },+ { id: 'nav.cos.agents', path: '/cos/agents', label: 'Agents', section: 'Chief of Staff', aliases: ['agents', 'cos-agents'] },+ { id: 'nav.cos.briefing', path: '/cos/briefing', label: 'Briefing', section: 'Chief of Staff', aliases: ['briefing', 'cos-briefing'] },+ { id: 'nav.cos.config', path: '/cos/config', label: 'Config', section: 'Chief of Staff', aliases: ['cos-config'] },+ { id: 'nav.cos.digest', path: '/cos/digest', label: 'Digest', section: 'Chief of Staff', aliases: ['cos-digest'] },+ { id: 'nav.cos.gsd', path: '/cos/gsd', label: 'GSD', section: 'Chief of Staff', aliases: ['gsd', 'cos-gsd'] },+ { id: 'nav.cos.health', path: '/cos/health', label: 'Health', section: 'Chief of Staff', aliases: ['cos-health'] },+ { id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', aliases: ['cos-learning'] },+ { id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', aliases: ['cos-memory'] },+ { id: 'nav.cos.schedule', path: '/cos/schedule', label: 'Schedule', section: 'Chief of Staff', aliases: ['schedule', 'cos-schedule'] },+ { id: 'nav.cos.scripts', path: '/cos/scripts', label: 'Scripts', section: 'Chief of Staff', aliases: ['cos-scripts'] },+ { id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Streaks', section: 'Chief of Staff', aliases: ['streaks', 'cos-productivity'] },+ { id: 'nav.cos.jobs', path: '/cos/jobs', label: 'System Tasks', section: 'Chief of Staff', aliases: ['cos-jobs', 'system-tasks'] },++ // ── Dev Tools ─────────────────────────────────────────────────────────+ { id: 'nav.devtools.runs', path: '/devtools/runs', label: 'AI Runs', section: 'Dev Tools', aliases: ['ai-runs', 'devtools'] },+ { id: 'nav.devtools.agents', path: '/devtools/agents', label: 'AI Agents', section: 'Dev Tools', aliases: ['ai-agents'] },+ { id: 'nav.devtools.runner', path: '/devtools/runner', label: 'Code', section: 'Dev Tools', aliases: ['devtools-runner'] },+ { id: 'nav.devtools.datadog', path: '/devtools/datadog', label: 'DataDog', section: 'Dev Tools', aliases: ['datadog', 'devtools-datadog'] },+ { id: 'nav.devtools.github', path: '/devtools/github', label: 'GitHub', section: 'Dev Tools', aliases: ['github', 'devtools-github'] },+ { id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },+ { id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', aliases: ['jira', 'devtools-jira'] },+ { id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', aliases: ['jira-reports'] },+ { id: 'nav.devtools.processes', path: '/devtools/processes', label: 'Processes', section: 'Dev Tools', aliases: ['devtools-processes'] },+ { id: 'nav.devtools.submodules', path: '/devtools/submodules', label: 'Submodules', section: 'Dev Tools', aliases: ['devtools-submodules'] },+ { id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },+ { id: 'nav.feature-agents', path: '/feature-agents', label: 'Feature Agents', section: 'Dev Tools', aliases: ['feature-agents'] },++ // ── Digital Twin ──────────────────────────────────────────────────────+ { id: 'nav.twin.overview', path: '/digital-twin/overview', label: 'Overview', section: 'Digital Twin', aliases: ['digital-twin', 'twin'] },+ { id: 'nav.twin.accounts', path: '/digital-twin/accounts', label: 'Accounts', section: 'Digital Twin', aliases: ['twin-accounts'] },+ { id: 'nav.twin.autobiography', path: '/digital-twin/autobiography', label: 'Autobiography', section: 'Digital Twin', aliases: ['twin-autobiography', 'autobiography'] },+ { id: 'nav.twin.documents', path: '/digital-twin/documents', label: 'Documents', section: 'Digital Twin', aliases: ['twin-documents'] },+ { id: 'nav.twin.enrich', path: '/digital-twin/enrich', label: 'Enrich', section: 'Digital Twin', aliases: ['twin-enrich'] },+ { id: 'nav.twin.export', path: '/digital-twin/export', label: 'Export', section: 'Digital Twin', aliases: ['twin-export'] },+ { id: 'nav.twin.goals', path: '/digital-twin/goals', label: 'Goals', section: 'Digital Twin', aliases: ['twin-goals'] },+ { id: 'nav.twin.identity', path: '/digital-twin/identity', label: 'Identity', section: 'Digital Twin', aliases: ['twin-identity', 'identity'] },+ { id: 'nav.twin.import', path: '/digital-twin/import', label: 'Import', section: 'Digital Twin', aliases: ['twin-import'] },+ { id: 'nav.twin.interview', path: '/digital-twin/interview', label: 'Interview', section: 'Digital Twin', aliases: ['twin-interview'] },+ { id: 'nav.twin.taste', path: '/digital-twin/taste', label: 'Taste', section: 'Digital Twin', aliases: ['twin-taste'] },+ { id: 'nav.twin.test', path: '/digital-twin/test', label: 'Test', section: 'Digital Twin', aliases: ['twin-test'] },++ // ── MeatSpace ─────────────────────────────────────────────────────────+ { id: 'nav.meatspace.overview', path: '/meatspace/overview', label: 'Overview', section: 'MeatSpace', aliases: ['meatspace'] },+ { id: 'nav.meatspace.health', path: '/meatspace/health', label: 'Health', section: 'MeatSpace', aliases: ['meatspace-health', 'health'] },+ { id: 'nav.meatspace.body', path: '/meatspace/body', label: 'Body', section: 'MeatSpace', aliases: ['meatspace-body', 'body'] },+ { id: 'nav.meatspace.alcohol', path: '/meatspace/alcohol', label: 'Alcohol', section: 'MeatSpace', aliases: ['meatspace-alcohol', 'alcohol'] },+ { id: 'nav.meatspace.nicotine', path: '/meatspace/nicotine', label: 'Nicotine', section: 'MeatSpace', aliases: ['meatspace-nicotine', 'nicotine'] },+ { id: 'nav.meatspace.age', path: '/meatspace/age', label: 'Age', section: 'MeatSpace', aliases: ['meatspace-age'] },+ { id: 'nav.meatspace.blood', path: '/meatspace/blood', label: 'Blood', section: 'MeatSpace', aliases: ['meatspace-blood', 'blood'] },+ { id: 'nav.meatspace.genome', path: '/meatspace/genome', label: 'Genome', section: 'MeatSpace', aliases: ['meatspace-genome', 'genome'] },+ { id: 'nav.meatspace.lifestyle', path: '/meatspace/lifestyle', label: 'Lifestyle', section: 'MeatSpace', aliases: ['meatspace-lifestyle', 'lifestyle'] },+ { id: 'nav.meatspace.settings', path: '/meatspace/settings', label: 'Settings', section: 'MeatSpace', aliases: ['meatspace-settings'] },++ // ── Messages ──────────────────────────────────────────────────────────+ { id: 'nav.messages.inbox', path: '/messages/inbox', label: 'Inbox', section: 'Messages', aliases: ['messages'] },+ { id: 'nav.messages.drafts', path: '/messages/drafts', label: 'Drafts', section: 'Messages', aliases: ['drafts'] },+ { id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Messages', aliases: ['messages-config'] },+ { id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Messages', aliases: ['messages-sync'] },++ // ── POST ──────────────────────────────────────────────────────────────+ { id: 'nav.post.launcher', path: '/post/launcher', label: 'Launcher', section: 'POST', aliases: ['post', 'post-launcher'] },+ { id: 'nav.post.config', path: '/post/config', label: 'Config', section: 'POST', aliases: ['post-config'] },+ { id: 'nav.post.history', path: '/post/history', label: 'History', section: 'POST', aliases: ['post-history'] },+ { id: 'nav.post.memory', path: '/post/memory', label: 'Memory', section: 'POST', aliases: ['post-memory'] },+ { id: 'nav.post.wordplay', path: '/post/wordplay', label: 'Wordplay', section: 'POST', aliases: ['post-wordplay'] },++ // ── Settings ──────────────────────────────────────────────────────────+ { id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['settings', 'backup'] },+ { id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },+ { id: 'nav.settings.image-gen', path: '/settings/image-gen', label: 'Image Gen', section: 'Settings', aliases: ['image-gen'] },+ { id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },+ { id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice'] },+ { id: 'nav.prompts', path: '/prompts', label: 'Prompts', section: 'Settings', aliases: ['prompts'] },+ { id: 'nav.providers', path: '/ai', label: 'Providers', section: 'Settings', aliases: ['providers', 'ai-providers'] },+ { id: 'nav.security', path: '/security', label: 'Security', section: 'Settings', aliases: ['security'] },+ { id: 'nav.uploads', path: '/uploads', label: 'Uploads', section: 'Settings', aliases: ['uploads'] },++ // ── Wiki ──────────────────────────────────────────────────────────────+ { id: 'nav.wiki.overview', path: '/wiki/overview', label: 'Overview', section: 'Wiki', aliases: ['wiki'] },+ { id: 'nav.wiki.browse', path: '/wiki/browse', label: 'Browse', section: 'Wiki', aliases: ['wiki-browse'] },+ { id: 'nav.wiki.graph', path: '/wiki/graph', label: 'Graph', section: 'Wiki', aliases: ['wiki-graph'] },+ { id: 'nav.wiki.log', path: '/wiki/log', label: 'Log', section: 'Wiki', aliases: ['wiki-log'] },+ { id: 'nav.wiki.search', path: '/wiki/search', label: 'Search', section: 'Wiki', aliases: ['wiki-search'] },+];++// Fail-fast: every entry must be syntactically well-formed. Catches typos at+// server boot instead of on first user interaction. The voice agent used to+// silently fail when NAV_PAGES and Layout.jsx drifted — this guard is why the+// manifest is the single source.+for (const cmd of NAV_COMMANDS) {+ if (!cmd.id || !cmd.path || !cmd.label || !cmd.section) {+ throw new Error(`navManifest: malformed entry ${JSON.stringify(cmd)}`);+ }+ if (!cmd.path.startsWith('/')) {+ throw new Error(`navManifest: path must start with / — got "${cmd.path}" for ${cmd.id}`);+ }+}+{+ const seen = new Set();+ for (const cmd of NAV_COMMANDS) {+ if (seen.has(cmd.id)) throw new Error(`navManifest: duplicate id ${cmd.id}`);+ seen.add(cmd.id);+ }+}++// Pre-compute { alias → path } for the voice agent. Alias collisions resolve+// to the first entry that declared them — order matters in NAV_COMMANDS.+const aliasToPath = {};+for (const cmd of NAV_COMMANDS) {+ for (const alias of (cmd.aliases || [])) {+ if (!aliasToPath[alias]) aliasToPath[alias] = cmd.path;+ }+}++export const getNavAliasMap = () => ({ ...aliasToPath });++const normalizeLabel = (s) => (s || '')+ .toLowerCase()+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/[.!?:;,"']+$/, '');++// Fuzzy nav resolver — shared by voice `ui_navigate` and the palette API.+// Returns { path, matched, command } or null. The matcher is forgiving:+// exact → user-input-starts-with-alias → alias-starts-with-input → trailing+// token → substring. This is the same tiered search the voice agent has used+// successfully; extracting it here means future refinements flow to both.+export const resolveNavCommand = (input) => {+ if (!input || typeof input !== 'string') return null;+ const norm = normalizeLabel(input).replace(/\s+/g, '-');+ if (!norm) return null;++ const aliases = Object.keys(aliasToPath);+ const tail = norm.split('-').filter(Boolean).pop();++ // Tiered alias match, ordered from strictest to loosest.+ const tiers = [+ (a) => a === norm,+ (a) => norm.startsWith(a) && a.length >= 3,+ (a) => a.startsWith(norm),+ (a) => norm.endsWith(`-${a}`) && a.length >= 3,+ (a) => norm.includes(a) && a.length >= 4,+ (a) => a.includes(norm),+ (a) => tail && tail !== norm && a === tail,+ ];++ let matched = null;+ for (const test of tiers) {+ matched = aliases.find(test);+ if (matched) break;+ }+ if (!matched) return null;++ const path = aliasToPath[matched];+ const command = NAV_COMMANDS.find((c) => c.path === path && (c.aliases || []).includes(matched))+ || NAV_COMMANDS.find((c) => c.path === path);+ return { path, matched, command };+};diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsnew file mode 100644index 0000000000..3ced81f46f--- /dev/null+++ b/server/lib/navManifest.test.js@@ -0,0 +1,66 @@+import { describe, it, expect } from 'vitest';+import { NAV_COMMANDS, getNavAliasMap, resolveNavCommand } from './navManifest.js';++describe('navManifest — shape invariants', () => {+ it('every command has id, path, label, section', () => {+ for (const cmd of NAV_COMMANDS) {+ expect(cmd.id).toBeTruthy();+ expect(cmd.path).toMatch(/^\//);+ expect(cmd.label).toBeTruthy();+ expect(cmd.section).toBeTruthy();+ }+ });++ it('ids are unique', () => {+ const ids = NAV_COMMANDS.map((c) => c.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});++describe('resolveNavCommand — fuzzy matching', () => {+ it('resolves exact alias', () => {+ expect(resolveNavCommand('dashboard')?.path).toBe('/');+ expect(resolveNavCommand('tasks')?.path).toBe('/cos/tasks');+ expect(resolveNavCommand('goals')?.path).toBe('/goals/list');+ });++ it('resolves multi-word voice phrasings that end on a known page', () => {+ // "take me to the tasks page" → normalized "take-me-to-the-tasks-page"+ // → the resolver's "key contained in norm" tier picks up "tasks" via the+ // trailing token fallback (tail = "page" doesn't match, then substring+ // "tasks" is present in the normalized input).+ expect(resolveNavCommand('chief of staff tasks')?.path).toBe('/cos/tasks');+ expect(resolveNavCommand('cos tasks')?.path).toBe('/cos/tasks');+ });++ it('is case- and punctuation-insensitive', () => {+ expect(resolveNavCommand('BRAIN.')?.path).toBe('/brain/inbox');+ expect(resolveNavCommand('Review Hub!')?.path).toBe('/review');+ });++ it('returns null for unknown pages', () => {+ expect(resolveNavCommand('this-page-does-not-exist')).toBeNull();+ expect(resolveNavCommand('')).toBeNull();+ expect(resolveNavCommand(null)).toBeNull();+ });++ it('surfaces the matched alias for logging/telemetry', () => {+ const hit = resolveNavCommand('gsd');+ expect(hit?.matched).toBe('gsd');+ expect(hit?.path).toBe('/cos/gsd');+ });+});++describe('getNavAliasMap — voice-agent compatibility', () => {+ it('exposes every alias as a flat path map', () => {+ const map = getNavAliasMap();+ expect(map.dashboard).toBe('/');+ expect(map.tasks).toBe('/cos/tasks');+ expect(map.twin).toBe('/digital-twin/overview');+ });++ it('preserves first-declared alias on collision', () => {+ // "inbox" appears under Brain first and Messages second; Brain wins.+ expect(getNavAliasMap().inbox).toBe('/brain/inbox');+ });+});diff --git a/server/routes/palette.js b/server/routes/palette.jsnew file mode 100644index 0000000000..53a261dfc3--- /dev/null+++ b/server/routes/palette.js@@ -0,0 +1,91 @@+/**+ * Command Palette Routes+ *+ * Feeds the client-side Cmd+K palette and exposes a narrow set of voice-agent+ * tools via HTTP so the palette can invoke them without re-implementing the+ * logic. This is the DRY backbone: navigation + actions have one source of+ * truth (navManifest.js + voice/tools.js), and the palette + voice agent are+ * two consumers of the same registry.+ *+ * GET /api/palette/manifest → { nav: [...], actions: [...] }+ * POST /api/palette/action/:id → dispatches a palette-safe tool+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { NAV_COMMANDS } from '../lib/navManifest.js';+import { dispatchTool, getToolSpecs } from '../services/voice/tools.js';++const router = Router();++// Palette-safe subset of voice tools. Excluded: ui_* (they drive the DOM from+// within the voice agent's live context; from the palette we'd have no target+// surface), dictation toggles (mode state that belongs to the voice widget),+// and daily_log_open (pushes a sideEffect the HTTP caller can't consume).+// pm2_restart is included but marked destructive so the client confirms.+const PALETTE_ACTIONS = [+ { id: 'brain_capture', label: 'Capture to Brain', section: 'Brain', hint: 'Capture a thought' },+ { id: 'brain_search', label: 'Search Brain', section: 'Brain' },+ { id: 'brain_list_recent', label: 'Recent Brain entries', section: 'Brain' },+ { id: 'goal_list', label: 'List goals', section: 'Goals' },+ { id: 'goal_update_progress', label: 'Update goal progress', section: 'Goals' },+ { id: 'goal_log_note', label: 'Log note on goal', section: 'Goals' },+ { id: 'meatspace_log_drink', label: 'Log a drink', section: 'Health' },+ { id: 'meatspace_log_nicotine',label: 'Log nicotine', section: 'Health' },+ { id: 'meatspace_log_weight', label: 'Log weight', section: 'Health' },+ { id: 'meatspace_summary_today', label: "Today's health summary", section: 'Health' },+ { id: 'feeds_digest', label: 'Feed digest', section: 'Feeds' },+ { id: 'pm2_status', label: 'PM2 status', section: 'System' },+ { id: 'pm2_restart', label: 'Restart a PM2 process', section: 'System', destructive: true },+ { id: 'daily_log_read', label: "Read today's log", section: 'Brain' },+ { id: 'daily_log_append', label: 'Append to daily log', section: 'Brain' },+ { id: 'time_now', label: 'Current time', section: 'System' },+];++const PALETTE_ACTION_IDS = new Set(PALETTE_ACTIONS.map((a) => a.id));++// Enrich action metadata with live schema from the voice tool registry. The+// palette fuzzy-matches on the description the LLM sees; lifting it from the+// same source keeps palette and voice hints in sync.+const buildActionManifest = () => {+ const specs = getToolSpecs();+ const byName = Object.fromEntries(specs.map((s) => [s.function.name, s.function]));+ return PALETTE_ACTIONS.map((a) => {+ const fn = byName[a.id];+ return {+ ...a,+ description: fn?.description || '',+ parameters: fn?.parameters || { type: 'object', properties: {} },+ };+ });+};++router.get('/manifest', asyncHandler(async (_req, res) => {+ res.json({+ nav: NAV_COMMANDS,+ actions: buildActionManifest(),+ });+}));++const actionBodySchema = z.object({+ args: z.record(z.any()).optional().default({}),+});++router.post('/action/:id', asyncHandler(async (req, res) => {+ const id = String(req.params.id || '');+ if (!PALETTE_ACTION_IDS.has(id)) {+ throw new ServerError(`Unknown palette action "${id}"`, { status: 404 });+ }+ const { args } = validateRequest(actionBodySchema, req.body ?? {});+ // Palette calls are fire-and-forget for side effects — we don't have a+ // live voice context, so UI-driving sideEffects (navigate/dictation) that+ // some tools push would be lost. The whitelist above already excludes the+ // tools that rely on them; passing a throwaway buffer here is defensive.+ const ctx = { sideEffects: [] };+ const result = await dispatchTool(id, args, ctx);+ res.json({ ok: result?.ok !== false, result });+}));++export default router;diff --git a/server/routes/palette.test.js b/server/routes/palette.test.jsnew file mode 100644index 0000000000..be2ef612dd--- /dev/null+++ b/server/routes/palette.test.js@@ -0,0 +1,106 @@+import { describe, it, expect, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Stub voice tool side-effects — the palette dispatches them, but we only+// want to verify routing and whitelisting here.+vi.mock('../services/brain.js', () => ({+ captureThought: vi.fn(async () => ({ inboxLog: { id: 'inbox-1' }, message: 'ok' })),+ getInboxLog: vi.fn(async () => []),+}));+vi.mock('../services/meatspaceAlcohol.js', () => ({+ logDrink: vi.fn(async () => ({ standardDrinks: 1, dayTotal: 1 })),+ getAlcoholSummary: vi.fn(async () => ({ today: 0 })),+}));+vi.mock('../services/meatspaceNicotine.js', () => ({+ logNicotine: vi.fn(async () => ({ totalMg: 1, dayTotal: 1 })),+ getNicotineSummary: vi.fn(async () => ({ today: 0 })),+}));+vi.mock('../services/meatspaceHealth.js', () => ({+ addBodyEntry: vi.fn(async () => ({ date: '2026-04-24' })),+}));+vi.mock('../services/identity.js', () => ({+ getGoals: vi.fn(async () => ({ goals: [] })),+ updateGoalProgress: vi.fn(async () => {}),+ addProgressEntry: vi.fn(async () => {}),+}));+vi.mock('../services/pm2.js', () => ({+ listProcesses: vi.fn(async () => [{ name: 'api', status: 'online', restarts: 0 }]),+ restartApp: vi.fn(async () => {}),+}));+vi.mock('../services/feeds.js', () => ({+ getItems: vi.fn(async () => []),+ getFeeds: vi.fn(async () => []),+}));++const { default: paletteRoutes } = await import('./palette.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/palette', paletteRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('GET /api/palette/manifest', () => {+ it('returns nav commands and palette-safe actions', async () => {+ const res = await request(makeApp()).get('/api/palette/manifest');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body.nav)).toBe(true);+ expect(Array.isArray(res.body.actions)).toBe(true);+ expect(res.body.nav.length).toBeGreaterThan(50);++ // Every nav entry is fully formed — the client fuzzy-matches on these.+ for (const cmd of res.body.nav) {+ expect(cmd.id).toBeTruthy();+ expect(cmd.path).toMatch(/^\//);+ expect(cmd.label).toBeTruthy();+ expect(cmd.section).toBeTruthy();+ }++ // Action descriptions hydrate from the voice tool registry, proving the+ // DRY link between voice schema and palette metadata.+ const brainCapture = res.body.actions.find((a) => a.id === 'brain_capture');+ expect(brainCapture).toBeTruthy();+ expect(brainCapture.description).toMatch(/capture/i);+ expect(brainCapture.parameters?.properties?.text).toBeTruthy();+ });++ it('excludes ui_* tools (only runnable inside voice DOM context)', async () => {+ const res = await request(makeApp()).get('/api/palette/manifest');+ const ids = res.body.actions.map((a) => a.id);+ expect(ids).not.toContain('ui_click');+ expect(ids).not.toContain('ui_fill');+ expect(ids).not.toContain('ui_navigate');+ });+});++describe('POST /api/palette/action/:id', () => {+ it('dispatches a whitelisted action and returns its result', async () => {+ const res = await request(makeApp())+ .post('/api/palette/action/brain_capture')+ .send({ args: { text: 'remember to drink water' } });+ expect(res.status).toBe(200);+ expect(res.body.ok).toBe(true);+ expect(res.body.result.id).toBe('inbox-1');+ expect(res.body.result.summary).toMatch(/Captured/);+ });++ it('rejects unknown action ids', async () => {+ const res = await request(makeApp())+ .post('/api/palette/action/unknown_tool')+ .send({ args: {} });+ expect(res.status).toBe(404);+ });++ it('rejects non-whitelisted voice tools even if they exist', async () => {+ // ui_click is a real voice tool but intentionally not in the palette+ // whitelist — the palette has no DOM context to drive.+ const res = await request(makeApp())+ .post('/api/palette/action/ui_click')+ .send({ args: { label: 'Save' } });+ expect(res.status).toBe(404);+ });+});diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex ba128feeff..1aff381f5c 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -11,134 +11,10 @@ import { listProcesses, restartApp } from '../pm2.js';import { getItems, getFeeds } from '../feeds.js';import { getUserTimezone, todayInTimezone, getLocalParts } from '../../lib/timezone.js';import * as journal from '../brainJournal.js';+import { resolveNavCommand } from '../../lib/navManifest.js';const DAILY_LOG_PATH = '/brain/daily-log';-// Named pages the voice agent can navigate to. Keys are spoken-friendly aliases-// (what the user is likely to say); values are app routes. Keep in sync with-// Layout.jsx — when you add a nav item the user might ask for by voice, add-// its alias(es) here.-const NAV_PAGES = {- dashboard: '/',- home: '/',- apps: '/apps',- 'review-hub': '/review',- review: '/review',- cybercity: '/city',- city: '/city',- character: '/character',- data: '/data',- shell: '/shell',- browser: '/browser',- instances: '/instances',- loops: '/loops',- openclaw: '/openclaw',- 'social-agents': '/agents',- // Chief of Staff- 'chief-of-staff': '/cos/tasks',- cos: '/cos/tasks',- tasks: '/cos/tasks',- 'cos-tasks': '/cos/tasks',- 'cos-agents': '/cos/agents',- agents: '/cos/agents',- 'cos-briefing': '/cos/briefing',- briefing: '/cos/briefing',- 'cos-gsd': '/cos/gsd',- gsd: '/cos/gsd',- 'cos-health': '/cos/health',- 'cos-jobs': '/cos/jobs',- 'system-tasks': '/cos/jobs',- 'cos-schedule': '/cos/schedule',- schedule: '/cos/schedule',- 'cos-scripts': '/cos/scripts',- 'cos-memory': '/cos/memory',- 'cos-learning': '/cos/learning',- 'cos-productivity': '/cos/productivity',- streaks: '/cos/productivity',- 'cos-digest': '/cos/digest',- 'cos-config': '/cos/config',- // Brain- brain: '/brain/inbox',- 'brain-inbox': '/brain/inbox',- inbox: '/brain/inbox',- 'daily-log': '/brain/daily-log',- 'brain-digest': '/brain/digest',- 'brain-graph': '/brain/graph',- 'brain-links': '/brain/links',- 'brain-memory': '/brain/memory',- 'brain-notes': '/brain/notes',- notes: '/brain/notes',- 'brain-trust': '/brain/trust',- // Calendar- calendar: '/calendar/agenda',- agenda: '/calendar/agenda',- 'calendar-day': '/calendar/day',- 'calendar-week': '/calendar/week',- 'calendar-month': '/calendar/month',- 'calendar-lifetime': '/calendar/lifetime',- 'calendar-review': '/calendar/review',- 'calendar-sync': '/calendar/sync',- // Digital Twin- 'digital-twin': '/digital-twin/overview',- twin: '/digital-twin/overview',- 'twin-autobiography': '/digital-twin/autobiography',- 'twin-documents': '/digital-twin/documents',- 'twin-identity': '/digital-twin/identity',- 'twin-interview': '/digital-twin/interview',- // Goals & Insights- goals: '/goals/list',- insights: '/insights/overview',- // MeatSpace- meatspace: '/meatspace/overview',- 'meatspace-health': '/meatspace/health',- 'meatspace-body': '/meatspace/body',- 'meatspace-alcohol': '/meatspace/alcohol',- 'meatspace-nicotine': '/meatspace/nicotine',- 'meatspace-age': '/meatspace/age',- 'meatspace-blood': '/meatspace/blood',- 'meatspace-genome': '/meatspace/genome',- 'meatspace-lifestyle': '/meatspace/lifestyle',- // Messages- messages: '/messages/inbox',- drafts: '/messages/drafts',- // POST- post: '/post/launcher',- 'post-launcher': '/post/launcher',- 'post-history': '/post/history',- 'post-wordplay': '/post/wordplay',- // Wiki- wiki: '/wiki/overview',- 'wiki-browse': '/wiki/browse',- 'wiki-graph': '/wiki/graph',- 'wiki-search': '/wiki/search',- // Dev tools- devtools: '/devtools/runs',- 'ai-runs': '/devtools/runs',- 'ai-agents': '/devtools/agents',- 'feature-agents': '/feature-agents',- 'devtools-github': '/devtools/github',- github: '/devtools/github',- 'devtools-jira': '/devtools/jira',- jira: '/devtools/jira',- 'devtools-datadog': '/devtools/datadog',- datadog: '/devtools/datadog',- 'devtools-history': '/devtools/history',- 'devtools-processes': '/devtools/processes',- 'devtools-usage': '/devtools/usage',- 'devtools-runner': '/devtools/runner',- 'devtools-submodules': '/devtools/submodules',- // Settings- settings: '/settings/backup',- 'settings-voice': '/settings/voice',- 'settings-telegram': '/settings/telegram',- 'settings-database': '/settings/database',- prompts: '/prompts',- providers: '/ai',- 'ai-providers': '/ai',- security: '/security',- uploads: '/uploads',-};-// Shorthand presets for voice logging. A user saying "I had a beer" should// not need to recite oz + ABV — these defaults match typical US servings.const DRINK_PRESETS = {@@ -894,24 +770,8 @@ const TOOLS = [let target = null;let resolvedKey = null;if (page && typeof page === 'string') {- const norm = normalizeLabel(page).replace(/\s+/g, '-');- const keys = Object.keys(NAV_PAGES);- // Tiered match: exact → key prefixes norm → norm prefixes key → key- // contained in norm (so "chief-of-staff-tasks" finds "tasks") → key- // contains norm substring. Last word tried as a standalone key at- // the end since voice phrasings often end with the target page.- const tail = norm.split('-').filter(Boolean).pop();- const picks = [- keys.find((k) => k === norm),- keys.find((k) => norm.startsWith(k) && k.length >= 3),- keys.find((k) => k.startsWith(norm)),- keys.find((k) => norm.endsWith(`-${k}`) && k.length >= 3),- keys.find((k) => norm.includes(k) && k.length >= 4),- keys.find((k) => k.includes(norm)),- tail && tail !== norm ? keys.find((k) => k === tail) : null,- ];- const hit = picks.find(Boolean);- if (hit) { target = NAV_PAGES[hit]; resolvedKey = hit; }+ const hit = resolveNavCommand(page);+ if (hit) { target = hit.path; resolvedKey = hit.matched; }}if (!target && path && typeof path === 'string' && path.startsWith('/')) target = path;if (!target) {