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

test: cover real agent error-analysis logic instead of inline copies (#1846)

[._.]/ Adam Eivy9cabb2b91650
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 84aaab680a..a0a2edd229 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -45,3 +45,4 @@
- **Decomposed `server/lib/editorial/checkRegistry.js` (7,474-line god file)** — the single module that held ~2,400 lines of shared infra plus a 68-entry `EDITORIAL_CHECKS` array (each embedding a full `run(ctx)` closure) is now split: shared infra lives in `checkInfra.js`, the 68 checks are grouped by category into `checks/*.js` (`naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`), and `checkRegistry.js` (~480 lines) stays the public entry point — assembling `EDITORIAL_CHECKS` from the per-category arrays and keeping the registry's lookup/state helpers. The check files import shared infra from `checkInfra.js` (not back through the registry) so the `EDITORIAL_CHECKS` spread can't hit a TDZ on the checks' eagerly-evaluated `configSchema`s. The editorial barrel's public API is byte-for-byte identical (173 exports, verified) and all editorial + runner tests pass unchanged. (#1829)
- **Dropped the `sax` dependency from the Apple Health XML importer** — the 500MB-export streaming path now uses a self-contained ~190-line `Record` parser (`server/services/appleHealthXmlParser.js`) that splits the byte stream on `<Record>` tag boundaries and parses attributes with a quote-aware scan, preserving the prior backpressure (caller pauses the source stream) and error-skip (malformed records dropped, not fatal) behavior. Per the PortOS "write small helpers yourself" policy; covered by new unit + chunk-boundary tests. Partial-ships the `sax` half of #1824; the client `three-fenestra` shader replacement is tracked separately. (#1824)
- **[issue-1837] On-disk JSON writes are now crash-safe across ~50 service/route files** — ~73 persistence sites used a raw `writeFile(path, JSON.stringify(data, null, 2))`, which truncates the JSON file if the process crashes mid-write (leaving an unparseable half-record on disk). Each was swapped to the canonical `atomicWrite` helper (`server/lib/fileUtils.js`), which writes to a temp file and atomically renames it over the target so readers never see a partial write. Covers brain storage, run/agent metadata, decision log, meatspace (calendar/alcohol/nicotine/health/post), mortal-loom store, identity goals, image/video sidecars, GitHub/Google/Obsidian configs, taste/usage/genome/epigenetic stores, and the scaffolding routes. Sites that intentionally append a trailing newline keep their exact byte output (passed as a pre-stringified string), and `videoGen/local.js`'s `{ flag: 'wx' }` exclusive-create write is left as-is (atomicWrite can't replicate exclusive-create). (#1837)
+- **[issue-1846] Replaced vacuous inline-copy tests with coverage of real production logic** — `subAgentSpawner.test.js` had four `describe` blocks that re-implemented production logic inline and tested the copies, so the real code could regress while the suite stayed green: an inline `ERROR_PATTERNS`/`categorizeError`, an inline `resolveFailedTaskStatus` (which omitted the `MAX_TOTAL_SPAWNS` short-circuit and `compaction` metadata that the real `resolveFailedTaskUpdate` has), and stub `exitCodeMessages`/`buildSpawnArgs` literals exported from no production module. The error-classification and retry-decision blocks now live in `agentErrorAnalysis.test.js` against the real exported `ERROR_PATTERNS` (via `analyzeAgentFailure`) and a new pure `resolveFailedTaskDecision` helper extracted from `resolveFailedTaskUpdate` (the async wrapper delegates to it and just stamps timestamps + creates the investigation task — behavior-preserving); the exit-code block is replaced by a new `agentRunTracking.test.js` covering the real `extractErrorFromOutput` mapping; and the redundant spawn-args stub is dropped since `agentCliSpawning.test.js` already covers the real `buildCliSpawnConfig`. The genuine imported-helper tests (`isTruthyMeta`/`isFalsyMeta`/`applyAppWorktreeDefault`) are kept. (#1846)
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 6bc8b660f0..9f52543efe 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -515,75 +515,123 @@ export async function maybeCreateInvestigationTask(agentId, task, analysis) {
}
/**
- * Handle task status update after agent failure.
- * Tracks retry count and blocks the task after MAX_TASK_RETRIES,
- * creating an investigation task instead of retrying endlessly.
+ * Pure decision logic for {@link resolveFailedTaskUpdate} — no I/O, no clock.
*
- * Returns { status, metadata } to apply to the task.
+ * Decides whether a failed task should be blocked or retried, the metadata
+ * fields to merge over `task.metadata` (timestamps excluded — they belong to
+ * the async wrapper), the analysis to hand to an investigation task, and
+ * whether such a task will actually be created. Extracted so the branching can
+ * be unit-tested directly (see `agentErrorAnalysis.test.js`) instead of through
+ * a drift-prone inline copy.
+ *
+ * @returns {{
+ * status: 'blocked'|'pending',
+ * shouldCreateInvestigation: boolean,
+ * investigationAnalysis: object|null,
+ * metadataUpdates: object,
+ * failureCount?: number,
+ * lastErrorCategory?: string
+ * }}
*/
-export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {
- // Actionable errors get blocked immediately (investigation task created unless API access is denied)
+export function resolveFailedTaskDecision(task, errorAnalysis) {
+ // Actionable errors get blocked immediately. An investigation task follows
+ // unless the failure is an API-access error (auth/forbidden/usage-limit),
+ // where a fresh agent would hit the same wall.
if (errorAnalysis?.actionable) {
- emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {
- taskId: task.id, category: errorAnalysis.category
- });
- await maybeCreateInvestigationTask(agentId, task, errorAnalysis);
return {
status: 'blocked',
- metadata: {
- ...task.metadata,
+ shouldCreateInvestigation: !API_ACCESS_ERROR_CATEGORIES.has(errorAnalysis.category),
+ investigationAnalysis: errorAnalysis,
+ metadataUpdates: {
blockedReason: errorAnalysis.message,
- blockedCategory: errorAnalysis.category,
- blockedAt: new Date().toISOString()
+ blockedCategory: errorAnalysis.category
}
};
}
- // Non-actionable errors: track retry count and block after max retries
+ // Non-actionable errors: track retry count and block once the task has either
+ // failed too many times in a row or spawned too many agents in total.
const failureCount = (Number(task.metadata?.failureCount) || 0) + 1;
const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
const lastErrorCategory = errorAnalysis?.category || 'unknown';
if (totalSpawns >= MAX_TOTAL_SPAWNS || failureCount >= MAX_TASK_RETRIES) {
- emitLog('warn', `🚫 Task ${task.id} blocked after ${failureCount} failures (${lastErrorCategory})`, {
- taskId: task.id, failureCount, category: lastErrorCategory
- });
const blockedAnalysis = {
...(errorAnalysis || {}),
message: `Task failed ${failureCount} times: ${errorAnalysis?.message || 'unknown error'}`,
suggestedFix: `Task has failed ${failureCount} consecutive times with ${lastErrorCategory} errors. ${errorAnalysis?.suggestedFix || 'Investigate agent output logs.'}`,
category: lastErrorCategory
};
- await maybeCreateInvestigationTask(agentId, task, blockedAnalysis);
return {
status: 'blocked',
- metadata: {
- ...task.metadata,
+ shouldCreateInvestigation: !API_ACCESS_ERROR_CATEGORIES.has(lastErrorCategory),
+ investigationAnalysis: blockedAnalysis,
+ failureCount,
+ lastErrorCategory,
+ metadataUpdates: {
failureCount,
- lastFailureAt: new Date().toISOString(),
lastErrorCategory,
blockedReason: `Max retries exceeded (${failureCount}/${MAX_TASK_RETRIES}): ${lastErrorCategory}`,
- blockedCategory: lastErrorCategory,
- blockedAt: new Date().toISOString()
+ blockedCategory: lastErrorCategory
}
};
}
- emitLog('info', `🔄 Task ${task.id} retry ${failureCount}/${MAX_TASK_RETRIES} (${lastErrorCategory})`, {
- taskId: task.id, failureCount, maxRetries: MAX_TASK_RETRIES, category: lastErrorCategory
- });
-
- // Propagate compaction hints to task metadata for retry prompt injection
+ // Retry: propagate compaction hints for retry prompt injection.
const compaction = errorAnalysis?.compaction || null;
-
return {
status: 'pending',
- metadata: {
- ...task.metadata,
+ shouldCreateInvestigation: false,
+ investigationAnalysis: null,
+ failureCount,
+ lastErrorCategory,
+ metadataUpdates: {
failureCount,
- lastFailureAt: new Date().toISOString(),
lastErrorCategory,
...(compaction && { compaction })
}
};
}
+
+/**
+ * Handle task status update after agent failure.
+ * Tracks retry count and blocks the task after MAX_TASK_RETRIES,
+ * creating an investigation task instead of retrying endlessly.
+ *
+ * Returns { status, metadata } to apply to the task.
+ */
+export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {
+ const decision = resolveFailedTaskDecision(task, errorAnalysis);
+ const now = new Date().toISOString();
+
+ // Actionable errors get blocked immediately (investigation task created unless API access is denied)
+ if (errorAnalysis?.actionable) {
+ emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {
+ taskId: task.id, category: errorAnalysis.category
+ });
+ await maybeCreateInvestigationTask(agentId, task, decision.investigationAnalysis);
+ return {
+ status: decision.status,
+ metadata: { ...task.metadata, ...decision.metadataUpdates, blockedAt: now }
+ };
+ }
+
+ if (decision.status === 'blocked') {
+ emitLog('warn', `🚫 Task ${task.id} blocked after ${decision.failureCount} failures (${decision.lastErrorCategory})`, {
+ taskId: task.id, failureCount: decision.failureCount, category: decision.lastErrorCategory
+ });
+ await maybeCreateInvestigationTask(agentId, task, decision.investigationAnalysis);
+ return {
+ status: 'blocked',
+ metadata: { ...task.metadata, ...decision.metadataUpdates, lastFailureAt: now, blockedAt: now }
+ };
+ }
+
+ emitLog('info', `🔄 Task ${task.id} retry ${decision.failureCount}/${MAX_TASK_RETRIES} (${decision.lastErrorCategory})`, {
+ taskId: task.id, failureCount: decision.failureCount, maxRetries: MAX_TASK_RETRIES, category: decision.lastErrorCategory
+ });
+ return {
+ status: 'pending',
+ metadata: { ...task.metadata, ...decision.metadataUpdates, lastFailureAt: now }
+ };
+}
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 83d2f56f3f..3a3ef6989e 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -1,5 +1,16 @@
import { describe, expect, it } from 'vitest';
-import { analyzeAgentFailure } from './agentErrorAnalysis.js';
+import {
+ analyzeAgentFailure,
+ resolveFailedTaskDecision,
+ MAX_TASK_RETRIES
+} from './agentErrorAnalysis.js';
+import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
+
+// analyzeAgentFailure ignores output shorter than 50 chars (treats it as a
+// startup failure), so wrap each error line with a benign, pattern-free lead
+// line that pushes the total past the threshold without matching any category.
+const withLead = (errorLine) =>
+ ['Initializing agent session and preparing the working directory.', errorLine].join('\n');
describe('analyzeAgentFailure', () => {
it('classifies unsupported Codex model errors instead of matching prompt text', () => {
@@ -57,3 +68,144 @@ describe('analyzeAgentFailure', () => {
expect(analysis.requiresFallback).toBeUndefined();
});
});
+
+// Exercises the real exported ERROR_PATTERNS via analyzeAgentFailure, replacing
+// the inline copy that used to live (and drift) in subAgentSpawner.test.js.
+describe('analyzeAgentFailure — ERROR_PATTERNS classification', () => {
+ it('classifies a 404 model-not-found error as actionable', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 404 - model: claude-4-ultra not found'), { id: 't' }, 'claude-4-ultra');
+ expect(analysis.category).toBe('model-not-found');
+ expect(analysis.actionable).toBe(true);
+ });
+
+ it('classifies a not_found_error model response as model-not-found', () => {
+ const analysis = analyzeAgentFailure(withLead('Response: not_found_error - the requested model does not exist'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('model-not-found');
+ expect(analysis.actionable).toBe(true);
+ });
+
+ it('classifies a 401/authentication error as actionable auth-error', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 401 Unauthorized — authentication failed'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('auth-error');
+ expect(analysis.actionable).toBe(true);
+ });
+
+ it('classifies a 429 rate-limit error as non-actionable (transient retry)', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 429 Too Many Requests, please slow down'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('rate-limit');
+ expect(analysis.actionable).toBe(false);
+ });
+
+ it('classifies a 5xx server error as non-actionable (transient)', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 500 Internal Server Error from the provider'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('server-error');
+ expect(analysis.actionable).toBe(false);
+ });
+
+ it('classifies a connection-refused error as network-error', () => {
+ const analysis = analyzeAgentFailure(withLead('Error: connect ECONNREFUSED 127.0.0.1:443 while reaching the API'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('network-error');
+ expect(analysis.actionable).toBe(false);
+ });
+
+ it('attaches compaction hints to context-length errors', () => {
+ const analysis = analyzeAgentFailure(withLead('Error: maximum context length exceeded for this request'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('context-length');
+ expect(analysis.compaction?.needed).toBe(true);
+ });
+
+ it('falls back to an unknown, non-actionable category for unrecognized output', () => {
+ const analysis = analyzeAgentFailure(withLead('The agent halted after an unrecognized condition with no diagnostic.'), { id: 't' }, 'x');
+ expect(analysis.category).toBe('unknown');
+ expect(analysis.actionable).toBe(false);
+ });
+
+ it('treats near-empty output as a startup failure', () => {
+ const analysis = analyzeAgentFailure('boom', { id: 't' }, 'x');
+ expect(analysis.category).toBe('startup-failure');
+ expect(analysis.actionable).toBe(false);
+ });
+});
+
+// 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.
+describe('resolveFailedTaskDecision', () => {
+ const task = (metadata = {}) => ({ id: 'task-1', description: 'test', metadata });
+
+ describe('actionable errors', () => {
+ it('blocks immediately and requests an investigation for a non-API-access category', () => {
+ const decision = resolveFailedTaskDecision(task(), { actionable: true, category: 'model-not-found', message: 'Model not found' });
+ expect(decision.status).toBe('blocked');
+ expect(decision.shouldCreateInvestigation).toBe(true);
+ expect(decision.metadataUpdates.blockedCategory).toBe('model-not-found');
+ expect(decision.metadataUpdates.blockedReason).toBe('Model not found');
+ });
+
+ it('blocks but skips investigation for API-access categories', () => {
+ for (const category of ['auth-error', 'forbidden', 'usage-limit']) {
+ const decision = resolveFailedTaskDecision(task(), { actionable: true, category, message: `${category} error` });
+ expect(decision.status).toBe('blocked');
+ expect(decision.shouldCreateInvestigation).toBe(false);
+ }
+ });
+
+ it('blocks regardless of prior failure count', () => {
+ const decision = resolveFailedTaskDecision(task({ failureCount: 0 }), { actionable: true, category: 'bad-request', message: 'bad' });
+ expect(decision.status).toBe('blocked');
+ expect(decision.shouldCreateInvestigation).toBe(true);
+ });
+ });
+
+ describe('non-actionable errors with retry tracking', () => {
+ it('retries on the first failure (failureCount → 1)', () => {
+ const decision = resolveFailedTaskDecision(task(), { actionable: false, category: 'rate-limit', message: 'Rate limited' });
+ expect(decision.status).toBe('pending');
+ expect(decision.metadataUpdates.failureCount).toBe(1);
+ expect(decision.metadataUpdates.lastErrorCategory).toBe('rate-limit');
+ expect(decision.shouldCreateInvestigation).toBe(false);
+ });
+
+ it('blocks once failureCount reaches MAX_TASK_RETRIES', () => {
+ const decision = resolveFailedTaskDecision(task({ failureCount: MAX_TASK_RETRIES - 1 }), { actionable: false, category: 'network-error', message: 'Network failed' });
+ expect(decision.status).toBe('blocked');
+ expect(decision.metadataUpdates.failureCount).toBe(MAX_TASK_RETRIES);
+ expect(decision.metadataUpdates.blockedReason).toContain('Max retries exceeded');
+ expect(decision.metadataUpdates.blockedCategory).toBe('network-error');
+ expect(decision.shouldCreateInvestigation).toBe(true);
+ });
+
+ it('blocks on the total-spawn ceiling even when the retry count is low (the gap the inline copy missed)', () => {
+ const decision = resolveFailedTaskDecision(
+ task({ failureCount: 0, totalSpawnCount: MAX_TOTAL_SPAWNS }),
+ { actionable: false, category: 'server-error', message: 'Server error' }
+ );
+ expect(decision.status).toBe('blocked');
+ expect(decision.metadataUpdates.failureCount).toBe(1);
+ expect(decision.shouldCreateInvestigation).toBe(true);
+ });
+
+ it('propagates compaction hints into the retry metadata (also missed by the inline copy)', () => {
+ const compaction = { needed: true, reason: 'context-limit' };
+ const decision = resolveFailedTaskDecision(task(), { actionable: false, category: 'context-length', message: 'too big', compaction });
+ expect(decision.status).toBe('pending');
+ expect(decision.metadataUpdates.compaction).toEqual(compaction);
+ });
+ });
+
+ describe('missing errorAnalysis', () => {
+ it('treats null as a non-actionable unknown error', () => {
+ const decision = resolveFailedTaskDecision(task(), null);
+ expect(decision.status).toBe('pending');
+ expect(decision.metadataUpdates.failureCount).toBe(1);
+ expect(decision.metadataUpdates.lastErrorCategory).toBe('unknown');
+ });
+
+ it('still blocks after max retries with null errorAnalysis', () => {
+ const decision = resolveFailedTaskDecision(task({ failureCount: MAX_TASK_RETRIES - 1 }), null);
+ expect(decision.status).toBe('blocked');
+ expect(decision.metadataUpdates.failureCount).toBe(MAX_TASK_RETRIES);
+ expect(decision.shouldCreateInvestigation).toBe(true);
+ });
+ });
+});
diff --git a/server/services/agentRunTracking.test.js b/server/services/agentRunTracking.test.js
new file mode 100644
index 0000000000..0e1d099c0d
--- /dev/null
+++ b/server/services/agentRunTracking.test.js
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { extractErrorFromOutput } from './agentRunTracking.js';
+
+// extractErrorFromOutput is the real home of the exit-code → message mapping
+// and the output error-pattern scan. subAgentSpawner.test.js used to assert an
+// inline `exitCodeMessages` literal copy that exercised no production code.
+describe('extractErrorFromOutput', () => {
+ describe('empty output — exit-code mapping', () => {
+ it.each([
+ [1, 'General error (exit code 1)', 'unknown'],
+ [2, 'Misuse of shell command (exit code 2)', 'unknown'],
+ [126, 'Command invoked cannot execute (permission or not executable) (exit code 126)', 'unknown'],
+ [127, 'Command not found (exit code 127)', 'unknown'],
+ [130, 'Script terminated by Ctrl+C (exit code 130)', 'unknown'],
+ [137, 'Process killed (SIGKILL) (exit code 137)', 'unknown'],
+ [143, 'Process terminated (SIGTERM - likely timeout) (exit code 143)', 'timeout']
+ ])('maps exit code %i to a readable message and category', (code, message, category) => {
+ const result = extractErrorFromOutput('', code);
+ expect(result.message).toBe(message);
+ expect(result.category).toBe(category);
+ expect(result.details).toBe(`Process exited with code ${code}. No output was captured.`);
+ });
+
+ it('falls back to "Unknown error" for an unmapped exit code', () => {
+ const result = extractErrorFromOutput('', 99);
+ expect(result.message).toBe('Unknown error (exit code 99)');
+ expect(result.category).toBe('unknown');
+ });
+
+ it('treats whitespace-only output as empty', () => {
+ const result = extractErrorFromOutput(' \n \t\n', 1);
+ expect(result.message).toBe('General error (exit code 1)');
+ });
+ });
+
+ describe('non-empty output — error-pattern extraction', () => {
+ it('categorizes an API error line', () => {
+ const result = extractErrorFromOutput('starting up\nAPI Error: 429 too many requests', 1);
+ expect(result.category).toBe('api-error');
+ expect(result.message).toContain('API Error: 429');
+ });
+
+ it('categorizes a permission-denied line', () => {
+ const result = extractErrorFromOutput('running task\npermission denied: /etc/shadow', 126);
+ expect(result.category).toBe('permission');
+ expect(result.message).toContain('permission denied');
+ });
+
+ it('categorizes a connection-refused line', () => {
+ const result = extractErrorFromOutput('working\nconnection refused by upstream service', 1);
+ expect(result.category).toBe('connection');
+ });
+
+ it('categorizes a timeout line', () => {
+ const result = extractErrorFromOutput('working\noperation timeout after 600s', 1);
+ expect(result.category).toBe('timeout');
+ });
+
+ it('keeps category "unknown" and returns the output when nothing matches', () => {
+ const result = extractErrorFromOutput('all quiet on the western front today', 1);
+ expect(result.category).toBe('unknown');
+ expect(result.message).toBe('all quiet on the western front today');
+ });
+ });
+});
diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.js
index c1d89437e3..487e036fbf 100644
--- a/server/services/subAgentSpawner.test.js
+++ b/server/services/subAgentSpawner.test.js
@@ -230,422 +230,9 @@ describe('Model Selection Logic', () => {
});
});
-// Test error pattern analysis
-describe('Error Analysis Logic', () => {
- const ERROR_PATTERNS = [
- {
- pattern: /API Error: 404.*model:\s*(\S+)/i,
- category: 'model-not-found',
- actionable: true
- },
- {
- pattern: /API Error: 401|authentication|unauthorized/i,
- category: 'auth-error',
- actionable: true
- },
- {
- pattern: /API Error: 429|rate.?limit|too many requests/i,
- category: 'rate-limit',
- actionable: false
- },
- {
- pattern: /API Error: 5\d{2}|server error|internal error/i,
- category: 'server-error',
- actionable: false
- },
- {
- pattern: /ECONNREFUSED|ETIMEDOUT|network error/i,
- category: 'network-error',
- actionable: false
- },
- {
- pattern: /not_found_error.*model/i,
- category: 'model-not-found',
- actionable: true
- }
- ];
-
- function categorizeError(output) {
- for (const errorDef of ERROR_PATTERNS) {
- if (errorDef.pattern.test(output)) {
- return {
- category: errorDef.category,
- actionable: errorDef.actionable
- };
- }
- }
- return { category: 'unknown', actionable: false };
- }
-
- describe('Model not found errors', () => {
- it('should detect 404 model error', () => {
- const output = 'API Error: 404 - model: claude-4-ultra not found';
- const result = categorizeError(output);
-
- expect(result.category).toBe('model-not-found');
- expect(result.actionable).toBe(true);
- });
-
- it('should detect not_found_error for model', () => {
- const output = 'Response: not_found_error - The specified model does not exist';
- const result = categorizeError(output);
-
- expect(result.category).toBe('model-not-found');
- expect(result.actionable).toBe(true);
- });
- });
-
- describe('Authentication errors', () => {
- it('should detect 401 error', () => {
- const output = 'API Error: 401 Unauthorized';
- const result = categorizeError(output);
-
- expect(result.category).toBe('auth-error');
- expect(result.actionable).toBe(true);
- });
-
- it('should detect authentication failure', () => {
- const output = 'Authentication failed: invalid API key';
- const result = categorizeError(output);
-
- expect(result.category).toBe('auth-error');
- expect(result.actionable).toBe(true);
- });
- });
-
- describe('Rate limit errors', () => {
- it('should detect 429 error', () => {
- const output = 'API Error: 429 Too Many Requests';
- const result = categorizeError(output);
-
- expect(result.category).toBe('rate-limit');
- expect(result.actionable).toBe(false);
- });
-
- it('should detect rate limit message', () => {
- const output = 'Error: Rate limit exceeded, please try again later';
- const result = categorizeError(output);
-
- expect(result.category).toBe('rate-limit');
- expect(result.actionable).toBe(false);
- });
- });
-
- describe('Server errors', () => {
- it('should detect 500 error', () => {
- const output = 'API Error: 500 Internal Server Error';
- const result = categorizeError(output);
-
- expect(result.category).toBe('server-error');
- expect(result.actionable).toBe(false);
- });
-
- it('should detect 502 error', () => {
- const output = 'API Error: 502 Bad Gateway';
- const result = categorizeError(output);
-
- expect(result.category).toBe('server-error');
- expect(result.actionable).toBe(false);
- });
- });
-
- describe('Network errors', () => {
- it('should detect connection refused', () => {
- const output = 'Error: connect ECONNREFUSED 127.0.0.1:443';
- const result = categorizeError(output);
-
- expect(result.category).toBe('network-error');
- expect(result.actionable).toBe(false);
- });
-
- it('should detect timeout', () => {
- const output = 'Error: ETIMEDOUT - connection timed out';
- const result = categorizeError(output);
-
- expect(result.category).toBe('network-error');
- expect(result.actionable).toBe(false);
- });
- });
-
- describe('Unknown errors', () => {
- it('should return unknown for unmatched patterns', () => {
- const output = 'Some random error message';
- const result = categorizeError(output);
-
- expect(result.category).toBe('unknown');
- expect(result.actionable).toBe(false);
- });
- });
-});
-
-// Test exit code message mapping
-describe('Exit Code Analysis', () => {
- const exitCodeMessages = {
- 1: 'General error',
- 2: 'Misuse of shell command',
- 126: 'Command invoked cannot execute (permission or not executable)',
- 127: 'Command not found',
- 128: 'Invalid exit argument',
- 130: 'Script terminated by Ctrl+C',
- 137: 'Process killed (SIGKILL)',
- 143: 'Process terminated (SIGTERM - likely timeout)',
- 255: 'Exit status out of range'
- };
-
- function getExitCodeMessage(exitCode) {
- return exitCodeMessages[exitCode] || 'Unknown error';
- }
-
- it.each([
- [1, 'General error'],
- [2, 'Misuse of shell command'],
- [126, 'Command invoked cannot execute (permission or not executable)'],
- [127, 'Command not found'],
- [130, 'Script terminated by Ctrl+C'],
- [137, 'Process killed (SIGKILL)'],
- [143, 'Process terminated (SIGTERM - likely timeout)']
- ])('exit code %i should map to: %s', (code, message) => {
- expect(getExitCodeMessage(code)).toBe(message);
- });
-
- it('should return Unknown error for unmapped codes', () => {
- expect(getExitCodeMessage(99)).toBe('Unknown error');
- });
-});
-
-// Test spawn args building
-describe('Spawn Arguments Building', () => {
- function buildSpawnArgs(config, model) {
- const args = [
- '--dangerously-skip-permissions',
- '--print',
- ];
-
- if (model) {
- args.push('--model', model);
- }
-
- return args;
- }
-
- it('should include base flags', () => {
- const args = buildSpawnArgs({}, null);
-
- expect(args).toContain('--dangerously-skip-permissions');
- expect(args).toContain('--print');
- });
-
- it('should include model when specified', () => {
- const args = buildSpawnArgs({}, 'claude-3-sonnet');
-
- expect(args).toContain('--model');
- expect(args).toContain('claude-3-sonnet');
- });
-
- it('should not include model flag when model is null', () => {
- const args = buildSpawnArgs({}, null);
-
- expect(args).not.toContain('--model');
- });
-});
-
-// Test failure retry logic
-describe('Task Failure Retry Logic', () => {
- const MAX_TASK_RETRIES = 3;
-
- const API_ACCESS_ERROR_CATEGORIES = new Set([
- 'auth-error',
- 'forbidden',
- 'usage-limit',
- ]);
-
- /**
- * Inline copy of resolveFailedTaskUpdate decision logic (sans async I/O).
- * Returns { status, metadata, shouldCreateInvestigation }
- */
- function resolveFailedTaskStatus(task, errorAnalysis) {
- // Actionable errors get blocked immediately (skip investigation for API access errors)
- if (errorAnalysis?.actionable) {
- return {
- status: 'blocked',
- metadata: {
- ...task.metadata,
- blockedReason: errorAnalysis.message,
- blockedCategory: errorAnalysis.category,
- blockedAt: 'test-timestamp'
- },
- shouldCreateInvestigation: !API_ACCESS_ERROR_CATEGORIES.has(errorAnalysis.category)
- };
- }
-
- // Non-actionable: track failure count
- const failureCount = (task.metadata?.failureCount || 0) + 1;
- const lastErrorCategory = errorAnalysis?.category || 'unknown';
-
- if (failureCount >= MAX_TASK_RETRIES) {
- return {
- status: 'blocked',
- metadata: {
- ...task.metadata,
- failureCount,
- lastFailureAt: 'test-timestamp',
- lastErrorCategory,
- blockedReason: `Max retries exceeded (${failureCount}/${MAX_TASK_RETRIES}): ${lastErrorCategory}`,
- blockedCategory: lastErrorCategory,
- blockedAt: 'test-timestamp'
- },
- shouldCreateInvestigation: true
- };
- }
-
- return {
- status: 'pending',
- metadata: {
- ...task.metadata,
- failureCount,
- lastFailureAt: 'test-timestamp',
- lastErrorCategory
- },
- shouldCreateInvestigation: false
- };
- }
-
- describe('Actionable errors', () => {
- it('should block immediately on actionable error (first failure)', () => {
- const task = { id: 'task-1', description: 'test', metadata: {} };
- const errorAnalysis = { actionable: true, category: 'model-not-found', message: 'Model not found' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.status).toBe('blocked');
- expect(result.metadata.blockedCategory).toBe('model-not-found');
- expect(result.shouldCreateInvestigation).toBe(true);
- });
-
- it('should skip investigation for API access error categories', () => {
- const task = { id: 'task-1', description: 'test', metadata: {} };
-
- for (const category of ['auth-error', 'forbidden', 'usage-limit']) {
- const result = resolveFailedTaskStatus(task, { actionable: true, category, message: `${category} error` });
- expect(result.status).toBe('blocked');
- expect(result.shouldCreateInvestigation).toBe(false);
- }
- });
-
- it('should block immediately regardless of failure count', () => {
- const task = { id: 'task-1', description: 'test', metadata: { failureCount: 0 } };
- const errorAnalysis = { actionable: true, category: 'model-not-found', message: 'Model not found' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.status).toBe('blocked');
- expect(result.shouldCreateInvestigation).toBe(true);
- });
- });
-
- describe('Non-actionable errors with retry tracking', () => {
- it('should retry on first failure (failureCount goes to 1)', () => {
- const task = { id: 'task-1', description: 'test', metadata: {} };
- const errorAnalysis = { actionable: false, category: 'rate-limit', message: 'Rate limited' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.status).toBe('pending');
- expect(result.metadata.failureCount).toBe(1);
- expect(result.metadata.lastErrorCategory).toBe('rate-limit');
- expect(result.shouldCreateInvestigation).toBe(false);
- });
-
- it('should retry on second failure (failureCount goes to 2)', () => {
- const task = { id: 'task-1', description: 'test', metadata: { failureCount: 1 } };
- const errorAnalysis = { actionable: false, category: 'server-error', message: 'Server error' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.status).toBe('pending');
- expect(result.metadata.failureCount).toBe(2);
- expect(result.metadata.lastErrorCategory).toBe('server-error');
- expect(result.shouldCreateInvestigation).toBe(false);
- });
-
- it('should block after MAX_TASK_RETRIES failures', () => {
- const task = { id: 'task-1', description: 'test', metadata: { failureCount: 2 } };
- const errorAnalysis = { actionable: false, category: 'network-error', message: 'Network failed' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.status).toBe('blocked');
- expect(result.metadata.failureCount).toBe(3);
- expect(result.metadata.blockedReason).toContain('Max retries exceeded');
- expect(result.metadata.blockedCategory).toBe('network-error');
- expect(result.shouldCreateInvestigation).toBe(true);
- });
-
- it('should block when already past max retries', () => {
- const task = { id: 'task-1', description: 'test', metadata: { failureCount: 5 } };
- const errorAnalysis = { actionable: false, category: 'unknown', message: 'Unknown error' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.status).toBe('blocked');
- expect(result.metadata.failureCount).toBe(6);
- expect(result.shouldCreateInvestigation).toBe(true);
- });
- });
-
- describe('Unknown errors (no errorAnalysis)', () => {
- it('should treat null errorAnalysis as non-actionable unknown', () => {
- const task = { id: 'task-1', description: 'test', metadata: {} };
-
- const result = resolveFailedTaskStatus(task, null);
-
- expect(result.status).toBe('pending');
- expect(result.metadata.failureCount).toBe(1);
- expect(result.metadata.lastErrorCategory).toBe('unknown');
- });
-
- it('should still block after max retries with null errorAnalysis', () => {
- const task = { id: 'task-1', description: 'test', metadata: { failureCount: 2 } };
-
- const result = resolveFailedTaskStatus(task, null);
-
- expect(result.status).toBe('blocked');
- expect(result.metadata.failureCount).toBe(3);
- expect(result.shouldCreateInvestigation).toBe(true);
- });
- });
-
- describe('Metadata preservation', () => {
- it('should preserve existing metadata fields on retry', () => {
- const task = {
- id: 'task-1',
- description: 'test',
- metadata: { app: 'my-app', context: 'some context', failureCount: 1 }
- };
- const errorAnalysis = { actionable: false, category: 'rate-limit', message: 'Rate limited' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.metadata.app).toBe('my-app');
- expect(result.metadata.context).toBe('some context');
- expect(result.metadata.failureCount).toBe(2);
- });
-
- it('should preserve existing metadata fields when blocked', () => {
- const task = {
- id: 'task-1',
- description: 'test',
- metadata: { app: 'my-app', failureCount: 2 }
- };
- const errorAnalysis = { actionable: false, category: 'server-error', message: 'Server error' };
-
- const result = resolveFailedTaskStatus(task, errorAnalysis);
-
- expect(result.metadata.app).toBe('my-app');
- expect(result.metadata.failureCount).toBe(3);
- expect(result.status).toBe('blocked');
- });
- });
+// Worktree/PR flag resolution + metadata coercion helpers, exercised through
+// the real production helpers (isTruthyMeta/isFalsyMeta/applyAppWorktreeDefault).
+describe('Worktree & metadata flag helpers', () => {
// --- isTruthyMeta helper (imported from production) ---
describe('isTruthyMeta', () => {