Skip to content

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

feat: surface product engagement actions

[._.]/ Adam Eivyc5b2f68dfbca
diff --git a/METRICS.md b/METRICS.md
new file mode 100644
index 0000000000..4fe778ad8f
--- /dev/null
+++ b/METRICS.md
@@ -0,0 +1,24 @@
+# Metrics — PortOS
+
+PortOS uses a small set of product-success signals in addition to infrastructure
+and agent-run health. The purpose of these metrics is to identify where the app
+should make the next user action easier or more visible.
+
+| Product outcome | Goal | Signal | Healthy direction |
+| --- | --- | --- | --- |
+| Daily POST engagement | Cognitive training is a daily exercise | Whether scored POST or training activity occurred today; active days in the last 7 and 30 days; unified streak | Activity today and at least 5 active days in 7 |
+| Creative feedback loop | Nightly commissions improve through user taste | Completed renders, unrated completed renders, oldest unrated age, and feedback coverage | Every completed render reviewed, preferably within 24 hours |
+| Action discoverability | The app turns a detected gap into a visible next step | Daily-action projection and reminder delivery are available without an AI call | The user can open the exact POST launcher or commission run from the action |
+
+## Source of truth
+
+The live values are derived by the read-only
+`server/services/portosProductMetrics.js` service from the local POST,
+creative-commission, and Creative Director stores. The dashboard projection is
+available at `GET /api/dashboard/daily-actions`; its `metrics` object preserves
+an explicit `unavailable` status when a source cannot be read.
+
+Layered Intelligence gathers the same aggregate values as its PortOS-only
+`productMetrics` source. It receives counts and ages, not commission names,
+briefs, prompts, or other record contents, and the source never invokes an AI
+provider.
diff --git a/client/src/components/DailyActionsWidget.jsx b/client/src/components/DailyActionsWidget.jsx
new file mode 100644
index 0000000000..c0e72a352a
--- /dev/null
+++ b/client/src/components/DailyActionsWidget.jsx
@@ -0,0 +1,64 @@
+import { memo } from 'react';
+import { Link } from 'react-router';
+import { ArrowRight, Brain, Sparkles } from 'lucide-react';
+
+const ACTION_ICONS = {
+ post_engagement: Brain,
+ commission_feedback: Sparkles,
+};
+
+const ACTION_TONES = {
+ high: 'border-port-warning/50 bg-port-warning/10',
+ medium: 'border-port-accent/40 bg-port-accent/10',
+};
+
+/**
+ * Landing-card projection of the same deterministic actions used by the
+ * proactive-alert and reminder-toast surfaces. It reads dashboardState rather
+ * than fetching inside a widget, so the dashboard has one refresh boundary.
+ */
+const DailyActionsWidget = memo(function DailyActionsWidget({ dashboardState }) {
+ const actions = dashboardState?.dailyActions?.actions || [];
+ if (actions.length === 0) return null;
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6" aria-labelledby="daily-actions-heading">
+ <div className="flex items-center justify-between gap-3 mb-3">
+ <div className="flex items-center gap-3 min-w-0">
+ <div className="shrink-0 p-2 rounded-lg bg-port-warning/10">
+ <ArrowRight className="w-5 h-5 text-port-warning" />
+ </div>
+ <div className="min-w-0">
+ <h3 id="daily-actions-heading" className="text-lg font-semibold text-port-text">Today&apos;s actions</h3>
+ <p className="text-sm text-port-text-muted truncate">Small actions that keep your feedback loops moving</p>
+ </div>
+ </div>
+ <span className="shrink-0 text-xs text-port-warning bg-port-warning/10 rounded-full px-2 py-1">
+ {actions.length} waiting
+ </span>
+ </div>
+
+ <div className="space-y-2">
+ {actions.map((action) => {
+ const Icon = ACTION_ICONS[action.type] || ArrowRight;
+ return (
+ <Link
+ key={action.id}
+ to={action.link || '/'}
+ className={`flex items-start gap-3 p-3 rounded-lg border ${ACTION_TONES[action.severity] || ACTION_TONES.medium} hover:brightness-110 transition-all min-h-[64px] group`}
+ >
+ <Icon size={17} className="mt-0.5 shrink-0 text-port-accent" />
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium text-port-text truncate">{action.title}</span>
+ <span className="block text-xs text-port-text-muted mt-0.5">{action.detail}</span>
+ </span>
+ <ArrowRight size={16} className="mt-0.5 shrink-0 text-port-text-subtle group-hover:text-port-accent transition-colors" />
+ </Link>
+ );
+ })}
+ </div>
+ </section>
+ );
+});
+
+export default DailyActionsWidget;
diff --git a/client/src/components/DailyActionsWidget.test.jsx b/client/src/components/DailyActionsWidget.test.jsx
new file mode 100644
index 0000000000..c9d53c84c6
--- /dev/null
+++ b/client/src/components/DailyActionsWidget.test.jsx
@@ -0,0 +1,31 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import DailyActionsWidget from './DailyActionsWidget';
+
+const renderWidget = (actions) => render(
+ <MemoryRouter>
+ <DailyActionsWidget dashboardState={{ dailyActions: { actions } }} />
+ </MemoryRouter>,
+);
+
+describe('DailyActionsWidget', () => {
+ it('renders deep-linked daily actions from dashboard state', () => {
+ renderWidget([{
+ id: 'daily-post',
+ type: 'post_engagement',
+ severity: 'high',
+ title: 'Daily POST is waiting',
+ detail: 'No POST activity today.',
+ link: '/post/launcher',
+ }]);
+
+ expect(screen.getByRole('heading', { name: "Today's actions" })).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /daily post is waiting.*no post activity today/i })).toHaveAttribute('href', '/post/launcher');
+ });
+
+ it('reserves no card when there are no actions', () => {
+ const { container } = renderWidget([]);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index fb5b7e69c6..10700d69a9 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -116,6 +116,7 @@ import { useErrorNotifications } from '../hooks/useErrorNotifications';
import { useNotifications } from '../hooks/useNotifications';
import { useAgentFeedbackToast } from '../hooks/useAgentFeedbackToast';
import { useOnDemandTaskToast } from '../hooks/useOnDemandTaskToast';
+import { useEngagementReminderToast } from '../hooks/useEngagementReminderToast';
import { useSharingNotifications } from '../hooks/useSharingNotifications';
import UpdateBanners from './UpdateBanners';
import { useAIStatusNotifications } from '../hooks/useAIStatusNotifications';
@@ -688,6 +689,10 @@ export default function Layout() {
// Toast when a user-triggered on-demand task run found no actionable work
useOnDemandTaskToast();
+ // Toast once per tab/day when deterministic product metrics identify a POST
+ // exercise or creative commission feedback action needing attention.
+ useEngagementReminderToast();
+
// Live AI operation status (model loads, "calling LM Studio…", etc.)
useAIStatusNotifications();
diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsx
index ef7344d65b..a079957c9c 100644
--- a/client/src/components/ProactiveAlertsWidget.jsx
+++ b/client/src/components/ProactiveAlertsWidget.jsx
@@ -12,7 +12,9 @@ import {
BookOpen,
CheckCircle,
Users,
- MessageSquareReply
+ MessageSquareReply,
+ Brain,
+ Sparkles
} from 'lucide-react';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
@@ -26,9 +28,9 @@ import ProvenanceChip from './ui/ProvenanceChip';
const ALERT_PROVENANCE = {
level: 'inferred',
explainer:
- 'Detected by your Chief of Staff from trends in your goals, task success rates, costs, and system metrics — inferred from your data, not thresholds you set by hand.',
+ 'Detected by your Chief of Staff from trends in your goals, task success rates, costs, system health, and product engagement — inferred from your data, not thresholds you set by hand.',
whatWouldChange:
- 'As the underlying trend reverses — a goal resumes progress, success rates recover, costs settle — the alert clears on the next sweep.',
+ 'As the underlying trend reverses — a goal resumes progress, success rates recover, costs settle, or a daily action is completed — the alert clears on the next sweep.',
};
const SEVERITY_STYLES = {
@@ -45,7 +47,9 @@ const TYPE_ICONS = {
process_error: AlertOctagon,
learning_health: BookOpen,
tribe_cadence: Users,
- tribe_unanswered: MessageSquareReply
+ tribe_unanswered: MessageSquareReply,
+ post_engagement: Brain,
+ commission_feedback: Sparkles
};
const ProactiveAlertsWidget = memo(function ProactiveAlertsWidget() {
diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsx
index 5af1828235..4651afc1fe 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx
@@ -22,6 +22,7 @@ export const LI_SOURCE_FIELDS = [
{ key: 'planMd', label: 'PLAN.md', hint: 'The app\'s open work-plan items' },
{ key: 'openIssues', label: 'Open issues', hint: 'Currently open tracker issues' },
{ key: 'plannedWork', label: 'Planned work', hint: 'The backlog you\'ve already committed to (plan-labeled issues / prioritized Jira backlog / unchecked PLAN.md items), so the loop won\'t propose work that\'s already in scope' },
+ { key: 'productMetrics', label: 'PortOS product engagement', hint: 'Daily POST activity and creative commission feedback coverage', portosOnly: true },
{ key: 'outcomes', label: 'Proposal outcomes', hint: 'Past LI proposals + how they fared (merge rate), fed back so the loop calibrates on its own results' },
{ key: 'selfEval', label: 'Self-evaluation', hint: 'A deterministic check of the loop\'s own record — merge rate, proposals it has already filed, and whether its own runs are succeeding — so it can judge proposal quality before filing instead of only learning from rejections' }
];
@@ -315,7 +316,7 @@ export default function LayeredIntelligenceTab({ appId, li, onChange, providers,
<div>
<span className="block text-sm text-gray-400 mb-2">Telemetry sources</span>
<div className="space-y-2">
- {LI_SOURCE_FIELDS.map(f => (
+ {LI_SOURCE_FIELDS.filter(f => !f.portosOnly || isPortos).map(f => (
<label key={f.key} className="flex items-start gap-2 cursor-pointer">
<input
type="checkbox"
diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
index 2823303fe5..134888cdaf 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
@@ -8,7 +8,7 @@ const baseline = {
providerId: null,
model: null,
rules: '',
- sources: { goals: true, appMetrics: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },
+ sources: { goals: true, appMetrics: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, productMetrics: true, custom: [] },
allowedScopes: ['app-improvement', 'app-data-gap']
};
diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsx
index ae598a94a3..d203828ae5 100644
--- a/client/src/components/dashboard/widgetRegistry.jsx
+++ b/client/src/components/dashboard/widgetRegistry.jsx
@@ -29,6 +29,7 @@ const MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceS
const AutoFixMetricsWidget = lazyWithReload(() => import('./builtins/AutoFixMetricsWidget'));
const DailyDriverWidget = lazyWithReload(() => import('./builtins/DailyDriverWidget'));
const ActiveProcessingWidget = lazyWithReload(() => import('./ActiveProcessingWidget'));
+const DailyActionsWidget = lazyWithReload(() => import('../DailyActionsWidget'));
// Each entry: { id, label, Component, width, defaultH?, gate? }.
// `gate(state) => bool` skips the widget when it has nothing useful to show.
@@ -40,6 +41,7 @@ const ActiveProcessingWidget = lazyWithReload(() => import('./ActiveProcessingWi
// dashboard cells measure their content and float up (see DashboardGrid), so
// this only has to be in the right ballpark for the first paint.
export const WIDGETS = [
+ { id: 'daily-actions', label: 'Today\'s Actions', Component: DailyActionsWidget, width: 'full', defaultH: 4, gate: (s) => (s.dailyActions?.actions?.length ?? 0) > 0 },
// Daily Driver self-hides once the day is handled — gated on the per-day
// first-visit/handled state so a handled day reserves no grid cell (#2666).
{ id: 'daily-driver', label: 'Daily Driver', Component: DailyDriverWidget, width: 'third', defaultH: 6, gate: (s) => !!s.dailyDriver && !s.dailyDriver.handledToday },
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f7e02c5e61..1070282550 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -24,6 +24,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useAIStatusNotifications` | Subscribes to AI operation status events. | Wire once to surface AI run lifecycle as toasts. |
| `useAgentFeedbackToast` | Agent completion toast with thumbs-up/down UI. | Show actionable agent-run completion feedback. |
| `useOnDemandTaskToast` | Toasts when a user-triggered on-demand task run found no work (parked). | Wire once high in the tree so an explicit "Run" that parks isn't a silent no-op. |
+| `useEngagementReminderToast` | Polls deterministic POST/creative-feedback actions and shows each reminder once per browser tab/day with a deep link. | Wire once high in the tree so daily actions remain visible outside the dashboard. |
| `useSharingNotifications` | Subscriber for share-bucket notifications. | Wire once to surface federation/sync events. |
## Pipeline / Story Builder wiring
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 745adf8a5f..bf204e88ed 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -110,6 +110,7 @@ export * from './useAgentFeedbackToast.jsx';
export * from './useErrorNotifications.js';
export * from './useNotifications.js';
export * from './useOnDemandTaskToast.js';
+export * from './useEngagementReminderToast.jsx';
export * from './useSharingNotifications.js';
// === Pipeline / Story Builder wiring ===
diff --git a/client/src/hooks/useEngagementReminderToast.jsx b/client/src/hooks/useEngagementReminderToast.jsx
new file mode 100644
index 0000000000..46d53c494b
--- /dev/null
+++ b/client/src/hooks/useEngagementReminderToast.jsx
@@ -0,0 +1,75 @@
+import { useCallback, useRef } from 'react';
+import { Link } from 'react-router';
+import toast from '../components/ui/Toast';
+import * as api from '../services/api';
+import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage';
+import { useAutoRefetch } from './useAutoRefetch';
+
+const SESSION_KEY = 'portos:engagement-reminders:v1';
+const MAX_REMINDER_KEYS = 100;
+
+function ReminderToast({ t, action }) {
+ return (
+ <div className="flex flex-col gap-2 max-w-[min(480px,calc(100vw-4rem))]">
+ <div className="flex items-start gap-2">
+ <span className="text-port-warning" aria-hidden="true">⚠️</span>
+ <span className="font-medium text-port-text text-sm flex-1">{action.title}</span>
+ </div>
+ <p className="text-xs text-port-text-muted">{action.detail}</p>
+ <div className="flex items-center gap-2 pt-1 border-t border-port-border/30">
+ <Link
+ to={action.link || '/'}
+ onClick={() => toast.dismiss(t.id)}
+ className="inline-flex items-center justify-center min-h-[40px] px-3 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-xs font-medium"
+ >
+ Open action
+ </Link>
+ <button
+ type="button"
+ onClick={() => toast.dismiss(t.id)}
+ className="inline-flex items-center justify-center min-h-[40px] px-3 text-xs text-port-text-muted hover:text-port-text"
+ >
+ Dismiss
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Poll the deterministic daily-action projection and show each actionable
+ * reminder once per browser tab/day. The session guard keeps a route reload
+ * from repeatedly interrupting the user while still allowing a new day's POST
+ * prompt or the next unrated commission run to surface.
+ */
+export function useEngagementReminderToast() {
+ const shownRef = useRef(null);
+ if (shownRef.current === null) {
+ const stored = safeReadJsonSession(SESSION_KEY, {});
+ shownRef.current = new Set(stored && typeof stored === 'object' ? Object.keys(stored) : []);
+ }
+
+ const showReminder = useCallback((today, action) => {
+ if (!action?.id) return;
+ const key = `${today || 'unknown'}:${action.id}`;
+ if (shownRef.current.has(key)) return;
+ shownRef.current.add(key);
+ const recent = [...shownRef.current].slice(-MAX_REMINDER_KEYS);
+ shownRef.current = new Set(recent);
+ safeWriteJsonSession(SESSION_KEY, Object.fromEntries(recent.map((item) => [item, true])));
+ toast((t) => <ReminderToast t={t} action={action} />, {
+ id: `engagement-reminder-${key}`,
+ duration: 12000,
+ icon: null,
+ label: action.title,
+ });
+ }, []);
+
+ const fetchActions = useCallback(async () => {
+ const data = await api.getDailyActions({ silent: true });
+ for (const action of data?.actions || []) showReminder(data.today, action);
+ return data;
+ }, [showReminder]);
+
+ useAutoRefetch(fetchActions, 300000, { pollOnly: true });
+}
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index aa95fb216d..5b6dd17b20 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -23,6 +23,7 @@ export default function Dashboard() {
const [feeds, setFeeds] = useState(null);
const [meatspaceLogging, setMeatspaceLogging] = useState(null);
const [dailyDriver, setDailyDriver] = useState(null);
+ const [dailyActions, setDailyActions] = useState(null);
const [loading, setLoading] = useState(true);
const [dataError, setDataError] = useState(null);
const [layoutsError, setLayoutsError] = useState(null);
@@ -88,7 +89,7 @@ export default function Dashboard() {
const fetchData = useCallback(async () => {
setDataError(null);
- const [appsData, , usageData, tribeCareData, feedsData, meatspaceLoggingData, dailyDriverData] = await Promise.all([
+ const [appsData, , usageData, tribeCareData, feedsData, meatspaceLoggingData, dailyDriverData, dailyActionsData] = await Promise.all([
api.getApps().catch((err) => { setDataError(err.message); return []; }),
refreshHealth(),
api.getUsage().catch(() => null),
@@ -98,6 +99,7 @@ export default function Dashboard() {
// GET records the first-visit-of-day signal (issue #2666); a failure just
// hides the Daily Driver card via its gate. No LLM calls here.
api.getDailyDriverState().catch(() => null),
+ api.getDailyActions({ silent: true }).catch(() => null),
]);
setApps(appsData);
setUsage(usageData);
@@ -105,6 +107,7 @@ export default function Dashboard() {
setFeeds(feedsData);
setMeatspaceLogging(meatspaceLoggingData);
setDailyDriver(dailyDriverData);
+ setDailyActions(dailyActionsData);
setLoading(false);
}, [refreshHealth]);
@@ -201,8 +204,8 @@ export default function Dashboard() {
}), [activeApps]);
const dashboardState = useMemo(
- () => ({ apps, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, dailyDriver, refetch: fetchData, refetchHealth: refreshHealth }),
- [apps, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, dailyDriver, fetchData, refreshHealth]
+ () => ({ apps, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, dailyDriver, dailyActions, refetch: fetchData, refetchHealth: refreshHealth }),
+ [apps, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, dailyDriver, dailyActions, fetchData, refreshHealth]
);
// Falls back to a local minimal layout only AFTER the initial fetch has
diff --git a/client/src/services/apiDashboard.js b/client/src/services/apiDashboard.js
index ef514959a7..22e3d9cfa8 100644
--- a/client/src/services/apiDashboard.js
+++ b/client/src/services/apiDashboard.js
@@ -2,6 +2,11 @@ import { request } from './apiCore.js';
export const getDashboardLayouts = () => request('/dashboard/layouts');
+// Deterministic product-engagement actions for the dashboard and global
+// reminder toast. The server returns explicit unavailable sentinels inside
+// `metrics`; callers must not turn those into zero-count activity.
+export const getDailyActions = (options = {}) => request('/dashboard/daily-actions', { silent: true, ...options });
+
// All mutations of dashboard-layouts.json are serialized through a single
// module-level promise tail so concurrent callers (Dashboard auto-window,
// Dashboard manual pick, ⌘K palette pick, LayoutEditor save) hit the server
diff --git a/scripts/migrations/297-seed-daily-actions-widget.js b/scripts/migrations/297-seed-daily-actions-widget.js
new file mode 100644
index 0000000000..e6000b3ed2
--- /dev/null
+++ b/scripts/migrations/297-seed-daily-actions-widget.js
@@ -0,0 +1,46 @@
+/**
+ * Seed the deterministic product-engagement action widget into the built-in
+ * Everything and Morning Review layouts. Custom/user layouts are intentionally
+ * untouched: the layout editor is the user's source of truth for those.
+ */
+
+import { readLayoutsDoc, writeLayoutsDoc } from './_lib.js';
+
+const LABEL = 'migration 297';
+const TARGET_LAYOUTS = new Set(['default', 'morning-review']);
+const WIDGET_ID = 'daily-actions';
+
+function applyToLayout(layout) {
+ if (!layout || !TARGET_LAYOUTS.has(layout.id) || !Array.isArray(layout.widgets)) return false;
+ const hasWidget = layout.widgets.includes(WIDGET_ID);
+ const hasGridEntry = Array.isArray(layout.grid) && layout.grid.some((item) => item?.id === WIDGET_ID);
+ if (hasWidget && hasGridEntry) return false;
+
+ if (!hasWidget) layout.widgets = [WIDGET_ID, ...layout.widgets];
+ const existingGrid = (Array.isArray(layout.grid) ? layout.grid : []).filter((item) => item?.id !== WIDGET_ID);
+ const shifted = existingGrid.map((item, index) => ({
+ ...item,
+ order: Number.isFinite(item?.order) ? item.order + 1 : index + 1,
+ }));
+ layout.grid = [
+ { id: WIDGET_ID, x: 0, w: 12, order: 0, h: 4 },
+ ...shifted,
+ ];
+ return true;
+}
+
+export default {
+ async up({ rootDir }) {
+ const result = await readLayoutsDoc({ rootDir, label: LABEL });
+ if (!result.ok) return { updated: 0, reason: result.reason };
+ const { doc, path } = result;
+ let updated = 0;
+ for (const layout of doc.layouts) {
+ if (applyToLayout(layout)) updated += 1;
+ }
+ if (updated === 0) return { updated: 0, reason: 'already-applied' };
+ await writeLayoutsDoc(path, doc);
+ console.log(`📦 ${LABEL}: seeded daily action widget in ${updated} built-in dashboard layout(s).`);
+ return { updated };
+ },
+};
diff --git a/scripts/migrations/297-seed-daily-actions-widget.test.js b/scripts/migrations/297-seed-daily-actions-widget.test.js
new file mode 100644
index 0000000000..59a2af303d
--- /dev/null
+++ b/scripts/migrations/297-seed-daily-actions-widget.test.js
@@ -0,0 +1,71 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './297-seed-daily-actions-widget.js';
+
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
+
+describe('migration 297 — seed daily action dashboard widget', () => {
+ let rootDir;
+ let layoutsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-297-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ layoutsPath = join(rootDir, 'data', 'dashboard-layouts.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('does nothing on a fresh install with no persisted layouts', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });
+ });
+
+ it('prepends the action widget and preserves the existing order', async () => {
+ writeJson(layoutsPath, {
+ activeLayoutId: 'default',
+ layouts: [
+ {
+ id: 'default', name: 'Everything', builtIn: true,
+ widgets: ['quick-brain', 'apps'],
+ grid: [
+ { id: 'quick-brain', x: 0, w: 3, order: 0, h: 2 },
+ { id: 'apps', x: 0, w: 12, order: 1, h: 8 },
+ ],
+ },
+ {
+ id: 'morning-review', name: 'Morning Review', builtIn: true,
+ widgets: ['proactive-alerts'], grid: [{ id: 'proactive-alerts', x: 0, w: 4, order: 0, h: 4 }],
+ },
+ {
+ id: 'custom', name: 'Mine', builtIn: false,
+ widgets: ['quick-brain'], grid: [{ id: 'quick-brain', x: 0, w: 12, order: 0, h: 2 }],
+ },
+ ],
+ });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 2 });
+ const after = readJson(layoutsPath);
+ const seeded = after.layouts.find((layout) => layout.id === 'default');
+ expect(seeded.widgets[0]).toBe('daily-actions');
+ expect(seeded.grid).toEqual([
+ { id: 'daily-actions', x: 0, w: 12, order: 0, h: 4 },
+ { id: 'quick-brain', x: 0, w: 3, order: 1, h: 2 },
+ { id: 'apps', x: 0, w: 12, order: 2, h: 8 },
+ ]);
+ expect(after.layouts.find((layout) => layout.id === 'custom').widgets).toEqual(['quick-brain']);
+ });
+
+ it('is idempotent once both built-ins contain the widget', async () => {
+ writeJson(layoutsPath, {
+ activeLayoutId: 'default',
+ layouts: [
+ { id: 'default', name: 'Everything', widgets: ['daily-actions'], grid: [{ id: 'daily-actions', x: 0, w: 12, order: 0, h: 4 }] },
+ { id: 'morning-review', name: 'Morning Review', widgets: ['daily-actions'], grid: [{ id: 'daily-actions', x: 0, w: 12, order: 0, h: 4 }] },
+ ],
+ });
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ });
+});
diff --git a/server/index.js b/server/index.js
index b98e09fecd..b9bb779ade 100644
--- a/server/index.js
+++ b/server/index.js
@@ -92,6 +92,7 @@ import codeReviewRoutes from './routes/codeReview.js';
import searchRoutes from './routes/search.js';
import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
+import dashboardDailyActionsRoutes from './routes/dashboardDailyActions.js';
import dailyDriverRoutes from './routes/dailyDriver.js';
import mediaCollectionsRoutes from './routes/mediaCollections.js';
import mediaAnnotationsRoutes from './routes/mediaAnnotations.js';
@@ -265,6 +266,7 @@ app.use('/api/shell', shellRoutes);
app.use('/api/search', searchRoutes);
app.use('/api/palette', paletteRoutes);
app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);
+app.use('/api/dashboard/daily-actions', dashboardDailyActionsRoutes);
app.use('/api/daily-driver', dailyDriverRoutes);
app.use('/api/media/collections', mediaCollectionsRoutes);
app.use('/api/media/annotations', mediaAnnotationsRoutes);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index a41208822e..f47f9a961b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -180,6 +180,9 @@ export const layeredIntelligenceConfigSchema = z.object({
// prioritized Jira backlog / PLAN.md's unchecked items, fed in so the reasoner
// can suppress a proposal that overlaps work already in scope. Default on.
plannedWork: z.boolean().optional(),
+ // PortOS-only product-success signals (POST engagement and creative
+ // commission feedback). Managed apps use appMetrics/custom sources.
+ productMetrics: z.boolean().optional(),
// Feedback loop (#2428): feed past LI proposals + their tracker outcomes back
// into the reasoning prompt. Default on for PortOS, off for managed apps.
outcomes: z.boolean().optional(),
diff --git a/server/routes/dashboardDailyActions.js b/server/routes/dashboardDailyActions.js
new file mode 100644
index 0000000000..4d79d1ee6f
--- /dev/null
+++ b/server/routes/dashboardDailyActions.js
@@ -0,0 +1,19 @@
+/**
+ * GET /api/dashboard/daily-actions
+ *
+ * A deterministic, read-only projection of today's product actions. It does
+ * not generate anything or call an AI provider; the client can poll it safely
+ * for a reminder and the dashboard can render the same action list.
+ */
+
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { getDailyActions } from '../services/portosProductMetrics.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await getDailyActions());
+}));
+
+export default router;
diff --git a/server/routes/dashboardDailyActions.test.js b/server/routes/dashboardDailyActions.test.js
new file mode 100644
index 0000000000..4b59b34822
--- /dev/null
+++ b/server/routes/dashboardDailyActions.test.js
@@ -0,0 +1,30 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/portosProductMetrics.js', () => ({
+ getDailyActions: vi.fn(),
+}));
+
+const svc = await import('../services/portosProductMetrics.js');
+const { default: routes } = await import('./dashboardDailyActions.js');
+
+const makeApp = () => {
+ const app = express();
+ app.use('/api/dashboard/daily-actions', routes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('GET /api/dashboard/daily-actions', () => {
+ it('returns the deterministic action projection', async () => {
+ svc.getDailyActions.mockResolvedValue({ today: '2026-08-24', actions: [], metrics: {}, checkedAt: '2026-08-24T12:00:00.000Z' });
+ const response = await request(makeApp()).get('/api/dashboard/daily-actions');
+ expect(response.status).toBe(200);
+ expect(response.body.today).toBe('2026-08-24');
+ expect(svc.getDailyActions).toHaveBeenCalledOnce();
+ });
+});
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index d5691ec499..41cce45634 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -565,14 +565,16 @@ async function clearInlineFeedback(id) {
});
}
-export async function listCommissions() {
+export async function listCommissions({ strict = false } = {}) {
const raw = await commissionStore().listRaw();
const recs = raw.map(sanitizeCommission).filter(Boolean);
// Hydrate the federated feedback view (read-through) in ONE pass — feedback is
// no longer stored inline on the machine-local commission (#2686). Read-only:
// any un-migrated legacy inline feedback is split lazily by getCommission /
// backfillAllCommissionFeedback, not on this hot list path.
- const byId = await listFeedbackByCommissionIds(recs.map((r) => r.id)).catch(() => new Map());
+ const byId = strict
+ ? await listFeedbackByCommissionIds(recs.map((r) => r.id))
+ : await listFeedbackByCommissionIds(recs.map((r) => r.id)).catch(() => new Map());
// Prefer the federated view; fall back to the record's own (sanitized) inline
// feedback only when NO federated reaction exists for it yet — the transient
// pre-migration window before getCommission / backfillAllCommissionFeedback has
diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.js
index 8396ba6fab..1e1c1af9f7 100644
--- a/server/services/dashboardLayouts.js
+++ b/server/services/dashboardLayouts.js
@@ -81,6 +81,27 @@ export const INTENT_LAYOUTS = [
},
];
+// Product engagement is a landing action surface, so seed it at the front of
+// the two user-facing day-start layouts. Existing installs receive the same
+// change through migration 297; custom layouts remain user-owned.
+const seedDailyActions = (layout) => {
+ if (!['default', 'morning-review'].includes(layout.id)) return layout;
+ const existingGrid = Array.isArray(layout.grid) ? layout.grid : [];
+ if (layout.widgets.includes('daily-actions') && existingGrid.some((item) => item.id === 'daily-actions')) return layout;
+ const grid = existingGrid.filter((item) => item.id !== 'daily-actions').map((item) => ({
+ ...item,
+ order: Number.isFinite(item.order) ? item.order + 1 : 1,
+ }));
+ return {
+ ...layout,
+ widgets: layout.widgets.includes('daily-actions') ? layout.widgets : ['daily-actions', ...layout.widgets],
+ grid: [
+ { id: 'daily-actions', x: 0, w: 12, order: 0, h: 4 },
+ ...grid,
+ ],
+ };
+};
+
const DEFAULT_LAYOUTS = [
{
id: 'default',
@@ -190,7 +211,7 @@ const DEFAULT_LAYOUTS = [
],
},
...INTENT_LAYOUTS.map((l) => ({ ...l, builtIn: true })),
-];
+].map(seedDailyActions);
const DEFAULT_STATE = {
activeLayoutId: 'default',
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 8e3ad2cbf3..5d28c7c760 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -160,6 +160,11 @@ describe('defaultLayeredIntelligenceConfig', () => {
expect(defaultLayeredIntelligenceConfig(false).sources.appMetrics).toBe(true);
expect(defaultLayeredIntelligenceConfig(true).sources.appMetrics).toBe(true);
});
+
+ it('defaults PortOS product-engagement metrics on only for the PortOS app', () => {
+ expect(defaultLayeredIntelligenceConfig(false).sources.productMetrics).toBe(false);
+ expect(defaultLayeredIntelligenceConfig(true).sources.productMetrics).toBe(true);
+ });
});
describe('getEffectiveConfig', () => {
@@ -1493,6 +1498,18 @@ describe('buildPrompt', () => {
.toContain('### cosMetrics');
});
+ it('renders PortOS product metrics as a dedicated engagement signal', () => {
+ const prompt = buildPrompt({
+ app,
+ isPortos: true,
+ config: { allowedScopes: ['app-improvement'], rules: '' },
+ sources: { productMetrics: '{"post":{"completedToday":false},"creativeCommissions":{"unreviewedRenders":2}}' },
+ });
+ expect(prompt).toContain('### productMetrics');
+ expect(prompt).toContain('inactive daily POST');
+ expect(prompt.match(/### productMetrics/g)).toHaveLength(1);
+ });
+
it('injects the scope-awareness block only when present, under its own heading (#2760)', () => {
const base = { app, isPortos: true, config: { allowedScopes: ['loop-meta'], rules: '' } };
const without = buildPrompt(base);
diff --git a/server/services/layeredIntelligence/config.js b/server/services/layeredIntelligence/config.js
index 6eb735f650..46ed835007 100644
--- a/server/services/layeredIntelligence/config.js
+++ b/server/services/layeredIntelligence/config.js
@@ -46,6 +46,9 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {
// default for every app: cross-referencing against committed work is only
// useful if it is there by default.
plannedWork: true,
+ // PortOS's own product-success signals (POST activity and creative
+ // commission feedback). Managed apps use appMetrics/custom sources.
+ productMetrics: isPortos,
// The self-feedback signal (#2428): past LI proposals + their tracker
// outcomes, fed back so the reasoner calibrates on its own merge rate.
// Default ON for the PortOS install (it improves itself), OFF for managed
diff --git a/server/services/layeredIntelligence/prompt.js b/server/services/layeredIntelligence/prompt.js
index cea5527fd1..cc4c5d6d8d 100644
--- a/server/services/layeredIntelligence/prompt.js
+++ b/server/services/layeredIntelligence/prompt.js
@@ -15,7 +15,7 @@ import { extractSlugFromBody } from './dedup.js';
// Keeping them in one named set — rather than accreting `&& k !== 'x'` clauses on the
// filter — documents WHY these keys are special and gives the next dedicated-block
// signal a single edit point.
-const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance', 'churnSignals']);
+const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'productMetrics', 'scopeGuidance', 'churnSignals']);
/**
* Build the JSON-only reasoning prompt for one app. Deterministic: given the
@@ -81,6 +81,13 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort
? `\n### plannedWork\n${sources.plannedWork.trim()}\n\n${PLANNED_WORK_GUIDANCE}\n`
: '';
+ // PortOS product-success telemetry: keep the interpretation next to the
+ // aggregate signal so inactivity is evaluated as product evidence, not as a
+ // generic request to add more telemetry.
+ const productMetricsBlock = (isPortos && typeof sources.productMetrics === 'string' && sources.productMetrics.trim())
+ ? `\n### productMetrics\n${sources.productMetrics.trim()}\n\nThese are current PortOS product-engagement signals. Treat an inactive daily POST or overdue creative feedback as evidence that the product should improve its prompts, visibility, or action flow. Prefer a concrete user-facing improvement grounded in these numbers; do not propose generic telemetry when the signal already identifies the engagement gap. If the source says unavailable, do not infer zero activity.\n`
+ : '';
+
// Feedback loop (#2428): show the reasoner how its own past proposals fared so
// it can calibrate scope/merge-rate instead of proposing in a vacuum.
const outcomesBlock = (typeof outcomesReport === 'string' && outcomesReport.trim())
@@ -175,7 +182,7 @@ ${openList}
Gathered sources:
${sourceBlocks || (plannedWorkBlock ? '(no other sources available — you may propose an app-data-gap to add telemetry)' : '(no sources available — you may propose an app-data-gap to add telemetry)')}
-${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${deliveryThrottleBlock}${scopeGuidanceBlock}${churnSignalsBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}
+${plannedWorkBlock}${productMetricsBlock}${outcomesBlock}${selfEvalBlock}${deliveryThrottleBlock}${scopeGuidanceBlock}${churnSignalsBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}
Respond with JSON only (no markdown fences):
{
"analysis": "brief reasoning summary",
diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.js
index 9921706251..7d199acc08 100644
--- a/server/services/layeredIntelligence/sources.js
+++ b/server/services/layeredIntelligence/sources.js
@@ -296,6 +296,14 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShe
const metrics = await tryReadFile(join(repo, 'METRICS.md'));
if (metrics) out.appMetrics = metrics.slice(0, 8000);
}
+ if (src.productMetrics && isPortos) {
+ // Product-success signals come from PortOS's local stores rather than a
+ // repo document. Preserve an unavailable sentinel on read failure so LI
+ // cannot mistake a failed read for zero engagement.
+ out.productMetrics = await import('../portosProductMetrics.js')
+ .then(({ getProductMetricsSource }) => getProductMetricsSource())
+ .catch(() => JSON.stringify({ status: 'unavailable', reason: 'product-metrics-read-failed' }));
+ }
if (src.planMd && repo) {
const plan = await tryReadFile(join(repo, 'PLAN.md'));
if (plan) out.planMd = plan.slice(0, 8000);
diff --git a/server/services/portosProductMetrics.js b/server/services/portosProductMetrics.js
new file mode 100644
index 0000000000..ce1ca84195
--- /dev/null
+++ b/server/services/portosProductMetrics.js
@@ -0,0 +1,302 @@
+/**
+ * PortOS product-engagement metrics.
+ *
+ * This is a read-only signal layer for surfaces that need to answer two
+ * 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.
+ */
+
+import { getPostSessions } from './meatspacePost.js';
+import { getAllTrainingEntries } from './postTrainingLogStore.js';
+import { listCommissions } from './creativeCommissions/store.js';
+import { getProjectsByIds } from './creativeDirector/local.js';
+import { computeUnifiedStreak, recordDayKey, ymdShift, ymdToUTC } from '../lib/postStreak.js';
+import { getUserTimezone, todayInTimezone } from '../lib/timezone.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']);
+
+const isObject = (value) => value && typeof value === 'object' && !Array.isArray(value);
+const asArray = (value) => (Array.isArray(value) ? value : []);
+
+function dateKey(value, timezone) {
+ return recordDayKey(value, timezone);
+}
+
+function windowStart(today, days) {
+ return ymdShift(today, -(days - 1));
+}
+
+function inWindow(date, today, days) {
+ return Boolean(date && date >= windowStart(today, days) && date <= today);
+}
+
+function daysSinceDate(lastDate, today) {
+ if (!lastDate) return null;
+ const age = Math.floor((ymdToUTC(today) - ymdToUTC(lastDate)) / DAY_MS);
+ return Math.max(0, age);
+}
+
+/**
+ * Pure POST activity rollup. Scored sessions and training entries both count
+ * as a daily exercise, while their separate counts remain visible for
+ * evaluation instead of collapsing into one opaque total.
+ */
+export function summarizePostEngagement({ sessions = [], trainingEntries = [], today, timezone }) {
+ if (typeof today !== 'string' || !today) {
+ return { status: 'unavailable', reason: 'missing-local-day' };
+ }
+
+ const scored = asArray(sessions);
+ const training = asArray(trainingEntries);
+ const scoredDates = new Set(scored.map((record) => dateKey(record, timezone)).filter(Boolean));
+ const trainingDates = new Set(training.map((record) => dateKey(record, timezone)).filter(Boolean));
+ const activeDates = new Set([...scoredDates, ...trainingDates]);
+ const lastActiveDate = [...activeDates].sort().at(-1) || null;
+ const unified = computeUnifiedStreak(scored, training, today, timezone);
+
+ const countRecent = (records, days) => records.filter((record) => inWindow(dateKey(record, timezone), today, days)).length;
+ const activeDays = (days) => [...activeDates].filter((date) => inWindow(date, today, days)).length;
+
+ return {
+ status: 'ok',
+ today,
+ completedToday: activeDates.has(today),
+ lastActiveDate,
+ daysSinceActivity: daysSinceDate(lastActiveDate, today),
+ currentStreak: unified.current,
+ longestStreak: unified.longest,
+ activeDaysLast7: activeDays(7),
+ activeDaysLast30: activeDays(30),
+ scoredSessionsLast7: countRecent(scored, 7),
+ scoredSessionsLast30: countRecent(scored, 30),
+ trainingEntriesLast7: countRecent(training, 7),
+ trainingEntriesLast30: countRecent(training, 30),
+ };
+}
+
+function feedbackIsUsable(feedback) {
+ return feedback?.rating === 'up'
+ || feedback?.rating === 'down'
+ || (typeof feedback?.rating === 'number' && feedback.rating !== 0);
+}
+
+function feedbackTimestamp(feedback) {
+ const value = Date.parse(feedback?.at || feedback?.updatedAt || '');
+ return Number.isFinite(value) ? value : null;
+}
+
+function latestFeedbackByRun(feedback) {
+ const latest = new Map();
+ for (const entry of asArray(feedback)) {
+ if (!entry?.runId || !feedbackIsUsable(entry)) continue;
+ const previous = latest.get(entry.runId);
+ const currentAt = feedbackTimestamp(entry) ?? 0;
+ const previousAt = feedbackTimestamp(previous) ?? 0;
+ if (!previous || currentAt >= previousAt) latest.set(entry.runId, entry);
+ }
+ return latest;
+}
+
+function runTimestamp(run) {
+ const value = Date.parse(run?.ranAt || '');
+ return Number.isFinite(value) ? value : null;
+}
+
+function runCanBeReviewed(run, project) {
+ if (!run?.id || !run?.projectId || !isObject(project)) return false;
+ if (NON_REVIEWABLE_RUN_STATUSES.has(run.status)) return false;
+ return COMPLETED_PROJECT_STATUSES.has(project.status);
+}
+
+/**
+ * Pure creative-feedback rollup. A render is reviewable only after its
+ * Creative Director project reaches a terminal success state; an in-flight or
+ * failed commission must never become a false overdue prompt.
+ */
+export function summarizeCreativeFeedback({ commissions = [], projects = [], now = new Date() }) {
+ const projectById = new Map(asArray(projects).filter((project) => project?.id).map((project) => [project.id, project]));
+ const nowMs = now instanceof Date ? now.getTime() : Date.parse(now);
+ const effectiveNow = Number.isFinite(nowMs) ? nowMs : Date.now();
+ const reviewable = [];
+
+ for (const commission of asArray(commissions)) {
+ if (!commission?.id || commission.deleted) continue;
+ const feedbackByRun = latestFeedbackByRun(commission.feedback);
+ for (const run of asArray(commission.runs)) {
+ const ranAtMs = runTimestamp(run);
+ const project = projectById.get(run?.projectId);
+ if (!runCanBeReviewed(run, project) || ranAtMs === null || ranAtMs > effectiveNow) continue;
+ const feedback = feedbackByRun.get(run.id) || null;
+ reviewable.push({
+ commissionId: commission.id,
+ commissionName: typeof commission.name === 'string' && commission.name.trim()
+ ? commission.name.trim().slice(0, 160)
+ : 'Creative commission',
+ runId: run.id,
+ ranAt: new Date(ranAtMs).toISOString(),
+ ageDays: Math.max(0, Math.floor((effectiveNow - ranAtMs) / DAY_MS)),
+ reviewed: Boolean(feedback),
+ });
+ }
+ }
+
+ reviewable.sort((a, b) => Date.parse(a.ranAt) - Date.parse(b.ranAt));
+ const recent = reviewable.filter((entry) => {
+ const ageMs = effectiveNow - Date.parse(entry.ranAt);
+ return ageMs >= 0 && ageMs <= FEEDBACK_WINDOW_DAYS * DAY_MS;
+ });
+ const pendingReviews = reviewable.filter((entry) => !entry.reviewed);
+ const reviewedCount = reviewable.length - pendingReviews.length;
+ const recentReviewedCount = recent.filter((entry) => entry.reviewed).length;
+ const coverage = (reviewed, total) => total > 0 ? Math.round((reviewed / total) * 100) : null;
+
+ return {
+ status: 'ok',
+ configuredCount: asArray(commissions).filter((commission) => commission && !commission.deleted).length,
+ completedRenders: reviewable.length,
+ completedRendersLast30: recent.length,
+ reviewedRenders: reviewedCount,
+ reviewedRendersLast30: recentReviewedCount,
+ unreviewedRenders: pendingReviews.length,
+ unreviewedRendersLast30: recent.filter((entry) => !entry.reviewed).length,
+ oldestUnreviewedAgeDays: pendingReviews.length ? pendingReviews[0].ageDays : null,
+ feedbackCoveragePercent: coverage(reviewedCount, reviewable.length),
+ feedbackCoverageLast30Percent: coverage(recentReviewedCount, recent.length),
+ pendingReviews: pendingReviews.slice(0, ACTION_PENDING_LIMIT),
+ };
+}
+
+function unavailableMetrics(reason) {
+ return { status: 'unavailable', reason };
+}
+
+export function buildProductActions({ post, creativeCommissions }) {
+ const actions = [];
+
+ if (post?.status === 'ok' && !post.completedToday) {
+ const daysSince = post.daysSinceActivity;
+ const detail = daysSince === null
+ ? 'No POST activity is recorded yet — take the daily brain exercise.'
+ : `No POST activity today${daysSince > 0 ? `; the last exercise was ${daysSince} day${daysSince === 1 ? '' : 's'} ago` : ''}.`;
+ actions.push({
+ id: 'daily-post',
+ type: 'post_engagement',
+ severity: daysSince === null || daysSince >= 2 ? 'high' : 'medium',
+ title: 'Daily POST is waiting',
+ detail,
+ link: '/post/launcher',
+ metadata: {
+ completedToday: false,
+ daysSinceActivity: daysSince,
+ activeDaysLast7: post.activeDaysLast7,
+ currentStreak: post.currentStreak,
+ },
+ });
+ }
+
+ 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 ? `await${creativeCommissions.unreviewedRenders === 1 ? 's' : ''}ing review for up to ${age} days` : 'awaiting your rating'}.`,
+ link,
+ metadata: {
+ unreviewedRenders: creativeCommissions.unreviewedRenders,
+ oldestUnreviewedAgeDays: age,
+ feedbackCoveragePercent: creativeCommissions.feedbackCoveragePercent,
+ },
+ });
+ }
+
+ return actions;
+}
+
+export function toProductMetricsAggregate(metrics) {
+ const { pendingReviews: _pendingReviews, ...creative } = metrics.creativeCommissions || {};
+ return {
+ today: metrics.today,
+ post: metrics.post,
+ creativeCommissions: creative,
+ };
+}
+
+/**
+ * Read all product signals. Each feature has an explicit unavailable sentinel,
+ * so a failed read cannot masquerade as an empty history and trigger a false
+ * user reminder or a misleading LI recommendation.
+ */
+export async function getProductEngagement({ now = new Date(), timezone: configuredTimezone } = {}) {
+ const nowDate = now instanceof Date ? now : new Date(now);
+ const timezoneResult = configuredTimezone
+ ? Promise.resolve(configuredTimezone)
+ : getUserTimezone().catch(() => null);
+ const timezone = await timezoneResult;
+ const today = timezone ? todayInTimezone(timezone, nowDate) : null;
+
+ const postPromise = timezone && today
+ ? Promise.all([
+ getPostSessions(undefined, undefined, { strict: true }),
+ getAllTrainingEntries({ strict: true }),
+ ])
+ .then(([sessions, trainingEntries]) => summarizePostEngagement({ sessions, trainingEntries, today, timezone }))
+ .catch(() => null)
+ : Promise.resolve(null);
+
+ const creativePromise = listCommissions({ strict: true })
+ .then(async (commissions) => {
+ const projectIds = [...new Set(asArray(commissions).flatMap((commission) => asArray(commission?.runs)
+ .map((run) => run?.projectId)
+ .filter(Boolean)))];
+ const projects = projectIds.length ? await getProjectsByIds(projectIds) : [];
+ return summarizeCreativeFeedback({ commissions, projects, now: nowDate });
+ })
+ .catch(() => null);
+
+ const [postData, creativeData] = await Promise.all([postPromise, creativePromise]);
+ const metrics = {
+ today,
+ post: postData || unavailableMetrics('post-read-failed'),
+ creativeCommissions: creativeData || unavailableMetrics('creative-read-failed'),
+ };
+ return {
+ ...metrics,
+ actions: buildProductActions(metrics),
+ checkedAt: nowDate.toISOString(),
+ timezone: timezone || null,
+ };
+}
+
+/** Return only aggregate metrics suitable for a Layered Intelligence prompt. */
+export async function getProductMetricsSource(options = {}) {
+ const result = await getProductEngagement(options);
+ return JSON.stringify(toProductMetricsAggregate(result)).slice(0, SOURCE_MAX_CHARS);
+}
+
+/** Return the user-facing daily action projection for the dashboard/toast. */
+export async function getDailyActions(options = {}) {
+ const result = await getProductEngagement(options);
+ return {
+ today: result.today,
+ actions: result.actions,
+ metrics: toProductMetricsAggregate(result),
+ checkedAt: result.checkedAt,
+ };
+}
diff --git a/server/services/portosProductMetrics.test.js b/server/services/portosProductMetrics.test.js
new file mode 100644
index 0000000000..7352004a27
--- /dev/null
+++ b/server/services/portosProductMetrics.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect } from 'vitest';
+import {
+ summarizePostEngagement,
+ summarizeCreativeFeedback,
+ buildProductActions,
+ toProductMetricsAggregate,
+} from './portosProductMetrics.js';
+
+const timezone = 'UTC';
+const today = '2026-08-24';
+
+describe('summarizePostEngagement', () => {
+ it('combines scored and training activity without losing feature-specific counts', () => {
+ const result = summarizePostEngagement({
+ timezone,
+ today,
+ sessions: [{ startedAt: '2026-08-23T12:00:00.000Z', date: '2026-08-23' }],
+ trainingEntries: [{ timestamp: '2026-08-22T12:00:00.000Z', date: '2026-08-22' }],
+ });
+
+ expect(result).toMatchObject({
+ status: 'ok',
+ completedToday: false,
+ lastActiveDate: '2026-08-23',
+ daysSinceActivity: 1,
+ currentStreak: 2,
+ activeDaysLast7: 2,
+ scoredSessionsLast7: 1,
+ trainingEntriesLast7: 1,
+ });
+ });
+
+ it('counts training as today activity and returns an explicit invalid-day sentinel', () => {
+ expect(summarizePostEngagement({ timezone, today, sessions: [], trainingEntries: [
+ { date: today, timestamp: `${today}T08:00:00.000Z` },
+ ] }).completedToday).toBe(true);
+ expect(summarizePostEngagement({ timezone, today: null })).toEqual({
+ status: 'unavailable',
+ reason: 'missing-local-day',
+ });
+ });
+});
+
+describe('summarizeCreativeFeedback', () => {
+ it('counts only completed successful projects and leaves unrated renders actionable', () => {
+ const result = summarizeCreativeFeedback({
+ now: new Date(`${today}T12:00:00.000Z`),
+ commissions: [{
+ id: 'commission-example',
+ name: 'Example Nightly Commission',
+ runs: [
+ { id: 'run-old', projectId: 'project-old', ranAt: '2026-08-20T02:00:00.000Z', status: 'started' },
+ { id: 'run-rated', projectId: 'project-rated', ranAt: '2026-08-23T02:00:00.000Z', status: 'started' },
+ { id: 'run-future', projectId: 'project-future', ranAt: '2026-08-25T02:00:00.000Z', status: 'started' },
+ { id: 'run-failed', projectId: 'project-failed', ranAt: '2026-08-22T02:00:00.000Z', status: 'failed' },
+ { id: 'run-active', projectId: 'project-active', ranAt: '2026-08-21T02:00:00.000Z', status: 'started' },
+ ],
+ feedback: [{ runId: 'run-rated', rating: 'up', at: '2026-08-23T10:00:00.000Z' }],
+ }],
+ projects: [
+ { id: 'project-old', status: 'complete' },
+ { id: 'project-rated', status: 'complete' },
+ { id: 'project-future', status: 'complete' },
+ { id: 'project-failed', status: 'complete' },
+ { id: 'project-active', status: 'rendering' },
+ ],
+ });
+
+ expect(result).toMatchObject({
+ status: 'ok',
+ configuredCount: 1,
+ completedRenders: 2,
+ reviewedRenders: 1,
+ unreviewedRenders: 1,
+ oldestUnreviewedAgeDays: 4,
+ feedbackCoveragePercent: 50,
+ });
+ expect(result.pendingReviews[0]).toMatchObject({
+ commissionId: 'commission-example',
+ runId: 'run-old',
+ commissionName: 'Example Nightly Commission',
+ });
+ });
+});
+
+describe('buildProductActions', () => {
+ it('creates deep-linked POST and feedback actions from current gaps', () => {
+ const actions = buildProductActions({
+ post: {
+ status: 'ok', completedToday: false, daysSinceActivity: 3,
+ activeDaysLast7: 2, currentStreak: 1,
+ },
+ creativeCommissions: {
+ status: 'ok', unreviewedRenders: 1, oldestUnreviewedAgeDays: 4,
+ feedbackCoveragePercent: 0,
+ pendingReviews: [{ commissionId: 'commission-example', commissionName: 'Example', runId: 'run-old' }],
+ },
+ });
+
+ expect(actions).toHaveLength(2);
+ expect(actions[0]).toMatchObject({ type: 'post_engagement', severity: 'high', link: '/post/launcher' });
+ expect(actions[1]).toMatchObject({
+ type: 'commission_feedback',
+ severity: 'high',
+ link: '/creative-commission/commission-example?run=run-old',
+ });
+ });
+
+ it('does not create actions from unavailable metrics', () => {
+ expect(buildProductActions({
+ post: { status: 'unavailable' },
+ creativeCommissions: { status: 'unavailable' },
+ })).toEqual([]);
+ });
+});
+
+describe('toProductMetricsAggregate', () => {
+ it('keeps user-facing action details out of the Layered Intelligence payload', () => {
+ const result = toProductMetricsAggregate({
+ today,
+ post: { status: 'ok', completedToday: false },
+ creativeCommissions: {
+ status: 'ok',
+ unreviewedRenders: 1,
+ pendingReviews: [{ commissionName: 'Example Commission', commissionId: 'commission-example', runId: 'run-example' }],
+ },
+ actions: [{ title: 'Creative feedback overdue: Example Commission', link: '/creative-commission/commission-example' }],
+ });
+
+ expect(result).toEqual({
+ today,
+ post: { status: 'ok', completedToday: false },
+ creativeCommissions: { status: 'ok', unreviewedRenders: 1 },
+ });
+ });
+});
diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.js
index aa420c4d62..f174788df2 100644
--- a/server/services/proactiveAlerts.js
+++ b/server/services/proactiveAlerts.js
@@ -21,6 +21,7 @@ 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;
@@ -319,6 +320,16 @@ async function checkUnansweredTribeThreads() {
});
}
+/**
+ * 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.
@@ -326,17 +337,18 @@ async function checkUnansweredTribeThreads() {
export async function generateAlerts() {
const startMs = Date.now();
- const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts, unansweredAlerts] = await Promise.all([
+ const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts, unansweredAlerts, productAlerts] = await Promise.all([
checkGoalStalls(),
checkSuccessRates(),
checkSystemHealth(),
checkLearningHealth(),
checkUsageSpikes(),
checkTribeCadence(),
- checkUnansweredTribeThreads()
+ checkUnansweredTribeThreads(),
+ checkProductEngagement()
]);
- const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts, ...tribeAlerts, ...unansweredAlerts];
+ const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts, ...tribeAlerts, ...unansweredAlerts, ...productAlerts];
// Sort by severity: critical > high > medium > low
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
diff --git a/server/services/proactiveAlerts.test.js b/server/services/proactiveAlerts.test.js
index 0b3632560f..d601a81a15 100644
--- a/server/services/proactiveAlerts.test.js
+++ b/server/services/proactiveAlerts.test.js
@@ -27,6 +27,9 @@ vi.mock('./tribeOutreach.js', () => ({ findUnansweredTribeThreads: vi.fn(async (
vi.mock('../lib/memoryStats.js', () => ({
getMemoryStats: vi.fn(async () => ({ used: 1, total: 100 }))
}));
+vi.mock('./portosProductMetrics.js', () => ({
+ getProductEngagement: vi.fn(async () => ({ actions: [] }))
+}));
import { generateAlerts } from './proactiveAlerts.js';