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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (claude): close the challenged-status dedup hole, TOCTOU, and cross-app headline collapse
[._.]/ Adam Eivyede8381e1481
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex be7dd33d70..a6122e55e7 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -525,9 +525,11 @@ export function analyzeAgentFailure(output, task, model) {// 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']);+// not new work. `completed` is the only terminal status in the task vocabulary+// (see taskParser.js STATUS_MAP); everything else — including `challenged`,+// where a task can park for days awaiting user arbitration — stays open, so a+// fresh task is only allowed once the prior cause was actually dealt with.+const OPEN_INVESTIGATION_STATUSES = new Set(['pending', 'in_progress', 'challenged', 'blocked']);// Rolling circuit breaker across ALL fingerprints, mirroring autoFixer.js's// tripCircuit: at most INVESTIGATION_CIRCUIT_MAX_CREATIONS investigation tasks@@ -585,8 +587,22 @@ async function findOpenInvestigation(fingerprint) {* 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.+ *+ * Serialized on a module-level promise tail: a failure storm fires several+ * concurrent finalize chains, and without the tail two same-fingerprint creates+ * can both pass the fingerprint scan (and both read a below-cap circuit) before+ * either addTask lands — the exact TOCTOU the guards exist to close. Each+ * caller still sees its own result/rejection; the tail itself never poisons.*/-export async function createInvestigationTask(agentId, originalTask, errorAnalysis) {+let investigationCreateTail = Promise.resolve();++export function createInvestigationTask(agentId, originalTask, errorAnalysis) {+ const run = investigationCreateTail.then(() => doCreateInvestigationTask(agentId, originalTask, errorAnalysis));+ investigationCreateTail = run.catch(() => {});+ return run;+}++async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {const analysis = errorAnalysis || {};const category = analysis.category || 'unknown';const rawMessage = analysis.message || 'Agent failed with an unrecognized error';@@ -626,7 +642,14 @@ export async function createInvestigationTask(agentId, originalTask, errorAnalys|| analysis.suggestedFix|| 'Review the agent output, decide whether to fix the underlying config/code and retry, or close the task.';- const description = `[Auto] Investigate agent failure: ${message}+ // The app rides in the headline (mirroring the `[Improvement: <app>]`+ // convention) so addTask's first-line dedup — which sees no `metadata.app`+ // on investigation tasks — can't collapse identical messages from DIFFERENT+ // apps into one task. Same-app repeats are already caught by the fingerprint+ // scan above; deliberately NOT passed as `app` to addTask, which would+ // change workspace routing for the investigation agent.+ const app = originalTask?.metadata?.app || null;+ const description = `[Auto] Investigate agent failure${app ? ` [${app}]` : ''}: ${message}## What happenedAgent \`${agentId}\` failed while working on task \`${originalTask.id}\` (${originalDesc}).diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex aeba1aa4fc..a5534f00e4 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -295,7 +295,7 @@ describe('createInvestigationTask guards (#2615)', () => {}), 'internal');});- it.each(['pending', 'in_progress', 'blocked'])(+ it.each(['pending', 'in_progress', 'challenged', 'blocked'])('skips creation while a same-fingerprint investigation is %s',async (status) => {const existing = { id: 'inv-open', status, metadata: { investigationFingerprint: 'startup-failure:user:none' } };@@ -356,6 +356,47 @@ describe('createInvestigationTask guards (#2615)', () => {// duplicate returns never consumed creation budget.expect(addTask).toHaveBeenCalledTimes(INVESTIGATION_CIRCUIT_MAX_CREATIONS + 1);});++ it('embeds the failed task\'s app in the headline so first-line dedup cannot collapse different apps', async () => {+ await createInvestigationTask('agent-1', { ...failedTask, metadata: { app: 'ExampleApp' } }, analysis);+ expect(addTask.mock.calls[0][0].description.split('\n')[0])+ .toBe('[Auto] Investigate agent failure [ExampleApp]: Agent exited during startup');+ // No app → unchanged headline shape.+ addTask.mockClear();+ mockEmptyStore();+ await createInvestigationTask('agent-2', failedTask, analysis);+ expect(addTask.mock.calls[0][0].description.split('\n')[0])+ .toBe('[Auto] Investigate agent failure: Agent exited during startup');+ });++ it('serializes concurrent same-fingerprint creates so only one task lands (TOCTOU)', async () => {+ // Stateful store double: created tasks become visible to the NEXT scan,+ // proving the second create's fingerprint scan runs after the first's+ // addTask instead of interleaving ahead of it.+ const store = [];+ getAllTasks.mockReset();+ getAllTasks.mockImplementation(async () => ({ user: { tasks: [] }, cos: { tasks: [...store] } }));+ addTask.mockReset();+ addTask.mockImplementation(async (taskData) => {+ const created = {+ id: `inv-${store.length + 1}`,+ status: 'pending',+ metadata: { investigationFingerprint: taskData.investigationFingerprint, isInvestigation: true }+ };+ store.push(created);+ return created;+ });++ const [first, second] = await Promise.all([+ createInvestigationTask('agent-a', failedTask, analysis),+ createInvestigationTask('agent-b', { ...failedTask, id: 'task-2' }, analysis)+ ]);++ expect(addTask).toHaveBeenCalledTimes(1);+ expect(store).toHaveLength(1);+ expect(first).toBe(store[0]); // creator gets the created task+ expect(second).toBe(store[0]); // second create deduped to the same task+ });});describe('redactFailureSnippet', () => {diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 77733f4c1b..725c73a05a 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -199,6 +199,30 @@ describe('cosTaskStore.addTask', () => {expect(reloaded.metadata.diagnostics).toEqual(diagnostics);});+ it('persists the investigation guard markers into metadata and round-trips them through markdown (#2615)', async () => {+ const created = await addTask({+ description: '[Auto] Investigate agent failure: agent exited during startup',+ approvalRequired: true,+ isInvestigation: true,+ investigationFingerprint: 'startup-failure:user:none'+ }, 'internal');+ expect(created.metadata.isInvestigation).toBe(true);+ expect(created.metadata.investigationFingerprint).toBe('startup-failure:user:none');+ // Survives the markdown serialize → parse round-trip: the colon-bearing+ // fingerprint stays intact (parser splits on the FIRST colon only) and the+ // boolean marker comes back as the string 'true' (isTruthyMeta territory).+ const { tasks } = await getCosTasks();+ const reloaded = tasks.find(t => t.id === created.id);+ expect(reloaded.metadata.investigationFingerprint).toBe('startup-failure:user:none');+ expect(reloaded.metadata.isInvestigation === true || reloaded.metadata.isInvestigation === 'true').toBe(true);+ });++ it('omits investigation guard metadata when not supplied', async () => {+ const created = await addTask({ description: 'ordinary task' }, 'user');+ expect(created.metadata.isInvestigation).toBeUndefined();+ expect(created.metadata.investigationFingerprint).toBeUndefined();+ });+it('omits diagnostics metadata when none is supplied and ignores a non-object / array value', async () => {const created = await addTask({ description: 'no diagnostics here' }, 'user');expect(created.metadata.diagnostics).toBeUndefined();