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: add review queue action contract and snapshots (#7737)

[._.]/ Adam Eivy45a8c9d89d94
diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.js
index c3686f9523..ec3ef0b314 100644
--- a/client/src/services/apiReview.js
+++ b/client/src/services/apiReview.js
@@ -1,4 +1,4 @@
-import { request } from './apiCore.js';
+import { request, queryString } from './apiCore.js';
// Review Hub
export const getReviewItems = (params) => {
@@ -10,8 +10,13 @@ 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)
-export const getReviewQueue = (options = {}) => request('/review/queue', options);
+// Cross-domain live queue (brain inbox, ask, CoS approvals, drafts, health, backups).
+// 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', {
method: 'POST',
diff --git a/client/src/services/apiReview.test.js b/client/src/services/apiReview.test.js
new file mode 100644
index 0000000000..fa80a5eec7
--- /dev/null
+++ b/client/src/services/apiReview.test.js
@@ -0,0 +1,41 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./apiCore.js', () => ({
+ request: vi.fn(),
+ queryString: (params = {}) => {
+ const query = new URLSearchParams();
+ for (const [key, value] of Object.entries(params)) {
+ if (value !== undefined && value !== null && value !== '') query.set(key, String(value));
+ }
+ const encoded = query.toString();
+ return encoded ? `?${encoded}` : '';
+ },
+}));
+
+let request;
+let getReviewQueue;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ request } = await import('./apiCore.js'));
+ ({ getReviewQueue } = await import('./apiReview.js'));
+ request.mockReset();
+});
+
+describe('getReviewQueue', () => {
+ it('encodes pagination in the query while preserving request options', async () => {
+ request.mockResolvedValue({ items: [] });
+
+ await getReviewQueue({ limit: 25, cursor: 'snapshot/page', silent: true });
+
+ expect(request).toHaveBeenCalledWith('/review/queue?limit=25&cursor=snapshot%2Fpage', { silent: true });
+ });
+
+ it('keeps the legacy options-only call query-free', async () => {
+ request.mockResolvedValue({ items: [] });
+
+ await getReviewQueue({ silent: true });
+
+ expect(request).toHaveBeenCalledWith('/review/queue', { silent: true });
+ });
+});
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 099042c308..f423bb04e4 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -67,7 +67,7 @@ Submit tasks, manage durable autonomous agents, schedule recurring automations,
| **Persistent Mind** | `/cos/mind` | Resident long-term conversational AI agent with persistent context memory, annotation support, and continuous system oversight. | [Agent Tools (MCP)](./agent-context.md), [Memory System](./memory-system.md) |
| **Mind Tools Governance** | `/cos/mind?panel=tools` | Fine-grained tool permission controls, MCP context disclosure settings (metadata-only vs redacted summaries), and semantic action grants. | [Agent Tools (MCP)](./agent-context.md), [Agent Skills](./agent-skills.md) |
| **Feature Agents** | `/feature-agents` | Durable, specialized agents assigned to specific feature domains or managed codebases. | — |
-| **Review Hub** | `/review` | Centralized triage inbox for agent-generated diffs, pull request reviews, approval requests, and code quality findings. | — |
+| **Review Hub** | `/review` | Centralized triage inbox for agent-generated diffs, pull request reviews, approval requests, and code quality findings. | [Review Queue Contract](./review-queue.md) |
| **Social Agents** | `/agents` | Autonomous agent personas for managing external social communications and community presence. | — |
| **AI Providers & Model Runner** | `/ai` | Multi-provider configuration supporting CLI agents (Claude Code, Codex, Antigravity, OpenCode), cloud APIs (OpenAI, Anthropic, Gemini, Grok), and local endpoints (Ollama, LM Studio, vLLM, SGLang). | [Claude on Ollama](./claude-ollama.md) |
| **Prompt Manager** | `/prompts` | Reusable prompt template library, variable substitution engine, prompt versioning, and auto-upgrade migrations. | [Prompt Manager](./prompt-manager.md) |
diff --git a/docs/features/review-queue.md b/docs/features/review-queue.md
new file mode 100644
index 0000000000..fc99e17b8b
--- /dev/null
+++ b/docs/features/review-queue.md
@@ -0,0 +1,64 @@
+# Review Queue Contract
+
+The Review Hub's cross-domain queue is a live projection of producer-owned
+records. It is not a durable universal task store, and it does not make an AI
+provider call. Source records remain authoritative for mutations and detail
+views.
+
+## Response envelope
+
+`GET /api/review/queue` without query parameters keeps the legacy full-list
+response. `?limit=<1..100>` opts into the canonical envelope and a short-lived
+snapshot:
+
+```json
+{
+ "items": [],
+ "total": 0,
+ "totalsBySource": {},
+ "sources": {},
+ "nextCursor": null,
+ "partial": false
+}
+```
+
+The response also carries the compatibility `counts`, `generatedAt`, and row
+fields already consumed by the Review Hub. `total` and each
+`totalsBySource` value are `null` when a source failed or its bounded read was
+truncated. `partial` is true in either case; an unavailable source must never
+be represented as an empty, healthy inbox.
+
+Each source descriptor includes `availability`, `available`, `error`,
+`truncation`, `lowerBound`, `total`, and `shown`. A numeric lower bound counts
+the unique rows collected from that source in the snapshot.
+
+## Canonical rows
+
+Rows retain the legacy `id`, `source`, `sourceLabel`, `title`, `summary`,
+`timestamp`, `severity`, `drillTo`, and mutation fields. New consumers can use
+the additive fields `sourceRef`, `actionKind`, `reason`, `nextAction`,
+`priority`, `dueAt`, `revision`, `occurrence`, `required`,
+`isRecommendation`, `operations`, and `availability`.
+
+`operations` contains only semantic, allowlisted descriptors such as
+`resolve`, `promote`, `review`, `investigate`, or `retry`; it never exposes a
+producer URL or arbitrary command. The existing route-specific mutation
+consumers remain the authority for executing those operations.
+
+Rows are deduplicated before totals and page slicing, then ordered by required
+work, severity, overdue/due time, priority, and stable row ID. Optional
+recommendations therefore remain below required work even when they are newer.
+
+## Snapshot and producer extension points
+
+The first paginated request reads each producer once and stores a process-local
+snapshot for 30 seconds. `nextCursor` is opaque: pass it back unchanged, with
+the same query, until it becomes `null`. An invalid, changed, or expired cursor
+returns an explicit error so the caller can restart from the first page.
+
+To add a producer, keep its source identity and mutation primitive in the
+producer registry, map its raw record through the canonical row projection,
+bound the upstream read, and report whether the bound was filled. Add a source
+descriptor and operation to this document and cover the healthy, failed, and
+truncated paths at the queue boundary. Do not add a second durable task store
+or invoke an LLM as part of queue assembly.
diff --git a/server/lib/apiOperationContracts.js b/server/lib/apiOperationContracts.js
index 3e33dd77f6..13137f2b6e 100644
--- a/server/lib/apiOperationContracts.js
+++ b/server/lib/apiOperationContracts.js
@@ -33,6 +33,21 @@ export const API_OPERATION_CONTRACTS = Object.freeze({
'/api/api-docs/tools.min.json': {
get: { summary: 'Read minimized semantic tool resource', responses: { 200: { description: 'Schema-optimized provider-neutral tool resource' } } },
},
+ '/api/review/queue': {
+ get: {
+ summary: 'Read the cross-domain review action queue',
+ description: 'Returns the canonical action projection. Passing limit opts into a short-lived snapshot; echo nextCursor unchanged for the next page. A null total means one or more sources are unavailable or bounded.',
+ parameters: [
+ { name: 'limit', in: 'query', required: false, schema: { type: 'integer', minimum: 1, maximum: 100 } },
+ { name: 'cursor', in: 'query', required: false, schema: { type: 'string', maxLength: 4096 } },
+ ],
+ responses: {
+ 200: { description: 'Canonical action rows, per-source health, totals, and an optional snapshot cursor' },
+ 400: { description: 'Invalid query or cursor', 'x-portos-error-codes': ['VALIDATION_ERROR', 'INVALID_CURSOR', 'CURSOR_QUERY_MISMATCH'] },
+ 409: { description: 'The short-lived snapshot expired and pagination must restart', 'x-portos-error-codes': ['CURSOR_EXPIRED'] },
+ },
+ },
+ },
'/api/agent-context/manifest': {
get: { summary: 'Read local Agent Tools MCP manifest', responses: { 200: { description: 'MCP transport, context scopes, semantic grants, schemas, and limits' } } },
},
diff --git a/server/lib/validation.js b/server/lib/validation.js
index dde51e8d25..3e2bf84892 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1771,6 +1771,14 @@ export const agentActivityCleanupSchema = z.object({
daysToKeep: z.coerce.number().int().min(1).max(3650).default(30),
}).strict();
+// GET /api/review/queue — pagination is opt-in so existing Review Hub clients
+// keep receiving the legacy full-list envelope. Cursors are opaque and bounded
+// before they reach the queue snapshot decoder.
+export const reviewQueueQuerySchema = z.object({
+ limit: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).max(100).optional()),
+ cursor: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(4096).optional()),
+}).strict();
+
// =============================================================================
// CLIENT ERROR REPORT
// =============================================================================
diff --git a/server/routes/review.js b/server/routes/review.js
index 758293d63f..cb7c2ed070 100644
--- a/server/routes/review.js
+++ b/server/routes/review.js
@@ -1,7 +1,7 @@
import express from 'express';
import { z } from 'zod';
import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
+import { reviewQueueQuerySchema, validateRequest } from '../lib/validation.js';
import * as reviewService from '../services/review.js';
import { buildQueue, resolveQueueItem, promoteAskQueueItem } from '../services/reviewQueue.js';
@@ -44,7 +44,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)
router.get('/queue', asyncHandler(async (req, res) => {
- const queue = await buildQueue();
+ const { limit, cursor } = validateRequest(reviewQueueQuerySchema, req.query);
+ const queue = await buildQueue({ limit, cursor, query: {} });
res.json(queue);
}));
diff --git a/server/routes/review.test.js b/server/routes/review.test.js
new file mode 100644
index 0000000000..1f3ab4b9ec
--- /dev/null
+++ b/server/routes/review.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const buildQueue = vi.fn();
+const resolveQueueItem = vi.fn();
+const promoteAskQueueItem = vi.fn();
+
+vi.mock('../services/review.js', () => ({}));
+vi.mock('../services/reviewQueue.js', () => ({
+ buildQueue,
+ resolveQueueItem,
+ promoteAskQueueItem,
+}));
+
+const { default: routes } = await import('./review.js');
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/review', routes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('GET /api/review/queue', () => {
+ it('passes the requested page through without reapplying the old source cap', async () => {
+ const items = Array.from({ length: 40 }, (_, index) => ({ id: `brain:b${index}` }));
+ buildQueue.mockResolvedValue({
+ items,
+ total: 40,
+ totalsBySource: { brain: 40 },
+ sources: { brain: { total: 40, shown: 40, availability: 'available', error: null, truncation: false } },
+ nextCursor: null,
+ partial: false,
+ });
+
+ const response = await request(makeApp()).get('/api/review/queue?limit=40');
+
+ expect(response.status).toBe(200);
+ expect(response.body.items).toHaveLength(40);
+ expect(buildQueue).toHaveBeenCalledWith({ limit: 40, cursor: undefined, query: {} });
+ });
+
+ it('rejects invalid pagination before the queue service is called', async () => {
+ const response = await request(makeApp()).get('/api/review/queue?limit=0');
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('VALIDATION_ERROR');
+ expect(buildQueue).not.toHaveBeenCalled();
+ });
+
+ it('forwards an opaque cursor unchanged for the next snapshot page', async () => {
+ buildQueue.mockResolvedValue({ items: [], total: 0, totalsBySource: {}, sources: {}, nextCursor: null, partial: false });
+
+ const response = await request(makeApp()).get('/api/review/queue?cursor=opaque-token');
+
+ expect(response.status).toBe(200);
+ expect(buildQueue).toHaveBeenCalledWith({ limit: undefined, cursor: 'opaque-token', query: {} });
+ });
+});
diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.js
index 0cc56a73f3..33a4dd6ff0 100644
--- a/server/services/reviewQueue.js
+++ b/server/services/reviewQueue.js
@@ -8,10 +8,12 @@
* persisted here — so the queue always reflects live state.
*
* Each producer is gathered independently and defensively: a single producer
- * throwing (or its data file being absent) degrades that one source to empty
- * rather than sinking the whole queue. Every row is normalized to:
+ * throwing (or its data file being absent) degrades that one source to an
+ * unavailable projection rather than sinking the whole queue. Every row keeps
+ * the legacy fields and adds a canonical action projection:
*
- * { id, source, sourceLabel, title, summary, timestamp, severity, drillTo }
+ * { id, source, sourceRef, actionKind, title, reason, nextAction,
+ * severity, priority, dueAt, revision, occurrence, operations }
*
* `drillTo` is a client route the UI deep-links to so "drill-down" works without
* the queue needing to know how to render each domain.
@@ -24,6 +26,7 @@
* retries by re-running with settings) stay drill-down + session-dismiss only.
*/
+import { randomUUID } from 'node:crypto';
import * as brain from './brain.js';
import * as askConversations from './askConversations.js';
import * as cosTaskStore from './cosTaskStore.js';
@@ -35,10 +38,41 @@ import * as stackerNews from './stackerNews.js';
import * as x from './x.js';
import { promoteLatestAssistantTurn } from './askPromote.js';
import { ServerError } from '../lib/errorHandler.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
-// Per-source cap so one noisy producer can't flood the queue; the UI shows a
-// "+N more in <domain>" affordance via the per-source `total` vs `items.length`.
-const PER_SOURCE_LIMIT = 25;
+// Producers are read with a bounded upper limit. The queue reports a lower
+// bound, rather than pretending that a full count is known, when a producer
+// fills this window. Pagination then slices the normalized snapshot, not a
+// fresh set of source reads, so adjacent pages cannot reorder underneath a
+// caller.
+export const REVIEW_QUEUE_SOURCE_READ_LIMIT = 100;
+export const REVIEW_QUEUE_MAX_PAGE_SIZE = 100;
+const REVIEW_QUEUE_SNAPSHOT_TTL_MS = 30_000;
+const REVIEW_QUEUE_MAX_SNAPSHOTS = 100;
+
+const ACTION_KINDS = Object.freeze({
+ brain: 'brain.classify',
+ ask: 'ask.promote',
+ cos: 'cos.approve',
+ drafts: 'message.approve',
+ stacker: 'stacker.review',
+ x: 'x.review',
+ health: 'health.investigate',
+ backup: 'backup.retry',
+});
+
+const OPERATION_LABELS = Object.freeze({
+ brain: 'Done',
+ ask: 'Promote',
+ cos: 'Approve',
+ drafts: 'Approve',
+ stacker: 'Review',
+ x: 'Review',
+ health: 'Investigate',
+ backup: 'Retry',
+});
+
+const PRIORITY_ORDER = { HIGH: 0, MEDIUM: 1, LOW: 2 };
// generateAlerts() runs a full system-health sweep (CPU/disk/PM2/goals/usage),
// so cache it briefly — the Review Hub can be polled, and a stale-by-seconds
@@ -94,10 +128,10 @@ const PRODUCERS = [
async resolve(id) {
return brain.markInboxDone(id);
},
- async gather() {
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
// Inbox entries the auto-classifier couldn't place — they need a human
// to pick a destination.
- return brain.getInboxLog({ status: 'needs_review', limit: PER_SOURCE_LIMIT * 2 });
+ return brain.getInboxLog({ status: 'needs_review', limit });
},
map(entry) {
const text = (entry.capturedText || '').trim();
@@ -128,15 +162,18 @@ const PRODUCERS = [
// inline via `promoteTargets` + `goalOptions`: brain/task in one click and
// goal via a picker (see map() below). Drilling into /ask still works for a
// per-turn promote the queue's latest-turn shortcut doesn't cover.
- async gather() {
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
// Conversations with a promotable assistant answer that haven't been
// promoted to brain/task/goal. Gate on assistantTurnCount, NOT turnCount:
// an Ask conversation whose stream errored (or whose client disconnected)
// before the assistant turn persisted still has the user turn (turnCount
// > 0), but promoteLatestAssistantTurn would fail with NO_ASSISTANT_TURN —
// so advertising a promote action on it would be a dead-end button.
- const convs = await askConversations.listConversations({ limit: PER_SOURCE_LIMIT * 2 });
- return convs.filter(c => !c.promoted && (c.assistantTurnCount || 0) > 0);
+ const convs = await askConversations.listConversations({ limit });
+ return {
+ items: (Array.isArray(convs) ? convs : []).filter(c => !c.promoted && (c.assistantTurnCount || 0) > 0),
+ truncated: Array.isArray(convs) && convs.length >= limit,
+ };
},
// 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
@@ -243,8 +280,8 @@ const PRODUCERS = [
source: 'stacker',
label: 'Stacker News approvals',
drillTo: '/stacker-news',
- async gather() {
- return stackerNews.listPendingReviewActions({ limit: PER_SOURCE_LIMIT * 2 });
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
+ return stackerNews.listPendingReviewActions({ limit });
},
map(action) {
return {
@@ -262,8 +299,8 @@ const PRODUCERS = [
source: 'x',
label: 'X drafts',
drillTo: '/x',
- async gather() {
- return x.listPendingReviewActions({ limit: PER_SOURCE_LIMIT * 2 });
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
+ return x.listPendingReviewActions({ limit });
},
map(draft) {
return {
@@ -360,27 +397,145 @@ const SEVERITY_ORDER = { critical: 0, high: 1, normal: 2 };
* `goal` only when goals exist), so the map result is spread AFTER the
* producer-level default.
*/
+const canonicalPriority = (value) =>
+ typeof value === 'string' && Object.hasOwn(PRIORITY_ORDER, value) ? value : null;
+
+const firstText = (...values) => values.find((value) => typeof value === 'string' && value.trim())?.trim() || null;
+
+const isCanonicalScalar = (value) => typeof value === 'string'
+ || (typeof value === 'number' && Number.isFinite(value));
+
+const firstScalar = (...values) => values.find(isCanonicalScalar) ?? null;
+
+function semanticOperations(producer, mapped) {
+ const operationId = producer.source === 'ask'
+ ? 'promote'
+ : producer.action && producer.resolve
+ ? 'resolve'
+ : producer.source === 'health'
+ ? 'investigate'
+ : producer.source === 'backup'
+ ? 'retry'
+ : 'review';
+ const targets = Array.isArray(mapped.promoteTargets) ? mapped.promoteTargets : null;
+ return [{
+ id: operationId,
+ label: OPERATION_LABELS[producer.source],
+ available: true,
+ ...(targets ? { targets } : {}),
+ }];
+}
+
+function normalizeQueueItem(producer, raw, mapped) {
+ const prefix = `${producer.source}:`;
+ const sourceRef = firstText(
+ 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'
+ ? 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);
+
+ return {
+ ...mapped,
+ sourceRef,
+ 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]),
+ priority,
+ dueAt,
+ revision,
+ occurrence,
+ required,
+ isRecommendation: !required,
+ operations,
+ availability: 'available',
+ available: true,
+ };
+}
+
+/**
+ * Gather one producer into normalized rows. A producer may return either an
+ * array or `{ items, truncated }` when it filtered a bounded upstream read.
+ * Totals are nullable whenever the read filled its bound: the collected rows
+ * are a lower bound, not evidence that the source is exhausted.
+ */
async function gatherProducer(producer, ctx = {}) {
- const raw = await producer.gather();
- const list = Array.isArray(raw) ? raw : [];
- const items = list.slice(0, PER_SOURCE_LIMIT).map((item, index) => ({
- source: producer.source,
- sourceLabel: producer.label,
- // Producer-level default promote targets — the row's map() may override
- // this (Ask adds `goal` + `goalOptions` when active goals exist).
- ...(Array.isArray(producer.promoteTargets) && producer.promoteTargets.length
- ? { promoteTargets: producer.promoteTargets }
- : {}),
- ...producer.map(item, index, ctx),
- // 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 } : {})
- }));
- return { items, total: list.length };
+ const gathered = await producer.gather(REVIEW_QUEUE_SOURCE_READ_LIMIT);
+ const descriptor = Array.isArray(gathered) ? { items: gathered } : gathered;
+ const rawItems = Array.isArray(descriptor?.items) ? descriptor.items : [];
+ const truncated = descriptor?.truncated === true || rawItems.length >= REVIEW_QUEUE_SOURCE_READ_LIMIT;
+ const list = rawItems.slice(0, REVIEW_QUEUE_SOURCE_READ_LIMIT);
+ const items = list.map((item, index) => {
+ const mapped = {
+ source: producer.source,
+ sourceLabel: producer.label,
+ ...(Array.isArray(producer.promoteTargets) && producer.promoteTargets.length
+ ? { promoteTargets: producer.promoteTargets }
+ : {}),
+ ...producer.map(item, index, ctx),
+ ...(producer.action && producer.resolve ? { action: producer.action } : {})
+ };
+ return normalizeQueueItem(producer, item, mapped);
+ });
+ return {
+ items,
+ total: truncated ? null : list.length,
+ lowerBound: list.length,
+ truncation: truncated,
+ };
}
const PRODUCERS_BY_SOURCE = Object.fromEntries(PRODUCERS.map(p => [p.source, p]));
+const queueSnapshots = new Map();
+
+const stableQueryValue = (value) => {
+ if (Array.isArray(value)) return value.map(stableQueryValue);
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(Object.entries(value)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, child]) => [key, stableQueryValue(child)]));
+ }
+ return value;
+};
+
+const queryKeyFor = (query = {}) => JSON.stringify(stableQueryValue(query));
+
+const invalidCursor = (message = 'Invalid review queue cursor') => {
+ throw new ServerError(message, { status: 400, code: 'INVALID_CURSOR' });
+};
+
+function encodeQueueCursor(snapshotId, offset) {
+ return Buffer.from(JSON.stringify({ v: 1, snapshotId, offset }), 'utf8').toString('base64url');
+}
+
+function decodeQueueCursor(cursor) {
+ const decoded = Buffer.from(String(cursor), 'base64url').toString('utf8');
+ const payload = safeJSONParse(decoded, null, { allowArray: false });
+ if (!payload || payload.v !== 1 || typeof payload.snapshotId !== 'string' || !payload.snapshotId
+ || !Number.isSafeInteger(payload.offset) || payload.offset < 0) {
+ invalidCursor();
+ }
+ return payload;
+}
+
+function pruneQueueSnapshots(now = Date.now()) {
+ for (const [id, snapshot] of queueSnapshots) {
+ if (snapshot.expiresAt <= now) queueSnapshots.delete(id);
+ }
+}
+
+// Test seam: snapshots are intentionally process-local and short-lived.
+export function __resetQueueSnapshots() {
+ queueSnapshots.clear();
+}
+
/**
* Accept/promote a single queue row in place. `queueItemId` is the row's
* normalized id (`<source>:<rawId>`); we split on the FIRST colon so raw ids
@@ -442,13 +597,56 @@ export async function promoteAskQueueItem(queueItemId, target, goalId) {
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
- * per-source `total` (pre-cap) + `error` so the UI can show "+N more" and flag
- * a source that failed to load.
- */
-export async function buildQueue() {
+const validDateMs = (value) => {
+ const parsed = Date.parse(value || '');
+ return Number.isFinite(parsed) ? parsed : null;
+};
+
+function compareQueueItems(a, b, now = Date.now()) {
+ const required = Number(Boolean(b.required)) - Number(Boolean(a.required));
+ if (required !== 0) return required;
+
+ const severity = (SEVERITY_ORDER[a.severity] ?? 2) - (SEVERITY_ORDER[b.severity] ?? 2);
+ if (severity !== 0) return severity;
+
+ const dueA = validDateMs(a.dueAt);
+ const dueB = validDateMs(b.dueAt);
+ const dueBucket = (due) => due === null ? 2 : due < now ? 0 : 1;
+ const dueClass = dueBucket(dueA) - dueBucket(dueB);
+ if (dueClass !== 0) return dueClass;
+ if (dueA !== null && dueB !== null && dueA !== dueB) return dueA - dueB;
+
+ const priority = (PRIORITY_ORDER[a.priority] ?? 3) - (PRIORITY_ORDER[b.priority] ?? 3);
+ if (priority !== 0) return priority;
+
+ return String(a.id || '').localeCompare(String(b.id || ''));
+}
+
+function deduplicateItems(items) {
+ const byId = new Map();
+ for (const item of items) {
+ const previous = byId.get(item.id);
+ if (!previous || compareQueueItems(item, previous) < 0) byId.set(item.id, item);
+ }
+ return [...byId.values()];
+}
+
+function queueCounts(items) {
+ const counts = { total: items.length, critical: 0, high: 0 };
+ for (const item of items) {
+ if (item.severity === 'critical') counts.critical++;
+ else if (item.severity === 'high') counts.high++;
+ }
+ return counts;
+}
+
+function sourceShownCounts(items) {
+ const shown = {};
+ for (const item of items) shown[item.source] = (shown[item.source] || 0) + 1;
+ return shown;
+}
+
+async function gatherFullQueue() {
// Fetch active goals once (not per Ask row) so the goal picker on Ask rows
// has targets. A failure here degrades to no goal targets, not a sunk queue.
const goalOptions = await getActiveGoalOptions();
@@ -456,36 +654,149 @@ export async function buildQueue() {
const results = await Promise.all(PRODUCERS.map(async (producer) => {
return gatherProducer(producer, ctx)
- .then(r => ({ source: producer.source, label: producer.label, ...r, error: null }))
- .catch(err => {
- console.error(`❌ Review queue: ${producer.source} source failed: ${err.message}`);
- return { source: producer.source, label: producer.label, items: [], total: 0, error: err.message };
+ .then((result) => ({ source: producer.source, label: producer.label, ...result, error: null }))
+ .catch((err) => {
+ const message = String(err?.message || err || 'Source read failed').slice(0, 300);
+ console.error(`❌ Review queue: ${producer.source} source failed: ${message}`);
+ return {
+ source: producer.source,
+ label: producer.label,
+ items: [],
+ total: null,
+ lowerBound: 0,
+ truncation: false,
+ error: message,
+ };
});
}));
- const items = results.flatMap(r => r.items);
-
- items.sort((a, b) => {
- const sev = (SEVERITY_ORDER[a.severity] ?? 2) - (SEVERITY_ORDER[b.severity] ?? 2);
- if (sev !== 0) return sev;
- return new Date(b.timestamp || 0) - new Date(a.timestamp || 0);
- });
-
+ const items = deduplicateItems(results.flatMap((result) => result.items));
+ items.sort((a, b) => compareQueueItems(a, b));
+ const shownCounts = sourceShownCounts(items);
const sources = {};
- for (const r of results) {
- sources[r.source] = { label: r.label, total: r.total, shown: r.items.length, error: r.error };
- }
+ const totalsBySource = {};
- const counts = { total: items.length, critical: 0, high: 0 };
- for (const i of items) {
- if (i.severity === 'critical') counts.critical++;
- else if (i.severity === 'high') counts.high++;
+ for (const result of results) {
+ const shown = shownCounts[result.source] || 0;
+ const knownTotal = result.error === null && !result.truncation && Number.isSafeInteger(result.total)
+ ? shown
+ : null;
+ totalsBySource[result.source] = knownTotal;
+ sources[result.source] = {
+ label: result.label,
+ total: knownTotal,
+ shown,
+ error: result.error,
+ availability: result.error ? 'unavailable' : 'available',
+ available: !result.error,
+ truncation: Boolean(result.truncation),
+ lowerBound: result.error ? 0 : shown,
+ };
}
+ const partial = results.some((result) => result.error || result.truncation);
return {
items,
- counts,
+ total: partial ? null : items.length,
+ totalsBySource,
sources,
- generatedAt: new Date().toISOString()
+ nextCursor: null,
+ partial,
+ counts: queueCounts(items),
+ generatedAt: new Date().toISOString(),
+ };
+}
+
+function pageSources(sources, pageItems) {
+ const shown = sourceShownCounts(pageItems);
+ return Object.fromEntries(Object.entries(sources).map(([source, descriptor]) => [source, {
+ ...descriptor,
+ shown: shown[source] || 0,
+ }]));
+}
+
+function pageFromSnapshot(snapshot, offset) {
+ if (offset > snapshot.items.length) invalidCursor('Review queue cursor offset is outside the snapshot');
+ const items = snapshot.items.slice(offset, offset + snapshot.pageSize);
+ const nextOffset = offset + items.length;
+ return {
+ items,
+ total: snapshot.total,
+ totalsBySource: snapshot.totalsBySource,
+ sources: pageSources(snapshot.sources, items),
+ nextCursor: nextOffset < snapshot.items.length ? encodeQueueCursor(snapshot.id, nextOffset) : null,
+ partial: snapshot.partial,
+ counts: queueCounts(items),
+ generatedAt: snapshot.generatedAt,
};
}
+
+function validatePageSize(limit) {
+ if (limit === undefined || limit === null) return null;
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > REVIEW_QUEUE_MAX_PAGE_SIZE) {
+ throw new ServerError(`Review queue limit must be an integer from 1 to ${REVIEW_QUEUE_MAX_PAGE_SIZE}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+ return limit;
+}
+
+function saveQueueSnapshot(queue, queryKey, pageSize) {
+ const now = Date.now();
+ pruneQueueSnapshots(now);
+ while (queueSnapshots.size >= REVIEW_QUEUE_MAX_SNAPSHOTS) {
+ queueSnapshots.delete(queueSnapshots.keys().next().value);
+ }
+ const id = randomUUID();
+ queueSnapshots.set(id, {
+ id,
+ ...queue,
+ pageSize,
+ queryKey,
+ expiresAt: now + REVIEW_QUEUE_SNAPSHOT_TTL_MS,
+ });
+ return queueSnapshots.get(id);
+}
+
+/**
+ * Build the cross-domain review queue. A request without pagination parameters
+ * retains the original full-list response. Passing `limit` opts into a
+ * short-lived process-local snapshot with an opaque offset cursor.
+ */
+export async function buildQueue({ limit, cursor, query = {} } = {}) {
+ const requestedLimit = validatePageSize(limit);
+ const queryKey = queryKeyFor(query);
+
+ if (cursor !== undefined && cursor !== null) {
+ const payload = decodeQueueCursor(cursor);
+ pruneQueueSnapshots();
+ const snapshot = queueSnapshots.get(payload.snapshotId);
+ if (!snapshot || snapshot.expiresAt <= Date.now()) {
+ queueSnapshots.delete(payload.snapshotId);
+ throw new ServerError('Review queue snapshot expired; restart pagination', {
+ status: 409,
+ code: 'CURSOR_EXPIRED',
+ });
+ }
+ if (snapshot.queryKey !== queryKey) {
+ throw new ServerError('Review queue query changed; restart pagination', {
+ status: 400,
+ code: 'CURSOR_QUERY_MISMATCH',
+ });
+ }
+ if (requestedLimit !== null && requestedLimit !== snapshot.pageSize) {
+ throw new ServerError('Review queue page size changed; restart pagination', {
+ status: 400,
+ code: 'CURSOR_QUERY_MISMATCH',
+ });
+ }
+ return pageFromSnapshot(snapshot, payload.offset);
+ }
+
+ const queue = await gatherFullQueue();
+ if (requestedLimit === null) return queue;
+
+ const snapshot = saveQueueSnapshot(queue, queryKey, requestedLimit);
+ return pageFromSnapshot(snapshot, 0);
+}
diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.js
index c32e5cc60d..f8e2436e21 100644
--- a/server/services/reviewQueue.test.js
+++ b/server/services/reviewQueue.test.js
@@ -1,7 +1,7 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock every producer service the aggregator pulls from, so the test exercises
-// only the normalization / sort / cap / degrade-on-failure logic.
+// only the normalization / sort / bounded-read / snapshot / degrade-on-failure logic.
const brain = { getInboxLog: vi.fn(), markInboxDone: vi.fn() };
const askConversations = { listConversations: vi.fn() };
const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn() };
@@ -29,7 +29,7 @@ vi.mock('./askPromote.js', () => askPromote);
vi.mock('./stackerNews.js', () => stackerNews);
vi.mock('./x.js', () => x);
-const { buildQueue, resolveQueueItem, promoteAskQueueItem, __resetAlertsCache } = await import('./reviewQueue.js');
+const { buildQueue, resolveQueueItem, promoteAskQueueItem, __resetAlertsCache, __resetQueueSnapshots } = await import('./reviewQueue.js');
// Default: every producer returns "nothing needs attention".
function resetEmpty() {
@@ -51,6 +51,12 @@ describe('reviewQueue.buildQueue', () => {
// The alerts sweep is cached with a TTL; clear it so each case sees its
// own generateAlerts mock rather than a prior case's cached result.
__resetAlertsCache();
+ __resetQueueSnapshots();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ __resetQueueSnapshots();
});
it('returns an empty queue when nothing needs attention', async () => {
@@ -70,7 +76,20 @@ describe('reviewQueue.buildQueue', () => {
sourceLabel: 'Brain inbox',
title: 'Inbox item needs classification',
summary: 'classify me',
- drillTo: '/brain/inbox'
+ drillTo: '/brain/inbox',
+ sourceRef: 'b1',
+ actionKind: 'brain.classify',
+ reason: 'classify me',
+ nextAction: 'Done',
+ priority: null,
+ dueAt: null,
+ revision: '2026-06-03T10:00:00.000Z',
+ occurrence: null,
+ required: true,
+ isRecommendation: false,
+ operations: [{ id: 'resolve', label: 'Done', available: true }],
+ availability: 'available',
+ available: true,
});
});
@@ -200,13 +219,33 @@ describe('reviewQueue.buildQueue', () => {
expect(queue.items.map(i => i.id)).toEqual(['brain:b1']);
});
- it('sorts by severity then recency', async () => {
+ it('sorts required work by severity, then due time, priority, and stable ID', async () => {
brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'normal', capturedAt: '2026-06-03T12:00:00.000Z' }]);
proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'disk:primary', type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps', timestamp: '2026-06-03T01:00:00.000Z' }] });
const queue = await buildQueue();
- // critical alert sorts ahead of the (newer) normal brain item
+ // critical alert sorts ahead of the normal brain item.
expect(queue.items[0].severity).toBe('critical');
expect(queue.counts.critical).toBe(1);
+
+ const past = new Date(Date.now() - 60_000).toISOString();
+ const future = new Date(Date.now() + 60_000).toISOString();
+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });
+ brain.getInboxLog.mockResolvedValue([
+ { id: 'optional', capturedText: 'optional', required: false, dueAt: past },
+ { id: 'required-low', capturedText: 'low', required: true, dueAt: future, priority: 'LOW' },
+ { id: 'required-high-b', capturedText: 'high b', required: true, dueAt: future, priority: 'HIGH' },
+ { id: 'required-overdue', capturedText: 'overdue', required: true, dueAt: past, priority: 'LOW' },
+ { id: 'required-high-a', capturedText: 'high a', required: true, dueAt: future, priority: 'HIGH' },
+ ]);
+ __resetAlertsCache();
+ const ordered = await buildQueue();
+ expect(ordered.items.map((item) => item.id)).toEqual([
+ 'brain:required-overdue',
+ 'brain:required-high-a',
+ 'brain:required-high-b',
+ 'brain:required-low',
+ 'brain:optional',
+ ]);
});
it('treats a producer returning null/non-array as empty', async () => {
@@ -223,18 +262,89 @@ describe('reviewQueue.buildQueue', () => {
messageDrafts.listDrafts.mockResolvedValue([{ id: 'd1', status: 'draft', subject: 'still here' }]);
const queue = await buildQueue();
expect(queue.sources.brain.error).toBe('inbox boom');
+ expect(queue.sources.brain.availability).toBe('unavailable');
+ expect(queue.sources.brain.total).toBeNull();
+ expect(queue.totalsBySource.brain).toBeNull();
+ expect(queue.total).toBeNull();
+ expect(queue.partial).toBe(true);
expect(queue.items.find(i => i.source === 'drafts')).toBeTruthy();
});
- it('caps each source and reports the pre-cap total', async () => {
+ it('returns every row within the bounded source read and reports its total', async () => {
brain.getInboxLog.mockResolvedValue(
Array.from({ length: 40 }, (_, i) => ({ id: `b${i}`, capturedText: `t${i}`, capturedAt: '2026-06-03T10:00:00.000Z' }))
);
const queue = await buildQueue();
const brainRows = queue.items.filter(i => i.source === 'brain');
- expect(brainRows).toHaveLength(25);
+ expect(brainRows).toHaveLength(40);
expect(queue.sources.brain.total).toBe(40);
- expect(queue.sources.brain.shown).toBe(25);
+ expect(queue.sources.brain.shown).toBe(40);
+ expect(queue.sources.brain.truncation).toBe(false);
+ });
+
+ it('keeps page order stable when a source changes between cursor requests', async () => {
+ const firstRows = Array.from({ length: 5 }, (_, i) => ({
+ id: `b${i}`,
+ capturedText: `row ${i}`,
+ capturedAt: '2026-06-03T10:00:00.000Z',
+ }));
+ brain.getInboxLog.mockResolvedValue(firstRows);
+ const first = await buildQueue({ limit: 2 });
+ expect(first.items.map((item) => item.id)).toEqual(['brain:b0', 'brain:b1']);
+ expect(first.total).toBe(5);
+ expect(first.nextCursor).toBeTruthy();
+
+ brain.getInboxLog.mockResolvedValue([{ id: 'new', capturedText: 'changed source' }]);
+ const second = await buildQueue({ limit: 2, cursor: first.nextCursor });
+ expect(second.items.map((item) => item.id)).toEqual(['brain:b2', 'brain:b3']);
+ expect(brain.getInboxLog).toHaveBeenCalledTimes(1);
+
+ const third = await buildQueue({ cursor: second.nextCursor });
+ expect(third.items.map((item) => item.id)).toEqual(['brain:b4']);
+ expect(third.nextCursor).toBeNull();
+ });
+
+ it('rejects malformed, changed, and expired cursors explicitly', async () => {
+ await expect(buildQueue({ cursor: 'not-a-cursor' })).rejects.toMatchObject({
+ status: 400,
+ code: 'INVALID_CURSOR',
+ });
+
+ brain.getInboxLog.mockResolvedValue([
+ { id: 'b1', capturedText: 'one' },
+ { id: 'b2', capturedText: 'two' },
+ ]);
+ const first = await buildQueue({ limit: 1, query: { source: 'brain' } });
+ await expect(buildQueue({ cursor: first.nextCursor, query: { source: 'ask' } })).rejects.toMatchObject({
+ status: 400,
+ code: 'CURSOR_QUERY_MISMATCH',
+ });
+
+ vi.useFakeTimers({ now: Date.now() });
+ const expiring = await buildQueue({ limit: 1 });
+ vi.advanceTimersByTime(30_001);
+ await expect(buildQueue({ cursor: expiring.nextCursor })).rejects.toMatchObject({
+ status: 409,
+ code: 'CURSOR_EXPIRED',
+ });
+ });
+
+ it('marks a bounded source as partial instead of claiming inbox zero', async () => {
+ brain.getInboxLog.mockResolvedValue(
+ Array.from({ length: 100 }, (_, i) => ({ id: `b${i}`, capturedText: `t${i}` }))
+ );
+ const queue = await buildQueue({ limit: 10 });
+ expect(brain.getInboxLog).toHaveBeenCalledWith({ status: 'needs_review', limit: 100 });
+ expect(queue.partial).toBe(true);
+ expect(queue.total).toBeNull();
+ expect(queue.totalsBySource.brain).toBeNull();
+ expect(queue.sources.brain).toMatchObject({
+ total: null,
+ lowerBound: 100,
+ truncation: true,
+ availability: 'available',
+ error: null,
+ });
});
it('tags resolvable rows with an inline action verb, leaves no-clean-resolve sources without one', async () => {