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): one-click promote assistant turns to brain/task/goal
Adam Eivye6d54c3f2216
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1a5f6a5fc4..236a51e1a9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **Ask Yourself: one-click promote each assistant turn into a Brain note, CoS task, or Goal progress entry.** Closes the second half of "Ask Yourself — slice (b)" — the Ask page's twin-flavored answers were trapped in the conversation. Each assistant turn now shows three buttons below its source chips: **Save to Brain** (calls `brainService.captureThought` with the answer text), **Create task** (creates a CoS task with the answer as the description, capped at 280 chars and tagged with a "Promoted from Ask Yourself <id>" context note), and **Attach to goal…** (inline goal picker → `identityService.addProgressEntry` writes the answer as a `progressLog` note dated today). After a successful promotion the button mutates to a green "Saved to Brain"/"Task created"/"Attached: <goal title>" chip that deep-links to the saved record (`/brain/inbox`, `/cos`, `/digital-twin/goals?id=…`). Server-side, every promotion also pins the conversation (`promoted = true`) so anything saved elsewhere survives the 30-day expiry sweep — without that, a saved brain note could outlive the conversation it cites. New endpoint `POST /api/ask/:id/turns/:turnId/promote` validates a discriminated zod union — `{ target: 'brain' }`, `{ target: 'task', priority? }`, `{ target: 'goal', goalId }` — fails fast with 400/404/409 on missing turns, user turns, empty content, missing goals, or duplicate tasks. 13 new route tests; the full server suite remains green at 2746/2746. The remaining slice-(b) item — the `ui_ask` voice tool + palette whitelist — is still pending. Files: `server/routes/ask.js`, `server/routes/ask.test.js`, `client/src/services/apiAsk.js`, `client/src/pages/Ask.jsx`, `PLAN.md`.- **Voice agent: `feeds_mark_read` tool.** Pairs with the existing `feeds_digest` so the user can say "mark that one read" / "mark them all read" / "mark all of Hacker News as read" without leaving the conversation. Two ways to call: `query` fuzzy-matches a single unread item by title (exact → substring → all-tokens fallback) using titles the LLM just spoke from `feeds_digest`; `all: true` marks every unread item read, optionally scoped to one feed via `feedQuery` (fuzzy-matched against feed title). The `feeds` intent regex was loosened to also match phrasings like "mark that one read" / "mark them all as read" / "headlines" so the tool is offered to the LLM on the right turns; the bare word "read" alone is intentionally NOT a feeds trigger (it collides with "read my log"). 11 new tests in `server/services/voice/tools.test.js` cover ok/error paths, feed scoping, fuzzy matching, and the new regex behavior. Files: `server/services/voice/tools.js`, `server/services/voice/tools.test.js`.- **Reimagined theme system — four named themes with full design tokens.** Replaced the five ad-hoc color-only themes (Midnight, Phosphor, Ember, Arctic, Synthwave) with a structured manifest of four themes that each carry a complete design system, not just a color palette: **Classic Midnight** (the existing baseline, kept stable), **Lumen Glass** (translucent glass panes with backdrop-blur), **Black ICE Terminal** (dense cyberpunk terminal with scanlines and monospace UI), and **Blueprint Ops** (drafting-grid systems-map aesthetic). Each theme manifest declares colors (`--port-bg`, `--port-card`, etc), per-channel "on-X" foreground colors for accessible contrast on accent/success/warning/error pills, and a tokens block covering radii, font stacks (UI/display/mono), motion durations, shadow variants, backdrop-filter, body gradient/texture, control surfaces, hover/active states, terminal styling, and chart colors. A new runtime layer in `client/src/index.css` keys off `html[data-port-theme="<id>"]` so theme switches restyle the entire UI in one paint — including transitions on inputs/buttons, toaster border/shadow tokens (`client/src/main.jsx`), per-theme card backgrounds, sidebar treatments, and theme-specific flourishes (Black ICE scanline overlay, Blueprint Ops grid-pattern card backgrounds + heading rules, Lumen Glass focus glows). The theme picker has two surfaces: a redesigned dropdown in the bottom-bar `ThemeSwitcher` (portal-rendered, viewport-clamped, rAF-throttled scroll/resize repositioning, with family icons + accent swatch) and a new card-grid `ThemePickerPanel` in Settings → General that shows each theme's concept, density, four-color swatch row, and an active-state check. Legacy theme ids stored in `localStorage` or server settings are normalized via `LEGACY_THEME_ALIASES` (`midnight` → `classic-midnight`, `phosphor`/`synthwave` → `black-ice-terminal`, `arctic` → `lumen-glass`, `ember` → `blueprint-ops`) so existing users don't lose their preference; the migrated id is written back so future loads are direct. A new `npm run theme:check` script (`scripts/check-themes.js`, runs at any time) enforces the theme contract: every theme must declare every required color/token var with valid RGB channels, must point at a doc under `docs/themes/<id>.md` containing the four required sections (`## Intent`, `## Integration Rules`, `## Component Notes`, `## Validation`), every legacy alias must resolve to a real theme, and `index.css` must include a theme-specific selector for each non-default theme. Files: `client/src/themes/portosThemes.js` (new), `client/src/themes/familyIcons.js` (new), `client/src/components/ThemePickerPanel.jsx` (new), `client/src/components/ThemeSwitcher.jsx`, `client/src/components/ThemeContext.jsx`, `client/src/components/settings/GeneralTab.jsx`, `client/src/hooks/useTheme.js`, `client/src/index.css`, `client/src/main.jsx`, `docs/themes/*.md` (new — one per theme + README), `scripts/check-themes.js` (new), `package.json` (new `theme:check` script).- **3D Chief of Staff avatars are draggable to re-orient.** All five 3D avatar styles (Cyber, Sigil, Esoteric, Nexus, Muse) now respond to typical mouse/touch drag controls — click-and-drag rotates the avatar around its center, with damping for a smooth feel. Pan and zoom are intentionally disabled so the framing stays consistent on the small avatar tile. Wrapper divs use `cursor-grab`/`active:cursor-grabbing` and `touch-none` so the affordance is visible and touch drags don't fight page scroll. Implemented via drei's `OrbitControls` inside each avatar's `<Scene>`. Files: `client/src/components/cos/CyberCoSAvatar.jsx`, `client/src/components/cos/SigilCoSAvatar.jsx`, `client/src/components/cos/EsotericCoSAvatar.jsx`, `client/src/components/cos/NexusCoSAvatar.jsx`, `client/src/components/cos/MuseCoSAvatar.jsx`.diff --git a/PLAN.md b/PLAN.mdindex 0a4bf978b4..7ab3da14d3 100644--- a/PLAN.md+++ b/PLAN.md@@ -128,11 +128,10 @@ 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.+- [ ] **Ask Yourself — slice (b)** — voice integration on top of the shipped text chat + promotions:+ - **Promotions ✅ shipped 2026-04-28.** Per-turn buttons on each assistant turn fire `POST /api/ask/:id/turns/:turnId/promote` (discriminated body `{ target: 'brain' | 'task' | 'goal', goalId? }`). Brain target calls `brainService.captureThought`, task target creates a CoS task with description capped at 280 chars and a "promoted from Ask Yourself <id>" context note, goal target appends a `progressLog` entry via `identityService.addProgressEntry`. Server pins the conversation (`promoted = true`) on every successful promotion so anything saved elsewhere survives the 30-day expiry sweep. UI shows inline "Saved to Brain"/"Task created"/"Attached: <goal title>" confirmation chips that deep-link to the saved record. 13 new route tests — full server suite stays green at 2746/2746.+ - `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). **Pending.**+ - 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. **Pending.**- [ ] **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, and `feeds_mark_read` (pairs with `feeds_digest` — fuzzy-matches an unread item by title or marks all read, optionally scoped to a feed). Remaining candidates:- `calendar_today` / `calendar_next` — surface today's Google Calendar events through the existing Google MCP integrationdiff --git a/client/src/pages/Ask.jsx b/client/src/pages/Ask.jsxindex 8cb8e1b320..ef97aa0bc5 100644--- a/client/src/pages/Ask.jsx+++ b/client/src/pages/Ask.jsx@@ -1,6 +1,6 @@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 { Send, Loader2, MessageCircle, Trash2, Pin, Brain, Calendar, Target, BookOpen, FileText, ExternalLink, ListTodo, CheckCircle2 } from 'lucide-react';import * as api from '../services/api';import toast from '../components/ui/Toast';@@ -107,11 +107,154 @@ function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading, st);}+// Promotion bar for assistant turns: 1-click save to Brain inbox, create a+// CoS task, or attach a progress note to a Goal. Local state tracks which+// targets have already been promoted so the UI doesn't let the user fire the+// same promotion twice (and so the success label persists across re-renders).+function PromoteBar({ conversationId, turn, goals, onPromoted }) {+ const [pending, setPending] = useState(null);+ const [saved, setSaved] = useState({ brain: null, task: null, goal: null });+ const [pickingGoal, setPickingGoal] = useState(false);++ const promote = useCallback(async (payload) => {+ setPending(payload.target);+ const data = await api.promoteAskTurn(conversationId, turn.id, payload).catch((err) => {+ toast.error(err?.message || 'Promote failed');+ return null;+ });+ setPending(null);+ if (!data?.ok) return;+ setSaved((prev) => ({ ...prev, [payload.target]: data.ref }));+ setPickingGoal(false);+ onPromoted?.(data);+ if (payload.target === 'brain') toast.success('Saved to Brain inbox');+ else if (payload.target === 'task') toast.success('Created CoS task');+ else if (payload.target === 'goal') toast.success('Attached to goal');+ }, [conversationId, turn.id, onPromoted]);++ // Pin saved state once goals are loaded so a goal-target chip can label+ // "Attached to <goal title>" instead of just "Attached".+ const savedGoal = saved.goal && goals?.find((g) => g.id === saved.goal.id);++ return (+ <div className="mt-3 pt-3 border-t border-port-border flex flex-wrap items-center gap-1.5">+ <PromoteButton+ label="Save to Brain"+ savedLabel="Saved to Brain"+ icon={Brain}+ savedRef={saved.brain}+ pending={pending === 'brain'}+ disabled={!!pending}+ onClick={() => promote({ target: 'brain' })}+ href={saved.brain ? '/brain/inbox' : null}+ />+ <PromoteButton+ label="Create task"+ savedLabel="Task created"+ icon={ListTodo}+ savedRef={saved.task}+ pending={pending === 'task'}+ disabled={!!pending}+ onClick={() => promote({ target: 'task' })}+ href={saved.task ? '/cos' : null}+ />+ {saved.goal ? (+ <PromoteButton+ label="Attach to goal"+ savedLabel={savedGoal ? `Attached: ${savedGoal.title}` : 'Attached to goal'}+ icon={Target}+ savedRef={saved.goal}+ pending={false}+ disabled+ onClick={() => {}}+ href={`/digital-twin/goals?id=${encodeURIComponent(saved.goal.id)}`}+ />+ ) : (+ <GoalPicker+ goals={goals}+ pending={pending === 'goal'}+ disabled={!!pending}+ open={pickingGoal}+ onToggle={() => setPickingGoal((v) => !v)}+ onPick={(goalId) => promote({ target: 'goal', goalId })}+ />+ )}+ </div>+ );+}++function PromoteButton({ label, savedLabel, icon: Icon, savedRef, pending, disabled, onClick, href }) {+ const navigate = useNavigate();+ const isSaved = !!savedRef;+ const text = isSaved ? savedLabel : label;+ const cls = `inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium transition-colors border ${+ isSaved+ ? 'bg-port-success/15 border-port-success/40 text-port-success hover:bg-port-success/20'+ : 'bg-port-bg border-port-border text-gray-300 hover:border-port-accent/60 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed'+ }`;+ const handleClick = () => {+ if (isSaved && href) navigate(href);+ else if (!disabled && !isSaved) onClick();+ };+ return (+ <button type="button" onClick={handleClick} disabled={disabled && !isSaved} className={cls} title={text}>+ {pending ? <Loader2 size={12} className="animate-spin" /> : isSaved ? <CheckCircle2 size={12} /> : <Icon size={12} />}+ <span className="truncate max-w-[200px]">{text}</span>+ </button>+ );+}++function GoalPicker({ goals, pending, disabled, open, onToggle, onPick }) {+ if (!open) {+ return (+ <button+ type="button"+ onClick={onToggle}+ disabled={disabled}+ className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium bg-port-bg border border-port-border text-gray-300 hover:border-port-accent/60 hover:text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {pending ? <Loader2 size={12} className="animate-spin" /> : <Target size={12} />}+ <span>Attach to goal…</span>+ </button>+ );+ }+ return (+ <div className="inline-flex items-center gap-1.5">+ <select+ defaultValue=""+ onChange={(e) => {+ const id = e.target.value;+ if (id) onPick(id);+ }}+ disabled={pending}+ className="px-2 py-1 rounded-md text-xs bg-port-bg border border-port-border text-gray-300 focus:outline-none focus:border-port-accent/60"+ >+ <option value="" disabled>Pick a goal…</option>+ {(goals || []).map((g) => (+ <option key={g.id} value={g.id}>{g.title}</option>+ ))}+ </select>+ <button+ type="button"+ onClick={onToggle}+ className="text-xs text-gray-500 hover:text-white"+ aria-label="Cancel goal picker"+ >+ Cancel+ </button>+ </div>+ );+}+// 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 Turn = memo(function Turn({ turn, sources, conversationId, goals, canPromote, onPromoted }) {const isUser = turn.role === 'user';const turnSources = turn.sources || sources || [];+ // Local-only partial turns (set when a stream errors mid-flight) carry no+ // server-side id, so promotion would 404 — gate the bar on a real persisted+ // id rather than hide it for every assistant turn.+ const showPromote = !isUser && canPromote && turn.content && turn.id && !String(turn.id).startsWith('partial-') && !String(turn.id).startsWith('streaming') && !String(turn.id).startsWith('optimistic-');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'}`}>@@ -121,6 +264,9 @@ const Turn = memo(function Turn({ turn, sources }) {{turnSources.map((s, i) => <SourceChip key={s.id} source={s} index={i} />)}</div>)}+ {showPromote && (+ <PromoteBar conversationId={conversationId} turn={turn} goals={goals} onPromoted={onPromoted} />+ )}</div></div>);@@ -134,6 +280,7 @@ export default function Ask() {const [loadingList, setLoadingList] = useState(true);const [activeConv, setActiveConv] = useState(null);const [loadingConv, setLoadingConv] = useState(false);+ const [goals, setGoals] = useState([]);// 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.@@ -158,6 +305,33 @@ export default function Ask() {useEffect(() => { refreshList(); }, [refreshList]);+ // Goals load lazily and only need a flat list for the picker dropdown — no+ // need to refetch on every conversation change. A failure leaves the+ // picker empty (the user just won't see options) so we don't toast here.+ useEffect(() => {+ let cancelled = false;+ api.getGoals().then((data) => {+ if (cancelled) return;+ const list = Array.isArray(data?.goals) ? data.goals : [];+ // Pre-sort so the dropdown is alphabetical without forcing PromoteBar+ // to sort on every render.+ const sorted = [...list].sort((a, b) => (a.title || '').localeCompare(b.title || ''));+ setGoals(sorted);+ }).catch(() => {});+ return () => { cancelled = true; };+ }, []);++ // Fired by PromoteBar after a successful promotion: the server already pins+ // the conversation, so reflect that locally without a refetch.+ const handlePromoted = useCallback((data) => {+ if (data?.conversation) {+ setActiveConv((prev) => prev ? { ...prev, promoted: !!data.conversation.promoted } : prev);+ setConversations((prev) => prev.map((c) => c.id === data.conversation.id+ ? { ...c, promoted: !!data.conversation.promoted }+ : c));+ }+ }, []);+useEffect(() => {let cancelled = false;if (!conversationId) {@@ -495,7 +669,14 @@ export default function Ask() {</div>)}{turns.map((t) => (- <Turn key={t.id} turn={t} />+ <Turn+ key={t.id}+ turn={t}+ conversationId={activeConv?.id}+ goals={goals}+ canPromote={!streaming && activeConv?.id && activeConv.id !== 'pending'}+ onPromoted={handlePromoted}+ />))}{streaming && streamingTurn && (<Turn turn={{ id: 'streaming', role: 'assistant', content: streamingTurn.content }} sources={streamingTurn.sources} />diff --git a/client/src/services/apiAsk.js b/client/src/services/apiAsk.jsindex 64e918d7dc..49c0e26860 100644--- a/client/src/services/apiAsk.js+++ b/client/src/services/apiAsk.js@@ -8,6 +8,17 @@ export const promoteAskConversation = (id, promoted = true) => request(`/ask/${ebody: JSON.stringify({ promoted }),});+// One-click promotion of an assistant turn to a Brain note, CoS task, or Goal+// progress entry. `payload` shape matches the server's discriminated union:+// { target: 'brain' }+// { target: 'task', priority?: 'LOW'|'MEDIUM'|'HIGH' }+// { target: 'goal', goalId: string }+export const promoteAskTurn = (conversationId, turnId, payload) =>+ request(`/ask/${encodeURIComponent(conversationId)}/turns/${encodeURIComponent(turnId)}/promote`, {+ method: 'POST',+ body: JSON.stringify(payload),+ });+/*** Stream an Ask turn via Server-Sent Events. Consumes the event-stream* response from POST /api/ask manually because EventSource only supports GET.diff --git a/server/routes/ask.js b/server/routes/ask.jsindex c20c344e57..1c1f9428e8 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -9,6 +9,13 @@* DELETE /api/ask/:id → delete a conversation* POST /api/ask/:id/promote → mark conversation exempt from* 30-day auto-expiry+ * POST /api/ask/:id/turns/:turnId/promote+ * → one-click promote an assistant+ * turn into a Brain note / CoS+ * task / Goal progress entry; also+ * pins the conversation so it+ * survives the 30-day expiry once+ * anything from it has been saved.*/import { Router } from 'express';@@ -18,6 +25,9 @@ import { validateRequest } from '../lib/validation.js';import * as convs from '../services/askConversations.js';import { runAsk, VALID_MODES } from '../services/askService.js';import { ID_RE as CONV_ID_RE } from '../services/askConversations.js';+import * as brainService from '../services/brain.js';+import * as cosService from '../services/cos.js';+import * as identityService from '../services/identity.js';const router = Router();@@ -53,6 +63,20 @@ const promoteBodySchema = z.object({promoted: z.boolean().optional().default(true),});+// Promote-turn payloads vary by target — keep the discriminated union narrow+// rather than a permissive bag so the route can fail-fast on a goal target+// missing its goalId before we touch any service.+const promoteTurnBodySchema = z.discriminatedUnion('target', [+ z.object({ target: z.literal('brain') }),+ z.object({ target: z.literal('task'), priority: z.enum(['LOW', 'MEDIUM', 'HIGH']).optional().default('MEDIUM') }),+ z.object({ target: z.literal('goal'), goalId: z.string().min(1).max(200) }),+]);++// Cap promoted task descriptions so a long assistant answer doesn't bloat+// TASKS.md — the full text is still in the conversation. CoS tasks are+// supposed to be one-line directives, not essays.+const TASK_DESCRIPTION_MAX = 280;+router.get('/', asyncHandler(async (_req, res) => {const conversations = await convs.listConversations({ limit: 100 });res.json({ conversations });@@ -80,6 +104,69 @@ router.post('/:id/promote', asyncHandler(async (req, res) => {res.json({ conversation: conv });}));+// One-click promote an assistant turn into a Brain note, CoS task, or Goal+// progress entry. Always sets the conversation `promoted` flag so anything+// the user has saved elsewhere survives the 30-day expiry sweep.+router.post('/:id/turns/:turnId/promote', asyncHandler(async (req, res) => {+ const id = validateRequest(idSchema, String(req.params.id));+ const turnId = String(req.params.turnId || '');+ if (!turnId) throw new ServerError('turnId is required', { status: 400, code: 'VALIDATION_ERROR' });++ const body = validateRequest(promoteTurnBodySchema, req.body ?? {});++ const conv = await convs.getConversation(id);+ if (!conv) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });++ const turn = (conv.turns || []).find((t) => t.id === turnId);+ if (!turn) throw new ServerError('Turn not found', { status: 404, code: 'NOT_FOUND' });+ // Only assistant turns carry promotable content — the user's question is+ // already implicit in the conversation and would just bloat the brain inbox+ // / task list with prompts, not insights.+ if (turn.role !== 'assistant') {+ throw new ServerError('Only assistant turns can be promoted', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const content = (turn.content || '').trim();+ if (!content) {+ throw new ServerError('Turn has no content to promote', { status: 400, code: 'EMPTY_CONTENT' });+ }++ let ref;+ if (body.target === 'brain') {+ const result = await brainService.captureThought(content);+ ref = { type: 'brain', id: result?.inboxLog?.id };+ } else if (body.target === 'task') {+ // Trim the description so the line in TASKS.md stays scannable; tag+ // the source so the user can trace a task back to where it came from.+ const description = content.length <= TASK_DESCRIPTION_MAX+ ? content+ : `${content.slice(0, TASK_DESCRIPTION_MAX - 1)}…`;+ const result = await cosService.addTask({+ description,+ priority: body.priority,+ context: `Promoted from Ask Yourself conversation ${id}`,+ }, 'user');+ if (result?.duplicate) {+ throw new ServerError('A task with this description is already pending', { status: 409, code: 'DUPLICATE_TASK' });+ }+ ref = { type: 'task', id: result?.id };+ } else if (body.target === 'goal') {+ const today = new Date().toISOString().slice(0, 10);+ const entry = await identityService.addProgressEntry(body.goalId, {+ date: today,+ note: content,+ durationMinutes: null,+ });+ if (!entry) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ ref = { type: 'goal', id: body.goalId, entryId: entry.id };+ }++ // Pin the conversation so anything the user has promoted survives the+ // 30-day auto-expiry sweep — without this, a saved brain note could+ // outlive the conversation it cites.+ const conversation = await convs.setPromoted(id, true);+ res.json({ ok: true, target: body.target, ref, conversation });+}));+// 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.diff --git a/server/routes/ask.test.js b/server/routes/ask.test.jsindex 28bf7aecd4..6162ff10a7 100644--- a/server/routes/ask.test.js+++ b/server/routes/ask.test.js@@ -23,8 +23,23 @@ vi.mock('../services/askService.js', () => ({runAsk: vi.fn(),}));+vi.mock('../services/brain.js', () => ({+ captureThought: vi.fn(),+}));++vi.mock('../services/cos.js', () => ({+ addTask: vi.fn(),+}));++vi.mock('../services/identity.js', () => ({+ addProgressEntry: vi.fn(),+}));+const convs = await import('../services/askConversations.js');const svc = await import('../services/askService.js');+const brainService = await import('../services/brain.js');+const cosService = await import('../services/cos.js');+const identityService = await import('../services/identity.js');const { default: routes } = await import('./ask.js');const makeApp = () => {@@ -99,6 +114,179 @@ describe('POST /api/ask/:id/promote', () => {});});+describe('POST /api/ask/:id/turns/:turnId/promote', () => {+ const convId = 'ask_lwg2x4abc_a1b2c3d4';+ const fullConv = {+ id: convId,+ mode: 'ask',+ promoted: false,+ turns: [+ { id: 'u1', role: 'user', content: 'what should I do?' },+ { id: 'a1', role: 'assistant', content: 'Block 30 minutes for deep work after lunch.' },+ ],+ };++ it('promotes an assistant turn to a Brain note and pins the conversation', async () => {+ convs.getConversation.mockResolvedValue(fullConv);+ convs.setPromoted.mockResolvedValue({ ...fullConv, promoted: true });+ brainService.captureThought.mockResolvedValue({ inboxLog: { id: 'inbox-1' } });++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'brain' });++ expect(res.status).toBe(200);+ expect(res.body.ok).toBe(true);+ expect(res.body.target).toBe('brain');+ expect(res.body.ref).toEqual({ type: 'brain', id: 'inbox-1' });+ expect(res.body.conversation.promoted).toBe(true);+ expect(brainService.captureThought).toHaveBeenCalledWith('Block 30 minutes for deep work after lunch.');+ expect(convs.setPromoted).toHaveBeenCalledWith(convId, true);+ });++ it('promotes an assistant turn to a CoS task with priority and source context', async () => {+ convs.getConversation.mockResolvedValue(fullConv);+ convs.setPromoted.mockResolvedValue({ ...fullConv, promoted: true });+ cosService.addTask.mockResolvedValue({ id: 'task-1', status: 'pending' });++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'task', priority: 'HIGH' });++ expect(res.status).toBe(200);+ expect(res.body.target).toBe('task');+ expect(res.body.ref).toEqual({ type: 'task', id: 'task-1' });+ expect(cosService.addTask).toHaveBeenCalledWith(+ expect.objectContaining({+ description: 'Block 30 minutes for deep work after lunch.',+ priority: 'HIGH',+ context: expect.stringContaining(convId),+ }),+ 'user',+ );+ });++ it('truncates long assistant text when promoting to a CoS task', async () => {+ const longContent = 'x'.repeat(600);+ convs.getConversation.mockResolvedValue({+ ...fullConv,+ turns: [{ id: 'a1', role: 'assistant', content: longContent }],+ });+ convs.setPromoted.mockResolvedValue({ ...fullConv, promoted: true });+ cosService.addTask.mockResolvedValue({ id: 'task-2' });++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'task' });++ expect(res.status).toBe(200);+ const description = cosService.addTask.mock.calls[0][0].description;+ expect(description.length).toBeLessThanOrEqual(280);+ expect(description.endsWith('…')).toBe(true);+ });++ it('returns 409 when the promoted task is a duplicate', async () => {+ convs.getConversation.mockResolvedValue(fullConv);+ cosService.addTask.mockResolvedValue({ id: 'task-existing', duplicate: true, status: 'pending' });++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'task' });++ expect(res.status).toBe(409);+ expect(convs.setPromoted).not.toHaveBeenCalled();+ });++ it('promotes an assistant turn to a goal progress entry', async () => {+ convs.getConversation.mockResolvedValue(fullConv);+ convs.setPromoted.mockResolvedValue({ ...fullConv, promoted: true });+ identityService.addProgressEntry.mockResolvedValue({ id: 'prog-1', date: '2026-04-28', note: 'x' });++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'goal', goalId: 'goal-123' });++ expect(res.status).toBe(200);+ expect(res.body.ref).toEqual({ type: 'goal', id: 'goal-123', entryId: 'prog-1' });+ expect(identityService.addProgressEntry).toHaveBeenCalledWith(+ 'goal-123',+ expect.objectContaining({ note: 'Block 30 minutes for deep work after lunch.', durationMinutes: null }),+ );+ });++ it('404s when the goal does not exist', async () => {+ convs.getConversation.mockResolvedValue(fullConv);+ identityService.addProgressEntry.mockResolvedValue(null);++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'goal', goalId: 'missing-goal' });++ expect(res.status).toBe(404);+ expect(convs.setPromoted).not.toHaveBeenCalled();+ });++ it('rejects promoting a user turn', async () => {+ convs.getConversation.mockResolvedValue(fullConv);++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/u1/promote`)+ .send({ target: 'brain' });++ expect(res.status).toBe(400);+ expect(brainService.captureThought).not.toHaveBeenCalled();+ });++ it('404s when the turn id is not in the conversation', async () => {+ convs.getConversation.mockResolvedValue(fullConv);++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/missing/promote`)+ .send({ target: 'brain' });++ expect(res.status).toBe(404);+ });++ it('rejects promoting an empty turn', async () => {+ convs.getConversation.mockResolvedValue({+ ...fullConv,+ turns: [{ id: 'a1', role: 'assistant', content: ' ' }],+ });++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'brain' });++ expect(res.status).toBe(400);+ });++ it('404s when the conversation does not exist', async () => {+ convs.getConversation.mockResolvedValue(null);++ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'brain' });++ expect(res.status).toBe(404);+ });++ it('rejects unknown promotion targets', async () => {+ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'mars' });++ expect(res.status).toBe(400);+ });++ it('rejects goal target without goalId', async () => {+ const res = await request(makeApp())+ .post(`/api/ask/${convId}/turns/a1/promote`)+ .send({ target: 'goal' });++ expect(res.status).toBe(400);+ });+});+describe('POST /api/ask (validation)', () => {it('rejects empty questions', async () => {const res = await request(makeApp())