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
refactor([issue-709]): extract ask turn-promote orchestration into askPromote service
[._.]/ Adam Eivye4a672659f66
diff --git a/server/routes/ask.js b/server/routes/ask.jsindex 1c1f9428e8..07cb115c26 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -25,9 +25,7 @@ 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';+import { promoteTurnById } from '../services/askPromote.js';const router = Router();@@ -72,11 +70,6 @@ const promoteTurnBodySchema = z.discriminatedUnion('target', [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 });@@ -114,57 +107,14 @@ router.post('/:id/turns/:turnId/promote', asyncHandler(async (req, res) => {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 });+ const result = await promoteTurnById({+ conversationId: id,+ turnId,+ target: body.target,+ priority: body.priority,+ goalId: body.goalId,+ });+ res.json({ ok: true, ...result });}));// Stream a new turn over SSE. Body { conversationId?, question, mode?, ... }.diff --git a/server/services/askPromote.js b/server/services/askPromote.jsnew file mode 100644index 0000000000..c8e80059b9--- /dev/null+++ b/server/services/askPromote.js@@ -0,0 +1,132 @@+/**+ * Promote an "Ask Yourself" assistant turn into a Brain note, CoS task, or+ * Goal progress entry.+ *+ * This is the single source of truth for the promote-a-turn orchestration —+ * extracted out of the `POST /api/ask/:id/turns/:turnId/promote` route so the+ * cross-domain Review Queue can promote an Ask answer in place (picking the+ * latest assistant turn for the caller) without duplicating the brain/task/goal+ * dispatch or the pin-on-promote behaviour.+ *+ * It lives in its own module (rather than `askConversations.js`) so the leaf+ * storage layer keeps its no-upstream-imports property — only this orchestrator+ * reaches across to brain/cos/identity.+ */++import { ServerError } from '../lib/errorHandler.js';+import * as convs from './askConversations.js';+import * as brainService from './brain.js';+import * as cosService from './cos.js';+import * as identityService from './identity.js';++// 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;++/**+ * Find the latest assistant turn in a conversation that carries promotable+ * (non-empty) content. Returns null when none exists — distinct from a+ * not-found conversation, so callers can map the two to different statuses.+ */+export function latestAssistantTurn(conversation) {+ const turns = Array.isArray(conversation?.turns) ? conversation.turns : [];+ for (let i = turns.length - 1; i >= 0; i--) {+ const turn = turns[i];+ if (turn?.role === 'assistant' && (turn.content || '').trim()) return turn;+ }+ return null;+}++/**+ * Promote a single assistant turn into the chosen target.+ *+ * @param {object} args+ * @param {string} args.conversationId+ * @param {object} args.turn the resolved assistant turn (content validated by caller)+ * @param {'brain'|'task'|'goal'} args.target+ * @param {'LOW'|'MEDIUM'|'HIGH'} [args.priority] task target only+ * @param {string} [args.goalId] goal target only+ * @returns {Promise<{ target, ref, conversation }>}+ *+ * Always pins the conversation (`promoted: true`) so anything the user saved+ * elsewhere survives the 30-day auto-expiry sweep.+ */+export async function promoteTurnContent({ conversationId, turn, target, priority = 'MEDIUM', goalId }) {+ const content = (turn?.content || '').trim();+ if (!content) {+ throw new ServerError('Turn has no content to promote', { status: 400, code: 'EMPTY_CONTENT' });+ }++ let ref;+ if (target === 'brain') {+ const result = await brainService.captureThought(content);+ ref = { type: 'brain', id: result?.inboxLog?.id };+ } else if (target === 'task') {+ const description = content.length <= TASK_DESCRIPTION_MAX+ ? content+ : `${content.slice(0, TASK_DESCRIPTION_MAX - 1)}…`;+ const result = await cosService.addTask({+ description,+ priority,+ context: `Promoted from Ask Yourself conversation ${conversationId}`,+ }, '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 (target === 'goal') {+ if (!goalId) throw new ServerError('goalId is required for goal target', { status: 400, code: 'VALIDATION_ERROR' });+ const today = new Date().toISOString().slice(0, 10);+ const entry = await identityService.addProgressEntry(goalId, {+ date: today,+ note: content,+ durationMinutes: null,+ });+ if (!entry) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ ref = { type: 'goal', id: goalId, entryId: entry.id };+ } else {+ throw new ServerError(`Unknown promote target "${target}"`, { status: 400, code: 'VALIDATION_ERROR' });+ }++ const conversation = await convs.setPromoted(conversationId, true);+ return { target, ref, conversation };+}++/**+ * Promote a turn referenced by id (used by the per-turn route). Looks up the+ * conversation + turn, asserts it's a non-empty assistant turn, then delegates.+ */+export async function promoteTurnById({ conversationId, turnId, target, priority, goalId }) {+ const conv = await convs.getConversation(conversationId);+ 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' });+ }++ return promoteTurnContent({ conversationId, turn, target, priority, goalId });+}++/**+ * Promote the conversation's *latest* assistant turn — the entry point the+ * Review Queue uses, so the client doesn't need to know turn ids. Restricted+ * to brain/task targets (goal needs a goalId the queue row can't supply; the+ * user drills into /ask for that). 404s when no assistant turn exists.+ */+export async function promoteLatestAssistantTurn({ conversationId, target, priority }) {+ const conv = await convs.getConversation(conversationId);+ if (!conv) throw new ServerError('Conversation not found', { status: 404, code: 'NOT_FOUND' });++ const turn = latestAssistantTurn(conv);+ if (!turn) {+ throw new ServerError('Conversation has no assistant answer to promote', { status: 404, code: 'NO_ASSISTANT_TURN' });+ }++ return promoteTurnContent({ conversationId, turn, target, priority });+}diff --git a/server/services/askPromote.test.js b/server/services/askPromote.test.jsnew file mode 100644index 0000000000..b743467902--- /dev/null+++ b/server/services/askPromote.test.js@@ -0,0 +1,125 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the cross-domain services askPromote orchestrates so the test exercises+// only the latest-turn selection + target dispatch + pin-on-promote logic.+const convs = { getConversation: vi.fn(), setPromoted: vi.fn() };+const brainService = { captureThought: vi.fn() };+const cosService = { addTask: vi.fn() };+const identityService = { addProgressEntry: vi.fn() };++vi.mock('./askConversations.js', () => convs);+vi.mock('./brain.js', () => brainService);+vi.mock('./cos.js', () => cosService);+vi.mock('./identity.js', () => identityService);++const { latestAssistantTurn, promoteLatestAssistantTurn, promoteTurnById } = await import('./askPromote.js');++describe('askPromote.latestAssistantTurn', () => {+ it('returns the last assistant turn with non-empty content', () => {+ const conv = { turns: [+ { id: 't1', role: 'assistant', content: 'first answer' },+ { id: 't2', role: 'user', content: 'follow-up' },+ { id: 't3', role: 'assistant', content: 'second answer' },+ ] };+ expect(latestAssistantTurn(conv).id).toBe('t3');+ });++ it('skips a trailing empty/whitespace assistant turn', () => {+ const conv = { turns: [+ { id: 't1', role: 'assistant', content: 'real answer' },+ { id: 't2', role: 'assistant', content: ' ' },+ ] };+ expect(latestAssistantTurn(conv).id).toBe('t1');+ });++ it('returns null when there is no assistant turn', () => {+ expect(latestAssistantTurn({ turns: [{ id: 't1', role: 'user', content: 'q' }] })).toBeNull();+ expect(latestAssistantTurn({ turns: [] })).toBeNull();+ expect(latestAssistantTurn(null)).toBeNull();+ });+});++describe('askPromote.promoteLatestAssistantTurn', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ convs.setPromoted.mockResolvedValue({ id: 'conv-1', promoted: true });+ });++ it('captures the latest answer to brain and pins the conversation', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [+ { id: 't1', role: 'user', content: 'q' },+ { id: 't2', role: 'assistant', content: 'the answer' },+ ] });+ brainService.captureThought.mockResolvedValue({ inboxLog: { id: 'note-1' } });++ const result = await promoteLatestAssistantTurn({ conversationId: 'conv-1', target: 'brain' });+ expect(brainService.captureThought).toHaveBeenCalledWith('the answer');+ expect(convs.setPromoted).toHaveBeenCalledWith('conv-1', true);+ expect(result).toMatchObject({ target: 'brain', ref: { type: 'brain', id: 'note-1' } });+ });++ it('adds a task for the latest answer', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [+ { id: 't2', role: 'assistant', content: 'do the thing' },+ ] });+ cosService.addTask.mockResolvedValue({ id: 'task-1' });++ const result = await promoteLatestAssistantTurn({ conversationId: 'conv-1', target: 'task' });+ expect(cosService.addTask).toHaveBeenCalledWith(+ expect.objectContaining({ description: 'do the thing', priority: 'MEDIUM' }),+ 'user'+ );+ expect(result).toMatchObject({ target: 'task', ref: { type: 'task', id: 'task-1' } });+ });++ it('404s when the conversation has no assistant turn', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [{ id: 't1', role: 'user', content: 'q' }] });+ await expect(promoteLatestAssistantTurn({ conversationId: 'conv-1', target: 'brain' }))+ .rejects.toMatchObject({ status: 404, code: 'NO_ASSISTANT_TURN' });+ expect(convs.setPromoted).not.toHaveBeenCalled();+ });++ it('404s when the conversation does not exist', async () => {+ convs.getConversation.mockResolvedValue(null);+ await expect(promoteLatestAssistantTurn({ conversationId: 'missing', target: 'brain' }))+ .rejects.toMatchObject({ status: 404 });+ });++ it('maps a duplicate task to a 409', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [{ id: 't2', role: 'assistant', content: 'dupe' }] });+ cosService.addTask.mockResolvedValue({ duplicate: true });+ await expect(promoteLatestAssistantTurn({ conversationId: 'conv-1', target: 'task' }))+ .rejects.toMatchObject({ status: 409, code: 'DUPLICATE_TASK' });+ });+});++describe('askPromote.promoteTurnById', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ convs.setPromoted.mockResolvedValue({ id: 'conv-1', promoted: true });+ });++ it('promotes a specific assistant turn by id', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [+ { id: 't1', role: 'assistant', content: 'older' },+ { id: 't2', role: 'assistant', content: 'target answer' },+ ] });+ brainService.captureThought.mockResolvedValue({ inboxLog: { id: 'note-2' } });++ const result = await promoteTurnById({ conversationId: 'conv-1', turnId: 't1', target: 'brain' });+ expect(brainService.captureThought).toHaveBeenCalledWith('older');+ expect(result.ref).toEqual({ type: 'brain', id: 'note-2' });+ });++ it('rejects a non-assistant turn with a 400', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [{ id: 't1', role: 'user', content: 'q' }] });+ await expect(promoteTurnById({ conversationId: 'conv-1', turnId: 't1', target: 'brain' }))+ .rejects.toMatchObject({ status: 400 });+ });++ it('404s on an unknown turn id', async () => {+ convs.getConversation.mockResolvedValue({ id: 'conv-1', turns: [{ id: 't1', role: 'assistant', content: 'a' }] });+ await expect(promoteTurnById({ conversationId: 'conv-1', turnId: 'nope', target: 'brain' }))+ .rejects.toMatchObject({ status: 404 });+ });+});