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: centralize review action admission (#7738)
[._.]/ Adam Eivy61f87240ba0a
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsxindex 4a81fce02d..cc0bbb6c40 100644--- a/client/src/pages/Review.jsx+++ b/client/src/pages/Review.jsx@@ -78,6 +78,29 @@ const TYPE_CONFIG = {const TYPE_PRIORITY = { alert: 0, cos: 1, todo: 2, briefing: 3 };+const SOURCE_OWNED_REVIEW_CATEGORIES = new Set([+ 'content-review',+ 'goal-fidelity',+ 'memory-approval',+ 'plan-question',+ 'task-approval',+ 'autopilot-paused',+]);++function isSourceOwnedReviewItem(item) {+ const metadata = item?.metadata && typeof item.metadata === 'object' ? item.metadata : {};+ const hasReference = (value) => (typeof value === 'string' && value.trim())+ || (typeof value === 'number' && Number.isFinite(value));+ if (metadata.sourceOwned === true || metadata.triageOnly === true) return true;+ if (SOURCE_OWNED_REVIEW_CATEGORIES.has(metadata.category)) return true;+ if (item?.type === 'cos' && (hasReference(metadata.taskId) || hasReference(metadata.referenceId))) return true;+ return item?.type === 'alert';+}++function isGenericCompletableItem(item) {+ return !isSourceOwnedReviewItem(item);+}+function isActionableItem(item) {if (item.type === 'alert' || item.type === 'todo') return true;if (item.type === 'cos') {@@ -287,6 +310,7 @@ export default function Review() {[queue]);const pendingItems = useMemo(() => items.filter(i => i.status === 'pending'), [items]);+ const genericCompletableCount = pendingItems.filter(isGenericCompletableItem).length;const actionableItems = useMemo(() => pendingItems.filter(isActionableItem)@@ -339,13 +363,15 @@ export default function Review() {</select>{pendingCount > 0 && (<>- <button- onClick={handleCompleteAll}- className="px-3 py-2 text-sm bg-port-success/10 hover:bg-port-success/20 border border-port-success/30 rounded-lg text-port-success transition-colors"- title="Mark all pending items as completed"- >- Complete All- </button>+ {genericCompletableCount > 0 && (+ <button+ onClick={handleCompleteAll}+ className="px-3 py-2 text-sm bg-port-success/10 hover:bg-port-success/20 border border-port-success/30 rounded-lg text-port-success transition-colors"+ title="Mark all general pending items as completed"+ >+ Complete All+ </button>+ )}<buttononClick={handleMarkAllRead}className="px-3 py-2 text-sm bg-port-border/50 hover:bg-port-border rounded-lg text-gray-300 transition-colors"@@ -851,13 +877,15 @@ function ReviewItem({ item, config, idScope, isEditing, onComplete, onDismiss, o<Pencil size={14} /></button>)}- <button- onClick={() => onComplete(item.id)}- className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-500 hover:text-port-success transition-colors"- title={item.type === 'alert' ? 'Accept' : 'Complete'} aria-label={item.type === 'alert' ? 'Accept' : 'Complete'}- >- <CheckCircle2 size={16} />- </button>+ {isGenericCompletableItem(item) && (+ <button+ onClick={() => onComplete(item.id)}+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-500 hover:text-port-success transition-colors"+ title="Complete" aria-label="Complete"+ >+ <CheckCircle2 size={16} />+ </button>+ )}<buttononClick={() => onDismiss(item.id)}className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-500 hover:text-port-warning transition-colors"diff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsxindex 3b2eb3ea0c..1717be09df 100644--- a/client/src/pages/Review.test.jsx+++ b/client/src/pages/Review.test.jsx@@ -152,8 +152,9 @@ describe('Review Hub queue-card triage (#3282)', () => {render(<Review />);await waitFor(() => expect(actionQueueBody()).toBeTruthy());- // Accept / Reject / Delete are all reachable on the collapsed card.- expect(screen.getAllByTitle('Accept').length).toBeGreaterThan(0);+ // Source-owned alerts cannot be silently accepted or deleted. Dismissal+ // remains available as the explicit triage action.+ expect(screen.queryByTitle('Accept')).not.toBeInTheDocument();expect(screen.getAllByTitle('Reject').length).toBeGreaterThan(0);expect(screen.getAllByTitle('Delete').length).toBeGreaterThan(0);});diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.jsindex ec3ef0b314..3eb84dd06a 100644--- a/client/src/services/apiReview.js+++ b/client/src/services/apiReview.js@@ -10,17 +10,19 @@ export const getReviewItems = (params) => {};export const getReviewCounts = (options = {}) => request('/review/counts', options);export const getReviewBriefing = () => request('/review/briefing');-// Cross-domain live queue (brain inbox, ask, CoS approvals, drafts, health, backups).+// Cross-domain live queue (source-owned obligations plus domain projections).// Keep transport options (silent, headers, abort signal) separate from the// pagination query so callers can continue using the old options-only shape.export const getReviewQueue = ({ limit, cursor, ...options } = {}) => {const query = queryString({ limit, cursor });return request(`/review/queue${query}`, options);};-// Accept/promote a single queue row in place (id is `<source>:<rawId>`)-export const resolveReviewQueueItem = (id, options = {}) => request('/review/queue/resolve', {+// Resolve a single queue row in place (id is `<source>:<rawId>`). Source-owned+// approvals may pass `operation` (approve/reject); transport options stay out+// of the JSON body.+export const resolveReviewQueueItem = (id, { operation, ...options } = {}) => request('/review/queue/resolve', {method: 'POST',- body: JSON.stringify({ id }),+ body: JSON.stringify({ id, ...(operation ? { operation } : {}) }),...options});// Promote an Ask row's latest assistant answer into Brain, a CoS task, or adiff --git a/client/src/services/apiReview.test.js b/client/src/services/apiReview.test.jsindex fa80a5eec7..2a3164a856 100644--- a/client/src/services/apiReview.test.js+++ b/client/src/services/apiReview.test.js@@ -14,11 +14,12 @@ vi.mock('./apiCore.js', () => ({let request;let getReviewQueue;+let resolveReviewQueueItem;beforeEach(async () => {vi.resetModules();({ request } = await import('./apiCore.js'));- ({ getReviewQueue } = await import('./apiReview.js'));+ ({ getReviewQueue, resolveReviewQueueItem } = await import('./apiReview.js'));request.mockReset();});@@ -39,3 +40,17 @@ describe('getReviewQueue', () => {expect(request).toHaveBeenCalledWith('/review/queue', { silent: true });});});++describe('resolveReviewQueueItem', () => {+ it('keeps source operations in the body and transport options separate', async () => {+ request.mockResolvedValue({ resolved: true });++ await resolveReviewQueueItem('memory:memory-1', { operation: 'approve', silent: true });++ expect(request).toHaveBeenCalledWith('/review/queue/resolve', {+ method: 'POST',+ body: JSON.stringify({ id: 'memory:memory-1', operation: 'approve' }),+ silent: true,+ });+ });+});diff --git a/docs/features/review-queue.md b/docs/features/review-queue.mdindex fc99e17b8b..611088e70d 100644--- a/docs/features/review-queue.md+++ b/docs/features/review-queue.md@@ -45,6 +45,12 @@ the additive fields `sourceRef`, `actionKind`, `reason`, `nextAction`,producer URL or arbitrary command. The existing route-specific mutationconsumers remain the authority for executing those operations.+Source-owned rows may also carry `sourceOwned: true` and `triageOnly: true`.+Generic Review completion rejects those rows; an explicit source operation+must revalidate the owning record at mutation time. A row with+`required: false` is a recommendation and remains available to its domain+without becoming an interruptive action.+Rows are deduplicated before totals and page slicing, then ordered by requiredwork, severity, overdue/due time, priority, and stable row ID. Optionalrecommendations therefore remain below required work even when they are newer.@@ -62,3 +68,29 @@ bound the upstream read, and report whether the bound was filled. Add a sourcedescriptor and operation to this document and cover the healthy, failed, andtruncated paths at the queue boundary. Do not add a second durable task storeor invoke an LLM as part of queue assembly.++## Action admission matrix++The queue admits an obligation only when its adapter has a stable reference and+a concrete human remedy or drill-down. Correlation uses source references and+metadata, never matching titles or prose. Two rows with the same proven+canonical reference are deduplicated; approval and feedback use different+action kinds and are never merged merely because they share a task or agent.++| Producer or bridge | Admission | Source reference and operation | History/context behavior |+| --- | --- | --- | --- |+| Brain inbox | Required when `needs_review` | Brain entry id; `brain.classify` / Done | Source remains authoritative |+| CoS approval store | Required when `awaitingApproval` | Task id; `task.approval` / Approve | Execution success does not create or complete an action |+| Message drafts | Required only for `pending_review` | Draft id; `message.approve` / Approve | Unsubmitted `draft` rows remain optional domain drafts |+| Memory approval | Required with `memoryId` | Memory id; `memory.approval` / Approve or Reject | Stale or already-resolved memory is a conflict/not-found, not a generic completion |+| Goal-fidelity hold | Required with agent/reference id | Agent id; `goal-fidelity.review` / Review | Remains pending until the source workflow resolves it |+| Plan question | Required with agent/app id and link | Agent/app id; `plan.question` / Review | The marker stays source-owned; generic warnings remain context |+| Paused automation | Required with series/run id and link | Series/run reference; `autopilot.resume` / Resume | Resume remains in the owning automation surface |+| Explicit content review | Required with report/reference id and link | Report or review id; `content.review` / Review | Private security and malware reports remain source-owned |+| Health and backup | Required only with a known human remedy | Alert or last-run identity; Investigate or Retry | No generic Complete operation |+| Legacy Review alerts | Required as explicit triage | Stored Review item id; `review.triage` / Review | Never silently completed or deleted |+| Briefings, generic warnings, client errors, and uncorrelated notifications | Not admitted | No proven obligation contract | Remain in Review history/context |++Optional Ask promotion is still available from Ask and its API, but it is not+required action admission. Routine task-ready/success attention generation is+not a queue producer; execution history and private reports remain separate.diff --git a/server/lib/README.md b/server/lib/README.mdindex 56c101eca9..dd5eed8981 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -559,7 +559,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. || `renderTiming.js` | `renderTimingFields(startedAtMs, nowMs?)` → the `{ renderMs, renderStartedAt, renderCompletedAt }` spread every image/video backend stamps on the record it persists, measuring ingestion → finished artifact (not queue wait). Returns `{}` when no start instant was observed, so absence stays the explicit unknown sentinel for the history cards and `services/videoGen/eta.js`. `omitRenderTiming(record)` is the inverse, for a DERIVED record built by spreading its source (an image variant) that must not inherit a duration it never took. || `telegramClient.js` | Telegram bot client. |-| `notificationTypes.js` | Notification vocabulary and human labels: `NOTIFICATION_CATALOG`, compatible `NOTIFICATION_TYPES`, and `AVAILABLE_FORWARD_TYPES` for Telegram settings. |+| `notificationTypes.js` | Notification vocabulary, forwarding labels, and the allowlisted `NOTIFICATION_ACTION_POLICY` used to admit source-owned obligations into the Review Queue. || `telegramMessage.js` | Pure builder for the Telegram notification wire message, shared by both transports (`services/telegram.js` and `services/telegramBridge.js`, which drifted apart while each kept a copy — #5688). `buildNotificationMessage(notification, { approvalBody })` → `{ text, options }`: emoji + escaped title, the body truncated to `TELEGRAM_MAX_RAW_CHARS` (2800) BEFORE escaping so the escaped result stays under Telegram's 4096 cap and a slice can't split an entity, the priority line, and the memory approve/reject `reply_markup` as a plain OBJECT (both transports post JSON, so a pre-serialized string would arrive as a literal string). `approvalBody` is resolved by the caller because the memory lookup is I/O. Also exports `escapeHtml`, `truncateForTelegram`, `isMemoryApprovalNotification`, the `NOTIFICATION_EMOJI`/`PRIORITY_EMOJI` maps (keyed by literal `NOTIFICATION_TYPES` values to stay a dependency-free leaf; pinned to the real enum by a parity test), and the `CALLBACK_APPROVE`/`CALLBACK_REJECT` prefixes the bot's `callback_query` handler parses back out. || `telegramRateLimit.js` | `createTokenBucket({ max = 30, refillMs = 60_000 })` → `{ consume() }` — the coarse full-refill-per-window bucket both Telegram transports use against Telegram's ~30 msg/min throttle. Each transport creates its OWN instance: they are never both active, and one shared bucket would let a transport inherit the other's drained budget. Pure (reads `Date.now()`, owns no timer). || `tempPathGuard.js` | Throwaway-path guard for destructive test fixtures. `isTempPath(target)` — true only for an absolute path that is a STRICT descendant of `os.tmpdir()` **after symlinks are resolved** (`os.tmpdir()` itself is refused, or `destroyGitSandbox(tmpdir())` would wipe every process's scratch; a `..` segment is refused rather than lexically collapsed; macOS `/var/folders/...` and `/private/var/folders/...` both pass). `assertTempPath(target, operation)` throws otherwise and returns `target` so it can wrap an argument inline. Use it before any fixture `git init` / `git config` / `rm -rf`: `spawn` silently substitutes `process.cwd()` for a missing cwd, which is how a test run once set `core.bare = true` on a real checkout (#4554). |diff --git a/server/lib/notificationTypes.js b/server/lib/notificationTypes.jsindex ae5c16adc3..8c6417a7ed 100644--- a/server/lib/notificationTypes.js+++ b/server/lib/notificationTypes.js@@ -17,4 +17,60 @@ export const NOTIFICATION_TYPES = Object.fromEntries(Object.entries(NOTIFICATION_CATALOG).map(([name, { key }]) => [name, key]));+// These are the only notification types that can enter the canonical action+// queue. Everything else remains history/context until its owning domain adds+// an explicit source adapter and mutation contract.+export const NOTIFICATION_ACTION_POLICY = Object.freeze({+ [NOTIFICATION_TYPES.MEMORY_APPROVAL]: {+ label: 'Memory approval',+ category: 'memory-approval',+ actionSource: 'memory',+ actionKind: 'memory.approval',+ referenceFields: ['memoryId'],+ required: true,+ operations: [+ { id: 'approve', label: 'Approve', available: true },+ { id: 'reject', label: 'Reject', available: true },+ ],+ },+ [NOTIFICATION_TYPES.TASK_APPROVAL]: {+ label: 'Task approval',+ category: 'task-approval',+ actionSource: 'cos',+ actionKind: 'task.approval',+ referenceFields: ['taskId'],+ required: true,+ operations: [{ id: 'approve', label: 'Approve', available: true }],+ },+ [NOTIFICATION_TYPES.CODE_REVIEW]: {+ label: 'Content review',+ category: 'content-review',+ actionSource: 'content',+ actionKind: 'content.review',+ referenceFields: ['prNumber', 'reviewId', 'referenceId'],+ required: true,+ operations: [{ id: 'review', label: 'Review', available: false }],+ },+ [NOTIFICATION_TYPES.PLAN_QUESTION]: {+ label: 'Plan question',+ category: 'plan-question',+ actionSource: 'plan',+ actionKind: 'plan.question',+ referenceFields: ['agentId', 'appId', 'referenceId'],+ fallbackDrillTo: '/cos',+ required: true,+ operations: [{ id: 'review', label: 'Review', available: false }],+ },+ [NOTIFICATION_TYPES.AUTOPILOT_PAUSED]: {+ label: 'Paused automation',+ category: 'autopilot-paused',+ actionSource: 'autopilot',+ actionKind: 'autopilot.resume',+ referenceFields: ['autopilotPauseSeriesId', 'runId'],+ compoundReference: true,+ required: true,+ operations: [{ id: 'resume', label: 'Resume', available: false }],+ },+});+export const AVAILABLE_FORWARD_TYPES = Object.values(NOTIFICATION_CATALOG);diff --git a/server/routes/review.js b/server/routes/review.jsindex cb7c2ed070..9e545c0213 100644--- a/server/routes/review.js+++ b/server/routes/review.js@@ -42,7 +42,8 @@ router.get('/briefing', asyncHandler(async (req, res) => {}));// GET /api/review/queue — cross-domain live aggregator of items needing-// attention (brain inbox, ask answers, CoS approvals, drafts, health, backups)+// attention, including source-owned review obligations and actionable+// notifications.router.get('/queue', asyncHandler(async (req, res) => {const { limit, cursor } = validateRequest(reviewQueueQuerySchema, req.query);const queue = await buildQueue({ limit, cursor, query: {} });@@ -50,17 +51,16 @@ router.get('/queue', asyncHandler(async (req, res) => {}));const resolveQueueSchema = z.object({- id: z.string().min(1).max(500)+ id: z.string().min(1).max(500),+ operation: z.enum(['resolve', 'approve', 'reject']).optional(),});// POST /api/review/queue/resolve — accept a single cross-domain queue row in-// place (mark a Brain inbox item done, approve a CoS task or message draft)-// without leaving the Review Hub. Sources with no clean one-click resolve-// (Ask, health, backup) have no inline action and 400 here. The `id` is the-// row's `<source>:<rawId>` — the service dispatches to that source's primitive.+// place. Source-owned approvals carry an explicit operation so the mutation+// revalidates the owning domain instead of using generic Review completion.router.post('/queue/resolve', asyncHandler(async (req, res) => {- const { id } = validateRequest(resolveQueueSchema, req.body);- const result = await resolveQueueItem(id);+ const { id, operation } = validateRequest(resolveQueueSchema, req.body);+ const result = operation ? await resolveQueueItem(id, operation) : await resolveQueueItem(id);res.json(result);}));diff --git a/server/routes/review.test.js b/server/routes/review.test.jsindex 1f3ab4b9ec..bf7536131a 100644--- a/server/routes/review.test.js+++ b/server/routes/review.test.js@@ -64,3 +64,25 @@ describe('GET /api/review/queue', () => {expect(buildQueue).toHaveBeenCalledWith({ limit: undefined, cursor: 'opaque-token', query: {} });});});++describe('POST /api/review/queue/resolve', () => {+ it('passes an explicit source operation to the queue service', async () => {+ resolveQueueItem.mockResolvedValue({ source: 'memory', id: 'memory:m1', operation: 'approve', resolved: true });++ const response = await request(makeApp())+ .post('/api/review/queue/resolve')+ .send({ id: 'memory:m1', operation: 'approve' });++ expect(response.status).toBe(200);+ expect(resolveQueueItem).toHaveBeenCalledWith('memory:m1', 'approve');+ });++ it('rejects unsupported mutation operations before the service is called', async () => {+ const response = await request(makeApp())+ .post('/api/review/queue/resolve')+ .send({ id: 'memory:m1', operation: 'review' });++ expect(response.status).toBe(400);+ expect(resolveQueueItem).not.toHaveBeenCalled();+ });+});diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 09e59a1c45..e9b5cc9ea0 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -468,7 +468,7 @@ async function notifyPlanQuestionIfNeeded({ agentId, task, agentState }) {message: markerContent,priority: PRIORITY_LEVELS.MEDIUM,link: appId ? `/apps/${appId}/documents` : undefined,- metadata: { appId, agentId, taskType: planAnalysisType }+ metadata: { appId, agentId, taskType: planAnalysisType, category: 'plan-question' }}).catch(err => {emitLog('warn', `Failed to create plan_question notification: ${err.message}`, { agentId });});diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex e4578e0af1..e780994bc0 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -694,7 +694,7 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {expect(addNotification).toHaveBeenCalledWith({type: 'plan_question', title: 'Choose the example scope', message: marker,priority: 'medium', link: '/apps/example-app/documents',- metadata: { appId: 'example-app', agentId: 'a1', taskType: 'plan-task' },+ metadata: { appId: 'example-app', agentId: 'a1', taskType: 'plan-task', category: 'plan-question' },});await expect(readFile(join(workspace, '.plan-questions.md'))).rejects.toMatchObject({ code: 'ENOENT' });expect(addNotification.mock.invocationCallOrder[0]).toBeLessThan(cleanupAgentWorktree.mock.invocationCallOrder[0]);diff --git a/server/services/malwareScanReports.js b/server/services/malwareScanReports.jsindex 3f3759c514..53ce287ca8 100644--- a/server/services/malwareScanReports.js+++ b/server/services/malwareScanReports.js@@ -60,7 +60,15 @@ export async function finalizeMalwareScan({ agentId, task, success }) {type: verdict === 'DANGEROUS' ? 'alert' : 'briefing',title: `${verdict || 'UNKNOWN'} malware scan: ${task.description}`,description: 'Open the attached markdown report for the complete static-analysis findings.',- metadata: { referenceId: `malware-scan:${scan.reportId}`, reportUrl, verdict, linkId: scan.linkId }+ metadata: {+ referenceId: `malware-scan:${scan.reportId}`,+ category: 'content-review',+ actionKind: 'content.review',+ sourceOwned: true,+ reportUrl,+ verdict,+ linkId: scan.linkId,+ }});}diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.jsindex 3e002a5711..b07fc3f5fc 100644--- a/server/services/memoryExtractor.js+++ b/server/services/memoryExtractor.js@@ -365,6 +365,9 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nulink: '/cos/memory',metadata: {memoryId: mem.id,+ category: 'memory-approval',+ actionKind: 'memory.approval',+ sourceOwned: true,memoryType: mem.type,agentId,taskIddiff --git a/server/services/notifications.js b/server/services/notifications.jsindex 789f7188c5..c99ddd0b50 100644--- a/server/services/notifications.js+++ b/server/services/notifications.js@@ -135,7 +135,9 @@ export async function addNotification(notification) {id: uuidv4(),type: notification.type,title: notification.title,- description: notification.description || '',+ // Some legacy producers call this field `message`. Preserve it at the+ // store boundary so the action adapter can retain the user's remedy.+ description: notification.description || notification.message || '',priority: notification.priority || PRIORITY_LEVELS.MEDIUM,timestamp: new Date().toISOString(),link: notification.link || null,diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.jsindex 76391f1fcc..0772b90138 100644--- a/server/services/pipeline/seriesAutopilot/session.js+++ b/server/services/pipeline/seriesAutopilot/session.js@@ -308,7 +308,13 @@ export async function notifyPause(record, sId, { reason, pauseKind = null, curredescription: reason || 'The run paused and needs human review before it can continue.',priority: PRIORITY_LEVELS.HIGH,link: `/pipeline/series/${sId}`,- metadata: { autopilotPauseSeriesId: sId, runId: record.runId, pauseKind, currentStep },+ metadata: {+ autopilotPauseSeriesId: sId,+ runId: record.runId,+ category: 'autopilot-paused',+ pauseKind,+ currentStep,+ },}).catch((err) => { console.log(`⚠️ autopilot: pause notification failed for ${sId.slice(0, 12)}: ${err.message}`); });}diff --git a/server/services/privateSecurityAssessment.js b/server/services/privateSecurityAssessment.jsindex 284840f45f..a123fce4d9 100644--- a/server/services/privateSecurityAssessment.js+++ b/server/services/privateSecurityAssessment.js@@ -122,6 +122,14 @@ export async function processTaskOutput({ success, payload, task, agentId }, dep].join('\n\n');const review = deps.review || await import('./review.js');const item = await review.createItem({ type: 'alert', title: 'Private security assessment report', description,- metadata: { referenceId: `private-security:${agentId}`, privateSecurity: true, agentId, appId: task.metadata.app } });+ metadata: {+ referenceId: `private-security:${agentId}`,+ category: 'content-review',+ actionKind: 'content.review',+ sourceOwned: true,+ privateSecurity: true,+ agentId,+ appId: task.metadata.app,+ } });return { accepted: true, success: true, reportId: item.id, findings: report.findings.length };}diff --git a/server/services/review.js b/server/services/review.jsindex 06e0ffe546..afc54a9e48 100644--- a/server/services/review.js+++ b/server/services/review.js@@ -11,6 +11,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { EventEmitter } from 'events';import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { cosEvents } from './cosEvents.js';+import { isSourceOwnedReviewItem } from './reviewActionAdapters.js';import { GOAL_FIDELITY_HOLD_EVENT, formatGoalFidelitySummary } from '../lib/goalFidelity.js';const DATA_DIR = join(PATHS.data, 'review');@@ -285,7 +286,7 @@ export async function createItem({ type, title, description = '', metadata = {}/*** Update an item's status*/-async function updateItemStatus(id, status) {+async function updateItemStatus(id, status, { allowSourceOwned = false } = {}) {if (!ITEM_STATUSES.includes(status)) {const err = new Error(`Invalid status: ${status}`);err.status = 400;@@ -300,6 +301,13 @@ async function updateItemStatus(id, status) {throw err;}+ if (status === 'completed' && !allowSourceOwned && isSourceOwnedReviewItem(item)) {+ const err = new Error('Source-owned review obligations require their owning action');+ err.status = 409;+ err.code = 'SOURCE_ACTION_REQUIRED';+ throw err;+ }+item.status = status;item.updatedAt = new Date().toISOString();await save(items);@@ -319,7 +327,7 @@ export async function completeItem(id) {* Dismiss an item*/export async function dismissItem(id) {- return updateItemStatus(id, 'dismissed');+ return updateItemStatus(id, 'dismissed', { allowSourceOwned: true });}/**@@ -346,6 +354,7 @@ export async function bulkUpdateStatus({ ids, status }) {for (const item of items) {if (item.status !== 'pending') continue;if (idSet && !idSet.has(item.id)) continue;+ if (status === 'completed' && isSourceOwnedReviewItem(item)) continue;item.status = status;item.updatedAt = now;updated.push(item);@@ -391,6 +400,13 @@ export async function deleteItem(id) {throw err;}+ if (isSourceOwnedReviewItem(items[index])) {+ const err = new Error('Source-owned review obligations require triage or their owning action');+ err.status = 409;+ err.code = 'SOURCE_ACTION_REQUIRED';+ throw err;+ }+const [removed] = items.splice(index, 1);await save(items);console.log(`📋 Review item deleted: ${removed.type} — ${removed.title}`);@@ -448,7 +464,14 @@ cosEvents.on('memory:approval-needed', (data) => {type: 'alert',title: `Memory approval: ${mem.content?.slice(0, 80) || 'New memory entry'}`,description: `Type: ${mem.type ?? 'unknown'} | Confidence: ${mem.confidence ?? 'N/A'}`,- metadata: { referenceId: mem.id, category: 'memory-approval', agentId: data?.agentId, taskId: data?.taskId }+ metadata: {+ referenceId: mem.id,+ category: 'memory-approval',+ actionKind: 'memory.approval',+ sourceOwned: true,+ agentId: data?.agentId,+ taskId: data?.taskId,+ }}).catch(err => console.error(`❌ Failed to create review alert: ${err.message}`));}});@@ -476,6 +499,8 @@ cosEvents.on(GOAL_FIDELITY_HOLD_EVENT, (data) => {metadata: {referenceId: data?.agentId,category: 'goal-fidelity',+ actionKind: 'goal-fidelity.review',+ sourceOwned: true,agentId: data?.agentId,taskId: data?.taskId,verdict: review.verdict@@ -502,8 +527,7 @@ async function updateStatusByReferenceId(referenceId, status) {for (const item of matching) reviewEvents.emit('item:updated', item);}-const dismissByReferenceId = (referenceId) => updateStatusByReferenceId(referenceId, 'dismissed');-const completeByReferenceId = (referenceId) => updateStatusByReferenceId(referenceId, 'completed');+export const dismissByReferenceId = (referenceId) => updateStatusByReferenceId(referenceId, 'dismissed');cosEvents.on('memory:approved', (data) => {if (data?.id) dismissByReferenceId(data.id).catch(err => console.error(`❌ Failed to dismiss approved memory review item: ${err.message}`));@@ -512,37 +536,3 @@ cosEvents.on('memory:approved', (data) => {cosEvents.on('memory:rejected', (data) => {if (data?.id) dismissByReferenceId(data.id).catch(err => console.error(`❌ Failed to dismiss rejected memory review item: ${err.message}`));});--cosEvents.on('task:ready', (data) => {- createItem({- type: 'cos',- title: data?.title ?? data?.description ?? 'CoS action requires review',- description: data?.description ?? '',- metadata: { taskId: data?.id, referenceId: data?.id }- }).catch(err => console.error(`❌ Failed to create review item: ${err.message}`));-});--// When a CoS agent finishes a task, auto-resolve the matching review item so-// the user isn't asked to manually mark something complete that an agent-// already handled. Success → complete; failure stays pending so the user can-// see and act on it.-cosEvents.on('agent:completed', (agent) => {- const taskId = agent?.taskId;- if (!taskId) return;- if (agent.result?.success) {- completeByReferenceId(taskId).catch(err =>- console.error(`❌ Failed to auto-complete review item for task ${taskId}: ${err.message}`)- );- }-});--// When a task is deleted, dismiss any pending review items still pointing at it.-// Otherwise the user is left staring at an orphaned alert for a task that no-// longer exists — and its "Review"/approve action resolves nothing because the-// underlying task is gone. Mirrors the memory:approved/rejected cleanup.-cosEvents.on('tasks:changed', (data) => {- if (data?.action !== 'deleted' || !data?.taskId) return;- dismissByReferenceId(data.taskId).catch(err =>- console.error(`❌ Failed to dismiss review items for deleted task ${data.taskId}: ${err.message}`)- );-});diff --git a/server/services/review.test.js b/server/services/review.test.jsindex 9bcd3413c2..b8fdaa4069 100644--- a/server/services/review.test.js+++ b/server/services/review.test.js@@ -153,6 +153,25 @@ describe('review service', () => {const updated = await dismissItem('1');expect(updated.status).toBe('dismissed');});++ it('rejects generic completion for source-owned obligations', async () => {+ const items = [{+ id: 'memory-review',+ type: 'alert',+ title: 'Approve memory',+ status: 'pending',+ metadata: { category: 'memory-approval', sourceOwned: true },+ createdAt: '',+ updatedAt: '',+ }];+ readFile.mockResolvedValue(JSON.stringify(items));++ await expect(completeItem('memory-review')).rejects.toMatchObject({+ status: 409,+ code: 'SOURCE_ACTION_REQUIRED',+ });+ expect(atomicWrite).not.toHaveBeenCalled();+ });});describe('updateItem', () => {@@ -179,6 +198,22 @@ describe('review service', () => {readFile.mockResolvedValue('[]');await expect(deleteItem('missing')).rejects.toThrow('Review item not found: missing');});++ it('rejects deleting source-owned obligations', async () => {+ readFile.mockResolvedValue(JSON.stringify([{+ id: 'legacy-alert',+ type: 'alert',+ title: 'Needs triage',+ status: 'pending',+ metadata: {},+ }]));++ await expect(deleteItem('legacy-alert')).rejects.toMatchObject({+ status: 409,+ code: 'SOURCE_ACTION_REQUIRED',+ });+ expect(atomicWrite).not.toHaveBeenCalled();+ });});it('keeps archived items editable, dismissible, and deletable through the public service', async () => {@@ -256,6 +291,21 @@ describe('review service', () => {expect(written.find(i => i.id === 'b').status).toBe('pending');});+ it('does not complete source-owned obligations through the bulk path', async () => {+ const items = [+ { id: 'todo', type: 'todo', status: 'pending', metadata: {} },+ { id: 'memory', type: 'alert', status: 'pending', metadata: { category: 'memory-approval', sourceOwned: true } },+ ];+ readFile.mockResolvedValue(JSON.stringify(items));++ const updated = await bulkUpdateStatus({ status: 'completed' });++ expect(updated.map(item => item.id)).toEqual(['todo']);+ const written = atomicWrite.mock.calls[0][1];+ expect(written.find(i => i.id === 'todo').status).toBe('completed');+ expect(written.find(i => i.id === 'memory').status).toBe('pending');+ });+it('skips the write entirely when nothing matches', async () => {const { bulkUpdateStatus } = await import('./review.js');readFile.mockResolvedValue(JSON.stringify([{ id: 'a', status: 'completed', metadata: {} }]));@@ -273,68 +323,10 @@ describe('review service', () => {});describe('cosEvents bridge', () => {- it('auto-completes the matching review item when an agent finishes successfully', async () => {- const handler = registeredHandlers['agent:completed'];- expect(handler).toBeDefined();-- const items = [- { id: 'r1', type: 'cos', status: 'pending', metadata: { referenceId: 'task-42', taskId: 'task-42' } },- { id: 'r2', type: 'cos', status: 'pending', metadata: { referenceId: 'task-99', taskId: 'task-99' } }- ];- readFile.mockResolvedValue(JSON.stringify(items));-- handler({ taskId: 'task-42', result: { success: true } });- // Wait a tick for the async chain inside the handler to flush- await new Promise(r => setImmediate(r));-- const written = atomicWrite.mock.calls[0][1];- const updated = written.find(i => i.id === 'r1');- const untouched = written.find(i => i.id === 'r2');- expect(updated.status).toBe('completed');- expect(untouched.status).toBe('pending');- });-- it('does not auto-complete when the agent failed', async () => {- const handler = registeredHandlers['agent:completed'];- const items = [- { id: 'r1', type: 'cos', status: 'pending', metadata: { referenceId: 'task-42', taskId: 'task-42' } }- ];- readFile.mockResolvedValue(JSON.stringify(items));-- handler({ taskId: 'task-42', result: { success: false, error: 'boom' } });- await new Promise(r => setImmediate(r));-- expect(atomicWrite).not.toHaveBeenCalled();- });-- it('dismisses pending review items when their task is deleted', async () => {- const handler = registeredHandlers['tasks:changed'];- expect(handler).toBeDefined();-- const items = [- { id: 'r1', type: 'cos', status: 'pending', metadata: { referenceId: 'task-42', taskId: 'task-42' } },- { id: 'r2', type: 'cos', status: 'pending', metadata: { referenceId: 'task-99', taskId: 'task-99' } }- ];- readFile.mockResolvedValue(JSON.stringify(items));-- handler({ type: 'user', action: 'deleted', taskId: 'task-42' });- await new Promise(r => setImmediate(r));-- const written = atomicWrite.mock.calls[0][1];- expect(written.find(i => i.id === 'r1').status).toBe('dismissed');- expect(written.find(i => i.id === 'r2').status).toBe('pending');- });-- it('ignores non-deletion task changes', async () => {- const handler = registeredHandlers['tasks:changed'];- readFile.mockResolvedValue(JSON.stringify([- { id: 'r1', type: 'cos', status: 'pending', metadata: { referenceId: 'task-42', taskId: 'task-42' } }- ]));-- handler({ type: 'user', action: 'updated', task: { id: 'task-42' } });- await new Promise(r => setImmediate(r));-- expect(atomicWrite).not.toHaveBeenCalled();+ it('does not auto-resolve task obligations from execution outcomes', () => {+ expect(registeredHandlers['agent:completed']).toBeUndefined();+ expect(registeredHandlers['tasks:changed']).toBeUndefined();+ expect(registeredHandlers['task:ready']).toBeUndefined();});});diff --git a/server/services/reviewActionAdapters.js b/server/services/reviewActionAdapters.jsnew file mode 100644index 0000000000..54254659f1--- /dev/null+++ b/server/services/reviewActionAdapters.js@@ -0,0 +1,223 @@+import { NOTIFICATION_ACTION_POLICY } from '../lib/notificationTypes.js';++const SOURCE_OWNED_REVIEW_CATEGORIES = new Set([+ 'content-review',+ 'goal-fidelity',+ 'memory-approval',+ 'plan-question',+ 'task-approval',+ 'autopilot-paused',+]);++const CONTEXT_ONLY_REVIEW_CATEGORIES = new Set([+ 'client-error',+ 'health-issue',+ 'warning',+]);++const toText = (value) => (typeof value === 'string' ? value.trim() : '');++const toReference = (value) => {+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);+ return toText(value);+};++const severityFor = (value) => {+ const normalized = toText(value).toLowerCase();+ if (['critical', 'high', 'medium', 'low'].includes(normalized)) return normalized;+ if (value === 1 || value === '1') return 'high';+ if (value === 2 || value === '2') return 'medium';+ return 'normal';+};++const operation = (id, label, available = true) => ({+ id,+ label,+ available,+});++export const canonicalActionId = (source, sourceRef) => `${source}:${sourceRef}`;++export const isSourceOwnedReviewItem = (item) => {+ const metadata = item?.metadata && typeof item.metadata === 'object' ? item.metadata : {};+ const category = toText(metadata.category);++ if (metadata.sourceOwned === true || metadata.triageOnly === true) return true;+ if (SOURCE_OWNED_REVIEW_CATEGORIES.has(category)) return true;+ if (item?.type === 'cos' && (toReference(metadata.taskId) || toReference(metadata.referenceId))) {+ return true;+ }+ return item?.type === 'alert';+};++const reviewItemBase = (item, values) => ({+ ...values,+ title: toText(item?.title) || 'Review obligation',+ summary: toText(item?.description) || toText(item?.title),+ timestamp: item?.createdAt,+ severity: severityFor(item?.metadata?.severity ?? item?.metadata?.priority),+ meta: {+ reviewItemId: item?.id,+ ...values.meta,+ },+});++export function adaptStoredReviewItem(item) {+ if (!item || item.status !== 'pending') return null;++ const metadata = item.metadata && typeof item.metadata === 'object' ? item.metadata : {};+ const category = toText(metadata.category);+ const referenceId = toReference(metadata.referenceId);+ const link = toText(metadata.link) || toText(metadata.reportUrl);++ if (category === 'memory-approval' || toReference(metadata.memoryId)) {+ const sourceRef = toReference(metadata.memoryId) || referenceId;+ if (!sourceRef) return null;+ return reviewItemBase(item, {+ id: canonicalActionId('memory', sourceRef),+ sourceRef,+ actionKind: 'memory.approval',+ required: true,+ sourceOwned: true,+ drillTo: link || '/cos/memory',+ operations: [operation('approve', 'Approve'), operation('reject', 'Reject')],+ meta: { category: 'memory-approval' },+ });+ }++ if (category === 'goal-fidelity') {+ const sourceRef = toReference(metadata.agentId) || referenceId;+ if (!sourceRef) return null;+ return reviewItemBase(item, {+ id: canonicalActionId('goal-fidelity', sourceRef),+ sourceRef,+ actionKind: 'goal-fidelity.review',+ required: true,+ sourceOwned: true,+ drillTo: link || `/cos/agents/${encodeURIComponent(sourceRef)}`,+ operations: [operation('review', 'Review', false)],+ meta: { category: 'goal-fidelity' },+ });+ }++ if (category === 'task-approval' || item.type === 'cos') {+ const sourceRef = toReference(metadata.taskId) || referenceId;+ if (!sourceRef) return null;+ return reviewItemBase(item, {+ id: canonicalActionId('cos', sourceRef),+ sourceRef,+ actionKind: 'task.approval',+ required: true,+ sourceOwned: true,+ drillTo: link || '/cos',+ operations: [operation('approve', 'Approve')],+ meta: { category: 'task-approval' },+ });+ }++ if (category === 'plan-question') {+ const sourceRef = toReference(metadata.agentId) || toReference(metadata.appId) || referenceId;+ if (!sourceRef) return null;+ return reviewItemBase(item, {+ id: canonicalActionId('plan', sourceRef),+ sourceRef,+ actionKind: 'plan.question',+ required: true,+ sourceOwned: true,+ drillTo: link || '/cos',+ operations: [operation('review', 'Review', false)],+ meta: { category: 'plan-question' },+ });+ }++ if (category === 'autopilot-paused') {+ const seriesId = toReference(metadata.autopilotPauseSeriesId) || toReference(metadata.seriesId);+ const runId = toReference(metadata.runId);+ const sourceRef = [seriesId, runId].filter(Boolean).join(':');+ if (!sourceRef) return null;+ return reviewItemBase(item, {+ id: canonicalActionId('autopilot', sourceRef),+ sourceRef,+ actionKind: 'autopilot.resume',+ required: true,+ sourceOwned: true,+ drillTo: link || `/pipeline/series/${encodeURIComponent(seriesId)}`,+ operations: [operation('resume', 'Resume', false)],+ meta: { category: 'autopilot-paused' },+ });+ }++ if (CONTEXT_ONLY_REVIEW_CATEGORIES.has(category)) return null;++ if (category === 'content-review' || metadata.contentReview === true || link) {+ if (!referenceId) return null;+ return reviewItemBase(item, {+ id: canonicalActionId('content', referenceId),+ sourceRef: referenceId,+ actionKind: 'content.review',+ required: true,+ sourceOwned: true,+ drillTo: link || '/review',+ operations: [operation('review', 'Review', false)],+ meta: { category: 'content-review' },+ });+ }++ if (item.type !== 'alert') return null;++ const legacyReference = toReference(item.id);+ if (!legacyReference) return null;++ return reviewItemBase(item, {+ id: canonicalActionId('review', legacyReference),+ sourceRef: legacyReference,+ actionKind: 'review.triage',+ required: true,+ sourceOwned: true,+ triageOnly: true,+ drillTo: link || '/review',+ operations: [operation('triage', 'Review', false)],+ meta: { category: 'legacy-review-triage', triage: true },+ });+}++const notificationReference = (notification, policy) => {+ const metadata = notification?.metadata && typeof notification.metadata === 'object'+ ? notification.metadata+ : {};+ const fields = policy.referenceFields ?? [];+ const values = fields.map((field) => toReference(metadata[field])).filter(Boolean);+ if (policy.compoundReference) return values.join(':');+ return values[0] || '';+};++export function adaptNotification(notification) {+ if (!notification || notification.read === true) return null;++ const policy = NOTIFICATION_ACTION_POLICY[notification.type];+ if (!policy) return null;++ const sourceRef = notificationReference(notification, policy);+ const drillTo = toText(notification.link) || toText(policy.fallbackDrillTo);+ if (!sourceRef || !drillTo) return null;++ const operations = policy.operations.map(({ id, label, available }) => operation(id, label, available));+ return {+ id: canonicalActionId(policy.actionSource, sourceRef),+ sourceRef,+ actionKind: policy.actionKind,+ required: policy.required,+ sourceOwned: true,+ title: toText(notification.title) || policy.label,+ summary: toText(notification.description) || toText(notification.message) || toText(notification.title),+ timestamp: notification.timestamp || notification.createdAt,+ severity: severityFor(notification.priority ?? notification.severity),+ drillTo,+ operations,+ meta: {+ notificationId: notification.id,+ category: policy.category,+ actionSource: policy.actionSource,+ },+ };+}diff --git a/server/services/reviewActionAdapters.test.js b/server/services/reviewActionAdapters.test.jsnew file mode 100644index 0000000000..424139e4b7--- /dev/null+++ b/server/services/reviewActionAdapters.test.js@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest';+import { NOTIFICATION_TYPES } from '../lib/notificationTypes.js';+import {+ adaptNotification,+ adaptStoredReviewItem,+ isSourceOwnedReviewItem,+} from './reviewActionAdapters.js';++describe('review action adapters', () => {+ it('adapts memory approval records into explicit source operations', () => {+ const item = adaptStoredReviewItem({+ id: 'review-1',+ type: 'alert',+ title: 'Memory approval',+ description: 'A memory needs approval',+ status: 'pending',+ createdAt: '2026-09-20T00:00:00.000Z',+ metadata: { referenceId: 'memory-1', category: 'memory-approval' },+ });++ expect(item).toMatchObject({+ id: 'memory:memory-1',+ sourceRef: 'memory-1',+ actionKind: 'memory.approval',+ sourceOwned: true,+ operations: [+ { id: 'approve', available: true },+ { id: 'reject', available: true },+ ],+ });+ });++ it('keeps uncorrelated legacy alerts as explicit triage, not generic completion', () => {+ const item = adaptStoredReviewItem({+ id: 'legacy-1',+ type: 'alert',+ title: 'Legacy alert',+ status: 'pending',+ metadata: {},+ });++ expect(item).toMatchObject({+ id: 'review:legacy-1',+ actionKind: 'review.triage',+ triageOnly: true,+ sourceOwned: true,+ operations: [{ id: 'triage', available: false }],+ });+ });++ it('leaves generic client-error alerts in history/context', () => {+ expect(adaptStoredReviewItem({+ id: 'error-1',+ type: 'alert',+ title: 'Client error',+ status: 'pending',+ metadata: { category: 'client-error', referenceId: 'client-error:hash' },+ })).toBeNull();+ });++ it('correlates a memory notification with the same canonical action id', () => {+ const item = adaptNotification({+ id: 'notification-1',+ type: NOTIFICATION_TYPES.MEMORY_APPROVAL,+ title: 'Memory needs approval',+ description: 'Review this memory',+ timestamp: '2026-09-20T00:00:00.000Z',+ link: '/cos/memory',+ metadata: { memoryId: 'memory-1' },+ });++ expect(item).toMatchObject({+ id: 'memory:memory-1',+ sourceRef: 'memory-1',+ required: true,+ operations: [+ { id: 'approve', available: true },+ { id: 'reject', available: true },+ ],+ });+ });++ it('requires a concrete reference and drill-down for actionable notifications', () => {+ expect(adaptNotification({+ id: 'notification-2',+ type: NOTIFICATION_TYPES.PLAN_QUESTION,+ title: 'Plan question',+ message: 'Choose a direction',+ metadata: {},+ })).toBeNull();+ });++ it('marks source-owned alerts as unavailable to generic completion', () => {+ expect(isSourceOwnedReviewItem({+ type: 'alert',+ metadata: { category: 'goal-fidelity' },+ })).toBe(true);+ expect(isSourceOwnedReviewItem({+ type: 'todo',+ metadata: {},+ })).toBe(false);+ });+});diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 529568fcd5..e9287aca3f 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -34,9 +34,12 @@ import * as messageDrafts from './messageDrafts.js';import * as proactiveAlerts from './proactiveAlerts.js';import * as backup from './backup.js';import * as identity from './identity.js';+import * as reviewService from './review.js';+import * as notifications from './notifications.js';import * as stackerNews from './stackerNews.js';import * as x from './x.js';import { promoteLatestAssistantTurn } from './askPromote.js';+import { adaptNotification, adaptStoredReviewItem } from './reviewActionAdapters.js';import { ServerError } from '../lib/errorHandler.js';import { safeJSONParse } from '../lib/fileUtils.js';@@ -60,6 +63,8 @@ const ACTION_KINDS = Object.freeze({x: 'x.review',health: 'health.investigate',backup: 'backup.retry',+ review: 'review.triage',+ notifications: 'notification.action',});const OPERATION_LABELS = Object.freeze({@@ -71,6 +76,8 @@ const OPERATION_LABELS = Object.freeze({x: 'Review',health: 'Investigate',backup: 'Retry',+ review: 'Review',+ notifications: 'Review',});const PRIORITY_ORDER = { HIGH: 0, MEDIUM: 1, LOW: 2 };@@ -125,7 +132,7 @@ const PRODUCERS = [label: 'Brain inbox',drillTo: '/brain/inbox',// Marking the entry done clears it from the needs-review queue.- action: 'Done',+ actionLabel: 'Done',async resolve(id) {return brain.markInboxDone(id);},@@ -192,6 +199,10 @@ const PRODUCERS = [summary: conv.title || '(untitled conversation)',timestamp: conv.updatedAt || conv.createdAt || null,severity: 'normal',+ // Promotion is still available from Ask, but an optional answer is+ // not a required user action in the canonical queue.+ required: false,+ isRecommendation: true,drillTo: `/ask/${conv.id}`,// Only advertise the goal target (and its picker options) when there's// at least one active goal to promote into — an empty picker would be a@@ -205,7 +216,7 @@ const PRODUCERS = [source: 'cos',label: 'CoS approvals',drillTo: '/cos/tasks',- action: 'Approve',+ actionLabel: 'Approve',// approveTask resolves to an `{ error }` object (not a throw) when the task// can't be approved; surface that as a failed resolve.async resolve(id) {@@ -239,7 +250,8 @@ const PRODUCERS = [drillTo: '/messages/drafts',// Approve (not send) — clears it from the awaiting-review queue without an// outward side effect; the user still triggers the actual send from /messages.- action: 'Approve',+ actionLabel: 'Approve',+ actionFor: (draft) => draft.status === 'pending_review',async resolve(id) {return messageDrafts.approveDraft(id);},@@ -273,11 +285,52 @@ const PRODUCERS = [summary: draft.subject || (draft.body || '').slice(0, 120) || '(no subject)',timestamp: draft.updatedAt || draft.createdAt || null,severity: 'normal',+ required: draft.status === 'pending_review',+ isRecommendation: draft.status !== 'pending_review',drillTo: '/messages/drafts',+ nextAction: draft.status === 'pending_review' ? 'Approve' : 'Open draft',...(Object.keys(meta).length ? { meta } : {})};}},+ {+ source: 'review',+ label: 'Stored review obligations',+ drillTo: '/review',+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {+ const pendingItems = await reviewService.getItems({ status: 'pending' });+ const items = (Array.isArray(pendingItems) ? pendingItems : [])+ .map(adaptStoredReviewItem)+ .filter(Boolean);+ return {+ items,+ truncated: items.length > limit,+ };+ },+ map(item) {+ return item;+ },+ },+ {+ source: 'notifications',+ label: 'Actionable notifications',+ drillTo: '/review',+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {+ // Filter before applying the queue cap. A busy history stream must not+ // hide a source-owned approval that happens to be older than it.+ const unread = await notifications.getNotifications({ unreadOnly: true });+ const items = (Array.isArray(unread) ? unread : [])+ .map(adaptNotification)+ .filter(Boolean);+ return {+ items,+ truncated: items.length > limit,+ };+ },+ map(item) {+ return item;+ },+ },{source: 'stacker',label: 'Stacker News approvals',@@ -409,10 +462,16 @@ const isCanonicalScalar = (value) => typeof value === 'string'const firstScalar = (...values) => values.find(isCanonicalScalar) ?? null;-function semanticOperations(producer, mapped) {+function semanticOperations(producer, mapped, raw) {+ if (Array.isArray(mapped.operations)) return mapped.operations;++ const canResolve = Boolean(+ producer.resolve+ && (!producer.actionFor || producer.actionFor(raw)),+ );const operationId = producer.source === 'ask'? 'promote'- : producer.action && producer.resolve+ : canResolve? 'resolve': producer.source === 'health'? 'investigate'@@ -423,7 +482,7 @@ function semanticOperations(producer, mapped) {return [{id: operationId,label: OPERATION_LABELS[producer.source],- available: true,+ available: operationId !== 'investigate' && operationId !== 'retry',...(targets ? { targets } : {}),}];}@@ -431,33 +490,44 @@ function semanticOperations(producer, mapped) {function normalizeQueueItem(producer, raw, mapped) {const prefix = `${producer.source}:`;const sourceRef = firstText(+ mapped.sourceRef,raw?.id == null ? null : String(raw.id),typeof mapped.id === 'string' && mapped.id.startsWith(prefix) ? mapped.id.slice(prefix.length) : null,);const priority = canonicalPriority(raw?.priority);- const required = typeof raw?.required === 'boolean'+ const required = typeof mapped.required === 'boolean'+ ? mapped.required+ : typeof raw?.required === 'boolean'? raw.required: !(raw?.recommendation === true || raw?.isRecommendation === true || raw?.optional === true);const dueAt = firstText(raw?.dueAt, raw?.due, raw?.deadline, raw?.scheduledFor);const revision = firstScalar(raw?.revision, raw?.version, raw?.updatedAt, raw?.updated_at, raw?.capturedAt, raw?.createdAt);const occurrence = firstScalar(raw?.occurrence, raw?.occurrenceId);- const operations = semanticOperations(producer, mapped);+ const operations = semanticOperations(producer, mapped, raw);+ const availableOperation = operations.find((entry) => entry.available)?.label;return {...mapped,sourceRef,- actionKind: ACTION_KINDS[producer.source],+ actionKind: mapped.actionKind || ACTION_KINDS[producer.source],reason: firstText(raw?.reason, mapped.summary, mapped.title),- nextAction: firstText(raw?.nextAction, mapped.action, mapped.promoteTargets?.length ? 'Promote' : null, OPERATION_LABELS[producer.source]),+ nextAction: firstText(+ raw?.nextAction,+ mapped.nextAction,+ mapped.action,+ mapped.promoteTargets?.length ? 'Promote' : null,+ availableOperation,+ OPERATION_LABELS[producer.source],+ ),priority,dueAt,revision,occurrence,required,- isRecommendation: !required,+ isRecommendation: typeof mapped.isRecommendation === 'boolean' ? mapped.isRecommendation : !required,operations,- availability: 'available',- available: true,+ availability: mapped.availability || 'available',+ available: typeof mapped.available === 'boolean' ? mapped.available : true,};}@@ -481,7 +551,10 @@ async function gatherProducer(producer, ctx = {}) {? { promoteTargets: producer.promoteTargets }: {}),...producer.map(item, index, ctx),- ...(producer.action && producer.resolve ? { action: producer.action } : {})+ ...(producer.actionLabel && producer.resolve+ && (!producer.actionFor || producer.actionFor(item))+ ? { action: producer.actionLabel }+ : {})};return normalizeQueueItem(producer, item, mapped);});@@ -545,11 +618,60 @@ export function __resetQueueSnapshots() {* source is unknown, has no inline resolve, or the underlying primitive can't* find the record — so the route surfaces a clean status instead of a 500.*/-export async function resolveQueueItem(queueItemId) {+async function resolveMemoryAction(id, operation) {+ const memory = await import('./memory.js');+ const result = await memory[operation === 'approve' ? 'approveMemory' : 'rejectMemory'](id);+ if (result?.success === false || result?.error) {+ const notFound = /not found/i.test(String(result.error || ''));+ throw new ServerError(result.error || `Memory ${operation} failed`, {+ status: notFound ? 404 : 409,+ code: notFound ? 'NOT_FOUND' : 'CONFLICT',+ });+ }+ return result;+}++async function resolveCosApproval(id) {+ const result = await cosTaskStore.approveTask(id);+ if (result && result.error) throw new ServerError(result.error, { status: 409, code: 'CONFLICT' });+ // Older installs may still have a stored CoS approval row from the former+ // task:ready bridge. The owning approval succeeded, so retire that legacy+ // projection by reference without allowing generic Review completion to+ // mutate the obligation directly.+ await reviewService.dismissByReferenceId(id);+ return result;+}++const SOURCE_ACTIONS = Object.freeze({+ memory: Object.freeze({+ approve: (id) => resolveMemoryAction(id, 'approve'),+ reject: (id) => resolveMemoryAction(id, 'reject'),+ }),+ cos: Object.freeze({+ approve: resolveCosApproval,+ }),+});++export async function resolveQueueItem(queueItemId, operation = 'resolve') {const sep = String(queueItemId).indexOf(':');const source = sep === -1 ? queueItemId : queueItemId.slice(0, sep);const rawId = sep === -1 ? '' : queueItemId.slice(sep + 1);+ if (operation !== 'resolve') {+ const resolver = SOURCE_ACTIONS[source]?.[operation];+ if (!resolver) {+ throw new ServerError(`No ${operation} action for source "${source}"`, {+ status: 400,+ code: 'BAD_REQUEST',+ });+ }+ const result = await resolver(rawId);+ if (result == null) {+ throw new ServerError(`${source} item not found: ${rawId}`, { status: 404, code: 'NOT_FOUND' });+ }+ return { source, id: queueItemId, operation, resolved: true };+ }+const producer = PRODUCERS_BY_SOURCE[source];if (!producer || !producer.resolve) {throw new ServerError(`No inline action for source "${source}"`, { status: 400, code: 'BAD_REQUEST' });diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex 6c98c850e6..d48b8b3085 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -8,6 +8,8 @@ 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() };+const reviewService = { getItems: vi.fn(), dismissByReferenceId: vi.fn() };+const notifications = { getNotifications: 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.@@ -24,6 +26,8 @@ vi.mock('./cosTaskStore.js', () => cosTaskStore);vi.mock('./messageDrafts.js', () => messageDrafts);vi.mock('./proactiveAlerts.js', () => proactiveAlerts);vi.mock('./backup.js', () => backup);+vi.mock('./review.js', () => reviewService);+vi.mock('./notifications.js', () => notifications);vi.mock('./identity.js', () => identity);vi.mock('./askPromote.js', () => askPromote);vi.mock('./stackerNews.js', () => stackerNews);@@ -46,6 +50,8 @@ function resetEmpty() {messageDrafts.listDrafts.mockResolvedValue([]);proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });backup.getState.mockResolvedValue({ status: 'ok', error: null });+ reviewService.getItems.mockResolvedValue([]);+ notifications.getNotifications.mockResolvedValue([]);identity.getGoals.mockResolvedValue({ goals: [] });stackerNews.listPendingReviewActions.mockResolvedValue([]);x.listPendingReviewActions.mockResolvedValue([]);@@ -135,6 +141,7 @@ describe('reviewQueue.buildQueue', () => {expect(askRows).toHaveLength(1);expect(askRows[0].id).toBe('ask:a1');expect(askRows[0].drillTo).toBe('/ask/a1');+ expect(askRows[0]).toMatchObject({ required: false, isRecommendation: true });});it('surfaces drafts and CoS approvals from their producers', async () => {@@ -155,6 +162,72 @@ describe('reviewQueue.buildQueue', () => {const draftRows = queue.items.filter(i => i.source === 'drafts');expect(draftRows).toHaveLength(1);expect(draftRows[0].id).toBe('drafts:d1');+ expect(draftRows[0]).toMatchObject({ required: false, isRecommendation: true, nextAction: 'Open draft' });+ });++ it('adapts stored obligations and notifications, deduplicating only proven references', async () => {+ reviewService.getItems.mockResolvedValue([+ {+ id: 'review-memory',+ type: 'alert',+ title: 'Memory approval',+ description: 'Approve a memory',+ status: 'pending',+ createdAt: '2026-09-20T00:00:00.000Z',+ metadata: { referenceId: 'memory-1', category: 'memory-approval' },+ },+ {+ id: 'legacy-alert',+ type: 'alert',+ title: 'Legacy review alert',+ description: 'Needs triage',+ status: 'pending',+ createdAt: '2026-09-20T00:00:00.000Z',+ metadata: {},+ },+ ]);+ notifications.getNotifications.mockResolvedValue([+ {+ id: 'memory-notification',+ type: 'memory_approval',+ title: 'Memory approval',+ description: 'Same obligation',+ timestamp: '2026-09-20T00:00:00.000Z',+ link: '/cos/memory',+ metadata: { memoryId: 'memory-1' },+ },+ {+ id: 'plan-notification',+ type: 'plan_question',+ title: 'Plan question',+ message: 'Choose a direction',+ timestamp: '2026-09-20T00:00:00.000Z',+ link: '/apps/example/documents',+ metadata: { agentId: 'agent-1' },+ },+ {+ id: 'briefing-notification',+ type: 'briefing_ready',+ title: 'Briefing',+ timestamp: '2026-09-20T00:00:00.000Z',+ metadata: {},+ },+ ]);++ const queue = await buildQueue();++ expect(queue.items.filter(item => item.id === 'memory:memory-1')).toHaveLength(1);+ expect(queue.items.find(item => item.id === 'review:legacy-alert')).toMatchObject({+ actionKind: 'review.triage',+ triageOnly: true,+ });+ expect(queue.items.find(item => item.id === 'plan:agent-1')).toMatchObject({+ source: 'notifications',+ actionKind: 'plan.question',+ summary: 'Choose a direction',+ operations: [{ id: 'review', available: false }],+ });+ expect(queue.items.find(item => item.id === 'briefing:briefing-notification')).toBeUndefined();});it('only surfaces critical/high health alerts and a failed backup', async () => {@@ -518,6 +591,14 @@ describe('reviewQueue.resolveQueueItem', () => {expect(messageDrafts.approveDraft).toHaveBeenCalledWith('d1');});+ it('dispatches explicit source operations through the owning service', async () => {+ cosTaskStore.approveTask.mockResolvedValue({ id: 'sys-1', approvalRequired: false });+ const result = await resolveQueueItem('cos:sys-1', 'approve');+ expect(cosTaskStore.approveTask).toHaveBeenCalledWith('sys-1');+ expect(reviewService.dismissByReferenceId).toHaveBeenCalledWith('sys-1');+ expect(result).toMatchObject({ source: 'cos', id: 'cos:sys-1', operation: 'approve', resolved: true });+ });+it('preserves colons in the raw id (splits on the first only)', async () => {brain.markInboxDone.mockResolvedValue({ id: 'b:1:2', status: 'done' });await resolveQueueItem('brain:b:1:2');