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: success-criteria validation booleans + correlation-quality window (#2344)

Adam Eivyccc04f228d8c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4f949b7dba..fcee1a2bf5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,7 @@
- **[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-2344] Task-learning now stamps a success-criteria validation verdict on every completion and gates routing aggressiveness on a correlation-quality window (the #2329 remainder).** Each completion now carries an explicit `validationPassed` boolean — "did the run meet its DECLARED success criteria?" — distinct from the runner's exit-code `success`, so a task-referencing-commit task that exits clean but committed nothing is honestly recorded as a miss. Computed once at the shared completion chokepoint (`finalizeAgent`) via the existing `[task-<id>]` commit check and threaded through `buildTaskTelemetryContext`, the persisted agent result, and the harvested failure-signature samples; a null sentinel means "no machine-checkable criterion was declared" (interactive/user tasks, user-terminated runs) so "not declared" never collapses into "declared and failed". Separately, a new rolling correlation-quality window (`server/services/taskLearning/correlationQuality.js`) pairs each run's failure-signal *prediction* (did the enriched signal flag this run's tier, from history before the run) with its actual outcome and scores their correlation via the Matthews/phi coefficient — with a null sentinel (not `0`) for a degenerate window where a class is absent. `suggestModelTier` gates auto-adjustment aggressiveness on that score: until it clears >0.8 with enough samples, tier-avoidance requires a higher failure-sample bar (5 vs 3) so the system doesn't over-correct on an unproven signal. The gauge is surfaced on the Learning insights payload. This closes out the two deferred #2329 slices.
- **[issue-2329] Model routing now consumes the enriched failure signatures, and the latency split derives a queue/compute breakdown when a source timestamp is missing.** The `failureSignatures` telemetry recorded per completion (provider/model/tier-attributed, recency-bounded) is now read by `suggestModelTier`: a new pure `deriveFailureSignalAvoidance` cross-references those recent failures against `routingAccuracy` and steers selection off a tier that is BOTH accumulating recent failures for a task type AND unproven (success rate < 80%, or no success data) — catching a freshly-degrading tier before its all-time rate crosses the hard misroute line, while a proven tier keeps its slot despite absolute failures (signatures record failures only, so counts alone can't condemn a tier). The dominant failing provider/model is surfaced as a `failureSignal` on the suggestion and named in the model-selection log, so the routing decision is legible rather than "avoid tier X". Separately, the queue/compute latency split now falls back to `wall − compute` (or `wall − queue`) when a run carries no `createdAt` or no runner duration, with a per-leg `source` marker (`measured`/`derived`/`null`) so a derived value is never confused with a measured one and a legitimate `0ms` is never confused with an absent leg. (Further #2329 work remains: success-criteria validation booleans on every completion path and the >0.8 correlation-quality measurement window.)
- **[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/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 8356798baa..2eeab63839 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -737,6 +737,35 @@ export function releaseAgentLane({ agentId, success, duration, exitCode, executi
}
}
+/**
+ * Evaluate a completed autonomous run against its DECLARED success criteria
+ * (issue #2344). Distinct from the runner's exit-code `success`: it answers
+ * "did the run actually produce the work it was supposed to?" using the one
+ * machine-checkable criterion the CoS already relies on — a `[task-<id>]` commit.
+ *
+ * Returns a null sentinel when NO criterion is declared (interactive/user tasks,
+ * user-terminated runs, or a run with no task id / workspace to validate
+ * against), so downstream telemetry never conflates "not declared" with
+ * "declared and failed". For autonomous tasks it verifies the commit on BOTH
+ * success and failure — a clean exit that committed nothing is an honest miss,
+ * and that is exactly the signal task-learning wants. `checkForTaskCommit` is
+ * git-repo-gated, off the event loop, and hard-timeout-bounded, so a non-repo
+ * workspace or a hung git degrades to "no commit" rather than stalling finalize.
+ */
+export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath }) {
+ if (terminatedByUser) return null;
+ const taskType = task?.taskType || 'user';
+ // Interactive/user tasks declare no machine-checkable criterion; neither does
+ // a run missing the task id or workspace needed to validate.
+ if (taskType === 'user' || !task?.id || !workspacePath) return null;
+ // Pipeline/media tasks deliver artifacts, not a `[task-<id>]` commit — the
+ // commit criterion doesn't apply, so don't mislabel a clean artifact run as a
+ // validation miss (which would also pollute the correlation window). null =
+ // no commit criterion declared for this task shape.
+ if (task?.metadata?.pipeline || task?.metadata?.mediaJob) return null;
+ return await checkForTaskCommit(task.id, workspacePath);
+}
+
/**
* Shared end-of-run state writes for all three spawn paths
* (`handleAgentCompletion` runner-mode, TUI `finish`, direct-CLI `close`).
@@ -780,6 +809,17 @@ export async function finalizeAgent({
? { status: 'completed' }
: await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
+ // Success-criteria validation (issue #2344): stamp an explicit pass/fail (or
+ // null-when-undeclared) verdict onto the completion result, distinct from the
+ // exit-code `success`, so task-learning telemetry can distinguish "ran clean
+ // but produced nothing" from a genuine success. Best-effort — a validation
+ // check failure must never block finalize (falls back to the null sentinel).
+ const validationPassed = await evaluateSuccessCriteria({ task, terminatedByUser, workspacePath })
+ .catch(err => {
+ emitLog('warn', `⚠️ Success-criteria validation failed for ${agentId}: ${err.message}`, { agentId });
+ return null;
+ });
+
// Sequential by design: completeAgent + updateTask share the cosState
// mutex (`withStateLock`) so parallelism gains nothing, AND ordering
// matters — if completeAgent throws, we must not mark the task completed.
@@ -788,6 +828,7 @@ export async function finalizeAgent({
// failure.
await completeAgent(agentId, {
success,
+ validationPassed,
exitCode,
duration,
outputLength: outputBuffer?.length ?? 0,
diff --git a/server/services/agentLifecycle.successCriteria.test.js b/server/services/agentLifecycle.successCriteria.test.js
new file mode 100644
index 0000000000..13acb0568d
--- /dev/null
+++ b/server/services/agentLifecycle.successCriteria.test.js
@@ -0,0 +1,56 @@
+/**
+ * Tests for `evaluateSuccessCriteria` (issue #2344) — the success-criteria
+ * validation verdict finalizeAgent stamps onto every completion, distinct from
+ * the runner's exit-code `success`. The `[task-<id>]` commit check is mocked so
+ * these run without git; the focus is the null-sentinel gating (no criterion
+ * declared vs declared-and-checked).
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./agentRunTracking.js', () => ({
+ checkForTaskCommit: vi.fn(),
+ // finalizeAgent's other imports from this module — stubbed so the graph loads.
+ createAgentRun: vi.fn(),
+ completeAgentRun: vi.fn(),
+}));
+
+import { evaluateSuccessCriteria } from './agentLifecycle.js';
+import { checkForTaskCommit } from './agentRunTracking.js';
+
+describe('evaluateSuccessCriteria (#2344)', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns null (no declared criterion) for interactive/user tasks', async () => {
+ expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'user' }, workspacePath: '/w' })).toBeNull();
+ expect(checkForTaskCommit).not.toHaveBeenCalled();
+ });
+
+ it('returns null for a user-terminated run — no criterion was evaluated', async () => {
+ const out = await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' }, terminatedByUser: true, workspacePath: '/w' });
+ expect(out).toBeNull();
+ expect(checkForTaskCommit).not.toHaveBeenCalled();
+ });
+
+ it('returns null when there is no task id or no workspace to validate against', async () => {
+ expect(await evaluateSuccessCriteria({ task: { taskType: 'internal' }, workspacePath: '/w' })).toBeNull();
+ expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' } })).toBeNull();
+ expect(checkForTaskCommit).not.toHaveBeenCalled();
+ });
+
+ it('returns null for pipeline/media tasks (they deliver artifacts, not a commit)', async () => {
+ expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal', metadata: { pipeline: true } }, workspacePath: '/w' })).toBeNull();
+ expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal', metadata: { mediaJob: true } }, workspacePath: '/w' })).toBeNull();
+ expect(checkForTaskCommit).not.toHaveBeenCalled();
+ });
+
+ it('returns the commit-check verdict for an autonomous code task (criterion declared)', async () => {
+ checkForTaskCommit.mockResolvedValueOnce(true);
+ expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' }, workspacePath: '/w' })).toBe(true);
+ expect(checkForTaskCommit).toHaveBeenCalledWith('t1', '/w');
+
+ // A clean run that produced NO commit is an honest miss (false, not null).
+ checkForTaskCommit.mockResolvedValueOnce(false);
+ expect(await evaluateSuccessCriteria({ task: { id: 't2', taskType: 'internal' }, workspacePath: '/w' })).toBe(false);
+ });
+});
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 5bbd3b8eb7..1c7c4b4ea0 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -313,7 +313,12 @@ export async function completeAgent(agentId, result = {}) {
...state.agents[agentId],
status: 'completed',
completedAt: new Date().toISOString(),
- result
+ // Success-criteria validation verdict (issue #2344): normalize to an
+ // explicit null sentinel when a completion path didn't declare/evaluate a
+ // machine-checkable criterion, so persisted telemetry never conflates
+ // "not declared" with "declared and failed" (false). Distinct from
+ // result.success (the runner's exit-code verdict).
+ result: { validationPassed: null, ...result },
};
if (result.success) {
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 7f5f862200..ddf0fc9a54 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -196,7 +196,10 @@ async function runInitSpawner() {
const agent = runnerAgents.get(agentId);
if (agent) {
clearTimeout(agent.initializationTimeout);
- await completeAgent(agentId, { success: false, error });
+ // Runner-level error before the run could produce work — no success
+ // criterion was evaluated, so validation is the null sentinel (issue
+ // #2344), never a false that would look like a declared-and-failed run.
+ await completeAgent(agentId, { success: false, validationPassed: null, error });
await completeAgentRun(agent.runId, '', 1, 0, { message: error, category: 'runner-error' });
runnerAgents.delete(agentId);
}
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 7cec3a0b46..518625cd26 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -92,6 +92,19 @@ tryReadFile: vi.fn().mockResolvedValue(null),
...overrides
});
+// A correlation-quality window proving the enriched failure signal predicts
+// outcomes (perfect correlation, >= MIN_CORRELATION_SAMPLES) — so `suggestModelTier`
+// runs the AGGRESSIVE failure-sample bar (3) and the #2329 avoidance mechanics
+// engage. Without this the #2344 gate holds avoidance back to the conservative
+// bar (5) until the signal has earned it. Injected into the #2329 avoidance
+// tests to isolate their intent from the new gate (which has its own tests).
+const provenCorrelationWindow = () => Array.from({ length: 24 }, (_, i) => ({
+ taskType: 'user-task', tier: 'heavy',
+ predictedRisk: i % 2 === 0,
+ bad: i % 2 === 0,
+ recordedAt: '2026-01-26T00:00:00.000Z'
+}));
+
describe('TaskLearning - resetTaskTypeLearning', () => {
let savedData;
@@ -598,6 +611,7 @@ describe('TaskLearning - suggestModelTier with routing signals', () => {
}
},
routingAccuracy: {},
+ correlationWindow: provenCorrelationWindow(),
failureSignatures: {
'test-failure': {
count: 3,
@@ -642,6 +656,7 @@ describe('TaskLearning - suggestModelTier with routing signals', () => {
}
},
routingAccuracy: {},
+ correlationWindow: provenCorrelationWindow(),
failureSignatures: {
'test-failure': {
count: 3,
@@ -680,6 +695,7 @@ describe('TaskLearning - suggestModelTier with routing signals', () => {
medium: { succeeded: 7, failed: 3, lastAttempt: '2026-01-26T00:00:00.000Z' } // 70% (unproven)
}
},
+ correlationWindow: provenCorrelationWindow(),
failureSignatures: {
'test-failure': {
count: 3,
@@ -699,6 +715,44 @@ describe('TaskLearning - suggestModelTier with routing signals', () => {
expect(result.failureSignal).toMatchObject({ tier: 'medium', provider: 'claude', model: 'sonnet' });
});
+ it('holds avoidance back to the conservative bar until correlation is proven (#2344)', async () => {
+ // 3 recent 'heavy' failures — enough for the AGGRESSIVE bar (3) — but the
+ // correlation window is empty (unproven), so the #2344 gate applies the
+ // conservative bar (5) and does NOT steer off 'heavy' yet.
+ const fixture = (correlationWindow) => makeLearningData({
+ byTaskType: {
+ 'gate-task': {
+ completed: 12, succeeded: 9, failed: 3,
+ totalDurationMs: 1200000, avgDurationMs: 100000, successRate: 75
+ }
+ },
+ routingAccuracy: {},
+ correlationWindow,
+ failureSignatures: {
+ 'test-failure': {
+ count: 3,
+ recent: [
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'gate-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'gate-task' },
+ { modelTier: 'heavy', provider: 'claude', model: 'opus', taskType: 'gate-task' }
+ ]
+ }
+ }
+ });
+
+ // Unproven correlation (empty window) → no avoidance despite 3 failures.
+ readFile.mockResolvedValue(JSON.stringify(fixture([])));
+ clearLearningCache();
+ expect(await suggestModelTier('gate-task')).toBeNull();
+
+ // Proven correlation (>0.8, >= min samples) → the same 3 failures now steer.
+ readFile.mockResolvedValue(JSON.stringify(fixture(provenCorrelationWindow())));
+ clearLearningCache();
+ const proven = await suggestModelTier('gate-task');
+ expect(proven).not.toBeNull();
+ expect(proven.avoidTiers).toContain('heavy');
+ });
+
it('does not let failure signatures condemn a proven tier (#2329)', async () => {
// 'heavy' clears the high-success threshold in routingAccuracy, so the
// proven-tier suggestion stands and its absolute failures never add it to
diff --git a/server/services/taskLearning/correlationQuality.js b/server/services/taskLearning/correlationQuality.js
new file mode 100644
index 0000000000..271ca8739c
--- /dev/null
+++ b/server/services/taskLearning/correlationQuality.js
@@ -0,0 +1,124 @@
+/**
+ * Task Learning — correlation-quality measurement window (issue #2344, carved
+ * out of #2329).
+ *
+ * The enriched failure signatures (#2329/#2332) let routing steer away from a
+ * tier that is freshly failing. But an avoidance signal is only worth acting on
+ * aggressively if it actually PREDICTS bad outcomes — otherwise the system
+ * over-corrects on noise. This module measures exactly that: over a rolling
+ * window it correlates each run's *prediction* (did the enriched signal flag
+ * this run's tier as risky, based on history BEFORE the run?) with its *actual
+ * outcome* (did the run fail / miss its declared success criteria?), and exposes
+ * a correlation-quality score.
+ *
+ * `suggestModelTier` (routing.js) gates auto-adjustment aggressiveness on that
+ * score clearing `CORRELATION_QUALITY_THRESHOLD` (>0.8): until the signal has
+ * demonstrably-good correlation over enough samples, avoidance requires a higher
+ * failure-sample bar before it steers selection.
+ *
+ * Pure — no I/O except the thin `getCorrelationQuality()` loader.
+ */
+
+import { loadLearningData } from './store.js';
+
+// Bounds `correlationWindow` growth the same way `failureSignatures.recent` and
+// `recentUnknownErrors` do — a rolling window, not an unbounded ledger.
+const MAX_CORRELATION_SAMPLES = 200;
+
+// Below this many samples the phi coefficient is too noisy to gate on — a score
+// computed from a handful of runs can swing wildly. `confident` stays false and
+// the routing gate treats the signal as unproven.
+export const MIN_CORRELATION_SAMPLES = 20;
+
+// Auto-adjustment aggressiveness gate: the enriched signal must correlate with
+// outcomes ABOVE this (Matthews/phi coefficient, [-1,1]) before routing acts on
+// it aggressively (issue #2344).
+export const CORRELATION_QUALITY_THRESHOLD = 0.8;
+
+/**
+ * Append one prediction/outcome pair to the rolling correlation window.
+ * Pure — mutates and returns `data`. Additive + back-compat: tolerates a
+ * learning.json that predates the `correlationWindow` key.
+ *
+ * @param {object} data - learning data
+ * @param {{ taskType?:string, tier?:string, predictedRisk:boolean, bad:boolean }} sample
+ * predictedRisk — did the enriched failure signal flag this run's tier as
+ * risky, computed from history BEFORE this completion (a genuine prediction,
+ * not leakage). bad — did the run actually fail or miss its declared criteria.
+ */
+export function recordCorrelationSample(data, { taskType, tier, predictedRisk, bad } = {}) {
+ if (!data) return data;
+ if (!Array.isArray(data.correlationWindow)) data.correlationWindow = [];
+
+ data.correlationWindow.push({
+ taskType: taskType ?? null,
+ tier: tier ?? null,
+ predictedRisk: !!predictedRisk,
+ bad: !!bad,
+ recordedAt: new Date().toISOString()
+ });
+
+ if (data.correlationWindow.length > MAX_CORRELATION_SAMPLES) {
+ data.correlationWindow = data.correlationWindow.slice(-MAX_CORRELATION_SAMPLES);
+ }
+ return data;
+}
+
+/**
+ * Compute the correlation-quality score for a window of prediction/outcome
+ * pairs. Pure. Uses the Matthews correlation coefficient (the phi coefficient
+ * for two binary variables — predictedRisk vs bad), which is robust to class
+ * imbalance (most runs succeed) in a way raw accuracy is not.
+ *
+ * Sentinel discipline: returns `score: null` (NOT 0) when a denominator factor
+ * is 0 — i.e. a predicted or actual class is entirely absent from the window
+ * (all runs predicted-safe, or none failed). "Not measurable" must never
+ * collapse into "measured zero correlation".
+ *
+ * @returns {{ score:number|null, sampleCount:number, confident:boolean,
+ * matrix:{ tp:number, fp:number, fn:number, tn:number } }}
+ */
+export function computeCorrelationQuality(window, { minSamples = MIN_CORRELATION_SAMPLES } = {}) {
+ const samples = Array.isArray(window) ? window : [];
+ let tp = 0, fp = 0, fn = 0, tn = 0;
+ for (const s of samples) {
+ const risk = !!s?.predictedRisk;
+ const bad = !!s?.bad;
+ if (risk && bad) tp++;
+ else if (risk && !bad) fp++;
+ else if (!risk && bad) fn++;
+ else tn++;
+ }
+
+ const denomSq = (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn);
+ const score = denomSq === 0 ? null : (tp * tn - fp * fn) / Math.sqrt(denomSq);
+ const sampleCount = samples.length;
+
+ return {
+ score,
+ sampleCount,
+ // Gate-ready: enough samples AND a measurable score. A null score (degenerate
+ // window) is never "confident", so the routing gate stays conservative.
+ confident: score !== null && sampleCount >= minSamples,
+ matrix: { tp, fp, fn, tn }
+ };
+}
+
+/**
+ * True when the enriched failure signal has proven, high-confidence correlation
+ * with outcomes — the gate `suggestModelTier` uses to decide whether to apply
+ * tier-avoidance aggressively (issue #2344). A `null`/low/low-confidence score
+ * returns false, keeping auto-adjustment conservative until the signal earns it.
+ */
+export function isCorrelationProven(quality, threshold = CORRELATION_QUALITY_THRESHOLD) {
+ return !!quality?.confident && quality.score !== null && quality.score > threshold;
+}
+
+/**
+ * Load learning data and compute the current correlation-quality gauge.
+ * Thin async wrapper over the pure `computeCorrelationQuality`.
+ */
+export async function getCorrelationQuality(options = {}) {
+ const data = await loadLearningData();
+ return computeCorrelationQuality(data.correlationWindow, options);
+}
diff --git a/server/services/taskLearning/correlationQuality.test.js b/server/services/taskLearning/correlationQuality.test.js
new file mode 100644
index 0000000000..486b3b24e1
--- /dev/null
+++ b/server/services/taskLearning/correlationQuality.test.js
@@ -0,0 +1,132 @@
+import { describe, it, expect } from 'vitest';
+import {
+ recordCorrelationSample,
+ computeCorrelationQuality,
+ isCorrelationProven,
+ CORRELATION_QUALITY_THRESHOLD,
+ MIN_CORRELATION_SAMPLES
+} from './correlationQuality.js';
+
+// Pure correlation-quality core for issue #2344. No I/O — exercised directly
+// against hand-built windows.
+
+const pair = (predictedRisk, bad, over = {}) => ({ predictedRisk, bad, taskType: 'user-task', tier: 'heavy', ...over });
+
+// Build a window of n perfectly-correlated pairs (risk↔bad), split good/bad.
+const perfectWindow = (bad, good) => [
+ ...Array.from({ length: bad }, () => pair(true, true)),
+ ...Array.from({ length: good }, () => pair(false, false))
+];
+
+describe('recordCorrelationSample', () => {
+ it('appends a normalized pair and is additive/back-compat on an old learning file', () => {
+ const data = { version: 1 }; // predates correlationWindow
+ const out = recordCorrelationSample(data, { taskType: 'user-task', tier: 'heavy', predictedRisk: true, bad: false });
+ expect(out).toBe(data); // mutates in place
+ expect(out.correlationWindow).toHaveLength(1);
+ expect(out.correlationWindow[0]).toMatchObject({
+ taskType: 'user-task', tier: 'heavy', predictedRisk: true, bad: false
+ });
+ expect(out.correlationWindow[0].recordedAt).toBeTruthy();
+ });
+
+ it('coerces predictedRisk/bad to booleans and nulls absent taskType/tier', () => {
+ const data = {};
+ recordCorrelationSample(data, { predictedRisk: 1, bad: 0 });
+ expect(data.correlationWindow[0]).toMatchObject({
+ predictedRisk: true, bad: false, taskType: null, tier: null
+ });
+ });
+
+ it('bounds the rolling window to the last 200 samples', () => {
+ const data = {};
+ for (let i = 0; i < 250; i++) recordCorrelationSample(data, { predictedRisk: false, bad: false });
+ expect(data.correlationWindow).toHaveLength(200);
+ });
+});
+
+describe('computeCorrelationQuality', () => {
+ it('scores a perfectly-correlated window at 1.0', () => {
+ const q = computeCorrelationQuality(perfectWindow(15, 15));
+ expect(q.score).toBe(1);
+ expect(q.sampleCount).toBe(30);
+ expect(q.confident).toBe(true);
+ expect(q.matrix).toEqual({ tp: 15, fp: 0, fn: 0, tn: 15 });
+ });
+
+ it('scores a perfectly-anticorrelated window at -1.0', () => {
+ const window = [
+ ...Array.from({ length: 15 }, () => pair(true, false)),
+ ...Array.from({ length: 15 }, () => pair(false, true))
+ ];
+ expect(computeCorrelationQuality(window).score).toBe(-1);
+ });
+
+ it('returns a null score (not 0) for a degenerate window with only one predicted class', () => {
+ // Every run predicted-safe → (tp+fp) === 0 → denominator 0 → not measurable.
+ const window = Array.from({ length: 30 }, () => pair(false, false));
+ const q = computeCorrelationQuality(window);
+ expect(q.score).toBeNull();
+ expect(q.confident).toBe(false); // null score is never confident
+ expect(q.sampleCount).toBe(30);
+ });
+
+ it('returns a null score for a degenerate window where no run went bad', () => {
+ const window = [
+ ...Array.from({ length: 15 }, () => pair(true, false)),
+ ...Array.from({ length: 15 }, () => pair(false, false))
+ ];
+ expect(computeCorrelationQuality(window).score).toBeNull();
+ });
+
+ it('is not confident below the minimum sample bar even with a perfect score', () => {
+ const q = computeCorrelationQuality(perfectWindow(2, 2)); // 4 < MIN_CORRELATION_SAMPLES
+ expect(q.score).toBe(1);
+ expect(q.sampleCount).toBe(4);
+ expect(q.confident).toBe(false);
+ });
+
+ it('tolerates a missing/undefined window (pre-#2344 learning file)', () => {
+ const q = computeCorrelationQuality(undefined);
+ expect(q).toEqual({ score: null, sampleCount: 0, confident: false, matrix: { tp: 0, fp: 0, fn: 0, tn: 0 } });
+ });
+
+ it('honors a custom minSamples override', () => {
+ const q = computeCorrelationQuality(perfectWindow(3, 2), { minSamples: 5 });
+ expect(q.confident).toBe(true); // 5 samples >= 5
+ });
+});
+
+describe('isCorrelationProven', () => {
+ it('is true only for a confident, measurable score above the threshold', () => {
+ expect(isCorrelationProven(computeCorrelationQuality(perfectWindow(15, 15)))).toBe(true);
+ });
+
+ it('is false when not confident (too few samples)', () => {
+ expect(isCorrelationProven(computeCorrelationQuality(perfectWindow(2, 2)))).toBe(false);
+ });
+
+ it('is false for a degenerate null score', () => {
+ const q = computeCorrelationQuality(Array.from({ length: 30 }, () => pair(false, false)));
+ expect(isCorrelationProven(q)).toBe(false);
+ });
+
+ it('is false for a confident score that sits at or below the threshold', () => {
+ // Mixed window with modest positive correlation below 0.8.
+ const window = [
+ ...Array.from({ length: 8 }, () => pair(true, true)),
+ ...Array.from({ length: 4 }, () => pair(true, false)),
+ ...Array.from({ length: 4 }, () => pair(false, true)),
+ ...Array.from({ length: 8 }, () => pair(false, false))
+ ];
+ const q = computeCorrelationQuality(window);
+ expect(q.confident).toBe(true);
+ expect(q.score).toBeLessThanOrEqual(CORRELATION_QUALITY_THRESHOLD);
+ expect(isCorrelationProven(q)).toBe(false);
+ });
+
+ it('exposes the documented threshold and sample-bar constants', () => {
+ expect(CORRELATION_QUALITY_THRESHOLD).toBe(0.8);
+ expect(MIN_CORRELATION_SAMPLES).toBeGreaterThan(0);
+ });
+});
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index cd42393938..a9203ed17a 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -9,6 +9,7 @@
* - store.js — shared persistence, cache, mutex, pure helpers
* - metrics.js — recording completions + rebuilding aggregates
* - routing.js — heuristic routing, cooldown, skip, confidence
+ * - correlationQuality.js — enriched-signal ↔ outcome correlation window
* - durations.js — duration estimates + queue completion
* - insights.js — insights view, recommendations, dismissals
* - promptRecommendations.js — prompt-improvement suggestions
@@ -51,6 +52,15 @@ export {
getConfidenceLevels
} from './routing.js';
+export {
+ computeCorrelationQuality,
+ recordCorrelationSample,
+ isCorrelationProven,
+ getCorrelationQuality,
+ CORRELATION_QUALITY_THRESHOLD,
+ MIN_CORRELATION_SAMPLES
+} from './correlationQuality.js';
+
export {
getTaskDurationEstimate,
getAllTaskDurations,
diff --git a/server/services/taskLearning/insights.js b/server/services/taskLearning/insights.js
index 24582c4e97..0a8473494d 100644
--- a/server/services/taskLearning/insights.js
+++ b/server/services/taskLearning/insights.js
@@ -13,6 +13,7 @@ import {
loadDismissedRecommendations,
saveDismissedRecommendations
} from './store.js';
+import { computeCorrelationQuality, CORRELATION_QUALITY_THRESHOLD } from './correlationQuality.js';
/**
* Get learning insights for display
@@ -61,6 +62,11 @@ export async function getLearningInsights() {
}))
.sort((a, b) => b.successRate - a.successRate);
+ // Correlation-quality gauge (issue #2344): how well the enriched failure
+ // signal predicts actual outcomes over the rolling window. `proven` mirrors the
+ // routing aggressiveness gate (score > threshold with enough samples).
+ const correlationQuality = computeCorrelationQuality(data.correlationWindow);
+
return {
lastUpdated: data.lastUpdated,
totals: {
@@ -68,6 +74,12 @@ export async function getLearningInsights() {
successRate: overallSuccessRate,
avgDurationMin: Math.round(data.totals.avgDurationMs / 60000)
},
+ correlationQuality: {
+ ...correlationQuality,
+ threshold: CORRELATION_QUALITY_THRESHOLD,
+ proven: correlationQuality.confident && correlationQuality.score !== null
+ && correlationQuality.score > CORRELATION_QUALITY_THRESHOLD
+ },
insights: {
bestPerforming: bestPerforming.map(t => ({
type: t.type,
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index b5446804b1..1fe2c61dfd 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -19,6 +19,8 @@ import {
loadLearningData,
saveLearningData
} from './store.js';
+import { deriveFailureSignalAvoidance } from './routing.js';
+import { recordCorrelationSample } from './correlationQuality.js';
// Cap on retained per-category signature samples — bounds file growth the same
// way `recentUnknownErrors` does, while keeping enough recent context to spot
@@ -88,11 +90,21 @@ export function computeLatencySplit({ startedAt, completedAt, createdAt, duratio
* failureSignature — { category, messageSnippet, failurePosition } (null on success)
* executionContext — { provider, model, modelTier, taskType, component, inputChars, routingReason }
* latency — { wallMs, queueMs, executionMs } (null members when not derivable)
+ * validationPassed — success-criteria validation boolean (issue #2344):
+ * did the run meet its DECLARED success criteria, distinct from the runner's
+ * exit-code `success`? null sentinel = no machine-checkable criterion was
+ * declared for this task; true/false = declared criterion met / not met.
+ * Stamped authoritatively at the completion chokepoint (finalizeAgent) onto
+ * `result.validationPassed`; surfaced here with an explicit null default so
+ * "absent" never masquerades as `false`.
*/
export function buildTaskTelemetryContext(agent, task) {
const meta = agent?.metadata || {};
const result = agent?.result || {};
const success = result.success || false;
+ // Sentinel discipline: only an explicit boolean counts as a validation verdict;
+ // anything else (undefined/null/non-bool) is "no criterion declared" → null.
+ const validationPassed = typeof result.validationPassed === 'boolean' ? result.validationPassed : null;
const taskType = extractTaskType(task);
const errorAnalysis = result.errorAnalysis || null;
@@ -131,6 +143,7 @@ export function buildTaskTelemetryContext(agent, task) {
return {
taskType,
success,
+ validationPassed,
failureSignature,
executionContext,
latency
@@ -165,6 +178,10 @@ export function recordFailureSignature(data, context) {
taskType: context.executionContext.taskType,
wallMs: context.latency.wallMs,
executionMs: context.latency.executionMs,
+ // Success-criteria validation verdict at failure time (issue #2344): null
+ // when no machine-checkable criterion was declared, false when declared and
+ // missed. Explicit null default keeps "absent" distinct from "failed".
+ validationPassed: context.validationPassed ?? null,
recordedAt
});
if (bucket.recent.length > MAX_SIGNATURE_SAMPLES) {
@@ -296,6 +313,23 @@ export async function recordTaskCompletion(agent, task) {
}
}
+ // Correlation-quality window (issue #2344): record whether the enriched
+ // failure signal — computed from history BEFORE this completion is folded in —
+ // flagged this run's tier as risky, paired with the actual outcome. Measured
+ // BEFORE recordFailureSignature so this run's own failure can't leak into its
+ // own prediction. Uses the signal's BASE sensitivity (the default aggressive
+ // sample bar) as the fixed predictor — measuring the gate against its own
+ // correlation-gated output would be circular. A run that "succeeded" but MISSED
+ // its declared success criteria (validationPassed === false) counts as a bad
+ // outcome, tying the two #2344 signals together. Skipped for the unknown tier
+ // (no routable prediction to make).
+ if (modelTier && modelTier !== 'unknown') {
+ const priorAvoidance = deriveFailureSignalAvoidance(data, taskType);
+ const predictedRisk = priorAvoidance.avoidTiers.includes(modelTier);
+ const bad = telemetry.validationPassed === false ? true : !success;
+ recordCorrelationSample(data, { taskType, tier: modelTier, predictedRisk, bad });
+ }
+
// Aggregate the enriched failure signature (category + snippet + position +
// execution context + latency) — a no-op on success (issue #2329).
recordFailureSignature(data, telemetry);
diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.js
index e6647a90c3..710829ec0a 100644
--- a/server/services/taskLearning/metrics.test.js
+++ b/server/services/taskLearning/metrics.test.js
@@ -158,6 +158,45 @@ describe('buildTaskTelemetryContext', () => {
});
});
+ it('surfaces the success-criteria validation boolean with a null sentinel default (#2344)', () => {
+ // No validationPassed on the result → null sentinel (no criterion declared),
+ // never conflated with a false.
+ const ctx = buildTaskTelemetryContext(baseAgent, { taskType: 'user' });
+ expect(ctx.validationPassed).toBeNull();
+
+ // Explicit true/false pass through unchanged — distinct from result.success.
+ const passed = buildTaskTelemetryContext(
+ { ...baseAgent, result: { success: true, duration: 1000, validationPassed: true } }, {});
+ expect(passed.validationPassed).toBe(true);
+
+ // "ran clean but produced nothing": success true yet criterion missed.
+ const missed = buildTaskTelemetryContext(
+ { ...baseAgent, result: { success: true, duration: 1000, validationPassed: false } }, {});
+ expect(missed.success).toBe(true);
+ expect(missed.validationPassed).toBe(false);
+
+ // A non-boolean (e.g. undefined-shaped) validation value never leaks through.
+ const bogus = buildTaskTelemetryContext(
+ { ...baseAgent, result: { success: false, duration: 1, validationPassed: 'nope' } }, {});
+ expect(bogus.validationPassed).toBeNull();
+ });
+
+ it('carries the validation verdict into the harvested failure signature sample (#2344)', () => {
+ const agent = {
+ ...baseAgent,
+ result: {
+ success: false,
+ duration: 2000,
+ validationPassed: false,
+ errorAnalysis: { category: 'test-failure', message: 'no commit produced' }
+ }
+ };
+ const ctx = buildTaskTelemetryContext(agent, { description: 'fix the flaky test', taskType: 'internal' });
+ const data = { failureSignatures: {} };
+ recordFailureSignature(data, ctx);
+ expect(data.failureSignatures['test-failure'].recent[0].validationPassed).toBe(false);
+ });
+
it('harvests failures even for the sandboxed external/untyped fallback (#2333)', () => {
const agent = {
...baseAgent,
diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.js
index 1c87f45aed..164fcca511 100644
--- a/server/services/taskLearning/routing.js
+++ b/server/services/taskLearning/routing.js
@@ -11,6 +11,7 @@
import { loadLearningData, emitLog, isSandboxedTaskType } from './store.js';
import { resetTaskTypeLearning } from './metrics.js';
+import { computeCorrelationQuality, isCorrelationProven } from './correlationQuality.js';
/**
* Relative resource cost of each tier name that can land in
@@ -62,9 +63,19 @@ const HIGH_SUCCESS_THRESHOLD = 80;
* Minimum recent failure samples on a single tier (scoped to a task type) before
* the enriched failure signatures can steer routing away from it. Matches the
* routingAccuracy "≥3 attempts" bar so a one-off failure never condemns a tier.
+ * This is the AGGRESSIVE bar, used once the correlation-quality window has proven
+ * the signal predicts outcomes well (>0.8, issue #2344).
*/
const MIN_FAILURE_SAMPLES = 3;
+/**
+ * Conservative failure-sample bar used until the correlation-quality window
+ * proves the enriched signal actually predicts bad outcomes (issue #2344). While
+ * the signal is unproven, require MORE recent failures before steering off a
+ * tier, so the system doesn't over-correct on a signal that hasn't earned it.
+ */
+const CONSERVATIVE_MIN_FAILURE_SAMPLES = 5;
+
/** NUL separator joining provider+model into one tally key (safe: neither contains NUL). */
const PAIR_SEP = '\x00';
@@ -95,10 +106,16 @@ function topKey(counts) {
* tier on their own (a tier with 100 successes + 3 failures is fine). The
* cross-check is what keeps this from starving a good tier.
*
+ * `minFailureSamples` (issue #2344) is the failure-sample bar a tier must clear
+ * before it is steered away from. Callers pass the conservative bar until the
+ * correlation-quality window proves the signal predicts outcomes (>0.8); default
+ * stays at the aggressive `MIN_FAILURE_SAMPLES` for back-compat with direct
+ * callers/tests.
+ *
* @returns {{ avoidTiers: string[], sampleCount: number,
* dominant: { tier, failures, provider, model }|null }}
*/
-export function deriveFailureSignalAvoidance(data, taskType) {
+export function deriveFailureSignalAvoidance(data, taskType, { minFailureSamples = MIN_FAILURE_SAMPLES } = {}) {
const signatures = data?.failureSignatures || {};
const routing = data?.routingAccuracy?.[taskType] || {};
@@ -128,7 +145,7 @@ export function deriveFailureSignalAvoidance(data, taskType) {
// null = no success data (not "0% success") — an unproven tier by default.
const successRate = attempts > 0 ? Math.round((r.succeeded / attempts) * 100) : null;
const proven = successRate !== null && successRate >= HIGH_SUCCESS_THRESHOLD;
- if (proven || stats.failures < MIN_FAILURE_SAMPLES) continue;
+ if (proven || stats.failures < minFailureSamples) continue;
avoidTiers.push(tier);
// `dominant` is the AVOIDED tier with the most recent failures — the tier we
// actually steer away from — so the attribution surfaced in logs/reasons can
@@ -182,14 +199,23 @@ export async function suggestModelTier(taskType) {
const data = await loadLearningData();
+ // Auto-adjustment aggressiveness gate (issue #2344): the enriched failure
+ // signal steers routing more aggressively only once the correlation-quality
+ // window proves it actually predicts bad outcomes (>0.8). Until then, require a
+ // higher failure-sample bar so the system doesn't over-correct on an unproven
+ // signal. Computed synchronously from the already-loaded window — no extra I/O.
+ const correlationQuality = computeCorrelationQuality(data.correlationWindow);
+ const aggressive = isCorrelationProven(correlationQuality);
+ const minFailureSamples = aggressive ? MIN_FAILURE_SAMPLES : CONSERVATIVE_MIN_FAILURE_SAMPLES;
+
// Recency-weighted, provider-attributed avoidance from the enriched failure
// signatures (#2329) — folded into every suggestion below so a tier that's
// freshly degrading is steered away from before its all-time routingAccuracy
// rate crosses the hard misroute line. Computed BEFORE the completions guard:
- // the signal has its own MIN_FAILURE_SAMPLES bar, so 3-4 recent failures on a
- // tier can steer selection even before routingAccuracy has enough data to
- // suggest a tier at all.
- const failureAvoidance = deriveFailureSignalAvoidance(data, taskType);
+ // the signal has its own failure-sample bar, so recent failures on a tier can
+ // steer selection even before routingAccuracy has enough data to suggest a
+ // tier at all.
+ const failureAvoidance = deriveFailureSignalAvoidance(data, taskType, { minFailureSamples });
const withFailureSignal = (suggestion, existingAvoid = []) => {
const avoidTiers = mergeAvoidTiers(existingAvoid, failureAvoidance.avoidTiers);
// If the tier we were about to suggest is itself failure-flagged (a 60-79%
diff --git a/server/services/taskLearning/routing.test.js b/server/services/taskLearning/routing.test.js
index b942bbd829..9f0529158a 100644
--- a/server/services/taskLearning/routing.test.js
+++ b/server/services/taskLearning/routing.test.js
@@ -84,4 +84,16 @@ describe('deriveFailureSignalAvoidance (#2329)', () => {
const out = deriveFailureSignalAvoidance({ routingAccuracy: {} }, 'user-task');
expect(out).toEqual({ avoidTiers: [], sampleCount: 0, dominant: null });
});
+
+ it('respects a caller-supplied minFailureSamples bar (issue #2344 aggressiveness gate)', () => {
+ // 3 unproven-tier failures: steered off at the aggressive default bar (3)...
+ const data = dataWith([sample(), sample(), sample()]);
+ expect(deriveFailureSignalAvoidance(data, 'user-task').avoidTiers).toContain('heavy');
+ // ...but held back at the conservative bar (5) the routing gate uses until
+ // the correlation-quality window proves the signal predicts outcomes.
+ expect(deriveFailureSignalAvoidance(data, 'user-task', { minFailureSamples: 5 }).avoidTiers).toEqual([]);
+ // Once enough failures accumulate, even the conservative bar steers off.
+ const more = dataWith([sample(), sample(), sample(), sample(), sample()]);
+ expect(deriveFailureSignalAvoidance(more, 'user-task', { minFailureSamples: 5 }).avoidTiers).toContain('heavy');
+ });
});
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 91f65e1aa0..ac674d70c3 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -65,6 +65,12 @@ const DEFAULT_LEARNING_DATA = {
// Records which model tiers work/fail for each task type
routingAccuracy: {},
+ // Rolling correlation-quality window (issue #2344): prediction/outcome pairs
+ // measuring how well the enriched failure signals predict actual outcomes.
+ // Gates auto-adjustment aggressiveness (see correlationQuality.js). Additive:
+ // older learning.json files predate this key and load fine.
+ correlationWindow: [],
+
// Overall stats
totals: {
completed: 0,