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

fix: require provider/runner provenance before excluding environmental failures from task learning (#2642)

Adam Eivyd35bd43f774d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fa18310569..af3a2da922 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -93,3 +93,4 @@
- **[issue-2616] Add type-level consecutive-failure backoff with auto-park + notification; count unparseable agent output as failure.** The agent engine had no failure memory at the task-*type* level, so a permanently-broken scheduled type (or one whose instances all fail) re-queued on schedule forever — burning provider quota with no backoff, auto-disable, or notification (`failureCount` lived only in per-instance metadata; ROTATION types had no cadence gate at all, returning `shouldRun: true` unconditionally). A new per-type failure ledger now lives on the schedule execution record (`consecutiveFailures`/`lastFailureAt`/`lastErrorCategory`, per app + global) — persisted alongside `lastRun`, so it survives restarts as per-install runtime state (additive, backward-compatible, never synced). `shouldRunTask` applies an escalating failure cooldown (`2^n × base`, capped at a day) to *all* cadence types including ROTATION, so a failing type slows down instead of re-queuing every tick; after 5 consecutive failures the type auto-parks (indefinitely, for every cadence type) and fires a user-facing `AGENT_WARNING` notification naming the type, app, and last error category. A success resets the counter and lifts the park; a manual "Run now" or a config change (`updateTaskInterval`) clears the ledger to unpark. Separately, an LLM run that exits 0 but whose `.agent-done` output is unparseable — previously recorded as a benign completed success, invisible to any failure accounting — now feeds a failure signal into the ledger via the pure `resolveTypeFailureSignal` (an `unparseable-response` hook reason, or a thrown output hook, counts as a failure regardless of exit code; benign hook reasons like `no-proposal`/`duplicate` defer to the exit code). The existing per-instance retry ladder (`MAX_TASK_RETRIES`/`MAX_TOTAL_SPAWNS`) is unchanged. New unit tests cover the backoff math, ledger increment/reset/auto-park/notify/unpark, the ROTATION cooldown/park gates, and the unparseable-as-failure decision.
- **[issue-2535] Paginate the creative-catalog + media list endpoints with the shared `paginateArray` helper.** The primary index `GET`s for creativeDirector (`/`), storyBuilder (`/`), universeBuilder (`/`), moodBoard (`/`), videoTimeline (`/projects`), and loras (`/`) returned unbounded arrays. Each now opts into pagination the moment a client sends `limit`/`offset`, mirroring the `brainCrud` precedent: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` envelope (via the existing `paginateArray` in `server/lib/validation.js`, `defaultLimit: 50`, `maxLimit: 500`), while a request with no pagination params still returns the full array byte-for-byte — so every current client (none of which pass those params to these routes) is unaffected and no client change is required. New route tests assert both the default array and the paginated envelope for each domain (moodBoard gains its first route test). Refs #2535 — CoS tasks (the `?full=1` default-paginated slice) already shipped; privacy vault/orgs/changes/brokers and digital-twin documents remain.
- **[issue-2535] Paginate the remaining privacy + digital-twin list endpoints, completing the sweep.** The last unbounded index `GET`s flagged by #2535 — privacy `/vault`, `/orgs`, `/changes`, `/brokers`, `/broker-cases`, and digital-twin `/documents` — now opt into the shared `paginateArray` envelope exactly like the creative-catalog routes shipped in #2636: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` response (`defaultLimit: 50`, `maxLimit: 500`) the moment a client passes `limit`/`offset`, while a param-less request returns the full array byte-for-byte, so no client change is required. Because the four privacy list-query schemas are `.strict()` (they'd reject unknown keys), a local `paginationQueryFields` fragment (`limit`/`offset` as passthrough strings — `parsePagination` does the parse+clamp) is spread into `privacyVaultListQuerySchema`, `privacyOrgListQuerySchema`, `privacyBrokerListQuerySchema`, and `privacyBrokerCaseListQuerySchema` in `privacyValidation.js`; the `/orgs` handler strips `limit`/`offset` before passing filters to `listOrgs` so pagination never leaks into the service query. New route tests cover the vault/orgs/changes/broker-cases envelopes (filters preserved) and the digital-twin documents envelope. This closes the remaining slice of #2535 (the CoS-tasks default-paginated shape and the creative-catalog/media routes shipped previously).
+- **[issue-2642] Require provider/runner provenance before excluding environmental failures from task learning.** Environmental-failure exclusion previously trusted `errorAnalysis.category` alone, but that category is produced by the `analyzeAgentFailure` regex sweep over the failed agent's output tail — so ordinary task output could be misclassified as an infra category (e.g. a failing test whose tail prints "rate limit" tripping the unscoped `/rate.?limit/`) and the run would be silently diverted out of the learning aggregates as an "outage." `analyzeAgentFailure` now stamps an `origin` provenance marker on every classification: `'provider'`/`'runner'` when the match carries a genuine structured signal (an `API Error: NNN` line, a Node error code like `ECONNREFUSED`, a provider token like `overloaded_error`/`not_found_error`, or the structural startup-failure), and `'output-scan'` when it comes only from a loose keyword alternative. Mixed patterns (e.g. `API Error: 429` vs a bare `rate limit`) gate the promotion through a per-pattern `structuredMarker` sub-pattern via the new pure `resolvePatternOrigin` helper. The exclusion gate in `recordTaskCompletion` (`server/services/taskLearning/metrics.js`) now runs through a pure `shouldDivertToEnvironmental(outcomeSuccess, category, origin)` that additionally requires `origin !== 'output-scan'`, so an output-scan false positive counts as a genuine failure while structured signals stay excluded. Back-compat is preserved: an `errorAnalysis` with no `origin` (older records / federated peers) keeps the category-only behavior, and the routing-side signature filter is unchanged (it already fails safe). New unit tests cover the provenance stamping across the classifiers and all three acceptance cases in the gate.
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 46e3ef58a3..f51fffdb14 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -66,6 +66,19 @@ function snippetAround(text, index) {
* Error patterns that warrant investigation tasks.
* Patterns are checked in order — first match wins.
* Categories help the learning system identify failure trends.
+ *
+ * Provenance (#2642): a pattern may carry a structured `origin`
+ * (`'provider'` | `'runner'`) declaring that a match comes from a genuine
+ * provider/runner signal (an `API Error: NNN` line, a Node error code, a
+ * provider-specific error token) rather than the loose regex sweep over agent
+ * output. When the same regex mixes a structured alternative with a loose
+ * keyword alternative (e.g. `API Error: 429` vs a bare `rate limit`), a
+ * `structuredMarker` sub-pattern gates the promotion: the structured `origin`
+ * is only honored when the marker is present in the matched text; otherwise the
+ * match is treated as `'output-scan'` (see `resolvePatternOrigin`). Patterns
+ * with no `origin` are always `'output-scan'`. Task-learning's environmental
+ * exclusion (metrics.js) diverts only non-`output-scan` failures, so a failing
+ * test whose tail prints "rate limit" is NOT misread as an infra outage.
*/
export const ERROR_PATTERNS = [
// ===== API & Authentication Errors =====
@@ -73,6 +86,7 @@ export const ERROR_PATTERNS = [
pattern: /API Error: 404.*model:\s*(\S+)/i,
category: 'model-not-found',
actionable: true,
+ origin: 'provider', // fully structured — requires an `API Error: 404 … model:` line
escalation: 'Set a valid model id for this task (or clear its model override so the CLI falls back to its own configured default), then approve the retry.',
extract: (match, output, task, model) => ({
message: `Model "${match[1]}" not found`,
@@ -85,6 +99,11 @@ export const ERROR_PATTERNS = [
pattern: /(?:model:\s*)?["']?([A-Za-z0-9._:-]+)["']?\s+model is not supported|model\s+["']?([A-Za-z0-9._:-]+)["']?.*not supported/i,
category: 'model-not-supported',
actionable: true,
+ // Intentionally no structured origin (#2642): the matched text is just the
+ // "<model> model is not supported" phrase — a test asserting that string is
+ // indistinguishable from a genuine provider rejection here, so it stays
+ // output-scan. Real provider model rejections still divert via the structured
+ // `API Error: 4NN`/`not_found_error` patterns and `detectTerminalModelError`.
escalation: 'Pick a model the provider account supports (or clear the override to use the CLI default), then approve the retry.',
extract: (match, output, task, model) => ({
message: `Model "${match[1] || match[2] || model || 'configured model'}" is not supported`,
@@ -97,6 +116,8 @@ export const ERROR_PATTERNS = [
pattern: /API Error: 401|authentication|unauthorized/i,
category: 'auth-error',
actionable: true,
+ origin: 'provider',
+ structuredMarker: /API Error:\s*401/i, // loose `authentication`/`unauthorized` in output stays output-scan
extract: () => ({
message: 'Authentication failed',
suggestedFix: 'Check API keys and provider configuration'
@@ -106,6 +127,8 @@ export const ERROR_PATTERNS = [
pattern: /API Error: 429|rate.?limit|too many requests/i,
category: 'rate-limit',
actionable: false, // Transient, retry will handle
+ origin: 'provider',
+ structuredMarker: /API Error:\s*429/i, // a bare `rate limit` / `too many requests` in output stays output-scan
extract: () => ({
message: 'Rate limit exceeded',
suggestedFix: 'Wait and retry - temporary rate limiting'
@@ -116,6 +139,12 @@ export const ERROR_PATTERNS = [
pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit|(?:^|\n)\s*(?:\[stderr\]\s*)?Now using extra usage\s*(?:\r?\n|$))/i,
category: 'usage-limit',
actionable: true, // Need to switch provider
+ // Promote only the distinctive provider-billing idioms (the matched
+ // alternative, i.e. match[0]) to a structured provider signal; generic
+ // phrasings like "quota exceeded" / "plan limit" / "daily limit" that a task's
+ // own output can print stay output-scan and count as genuine failures (#2642).
+ origin: 'provider',
+ structuredMarker: /hit your (?:usage )?limit|Upgrade to Pro|Now using extra usage/i,
extract: (match, output) => {
const timeMatch = output.match(/(?:try again in|resets?)\s+(.+?)(?:\.|·|\n|$)/im);
const waitTime = timeMatch ? timeMatch[1].trim() : null;
@@ -143,6 +172,8 @@ export const ERROR_PATTERNS = [
pattern: /API Error: 403|forbidden/i,
category: 'forbidden',
actionable: true,
+ origin: 'provider',
+ structuredMarker: /API Error:\s*403/i, // loose `forbidden` in output stays output-scan
extract: () => ({
message: 'API access forbidden',
suggestedFix: 'API key lacks permission for this operation. Check API key permissions and provider configuration.'
@@ -161,6 +192,7 @@ export const ERROR_PATTERNS = [
pattern: /not_found_error.*model/i,
category: 'model-not-found',
actionable: true,
+ origin: 'provider', // structured provider `not_found_error` API token
extract: (match, output, task, model) => ({
message: `Model not found in API response`,
suggestedFix: `The model "${model}" specified for this task doesn't exist. Update provider or task configuration.`,
@@ -320,6 +352,8 @@ export const ERROR_PATTERNS = [
pattern: /ECONNREFUSED|ETIMEDOUT|network error/i,
category: 'network-error',
actionable: false,
+ origin: 'runner',
+ structuredMarker: /ECONNREFUSED|ETIMEDOUT/i, // a bare `network error` in output stays output-scan
extract: () => ({
message: 'Network connection failed',
suggestedFix: 'Check network connectivity and service availability.'
@@ -400,6 +434,8 @@ export const ERROR_PATTERNS = [
pattern: /(?:claude|anthropic).?(?:error|failed)|overloaded_error/i,
category: 'claude-error',
actionable: false,
+ origin: 'provider',
+ structuredMarker: /overloaded_error/i, // loose `claude error`/`anthropic failed` in output stays output-scan
extract: () => ({
message: 'Claude API error',
suggestedFix: 'Claude API returned an error. This is usually transient - retry recommended.'
@@ -466,6 +502,26 @@ function getFailureAnalysisWindow(output) {
.join('\n');
}
+/**
+ * Resolve the provenance origin for a matched ERROR_PATTERN (#2642). Returns the
+ * pattern's structured `origin` (`'provider'`/`'runner'`) only when it is
+ * declared AND — if a `structuredMarker` sub-pattern is present — that marker
+ * appears somewhere in the failure window. A pattern with no structured origin,
+ * or a `structuredMarker` that is absent, falls through to `'output-scan'`,
+ * marking the classification as coming solely from the loose regex sweep.
+ *
+ * The marker is tested against the WHOLE analysis window, not just the matched
+ * substring: the main pattern's alternation returns the LEFTMOST match, which
+ * may be a loose alternative (a bare `rate limit`) even when a genuine
+ * `API Error: 429` appears later in the same output — so a real provider signal
+ * anywhere in the window still promotes the classification (#2642 review). Pure.
+ */
+function resolvePatternOrigin(errorDef, analysisOutput) {
+ if (!errorDef.origin) return 'output-scan';
+ if (errorDef.structuredMarker && !errorDef.structuredMarker.test(analysisOutput || '')) return 'output-scan';
+ return errorDef.origin;
+}
+
/**
* Analyze agent failure output and categorize the error.
*/
@@ -475,6 +531,9 @@ export function analyzeAgentFailure(output, task, model) {
return {
category: 'startup-failure',
actionable: false,
+ // Structural runner signal (#2642): inferred from the process producing no
+ // usable output, not from a regex sweep — so it stays environmental-eligible.
+ origin: 'runner',
message: 'Agent failed to start or produced no output',
suggestedFix: 'Agent process exited immediately. Check system resources and provider availability.',
snippet: (output || '').trim(),
@@ -491,6 +550,9 @@ export function analyzeAgentFailure(output, task, model) {
return {
category: errorDef.category,
actionable: errorDef.actionable,
+ // Provenance (#2642): 'provider'/'runner' only when a structured marker
+ // is present in the failure window; a loose keyword match stays 'output-scan'.
+ origin: resolvePatternOrigin(errorDef, analysisOutput),
// Captured for the human-facing investigation body; redacted at embed time.
snippet: snippetAround(analysisOutput, match.index ?? 0),
// Optional category-specific "what to approve" prose (may be undefined).
@@ -513,6 +575,9 @@ export function analyzeAgentFailure(output, task, model) {
return {
category: 'unknown',
actionable: false,
+ // Pure regex/keyword sweep over the output tail (#2642) — never diverted as
+ // environmental (and 'unknown' isn't an environmental category anyway).
+ origin: 'output-scan',
message: summary,
details: contextLines.map(l => l.trim()).join('\n'),
snippet: contextLines.map(l => l.trim()).join(' '),
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 869f2ae63a..31d43c40a6 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -151,6 +151,89 @@ describe('analyzeAgentFailure — ERROR_PATTERNS classification', () => {
});
});
+// Classification provenance (#2642): the environmental-exclusion gate in
+// task-learning trusts `origin` to tell a genuine provider/runner signal from a
+// loose keyword sweep over agent output, so every classifier return stamps one.
+describe('analyzeAgentFailure — provenance origin (#2642)', () => {
+ it('stamps provider origin on a structured API-error rate-limit', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 429 Too Many Requests, please slow down'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('rate-limit');
+ expect(analysis.origin).toBe('provider');
+ });
+
+ it('stamps output-scan origin on a bare "rate limit" phrase in agent output', () => {
+ // A failing test whose tail prints "rate limit" trips /rate.?limit/ but is NOT
+ // a provider signal — it must stay output-scan so learning counts it as real.
+ const analysis = analyzeAgentFailure(withLead('FAIL src/foo.test.js — the rate limit guard rejected the request'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('rate-limit');
+ expect(analysis.origin).toBe('output-scan');
+ });
+
+ it('stamps runner origin on a structured ECONNREFUSED but output-scan on a bare "network error"', () => {
+ const refused = analyzeAgentFailure(withLead('Error: connect ECONNREFUSED 127.0.0.1:443 while reaching the API'), { id: 't' }, 'x');
+ expect(refused.category).toBe('network-error');
+ expect(refused.origin).toBe('runner');
+
+ const bare = analyzeAgentFailure(withLead('The integration test asserted a network error banner is shown'), { id: 't' }, 'x');
+ expect(bare.category).toBe('network-error');
+ expect(bare.origin).toBe('output-scan');
+ });
+
+ it('stamps provider origin on a structured 401 but output-scan on a bare "unauthorized"', () => {
+ const structured = analyzeAgentFailure(withLead('API Error: 401 Unauthorized — authentication failed'), { id: 't' }, 'x');
+ expect(structured.origin).toBe('provider');
+
+ const bare = analyzeAgentFailure(withLead('The e2e suite failed: expected a 403 when unauthorized users hit /admin'), { id: 't' }, 'x');
+ expect(bare.category).toBe('auth-error');
+ expect(bare.origin).toBe('output-scan');
+ });
+
+ it('stamps provider origin on structured model errors', () => {
+ expect(analyzeAgentFailure(withLead('API Error: 404 - model: claude-4-ultra not found'), { id: 't' }, 'x').origin).toBe('provider');
+ expect(analyzeAgentFailure(withLead('Response: not_found_error - the requested model does not exist'), { id: 't' }, 'x').origin).toBe('provider');
+ });
+
+ it('stamps provider origin on a distinctive usage-limit idiom but output-scan on a bare "quota exceeded"', () => {
+ const idiom = analyzeAgentFailure(withLead('You have hit your usage limit for this account.'), { id: 't' }, 'x');
+ expect(idiom.category).toBe('usage-limit');
+ expect(idiom.origin).toBe('provider');
+
+ const generic = analyzeAgentFailure(withLead('The integration test expected a quota exceeded response from the stub.'), { id: 't' }, 'x');
+ expect(generic.category).toBe('usage-limit');
+ expect(generic.origin).toBe('output-scan');
+ });
+
+ it('stamps output-scan on model-not-supported (indistinguishable from a test asserting the phrase)', () => {
+ const analysis = analyzeAgentFailure(withLead("The 'gpt-5' model is not supported when using Codex with a ChatGPT account."), { id: 't' }, 'gpt-5');
+ expect(analysis.category).toBe('model-not-supported');
+ expect(analysis.origin).toBe('output-scan');
+ });
+
+ it('promotes to provider when a structured marker appears LATER than a loose match in the window', () => {
+ // Regex returns the leftmost match ("rate limit"), but a genuine "API Error: 429"
+ // later in the same output is still a real provider signal → provider, not output-scan.
+ const output = [
+ 'Initializing agent session and preparing the working directory.',
+ 'Note: the rate limit guard is enabled for this run',
+ 'API Error: 429 Too Many Requests — backing off'
+ ].join('\n');
+ const analysis = analyzeAgentFailure(output, { id: 't' }, 'x');
+ expect(analysis.category).toBe('rate-limit');
+ expect(analysis.origin).toBe('provider');
+ });
+
+ it('stamps runner origin on a startup failure and output-scan on an unknown match', () => {
+ expect(analyzeAgentFailure('boom', { id: 't' }, 'x').origin).toBe('runner');
+ expect(analyzeAgentFailure(withLead('The agent halted after an unrecognized condition with no diagnostic.'), { id: 't' }, 'x').origin).toBe('output-scan');
+ });
+
+ it('stamps output-scan on a non-environmental keyword match (test-failure)', () => {
+ const analysis = analyzeAgentFailure(withLead('A unit test failed while running the suite; review the assertions'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('test-failure');
+ expect(analysis.origin).toBe('output-scan');
+ });
+});
+
// Pure decision branch of resolveFailedTaskUpdate. Replaces the inline
// resolveFailedTaskStatus copy in subAgentSpawner.test.js, which omitted the
// MAX_TOTAL_SPAWNS short-circuit and the compaction metadata entirely.
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 478d1629de..615fc1a8aa 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -61,6 +61,33 @@ export function recordEnvironmentalFailure(data, { category, taskType } = {}) {
return data;
}
+/**
+ * Decide whether a failed run should be diverted to `environmentalFailures`
+ * instead of counting against the learning aggregates (issues #2618, #2642).
+ * Pure. Two gates, both required:
+ *
+ * 1. Category gate (#2618) — `category` is in ENVIRONMENTAL_ERROR_CATEGORIES.
+ * 2. Provenance gate (#2642) — only an allowlisted provenance authorizes the
+ * diversion. Structured provider/runner signals (`origin: 'provider'|
+ * 'runner'`) and records with NO origin marker (older runs / federated
+ * peers — back-compat, category-only as before) divert. Everything else —
+ * `'output-scan'` (a false positive: ordinary task output tripping a loose
+ * pattern, e.g. a failing test whose tail prints "rate limit") OR an
+ * unrecognized/future/malformed marker — is NOT diverted and counts as a
+ * genuine failure. Allowlist (not `!== 'output-scan'`) so an unknown origin
+ * can never silently exclude a real failure from the aggregates.
+ *
+ * @param {boolean} outcomeSuccess validation-authoritative outcome (#2344)
+ * @param {string|null} category failure category
+ * @param {string|null|undefined} origin provenance marker ('provider'|'runner'|'output-scan'|null)
+ */
+const DIVERTIBLE_ORIGINS = new Set(['provider', 'runner']);
+export function shouldDivertToEnvironmental(outcomeSuccess, category, origin) {
+ if (outcomeSuccess) return false;
+ if (!ENVIRONMENTAL_ERROR_CATEGORIES.has(category)) return false;
+ return origin == null || DIVERTIBLE_ORIGINS.has(origin);
+}
+
/**
* Remove a task type's contribution from every environmental bucket (issue
* #2618 reset parity): decrement each bucket's count by the type's share,
@@ -174,6 +201,13 @@ export function buildTaskTelemetryContext(agent, task) {
const rawMessage = errorAnalysis?.message || errorAnalysis?.details || '';
const failureSignature = outcomeSuccess ? null : {
category: errorAnalysis?.category || null,
+ // Classification provenance (#2642): 'provider'|'runner'|'output-scan', or
+ // null on records that predate the marker (older runs / federated peers).
+ // Gates the environmental exclusion below so an output-scan false positive
+ // isn't diverted out of the learning aggregates. `?? null` (not `|| null`) so
+ // only a genuinely-absent marker becomes the back-compat null — a malformed
+ // falsy value (e.g. '') is preserved and rejected by the gate's allowlist.
+ origin: errorAnalysis?.origin ?? 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.
@@ -278,6 +312,9 @@ export async function recordTaskCompletion(agent, task) {
const outcomeSuccess = telemetry.outcomeSuccess;
const duration = agent.result?.duration || 0;
const errorCategory = telemetry.failureSignature?.category || null;
+ // `?? null` preserves a malformed falsy origin ('') so the gate's allowlist
+ // rejects it, rather than `|| null` collapsing it into the back-compat null (#2642).
+ const errorOrigin = telemetry.failureSignature?.origin ?? null;
// Environmental failure gate (issue #2618): a rate-limit/auth/billing/startup
// failure says nothing about the task type or the model tier, so it must not
@@ -285,7 +322,11 @@ export async function recordTaskCompletion(agent, task) {
// get a healthy task type skipped (<30% gate) or a healthy tier avoided. Such
// runs are diverted to `environmentalFailures` below; errorPatterns and
// failureSignatures still record them for diagnostics/prompt hints.
- const isEnvironmentalFailure = !outcomeSuccess && ENVIRONMENTAL_ERROR_CATEGORIES.has(errorCategory);
+ // Provenance gate (#2642): a category derived only from the output-text regex
+ // sweep (`origin: 'output-scan'`) is NOT diverted — it may be a false positive
+ // (ordinary task output tripping a loose pattern). Structured provider/runner
+ // signals and pre-marker records (null origin) keep the category-only behavior.
+ const isEnvironmentalFailure = shouldDivertToEnvironmental(outcomeSuccess, errorCategory, errorOrigin);
// Correlation-quality prediction snapshot (issue #2344) — captured HERE, before
// ANY of this run's aggregates (byModelTier, routingAccuracy, failureSignatures)
diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.js
index 4f271f07d1..2ef77f235d 100644
--- a/server/services/taskLearning/metrics.test.js
+++ b/server/services/taskLearning/metrics.test.js
@@ -10,7 +10,7 @@ vi.mock('./store.js', async (importActual) => {
return { ...actual, loadLearningData: vi.fn() };
});
-import { buildTaskTelemetryContext, computeLatencySplit, recordFailureSignature, getWindowedStats, recordEnvironmentalFailure, ENVIRONMENTAL_ERROR_CATEGORIES } from './metrics.js';
+import { buildTaskTelemetryContext, computeLatencySplit, recordFailureSignature, getWindowedStats, recordEnvironmentalFailure, shouldDivertToEnvironmental, ENVIRONMENTAL_ERROR_CATEGORIES } from './metrics.js';
import { loadLearningData } from './store.js';
// buildTaskTelemetryContext + recordFailureSignature are the pure telemetry
@@ -69,7 +69,7 @@ describe('buildTaskTelemetryContext', () => {
result: {
success: false,
duration: 120000,
- errorAnalysis: { category: 'test-failure', message: 'Tests failed: 3 assertions' }
+ errorAnalysis: { category: 'test-failure', origin: 'output-scan', message: 'Tests failed: 3 assertions' }
}
};
const ctx = buildTaskTelemetryContext(agent, { taskType: 'internal', description: 'run tests' });
@@ -77,12 +77,42 @@ describe('buildTaskTelemetryContext', () => {
expect(ctx.success).toBe(false);
expect(ctx.failureSignature).toEqual({
category: 'test-failure',
+ origin: 'output-scan',
messageSnippet: 'Tests failed: 3 assertions',
failurePosition: 'testing'
});
expect(ctx.executionContext.taskType).toBe('internal-task');
});
+ it('carries a null origin on an errorAnalysis that predates the provenance marker (#2642)', () => {
+ const agent = {
+ ...baseAgent,
+ result: { success: false, duration: 1000, errorAnalysis: { category: 'rate-limit', message: 'Rate limited' } }
+ };
+ const ctx = buildTaskTelemetryContext(agent, { taskType: 'internal' });
+ expect(ctx.failureSignature.origin).toBeNull();
+ });
+
+ it('surfaces a structured provider origin from the errorAnalysis (#2642)', () => {
+ const agent = {
+ ...baseAgent,
+ result: { success: false, duration: 1000, errorAnalysis: { category: 'rate-limit', origin: 'provider', message: 'API Error: 429' } }
+ };
+ const ctx = buildTaskTelemetryContext(agent, { taskType: 'internal' });
+ expect(ctx.failureSignature.origin).toBe('provider');
+ });
+
+ it('preserves a malformed falsy origin instead of collapsing it into the back-compat null (#2642)', () => {
+ // A '' origin must NOT become null (which would divert as legacy) — it stays
+ // '' so the gate's allowlist rejects it and the failure is counted.
+ const agent = {
+ ...baseAgent,
+ result: { success: false, duration: 1000, errorAnalysis: { category: 'rate-limit', origin: '', message: 'x' } }
+ };
+ const ctx = buildTaskTelemetryContext(agent, { taskType: 'internal' });
+ expect(ctx.failureSignature.origin).toBe('');
+ });
+
it('falls back to errorAnalysis.details for the snippet and truncates to 200 chars', () => {
const longDetails = 'e'.repeat(500);
const agent = {
@@ -115,6 +145,7 @@ describe('buildTaskTelemetryContext', () => {
});
expect(ctx.failureSignature).toEqual({
category: null,
+ origin: null,
messageSnippet: null,
failurePosition: null
});
@@ -155,6 +186,7 @@ describe('buildTaskTelemetryContext', () => {
expect(ctx.executionContext.taskType).toBe('auto-fix'); // classified, not 'unknown'
expect(ctx.failureSignature).toEqual({
category: 'tool-error',
+ origin: null,
messageSnippet: 'ripgrep not found',
failurePosition: 'diagnosing'
});
@@ -437,6 +469,39 @@ describe('ENVIRONMENTAL_ERROR_CATEGORIES (issue #2618)', () => {
});
});
+describe('shouldDivertToEnvironmental (issue #2642)', () => {
+ it('diverts a structured provider/runner environmental failure (current behavior preserved)', () => {
+ // A rate-limit classified from a genuine provider signal is excluded from aggregates.
+ expect(shouldDivertToEnvironmental(false, 'rate-limit', 'provider')).toBe(true);
+ expect(shouldDivertToEnvironmental(false, 'startup-failure', 'runner')).toBe(true);
+ });
+
+ it('does NOT divert an environmental category that came only from the output-text sweep', () => {
+ // "rate limit" printed in ordinary task output → counts as a genuine failure.
+ expect(shouldDivertToEnvironmental(false, 'rate-limit', 'output-scan')).toBe(false);
+ expect(shouldDivertToEnvironmental(false, 'network-error', 'output-scan')).toBe(false);
+ });
+
+ it('preserves category-only behavior for records without a provenance marker (back-compat)', () => {
+ // Older runs / federated peers have no origin — null falls through to divert.
+ expect(shouldDivertToEnvironmental(false, 'rate-limit', null)).toBe(true);
+ expect(shouldDivertToEnvironmental(false, 'auth-error', undefined)).toBe(true);
+ });
+
+ it('never diverts a success or a non-environmental category', () => {
+ expect(shouldDivertToEnvironmental(true, 'rate-limit', 'provider')).toBe(false); // success
+ expect(shouldDivertToEnvironmental(false, 'test-failure', 'provider')).toBe(false); // not environmental
+ expect(shouldDivertToEnvironmental(false, 'unknown', 'output-scan')).toBe(false);
+ expect(shouldDivertToEnvironmental(false, null, null)).toBe(false);
+ });
+
+ it('does NOT divert an unrecognized/future/malformed origin (allowlist, fail-safe)', () => {
+ expect(shouldDivertToEnvironmental(false, 'rate-limit', 'exit-code')).toBe(false);
+ expect(shouldDivertToEnvironmental(false, 'rate-limit', 'PROVIDER')).toBe(false); // case-sensitive
+ expect(shouldDivertToEnvironmental(false, 'rate-limit', '')).toBe(false);
+ });
+});
+
describe('recordEnvironmentalFailure (issue #2618)', () => {
it('initializes the additive key on data that predates it (back-compat)', () => {
const data = {}; // old learning.json shape — no environmentalFailures key