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([issue-2615]): dedupe investigation tasks by durable fingerprint with hourly circuit breaker and meta-cascade guard

[._.]/ Adam Eivy98455257f92c
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index e7fcabe87d..1fe5f317f1 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -6,10 +6,11 @@
*/
import { emitLog } from './cosEvents.js';
-import { addTask, updateTask } from './cos.js';
+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 { isTruthyMeta } from './agentState.js';
// Max retries before blocking a task
export const MAX_TASK_RETRIES = 3;
@@ -520,8 +521,70 @@ export function analyzeAgentFailure(output, task, model) {
};
}
+// ===== Investigation-task creation guards (#2615) =====
+
+// An investigation in any of these states means the failure cause is already
+// being tracked — a repeat failure with the same fingerprint is the SAME cause,
+// not new work. Terminal states (completed/cancelled) allow a fresh task: the
+// cause was dealt with, so a recurrence is genuinely new.
+const OPEN_INVESTIGATION_STATUSES = new Set(['pending', 'in_progress', 'blocked']);
+
+// Rolling circuit breaker across ALL fingerprints, mirroring autoFixer.js's
+// tripCircuit: at most INVESTIGATION_CIRCUIT_MAX_CREATIONS investigation tasks
+// per rolling window. A systemic failure storm (provider outage, broken spawn
+// path) fails MANY distinct tasks at once, each minting a distinct fingerprint —
+// the per-fingerprint dedup alone can't stop that fan-out. The window is rolling:
+// stamps older than the window are pruned on every check, so the circuit
+// auto-closes once creations age out (no manual reset needed).
+export const INVESTIGATION_CIRCUIT_WINDOW_MS = 60 * 60 * 1000; // 1 hour
+export const INVESTIGATION_CIRCUIT_MAX_CREATIONS = 3;
+let investigationCreationStamps = []; // ms timestamps, newest-last
+
+function investigationCircuitOpen(now) {
+ investigationCreationStamps = investigationCreationStamps.filter(t => now - t < INVESTIGATION_CIRCUIT_WINDOW_MS);
+ return investigationCreationStamps.length >= INVESTIGATION_CIRCUIT_MAX_CREATIONS;
+}
+
+// Test hook — the stamp list is module state, so suites reset it between cases.
+export function __resetInvestigationCircuit() {
+ investigationCreationStamps = [];
+}
+
+/**
+ * Durable dedup key for investigation tasks: same failure category against the
+ * same kind of task in the same app is the same cause. Deliberately NOT keyed
+ * on the free-text failure message — for `unknown`-category failures that is a
+ * raw agent-output line that varies per run, which is exactly the dedup hole
+ * that let near-identical investigations pile up (#2615).
+ */
+export function buildInvestigationFingerprint(originalTask, analysis) {
+ const category = analysis?.category || 'unknown';
+ const kind = originalTask?.metadata?.analysisType
+ || originalTask?.metadata?.selfImprovementType
+ || originalTask?.taskType
+ || 'task';
+ const app = originalTask?.metadata?.app || 'none';
+ return `${category}:${kind}:${app}`;
+}
+
+// Find an existing investigation task (user or internal queue) still tracking
+// this fingerprint in a non-terminal status.
+async function findOpenInvestigation(fingerprint) {
+ const { user, cos } = await getAllTasks();
+ const tasks = [...(user?.tasks || []), ...(cos?.tasks || [])];
+ return tasks.find(t =>
+ OPEN_INVESTIGATION_STATUSES.has(t.status) &&
+ t.metadata?.investigationFingerprint === fingerprint
+ ) || null;
+}
+
/**
* Create an investigation task in COS-TASKS.md for a failed agent.
+ *
+ * Guarded two ways (#2615): a durable fingerprint dedup (one open investigation
+ * per failure cause — returns the existing task when it fires) and a rolling
+ * circuit breaker (returns null when open). See maybeCreateInvestigationTask
+ * for the meta-cascade guard.
*/
export async function createInvestigationTask(agentId, originalTask, errorAnalysis) {
const analysis = errorAnalysis || {};
@@ -529,6 +592,25 @@ export async function createInvestigationTask(agentId, originalTask, errorAnalys
const rawMessage = analysis.message || 'Agent failed with an unrecognized error';
const modelAttribution = analysis.affectedModel || analysis.configuredModel || null;
+ // Durable-fingerprint dedup: one open investigation per failure cause.
+ const fingerprint = buildInvestigationFingerprint(originalTask, analysis);
+ const existing = await findOpenInvestigation(fingerprint);
+ if (existing) {
+ emitLog('info', `⏭️ Skipping duplicate investigation for ${fingerprint}: ${existing.id} is still ${existing.status}`, {
+ agentId, taskId: originalTask.id, fingerprint, existingTaskId: existing.id, existingStatus: existing.status
+ });
+ return existing;
+ }
+
+ // Rolling circuit breaker: cap creations per window across all fingerprints.
+ const now = Date.now();
+ if (investigationCircuitOpen(now)) {
+ emitLog('warn', `🔌 Investigation circuit OPEN — ${INVESTIGATION_CIRCUIT_MAX_CREATIONS} investigations created within the last hour; suppressing task for ${fingerprint}`, {
+ agentId, taskId: originalTask.id, fingerprint
+ });
+ return null;
+ }
+
// Every interpolated free-text field is redacted before it lands in the body —
// this task is human-facing and may sync across federated peers, so no
// hostnames/paths/IPs/PII/secrets from the live instance may leak in. `message`
@@ -562,9 +644,15 @@ Approving and applying the fix lets the original task \`${originalTask.id}\` be
description,
priority: 'HIGH',
context: `Auto-generated from agent ${agentId} failure`,
- approvalRequired: true // Require human approval before auto-fixing
+ approvalRequired: true, // Require human approval before auto-fixing
+ isInvestigation: true, // Meta-cascade guard marker (#2615)
+ investigationFingerprint: fingerprint
}, 'internal');
+ // Count only genuine creations against the circuit — addTask's own
+ // description-level dedup returning an existing task is not a new creation.
+ if (!investigationTask.duplicate) investigationCreationStamps.push(now);
+
emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId}`, {
agentId,
taskId: investigationTask.id,
@@ -594,6 +682,13 @@ export async function maybeCreateInvestigationTask(agentId, task, analysis) {
emitLog('debug', `⏭️ Skipping investigation task for ${task.id}: API access error (${analysis.category})`, { agentId, taskId: task.id, category: analysis.category });
return;
}
+ // Meta-cascade guard (#2615): a failed investigation task must never spawn an
+ // investigation of the investigation. isTruthyMeta covers the markdown
+ // round-trip, where boolean metadata comes back as the string 'true'.
+ if (isTruthyMeta(task?.metadata?.isInvestigation)) {
+ emitLog('info', `⏭️ Skipping meta-investigation for ${task.id}: failed task is itself an investigation`, { agentId, taskId: task.id, category: analysis?.category });
+ return;
+ }
await createInvestigationTask(agentId, task, analysis).catch(err => {
emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId, taskId: task.id, category: analysis?.category });
});
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index ab37346c18..aeba1aa4fc 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -2,19 +2,31 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
// maybeCreateInvestigationTask → createInvestigationTask → addTask does real
// store I/O; stub it so the skip-vs-create gate can be asserted in isolation.
-vi.mock('./cos.js', () => ({ addTask: vi.fn(), updateTask: vi.fn() }));
+// getAllTasks feeds the fingerprint dedup scan (#2615).
+vi.mock('./cos.js', () => ({ addTask: vi.fn(), updateTask: vi.fn(), getAllTasks: vi.fn() }));
import {
analyzeAgentFailure,
resolveFailedTaskDecision,
maybeCreateInvestigationTask,
createInvestigationTask,
+ buildInvestigationFingerprint,
redactFailureSnippet,
- MAX_TASK_RETRIES
+ MAX_TASK_RETRIES,
+ INVESTIGATION_CIRCUIT_WINDOW_MS,
+ INVESTIGATION_CIRCUIT_MAX_CREATIONS,
+ __resetInvestigationCircuit
} from './agentErrorAnalysis.js';
-import { addTask } from './cos.js';
+import { addTask, getAllTasks } from './cos.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
+// Default store shape for suites that exercise the create path: no existing
+// tasks, so the fingerprint dedup never fires unless a test arranges it.
+const mockEmptyStore = () => {
+ getAllTasks.mockReset();
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
+};
+
// 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.
@@ -217,6 +229,8 @@ describe('maybeCreateInvestigationTask', () => {
beforeEach(() => {
addTask.mockReset();
addTask.mockResolvedValue({ id: 'investigation-1' });
+ mockEmptyStore();
+ __resetInvestigationCircuit();
});
const task = { id: 'task-1', description: 'do the thing', metadata: {} };
@@ -233,6 +247,115 @@ describe('maybeCreateInvestigationTask', () => {
await maybeCreateInvestigationTask('agent-1', task, { category: 'model-not-found', message: 'Model not found' });
expect(addTask).toHaveBeenCalledTimes(1);
});
+
+ it('never spawns an investigation for a failed investigation task (meta-cascade guard)', async () => {
+ await maybeCreateInvestigationTask('agent-1', { id: 'inv-1', description: '[Auto] Investigate agent failure: x', metadata: { isInvestigation: true } }, { category: 'unknown', message: 'boom' });
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('honors the string-true marker from the markdown metadata round-trip', async () => {
+ await maybeCreateInvestigationTask('agent-1', { id: 'inv-2', description: 'x', metadata: { isInvestigation: 'true' } }, { category: 'unknown', message: 'boom' });
+ expect(addTask).not.toHaveBeenCalled();
+ });
+});
+
+describe('buildInvestigationFingerprint', () => {
+ it('keys on category, analysisType/taskType, and app — never the free-text message', () => {
+ const fp = buildInvestigationFingerprint(
+ { id: 't', taskType: 'internal', metadata: { analysisType: 'app-improve', app: 'ExampleApp' } },
+ { category: 'startup-failure', message: 'raw output line that varies per run' }
+ );
+ expect(fp).toBe('startup-failure:app-improve:ExampleApp');
+ });
+
+ it('falls back to taskType, then generic sentinels, when analysisType/app are absent', () => {
+ expect(buildInvestigationFingerprint({ id: 't', taskType: 'user', metadata: {} }, { category: 'unknown' })).toBe('unknown:user:none');
+ expect(buildInvestigationFingerprint({ id: 't' }, null)).toBe('unknown:task:none');
+ });
+});
+
+describe('createInvestigationTask guards (#2615)', () => {
+ const failedTask = { id: 'task-1', description: 'do the thing', taskType: 'user', metadata: {} };
+ const analysis = { category: 'startup-failure', message: 'Agent exited during startup' };
+
+ beforeEach(() => {
+ addTask.mockReset();
+ addTask.mockResolvedValue({ id: 'investigation-1' });
+ mockEmptyStore();
+ __resetInvestigationCircuit();
+ });
+
+ it('stamps the fingerprint and isInvestigation marker onto the created task', async () => {
+ await createInvestigationTask('agent-1', failedTask, analysis);
+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({
+ priority: 'HIGH',
+ approvalRequired: true,
+ isInvestigation: true,
+ investigationFingerprint: 'startup-failure:user:none'
+ }), 'internal');
+ });
+
+ it.each(['pending', 'in_progress', 'blocked'])(
+ 'skips creation while a same-fingerprint investigation is %s',
+ async (status) => {
+ const existing = { id: 'inv-open', status, metadata: { investigationFingerprint: 'startup-failure:user:none' } };
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [existing] } });
+ const result = await createInvestigationTask('agent-1', failedTask, analysis);
+ expect(addTask).not.toHaveBeenCalled();
+ expect(result).toBe(existing);
+ }
+ );
+
+ it('creates a fresh task once the prior investigation reached a terminal status', async () => {
+ const done = { id: 'inv-done', status: 'completed', metadata: { investigationFingerprint: 'startup-failure:user:none' } };
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [done] } });
+ await createInvestigationTask('agent-1', failedTask, analysis);
+ expect(addTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not dedupe against an open investigation with a DIFFERENT fingerprint', async () => {
+ const other = { id: 'inv-other', status: 'pending', metadata: { investigationFingerprint: 'network-error:user:none' } };
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [other] } });
+ await createInvestigationTask('agent-1', failedTask, analysis);
+ expect(addTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('caps creations per rolling hour across all fingerprints', async () => {
+ for (let i = 0; i < INVESTIGATION_CIRCUIT_MAX_CREATIONS; i++) {
+ await createInvestigationTask(`agent-${i}`, { ...failedTask, id: `task-${i}` }, { category: `cat-${i}`, message: 'x' });
+ }
+ expect(addTask).toHaveBeenCalledTimes(INVESTIGATION_CIRCUIT_MAX_CREATIONS);
+
+ const suppressed = await createInvestigationTask('agent-over', failedTask, analysis);
+ expect(suppressed).toBeNull();
+ expect(addTask).toHaveBeenCalledTimes(INVESTIGATION_CIRCUIT_MAX_CREATIONS);
+ });
+
+ it('re-closes the circuit once creations age out of the rolling window', async () => {
+ vi.useFakeTimers();
+ try {
+ for (let i = 0; i < INVESTIGATION_CIRCUIT_MAX_CREATIONS; i++) {
+ await createInvestigationTask(`agent-${i}`, { ...failedTask, id: `task-${i}` }, { category: `cat-${i}`, message: 'x' });
+ }
+ expect(await createInvestigationTask('agent-over', failedTask, analysis)).toBeNull();
+
+ vi.advanceTimersByTime(INVESTIGATION_CIRCUIT_WINDOW_MS + 1);
+ await createInvestigationTask('agent-later', failedTask, analysis);
+ expect(addTask).toHaveBeenCalledTimes(INVESTIGATION_CIRCUIT_MAX_CREATIONS + 1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not count an addTask description-level duplicate against the circuit', async () => {
+ addTask.mockResolvedValue({ id: 'inv-existing', duplicate: true });
+ for (let i = 0; i < INVESTIGATION_CIRCUIT_MAX_CREATIONS + 1; i++) {
+ await createInvestigationTask(`agent-${i}`, { ...failedTask, id: `task-${i}` }, { category: `cat-${i}`, message: 'x' });
+ }
+ // Every call reached addTask — none were suppressed by the circuit, because
+ // duplicate returns never consumed creation budget.
+ expect(addTask).toHaveBeenCalledTimes(INVESTIGATION_CIRCUIT_MAX_CREATIONS + 1);
+ });
});
describe('redactFailureSnippet', () => {
@@ -291,6 +414,8 @@ describe('createInvestigationTask body', () => {
beforeEach(() => {
addTask.mockReset();
addTask.mockResolvedValue({ id: 'investigation-1' });
+ mockEmptyStore();
+ __resetInvestigationCircuit();
});
const bodyOf = () => addTask.mock.calls[0][0].description;
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index dd35b79ee6..29f798bebc 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -242,6 +242,10 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
// speech layer can announce its completion (see voice/proactiveTriggers.js).
if (taskData.voiceDispatch === true) metadata.voiceDispatch = true;
if (taskData.isRecovery === true) metadata.isRecovery = true;
+ // Investigation-task guards (#2615): the durable fingerprint dedupes repeat
+ // failures of the same cause; the marker blocks investigations-of-investigations.
+ if (taskData.isInvestigation === true) metadata.isInvestigation = true;
+ if (taskData.investigationFingerprint) metadata.investigationFingerprint = taskData.investigationFingerprint;
if (taskData.createJiraTicket) metadata.createJiraTicket = true;
// Boolean flags: persist both true and false so users can explicitly override defaults.
// The string round-trip ('false' from TASKS.md) is handled by isTruthyMeta/isFalsyMeta.