Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: aggregate auto-fix diagnostics + dashboard telemetry (#2328)
Adam Eivy4033b4ed4199
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f9c0bceea7..2bc959e157 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,7 @@## Added+- **[issue-2328] Auto-fix outcomes are now aggregated into dashboard telemetry with a success-rate trend.** The structured `metadata.diagnostics` persisted on every error-driven task (tier / category / failure reason) were queryable but never surfaced. A new pure aggregator (`server/services/autoFixMetrics.js`) reads them off task records and rolls them up by fallback tier, failure category, and task status — plus a time-to-recovery summary (count / avg / median / min / max) and a daily success-rate trend — exposed via `GET /api/autofix/metrics` and rendered by a new **Auto-Fix Telemetry** dashboard widget (overall recovery rate, trend sparkline, per-tier breakdown, median recovery time). To measure time-to-recovery, each diagnostics record now carries an `observedAt` failure timestamp; recovery is derived from the task's completion edit. Sentinel discipline throughout — a rate with no denominator and a duration with no completed-with-timing samples return `null`, never a fabricated `0`, so "no data yet" can't read as "0% success". (Further #2328 slice remains: full 4-tier fallback *execution* wiring — the classifier still annotates the investigation task rather than attempting each tier's fix in sequence.)- **[issue-2333] Untyped task executions are now auto-classified instead of piling up as `unknown`.** Task-learning's `extractTaskType` used to dump every execution it couldn't pattern-match into a single blind `unknown` bucket — those tasks bypassed routing logic, skipped outcome learning, and leaked unstructured failures. It now runs an execution-entry classification hook (`classifyUntypedTask`, pure/idempotent/<50ms) that, before giving up, infers a concrete domain from additional signals — a `selfImprovementType` metadata hint, an explicit `task.taskType` the primary extractor didn't special-case (e.g. `scheduled` → `scheduled-task`), and broader whole-word description keyword signatures (`fix`/`investigate`/`crash` → `auto-fix`, `refactor`/`optimize` → `self-improve:general`, `review`/`audit` → `idle-review`, `unit test`/`coverage` → `test-task`) — and only falls back to a new sandboxed `external/untyped` type when nothing matches. Newly-classified and fallback executions flow through the existing #2329 failure-signature harvesting so their failures are captured in the normalized telemetry schema. The `external/untyped` bucket is explicitly walled off from routing (it never drives a model-tier suggestion and is never globally skipped) so a heterogeneous grab-bag can't create a routing blind spot or loop. (Partial delivery of #2333; the spawn-time key mirror in `agentModelSelection.extractTaskTypeKey` and deeper self-improvement-loop consumption of the harvested `failureSignatures` remain.)- **[issue-2329] Task-learning now records a structured telemetry context for every completed agent.** On each completion the learning system builds a `TaskTelemetryContext` — a failure signature (`{ category, messageSnippet, failurePosition }`, reusing the category `agentErrorAnalysis` already classified), execution context (`provider`, `model`, `modelTier`, `taskType`, `component`, input-size, and the routing decision rationale), and a latency breakdown (`wallMs` spawn→completion vs. `queueMs` wait vs. `executionMs` measured) — using explicit null sentinels for anything not cheaply derivable rather than fabricating values. Failure signatures are aggregated per error category into a new additive `failureSignatures` block in `learning.json` (older files without the key load unchanged), and the enriched context is surfaced on the single-line completion log. (Partial delivery of #2329; routing auto-adjustment that consumes these signals, success-criteria validation flags, the queue/compute split where spawn timestamps are missing, and correlation-quality measurement remain.)diff --git a/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsx b/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsxnew file mode 100644index 0000000000..03ed0ef141--- /dev/null+++ b/client/src/components/dashboard/builtins/AutoFixMetricsWidget.jsx@@ -0,0 +1,162 @@+import { memo } from 'react';+import { Link } from 'react-router-dom';+import { Wrench, ArrowRight } from 'lucide-react';+import * as api from '../../../services/api';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+import { formatDurationMs } from '../../../utils/formatters';++// Auto-fix telemetry (issue #2328). Self-fetches the aggregated+// GET /api/autofix/metrics (derived server-side from persisted+// metadata.diagnostics) — this data is NOT part of dashboardState, so unlike+// the dashboardState-slice widgets this one owns its own poll. Renders the+// overall auto-fix success rate, a daily success-rate trend sparkline, the+// fallback-tier breakdown, and median time-to-recovery.++const TIER_COLORS = {+ 1: '#22c55e', // port-success — config/env (cheapest fix)+ 2: '#3b82f6', // port-accent — schema/type+ 3: '#f59e0b', // port-warning — constrained-agent-retry+ 4: '#ef4444', // port-error — escalate+};++// Render a rate in [0,1] as a percent string, or an em dash for the null+// sentinel ("no data yet" must not read as 0%).+const pct = (rate) => (rate == null ? '—' : `${Math.round(rate * 100)}%`);++// Inline SVG sparkline of the daily success-rate trend. No chart dependency —+// a handful of points plotted on a 0–100 y-axis. Days with a null rate (no+// denominator) are skipped so a gap doesn't read as 0%.+function TrendSparkline({ trend }) {+ const points = (trend || []).filter((d) => d.successRate != null);+ if (points.length < 2) return null;++ const W = 120;+ const H = 28;+ const stepX = W / (points.length - 1);+ const coords = points.map((d, i) => {+ const x = i * stepX;+ const y = H - d.successRate * H; // 0% at bottom, 100% at top+ return `${x.toFixed(1)},${y.toFixed(1)}`;+ });+ const last = points[points.length - 1];+ const lastX = (points.length - 1) * stepX;+ const lastY = H - last.successRate * H;++ return (+ <svg+ viewBox={`0 0 ${W} ${H}`}+ width={W}+ height={H}+ className="overflow-visible"+ role="img"+ aria-label={`Success-rate trend, latest ${pct(last.successRate)}`}+ >+ <polyline+ points={coords.join(' ')}+ fill="none"+ stroke="#3b82f6"+ strokeWidth="1.5"+ strokeLinejoin="round"+ strokeLinecap="round"+ />+ <circle cx={lastX} cy={lastY} r="2" fill="#3b82f6" />+ </svg>+ );+}++function AutoFixMetricsWidget() {+ const { data, loading } = useAutoRefetch(+ () => api.getAutoFixMetrics({ silent: true }),+ 60000,+ {+ // Skip the re-render when nothing observable moved. `generatedAt` is the+ // server's wall clock and changes every poll, so it must NOT be part of+ // this comparison — key on the aggregates the widget actually renders.+ compare: (prev, next) =>+ prev?.total === next?.total+ && prev?.overall?.resolved === next?.overall?.resolved+ && prev?.overall?.open === next?.overall?.open+ && (prev?.timeToRecovery?.count ?? null) === (next?.timeToRecovery?.count ?? null)+ && (prev?.timeToRecovery?.medianMs ?? null) === (next?.timeToRecovery?.medianMs ?? null)+ && (prev?.trend?.length ?? 0) === (next?.trend?.length ?? 0),+ },+ );++ const header = (+ <div className="flex items-center gap-2 mb-3">+ <Wrench size={16} className="text-gray-500" />+ <h3 className="text-sm font-semibold text-white">Auto-Fix Telemetry</h3>+ <Link to="/cos" className="ml-auto flex items-center gap-1 text-xs text-port-accent hover:underline">+ Open <ArrowRight size={12} />+ </Link>+ </div>+ );++ const shell = (children) => (+ <div className="bg-port-card border border-port-border rounded-xl p-4 h-full">+ {header}+ {children}+ </div>+ );++ if (loading && !data) {+ return shell(<div className="text-xs text-gray-500">Loading…</div>);+ }++ // Empty state — no diagnostics-bearing tasks yet. Distinct from a 0% rate.+ if (!data || data.total === 0) {+ return shell(+ <div className="text-xs text-gray-500">+ No auto-fix activity yet. Provider/agent failures that trigger an+ investigation task will show up here, broken out by fallback tier and+ recovery rate.+ </div>,+ );+ }++ const { total, overall, byTier, timeToRecovery, trend } = data;++ return shell(+ <>+ <div className="flex items-end gap-3 mb-3">+ <div>+ <div className="text-2xl font-bold text-white leading-none">{pct(overall.successRate)}</div>+ <div className="text-xs text-gray-500 mt-1">+ {overall.resolved}/{total} recovered+ </div>+ </div>+ <div className="ml-auto">+ <TrendSparkline trend={trend} />+ </div>+ </div>++ <div className="space-y-1.5 mb-3">+ {byTier.map((t) => (+ <div key={t.tier} className="flex items-center gap-2 text-xs">+ <span+ className="inline-block w-2 h-2 rounded-full shrink-0"+ style={{ backgroundColor: TIER_COLORS[t.tier] || '#6b7280' }}+ aria-hidden="true"+ />+ <span className="text-gray-300 flex-1 truncate" title={t.label}>+ T{t.tier} · {t.strategy}+ </span>+ <span className="text-gray-500 tabular-nums">+ {t.resolved}/{t.total}+ </span>+ <span className="text-gray-400 tabular-nums w-9 text-right">{pct(t.successRate)}</span>+ </div>+ ))}+ </div>++ <div className="flex items-center justify-between text-xs border-t border-port-border pt-2">+ <span className="text-gray-500">Median recovery</span>+ <span className="text-gray-300 tabular-nums">+ {timeToRecovery ? formatDurationMs(timeToRecovery.medianMs) : '—'}+ </span>+ </div>+ </>,+ );+}++export default memo(AutoFixMetricsWidget);diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 0a3a4a2ebe..daa1342c15 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -26,6 +26,7 @@ const ActivityStreakWidget = lazyWithReload(() => import('./builtins/ActivityStconst HourlyActivityWidget = lazyWithReload(() => import('./builtins/HourlyActivityWidget'));const FeedsWidget = lazyWithReload(() => import('./builtins/FeedsWidget'));const MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceStreakWidget'));+const AutoFixMetricsWidget = lazyWithReload(() => import('./builtins/AutoFixMetricsWidget'));// Each entry: { id, label, Component, width, defaultH?, gate?, module? }.// `gate(state) => bool` skips the widget when it has nothing useful to show.@@ -66,6 +67,7 @@ export const WIDGETS = [{ id: 'hourly-activity', label: 'Activity by Hour', Component: HourlyActivityWidget, width: 'full', defaultH: 4, gate: (s) => !!s.usage?.hourlyActivity && s.usage.hourlyActivity.some((v) => v > 0) },{ id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },{ id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },+ { id: 'autofix-metrics', label: 'Auto-Fix Telemetry', Component: AutoFixMetricsWidget, width: 'quarter', defaultH: 5, module: { id: '09', status: 'AUTOFIX', glyph: 'warning-tri' } },];export const WIDGETS_BY_ID = Object.fromEntries(WIDGETS.map((w) => [w.id, w]));diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 85910f1d24..20bf00b6a0 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -202,6 +202,9 @@ export const getCosActionableInsights = (options) => request('/cos/actionable-inexport const getCosGoalProgress = () => request('/cos/goal-progress');export const getCosGoalProgressSummary = (options) => request('/cos/goal-progress/summary', options);+// Auto-Fix Telemetry (issue #2328) — aggregated from persisted metadata.diagnostics+export const getAutoFixMetrics = (options) => request('/autofix/metrics', options);+// Decision Logexport const getCosDecisions = (limit = 20, type = null) => {const params = new URLSearchParams({ limit: limit.toString() });diff --git a/server/index.js b/server/index.jsindex 974cddaa14..033a499a3f 100644--- a/server/index.js+++ b/server/index.js@@ -32,6 +32,7 @@ import usageRoutes from './routes/usage.js';import screenshotsRoutes from './routes/screenshots.js';import attachmentsRoutes from './routes/attachments.js';import clientErrorsRoutes from './routes/clientErrors.js';+import autoFixMetricsRoutes from './routes/autoFixMetrics.js';import uploadsRoutes from './routes/uploads.js';import imageCleanRoutes from './routes/imageClean.js';import agentsRoutes from './routes/agents.js';@@ -461,6 +462,7 @@ app.use('/api/media/annotations', mediaAnnotationsRoutes);app.use('/api/media/sketches', mediaSketchesRoutes);app.use('/api/attachments', attachmentsRoutes);app.use('/api/client-errors', clientErrorsRoutes);+app.use('/api/autofix', autoFixMetricsRoutes);app.use('/api/backup', backupRoutes);app.use('/api/legacy-export', legacyExportRoutes);app.use('/api/city', cityRoutes);diff --git a/server/routes/autoFixMetrics.js b/server/routes/autoFixMetrics.jsnew file mode 100644index 0000000000..8fb8096351--- /dev/null+++ b/server/routes/autoFixMetrics.js@@ -0,0 +1,24 @@+/**+ * Auto-Fix Metrics Routes (issue #2328)+ *+ * GET /api/autofix/metrics — aggregated auto-fix telemetry derived from the+ * structured `metadata.diagnostics` persisted on task records: outcomes broken+ * out by fallback tier, failure category, and task status, a time-to-recovery+ * summary, and a daily success-rate trend for the dashboard widget.+ *+ * Read-only, no inputs — so no Zod schema. Errors bubble to the centralized+ * middleware via asyncHandler.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { getAutoFixMetrics } from '../services/autoFixMetrics.js';++const router = Router();++router.get('/metrics', asyncHandler(async (req, res) => {+ const metrics = await getAutoFixMetrics();+ res.json(metrics);+}));++export default router;diff --git a/server/services/autoFixMetrics.js b/server/services/autoFixMetrics.jsnew file mode 100644index 0000000000..73e3de0903--- /dev/null+++ b/server/services/autoFixMetrics.js@@ -0,0 +1,178 @@+/**+ * Auto-Fix Metrics aggregation (issue #2328)+ *+ * Reads the structured per-attempt auto-fix diagnostics that ride on task+ * records (`metadata.diagnostics`, persisted since #2335) and aggregates+ * auto-fix outcomes by fallback tier, failure category, task status, and+ * time-to-recovery — plus a daily success-rate trend for the dashboard.+ *+ * `aggregateAutoFixDiagnostics` is a pure reducer over an in-memory task list+ * (no I/O — trivially unit-testable); `getAutoFixMetrics` is the thin I/O shim+ * the route calls to load persisted tasks and hand them to the reducer.+ *+ * Sentinel discipline (per CLAUDE.md): a rate with no denominator and a+ * duration summary with no completed-with-timing samples return `null`, NOT a+ * fabricated 0 — "no data yet" must never read as "0% success" or "0ms+ * recovery".+ */++import { getAllTasks } from './cosTaskStore.js';+import { fixTierMeta } from './autoFixer.js';++// A diagnostics-bearing task is "resolved" once its task reaches the terminal+// completed status. Everything else (pending / in_progress / blocked) is still+// open — not a failure, just not-yet-recovered — so it drags the success rate+// but is never counted as a failed recovery.+const isResolved = (status) => status === 'completed';++// Parse an ISO string → epoch ms, or null when absent/invalid. Sentinel+// discipline: a missing or garbled timestamp must not collapse into 0 (the+// Unix epoch) and manufacture a ~57-year recovery duration.+function toMs(iso) {+ if (!iso || typeof iso !== 'string') return null;+ const ms = Date.parse(iso);+ return Number.isFinite(ms) ? ms : null;+}++// resolved / total, or null when there's no denominator to divide by.+const rate = (resolved, total) => (total > 0 ? resolved / total : null);++// Median of an ascending numeric array (caller sorts once and reuses).+function median(sortedAsc) {+ const n = sortedAsc.length;+ if (n === 0) return null;+ const mid = Math.floor(n / 2);+ return n % 2 === 0 ? Math.round((sortedAsc[mid - 1] + sortedAsc[mid]) / 2) : sortedAsc[mid];+}++function hasDiagnostics(task) {+ const d = task?.metadata?.diagnostics;+ return !!d && typeof d === 'object' && !Array.isArray(d);+}++/**+ * Aggregate auto-fix diagnostics across a flat list of task records. Pure.+ *+ * @param {Array<object>} tasks - task records ({ status, metadata: { diagnostics, updatedAt } }).+ * @param {object} [opts]+ * @param {number} [opts.now=Date.now()] - injectable clock for deterministic `generatedAt`.+ * @returns {{+ * generatedAt: string,+ * total: number,+ * byStatus: { pending: number, in_progress: number, blocked: number, completed: number },+ * overall: { resolved: number, open: number, successRate: number|null },+ * byTier: Array<{ tier: number, strategy: string, label: string, total: number, resolved: number, open: number, successRate: number|null }>,+ * byCategory: Array<{ category: string, total: number, resolved: number, open: number, successRate: number|null }>,+ * timeToRecovery: { count: number, avgMs: number, medianMs: number, minMs: number, maxMs: number }|null,+ * trend: Array<{ date: string, total: number, resolved: number, successRate: number|null }>+ * }}+ */+export function aggregateAutoFixDiagnostics(tasks, { now = Date.now() } = {}) {+ const records = (Array.isArray(tasks) ? tasks : []).filter(hasDiagnostics);++ const byStatus = { pending: 0, in_progress: 0, blocked: 0, completed: 0 };+ const tierMap = new Map(); // tier -> { tier, strategy, label, total, resolved }+ const categoryMap = new Map(); // category -> { category, total, resolved }+ const dayMap = new Map(); // 'YYYY-MM-DD' -> { date, total, resolved }+ const recoveryMs = [];+ let resolvedCount = 0;++ for (const task of records) {+ const d = task.metadata.diagnostics;+ const status = task.status || 'pending';+ byStatus[status] = (byStatus[status] || 0) + 1;+ const resolved = isResolved(status);+ if (resolved) resolvedCount += 1;++ // Tier breakdown (tier number rides on the persisted diagnostics; resolve+ // its label from the number rather than re-classifying the category).+ const tier = Number.isFinite(d.tier) ? d.tier : 0;+ if (!tierMap.has(tier)) {+ const meta = fixTierMeta(tier);+ tierMap.set(tier, { tier, strategy: d.fixStrategy || meta.strategy, label: meta.label, total: 0, resolved: 0 });+ }+ const te = tierMap.get(tier);+ te.total += 1;+ if (resolved) te.resolved += 1;++ // Failure-category breakdown.+ const category = d.category || d.errorType || 'unknown';+ if (!categoryMap.has(category)) categoryMap.set(category, { category, total: 0, resolved: 0 });+ const ce = categoryMap.get(category);+ ce.total += 1;+ if (resolved) ce.resolved += 1;++ // Time-to-recovery: failure observed at diagnostics.observedAt; recovery at+ // the task's last content edit (metadata.updatedAt), which for a completed+ // task is its completion. Only count a completed task with BOTH timestamps+ // present, parseable, and ordered — a legacy diagnostics record without+ // observedAt (pre-#2328) is simply excluded from the duration sample rather+ // than fabricating a bogus interval.+ const observedMs = toMs(d.observedAt);+ if (resolved) {+ const recoveredMs = toMs(task.metadata.updatedAt);+ if (observedMs !== null && recoveredMs !== null && recoveredMs >= observedMs) {+ recoveryMs.push(recoveredMs - observedMs);+ }+ }++ // Daily trend bucket keyed on the failure day (fall back to the last-edit+ // day for legacy records missing observedAt).+ const dayMs = observedMs ?? toMs(task.metadata.updatedAt);+ if (dayMs !== null) {+ const date = new Date(dayMs).toISOString().slice(0, 10);+ if (!dayMap.has(date)) dayMap.set(date, { date, total: 0, resolved: 0 });+ const de = dayMap.get(date);+ de.total += 1;+ if (resolved) de.resolved += 1;+ }+ }++ const total = records.length;++ const byTier = [...tierMap.values()]+ .sort((a, b) => a.tier - b.tier)+ .map((e) => ({ ...e, open: e.total - e.resolved, successRate: rate(e.resolved, e.total) }));++ const byCategory = [...categoryMap.values()]+ .sort((a, b) => b.total - a.total || a.category.localeCompare(b.category))+ .map((e) => ({ ...e, open: e.total - e.resolved, successRate: rate(e.resolved, e.total) }));++ const trend = [...dayMap.values()]+ .sort((a, b) => a.date.localeCompare(b.date))+ .map((e) => ({ ...e, successRate: rate(e.resolved, e.total) }));++ let timeToRecovery = null;+ if (recoveryMs.length > 0) {+ const sorted = [...recoveryMs].sort((a, b) => a - b);+ const sum = sorted.reduce((acc, v) => acc + v, 0);+ timeToRecovery = {+ count: sorted.length,+ avgMs: Math.round(sum / sorted.length),+ medianMs: median(sorted),+ minMs: sorted[0],+ maxMs: sorted[sorted.length - 1],+ };+ }++ return {+ generatedAt: new Date(now).toISOString(),+ total,+ byStatus,+ overall: { resolved: resolvedCount, open: total - resolvedCount, successRate: rate(resolvedCount, total) },+ byTier,+ byCategory,+ timeToRecovery,+ trend,+ };+}++/**+ * Load all persisted tasks (user + internal) and aggregate their auto-fix+ * diagnostics. Thin I/O shim over the pure reducer above.+ */+export async function getAutoFixMetrics({ now = Date.now() } = {}) {+ const { user, cos } = await getAllTasks();+ const tasks = [...(user?.tasks || []), ...(cos?.tasks || [])];+ return aggregateAutoFixDiagnostics(tasks, { now });+}diff --git a/server/services/autoFixMetrics.test.js b/server/services/autoFixMetrics.test.jsnew file mode 100644index 0000000000..4d6f5f86ae--- /dev/null+++ b/server/services/autoFixMetrics.test.js@@ -0,0 +1,131 @@+import { describe, it, expect } from 'vitest';+import { aggregateAutoFixDiagnostics } from './autoFixMetrics.js';++// Build a task record carrying auto-fix diagnostics, mirroring the persisted+// shape (metadata.diagnostics + metadata.updatedAt) that #2335 writes.+function task({ id = 't', status = 'pending', tier = 4, strategy = 'escalate', category = 'unknown', observedAt, updatedAt }) {+ const diagnostics = {+ triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',+ target: 'Claude Code CLI (opus)',+ errorType: category,+ category,+ tier,+ fixStrategy: strategy,+ failureReason: 'boom',+ };+ if (observedAt) diagnostics.observedAt = observedAt;+ const metadata = { diagnostics };+ if (updatedAt) metadata.updatedAt = updatedAt;+ return { id, status, metadata };+}++const NOW = Date.parse('2026-07-09T12:00:00.000Z');++describe('aggregateAutoFixDiagnostics (issue #2328)', () => {+ it('returns an empty-but-sentinel shape when no tasks carry diagnostics', () => {+ const out = aggregateAutoFixDiagnostics(+ [{ id: 'x', status: 'completed', metadata: {} }, { id: 'y', status: 'pending', metadata: { diagnostics: 'not-an-object' } }],+ { now: NOW },+ );+ expect(out.total).toBe(0);+ expect(out.byTier).toEqual([]);+ expect(out.byCategory).toEqual([]);+ expect(out.trend).toEqual([]);+ // No denominator / no samples → null, NOT a fabricated 0.+ expect(out.overall.successRate).toBeNull();+ expect(out.timeToRecovery).toBeNull();+ expect(out.byStatus).toEqual({ pending: 0, in_progress: 0, blocked: 0, completed: 0 });+ expect(out.generatedAt).toBe(new Date(NOW).toISOString());+ });++ it('ignores array-valued diagnostics (defensive) and non-diagnostics tasks', () => {+ const out = aggregateAutoFixDiagnostics([+ { id: 'a', status: 'completed', metadata: { diagnostics: ['nope'] } },+ task({ id: 'b', status: 'completed', tier: 1, strategy: 'config/env', category: 'auth-error' }),+ ], { now: NOW });+ expect(out.total).toBe(1);+ });++ it('breaks outcomes out by tier with per-tier success rate', () => {+ const out = aggregateAutoFixDiagnostics([+ task({ id: '1', status: 'completed', tier: 1, strategy: 'config/env', category: 'auth-error' }),+ task({ id: '2', status: 'pending', tier: 1, strategy: 'config/env', category: 'model-not-found' }),+ task({ id: '3', status: 'completed', tier: 3, strategy: 'constrained-agent-retry', category: 'rate-limit' }),+ ], { now: NOW });++ expect(out.total).toBe(3);+ expect(out.byStatus).toMatchObject({ completed: 2, pending: 1 });+ expect(out.overall).toMatchObject({ resolved: 2, open: 1 });+ expect(out.overall.successRate).toBeCloseTo(2 / 3);++ const t1 = out.byTier.find((t) => t.tier === 1);+ expect(t1).toMatchObject({ total: 2, resolved: 1, open: 1, strategy: 'config/env' });+ expect(t1.successRate).toBeCloseTo(0.5);+ expect(t1.label).toBe('config/env correction'); // resolved from the tier number++ const t3 = out.byTier.find((t) => t.tier === 3);+ expect(t3).toMatchObject({ total: 1, resolved: 1, successRate: 1 });+ // byTier is tier-ascending+ expect(out.byTier.map((t) => t.tier)).toEqual([1, 3]);+ });++ it('breaks outcomes out by failure category, most-frequent first', () => {+ const out = aggregateAutoFixDiagnostics([+ task({ id: '1', category: 'rate-limit', tier: 3 }),+ task({ id: '2', category: 'rate-limit', tier: 3 }),+ task({ id: '3', category: 'auth-error', tier: 1 }),+ ], { now: NOW });+ expect(out.byCategory[0]).toMatchObject({ category: 'rate-limit', total: 2 });+ expect(out.byCategory[1]).toMatchObject({ category: 'auth-error', total: 1 });+ });++ it('computes time-to-recovery only from completed tasks with both timestamps ordered', () => {+ const out = aggregateAutoFixDiagnostics([+ // 60s recovery+ task({ id: '1', status: 'completed', observedAt: '2026-07-09T10:00:00.000Z', updatedAt: '2026-07-09T10:01:00.000Z' }),+ // 120s recovery+ task({ id: '2', status: 'completed', observedAt: '2026-07-09T10:00:00.000Z', updatedAt: '2026-07-09T10:02:00.000Z' }),+ // completed but missing observedAt (legacy) → excluded from the sample+ task({ id: '3', status: 'completed', updatedAt: '2026-07-09T10:05:00.000Z' }),+ // pending → not a recovery+ task({ id: '4', status: 'pending', observedAt: '2026-07-09T10:00:00.000Z', updatedAt: '2026-07-09T10:03:00.000Z' }),+ // completed but updatedAt precedes observedAt (clock skew) → excluded+ task({ id: '5', status: 'completed', observedAt: '2026-07-09T10:02:00.000Z', updatedAt: '2026-07-09T10:00:00.000Z' }),+ ], { now: NOW });++ expect(out.timeToRecovery).toMatchObject({+ count: 2,+ minMs: 60000,+ maxMs: 120000,+ avgMs: 90000,+ medianMs: 90000,+ });+ });++ it('builds a daily success-rate trend keyed on the failure day', () => {+ const out = aggregateAutoFixDiagnostics([+ task({ id: '1', status: 'completed', observedAt: '2026-07-08T09:00:00.000Z' }),+ task({ id: '2', status: 'pending', observedAt: '2026-07-08T11:00:00.000Z' }),+ task({ id: '3', status: 'completed', observedAt: '2026-07-09T09:00:00.000Z' }),+ ], { now: NOW });++ expect(out.trend).toHaveLength(2);+ expect(out.trend[0]).toMatchObject({ date: '2026-07-08', total: 2, resolved: 1 });+ expect(out.trend[0].successRate).toBeCloseTo(0.5);+ expect(out.trend[1]).toMatchObject({ date: '2026-07-09', total: 1, resolved: 1, successRate: 1 });+ // ascending by date+ expect(out.trend.map((d) => d.date)).toEqual(['2026-07-08', '2026-07-09']);+ });++ it('falls back to updatedAt for the trend day when observedAt is absent', () => {+ const out = aggregateAutoFixDiagnostics([+ task({ id: '1', status: 'completed', updatedAt: '2026-07-07T09:00:00.000Z' }),+ ], { now: NOW });+ expect(out.trend).toEqual([{ date: '2026-07-07', total: 1, resolved: 1, successRate: 1 }]);+ });++ it('handles a non-array / empty input without throwing', () => {+ expect(aggregateAutoFixDiagnostics(null, { now: NOW }).total).toBe(0);+ expect(aggregateAutoFixDiagnostics(undefined, { now: NOW }).total).toBe(0);+ });+});diff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex 2e9d5413e5..0713824ed0 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -162,15 +162,29 @@ export function classifyFixTier(category) {return { tier, ...FIX_TIER_META[tier] };}+/**+ * Look up the human-facing metadata for a fallback tier NUMBER (issue #2328).+ * The persisted diagnostics record already carries the tier number, so the+ * telemetry aggregator resolves labels from the number rather than re-running+ * the category classifier. Unknown tiers degrade to an explicit 'unknown'+ * rather than throwing. Pure — no I/O.+ * @param {number} tier+ * @returns {{ strategy: string, label: string }}+ */+export function fixTierMeta(tier) {+ return FIX_TIER_META[tier] || { strategy: 'unknown', label: 'unknown' };+}+/*** Build a structured, per-attempt auto-fix diagnostics record (issue #2328).* Beyond the single-line log, this object rides on the task/return shape so* downstream telemetry can break failures out by tier / category / reason /* time-to-recovery. Pure — no I/O.* @returns {{ triggerEvent: string, target: string, errorType: string,- * category: string, tier: number, fixStrategy: string, failureReason: string }}+ * category: string, tier: number, fixStrategy: string, failureReason: string,+ * observedAt: string }}*/-export function buildFixDiagnostics({ triggerEvent, target, category, failureReason } = {}) {+export function buildFixDiagnostics({ triggerEvent, target, category, failureReason, observedAt } = {}) {const cat = category || 'unknown';const { tier, strategy } = classifyFixTier(cat);return {@@ -181,6 +195,12 @@ export function buildFixDiagnostics({ triggerEvent, target, category, failureReatier,fixStrategy: strategy,failureReason: oneLine(failureReason) || 'no error text captured',+ // ISO timestamp of when the failure was observed (issue #2328). Rides on the+ // persisted diagnostics so the telemetry aggregator can compute+ // time-to-recovery (task completion time − this) without a second timestamp+ // source. Injectable so callers pass the failure's real timestamp (and tests+ // stay deterministic); defaults to now when the caller has none.+ observedAt: observedAt || new Date().toISOString(),};}@@ -196,6 +216,11 @@ function providerFixDiagnostics(error) {target: `${ctx.provider || 'Unknown'} (${ctx.model || 'N/A'})`,category: ctx.errorAnalysis?.category,failureReason: ctx.errorDetails || ctx.errorAnalysis?.message,+ // Pin observedAt to the failure's own timestamp so the log-line record and+ // the persisted task record (both built from this helper) agree, and so+ // time-to-recovery measures from the actual failure, not from whenever the+ // deferred handler ran.+ observedAt: error.timestamp ? new Date(error.timestamp).toISOString() : undefined,});}@@ -579,6 +604,7 @@ async function createAutoFixTask(error) {target: error.code,category: error.context?.errorAnalysis?.category,failureReason: error.message,+ observedAt: error.timestamp ? new Date(error.timestamp).toISOString() : undefined,});console.log(`🤖 Creating auto-fix task for error: ${error.code} [tier ${diagnostics.tier}: ${diagnostics.fixStrategy}]`);diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.jsindex 7cc9b0c900..803697617f 100644--- a/server/services/autoFixer.test.js+++ b/server/services/autoFixer.test.js@@ -513,6 +513,16 @@ describe('autoFixer — structured per-attempt diagnostics (issue #2328)', () =>it("reports 'no error text captured' when no reason is supplied", () => {expect(buildFixDiagnostics({ category: 'auth-error' }).failureReason).toBe('no error text captured');});++ it('stamps observedAt — the injected value when given, else a valid ISO now (#2328)', () => {+ const at = '2026-07-09T10:00:00.000Z';+ expect(buildFixDiagnostics({ category: 'auth-error', observedAt: at }).observedAt).toBe(at);+ // Default: a parseable ISO timestamp so the telemetry aggregator can derive+ // time-to-recovery from it.+ const defaulted = buildFixDiagnostics({ category: 'auth-error' }).observedAt;+ expect(typeof defaulted).toBe('string');+ expect(Number.isFinite(Date.parse(defaulted))).toBe(true);+ });});describe('autoFixer — diagnostics ride on the created task record (issue #2328)', () => {