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: stop reading a whole TUI session as one line when classifying agent failures

[._.]/ Adam Eivy84667b1cee9e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..a53d497266
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,7 @@
+# Unreleased Changes
+
+## CoS agent failure reporting
+
+- Failed agent runs are classified far more accurately. A terminal-UI agent's transcript is a repainted *screen*, not a log — it can run to hundreds of kilobytes while containing barely any line breaks — so the analyzer's "look at the recent output" window was quietly reading the entire session. Any keyword anywhere in it, including commands the agent itself typed, decided the verdict: one run reaped for going idle was reported as "Context length exceeded", which blocked its task and auto-filed an investigation for a problem that never happened.
+- When the system already knows why a run ended — the idle watchdog fired, the runtime budget ran out, the provider CLI wasn't installed — that is now what gets reported. Only a genuine provider or system error in the transcript can override it.
+- Failure snippets shown on an agent's record are now short, readable excerpts centered on the actual error instead of raw terminal escape codes. One failed run had been writing an 816KB blob of control characters into its own record.
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index f51fffdb14..2d7070d80c 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -10,6 +10,7 @@ import { addTask, updateTask, getAllTasks } from './cos.js';
import { cosEvents } from './cosEvents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { redactOutput } from '../lib/commandSecurity.js';
+import { stripAnsi } from '../lib/ansiStrip.js';
import { isTruthyMeta } from './agentState.js';
// Max retries before blocking a task
@@ -53,12 +54,29 @@ export function redactFailureSnippet(text) {
return out.length > SNIPPET_MAX_CHARS ? `${out.slice(0, SNIPPET_MAX_CHARS)}…` : out;
}
+// Hard ceiling on the raw snippet captured off the analysis window. The
+// human-facing body re-truncates to SNIPPET_MAX_CHARS, but the analysis object
+// itself is PERSISTED verbatim into the agent's metadata.json — an unbounded
+// snippet wrote an 816KB blob into a single failed TUI agent's record (a 1.28MB
+// metadata.json) because a repaint-driven PTY transcript has almost no newlines,
+// so "the line containing the match" was the whole session. Keep enough context
+// to read the failure, never enough to bloat the record.
+export const SNIPPET_RAW_MAX_CHARS = 400;
+
// Extract the single output line containing `index` — the matched failure line
-// makes the most useful snippet without dragging in surrounding noise.
+// makes the most useful snippet without dragging in surrounding noise. Bounded
+// on BOTH sides of the match so a newline-free buffer (raw PTY output) yields a
+// readable excerpt instead of the entire stream.
function snippetAround(text, index) {
- const start = text.lastIndexOf('\n', index) + 1; // -1 → 0 (first line)
+ const lineStart = text.lastIndexOf('\n', index) + 1; // -1 → 0 (first line)
const nl = text.indexOf('\n', index);
- const end = nl === -1 ? text.length : nl;
+ const lineEnd = nl === -1 ? text.length : nl;
+ // Anchor the window on the match itself, not the line start: on a very long
+ // line the match can sit thousands of chars in, and a head-anchored slice
+ // would cut away the very text that classified the failure.
+ const half = Math.floor(SNIPPET_RAW_MAX_CHARS / 2);
+ const start = Math.max(lineStart, index - half);
+ const end = Math.min(lineEnd, start + SNIPPET_RAW_MAX_CHARS);
return text.slice(start, end).trim();
}
@@ -494,12 +512,33 @@ export const ERROR_PATTERNS = [
}
];
+// Analysis-window bounds. The line cap is the primary "only look at the tail"
+// rule; the char cap is the backstop that makes it hold for PTY transcripts.
+export const FAILURE_WINDOW_MAX_LINES = 200;
+export const FAILURE_WINDOW_MAX_CHARS = 16000;
+
+/**
+ * Reduce raw agent output to the tail worth classifying.
+ *
+ * A TUI transcript is a *screen*, not a log: it arrives as ANSI cursor-addressing
+ * and repaints, so a raw 838KB PTY spool can collapse to ~14 `\n`-delimited
+ * "lines". That defeated a line-only window entirely — the "last 200 lines" was
+ * the WHOLE 17-minute session, so a keyword anywhere in it (in the pasted prompt,
+ * or in a `grep -rn "maxTokens\|max_tokens"` the agent itself ran) classified the
+ * failure. That is exactly how an idle-reaper kill got labelled `context-length`.
+ *
+ * So: strip escape sequences, treat CR as a line break (repaints overwrite a
+ * line rather than starting one), drop blanks, then bound by lines AND by
+ * characters. Pure.
+ */
function getFailureAnalysisWindow(output) {
- return output
+ const windowed = stripAnsi(output)
+ .replace(/\r\n?/g, '\n')
.split('\n')
.filter(l => l.trim())
- .slice(-200)
+ .slice(-FAILURE_WINDOW_MAX_LINES)
.join('\n');
+ return windowed.length > FAILURE_WINDOW_MAX_CHARS ? windowed.slice(-FAILURE_WINDOW_MAX_CHARS) : windowed;
}
/**
@@ -522,12 +561,106 @@ function resolvePatternOrigin(errorDef, analysisOutput) {
return errorDef.origin;
}
+/**
+ * Runner-resolved completion reasons → the failure they actually describe.
+ *
+ * When the spawner's own finalize path already KNOWS why a run ended (the idle
+ * reaper fired, max runtime elapsed, the shell session never came up), that is a
+ * structural signal about the process — strictly better evidence than a regex
+ * sweep over the transcript. Keyed by the `reason` each `finish()` call passes;
+ * see `server/services/agentTuiSpawning.js`. Categories are deliberately reused
+ * from ERROR_PATTERNS so downstream taxonomies (task-learning metrics,
+ * layeredIntelligenceExecutionFailures) keep classifying them without a new token.
+ */
+export const COMPLETION_REASON_ANALYSES = {
+ 'idle-no-changes': {
+ category: 'no-changes',
+ actionable: false,
+ message: 'Agent idled out with no file changes',
+ suggestedFix: 'The agent stopped producing output before writing any files. Check the raw transcript for where it stalled — a provider retry loop or a long-running command can outlast the idle reaper.'
+ },
+ 'idle-no-activity': {
+ category: 'startup-failure',
+ actionable: false,
+ message: 'Agent idled out before any work started',
+ suggestedFix: 'The prompt likely never submitted — no working indicator ever appeared. Check the TUI paste/submit path and provider availability.'
+ },
+ 'review-loop-idle-timeout': {
+ category: 'timeout',
+ actionable: false,
+ message: 'Agent idled out inside the multi-reviewer loop',
+ suggestedFix: 'A reviewer may have hung or the wait exceeded budget. Check the PR review/merge state and finish it manually.'
+ },
+ 'merge-queue-idle-timeout': {
+ category: 'timeout',
+ actionable: false,
+ message: 'Agent idled out waiting on the merge queue',
+ suggestedFix: 'The merge queue wait exceeded budget. Check the PR merge state and finish it manually.'
+ },
+ 'max-runtime-timeout': {
+ category: 'timeout',
+ actionable: false,
+ message: 'Agent exceeded its maximum runtime',
+ suggestedFix: 'Task took longer than the configured max runtime. Break it into smaller subtasks or raise the runtime budget.'
+ },
+ 'command-not-found': {
+ category: 'spawn-error',
+ actionable: true,
+ escalation: 'Confirm the required CLI/tool is installed and on PATH for the agent user (or fix the command), then approve the retry.',
+ message: 'TUI command not found',
+ suggestedFix: 'The configured provider CLI is not installed or not on PATH. Install it or correct the provider command.'
+ },
+ 'spawn-error': {
+ category: 'spawn-error',
+ actionable: true,
+ escalation: 'Confirm the required CLI/tool is installed and on PATH for the agent user (or fix the command), then approve the retry.',
+ message: 'Failed to start the agent session',
+ suggestedFix: 'The shell/PTY session could not be created. Check system resources and the provider command configuration.'
+ }
+};
+
+/**
+ * Build the analysis object for a runner-resolved completion reason. The
+ * snippet comes from the runner's own error prose — clean, already-scoped text —
+ * never from the escape-laden transcript.
+ */
+function structuralReasonAnalysis(def, completionReason, completionError) {
+ return {
+ category: def.category,
+ actionable: def.actionable,
+ // Structural runner signal (#2642): the spawner observed the process end
+ // this way, so it stays eligible for environmental diversion.
+ origin: 'runner',
+ snippet: typeof completionError === 'string' ? completionError.trim().slice(0, SNIPPET_RAW_MAX_CHARS) : '',
+ escalation: def.escalation || null,
+ completionReason,
+ message: def.message,
+ suggestedFix: def.suggestedFix
+ };
+}
+
/**
* Analyze agent failure output and categorize the error.
+ *
+ * `options.completionReason` / `options.completionError` carry the spawner's own
+ * verdict when it has one (see COMPLETION_REASON_ANALYSES). A recognized reason
+ * becomes the default classification, and only a STRUCTURED provider/runner
+ * signal in the transcript (an `API Error: NNN` line, a Node error code) may
+ * override it — a loose output-scan keyword match may not. Without that gate an
+ * idle-reaper kill was labelled `context-length` (actionable → task blocked +
+ * investigation filed) purely because the agent had run a grep for `max_tokens`
+ * fifteen minutes earlier.
*/
-export function analyzeAgentFailure(output, task, model) {
- // Agent produced no meaningful output — likely failed to start
- if (!output || output.trim().length < 50) {
+export function analyzeAgentFailure(output, task, model, options = {}) {
+ const completionReason = options?.completionReason || null;
+ const structuralDef = completionReason ? COMPLETION_REASON_ANALYSES[completionReason] : null;
+ const analysisOutput = getFailureAnalysisWindow(output || '');
+
+ // Agent produced no meaningful output — likely failed to start. Measured on
+ // the CLEANED window: a transcript that is nothing but cursor repaints carries
+ // no more signal than an empty one.
+ if (analysisOutput.trim().length < 50) {
+ if (structuralDef) return structuralReasonAnalysis(structuralDef, completionReason, options?.completionError);
return {
category: 'startup-failure',
actionable: false,
@@ -536,41 +669,47 @@ export function analyzeAgentFailure(output, task, model) {
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(),
+ snippet: analysisOutput.trim(),
escalation: null
};
}
- const analysisOutput = getFailureAnalysisWindow(output);
-
for (const errorDef of ERROR_PATTERNS) {
const match = analysisOutput.match(errorDef.pattern);
if (match) {
+ // Provenance (#2642): 'provider'/'runner' only when a structured marker
+ // is present in the failure window; a loose keyword match stays 'output-scan'.
+ const origin = resolvePatternOrigin(errorDef, analysisOutput);
+ // Keep scanning (not `break`) so a structured match later in the list can
+ // still beat the runner's verdict — only the loose match is discarded.
+ if (structuralDef && origin === 'output-scan') continue;
const extracted = errorDef.extract(match, analysisOutput, 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),
+ origin,
// 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).
escalation: errorDef.escalation || null,
+ ...(completionReason ? { completionReason } : {}),
...extracted
};
}
}
- // No pattern matched — extract meaningful context from the output
- const lines = output.split('\n').filter(l => l.trim());
- const lastLines = lines.slice(-20);
+ if (structuralDef) return structuralReasonAnalysis(structuralDef, completionReason, options?.completionError);
+
+ // No pattern matched — extract meaningful context from the cleaned window
+ // (NOT the raw output: on a PTY transcript the raw tail is escape codes).
+ const lastLines = analysisOutput.split('\n').slice(-20);
const errorKeywords = /\b(error|fail|exception|fatal|panic|abort|crash|denied|refused|invalid|cannot|could not|unable to)\b/i;
const errorLines = lastLines.filter(l => errorKeywords.test(l)).slice(0, 5);
- const contextLines = errorLines.length > 0 ? errorLines : lastLines.slice(-5);
- const summary = contextLines[0]?.trim().substring(0, 120) || 'Agent failed with unrecognized error';
+ const contextLines = (errorLines.length > 0 ? errorLines : lastLines.slice(-5))
+ .map(l => l.trim().slice(0, SNIPPET_RAW_MAX_CHARS));
+ const summary = contextLines[0]?.substring(0, 120) || 'Agent failed with unrecognized error';
return {
category: 'unknown',
@@ -579,9 +718,10 @@ export function analyzeAgentFailure(output, task, model) {
// 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(' '),
+ details: contextLines.join('\n'),
+ snippet: contextLines.join(' ').slice(0, SNIPPET_RAW_MAX_CHARS),
escalation: null,
+ ...(completionReason ? { completionReason } : {}),
suggestedFix: 'Error did not match known patterns. Review the details or agent output logs.'
};
}
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 31d43c40a6..f183c5b3f3 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -7,6 +7,9 @@ vi.mock('./cos.js', () => ({ addTask: vi.fn(), updateTask: vi.fn(), getAllTasks:
import {
analyzeAgentFailure,
+ COMPLETION_REASON_ANALYSES,
+ ERROR_PATTERNS,
+ SNIPPET_RAW_MAX_CHARS,
resolveFailedTaskDecision,
resolveTypeFailureSignal,
maybeCreateInvestigationTask,
@@ -634,6 +637,116 @@ describe('analyzeAgentFailure — snippet & escalation enrichment', () => {
});
});
+// A TUI transcript is a SCREEN, not a log: ANSI cursor-addressing repaints mean a
+// multi-hundred-KB PTY spool can carry almost no newlines. Regression cover for the
+// incident where that collapsed the "last 200 lines" window onto a whole 17-minute
+// session — a `grep max_tokens` the agent itself ran classified an idle-reaper kill
+// as `context-length` (actionable → task blocked + investigation filed), and the
+// "matched line" snippet persisted 816KB of escape codes into metadata.json.
+describe('analyzeAgentFailure — PTY transcript windowing', () => {
+ // Cursor-addressed repaint: no newline anywhere, escapes between every token.
+ const repaint = (text) => `\x1B[H\x1B[2J\x1B[38;2;215;119;87m${text}\x1B[39m\x1B[24;1H`;
+
+ it('bounds the analysis window by characters so a newline-free transcript cannot match its own head', () => {
+ const stale = repaint('Bash(grep -rn "budget\\|maxTokens\\|max_tokens\\|cost" server/services/)');
+ const filler = repaint('Synthesizing… ').repeat(3000); // ≫ FAILURE_WINDOW_MAX_CHARS of escapes+text
+ const analysis = analyzeAgentFailure(stale + filler, { id: 't' }, 'x');
+ expect(analysis.category).not.toBe('context-length');
+ });
+
+ it('caps the captured snippet instead of persisting the whole newline-free buffer', () => {
+ // Match sits deep inside a single newline-free line — the snippet must be a
+ // bounded window around it, not the line (i.e. the whole transcript).
+ const analysis = analyzeAgentFailure(
+ repaint(`${'noise '.repeat(1000)}API Error: 401 Unauthorized${' trailing'.repeat(1000)}`),
+ { id: 't' }, 'x'
+ );
+ expect(analysis.category).toBe('auth-error');
+ expect(analysis.snippet.length).toBeLessThanOrEqual(SNIPPET_RAW_MAX_CHARS);
+ expect(analysis.snippet).toContain('API Error: 401');
+ });
+
+ it('strips escape sequences out of the snippet', () => {
+ const analysis = analyzeAgentFailure(withLead(repaint('API Error: 401 Unauthorized')), { id: 't' }, 'x');
+ expect(analysis.snippet).not.toMatch(/\x1B/);
+ });
+
+ it('treats an all-escape transcript as a startup failure rather than scanning garbage', () => {
+ const analysis = analyzeAgentFailure('\x1B[H\x1B[2J\x1B[?25l\x1B[24;1H'.repeat(200), { id: 't' }, 'x');
+ expect(analysis.category).toBe('startup-failure');
+ expect(analysis.origin).toBe('runner');
+ });
+});
+
+describe('analyzeAgentFailure — runner completion reason (COMPLETION_REASON_ANALYSES)', () => {
+ // The transcript the real incident produced: a keyword the AGENT typed, with the
+ // run actually ended by the idle reaper.
+ const noisyTranscript = withLead('Bash(grep -rn "maxTokens\\|max_tokens\\|cost" server/services/)');
+
+ it('prefers the runner verdict over a loose output-scan match', () => {
+ const analysis = analyzeAgentFailure(noisyTranscript, { id: 't' }, 'x', {
+ completionReason: 'idle-no-changes',
+ completionError: 'TUI agent idled out with zero uncommitted file changes',
+ });
+ expect(analysis.category).toBe('no-changes');
+ expect(analysis.actionable).toBe(false);
+ expect(analysis.origin).toBe('runner');
+ expect(analysis.completionReason).toBe('idle-no-changes');
+ // The runner's own prose is the snippet — never the escape-laden transcript.
+ expect(analysis.snippet).toContain('idled out');
+ });
+
+ it('still yields to a STRUCTURED provider signal in the transcript', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 429 Too Many Requests — backing off'), { id: 't' }, 'x', {
+ completionReason: 'idle-no-changes',
+ });
+ expect(analysis.category).toBe('rate-limit');
+ expect(analysis.origin).toBe('provider');
+ });
+
+ it('keeps scanning past a loose match so a later structured one still wins', () => {
+ // `context-length` (output-scan) matches earlier in the text than the
+ // structured 401; discarding the loose match must not abort the sweep.
+ const output = [
+ 'Initializing agent session and preparing the working directory.',
+ 'Checked the max_tokens budget helper in server/lib/',
+ 'API Error: 401 Unauthorized',
+ ].join('\n');
+ const analysis = analyzeAgentFailure(output, { id: 't' }, 'x', { completionReason: 'idle-no-changes' });
+ expect(analysis.category).toBe('auth-error');
+ expect(analysis.origin).toBe('provider');
+ });
+
+ it('applies the runner verdict when nothing in the transcript matches at all', () => {
+ const analysis = analyzeAgentFailure(withLead('Reviewed the reference commits and recorded proposals.'), { id: 't' }, 'x', {
+ completionReason: 'max-runtime-timeout',
+ completionError: 'TUI agent exceeded max runtime',
+ });
+ expect(analysis.category).toBe('timeout');
+ expect(analysis.completionReason).toBe('max-runtime-timeout');
+ });
+
+ it('applies the runner verdict when the transcript is empty', () => {
+ const analysis = analyzeAgentFailure('', { id: 't' }, 'x', { completionReason: 'idle-no-activity' });
+ expect(analysis.category).toBe('startup-failure');
+ expect(analysis.completionReason).toBe('idle-no-activity');
+ });
+
+ it('ignores an unrecognized reason and classifies from the output as before', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 429 Too Many Requests'), { id: 't' }, 'x', {
+ completionReason: 'agent-signaled-done',
+ });
+ expect(analysis.category).toBe('rate-limit');
+ });
+
+ it('maps every reason to a category ERROR_PATTERNS already produces (no orphan taxonomy tokens)', () => {
+ const known = new Set([...ERROR_PATTERNS.map(p => p.category), 'startup-failure']);
+ for (const [reason, def] of Object.entries(COMPLETION_REASON_ANALYSES)) {
+ expect(known.has(def.category), `${reason} → ${def.category}`).toBe(true);
+ }
+ });
+});
+
describe('createInvestigationTask body', () => {
beforeEach(() => {
addTask.mockReset();
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 916e313a17..49bff3ab2d 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -437,10 +437,11 @@ export async function spawnTuiAgent({
// record for long runs. The append-only stream is the authoritative copy.
//
// For failure analysis: resolveErrorAnalysis reads only the tail of the raw
- // PTY spool (the analyzer's window is the last ~200 lines) and falls back to
- // the capped output buffer if the spool is missing/unreadable. Successful
- // runs skip the read entirely. raw.txt stays in agentDir alongside
- // output.txt as the persistent record of the agent's full PTY transcript.
+ // PTY spool (the analyzer strips ANSI and windows it to the last ~200 lines /
+ // 16K chars) and falls back to the capped output buffer if the spool is
+ // missing/unreadable. Successful runs skip the read entirely. raw.txt stays
+ // in agentDir alongside output.txt as the persistent record of the agent's
+ // full PTY transcript.
const errorAnalysis = await resolveErrorAnalysis({
finalSuccess,
rawFile,
@@ -448,6 +449,10 @@ export async function spawnTuiAgent({
task,
model,
immediateFallbackAnalysis,
+ // The finalize path's own verdict outranks a keyword sweep of the
+ // transcript when the analyzer recognizes it (COMPLETION_REASON_ANALYSES).
+ completionReason: reason,
+ completionError: finalError,
});
// try/finally so a throw from finalizeAgent (e.g. processAgentCompletion
diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.js
index 06aa99a881..c64bf21618 100644
--- a/server/services/agentTuiSpawning/finalizeHelpers.js
+++ b/server/services/agentTuiSpawning/finalizeHelpers.js
@@ -13,11 +13,13 @@ import { open, stat as fsStat, writeFile } from 'fs/promises';
import * as git from '../git.js';
import { analyzeAgentFailure } from '../agentErrorAnalysis.js';
-// Tail-read window for raw.txt at failure analysis. analyzeAgentFailure only
-// inspects the last ~200 lines, so reading the whole file (which has no upper
-// bound for long-running agents) would reintroduce the OOM risk the disk
-// spool was meant to avoid. 1MB easily contains the last 200 lines of any
-// realistic PTY stream while keeping peak finalize memory bounded.
+// Tail-read window for raw.txt at failure analysis. analyzeAgentFailure narrows
+// further (ANSI-stripped, last ~200 lines AND ≤16K chars), so reading the whole
+// file (which has no upper bound for long-running agents) would reintroduce the
+// OOM risk the disk spool was meant to avoid. 1MB comfortably covers the
+// analyzer's window on any realistic PTY stream — including a repaint-heavy TUI
+// transcript, where escape sequences dominate the byte count — while keeping
+// peak finalize memory bounded.
export const RAW_TAIL_ANALYSIS_BYTES = 1024 * 1024;
/**
@@ -103,10 +105,17 @@ export async function captureWorktreeDiff(workspacePath, agentDir) {
* notices). An immediate-fallback signal, if one was detected mid-stream,
* short-circuits the analysis entirely.
*
+ * `completionReason` / `completionError` carry the finalize path's OWN verdict
+ * (idle reaper, max runtime, spawn failure). The analyzer prefers that structural
+ * signal over a loose keyword match in the transcript — a repaint-driven PTY
+ * transcript is a whole session's worth of text, and any keyword in it (including
+ * ones the agent itself typed) would otherwise classify the failure.
+ *
* @returns {Promise<object|null>} The error-analysis object, or null on success.
*/
-export async function resolveErrorAnalysis({ finalSuccess, rawFile, fallbackText, task, model, immediateFallbackAnalysis }) {
+export async function resolveErrorAnalysis({ finalSuccess, rawFile, fallbackText, task, model, immediateFallbackAnalysis, completionReason, completionError }) {
if (finalSuccess) return null;
const rawAnalysisText = await readFileTail(rawFile, RAW_TAIL_ANALYSIS_BYTES);
- return immediateFallbackAnalysis || analyzeAgentFailure(rawAnalysisText ?? fallbackText, task, model);
+ return immediateFallbackAnalysis
+ || analyzeAgentFailure(rawAnalysisText ?? fallbackText, task, model, { completionReason, completionError });
}
diff --git a/server/services/agentTuiSpawning/finalizeHelpers.test.js b/server/services/agentTuiSpawning/finalizeHelpers.test.js
index 458a16cd0f..2eed19e800 100644
--- a/server/services/agentTuiSpawning/finalizeHelpers.test.js
+++ b/server/services/agentTuiSpawning/finalizeHelpers.test.js
@@ -136,7 +136,9 @@ describe('finalizeHelpers', () => {
const result = await resolveErrorAnalysis({
finalSuccess: false, rawFile: p, fallbackText: 'buf', task, model: 'm',
});
- expect(analyzeAgentFailure).toHaveBeenCalledWith('PTY TAIL OUTPUT', task, 'm');
+ expect(analyzeAgentFailure).toHaveBeenCalledWith('PTY TAIL OUTPUT', task, 'm', {
+ completionReason: undefined, completionError: undefined,
+ });
expect(result).toEqual({ classification: 'x' });
});
@@ -147,8 +149,26 @@ describe('finalizeHelpers', () => {
task: {}, model: 'm',
});
// Missing file → readFileTail null → `?? fallbackText` supplies the buffer.
- expect(analyzeAgentFailure).toHaveBeenCalledWith('BUFFER FALLBACK', {}, 'm');
+ expect(analyzeAgentFailure).toHaveBeenCalledWith('BUFFER FALLBACK', {}, 'm', {
+ completionReason: undefined, completionError: undefined,
+ });
expect(result).toEqual({ classification: 'fb' });
});
+
+ it('forwards the finalize path\'s own completion verdict to the analyzer', async () => {
+ // The idle reaper / max-runtime timer already knows WHY the run ended;
+ // that structural signal must reach analyzeAgentFailure so a stray keyword
+ // in the transcript can't outrank it.
+ const p = join(dir, 'raw.txt');
+ await writeFile(p, 'PTY TAIL OUTPUT');
+ vi.mocked(analyzeAgentFailure).mockReturnValue({ classification: 'reaped' });
+ await resolveErrorAnalysis({
+ finalSuccess: false, rawFile: p, fallbackText: 'buf', task: { id: 't' }, model: 'm',
+ completionReason: 'idle-no-changes', completionError: 'idled out with zero changes',
+ });
+ expect(analyzeAgentFailure).toHaveBeenCalledWith('PTY TAIL OUTPUT', { id: 't' }, 'm', {
+ completionReason: 'idle-no-changes', completionError: 'idled out with zero changes',
+ });
+ });
});
});