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

address review (codex): honor the outcomes opt-out + serialize the per-proposal execution RMW

[._.]/ Adam Eivyd84d4c732775
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index 009f28e37f..4d16e5559e 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -553,7 +553,8 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
// read back its outcome. Gated on the app's `outcomes` source toggle AND
// an outcomes-capable tracker (forge / jira / plan — a checked `- [x]`
// PLAN item now reconciles, #2435).
- if (config.sources?.outcomes && outcomesTrackerSupported(filer)) {
+ const outcomesRecordable = !!(config.sources?.outcomes && outcomesTrackerSupported(filer))
+ if (outcomesRecordable) {
await recordFiledProposal({
appId: app.id, slug: proposal.slug, tracker: tracker.resolved,
issueRef: filedRef(filedKey, filedNumber), scope: proposal.scope
@@ -561,7 +562,10 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
}
const issueRef = filedKey || filedNumber
if (isHandoffEligible({ proposal, config, filed: issueRef })) {
- const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef }))
+ // Only mark the hand-off for per-domain execution recording (#2765) when the
+ // proposal itself was recorded above — same gate — so execution-tracking never
+ // creates an outcome row for a proposal the `outcomes` toggle says isn't tracked.
+ const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef, recordExecution: outcomesRecordable }))
.catch((err) => { console.error(`❌ Layered Intelligence: ${app.name} hand-off enqueue failed: ${err.message}`); return null })
if (task && !task.duplicate) {
handedOff = true
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index eabaa753bc..67f622eab4 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -534,7 +534,7 @@ export function isHandoffEligible({ proposal, config, filed } = {}) {
* `LI hand-off:` prefix so addTask's per-app dedup suppresses a re-enqueue while
* the same proposal's task is still pending/in-flight.
*/
-export function buildHandoffTask({ app, proposal, issueRef } = {}) {
+export function buildHandoffTask({ app, proposal, issueRef, recordExecution = false } = {}) {
const ref = typeof issueRef === 'number' ? `#${issueRef}` : String(issueRef ?? '').trim();
const context = [
'# Layered Intelligence hand-off',
@@ -551,26 +551,36 @@ export function buildHandoffTask({ app, proposal, issueRef } = {}) {
'',
proposal?.body || ''
].join('\n');
- return {
+ const task = {
description: `LI hand-off: ${proposal?.title || ref}`,
priority: 'MEDIUM',
context,
app: app?.id,
- approvalRequired: true,
- // Per-proposal-domain execution tracking (#2765): stamp the proposal's identity
- // + domain onto the task so, when this agent run completes, recordTaskCompletion
- // can attribute the execution success/failure back to the proposal's DOMAIN (not
- // the generic `internal-task` bucket this hand-off would otherwise land in).
- // addTask allowlists this top-level field into `metadata.liProposal`, and
- // registerAgent projects it onto `agent.metadata.taskLiProposal`. Kept a
- // dedicated key (not any of the extractTaskType-recognized metadata fields) so it
- // never reclassifies the task's own byTaskType bucket.
- liProposal: {
+ approvalRequired: true
+ };
+ // Per-proposal-domain execution tracking (#2765): stamp the proposal's identity +
+ // domain onto the task so, when this agent run completes, recordTaskCompletion can
+ // attribute the execution success/failure back to the proposal's DOMAIN (not the
+ // generic `internal-task` bucket this hand-off would otherwise land in). addTask
+ // allowlists this top-level field into `metadata.liProposal`, and registerAgent
+ // projects it onto `agent.metadata.taskLiProposal`. Kept a dedicated key (not any of
+ // the extractTaskType-recognized metadata fields) so it never reclassifies the task's
+ // own byTaskType bucket.
+ //
+ // Gated on `recordExecution` — the caller passes true ONLY when the outcomes source is
+ // on AND the tracker is outcomes-capable, the SAME gate that governs recordFiledProposal.
+ // Without this, a hand-off filed while outcomes-tracking is OFF would still carry the
+ // marker, and recordProposalExecution's missing-record fallback would create an outcome
+ // row — recording a proposal the source toggle says isn't tracked (codex P2). Omitting
+ // the marker keeps filing and execution-recording consistent with the one toggle.
+ if (recordExecution) {
+ task.liProposal = {
appId: app?.id ?? null,
slug: proposal?.slug ?? null,
scope: proposal?.scope ?? null
- }
- };
+ };
+ }
+ return task;
}
/**
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index f261374ff1..d3c4c233d4 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -421,10 +421,18 @@ describe('buildHandoffTask', () => {
expect(jira).toContain('change X to Y'); // carries the proposal body
});
- it('stamps the proposal identity + domain for per-domain execution tracking (#2765)', () => {
- const t = buildHandoffTask({ app, proposal: { ...proposal, scope: 'loop-meta' }, issueRef: 42 });
+ it('stamps the proposal identity + domain for per-domain execution tracking when recordExecution (#2765)', () => {
+ const t = buildHandoffTask({ app, proposal: { ...proposal, scope: 'loop-meta' }, issueRef: 42, recordExecution: true });
expect(t.liProposal).toEqual({ appId: 'app-1', slug: 'fix-typo', scope: 'loop-meta' });
});
+
+ it('omits the execution marker when outcomes tracking is off (recordExecution false/absent) (#2765)', () => {
+ // Honors the `outcomes` source toggle: a hand-off filed while tracking is off must
+ // not carry a marker, or recordProposalExecution's fallback would create an orphan
+ // outcome row the toggle says isn't tracked (codex P2).
+ expect(buildHandoffTask({ app, proposal: { ...proposal, scope: 'loop-meta' }, issueRef: 42, recordExecution: false }).liProposal).toBeUndefined();
+ expect(buildHandoffTask({ app, proposal: { ...proposal, scope: 'loop-meta' }, issueRef: 42 }).liProposal).toBeUndefined();
+ });
});
describe('computeExecutionByDomain (#2765)', () => {
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index 8ee4a01d5b..4f96943d16 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -177,29 +177,38 @@ export async function recordProposalExecution({ appId, slug, scope = null, succe
// per-domain aggregation. Normalized once and reused by both the missing-record
// fallback and the scope-preservation merge below.
const normScope = typeof scope === 'string' && scope.trim() ? scope.trim() : null;
- const existing = await store.loadOne(id).catch(() => null);
- const base = existing && typeof existing === 'object'
- ? existing
- : {
- appId, slug: normSlug, tracker: null, issueRef: null,
- scope: normScope,
- filedAt: new Date(now).toISOString(),
- outcome: null, outcomeAt: null, outcomeReason: null, rejectionReason: null
- };
- const next = {
- ...base,
- // Preserve the filed scope when the record already carries one; otherwise adopt
- // 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()
- };
await ensureTypeIndex(store);
- const ok = await store.saveOne(id, next).then(() => true, (err) => {
+ // Fence the whole read-modify-write in the per-id write queue (#2765, codex P2). A bare
+ // loadOne→saveOne lets a concurrent reconcileOutcomes write on the same slug interleave
+ // between our read and write and clobber either the executionOutcome we're setting or
+ // the reconciled filing outcome. queueRecordWrite tail-chains per id, so re-reading
+ // INSIDE the fence sees the other write path's committed record and the two compose
+ // (reconcile uses the same fence). Best-effort — a failure logs and returns false
+ // 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'
+ ? existing
+ : {
+ appId, slug: normSlug, tracker: null, issueRef: null,
+ scope: normScope,
+ filedAt: new Date(now).toISOString(),
+ outcome: null, outcomeAt: null, outcomeReason: null, rejectionReason: null
+ };
+ const next = {
+ ...base,
+ // Preserve the filed scope when the record already carries one; otherwise adopt
+ // 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()
+ };
+ await store.saveOneNow(id, next);
+ return true;
+ }).catch((err) => {
console.error(`❌ Layered Intelligence: failed to record execution outcome for ${appId}/${normSlug}: ${err.message}`);
return false;
});
- return ok;
}
/**
@@ -306,14 +315,26 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date
// derived token to the stored one (rather than writing unconditionally) keeps
// a settled record from churning on every reconcile.
if (outcome === r.outcome && rejectionReason === r.rejectionReason && !newerClose) continue;
- const next = {
- ...r,
- outcome,
- outcomeAt: issue.closedAt || r.outcomeAt || new Date(now).toISOString(),
- outcomeReason: issue.stateReason || 'auto-derived from tracker state',
- rejectionReason
- };
- const ok = await store.saveOne(outcomeId(appId, r.slug), next).then(() => true, () => false);
+ const id = outcomeId(appId, r.slug);
+ // Fence the per-record write in the same per-id queue recordProposalExecution uses
+ // (#2765, codex P2), and re-read INSIDE the fence: `records` came from an upfront
+ // listOutcomes read, so a hand-off completion that wrote `executionOutcome` after that
+ // read but before here would be clobbered by a stale `{...r}`. Merging over the FRESH
+ // record (loadOne, falling back to `r` only if GC'd mid-flight) preserves the execution
+ // fields while still applying the recomputed filing outcome. The recomputed fields come
+ // from `issue`, not `fresh`, so a concurrent execution write can't revert them either.
+ const ok = await store.queueRecordWrite(id, async () => {
+ const fresh = (await store.loadOne(id).catch(() => null)) || r;
+ const next = {
+ ...fresh,
+ outcome,
+ outcomeAt: issue.closedAt || fresh.outcomeAt || new Date(now).toISOString(),
+ outcomeReason: issue.stateReason || 'auto-derived from tracker state',
+ rejectionReason
+ };
+ await store.saveOneNow(id, next);
+ return true;
+ }).catch(() => false);
if (ok) updated += 1;
}
return updated;
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index 10c1af3edc..97d9597b4a 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -498,6 +498,21 @@ describe('recordProposalExecution (#2765)', () => {
expect(byDomain['app-improvement']).toBeUndefined();
});
+ it('reconcile preserves executionOutcome when it later stamps the filing outcome (#2765 field-preservation)', async () => {
+ // The reverse-race guard: execution is recorded first, then reconcile marks the
+ // issue merged. The fenced re-read must carry executionOutcome through, not clobber
+ // it with a stale pre-execution record.
+ await recordFiledProposal({ appId: 'app-1', slug: 'both', scope: 'loop-meta' }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'both', success: true }, store);
+ await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [{ slug: 'both', state: 'closed', stateReason: 'completed', closedAt: new Date().toISOString() }]
+ }, store);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.outcome).toBe('merged'); // reconcile applied the filing outcome
+ expect(row.executionOutcome).toBe('success'); // …without dropping the execution signal
+ });
+
it('aggregates a domain’s success rate across multiple executions', async () => {
await recordFiledProposal({ appId: 'app-1', slug: 'a', scope: 'loop-meta' }, store);
await recordFiledProposal({ appId: 'app-1', slug: 'b', scope: 'loop-meta' }, store);