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

harden LI verdict federation: durable record-level idempotency + broader stamp coverage (#2779)

[._.]/ Adam Eivy4d67fa8a0b0f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7da9c25f80..6bb478efdc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,7 +6,7 @@
## Federation
-- [issue-2779] Layered Intelligence proposal-execution outcomes now federate back to the peer that filed the proposal. A CoS hand-off task filed on one machine can be claimed and executed on another (task federation, #1712/#1714), but the per-proposal execution outcome (#2765) was only recorded into the machine that ran the agent — its `li-outcomes` collection isn't federated, so the originating machine's execution awareness never reflected a proposal a peer implemented. The executing machine now stamps the execution verdict into the completed hand-off task's federated metadata, and when that terminal state syncs back the originating machine derives the outcome from it — so its per-domain "how reliably do my own hand-offs get implemented" signal now reflects cross-peer executions. The verdict is recorded once (only on a non-terminal→terminal adoption) and only by the machine that actually filed the proposal, so a third sync peer that merely adopts the finished task records nothing. `li-outcomes` stays local; the verdict rides the already-federated task as additive metadata (no schema-version bump).
+- [issue-2779] Layered Intelligence proposal-execution outcomes now federate back to the peer that filed the proposal. A CoS hand-off task filed on one machine can be claimed and executed on another (task federation, #1712/#1714), but the per-proposal execution outcome (#2765) was only recorded into the machine that ran the agent — its `li-outcomes` collection isn't federated, so the originating machine's execution awareness never reflected a proposal a peer implemented. The executing machine now stamps the execution verdict (with its completion time) into the completed hand-off task's federated metadata, and when that terminal state syncs back the originating machine derives the outcome from it — so its per-domain "how reliably do my own hand-offs get implemented" signal now reflects cross-peer executions. Only the machine that actually filed the proposal records it (a third sync peer that merely adopts the finished task records nothing), and recording is durably idempotent: a re-synced terminal task is a no-op while a genuinely re-executed (newer) hand-off overwrites, so the outcome converges even across a crash or a peer that stored the terminal task before upgrading. `li-outcomes` stays local; the verdict rides the already-federated task as additive metadata (no schema-version bump).
- [issue-2628] Same-cause auto-investigation tasks no longer pile up across federated machines. The per-machine "one open investigation per failure fingerprint" guard couldn't see a second machine that minted its own investigation for the same cause before the next sync, so both survived the peer merge. The CoS task merge now collapses same-fingerprint OPEN investigations to a single active row: it keeps the older copy (or, if one is already being worked, the in-progress copy so a running investigation is never cut off), folds every duplicate's list of blocked tasks onto the survivor, and marks the others done rather than deleting them (so the collapse converges the same way on every peer). Two machines that each opened an investigation for one failure now settle on one.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 83fe6a89dc..971cd2ce6b 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -973,6 +973,44 @@ export function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOO
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
+/**
+ * Stamp an LI hand-off's per-proposal execution verdict into a completion `taskUpdate`'s
+ * federated metadata (#2779), mutating `taskUpdate.metadata` in place. Shared by every
+ * agent-completion path that marks an LI hand-off task terminal — finalizeAgent (the main
+ * path) AND the post-restart recovery path in handleAgentCompletion — so a hand-off that
+ * completes through a bypass still federates its outcome to the originating peer (codex P2);
+ * without this only finalizeAgent-completed hand-offs would ever reach peer A.
+ *
+ * `buildLiExecutionVerdict` reuses the exact validation-authoritative outcome + environmental
+ * gate the LOCAL #2765 write uses, so both peers record the identical verdict; a non-hand-off
+ * task (no `liProposal`) or an environmental completion yields null (no stamp). Best-effort
+ * and defensive (runs outside the request lifecycle): a lazy-import/build failure logs and
+ * leaves `taskUpdate` unstamped rather than throwing into the completion path. Lazy imports
+ * keep the taskLearning/LI graphs off agentLifecycle's static chain.
+ *
+ * @param {object} taskUpdate the update object about to be passed to updateTask (mutated)
+ * @param {object} task the persisted task (carries `metadata.liProposal` when a hand-off)
+ * @param {{ success:boolean, validationPassed?:boolean|null, errorAnalysis?:object|null }} signals
+ * @returns {Promise<object>} the same `taskUpdate` (stamped when applicable)
+ */
+async function stampLiExecutionVerdict(taskUpdate, task, { success, validationPassed = null, errorAnalysis = null } = {}) {
+ const liProposal = task?.metadata?.liProposal || null;
+ if (!liProposal) return taskUpdate;
+ try {
+ const [{ buildLiExecutionVerdict }, { LI_EXECUTION_VERDICT_KEY }] = await Promise.all([
+ import('./taskLearning/metrics.js'),
+ import('./layeredIntelligenceOutcomes.js')
+ ]);
+ const verdict = buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis, executedAt: new Date().toISOString() });
+ if (verdict) {
+ taskUpdate.metadata = { ...(taskUpdate.metadata || {}), [LI_EXECUTION_VERDICT_KEY]: verdict };
+ }
+ } catch (err) {
+ emitLog('warn', `⚠️ Failed to stamp LI execution verdict for task ${task?.id}: ${err.message}`, { taskId: task?.id });
+ }
+ return taskUpdate;
+}
+
/**
* Shared end-of-run state writes for all three spawn paths
* (`handleAgentCompletion` runner-mode, TUI `finish`, direct-CLI `close`).
@@ -1080,26 +1118,12 @@ export async function finalizeAgent({
await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);
}
- // LI hand-off execution verdict (#2779): stamp the per-proposal execution outcome
- // into the task's FEDERATED metadata as part of this completion write, so the
- // originating peer (which filed the proposal and runs LI for that app) can derive
- // `recordProposalExecution` from the terminal synced task — cross-peer parity for the
- // #2765 LOCAL write, which only lands on the peer that ran the agent. `buildLiExecutionVerdict`
- // reuses the exact validation-authoritative outcome + environmental gate the local write
- // uses, so both peers record the identical verdict; a non-hand-off/environmental completion
- // yields null (no stamp). Lazy imports keep the taskLearning/LI graphs off finalize's
- // static chain. `updateTask` merges metadata, so this composes with `taskUpdate`.
- const liProposal = task?.metadata?.liProposal || null;
- if (liProposal) {
- const [{ buildLiExecutionVerdict }, { LI_EXECUTION_VERDICT_KEY }] = await Promise.all([
- import('./taskLearning/metrics.js'),
- import('./layeredIntelligenceOutcomes.js')
- ]);
- const verdict = buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis });
- if (verdict) {
- taskUpdate.metadata = { ...(taskUpdate.metadata || {}), [LI_EXECUTION_VERDICT_KEY]: verdict };
- }
- }
+ // LI hand-off execution verdict (#2779): stamp the per-proposal execution outcome into
+ // the task's FEDERATED metadata as part of this completion write, so the originating peer
+ // (which filed the proposal and runs LI for that app) can derive `recordProposalExecution`
+ // from the terminal synced task — cross-peer parity for the #2765 LOCAL write, which only
+ // lands on the peer that ran the agent.
+ await stampLiExecutionVerdict(taskUpdate, task, { success, validationPassed, errorAnalysis });
const taskResult = await updateTask(task.id, taskUpdate, taskType);
if (taskResult?.error) {
@@ -1297,7 +1321,12 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
const task = await getTaskById(cosAgent.taskId).catch(() => null);
if (task && task.status !== 'completed') {
if (success) {
- await updateTask(cosAgent.taskId, { status: 'completed' }, task.taskType || 'user');
+ // Stamp the LI hand-off verdict here too (#2779, codex P2) — this post-restart
+ // recovery bypasses finalizeAgent, so without it a hand-off that finished while
+ // the server was down would never federate its outcome. Only `success` is known
+ // on this path (no validationPassed/errorAnalysis), so it records a clean success.
+ const taskUpdate = await stampLiExecutionVerdict({ status: 'completed' }, task, { success });
+ await updateTask(cosAgent.taskId, taskUpdate, task.taskType || 'user');
} else {
// Import handleOrphanedTask dynamically to avoid circular dep with agentManagement
const { handleOrphanedTask } = await import('./agentManagement.js');
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 73967d7b43..255480c24e 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -249,14 +249,30 @@ describe('agentLifecycle — guard wiring', () => {
const updateIdx = AGENT_LIFECYCLE_SRC.indexOf('await updateTask(task.id, taskUpdate, taskType)', idx);
expect(updateIdx, 'finalizeAgent must persist the task via updateTask').toBeGreaterThan(idx);
const body = AGENT_LIFECYCLE_SRC.slice(idx, updateIdx);
- // Verdict is derived from the persisted task's liProposal marker via the shared
- // builder (parity with the local #2765 write) and merged into taskUpdate.metadata
- // under LI_EXECUTION_VERDICT_KEY — BEFORE the updateTask call, so it federates in
- // the same write that marks the task terminal.
+ // The verdict is stamped into taskUpdate via the shared helper BEFORE the updateTask
+ // call, so it federates in the same write that marks the task terminal.
+ expect(body).toMatch(/await stampLiExecutionVerdict\(taskUpdate, task, \{ success, validationPassed, errorAnalysis \}\)/);
+ });
+
+ it('stampLiExecutionVerdict builds the verdict from the task liProposal marker via the shared builder (#2779)', () => {
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('async function stampLiExecutionVerdict');
+ expect(idx, 'stampLiExecutionVerdict must exist').toBeGreaterThan(-1);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1500);
+ // Derived from the persisted task's liProposal marker via the shared builder (parity
+ // with the local #2765 write) and merged into taskUpdate.metadata under the verdict key.
expect(body).toMatch(/task\?\.metadata\?\.liProposal/);
expect(body).toMatch(/buildLiExecutionVerdict\(/);
expect(body).toMatch(/\[LI_EXECUTION_VERDICT_KEY\]:\s*verdict/);
});
+
+ it('the post-restart recovery completion path also stamps the LI verdict (#2779, codex P2)', () => {
+ // A hand-off that finished while the server was down completes via this bypass, not
+ // finalizeAgent — it must still stamp so the outcome federates to the originating peer.
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('Completing untracked agent');
+ expect(idx, 'post-restart recovery branch must exist').toBeGreaterThan(-1);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1200);
+ expect(body).toMatch(/await stampLiExecutionVerdict\(\{ status: 'completed' \}, task, \{ success \}\)/);
+ });
});
// ─── Non-negotiable orderings inside runAgentSpawn (no behavioral seam) ──────
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 4c90253813..fe33e963f1 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -513,7 +513,7 @@ export async function reviveBlockedTask(taskId, { priority, metadata } = {}, tas
* @returns {Promise<{ changed: boolean, count?: number }>}
*/
export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() } = {}) {
- const { changed, count, merged, localTerminalIds } = await withStateLock(async () => {
+ const { changed, count, merged } = await withStateLock(async () => {
const state = await loadState();
const filePath = taskType === 'user'
? join(ROOT_DIR, state.config.userTasksFile)
@@ -528,38 +528,35 @@ export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() }
const includeApprovalFlags = taskType === 'internal';
const localMarkdown = generateTasksMarkdown(localTasks, includeApprovalFlags);
const mergedMarkdown = generateTasksMarkdown(merged, includeApprovalFlags);
- // Nothing the peer sent changed our state — skip the write (and the event
- // that would wake the scheduler) so a steady-state sweep is a pure no-op.
- if (mergedMarkdown === localMarkdown) return { changed: false };
+ // Nothing the peer sent changed our state — skip the write (and the event that would
+ // wake the scheduler). `merged` is still returned so the post-lock LI-verdict consume
+ // (#2779) can run even on a no-op sweep — durability requires it (an old peer that
+ // stored a terminal verdict before upgrading, or a crash before a prior consume, leaves
+ // the task terminal with the merge producing no change, so a changed-only consume would
+ // never catch up). Re-offering is cheap: the consumer is a durable no-op after the first.
+ if (mergedMarkdown === localMarkdown) return { changed: false, merged };
await writeFile(filePath, mergedMarkdown);
cosEvents.emit('tasks:changed', { type: taskType, action: 'peer-merged' });
- // Return the merged set + which local ids were ALREADY terminal so the post-lock
- // LI-verdict consume (#2779) can spot non-terminal→terminal adoptions. Kept out of
- // the lock — recordProposalExecution touches a different store (li-outcomes), and
- // the LI import graph stays off cosTaskStore's static chain (lazy below).
- const localTerminalIds = localTasks.filter(t => t && isTerminalTaskStatus(t.status)).map(t => t.id);
- return { changed: true, count: merged.length, merged, localTerminalIds };
+ return { changed: true, count: merged.length, merged };
});
- // Post-lock, best-effort: derive recordProposalExecution from each hand-off task that
- // this merge just ADOPTED into a terminal state carrying an LI execution verdict (#2779) —
- // a task filed here but executed on a peer, whose terminal state (with the stamped
- // LI_EXECUTION_VERDICT_KEY) has now synced back. The non-terminal→terminal transition is
- // the idempotency guard: the next sweep sees the task already terminal locally and skips
- // it, so a repeatedly-synced completion is consumed exactly once. `requireExisting` inside
- // the consumer scopes the write to a proposal THIS peer filed, so a non-originating peer
- // that also adopts the task is a no-op.
- if (changed) {
- const { LI_EXECUTION_VERDICT_KEY, recordProposalExecutionFromVerdict } = await import('./layeredIntelligenceOutcomes.js');
- const alreadyTerminal = new Set(localTerminalIds);
- const verdicts = merged
- .filter(t => isTerminalTaskStatus(t?.status) && t?.metadata?.[LI_EXECUTION_VERDICT_KEY] && !alreadyTerminal.has(t.id))
- .map(t => t.metadata[LI_EXECUTION_VERDICT_KEY]);
- for (const verdict of verdicts) {
- await recordProposalExecutionFromVerdict(verdict)
- .catch(err => console.error(`❌ 📚 cosTaskStore: failed to consume LI execution verdict: ${err.message}`));
- }
+ // Post-lock, best-effort: derive recordProposalExecution from every terminal hand-off task
+ // carrying an LI execution verdict (#2779) — a task filed here but executed on a peer, whose
+ // terminal state (with the stamped LI_EXECUTION_VERDICT_KEY) has synced back. Runs on EVERY
+ // sweep (changed or not); idempotency + retry-correctness are durable and record-level in the
+ // consumer (skips a verdict no newer than the stored execution), so re-offering the same
+ // verdict is a no-op while a genuinely re-executed hand-off overwrites. `requireExisting`
+ // there scopes the write to a proposal THIS peer filed, so a non-originating peer is a no-op.
+ // Kept out of the lock — recordProposalExecution touches a different store (li-outcomes) — and
+ // the LI import graph stays off cosTaskStore's static chain (lazy import).
+ const { LI_EXECUTION_VERDICT_KEY, recordProposalExecutionFromVerdict } = await import('./layeredIntelligenceOutcomes.js');
+ for (const task of merged || []) {
+ if (!isTerminalTaskStatus(task?.status)) continue;
+ const verdict = task?.metadata?.[LI_EXECUTION_VERDICT_KEY];
+ if (!verdict) continue;
+ await recordProposalExecutionFromVerdict(verdict)
+ .catch(err => console.error(`❌ 📚 cosTaskStore: failed to consume LI execution verdict: ${err.message}`));
}
return changed ? { changed, count } : { changed: false };
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index aefbebb9ef..91647a0668 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -717,7 +717,7 @@ describe('cosTaskStore.mergePeerTasks', () => {
beforeEach(() => { mock.liVerdicts = []; });
- it('derives recordProposalExecution when a terminal hand-off verdict is newly adopted', async () => {
+ it('derives recordProposalExecution when a terminal hand-off verdict is adopted', async () => {
// Peer A holds the task in_progress (it filed + handed it off); peer B executed it
// and its terminal state syncs back carrying the stamped verdict.
await addTask({ description: 'implement LI proposal', id: 'task-handoff', priority: 'HIGH' }, 'internal');
@@ -728,17 +728,18 @@ describe('cosTaskStore.mergePeerTasks', () => {
expect(mock.liVerdicts[0]).toMatchObject({ appId: 'app-x', slug: 'add-metrics', success: true });
});
- it('consumes exactly once — a re-sync of the already-terminal task does not re-record', async () => {
+ it('re-offers the terminal verdict on EVERY sweep, including a no-op (durability replay, codex P2)', async () => {
+ // The consumer owns durable, record-level idempotency, so mergePeerTasks re-offers every
+ // terminal verdict each sweep — this catches a verdict a crash (or an old peer that stored
+ // the terminal task before upgrading) left unconsumed, which a changed-only consume would
+ // miss because the merge produces no change once the task is already terminal locally.
await addTask({ description: 'implement LI proposal', id: 'task-handoff', priority: 'HIGH' }, 'internal');
- await updateTask('task-handoff', { status: 'in_progress' }, 'internal');
- await mergePeerTasks('internal', handoff('completed'), { now: NOW }); // adoption → consume
- expect(mock.liVerdicts).toHaveLength(1);
+ await updateTask('task-handoff', { status: 'completed', metadata: { liExecution: verdict } }, 'internal');
mock.liVerdicts = [];
- // Re-sync the same completed task. The local copy is ALREADY terminal, so the
- // non-terminal→terminal adoption never re-fires — the verdict is not re-consumed
- // even if an unrelated re-serialization flips `changed`.
- await mergePeerTasks('internal', handoff('completed'), { now: NOW });
- expect(mock.liVerdicts).toHaveLength(0);
+ const res = await mergePeerTasks('internal', handoff('completed'), { now: NOW });
+ expect(res.changed).toBe(false); // already terminal locally → no file write
+ expect(mock.liVerdicts).toHaveLength(1); // …but the verdict is still re-offered
+ expect(mock.liVerdicts[0]).toMatchObject({ appId: 'app-x', slug: 'add-metrics' });
});
it('ignores a stale verdict on a NON-terminal synced task', async () => {
diff --git a/server/services/layeredIntelligenceHandoffFederation.test.js b/server/services/layeredIntelligenceHandoffFederation.test.js
index afa7e09f30..d36a6b7716 100644
--- a/server/services/layeredIntelligenceHandoffFederation.test.js
+++ b/server/services/layeredIntelligenceHandoffFederation.test.js
@@ -66,18 +66,25 @@ describe('buildLiExecutionVerdict (#2779) — the executing peer stamp', () => {
expect(buildLiExecutionVerdict({ liProposal: { slug: 's' }, success: true })).toBeNull();
});
- it('carries the proposal identity + domain and a clean-exit success', () => {
- const v = buildLiExecutionVerdict({ liProposal: proposal, success: true });
+ it('carries the proposal identity + domain, a clean-exit success, and the execution time', () => {
+ const v = buildLiExecutionVerdict({ liProposal: proposal, success: true, executedAt: '2026-07-20T10:00:00.000Z' });
expect(v).toEqual({
appId: 'app-x',
slug: 'Add Metrics',
scope: 'refactor',
success: true,
errorCategory: null,
- validationPassed: null
+ validationPassed: null,
+ executedAt: '2026-07-20T10:00:00.000Z'
});
});
+ it('defaults executedAt to a timestamp when the caller omits it', () => {
+ const v = buildLiExecutionVerdict({ liProposal: proposal, success: true });
+ expect(typeof v.executedAt).toBe('string');
+ expect(Number.isFinite(Date.parse(v.executedAt))).toBe(true);
+ });
+
it('is validation-authoritative — a declared verdict overrides the exit code (#2344)', () => {
// commit-found run: raw exit-code success=false but the criterion passed.
const passed = buildLiExecutionVerdict({ liProposal: proposal, success: false, validationPassed: true });
@@ -196,6 +203,35 @@ describe('recordProposalExecutionFromVerdict (#2779) — the originating peer de
expect(awareness).toContain('refactor');
});
+ it('is a durable no-op when the same verdict re-syncs (idempotency, codex P2)', async () => {
+ await recordFiledProposal({ appId: 'app-x', slug: 'add-metrics', scope: 'refactor' }, store);
+ const verdict = { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: true, executedAt: '2026-07-20T10:00:00.000Z' };
+ expect(await recordProposalExecutionFromVerdict(verdict, store)).toBe(true);
+ const [first] = await listOutcomes({ appId: 'app-x' }, store);
+ expect(first.executionOutcome).toBe('success');
+ // Re-offering the identical verdict (the merge re-scans terminal tasks every sweep) does
+ // NOT rewrite — the stored execution is not older than the incoming one.
+ expect(await recordProposalExecutionFromVerdict(verdict, store)).toBe(false);
+ const [again] = await listOutcomes({ appId: 'app-x' }, store);
+ expect(again.executionAt).toBe(first.executionAt); // unchanged, no churn
+ });
+
+ it('overwrites with a genuinely NEWER (re-executed) verdict — latest wins (parity)', async () => {
+ await recordFiledProposal({ appId: 'app-x', slug: 'add-metrics', scope: 'refactor' }, store);
+ // First hand-off failed on a peer.
+ expect(await recordProposalExecutionFromVerdict(
+ { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: false, errorCategory: 'test-failure', executedAt: '2026-07-20T10:00:00.000Z' },
+ store
+ )).toBe(true);
+ expect((await listOutcomes({ appId: 'app-x' }, store))[0].executionOutcome).toBe('failure');
+ // Re-executed later and passed — a newer executedAt overwrites the stale failure.
+ expect(await recordProposalExecutionFromVerdict(
+ { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: true, executedAt: '2026-07-20T12:00:00.000Z' },
+ store
+ )).toBe(true);
+ expect((await listOutcomes({ appId: 'app-x' }, store))[0].executionOutcome).toBe('success');
+ });
+
it('records a cross-peer FAILURE so a failing domain surfaces to A', async () => {
await recordFiledProposal({ appId: 'app-x', slug: 'flaky-thing', scope: 'testing' }, store);
const verdict = buildLiExecutionVerdict({
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index a37598bc54..3c52fb49ae 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -216,10 +216,15 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe
* nothing about the domain — same gate as #2618); this helper records whatever it is
* given.
*/
-export async function recordProposalExecution({ appId, slug, scope = null, success, errorCategory = null, validationPassed = null, requireExisting = false, now = Date.now() } = {}, store = outcomesStore()) {
+export async function recordProposalExecution({ appId, slug, scope = null, success, errorCategory = null, validationPassed = null, requireExisting = false, executedAt = null, now = Date.now() } = {}, store = outcomesStore()) {
const normSlug = normalizeSlug(slug);
if (!appId || !normSlug || typeof success !== 'boolean') return false;
const id = outcomeId(appId, normSlug);
+ // The execution's completion time. For the federated consume it rides the verdict
+ // (`executedAt`) so idempotency/retry can compare it against the stored record; the
+ // local #2765 path passes none and uses `now`. Stored as `executionAt` either way.
+ const executionAtIso = (typeof executedAt === 'string' && executedAt) ? executedAt : new Date(now).toISOString();
+ const executionAtMs = Date.parse(executionAtIso);
// The domain to adopt when we don't already have one — the load-bearing field for
// per-domain aggregation. Normalized once and reused by both the missing-record
// fallback and the scope-preservation merge below.
@@ -251,6 +256,19 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe
// (never filed it) has no record, so `requireExisting` makes it a no-op there
// instead of minting a stray minimal record on every full-sync peer.
if (!hasExisting && requireExisting) return false;
+ // Durable idempotency for the federated consume (#2779, codex P2): the record's own
+ // executionOutcome/executionAt IS the consumed-marker, so a re-synced terminal task is
+ // a no-op WITHOUT relying on the in-memory status transition (which a crash between the
+ // task-file write and this call, or an old peer that stored the terminal task before
+ // upgrading, would otherwise skip forever). Only skip when the stored execution is at
+ // least as new — a genuinely NEWER (re-executed) hand-off still overwrites, matching the
+ // local latest-wins. The marker lives in THIS peer's (unfederated) li-outcomes record, so
+ // one peer consuming never blocks another. Applies only to the federated path
+ // (requireExisting); the local write always overwrites, unchanged.
+ if (requireExisting && hasExisting && existing.executionOutcome && existing.executionAt) {
+ const storedMs = Date.parse(existing.executionAt);
+ if (Number.isFinite(storedMs) && Number.isFinite(executionAtMs) && executionAtMs <= storedMs) return false;
+ }
const base = hasExisting
? existing
: {
@@ -266,7 +284,7 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe
// the domain the completion hook passed (a missing-record fallback).
scope: (typeof base.scope === 'string' && base.scope.trim()) ? base.scope : normScope,
executionOutcome: success ? 'success' : 'failure',
- executionAt: new Date(now).toISOString(),
+ executionAt: executionAtIso,
// Set the failure diagnosis (#2764 §1) unconditionally so a success overwrites
// any stale failure fields from a prior failed run that later re-ran and passed.
failureCategory,
@@ -289,17 +307,20 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe
*
* `requireExisting: true` — A only records for a proposal it actually FILED (it has the
* li-outcomes record); a third full-sync peer that merely adopts the terminal task never
- * mints a stray record. Idempotency is owned by the CALLER (cosTaskStore.mergePeerTasks
- * only consumes on a non-terminal→terminal adoption, once per task), so a task re-syncing
- * doesn't re-record. Pure input validation (a hand-corrupt/foreign verdict is dropped);
- * best-effort like the sibling recorders (never throws into the merge path).
+ * mints a stray record. Idempotency is DURABLE and record-level: recordProposalExecution
+ * skips a verdict no newer than the stored executionAt, so mergePeerTasks can safely re-offer
+ * every terminal verdict on every sweep (surviving a crash between the task-file write and the
+ * consume, or an older peer that stored the terminal task before upgrading) while a re-sync
+ * stays a no-op and a genuinely re-executed hand-off (newer `executedAt`) still overwrites.
+ * Pure input validation (a hand-corrupt/foreign verdict is dropped); best-effort like the
+ * sibling recorders (never throws into the merge path).
*/
export async function recordProposalExecutionFromVerdict(verdict, store = outcomesStore()) {
if (!verdict || typeof verdict !== 'object' || Array.isArray(verdict)) return false;
- const { appId, slug, scope = null, success, errorCategory = null, validationPassed = null } = verdict;
+ const { appId, slug, scope = null, success, errorCategory = null, validationPassed = null, executedAt = null } = verdict;
if (typeof success !== 'boolean') return false;
return recordProposalExecution(
- { appId, slug, scope, success, errorCategory, validationPassed, requireExisting: true },
+ { appId, slug, scope, success, errorCategory, validationPassed, executedAt, requireExisting: true },
store
);
}
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 83b45f56c4..30a0d8353b 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -337,12 +337,19 @@ function deriveLiExecutionPayload(task, success, { errorCategory = null, validat
* write. Returns null for a non-hand-off task (no `liProposal`) or a proposal missing its
* (appId, slug) identity. Pure.
*
+ * `executedAt` (ISO) stamps WHEN this execution completed. It rides the verdict so the
+ * originating peer's consume can be durably idempotent AND retry-correct: it records only
+ * when its li-outcomes record has no execution yet OR this verdict is NEWER than the stored
+ * one (a re-synced terminal task is a no-op; a genuinely re-executed hand-off overwrites,
+ * matching the local latest-wins). Defaults to now so a caller that omits it still gets a
+ * usable stamp.
+ *
* @param {{ liProposal?:object|null, success?:boolean, validationPassed?:boolean|null,
- * errorAnalysis?:{category?:string|null, origin?:string|null}|null }} args
+ * errorAnalysis?:{category?:string|null, origin?:string|null}|null, executedAt?:string }} args
* @returns {{ appId:string, slug:string, scope:string|null, success:boolean,
- * errorCategory:string|null, validationPassed:boolean|null } | null}
+ * errorCategory:string|null, validationPassed:boolean|null, executedAt:string } | null}
*/
-export function buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis } = {}) {
+export function buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis, executedAt } = {}) {
if (!liProposal || typeof liProposal !== 'object' || Array.isArray(liProposal)) return null;
if (!liProposal.appId || !liProposal.slug) return null;
const vp = typeof validationPassed === 'boolean' ? validationPassed : null;
@@ -358,7 +365,8 @@ export function buildLiExecutionVerdict({ liProposal, success, validationPassed,
scope: liProposal.scope ?? null,
success: outcomeSuccess,
errorCategory,
- validationPassed: vp
+ validationPassed: vp,
+ executedAt: typeof executedAt === 'string' && executedAt ? executedAt : new Date().toISOString()
};
}