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-2628]): dedupe same-fingerprint investigation tasks at peer-merge boundary

[._.]/ Adam Eivy345bbeefc9af
diff --git a/server/services/cosTaskMerge.js b/server/services/cosTaskMerge.js
index 7e3e1af8d4..97c0788862 100644
--- a/server/services/cosTaskMerge.js
+++ b/server/services/cosTaskMerge.js
@@ -40,6 +40,20 @@
* guard. A claim is never kept on a terminal (completed/blocked) task —
* that mirrors cosTaskStore's release-on-transition so a finished task is
* freely re-claimable.
+ *
+ * 4. After the per-id merge, collapse same-`investigationFingerprint` OPEN
+ * investigation duplicates (#2628). The per-process fingerprint dedup in
+ * agentErrorAnalysis (#2615) is serialized on a module-level tail, so a single
+ * install never mints two open investigations for one failure cause — but two
+ * federated peers can each mint one before the next sweep, and rule 1's
+ * union-by-id keeps BOTH. A deterministic, side-independent post-pass folds
+ * them to a single active row: keep the older/lower-id copy (or the copy
+ * holding a live lease, so an in-flight investigation is never orphaned),
+ * union every duplicate's `metadata.affectedTasks` onto it, and flip the
+ * other open copies to `completed` (never delete — LWW sync never propagates
+ * deletions; a terminal status converges via rule 2's status rank). Runs
+ * identically on both peers over the converged per-id set, so they reach the
+ * same single survivor regardless of which side sweeps.
*/
import { isLeaseLive, getClaimOwner, CLAIM_METADATA_KEYS, parseTimestampMs } from './cosTaskClaim.js';
@@ -252,6 +266,100 @@ function normalizeAdopted(task) {
};
}
+// (rule 4) The terminal status an OPEN investigation loser is flipped to when a
+// same-fingerprint winner is chosen. `completed` (not `blocked`) — the duplicate
+// is subsumed, not stuck; it needs no further work. Marked with `supersededBy` so
+// the collapse is auditable and the pass stays idempotent (a superseded copy is
+// terminal, so it never re-enters the open-duplicate set on the next sweep).
+const SUPERSEDED_STATUS = 'completed';
+const SUPERSEDED_BY_KEY = 'supersededBy';
+
+// The metadata marker every investigation task carries (#2615). Grouping keys off
+// this so only real investigation duplicates are ever collapsed.
+const FINGERPRINT_KEY = 'investigationFingerprint';
+const AFFECTED_TASKS_KEY = 'affectedTasks';
+
+const affectedTaskIds = (task) => {
+ const arr = task?.metadata?.[AFFECTED_TASKS_KEY];
+ return Array.isArray(arr) ? arr.filter((id) => typeof id === 'string' && id) : [];
+};
+
+/**
+ * Choose the surviving row among the OPEN (non-terminal) copies of one
+ * investigation fingerprint. A copy holding a live lease wins outright so an
+ * in-flight investigation is never orphaned by the collapse; if MORE than one is
+ * live-leased (two peers both spawned in the sub-second claim window), return null
+ * to skip the collapse this sweep — both run to completion and the group self-heals
+ * as each turns terminal, rather than killing a running agent. With no live lease,
+ * the older/lower-id copy wins deterministically (investigation ids embed a base36
+ * creation timestamp, so lower id == older), side-independent so both peers agree.
+ */
+function pickInvestigationSurvivor(openCopies, now) {
+ const leased = openCopies.filter((t) => isLeaseLive(t.metadata, now));
+ if (leased.length > 1) return null;
+ if (leased.length === 1) return leased[0];
+ return openCopies.reduce((a, b) => (a.id <= b.id ? a : b));
+}
+
+/**
+ * (rule 4) Collapse same-fingerprint OPEN investigation duplicates that rule 1's
+ * union-by-id let survive across two peers. Pure: returns a new array (new objects
+ * only for the rows it rewrites), never mutates inputs. Deterministic over the
+ * converged per-id merge output, so both peers reach the same single survivor.
+ */
+function dedupeInvestigations(tasks, now) {
+ const groups = new Map();
+ for (const t of tasks) {
+ const fp = t?.metadata?.[FINGERPRINT_KEY];
+ if (typeof fp !== 'string' || !fp) continue;
+ if (!groups.has(fp)) groups.set(fp, []);
+ groups.get(fp).push(t);
+ }
+
+ const rewrites = new Map(); // original task ref -> replacement
+ for (const group of groups.values()) {
+ const open = group.filter((t) => !isTerminalStatus(t.status));
+ if (open.length === 0) continue;
+ // Act on a genuine open duplicate, OR to re-fold a prior collapse whose
+ // survivor a mid-propagation per-id LWW may have reverted to a partial
+ // affectedTasks set (a terminal `supersededBy` sibling marks that history).
+ const collapsedBefore = group.some((t) => t?.metadata?.[SUPERSEDED_BY_KEY]);
+ if (open.length < 2 && !collapsedBefore) continue;
+
+ const survivor = pickInvestigationSurvivor(open, now);
+ if (!survivor) continue; // multiple live leases — don't orphan; wait a sweep
+
+ // Union affectedTasks across EVERY copy (open + already-superseded) so the one
+ // surviving row names every task blocked on this cause. Sorted so both peers
+ // serialize an identical set (their group order differs by local-first).
+ const affected = new Set();
+ for (const t of group) for (const id of affectedTaskIds(t)) affected.add(id);
+ const unionAffected = [...affected].sort();
+
+ const currentAffected = affectedTaskIds(survivor);
+ const affectedChanged =
+ unionAffected.length !== currentAffected.length ||
+ unionAffected.some((id, i) => id !== currentAffected[i]);
+ if (affectedChanged && unionAffected.length > 0) {
+ rewrites.set(survivor, {
+ ...survivor,
+ metadata: { ...(survivor.metadata || {}), [AFFECTED_TASKS_KEY]: unionAffected },
+ });
+ }
+
+ for (const loser of open) {
+ if (loser === survivor) continue;
+ const metadata = { ...(loser.metadata || {}) };
+ for (const key of CLAIM_METADATA_KEYS) delete metadata[key]; // terminal → no claim
+ metadata[SUPERSEDED_BY_KEY] = survivor.id;
+ rewrites.set(loser, { ...loser, status: SUPERSEDED_STATUS, metadata });
+ }
+ }
+
+ if (rewrites.size === 0) return tasks;
+ return tasks.map((t) => rewrites.get(t) || t);
+}
+
/**
* Merge a peer's task list into the local one. Pure: returns a new array, never
* mutates the inputs. `now` is injectable for deterministic tests.
@@ -283,5 +391,7 @@ export function mergeTaskLists(localTasks, remoteTasks, { now = Date.now() } = {
seen.add(r.id);
merged.push(normalizeAdopted(r));
}
- return merged;
+ // (rule 4) Collapse same-fingerprint OPEN investigation duplicates that the
+ // per-id union above let survive across two peers (#2628).
+ return dedupeInvestigations(merged, now);
}
diff --git a/server/services/cosTaskMerge.test.js b/server/services/cosTaskMerge.test.js
index b027d22235..c82831c554 100644
--- a/server/services/cosTaskMerge.test.js
+++ b/server/services/cosTaskMerge.test.js
@@ -296,4 +296,126 @@ describe('mergeTaskLists', () => {
expect(merged.metadata.claimedBy).toBe('peer-A');
});
});
+
+ describe('cross-peer investigation fingerprint dedup (#2628)', () => {
+ // An investigation task carries a durable fingerprint marker (#2615). Two
+ // federated peers can each mint one for the SAME failure cause before syncing;
+ // rule 1 unions them by id so both survive. `inv` builds one.
+ const inv = (id, status, fp, overrides = {}) =>
+ task(id, status, {
+ metadata: {
+ isInvestigation: true,
+ investigationFingerprint: fp,
+ ...(overrides.affectedTasks ? { affectedTasks: overrides.affectedTasks } : {}),
+ ...(overrides.metadata || {}),
+ },
+ ...(overrides.priority ? { priority: overrides.priority } : {}),
+ });
+
+ it('collapses two same-fingerprint OPEN investigations from two peers to one active row', () => {
+ const local = [inv('sys-a', 'pending', 'fp-1', { affectedTasks: ['task-1'] })];
+ const remote = [inv('sys-b', 'pending', 'fp-1', { affectedTasks: ['task-2'] })];
+
+ // Symmetric: same survivor regardless of which side initiates the sweep.
+ for (const merged of [
+ mergeTaskLists(local, remote, { now: NOW }),
+ mergeTaskLists(remote, local, { now: NOW }),
+ ]) {
+ const byId = Object.fromEntries(merged.map((t) => [t.id, t]));
+ // Older/lower id survives as the single OPEN row.
+ expect(byId['sys-a'].status).toBe('pending');
+ // Loser flipped to a terminal status — NOT deleted (LWW never propagates a
+ // delete), and marked so the collapse is auditable + idempotent.
+ expect(byId['sys-b'].status).toBe('completed');
+ expect(byId['sys-b'].metadata.supersededBy).toBe('sys-a');
+ // affectedTasks unioned (deduped, sorted) onto the survivor.
+ expect(byId['sys-a'].metadata.affectedTasks).toEqual(['task-1', 'task-2']);
+ // Exactly one non-terminal investigation remains for this fingerprint.
+ const open = merged.filter(
+ (t) => t.metadata?.investigationFingerprint === 'fp-1' && t.status !== 'completed'
+ );
+ expect(open).toHaveLength(1);
+ }
+ });
+
+ it('unions affectedTasks by id (no duplicates)', () => {
+ const local = [inv('sys-a', 'pending', 'fp-1', { affectedTasks: ['task-1', 'task-2'] })];
+ const remote = [inv('sys-b', 'pending', 'fp-1', { affectedTasks: ['task-2', 'task-3'] })];
+ const merged = mergeTaskLists(local, remote, { now: NOW });
+ const survivor = merged.find((t) => t.id === 'sys-a');
+ expect(survivor.metadata.affectedTasks).toEqual(['task-1', 'task-2', 'task-3']);
+ });
+
+ it('never orphans an in-flight investigation: a live-leased loser survives over a lower idle id', () => {
+ // The lower id (sys-a) is idle; the higher id (sys-b) holds a live lease —
+ // an agent is actively investigating it. The live copy must survive so its
+ // execution is not orphaned, even though its id sorts later.
+ const local = [inv('sys-a', 'pending', 'fp-1', { affectedTasks: ['task-1'] })];
+ const remote = [
+ inv('sys-b', 'in_progress', 'fp-1', { affectedTasks: ['task-2'], metadata: liveClaim('instance-B') }),
+ ];
+ const merged = mergeTaskLists(local, remote, { now: NOW });
+ const byId = Object.fromEntries(merged.map((t) => [t.id, t]));
+ expect(byId['sys-b'].status).toBe('in_progress');
+ expect(byId['sys-b'].metadata.claimedBy).toBe('instance-B');
+ expect(byId['sys-b'].metadata.affectedTasks).toEqual(['task-1', 'task-2']);
+ expect(byId['sys-a'].status).toBe('completed');
+ expect(byId['sys-a'].metadata.supersededBy).toBe('sys-b');
+ });
+
+ it('does NOT collapse when both copies hold a live lease (two in-flight agents)', () => {
+ // Sub-second claim race: both peers spawned. Killing either orphans a running
+ // agent, so the collapse is skipped this sweep — the group self-heals as each
+ // investigation completes (turns terminal) and drops out of the open set.
+ const local = [inv('sys-a', 'in_progress', 'fp-1', { metadata: liveClaim('instance-A') })];
+ const remote = [inv('sys-b', 'in_progress', 'fp-1', { metadata: liveClaim('instance-B') })];
+ const merged = mergeTaskLists(local, remote, { now: NOW });
+ const open = merged.filter((t) => t.status === 'in_progress');
+ expect(open.map((t) => t.id).sort()).toEqual(['sys-a', 'sys-b']);
+ });
+
+ it('does not collapse a single open investigation (no duplicate)', () => {
+ const local = [inv('sys-a', 'pending', 'fp-1', { affectedTasks: ['task-1'] })];
+ const merged = mergeTaskLists(local, [], { now: NOW });
+ expect(merged).toHaveLength(1);
+ expect(merged[0].status).toBe('pending');
+ expect(merged[0].metadata.supersededBy).toBeUndefined();
+ });
+
+ it('does not collapse investigations with DIFFERENT fingerprints', () => {
+ const local = [inv('sys-a', 'pending', 'fp-1')];
+ const remote = [inv('sys-b', 'pending', 'fp-2')];
+ const merged = mergeTaskLists(local, remote, { now: NOW });
+ expect(merged.every((t) => t.status === 'pending')).toBe(true);
+ });
+
+ it('ignores non-investigation tasks (no fingerprint) entirely', () => {
+ const local = [task('task-a', 'pending'), task('task-b', 'pending')];
+ const merged = mergeTaskLists(local, [], { now: NOW });
+ expect(merged.every((t) => t.status === 'pending')).toBe(true);
+ expect(merged.every((t) => t.metadata.supersededBy === undefined)).toBe(true);
+ });
+
+ it('is idempotent — re-merging the collapsed result changes nothing', () => {
+ const local = [inv('sys-a', 'pending', 'fp-1', { affectedTasks: ['task-1'] })];
+ const remote = [inv('sys-b', 'pending', 'fp-1', { affectedTasks: ['task-2'] })];
+ const once = mergeTaskLists(local, remote, { now: NOW });
+ const twice = mergeTaskLists(once, [], { now: NOW });
+ expect(twice).toEqual(once);
+ });
+
+ it('re-folds affectedTasks onto the survivor after a partial per-id revert', () => {
+ // Mid-propagation, a peer can hold the survivor with a stale (partial)
+ // affectedTasks while a terminal `supersededBy` sibling records the collapse.
+ // The pass must re-fold the full union rather than leave the survivor partial.
+ const partialSurvivor = inv('sys-a', 'pending', 'fp-1', { affectedTasks: ['task-1'] });
+ const supersededSibling = inv('sys-b', 'completed', 'fp-1', {
+ affectedTasks: ['task-2'],
+ metadata: { supersededBy: 'sys-a' },
+ });
+ const merged = mergeTaskLists([partialSurvivor, supersededSibling], [], { now: NOW });
+ const survivor = merged.find((t) => t.id === 'sys-a');
+ expect(survivor.metadata.affectedTasks).toEqual(['task-1', 'task-2']);
+ });
+ });
});