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: route product recommendations through review queue (#7742)
[._.]/ Adam Eivye12b33f3462c
diff --git a/docs/features/review-queue.md b/docs/features/review-queue.mdindex 9f3dc4110b..3518e07a22 100644--- a/docs/features/review-queue.md+++ b/docs/features/review-queue.md@@ -97,9 +97,17 @@ action kinds and are never merged merely because they share a task or agent.| Paused automation | Required with series/run id and link | Series/run reference; `autopilot.resume` / Resume | Resume remains in the owning automation surface || Explicit content review | Required with report/reference id and link | Report or review id; `content.review` / Review | Private security and malware reports remain source-owned || Health and backup | Required only with a known human remedy | Alert or last-run identity; Investigate or Retry | No generic Complete operation |+| Product recommendations | Optional when a current POST or creative-feedback signal is available | Product action id plus local-day/run occurrence; Open | Feature-disabled signals disappear without deleting their local triage marker || Legacy Review alerts | Required as explicit triage | Stored Review item id; `review.triage` / Review | Never silently completed or deleted || Briefings, generic warnings, client errors, and uncorrelated notifications | Not admitted | No proven obligation contract | Remain in Review history/context |-Optional Ask promotion is still available from Ask and its API, but it is not-required action admission. Routine task-ready/success attention generation is-not a queue producer; execution history and private reports remain separate.+Product recommendations are admitted once per current occurrence: POST uses the+configured local calendar day, while creative feedback uses one row per+reviewable commission run. The product source returns every pending run before+the queue's bounded read, and a full bound is reported as truncation rather+than an inbox-zero claim. Product read failures are reported as an unavailable+source; legacy metrics and proactive-alert endpoints keep their existing+compatibility projections. Optional Ask promotion is still available from Ask+and its API, but it is not required action admission. Routine task-ready/success+attention generation is not a queue producer; execution history and private+reports remain separate.diff --git a/server/services/portosProductMetrics.js b/server/services/portosProductMetrics.jsindex b65eba0e57..80af851dd6 100644--- a/server/services/portosProductMetrics.js+++ b/server/services/portosProductMetrics.js@@ -5,8 +5,8 @@* questions the generic CoS telemetry cannot: did the user exercise POST today,* and did they close the feedback loop on completed creative commissions?* The aggregate shape is deliberately safe to put in a reasoning prompt; the- * user-facing action projection may additionally carry a deep link to the- * oldest item needing attention.+ * user-facing action projection may additionally carry deep links to every+ * item needing attention.*/import { getPostSessions } from './meatspacePost.js';@@ -20,7 +20,6 @@ import { getUserTimezone } from './userTimezone.js';const DAY_MS = 24 * 60 * 60 * 1000;const FEEDBACK_WINDOW_DAYS = 30;-const ACTION_PENDING_LIMIT = 8;const SOURCE_MAX_CHARS = 8000;const COMPLETED_PROJECT_STATUSES = new Set(['complete', 'completed']);const NON_REVIEWABLE_RUN_STATUSES = new Set(['failed', 'skipped', 'cancelled', 'canceled', 'error']);@@ -172,7 +171,10 @@ export function summarizeCreativeFeedback({ commissions = [], projects = [], nowoldestUnreviewedAgeDays: pendingReviews.length ? pendingReviews[0].ageDays : null,feedbackCoveragePercent: coverage(reviewedCount, reviewable.length),feedbackCoverageLast30Percent: coverage(recentReviewedCount, recent.length),- pendingReviews: pendingReviews.slice(0, ACTION_PENDING_LIMIT),+ // Keep every reviewable run addressable. The Review Queue applies its own+ // bounded source read and discloses truncation at that boundary, while+ // this compatibility service remains a complete metrics projection.+ pendingReviews,};}@@ -197,6 +199,9 @@ export function buildProductActions({ post, creativeCommissions }) {link: '/post/launcher',featureId: 'post',featureLabel: 'POST',+ required: false,+ isRecommendation: true,+ ...(typeof post.today === 'string' && post.today ? { occurrence: post.today } : {}),metadata: {completedToday: false,daysSinceActivity: daysSince,@@ -207,27 +212,48 @@ export function buildProductActions({ post, creativeCommissions }) {}if (creativeCommissions?.status === 'ok' && creativeCommissions.unreviewedRenders > 0) {- const oldest = creativeCommissions.pendingReviews?.[0];- const link = oldest- ? `/creative-commission/${encodeURIComponent(oldest.commissionId)}?run=${encodeURIComponent(oldest.runId)}`- : '/creative-commission';- const name = oldest?.commissionName && oldest.commissionName !== 'Creative commission'- ? `: ${oldest.commissionName}`- : '';- const age = creativeCommissions.oldestUnreviewedAgeDays;- actions.push({- id: `creative-feedback:${oldest?.commissionId || 'pending'}:${oldest?.runId || 'latest'}`,- type: 'commission_feedback',- severity: age !== null && age >= 3 ? 'high' : 'medium',- title: `Creative feedback overdue${name}`,- detail: `${creativeCommissions.unreviewedRenders} completed render${creativeCommissions.unreviewedRenders === 1 ? '' : 's'} ${age > 0 ? 'awaiting review' : 'awaiting your rating'}${age > 0 ? ` for up to ${age} days` : ''}.`,- link,- metadata: {- unreviewedRenders: creativeCommissions.unreviewedRenders,- oldestUnreviewedAgeDays: age,- feedbackCoveragePercent: creativeCommissions.feedbackCoveragePercent,- },- });+ const pendingReviews = Array.isArray(creativeCommissions.pendingReviews)+ ? creativeCommissions.pendingReviews+ : [];+ const renderCount = creativeCommissions.unreviewedRenders;++ for (const pending of pendingReviews) {+ // A queue row without both source identifiers cannot be opened or+ // triaged safely. summarizeCreativeFeedback only emits valid entries,+ // but retain the guard for legacy/forward-version records.+ if (!pending?.commissionId || !pending?.runId) continue;+ const age = Number.isFinite(pending.ageDays)+ ? pending.ageDays+ : (Number.isFinite(creativeCommissions.oldestUnreviewedAgeDays)+ ? creativeCommissions.oldestUnreviewedAgeDays+ : null);+ const name = pending.commissionName && pending.commissionName !== 'Creative commission'+ ? `: ${pending.commissionName}`+ : '';+ const runId = encodeURIComponent(pending.runId);+ const commissionId = encodeURIComponent(pending.commissionId);+ actions.push({+ id: `creative-feedback:${commissionId}:${runId}`,+ type: 'commission_feedback',+ severity: age !== null && age >= 3 ? 'high' : 'medium',+ title: `Creative feedback overdue${name}`,+ detail: `${renderCount} completed render${renderCount === 1 ? '' : 's'} ${age !== null && age > 0 ? 'awaiting review' : 'awaiting your rating'}${age !== null && age > 0 ? ` for up to ${age} days` : ''}.`,+ link: `/creative-commission/${commissionId}?run=${runId}`,+ timestamp: pending.ranAt || null,+ required: false,+ isRecommendation: true,+ // A run is the durable occurrence identity. It keeps a snooze or+ // dismissal attached to this run even when another run becomes oldest.+ occurrence: pending.runId,+ metadata: {+ commissionId: pending.commissionId,+ runId: pending.runId,+ unreviewedRenders: renderCount,+ oldestUnreviewedAgeDays: creativeCommissions.oldestUnreviewedAgeDays,+ feedbackCoveragePercent: creativeCommissions.feedbackCoveragePercent,+ },+ });+ }}return actions;diff --git a/server/services/portosProductMetrics.test.js b/server/services/portosProductMetrics.test.jsindex 1f449229fa..21384d60b9 100644--- a/server/services/portosProductMetrics.test.js+++ b/server/services/portosProductMetrics.test.js@@ -81,6 +81,24 @@ describe('summarizeCreativeFeedback', () => {commissionName: 'Example Nightly Commission',});});++ it('keeps every pending run addressable instead of truncating the compatibility metrics', () => {+ const runs = Array.from({ length: 9 }, (_, index) => ({+ id: `run-${index}`,+ projectId: `project-${index}`,+ ranAt: `2026-08-${String(10 + index).padStart(2, '0')}T12:00:00.000Z`,+ status: 'started',+ }));+ const result = summarizeCreativeFeedback({+ now: new Date(`${today}T12:00:00.000Z`),+ commissions: [{ id: 'commission-example', runs, feedback: [] }],+ projects: runs.map((run) => ({ id: run.projectId, status: 'complete' })),+ });++ expect(result.unreviewedRenders).toBe(9);+ expect(result.pendingReviews).toHaveLength(9);+ expect(result.pendingReviews.at(-1).runId).toBe('run-8');+ });});describe('buildProductActions', () => {@@ -88,7 +106,7 @@ describe('buildProductActions', () => {const actions = buildProductActions({post: {status: 'ok', completedToday: false, daysSinceActivity: 3,- activeDaysLast7: 2, currentStreak: 1,+ activeDaysLast7: 2, currentStreak: 1, today,},creativeCommissions: {status: 'ok', unreviewedRenders: 1, oldestUnreviewedAgeDays: 4,@@ -104,6 +122,9 @@ describe('buildProductActions', () => {link: '/post/launcher',featureId: 'post',featureLabel: 'POST',+ required: false,+ isRecommendation: true,+ occurrence: today,});expect(actions[1]).toMatchObject({type: 'commission_feedback',@@ -114,6 +135,56 @@ describe('buildProductActions', () => {expect(actions[1].detail).not.toContain('awaitsing');});+ it('creates one optional feedback action per pending run with stable occurrence identity', () => {+ const actions = buildProductActions({+ post: { status: 'ok', completedToday: true, today },+ creativeCommissions: {+ status: 'ok',+ unreviewedRenders: 2,+ oldestUnreviewedAgeDays: 5,+ feedbackCoveragePercent: 33,+ pendingReviews: [+ {+ commissionId: 'commission-example',+ commissionName: 'Example Commission',+ runId: 'run-old',+ ranAt: '2026-08-19T12:00:00.000Z',+ ageDays: 5,+ },+ {+ commissionId: 'commission-example',+ commissionName: 'Example Commission',+ runId: 'run-new',+ ranAt: '2026-08-23T12:00:00.000Z',+ ageDays: 1,+ },+ ],+ },+ });++ expect(actions).toHaveLength(2);+ expect(actions.map((action) => action.id)).toEqual([+ 'creative-feedback:commission-example:run-old',+ 'creative-feedback:commission-example:run-new',+ ]);+ expect(actions).toEqual(expect.arrayContaining([+ expect.objectContaining({+ occurrence: 'run-old',+ timestamp: '2026-08-19T12:00:00.000Z',+ required: false,+ isRecommendation: true,+ severity: 'high',+ }),+ expect.objectContaining({+ occurrence: 'run-new',+ timestamp: '2026-08-23T12:00:00.000Z',+ required: false,+ isRecommendation: true,+ severity: 'medium',+ }),+ ]));+ });+it('does not create actions from unavailable metrics', () => {expect(buildProductActions({post: { status: 'unavailable' },diff --git a/server/services/proactiveAlertSources.js b/server/services/proactiveAlertSources.jsnew file mode 100644index 0000000000..af15432e91--- /dev/null+++ b/server/services/proactiveAlertSources.js@@ -0,0 +1,341 @@+/**+ * Non-product proactive alert sources.+ *+ * These checks are shared by the legacy proactive-alert projection and the+ * Review Queue's health producer. Product-engagement recommendations stay in+ * portosProductMetrics.js as a leaf source so the queue never imports an+ * aggregate that also consumes the queue's product actions.+ */++import os from 'os';+import { getGoals } from './identity.js';+import { getPerformanceSummary } from './taskLearning.js';+import { listProcesses } from './pm2.js';+import { annotateExpectedExit } from './apps.js';+import { getUsage } from './usage.js';+import { getCareSummary } from './tribe.js';+import { findUnansweredTribeThreads } from './tribeOutreach.js';+import { getMemoryStats } from '../lib/memoryStats.js';++const STALL_THRESHOLD_DAYS = 14;+const SUCCESS_RATE_WARNING = 50;+const MEMORY_WARNING_PCT = 85;+const MEMORY_CRITICAL_PCT = 95;+const CPU_WARNING_PCT = 90;+const USAGE_SPIKE_MULTIPLIER = 2.5;+const USAGE_MIN_HISTORY_DAYS = 3;++/**+ * Condition + explicit resource identity, never presentation text or+ * position. Encode each segment separately so a resource containing ':'+ * cannot collide. Missing resource identity is a failed source read, not+ * permission to mint a positional ID or claim the queue is empty.+ */+function alertId(condition, resource) {+ const valid = typeof resource === 'string' ? resource.trim().length > 0+ : Number.isSafeInteger(resource) && resource >= 0;+ if (!valid) throw new Error('Alert resource identity is unavailable');+ return `${condition}:${encodeURIComponent(resource)}`;+}++/** Detect goals that have stalled (no progress update in 14+ days). */+async function checkGoalStalls() {+ const goalsData = await getGoals().catch(() => null);+ if (!goalsData?.goals?.length) return [];++ const now = Date.now();+ const alerts = [];++ for (const goal of goalsData.goals) {+ if (goal.status !== 'active' || goal.parentId) continue;++ const lastUpdate = goal.progressHistory?.length+ ? goal.progressHistory.reduce((a, b) => b.timestamp > a.timestamp ? b : a).timestamp+ : goal.createdAt;++ if (!lastUpdate) continue;++ const daysSince = Math.floor((now - new Date(lastUpdate).getTime()) / 86400000);+ if (daysSince >= STALL_THRESHOLD_DAYS) {+ alerts.push({+ id: alertId('goal_stall', goal.id),+ type: 'goal_stall',+ severity: daysSince >= 30 ? 'high' : 'medium',+ title: `Goal stalled: ${goal.title}`,+ detail: `No progress in ${daysSince} days`,+ link: '/goals',+ metadata: { goalId: goal.id, daysSince, progress: goal.progress || 0 },+ });+ }+ }++ return alerts;+}++/**+ * A low lifetime rate is historical context, not a current anomaly. The+ * performance summary only selects `windowed` after enough recent runs, so+ * thin samples do not create noisy alerts.+ */+function hasCurrentPerformanceEvidence(item) {+ return item?.rateSource === 'windowed';+}++/** Detect recently active task types with poor success rates. */+async function checkSuccessRates() {+ const perf = await getPerformanceSummary().catch(() => null);+ if (!perf) return [];++ return (perf.needsAttention || [])+ .filter(hasCurrentPerformanceEvidence)+ .map(item => ({+ id: alertId('success_drop', item.taskType),+ type: 'success_drop',+ severity: item.successRate < 30 ? 'high' : 'medium',+ title: `Low success rate: ${item.taskType}`,+ detail: `${item.successRate}% success across the last ${item.windowedCompleted} runs`,+ link: '/cos/learning',+ metadata: {+ taskType: item.taskType,+ successRate: item.successRate,+ completed: item.completed,+ rateSource: item.rateSource,+ windowedCompleted: item.windowedCompleted,+ },+ }));+}++/** Check for system resource warnings (memory, CPU, errored processes). */+async function checkSystemHealth() {+ const alerts = [];++ const memStats = await getMemoryStats();+ const memPct = Math.round((memStats.used / memStats.total) * 100);++ if (memPct >= MEMORY_WARNING_PCT) {+ const formatGB = (bytes) => `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;+ alerts.push({+ id: alertId('system_resource', 'memory'),+ type: 'system_resource',+ severity: memPct >= MEMORY_CRITICAL_PCT ? 'critical' : 'high',+ title: 'High memory usage',+ detail: `${memPct}% — ${formatGB(memStats.used)} / ${formatGB(memStats.total)}`,+ link: '/apps',+ metadata: { resource: 'memory', percent: memPct },+ });+ }++ const cpuLoad = os.loadavg()[0];+ const cpuCount = os.cpus().length;+ const cpuPct = Math.round((cpuLoad / cpuCount) * 100);++ if (cpuPct >= CPU_WARNING_PCT) {+ alerts.push({+ id: alertId('system_resource', 'cpu'),+ type: 'system_resource',+ severity: 'high',+ title: 'High CPU usage',+ detail: `${cpuPct}% across ${cpuCount} cores`,+ link: '/apps',+ metadata: { resource: 'cpu', percent: cpuPct },+ });+ }++ // PM2 process errors. Processes whose exit is expected (a desktop app the+ // user quit) are excluded: that is a normal end to a session, and alerting+ // on it would report every play session as a failure. See issue #2991.+ const processes = await listProcesses().catch(() => []);+ const alertable = (await annotateExpectedExit(processes)).filter(p => !p.expectedExit);+ for (const process of alertable) {+ if (process.status === 'errored') {+ alerts.push({+ id: alertId('process_errored', process.pm_id),+ type: 'process_error',+ severity: 'high',+ title: `Errored process: ${process.name}`,+ detail: 'Review the process logs and restart it after addressing the failure',+ link: '/apps',+ metadata: { processId: process.pm_id, errored: 1, total: alertable.length },+ });+ }+ if ((process.unstableRestarts || 0) > 0) {+ alerts.push({+ id: alertId('process_crash_loop', process.pm_id),+ type: 'process_error',+ severity: 'high',+ title: `Process in crash loop: ${process.name}`,+ detail: `${process.unstableRestarts} crash-loop restarts — review the process logs`,+ link: '/apps',+ metadata: { processId: process.pm_id, unstableRestarts: process.unstableRestarts, names: [process.name] },+ });+ }+ }++ return alerts;+}++/** Check task learning health for critical issues. */+async function checkLearningHealth() {+ const perf = await getPerformanceSummary().catch(() => null);+ if (!perf) return [];++ const alerts = [];+ const recentAttention = (perf.needsAttention || []).filter(hasCurrentPerformanceEvidence);+ const skipped = (perf.skipped || []).filter(hasCurrentPerformanceEvidence).length;+ const critical = recentAttention.filter(item => item.successRate < 40).length;+ const warning = recentAttention.length - critical;++ if (skipped > 0) {+ alerts.push({+ id: alertId('learning_skipped', 'all'),+ type: 'learning_health',+ severity: 'high',+ title: `${skipped} task type${skipped > 1 ? 's' : ''} being skipped`,+ detail: 'Very low success rates caused automatic skip — review task configuration',+ link: '/cos/learning',+ metadata: { skipped, critical },+ });+ } else if (critical > 0) {+ alerts.push({+ id: alertId('learning_critical', 'all'),+ type: 'learning_health',+ severity: 'medium',+ title: `${critical} task type${critical > 1 ? 's' : ''} need attention`,+ detail: `Success rates below ${SUCCESS_RATE_WARNING}% — may need provider or prompt adjustments`,+ link: '/cos/learning',+ metadata: { critical, warning },+ });+ }++ return alerts;+}++/** Detect AI usage spikes against the recent rolling average. */+async function checkUsageSpikes() {+ const usage = getUsage();+ if (!usage?.dailyActivity) return [];++ const daily = usage.dailyActivity;+ const today = new Date().toISOString().split('T')[0];+ const recentDays = [];+ for (let i = 1; i <= 14; i++) {+ const date = new Date();+ date.setDate(date.getDate() - i);+ const dateStr = date.toISOString().split('T')[0];+ const dayData = daily[dateStr];+ if (dayData && dayData.sessions > 0) recentDays.push(dayData);+ }++ if (recentDays.length < USAGE_MIN_HISTORY_DAYS) return [];++ const avgTokens = recentDays.reduce((sum, day) => sum + (day.tokens || 0), 0) / recentDays.length;+ const avgSessions = recentDays.reduce((sum, day) => sum + (day.sessions || 0), 0) / recentDays.length;+ const alerts = [];+ const todayData = daily[today];++ if (todayData && avgTokens > 0) {+ const tokenRatio = todayData.tokens / avgTokens;+ if (tokenRatio >= USAGE_SPIKE_MULTIPLIER) {+ const formatTokens = (tokens) => tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);+ alerts.push({+ id: alertId('cost_spike', 'tokens'),+ type: 'cost_spike',+ severity: tokenRatio >= 5 ? 'high' : 'medium',+ title: 'AI token usage spike',+ detail: `${formatTokens(todayData.tokens)} tokens today vs ${formatTokens(Math.round(avgTokens))} avg/day (${tokenRatio.toFixed(1)}x)`,+ link: '/devtools/usage',+ metadata: { resource: 'tokens', today: todayData.tokens, average: Math.round(avgTokens), ratio: Math.round(tokenRatio * 10) / 10 },+ });+ }++ const sessionRatio = todayData.sessions / avgSessions;+ if (sessionRatio >= USAGE_SPIKE_MULTIPLIER && avgSessions > 0) {+ alerts.push({+ id: alertId('cost_spike', 'sessions'),+ type: 'cost_spike',+ severity: sessionRatio >= 5 ? 'high' : 'medium',+ title: 'AI session spike',+ detail: `${todayData.sessions} sessions today vs ${Math.round(avgSessions)} avg/day (${sessionRatio.toFixed(1)}x)`,+ link: '/devtools/usage',+ metadata: { resource: 'sessions', today: todayData.sessions, average: Math.round(avgSessions), ratio: Math.round(sessionRatio * 10) / 10 },+ });+ }+ }++ return alerts;+}++/** Detect Tribe relationships overdue for contact. */+async function checkTribeCadence() {+ const summary = await getCareSummary(3).catch(() => null);+ if (!summary || summary.overdueCount === 0) return [];++ const names = summary.overdue.map((person) => person.name).filter(Boolean).join(', ');+ const overflow = summary.overdueCount > summary.overdue.length ? ', …' : '';+ return [{+ id: alertId('tribe_cadence', 'all'),+ type: 'tribe_cadence',+ severity: summary.overdueCount >= 3 ? 'high' : 'medium',+ title: `${summary.overdueCount} ${summary.overdueCount === 1 ? 'person is' : 'people are'} overdue for contact`,+ detail: names ? `Reach out to ${names}${overflow}` : 'Overdue check-ins in your Tribe',+ link: '/tribe',+ metadata: { overdueCount: summary.overdueCount, peopleCount: summary.peopleCount },+ }];+}++/**+ * Detect unanswered inbound Tribe threads. Detection only — drafting a reply+ * is a separate user-action-gated step.+ */+async function checkUnansweredTribeThreads() {+ const threads = await findUnansweredTribeThreads().catch(() => []);+ if (!threads.length) return [];++ const ago = (days) => (days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${days} days ago`);+ return threads.map((thread) => {+ const snippet = thread.snippet ? `“${thread.snippet}”` : 'their message';+ return {+ id: alertId('tribe_unanswered', thread.conversationKey),+ type: 'tribe_unanswered',+ severity: thread.daysAgo >= 7 ? 'high' : 'medium',+ title: `Unanswered: ${thread.personName}`,+ detail: `You never replied to ${snippet} (${ago(thread.daysAgo)})`,+ link: `/tribe?tab=care&outreach=${encodeURIComponent(thread.conversationKey)}`,+ metadata: {+ personId: thread.personId,+ source: thread.source,+ threadId: thread.threadId,+ chatGuid: thread.chatGuid,+ conversationId: thread.conversationId,+ handle: thread.handle,+ lastInboundAt: thread.lastInboundAt,+ daysAgo: thread.daysAgo,+ },+ };+ });+}++/**+ * Collect only the non-product alert sources. Product engagement is composed+ * separately by proactiveAlerts.js and by the Review Queue product producer.+ */+export async function generateNonProductAlerts() {+ const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts, unansweredAlerts] = await Promise.all([+ checkGoalStalls(),+ checkSuccessRates(),+ checkSystemHealth(),+ checkLearningHealth(),+ checkUsageSpikes(),+ checkTribeCadence(),+ checkUnansweredTribeThreads(),+ ]);+ return [+ ...goalAlerts,+ ...successAlerts,+ ...systemAlerts,+ ...learningAlerts,+ ...usageAlerts,+ ...tribeAlerts,+ ...unansweredAlerts,+ ];+}diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex e0b0aec601..72505c211b 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -1,388 +1,34 @@/**- * Proactive Alerts Service+ * Legacy proactive alert aggregation.*- * Analyzes system data to surface actionable alerts proactively:- * - Goal stalls (no progress in 14+ days)- * - Task success rate drops (task types with low success rates)- * - System health warnings (high memory/CPU, errored processes)- * - Learning health issues (skipped or critical task types)- * - AI usage spikes (token/session usage significantly above rolling average)- *- * Designed to be called on-demand from the dashboard widget- * and optionally from autonomous jobs.+ * The Review Queue consumes non-product sources and product metrics+ * separately. This compatibility aggregate keeps the existing alerts API+ * shape, including product engagement, until the attention surfaces migrate.*/-import os from 'os';-import { getGoals } from './identity.js';-import { getPerformanceSummary } from './taskLearning.js';-import { listProcesses } from './pm2.js';-import { annotateExpectedExit } from './apps.js';-import { getUsage } from './usage.js';-import { getCareSummary } from './tribe.js';-import { findUnansweredTribeThreads } from './tribeOutreach.js';-import { getMemoryStats } from '../lib/memoryStats.js';import { getProductEngagement } from './portosProductMetrics.js';--const STALL_THRESHOLD_DAYS = 14;-const SUCCESS_RATE_WARNING = 50;-const MEMORY_WARNING_PCT = 85;-const MEMORY_CRITICAL_PCT = 95;-const CPU_WARNING_PCT = 90;-const USAGE_SPIKE_MULTIPLIER = 2.5;-const USAGE_MIN_HISTORY_DAYS = 3;--/**- * Condition + explicit resource identity, never presentation text or position.- * Encode each segment separately so a resource containing ':' cannot collide.- * These keys name the active condition; severity/wording changes keep the key.- * Domain-wide checks use an explicit 'all' resource. Recurring product actions- * supply their own IDs. Missing resource identity is a failed source read,- * not permission to mint a positional ID or claim the queue is empty.- */-function alertId(condition, resource) {- const valid = typeof resource === 'string' ? resource.trim().length > 0- : Number.isSafeInteger(resource) && resource >= 0;- if (!valid) throw new Error('Alert resource identity is unavailable');- return `${condition}:${encodeURIComponent(resource)}`;-}--/**- * Detect goals that have stalled (no progress update in 14+ days)- */-async function checkGoalStalls() {- const goalsData = await getGoals().catch(() => null);- if (!goalsData?.goals?.length) return [];-- const now = Date.now();- const alerts = [];-- for (const goal of goalsData.goals) {- if (goal.status !== 'active' || goal.parentId) continue;-- const lastUpdate = goal.progressHistory?.length- ? goal.progressHistory.reduce((a, b) => b.timestamp > a.timestamp ? b : a).timestamp- : goal.createdAt;-- if (!lastUpdate) continue;-- const daysSince = Math.floor((now - new Date(lastUpdate).getTime()) / 86400000);- if (daysSince >= STALL_THRESHOLD_DAYS) {- alerts.push({- id: alertId('goal_stall', goal.id),- type: 'goal_stall',- severity: daysSince >= 30 ? 'high' : 'medium',- title: `Goal stalled: ${goal.title}`,- detail: `No progress in ${daysSince} days`,- link: '/goals',- metadata: { goalId: goal.id, daysSince, progress: goal.progress || 0 }- });- }- }-- return alerts;-}--/**- * A low lifetime rate is historical context, not a current anomaly. The- * performance summary only selects `windowed` after at least five runs in the- * 30-day window, so this also keeps thin samples from creating noisy alerts.- */-function hasCurrentPerformanceEvidence(item) {- return item?.rateSource === 'windowed';-}--/**- * Detect recently active task types with poor success rates- */-async function checkSuccessRates() {- const perf = await getPerformanceSummary().catch(() => null);- if (!perf) return [];-- return (perf.needsAttention || [])- .filter(hasCurrentPerformanceEvidence)- .map(item => ({- id: alertId('success_drop', item.taskType),- type: 'success_drop',- severity: item.successRate < 30 ? 'high' : 'medium',- title: `Low success rate: ${item.taskType}`,- detail: `${item.successRate}% success across the last ${item.windowedCompleted} runs`,- link: '/cos/learning',- metadata: { taskType: item.taskType, successRate: item.successRate, completed: item.completed, rateSource: item.rateSource, windowedCompleted: item.windowedCompleted }- }));-}--/**- * Check for system resource warnings (memory, CPU, errored processes)- */-async function checkSystemHealth() {- const alerts = [];-- const memStats = await getMemoryStats();- const memPct = Math.round((memStats.used / memStats.total) * 100);-- if (memPct >= MEMORY_WARNING_PCT) {- const formatGB = (bytes) => `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;- alerts.push({- id: alertId('system_resource', 'memory'),- type: 'system_resource',- severity: memPct >= MEMORY_CRITICAL_PCT ? 'critical' : 'high',- title: 'High memory usage',- detail: `${memPct}% — ${formatGB(memStats.used)} / ${formatGB(memStats.total)}`,- link: '/apps',- metadata: { resource: 'memory', percent: memPct }- });- }-- // CPU check- const cpuLoad = os.loadavg()[0];- const cpuCount = os.cpus().length;- const cpuPct = Math.round((cpuLoad / cpuCount) * 100);-- if (cpuPct >= CPU_WARNING_PCT) {- alerts.push({- id: alertId('system_resource', 'cpu'),- type: 'system_resource',- severity: 'high',- title: 'High CPU usage',- detail: `${cpuPct}% across ${cpuCount} cores`,- link: '/apps',- metadata: { resource: 'cpu', percent: cpuPct }- });- }-- // PM2 process errors. Processes whose exit is expected (a desktop app the user- // quit) are excluded: that is a normal end to a session, and alerting on it- // would report every play session as a failure. See issue #2991.- const processes = await listProcesses().catch(() => []);- const alertable = (await annotateExpectedExit(processes)).filter(p => !p.expectedExit);- for (const process of alertable) {- if (process.status === 'errored') {- alerts.push({- id: alertId('process_errored', process.pm_id),- type: 'process_error',- severity: 'high',- title: `Errored process: ${process.name}`,- detail: 'Review the process logs and restart it after addressing the failure',- link: '/apps',- metadata: { processId: process.pm_id, errored: 1, total: alertable.length }- });- }- if ((process.unstableRestarts || 0) > 0) {- alerts.push({- id: alertId('process_crash_loop', process.pm_id),- type: 'process_error',- severity: 'high',- title: `Process in crash loop: ${process.name}`,- detail: `${process.unstableRestarts} crash-loop restarts — review the process logs`,- link: '/apps',- metadata: { processId: process.pm_id, unstableRestarts: process.unstableRestarts, names: [process.name] }- });- }- }-- return alerts;-}+import { generateNonProductAlerts } from './proactiveAlertSources.js';/**- * Check task learning health for critical issues- */-async function checkLearningHealth() {- const perf = await getPerformanceSummary().catch(() => null);- if (!perf) return [];-- const alerts = [];- const recentAttention = (perf.needsAttention || []).filter(hasCurrentPerformanceEvidence);- const skipped = (perf.skipped || []).filter(hasCurrentPerformanceEvidence).length;- const critical = recentAttention.filter(item => item.successRate < 40).length;- const warning = recentAttention.length - critical;-- if (skipped > 0) {- alerts.push({- id: alertId('learning_skipped', 'all'),- type: 'learning_health',- severity: 'high',- title: `${skipped} task type${skipped > 1 ? 's' : ''} being skipped`,- detail: 'Very low success rates caused automatic skip — review task configuration',- link: '/cos/learning',- metadata: { skipped, critical }- });- } else if (critical > 0) {- alerts.push({- id: alertId('learning_critical', 'all'),- type: 'learning_health',- severity: 'medium',- title: `${critical} task type${critical > 1 ? 's' : ''} need attention`,- detail: `Success rates below ${SUCCESS_RATE_WARNING}% — may need provider or prompt adjustments`,- link: '/cos/learning',- metadata: { critical, warning }- });- }-- return alerts;-}--/**- * Detect AI usage spikes (tokens or sessions significantly above rolling average)- */-async function checkUsageSpikes() {- const usage = getUsage();- if (!usage?.dailyActivity) return [];-- const daily = usage.dailyActivity;- const today = new Date().toISOString().split('T')[0];-- // Collect recent days (excluding today since it's incomplete)- const recentDays = [];- for (let i = 1; i <= 14; i++) {- const d = new Date();- d.setDate(d.getDate() - i);- const dateStr = d.toISOString().split('T')[0];- const dayData = daily[dateStr];- if (dayData && dayData.sessions > 0) {- recentDays.push(dayData);- }- }-- if (recentDays.length < USAGE_MIN_HISTORY_DAYS) return [];-- const avgTokens = recentDays.reduce((sum, d) => sum + (d.tokens || 0), 0) / recentDays.length;- const avgSessions = recentDays.reduce((sum, d) => sum + (d.sessions || 0), 0) / recentDays.length;-- const alerts = [];- const todayData = daily[today];-- if (todayData && avgTokens > 0) {- const tokenRatio = todayData.tokens / avgTokens;- if (tokenRatio >= USAGE_SPIKE_MULTIPLIER) {- const formatTokens = (t) => t >= 1000 ? `${(t / 1000).toFixed(1)}k` : String(t);- alerts.push({- id: alertId('cost_spike', 'tokens'),- type: 'cost_spike',- severity: tokenRatio >= 5 ? 'high' : 'medium',- title: 'AI token usage spike',- detail: `${formatTokens(todayData.tokens)} tokens today vs ${formatTokens(Math.round(avgTokens))} avg/day (${tokenRatio.toFixed(1)}x)`,- link: '/devtools/usage',- metadata: { resource: 'tokens', today: todayData.tokens, average: Math.round(avgTokens), ratio: Math.round(tokenRatio * 10) / 10 }- });- }-- const sessionRatio = todayData.sessions / avgSessions;- if (sessionRatio >= USAGE_SPIKE_MULTIPLIER && avgSessions > 0) {- alerts.push({- id: alertId('cost_spike', 'sessions'),- type: 'cost_spike',- severity: sessionRatio >= 5 ? 'high' : 'medium',- title: 'AI session spike',- detail: `${todayData.sessions} sessions today vs ${Math.round(avgSessions)} avg/day (${sessionRatio.toFixed(1)}x)`,- link: '/devtools/usage',- metadata: { resource: 'sessions', today: todayData.sessions, average: Math.round(avgSessions), ratio: Math.round(sessionRatio * 10) / 10 }- });- }- }-- return alerts;-}--/**- * Detect Tribe relationships overdue for contact (or never contacted).- * Quiet when nobody is overdue. Reuses the server-side cadence source of truth.- */-async function checkTribeCadence() {- const summary = await getCareSummary(3).catch(() => null);- if (!summary || summary.overdueCount === 0) return [];-- const names = summary.overdue.map((p) => p.name).filter(Boolean).join(', ');- const overflow = summary.overdueCount > summary.overdue.length ? ', …' : '';- return [{- id: alertId('tribe_cadence', 'all'),- type: 'tribe_cadence',- severity: summary.overdueCount >= 3 ? 'high' : 'medium',- title: `${summary.overdueCount} ${summary.overdueCount === 1 ? 'person is' : 'people are'} overdue for contact`,- detail: names ? `Reach out to ${names}${overflow}` : 'Overdue check-ins in your Tribe',- link: '/tribe',- metadata: { overdueCount: summary.overdueCount, peopleCount: summary.peopleCount }- }];-}--/**- * Detect unanswered inbound threads from Tribe people via the activity timeline- * (#2158). Cadence-only nudges (checkTribeCadence) say "you haven't talked in a- * while"; this says "you never replied to X's message about Y" with real- * conversational grounding. Detection only — NO LLM here (the AI-provider policy- * forbids cold-bootstrap calls); drafting a reply is a separate user-action-gated- * step. Quiet when nothing is unanswered. Reuses the shared detection service.- */-async function checkUnansweredTribeThreads() {- const threads = await findUnansweredTribeThreads().catch(() => []);- if (!threads.length) return [];-- const ago = (days) => (days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${days} days ago`);- return threads.map((t) => {- const snippet = t.snippet ? `“${t.snippet}”` : 'their message';- return {- id: alertId('tribe_unanswered', t.conversationKey),- type: 'tribe_unanswered',- // A week-stale unanswered message from someone you care about is worth more- // than a fresh one still within normal reply latency.- severity: t.daysAgo >= 7 ? 'high' : 'medium',- title: `Unanswered: ${t.personName}`,- detail: `You never replied to ${snippet} (${ago(t.daysAgo)})`,- // Deep-link to the specific outreach item by CONVERSATION (not person — one- // person can have several unanswered threads, e.g. iMessage + Signal), so- // clicking one of several alerts scrolls to and highlights the right thread.- link: `/tribe?tab=care&outreach=${encodeURIComponent(t.conversationKey)}`,- metadata: {- personId: t.personId,- source: t.source,- threadId: t.threadId,- chatGuid: t.chatGuid,- conversationId: t.conversationId,- handle: t.handle,- lastInboundAt: t.lastInboundAt,- daysAgo: t.daysAgo,- },- };- });-}--/**- * Surface user-success gaps alongside infrastructure and CoS health. This is- * deterministic read-only telemetry; it deliberately does not bypass the- * Layered Intelligence delivery throttle or call an AI provider.- */-async function checkProductEngagement() {- const result = await getProductEngagement().catch(() => null);- return result?.actions || [];-}--/**- * Generate all proactive alerts by running all checks.- * Returns a sorted list with critical/high items first.+ * Generate all legacy proactive alerts by combining non-product health+ * signals with the product-engagement compatibility projection.*/export async function generateAlerts() {const startMs = Date.now();-- const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts, unansweredAlerts, productAlerts] = await Promise.all([- checkGoalStalls(),- checkSuccessRates(),- checkSystemHealth(),- checkLearningHealth(),- checkUsageSpikes(),- checkTribeCadence(),- checkUnansweredTribeThreads(),- checkProductEngagement()+ const [nonProductAlerts, productResult] = await Promise.all([+ generateNonProductAlerts(),+ getProductEngagement().catch(() => null),]);+ const productAlerts = productResult?.actions || [];+ const all = [...nonProductAlerts, ...productAlerts];- const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts, ...tribeAlerts, ...unansweredAlerts, ...productAlerts];-- // Sort by severity: critical > high > medium > low+ // Sort by severity: critical > high > medium > low.const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };all.sort((a, b) => (severityOrder[a.severity] ?? 3) - (severityOrder[b.severity] ?? 3));- // Single-pass severity countsconst counts = { total: all.length, critical: 0, high: 0, medium: 0 };- for (const a of all) {- if (counts[a.severity] !== undefined) counts[a.severity]++;+ for (const alert of all) {+ if (counts[alert.severity] !== undefined) counts[alert.severity]++;}const durationMs = Date.now() - startMs;@@ -391,15 +37,12 @@ export async function generateAlerts() {return { alerts: all, counts, checkedAt: new Date().toISOString() };}-/**- * Get a compact summary suitable for dashboard display.- * Returns top 5 alerts and aggregate counts.- */+/** Get a compact summary suitable for dashboard display. */export async function getAlertsSummary() {const result = await generateAlerts();return {alerts: result.alerts.slice(0, 5),counts: result.counts,- checkedAt: result.checkedAt+ checkedAt: result.checkedAt,};}diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 21967f9513..2ddd5f598b 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -34,7 +34,7 @@ import * as askConversations from './askConversations.js';import * as cosTaskStore from './cosTaskStore.js';import * as cosAgentFeedback from './cosAgentFeedback.js';import * as messageDrafts from './messageDrafts.js';-import * as proactiveAlerts from './proactiveAlerts.js';+import { generateNonProductAlerts } from './proactiveAlertSources.js';import * as backup from './backup.js';import * as identity from './identity.js';import * as reviewService from './review.js';@@ -46,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 { getProductEngagement } from './portosProductMetrics.js';import * as reviewQueueTriageStore from './reviewQueueTriageStore.js';import { todayInTimezone } from '../lib/timezone.js';import { isTerminalThreadStatus, threadNextLine } from '../lib/brainThreads.js';@@ -77,6 +78,7 @@ const ACTION_KINDS = Object.freeze({todo: 'review.todo',history: 'review.history',feedback: 'cos.feedback',+ product: 'product.recommendation',});const OPERATION_LABELS = Object.freeze({@@ -98,7 +100,7 @@ const OPERATION_LABELS = Object.freeze({const PRIORITY_ORDER = { HIGH: 0, MEDIUM: 1, LOW: 2 };-// generateAlerts() runs a full system-health sweep (CPU/disk/PM2/goals/usage),+// generateNonProductAlerts() 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// alert list is fine here (the dedicated health views read it live).const ALERTS_TTL_MS = 30_000;@@ -108,7 +110,7 @@ async function getAlertsCached() {if (alertsCache.data && (Date.now() - alertsCache.timestamp) < ALERTS_TTL_MS) {return alertsCache.data;}- const result = await proactiveAlerts.generateAlerts();+ const result = await generateNonProductAlerts();alertsCache = { data: result, timestamp: Date.now() };return result;}@@ -576,13 +578,62 @@ const PRODUCERS = [};},},+ {+ source: 'product',+ label: 'Product recommendations',+ drillTo: '/review',+ preserveTriageActionKinds: [ACTION_KINDS.product],+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {+ const result = await getProductEngagement();+ const actions = Array.isArray(result?.actions) ? result.actions : [];+ const unavailable = [result?.post, result?.creativeCommissions]+ .filter((metric) => metric?.status === 'unavailable');+ if (unavailable.length) {+ const reasons = unavailable+ .map((metric) => metric.reason)+ .filter((reason) => typeof reason === 'string' && reason.trim());+ throw new Error(`Product metrics unavailable${reasons.length ? `: ${reasons.join(', ')}` : ''}`);+ }+ if (actions.some((action) => typeof action?.id !== 'string' || !action.id.trim())) {+ throw new Error('Product recommendation identity is unavailable');+ }+ return {+ items: actions.slice(0, limit),+ truncated: actions.length > limit,+ };+ },+ map(action) {+ const metadata = action.metadata && typeof action.metadata === 'object' && !Array.isArray(action.metadata)+ ? action.metadata+ : {};+ return {+ id: `product:${action.id}`,+ sourceRef: action.id,+ actionKind: ACTION_KINDS.product,+ title: action.title || 'Product recommendation',+ summary: action.detail || '',+ timestamp: action.timestamp || null,+ severity: ['critical', 'high', 'medium', 'normal'].includes(action.severity) ? action.severity : 'normal',+ drillTo: action.link || '/review',+ nextAction: 'Open',+ required: false,+ isRecommendation: true,+ occurrence: action.occurrence ?? null,+ revision: action.revision ?? null,+ operations: [],+ ...(action.featureId ? { featureId: action.featureId } : {}),+ ...(action.featureLabel ? { featureLabel: action.featureLabel } : {}),+ ...(Object.keys(metadata).length ? { meta: metadata } : {}),+ };+ },+ },{source: 'health',label: 'Health anomalies',drillTo: '/system-resources/overview',async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {// System/health alerts; only surface the ones worth interrupting for.- const { alerts = [] } = await getAlertsCached();+ const alerts = await getAlertsCached();const byId = new Map();for (const alert of alerts) {if (alert.severity !== 'critical' && alert.severity !== 'high') continue;@@ -865,6 +916,9 @@ async function gatherProducer(producer, ctx = {}) {total: truncated ? null : list.length,lowerBound: list.length,truncation: truncated,+ preserveTriageActionKinds: Array.isArray(descriptor?.preserveTriageActionKinds)+ ? descriptor.preserveTriageActionKinds+ : (producer.preserveTriageActionKinds || []),};}@@ -1234,11 +1288,17 @@ function sourceShownCounts(items) {return shown;}-async function readQueueTriageForProjection({ now = new Date(), currentItems = [], pruneOrphans = false } = {}) {+async function readQueueTriageForProjection({+ now = new Date(),+ currentItems = [],+ pruneOrphans = false,+ preserveTriageActionKinds = [],+} = {}) {const entries = await reviewQueueTriageStore.listReviewQueueTriage();if (!Array.isArray(entries)) return [];const nowMs = now instanceof Date && Number.isFinite(now.getTime()) ? now.getTime() : Date.now();+ const preservedKinds = new Set(preserveTriageActionKinds);const currentKeys = pruneOrphans? new Set(currentItems.map((item) => reviewQueueTriageStore.triageIdentityKey(queueActionIdentity(item)))): null;@@ -1247,7 +1307,8 @@ async function readQueueTriageForProjection({ now = new Date(), currentItems = [const key = reviewQueueTriageStore.triageIdentityKey(entry);const expired = entry.snoozedUntil && Date.parse(entry.snoozedUntil) <= nowMs;const unused = expired && entry.dismissed !== true && entry.deliveryGeneration === 0;- const orphaned = currentKeys && !currentKeys.has(key);+ const actionKind = typeof entry.actionKey === 'string' ? entry.actionKey.split(':')[0] : null;+ const orphaned = currentKeys && !currentKeys.has(key) && !preservedKinds.has(actionKind);if (unused || orphaned) removableKeys.add(key);}for (const entry of entries) {@@ -1286,6 +1347,7 @@ async function gatherFullQueue(query = {}, { applyTriageState = true, now = newtotal: null,lowerBound: 0,truncation: false,+ preserveTriageActionKinds: producer.preserveTriageActionKinds || [],error: message,};});@@ -1294,10 +1356,12 @@ async function gatherFullQueue(query = {}, { applyTriageState = true, now = newlet items = deduplicateItems(results.flatMap((result) => result.items));if (applyTriageState) {const sourceReadComplete = results.every((result) => result.error === null && !result.truncation);+ const preserveTriageActionKinds = results.flatMap((result) => result.preserveTriageActionKinds || []);const triageEntries = await readQueueTriageForProjection({now: clock,currentItems: items,pruneOrphans: sourceReadComplete && (view === null || view === 'all'),+ preserveTriageActionKinds,});items = applyQueueTriage(items, triageEntries, clock, { includeSnoozed: view === 'snoozed' });}diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex 6f53d37758..2892774f1a 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -8,7 +8,8 @@ const askConversations = { listConversations: vi.fn() };const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn() };const cosAgentFeedback = { getPendingAgentFeedback: vi.fn(), submitAgentFeedback: vi.fn() };const messageDrafts = { listDrafts: vi.fn(), approveDraft: vi.fn() };-const proactiveAlerts = { generateAlerts: vi.fn() };+const proactiveAlerts = { generateNonProductAlerts: vi.fn() };+const productMetrics = { getProductEngagement: vi.fn() };const backup = { getState: vi.fn() };const reviewService = { getItems: vi.fn(), dismissByReferenceId: vi.fn(), completeItem: vi.fn(), reopenItem: vi.fn() };const notifications = { getNotifications: vi.fn() };@@ -47,7 +48,8 @@ vi.mock('./askConversations.js', () => askConversations);vi.mock('./cosTaskStore.js', () => cosTaskStore);vi.mock('./cosAgentFeedback.js', () => cosAgentFeedback);vi.mock('./messageDrafts.js', () => messageDrafts);-vi.mock('./proactiveAlerts.js', () => proactiveAlerts);+vi.mock('./proactiveAlertSources.js', () => proactiveAlerts);+vi.mock('./portosProductMetrics.js', () => productMetrics);vi.mock('./backup.js', () => backup);vi.mock('./review.js', () => reviewService);vi.mock('./notifications.js', () => notifications);@@ -81,7 +83,8 @@ function resetEmpty() {cosAgentFeedback.getPendingAgentFeedback.mockResolvedValue({ agents: [], unavailable: [], count: 0 });cosAgentFeedback.submitAgentFeedback.mockResolvedValue({ success: true });messageDrafts.listDrafts.mockResolvedValue([]);- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([]);+ productMetrics.getProductEngagement.mockResolvedValue({ actions: [] });backup.getState.mockResolvedValue({ status: 'ok', error: null });reviewService.getItems.mockResolvedValue([]);reviewService.dismissByReferenceId.mockResolvedValue(undefined);@@ -102,7 +105,7 @@ describe('reviewQueue.buildQueue', () => {vi.clearAllMocks();resetEmpty();// 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.+ // own generateNonProductAlerts mock rather than a prior case's cached result.__resetAlertsCache();__resetQueueSnapshots();});@@ -146,6 +149,147 @@ describe('reviewQueue.buildQueue', () => {});});+ it('admits product recommendations once per occurrence below required work', async () => {+ brain.getInboxLog.mockResolvedValue([{ id: 'required-1', capturedText: 'required work' }]);+ productMetrics.getProductEngagement.mockResolvedValue({+ actions: [+ {+ id: 'daily-post',+ type: 'post_engagement',+ severity: 'high',+ title: 'Daily POST is waiting',+ detail: 'No POST activity today.',+ link: '/post/launcher',+ occurrence: '2026-09-20',+ },+ {+ id: 'creative-feedback:commission-example:run-1',+ type: 'commission_feedback',+ severity: 'medium',+ title: 'Creative feedback overdue',+ detail: 'A completed render is awaiting review.',+ link: '/creative-commission/commission-example?run=run-1',+ occurrence: 'run-1',+ },+ ],+ post: { status: 'ok' },+ creativeCommissions: { status: 'ok' },+ });++ const queue = await buildQueue();+ const productRows = queue.items.filter((item) => item.source === 'product');++ expect(queue.items[0].id).toBe('brain:required-1');+ expect(productRows).toHaveLength(2);+ expect(productRows).toEqual(expect.arrayContaining([+ expect.objectContaining({+ id: 'product:daily-post',+ sourceRef: 'daily-post',+ actionKind: 'product.recommendation',+ required: false,+ isRecommendation: true,+ occurrence: '2026-09-20',+ triageOperations: [+ { id: 'snooze', label: 'Snooze', available: true },+ { id: 'dismiss', label: 'Dismiss', available: true },+ ],+ }),+ expect.objectContaining({+ id: 'product:creative-feedback:commission-example:run-1',+ occurrence: 'run-1',+ }),+ ]));+ });++ it('reports product-source truncation instead of claiming every recommendation was read', async () => {+ productMetrics.getProductEngagement.mockResolvedValue({+ actions: Array.from({ length: REVIEW_QUEUE_SOURCE_READ_LIMIT + 1 }, (_, index) => ({+ id: `creative-feedback:commission-example:run-${index}`,+ type: 'commission_feedback',+ title: `Feedback ${index}`,+ detail: 'Awaiting review.',+ occurrence: `run-${index}`,+ })),+ post: { status: 'disabled' },+ creativeCommissions: { status: 'ok' },+ });++ const queue = await buildQueue({ limit: 10 });++ expect(queue.sources.product).toMatchObject({+ total: null,+ lowerBound: REVIEW_QUEUE_SOURCE_READ_LIMIT,+ truncation: true,+ availability: 'available',+ error: null,+ });+ expect(queue.partial).toBe(true);+ });++ it('keeps a product triage marker through a disabled source and reapplies it after re-enable', async () => {+ const action = {+ id: 'daily-post',+ type: 'post_engagement',+ title: 'Daily POST is waiting',+ detail: 'No POST activity today.',+ occurrence: '2026-09-20',+ };+ productMetrics.getProductEngagement.mockResolvedValue({+ actions: [action],+ post: { status: 'ok' },+ creativeCommissions: { status: 'ok' },+ });++ await expect(triageQueueItem('product:daily-post', 'dismiss')).resolves.toMatchObject({+ id: 'product:daily-post',+ operation: 'dismiss',+ triaged: true,+ });+ const marker = {+ actionKey: 'product.recommendation:daily-post',+ occurrence: '2026-09-20',+ revision: null,+ dismissed: true,+ deliveryGeneration: 0,+ };+ expect(reviewQueueTriageStore.upsertReviewQueueTriage).toHaveBeenCalledWith(expect.objectContaining(marker));++ reviewQueueTriageStore.listReviewQueueTriage.mockResolvedValue([marker]);+ productMetrics.getProductEngagement.mockResolvedValue({+ actions: [],+ post: { status: 'disabled' },+ creativeCommissions: { status: 'ok' },+ });+ const disabled = await buildQueue();+ expect(disabled.items.find((item) => item.id === 'product:daily-post')).toBeUndefined();+ expect(reviewQueueTriageStore.removeReviewQueueTriage).not.toHaveBeenCalledWith(marker);++ productMetrics.getProductEngagement.mockResolvedValue({+ actions: [action],+ post: { status: 'ok' },+ creativeCommissions: { status: 'ok' },+ });+ const reenabled = await buildQueue();+ expect(reenabled.items.find((item) => item.id === 'product:daily-post')).toBeUndefined();+ });++ it('surfaces product metric read failures as an unavailable source', async () => {+ productMetrics.getProductEngagement.mockResolvedValue({+ actions: [],+ post: { status: 'unavailable', reason: 'post-read-failed' },+ creativeCommissions: { status: 'ok' },+ });++ const queue = await buildQueue();++ expect(queue.sources.product).toMatchObject({+ availability: 'unavailable',+ available: false,+ total: null,+ error: 'Product metrics unavailable: post-read-failed',+ });+ });+it('surfaces pending CoS feedback with a required source-owned Rate operation', async () => {cosAgentFeedback.getPendingAgentFeedback.mockResolvedValue({count: 1,@@ -399,11 +543,11 @@ describe('reviewQueue.buildQueue', () => {});it('only surfaces critical/high health alerts and a failed backup', async () => {- // Real proactiveAlerts shape: { id, type, severity, title, detail, link }.- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [+ // Real non-product alert shape: { id, type, severity, title, detail, link }.+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([{ id: 'system_resource:memory', type: 'system_resource', severity: 'critical', title: 'High memory usage', detail: '95% used', link: '/apps' },{ id: 'goal_stall:example-goal', type: 'goal_stall', severity: 'medium', title: 'meh', detail: 'low' }- ] });+ ]);// Real backup failure shape: status 'error' with an `error` field.backup.getState.mockResolvedValue({ status: 'error', error: 'disk full', lastRun: '2026-06-03T07:00:00.000Z' });const queue = await buildQueue();@@ -414,7 +558,7 @@ describe('reviewQueue.buildQueue', () => {});it('surfaces a degraded backup as a normal-severity warning, not a high-severity failure', async () => {- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([]);// Degraded shape: files saved (status 'degraded') but the DB dump failed,// so an `error` string is also present. Must NOT read as a full failure.backup.getState.mockResolvedValue({ status: 'degraded', error: 'DB dump dump_error', lastRun: '2026-06-03T07:00:00.000Z' });@@ -445,7 +589,7 @@ describe('reviewQueue.buildQueue', () => {actionKey: 'health.investigate:system_resource:memory',snoozedUntil: '2026-09-27T10:00:00.000Z',};- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [alert] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([alert]);reviewQueueTriageStore.listReviewQueueTriage.mockResolvedValueOnce([marker]).mockResolvedValueOnce([marker])@@ -453,7 +597,7 @@ describe('reviewQueue.buildQueue', () => {await buildQueue({ now: new Date('2026-09-20T10:00:00.000Z') });__resetAlertsCache();- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([]);const clear = await buildQueue({ now: new Date('2026-09-20T10:00:00.000Z') });expect(clear.items.find((item) => item.id === 'health:system_resource:memory')).toBeUndefined();expect(reviewQueueTriageStore.removeReviewQueueTriage).toHaveBeenCalledWith(expect.objectContaining({@@ -461,7 +605,7 @@ describe('reviewQueue.buildQueue', () => {}));__resetAlertsCache();- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [alert] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([alert]);const reappeared = await buildQueue({ now: new Date('2026-09-20T10:00:00.000Z') });expect(reappeared.items.find((item) => item.id === 'health:system_resource:memory')).toBeTruthy();});@@ -469,15 +613,15 @@ describe('reviewQueue.buildQueue', () => {it('preserves condition identity through reorder, wording changes and severity escalation', async () => {const memory = { id: 'system_resource:memory', type: 'system_resource', severity: 'high', title: 'High memory', detail: 'mem', link: '/apps' };const cpu = { id: 'system_resource:cpu', type: 'system_resource', severity: 'high', title: 'High CPU', detail: 'cpu', link: '/apps' };- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [memory, cpu] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([memory, cpu]);const first = await buildQueue();expect(first.items.map(i => i.id).sort()).toEqual(['health:system_resource:cpu', 'health:system_resource:memory']);__resetAlertsCache();- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([cpu, { ...memory, title: 'Memory pressure', severity: 'critical' },{ id: 'goal_stall:example', type: 'goal_stall', severity: 'high', title: 'Check goal' }- ] });+ ]);const next = await buildQueue();expect(next.items.find(i => i.title === 'Memory pressure')).toMatchObject({id: 'health:system_resource:memory', severity: 'critical'@@ -485,17 +629,17 @@ describe('reviewQueue.buildQueue', () => {expect(next.items.find(i => i.title === 'High CPU').id).toBe('health:system_resource:cpu');__resetAlertsCache();- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [cpu] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([cpu]);expect((await buildQueue()).items.map(i => i.id)).toEqual(['health:system_resource:cpu']);});it('deduplicates before caps and counts while retaining severity escalation', async () => {const memory = { id: 'system_resource:memory', type: 'system_resource', severity: 'high' };- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([...Array.from({ length: 30 }, () => memory),{ ...memory, severity: 'critical' },{ id: 'system_resource:cpu', type: 'system_resource', severity: 'high' }- ] });+ ]);const queue = await buildQueue();expect(queue.items.map(i => i.id)).toEqual(['health:system_resource:memory', 'health:system_resource:cpu']);expect(queue.sources.health).toMatchObject({ total: 2, shown: 2, error: null });@@ -503,7 +647,7 @@ describe('reviewQueue.buildQueue', () => {});it('reports missing health identity without hiding healthy sources', async () => {- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ type: 'system_resource', severity: 'critical' }] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([{ type: 'system_resource', severity: 'critical' }]);brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify' }]);const queue = await buildQueue();expect(queue.sources.health.error).toBe('Health alert identity is unavailable');@@ -512,7 +656,7 @@ describe('reviewQueue.buildQueue', () => {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' }] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([{ 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 normal brain item.expect(queue.items[0].severity).toBe('critical');@@ -520,7 +664,7 @@ describe('reviewQueue.buildQueue', () => {const past = new Date(Date.now() - 60_000).toISOString();const future = new Date(Date.now() + 60_000).toISOString();- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([]);brain.getInboxLog.mockResolvedValue([{ id: 'optional', capturedText: 'optional', required: false, dueAt: past },{ id: 'required-low', capturedText: 'low', required: true, dueAt: future, priority: 'LOW' },@@ -644,7 +788,7 @@ describe('reviewQueue.buildQueue', () => {brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify', capturedAt: '2026-06-03T10:00:00.000Z' }]);cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'approve me', priority: 'HIGH', createdAt: '2026-06-03T09:00:00.000Z' }] });askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'promote me', promoted: false, turnCount: 1, assistantTurnCount: 1 }]);- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'disk:primary', type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps' }] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([{ id: 'disk:primary', type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps' }]);backup.getState.mockResolvedValue({ status: 'error', error: 'disk full' });const queue = await buildQueue();expect(queue.items.find(i => i.source === 'brain').action).toBe('Done');@@ -662,7 +806,7 @@ describe('reviewQueue.buildQueue', () => {askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'promote me', promoted: false, turnCount: 4, assistantTurnCount: 2 }]);cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'approve me', priority: 'MEDIUM', createdAt: '2026-06-03T09:00:00.000Z' }] });messageDrafts.listDrafts.mockResolvedValue([{ id: 'd1', status: 'draft', subject: 's', to: ['[email protected]'], sendVia: 'gmail', updatedAt: '2026-06-03T08:00:00.000Z' }]);- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'system_resource:memory', type: 'system_resource', severity: 'critical', title: 'mem', detail: 'high', link: '/apps' }] });+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([{ id: 'system_resource:memory', type: 'system_resource', severity: 'critical', title: 'mem', detail: 'high', link: '/apps' }]);const queue = await buildQueue();expect(queue.items.find(i => i.source === 'brain').meta).toEqual({ captureSource: 'voice' });expect(queue.items.find(i => i.source === 'ask').meta).toEqual({ turnCount: 4 });