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

docs(05-unified-search): create phase plan

Adam Eivyff11610964a0
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
index 3acd0fff99..3fee828709 100644
--- a/.planning/ROADMAP.md
+++ b/.planning/ROADMAP.md
@@ -89,10 +89,11 @@ Plans:
2. Typing a query returns results from all data sources (Brain, Memory, Apps, History, Health, etc.) via server-side fan-out
3. Results are categorized by source with icons and text snippets
4. Clicking a result navigates to the deep-linked location (specific brain capture, agent run, health entry, etc.)
-**Plans**: TBD
+**Plans**: 2 plans
Plans:
-- [ ] 05-01: TBD
+- [ ] 05-01-PLAN.md -- Server search engine: fan-out search service with 5 source adapters, GET /api/search route, Zod validation, client API function (SRC-02, SRC-03)
+- [ ] 05-02-PLAN.md -- Cmd+K overlay UI: useCmdKSearch hook, CmdKSearch portal component with keyboard nav, highlighted snippets, deep-link navigation, Layout.jsx mount (SRC-01, SRC-03, SRC-04)
## Progress
@@ -106,4 +107,4 @@ Note: Phases 1 and 2 have no dependency on each other and can execute in paralle
| 2. Data Backup & Recovery | 2/2 | Complete | 2026-02-26 |
| 3. Apple Health Integration | 2/3 | Complete | 2026-02-26 |
| 4. Cross-Domain Insights Engine | 0/2 | Planned | - |
-| 5. Unified Search (Cmd+K) | 0/1 | Not started | - |
+| 5. Unified Search (Cmd+K) | 0/2 | Not started | - |
diff --git a/.planning/phases/05-unified-search/05-01-PLAN.md b/.planning/phases/05-unified-search/05-01-PLAN.md
new file mode 100644
index 0000000000..45a76a1f24
--- /dev/null
+++ b/.planning/phases/05-unified-search/05-01-PLAN.md
@@ -0,0 +1,318 @@
+---
+phase: 05-unified-search
+plan: 01
+type: execute
+wave: 1
+depends_on: []
+files_modified:
+ - server/lib/validation.js
+ - server/services/search.js
+ - server/routes/search.js
+ - server/index.js
+ - client/src/services/api.js
+autonomous: true
+requirements:
+ - SRC-02
+ - SRC-03
+
+must_haves:
+ truths:
+ - "GET /api/search?q=foo returns categorized results from Brain, Memory, Apps, History, and Health sources"
+ - "Each source result includes id, title, snippet, url, and type fields"
+ - "Failed source adapters return empty results instead of failing the entire request"
+ - "Query param q is validated (min 2 chars, max 200, trimmed)"
+ - "Snippets contain ~100 char window around the keyword match"
+ - "Sources with zero results are omitted from the response"
+ artifacts:
+ - path: "server/services/search.js"
+ provides: "Fan-out search engine with source adapters"
+ exports: ["fanOutSearch"]
+ - path: "server/routes/search.js"
+ provides: "GET /api/search route handler"
+ - path: "server/lib/validation.js"
+ provides: "searchQuerySchema export"
+ contains: "searchQuerySchema"
+ - path: "client/src/services/api.js"
+ provides: "search() client API function"
+ contains: "search"
+ key_links:
+ - from: "server/routes/search.js"
+ to: "server/services/search.js"
+ via: "import fanOutSearch"
+ pattern: "fanOutSearch"
+ - from: "server/routes/search.js"
+ to: "server/lib/validation.js"
+ via: "import searchQuerySchema"
+ pattern: "searchQuerySchema"
+ - from: "server/index.js"
+ to: "server/routes/search.js"
+ via: "app.use('/api/search', searchRoutes)"
+ pattern: "api/search"
+ - from: "client/src/services/api.js"
+ to: "server/routes/search.js"
+ via: "request('/search?q=')"
+ pattern: "/search"
+---
+
+<objective>
+Build the server-side unified search engine and client API function. A single GET /api/search?q= endpoint fans out keyword queries to all PortOS data sources (Brain inbox/people/projects/ideas/links, CoS Memory via BM25, Apps, History, Health metrics) using Promise.allSettled for fault isolation. Each source adapter performs case-insensitive substring matching, returns categorized results with deep-link URLs, and extracts ~100-char snippets around keyword matches. The client API function is added to api.js for consumption by the overlay component (Plan 05-02).
+
+Purpose: SRC-02 (server fan-out search) and SRC-03 (categorized results with icons/snippets) — backend foundation
+Output: search.js service, search.js route, searchQuerySchema in validation.js, search() in api.js
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/05-unified-search/05-RESEARCH.md
+
+<interfaces>
+<!-- Key types and contracts the executor needs. Extracted from codebase. -->
+
+From server/services/brainStorage.js:
+```js
+export async function getInboxLog(options = {}) // options: { limit, offset, status }
+// Returns: { entries: [...], total, hasMore }
+// Each entry: { id, text, timestamp, status, ... }
+
+export async function getAll(type) // type: 'people'|'projects'|'ideas'|'links'
+// Returns: array of records
+// people: { id, name, notes, ... }
+// projects: { id, name, description, ... }
+// ideas: { id, title, description, ... }
+// links: { id, title, url, description, ... }
+
+export const getPeople = (filters) => ...
+export const getProjects = (filters) => ...
+export const getIdeas = (filters) => ...
+export const getLinks = (filters) => ...
+```
+
+From server/services/memoryBM25.js:
+```js
+async function searchBM25(query, options = {}) // options: { limit, threshold }
+// Returns: [{ id, score }] — no content, no summary
+// Must load summary from memory index for snippet
+```
+
+From server/services/memory.js:
+```js
+export async function getMemory(id) // Returns full memory object with content
+export async function getMemories(options = {}) // Returns { memories: [...], total }
+// Each memory has: id, content, summary (150 char), category, tags, status, ...
+```
+
+From server/services/apps.js:
+```js
+export async function getAllApps({ includeArchived = true } = {})
+// Returns: [{ id, name, description, type, repoPath, ... }]
+```
+
+From server/services/history.js:
+```js
+export async function getHistory(options = {})
+// options: { limit, offset, action, target, success }
+// Returns: { entries: [...], total }
+// Each entry: { id, action, target, targetName, details, timestamp, ... }
+```
+
+From server/services/appleHealthQuery.js:
+```js
+export async function listDayFiles()
+// Returns: ['2024-01-15', '2024-01-16', ...] sorted date strings
+```
+
+From server/lib/validation.js:
+```js
+// Uses Zod schemas — add searchQuerySchema to existing exports
+// Pattern: export const {name}Schema = z.object({ ... });
+```
+
+From server/index.js route registration pattern:
+```js
+import searchRoutes from './routes/search.js';
+app.use('/api/search', searchRoutes);
+```
+
+From client/src/services/api.js:
+```js
+// request(endpoint, options) — internal helper
+// Pattern: export const fnName = (params) => request('/path', { ... });
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create search service with source adapters and fan-out engine</name>
+ <files>server/services/search.js</files>
+ <action>
+Create `server/services/search.js` with the following structure:
+
+1. **Import source services:**
+ - `brainStorage` (getInboxLog, getAll for people/projects/ideas/links)
+ - `memoryBM25` (searchBM25) and `memory` (getMemories for summary lookup)
+ - `apps` (getAllApps)
+ - `history` (getHistory)
+ - `appleHealthQuery` (listDayFiles)
+
+2. **extractSnippet(text, query, maxLen = 100) helper function:**
+ - If text is falsy, return empty string
+ - Find first case-insensitive occurrence of query in text
+ - Extract ~100 char window centered around the match (30 chars before match start)
+ - Prepend '...' if excerpt doesn't start at beginning, append '...' if it doesn't reach end
+ - If no match found, return first maxLen chars of text
+
+3. **Create source adapter functions** — each returns `{ id, label, icon, results }`:
+
+ **searchBrain(query):**
+ - Fan out to getInboxLog({ limit: 200 }), getPeople(), getProjects(), getIdeas(), getLinks() using Promise.allSettled
+ - For inbox: filter entries where `text` includes query (case-insensitive), map to `{ id, title: text.substring(0, 60), snippet: extractSnippet(text, query), url: '/brain/inbox', type: 'inbox' }`
+ - For people: filter on `name` or `notes`, map to `{ id, title: name, snippet: extractSnippet(notes, query), url: '/brain/inbox', type: 'person' }`
+ - For projects: filter on `name` or `description`, map to `{ id, title: name, snippet: extractSnippet(description, query), url: '/brain/inbox', type: 'project' }`
+ - For ideas: filter on `title` or `description`, map to `{ id, title, snippet: extractSnippet(description, query), url: '/brain/inbox', type: 'idea' }`
+ - For links: filter on `title`, `url`, or `description`, map to `{ id, title: title || url, snippet: extractSnippet(description || url, query), url: '/brain/inbox', type: 'link' }`
+ - Combine all matches, sort by most recent, take first 5
+ - Return `{ id: 'brain', label: 'Brain', icon: 'Brain', results }`
+
+ **searchMemory(query):**
+ - Call searchBM25(query, { limit: 10, threshold: 0.1 })
+ - Use getMemories() to load the full index, then map BM25 result IDs to their summary from the index
+ - Map to `{ id, title: summary.substring(0, 60), snippet: summary, url: '/cos/memory', type: 'memory' }`
+ - Take first 5 results
+ - Return `{ id: 'memory', label: 'Memory', icon: 'Cpu', results }`
+
+ **searchApps(query):**
+ - Call getAllApps({ includeArchived: false })
+ - Filter where `name` or `description` includes query (case-insensitive)
+ - Map to `{ id, title: name, snippet: extractSnippet(description, query), url: '/apps', type: 'app' }`
+ - Take first 5
+ - Return `{ id: 'apps', label: 'Apps', icon: 'Package', results }`
+
+ **searchHistory(query):**
+ - Call getHistory({ limit: 500 })
+ - Filter entries where `targetName` or `action` includes query (case-insensitive)
+ - Map to `{ id, title: targetName || action, snippet: extractSnippet(action + ' ' + (targetName || ''), query), url: '/devtools/history', type: 'history' }`
+ - Take first 5
+ - Return `{ id: 'history', label: 'History', icon: 'History', results }`
+
+ **searchHealth(query):**
+ - Define known metric names: `['step_count', 'heart_rate', 'sleep_analysis', 'hrv', 'blood_pressure', 'body_mass', 'respiratory_rate', 'blood_glucose', 'body_temperature']`
+ - Also define display-friendly aliases: `{ step_count: 'Steps', heart_rate: 'Heart Rate', sleep_analysis: 'Sleep', hrv: 'HRV', blood_pressure: 'Blood Pressure', body_mass: 'Body Mass', respiratory_rate: 'Respiratory Rate', blood_glucose: 'Blood Glucose', body_temperature: 'Body Temperature' }`
+ - Filter metrics where either the key or the display name includes query (case-insensitive)
+ - Map to `{ id: metricKey, title: displayName, snippet: displayName + ' health metric data', url: '/meatspace/health', type: 'health-metric' }`
+ - Return `{ id: 'health', label: 'Health', icon: 'HeartPulse', results }`
+
+4. **fanOutSearch(query) export:**
+ - Call all 5 adapters via `Promise.allSettled([searchBrain(q), searchMemory(q), searchApps(q), searchHistory(q), searchHealth(q)])`
+ - Map settled results: fulfilled => value, rejected => source with empty results array (use a fallback array of empty source objects keyed by index)
+ - Filter out sources where `results.length === 0`
+ - Return the array of non-empty sources
+
+Use single-line logging per CLAUDE.md: `console.log(\`🔍 Search fan-out for "${query}" across ${adapters.length} sources\`)` at start, and log count of total results at end.
+
+Do NOT use try/catch — per CLAUDE.md, errors bubble to centralized middleware. The Promise.allSettled pattern naturally handles per-adapter failures.
+ </action>
+ <verify>
+ <automated>cd server && node -e "import('./services/search.js').then(m => console.log('✅ search.js loads, exports:', Object.keys(m)))"</automated>
+ </verify>
+ <done>search.js exports fanOutSearch function; imports compile; all 5 source adapters defined</done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Create search route, Zod schema, register in index.js, and add client API function</name>
+ <files>server/routes/search.js, server/lib/validation.js, server/index.js, client/src/services/api.js</files>
+ <action>
+**1. Add searchQuerySchema to server/lib/validation.js:**
+
+Add to the existing file (find an appropriate location near other query schemas, or at the end before the closing section):
+
+```js
+// =============================================================================
+// SEARCH SCHEMAS
+// =============================================================================
+
+export const searchQuerySchema = z.object({
+ q: z.string().min(2).max(200).trim()
+});
+```
+
+**2. Create server/routes/search.js:**
+
+```js
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest, searchQuerySchema } from '../lib/validation.js';
+import { fanOutSearch } from '../services/search.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (req, res) => {
+ const { data } = validateRequest(searchQuerySchema, req.query);
+ const sources = await fanOutSearch(data.q);
+ res.json({ query: data.q, sources });
+}));
+
+export default router;
+```
+
+Follow the exact pattern from existing routes (e.g., history.js). Use `asyncHandler` wrapper. Use `validateRequest` for Zod validation. Return `{ query, sources }` response shape.
+
+**3. Register route in server/index.js:**
+
+Add import at top with other route imports:
+```js
+import searchRoutes from './routes/search.js';
+```
+
+Add route registration. Place it alphabetically among the existing `app.use('/api/...')` lines — it should go near `/api/screenshots` and `/api/settings`:
+```js
+app.use('/api/search', searchRoutes);
+```
+
+**4. Add search function to client/src/services/api.js:**
+
+Add near the top of the export functions (or in a logical location with other utility endpoints):
+
+```js
+export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);
+```
+
+This follows the exact pattern of existing API functions (e.g., `getAppleHealthRange`).
+ </action>
+ <verify>
+ <automated>cd server && node -e "import('./lib/validation.js').then(m => { if (!m.searchQuerySchema) throw new Error('missing searchQuerySchema'); console.log('✅ searchQuerySchema exists'); })" && node -e "import('./routes/search.js').then(m => console.log('✅ search route loads'))"</automated>
+ </verify>
+ <done>GET /api/search?q=test is a registered route; searchQuerySchema validates q param; client api.js exports search() function</done>
+</task>
+
+</tasks>
+
+<verification>
+1. Server starts without errors after changes: `cd server && node -e "import('./index.js')"`
+2. Search route responds: `curl "http://localhost:5554/api/search?q=test"` returns JSON with `query` and `sources` fields
+3. Validation rejects short queries: `curl "http://localhost:5554/api/search?q=a"` returns 400
+4. Empty query rejected: `curl "http://localhost:5554/api/search"` returns 400
+5. Failed adapters don't crash the entire request — if one service has no data, the response still returns other sources
+</verification>
+
+<success_criteria>
+- GET /api/search?q=foo returns `{ query, sources: [...] }` with results from all available data sources
+- Each source has { id, label, icon, results } structure
+- Each result has { id, title, snippet, url, type } structure
+- Sources with zero results are omitted from response
+- Query validation enforces min 2 chars, max 200
+- client api.js exports search(q) function
+- Server starts cleanly with no import errors
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/05-unified-search/05-01-SUMMARY.md`
+</output>
diff --git a/.planning/phases/05-unified-search/05-02-PLAN.md b/.planning/phases/05-unified-search/05-02-PLAN.md
new file mode 100644
index 0000000000..a3068a6463
--- /dev/null
+++ b/.planning/phases/05-unified-search/05-02-PLAN.md
@@ -0,0 +1,319 @@
+---
+phase: 05-unified-search
+plan: 02
+type: execute
+wave: 2
+depends_on:
+ - 05-01
+files_modified:
+ - client/src/hooks/useCmdKSearch.js
+ - client/src/components/CmdKSearch.jsx
+ - client/src/components/Layout.jsx
+autonomous: false
+requirements:
+ - SRC-01
+ - SRC-03
+ - SRC-04
+
+must_haves:
+ truths:
+ - "Pressing Cmd+K or Ctrl+K from any page opens a search overlay"
+ - "Typing 2+ characters triggers debounced search-as-you-type"
+ - "Results are grouped by source with section headers, icons, and text snippets"
+ - "Keyword matches are highlighted in result snippets"
+ - "Arrow keys move selection highlight, Enter navigates to result URL, Escape closes overlay"
+ - "Clicking a result navigates to its deep-linked location and closes the overlay"
+ - "Clicking the backdrop dismisses the overlay"
+ - "Before typing, empty area shows placeholder hint"
+ - "No-results state shows centered message"
+ - "Input auto-focuses when overlay opens"
+ - "Body scroll is locked when overlay is open"
+ artifacts:
+ - path: "client/src/hooks/useCmdKSearch.js"
+ provides: "Global Cmd+K keyboard shortcut hook"
+ exports: ["useCmdKSearch"]
+ - path: "client/src/components/CmdKSearch.jsx"
+ provides: "Search overlay modal component with results display"
+ - path: "client/src/components/Layout.jsx"
+ provides: "CmdKSearch mounted in layout shell"
+ contains: "CmdKSearch"
+ key_links:
+ - from: "client/src/components/Layout.jsx"
+ to: "client/src/components/CmdKSearch.jsx"
+ via: "import and render <CmdKSearch />"
+ pattern: "CmdKSearch"
+ - from: "client/src/components/CmdKSearch.jsx"
+ to: "client/src/hooks/useCmdKSearch.js"
+ via: "import useCmdKSearch"
+ pattern: "useCmdKSearch"
+ - from: "client/src/components/CmdKSearch.jsx"
+ to: "client/src/services/api.js"
+ via: "import { search } from api.js"
+ pattern: "search"
+ - from: "client/src/components/CmdKSearch.jsx"
+ to: "react-router-dom"
+ via: "useNavigate() for deep-link navigation"
+ pattern: "navigate"
+---
+
+<objective>
+Build the Cmd+K search overlay UI — a Spotlight/Raycast-style modal that appears on Cmd+K/Ctrl+K from any page, displays categorized search results with keyboard navigation, and navigates to deep-linked locations on selection. The overlay uses a React portal for z-index isolation, debounced search-as-you-type, arrow key navigation, and highlighted keyword matches in snippets.
+
+Purpose: SRC-01 (Cmd+K opens overlay), SRC-03 (categorized results with icons/snippets), SRC-04 (deep-link navigation)
+Output: useCmdKSearch.js hook, CmdKSearch.jsx overlay component, Layout.jsx updated with mount point
+</objective>
+
+<execution_context>
+@/Users/antic/.claude/get-shit-done/workflows/execute-plan.md
+@/Users/antic/.claude/get-shit-done/templates/summary.md
+</execution_context>
+
+<context>
[email protected]/phases/05-unified-search/05-RESEARCH.md
[email protected]/phases/05-unified-search/05-01-SUMMARY.md
+
+<interfaces>
+<!-- Key contracts from Plan 05-01 that this plan consumes -->
+
+From client/src/services/api.js (added by Plan 05-01):
+```js
+export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);
+// Returns: { query: string, sources: Source[] }
+// Source: { id: string, label: string, icon: string, results: Result[] }
+// Result: { id: string, title: string, snippet: string, url: string, type: string }
+```
+
+From client/src/components/Layout.jsx (existing):
+```jsx
+// Layout is the root shell wrapping all pages via <Outlet />
+// Import lucide-react icons already present: Brain, Package, History, HeartPulse, Cpu, Search, etc.
+// CmdKSearch should be mounted as a sibling to the main content area
+// Layout uses Tailwind classes with port-* design tokens
+```
+
+From client/src/App.jsx route patterns:
+```
+/brain/inbox — Brain captures
+/cos/memory — CoS memory entries
+/apps — App registry
+/devtools/history — Activity history
+/meatspace/health — Health metrics
+```
+</interfaces>
+</context>
+
+<tasks>
+
+<task type="auto">
+ <name>Task 1: Create Cmd+K hook and search overlay component</name>
+ <files>client/src/hooks/useCmdKSearch.js, client/src/components/CmdKSearch.jsx</files>
+ <action>
+**1. Create client/src/hooks/useCmdKSearch.js:**
+
+```js
+import { useState, useEffect } from 'react';
+
+export function useCmdKSearch() {
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ const handler = (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
+ e.preventDefault();
+ setOpen(prev => !prev);
+ }
+ };
+ document.addEventListener('keydown', handler);
+ return () => document.removeEventListener('keydown', handler);
+ }, []);
+
+ return { open, setOpen };
+}
+```
+
+Note on Pitfall 6 from research: The global Cmd+K handler fires even when an input/textarea is focused. This is the correct behavior — Spotlight and Raycast both override Cmd+K in inputs. The search overlay is the highest-priority action for this shortcut.
+
+**2. Create client/src/components/CmdKSearch.jsx:**
+
+Build a Spotlight-style search overlay using React portal. Key specifications from CONTEXT.md (locked decisions):
+
+**Overlay appearance:**
+- Spotlight-style centered modal, ~800px wide (use `max-w-3xl` which is 768px, close to 800)
+- Semi-transparent dark backdrop (`bg-black/60`) — click backdrop to dismiss
+- Subtle fade+scale animation (~150ms): use Tailwind `transition-all duration-150`
+- Use `createPortal(document.body)` to render above sidebar z-index
+
+**Result presentation:**
+- Results grouped by source under section headers with icon + label
+- Top 3 results per source category initially, with "Show more" button to expand to all
+- Each result row: source icon + title (bold) + 1-line text snippet with keyword highlighted
+- Categories with zero results hidden (server already omits them)
+
+**Search interaction:**
+- Full keyboard navigation: ArrowDown/ArrowUp move highlight, Enter navigates, Escape closes
+- Search-as-you-type after 2+ characters with 300ms debounce
+- Before typing: empty results area with placeholder hint "Search Brain, Memory, Health..."
+- No-results state: subtle centered "No results for 'xyz'" message
+
+**Implementation details:**
+
+Import `{ search }` from `../services/api.js` for the API call.
+Import `{ useNavigate }` from `react-router-dom` for deep-link navigation.
+Import `{ createPortal }` from `react-dom`.
+Import Lucide icons: `Brain, Cpu, Package, History, HeartPulse, Search, Loader2` from `lucide-react`.
+
+**Component state:**
+- `query` (string) — current search input
+- `results` (array of source objects) — from API response
+- `loading` (boolean) — true while fetching
+- `focusedIndex` (number) — currently highlighted result in flat list
+- `expandedSources` (Set) — source IDs where "Show more" is clicked
+
+**Debounce logic:**
+- Use a `useEffect` with `setTimeout`/`clearTimeout` pattern (no external library)
+- When `query.length >= 2`, set 300ms timeout, then call `search(query)` and update results
+- When `query.length < 2`, clear results immediately
+
+**Flat result list for keyboard navigation:**
+- Compute `flatResults` from sources: iterate sources, for each source take first 3 results (or all if source is in expandedSources), flatten into a single array
+- Each flat item gets a reference to its source id for rendering
+
+**Reset focusedIndex to 0 whenever results change** (Pitfall 5 from research).
+
+**Auto-focus input on open** (Pitfall 1): `useEffect(() => { if (open) inputRef.current?.focus(); }, [open])`.
+
+**Lock body scroll when open** (Pitfall 2): `useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; return () => { document.body.style.overflow = ''; }; }, [open])`.
+
+**Clear query and results when overlay closes** so it starts fresh each time.
+
+**Keyboard handler** (on the overlay container div, not the input):
+- ArrowDown: increment focusedIndex (clamp to flatResults.length - 1)
+- ArrowUp: decrement focusedIndex (clamp to 0)
+- Enter: if flatResults[focusedIndex] exists, call `navigate(flatResults[focusedIndex].url)` and close overlay
+- Escape: close overlay
+
+**Highlight component** (inline helper):
+- Split snippet text on the search query (case-insensitive regex with special char escaping)
+- Wrap matched parts with `<mark className="bg-port-accent/30 text-white rounded px-0.5">`
+
+**Icon mapping:**
+Create a map from icon string to Lucide component:
+```js
+const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };
+```
+Look up `source.icon` in the map; fallback to `Search` icon.
+
+**Rendering structure (inside portal):**
+
+```
+backdrop (fixed inset-0, bg-black/60, onClick close)
+ container (centered, max-w-3xl, bg-port-card, rounded-xl, border border-port-border, shadow-2xl)
+ search input row (flex, border-b border-port-border, p-4)
+ Search icon (text-gray-400)
+ input (flex-1, bg-transparent, text-white, placeholder, ref=inputRef)
+ Cmd+K badge (text-xs text-gray-500 border border-port-border rounded px-1.5)
+ results area (max-h-96 overflow-y-auto p-2)
+ if loading: centered Loader2 spinner (animate-spin)
+ if query.length >= 2 && !loading && results.length === 0: "No results for 'query'"
+ if query.length < 2: placeholder hint
+ for each source in results:
+ source header (flex items-center gap-2, text-xs text-gray-400 uppercase, px-3 py-2)
+ SourceIcon (size=14)
+ source.label
+ for each result (first 3 or all if expanded):
+ result row (flex items-start gap-3, px-3 py-2, rounded-lg, cursor-pointer)
+ highlight bg if focusedIndex matches this flat index (bg-port-accent/10)
+ hover state (hover:bg-white/5)
+ title (text-sm font-medium text-white, truncate)
+ snippet (text-xs text-gray-400, with Highlight component)
+ if source has >3 results and not expanded:
+ "Show more" button (text-xs text-port-accent, px-3 py-1)
+```
+
+Use Tailwind design tokens from CLAUDE.md: port-bg, port-card, port-border, port-accent.
+
+On result click: `navigate(result.url)` then `setOpen(false)`.
+
+Scroll the focused result into view: on the result row div, use `ref` callback and `scrollIntoView({ block: 'nearest' })` when it becomes focused.
+ </action>
+ <verify>
+ <automated>cd client && node -e "import('./src/hooks/useCmdKSearch.js').then(() => console.log('✅ hook imports ok'))" && node -e "import('./src/components/CmdKSearch.jsx').then(() => console.log('✅ CmdKSearch imports ok'))" 2>&1 || echo "Note: JSX import may fail in plain node — verify via dev server build"</automated>
+ </verify>
+ <done>useCmdKSearch hook handles Cmd+K/Ctrl+K toggle; CmdKSearch component renders portal overlay with debounced search, grouped results, keyboard navigation, highlighted snippets, and deep-link navigation</done>
+</task>
+
+<task type="auto">
+ <name>Task 2: Mount CmdKSearch in Layout.jsx</name>
+ <files>client/src/components/Layout.jsx</files>
+ <action>
+Edit `client/src/components/Layout.jsx` to mount the CmdKSearch overlay:
+
+1. Add import at the top with other component imports:
+```js
+import CmdKSearch from './CmdKSearch';
+```
+
+2. Inside the Layout component's return JSX, add `<CmdKSearch />` as a sibling — place it just before the closing `</div>` of the outermost wrapper (or at the end of the return). Since CmdKSearch renders via a portal to document.body, its placement in the JSX tree doesn't affect layout, but placing it in Layout ensures it's always mounted regardless of which page route is active.
+
+The component is self-contained — it uses the useCmdKSearch hook internally for open/close state and renders via portal. No props needed.
+
+Verify the dev server builds without errors after the change.
+ </action>
+ <verify>
+ <automated>cd client && npx vite build 2>&1 | tail -5</automated>
+ </verify>
+ <done>CmdKSearch is mounted in Layout.jsx; client builds without errors; overlay is available on every page</done>
+</task>
+
+<task type="checkpoint:human-verify" gate="blocking">
+ <name>Task 3: Verify Cmd+K search overlay end-to-end</name>
+ <files>none</files>
+ <action>
+Human verifies the complete Cmd+K search overlay:
+1. Open PortOS in browser (http://localhost:5555 or Tailscale URL)
+2. Press Cmd+K (Mac) or Ctrl+K (other) — search overlay should appear centered with ~800px width, dark backdrop
+3. Type "test" (or any 2+ char query) — results should appear grouped by source (Brain, Memory, Apps, History, Health)
+4. Verify each result shows: icon, bold title, snippet text with keyword highlighted
+5. Press ArrowDown/ArrowUp — selection highlight should move between results
+6. Press Enter on a highlighted result — should navigate to the deep-linked page and close overlay
+7. Reopen with Cmd+K, type a query, click a result — should navigate and close
+8. Click the dark backdrop — overlay should dismiss
+9. Press Escape — overlay should dismiss
+10. Try a query with no results — should show "No results for 'xyz'" message
+11. Verify overlay feels fast and responsive (300ms debounce, no lag)
+12. Verify body scroll is locked when overlay is open
+ </action>
+ <verify>Human approves the overlay appearance, keyboard navigation, result categorization, and deep-link navigation</verify>
+ <done>User types "approved" confirming the Cmd+K search overlay works correctly end-to-end</done>
+</task>
+
+</tasks>
+
+<verification>
+1. Cmd+K/Ctrl+K opens overlay from any page (Dashboard, Brain, Apps, etc.)
+2. Search returns results from all data sources that have matching content
+3. Results are visually grouped by source with icons and highlighted snippets
+4. Keyboard navigation (arrows + Enter + Escape) works fluidly
+5. Click navigation closes overlay and lands on correct deep-linked page
+6. Empty and loading states render correctly
+7. Client build succeeds: `cd client && npx vite build`
+</verification>
+
+<success_criteria>
+- Cmd+K / Ctrl+K opens search overlay from any page in PortOS
+- Typing 2+ chars triggers debounced search, results appear grouped by source
+- Each result shows icon, title, snippet with keyword highlighted
+- Arrow keys navigate results, Enter opens deep link, Escape closes
+- Clicking result navigates to URL and closes overlay
+- Clicking backdrop dismisses overlay
+- No-results and loading states render appropriately
+- Client builds without errors
+- Human verification approved
+</success_criteria>
+
+<output>
+After completion, create `.planning/phases/05-unified-search/05-02-SUMMARY.md`
+</output>