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
fix: keep health alerts actionable and honor correction baselines
[._.]/ Adam Eivy4a5c96316f13
diff --git a/client/src/components/ActionQueuePreview.jsx b/client/src/components/ActionQueuePreview.jsxindex f63c1244e9..d54d447934 100644--- a/client/src/components/ActionQueuePreview.jsx+++ b/client/src/components/ActionQueuePreview.jsx@@ -13,7 +13,17 @@ export default function ActionQueuePreview({ title = 'Actions', sources, queue,const items = (data?.items || []).filter((item) => !sources || sources.includes(item.source));const required = items.filter((item) => item.required === true);const optional = items.filter((item) => item.isRecommendation === true);- const lowerBound = data?.partial || Boolean(error);+ const sourceStates = Object.entries(data?.sources || {})+ .filter(([source]) => !sources || sources.includes(source));+ const unavailable = sourceStates.filter(([, state]) => state.availability === 'unavailable' || state.available === false);+ const limited = sourceStates.filter(([, state]) => state.truncation);+ const morePages = sourceStates.some(([, state]) => state.lowerBound > state.shown)+ || (!sources && Boolean(data?.nextCursor));+ // Older servers may not identify the partial source. Keep that uncertainty,+ // but do not spread another source's preview cap into a filtered widget.+ const unknownPartial = data?.partial && sourceStates.length === 0;+ const lowerBound = unavailable.length > 0 || limited.length > 0 || morePages || unknownPartial || Boolean(error);+ const sourceNames = (entries) => entries.map(([source, state]) => state.label || source).join(', ');const groups = [{ label: 'Required', items: required }, { label: 'Optional recommendations', items: optional }];return (<section className={compact ? '@container p-4' : '@container bg-port-card border border-port-border rounded-xl p-4'} aria-labelledby={heading}>@@ -23,8 +33,11 @@ export default function ActionQueuePreview({ title = 'Actions', sources, queue,</div>{loading && !data && <p role="status" className="text-sm text-port-text-muted">Loading actions…</p>}{error && <p role="alert" className="text-sm text-port-warning">{data ? 'Actions could not refresh. Showing the last known actions.' : 'Actions unavailable.'} <button type="button" onClick={live.refetch} className="underline min-h-[44px]">Retry</button></p>}- {data?.partial && <p role="status" className="text-xs text-port-warning mb-2">Some sources are unavailable or truncated. Counts are lower bounds.</p>}- {data && !error && !data.partial && items.length === 0 && <p className="text-sm text-port-text-muted">All caught up!</p>}+ {unavailable.length > 0 && <p role="status" className="text-xs text-port-warning mb-2">Could not load {sourceNames(unavailable)}. <button type="button" onClick={live.refetch} className="underline min-h-[44px]">Retry</button> <Link to="/review?view=today" onClick={onSelect} className="underline">View source details</Link></p>}+ {limited.length > 0 && <p className="text-xs text-port-text-muted mb-2">Showing a limited preview of {sourceNames(limited)}. Open Actions for source details.</p>}+ {unknownPartial && <p role="status" className="text-xs text-port-text-muted mb-2">Action counts are incomplete. Open Actions for source details.</p>}+ {morePages && <p className="text-xs text-port-text-muted mb-2">More actions are available in Open Actions.</p>}+ {data && !lowerBound && items.length === 0 && <p className="text-sm text-port-text-muted">All caught up!</p>}{groups.map((group) => group.items.length > 0 && (<div key={group.label} className="mb-3"><h4 className="text-xs text-port-text-muted mb-1">{group.label}</h4>diff --git a/client/src/components/ActionQueuePreview.test.jsx b/client/src/components/ActionQueuePreview.test.jsxindex 7edf6c2443..36637d0039 100644--- a/client/src/components/ActionQueuePreview.test.jsx+++ b/client/src/components/ActionQueuePreview.test.jsx@@ -68,7 +68,7 @@ describe('canonical action previews', () => {expect(screen.queryByText('All caught up!')).not.toBeInTheDocument();await act(async () => finish(envelope([required], true)));expect(screen.getByRole('button', { name: /at least 1 required actions/ })).toBeInTheDocument();- expect(screen.getAllByText(/Counts are lower bounds/)).toHaveLength(3);+ expect(screen.getAllByText(/Action counts are incomplete/)).toHaveLength(3);mock.getReviewQueue.mockRejectedValue(new Error('offline'));act(() => window.dispatchEvent(new Event(ACTION_QUEUE_CHANGED)));await waitFor(() => expect(screen.getAllByRole('alert')).toHaveLength(3));@@ -76,6 +76,36 @@ describe('canonical action previews', () => {expect(screen.queryByText('All caught up!')).not.toBeInTheDocument();});+ it('treats a source preview limit as context and keeps unrelated widgets healthy', async () => {+ mock.getReviewQueue.mockResolvedValue({ ...envelope([required], true), sources: {+ review: { label: 'Stored review obligations', availability: 'available', truncation: true },+ product: { label: 'Product recommendations', availability: 'available', truncation: false },+ health: { label: 'Health anomalies', availability: 'available', truncation: false },+ } });+ show();+ fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }));+ const daily = screen.getByRole('region', { name: "Today's actions" });+ expect(within(daily).getByText('All caught up!')).toBeInTheDocument();+ expect(within(daily).queryByText(/limited preview|unavailable|incomplete/)).not.toBeInTheDocument();+ const notices = screen.getAllByText(/Showing a limited preview of Stored review obligations/);+ expect(notices).toHaveLength(2);+ for (const notice of notices) expect(notice).not.toHaveClass('text-port-warning');+ expect(screen.queryByText(/Could not load/)).not.toBeInTheDocument();+ });++ it('names failed sources and offers recovery only in affected previews', async () => {+ mock.getReviewQueue.mockResolvedValue({ ...envelope([], true), sources: {+ review: { label: 'Stored review obligations', availability: 'unavailable', available: false },+ product: { label: 'Product recommendations', availability: 'available', truncation: false },+ health: { label: 'Health anomalies', availability: 'available', truncation: false },+ } });+ show();+ const notice = await screen.findByText(/Could not load Stored review obligations/);+ expect(within(notice).getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(within(notice).getByRole('link', { name: 'View source details' })).toHaveAttribute('href', '/review?view=today');+ expect(within(screen.getByRole('region', { name: "Today's actions" })).getByText('All caught up!')).toBeInTheDocument();+ });+it('drops an older response when completion invalidates a pending read', async () => {let finish;mock.getReviewQueue.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));diff --git a/client/src/components/SystemHealthWidget.jsx b/client/src/components/SystemHealthWidget.jsxindex b8e787705a..fe698d082c 100644--- a/client/src/components/SystemHealthWidget.jsx+++ b/client/src/components/SystemHealthWidget.jsx@@ -154,7 +154,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })<HardDrive size={14} className="text-purple-400" /><span className="text-xs text-gray-500">Memory</span></div>- <div className={`text-lg sm:text-xl font-bold ${pctTone(system.memory.usagePercent, thresholds.memoryWarn, thresholds.memoryCritical)}`}>+ <div className="text-lg sm:text-xl font-bold text-port-accent">{system.memory.usagePercent}%</div><div className="text-xs text-gray-500">@@ -162,7 +162,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })</div><div className="mt-2 h-1.5 bg-port-border rounded-full overflow-hidden"><div- className={`h-full rounded-full transition-all ${barTone(system.memory.usagePercent, thresholds.memoryWarn, thresholds.memoryCritical)}`}+ className="h-full rounded-full transition-all bg-port-accent"style={{ width: `${system.memory.usagePercent}%` }}/></div>@@ -174,7 +174,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })<Cpu size={14} className="text-blue-400" /><span className="text-xs text-gray-500">CPU</span></div>- <div className={`text-lg sm:text-xl font-bold ${pctTone(system.cpu.usagePercent, thresholds.cpuWarn, thresholds.cpuCritical)}`}>+ <div className="text-lg sm:text-xl font-bold text-port-accent">{system.cpu.usagePercent}%</div><div className="text-xs text-gray-500">@@ -182,7 +182,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })</div><div className="mt-2 h-1.5 bg-port-border rounded-full overflow-hidden"><div- className={`h-full rounded-full transition-all ${barTone(Math.min(100, system.cpu.usagePercent), thresholds.cpuWarn, thresholds.cpuCritical)}`}+ className="h-full rounded-full transition-all bg-port-accent"style={{ width: `${Math.min(100, system.cpu.usagePercent)}%` }}/></div>diff --git a/client/src/components/SystemHealthWidget.test.jsx b/client/src/components/SystemHealthWidget.test.jsxindex 15b5d02fdf..15e43b0628 100644--- a/client/src/components/SystemHealthWidget.test.jsx+++ b/client/src/components/SystemHealthWidget.test.jsx@@ -73,7 +73,7 @@ describe('SystemHealthWidget', () => {expect(screen.getByRole('link', { name: /Details/ })).toHaveAttribute('href', '/system-resources/overview');});- it('uses configured health thresholds for metric colors', () => {+ it('keeps memory neutral while honoring configured disk thresholds', () => {const health = {...HEALTH,system: {@@ -85,7 +85,7 @@ describe('SystemHealthWidget', () => {};renderWidget({ health, refetchHealth: vi.fn() });- expect(screen.getByText('80%')).toHaveClass('text-port-warning');+ expect(screen.getByText('80%')).toHaveClass('text-port-accent');expect(screen.getByText('91%')).toHaveClass('text-port-success');});@@ -97,7 +97,7 @@ describe('SystemHealthWidget', () => {};renderWidget({ health, refetchHealth: vi.fn() });- expect(screen.getByText('80%')).toHaveClass('text-port-success');+ expect(screen.getByText('80%')).toHaveClass('text-port-accent');});it('dismisses a warning as resolved and refetches health', async () => {diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex 649cabb331..324f928b82 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -437,7 +437,6 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3"><ConfigRow label="Concurrent agents" description="Maximum active agents across all projects." value={formData.maxConcurrentAgents} editing={editing} type="number" inputValue={formData.maxConcurrentAgents} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxConcurrentAgents: value }))} /><ConfigRow label="Agents per project" description="Prevents one project from consuming every agent slot." value={formData.maxConcurrentAgentsPerProject} editing={editing} type="number" inputValue={formData.maxConcurrentAgentsPerProject} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxConcurrentAgentsPerProject: value }))} />- <ConfigRow label="Process memory alert" description="Flags non-model processes above this memory use." value={`${formData.maxProcessMemoryMb} MB`} editing={editing} type="number" inputValue={formData.maxProcessMemoryMb} min={128} suffix="MB" onChange={(value) => setFormData((current) => ({ ...current, maxProcessMemoryMb: value }))} /><ConfigRow label="Process count alert" description="Flags an unexpectedly large PM2 process fleet." value={formData.maxTotalProcesses} editing={editing} type="number" inputValue={formData.maxTotalProcesses} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxTotalProcesses: value }))} /><ConfigRow label="Health check interval" description="How often CoS checks processes and memory." value={`${formData.healthCheckIntervalMs / 60_000} min`} editing={editing} type="number" inputValue={formData.healthCheckIntervalMs / 60_000} min={1} suffix="minutes" onChange={(value) => setFormData((current) => ({ ...current, healthCheckIntervalMs: value * 60_000 }))} /><ConfigRow label="Start on server boot" description="Start the CoS daemon when PortOS starts." value={formData.startOnBoot ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.startOnBoot} onChange={(value) => setFormData((current) => ({ ...current, startOnBoot: value }))} />diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsxindex 1ed21d420c..f47d1823e5 100644--- a/client/src/pages/Review.jsx+++ b/client/src/pages/Review.jsx@@ -1301,6 +1301,7 @@ function ActionDetail({ item, onClose, onResolve, onTriage, triagePending = fals</section>)}+ {item.source === 'health' && <p className="text-sm text-gray-400">Mark resolved after correcting the issue. Earlier runs will no longer count toward run-based alerts; new evidence can raise another alert.</p>}{operations.length > 0 && (<section className="flex flex-wrap gap-2">{operations.map((operation) => (diff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsxindex 92fc65c2b3..e01d43631b 100644--- a/client/src/pages/Review.test.jsx+++ b/client/src/pages/Review.test.jsx@@ -203,6 +203,19 @@ describe('Review Hub queue-card triage (#3282)', () => {expect(screen.getAllByTitle('Delete')).toHaveLength(2);});+ it('lets a corrected health issue be resolved from its card', async () => {+ const item = {+ id: 'health:success_drop:example', source: 'health', sourceLabel: 'Health anomalies',+ title: 'Low success rate: example', summary: '3% success across the last 30 runs',+ operations: [{ id: 'complete', label: 'Mark resolved', available: true }],+ };+ api.getReviewQueue.mockResolvedValueOnce({ partial: false, items: [item], sources: {} });+ render(<Review />);+ fireEvent.click(await screen.findByRole('button', { name: 'Mark resolved' }));+ await waitFor(() => expect(api.resolveReviewQueueItem).toHaveBeenCalledWith(item.id, { operation: 'complete' }));+ await waitFor(() => expect(screen.queryByText(item.title)).not.toBeInTheDocument());+ });+it('forwards an explicit source operation for source-owned queue actions', async () => {api.getReviewQueue.mockResolvedValueOnce({partial: false,diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsxindex 6580dfbc11..7dde9a0367 100644--- a/client/src/pages/SystemHealthPage.jsx+++ b/client/src/pages/SystemHealthPage.jsx@@ -177,13 +177,10 @@ function SystemHealthOverview() {const t = resolveHealthThresholds(health.thresholds);const draftValid =draft &&- draft.memoryWarn < draft.memoryCritical &&draft.diskWarn < draft.diskCritical;const draftDirty =draft &&- (draft.memoryWarn !== t.memoryWarn ||- draft.memoryCritical !== t.memoryCritical ||- draft.diskWarn !== t.diskWarn ||+ (draft.diskWarn !== t.diskWarn ||draft.diskCritical !== t.diskCritical);return (@@ -261,16 +258,12 @@ function SystemHealthOverview() {icon={HardDrive}label="Memory"pct={health.system.memory.usagePercent}- warn={t.memoryWarn}- critical={t.memoryCritical}sub={`${health.system.memory.usedFormatted} / ${health.system.memory.totalFormatted}`}/><ResourceCardicon={Cpu}label="CPU Load (1m)"pct={Math.min(100, health.system.cpu.usagePercent)}- warn={75}- critical={100}sub={`${health.system.cpu.cores} cores · ${health.system.cpu.loadAvg1m.toFixed(2)} load`}/>{health.system.disk && (@@ -322,11 +315,9 @@ function SystemHealthOverview() {<Zap size={16} />Alert thresholds</h3>- <span className="text-xs text-gray-500">Tune to your machine. Defaults: 85/95 mem, 90/98 disk.</span>+ <span className="text-xs text-gray-500">Disk capacity alerts. Defaults: 90/98%.</span></div><div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <ThresholdField id="system-health-memory-warn" label="Memory warn %" value={draft?.memoryWarn} onChange={(v) => setDraft(d => ({ ...d, memoryWarn: v }))} />- <ThresholdField id="system-health-memory-critical" label="Memory critical %" value={draft?.memoryCritical} onChange={(v) => setDraft(d => ({ ...d, memoryCritical: v }))} /><ThresholdField id="system-health-disk-warn" label="Disk warn %" value={draft?.diskWarn} onChange={(v) => setDraft(d => ({ ...d, diskWarn: v }))} /><ThresholdField id="system-health-disk-critical" label="Disk critical %" value={draft?.diskCritical} onChange={(v) => setDraft(d => ({ ...d, diskCritical: v }))} /></div>@@ -360,13 +351,13 @@ function ResourceCard({ icon: Icon, label, pct, warn, critical, sub }) {<Icon size={14} />{label}</div>- <div className={`text-3xl font-bold ${pctTone(pct, warn, critical)}`}>{Math.round(pct)}%</div>+ <div className={`text-3xl font-bold ${warn == null ? 'text-port-accent' : pctTone(pct, warn, critical)}`}>{Math.round(pct)}%</div><div className="text-xs text-gray-500 mt-1">{sub}</div><div className="mt-3 h-1.5 bg-port-border rounded-full overflow-hidden">- <div className={`h-full ${barTone(pct, warn, critical)} transition-all`} style={{ width: `${Math.min(100, pct)}%` }} />+ <div className={`h-full ${warn == null ? 'bg-port-accent' : barTone(pct, warn, critical)} transition-all`} style={{ width: `${Math.min(100, pct)}%` }} /></div><div className="mt-2 text-[11px] text-gray-600">- warn {warn}% · critical {critical}%+ {warn == null ? 'Usage telemetry — does not affect health' : `warn ${warn}% · critical ${critical}%`}</div></div>);diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex f901b2e525..8661357f02 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -37,7 +37,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `memories` / `memory_links` — long-term memory + pgvector similarity.- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and this ledger has no cross-machine merge contract. This is a store-specific implementation boundary, not a ban on syncing personal records to the user's own machines (ADR [user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).-- `review_queue_triage` — the Review Hub's machine-local presentation and delivery markers: canonical `action_key` plus `occurrence`/`revision`, `snoozed_until`, optional recommendation `dismissed`, and `delivery_generation`. Delivery-only keys use `delivery:<canonical-id>` plus occurrence (empty revision); the additive `delivery` JSONB holds severity and per-channel generations. It contains no queue title, summary, prompt, source payload, or notification-read state; the live producer remains authoritative. New occurrence/revision gets a fresh presentation decision, but a text revision does not reset delivery. **Intentionally machine-local — never federated**, including when the source row is a federated Brain record. PostgreSQL is authoritative and the normal `pg_dump` captures it; the JSON adapter exists only for the documented dev/test file escape hatch. Adapter: `server/services/reviewQueueTriageStore.js`.+- `review_queue_triage` — the Review Hub's machine-local presentation and delivery markers: canonical `action_key` plus `occurrence`/`revision`, `snoozed_until`, optional recommendation `dismissed`, and `delivery_generation`. Delivery-only keys use `delivery:<canonical-id>` plus occurrence (empty revision); the additive `delivery` JSONB holds severity and per-channel generations. Health correction keys use `health.resolved:<alert-id>` with the correction timestamp as `occurrence` and a SHA-256 evidence fingerprint as `revision`; these durable baselines survive queue pruning and exclude earlier run evidence from future alerts without changing source history. It contains no queue title, summary, prompt, source payload, or notification-read state; the live producer remains authoritative. New occurrence/revision gets a fresh presentation decision, but a text revision does not reset delivery. **Intentionally machine-local — never federated**, including when the source row is a federated Brain record. PostgreSQL is authoritative and the normal `pg_dump` captures it; the JSON adapter exists only for the documented dev/test file escape hatch. Adapter: `server/services/reviewQueueTriageStore.js`.- `cos_pending_agent_feedback` — a bounded, machine-local index of completed manual CoS runs that still need a human rating. It stores only `agent_id` plus the archive date locator; the agent archive remains the source-owned record and the rating is removed from this index only after that archive carries the durable rating. PostgreSQL is authoritative in normal installs (with the documented file backend only for dev/test), the input-gated migration 008 derives existing refs from live state without a seed or provider call, and future completion events enroll new refs. **Intentionally machine-local — never federated**; the DB dump backs it up alongside the agent archive under the filesystem snapshot. Adapter: `server/services/cosAgentFeedbackStore.js`.- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.diff --git a/docs/decisions/2026-09-21-actionable-system-alerts.md b/docs/decisions/2026-09-21-actionable-system-alerts.mdnew file mode 100644index 0000000000..e2fe16ffd3--- /dev/null+++ b/docs/decisions/2026-09-21-actionable-system-alerts.md@@ -0,0 +1,50 @@+# System alerts report actionable failures++Memory occupancy and short CPU-load samples are usage telemetry, not health+failures. Machines routinely fill RAM with models and run their CPUs at capacity.+Keep those measurements and process rankings, but do not turn them into warnings,+critical colors, Review items, or degraded health. Memory threshold fields remain+accepted for compatibility with older clients; the current UI no longer offers+controls that have no effect.++The alert audit retains these signals:++- Disk capacity nearing exhaustion: free storage before writes fail.+- Errored processes, crash loops, or failed automatic restart: inspect logs and repair.+- Process count exceeding the operator's configured limit: inspect runaway processes.+- Unavailable app status, database/schema, forge access, or reviewer configuration:+ restore the failed dependency or configuration.+- Recent task failures or skipped task types: repair the provider/prompt/task setup.+- Stalled goals and overdue relationships/replies: make the corresponding personal decision.+- Explicit approvals, unresolved task blocks, and requested feedback: provide the input.++Successful automatic restarts remain activity logs, not unresolved health issues.+Token/session volume spikes remain usage statistics: neither demonstrates actual+unexpected spending, so they must not produce a cost alert.++CoS-created Brain commitments with a `cos.task` reference consult their task's+current state before entering the Review queue. Queued/running automation,+completed/cancelled tasks, and timed cooldowns do not require human review.+Pending approvals and unresolved blocks remain visible. Missing tasks remain+visible; a failed task read reports source unavailability. Personal commitments+and history are preserved. This read-time projection covers existing recovery+threads without deleting records or rewriting user-owned state.++Health anomalies offer **Mark resolved**. Acknowledgements persist in the existing+machine-local Review triage store as `health.resolved:<alert-id>` actions, with+resolution time as occurrence and an evidence hash as revision. This adds a key+namespace, not an on-disk format or schema. The latest acknowledgement wins, even+if concurrent writes finish out of order, and queue pruning preserves it.++For low-success and learning warnings, only dated outcomes strictly after the+correction time count. Five new outcomes are required before another run-based+alert can appear. Neither lifetime learning history nor scheduler policy is+reset. Other alerts compare stable source evidence, so a renamed title or another+day passing does not resurrect an acknowledged issue. Changed failure evidence+can raise a new alert.++Compact action previews distinguish unavailable sources from bounded reads.+Preview limits use neutral explanatory text; real failures name their source and+offer Retry. A filtered widget derives completeness from its own sources, not+from an unrelated source's cap. Counts remain explicitly lower bounds when the+relevant source is incomplete or another page contains relevant actions.diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex 51205d9c88..db223b49cc 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -1,5 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import os from 'os';+import { checkHealth } from '../lib/db.js';+import { getMemoryStats } from '../lib/memoryStats.js';import express from 'express';import { request } from '../lib/testHelper.js';import systemHealthRoutes from './systemHealth.js';@@ -193,6 +195,22 @@ describe('System Health Routes', () => {});+ it('reports saturated memory and CPU without degrading health', async () => {+ checkHealth.mockResolvedValueOnce({ connected: true, hasSchema: true });+ getMemoryStats.mockResolvedValueOnce({ total: 100, used: 99, free: 1 });+ const load = vi.spyOn(os, 'loadavg').mockReturnValue([1000, 1000, 1000]);+ try {+ const response = await request(app).get('/api/system/health/details');+ expect(response.status).toBe(200);+ expect(response.body.system.memory.usagePercent).toBe(99);+ expect(response.body.system.cpu.usagePercent).toBeGreaterThan(100);+ expect(response.body.warnings).toEqual([]);+ expect(response.body.overallHealth).toBe('healthy');+ } finally {+ load.mockRestore();+ }+ });+it('does not warn on cumulative restart_time (developer-driven restarts)', async () => {listProcesses.mockResolvedValueOnce([{ name: 'portos', status: 'online', restarts: 97, unstableRestarts: 0, cpu: 0, memory: 0 }diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 1eb05cc908..fd8c426287 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -21,11 +21,8 @@ import { getMediaCapacity } from '../services/mediaCapacity.js';import { runningAgentsByTaskId, unclaimedTaskIds } from '../lib/cosSpawnWindow.js';import { getBuildIdentity } from '../lib/buildIdentity.js';-// Defaults are tuned for a real dev machine: memory routinely sits in the-// 75-85% band on a host with a couple of LLMs loaded, and big SSDs commonly-// run >85% before being a real problem. Earlier thresholds (75/90 mem,-// 85/95 disk) fired warnings on every healthy laptop. Users can override-// these from /system-resources/overview (persisted to settings.json under `health`).+// Disk capacity remains actionable. Memory thresholds are retained on the wire+// for older clients, but no longer generate warnings or degrade health.const DEFAULT_THRESHOLDS = {memoryWarn: 85,memoryCritical: 95,@@ -215,15 +212,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {// dismissals are filtered out, from whatever warnings remain visible.const rawWarnings = [];- if (memUsagePercent >= thresholds.memoryCritical) {- rawWarnings.push({ type: 'memory', severity: 'critical', message: `Memory usage at or above ${thresholds.memoryCritical}%` });- } else if (memUsagePercent >= thresholds.memoryWarn) {- rawWarnings.push({ type: 'memory', severity: 'warning', message: `Memory usage at or above ${thresholds.memoryWarn}%` });- }-- if (cpuUsagePercent > 100) {- rawWarnings.push({ type: 'cpu', severity: 'warning', message: 'CPU load high' });- }+ // Memory occupancy and CPU load describe work, not a health failure.if (disk) {if (disk.usagePercent >= thresholds.diskCritical) {diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.jsindex 2d1d883073..8eb5c7b6e9 100644--- a/server/services/cosHealthMonitor.js+++ b/server/services/cosHealthMonitor.js@@ -9,7 +9,6 @@import { execPm2 } from './pm2.js';import { safeJSONParse } from '../lib/fileUtils.js';import { getMemoryStats } from '../lib/memoryStats.js';-import { isModelServerProcess } from '../lib/managedDaemon.js';import { loadState, saveState, withStateLock, isDaemonRunning } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';import { annotateExpectedExit } from './apps.js';@@ -107,37 +106,9 @@ export async function runHealthCheck() {message: `${failedRestarts.length} errored PM2 process(es) failed to auto-restart: ${failedRestarts.map(r => r.name).join(', ')}`});}-- const succeededRestarts = restartResults.filter(r => r.success);- if (succeededRestarts.length > 0) {- issues.push({- type: 'warning',- category: 'processes',- message: `Auto-restarted ${succeededRestarts.length} errored PM2 process(es): ${succeededRestarts.map(r => r.name).join(', ')}`- });- }- }-- // Check memory usage per process. The local model servers are exempt: their- // resident size is the checkpoint they loaded, so a healthy llama-server or- // MTPLX sits tens of GB over any generic cap from the moment it starts, and- // the warning it raises can never be cleared. Host-wide pressure — where an- // oversized model actually matters — is reported by proactiveAlerts.js.- // Releasing that memory while nothing is using it is issue #4863.- const highMemoryProcesses = pm2Processes.filter(p => {- if (isModelServerProcess(p?.name)) return false;- const memMb = (p.monit?.memory || 0) / (1024 * 1024);- return memMb > state.config.maxProcessMemoryMb;- });-- if (highMemoryProcesses.length > 0) {- issues.push({- type: 'warning',- category: 'memory',- message: `High memory usage in: ${highMemoryProcesses.map(p => `${p.name} (${Math.round((p.monit?.memory || 0) / (1024 * 1024))}MB)`).join(', ')}`- });}+ // Keep memory telemetry without treating expected occupancy as a failure.metrics.memory = await getMemoryStats();// Store health check result with lock to prevent race conditions@@ -165,6 +136,8 @@ export async function getHealthStatus() {const state = await loadState();return {lastCheck: state.stats.lastHealthCheck,- issues: state.stats.healthIssues || []+ // Older snapshots can survive until the next daemon poll.+ issues: (state.stats.healthIssues || []).filter(issue => issue.category !== 'memory'+ && !(issue.category === 'processes' && issue.message?.startsWith('Auto-restarted ')))};}diff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.jsindex de8afa3f78..69fd4f78f6 100644--- a/server/services/cosHealthMonitor.test.js+++ b/server/services/cosHealthMonitor.test.js@@ -95,10 +95,10 @@ describe('cosHealthMonitor.runHealthCheck', () => {expect(issues.some(i => i.category === 'processes' && /High process count/.test(i.message))).toBe(true);});- it('auto-restarts errored processes and records a warning on success', async () => {+ it('auto-restarts errored processes without reporting a resolved problem', async () => {mock.pm2Stdout = JSON.stringify([{ name: 'boom', pm2_env: { status: 'errored' }, monit: { memory: 0 } }]);const { issues } = await runHealthCheck();- expect(issues.some(i => i.type === 'warning' && /Auto-restarted 1/.test(i.message))).toBe(true);+ expect(issues).toEqual([]);expect(issues.some(i => i.type === 'error')).toBe(false);});@@ -180,7 +180,7 @@ describe('cosHealthMonitor.runHealthCheck', () => {expect(restarted).toEqual(['web']);expect(metrics.pm2.errored).toBe(1);- expect(issues.some(i => /Auto-restarted 1/.test(i.message))).toBe(true);+ expect(issues).toEqual([]);});it('exempts nothing when the registry read fails (pre-existing behavior stands)', async () => {@@ -198,36 +198,14 @@ describe('cosHealthMonitor.runHealthCheck', () => {});});- it('flags processes over the memory limit', async () => {- const overLimitBytes = 2048 * 1024 * 1024;- mock.pm2Stdout = JSON.stringify([{ name: 'hog', pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } }]);- const { issues } = await runHealthCheck();- expect(issues.some(i => i.category === 'memory' && /High memory usage/.test(i.message))).toBe(true);- });-- // A model server's RSS is the checkpoint it loaded, so it clears any generic- // cap the moment it comes up — flagging it produced a warning the user could- // never clear, on every install that runs a local model.- describe('model servers are exempt from the per-process memory cap', () => {- const overLimitBytes = 24 * 1024 * 1024 * 1024;-- it.each(['portos-llama-server', 'portos-mtplx'])('does not flag %s', async (name) => {- mock.pm2Stdout = JSON.stringify([{ name, pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } }]);- const { issues } = await runHealthCheck();- expect(issues.filter(i => i.category === 'memory')).toEqual([]);- });-- it('still flags a non-model-server process alongside an exempt one', async () => {- mock.pm2Stdout = JSON.stringify([- { name: 'portos-llama-server', pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } },- { name: 'hog', pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } }- ]);- const { issues } = await runHealthCheck();- const memoryIssues = issues.filter(i => i.category === 'memory');- expect(memoryIssues).toHaveLength(1);- expect(memoryIssues[0].message).toContain('hog');- expect(memoryIssues[0].message).not.toContain('portos-llama-server');- });+ it('keeps memory telemetry without flagging large processes', async () => {+ mock.pm2Stdout = JSON.stringify([+ { name: 'example-worker', pm2_env: { status: 'online' }, monit: { memory: 24 * 1024 ** 3 } },+ { name: 'portos-llama-server', pm2_env: { status: 'online' }, monit: { memory: 24 * 1024 ** 3 } }+ ]);+ const { metrics, issues } = await runHealthCheck();+ expect(metrics.memory).toEqual({ usedMb: 100 });+ expect(issues).toEqual([]);});it('persists the latest snapshot to state and emits health:check', async () => {@@ -245,6 +223,16 @@ describe('cosHealthMonitor.getHealthStatus', () => {expect(status).toEqual({ lastCheck: 'T', issues: [{ type: 'warning' }] });});+ it('drops legacy memory and successful-restart warnings before the next poll', async () => {+ const failure = { type: 'error', category: 'processes', message: 'Failed to restart' };+ mock.state = { ...baseState(), stats: { healthIssues: [+ { type: 'warning', category: 'memory', message: 'High memory usage' },+ { type: 'warning', category: 'processes', message: 'Auto-restarted 1 errored PM2 process(es)' },+ failure+ ] } };+ expect((await getHealthStatus()).issues).toEqual([failure]);+ });+it('defaults issues to an empty array when none recorded', async () => {mock.state = { ...baseState(), stats: {} };const status = await getHealthStatus();diff --git a/server/services/healthAlertResolutions.js b/server/services/healthAlertResolutions.jsnew file mode 100644index 0000000000..16dfc7b219--- /dev/null+++ b/server/services/healthAlertResolutions.js@@ -0,0 +1,36 @@+/** Machine-local acknowledgement baselines; source evidence remains untouched. */+import { createHash } from 'node:crypto';+import { listReviewQueueTriage, upsertReviewQueueTriage } from './reviewQueueTriageStore.js';++export const HEALTH_RESOLUTION_PREFIX = 'health.resolved:';++// A resolution is its own action occurrence. Reuse the existing durable triage+// identity: occurrence records when it happened, revision fingerprints evidence.+// No titles, personal records, or copies of source payloads are persisted.+export async function getHealthAlertResolutions() {+ const entries = await listReviewQueueTriage();+ const resolutions = new Map();+ for (const entry of entries) {+ if (!entry.actionKey.startsWith(HEALTH_RESOLUTION_PREFIX) || !Number.isFinite(Date.parse(entry.occurrence))) continue;+ const id = entry.actionKey.slice(HEALTH_RESOLUTION_PREFIX.length);+ if (!resolutions.has(id) || Date.parse(entry.occurrence) > Date.parse(resolutions.get(id).at)) {+ resolutions.set(id, { at: entry.occurrence, evidence: entry.revision });+ }+ }+ return resolutions;+}++export function healthAlertEvidence(alert) {+ // Producers supply stable evidence, not rolling display text (e.g. days ago).+ const evidence = alert.evidence ?? alert.metadata ?? { message: alert.detail || alert.message };+ return createHash('sha256').update(JSON.stringify(evidence)).digest('hex');+}++export async function recordHealthAlertResolution(alert, now = new Date()) {+ return upsertReviewQueueTriage({+ actionKey: `${HEALTH_RESOLUTION_PREFIX}${alert.id}`,+ occurrence: now.toISOString(),+ revision: healthAlertEvidence(alert),+ dismissed: true,+ });+}diff --git a/server/services/proactiveAlertSources.js b/server/services/proactiveAlertSources.jsindex af15432e91..696450a8b1 100644--- a/server/services/proactiveAlertSources.js+++ b/server/services/proactiveAlertSources.js@@ -7,23 +7,16 @@* aggregate that also consumes the queue's product actions.*/-import os from 'os';+import { getHealthAlertResolutions, healthAlertEvidence, recordHealthAlertResolution } from './healthAlertResolutions.js';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@@ -65,6 +58,7 @@ async function checkGoalStalls() {detail: `No progress in ${daysSince} days`,link: '/goals',metadata: { goalId: goal.id, daysSince, progress: goal.progress || 0 },+ evidence: { goalId: goal.id, lastUpdate, progress: goal.progress || 0 },});}}@@ -82,8 +76,7 @@ function hasCurrentPerformanceEvidence(item) {}/** Detect recently active task types with poor success rates. */-async function checkSuccessRates() {- const perf = await getPerformanceSummary().catch(() => null);+async function checkSuccessRates(perf) {if (!perf) return [];return (perf.needsAttention || [])@@ -105,41 +98,11 @@ async function checkSuccessRates() {}));}-/** Check for system resource warnings (memory, CPU, errored processes). */+/** Check for failed processes requiring intervention. */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 },- });- }+ // Resource occupancy is telemetry: busy machines are not broken machines.// 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@@ -156,6 +119,7 @@ async function checkSystemHealth() {detail: 'Review the process logs and restart it after addressing the failure',link: '/apps',metadata: { processId: process.pm_id, errored: 1, total: alertable.length },+ evidence: { processId: process.pm_id, status: process.status, restarts: process.restarts || 0 },});}if ((process.unstableRestarts || 0) > 0) {@@ -167,6 +131,7 @@ async function checkSystemHealth() {detail: `${process.unstableRestarts} crash-loop restarts — review the process logs`,link: '/apps',metadata: { processId: process.pm_id, unstableRestarts: process.unstableRestarts, names: [process.name] },+ evidence: { processId: process.pm_id, unstableRestarts: process.unstableRestarts, restarts: process.restarts || 0 },});}}@@ -175,8 +140,7 @@ async function checkSystemHealth() {}/** Check task learning health for critical issues. */-async function checkLearningHealth() {- const perf = await getPerformanceSummary().catch(() => null);+async function checkLearningHealth(perf) {if (!perf) return [];const alerts = [];@@ -210,61 +174,6 @@ async function checkLearningHealth() {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);@@ -280,6 +189,7 @@ async function checkTribeCadence() {detail: names ? `Reach out to ${names}${overflow}` : 'Overdue check-ins in your Tribe',link: '/tribe',metadata: { overdueCount: summary.overdueCount, peopleCount: summary.peopleCount },+ evidence: { overdueCount: summary.overdueCount, people: summary.overdue.map(person => ({ id: person.id, lastContact: person.lastContact })) },}];}@@ -301,6 +211,7 @@ async function checkUnansweredTribeThreads() {title: `Unanswered: ${thread.personName}`,detail: `You never replied to ${snippet} (${ago(thread.daysAgo)})`,link: `/tribe?tab=care&outreach=${encodeURIComponent(thread.conversationKey)}`,+ evidence: { conversationKey: thread.conversationKey, lastInboundAt: thread.lastInboundAt },metadata: {personId: thread.personId,source: thread.source,@@ -320,12 +231,19 @@ async function checkUnansweredTribeThreads() {* 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([+ const resolutions = await getHealthAlertResolutions();+ const sinceByTaskType = Object.create(null);+ let learningSince = null;+ for (const [id, resolution] of resolutions) {+ if (id.startsWith('success_drop:')) sinceByTaskType[decodeURIComponent(id.slice('success_drop:'.length))] = resolution.at;+ if (id.startsWith('learning_') && (!learningSince || resolution.at > learningSince)) learningSince = resolution.at;+ }+ const performance = await getPerformanceSummary({ sinceByTaskType, since: learningSince }).catch(() => null);+ const [goalAlerts, successAlerts, systemAlerts, learningAlerts, tribeAlerts, unansweredAlerts] = await Promise.all([checkGoalStalls(),- checkSuccessRates(),+ checkSuccessRates(performance),checkSystemHealth(),- checkLearningHealth(),- checkUsageSpikes(),+ checkLearningHealth(performance),checkTribeCadence(),checkUnansweredTribeThreads(),]);@@ -334,8 +252,29 @@ export async function generateNonProductAlerts() {...successAlerts,...systemAlerts,...learningAlerts,- ...usageAlerts,...tribeAlerts,...unansweredAlerts,- ];+ ].filter(alert => {+ // Run-based alerts have already excluded every outcome before resolution.+ if (alert.type === 'success_drop' || alert.type === 'learning_health') return true;+ const resolved = resolutions.get(alert.id);+ return !resolved || resolved.evidence !== healthAlertEvidence(alert);+ }).map(alert => ({+ ...alert,+ // New post-correction evidence is a new occurrence, even if its rounded+ // percentage matches the old one. Local UI triage cannot hide it forever.+ occurrence: [resolutions.get(alert.id)?.at,+ ['success_drop', 'learning_health'].includes(alert.type) ? learningSince : null]+ .filter(Boolean).sort().at(-1) || null,+ revision: healthAlertEvidence(alert),+ }));+}++/** Validate against fresh source evidence before acknowledging a health issue. */+export async function resolveHealthAlert(id) {+ const alerts = await generateNonProductAlerts();+ const alert = alerts.find(candidate => candidate.id === id);+ if (!alert) return null;+ await recordHealthAlertResolution(alert);+ return { resolved: true };}diff --git a/server/services/proactiveAlerts.test.js b/server/services/proactiveAlerts.test.jsindex 00ca0b3c57..ffadfd47a3 100644--- a/server/services/proactiveAlerts.test.js+++ b/server/services/proactiveAlerts.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const mock = vi.hoisted(() => ({+ resolutions: [],goals: [],memory: { used: 1, total: 100 },processes: [],@@ -9,6 +10,10 @@ const mock = vi.hoisted(() => ({performance: { needsAttention: [], skipped: [] }}));+vi.mock('./reviewQueueTriageStore.js', () => ({+ listReviewQueueTriage: vi.fn(async () => mock.resolutions),+ upsertReviewQueueTriage: vi.fn(async value => { mock.resolutions.push(value); return value; }),+}));vi.mock('./identity.js', () => ({ getGoals: vi.fn(async () => ({ goals: mock.goals })) }));vi.mock('./taskLearning.js', () => ({getPerformanceSummary: vi.fn(async () => mock.performance)@@ -22,10 +27,10 @@ vi.mock('./apps.js', () => ({return processes.map(p => ({ ...p, expectedExit: names.has(p?.name) }));})}));-vi.mock('./usage.js', () => ({ getUsage: vi.fn(async () => ({ daily: [] })) }));+vi.mock('./usage.js', () => ({ getUsage: vi.fn(() => ({ dailyActivity: {} })) }));vi.mock('./tribe.js', () => ({ getCareSummary: vi.fn(async () => ({ overdueCount: 0, overdue: [] })) }));vi.mock('./tribeOutreach.js', () => ({ findUnansweredTribeThreads: vi.fn(async () => []) }));-// Keep memory/CPU below their warning thresholds so only process alerts surface.+// Saturated resources remain telemetry, not an alert.vi.mock('../lib/memoryStats.js', () => ({getMemoryStats: vi.fn(async () => mock.memory)}));@@ -33,8 +38,11 @@ vi.mock('./portosProductMetrics.js', () => ({getProductEngagement: vi.fn(async () => ({ actions: [] }))}));-vi.mock('os', () => ({ default: { loadavg: () => [0], cpus: () => [{}] } }));+vi.mock('os', () => ({ default: { loadavg: () => [100], cpus: () => [{}] } }));+import { resolveHealthAlert } from './proactiveAlertSources.js';+import { getPerformanceSummary } from './taskLearning.js';+import { getUsage } from './usage.js';import { generateAlerts } from './proactiveAlerts.js';const processAlerts = async () => {@@ -183,13 +191,72 @@ describe('proactiveAlerts — resource identities', () => {mock.memory = { used: 90, total: 100 };const first = await generateAlerts();expect(first.alerts.map(a => a.id).sort()).toEqual([- 'goal_stall:example%253Aone', 'goal_stall:example%3Aone', 'system_resource:memory'+ 'goal_stall:example%253Aone', 'goal_stall:example%3Aone']);mock.goals.reverse();mock.goals[0].title = 'Renamed goal';mock.memory = { used: 99, total: 100 };const next = await generateAlerts();expect(next.alerts.map(a => a.id).sort()).toEqual(first.alerts.map(a => a.id).sort());- expect(next.alerts.find(a => a.id === 'system_resource:memory').severity).toBe('critical');+ expect(next.alerts.some(a => a.type === 'system_resource')).toBe(false);+ });+});+++describe('proactiveAlerts — activity is not spending evidence', () => {+ it('does not turn a busy day into a cost warning', async () => {+ const dailyActivity = {};+ for (let offset = 0; offset < 5; offset++) {+ const date = new Date();+ date.setDate(date.getDate() - offset);+ dailyActivity[date.toISOString().slice(0, 10)] = {+ tokens: offset === 0 ? 1_000_000 : 100,+ sessions: offset === 0 ? 1000 : 1,+ };+ }+ getUsage.mockReturnValue({ dailyActivity });+ const { alerts } = await generateAlerts();+ expect(alerts.filter(alert => alert.type === 'cost_spike')).toEqual([]);+ });+});+++describe('health alert resolution', () => {+ beforeEach(() => {+ mock.resolutions = [];+ mock.goals = [];+ mock.performance = { needsAttention: [], skipped: [] };+ mock.desktopProcessNames = new Set();+ mock.desktopLookupError = null;+ mock.processes = [{ pm_id: 7, name: 'example-service', status: 'errored', restarts: 3 }];+ });++ it('keeps corrected evidence quiet and permits a new failure', async () => {+ expect(await resolveHealthAlert('process_errored:7')).toEqual({ resolved: true });+ expect(await processAlerts()).toEqual([]);+ expect(mock.resolutions[0]).toMatchObject({ actionKey: 'health.resolved:process_errored:7', dismissed: true });+ expect(mock.resolutions[0].revision).toMatch(/^[a-f0-9]{64}$/);+ mock.processes[0].restarts++;+ expect(await processAlerts()).toHaveLength(1);+ });++ it('passes the correction time into both run-based alert detectors', async () => {+ mock.performance = { needsAttention: [{ taskType: 'example:task', rateSource: 'windowed', successRate: 3, windowedCompleted: 30 }], skipped: [] };+ await resolveHealthAlert('success_drop:example%3Atask');+ const regenerated = await generateAlerts();+ expect(regenerated.alerts.find(alert => alert.id === 'success_drop:example%3Atask').occurrence)+ .toBe(mock.resolutions[0].occurrence);+ expect(getPerformanceSummary).toHaveBeenLastCalledWith({+ sinceByTaskType: { 'example:task': mock.resolutions[0].occurrence }, since: null,+ });+ });++ it('does not resurrect a stalled goal merely because another day passed', async () => {+ mock.goals = [{ id: 'example', title: 'Example goal', status: 'active', createdAt: '2020-01-01' }];+ await resolveHealthAlert('goal_stall:example');+ mock.goals[0].title = 'Renamed goal';+ const { alerts } = await generateAlerts();+ expect(alerts.some(alert => alert.type === 'goal_stall')).toBe(false);+ expect(await resolveHealthAlert('goal_stall:missing')).toBeNull();});});diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 8b15dd79d8..3e79f49378 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -33,6 +33,7 @@ import * as brainStorage from './brainStorage.js';import * as askConversations from './askConversations.js';import * as cosTaskStore from './cosTaskStore.js';import * as messageDrafts from './messageDrafts.js';+import { HEALTH_RESOLUTION_PREFIX } from './healthAlertResolutions.js';import { generateNonProductAlerts } from './proactiveAlertSources.js';import * as identity from './identity.js';import * as reviewService from './review.js';@@ -45,6 +46,7 @@ import { getUserTimezone } from './userTimezone.js';import { getProductEngagement } from './portosProductMetrics.js';import * as reviewQueueTriageStore from './reviewQueueTriageStore.js';import { todayInTimezone } from '../lib/timezone.js';+import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';import { isTerminalThreadStatus, threadNextLine } from '../lib/brainThreads.js';// Producers are read with a bounded upper limit. The queue reports a lower@@ -101,18 +103,21 @@ const PRIORITY_ORDER = { HIGH: 0, MEDIUM: 1, LOW: 2 };// alert list is fine here (the dedicated health views read it live).const ALERTS_TTL_MS = 30_000;let alertsCache = { data: null, timestamp: 0 };+let alertsGeneration = 0;async function getAlertsCached() {if (alertsCache.data && (Date.now() - alertsCache.timestamp) < ALERTS_TTL_MS) {return alertsCache.data;}+ const generation = alertsGeneration;const result = await generateNonProductAlerts();- alertsCache = { data: result, timestamp: Date.now() };+ if (generation === alertsGeneration) alertsCache = { data: result, timestamp: Date.now() };return result;}// Test seam: drop the alerts cache so a suite can assert fresh per-case data.export function __resetAlertsCache() {+ alertsGeneration++;alertsCache = { data: null, timestamp: 0 };}@@ -158,6 +163,18 @@ function threadBelongsToView(thread, view, timezone, now = new Date()) {return ACTIVE_THREAD_STATUSES.has(thread.status) && isDueByLocalToday(thread, timezone, now);}+// These are task-owned obligations, not independent promises made by the user.+// Read live state so legacy recovery commitments clear as soon as+// automation resumes or finishes. Missing tasks stay visible; unreadable tasks+// fail the source read rather than falsely reporting an empty queue.+async function taskNeedsUserAction(taskId) {+ const task = await cosTaskStore.getTaskById(taskId);+ if (!task) return true;+ if (task.status === 'pending' && task.approvalRequired) return true;+ if (task.status === 'blocked') return !TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory);+ return !['pending', 'in_progress', 'completed', 'cancelled'].includes(task.status);+}+const visibleInLiveViews = (producer, view) => {if (!view) return producer.source !== 'history';if (view === 'snoozed') return producer.source !== 'history';@@ -230,8 +247,13 @@ const PRODUCERS = [const timezone = ctx.timezone || 'UTC';const now = ctx.now || new Date();const threads = await brainStorage.getThreads();- const matching = (Array.isArray(threads) ? threads : [])+ const candidates = (Array.isArray(threads) ? threads : []).filter((thread) => threadBelongsToView(thread, ctx.view, timezone, now));+ const actionable = await Promise.all(candidates.map(async thread => {+ const taskRef = thread.source === 'cos' && thread.refs?.find(ref => ref?.kind === 'cos.task' && ref.id);+ return !taskRef || ctx.view === 'history' || await taskNeedsUserAction(taskRef.id);+ }));+ const matching = candidates.filter((_, index) => actionable[index]);return { items: matching, truncated: matching.length > limit };},map(thread) {@@ -657,6 +679,8 @@ const PRODUCERS = [: null;return {id: `health:${alert.id}`,+ operations: [{ id: 'complete', label: 'Mark resolved', available: true }],+ nextAction: 'Investigate or mark resolved',title: alert.title || `${alert.type || 'System'} alert`,summary: (alert.detail || alert.message || '').slice(0, 200),timestamp: alert.timestamp || null,@@ -1036,6 +1060,14 @@ const SOURCE_ACTIONS = Object.freeze({complete: (id) => reviewService.completeItem(id),reopen: (id) => reviewService.reopenItem(id),}),+ health: Object.freeze({+ complete: async (id) => {+ const { resolveHealthAlert } = await import('./proactiveAlertSources.js');+ const result = await resolveHealthAlert(id);+ if (result) __resetAlertsCache();+ return result;+ },+ }),feedback: Object.freeze({rate: async (id, input) => {const { submitAgentFeedback } = await import('./cosAgentFeedback.js');@@ -1314,6 +1346,8 @@ async function readQueueTriageForProjection({: null;const removableKeys = new Set();for (const entry of entries) {+ // Acknowledgement baselines must survive the disappearance of their alert.+ if (entry.actionKey.startsWith(HEALTH_RESOLUTION_PREFIX)) continue;const key = reviewQueueTriageStore.triageIdentityKey(entry);const expired = entry.snoozedUntil && Date.parse(entry.snoozedUntil) <= nowMs;const unused = expired && entry.dismissed !== true && entry.deliveryGeneration === 0;diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex 2892774f1a..1609ac2612 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -5,10 +5,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';const brain = { getInboxLog: vi.fn(), markInboxDone: vi.fn() };const brainStorage = { getThreads: vi.fn(), getThreadById: vi.fn(), updateWith: vi.fn() };const askConversations = { listConversations: vi.fn() };-const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn() };+const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn(), getTaskById: vi.fn() };const cosAgentFeedback = { getPendingAgentFeedback: vi.fn(), submitAgentFeedback: vi.fn() };const messageDrafts = { listDrafts: vi.fn(), approveDraft: vi.fn() };-const proactiveAlerts = { generateNonProductAlerts: vi.fn() };+const proactiveAlerts = { generateNonProductAlerts: vi.fn(), resolveHealthAlert: 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() };@@ -74,6 +74,7 @@ const {// Default: every producer returns "nothing needs attention".function resetEmpty() {+ cosTaskStore.getTaskById.mockResolvedValue(null);brain.getInboxLog.mockResolvedValue([]);brainStorage.getThreads.mockResolvedValue([]);brainStorage.getThreadById.mockResolvedValue(null);@@ -477,6 +478,39 @@ describe('reviewQueue.buildQueue', () => {expect(draftRows[0]).toMatchObject({ required: false, isRecommendation: true, nextAction: 'Open draft' });});+ it('only surfaces task-owned commitments when automation needs user action', async () => {+ const tasks = [+ { id: 'running', status: 'in_progress' },+ { id: 'queued', status: 'pending' },+ { id: 'approval', status: 'pending', approvalRequired: true },+ { id: 'finished', status: 'completed' },+ { id: 'retry', status: 'blocked', metadata: { blockedCategory: 'worktree-busy' } },+ { id: 'blocked', status: 'blocked', metadata: { blockedCategory: 'provider-config' } },+ ];+ cosTaskStore.getTaskById.mockImplementation(async id => tasks.find(task => task.id === id));+ brainStorage.getThreads.mockResolvedValue([...tasks, { id: 'missing' }].map(task => ({+ id: task.id, title: 'Example recovery', status: 'open', source: 'cos',+ refs: [{ kind: 'cos.task', id: task.id }]+ })).concat({ id: 'personal', title: 'My commitment', status: 'open' }));+ const queue = await buildQueue();+ expect(queue.items.filter(item => item.source === 'threads').map(item => item.id).sort())+ .toEqual(['threads:approval', 'threads:blocked', 'threads:missing', 'threads:personal']);++ tasks.find(task => task.id === 'blocked').status = 'completed';+ const resolved = await buildQueue();+ expect(resolved.items.some(item => item.id === 'threads:blocked')).toBe(false);+ });++ it('reports unavailable task state instead of hiding unverified commitments', async () => {+ brainStorage.getThreads.mockResolvedValue([{+ id: 'recovery', title: 'Example recovery', status: 'open', source: 'cos',+ refs: [{ kind: 'cos.task', id: 'unreadable' }]+ }]);+ cosTaskStore.getTaskById.mockRejectedValue(new Error('Task store unavailable'));+ const queue = await buildQueue();+ expect(queue.sources.threads).toMatchObject({ availability: 'unavailable', available: false, total: null });+ });+it('adapts stored obligations and notifications, deduplicating only proven references', async () => {reviewService.getItems.mockResolvedValue([{@@ -557,6 +591,24 @@ describe('reviewQueue.buildQueue', () => {expect(queue.items.find(i => i.source === 'backup')).toMatchObject({ title: 'Backup failed', summary: 'disk full' });});+ it('offers health resolution, clears cached alerts, and preserves durable baselines', async () => {+ const alert = { id: 'success_drop:example', type: 'success_drop', severity: 'high', title: 'Low success rate' };+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([alert]);+ const queue = await buildQueue();+ expect(queue.items.find(item => item.source === 'health').operations)+ .toContainEqual({ id: 'complete', label: 'Mark resolved', available: true });+ const baseline = { actionKey: 'health.resolved:success_drop:example', occurrence: '2026-01-01T00:00:00.000Z', revision: 'fingerprint', dismissed: true };+ proactiveAlerts.resolveHealthAlert.mockImplementation(async () => {+ reviewQueueTriageStore.listReviewQueueTriage.mockResolvedValue([baseline]);+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([]);+ return { resolved: true };+ });+ await expect(resolveQueueItem('health:success_drop:example', 'complete')).resolves.toMatchObject({ resolved: true });+ expect(proactiveAlerts.resolveHealthAlert).toHaveBeenCalledWith('success_drop:example');+ expect((await buildQueue()).items.some(item => item.source === 'health')).toBe(false);+ expect(reviewQueueTriageStore.removeReviewQueueTriage).not.toHaveBeenCalledWith(baseline);+ });+it('surfaces a degraded backup as a normal-severity warning, not a high-severity failure', async () => {proactiveAlerts.generateNonProductAlerts.mockResolvedValue([]);// Degraded shape: files saved (status 'degraded') but the DB dump failed,diff --git a/server/services/reviewQueueTriageStore.test.js b/server/services/reviewQueueTriageStore.test.jsindex 09e336a97b..14a3c7b8d2 100644--- a/server/services/reviewQueueTriageStore.test.js+++ b/server/services/reviewQueueTriageStore.test.js@@ -15,6 +15,8 @@ const {upsertReviewQueueTriage,} = await import('./reviewQueueTriageStore.js');+const { getHealthAlertResolutions, recordHealthAlertResolution } = await import('./healthAlertResolutions.js');+const dataRoot = lazyTempDataRoot('portos-review-queue-triage-');const triageFile = join(dataRoot, 'review-queue-triage.json');const previousBackend = process.env.MEMORY_BACKEND;@@ -49,6 +51,16 @@ describe('reviewQueueTriageStore', () => {await expect(listReviewQueueTriage()).resolves.toEqual([marker]);});+ it('retains the newest health correction time across restart without storing source content', async () => {+ const alert = { id: 'success_drop:example', metadata: { taskType: 'example' }, title: 'Private example title' };+ await recordHealthAlertResolution(alert, new Date('2026-01-02T00:00:00.000Z'));+ await recordHealthAlertResolution(alert, new Date('2026-01-01T00:00:00.000Z'));+ resetReviewQueueTriageStore();+ const resolutions = await getHealthAlertResolutions();+ expect(resolutions.get(alert.id)).toMatchObject({ at: '2026-01-02T00:00:00.000Z' });+ expect(JSON.stringify(await listReviewQueueTriage())).not.toContain('Private example title');+ });+it('keeps rollover occurrences distinct and removes a cleared marker', async () => {const first = { actionKey: 'ask.promote:example', occurrence: '1', revision: 'r1', dismissed: true };const second = { actionKey: 'ask.promote:example', occurrence: '2', revision: 'r1', dismissed: true };diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.jsindex a239741422..82c1f1247b 100644--- a/server/services/taskLearning/routing.js+++ b/server/services/taskLearning/routing.js@@ -483,7 +483,7 @@ export async function getRoutingAccuracy() {* Get a performance summary for logging during task evaluation* Provides insights about how different task types are performing*/-export async function getPerformanceSummary() {+export async function getPerformanceSummary({ sinceByTaskType = {}, since = null } = {}) {const data = await loadLearningData();const summary = {@@ -504,7 +504,13 @@ export async function getPerformanceSummary() {for (const [taskType, metrics] of Object.entries(data.byTaskType)) {if (metrics.completed < 3) continue;- const { successRate, source: rateSource, windowedCompleted } = computeEffectiveSuccessRate(metrics);+ // Alert acknowledgements reset only the evidence window, never learning+ // history or scheduler decisions. Undated samples cannot prove a new issue.+ const cutoff = Math.max(Date.parse(since) || 0, Date.parse(sinceByTaskType[taskType]) || 0);+ const alertMetrics = cutoff ? { ...metrics, recentOutcomes: (metrics.recentOutcomes || [])+ .filter(outcome => Date.parse(outcome.t) > cutoff) } : metrics;+ const { successRate, source: rateSource, windowedCompleted } = computeEffectiveSuccessRate(alertMetrics);+ if (cutoff && rateSource !== 'windowed') continue;const entry = {taskType,successRate,@@ -522,7 +528,7 @@ export async function getPerformanceSummary() {} else if (successRate !== null && successRate < 50 && metrics.completed >= 5) {summary.needsAttention.push(entry);// Also mark as skipped if very low (same predicate as getSkippedTaskTypes)- if (isSkipCandidate(metrics)) {+ if (isSkipCandidate(alertMetrics)) {summary.skipped.push(entry);}}diff --git a/server/services/taskLearning/routing.test.js b/server/services/taskLearning/routing.test.jsindex cf9a3a1b59..224b63da9a 100644--- a/server/services/taskLearning/routing.test.js+++ b/server/services/taskLearning/routing.test.js@@ -469,6 +469,25 @@ describe('windowed-rate decisions (issue #2617)', () => {expect(summary.skipped.map(e => e.taskType)).toContain('still-broken');});+ it('starts alert evidence after correction without erasing learning history', async () => {+ const now = Date.now();+ const at = new Date(now - 60_000).toISOString();+ const old = Array.from({ length: 30 }, () => ({ t: at, s: false }));+ const metrics = { ...stillFailingMetrics(), recentOutcomes: [...old] };+ loadLearningData.mockResolvedValue(learningWith({ example: metrics }));+ const options = { sinceByTaskType: { example: at } };+ expect((await getPerformanceSummary(options)).needsAttention).toEqual([]);+ metrics.recentOutcomes.push({ t: 'unknown', s: false });+ metrics.recentOutcomes.push(...Array.from({ length: 4 }, () => ({ t: new Date(now).toISOString(), s: false })));+ expect((await getPerformanceSummary(options)).needsAttention).toEqual([]);+ metrics.recentOutcomes.push({ t: new Date(now).toISOString(), s: false });+ expect((await getPerformanceSummary(options)).needsAttention).toEqual([+ expect.objectContaining({ taskType: 'example', successRate: 0, windowedCompleted: 5 })+ ]);+ expect(metrics.recentOutcomes.slice(0, 30)).toEqual(old);+ expect((await getPerformanceSummary({ since: new Date(now).toISOString() })).needsAttention).toEqual([]);+ });+it('pairs a windowed rate with its own sample count (evidence pairing for alerts/UI)', async () => {// Healthy lifetime (200 runs) hit by a 6-failure burst: the windowed 0%// must travel with windowedCompleted=6, not the 200 lifetime completions.