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: Ask Yourself — conversational digital twin (slice a)
Adam Eivye42cdfb0af87
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fb67b275c0..363ec3f2f0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,14 @@## Added+- **"Ask Yourself" — conversational digital twin (slice a: text chat + sources)** — a new top-level page (`/ask`, deep-linked at `/ask/:conversationId`) that runs a retrieval-augmented chat against your own data. Every question fans out in parallel across memory (hybrid BM25 + vector), brain notes (ideas / projects / inbox), autobiography stories, goals, and calendar events; results are reranked with kind-weighted scoring (memory + goals weighted highest) and deduped by source id. The persona preamble is sourced from `character.json` so answers come back in the user's voice; three modes (`ask` / `advise` / `draft`) swap directives without changing the source pipeline. Streaming is wired end-to-end: API providers stream OpenAI-style SSE chunks; CLI providers fall back to a single-shot completion. Each assistant turn renders source chips that deep-link to the origin (`/brain/memory?id=…`, `/digital-twin/goals?id=…`, `/calendar/agenda?date=…`, etc.). Conversations persist as JSON under `data/ask-conversations/<id>.json`, auto-expire after 30 days unless pinned (📌 button on the conversation header), and are listable in a sidebar. The user turn is persisted before streaming starts so a mid-stream disconnect still leaves the question on disk.++ **Nav integration**: registered in `server/lib/navManifest.js` (`nav.ask`) with aliases `ask`, `ask-yourself`, `twin-chat` so `⌘K` and the voice agent's `ui_navigate` resolve "ask" to `/ask` automatically. Sidebar entry alphabetized between Apps and Brain.++ **Slice (b) deferred**: voice integration, `ui_ask` tool, and one-click "Save as Brain note / Create CoS task / Attach to Goal" promotions will land in a follow-up.++ Files: `server/services/askService.js` (new — orchestration, retrieval, prompt assembly, streaming), `server/services/askConversations.js` (new — persistent storage with expiry + pin), `server/services/askService.test.js` (new — 11 tests), `server/services/askConversations.test.js` (new — 16 tests), `server/routes/ask.js` (new — SSE stream + list/get/delete/promote), `server/routes/ask.test.js` (new — 12 tests), `server/index.js` (mounts `/api/ask`), `server/lib/navManifest.js` (Ask entry), `client/src/services/apiAsk.js` (new — manual SSE reader since EventSource is GET-only), `client/src/services/api.js` (re-export), `client/src/pages/Ask.jsx` (new — chat transcript, source chips, mode switcher, conversation sidebar), `client/src/App.jsx` (routes), `client/src/components/Layout.jsx` (sidebar entry).+- **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.diff --git a/PLAN.md b/PLAN.mdindex af6958127b..efdea729f5 100644--- a/PLAN.md+++ b/PLAN.md@@ -83,7 +83,11 @@ Three high-value work items drawn from an inventory of the current app surface (----### 3. "Ask Yourself" — Unified Conversational Twin over Brain + Memory + Goals + Identity + Calendar+### 3. "Ask Yourself" — Unified Conversational Twin over Brain + Memory + Goals + Identity + Calendar — slice (a) ✅ SHIPPED 2026-04-24++> **Slice (a) — text chat + sources — shipped.** `/ask` and `/ask/:conversationId` are live. `server/services/askService.js` orchestrates parallel retrieval across memory (hybrid), brain notes, autobiography, goals, and calendar with kind-weighted reranking. Persona preamble is sourced from `character.json`. Three modes (`ask` / `advise` / `draft`) swap directives. API providers stream SSE; CLI providers single-shot. Conversations persist to `data/ask-conversations/<id>.json` with 30-day auto-expiry unless pinned. Source chips deep-link back to origin. Registered in the nav manifest so `⌘K` and voice (`ui_navigate`) resolve "ask" automatically. **Slice (b) (voice + promotion actions) still pending** — see backlog item below.+>+> 39 new tests (askService 11, askConversations 16, ask routes 12); full server suite stays green at 2548/2548.**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.@@ -124,6 +128,12 @@ Three high-value work items drawn from an inventory of the current app surface (## Backlog+- [ ] **Ask Yourself — slice (b)** — voice + promotion actions on top of the shipped text chat:+ - `ui_ask` voice tool that pipes a spoken question through `askService.runAsk` and reads the streamed answer aloud (reuses the existing voice widget's TTS path).+ - One-click promotions on each assistant turn: "Save as Brain note" (POST `/api/brain/capture`), "Create CoS task" (POST `/api/cos/tasks`), "Attach to Goal…" (link the answer text + sources as a goal note).+ - Promote action also sets `conversation.promoted = true` (already wired) so the conversation is exempt from 30-day auto-expiry once anything from it has been saved elsewhere.+ - Add `Ask` to the palette action whitelist (`server/routes/palette.js`) once the voice tool exists, so `⌘K` → "ask: …" can fire a prompt without leaving the current page.+- [ ] **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:- `calendar_today` / `calendar_next` — surface today's Google Calendar events through the existing Google MCP integration- `meatspace_log_workout` — wrap `meatspaceHealth.js` workout/activity exportsdiff --git a/client/src/App.jsx b/client/src/App.jsxindex caa47a6580..21e2717f75 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -66,6 +66,7 @@ const Goals = lazyWithReload(() => import('./pages/Goals'));const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));const Submodules = lazyWithReload(() => import('./pages/Submodules'));const ChiefOfStaff = lazyWithReload(() => import('./pages/ChiefOfStaff'));+const Ask = lazyWithReload(() => import('./pages/Ask'));// Loading fallback for lazy-loaded pagesconst PageLoader = () => (@@ -162,6 +163,8 @@ export default function App() {<Route path="city/settings" element={<CyberCity />} /><Route path="data" element={<DataManager />} /><Route path="character" element={<CharacterSheet />} />+ <Route path="ask" element={<Ask />} />+ <Route path="ask/:conversationId" element={<Ask />} /><Route path="wiki" element={<Navigate to="/wiki/overview" replace />} /><Route path="wiki/:tab" element={<Wiki />} /><Route path="agents" element={<Agents />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 915362c0c2..5ad06c8901 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -96,6 +96,7 @@ const navItems = [{ to: '/city', label: 'CyberCity', icon: Building2, single: true },{ separator: true },{ label: 'Apps', icon: Package, dynamic: 'apps', children: [] },+ { to: '/ask', label: 'Ask Yourself', icon: MessageCircle, single: true },{label: 'Brain',icon: Brain,diff --git a/client/src/pages/Ask.jsx b/client/src/pages/Ask.jsxnew file mode 100644index 0000000000..0af2704dbc--- /dev/null+++ b/client/src/pages/Ask.jsx@@ -0,0 +1,358 @@+import { useEffect, useRef, useState, useCallback, memo } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import { Send, Loader2, MessageCircle, Trash2, Pin, Brain, Calendar, Target, BookOpen, FileText, ExternalLink } from 'lucide-react';+import * as api from '../services/api';+import toast from '../components/ui/Toast';++export const ASK_MODES = [+ { id: 'ask', label: 'Ask', help: 'Answer as yourself, grounded in your own notes and goals.' },+ { id: 'advise', label: 'Advise', help: 'Coach you using your goals and constraints — push back where they conflict.' },+ { id: 'draft', label: 'Draft', help: 'Produce text in your voice for the recipient/platform you specify.' },+];++const KIND_META = {+ memory: { icon: Brain, label: 'Memory', tone: 'text-purple-400' },+ 'brain-note': { icon: FileText, label: 'Brain note', tone: 'text-blue-400' },+ autobiography: { icon: BookOpen, label: 'Autobiography', tone: 'text-amber-400' },+ goal: { icon: Target, label: 'Goal', tone: 'text-emerald-400' },+ calendar: { icon: Calendar, label: 'Calendar', tone: 'text-cyan-400' },+};++function SourceChip({ source, index }) {+ const meta = KIND_META[source.kind] || { icon: FileText, label: source.kind, tone: 'text-gray-400' };+ const Icon = meta.icon;+ const navigate = useNavigate();+ const onClick = () => {+ if (source.href?.startsWith('/')) navigate(source.href);+ else if (source.href) window.open(source.href, '_blank', 'noopener,noreferrer');+ };+ return (+ <button+ type="button"+ onClick={onClick}+ title={source.snippet || source.title}+ className="inline-flex items-center gap-1.5 max-w-[260px] truncate px-2 py-1 rounded-md bg-port-bg border border-port-border hover:border-port-accent/60 transition-colors text-xs"+ >+ <span className="text-gray-500">[{index + 1}]</span>+ <Icon size={12} className={meta.tone} />+ <span className="truncate">{source.title}</span>+ {source.href && <ExternalLink size={10} className="text-gray-500 shrink-0" />}+ </button>+ );+}++function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading }) {+ return (+ <aside className="w-full md:w-64 md:shrink-0 border-r border-port-border bg-port-card md:h-full md:overflow-y-auto">+ <div className="p-3 border-b border-port-border flex items-center gap-2">+ <button+ onClick={onNew}+ className="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-md bg-port-accent/15 text-port-accent hover:bg-port-accent/25 text-sm font-medium transition-colors"+ >+ <MessageCircle size={14} /> New conversation+ </button>+ </div>+ <div className="py-1">+ {loading && <div className="p-3 text-xs text-gray-500">Loading…</div>}+ {!loading && conversations.length === 0 && (+ <div className="p-3 text-xs text-gray-500">No conversations yet. Ask yourself something.</div>+ )}+ {conversations.map((c) => (+ <div+ key={c.id}+ className={`group flex items-center justify-between gap-2 px-3 py-2 cursor-pointer hover:bg-port-border/30 ${c.id === activeId ? 'bg-port-border/40' : ''}`}+ onClick={() => onPick(c.id)}+ >+ <div className="min-w-0 flex-1">+ <div className="text-sm truncate">{c.title}</div>+ <div className="text-xs text-gray-500 flex items-center gap-1.5">+ <span>{c.mode}</span>+ <span>·</span>+ <span>{c.turnCount} turns</span>+ {c.promoted && <Pin size={10} className="text-amber-400" />}+ </div>+ </div>+ <button+ onClick={(e) => { e.stopPropagation(); onDelete(c.id); }}+ className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-port-error transition-opacity"+ title="Delete conversation"+ >+ <Trash2 size={14} />+ </button>+ </div>+ ))}+ </div>+ </aside>+ );+}++// Memoized so previously-rendered turns don't re-render on every streaming+// delta — only the actively-streaming Turn at the bottom flips on each chunk.+const Turn = memo(function Turn({ turn, sources }) {+ const isUser = turn.role === 'user';+ const turnSources = turn.sources || sources || [];+ return (+ <div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>+ <div className={`max-w-[85%] rounded-lg px-4 py-3 ${isUser ? 'bg-port-accent/15 border border-port-accent/30' : 'bg-port-card border border-port-border'}`}>+ <div className="text-sm whitespace-pre-wrap break-words">{turn.content || (isUser ? '' : <span className="text-gray-500"><Loader2 size={14} className="inline animate-spin mr-1" />thinking…</span>)}</div>+ {!isUser && turnSources.length > 0 && (+ <div className="mt-3 pt-3 border-t border-port-border flex flex-wrap gap-1.5">+ {turnSources.map((s, i) => <SourceChip key={s.id} source={s} index={i} />)}+ </div>+ )}+ </div>+ </div>+ );+});++export default function Ask() {+ const { conversationId } = useParams();+ const navigate = useNavigate();++ const [conversations, setConversations] = useState([]);+ const [loadingList, setLoadingList] = useState(true);+ const [activeConv, setActiveConv] = useState(null);+ const [loadingConv, setLoadingConv] = useState(false);+ // streamingTurn === null means "not streaming". Storing the partial content+ // and sources in a single object is enough to drive both the UI and the+ // disabled-while-streaming guards.+ const [streamingTurn, setStreamingTurn] = useState(null);+ const [question, setQuestion] = useState('');+ const [mode, setMode] = useState('ask');+ const abortRef = useRef(null);+ const scrollRef = useRef(null);+ const streaming = streamingTurn !== null;++ const refreshList = useCallback(async () => {+ setLoadingList(true);+ const data = await api.listAskConversations().catch(() => null);+ setLoadingList(false);+ if (data?.conversations) setConversations(data.conversations);+ }, []);++ useEffect(() => { refreshList(); }, [refreshList]);++ useEffect(() => {+ let cancelled = false;+ if (!conversationId) {+ setActiveConv(null);+ return undefined;+ }+ setLoadingConv(true);+ api.getAskConversation(conversationId).then((data) => {+ if (cancelled) return;+ if (data?.conversation) {+ setActiveConv(data.conversation);+ setMode(data.conversation.mode || 'ask');+ } else {+ setActiveConv(null);+ }+ }).catch(() => {+ if (!cancelled) setActiveConv(null);+ }).finally(() => {+ if (!cancelled) setLoadingConv(false);+ });+ return () => { cancelled = true; };+ }, [conversationId]);++ // Auto-scroll the transcript to the bottom on new turns / streaming deltas.+ useEffect(() => {+ if (scrollRef.current) {+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;+ }+ }, [activeConv?.turns?.length, streamingTurn?.content]);++ const startNew = useCallback(() => {+ if (streaming) return;+ navigate('/ask');+ setActiveConv(null);+ setQuestion('');+ }, [navigate, streaming]);++ // Two-step delete: first click arms the row (toast confirms), second click+ // (within 4s) actually deletes. Per CLAUDE.md "no window.confirm".+ const pendingDeleteRef = useRef({ id: null, expiresAt: 0 });+ const handleDelete = useCallback(async (id) => {+ if (streaming && id === activeConv?.id) return;+ const pending = pendingDeleteRef.current;+ if (pending.id !== id || Date.now() > pending.expiresAt) {+ pendingDeleteRef.current = { id, expiresAt: Date.now() + 4000 };+ toast('Click delete again to confirm', { icon: '⚠️' });+ return;+ }+ pendingDeleteRef.current = { id: null, expiresAt: 0 };+ await api.deleteAskConversation(id).catch(() => null);+ setConversations((prev) => prev.filter((c) => c.id !== id));+ if (id === conversationId) navigate('/ask');+ }, [activeConv?.id, conversationId, navigate, streaming]);++ const handlePromote = useCallback(async () => {+ if (!activeConv) return;+ const next = !activeConv.promoted;+ const data = await api.promoteAskConversation(activeConv.id, next).catch(() => null);+ if (data?.conversation) {+ setActiveConv(data.conversation);+ setConversations((prev) => prev.map((c) => c.id === activeConv.id ? { ...c, promoted: next } : c));+ }+ }, [activeConv]);++ const handleSend = useCallback(async (e) => {+ e?.preventDefault?.();+ const trimmed = question.trim();+ if (!trimmed || streaming) return;+ setQuestion('');+ setStreamingTurn({ content: '', sources: [] });+ const controller = new AbortController();+ abortRef.current = controller;++ // Optimistic user turn so the UI doesn't sit blank between submit and+ // the first SSE 'open' event (gather-sources + provider connect = 100s+ // of ms).+ const nowIso = new Date().toISOString();+ const optimisticUserTurn = { id: `optimistic-${Date.now()}`, role: 'user', content: trimmed, createdAt: nowIso };+ setActiveConv((prev) => prev+ ? { ...prev, turns: [...(prev.turns || []), optimisticUserTurn] }+ : { id: 'pending', title: trimmed.slice(0, 80), mode, turns: [optimisticUserTurn], createdAt: nowIso, updatedAt: nowIso },+ );++ let serverConvId = activeConv?.id;+ let collectedSources = [];+ let answer = '';+ let persistedTurn = null;++ await api.streamAskTurn(+ { conversationId: activeConv?.id, question: trimmed, mode },+ {+ signal: controller.signal,+ onEvent: ({ event, data }) => {+ if (event === 'open') {+ serverConvId = data.conversationId;+ if (!activeConv?.id || activeConv.id === 'pending') {+ navigate(`/ask/${data.conversationId}`, { replace: true });+ }+ } else if (event === 'sources') {+ collectedSources = data.sources || [];+ setStreamingTurn((prev) => ({ content: prev?.content || '', sources: collectedSources }));+ } else if (event === 'delta') {+ answer += data.text || '';+ setStreamingTurn({ content: answer, sources: collectedSources });+ } else if (event === 'done') {+ persistedTurn = data.turn || null;+ } else if (event === 'error') {+ toast.error(data.error || 'Stream error');+ }+ },+ },+ ).catch((err) => {+ if (err.name !== 'AbortError') toast.error(err.message || 'Ask failed');+ });++ setStreamingTurn(null);+ abortRef.current = null;++ // Append the persisted assistant turn locally rather than refetching the+ // whole conversation — server returned the canonical record in 'done'.+ if (persistedTurn && serverConvId) {+ setActiveConv((prev) => {+ if (!prev || (prev.id !== 'pending' && prev.id !== serverConvId)) return prev;+ return { ...prev, id: serverConvId, turns: [...(prev.turns || []), persistedTurn], updatedAt: persistedTurn.createdAt };+ });+ }+ refreshList();+ }, [activeConv, mode, navigate, question, refreshList, streaming]);++ const turns = activeConv?.turns || [];+ const showEmptyState = !conversationId && !streaming;++ return (+ <div className="flex flex-col md:flex-row h-[calc(100vh-4rem)] -m-4">+ <Sidebar+ conversations={conversations}+ activeId={conversationId}+ onPick={(id) => navigate(`/ask/${id}`)}+ onNew={startNew}+ onDelete={handleDelete}+ loading={loadingList}+ />++ <main className="flex-1 flex flex-col min-w-0">+ <div className="px-4 md:px-6 py-3 border-b border-port-border flex items-center gap-3 flex-wrap">+ <h1 className="text-lg font-semibold flex items-center gap-2"><MessageCircle size={18} /> Ask Yourself</h1>+ <div className="flex items-center gap-1 ml-auto">+ {ASK_MODES.map((m) => (+ <button+ key={m.id}+ onClick={() => setMode(m.id)}+ title={m.help}+ className={`px-2.5 py-1 rounded-md text-xs font-medium transition-colors ${+ mode === m.id ? 'bg-port-accent/20 text-port-accent border border-port-accent/40' : 'text-gray-400 hover:text-white border border-transparent'+ }`}+ >+ {m.label}+ </button>+ ))}+ {activeConv && (+ <button+ onClick={handlePromote}+ title={activeConv.promoted ? 'Unpin (allow auto-expiry after 30d)' : 'Pin (exempt from auto-expiry)'}+ className={`p-1.5 rounded-md transition-colors ${activeConv.promoted ? 'text-amber-400 hover:text-amber-300' : 'text-gray-500 hover:text-white'}`}+ >+ <Pin size={14} />+ </button>+ )}+ </div>+ </div>++ <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 md:px-6 py-4 space-y-3">+ {loadingConv && <div className="text-sm text-gray-500"><Loader2 size={14} className="inline animate-spin mr-1" /> Loading…</div>}+ {showEmptyState && (+ <div className="max-w-2xl mx-auto mt-8 text-center text-gray-400 space-y-3">+ <h2 className="text-xl text-white">Talk to your digital twin.</h2>+ <p className="text-sm">+ Every question pulls from your memory, brain notes, autobiography, goals, and calendar in parallel — answers come back in your voice with the sources cited.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-left mt-6">+ {ASK_MODES.map((m) => (+ <div key={m.id} className="p-3 bg-port-card border border-port-border rounded-lg">+ <div className="text-sm text-white font-medium">{m.label}</div>+ <div className="text-xs text-gray-500 mt-1">{m.help}</div>+ </div>+ ))}+ </div>+ </div>+ )}+ {turns.map((t) => (+ <Turn key={t.id} turn={t} />+ ))}+ {streaming && streamingTurn && (+ <Turn turn={{ id: 'streaming', role: 'assistant', content: streamingTurn.content }} sources={streamingTurn.sources} />+ )}+ </div>++ <form onSubmit={handleSend} className="border-t border-port-border bg-port-card p-3 md:p-4">+ <div className="flex items-end gap-2">+ <textarea+ value={question}+ onChange={(e) => setQuestion(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) handleSend(e);+ }}+ placeholder={mode === 'draft' ? 'Describe what you want drafted (recipient, tone, key points)…' : 'Ask yourself anything…'}+ rows={2}+ className="flex-1 resize-none rounded-md bg-port-bg border border-port-border px-3 py-2 text-sm focus:outline-none focus:border-port-accent/60"+ />+ <button+ type="submit"+ disabled={streaming || !question.trim()}+ className="px-3 py-2 rounded-md bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5 text-sm font-medium"+ >+ {streaming ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}+ {streaming ? 'Streaming…' : 'Send'}+ </button>+ </div>+ <div className="mt-1.5 text-xs text-gray-500">⌘/Ctrl + Enter to send</div>+ </form>+ </main>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 0bb9104513..8c194b1c61 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -34,6 +34,7 @@ export * from './apiMortalLoom.js';export * from './apiOpenClaw.js';export * from './apiPalette.js';export * from './apiDashboard.js';+export * from './apiAsk.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiAsk.js b/client/src/services/apiAsk.jsnew file mode 100644index 0000000000..ccda860310--- /dev/null+++ b/client/src/services/apiAsk.js@@ -0,0 +1,60 @@+import { request, API_BASE } from './apiCore.js';++export const listAskConversations = () => request('/ask');+export const getAskConversation = (id) => request(`/ask/${encodeURIComponent(id)}`);+export const deleteAskConversation = (id) => request(`/ask/${encodeURIComponent(id)}`, { method: 'DELETE' });+export const promoteAskConversation = (id, promoted = true) => request(`/ask/${encodeURIComponent(id)}/promote`, {+ method: 'POST',+ body: JSON.stringify({ promoted }),+});++/**+ * Stream an Ask turn via Server-Sent Events. Consumes the event-stream+ * response from POST /api/ask manually because EventSource only supports GET.+ *+ * Returns an AbortController.signal-aware Promise that resolves when the+ * server closes the stream. Each event is delivered to `onEvent({ event, data })`.+ *+ * Events: 'open' | 'sources' | 'delta' | 'error' | 'done'+ */+export async function streamAskTurn(payload, { onEvent, signal } = {}) {+ const response = await fetch(`${API_BASE}/ask`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },+ body: JSON.stringify(payload),+ signal,+ });+ if (!response.ok || !response.body) {+ const text = await response.text().catch(() => '');+ let message = `HTTP ${response.status}`;+ try { message = JSON.parse(text)?.error || message; } catch { /* not JSON */ }+ throw new Error(message);+ }++ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let currentEvent = 'message';++ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });++ let frameEnd;+ while ((frameEnd = buffer.indexOf('\n\n')) !== -1) {+ const frame = buffer.slice(0, frameEnd);+ buffer = buffer.slice(frameEnd + 2);+ currentEvent = 'message';+ let dataLine = '';+ for (const line of frame.split('\n')) {+ if (line.startsWith('event:')) currentEvent = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLine += line.slice(5).trim();+ }+ if (!dataLine) continue;+ let data = null;+ try { data = JSON.parse(dataLine); } catch { data = { raw: dataLine }; }+ onEvent?.({ event: currentEvent, data });+ }+ }+}diff --git a/server/index.js b/server/index.jsindex 0df16d159e..43d436d10b 100644--- a/server/index.js+++ b/server/index.js@@ -77,6 +77,7 @@ import characterRoutes from './routes/character.js';import toolsRoutes from './routes/tools.js';import imageGenRoutes from './routes/imageGen.js';import openclawRoutes from './routes/openclaw.js';+import askRoutes from './routes/ask.js';import { ensureSelf, startPolling } from './services/instances.js';import { initSyncLog } from './services/brainSyncLog.js';import { backfillOriginInstanceId } from './services/brainStorage.js';@@ -301,6 +302,7 @@ app.use('/api/character', characterRoutes);app.use('/api/tools', toolsRoutes);app.use('/api/image-gen', imageGenRoutes);app.use('/api/openclaw', openclawRoutes);+app.use('/api/ask', askRoutes);// Initialize agent automation scheduler and action executorautomationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 7f21b8d669..d915c6e2c1 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -5,6 +5,7 @@export const NAV_COMMANDS = [{ id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['dashboard', 'home'], keywords: ['overview', 'start'] },+ { id: 'nav.ask', path: '/ask', label: 'Ask Yourself', section: 'Main', aliases: ['ask', 'ask-yourself', 'twin-chat'], keywords: ['chat', 'twin', 'conversation', 'advise', 'draft'] },{ 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'] },diff --git a/server/routes/ask.js b/server/routes/ask.jsnew file mode 100644index 0000000000..1503732892--- /dev/null+++ b/server/routes/ask.js@@ -0,0 +1,168 @@+/**+ * "Ask Yourself" Routes+ *+ * GET /api/ask → list conversations (summaries)+ * GET /api/ask/:id → full conversation+ * POST /api/ask → SSE-stream a new turn (creates a+ * conversation if no `id` in body)+ * DELETE /api/ask/:id → delete a conversation+ * POST /api/ask/:id/promote → mark conversation exempt from+ * 30-day auto-expiry+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as convs from '../services/askConversations.js';+import { runAsk, VALID_MODES } from '../services/askService.js';++const router = Router();++// How many prior turns to include when assembling the prompt. The persisted+// conversation file keeps everything; trimming here keeps the prompt bounded+// against multi-turn token blowup.+const PROMPT_HISTORY_TURNS = 12;++const idSchema = z.string().regex(/^ask_[a-z0-9]+_[a-f0-9]+$/, 'invalid conversation id');++const askBodySchema = z.object({+ conversationId: idSchema.optional(),+ question: z.string().trim().min(1).max(4000),+ mode: z.enum([...VALID_MODES]).optional().default('ask'),+ providerId: z.string().min(1).max(100).optional(),+ model: z.string().min(1).max(200).optional(),+ maxSources: z.number().int().min(1).max(50).optional().default(12),+ timeWindow: z.object({+ days: z.number().int().min(1).max(365).optional(),+ startDate: z.string().datetime().optional(),+ endDate: z.string().datetime().optional(),+ }).optional(),+});++const promoteBodySchema = z.object({+ promoted: z.boolean().optional().default(true),+});++router.get('/', asyncHandler(async (_req, res) => {+ const conversations = await convs.listConversations({ limit: 100 });+ res.json({ conversations });+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const conv = await convs.getConversation(String(req.params.id));+ if (!conv) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });+ res.json({ conversation: conv });+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ const removed = await convs.deleteConversation(String(req.params.id));+ if (!removed) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });+ res.json({ ok: true });+}));++router.post('/:id/promote', asyncHandler(async (req, res) => {+ const { promoted } = validateRequest(promoteBodySchema, req.body ?? {});+ const conv = await convs.setPromoted(String(req.params.id), promoted);+ if (!conv) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });+ res.json({ conversation: conv });+}));++// Stream a new turn over SSE. Body { conversationId?, question, mode?, ... }.+// If no conversationId, a new conversation is created and its id is+// surfaced in the first SSE event so the client can deep-link.+router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(askBodySchema, req.body ?? {});++ let conversation = body.conversationId+ ? await convs.getConversation(body.conversationId)+ : null;+ if (body.conversationId && !conversation) {+ throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });+ }+ if (!conversation) {+ conversation = await convs.createConversation({ mode: body.mode, title: body.question });+ }++ // Persist the user turn before streaming so a mid-stream disconnect still+ // leaves the question on disk — the user can reopen the conversation and+ // see their own question waiting.+ const { conversation: afterUser } = await convs.appendTurn(conversation.id, {+ role: 'user',+ content: body.question,+ mode: body.mode,+ });+ conversation = afterUser;++ // SSE handshake.+ res.set({+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache, no-transform',+ Connection: 'keep-alive',+ 'X-Accel-Buffering': 'no',+ });+ res.flushHeaders?.();++ const send = (event, data) => {+ res.write(`event: ${event}\n`);+ res.write(`data: ${JSON.stringify(data)}\n\n`);+ };++ // Tell the client the conversation id up-front so it can deep-link the URL+ // before the answer finishes streaming.+ send('open', { conversationId: conversation.id, mode: body.mode });++ // Drop the just-appended user turn (we're about to answer it) plus take+ // the last PROMPT_HISTORY_TURNS prior turns as multi-turn context.+ const history = (conversation.turns || []).slice(-(PROMPT_HISTORY_TURNS + 1), -1);++ let assistantText = '';+ let assistantSources = [];+ let providerInfo = {};++ let streamErrored = false;+ for await (const evt of runAsk({+ question: body.question,+ mode: body.mode,+ history,+ timeWindow: body.timeWindow,+ maxSources: body.maxSources,+ providerId: body.providerId,+ model: body.model,+ })) {+ if (evt.type === 'sources') {+ assistantSources = evt.sources;+ send('sources', { sources: evt.sources });+ } else if (evt.type === 'delta') {+ assistantText += evt.text;+ send('delta', { text: evt.text });+ } else if (evt.type === 'done') {+ providerInfo = { providerId: evt.providerId, model: evt.model };+ // Streaming providers accumulate via delta events; one-shot CLI+ // providers report the full answer once at 'done'.+ if (!assistantText && evt.answer) assistantText = evt.answer;+ } else if (evt.type === 'error') {+ streamErrored = true;+ send('error', { error: evt.error });+ }+ }++ let persistedAssistantTurn = null;+ if (!streamErrored && assistantText) {+ const result = await convs.appendTurn(conversation.id, {+ role: 'assistant',+ content: assistantText,+ sources: assistantSources,+ mode: body.mode,+ ...providerInfo,+ });+ persistedAssistantTurn = result.turn;+ }++ // Hand back the persisted turn so the client can append to local state+ // instead of round-tripping a full conversation refetch.+ send('done', { conversationId: conversation.id, turn: persistedAssistantTurn });+ res.end();+}));++export default router;diff --git a/server/routes/ask.test.js b/server/routes/ask.test.jsnew file mode 100644index 0000000000..c10f67b225--- /dev/null+++ b/server/routes/ask.test.js@@ -0,0 +1,166 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/askConversations.js', () => ({+ listConversations: vi.fn(),+ getConversation: vi.fn(),+ createConversation: vi.fn(),+ appendTurn: vi.fn(),+ deleteConversation: vi.fn(),+ setPromoted: vi.fn(),+}));++vi.mock('../services/askService.js', () => ({+ // The route imports the literal Set and spreads it for zod — keep the real+ // type so zod validation matches what production sees.+ VALID_MODES: new Set(['ask', 'advise', 'draft']),+ runAsk: vi.fn(),+}));++const convs = await import('../services/askConversations.js');+const svc = await import('../services/askService.js');+const { default: routes } = await import('./ask.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/ask', routes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('GET /api/ask', () => {+ it('returns a list of conversation summaries', async () => {+ convs.listConversations.mockResolvedValue([+ { id: 'ask_a_b', title: 'Old', mode: 'ask', turnCount: 2, createdAt: 'x', updatedAt: 'x', promoted: false },+ ]);+ const res = await request(makeApp()).get('/api/ask');+ expect(res.status).toBe(200);+ expect(res.body.conversations).toHaveLength(1);+ });+});++describe('GET /api/ask/:id', () => {+ it('404s for missing conversation', async () => {+ convs.getConversation.mockResolvedValue(null);+ const res = await request(makeApp()).get('/api/ask/ask_x_dead');+ expect(res.status).toBe(404);+ });++ it('returns the conversation', async () => {+ convs.getConversation.mockResolvedValue({ id: 'ask_x_a1', turns: [], mode: 'ask' });+ const res = await request(makeApp()).get('/api/ask/ask_x_a1');+ expect(res.status).toBe(200);+ expect(res.body.conversation.id).toBe('ask_x_a1');+ });+});++describe('DELETE /api/ask/:id', () => {+ it('deletes when the service confirms', async () => {+ convs.deleteConversation.mockResolvedValue(true);+ const res = await request(makeApp()).delete('/api/ask/ask_x_a1');+ expect(res.status).toBe(200);+ expect(res.body.ok).toBe(true);+ });++ it('404s when nothing was removed', async () => {+ convs.deleteConversation.mockResolvedValue(false);+ const res = await request(makeApp()).delete('/api/ask/ask_x_a1');+ expect(res.status).toBe(404);+ });+});++describe('POST /api/ask/:id/promote', () => {+ it('promotes the conversation', async () => {+ convs.setPromoted.mockResolvedValue({ id: 'ask_x_a1', promoted: true });+ const res = await request(makeApp())+ .post('/api/ask/ask_x_a1/promote')+ .send({ promoted: true });+ expect(res.status).toBe(200);+ expect(convs.setPromoted).toHaveBeenCalledWith('ask_x_a1', true);+ });++ it('404s when the conversation does not exist', async () => {+ convs.setPromoted.mockResolvedValue(null);+ const res = await request(makeApp())+ .post('/api/ask/ask_x_a1/promote')+ .send({ promoted: true });+ expect(res.status).toBe(404);+ });+});++describe('POST /api/ask (validation)', () => {+ it('rejects empty questions', async () => {+ const res = await request(makeApp())+ .post('/api/ask')+ .send({ question: ' ' });+ expect(res.status).toBe(400);+ });++ it('rejects unknown modes', async () => {+ const res = await request(makeApp())+ .post('/api/ask')+ .send({ question: 'hi', mode: 'shout' });+ expect(res.status).toBe(400);+ });++ it('rejects malformed conversationIds', async () => {+ const res = await request(makeApp())+ .post('/api/ask')+ .send({ question: 'hi', conversationId: 'not-an-id' });+ expect(res.status).toBe(400);+ });++ it('404s when conversationId is well-formed but unknown', async () => {+ convs.getConversation.mockResolvedValue(null);+ const res = await request(makeApp())+ .post('/api/ask')+ .send({ question: 'hi', conversationId: 'ask_x_aaaaaa' });+ expect(res.status).toBe(404);+ });+});++describe('POST /api/ask (streaming happy path)', () => {+ it('streams open → sources → delta → done as SSE', async () => {+ convs.createConversation.mockResolvedValue({ id: 'ask_new_abcdef', mode: 'ask', turns: [] });+ convs.appendTurn.mockImplementation((id, turn) => Promise.resolve({+ conversation: { id, mode: 'ask', turns: [{ ...turn, id: 'tid' }] },+ turn: { ...turn, id: 'tid' },+ }));+ // runAsk is async-iterable — emit a deterministic event sequence.+ svc.runAsk.mockImplementation(async function* () {+ yield { type: 'sources', sources: [{ kind: 'memory', id: 'memory:1', title: 'a', snippet: 'b' }] };+ yield { type: 'delta', text: 'Hi ' };+ yield { type: 'delta', text: 'there.' };+ yield { type: 'done', answer: 'Hi there.', sources: [], providerId: 'fake', model: 'm' };+ });++ const res = await request(makeApp())+ .post('/api/ask')+ .send({ question: 'hello' });++ expect(res.status).toBe(200);+ expect(res.headers['content-type'] || '').toMatch(/text\/event-stream/);+ // testHelper buffers the whole body — assert event ordering and payloads+ // by string matching rather than parsing each frame.+ const body = res.text || '';+ expect(body).toContain('event: open');+ expect(body).toContain('"conversationId":"ask_new_abcdef"');+ expect(body).toContain('event: sources');+ expect(body).toContain('event: delta');+ expect(body).toContain('"text":"Hi "');+ expect(body).toContain('event: done');++ // The user turn must be persisted before streaming begins, and the+ // assistant turn after the stream closes — assert both happened.+ const roles = convs.appendTurn.mock.calls.map((c) => c[1].role);+ expect(roles).toContain('user');+ expect(roles).toContain('assistant');+ });+});diff --git a/server/services/askConversations.js b/server/services/askConversations.jsnew file mode 100644index 0000000000..a056467fd8--- /dev/null+++ b/server/services/askConversations.js@@ -0,0 +1,178 @@+/**+ * Ask Conversations+ *+ * Persistent storage for "Ask Yourself" conversations — the chat transcript+ * the user has with their digital twin, with sources cited per turn.+ *+ * Each conversation is one JSON file under data/ask-conversations/<id>.json.+ * Files older than 30 days are auto-pruned on list, unless the user has+ * pinned them via setPromoted().+ *+ * Conversation shape:+ * { id, title, mode, createdAt, updatedAt, promoted, turns[] }+ * Turn shape:+ * { id, role: 'user'|'assistant', content, sources?, mode?, providerId?, model?, createdAt }+ *+ * Conversation ids are sortable: `ask_<base36-ms>_<hex>`. Lexically sorting+ * filenames descending therefore returns newest-first without reading any+ * file — `listConversations` exploits this so it doesn't have to parse every+ * JSON in the directory just to honour `limit`.+ */++import { join } from 'path';+import { readdir, unlink } from 'fs/promises';+import { randomUUID } from 'crypto';+import { PATHS, atomicWrite, ensureDir, readJSONFile, safeDate } from '../lib/fileUtils.js';+import { VALID_MODES as VALID_MODES_SET } from './askService.js';++export const ASK_DIR = join(PATHS.data, 'ask-conversations');+export const EXPIRY_DAYS = 30;+export const TITLE_MAX_LENGTH = 120;+export { VALID_MODES_SET as VALID_MODES };++const ID_RE = /^ask_[a-z0-9]+_[a-f0-9]+$/;++function generateId() {+ // Sortable timestamp + short random suffix; safe filename component.+ return `ask_${Date.now().toString(36)}_${randomUUID().split('-')[0]}`;+}++export function isValidId(id) {+ return typeof id === 'string' && ID_RE.test(id);+}++function pathFor(id) {+ if (!isValidId(id)) throw new Error(`Invalid conversation id: ${id}`);+ return join(ASK_DIR, `${id}.json`);+}++function truncateTitle(text) {+ if (typeof text !== 'string') return '';+ const trimmed = text.trim().replace(/\s+/g, ' ');+ if (trimmed.length <= TITLE_MAX_LENGTH) return trimmed;+ return trimmed.slice(0, TITLE_MAX_LENGTH - 1) + '…';+}++async function readConversation(id) {+ const data = await readJSONFile(pathFor(id), null, { logError: false });+ if (!data || typeof data !== 'object' || data.id !== id) return null;+ return data;+}++export async function getConversation(id) {+ if (!isValidId(id)) return null;+ return readConversation(id);+}++export async function listConversations({ limit = 50 } = {}) {+ await ensureDir(ASK_DIR);+ const entries = await readdir(ASK_DIR).catch((err) => {+ if (err.code === 'ENOENT') return [];+ throw err;+ });++ // Filenames carry a sortable timestamp prefix (`ask_<base36-ms>_…`) so a+ // descending lexical sort gives newest-first ordering without reading any+ // file. This caps the number of disk reads at `limit` instead of scanning+ // every conversation just to satisfy a paginated UI.+ const ids = entries+ .filter((f) => f.endsWith('.json'))+ .map((f) => f.slice(0, -5))+ .filter(isValidId)+ .sort((a, b) => b.localeCompare(a));++ const summaries = [];+ const now = Date.now();+ const expiryMs = EXPIRY_DAYS * 24 * 60 * 60 * 1000;++ for (const id of ids) {+ if (summaries.length >= limit) break;+ const conv = await readConversation(id);+ if (!conv) continue;++ const updated = safeDate(conv.updatedAt) || safeDate(conv.createdAt);+ if (!conv.promoted && updated && (now - updated) > expiryMs) {+ // Single-user app — no concurrency races to worry about pruning here.+ await unlink(pathFor(id)).catch(() => {});+ continue;+ }++ summaries.push({+ id: conv.id,+ title: conv.title || '(untitled)',+ mode: conv.mode,+ createdAt: conv.createdAt,+ updatedAt: conv.updatedAt,+ turnCount: Array.isArray(conv.turns) ? conv.turns.length : 0,+ promoted: !!conv.promoted,+ });+ }++ return summaries;+}++export async function createConversation({ mode = 'ask', title = '' } = {}) {+ if (!VALID_MODES_SET.has(mode)) throw new Error(`Invalid mode: ${mode}`);+ await ensureDir(ASK_DIR);+ const now = new Date().toISOString();+ const conv = {+ id: generateId(),+ title: truncateTitle(title) || '(new conversation)',+ mode,+ createdAt: now,+ updatedAt: now,+ promoted: false,+ turns: [],+ };+ await atomicWrite(pathFor(conv.id), conv);+ return conv;+}++export async function appendTurn(conversationId, turn) {+ const conv = await readConversation(conversationId);+ if (!conv) throw new Error(`Conversation not found: ${conversationId}`);+ if (!turn || (turn.role !== 'user' && turn.role !== 'assistant')) {+ throw new Error('Turn must include role of "user" or "assistant"');+ }+ const stamped = {+ id: turn.id || randomUUID(),+ role: turn.role,+ content: typeof turn.content === 'string' ? turn.content : '',+ createdAt: turn.createdAt || new Date().toISOString(),+ ...(turn.sources ? { sources: turn.sources } : {}),+ ...(turn.mode ? { mode: turn.mode } : {}),+ ...(turn.providerId ? { providerId: turn.providerId } : {}),+ ...(turn.model ? { model: turn.model } : {}),+ };+ conv.turns = [...(conv.turns || []), stamped];+ // First user turn becomes the conversation title — give the listing a+ // useful label without a separate naming step.+ if (turn.role === 'user' && (!conv.title || conv.title === '(new conversation)')) {+ conv.title = truncateTitle(turn.content);+ }+ conv.updatedAt = stamped.createdAt;+ await atomicWrite(pathFor(conversationId), conv);+ return { conversation: conv, turn: stamped };+}++export async function deleteConversation(id) {+ if (!isValidId(id)) return false;+ const removed = await unlink(pathFor(id)).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+ });+ return removed;+}++export async function setPromoted(id, promoted) {+ const conv = await readConversation(id);+ if (!conv) return null;+ conv.promoted = !!promoted;+ conv.updatedAt = new Date().toISOString();+ await atomicWrite(pathFor(id), conv);+ return conv;+}++// Test helper — exposed so tests can introspect/clean state without+// duplicating path math. Not part of the public API.+export const __test = { pathFor, generateId, ASK_DIR };diff --git a/server/services/askConversations.test.js b/server/services/askConversations.test.jsnew file mode 100644index 0000000000..6540910660--- /dev/null+++ b/server/services/askConversations.test.js@@ -0,0 +1,178 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdirSync, rmSync } from 'fs';+import { join } from 'path';++const { TEMP_ROOT } = vi.hoisted(() => {+ const { mkdtempSync } = require('fs');+ const { tmpdir } = require('os');+ const { join } = require('path');+ return { TEMP_ROOT: mkdtempSync(join(tmpdir(), 'ask-conversations-')) };+});++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...actual,+ PATHS: { ...actual.PATHS, data: TEMP_ROOT },+ };+});++const convs = await import('./askConversations.js');++afterAll(() => {+ rmSync(TEMP_ROOT, { recursive: true, force: true });+});++beforeEach(() => {+ // Fresh scratch state per test — rm then recreate the same dir so the+ // vi.mock of PATHS.data still resolves to a real path.+ rmSync(TEMP_ROOT, { recursive: true, force: true });+ mkdirSync(TEMP_ROOT, { recursive: true });+});++describe('askConversations', () => {+ describe('isValidId', () => {+ it('accepts a canonical literal id', () => {+ // Literal so the regex breaks if the format changes silently —+ // generator round-trips alone wouldn't catch a regex relaxation.+ expect(convs.isValidId('ask_lwg2x4_abcdef12')).toBe(true);+ });++ it('accepts ids produced by the generator', () => {+ const id = convs.__test.generateId();+ expect(convs.isValidId(id)).toBe(true);+ });++ it('rejects ids with path traversal characters', () => {+ expect(convs.isValidId('ask_x_..')).toBe(false);+ expect(convs.isValidId('../etc/passwd')).toBe(false);+ expect(convs.isValidId('ask_x/y_abc')).toBe(false);+ });++ it('rejects empty / non-string', () => {+ expect(convs.isValidId('')).toBe(false);+ expect(convs.isValidId(null)).toBe(false);+ expect(convs.isValidId(undefined)).toBe(false);+ expect(convs.isValidId(123)).toBe(false);+ });+ });++ describe('createConversation', () => {+ it('creates a conversation with a usable id and persists it', async () => {+ const conv = await convs.createConversation({ mode: 'ask', title: 'Hello world' });+ expect(convs.isValidId(conv.id)).toBe(true);+ expect(conv.mode).toBe('ask');+ expect(conv.title).toBe('Hello world');+ expect(conv.turns).toEqual([]);+ const refetch = await convs.getConversation(conv.id);+ expect(refetch).toEqual(conv);+ });++ it('rejects invalid modes', async () => {+ await expect(convs.createConversation({ mode: 'shout' })).rejects.toThrow(/Invalid mode/);+ });++ it('truncates long titles', async () => {+ const long = 'x'.repeat(500);+ const conv = await convs.createConversation({ title: long });+ expect(conv.title.length).toBeLessThanOrEqual(convs.TITLE_MAX_LENGTH);+ expect(conv.title.endsWith('…')).toBe(true);+ });+ });++ describe('appendTurn', () => {+ it('appends user then assistant turns', async () => {+ const conv = await convs.createConversation({ mode: 'ask' });+ await convs.appendTurn(conv.id, { role: 'user', content: 'What did I decide last week?' });+ const { conversation } = await convs.appendTurn(conv.id, {+ role: 'assistant',+ content: 'You decided to ship slice (a) first.',+ sources: [{ kind: 'memory', id: 'memory:1', title: 'Decision', snippet: 'shipped slice a' }],+ });+ expect(conversation.turns).toHaveLength(2);+ expect(conversation.turns[0].role).toBe('user');+ expect(conversation.turns[1].sources).toHaveLength(1);+ });++ it('uses the first user turn as the conversation title when none was given', async () => {+ const conv = await convs.createConversation({ mode: 'ask' });+ // createConversation defaulted to "(new conversation)" — the first user+ // turn should overwrite it so the listing is meaningful.+ const { conversation } = await convs.appendTurn(conv.id, {+ role: 'user',+ content: 'Should I move my workout to mornings?',+ });+ expect(conversation.title).toMatch(/Should I move my workout/);+ });++ it('rejects unknown roles', async () => {+ const conv = await convs.createConversation({ mode: 'ask' });+ await expect(convs.appendTurn(conv.id, { role: 'system', content: 'x' })).rejects.toThrow(/role/);+ });++ it('rejects unknown conversation ids', async () => {+ await expect(convs.appendTurn('ask_zzz_dead', { role: 'user', content: 'x' })).rejects.toThrow(/not found/);+ });+ });++ describe('listConversations', () => {+ it('returns summaries newest-first', async () => {+ const a = await convs.createConversation({ title: 'oldest' });+ // Force distinct updatedAt timestamps so the sort is deterministic.+ await new Promise((r) => setTimeout(r, 5));+ await convs.appendTurn(a.id, { role: 'user', content: 'oldest q' });+ const b = await convs.createConversation({ title: 'newest' });+ await new Promise((r) => setTimeout(r, 5));+ await convs.appendTurn(b.id, { role: 'user', content: 'newest q' });++ const summaries = await convs.listConversations();+ expect(summaries.map((s) => s.id)).toEqual([b.id, a.id]);+ expect(summaries[0].turnCount).toBe(1);+ });++ it('prunes non-promoted conversations older than 30 days', async () => {+ const stale = await convs.createConversation({ title: 'stale' });+ // Backdate the file by writing a stale updatedAt. We cheat by re-saving+ // the conversation with an old timestamp via the underlying path.+ const { writeFileSync, readFileSync } = await import('fs');+ const path = convs.__test.pathFor(stale.id);+ const data = JSON.parse(readFileSync(path, 'utf-8'));+ data.updatedAt = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000).toISOString();+ writeFileSync(path, JSON.stringify(data));++ const summaries = await convs.listConversations();+ expect(summaries.find((s) => s.id === stale.id)).toBeUndefined();+ });++ it('keeps promoted conversations regardless of age', async () => {+ const promoted = await convs.createConversation({ title: 'pinned' });+ await convs.setPromoted(promoted.id, true);+ const { writeFileSync, readFileSync } = await import('fs');+ const path = convs.__test.pathFor(promoted.id);+ const data = JSON.parse(readFileSync(path, 'utf-8'));+ data.updatedAt = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString();+ writeFileSync(path, JSON.stringify(data));++ const summaries = await convs.listConversations();+ expect(summaries.find((s) => s.id === promoted.id)).toBeDefined();+ });+ });++ describe('deleteConversation', () => {+ it('removes the file and reports true', async () => {+ const conv = await convs.createConversation({ title: 'to delete' });+ const removed = await convs.deleteConversation(conv.id);+ expect(removed).toBe(true);+ expect(await convs.getConversation(conv.id)).toBeNull();+ });++ it('returns false when nothing was deleted', async () => {+ const fakeId = convs.__test.generateId();+ expect(await convs.deleteConversation(fakeId)).toBe(false);+ });++ it('refuses path-traversal ids', async () => {+ expect(await convs.deleteConversation('../etc/passwd')).toBe(false);+ });+ });+});diff --git a/server/services/askService.js b/server/services/askService.jsnew file mode 100644index 0000000000..8428ad9e0f--- /dev/null+++ b/server/services/askService.js@@ -0,0 +1,495 @@+/**+ * Ask Service+ *+ * Powers the "Ask Yourself" page — a retrieval-augmented chat with the user's+ * own digital twin. For each question:+ *+ * 1. Fan-out retrieval in parallel across memory (hybrid BM25 + vector),+ * brain notes, autobiography stories, goals, and calendar events.+ * 2. Rerank + cap each source, then dedupe across sources.+ * 3. Assemble a persona-flavored prompt (twin tone + life context).+ * 4. Stream the completion through the active AI provider.+ *+ * The function exported here returns an async iterable of stream events:+ * { type: 'sources', sources: Source[] }+ * { type: 'delta', text: string }+ * { type: 'done', usage?: {...} }+ * { type: 'error', error: string }+ *+ * Routes consume this and forward as Server-Sent Events.+ */++import { getActiveProvider, getProviderById } from './providers.js';+import { hybridSearchMemories, getMemory } from './memoryBackend.js';+import { generateQueryEmbedding } from './memoryEmbeddings.js';+import { getInboxLog, getProjects, getIdeas } from './brainStorage.js';+import { getStories } from './autobiography.js';+import { getGoals } from './identity.js';+import { getCharacter } from './character.js';+import { getEvents as getCalendarEvents } from './calendarSync.js';+import { tokenize as bm25Tokenize, STOP_WORDS } from '../lib/bm25.js';++export const VALID_MODES = new Set(['ask', 'advise', 'draft']);+export const SOURCE_KINDS = ['memory', 'brain-note', 'autobiography', 'goal', 'calendar'];++const PER_SOURCE_LIMIT = {+ memory: 6,+ 'brain-note': 5,+ autobiography: 3,+ goal: 5,+ calendar: 6,+};++// Truncation caps for prompt assembly. Source snippets are short summaries;+// transcript turns are previous chat turns trimmed so multi-turn history+// can't blow the token budget alone.+const SNIPPET_MAX_CHARS = 600;+const HISTORY_TURN_MAX_CHARS = 1500;+// Autobiography stories grow over time — cap how many we score per question+// so a user with hundreds of stories doesn't make every Ask quadratic.+const AUTOBIO_SCAN_LIMIT = 50;+// Calendar window default + cap. ±7 days covers the ambient "what do I have+// going on" case; the per-source cap on the result list does the rest.+const CALENDAR_DEFAULT_DAYS = 7;+const CALENDAR_FETCH_LIMIT = 50;+const MS_PER_DAY = 24 * 60 * 60 * 1000;++const PERSONA_FALLBACK = `You are the user's digital twin — speak in the first person, in their voice and with their values. Be direct, specific, and practical.`;++// =============================================================================+// PARALLEL RETRIEVAL+// =============================================================================++// `gatherSources` wraps every retriever in `Promise.allSettled`, so a thrown+// error here surfaces as `status: 'rejected'` rather than killing the answer+// — that's why these functions don't carry their own try/catch.++async function retrieveMemories(question) {+ const queryEmbedding = await generateQueryEmbedding(question);+ if (!queryEmbedding) return [];+ const result = await hybridSearchMemories(question, queryEmbedding, {+ limit: PER_SOURCE_LIMIT.memory,+ ftsWeight: 0.4,+ vectorWeight: 0.6,+ });+ const hits = result?.memories || [];+ // Single missing record shouldn't drop the whole batch — allSettled per id.+ const fetched = await Promise.allSettled(hits.map((h) => getMemory(h.id)));+ const sources = [];+ for (let i = 0; i < hits.length; i++) {+ const settled = fetched[i];+ const mem = settled.status === 'fulfilled' ? settled.value : null;+ if (!mem) continue;+ sources.push({+ kind: 'memory',+ id: `memory:${mem.id}`,+ title: mem.summary || mem.type || 'Memory',+ snippet: mem.content || '',+ relevance: hits[i].rrfScore || hits[i].similarity || 0.5,+ href: `/brain/memory?id=${encodeURIComponent(mem.id)}`,+ meta: { type: mem.type, importance: mem.importance, updatedAt: mem.updatedAt },+ });+ }+ return sources;+}++// askService scores by query-term overlap, not BM25 — but the tokenizer+// (lowercase, stopword-strip, punctuation-strip) is identical, so we share+// it with the BM25 module to keep stopword lists in lockstep.+function tokenize(text) {+ return bm25Tokenize(text).filter((t) => t.length >= 3 && !STOP_WORDS.has(t));+}++function lexicalScore(text, queryTokens) {+ if (!queryTokens.length) return 0;+ const docTokens = tokenize(text);+ if (!docTokens.length) return 0;+ const docSet = new Set(docTokens);+ let hits = 0;+ for (const q of queryTokens) {+ if (docSet.has(q)) hits++;+ }+ return hits / queryTokens.length;+}++function rankAndCap(candidates, kind) {+ return candidates+ .filter((c) => c.relevance > 0)+ .sort((a, b) => b.relevance - a.relevance)+ .slice(0, PER_SOURCE_LIMIT[kind]);+}++async function retrieveBrainNotes(question, queryTokens) {+ if (!queryTokens.length) return [];+ // Memory already covers free-form thoughts via the brain→memory bridge;+ // this layer catches the structured records (ideas/projects/inbox) the+ // user is more likely to call by name.+ const [ideasArr, projectsArr, inbox] = await Promise.all([+ getIdeas(),+ getProjects(),+ getInboxLog({ limit: 200 }),+ ]);++ const candidates = [];+ for (const idea of ideasArr || []) {+ const text = `${idea.title || ''} ${idea.description || ''}`.trim();+ candidates.push({ kind: 'brain-note', subkind: 'idea', recordId: idea.id, title: idea.title || '(idea)', snippet: text, href: `/brain/memory?type=ideas&id=${encodeURIComponent(idea.id)}`, updatedAt: idea.updatedAt || idea.createdAt });+ }+ for (const proj of projectsArr || []) {+ const text = `${proj.title || ''} ${proj.description || ''}`.trim();+ candidates.push({ kind: 'brain-note', subkind: 'project', recordId: proj.id, title: proj.title || '(project)', snippet: text, href: `/brain/memory?type=projects&id=${encodeURIComponent(proj.id)}`, updatedAt: proj.updatedAt || proj.createdAt });+ }+ for (const entry of inbox || []) {+ const text = entry.text || entry.summary || '';+ if (!text) continue;+ candidates.push({ kind: 'brain-note', subkind: 'inbox', recordId: entry.id, title: text.slice(0, 80), snippet: text, href: '/brain/inbox', updatedAt: entry.timestamp || entry.createdAt });+ }++ for (const c of candidates) {+ c.relevance = lexicalScore(`${c.title} ${c.snippet}`, queryTokens);+ c.id = `brain-note:${c.subkind}:${c.recordId}`;+ }+ return rankAndCap(candidates, 'brain-note');+}++async function retrieveAutobiography(queryTokens) {+ if (!queryTokens.length) return [];+ const stories = await getStories();+ // Stories accumulate over time; scoring everything is wasteful when only+ // the per-source cap survives. Trim to the most recent slice first —+ // getStories already sorts newest-first.+ const recent = (stories || []).slice(0, AUTOBIO_SCAN_LIMIT);+ const ranked = recent.map((s) => ({+ kind: 'autobiography',+ id: `autobiography:${s.id}`,+ title: s.themeId ? `${s.themeId} — ${(s.promptText || '').slice(0, 60)}` : (s.promptText || 'Autobiography'),+ snippet: s.content || '',+ href: '/digital-twin/autobiography',+ relevance: lexicalScore(`${s.promptText || ''} ${s.content || ''}`, queryTokens),+ meta: { themeId: s.themeId, createdAt: s.createdAt },+ }));+ return rankAndCap(ranked, 'autobiography');+}++async function retrieveGoals(queryTokens) {+ const goalsData = await getGoals();+ const goals = goalsData?.goals || [];+ // Active goals get a small floor so they surface even on weak lexical+ // matches — your in-flight goals are nearly always relevant context.+ const ranked = goals.map((g) => ({+ kind: 'goal',+ id: `goal:${g.id}`,+ title: g.title || '(goal)',+ snippet: [g.description, g.horizon ? `horizon: ${g.horizon}` : '', g.status ? `status: ${g.status}` : ''].filter(Boolean).join(' · '),+ href: `/digital-twin/goals?id=${encodeURIComponent(g.id)}`,+ relevance: lexicalScore(`${g.title || ''} ${g.description || ''} ${(g.tags || []).join(' ')}`, queryTokens) + (g.status === 'active' ? 0.05 : 0),+ meta: { status: g.status, horizon: g.horizon, category: g.category },+ }));+ return rankAndCap(ranked, 'goal');+}++async function retrieveCalendar(question, queryTokens, timeWindow) {+ if (!queryTokens.length) return [];+ const now = Date.now();+ const days = Number(timeWindow?.days) || CALENDAR_DEFAULT_DAYS;+ const startDate = timeWindow?.startDate || new Date(now - days * MS_PER_DAY).toISOString();+ const endDate = timeWindow?.endDate || new Date(now + days * MS_PER_DAY).toISOString();+ const result = await getCalendarEvents({ startDate, endDate, limit: CALENDAR_FETCH_LIMIT });+ const events = result?.events || [];+ const ranked = events.map((e) => {+ const text = `${e.title || ''} ${e.description || ''} ${e.location || ''}`.trim();+ return {+ kind: 'calendar',+ id: `calendar:${e.id || `${e.startTime}-${e.title}`}`,+ title: e.title || '(event)',+ snippet: [e.startTime ? new Date(e.startTime).toLocaleString() : '', e.location || '', (e.description || '').slice(0, 200)].filter(Boolean).join(' · '),+ href: `/calendar/agenda?date=${encodeURIComponent(e.startTime || '')}`,+ relevance: lexicalScore(text, queryTokens),+ meta: { startTime: e.startTime, endTime: e.endTime, accountId: e.accountId },+ };+ });+ return rankAndCap(ranked, 'calendar');+}++// =============================================================================+// AGGREGATION+// =============================================================================++export async function gatherSources(question, { timeWindow, maxSources = 12 } = {}) {+ const queryTokens = tokenize(question);++ // Fan out — each retriever is independently failable, so allSettled keeps+ // a single-source outage from killing the answer.+ const [memSettled, brainSettled, autoSettled, goalSettled, calSettled] = await Promise.allSettled([+ retrieveMemories(question),+ retrieveBrainNotes(question, queryTokens),+ retrieveAutobiography(queryTokens),+ retrieveGoals(queryTokens),+ retrieveCalendar(question, queryTokens, timeWindow),+ ]);++ const all = [+ ...(memSettled.status === 'fulfilled' ? memSettled.value : []),+ ...(brainSettled.status === 'fulfilled' ? brainSettled.value : []),+ ...(autoSettled.status === 'fulfilled' ? autoSettled.value : []),+ ...(goalSettled.status === 'fulfilled' ? goalSettled.value : []),+ ...(calSettled.status === 'fulfilled' ? calSettled.value : []),+ ];++ // Dedupe by id (parallel retrievers can occasionally surface the same+ // record via the brain→memory bridge).+ const seen = new Set();+ const deduped = [];+ for (const s of all) {+ if (seen.has(s.id)) continue;+ seen.add(s.id);+ deduped.push(s);+ }++ // Source-weighted final ranking — memory and goals are the highest-signal+ // PortOS surfaces; calendar wins time-bounded questions; autobiography is+ // long-form so it ranks last unless lexical match is very strong.+ const KIND_WEIGHT = { memory: 1.0, goal: 0.95, 'brain-note': 0.85, calendar: 0.85, autobiography: 0.7 };+ deduped.sort((a, b) => (b.relevance * (KIND_WEIGHT[b.kind] || 0.5)) - (a.relevance * (KIND_WEIGHT[a.kind] || 0.5)));++ return deduped.slice(0, Math.max(1, Math.min(50, maxSources)));+}++// =============================================================================+// PROMPT ASSEMBLY+// =============================================================================++const MODE_DIRECTIVES = {+ ask: `Answer the question as the user would answer it themselves, drawing on their notes, memories, and goals below. If the sources don't contain the answer, say so plainly — don't fabricate.`,+ advise: `You are advising the user. Use the sources to ground the advice in their own life: their goals, their constraints, what they've already decided. Push back where their stated goals contradict the question.`,+ draft: `Draft text in the user's voice for the recipient/platform they specified. Keep it tight and authentic to the tone in the sources. Return only the drafted text — no preamble, no commentary.`,+};++export async function buildPersonaPreamble() {+ const character = await getCharacter().catch(() => null);+ // The character sheet is the closest thing to a persona surface today.+ // Autobiography stories carry the voice; we sample the most recent one+ // separately in the source pipeline. Keep this preamble small.+ if (!character?.name && !character?.class) return PERSONA_FALLBACK;+ const name = character?.name || 'the user';+ return `You are ${name}'s digital twin. Speak in the first person, in their voice. Be direct, specific, and grounded in the sources below. Where the user's perspective is unclear, say so explicitly rather than guessing.`;+}++function formatSourcesForPrompt(sources) {+ if (!sources?.length) return 'No retrieved sources for this question.';+ const lines = ['## Retrieved Sources', ''];+ sources.forEach((s, i) => {+ const tag = `[${i + 1}]`;+ const snippet = (s.snippet || '').replace(/\s+/g, ' ').slice(0, SNIPPET_MAX_CHARS);+ lines.push(`${tag} ${s.kind} — ${s.title}`);+ if (snippet) lines.push(` ${snippet}`);+ });+ return lines.join('\n');+}++function formatTranscriptForPrompt(history = []) {+ if (!history.length) return '';+ const lines = ['## Conversation so far'];+ for (const turn of history) {+ const who = turn.role === 'assistant' ? 'You (twin)' : 'User';+ lines.push(`${who}: ${(turn.content || '').slice(0, HISTORY_TURN_MAX_CHARS)}`);+ }+ return lines.join('\n');+}++export async function buildPrompt({ question, mode = 'ask', sources = [], history = [] }) {+ const persona = await buildPersonaPreamble();+ const directive = MODE_DIRECTIVES[mode] || MODE_DIRECTIVES.ask;+ const transcript = formatTranscriptForPrompt(history);+ return [+ persona,+ '',+ directive,+ '',+ 'Cite sources inline using their bracket numbers, e.g. [1] [3]. Only cite sources you actually relied on.',+ '',+ formatSourcesForPrompt(sources),+ '',+ transcript,+ '',+ `## Question`,+ question,+ ].join('\n');+}++// =============================================================================+// PROVIDER STREAMING+// =============================================================================++async function pickProvider(providerId) {+ if (providerId) {+ const p = await getProviderById(providerId).catch(() => null);+ if (p?.enabled) return p;+ }+ const active = await getActiveProvider().catch(() => null);+ if (active?.enabled) return active;+ throw new Error('No AI provider available');+}++/**+ * Stream a completion from an API-style provider. Yields text chunks.+ * Falls back to a single-shot call for non-streaming providers (CLI).+ */+async function* streamCompletion(provider, model, prompt) {+ if (provider.type === 'api') {+ const headers = { 'Content-Type': 'application/json' };+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;+ const response = await fetch(`${provider.endpoint}/chat/completions`, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ model,+ messages: [{ role: 'user', content: prompt }],+ temperature: 0.4,+ stream: true,+ }),+ signal: AbortSignal.timeout(provider.timeout || 300000),+ });+ if (!response.ok || !response.body) {+ const text = await response.text().catch(() => '');+ throw new Error(`AI API error: ${response.status} - ${text.slice(0, 500)}`);+ }+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let idx;+ while ((idx = buffer.indexOf('\n\n')) !== -1) {+ const frame = buffer.slice(0, idx).trim();+ buffer = buffer.slice(idx + 2);+ if (!frame.startsWith('data:')) continue;+ const payload = frame.slice(5).trim();+ if (payload === '[DONE]') return;+ const parsed = JSON.parse(payload);+ const delta = parsed?.choices?.[0]?.delta?.content;+ if (delta) yield delta;+ }+ }+ return;+ }++ // CLI providers can't stream chunked text out of a child process without+ // a lot more wiring; fall back to a single-shot call via the shared+ // brain-style invocation pattern.+ const { spawn } = await import('child_process');+ const args = [...(provider.args || [])];+ if (provider.headlessArgs?.length) args.push(...provider.headlessArgs);+ if (provider.id === 'gemini-cli') {+ if (!args.includes('--output-format') && !args.includes('-o')) args.push('--output-format', 'text');+ if (model) args.push('--model', model);+ args.push('--prompt', prompt);+ } else {+ if (model) args.push('--model', model);+ args.push(prompt);+ }+ const out = await new Promise((resolve, reject) => {+ let buf = '';+ const child = spawn(provider.command, args, {+ env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),+ stdio: ['ignore', 'pipe', 'pipe'],+ shell: false,+ windowsHide: true,+ });+ child.stdout.on('data', (d) => { buf += d.toString(); });+ child.stderr.on('data', (d) => { buf += d.toString(); });+ const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('CLI timed out')); }, provider.timeout || 300000);+ child.on('close', (code) => {+ clearTimeout(timer);+ if (code === 0) resolve(buf);+ else reject(new Error(`CLI exited ${code}: ${buf.slice(0, 500)}`));+ });+ child.on('error', (err) => { clearTimeout(timer); reject(err); });+ });+ yield out;+}++// =============================================================================+// PUBLIC ENTRY+// =============================================================================++/**+ * Run an Ask turn end-to-end. Returns an async iterable of stream events.+ *+ * @param {Object} opts+ * @param {string} opts.question - The user's question.+ * @param {'ask'|'advise'|'draft'} [opts.mode]+ * @param {Array} [opts.history] - Prior turns for multi-turn context.+ * @param {Object} [opts.timeWindow] - { days?, startDate?, endDate? } for calendar.+ * @param {number} [opts.maxSources]+ * @param {string} [opts.providerId]+ * @param {string} [opts.model]+ */+export async function* runAsk({+ question,+ mode = 'ask',+ history = [],+ timeWindow,+ maxSources = 12,+ providerId,+ model,+}) {+ if (!question || typeof question !== 'string' || !question.trim()) {+ yield { type: 'error', error: 'question is required' };+ return;+ }+ if (!VALID_MODES.has(mode)) {+ yield { type: 'error', error: `invalid mode: ${mode}` };+ return;+ }++ let sources;+ try {+ sources = await gatherSources(question, { timeWindow, maxSources });+ } catch (err) {+ yield { type: 'error', error: `Source retrieval failed: ${err.message}` };+ return;+ }++ yield { type: 'sources', sources };++ let provider;+ try {+ provider = await pickProvider(providerId);+ } catch (err) {+ yield { type: 'error', error: err.message };+ return;+ }+ const effectiveModel = model || provider.defaultModel;+ const prompt = await buildPrompt({ question, mode, sources, history });++ const startedAt = Date.now();+ console.log(`🪞 Ask start: ${provider.id}/${effectiveModel} mode=${mode} sources=${sources.length}`);++ // Stream errors are caught here (rather than letting them bubble) so the+ // route can flush a terminal SSE 'error' frame to the client — once the+ // stream has started, we can't change to a 5xx response any longer.+ let answer = '';+ try {+ for await (const chunk of streamCompletion(provider, effectiveModel, prompt)) {+ if (!chunk) continue;+ answer += chunk;+ yield { type: 'delta', text: chunk };+ }+ } catch (err) {+ yield { type: 'error', error: `Provider stream failed: ${err.message}` };+ return;+ }++ console.log(`✅ Ask complete: ${provider.id}/${effectiveModel} ${Date.now() - startedAt}ms ${answer.length} chars`);++ yield {+ type: 'done',+ answer,+ sources,+ providerId: provider.id,+ model: effectiveModel,+ };+}diff --git a/server/services/askService.test.js b/server/services/askService.test.jsnew file mode 100644index 0000000000..e8f1dd0b44--- /dev/null+++ b/server/services/askService.test.js@@ -0,0 +1,241 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// All upstream services are mocked so the unit under test is the+// orchestration logic itself: parallel retrieval, ranking, prompt assembly,+// and stream-event shape.++vi.mock('./providers.js', () => ({+ getActiveProvider: vi.fn(),+ getProviderById: vi.fn(),+}));++vi.mock('./memoryBackend.js', () => ({+ hybridSearchMemories: vi.fn(),+ getMemory: vi.fn(),+}));++vi.mock('./memoryEmbeddings.js', () => ({+ generateQueryEmbedding: vi.fn(),+}));++vi.mock('./brainStorage.js', () => ({+ getInboxLog: vi.fn(),+ getProjects: vi.fn(),+ getIdeas: vi.fn(),+}));++vi.mock('./autobiography.js', () => ({+ getStories: vi.fn(),+}));++vi.mock('./identity.js', () => ({+ getGoals: vi.fn(),+}));++vi.mock('./character.js', () => ({+ getCharacter: vi.fn(),+}));++vi.mock('./calendarSync.js', () => ({+ getEvents: vi.fn(),+}));++const memoryBackend = await import('./memoryBackend.js');+const memoryEmbeddings = await import('./memoryEmbeddings.js');+const brainStorage = await import('./brainStorage.js');+const autobiography = await import('./autobiography.js');+const identity = await import('./identity.js');+const character = await import('./character.js');+const calendarSync = await import('./calendarSync.js');+const providers = await import('./providers.js');++const askService = await import('./askService.js');++beforeEach(() => {+ vi.clearAllMocks();+ // Sensible defaults — each test overrides what it cares about.+ memoryEmbeddings.generateQueryEmbedding.mockResolvedValue([0.1, 0.2, 0.3]);+ memoryBackend.hybridSearchMemories.mockResolvedValue({ memories: [] });+ memoryBackend.getMemory.mockResolvedValue(null);+ brainStorage.getInboxLog.mockResolvedValue([]);+ brainStorage.getProjects.mockResolvedValue([]);+ brainStorage.getIdeas.mockResolvedValue([]);+ autobiography.getStories.mockResolvedValue([]);+ identity.getGoals.mockResolvedValue({ goals: [] });+ character.getCharacter.mockResolvedValue({ name: 'Adam', class: 'Developer' });+ calendarSync.getEvents.mockResolvedValue({ events: [] });+});++describe('gatherSources', () => {+ it('returns memories with stable ids and tagged kind', async () => {+ memoryBackend.hybridSearchMemories.mockResolvedValue({+ memories: [{ id: 'mem-1', rrfScore: 0.9 }, { id: 'mem-2', rrfScore: 0.7 }],+ });+ memoryBackend.getMemory.mockImplementation((id) => Promise.resolve({+ id,+ content: `body of ${id}`,+ summary: `summary ${id}`,+ type: 'fact',+ }));++ const sources = await askService.gatherSources('what did i decide about X');+ expect(sources).toHaveLength(2);+ expect(sources[0].kind).toBe('memory');+ expect(sources[0].id).toBe('memory:mem-1');+ });++ it('keeps producing answers when one retriever throws', async () => {+ // Memory throws — brain notes still surface.+ memoryBackend.hybridSearchMemories.mockRejectedValue(new Error('vector backend down'));+ brainStorage.getIdeas.mockResolvedValue([+ { id: 'idea-1', title: 'Move workout to mornings', description: 'shift to AM for better adherence' },+ ]);++ const sources = await askService.gatherSources('move workout to mornings');+ expect(sources.length).toBeGreaterThan(0);+ expect(sources[0].kind).toBe('brain-note');+ });++ it('dedupes by source id when a retriever returns the same hit twice', async () => {+ // Hybrid memory search can occasionally return the same record twice+ // (BM25 + vector hits both surface it before RRF) — the merged source+ // list should only carry one copy regardless.+ memoryBackend.hybridSearchMemories.mockResolvedValue({+ memories: [+ { id: 'mem-dup', rrfScore: 0.9 },+ { id: 'mem-dup', rrfScore: 0.8 },+ ],+ });+ memoryBackend.getMemory.mockResolvedValue({+ id: 'mem-dup',+ content: 'workout decision',+ summary: 'workout',+ });++ const sources = await askService.gatherSources('workout');+ const memorySources = sources.filter((s) => s.id === 'memory:mem-dup');+ expect(memorySources).toHaveLength(1);+ });++ it('caps the result list to maxSources', async () => {+ // Generate 20 idea-style brain notes, all matching the question.+ brainStorage.getIdeas.mockResolvedValue(+ Array.from({ length: 20 }, (_, i) => ({+ id: `idea-${i}`,+ title: `workout idea ${i}`,+ description: 'workout details',+ })),+ );+ const sources = await askService.gatherSources('workout details', { maxSources: 3 });+ expect(sources).toHaveLength(3);+ });++ it('ranks active goals when lexical match is weak', async () => {+ identity.getGoals.mockResolvedValue({+ goals: [+ { id: 'g-1', title: 'Run a marathon', description: 'finish a 26.2', status: 'active', horizon: 'year' },+ { id: 'g-2', title: 'Watch movies', description: 'leisure', status: 'archived', horizon: 'month' },+ ],+ });+ const sources = await askService.gatherSources('marathon training');+ expect(sources.find((s) => s.id === 'goal:g-1')).toBeDefined();+ });+});++describe('buildPrompt', () => {+ it('composes persona + directive + sources + question', async () => {+ const sources = [+ { kind: 'memory', id: 'memory:1', title: 'Past decision', snippet: 'I decided to ship slice (a) first.' },+ { kind: 'goal', id: 'goal:g-1', title: 'Run a marathon', snippet: 'horizon: year · status: active' },+ ];+ const prompt = await askService.buildPrompt({ question: 'What should I do today?', mode: 'advise', sources });+ expect(prompt).toContain('digital twin');+ expect(prompt).toContain('What should I do today?');+ expect(prompt).toContain('[1] memory — Past decision');+ expect(prompt).toContain('[2] goal — Run a marathon');+ // 'advise' directive is distinct from 'ask' so a typo in mode wiring would catch.+ expect(prompt).toContain('advising');+ });++ it('inlines history for multi-turn context', async () => {+ const prompt = await askService.buildPrompt({+ question: 'Follow-up?',+ mode: 'ask',+ sources: [],+ history: [+ { role: 'user', content: 'previous question' },+ { role: 'assistant', content: 'previous answer' },+ ],+ });+ expect(prompt).toContain('previous question');+ expect(prompt).toContain('previous answer');+ });++ it('falls back to a generic persona when character is absent', async () => {+ character.getCharacter.mockResolvedValue(null);+ const preamble = await askService.buildPersonaPreamble();+ expect(preamble).toMatch(/digital twin/i);+ });+});++describe('runAsk', () => {+ // Minimal API-shaped provider; fetch is mocked to return the SSE response.+ function fakeStreamProvider() {+ return {+ id: 'fake',+ type: 'api',+ enabled: true,+ apiKey: 'k',+ endpoint: 'https://example.test/v1',+ defaultModel: 'fake-model',+ timeout: 5000,+ };+ }++ function buildSSEResponse(deltas) {+ const encoder = new TextEncoder();+ const frames = deltas.map((d) =>+ `data: ${JSON.stringify({ choices: [{ delta: { content: d } }] })}\n\n`+ ).concat('data: [DONE]\n\n');+ return new Response(new ReadableStream({+ start(ctrl) {+ for (const f of frames) ctrl.enqueue(encoder.encode(f));+ ctrl.close();+ },+ }), { status: 200, headers: { 'Content-Type': 'text/event-stream' } });+ }++ it('emits sources, deltas, then done', async () => {+ providers.getActiveProvider.mockResolvedValue(fakeStreamProvider());+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(buildSSEResponse(['Hello, ', 'world.']));++ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi' })) {+ events.push(evt);+ }+ fetchSpy.mockRestore();++ const types = events.map((e) => e.type);+ expect(types[0]).toBe('sources');+ expect(types).toContain('delta');+ expect(types[types.length - 1]).toBe('done');+ const fullText = events.filter((e) => e.type === 'delta').map((e) => e.text).join('');+ expect(fullText).toBe('Hello, world.');+ });++ it('emits an error event for an empty question', async () => {+ const events = [];+ for await (const evt of askService.runAsk({ question: ' ' })) events.push(evt);+ expect(events).toHaveLength(1);+ expect(events[0].type).toBe('error');+ });++ it('emits an error when no provider is available', async () => {+ providers.getActiveProvider.mockResolvedValue(null);+ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi' })) events.push(evt);+ // Expect one sources event then a terminating error.+ expect(events.find((e) => e.type === 'error')).toBeDefined();+ expect(events.find((e) => e.type === 'done')).toBeUndefined();+ });+});