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
feat: federate LI proposal-execution verdict via terminal synced task (#2779)
[._.]/ Adam Eivy03b7a88b5efa
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 41c47162e5..7da9c25f80 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,8 @@## 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-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.## Layered Intelligence rejection diagnosisdiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 9d0d1f23ad..83fe6a89dc 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1080,6 +1080,27 @@ 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 };+ }+ }+const taskResult = await updateTask(task.id, taskUpdate, taskType);if (taskResult?.error) {const label = terminatedByUser ? 'blocked' : success ? 'completed' : 'failed';diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex b629549d0e..73967d7b43 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -242,6 +242,21 @@ describe('agentLifecycle — guard wiring', () => {const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 60_000);expect(body).toMatch(/withMapEntryCleanup\(\s*runnerAgents\s*,\s*agentId\s*,/);});++ it('finalizeAgent stamps the LI execution verdict into the completion task write (#2779)', () => {+ const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function finalizeAgent');+ expect(idx, 'finalizeAgent must exist').toBeGreaterThan(-1);+ 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.+ expect(body).toMatch(/task\?\.metadata\?\.liProposal/);+ expect(body).toMatch(/buildLiExecutionVerdict\(/);+ expect(body).toMatch(/\[LI_EXECUTION_VERDICT_KEY\]:\s*verdict/);+ });});// ─── Non-negotiable orderings inside runAgentSpawn (no behavioral seam) ──────diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex bb1ff0121c..4c90253813 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -40,6 +40,12 @@ export const PRIORITY_VALUES = {const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);+// A task is terminal once it is completed or blocked — the same set cosTaskMerge's+// release-on-transition uses. Consumed by the LI cross-peer verdict consume (#2779) to+// spot a non-terminal→terminal ADOPTION (a failed hand-off blocks, a clean one completes;+// both are legitimate execution outcomes worth recording).+const isTerminalTaskStatus = (status) => status === 'completed' || status === 'blocked';+// Legacy fields an `updateTask` patch may carry directly (vs nested under// `metadata`); they're normalized into `metadata` on write. Listed once so the// content-edit detector and the normalizer below can't drift apart.@@ -507,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() } = {}) {- return withStateLock(async () => {+ const { changed, count, merged, localTerminalIds } = await withStateLock(async () => {const state = await loadState();const filePath = taskType === 'user'? join(ROOT_DIR, state.config.userTasksFile)@@ -528,8 +534,35 @@ export async function mergePeerTasks(taskType, remoteTasks, { now = Date.now() }await writeFile(filePath, mergedMarkdown);cosEvents.emit('tasks:changed', { type: taskType, action: 'peer-merged' });- return { changed: true, count: merged.length };+ // 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 };});++ // 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}`));+ }+ }++ return changed ? { changed, count } : { changed: false };}/**diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 7a93658104..aefbebb9ef 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -21,7 +21,9 @@ const mock = vi.hoisted(() => ({// Controls the mocked codeReview.js for resolveTaskChallengeWithRecheck (#2471).review: { ok: true, findings: 'No findings.' },reviewDefaults: { lmstudioModel: 'default-lmstudio', ollamaModel: 'default-ollama' },- reviewCalls: []+ reviewCalls: [],+ // Captures cross-peer LI execution verdicts consumed by mergePeerTasks (#2779).+ liVerdicts: []}));// existsSync is driven by the in-memory file map; readFileSync stays real so@@ -57,6 +59,15 @@ vi.mock('./codeReview.js', () => ({getCodeReviewDefaults: vi.fn(async () => mock.reviewDefaults)}));+// The LI cross-peer verdict consumer (#2779). Mocked so mergePeerTasks's post-lock+// consume never touches the real li-outcomes store, and so the tests can assert which+// verdicts were consumed. The key literal MUST mirror layeredIntelligenceOutcomes.js's+// LI_EXECUTION_VERDICT_KEY (a stamp/consume metadata contract).+vi.mock('./layeredIntelligenceOutcomes.js', () => ({+ LI_EXECUTION_VERDICT_KEY: 'liExecution',+ recordProposalExecutionFromVerdict: vi.fn(async (verdict) => { mock.liVerdicts.push(verdict); return true; })+}));+import {firstLine,PRIORITY_VALUES,@@ -692,6 +703,59 @@ describe('cosTaskStore.mergePeerTasks', () => {expect(adopted).toBeTruthy();expect(adopted.description).toBe('no metadata here');});++ describe('LI cross-peer execution verdict consume (#2779)', () => {+ const verdict = { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: true, errorCategory: null, validationPassed: null };+ const handoff = (status, extraMeta = {}) => ([{+ id: 'task-handoff',+ taskType: 'internal',+ status,+ priority: 'HIGH',+ description: 'implement LI proposal',+ metadata: { liExecution: verdict, ...extraMeta }+ }]);++ beforeEach(() => { mock.liVerdicts = []; });++ it('derives recordProposalExecution when a terminal hand-off verdict is newly 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');+ await updateTask('task-handoff', { status: 'in_progress' }, 'internal');+ const res = await mergePeerTasks('internal', handoff('completed'), { now: NOW });+ expect(res.changed).toBe(true);+ expect(mock.liVerdicts).toHaveLength(1);+ 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 () => {+ 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);+ 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);+ });++ it('ignores a stale verdict on a NON-terminal synced task', async () => {+ // A verdict riding a pending/in_progress task (e.g. a failed attempt that will+ // retry) is not a settled execution — only a terminal adoption is consumed.+ const res = await mergePeerTasks('internal', handoff('in_progress'), { now: NOW });+ expect(res.changed).toBe(true); // task adopted+ expect(mock.liVerdicts).toHaveLength(0);+ });++ it('does not consume a terminal task that carries no verdict', async () => {+ const remote = [{ id: 'plain-done', taskType: 'internal', status: 'completed', priority: 'LOW', description: 'unrelated', metadata: {} }];+ const res = await mergePeerTasks('internal', remote, { now: NOW });+ expect(res.changed).toBe(true);+ expect(mock.liVerdicts).toHaveLength(0);+ });+ });});describe('cosTaskStore — stale failure-artifact reaper (#2619)', () => {diff --git a/server/services/layeredIntelligenceHandoffFederation.test.js b/server/services/layeredIntelligenceHandoffFederation.test.jsnew file mode 100644index 0000000000..afa7e09f30--- /dev/null+++ b/server/services/layeredIntelligenceHandoffFederation.test.js@@ -0,0 +1,211 @@+/**+ * Cross-peer LI hand-off execution federation (#2779).+ *+ * A CoS LI hand-off task filed on peer A can be claimed and executed on peer B+ * (#1712/#1714). #2765 records the execution outcome (`recordProposalExecution`)+ * only into whichever peer RAN the agent, and the `li-outcomes` collection is NOT+ * federated — so the originating peer A never learned. Option 2 (the chosen+ * approach) routes the verdict via the already-federated task: the executing peer+ * stamps a small verdict into the terminal task's metadata (`buildLiExecutionVerdict`+ * → `LI_EXECUTION_VERDICT_KEY`), and when that terminal state syncs back A derives+ * `recordProposalExecution` from it (`recordProposalExecutionFromVerdict`, driven by+ * cosTaskStore.mergePeerTasks — covered in cosTaskStore.test.js).+ *+ * These tests cover the two pure/injectable seams of that route end to end:+ * 1. `buildLiExecutionVerdict` — the executing peer's stamp (parity with the local+ * write: validation-authoritative outcome + the #2618 environmental gate).+ * 2. `recordProposalExecutionFromVerdict` — the originating peer's derive, scoped by+ * `requireExisting` to a proposal THIS peer filed, feeding+ * `computeProposalExecutionAwareness` after the sync.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { createCollectionStore } from '../lib/collectionStore.js';+import { buildLiExecutionVerdict } from './taskLearning/metrics.js';+import {+ sanitizeOutcomeRecord,+ recordFiledProposal,+ recordProposalExecution,+ recordProposalExecutionFromVerdict,+ listOutcomes,+ LI_OUTCOMES_SCHEMA_VERSION,+ LI_EXECUTION_VERDICT_KEY+} from './layeredIntelligenceOutcomes.js';+import { computeExecutionByDomain, computeProposalExecutionAwareness } from './layeredIntelligence.js';++// Isolated store over a temp dir — never touches the real data/cos/li-outcomes.+let dir;+let store;+beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'li-handoff-fed-'));+ store = createCollectionStore({+ dir,+ type: 'li-outcomes',+ schemaVersion: LI_OUTCOMES_SCHEMA_VERSION,+ sanitizeRecord: sanitizeOutcomeRecord+ });+});+afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+});++describe('buildLiExecutionVerdict (#2779) — the executing peer stamp', () => {+ const proposal = { appId: 'app-x', slug: 'Add Metrics', scope: 'refactor' };++ it('returns null for a non-hand-off task (no liProposal)', () => {+ expect(buildLiExecutionVerdict({ liProposal: null, success: true })).toBeNull();+ expect(buildLiExecutionVerdict({ success: true })).toBeNull();+ expect(buildLiExecutionVerdict({ liProposal: [], success: true })).toBeNull();+ });++ it('returns null when the proposal is missing its (appId, slug) identity', () => {+ expect(buildLiExecutionVerdict({ liProposal: { appId: 'a' }, success: true })).toBeNull();+ 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 });+ expect(v).toEqual({+ appId: 'app-x',+ slug: 'Add Metrics',+ scope: 'refactor',+ success: true,+ errorCategory: null,+ validationPassed: null+ });+ });++ 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 });+ expect(passed.success).toBe(true);+ expect(passed.validationPassed).toBe(true);+ // clean exit that missed its declared criterion → a failure.+ const missed = buildLiExecutionVerdict({ liProposal: proposal, success: true, validationPassed: false });+ expect(missed.success).toBe(false);+ });++ it('applies the environmental gate (#2618) — a rate-limit says nothing about the domain', () => {+ const v = buildLiExecutionVerdict({+ liProposal: proposal,+ success: false,+ errorAnalysis: { category: 'rate-limit', origin: 'provider' }+ });+ expect(v).toBeNull();+ });++ it('records a genuine (non-environmental) failure with its error category', () => {+ const v = buildLiExecutionVerdict({+ liProposal: proposal,+ success: false,+ errorAnalysis: { category: 'test-failure', origin: 'runner' }+ });+ expect(v.success).toBe(false);+ expect(v.errorCategory).toBe('test-failure');+ });++ it('does not divert an output-scan false positive (parity with the local write, #2642)', () => {+ // An environmental category derived only from the output-text regex sweep is NOT+ // diverted — it may be a false positive, so it still counts as a real failure.+ const v = buildLiExecutionVerdict({+ liProposal: proposal,+ success: false,+ errorAnalysis: { category: 'rate-limit', origin: 'output-scan' }+ });+ expect(v).not.toBeNull();+ expect(v.success).toBe(false);+ });+});++describe('recordProposalExecution requireExisting (#2779)', () => {+ it('is a no-op on a peer that never filed the proposal (no minimal record minted)', async () => {+ const ok = await recordProposalExecution(+ { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: true, requireExisting: true },+ store+ );+ expect(ok).toBe(false);+ expect(await listOutcomes({ appId: 'app-x' }, store)).toEqual([]);+ });++ it('updates the existing FILED record on the originating peer', async () => {+ await recordFiledProposal({ appId: 'app-x', slug: 'add-metrics', scope: 'refactor' }, store);+ const ok = await recordProposalExecution(+ { appId: 'app-x', slug: 'add-metrics', success: true, requireExisting: true },+ store+ );+ expect(ok).toBe(true);+ const [rec] = await listOutcomes({ appId: 'app-x' }, store);+ expect(rec.executionOutcome).toBe('success');+ expect(rec.scope).toBe('refactor'); // filed scope preserved+ });++ it('still mints a minimal record when requireExisting is not set (local #2765 path)', async () => {+ const ok = await recordProposalExecution(+ { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: false },+ store+ );+ expect(ok).toBe(true);+ const [rec] = await listOutcomes({ appId: 'app-x' }, store);+ expect(rec.executionOutcome).toBe('failure');+ });+});++describe('recordProposalExecutionFromVerdict (#2779) — the originating peer derive', () => {+ it('drops a malformed / foreign verdict without writing', async () => {+ expect(await recordProposalExecutionFromVerdict(null, store)).toBe(false);+ expect(await recordProposalExecutionFromVerdict({ appId: 'a', slug: 's' }, store)).toBe(false); // no boolean success+ expect(await listOutcomes({ appId: 'a' }, store)).toEqual([]);+ });++ it('only records for a proposal THIS peer filed (requireExisting)', async () => {+ // Peer C adopted the terminal task but never filed the proposal → no record.+ const verdict = { appId: 'app-x', slug: 'add-metrics', scope: 'refactor', success: true };+ expect(await recordProposalExecutionFromVerdict(verdict, store)).toBe(false);+ expect(await listOutcomes({ appId: 'app-x' }, store)).toEqual([]);+ });++ it("reflects a peer-B execution in A's computeProposalExecutionAwareness after a sync", async () => {+ // Peer A filed three proposals in the same domain (min-sample for awareness).+ for (const slug of ['add-metrics', 'trim-logs', 'split-store']) {+ await recordFiledProposal({ appId: 'app-x', slug, scope: 'refactor' }, store);+ }+ // Peer B executed each hand-off and stamped a verdict onto the terminal task; A+ // derives each from the synced terminal task via the consumer.+ for (const slug of ['add-metrics', 'trim-logs', 'split-store']) {+ const verdict = buildLiExecutionVerdict({+ liProposal: { appId: 'app-x', slug, scope: 'refactor' },+ success: true+ });+ // Sanity: this is exactly what the wire metadata key carries.+ expect(LI_EXECUTION_VERDICT_KEY).toBe('liExecution');+ expect(await recordProposalExecutionFromVerdict(verdict, store)).toBe(true);+ }++ const outcomes = await listOutcomes({ appId: 'app-x' }, store);+ const byDomain = computeExecutionByDomain(outcomes);+ expect(byDomain.refactor.completed).toBe(3);+ expect(byDomain.refactor.succeeded).toBe(3);+ expect(byDomain.refactor.successRate).toBe(100);++ // The per-domain execution now surfaces in the reasoner-facing awareness text —+ // proof the cross-peer execution reached A's computeProposalExecutionAwareness.+ const awareness = computeProposalExecutionAwareness({ outcomes });+ expect(awareness).toContain('refactor');+ });++ 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({+ liProposal: { appId: 'app-x', slug: 'flaky-thing', scope: 'testing' },+ success: false,+ errorAnalysis: { category: 'test-failure', origin: 'runner' }+ });+ expect(await recordProposalExecutionFromVerdict(verdict, store)).toBe(true);+ const [rec] = await listOutcomes({ appId: 'app-x' }, store);+ expect(rec.executionOutcome).toBe('failure');+ expect(rec.scope).toBe('testing');+ });+});diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.jsindex cff77a3f5b..a37598bc54 100644--- a/server/services/layeredIntelligenceOutcomes.js+++ b/server/services/layeredIntelligenceOutcomes.js@@ -40,6 +40,19 @@ export const OUTCOME_RETENTION_MS = CLOSED_SUPPRESSION_MS;// changes the record directory shape (there is none yet).export const LI_OUTCOMES_SCHEMA_VERSION = 1;+// The federated-task metadata key that carries a hand-off's per-proposal EXECUTION+// verdict across peers (#2779). A CoS LI hand-off task filed on peer A can be claimed+// and executed on peer B; #2765 only records the outcome into whichever peer RAN the+// agent, so the originating peer never learns. The executing peer stamps this small+// verdict (the same payload `recordProposalExecution` consumes) into the terminal+// task's metadata; when that terminal state syncs back, the originating peer derives+// `recordProposalExecution` from it (see cosTaskStore.mergePeerTasks) so its+// `computeProposalExecutionAwareness` reflects the cross-peer execution. Kept local:+// the li-outcomes collection itself is NOT federated — only this verdict rides the+// already-federated task. Additive metadata on an existing federated task shape → no+// schema bump (the wire metadata record is permissive; the listHash covers it).+export const LI_EXECUTION_VERDICT_KEY = 'liExecution';+/*** Normalize one on-disk outcome record. Drops anything without a usable* appId+slug (the identity), coerces the outcome to a known value or null, and@@ -203,7 +216,7 @@ 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, now = Date.now() } = {}, store = outcomesStore()) {+export async function recordProposalExecution({ appId, slug, scope = null, success, errorCategory = null, validationPassed = null, requireExisting = false, now = Date.now() } = {}, store = outcomesStore()) {const normSlug = normalizeSlug(slug);if (!appId || !normSlug || typeof success !== 'boolean') return false;const id = outcomeId(appId, normSlug);@@ -230,7 +243,15 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe// rather than throwing into the completion hook.return store.queueRecordWrite(id, async () => {const existing = await store.loadOne(id).catch(() => null);- const base = existing && typeof existing === 'object'+ const hasExisting = existing && typeof existing === 'object';+ // Cross-peer consume gate (#2779): when the verdict arrives via a synced task+ // rather than a locally-run agent, ONLY the originating peer — the one that+ // filed the proposal and therefore already carries an li-outcomes record for+ // (app, slug) — should record it. A peer that merely ADOPTED the terminal task+ // (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;+ const base = hasExisting? existing: {appId, slug: normSlug, tracker: null, issueRef: null,@@ -259,6 +280,30 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe});}+/**+ * Derive `recordProposalExecution` from a hand-off task's federated EXECUTION verdict+ * (#2779) — the receiver side of the cross-peer loop. When a hand-off task that peer B+ * executed syncs its terminal state back to peer A (the originating peer), A calls this+ * with the `LI_EXECUTION_VERDICT_KEY` metadata the executing peer stamped, so A's+ * `computeProposalExecutionAwareness` reflects the execution B ran.+ *+ * `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).+ */+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;+ if (typeof success !== 'boolean') return false;+ return recordProposalExecution(+ { appId, slug, scope, success, errorCategory, validationPassed, requireExisting: true },+ store+ );+}+/*** Load this app's outcome records, GC-ing stale ones from disk so the store stays* bounded. GC mirrors the dedup window (isIssueWithinDedupWindow): an UNRESOLVEDdiff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.jsindex 47684a8c96..83b45f56c4 100644--- a/server/services/taskLearning/metrics.js+++ b/server/services/taskLearning/metrics.js@@ -318,6 +318,50 @@ function deriveLiExecutionPayload(task, success, { errorCategory = null, validat};}+/**+ * Build the cross-peer LI hand-off EXECUTION verdict (#2779) from a completing agent's+ * raw signals — the SAME small payload `recordProposalExecution` consumes, stamped by the+ * executing peer into the federated task metadata (LI_EXECUTION_VERDICT_KEY) so the+ * originating peer can derive the outcome from the terminal synced task.+ *+ * Exported (unlike the private `deriveLiExecutionPayload`) so the completion chokepoint in+ * agentLifecycle.finalizeAgent can stamp the verdict as part of the task's completion write+ * — the reconstructed-task learning hook there projects `taskLiProposal`, but the persisted+ * task carries `metadata.liProposal`, so this takes the proposal object directly to stay+ * agnostic to the field name.+ *+ * Parity with the LOCAL write: it computes the validation-authoritative `outcomeSuccess`+ * (a declared verdict overrides the exit code, #2344) and applies the SAME environmental+ * gate (#2618) the local recordTaskCompletion path uses — a rate-limit/outage says nothing+ * about the proposal's domain, so it yields null (no stamp) exactly as it yields no local+ * write. Returns null for a non-hand-off task (no `liProposal`) or a proposal missing its+ * (appId, slug) identity. Pure.+ *+ * @param {{ liProposal?:object|null, success?:boolean, validationPassed?:boolean|null,+ * errorAnalysis?:{category?:string|null, origin?:string|null}|null }} args+ * @returns {{ appId:string, slug:string, scope:string|null, success:boolean,+ * errorCategory:string|null, validationPassed:boolean|null } | null}+ */+export function buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis } = {}) {+ if (!liProposal || typeof liProposal !== 'object' || Array.isArray(liProposal)) return null;+ if (!liProposal.appId || !liProposal.slug) return null;+ const vp = typeof validationPassed === 'boolean' ? validationPassed : null;+ const outcomeSuccess = vp === null ? !!success : vp;+ const errorCategory = errorAnalysis?.category || null;+ // `?? null` (not `|| null`) preserves a malformed falsy origin ('') so the gate's+ // allowlist rejects it, mirroring recordTaskCompletion's handling (#2642).+ const errorOrigin = errorAnalysis?.origin ?? null;+ if (shouldDivertToEnvironmental(outcomeSuccess, errorCategory, errorOrigin)) return null;+ return {+ appId: liProposal.appId,+ slug: liProposal.slug,+ scope: liProposal.scope ?? null,+ success: outcomeSuccess,+ errorCategory,+ validationPassed: vp+ };+}+/*** Record a completed task for learning*/