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: persist review queue triage state (#7741)
[._.]/ Adam Eivy587fe7893149
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsxindex 34f47e903c..954b2e040f 100644--- a/client/src/pages/Review.jsx+++ b/client/src/pages/Review.jsx@@ -108,6 +108,19 @@ const ACTION_VIEWS = [];const ACTION_VIEW_IDS = new Set(ACTION_VIEWS.map(({ id }) => id));+const QUEUE_SNOOZE_OPTIONS = [+ { value: 60 * 60 * 1000, label: '1 hour' },+ { value: 24 * 60 * 60 * 1000, label: '1 day' },+ { value: 7 * 24 * 60 * 60 * 1000, label: '1 week' },+];++const queueItemKey = (itemOrId) => {+ if (itemOrId && typeof itemOrId === 'object') {+ return JSON.stringify([itemOrId.id || '', itemOrId.occurrence ?? '', itemOrId.revision ?? '']);+ }+ return JSON.stringify([itemOrId || '', '', '']);+};+const SOURCE_OWNED_REVIEW_CATEGORIES = new Set(['content-review','goal-fidelity',@@ -155,10 +168,9 @@ export default function Review() {const [counts, setCounts] = useState(null);const countsRequestId = useRef(0);- // Cross-domain live queue (M42 P5). These rows are derived live from each- // producer, not stored, so "dismiss" is a per-session client-side hide rather- // than a server mutation. Rows whose producer declares an inline action also- // get a server-backed accept/promote that resolves the underlying record.+ // Cross-domain live queue (M42 P5). Source payloads remain live projections;+ // presentation decisions are durable server-side markers keyed by the row's+ // canonical action identity, occurrence, and revision.const [queue, setQueue] = useState(null);const [dismissedQueueIds, setDismissedQueueIds] = useState(() => new Set());// Rows with an inline accept/promote in flight — disables the button so a@@ -282,10 +294,11 @@ export default function Review() {const handleMarkAllRead = () => api.bulkUpdateReviewStatus({ status: 'dismissed' }).catch(() => null);const handleCompleteAll = () => api.bulkUpdateReviewStatus({ status: 'completed' }).catch(() => null);- const handleQueueDismiss = (id) => {+ const handleQueueDismiss = (itemOrId) => {+ const key = queueItemKey(itemOrId);setDismissedQueueIds(prev => {const next = new Set(prev);- next.add(id);+ next.add(key);return next;});};@@ -315,7 +328,26 @@ export default function Review() {// matters for status views: a completed commitment must disappear from// Today but remain reachable in History.if (ok) {- handleQueueDismiss(item.id);+ handleQueueDismiss(item);+ await fetchQueue();+ if (actionId === item.id) navigate(`/review?view=${actionView}`, { replace: true });+ }+ return ok;+ };++ const handleQueueTriage = async (item, operation, input = {}) => {+ if (resolvingQueueIds.has(item.id)) return false;+ setResolvingQueueIds(prev => new Set(prev).add(item.id));+ const ok = await api.triageReviewQueueItem(item.id, { operation, ...input })+ .then(() => true)+ .catch(() => false);+ setResolvingQueueIds(prev => {+ const next = new Set(prev);+ next.delete(item.id);+ return next;+ });+ if (ok) {+ handleQueueDismiss(item);await fetchQueue();if (actionId === item.id) navigate(`/review?view=${actionView}`, { replace: true });}@@ -335,7 +367,7 @@ export default function Review() {// Reactive removal — drop the promoted row in place, then refresh the// source-backed queue so counts and partial-source metadata stay truthful.if (ok) {- handleQueueDismiss(item.id);+ handleQueueDismiss(item);await fetchQueue();}};@@ -364,7 +396,7 @@ export default function Review() {}, {}), [visibleItems]);const queueItems = useMemo(- () => (queue?.items || []).filter(i => !dismissedQueueIds.has(i.id)),+ () => (queue?.items || []).filter(i => !dismissedQueueIds.has(queueItemKey(i))),[queue, dismissedQueueIds]);const queueSourceErrors = useMemo(() => Object.entries(queue?.sources || {}).filter(([, s]) => s.error),@@ -495,9 +527,9 @@ export default function Review() {item={item}onSelect={handleQueueSelect}onDrill={handleQueueDrill}- onDismiss={handleQueueDismiss}onResolve={handleQueueResolve}onPromoteAsk={handleQueuePromoteAsk}+ onTriage={handleQueueTriage}resolving={resolvingQueueIds.has(item.id)}/>))}@@ -654,6 +686,8 @@ export default function Review() {item={selectedAction}onClose={() => navigate(`/review?view=${actionView}`, { replace: true })}onResolve={handleQueueResolve}+ onTriage={handleQueueTriage}+ triagePending={Boolean(actionId && resolvingQueueIds.has(actionId))}onSaved={fetchQueue}onDrill={handleQueueDrill}/>@@ -790,7 +824,69 @@ function FeedbackRatingControls({ id, onSubmit, disabled = false, options = ['po);}-function QueueRow({ item, onSelect, onDrill, onDismiss, onResolve, onPromoteAsk, resolving = false }) {+function QueueTriageControls({ item, onTriage, disabled = false }) {+ const operations = Array.isArray(item?.triageOperations)+ ? item.triageOperations.filter((operation) => operation?.available !== false)+ : [];+ if (!onTriage || operations.length === 0) return null;++ const hasOperation = (id) => operations.some((operation) => operation.id === id);+ const snooze = (event) => {+ const duration = Number(event.target.value);+ event.target.value = '';+ if (!Number.isFinite(duration) || duration <= 0) return;+ onTriage(item, 'snooze', { snoozedUntil: new Date(Date.now() + duration).toISOString() });+ };++ return (+ <div className="inline-flex items-center gap-2 flex-wrap">+ {hasOperation('snooze') && (+ <label className="inline-flex items-center">+ <span className="sr-only">Snooze {item.title}</span>+ <select+ defaultValue=""+ aria-label={`Snooze ${item.title}`}+ onChange={snooze}+ disabled={disabled}+ className="min-h-[36px] rounded-md border border-port-warning/30 bg-port-warning/10 px-2 py-1 text-xs font-medium text-port-warning transition-colors hover:bg-port-warning/20 focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent disabled:cursor-not-allowed disabled:opacity-40"+ title="Snooze this action"+ >+ <option value="">Snooze…</option>+ {QUEUE_SNOOZE_OPTIONS.map((option) => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>+ </label>+ )}+ {hasOperation('unsnooze') && (+ <button+ type="button"+ onClick={() => onTriage(item, 'unsnooze')}+ disabled={disabled}+ className="inline-flex min-h-[36px] items-center gap-1 rounded-md border border-port-warning/30 bg-port-warning/10 px-2 py-1 text-xs font-medium text-port-warning transition-colors hover:bg-port-warning/20 disabled:cursor-not-allowed disabled:opacity-40"+ title="Show this action again"+ >+ <Clock3 size={13} />+ Unsnooze+ </button>+ )}+ {hasOperation('dismiss') && (+ <button+ type="button"+ onClick={() => onTriage(item, 'dismiss')}+ disabled={disabled}+ className="min-h-[36px] min-w-[36px] inline-flex items-center justify-center rounded-md border border-port-border px-2 py-1 text-gray-500 transition-colors hover:border-port-warning/40 hover:text-port-warning disabled:cursor-not-allowed disabled:opacity-40"+ title="Dismiss this recommendation"+ aria-label="Dismiss this recommendation"+ >+ <X size={15} />+ </button>+ )}+ </div>+ );+}++function QueueRow({ item, onSelect, onDrill, onResolve, onPromoteAsk, onTriage, resolving = false }) {const config = QUEUE_SOURCE_CONFIG[item.source] || { icon: Inbox, color: 'text-gray-400' };const Icon = config.icon;const borderTone = QUEUE_SEVERITY_STYLE[item.severity] || QUEUE_SEVERITY_STYLE.normal;@@ -893,20 +989,15 @@ function QueueRow({ item, onSelect, onDrill, onDismiss, onResolve, onPromoteAsk,</select></label>)}+ <QueueTriageControls item={item} onTriage={onTriage} disabled={resolving} /><button+ type="button"onClick={() => onDrill(item)}className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1.5 text-gray-500 hover:text-port-accent transition-colors"title="Open" aria-label="Open"><ArrowRight size={16} /></button>- <button- onClick={() => 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"- title="Dismiss from queue (this session)" aria-label="Dismiss from queue (this session)"- >- <X size={16} />- </button></div></div>);@@ -1099,7 +1190,7 @@ const threadDraft = (record) => ({notes: record?.notes || '',});-function ActionDetail({ item, onClose, onResolve, onSaved, onDrill }) {+function ActionDetail({ item, onClose, onResolve, onTriage, triagePending = false, onSaved, onDrill }) {const isThread = item?.source === 'threads';const isTodo = item?.source === 'todo';const [record, setRecord] = useState(item);@@ -1263,6 +1354,16 @@ function ActionDetail({ item, onClose, onResolve, onSaved, onDrill }) {</section>)}+ <QueueTriageControls+ item={item}+ onTriage={async (...args) => {+ const ok = await onTriage?.(...args);+ if (ok) onClose();+ return ok;+ }}+ disabled={triagePending}+ />+{item.drillTo && (<button type="button" onClick={() => { onClose(); onDrill(item); }} className="inline-flex items-center gap-2 text-sm text-port-accent hover:underline"><ExternalLink size={14} /> Open source editordiff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsxindex 2904bd242e..b43b172e60 100644--- a/client/src/pages/Review.test.jsx+++ b/client/src/pages/Review.test.jsx@@ -73,6 +73,18 @@ const FEEDBACK_ITEM = {}],};+const TRIAGE_RECOMMENDATION = {+ id: 'ask:conversation-example',+ source: 'ask',+ sourceLabel: 'Ask answers',+ title: 'Optional answer ready',+ summary: 'A recommendation to triage',+ triageOperations: [+ { id: 'snooze', label: 'Snooze', available: true },+ { id: 'dismiss', label: 'Dismiss', available: true },+ ],+};+vi.mock('../services/api', () => ({getReviewItems: vi.fn(() => Promise.resolve([ITEM, SHORT_ITEM, COMPLETED_ITEM])),getReviewCounts: vi.fn(),@@ -87,6 +99,7 @@ vi.mock('../services/api', () => ({updateReviewItem: vi.fn(() => Promise.resolve({})),bulkUpdateReviewStatus: vi.fn(() => Promise.resolve({})),resolveReviewQueueItem: vi.fn(() => Promise.resolve({})),+ triageReviewQueueItem: vi.fn(() => Promise.resolve({})),promoteAskReviewQueueItem: vi.fn(() => Promise.resolve({})),normalizeBrainScanReportPath: vi.fn((p) => p)}));@@ -216,6 +229,33 @@ describe('Review Hub queue-card triage (#3282)', () => {));});+ it('shows durable snooze and recommendation-dismiss controls', async () => {+ api.getReviewQueue.mockResolvedValueOnce({ items: [TRIAGE_RECOMMENDATION], sources: {} });++ render(<Review />);+ const snooze = await screen.findByRole('combobox', { name: 'Snooze Optional answer ready' });+ expect(screen.getByRole('button', { name: 'Dismiss this recommendation' })).toBeInTheDocument();++ fireEvent.change(snooze, { target: { value: String(60 * 60 * 1000) } });++ await waitFor(() => expect(api.triageReviewQueueItem).toHaveBeenCalledWith(+ TRIAGE_RECOMMENDATION.id,+ { operation: 'snooze', snoozedUntil: expect.any(String) },+ ));+ });++ it('persists dismissal only for an optional recommendation', async () => {+ api.getReviewQueue.mockResolvedValueOnce({ items: [TRIAGE_RECOMMENDATION], sources: {} });++ render(<Review />);+ fireEvent.click(await screen.findByRole('button', { name: 'Dismiss this recommendation' }));++ await waitFor(() => expect(api.triageReviewQueueItem).toHaveBeenCalledWith(+ TRIAGE_RECOMMENDATION.id,+ { operation: 'dismiss' },+ ));+ });+it('requires a rating before sending the source-owned feedback action', async () => {api.getReviewQueue.mockResolvedValueOnce({ items: [FEEDBACK_ITEM], sources: {} });diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.jsindex 629ad89ac8..25f12a4570 100644--- a/client/src/services/apiReview.js+++ b/client/src/services/apiReview.js@@ -31,6 +31,17 @@ export const resolveReviewQueueItem = (id, { operation, rating, comment, ...opti}),...options});+// Persist a presentation-only queue decision. The server re-reads the source+// row, so the client supplies only the row id and the selected operation/time.+export const triageReviewQueueItem = (id, { operation, snoozedUntil, ...options } = {}) => request('/review/queue/triage', {+ method: 'POST',+ body: JSON.stringify({+ id,+ operation,+ ...(snoozedUntil ? { snoozedUntil } : {}),+ }),+ ...options+});// Promote an Ask row's latest assistant answer into Brain, a CoS task, or a// Goal's progress in place (id is `ask:<conversationId>`, target is// 'brain' | 'task' | 'goal'; goalId is required for the 'goal' target).diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex dcfbd59705..b21ee5d99e 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -7,7 +7,7 @@ PortOS backs up two things together, into a single timestamped snapshot:Now that PostgreSQL is a **required** dependency (it owns the creative catalog, memory, and a growing set of app-native records — see [Storage Classification Contract](./STORAGE.md)), **the database dump is part of required system state, not an optional extra.** A snapshot that captured `data/` but failed to capture the DB is incomplete, and PortOS surfaces that explicitly.-The dump includes the machine-local `cos_pending_agent_feedback` reference index. Its source agent archive and metadata remain in the filesystem half of the same snapshot, so restoring both halves preserves pending feedback without exporting it through federation.+The dump includes the machine-local `cos_pending_agent_feedback` reference index and `review_queue_triage` presentation markers. The queue's source records remain in their owning stores; restoring the dump therefore preserves snooze/dismissal decisions without exporting them through federation or duplicating source payloads.Implementation: `server/services/backup.js` (snapshot/dump/restore), `server/services/backupScheduler.js` (cron), `server/routes/backup.js` (API), and `server/routes/database.js` (DB export/sync).diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex cce78e9103..9c91b68e46 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -37,6 +37,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `memories` / `memory_links` — long-term memory + pgvector similarity.- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and this ledger has no cross-machine merge contract. This is a store-specific implementation boundary, not a ban on syncing personal records to the user's own machines (ADR [user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).+- `review_queue_triage` — the Review Hub's machine-local presentation markers: canonical `action_key` plus `occurrence`/`revision`, `snoozed_until`, optional recommendation `dismissed`, and a delivery `generation` marker reserved for the delivery layer. It contains no queue title, summary, prompt, source payload, or notification-read state; the live producer remains authoritative and a new occurrence/revision gets a fresh presentation decision. **Intentionally machine-local — never federated**, including when the source row is a federated Brain record. PostgreSQL is authoritative and the normal `pg_dump` captures it; the JSON adapter exists only for the documented dev/test file escape hatch. Adapter: `server/services/reviewQueueTriageStore.js`.- `cos_pending_agent_feedback` — a bounded, machine-local index of completed manual CoS runs that still need a human rating. It stores only `agent_id` plus the archive date locator; the agent archive remains the source-owned record and the rating is removed from this index only after that archive carries the durable rating. PostgreSQL is authoritative in normal installs (with the documented file backend only for dev/test), the input-gated migration 008 derives existing refs from live state without a seed or provider call, and future completion events enroll new refs. **Intentionally machine-local — never federated**; the DB dump backs it up alongside the agent archive under the filesystem snapshot. Adapter: `server/services/cosAgentFeedbackStore.js`.- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.diff --git a/docs/features/review-queue.md b/docs/features/review-queue.mdindex 611088e70d..df06b97233 100644--- a/docs/features/review-queue.md+++ b/docs/features/review-queue.md@@ -45,6 +45,14 @@ the additive fields `sourceRef`, `actionKind`, `reason`, `nextAction`,producer URL or arbitrary command. The existing route-specific mutationconsumers remain the authority for executing those operations.+The queue may also include `triage` and `triageOperations`. `triage` contains+only `snoozedUntil`, `dismissed`, and `deliveryGeneration`; the latter is kept+separate from notification-read state for the delivery layer. `snooze` and+`unsnooze` change presentation only, while `dismiss` is advertised only for+`isRecommendation` rows. A triage mutation re-reads the source and rejects+unavailable sources or unsupported capabilities before writing the local+marker.+Source-owned rows may also carry `sourceOwned: true` and `triageOnly: true`.Generic Review completion rejects those rows; an explicit source operationmust revalidate the owning record at mutation time. A row withdiff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 4c0fee62c8..1ed2b184ae 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -29,6 +29,7 @@ init-db.sql, each with a one-line reason.| `post.js` | `postDdl` | MeatSpace POST normalized runs and attempts (machine-local) || `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) || `userActions.js` | `userActionsDdl` | Operator-action ledger — what the human did in the UI (machine-local) |+| `reviewQueueTriage.js` | `reviewQueueTriageDdl` | Machine-local Review Hub presentation markers — snooze, optional dismissal, and delivery generation keyed by canonical action identity || `cosAgentFeedback.js` | `cosAgentFeedbackDdl` | Durable machine-local references to completed manual CoS runs awaiting a rating (agent id + archive locator only) || `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types |@@ -46,7 +47,7 @@ init-db.sql, each with a one-line reason.### Composer (`index.js`)-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `cosAgentFeedback` → `aiGraph`).+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `aiGraph`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →`beeper` → `audit` DDL → audit triggers).diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.jsindex 9a7595a669..dba171fb96 100644--- a/server/lib/db/schema/index.js+++ b/server/lib/db/schema/index.js@@ -19,6 +19,7 @@ import { humanActivityDdl } from './humanActivity.js';import { postDdl } from './post.js';import { commissionsDdl } from './commissions.js';import { userActionsDdl } from './userActions.js';+import { reviewQueueTriageDdl } from './reviewQueueTriage.js';import { cosAgentFeedbackDdl } from './cosAgentFeedback.js';import { aiGraphDdl } from './aiGraph.js';import { catalogDdl, catalogUserTypesDdl } from './catalog.js';@@ -43,6 +44,7 @@ export {postDdl,commissionsDdl,userActionsDdl,+ reviewQueueTriageDdl,cosAgentFeedbackDdl,aiGraphDdl,catalogDdl,@@ -75,6 +77,7 @@ export function buildUpgradeDdl() {...postDdl,...commissionsDdl,...userActionsDdl,+ ...reviewQueueTriageDdl,...cosAgentFeedbackDdl,...aiGraphDdl,];diff --git a/server/lib/db/schema/reviewQueueTriage.js b/server/lib/db/schema/reviewQueueTriage.jsnew file mode 100644index 0000000000..28f48fe7a2--- /dev/null+++ b/server/lib/db/schema/reviewQueueTriage.js@@ -0,0 +1,14 @@+// Machine-local Review Hub presentation state. The queue remains a live+// projection of source-owned records; this table stores only the user's+// presentation decisions, never a copy of a source payload.+export const reviewQueueTriageDdl = [+ `CREATE TABLE IF NOT EXISTS review_queue_triage (+ action_key TEXT NOT NULL,+ occurrence TEXT NOT NULL DEFAULT '',+ revision TEXT NOT NULL DEFAULT '',+ snoozed_until TIMESTAMPTZ,+ dismissed BOOLEAN NOT NULL DEFAULT FALSE,+ delivery_generation INTEGER NOT NULL DEFAULT 0 CHECK (delivery_generation >= 0),+ PRIMARY KEY (action_key, occurrence, revision)+ )`,+];diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex e16608d400..f7eaf2ce93 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -25,7 +25,7 @@ import {} from './index.js';const DOMAIN_ARRAYS = [- 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'cosAgentFeedbackDdl', 'aiGraphDdl',+ 'coreDdl', 'tribeDdl', 'humanActivityDdl', 'postDdl', 'commissionsDdl', 'userActionsDdl', 'reviewQueueTriageDdl', 'cosAgentFeedbackDdl', 'aiGraphDdl','catalogDdl', 'catalogUserTypesDdl', 'mediaDdl', 'universesDdl','libraryDdl', 'pipelineDdl', 'writersRoomDdl', 'loraDdl', 'privacyDdl', 'stackerNewsDdl', 'xDdl','beeperDdl', 'mindToolRecipesDdl',@@ -48,6 +48,7 @@ describe('db/schema barrel + composer (#2832)', () => {...schema.postDdl,...schema.commissionsDdl,...schema.userActionsDdl,+ ...schema.reviewQueueTriageDdl,...schema.cosAgentFeedbackDdl,...schema.aiGraphDdl,];diff --git a/server/routes/review.js b/server/routes/review.jsindex 9e1ed0b825..f84e640317 100644--- a/server/routes/review.js+++ b/server/routes/review.js@@ -3,7 +3,7 @@ import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { reviewQueueQuerySchema, validateRequest } from '../lib/validation.js';import * as reviewService from '../services/review.js';-import { buildQueue, resolveQueueItem, promoteAskQueueItem } from '../services/reviewQueue.js';+import { buildQueue, resolveQueueItem, triageQueueItem, promoteAskQueueItem } from '../services/reviewQueue.js';const router = express.Router();@@ -76,6 +76,27 @@ router.post('/queue/resolve', asyncHandler(async (req, res) => {res.json(result);}));+const triageQueueSchema = z.object({+ id: z.string().min(1).max(500),+ operation: z.enum(['snooze', 'unsnooze', 'dismiss']),+ snoozedUntil: z.string().datetime().optional(),+}).superRefine((value, context) => {+ if (value.operation === 'snooze' && !value.snoozedUntil) {+ context.addIssue({ code: z.ZodIssueCode.custom, path: ['snoozedUntil'], message: 'snoozedUntil is required for the snooze operation' });+ }+ if (value.operation !== 'snooze' && value.snoozedUntil !== undefined) {+ context.addIssue({ code: z.ZodIssueCode.custom, path: ['snoozedUntil'], message: 'snoozedUntil is only valid for the snooze operation' });+ }+});++// POST /api/review/queue/triage — persist a presentation-only decision after+// the queue service re-reads the source and its current capabilities.+router.post('/queue/triage', asyncHandler(async (req, res) => {+ const { id, operation, snoozedUntil } = validateRequest(triageQueueSchema, req.body);+ const result = await triageQueueItem(id, operation, snoozedUntil ? { snoozedUntil } : {});+ res.json(result);+}));+const promoteAskQueueSchema = z.object({id: z.string().min(1).max(500),target: z.enum(['brain', 'task', 'goal']),diff --git a/server/routes/review.test.js b/server/routes/review.test.jsindex 0305579a7e..bc2251a8c0 100644--- a/server/routes/review.test.js+++ b/server/routes/review.test.js@@ -5,12 +5,14 @@ import { errorMiddleware } from '../lib/errorHandler.js';const buildQueue = vi.fn();const resolveQueueItem = vi.fn();+const triageQueueItem = vi.fn();const promoteAskQueueItem = vi.fn();vi.mock('../services/review.js', () => ({}));vi.mock('../services/reviewQueue.js', () => ({buildQueue,resolveQueueItem,+ triageQueueItem,promoteAskQueueItem,}));@@ -105,3 +107,31 @@ describe('POST /api/review/queue/resolve', () => {);});});++describe('POST /api/review/queue/triage', () => {+ it('validates the snooze timestamp and forwards it to the queue service', async () => {+ const snoozedUntil = '2099-01-01T00:00:00.000Z';+ triageQueueItem.mockResolvedValue({ id: 'brain:b1', operation: 'snooze', triaged: true });++ const response = await request(makeApp())+ .post('/api/review/queue/triage')+ .send({ id: 'brain:b1', operation: 'snooze', snoozedUntil });++ expect(response.status).toBe(200);+ expect(triageQueueItem).toHaveBeenCalledWith('brain:b1', 'snooze', { snoozedUntil });+ });++ it('requires a timestamp for snooze and rejects timestamps on other operations', async () => {+ const missing = await request(makeApp())+ .post('/api/review/queue/triage')+ .send({ id: 'brain:b1', operation: 'snooze' });+ expect(missing.status).toBe(400);+ expect(triageQueueItem).not.toHaveBeenCalled();++ const extra = await request(makeApp())+ .post('/api/review/queue/triage')+ .send({ id: 'ask:a1', operation: 'dismiss', snoozedUntil: '2099-01-01T00:00:00.000Z' });+ expect(extra.status).toBe(400);+ expect(triageQueueItem).not.toHaveBeenCalled();+ });+});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 5be79de7e1..7e4a28f212 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -246,6 +246,19 @@ CREATE INDEX IF NOT EXISTS idx_user_action_happened ON user_action_events (happeCREATE INDEX IF NOT EXISTS idx_user_action_type_time ON user_action_events (type, happened_at DESC);CREATE INDEX IF NOT EXISTS idx_user_action_actor_time ON user_action_events (actor, happened_at DESC);+-- Machine-local Review Hub presentation markers. Queue payloads remain owned by+-- their source records; this table stores only keyed snooze/dismissal state and+-- a delivery-generation marker reserved for the delivery layer.+CREATE TABLE IF NOT EXISTS review_queue_triage (+ action_key TEXT NOT NULL,+ occurrence TEXT NOT NULL DEFAULT '',+ revision TEXT NOT NULL DEFAULT '',+ snoozed_until TIMESTAMPTZ,+ dismissed BOOLEAN NOT NULL DEFAULT FALSE,+ delivery_generation INTEGER NOT NULL DEFAULT 0 CHECK (delivery_generation >= 0),+ PRIMARY KEY (action_key, occurrence, revision)+);+-- Machine-local CoS feedback obligations. Only the completed agent id and its-- archive date-bucket locator are retained here; prose and ratings stay with-- the source agent record and this table never enters federation payloads.diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 846b96ccc4..86ac7cda1f 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -4,8 +4,8 @@* Where review.js manages *stored* review items (todos/alerts/briefing/cos that* producers push in via cosEvents), this module *live-pulls* the things across* PortOS that are currently waiting on the user and normalizes them into one- * list. It reads each producer's existing service on demand — nothing is- * persisted here — so the queue always reflects live state.+ * list. It reads each producer's existing service on demand; only separate+ * presentation markers are persisted, so source payloads remain live state.** Each producer is gathered independently and defensively: a single producer* throwing (or its data file being absent) degrades that one source to an@@ -23,7 +23,8 @@* accept/promote it in place without leaving the Review Hub (issue #709 follow-up* to the v1 read-only aggregator). Sources with no clean local resolve (health* alerts are live-computed and clear when the condition does; a failed backup- * retries by re-running with settings) stay drill-down + session-dismiss only.+ * retries by re-running with settings) stay drill-down plus capability-aware+ * presentation triage.*/import { randomUUID } from 'node:crypto';@@ -45,6 +46,7 @@ import { adaptNotification, adaptStoredReviewItem } from './reviewActionAdaptersimport { ServerError } from '../lib/errorHandler.js';import { safeJSONParse } from '../lib/fileUtils.js';import { getUserTimezone } from './userTimezone.js';+import * as reviewQueueTriageStore from './reviewQueueTriageStore.js';import { todayInTimezone } from '../lib/timezone.js';import { isTerminalThreadStatus, threadNextLine } from '../lib/brainThreads.js';@@ -740,6 +742,72 @@ function normalizeQueueItem(producer, raw, mapped) {};}+/**+ * The queue row id is a projection identity. Triage needs the source's+ * canonical action kind/reference plus occurrence and revision so a later+ * occurrence of the same source record is not hidden by an older decision.+ */+export function queueActionIdentity(item) {+ const actionKind = firstText(item?.actionKind, item?.source) || 'review';+ const sourceRef = firstText(item?.sourceRef, item?.id) || '';+ return {+ actionKey: `${actionKind}:${sourceRef}`,+ occurrence: item?.occurrence ?? null,+ revision: item?.revision ?? null,+ };+}++const emptyTriageState = Object.freeze({+ snoozedUntil: null,+ dismissed: false,+ deliveryGeneration: 0,+});++function triageOperationsFor(item) {+ return [+ { id: 'snooze', label: 'Snooze', available: true },+ ...(item.isRecommendation === true+ ? [{ id: 'dismiss', label: 'Dismiss', available: true }]+ : []),+ ];+}++/**+ * Apply durable presentation markers without changing the source-owned row.+ * This is exported as a pure boundary so expiry and occurrence rollover can+ * be tested with an injected clock.+ */+export function applyQueueTriage(items, entries = [], now = new Date()) {+ const byIdentity = new Map(+ entries+ .map((entry) => {+ const normalized = reviewQueueTriageStore.normalizeReviewQueueTriage(entry);+ return normalized ? [reviewQueueTriageStore.triageIdentityKey(normalized), normalized] : null;+ })+ .filter(Boolean),+ );+ const nowMs = now instanceof Date ? now.getTime() : Date.parse(now);+ const currentTime = Number.isFinite(nowMs) ? nowMs : Date.now();++ return items.flatMap((item) => {+ const identity = queueActionIdentity(item);+ const state = byIdentity.get(reviewQueueTriageStore.triageIdentityKey(identity)) || emptyTriageState;+ const snoozedUntilMs = state.snoozedUntil ? Date.parse(state.snoozedUntil) : NaN;+ const snoozed = Number.isFinite(snoozedUntilMs) && snoozedUntilMs > currentTime;+ const dismissed = state.dismissed && item.isRecommendation === true;+ if (snoozed || dismissed) return [];+ return [{+ ...item,+ triage: {+ snoozedUntil: state.snoozedUntil,+ dismissed: state.dismissed,+ deliveryGeneration: state.deliveryGeneration,+ },+ triageOperations: triageOperationsFor(item),+ }];+ });+}+/*** Gather one producer into normalized rows. A producer may return either an* array or `{ items, truncated }` when it filtered a bounded upstream read.@@ -924,6 +992,105 @@ export async function resolveQueueItem(queueItemId, operation = 'resolve', inputreturn { source, id: queueItemId, resolved: true };}+const REVIEW_QUEUE_TRIAGE_OPERATIONS = new Set(['snooze', 'unsnooze', 'dismiss']);++function queueSourceAndRawId(queueItemId) {+ const value = String(queueItemId || '');+ const sep = value.indexOf(':');+ return {+ source: sep === -1 ? value : value.slice(0, sep),+ rawId: sep === -1 ? '' : value.slice(sep + 1),+ };+}++/**+ * Apply a presentation-only queue decision after re-reading the live source.+ * The mutation never accepts source identity, occurrence, or capability from+ * the client; those values come from the fresh normalized queue row.+ */+export async function triageQueueItem(queueItemId, operation, input = {}, { now: injectedNow } = {}) {+ if (!REVIEW_QUEUE_TRIAGE_OPERATIONS.has(operation)) {+ throw new ServerError(`Unsupported review queue triage operation "${operation}"`, {+ status: 400,+ code: 'BAD_REQUEST',+ });+ }++ const now = injectedNow instanceof Date && Number.isFinite(injectedNow.getTime())+ ? injectedNow+ : new Date();+ let snoozedUntil = null;+ if (operation === 'snooze') {+ const parsed = new Date(input?.snoozedUntil || '');+ if (Number.isNaN(parsed.getTime()) || parsed.getTime() <= now.getTime()) {+ throw new ServerError('snoozedUntil must be a future ISO timestamp', {+ status: 400,+ code: 'VALIDATION_ERROR',+ });+ }+ snoozedUntil = parsed.toISOString();+ } else if (input?.snoozedUntil !== undefined) {+ throw new ServerError('snoozedUntil is only valid for the snooze operation', {+ status: 400,+ code: 'VALIDATION_ERROR',+ });+ }++ const { source } = queueSourceAndRawId(queueItemId);+ const queue = await gatherFullQueue({}, { applyTriageState: false, now });+ const sourceDescriptor = queue.sources[source];+ if (sourceDescriptor?.error) {+ throw new ServerError(`Cannot triage ${source} while its source is unavailable`, {+ status: 503,+ code: 'SOURCE_UNAVAILABLE',+ });+ }+ const item = queue.items.find((candidate) => candidate.id === queueItemId);+ if (!item) {+ throw new ServerError(`Review queue item not found: ${queueItemId}`, { status: 404, code: 'NOT_FOUND' });+ }+ if (operation === 'dismiss' && item.isRecommendation !== true) {+ throw new ServerError('Only optional recommendations can be dismissed from the queue', {+ status: 400,+ code: 'CAPABILITY_UNAVAILABLE',+ });+ }++ const identity = queueActionIdentity(item);+ const existingEntries = await reviewQueueTriageStore.listReviewQueueTriage();+ const identityKey = reviewQueueTriageStore.triageIdentityKey(identity);+ const existing = existingEntries.find((entry) => (+ reviewQueueTriageStore.triageIdentityKey(entry) === identityKey+ ));+ const next = {+ ...identity,+ snoozedUntil: existing?.snoozedUntil || null,+ dismissed: existing?.dismissed === true,+ deliveryGeneration: existing?.deliveryGeneration || 0,+ };++ if (operation === 'snooze') next.snoozedUntil = snoozedUntil;+ if (operation === 'unsnooze') next.snoozedUntil = null;+ if (operation === 'dismiss') next.dismissed = true;++ if (!next.snoozedUntil && !next.dismissed && next.deliveryGeneration === 0) {+ await reviewQueueTriageStore.removeReviewQueueTriage(next);+ } else {+ await reviewQueueTriageStore.upsertReviewQueueTriage(next);+ }++ return {+ id: queueItemId,+ operation,+ triaged: true,+ triage: {+ snoozedUntil: next.snoozedUntil,+ dismissed: next.dismissed,+ deliveryGeneration: next.deliveryGeneration,+ },+ };+}+// Targets the queue can promote an Ask answer into directly. brain/task pick// the latest assistant turn with no extra input; goal additionally needs a// goalId (the row carries `goalOptions` so the UI can supply it). Goal is in@@ -1009,7 +1176,12 @@ function sourceShownCounts(items) {return shown;}-async function gatherFullQueue(query = {}) {+async function readQueueTriageForProjection() {+ const entries = await reviewQueueTriageStore.listReviewQueueTriage();+ return Array.isArray(entries) ? entries : [];+}++async function gatherFullQueue(query = {}, { applyTriageState = true, now = new Date() } = {}) {// 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();@@ -1020,7 +1192,8 @@ async function gatherFullQueue(query = {}) {return 'UTC';}): 'UTC';- const ctx = { goalOptions, view, timezone, now: new Date() };+ const clock = now instanceof Date && Number.isFinite(now.getTime()) ? now : new Date();+ const ctx = { goalOptions, view, timezone, now: clock };const visibleProducers = PRODUCERS.filter((producer) => visibleInLiveViews(producer, view));const results = await Promise.all(visibleProducers.map(async (producer) => {@@ -1041,8 +1214,9 @@ async function gatherFullQueue(query = {}) {});}));- const items = deduplicateItems(results.flatMap((result) => result.items));- items.sort((a, b) => compareQueueItems(a, b));+ let items = deduplicateItems(results.flatMap((result) => result.items));+ if (applyTriageState) items = applyQueueTriage(items, await readQueueTriageForProjection(), clock);+ items.sort((a, b) => compareQueueItems(a, b, clock.getTime()));const shownCounts = sourceShownCounts(items);const sources = {};const totalsBySource = {};@@ -1074,7 +1248,7 @@ async function gatherFullQueue(query = {}) {nextCursor: null,partial,counts: queueCounts(items),- generatedAt: new Date().toISOString(),+ generatedAt: clock.toISOString(),};}@@ -1135,7 +1309,7 @@ function saveQueueSnapshot(queue, queryKey, pageSize) {* 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 = {} } = {}) {+export async function buildQueue({ limit, cursor, query = {}, now } = {}) {const requestedLimit = validatePageSize(limit);const queryKey = queryKeyFor(query);@@ -1165,7 +1339,7 @@ export async function buildQueue({ limit, cursor, query = {} } = {}) {return pageFromSnapshot(snapshot, payload.offset);}- const queue = await gatherFullQueue(query);+ const queue = await gatherFullQueue(query, { now });if (requestedLimit === null) return queue;const snapshot = saveQueueSnapshot(queue, queryKey, requestedLimit);diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex 70b4492de5..bfdc5c77fc 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -22,6 +22,24 @@ const identity = { getGoals: vi.fn() };const stackerNews = { listPendingReviewActions: vi.fn() };const x = { listPendingReviewActions: vi.fn() };const userTimezone = { getUserTimezone: vi.fn() };+const reviewQueueTriageStore = {+ listReviewQueueTriage: vi.fn(),+ upsertReviewQueueTriage: vi.fn(),+ removeReviewQueueTriage: vi.fn(),+ normalizeReviewQueueTriage: (value = {}) => ({+ actionKey: String(value.actionKey || '').trim(),+ occurrence: value.occurrence == null ? '' : String(value.occurrence),+ revision: value.revision == null ? '' : String(value.revision),+ snoozedUntil: value.snoozedUntil || null,+ dismissed: value.dismissed === true,+ deliveryGeneration: value.deliveryGeneration || 0,+ }),+ triageIdentityKey: (value = {}) => JSON.stringify([+ String(value.actionKey || ''),+ value.occurrence == null ? '' : String(value.occurrence),+ value.revision == null ? '' : String(value.revision),+ ]),+};vi.mock('./brain.js', () => brain);vi.mock('./brainStorage.js', () => brainStorage);@@ -38,10 +56,14 @@ vi.mock('./askPromote.js', () => askPromote);vi.mock('./stackerNews.js', () => stackerNews);vi.mock('./x.js', () => x);vi.mock('./userTimezone.js', () => userTimezone);+vi.mock('./reviewQueueTriageStore.js', () => reviewQueueTriageStore);const {buildQueue,resolveQueueItem,+ triageQueueItem,+ applyQueueTriage,+ queueActionIdentity,promoteAskQueueItem,__resetAlertsCache,__resetQueueSnapshots,@@ -70,6 +92,9 @@ function resetEmpty() {stackerNews.listPendingReviewActions.mockResolvedValue([]);x.listPendingReviewActions.mockResolvedValue([]);userTimezone.getUserTimezone.mockResolvedValue('UTC');+ reviewQueueTriageStore.listReviewQueueTriage.mockResolvedValue([]);+ reviewQueueTriageStore.upsertReviewQueueTriage.mockResolvedValue(undefined);+ reviewQueueTriageStore.removeReviewQueueTriage.mockResolvedValue(undefined);}describe('reviewQueue.buildQueue', () => {@@ -668,6 +693,125 @@ describe('reviewQueue.buildQueue', () => {});});+describe('reviewQueue triage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetEmpty();+ __resetAlertsCache();+ __resetQueueSnapshots();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('hides a snoozed row until the injected expiry, then shows it again', async () => {+ const now = Date.parse('2026-09-20T10:00:00.000Z');+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify', capturedAt: 'revision-1' }]);+ reviewQueueTriageStore.listReviewQueueTriage.mockResolvedValue([{+ actionKey: 'brain.classify:b1',+ occurrence: '',+ revision: 'revision-1',+ snoozedUntil: '2026-09-20T11:00:00.000Z',+ }]);++ const hidden = await buildQueue({ now: new Date(now) });+ expect(hidden.items).toEqual([]);+ expect(hidden.counts.total).toBe(0);++ const visible = await buildQueue({ now: new Date('2026-09-20T11:00:00.000Z') });+ expect(visible.items.map((item) => item.id)).toEqual(['brain:b1']);+ });++ it('keys presentation state by occurrence and revision instead of source id alone', () => {+ const item = {+ id: 'thread:one',+ source: 'threads',+ sourceRef: 'one',+ actionKind: 'brain.thread',+ occurrence: 'morning',+ revision: 'revision-1',+ isRecommendation: false,+ };+ const identity = queueActionIdentity(item);+ const state = {+ ...identity,+ snoozedUntil: '2026-09-20T11:00:00.000Z',+ };++ expect(applyQueueTriage([item], [state], new Date('2026-09-20T10:00:00.000Z'))).toEqual([]);+ expect(applyQueueTriage([+ { ...item, occurrence: 'evening' },+ ], [state], new Date('2026-09-20T10:00:00.000Z'))).toHaveLength(1);+ });++ it('revalidates capabilities before allowing an optional dismissal', async () => {+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'required' }]);++ await expect(triageQueueItem('brain:b1', 'dismiss')).rejects.toMatchObject({+ status: 400,+ code: 'CAPABILITY_UNAVAILABLE',+ });+ expect(reviewQueueTriageStore.upsertReviewQueueTriage).not.toHaveBeenCalled();++ askConversations.listConversations.mockResolvedValue([{+ id: 'a1', title: 'optional', promoted: false, assistantTurnCount: 1, updatedAt: 'revision-1',+ }]);+ await expect(triageQueueItem('ask:a1', 'dismiss')).resolves.toMatchObject({+ id: 'ask:a1', operation: 'dismiss', triaged: true,+ });+ expect(reviewQueueTriageStore.upsertReviewQueueTriage).toHaveBeenCalledWith(expect.objectContaining({+ actionKey: 'ask.promote:a1',+ revision: 'revision-1',+ dismissed: true,+ }));+ });++ it('rejects a triage mutation when the owning source read is unavailable', async () => {+ brain.getInboxLog.mockRejectedValue(new Error('inbox unavailable'));++ await expect(triageQueueItem('brain:b1', 'snooze', {+ snoozedUntil: '2026-09-20T11:00:00.000Z',+ })).rejects.toMatchObject({ status: 503, code: 'SOURCE_UNAVAILABLE' });+ expect(reviewQueueTriageStore.upsertReviewQueueTriage).not.toHaveBeenCalled();+ });++ it('persists a future snooze without invoking the source completion primitive', async () => {+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'required', capturedAt: 'revision-1' }]);++ await expect(triageQueueItem('brain:b1', 'snooze', {+ snoozedUntil: '2099-01-01T00:00:00.000Z',+ })).resolves.toMatchObject({ id: 'brain:b1', operation: 'snooze', triaged: true });+ expect(reviewQueueTriageStore.upsertReviewQueueTriage).toHaveBeenCalledWith(expect.objectContaining({+ actionKey: 'brain.classify:b1',+ revision: 'revision-1',+ snoozedUntil: '2099-01-01T00:00:00.000Z',+ }));+ expect(brain.markInboxDone).not.toHaveBeenCalled();+ });++ it('clears a stored snooze through the explicit unsnooze operation', async () => {+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'required', capturedAt: 'revision-1' }]);+ reviewQueueTriageStore.listReviewQueueTriage.mockResolvedValue([{+ actionKey: 'brain.classify:b1',+ occurrence: '',+ revision: 'revision-1',+ snoozedUntil: '2099-01-01T00:00:00.000Z',+ }]);++ await expect(triageQueueItem('brain:b1', 'unsnooze')).resolves.toMatchObject({+ id: 'brain:b1',+ operation: 'unsnooze',+ triaged: true,+ triage: { snoozedUntil: null },+ });+ expect(reviewQueueTriageStore.removeReviewQueueTriage).toHaveBeenCalledWith(expect.objectContaining({+ actionKey: 'brain.classify:b1',+ revision: 'revision-1',+ }));+ });+});+describe('reviewQueue.promoteAskQueueItem', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/server/services/reviewQueueTriageStore.js b/server/services/reviewQueueTriageStore.jsnew file mode 100644index 0000000000..8b6f7c63d3--- /dev/null+++ b/server/services/reviewQueueTriageStore.js@@ -0,0 +1,160 @@+/**+ * Durable presentation markers for the live Review Hub queue.+ *+ * The source record remains authoritative. This store deliberately contains+ * only the canonical action identity plus snooze/dismissal/delivery markers;+ * it never copies a queue title, summary, prompt, or source payload.+ * PostgreSQL is authoritative for normal installs. The JSON backend is the+ * documented development/test escape hatch only.+ */++import { join } from 'node:path';+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';++const triageFile = () => join(PATHS.data, 'review-queue-triage.json');+const queueFileWrite = createFileWriteQueue();++const normalizeIdentityPart = (value) => (value == null ? '' : String(value));++const normalizeSnoozedUntil = (value) => {+ if (value == null || value === '') return null;+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return null;+ return date.toISOString();+};++export function triageIdentityKey({ actionKey, occurrence, revision } = {}) {+ return JSON.stringify([+ normalizeIdentityPart(actionKey),+ normalizeIdentityPart(occurrence),+ normalizeIdentityPart(revision),+ ]);+}++export function normalizeReviewQueueTriage(value = {}, { rejectInvalid = false } = {}) {+ const actionKey = normalizeIdentityPart(value.actionKey).trim();+ if (!actionKey) {+ if (rejectInvalid) throw new Error('Review queue triage is missing actionKey');+ return null;+ }+ const rawSnoozedUntil = value.snoozedUntil;+ const snoozedUntil = normalizeSnoozedUntil(rawSnoozedUntil);+ if (rejectInvalid && rawSnoozedUntil != null && rawSnoozedUntil !== '' && !snoozedUntil) {+ throw new Error('Review queue triage has an invalid snoozedUntil');+ }+ const deliveryGeneration = value.deliveryGeneration == null ? 0 : Number(value.deliveryGeneration);+ if (!Number.isSafeInteger(deliveryGeneration) || deliveryGeneration < 0) {+ if (rejectInvalid) throw new Error('Review queue triage has an invalid deliveryGeneration');+ return null;+ }+ return {+ actionKey,+ occurrence: normalizeIdentityPart(value.occurrence),+ revision: normalizeIdentityPart(value.revision),+ snoozedUntil,+ dismissed: value.dismissed === true,+ deliveryGeneration,+ };+}++async function readFileTriage() {+ const raw = await readJSONFile(triageFile(), [], { allowArray: true, logError: false, strict: true });+ return (Array.isArray(raw) ? raw : []).map((entry) => normalizeReviewQueueTriage(entry)).filter(Boolean);+}++const findEntry = (entries, value) => {+ const key = triageIdentityKey(value);+ return entries.findIndex((entry) => triageIdentityKey(entry) === key);+};++function makeFileBackend() {+ return {+ name: 'file',+ list: readFileTriage,+ upsert: (value) => queueFileWrite(async () => {+ const entries = await readFileTriage();+ const index = findEntry(entries, value);+ if (index === -1) entries.push(value);+ else entries[index] = value;+ await atomicWrite(triageFile(), entries);+ }),+ remove: (value) => queueFileWrite(async () => {+ const entries = await readFileTriage();+ const index = findEntry(entries, value);+ if (index === -1) return;+ entries.splice(index, 1);+ await atomicWrite(triageFile(), entries);+ }),+ };+}++function makePgBackend(db) {+ return {+ name: 'postgres',+ async list() {+ const { rows } = await db.query(+ `SELECT action_key, occurrence, revision, snoozed_until, dismissed, delivery_generation+ FROM review_queue_triage+ ORDER BY action_key, occurrence, revision`,+ );+ return rows.map((row) => normalizeReviewQueueTriage({+ actionKey: row.action_key,+ occurrence: row.occurrence,+ revision: row.revision,+ snoozedUntil: row.snoozed_until,+ dismissed: row.dismissed,+ deliveryGeneration: row.delivery_generation,+ })).filter(Boolean);+ },+ async upsert(value) {+ await db.query(+ `INSERT INTO review_queue_triage+ (action_key, occurrence, revision, snoozed_until, dismissed, delivery_generation)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (action_key, occurrence, revision) DO UPDATE SET+ snoozed_until = EXCLUDED.snoozed_until,+ dismissed = EXCLUDED.dismissed,+ delivery_generation = EXCLUDED.delivery_generation`,+ [value.actionKey, value.occurrence, value.revision, value.snoozedUntil, value.dismissed, value.deliveryGeneration],+ );+ },+ async remove(value) {+ await db.query(+ `DELETE FROM review_queue_triage+ WHERE action_key = $1 AND occurrence = $2 AND revision = $3`,+ [value.actionKey, value.occurrence, value.revision],+ );+ },+ };+}++const backendFacade = createPgFileFacade({+ makeFile: makeFileBackend,+ makePg: () => resolvePgBackend({+ requirement: 'Review queue triage requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the file escape hatch)',+ loadDb: () => import('../lib/db.js'),+ makePg: makePgBackend,+ }),+});++export async function listReviewQueueTriage() {+ return (await backendFacade.getBackend()).list();+}++export async function upsertReviewQueueTriage(value) {+ const normalized = normalizeReviewQueueTriage(value, { rejectInvalid: true });+ await (await backendFacade.getBackend()).upsert(normalized);+ return normalized;+}++export async function removeReviewQueueTriage(value) {+ const normalized = normalizeReviewQueueTriage(value, { rejectInvalid: true });+ await (await backendFacade.getBackend()).remove(normalized);+}++/** Test seam for suites that swap the file data root between cases. */+export function resetReviewQueueTriageStore() {+ backendFacade.reset();+}diff --git a/server/services/reviewQueueTriageStore.test.js b/server/services/reviewQueueTriageStore.test.jsnew file mode 100644index 0000000000..09e336a97b--- /dev/null+++ b/server/services/reviewQueueTriageStore.test.js@@ -0,0 +1,69 @@+import { rm } from 'node:fs/promises';+import { join } from 'node:path';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('portos-review-queue-triage-') });+});++const {+ listReviewQueueTriage,+ removeReviewQueueTriage,+ resetReviewQueueTriageStore,+ upsertReviewQueueTriage,+} = await import('./reviewQueueTriageStore.js');++const dataRoot = lazyTempDataRoot('portos-review-queue-triage-');+const triageFile = join(dataRoot, 'review-queue-triage.json');+const previousBackend = process.env.MEMORY_BACKEND;++beforeEach(async () => {+ process.env.MEMORY_BACKEND = 'file';+ resetReviewQueueTriageStore();+ await rm(triageFile, { force: true });+});++afterAll(async () => {+ resetReviewQueueTriageStore();+ if (previousBackend === undefined) delete process.env.MEMORY_BACKEND;+ else process.env.MEMORY_BACKEND = previousBackend;+ cleanupTempDataRoots();+});++describe('reviewQueueTriageStore', () => {+ it('persists only keyed presentation markers across a backend restart', async () => {+ const marker = {+ actionKey: 'brain.classify:example',+ occurrence: 'morning',+ revision: 'revision-1',+ snoozedUntil: '2099-01-01T00:00:00.000Z',+ dismissed: false,+ deliveryGeneration: 0,+ };++ await upsertReviewQueueTriage(marker);+ resetReviewQueueTriageStore();++ await expect(listReviewQueueTriage()).resolves.toEqual([marker]);+ });++ it('keeps rollover occurrences distinct and removes a cleared marker', async () => {+ const first = { actionKey: 'ask.promote:example', occurrence: '1', revision: 'r1', dismissed: true };+ const second = { actionKey: 'ask.promote:example', occurrence: '2', revision: 'r1', dismissed: true };+ await upsertReviewQueueTriage(first);+ await upsertReviewQueueTriage(second);++ await expect(listReviewQueueTriage()).resolves.toHaveLength(2);+ await removeReviewQueueTriage(first);+ await expect(listReviewQueueTriage()).resolves.toEqual([{+ actionKey: second.actionKey,+ occurrence: second.occurrence,+ revision: second.revision,+ snoozedUntil: null,+ dismissed: true,+ deliveryGeneration: 0,+ }]);+ });+});