Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-709]): richer Review Hub rows + inline Ask-answer promote

[._.]/ Adam Eivyaba28ce6d728
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 467e9f0180..fb26d08f96 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **[issue-709] Review Hub "Needs Attention" queue** — the Review Hub now opens with a cross-domain queue that pulls everything currently waiting on you into one list: Brain inbox items that need classifying, Ask answers ready to promote, CoS tasks awaiting approval, unsent message drafts, critical/high health anomalies, and failed backups. The most urgent items sort to the top, each row opens straight to where you handle it, and you can dismiss anything you don't want to act on right now. A slow or unavailable source is noted instead of blocking the rest.
- **[issue-709] Act on Review Hub items in place** — rows in the "Needs Attention" queue now carry an inline action so you can clear them without leaving the page: mark a Brain inbox item done, or approve a waiting CoS task or message draft. The row drops away the moment it's handled. Items that need a choice or have no one-click resolution (promoting an Ask answer to a note/task/goal, health anomalies that clear when the condition does, a failed backup retried from Backup settings) keep their open-and-dismiss controls.
+- **[issue-709] Richer triage context in the Review Hub queue** — "Needs Attention" rows now show at-a-glance context so you can decide without opening them: a HIGH/MEDIUM/LOW badge on CoS approvals, the turn count on Ask answers, the recipient and channel on message drafts, where a Brain inbox item was captured from, and the category of a health anomaly. Each chip only appears when that detail exists, so nothing is invented to fill space.
+- **[issue-709] Promote an Ask answer straight from the Review Hub** — Ask rows in the "Needs Attention" queue now offer inline "→ Brain" and "→ Task" buttons that save the conversation's latest answer as a Brain note or a CoS task in one click, then clear the row. Promoting to a Goal still opens the conversation, since it needs you to pick which goal.
- **[issue-708] Digital Twin personas** — give your twin named contexts — Professional, Casual, Family, or your own — each with instructions for how it should modulate voice and behavior. Activate one from the new Personas tab and your CoS agents adopt that context when they act on your behalf, while building your base identity stays unaffected. Create, edit, switch, and clear personas at any time.
- **[issue-708] Digital Twin values-alignment tests** — the Digital Twin's Test tab gains a second test mode: instead of only checking whether your twin *sounds* like you, it poses ethical dilemmas and grades whether the twin's choice is consistent with your ranked values. Each dilemma names the values at stake and ships an "aligned" and "misaligned" reference, and runs score against the values hierarchy from your Identity tab — so you can see, per model, where your twin holds your values and where it drifts. Ships a starter dilemma suite you can customize.
- **[issue-708] Test your twin as a persona** — the Digital Twin's Test tab can now run both the behavioral and values-alignment suites *as* a chosen persona instead of only the base twin: pick "Professional", "Casual", or any persona you've created and the suite embodies that context's instructions before answering. Each run is tagged in the history with the persona it used, so you can compare how the same model behaves across contexts. With no personas defined, the picker stays hidden and nothing changes.
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index ca6250df8e..1d53f71247 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -187,6 +187,20 @@ export default function Review() {
if (ok) handleQueueDismiss(item.id);
};
+ const handleQueuePromoteAsk = async (item, target) => {
+ if (resolvingQueueIds.has(item.id)) return;
+ setResolvingQueueIds(prev => new Set(prev).add(item.id));
+ // The helper toasts on failure (default), so don't add a custom catch toast.
+ const ok = await api.promoteAskReviewQueueItem(item.id, target).then(() => true).catch(() => false);
+ setResolvingQueueIds(prev => {
+ const next = new Set(prev);
+ next.delete(item.id);
+ return next;
+ });
+ // Reactive removal — drop the promoted row in place rather than refetching.
+ if (ok) handleQueueDismiss(item.id);
+ };
+
const grouped = items.reduce((acc, item) => {
if (!acc[item.type]) acc[item.type] = [];
acc[item.type].push(item);
@@ -296,6 +310,7 @@ export default function Review() {
onDrill={handleQueueDrill}
onDismiss={handleQueueDismiss}
onResolve={handleQueueResolve}
+ onPromoteAsk={handleQueuePromoteAsk}
resolving={resolvingQueueIds.has(item.id)}
/>
))}
@@ -439,10 +454,73 @@ export default function Review() {
);
}
-function QueueRow({ item, onDrill, onDismiss, onResolve, resolving = false }) {
+// Priority badge tint for CoS rows so HIGH/MEDIUM/LOW read at a glance.
+const QUEUE_PRIORITY_STYLE = {
+ HIGH: 'text-port-error border-port-error/30 bg-port-error/10',
+ MEDIUM: 'text-port-warning border-port-warning/30 bg-port-warning/10',
+ LOW: 'text-gray-400 border-gray-500/30 bg-gray-500/10'
+};
+
+// Render the source-appropriate triage chips from item.meta. Each field is
+// optional — the server omits it when the underlying record lacks it, so we
+// only render the chips that are present (no fabricated values).
+function QueueMetaChips({ meta }) {
+ if (!meta) return null;
+ const chips = [];
+ if (meta.priority) {
+ chips.push(
+ <span key="priority" className={`text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border ${QUEUE_PRIORITY_STYLE[meta.priority] || QUEUE_PRIORITY_STYLE.LOW}`}>
+ {meta.priority}
+ </span>
+ );
+ }
+ if (typeof meta.turnCount === 'number') {
+ chips.push(
+ <span key="turns" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
+ {meta.turnCount} turn{meta.turnCount === 1 ? '' : 's'}
+ </span>
+ );
+ }
+ if (meta.recipient) {
+ chips.push(
+ <span key="recipient" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400 max-w-[12rem] truncate" title={meta.recipient}>
+ → {meta.recipient}
+ </span>
+ );
+ }
+ if (meta.channel) {
+ chips.push(
+ <span key="channel" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
+ {meta.channel}
+ </span>
+ );
+ }
+ if (meta.captureSource) {
+ chips.push(
+ <span key="capture" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
+ {meta.captureSource}
+ </span>
+ );
+ }
+ if (meta.alertType) {
+ chips.push(
+ <span key="alert" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
+ {meta.alertType}
+ </span>
+ );
+ }
+ if (!chips.length) return null;
+ return <div className="flex items-center gap-1.5 flex-wrap mt-1">{chips}</div>;
+}
+
+// Promote-target label for the Ask picker buttons.
+const PROMOTE_TARGET_LABEL = { brain: 'Brain', task: 'Task' };
+
+function QueueRow({ item, onDrill, onDismiss, onResolve, onPromoteAsk, resolving = false }) {
const config = QUEUE_SOURCE_CONFIG[item.source] || { icon: Inbox, color: 'text-gray-400' };
const Icon = config.icon;
const borderTone = QUEUE_SEVERITY_STYLE[item.severity] || QUEUE_SEVERITY_STYLE.normal;
+ const promoteTargets = Array.isArray(item.promoteTargets) ? item.promoteTargets : [];
return (
<div className={`flex items-start gap-3 p-3 rounded-lg border bg-port-card ${borderTone}`}>
@@ -459,6 +537,7 @@ function QueueRow({ item, onDrill, onDismiss, onResolve, resolving = false }) {
{item.summary && (
<p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{item.summary}</p>
)}
+ <QueueMetaChips meta={item.meta} />
{item.timestamp && (
<p className="text-xs text-gray-600 mt-1 flex items-center gap-1">
<Clock3 size={12} />
@@ -466,7 +545,7 @@ function QueueRow({ item, onDrill, onDismiss, onResolve, resolving = false }) {
</p>
)}
</div>
- <div className="flex items-center gap-1 shrink-0">
+ <div className="flex items-center gap-1 shrink-0 flex-wrap justify-end">
{item.action && onResolve && (
<button
onClick={() => onResolve(item)}
@@ -478,6 +557,18 @@ function QueueRow({ item, onDrill, onDismiss, onResolve, resolving = false }) {
{item.action}
</button>
)}
+ {promoteTargets.length > 0 && onPromoteAsk && promoteTargets.map(target => (
+ <button
+ key={target}
+ onClick={() => onPromoteAsk(item, target)}
+ disabled={resolving}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-port-accent bg-port-accent/10 hover:bg-port-accent/20 border border-port-accent/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
+ title={`Promote the latest answer to ${PROMOTE_TARGET_LABEL[target] || target}`}
+ >
+ <ArrowRight size={12} />
+ {PROMOTE_TARGET_LABEL[target] || target}
+ </button>
+ ))}
<button
onClick={() => onDrill(item)}
className="p-1.5 text-gray-500 hover:text-port-accent transition-colors"
diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.js
index adec4d9014..a8c73f77d6 100644
--- a/client/src/services/apiReview.js
+++ b/client/src/services/apiReview.js
@@ -18,6 +18,13 @@ export const resolveReviewQueueItem = (id, options = {}) => request('/review/que
body: JSON.stringify({ id }),
...options
});
+// Promote an Ask row's latest assistant answer into Brain or a CoS task in
+// place (id is `ask:<conversationId>`, target is 'brain' | 'task')
+export const promoteAskReviewQueueItem = (id, target, options = {}) => request('/review/queue/promote-ask', {
+ method: 'POST',
+ body: JSON.stringify({ id, target }),
+ ...options
+});
export const createReviewTodo = (data) => request('/review/todo', {
method: 'POST',
body: JSON.stringify(data)
diff --git a/server/routes/review.js b/server/routes/review.js
index 969b33c546..5417735961 100644
--- a/server/routes/review.js
+++ b/server/routes/review.js
@@ -3,7 +3,7 @@ import { z } from 'zod';
import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import * as reviewService from '../services/review.js';
-import { buildQueue, resolveQueueItem } from '../services/reviewQueue.js';
+import { buildQueue, resolveQueueItem, promoteAskQueueItem } from '../services/reviewQueue.js';
const router = express.Router();
@@ -63,6 +63,22 @@ router.post('/queue/resolve', asyncHandler(async (req, res) => {
res.json(result);
}));
+const promoteAskQueueSchema = z.object({
+ id: z.string().min(1).max(500),
+ target: z.enum(['brain', 'task'])
+});
+
+// POST /api/review/queue/promote-ask — promote an Ask row's latest assistant
+// answer into Brain or a CoS task, in place, without leaving the Review Hub.
+// The `id` is the row's `ask:<conversationId>`; the service finds the latest
+// assistant turn so the client doesn't track turn ids. Goal targets stay a
+// drill-down (they need a goalId choice the queue row can't supply).
+router.post('/queue/promote-ask', asyncHandler(async (req, res) => {
+ const { id, target } = validateRequest(promoteAskQueueSchema, req.body);
+ const result = await promoteAskQueueItem(id, target);
+ res.json(result);
+}));
+
// POST /api/review/todo — create a user todo
router.post('/todo', asyncHandler(async (req, res) => {
const data = validateRequest(createTodoSchema, req.body);
diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.js
index af0cbf44be..13fc690d98 100644
--- a/server/services/reviewQueue.js
+++ b/server/services/reviewQueue.js
@@ -30,6 +30,7 @@ import * as cosTaskStore from './cosTaskStore.js';
import * as messageDrafts from './messageDrafts.js';
import * as proactiveAlerts from './proactiveAlerts.js';
import * as backup from './backup.js';
+import { promoteLatestAssistantTurn } from './askPromote.js';
import { ServerError } from '../lib/errorHandler.js';
// Per-source cap so one noisy producer can't flood the queue; the UI shows a
@@ -78,13 +79,20 @@ const PRODUCERS = [
},
map(entry) {
const text = (entry.capturedText || '').trim();
+ // Surface where the capture came from (brain_ui / voice / a managed app)
+ // so the user can triage by origin. Absent on legacy entries — omit the
+ // field entirely rather than fabricate one (absent vs empty).
+ const captureSource = typeof entry.source === 'string' && entry.source.trim()
+ ? entry.source.trim()
+ : null;
return {
id: `brain:${entry.id}`,
title: 'Inbox item needs classification',
summary: text.slice(0, 200),
timestamp: entry.capturedAt || entry.createdAt || null,
severity: 'normal',
- drillTo: '/brain/inbox'
+ drillTo: '/brain/inbox',
+ ...(captureSource ? { meta: { captureSource } } : {})
};
}
},
@@ -102,14 +110,21 @@ const PRODUCERS = [
const convs = await askConversations.listConversations({ limit: PER_SOURCE_LIMIT * 2 });
return convs.filter(c => !c.promoted && (c.turnCount || 0) > 0);
},
+ // Inline promote targets the UI can offer without a per-turn drill-down.
+ // The queue picks the conversation's latest assistant turn server-side, so
+ // brain/task need no extra choice; goal needs a goalId, so it stays a
+ // drill-down only.
+ promoteTargets: ['brain', 'task'],
map(conv) {
+ const turnCount = Number.isFinite(conv.turnCount) ? conv.turnCount : null;
return {
id: `ask:${conv.id}`,
title: 'Ask answer ready to promote',
summary: conv.title || '(untitled conversation)',
timestamp: conv.updatedAt || conv.createdAt || null,
severity: 'normal',
- drillTo: `/ask/${conv.id}`
+ drillTo: `/ask/${conv.id}`,
+ ...(turnCount != null ? { meta: { turnCount } } : {})
};
}
},
@@ -131,13 +146,17 @@ const PRODUCERS = [
return awaitingApproval;
},
map(task) {
+ // Surface the task priority as a triage badge. Only HIGH/MEDIUM/LOW are
+ // meaningful — anything else (or absent) is omitted rather than guessed.
+ const priority = ['HIGH', 'MEDIUM', 'LOW'].includes(task.priority) ? task.priority : null;
return {
id: `cos:${task.id}`,
title: 'CoS task pending approval',
summary: (task.description || '').slice(0, 200),
timestamp: task.createdAt || null,
severity: task.priority === 'HIGH' ? 'high' : 'normal',
- drillTo: '/cos/tasks'
+ drillTo: '/cos/tasks',
+ ...(priority ? { meta: { priority } } : {})
};
}
},
@@ -160,6 +179,18 @@ const PRODUCERS = [
return messageDrafts.listDrafts({ status: ['draft', 'pending_review'] });
},
map(draft) {
+ // Show who/where the draft is headed so the user can triage without
+ // opening it: the first recipient, plus the channel it'd send through.
+ // Each is omitted when absent rather than rendered as an empty string.
+ const recipient = Array.isArray(draft.to) && typeof draft.to[0] === 'string' && draft.to[0].trim()
+ ? draft.to[0].trim()
+ : null;
+ const channel = typeof draft.sendVia === 'string' && draft.sendVia.trim()
+ ? draft.sendVia.trim()
+ : null;
+ const meta = {};
+ if (recipient) meta.recipient = recipient;
+ if (channel) meta.channel = channel;
return {
// Prefix matches `source` ('drafts') so resolveQueueItem's
// split-on-first-colon dispatch lands on this producer.
@@ -168,7 +199,8 @@ const PRODUCERS = [
summary: draft.subject || (draft.body || '').slice(0, 120) || '(no subject)',
timestamp: draft.updatedAt || draft.createdAt || null,
severity: 'normal',
- drillTo: '/messages/drafts'
+ drillTo: '/messages/drafts',
+ ...(Object.keys(meta).length ? { meta } : {})
};
}
},
@@ -184,13 +216,19 @@ const PRODUCERS = [
// proactiveAlerts emits { type, severity, title, detail, link } with no
// stable id and possibly-repeating types, so key on the array index too.
map(alert, index) {
+ // Surface the alert category (system_resource / goal_stall / …) so the
+ // user can tell at a glance what kind of anomaly it is. Absent → omitted.
+ const alertType = typeof alert.type === 'string' && alert.type.trim()
+ ? alert.type.trim()
+ : null;
return {
id: `health:${alert.type || 'alert'}:${index}`,
title: alert.title || `${alert.type || 'System'} alert`,
summary: (alert.detail || alert.message || '').slice(0, 200),
timestamp: alert.timestamp || null,
severity: alert.severity === 'critical' ? 'critical' : 'high',
- drillTo: alert.link || '/system-health'
+ drillTo: alert.link || '/system-health',
+ ...(alertType ? { meta: { alertType } } : {})
};
}
},
@@ -234,7 +272,12 @@ async function gatherProducer(producer) {
...producer.map(item, index),
// Inline-action verb when the producer declares one resolve primitive; the
// UI shows an accept/promote button only for rows that carry it.
- ...(producer.action && producer.resolve ? { action: producer.action } : {})
+ ...(producer.action && producer.resolve ? { action: producer.action } : {}),
+ // Inline promote targets (Ask rows) — the UI renders a compact target
+ // picker for rows that carry a non-empty list.
+ ...(Array.isArray(producer.promoteTargets) && producer.promoteTargets.length
+ ? { promoteTargets: producer.promoteTargets }
+ : {})
}));
return { items, total: list.length };
}
@@ -266,6 +309,31 @@ export async function resolveQueueItem(queueItemId) {
return { source, id: queueItemId, resolved: true };
}
+/**
+ * Promote an Ask queue row's latest assistant answer into a chosen target
+ * (brain/task). `queueItemId` is the row id (`ask:<conversationId>`); `target`
+ * must be one of the Ask producer's declared `promoteTargets`. The service
+ * picks the conversation's latest assistant turn so the client doesn't carry
+ * turn ids — a conversation with no assistant answer 404s. Reuses the same
+ * promote orchestration the per-turn Ask route uses (no duplication).
+ */
+export async function promoteAskQueueItem(queueItemId, target) {
+ const sep = String(queueItemId).indexOf(':');
+ const source = sep === -1 ? queueItemId : queueItemId.slice(0, sep);
+ const conversationId = sep === -1 ? '' : queueItemId.slice(sep + 1);
+
+ if (source !== 'ask') {
+ throw new ServerError(`Promote is only supported for Ask rows, got "${source}"`, { status: 400, code: 'BAD_REQUEST' });
+ }
+ const allowed = PRODUCERS_BY_SOURCE.ask.promoteTargets || [];
+ if (!allowed.includes(target)) {
+ throw new ServerError(`Unsupported promote target "${target}" for Ask`, { status: 400, code: 'BAD_REQUEST' });
+ }
+
+ const result = await promoteLatestAssistantTurn({ conversationId, target });
+ return { source, id: queueItemId, promoted: true, target: result.target, ref: result.ref };
+}
+
/**
* Build the cross-domain review queue. Returns the normalized item list (sorted
* by severity then recency), aggregate `counts`, and a `sources` map with
diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.js
index e854f18fdf..9afc276afe 100644
--- a/server/services/reviewQueue.test.js
+++ b/server/services/reviewQueue.test.js
@@ -8,6 +8,10 @@ const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn() };
const messageDrafts = { listDrafts: vi.fn(), approveDraft: vi.fn() };
const proactiveAlerts = { generateAlerts: vi.fn() };
const backup = { getState: vi.fn() };
+// Mocked so the meta-field / buildQueue cases don't pull the brain/cos/identity
+// stack in transitively (askPromote imports all three). The promoteAskQueueItem
+// suite drives this mock directly.
+const askPromote = { promoteLatestAssistantTurn: vi.fn() };
vi.mock('./brain.js', () => brain);
vi.mock('./askConversations.js', () => askConversations);
@@ -15,8 +19,9 @@ vi.mock('./cosTaskStore.js', () => cosTaskStore);
vi.mock('./messageDrafts.js', () => messageDrafts);
vi.mock('./proactiveAlerts.js', () => proactiveAlerts);
vi.mock('./backup.js', () => backup);
+vi.mock('./askPromote.js', () => askPromote);
-const { buildQueue, resolveQueueItem, __resetAlertsCache } = await import('./reviewQueue.js');
+const { buildQueue, resolveQueueItem, promoteAskQueueItem, __resetAlertsCache } = await import('./reviewQueue.js');
// Default: every producer returns "nothing needs attention".
function resetEmpty() {
@@ -169,6 +174,80 @@ describe('reviewQueue.buildQueue', () => {
expect(queue.items.find(i => i.source === 'health').action).toBeUndefined();
expect(queue.items.find(i => i.source === 'backup').action).toBeUndefined();
});
+
+ it('attaches source-appropriate meta chips when the raw field is present', async () => {
+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify', source: 'voice', capturedAt: '2026-06-03T10:00:00.000Z' }]);
+ askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'promote me', promoted: false, turnCount: 4 }]);
+ cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'approve me', priority: 'MEDIUM', createdAt: '2026-06-03T09:00:00.000Z' }] });
+ messageDrafts.listDrafts.mockResolvedValue([{ id: 'd1', status: 'draft', subject: 's', to: ['[email protected]'], sendVia: 'gmail', updatedAt: '2026-06-03T08:00:00.000Z' }]);
+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ type: 'system_resource', severity: 'critical', title: 'mem', detail: 'high', link: '/apps' }] });
+ const queue = await buildQueue();
+ expect(queue.items.find(i => i.source === 'brain').meta).toEqual({ captureSource: 'voice' });
+ expect(queue.items.find(i => i.source === 'ask').meta).toEqual({ turnCount: 4 });
+ expect(queue.items.find(i => i.source === 'cos').meta).toEqual({ priority: 'MEDIUM' });
+ expect(queue.items.find(i => i.source === 'drafts').meta).toEqual({ recipient: '[email protected]', channel: 'gmail' });
+ expect(queue.items.find(i => i.source === 'health').meta).toEqual({ alertType: 'system_resource' });
+ });
+
+ it('omits meta entirely when the raw fields are missing (no fabricated values)', async () => {
+ // Brain entry with no `source`, draft with no recipient/channel — meta should
+ // be absent, not an empty object.
+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify', capturedAt: '2026-06-03T10:00:00.000Z' }]);
+ messageDrafts.listDrafts.mockResolvedValue([{ id: 'd1', status: 'draft', subject: 's', to: [], updatedAt: '2026-06-03T08:00:00.000Z' }]);
+ const queue = await buildQueue();
+ expect(queue.items.find(i => i.source === 'brain').meta).toBeUndefined();
+ expect(queue.items.find(i => i.source === 'drafts').meta).toBeUndefined();
+ });
+
+ it('drops an out-of-range cos priority rather than badge-ing it', async () => {
+ cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'x', priority: 'URGENT', createdAt: '2026-06-03T09:00:00.000Z' }] });
+ const queue = await buildQueue();
+ expect(queue.items.find(i => i.source === 'cos').meta).toBeUndefined();
+ });
+
+ it('advertises Ask promote targets (brain/task) and no other source carries them', async () => {
+ askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'promote me', promoted: false, turnCount: 1 }]);
+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify', capturedAt: '2026-06-03T10:00:00.000Z' }]);
+ const queue = await buildQueue();
+ expect(queue.items.find(i => i.source === 'ask').promoteTargets).toEqual(['brain', 'task']);
+ expect(queue.items.find(i => i.source === 'brain').promoteTargets).toBeUndefined();
+ });
+});
+
+describe('reviewQueue.promoteAskQueueItem', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('promotes the latest assistant turn to brain via the shared promote helper', async () => {
+ askPromote.promoteLatestAssistantTurn.mockResolvedValue({ target: 'brain', ref: { type: 'brain', id: 'note-1' } });
+ const result = await promoteAskQueueItem('ask:conv-1', 'brain');
+ expect(askPromote.promoteLatestAssistantTurn).toHaveBeenCalledWith({ conversationId: 'conv-1', target: 'brain' });
+ expect(result).toMatchObject({ source: 'ask', id: 'ask:conv-1', promoted: true, target: 'brain', ref: { type: 'brain', id: 'note-1' } });
+ });
+
+ it('promotes to task target', async () => {
+ askPromote.promoteLatestAssistantTurn.mockResolvedValue({ target: 'task', ref: { type: 'task', id: 't-1' } });
+ await promoteAskQueueItem('ask:conv-2', 'task');
+ expect(askPromote.promoteLatestAssistantTurn).toHaveBeenCalledWith({ conversationId: 'conv-2', target: 'task' });
+ });
+
+ it('rejects a non-ask row with a 400', async () => {
+ await expect(promoteAskQueueItem('brain:b1', 'brain')).rejects.toMatchObject({ status: 400 });
+ expect(askPromote.promoteLatestAssistantTurn).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unsupported target (goal) with a 400', async () => {
+ await expect(promoteAskQueueItem('ask:conv-1', 'goal')).rejects.toMatchObject({ status: 400 });
+ expect(askPromote.promoteLatestAssistantTurn).not.toHaveBeenCalled();
+ });
+
+ it('propagates the 404 when no assistant turn exists', async () => {
+ const err = new Error('Conversation has no assistant answer to promote');
+ err.status = 404;
+ askPromote.promoteLatestAssistantTurn.mockRejectedValue(err);
+ await expect(promoteAskQueueItem('ask:conv-3', 'brain')).rejects.toMatchObject({ status: 404 });
+ });
});
describe('reviewQueue.resolveQueueItem', () => {