Skip to content

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

feat: enrich task telemetry with failure signatures + execution context (#2329)

Adam Eivy92a8435ee5e2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8a946bd7df..542bd7ce18 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,10 @@
- The standalone `/layered-intelligence` page has been removed — with the loop now a per-app scheduled task, its status is seen and managed in CoS → Schedule like every other task, and per-app behavior stays on Edit App → Intelligence. (The dedicated cross-app overview/proposals page and its endpoints are gone; nothing else surfaced there.)
- **[issue-2326] The app Automation page now edits per-task provider/model overrides inline.** Each task row on Edit App → Automation gained a "⚙ Configure" disclosure that expands a per-app provider + model override (with "Use default provider" to inherit the global/task default) — previously reachable only from CoS → Schedule → Configure. The `layered-intelligence` row additionally links straight to its behavior config (telemetry sources, allowed scopes, guidance rules) on the Edit App → Intelligence tab, so an app's full self-improvement setup is configurable without leaving the app.
+## Added
+
+- **[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.)
+
## Fixed
- **[issue-2328] Auto-fixer now has a circuit breaker so a persistently-failing resource can't flood the task queue.** The auto-fixer only deduped identical errors within a 60-second window, so a provider/model (or critical error) that failed every ~minute would queue a fresh investigation/fix task indefinitely — a runaway loop that exhausts the plan queue and never gets healed by yet another identical task. It now trips a per-resource circuit after more than 3 task-worthy failures within a rolling 1-hour window, suppressing further task creation (logged as `🔌 Auto-fix circuit OPEN …`) until the failure rate ages out and the circuit auto-closes. (Partial delivery of #2328's guardrails; the tiered fallback chain, structured failure-reason telemetry, and dashboard metrics remain.)
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index 76d5faa363..2d249ba169 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -22,6 +22,8 @@ export { clearLearningCache } from './store.js';
export {
recordTaskCompletion,
+ buildTaskTelemetryContext,
+ recordFailureSignature,
resetTaskTypeLearning,
recalculateModelTierMetrics,
recalculateDurationStats
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 3b6c66034a..14f1f2fa93 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -20,6 +20,117 @@ import {
saveLearningData
} from './store.js';
+// Cap on retained per-category signature samples — bounds file growth the same
+// way `recentUnknownErrors` does, while keeping enough recent context to spot
+// trends (provider/model/tier correlation) without a full agent-archive scan.
+const MAX_SIGNATURE_SAMPLES = 10;
+
+/**
+ * Milliseconds between two ISO timestamps. Pure. Returns null (not 0) when
+ * either bound is missing/unparseable so an absent timestamp never masquerades
+ * as a zero-latency measurement (repo "sentinel, don't conflate absent" rule).
+ */
+function msBetween(startIso, endIso) {
+ if (!startIso || !endIso) return null;
+ const start = Date.parse(startIso);
+ const end = Date.parse(endIso);
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
+ return Math.max(0, end - start);
+}
+
+/**
+ * Build a structured TaskTelemetryContext for a completed agent run (issue
+ * #2329). Pure — no I/O. Derives what is cheaply available from the agent/task
+ * and their timestamps/metadata; uses explicit null sentinels for anything not
+ * derivable rather than fabricating a value.
+ *
+ * failureSignature — { category, messageSnippet, failurePosition } (null on success)
+ * executionContext — { provider, model, modelTier, taskType, component, inputChars, routingReason }
+ * latency — { wallMs, queueMs, executionMs } (null members when not derivable)
+ */
+export function buildTaskTelemetryContext(agent, task) {
+ const meta = agent?.metadata || {};
+ const result = agent?.result || {};
+ const success = result.success || false;
+ const taskType = extractTaskType(task);
+
+ const errorAnalysis = result.errorAnalysis || null;
+ const rawMessage = errorAnalysis?.message || errorAnalysis?.details || '';
+ const failureSignature = success ? null : {
+ category: errorAnalysis?.category || null,
+ messageSnippet: rawMessage ? String(rawMessage).substring(0, 200) : null,
+ // Best-available proxy for "where in a multi-step workflow it failed": the
+ // phase the agent had reached at completion. null when no phase was stamped.
+ failurePosition: meta.phase ?? null
+ };
+
+ const taskDescription = task?.description ?? meta.taskDescription ?? null;
+ const executionContext = {
+ provider: meta.providerId ?? null,
+ model: meta.model ?? null,
+ modelTier: meta.modelTier ?? null,
+ taskType,
+ // Component/runner that executed the agent (tui | runner | direct).
+ component: meta.executionMode ?? null,
+ // Input dimension: prompt/description size in chars (null, not 0, when absent).
+ inputChars: typeof taskDescription === 'string' ? taskDescription.length : null,
+ // Routing decision rationale captured at spawn time (modelSelection.reason).
+ routingReason: meta.modelReason ?? null
+ };
+
+ const executionMs = Number.isFinite(result.duration) ? result.duration : null;
+ return {
+ taskType,
+ success,
+ failureSignature,
+ executionContext,
+ latency: {
+ // Wall time: spawn → completion (includes any in-agent waiting).
+ wallMs: msBetween(agent?.startedAt, agent?.completedAt),
+ // Queue/wait time only derivable when the source task carried a createdAt.
+ queueMs: msBetween(task?.createdAt, agent?.startedAt),
+ // Measured execution time reported by the runner.
+ executionMs
+ }
+ };
+}
+
+/**
+ * Persist a failure signature aggregate onto the learning data (issue #2329).
+ * Pure — mutates and returns `data`. Additive + back-compat: tolerates an old
+ * learning.json that predates the `failureSignatures` key. No-op on success or
+ * when the failure carries no category.
+ */
+export function recordFailureSignature(data, context) {
+ const sig = context?.failureSignature;
+ if (!sig || !sig.category) return data;
+
+ if (!data.failureSignatures) data.failureSignatures = {};
+ if (!data.failureSignatures[sig.category]) {
+ data.failureSignatures[sig.category] = { count: 0, lastOccurred: null, recent: [] };
+ }
+
+ const bucket = data.failureSignatures[sig.category];
+ const recordedAt = new Date().toISOString();
+ bucket.count++;
+ bucket.lastOccurred = recordedAt;
+ bucket.recent.push({
+ messageSnippet: sig.messageSnippet,
+ failurePosition: sig.failurePosition,
+ provider: context.executionContext.provider,
+ model: context.executionContext.model,
+ modelTier: context.executionContext.modelTier,
+ taskType: context.executionContext.taskType,
+ wallMs: context.latency.wallMs,
+ executionMs: context.latency.executionMs,
+ recordedAt
+ });
+ if (bucket.recent.length > MAX_SIGNATURE_SAMPLES) {
+ bucket.recent = bucket.recent.slice(-MAX_SIGNATURE_SAMPLES);
+ }
+ return data;
+}
+
/**
* Record a completed task for learning
*/
@@ -27,11 +138,14 @@ export async function recordTaskCompletion(agent, task) {
return withLock(async () => {
const data = await loadLearningData();
- const taskType = extractTaskType(task);
+ // Structured telemetry context (failure signature + execution context +
+ // latency breakdown) derived once and reused for aggregate + log (issue #2329).
+ const telemetry = buildTaskTelemetryContext(agent, task);
+ const taskType = telemetry.taskType;
const modelTier = agent.metadata?.modelTier || 'unknown';
- const success = agent.result?.success || false;
+ const success = telemetry.success;
const duration = agent.result?.duration || 0;
- const errorCategory = agent.result?.errorAnalysis?.category || null;
+ const errorCategory = telemetry.failureSignature?.category || null;
// Initialize task type bucket if needed
if (!data.byTaskType[taskType]) {
@@ -140,6 +254,10 @@ export async function recordTaskCompletion(agent, task) {
}
}
+ // Aggregate the enriched failure signature (category + snippet + position +
+ // execution context + latency) — a no-op on success (issue #2329).
+ recordFailureSignature(data, telemetry);
+
// Update totals
data.totals.completed++;
if (success) {
@@ -154,10 +272,22 @@ export async function recordTaskCompletion(agent, task) {
await saveLearningData(data);
- emitLog('debug', `Recorded task completion: ${taskType} (${success ? 'success' : 'failed'})`, {
+ const { provider, model, component, routingReason } = telemetry.executionContext;
+ const { wallMs, queueMs } = telemetry.latency;
+ const wallSecs = Math.round((wallMs ?? duration) / 1000);
+ emitLog('debug', `Recorded task completion: ${taskType} (${success ? 'success' : `failed:${errorCategory || 'uncategorized'}`}) via ${provider || '?'}/${model || '?'}@${modelTier} [${component || '?'}] wall=${wallSecs}s`, {
taskType,
modelTier,
+ provider,
+ model,
+ component,
+ routingReason,
success,
+ errorCategory,
+ failurePosition: telemetry.failureSignature?.failurePosition ?? null,
+ wallMs,
+ queueMs,
+ executionMs: telemetry.latency.executionMs,
duration: Math.round(duration / 1000) + 's'
}, '[TaskLearning]');
diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.js
new file mode 100644
index 0000000000..59b3cddc85
--- /dev/null
+++ b/server/services/taskLearning/metrics.test.js
@@ -0,0 +1,169 @@
+import { describe, it, expect } from 'vitest';
+import { buildTaskTelemetryContext, recordFailureSignature } from './metrics.js';
+
+// buildTaskTelemetryContext + recordFailureSignature are the pure telemetry
+// enrichment core added for issue #2329. They take no I/O, so every branch is
+// exercised directly against hand-built agent/task/data objects — no mocking of
+// the learning-store persistence layer (which would risk the real learning.json).
+
+const baseAgent = {
+ id: 'agent-1',
+ startedAt: '2026-07-09T10:00:00.000Z',
+ completedAt: '2026-07-09T10:05:00.000Z', // +5min wall
+ metadata: {
+ providerId: 'claude',
+ model: 'opus',
+ modelTier: 'heavy',
+ modelReason: 'complex task → heavy tier',
+ executionMode: 'runner',
+ phase: 'implementing',
+ taskDescription: 'x'.repeat(42)
+ },
+ result: { success: true, duration: 250000 }
+};
+
+describe('buildTaskTelemetryContext', () => {
+ it('captures execution context, latency, and no failure signature on success', () => {
+ const ctx = buildTaskTelemetryContext(baseAgent, {
+ description: 'x'.repeat(42),
+ taskType: 'user',
+ createdAt: '2026-07-09T09:59:30.000Z' // 30s before startedAt
+ });
+
+ expect(ctx.success).toBe(true);
+ expect(ctx.failureSignature).toBeNull();
+ expect(ctx.executionContext).toEqual({
+ provider: 'claude',
+ model: 'opus',
+ modelTier: 'heavy',
+ taskType: 'user-task',
+ component: 'runner',
+ inputChars: 42,
+ routingReason: 'complex task → heavy tier'
+ });
+ expect(ctx.latency).toEqual({
+ wallMs: 300000, // 5 min
+ queueMs: 30000, // 30s
+ executionMs: 250000
+ });
+ });
+
+ it('builds a structured failure signature (category, snippet, position) on failure', () => {
+ const agent = {
+ ...baseAgent,
+ metadata: { ...baseAgent.metadata, phase: 'testing' },
+ result: {
+ success: false,
+ duration: 120000,
+ errorAnalysis: { category: 'test-failure', message: 'Tests failed: 3 assertions' }
+ }
+ };
+ const ctx = buildTaskTelemetryContext(agent, { taskType: 'internal', description: 'run tests' });
+
+ expect(ctx.success).toBe(false);
+ expect(ctx.failureSignature).toEqual({
+ category: 'test-failure',
+ messageSnippet: 'Tests failed: 3 assertions',
+ failurePosition: 'testing'
+ });
+ expect(ctx.executionContext.taskType).toBe('internal-task');
+ });
+
+ it('falls back to errorAnalysis.details for the snippet and truncates to 200 chars', () => {
+ const longDetails = 'e'.repeat(500);
+ const agent = {
+ ...baseAgent,
+ result: {
+ success: false,
+ duration: 1000,
+ errorAnalysis: { category: 'unknown', details: longDetails }
+ }
+ };
+ const ctx = buildTaskTelemetryContext(agent, {});
+ expect(ctx.failureSignature.messageSnippet).toHaveLength(200);
+ });
+
+ it('uses explicit null sentinels — never fabricates — for absent data', () => {
+ // Bare agent: no metadata, no timestamps, no duration.
+ const ctx = buildTaskTelemetryContext({ result: { success: false } }, {});
+ expect(ctx.executionContext).toEqual({
+ provider: null,
+ model: null,
+ modelTier: null,
+ taskType: 'unknown',
+ component: null,
+ inputChars: null, // null, not 0 — description absent, not empty
+ routingReason: null
+ });
+ expect(ctx.latency).toEqual({ wallMs: null, queueMs: null, executionMs: null });
+ expect(ctx.failureSignature).toEqual({
+ category: null,
+ messageSnippet: null,
+ failurePosition: null
+ });
+ });
+
+ it('distinguishes an empty-string description (0 chars) from an absent one (null)', () => {
+ const emptyDescAgent = { ...baseAgent, metadata: { ...baseAgent.metadata, taskDescription: '' } };
+ expect(buildTaskTelemetryContext(emptyDescAgent, { description: '' }).executionContext.inputChars).toBe(0);
+ // Neither task.description nor metadata.taskDescription → null
+ const noDescAgent = { ...baseAgent, metadata: { ...baseAgent.metadata, taskDescription: undefined } };
+ expect(buildTaskTelemetryContext(noDescAgent, {}).executionContext.inputChars).toBeNull();
+ });
+
+ it('leaves queueMs null when the task carries no createdAt', () => {
+ const ctx = buildTaskTelemetryContext(baseAgent, { description: 'no createdAt', taskType: 'user' });
+ expect(ctx.latency.queueMs).toBeNull();
+ expect(ctx.latency.wallMs).toBe(300000); // wall still derivable from agent timestamps
+ });
+});
+
+describe('recordFailureSignature', () => {
+ const failureCtx = {
+ success: false,
+ failureSignature: { category: 'test-failure', messageSnippet: 'boom', failurePosition: 'testing' },
+ executionContext: { provider: 'claude', model: 'opus', modelTier: 'heavy', taskType: 'user-task' },
+ latency: { wallMs: 300000, executionMs: 250000 }
+ };
+
+ it('is additive/back-compat: seeds failureSignatures onto an OLD learning.json without the key', () => {
+ // Simulates a pre-#2329 learning.json that has no failureSignatures field.
+ const oldData = { version: 1, byTaskType: {}, errorPatterns: {}, totals: { completed: 0 } };
+ expect(oldData.failureSignatures).toBeUndefined();
+
+ const out = recordFailureSignature(oldData, failureCtx);
+
+ expect(out).toBe(oldData); // mutates in place
+ expect(out.failureSignatures['test-failure'].count).toBe(1);
+ const sample = out.failureSignatures['test-failure'].recent[0];
+ expect(sample).toMatchObject({
+ messageSnippet: 'boom',
+ failurePosition: 'testing',
+ provider: 'claude',
+ model: 'opus',
+ modelTier: 'heavy',
+ taskType: 'user-task',
+ wallMs: 300000,
+ executionMs: 250000
+ });
+ expect(sample.recordedAt).toBeTruthy();
+ // Untouched legacy keys survive.
+ expect(out.byTaskType).toEqual({});
+ expect(out.totals.completed).toBe(0);
+ });
+
+ it('accumulates count and bounds recent samples to the last 10', () => {
+ const data = { failureSignatures: {} };
+ for (let i = 0; i < 15; i++) recordFailureSignature(data, failureCtx);
+ const bucket = data.failureSignatures['test-failure'];
+ expect(bucket.count).toBe(15);
+ expect(bucket.recent).toHaveLength(10);
+ });
+
+ it('is a no-op on success or when the failure has no category', () => {
+ const data = { failureSignatures: {} };
+ recordFailureSignature(data, { success: true, failureSignature: null });
+ recordFailureSignature(data, { failureSignature: { category: null, messageSnippet: 'x' } });
+ expect(data.failureSignatures).toEqual({});
+ });
+});
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index d64e1aa917..d2244f115b 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -55,6 +55,12 @@ const DEFAULT_LEARNING_DATA = {
// Metrics by error category
errorPatterns: {},
+ // Structured failure signatures by error category (issue #2329): each entry
+ // aggregates enriched telemetry — recent messageSnippet/failurePosition plus
+ // the execution context (provider/model/tier) and latency of failures in that
+ // category. Additive: older learning.json files predate this key and load fine.
+ failureSignatures: {},
+
// Routing accuracy: taskType → modelTier → { succeeded, failed }
// Records which model tiers work/fail for each task type
routingAccuracy: {},