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([issue-2764]): capture structured execution-failure taxonomy for LI hand-offs

[._.]/ Adam Eivyfd684ca2c982
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 28be91cf11..a2263883b9 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -32,6 +32,7 @@ import { getSettings } from './settings.js';
import { createTicket, searchIssues, addLabels, escapeJql } from './jira.js';
import { computeWindowedStats, computeEffectiveSuccessRate, EFFECTIVE_RATE_MIN_WINDOW_SAMPLES, extractTaskType } from './taskLearning/store.js';
import { formatRejectionReasons, formatRejectionReason, REJECTION_REASONS } from './layeredIntelligenceRejections.js';
+import { formatExecutionFailures } from './layeredIntelligenceExecutionFailures.js';
// Tracker labels + slug marker. The slug is the stable dedup key the reasoner
// chooses; it is embedded in each filed issue body so a later run (or the
@@ -711,6 +712,12 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }
// unknown", which the line reports explicitly.
const rejectionReasons = formatRejectionReasons(filed, 5);
+ // Structured diagnosis of every FAILED hand-off (#2764 §1) — the "why" behind the
+ // per-domain execution rate the liProposalExecution block reports (#2765). '' when
+ // no hand-off has failed, so the line below is omitted rather than contradicting a
+ // clean execution record.
+ const executionFailures = formatExecutionFailures(filed, 5);
+
// Low-merge-rate alarm (#2698). `rawMergeRate` is measured over RESOLVED
// proposals only and is null when none have resolved — see summarizeOutcomeStats
// for the sentinel rationale (pending ≠ rejected). A null rate stays silent
@@ -745,6 +752,10 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }
scopeLines || '- (none)',
'',
`Why non-merged proposals were closed: ${rejectionReasons || 'nothing has been closed unmerged yet'}`,
+ // Only emit the execution-failure line when a hand-off has actually failed —
+ // an app whose proposals were never handed off (or all succeeded) shows nothing
+ // here rather than a misleading "no failures" line.
+ ...(executionFailures ? [`Why LI's own hand-offs failed when implemented: ${executionFailures}`] : []),
...lowMergeWarning
].join('\n');
}
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index ae382d6b6e..55f45ae698 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -897,6 +897,27 @@ describe('computeOutcomesReport', () => {
expect(report).toContain('Why non-merged proposals were closed: already tracked elsewhere (duplicate) (1)');
});
+ it('surfaces the execution-failure taxonomy line only when a hand-off has failed (#2764 §1)', () => {
+ // A clean execution record shows no failure line…
+ const clean = computeOutcomesReport({
+ outcomes: [{ scope: 'loop-meta', outcome: 'merged', executionOutcome: 'success' }]
+ });
+ expect(clean).not.toContain("Why LI's own hand-offs failed");
+
+ // …but a failed hand-off surfaces the classified "why".
+ const withFailure = computeOutcomesReport({
+ outcomes: [
+ { scope: 'loop-meta', outcome: 'merged', executionOutcome: 'success' },
+ { scope: 'loop-meta', outcome: null, executionOutcome: 'failure', failureCategory: 'testing' },
+ { scope: 'loop-meta', outcome: null, executionOutcome: 'failure', failureCategory: 'testing' },
+ { scope: 'loop-meta', outcome: null, executionOutcome: 'failure', failureCategory: 'execution' }
+ ]
+ });
+ expect(withFailure).toContain("Why LI's own hand-offs failed when implemented:");
+ expect(withFailure).toContain('regression'); // the `testing` gloss
+ expect(withFailure).toContain('(2)'); // commonest diagnosis count
+ });
+
it('reports an undiagnosed rejection history as the data gap it is (#2689)', () => {
const report = computeOutcomesReport({
outcomes: [
diff --git a/server/services/layeredIntelligenceExecutionFailures.js b/server/services/layeredIntelligenceExecutionFailures.js
new file mode 100644
index 0000000000..0336960752
--- /dev/null
+++ b/server/services/layeredIntelligenceExecutionFailures.js
@@ -0,0 +1,268 @@
+/**
+ * Layered Intelligence execution-FAILURE taxonomy + classifier (#2764 §1).
+ *
+ * `computeExecutionByDomain` / `computeProposalExecutionAwareness` (#2765) answer
+ * *how often* LI's own hand-offs succeed per domain — a binary success/failure
+ * rate. They do not answer *why* an execution failed. Today the outcome store's
+ * `executionOutcome` slot holds only `'success'` / `'failure'`, so when the
+ * reasoner is told "LI implemented 0% of its loop-meta proposals" it learns the
+ * gap exists but nothing about its shape — planning? a regression? missing repo
+ * context? — which is exactly the signal needed to decide whether to narrow a
+ * proposal, defer it, or route it elsewhere.
+ *
+ * This module owns the structured vocabulary for that "why" and the deterministic
+ * mapping onto it. Pure, no I/O, no LLM call: the classification is derived from
+ * the failure signal the task-learning layer ALREADY computed for the run
+ * (`errorCategory` from agentErrorAnalysis's pattern sweep, plus the
+ * validation-authoritative `validationPassed`), so it adds no provider round-trip
+ * (the "no cold-bootstrap LLM calls" policy) and no extra work at the recording
+ * site.
+ *
+ * A LEAF module by design — it imports nothing from the LI graph — so both
+ * `layeredIntelligence.js` (which formats the report) and
+ * `layeredIntelligenceOutcomes.js` (which persists the classification) can use it
+ * without an import cycle. It intentionally mirrors the shape of its sibling
+ * `layeredIntelligenceRejections.js` (the proposal-REJECTION taxonomy): same
+ * three-valued sentinel discipline, same "diagnosed / unknown / unclassified"
+ * split, same bounded prompt-line renderer.
+ *
+ * SCOPE NOTE. Only NON-ENVIRONMENTAL failures ever reach this classifier: the
+ * recording site (`taskLearning/metrics.js`) already nulls the LI execution
+ * payload for environmental failures (rate-limit / outage / auth), so a
+ * provider-outage category never lands here and never dents a domain's failure
+ * shape. The remaining raw categories describe how LI's OWN implementation attempt
+ * went wrong — which is what this taxonomy classifies.
+ */
+
+// The execution-failure vocabulary (#2764 §1). Stored on the outcome record and
+// rendered into the reasoner's prompt, so these tokens are a persisted contract:
+// rename one and old records fail the sanitizer's membership check and coerce to
+// null (re-derived on the next execution write) — prefer ADDING over renaming.
+//
+// The five categories are the ones #2764 §1 names, each defined by the QUESTION it
+// answers about a failed hand-off:
+export const EXECUTION_FAILURE_CATEGORIES = [
+ // The task/proposal was under-defined or already satisfied — the agent had
+ // nothing correct to do (e.g. it produced no changes). A signal to write a
+ // sharper, smaller proposal body, not to try harder.
+ 'planning',
+ // The agent attempted the change but got it mechanically wrong — a merge
+ // conflict, a malformed edit, a tool/subprocess failure while applying it.
+ 'execution',
+ // The change was made but broke something the project checks — a failing test,
+ // a lint/build break, or a missed validation criterion (a regression).
+ 'testing',
+ // The agent lacked repo knowledge it needed — an expected file wasn't there, or
+ // the task overran the context/turn budget gathering what it needed to know.
+ 'context',
+ // The work was outside what an autonomous agent could do here — it declined the
+ // task, tripped a content filter, or hit a permission boundary. A signal to keep
+ // this kind of proposal for a human rather than hand it off.
+ 'scope'
+];
+
+/**
+ * The explicit "we classified this failure and no signal explained it" sentinel.
+ * NOT a member of EXECUTION_FAILURE_CATEGORIES: it is the ABSENCE of a diagnosis,
+ * not a diagnosis. Kept distinct from a `null` failureCategory, which means "not
+ * classified yet / not a failure" — conflating the two would either hide the data
+ * gap this taxonomy exists to measure or re-classify the same record forever. See
+ * sanitizeOutcomeRecord.
+ */
+export const UNKNOWN_EXECUTION_FAILURE = 'unknown-failure';
+
+// Every value the store may legitimately hold in `failureCategory` for a failed
+// execution.
+export const EXECUTION_FAILURE_VALUES = [...EXECUTION_FAILURE_CATEGORIES, UNKNOWN_EXECUTION_FAILURE];
+
+// Human-readable gloss, used to render the prompt line. A token with no gloss
+// degrades to the raw token rather than being dropped.
+const EXECUTION_FAILURE_LABELS = {
+ planning: 'the task was under-defined or already done (no correct change to make)',
+ execution: 'the agent applied the change incorrectly',
+ testing: 'the change broke a test / lint / build check (a regression)',
+ context: 'the agent lacked repo knowledge or ran out of context',
+ scope: "the work was outside an autonomous agent's reach here",
+ [UNKNOWN_EXECUTION_FAILURE]: 'failed with no recognized cause'
+};
+
+/**
+ * Render one token as prose for the reasoner. An unglossed token passes through;
+ * a nullish (unclassified) input renders as '' — mapping it onto the sentinel
+ * would invert the module's central rule by dressing "not classified" up as
+ * "classified, and we found nothing".
+ */
+export function formatExecutionFailure(category) {
+ if (!category) return '';
+ return EXECUTION_FAILURE_LABELS[category] || category;
+}
+
+// Normalize a raw error-category token for matching: lowercased, with separators
+// collapsed so `test_failure`, `test-failure`, and `Test Failure` all land on the
+// same key.
+function normalizeToken(value) {
+ return typeof value === 'string' ? value.trim().toLowerCase().replace(/[\s_-]+/g, '-') : '';
+}
+
+// Raw agentErrorAnalysis category → execution-failure taxonomy. Every key is one of
+// the `category` tokens ERROR_PATTERNS / analyzeAgentFailure produces
+// (server/services/agentErrorAnalysis.js), plus the validation-authoritative
+// `hook-error` / `unparseable-response` tokens the LI hook path can raise. The
+// mapping is deliberately conservative — a raw category with no confident home is
+// LEFT OUT so it falls through to the honest `unknown-failure` rather than being
+// forced into a bucket it doesn't belong in (the same "a miss is the correct
+// failure" discipline the rejection classifier uses).
+//
+// ENVIRONMENTAL categories (rate-limit, usage-limit, auth-error, forbidden,
+// billing-error, server-error, network-error, startup-failure, timeout,
+// claude-error, model-not-found/-not-supported) are intentionally ABSENT: they are
+// filtered out upstream (isEnvironmentalFailure → null LI payload) and say nothing
+// about LI's own capability, so on the off chance one arrives it correctly reads as
+// `unknown-failure` rather than a real capability signal.
+const RAW_CATEGORY_TAXONOMY = new Map(Object.entries({
+ // testing — the change was made but broke a project check (a regression).
+ 'test-failure': 'testing',
+ 'lint-error': 'testing',
+ 'build-error': 'testing',
+ 'npm-error': 'testing',
+ 'validation-miss': 'testing',
+
+ // execution — the agent got the mechanical application of the change wrong.
+ 'git-conflict': 'execution',
+ 'git-error': 'execution',
+ 'tool-error': 'execution',
+ 'mcp-error': 'execution',
+ 'parse-error': 'execution',
+ 'locator-error': 'execution',
+ 'browser-error': 'execution',
+ 'process-killed': 'execution',
+ 'spawn-error': 'execution',
+ 'memory-error': 'execution',
+ 'hook-error': 'execution',
+ 'unparseable-response': 'execution',
+
+ // context — the agent lacked repo knowledge, or overran the context/turn budget.
+ 'context-length': 'context',
+ 'output-length': 'context',
+ 'turn-limit': 'context',
+ 'file-not-found': 'context',
+
+ // scope — the work was outside what an autonomous agent could do here.
+ 'task-rejected': 'scope',
+ 'content-filtered': 'scope',
+ 'permission-denied': 'scope',
+ 'bad-request': 'scope',
+
+ // planning — the task was under-defined or already satisfied.
+ 'no-changes': 'planning'
+}));
+
+/**
+ * Classify WHY a handed-off LI proposal FAILED to execute (#2764 §1).
+ *
+ * Returns:
+ * - `null` when the execution did NOT fail — a success, or nothing to diagnose.
+ * Never invent a failure category for a successful run.
+ * - an EXECUTION_FAILURE_CATEGORIES token when a signal supports it.
+ * - UNKNOWN_EXECUTION_FAILURE when the run demonstrably failed but no signal
+ * explains it. This is the honest answer and a measured gap ("how much of our
+ * execution-failure history is undiagnosed"), so it must never be silently
+ * dressed up as a real cause.
+ *
+ * Signal precedence (most authoritative first):
+ * 1. the raw `errorCategory` (agentErrorAnalysis's pattern sweep) when it maps to
+ * a taxonomy token — the most specific evidence available;
+ * 2. `validationPassed === false` → `testing`: the run exited without a
+ * recognized error but missed its declared validation criterion, which is a
+ * regression/validation failure even though no error pattern matched (the
+ * validation-miss case the raw category can't express when errorCategory is
+ * null).
+ * Anything else falls through to `unknown-failure`.
+ *
+ * Deterministic and total: same inputs always yield the same token.
+ */
+export function classifyExecutionFailure({ success = null, executionOutcome = null, errorCategory = null, validationPassed = null } = {}) {
+ // Resolve whether this is a failed execution. Prefer an explicit boolean
+ // `success`; otherwise fall back to the stored `executionOutcome` token so the
+ // classifier can also re-diagnose a persisted record.
+ const failed = success === false || (success === null && executionOutcome === 'failure');
+ if (!failed) return null;
+
+ // 1. A mapped raw error category is the most specific signal.
+ const mapped = RAW_CATEGORY_TAXONOMY.get(normalizeToken(errorCategory));
+ if (mapped) return mapped;
+
+ // 2. No recognized error, but the run missed its declared validation criterion —
+ // a regression the error sweep didn't produce a category for.
+ if (validationPassed === false) return 'testing';
+
+ return UNKNOWN_EXECUTION_FAILURE;
+}
+
+/**
+ * Tally execution-failure categories across every FAILED-execution record. A
+ * successful execution has nothing to explain, and a record that was never handed
+ * off (executionOutcome null) never executed — neither is counted.
+ *
+ * Returns `{ entries, unknown, unclassified, diagnosed, total }` — the same shape,
+ * and the same three-bucket discipline, as summarizeRejectionReasons:
+ * - `entries` — `[{ category, count }]` of REAL diagnoses only, commonest first.
+ * - `unknown` — classified `unknown-failure`: we looked, no signal explained
+ * it. A MEASURED gap.
+ * - `unclassified` — a failed execution with no valid category stored at all:
+ * recorded before this field existed, or by a path that passed
+ * no failure signal. An UNMEASURED gap — a different fact from
+ * `unknown`, with a different remedy.
+ * - `diagnosed` — records carrying a real diagnosis (sum of `entries`).
+ * - `total` — every failed-execution record: the population being diagnosed.
+ * `total === 0` means, and only means, "no hand-off has failed".
+ *
+ * `unknown`/`unclassified` stay OUT of `entries` so they can't crowd real diagnoses
+ * out of a caller's top-N list — they measure missing data, they are not findings.
+ */
+export function summarizeExecutionFailures(outcomes = []) {
+ const counts = new Map();
+ let unknown = 0;
+ let unclassified = 0;
+ for (const o of Array.isArray(outcomes) ? outcomes : []) {
+ if (!o || o.executionOutcome !== 'failure') continue;
+ const category = o.failureCategory;
+ if (category === UNKNOWN_EXECUTION_FAILURE) { unknown += 1; continue; }
+ // Absent OR unrecognized (hand-edited, or a token from a newer version): both
+ // mean we hold no valid diagnosis for an execution that demonstrably failed.
+ if (!EXECUTION_FAILURE_CATEGORIES.includes(category)) { unclassified += 1; continue; }
+ counts.set(category, (counts.get(category) || 0) + 1);
+ }
+ const entries = [...counts.entries()]
+ // Commonest first; ties broken by taxonomy order so the output is stable rather
+ // than dependent on Map insertion (i.e. on record ordering).
+ .sort((a, b) => b[1] - a[1] || EXECUTION_FAILURE_CATEGORIES.indexOf(a[0]) - EXECUTION_FAILURE_CATEGORIES.indexOf(b[0]))
+ .map(([category, count]) => ({ category, count }));
+ const diagnosed = entries.reduce((n, e) => n + e.count, 0);
+ return { entries, unknown, unclassified, diagnosed, total: diagnosed + unknown + unclassified };
+}
+
+/**
+ * Render a tally as one prompt line: the commonest `limit` diagnoses, glossed,
+ * followed by whichever gaps are non-zero.
+ *
+ * Returns '' ONLY when no hand-off has failed, so a caller may safely read '' as
+ * "there is nothing to explain". It must never fall silent merely because the
+ * failures are undiagnosed: a report that says "0% executed" and then stays quiet
+ * about why is exactly the blindness this taxonomy exists to remove.
+ */
+export function formatExecutionFailures(outcomes = [], limit = 3) {
+ const { entries, unknown, unclassified, total } = summarizeExecutionFailures(outcomes);
+ if (total === 0) return '';
+ const listed = entries
+ .slice(0, limit)
+ .map(({ category, count }) => `${formatExecutionFailure(category)} (${count})`)
+ .join('; ');
+ // Name every gap: "2 of 3 failed with no recognized cause" is a real, actionable
+ // fact about LI's own blind spot, and the honest line when it's all we have.
+ const gaps = [
+ unknown ? `${unknown} of ${total} failed with no recognized cause` : '',
+ unclassified ? `${unclassified} of ${total} not yet classified` : ''
+ ];
+ return [listed, ...gaps].filter(Boolean).join(' — ');
+}
diff --git a/server/services/layeredIntelligenceExecutionFailures.test.js b/server/services/layeredIntelligenceExecutionFailures.test.js
new file mode 100644
index 0000000000..eeaffb5cc2
--- /dev/null
+++ b/server/services/layeredIntelligenceExecutionFailures.test.js
@@ -0,0 +1,162 @@
+import { describe, it, expect } from 'vitest';
+import {
+ EXECUTION_FAILURE_CATEGORIES,
+ EXECUTION_FAILURE_VALUES,
+ UNKNOWN_EXECUTION_FAILURE,
+ classifyExecutionFailure,
+ formatExecutionFailure,
+ formatExecutionFailures,
+ summarizeExecutionFailures
+} from './layeredIntelligenceExecutionFailures.js';
+
+// A minimal failed-execution outcome record.
+const failed = (failureCategory) => ({ executionOutcome: 'failure', failureCategory });
+
+describe('execution-failure taxonomy vocabulary', () => {
+ it('keeps the unknown sentinel OUT of the diagnosis vocabulary but inside the storable values', () => {
+ expect(EXECUTION_FAILURE_CATEGORIES).not.toContain(UNKNOWN_EXECUTION_FAILURE);
+ expect(EXECUTION_FAILURE_VALUES).toContain(UNKNOWN_EXECUTION_FAILURE);
+ expect(EXECUTION_FAILURE_VALUES).toEqual([...EXECUTION_FAILURE_CATEGORIES, UNKNOWN_EXECUTION_FAILURE]);
+ });
+
+ it('carries exactly the five #2764 §1 categories', () => {
+ expect(EXECUTION_FAILURE_CATEGORIES).toEqual(['planning', 'execution', 'testing', 'context', 'scope']);
+ });
+
+ it('has no duplicate tokens', () => {
+ expect(new Set(EXECUTION_FAILURE_VALUES).size).toBe(EXECUTION_FAILURE_VALUES.length);
+ });
+
+ it('glosses every storable token, and passes an unglossed token through', () => {
+ for (const token of EXECUTION_FAILURE_VALUES) {
+ expect(formatExecutionFailure(token)).toBeTruthy();
+ expect(typeof formatExecutionFailure(token)).toBe('string');
+ }
+ expect(formatExecutionFailure('some-future-token')).toBe('some-future-token');
+ });
+
+ it('renders a nullish (unclassified) input as empty, NOT as the unknown sentinel', () => {
+ expect(formatExecutionFailure(null)).toBe('');
+ expect(formatExecutionFailure(undefined)).toBe('');
+ expect(formatExecutionFailure('')).toBe('');
+ });
+});
+
+describe('classifyExecutionFailure', () => {
+ it('returns null when the execution did not fail', () => {
+ expect(classifyExecutionFailure({ success: true, errorCategory: 'test-failure' })).toBeNull();
+ expect(classifyExecutionFailure({ success: null, executionOutcome: 'success' })).toBeNull();
+ // Nothing at all → nothing to diagnose.
+ expect(classifyExecutionFailure({})).toBeNull();
+ });
+
+ it('maps raw error categories to the taxonomy', () => {
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'test-failure' })).toBe('testing');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'build-error' })).toBe('testing');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'lint-error' })).toBe('testing');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'git-conflict' })).toBe('execution');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'tool-error' })).toBe('execution');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'context-length' })).toBe('context');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'file-not-found' })).toBe('context');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'turn-limit' })).toBe('context');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'task-rejected' })).toBe('scope');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'content-filtered' })).toBe('scope');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'no-changes' })).toBe('planning');
+ });
+
+ it('normalizes separators and case in the raw category', () => {
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'Test_Failure' })).toBe('testing');
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'GIT CONFLICT' })).toBe('execution');
+ });
+
+ it('classifies a clean-exit validation miss (no error category) as testing', () => {
+ // The run exited without a recognized error but missed its declared criterion —
+ // a regression the error sweep produced no category for.
+ expect(classifyExecutionFailure({ success: false, errorCategory: null, validationPassed: false })).toBe('testing');
+ });
+
+ it('falls through to the unknown sentinel when a failure has no usable signal', () => {
+ expect(classifyExecutionFailure({ success: false, errorCategory: null, validationPassed: null })).toBe(UNKNOWN_EXECUTION_FAILURE);
+ // An environmental token that slipped past the upstream filter is not a
+ // capability signal — it reads as unknown, never a fabricated taxonomy token.
+ expect(classifyExecutionFailure({ success: false, errorCategory: 'rate-limit' })).toBe(UNKNOWN_EXECUTION_FAILURE);
+ });
+
+ it('re-diagnoses a persisted record from executionOutcome when no explicit success is given', () => {
+ expect(classifyExecutionFailure({ executionOutcome: 'failure', errorCategory: 'test-failure' })).toBe('testing');
+ });
+
+ it('is deterministic', () => {
+ const args = { success: false, errorCategory: 'git-error', validationPassed: false };
+ expect(classifyExecutionFailure(args)).toBe(classifyExecutionFailure(args));
+ });
+});
+
+describe('summarizeExecutionFailures', () => {
+ it('counts only failed-execution records, commonest first', () => {
+ const { entries, total, diagnosed } = summarizeExecutionFailures([
+ failed('testing'),
+ failed('testing'),
+ failed('execution'),
+ { executionOutcome: 'success', failureCategory: null }, // ignored
+ { executionOutcome: null, failureCategory: null } // never executed, ignored
+ ]);
+ expect(entries).toEqual([{ category: 'testing', count: 2 }, { category: 'execution', count: 1 }]);
+ expect(total).toBe(3);
+ expect(diagnosed).toBe(3);
+ });
+
+ it('breaks count ties by taxonomy order for stable output', () => {
+ const { entries } = summarizeExecutionFailures([failed('scope'), failed('planning')]);
+ // planning precedes scope in EXECUTION_FAILURE_CATEGORIES → planning first on a tie.
+ expect(entries.map(e => e.category)).toEqual(['planning', 'scope']);
+ });
+
+ it('separates the unknown sentinel from unclassified records', () => {
+ const { entries, unknown, unclassified, diagnosed, total } = summarizeExecutionFailures([
+ failed('execution'),
+ failed(UNKNOWN_EXECUTION_FAILURE),
+ failed(null), // never classified (pre-field / no signal path)
+ failed('bogus-future-token') // unrecognized → unclassified, not a finding
+ ]);
+ expect(entries).toEqual([{ category: 'execution', count: 1 }]);
+ expect(unknown).toBe(1);
+ expect(unclassified).toBe(2);
+ expect(diagnosed).toBe(1);
+ expect(total).toBe(4);
+ });
+
+ it('reports zero across the board for an empty / all-success history', () => {
+ expect(summarizeExecutionFailures([]).total).toBe(0);
+ expect(summarizeExecutionFailures([{ executionOutcome: 'success', failureCategory: null }]).total).toBe(0);
+ expect(summarizeExecutionFailures('not-an-array').total).toBe(0);
+ });
+});
+
+describe('formatExecutionFailures', () => {
+ it('returns empty ONLY when nothing has failed', () => {
+ expect(formatExecutionFailures([])).toBe('');
+ expect(formatExecutionFailures([{ executionOutcome: 'success' }])).toBe('');
+ });
+
+ it('lists the commonest diagnoses, glossed', () => {
+ const line = formatExecutionFailures([failed('testing'), failed('testing'), failed('execution')]);
+ expect(line).toContain('(2)');
+ expect(line).toContain('regression');
+ });
+
+ it('names every non-zero gap rather than falling silent', () => {
+ const line = formatExecutionFailures([failed(UNKNOWN_EXECUTION_FAILURE), failed(null)]);
+ expect(line).toContain('1 of 2 failed with no recognized cause');
+ expect(line).toContain('1 of 2 not yet classified');
+ });
+
+ it('respects the limit on listed diagnoses', () => {
+ const line = formatExecutionFailures(
+ [failed('planning'), failed('execution'), failed('testing'), failed('context')],
+ 2
+ );
+ // Four distinct single-count categories; only two are listed.
+ expect(line.split(';').length).toBe(2);
+ });
+});
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index 4f96943d16..88db22ecde 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -24,6 +24,12 @@ import { PATHS } from '../lib/fileUtils.js';
import { createCollectionStore } from '../lib/collectionStore.js';
import { normalizeSlug, deriveOutcome, PROPOSAL_OUTCOMES, PROPOSAL_EXECUTION_OUTCOMES, CLOSED_SUPPRESSION_MS } from './layeredIntelligence.js';
import { classifyRejection, REJECTION_REASON_VALUES } from './layeredIntelligenceRejections.js';
+import { classifyExecutionFailure, EXECUTION_FAILURE_VALUES } from './layeredIntelligenceExecutionFailures.js';
+
+// Longest raw failure-signal token stored on a record. The signal is one of
+// agentErrorAnalysis's controlled `category` tokens (e.g. `test-failure`), so this
+// only bounds a hand-edited/corrupt value — the real tokens are far shorter.
+const FAILURE_SIGNAL_MAX_LEN = 64;
// The report/retention window. Reuses the dedup suppression window so a proposal
// stays in the outcome report exactly as long as it still suppresses re-proposal —
@@ -80,7 +86,22 @@ export function sanitizeOutcomeRecord(raw) {
// to null (re-derivable on the next run) rather than a fake result. `executionAt`
// is kept only alongside a real executionOutcome.
executionOutcome: PROPOSAL_EXECUTION_OUTCOMES.includes(raw.executionOutcome) ? raw.executionOutcome : null,
- executionAt: PROPOSAL_EXECUTION_OUTCOMES.includes(raw.executionOutcome) && typeof raw.executionAt === 'string' ? raw.executionAt : null
+ executionAt: PROPOSAL_EXECUTION_OUTCOMES.includes(raw.executionOutcome) && typeof raw.executionAt === 'string' ? raw.executionAt : null,
+ // Execution-FAILURE taxonomy (#2764 §1) — the structured "why" for a failed
+ // hand-off, orthogonal to the binary executionOutcome above. Both fields are
+ // three-valued in the same spirit as rejectionReason, and only ever populated
+ // for a FAILED execution (a success/unresolved has nothing to diagnose, so a
+ // stray token there would inflate the failure tally):
+ // - `failureCategory` — an EXECUTION_FAILURE_VALUES token, or null. An
+ // unrecognized/future token coerces to null (re-derivable on the next
+ // execution write) rather than being laundered into a fake `unknown-failure`.
+ // - `failureSignal` — the raw agentErrorAnalysis `category` the classification
+ // was derived from (the root-cause signal #2764 §1 asks to keep), a short
+ // controlled token bounded defensively; null when none was captured.
+ failureCategory: raw.executionOutcome === 'failure' && EXECUTION_FAILURE_VALUES.includes(raw.failureCategory) ? raw.failureCategory : null,
+ failureSignal: raw.executionOutcome === 'failure' && typeof raw.failureSignal === 'string' && raw.failureSignal.trim()
+ ? raw.failureSignal.trim().slice(0, FAILURE_SIGNAL_MAX_LEN)
+ : null
};
}
@@ -145,7 +166,10 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe
// Not executed yet — set only if this proposal is later handed off and its agent
// run completes (recordProposalExecution, #2765).
executionOutcome: null,
- executionAt: null
+ executionAt: null,
+ // No execution has failed yet, so there is no failure to diagnose (#2764 §1).
+ failureCategory: null,
+ failureSignal: null
};
await ensureTypeIndex(store);
const ok = await store.saveOne(outcomeId(appId, normSlug), record).then(() => true, (err) => {
@@ -169,7 +193,7 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe
* nothing about the domain — same gate as #2618); this helper records whatever it is
* given.
*/
-export async function recordProposalExecution({ appId, slug, scope = null, success, now = Date.now() } = {}, store = outcomesStore()) {
+export async function recordProposalExecution({ appId, slug, scope = null, success, errorCategory = null, validationPassed = null, now = Date.now() } = {}, store = outcomesStore()) {
const normSlug = normalizeSlug(slug);
if (!appId || !normSlug || typeof success !== 'boolean') return false;
const id = outcomeId(appId, normSlug);
@@ -177,6 +201,14 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe
// per-domain aggregation. Normalized once and reused by both the missing-record
// fallback and the scope-preservation merge below.
const normScope = typeof scope === 'string' && scope.trim() ? scope.trim() : null;
+ // Diagnose WHY a failed hand-off failed (#2764 §1) from the failure signal the
+ // caller already computed — a success has nothing to diagnose, so both fields
+ // stay null on success. `failureSignal` keeps the raw category (root-cause
+ // signal) even when it doesn't map to a taxonomy token, so a later reconcile
+ // could re-classify without re-running the task. Classification is deterministic
+ // and pure — no provider round-trip (the "no cold-bootstrap LLM" policy).
+ const failureCategory = success ? null : classifyExecutionFailure({ success, errorCategory, validationPassed });
+ const failureSignal = success ? null : (typeof errorCategory === 'string' && errorCategory.trim() ? errorCategory.trim() : null);
await ensureTypeIndex(store);
// Fence the whole read-modify-write in the per-id write queue (#2765, codex P2). A bare
// loadOne→saveOne lets a concurrent reconcileOutcomes write on the same slug interleave
@@ -201,7 +233,11 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe
// the domain the completion hook passed (a missing-record fallback).
scope: (typeof base.scope === 'string' && base.scope.trim()) ? base.scope : normScope,
executionOutcome: success ? 'success' : 'failure',
- executionAt: new Date(now).toISOString()
+ executionAt: new Date(now).toISOString(),
+ // Set the failure diagnosis (#2764 §1) unconditionally so a success overwrites
+ // any stale failure fields from a prior failed run that later re-ran and passed.
+ failureCategory,
+ failureSignal
};
await store.saveOneNow(id, next);
return true;
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index 97d9597b4a..5986637235 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -104,6 +104,41 @@ describe('sanitizeOutcomeRecord', () => {
expect(r.executionAt).toBeNull();
});
});
+
+ describe('failureCategory + failureSignal (#2764 §1)', () => {
+ const sanitize = (over) => sanitizeOutcomeRecord({ appId: 'a', slug: 's', ...over });
+
+ it('keeps a recognized failure category + signal on a FAILED execution', () => {
+ const r = sanitize({ executionOutcome: 'failure', executionAt: 'x', failureCategory: 'testing', failureSignal: 'test-failure' });
+ expect(r.failureCategory).toBe('testing');
+ expect(r.failureSignal).toBe('test-failure');
+ });
+
+ it('keeps the unknown-failure sentinel', () => {
+ expect(sanitize({ executionOutcome: 'failure', executionAt: 'x', failureCategory: 'unknown-failure' }).failureCategory).toBe('unknown-failure');
+ });
+
+ it('coerces an unrecognized/future category to null (re-derivable), not the sentinel', () => {
+ expect(sanitize({ executionOutcome: 'failure', executionAt: 'x', failureCategory: 'bogus' }).failureCategory).toBeNull();
+ });
+
+ it('drops the diagnosis on a SUCCESS — a success has nothing to explain', () => {
+ const r = sanitize({ executionOutcome: 'success', executionAt: 'x', failureCategory: 'testing', failureSignal: 'test-failure' });
+ expect(r.failureCategory).toBeNull();
+ expect(r.failureSignal).toBeNull();
+ });
+
+ it('defaults both fields to null on a record that never executed', () => {
+ const r = sanitize({ outcome: 'merged' });
+ expect(r.failureCategory).toBeNull();
+ expect(r.failureSignal).toBeNull();
+ });
+
+ it('bounds a hand-edited over-long failure signal', () => {
+ const r = sanitize({ executionOutcome: 'failure', executionAt: 'x', failureSignal: 'z'.repeat(500) });
+ expect(r.failureSignal.length).toBe(64);
+ });
+ });
});
describe('recordFiledProposal + listOutcomes', () => {
@@ -471,6 +506,39 @@ describe('recordProposalExecution (#2765)', () => {
expect(row.executionOutcome).toBe('failure');
});
+ it('classifies + persists the failure taxonomy from the run signal (#2764 §1)', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'regressed', scope: 'loop-meta' }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'regressed', success: false, errorCategory: 'test-failure' }, store);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row).toMatchObject({ executionOutcome: 'failure', failureCategory: 'testing', failureSignal: 'test-failure' });
+ });
+
+ it('classifies a clean-exit validation miss as testing even with no error category (#2764 §1)', async () => {
+ await recordProposalExecution({ appId: 'app-1', slug: 'missed', scope: 'loop-meta', success: false, errorCategory: null, validationPassed: false }, store);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.failureCategory).toBe('testing');
+ expect(row.failureSignal).toBeNull(); // no raw category to keep
+ });
+
+ it('leaves the diagnosis null on a SUCCESS, and clears a prior failure on a passing re-run (#2764 §1)', async () => {
+ await recordProposalExecution({ appId: 'app-1', slug: 'retry', scope: 'loop-meta', success: false, errorCategory: 'git-conflict' }, store);
+ let [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.failureCategory).toBe('execution');
+ // A later passing re-run must overwrite the stale failure diagnosis.
+ await recordProposalExecution({ appId: 'app-1', slug: 'retry', scope: 'loop-meta', success: true }, store);
+ [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.executionOutcome).toBe('success');
+ expect(row.failureCategory).toBeNull();
+ expect(row.failureSignal).toBeNull();
+ });
+
+ it('stores an unmapped failure signal as unknown-failure but keeps the raw signal (#2764 §1)', async () => {
+ await recordProposalExecution({ appId: 'app-1', slug: 'mystery', scope: 'loop-meta', success: false, errorCategory: 'weird-new-category' }, store);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.failureCategory).toBe('unknown-failure');
+ expect(row.failureSignal).toBe('weird-new-category');
+ });
+
it('creates a minimal record (adopting the passed scope) when the filed record is missing', async () => {
// GC'd or a filing-write miss — the execution signal must not be silently lost.
const ok = await recordProposalExecution({ appId: 'app-2', slug: 'orphan', scope: 'portos-self', success: true }, store);
@@ -513,6 +581,23 @@ describe('recordProposalExecution (#2765)', () => {
expect(row.executionOutcome).toBe('success'); // …without dropping the execution signal
});
+ it('reconcile preserves the failure diagnosis when it later stamps the filing outcome (#2764 §1)', async () => {
+ // A failed hand-off later gets its issue closed-as-rejected. Reconcile applies the
+ // filing outcome via a fenced re-read that spreads the fresh record — the
+ // execution-failure fields must ride through untouched.
+ await recordFiledProposal({ appId: 'app-1', slug: 'diag', scope: 'loop-meta' }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'diag', success: false, errorCategory: 'git-conflict' }, store);
+ await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [{ slug: 'diag', state: 'closed', stateReason: 'not_planned', closedAt: new Date().toISOString() }]
+ }, store);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.outcome).toBe('rejected'); // reconcile applied the filing outcome
+ expect(row.executionOutcome).toBe('failure'); // …preserving the execution signal
+ expect(row.failureCategory).toBe('execution'); // …and the failure diagnosis
+ expect(row.failureSignal).toBe('git-conflict');
+ });
+
it('aggregates a domain’s success rate across multiple executions', async () => {
await recordFiledProposal({ appId: 'app-1', slug: 'a', scope: 'loop-meta' }, store);
await recordFiledProposal({ appId: 'app-1', slug: 'b', scope: 'loop-meta' }, store);
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index c4554fd6d9..2b0e66aaf0 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -298,11 +298,23 @@ export function recordFailureSignature(data, context) {
* the proposal's app, slug, and domain (scope). `success` is the validation-authoritative
* learning outcome, so it agrees with the byTaskType aggregate for the same run.
*/
-function deriveLiExecutionPayload(task, success) {
+function deriveLiExecutionPayload(task, success, { errorCategory = null, validationPassed = null } = {}) {
const li = task?.metadata?.taskLiProposal;
if (!li || typeof li !== 'object' || Array.isArray(li)) return null;
if (!li.appId || !li.slug) return null;
- return { appId: li.appId, slug: li.slug, scope: li.scope ?? null, success: !!success };
+ // On failure, carry the run's failure signal so the outcome store can classify
+ // the execution-failure taxonomy (#2764 §1). Harmless on success (the store
+ // ignores it and nulls both diagnosis fields). `errorCategory` is the raw
+ // agentErrorAnalysis category; `validationPassed` distinguishes a clean-exit
+ // criterion miss (→ testing) when no error pattern matched.
+ return {
+ appId: li.appId,
+ slug: li.slug,
+ scope: li.scope ?? null,
+ success: !!success,
+ errorCategory: success ? null : errorCategory,
+ validationPassed: success ? null : validationPassed
+ };
}
/**
@@ -351,7 +363,7 @@ export async function recordTaskCompletion(agent, task) {
// Attribute an LI hand-off's outcome to the proposal's DOMAIN (#2765). Only a
// non-environmental completion counts: a rate-limit/outage says nothing about the
// domain, exactly as it is barred from denting the byTaskType aggregate below.
- liExecPayload = isEnvironmentalFailure ? null : deriveLiExecutionPayload(task, outcomeSuccess);
+ liExecPayload = isEnvironmentalFailure ? null : deriveLiExecutionPayload(task, outcomeSuccess, { errorCategory, validationPassed: telemetry.validationPassed });
// Correlation-quality prediction snapshot (issue #2344) — captured HERE, before
// ANY of this run's aggregates (byModelTier, routingAccuracy, failureSignatures)