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([issue-2748]): classify LI merge-conflict/validation-failed from the implementing PR
[._.]/ Adam Eivy953765d6948d
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex cb9f60b57e..e27ba04906 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -332,7 +332,10 @@ export async function buildTaskInput({ app } = {}) {// diagnosed failed hand-off.let crossReferenceReport = ''if (config.sources?.outcomes && outcomesTrackerSupported(filer)) {- if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues })+ // Pass the forge handle so the reconciler can read an implementing PR's merge+ // state/checks (#2748, deliverable 2) to classify merge-conflict/validation-failed.+ // gh-only + bounded inside reconcileOutcomes; glab/plan carry no PR ref so no read.+ if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues, cli: forgeCli, cwd })// Discriminated read: an unreadable outcome store stays `null` here rather than// collapsing to `[]`, so selfEval reports its merge rate as UNAVAILABLE instead// of telling the reasoner it has never filed a proposal.diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex c639db4f52..eb5bf21a43 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -2073,7 +2073,7 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =// gh takes the state explicitly.const args = cli === 'glab'? ['issue', 'list', '--label', label, ...(state === 'all' ? ['--all'] : []), '-P', '100', '-F', 'json']- : ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels,comments'];+ : ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels,comments,closedByPullRequestsReferences'];const { code, stdout } = await exec(cli, args, { cwd, env });if (code !== 0) return { ok: false, issues: [] };if (!stdout.trim()) return { ok: true, issues: [] };@@ -2101,11 +2101,55 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =// `-F json` omits them, so its rows carry null and fall through to label/// stateReason only (tracked in the issue's Remaining).closingComment: extractClosingComment(i.comments),+ // The implementing-PR handle (#2748, deliverable 2): gh reports every PR that+ // closes/references this issue in `closedByPullRequestsReferences`. Additive+ // and null-defaulted — glab's `-F json` omits it, so its rows carry null and+ // fall through to the label/comment signals, and the reconciler only reads a+ // PR's state when it holds a number here.+ implementingPr: extractImplementingPr(i.closedByPullRequestsReferences),slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')}))};}+/**+ * The number of the PR that implements a proposal, from gh's+ * `closedByPullRequestsReferences` (#2748, deliverable 2). Takes the LAST reference —+ * the most recent PR linked to the issue — and returns its number, or null when there+ * is none (glab, or an issue closed by hand). Pure.+ */+export function extractImplementingPr(refs) {+ if (!Array.isArray(refs)) return null;+ for (let i = refs.length - 1; i >= 0; i -= 1) {+ const n = refs[i]?.number;+ if (Number.isInteger(n) && n > 0) return n;+ }+ return null;+}++/**+ * Read the merge state + check rollup of an implementing PR (#2748, deliverable 2),+ * so the rejection reconciler can classify `merge-conflict` / `validation-failed`.+ * gh-only (glab carries no PR handle) and bounded by the caller to the small set of+ * non-merged proposals that both hold a PR ref and were left undiagnosed by the free+ * signals — this is the ONE tracker fetch classification adds, and it never runs at+ * boot (only the scheduler-tick reconcile, gated behind `sources.outcomes`).+ * Returns `{ state, mergeStateStatus, statusCheckRollup }`, or null on any failure+ * (a null read simply leaves the proposal on its existing, honest fallback reason).+ */+export async function readImplementingPrState({ cli, cwd, env, number, exec = runCli } = {}) {+ if (cli !== 'gh' || !Number.isInteger(number)) return null;+ const { code, stdout } = await exec(cli, ['pr', 'view', String(number), '--json', 'state,mergeStateStatus,statusCheckRollup'], { cwd, env });+ if (code !== 0 || !stdout.trim()) return null;+ const parsed = safeJSONParse(stdout, null, { logError: false });+ if (!parsed || typeof parsed !== 'object') return null;+ return {+ state: parsed.state ?? null,+ mergeStateStatus: parsed.mergeStateStatus ?? null,+ statusCheckRollup: Array.isArray(parsed.statusCheckRollup) ? parsed.statusCheckRollup : []+ };+}+/*** The rationale a human left when closing a proposal, for the rejection classifier* (#2748). gh returns issue comments oldest-first; the LAST non-empty one sitsdiff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex c046671564..ab5e626974 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -64,6 +64,8 @@ import {normalizeIssueState,listForgeIssues,extractClosingComment,+ extractImplementingPr,+ readImplementingPrState,listBlockingIssues,fileProposalToForge,ensureForgeLabels,@@ -1892,8 +1894,10 @@ describe('forge I/O (injected exec)', () => {});const { ok, issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });expect(ok).toBe(true);- // The batched list call must ask gh for `comments` so no extra fetch is needed.- expect(exec.mock.calls[0][1]).toContain('number,title,body,state,stateReason,closedAt,url,labels,comments');+ // The batched list call must ask gh for `comments` (closing-comment signal) and+ // `closedByPullRequestsReferences` (implementing-PR ref, #2748 deliverable 2) so+ // no extra fetch is needed for either.+ expect(exec.mock.calls[0][1]).toContain('number,title,body,state,stateReason,closedAt,url,labels,comments,closedByPullRequestsReferences');// The LAST comment (closest to the close) becomes the classifier's signal.expect(issues[0].closingComment).toBe('Closing — this is out of scope for the app.');});@@ -1915,6 +1919,60 @@ describe('forge I/O (injected exec)', () => {expect(extractClosingComment([{ body: ' ' }, { body: null }])).toBeNull();});+ it('listForgeIssues threads the implementing-PR number from closedByPullRequestsReferences (#2748)', async () => {+ const exec = vi.fn().mockResolvedValue({+ code: 0,+ stdout: JSON.stringify([+ {+ number: 5,+ title: 'E',+ body: `x ${slugMarker('slug-e')}`,+ state: 'CLOSED',+ closedByPullRequestsReferences: [{ number: 900 }, { number: 901 }]+ },+ { number: 6, title: 'F', body: `x ${slugMarker('slug-f')}`, state: 'CLOSED' }+ ])+ });+ const { issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });+ // The batched call must ALSO ask gh for the closing-PR refs — no extra round-trip.+ expect(exec.mock.calls[0][1]).toContain('number,title,body,state,stateReason,closedAt,url,labels,comments,closedByPullRequestsReferences');+ // The LAST ref (most recent linked PR) is the implementing handle.+ expect(issues[0].implementingPr).toBe(901);+ // No refs ⇒ null (glab rows, or a hand-closed issue) — falls through cleanly.+ expect(issues[1].implementingPr).toBeNull();+ });++ it('extractImplementingPr returns the last positive-integer ref, else null', () => {+ expect(extractImplementingPr([{ number: 10 }, { number: 11 }])).toBe(11);+ expect(extractImplementingPr([{ number: 12 }, { number: null }])).toBe(12);+ expect(extractImplementingPr([])).toBeNull();+ expect(extractImplementingPr(null)).toBeNull();+ expect(extractImplementingPr([{ number: 0 }, { number: -3 }])).toBeNull();+ });++ it('readImplementingPrState parses gh pr view, and is gh-only (#2748)', async () => {+ const exec = vi.fn().mockResolvedValue({+ code: 0,+ stdout: JSON.stringify({ state: 'CLOSED', mergeStateStatus: 'DIRTY', statusCheckRollup: [{ conclusion: 'FAILURE' }] })+ });+ const view = await readImplementingPrState({ cli: 'gh', cwd: '/x', number: 42, exec });+ expect(exec).toHaveBeenCalledWith('gh', ['pr', 'view', '42', '--json', 'state,mergeStateStatus,statusCheckRollup'], { cwd: '/x', env: undefined });+ expect(view).toEqual({ state: 'CLOSED', mergeStateStatus: 'DIRTY', statusCheckRollup: [{ conclusion: 'FAILURE' }] });++ // glab carries no PR handle → no fetch, null.+ const glabExec = vi.fn();+ expect(await readImplementingPrState({ cli: 'glab', number: 42, exec: glabExec })).toBeNull();+ expect(glabExec).not.toHaveBeenCalled();+ // A non-integer number is a caller bug → null without fetching.+ expect(await readImplementingPrState({ cli: 'gh', number: null, exec: glabExec })).toBeNull();+ });++ it('readImplementingPrState returns null on a CLI error or unparseable output (#2748)', async () => {+ expect(await readImplementingPrState({ cli: 'gh', number: 1, exec: vi.fn().mockResolvedValue({ code: 1, stdout: '' }) })).toBeNull();+ expect(await readImplementingPrState({ cli: 'gh', number: 1, exec: vi.fn().mockResolvedValue({ code: 0, stdout: 'not json' }) })).toBeNull();+ expect(await readImplementingPrState({ cli: 'gh', number: 1, exec: vi.fn().mockResolvedValue({ code: 0, stdout: ' ' }) })).toBeNull();+ });+it('listForgeIssues normalizes GitLab "opened" state to open', async () => {const exec = vi.fn().mockResolvedValue({code: 0,diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.jsindex 46ed27c868..0ab6111869 100644--- a/server/services/layeredIntelligenceOutcomes.js+++ b/server/services/layeredIntelligenceOutcomes.js@@ -22,8 +22,8 @@import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';import { createCollectionStore } from '../lib/collectionStore.js';-import { normalizeSlug, deriveOutcome, PROPOSAL_OUTCOMES, PROPOSAL_EXECUTION_OUTCOMES, CLOSED_SUPPRESSION_MS } from './layeredIntelligence.js';-import { classifyRejection, REJECTION_REASON_VALUES } from './layeredIntelligenceRejections.js';+import { normalizeSlug, deriveOutcome, readImplementingPrState, PROPOSAL_OUTCOMES, PROPOSAL_EXECUTION_OUTCOMES, CLOSED_SUPPRESSION_MS } from './layeredIntelligence.js';+import { classifyRejection, classifyPrFailure, isPrRefinableReason, REJECTION_REASON_VALUES } from './layeredIntelligenceRejections.js';import { classifyExecutionFailure, EXECUTION_FAILURE_VALUES } from './layeredIntelligenceExecutionFailures.js';// Longest raw failure-signal token stored on a record. The signal is one of@@ -79,6 +79,13 @@ export function sanitizeOutcomeRecord(raw) {outcomeAt: outcome && typeof raw.outcomeAt === 'string' ? raw.outcomeAt : null,outcomeReason: outcome && typeof raw.outcomeReason === 'string' ? raw.outcomeReason : null,rejectionReason: rejectable && REJECTION_REASON_VALUES.includes(raw.rejectionReason) ? raw.rejectionReason : null,+ // Implementing-PR handle (#2748, deliverable 2) — the number of the PR that was+ // meant to implement this proposal, so a later reconcile can read its merge+ // state/checks and classify `merge-conflict`/`validation-failed`. Additive with a+ // null default (no record-shape migration): a positive integer or null. Kept+ // regardless of outcome — it is a fact about the proposal, and a merged proposal's+ // PR ref is harmless — so a coerced non-int/absent value simply reads as null.+ implementingPr: Number.isInteger(raw.implementingPr) && raw.implementingPr > 0 ? raw.implementingPr : null,// Per-proposal-domain EXECUTION record (#2765) — orthogonal to `outcome` (the// FILING fate): whether LI's own coding agent implemented the proposal after the// Engine-A hand-off. `null` = never handed off / not yet executed; a token only@@ -163,6 +170,9 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueReoutcomeReason: null,// Unresolved: nothing has rejected it yet, so there is nothing to diagnose.rejectionReason: null,+ // Learned at reconcile time from the tracker's closedByPullRequestsReferences+ // (#2748, deliverable 2); unknown at filing.+ implementingPr: null,// Not executed yet — set only if this proposal is later handed off and its agent// run completes (recordProposalExecution, #2765).executionOutcome: null,@@ -226,7 +236,8 @@ export async function recordProposalExecution({ appId, slug, scope = null, succeappId, slug: normSlug, tracker: null, issueRef: null,scope: normScope,filedAt: new Date(now).toISOString(),- outcome: null, outcomeAt: null, outcomeReason: null, rejectionReason: null+ outcome: null, outcomeAt: null, outcomeReason: null, rejectionReason: null,+ implementingPr: null};const next = {...base,@@ -327,8 +338,14 @@ export async function listOutcomesResult({ appId, now = Date.now() } = {}, store* from the latest closure, not the first. Returns the number of records* updated. Never throws — a per-record write failure is swallowed so one bad* row can't abort the whole reconciliation.+ *+ * When a forge handle (`cli`/`cwd`) is supplied, a non-merged proposal that carries+ * an `implementingPr` ref and was left undiagnosed by the free signals gets ONE+ * bounded `gh pr view` read (`readPrState`, gh-only) to classify+ * `merge-conflict`/`validation-failed` from the implementing PR's merge state/checks+ * (#2748, deliverable 2). `readPrState` is injectable so tests never hit the network.*/-export async function reconcileOutcomes({ appId, existingIssues = [], now = Date.now() } = {}, store = outcomesStore()) {+export async function reconcileOutcomes({ appId, existingIssues = [], now = Date.now(), cli = null, cwd = null, env = undefined, readPrState = readImplementingPrState } = {}, store = outcomesStore()) {if (!appId || !Array.isArray(existingIssues) || existingIssues.length === 0) return 0;// Index existing issues by normalized slug for O(1) lookup.const bySlug = new Map();@@ -348,12 +365,25 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date// tracker call. Merged/unresolved → null. `closingComment` (#2748) is the// deterministic last-resort signal for a close stated only in prose; forges// that don't surface comments simply pass null.- const rejectionReason = classifyRejection({+ const base = {outcome,stateReason: issue.stateReason,labels: issue.labels,closingComment: issue.closingComment- });+ };+ let rejectionReason = classifyRejection(base);+ // Implementing-PR failure refinement (#2748, deliverable 2). Only read the PR's+ // merge state/checks when it could actually change the answer: there is a PR ref+ // (gh-only), and the free signals left the proposal on a generic/undiagnosed+ // reason a mechanical PR fact is allowed to sharpen. This bounds the one extra+ // tracker fetch classification makes to the small set of records it can move — a+ // label / specific close-reason / prose rationale already wins and skips the read.+ const implementingPr = Number.isInteger(issue.implementingPr) && issue.implementingPr > 0 ? issue.implementingPr : null;+ if (implementingPr && cli && isPrRefinableReason(rejectionReason)) {+ const prView = await readPrState({ cli, cwd, env, number: implementingPr }).catch(() => null);+ const prFailure = classifyPrFailure(prView);+ if (prFailure) rejectionReason = classifyRejection({ ...base, prFailure });+ }// A same-outcome record is only rewritten when the tracker reports a NEWER// close time (closed → reopened → re-closed): outcomeAt drives retention/GC,// so it must track the latest closure. Timestampless trackers (plan) and an@@ -367,7 +397,11 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date// `unknown-reason` record once someone finally labels the issue. Comparing the// 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;+ // Learning the implementing-PR ref (#2748, deliverable 2) is itself a reason to+ // rewrite — it BACKFILLS the additive field on records filed before it existed,+ // and prefers the freshly-read ref over a stored one so a re-linked PR updates.+ const nextImplementingPr = implementingPr ?? (r.implementingPr ?? null);+ if (outcome === r.outcome && rejectionReason === r.rejectionReason && nextImplementingPr === (r.implementingPr ?? null) && !newerClose) continue;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@@ -383,7 +417,8 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Dateoutcome,outcomeAt: issue.closedAt || fresh.outcomeAt || new Date(now).toISOString(),outcomeReason: issue.stateReason || 'auto-derived from tracker state',- rejectionReason+ rejectionReason,+ implementingPr: nextImplementingPr};await store.saveOneNow(id, next);return true;diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.jsindex a95b23f784..b86c1da9a8 100644--- a/server/services/layeredIntelligenceOutcomes.test.js+++ b/server/services/layeredIntelligenceOutcomes.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { mkdtemp, rm, mkdir, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';@@ -55,6 +55,21 @@ describe('sanitizeOutcomeRecord', () => {expect(unresolved.outcomeReason).toBeNull();});+ describe('implementingPr (#2748, deliverable 2)', () => {+ it('keeps a positive integer PR ref and null-defaults everything else', () => {+ expect(sanitizeOutcomeRecord({ appId: 'a', slug: 's', implementingPr: 902 }).implementingPr).toBe(902);+ // Additive/null default: absent, non-int, zero, or negative all coerce to null.+ expect(sanitizeOutcomeRecord({ appId: 'a', slug: 's' }).implementingPr).toBeNull();+ expect(sanitizeOutcomeRecord({ appId: 'a', slug: 's', implementingPr: '902' }).implementingPr).toBeNull();+ expect(sanitizeOutcomeRecord({ appId: 'a', slug: 's', implementingPr: 0 }).implementingPr).toBeNull();+ expect(sanitizeOutcomeRecord({ appId: 'a', slug: 's', implementingPr: -1 }).implementingPr).toBeNull();+ });++ it('is preserved regardless of outcome (a fact about the proposal, not the rejection)', () => {+ expect(sanitizeOutcomeRecord({ appId: 'a', slug: 's', outcome: 'merged', implementingPr: 903 }).implementingPr).toBe(903);+ });+ });+describe('rejectionReason (#2689)', () => {const sanitize = (over) => sanitizeOutcomeRecord({ appId: 'a', slug: 's', ...over });@@ -449,6 +464,113 @@ describe('reconcileOutcomes', () => {expect(await reconcileOutcomes({ appId: 'app-1', existingIssues: [issue] }, store)).toBe(0);});});++ describe('implementing-PR failure classification (#2748, deliverable 2)', () => {+ const rowsBySlug = async () =>+ Object.fromEntries((await listOutcomes({ appId: 'app-1' }, store)).map(r => [r.slug, r]));++ it('refines a generic decline to validation-failed from the implementing PR checks', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'ci-failed' }, store);+ const readPrState = vi.fn().mockResolvedValue({ state: 'CLOSED', mergeStateStatus: 'UNKNOWN', statusCheckRollup: [{ conclusion: 'FAILURE' }] });+ const updated = await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', cwd: '/x', readPrState,+ existingIssues: [{ slug: 'ci-failed', state: 'closed', stateReason: 'not_planned', implementingPr: 900, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect(updated).toBe(1);+ expect(readPrState).toHaveBeenCalledWith({ cli: 'gh', cwd: '/x', env: undefined, number: 900 });+ const row = (await rowsBySlug())['ci-failed'];+ expect(row.rejectionReason).toBe('validation-failed');+ // The implementing-PR ref is persisted (additive field).+ expect(row.implementingPr).toBe(900);+ });++ it('refines an otherwise-unknown close to merge-conflict from the PR merge state', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'dirty-branch' }, store);+ const readPrState = vi.fn().mockResolvedValue({ state: 'OPEN', mergeStateStatus: 'DIRTY', statusCheckRollup: [] });+ await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', readPrState,+ existingIssues: [{ slug: 'dirty-branch', state: 'closed', stateReason: 'reopened', implementingPr: 901, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect((await rowsBySlug())['dirty-branch'].rejectionReason).toBe('merge-conflict');+ });++ it('does NOT read the PR when a more authoritative signal already diagnosed the close', async () => {+ // A human label wins; the bounded fetch is skipped entirely.+ await recordFiledProposal({ appId: 'app-1', slug: 'labelled' }, store);+ const readPrState = vi.fn();+ await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', readPrState,+ existingIssues: [{ slug: 'labelled', state: 'closed', stateReason: 'not_planned', labels: ['duplicate'], implementingPr: 902, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect(readPrState).not.toHaveBeenCalled();+ expect((await rowsBySlug())['labelled'].rejectionReason).toBe('duplicate');+ // But the PR ref is still persisted so it's available if the label is later removed.+ expect((await rowsBySlug())['labelled'].implementingPr).toBe(902);+ });++ it('does NOT read the PR when there is no implementing ref or no forge handle', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'no-pr' }, store);+ await recordFiledProposal({ appId: 'app-1', slug: 'no-cli' }, store);+ const readPrState = vi.fn();+ await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', readPrState,+ existingIssues: [{ slug: 'no-pr', state: 'closed', stateReason: 'not_planned', closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ // No cli (plan/jira path) — even with a ref there's no PR to read.+ await reconcileOutcomes({+ appId: 'app-1', readPrState,+ existingIssues: [{ slug: 'no-cli', state: 'closed', stateReason: 'not_planned', implementingPr: 903, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect(readPrState).not.toHaveBeenCalled();+ const rows = await rowsBySlug();+ expect(rows['no-pr'].rejectionReason).toBe('user-rejected');+ expect(rows['no-cli'].rejectionReason).toBe('user-rejected');+ });++ it('falls back to the free-signal reason when the PR read is inconclusive', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'clean-pr' }, store);+ // PR merged / clean → classifyPrFailure returns null → keep the generic decline.+ const readPrState = vi.fn().mockResolvedValue({ state: 'CLOSED', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }] });+ await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', readPrState,+ existingIssues: [{ slug: 'clean-pr', state: 'closed', stateReason: 'not_planned', implementingPr: 904, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect((await rowsBySlug())['clean-pr'].rejectionReason).toBe('user-rejected');+ });++ it('survives a throwing PR read, keeping the free-signal reason (never throws)', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'boom' }, store);+ const readPrState = vi.fn().mockRejectedValue(new Error('gh exploded'));+ const updated = await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', readPrState,+ existingIssues: [{ slug: 'boom', state: 'closed', stateReason: 'not_planned', implementingPr: 905, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect(updated).toBe(1);+ expect((await rowsBySlug())['boom'].rejectionReason).toBe('user-rejected');+ });++ it('backfills the implementing-PR ref on an already-settled record without changing its reason', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'backfill' }, store);+ // First pass: a duplicate close with no PR ref yet.+ await reconcileOutcomes({+ appId: 'app-1',+ existingIssues: [{ slug: 'backfill', state: 'closed', stateReason: 'duplicate', closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect((await rowsBySlug())['backfill'].implementingPr).toBeNull();+ // Second pass: the ref is now known. Reason is unchanged (duplicate wins), but+ // learning the ref is itself a reason to rewrite.+ const readPrState = vi.fn();+ const updated = await reconcileOutcomes({+ appId: 'app-1', cli: 'gh', readPrState,+ existingIssues: [{ slug: 'backfill', state: 'closed', stateReason: 'duplicate', implementingPr: 906, closedAt: '2026-07-01T00:00:00Z' }]+ }, store);+ expect(updated).toBe(1);+ expect(readPrState).not.toHaveBeenCalled(); // duplicate is not refinable → no fetch+ const row = (await rowsBySlug())['backfill'];+ expect(row.rejectionReason).toBe('duplicate');+ expect(row.implementingPr).toBe(906);+ });+ });});describe('listOutcomesResult read sentinel (#2700)', () => {diff --git a/server/services/layeredIntelligenceRejections.js b/server/services/layeredIntelligenceRejections.jsindex ab9306faaa..5f86a813a1 100644--- a/server/services/layeredIntelligenceRejections.js+++ b/server/services/layeredIntelligenceRejections.js@@ -10,9 +10,13 @@* outcome rather than diagnosing it.** This module owns the structured vocabulary and the deterministic mapping onto- * it. Pure, no I/O, no LLM call — every token is derived from data the reconciler- * already holds, so classification never adds a provider round-trip (the- * "no cold-bootstrap LLM calls" policy) and never adds a tracker fetch.+ * it. Pure, no I/O, no LLM call — every classifier here derives its token from data+ * handed to it, so classification never adds a provider round-trip (the+ * "no cold-bootstrap LLM calls" policy). One signal, the implementing-PR failure+ * (#2748, deliverable 2), needs a `gh pr view` read the pure classifiers can't do —+ * the RECONCILER owns that I/O (bounded to non-merged proposals that carry a PR ref+ * and whose free signals left them undiagnosed) and passes the resolved token in, so+ * this module stays pure.** A LEAF module by design: it imports nothing from the LI graph, so both* `layeredIntelligence.js` (which formats the reports) and@@ -73,8 +77,12 @@ export const REJECTION_REASONS = ['quality-issue',// Label-only today.'environment-blocker',- // Label-only today. These are properties of the PR that IMPLEMENTS a proposal,- // and LI tracks proposals as issues — it has no PR handle to read checks from.+ // (live) From a human-applied label, OR the implementing-PR state read (#2748,+ // deliverable 2): these are properties of the PR that IMPLEMENTS a proposal, and+ // LI tracks proposals as issues. The reconciler now threads the implementing-PR ref+ // (`closedByPullRequestsReferences`, additive/null-default) and reads its merge+ // state / checks via `classifyPrFailure`, so a conflicted or CI-failed implementing+ // PR is reachable without a record-shape migration.'merge-conflict','validation-failed'];@@ -172,6 +180,59 @@ const STATE_REASON_REASONS = new Map(Object.entries({// already fixed that), so the merge rate the reasoner calibrates on is untouched.const GENERIC_REJECTION_REASONS = new Set(['user-rejected']);+/**+ * The reasons a PR-state read (#2748, deliverable 2) is ALLOWED to refine: the honest+ * `unknown-reason` and the generic user-rejection. A more authoritative signal — a+ * human-applied label, a specific close reason (duplicate), or a closing-comment+ * rationale — already states WHY, and a mechanical fact about the implementing PR+ * must never override a human's explicit judgement. The reconciler consults this so it+ * can SKIP the extra `gh pr view` round-trip whenever the free signals already+ * diagnosed the close (the read is bounded to the records it could actually change).+ */+export function isPrRefinableReason(reason) {+ return reason === UNKNOWN_REJECTION_REASON || GENERIC_REJECTION_REASONS.has(reason);+}++// PR-check verdicts that mean the implementing change FAILED validation. gh's+// statusCheckRollup mixes CheckRun (`conclusion`) and StatusContext (`state`) rows;+// both are normalized to upper-case and tested against this set. Deliberately+// conservative — CANCELLED/SKIPPED/NEUTRAL are ambiguous (superseded runs, opt-out+// checks) and excluded, so a miss falls through to the honest `unknown-reason`+// rather than a fabricated validation-failed.+const FAILED_CHECK_VERDICTS = new Set(['FAILURE', 'ERROR', 'TIMED_OUT', 'STARTUP_FAILURE', 'ACTION_REQUIRED']);++/**+ * Classify why the PR that was meant to IMPLEMENT a proposal failed, from a+ * `gh pr view --json state,mergeStateStatus,statusCheckRollup` read (#2748,+ * deliverable 2). Pure, total, deterministic — the reconciler owns the I/O and hands+ * the parsed object here. Returns a REJECTION_REASONS token, or null when the PR+ * merged or nothing indicates a failure (→ the caller keeps the honest fallback).+ *+ * - `merge-conflict` — the branch could not be merged (`mergeStateStatus` DIRTY).+ * GitHub only computes mergeability while the PR is open, so+ * this fires on an open/last-known-dirty PR; it is checked+ * first because a conflicted branch is the more fundamental+ * blocker than a failed check on top of it.+ * - `validation-failed` — a required check reported a failing verdict. Readable even+ * on a CLOSED (abandoned) PR from its last recorded rollup,+ * which is the common terminal state for a proposal whose+ * implementing PR was given up on.+ *+ * A MERGED PR is never a failure (returns null): if it merged, the proposal's outcome+ * is `merged` and there is no rejection to diagnose.+ */+export function classifyPrFailure(prView) {+ if (!prView || typeof prView !== 'object') return null;+ if (String(prView.state || '').toUpperCase() === 'MERGED') return null;+ if (String(prView.mergeStateStatus || '').toUpperCase() === 'DIRTY') return 'merge-conflict';+ const rollup = Array.isArray(prView.statusCheckRollup) ? prView.statusCheckRollup : [];+ for (const check of rollup) {+ const verdict = String(check?.conclusion || check?.state || '').toUpperCase();+ if (FAILED_CHECK_VERDICTS.has(verdict)) return 'validation-failed';+ }+ return null;+}+// Closing-comment keyword pass (#2748). Some closures state their rationale only in// prose — a human declines in a comment without applying a matching label or (on// glab/jira) any close reason at all. This is a DETERMINISTIC keyword/heuristic@@ -267,19 +328,25 @@ export function classifyClosingComment(text) {* 1. a human-applied label (the most deliberate signal);* 2. a SPECIFIC tracker close reason (duplicate);* 3. the deterministic closing-comment keyword pass (#2748);- * 4. a GENERIC tracker close reason (GitHub `not_planned` → user-rejected: it+ * 4. an implementing-PR failure token (#2748, deliverable 2) — a mechanical fact+ * about the PR that was meant to implement the proposal (`merge-conflict` /+ * `validation-failed`), pre-resolved by the reconciler from a `gh pr view` read;+ * 5. a GENERIC tracker close reason (GitHub `not_planned` → user-rejected: it* says the proposal was declined, but not why).- * The comment sits BELOW a label/specific reason but ABOVE the generic decline, so- * a prose rationale REFINES a bare not_planned into a precise token instead of- * being shadowed by it — the refinement changes only the reason, never the- * outcome deriveOutcome already fixed, so it can't move the merge rate. The comment- * NEVER overrides the merged fallback (deriveOutcome runs first and never reaches- * here for a merge), so the reasonless-close-reads-as-merged gap the module header- * documents is untouched by this pass.+ * The comment and the PR-failure both sit BELOW a label/specific reason but ABOVE the+ * generic decline, so each REFINES a bare not_planned into a precise token instead of+ * being shadowed by it. The PR-failure sits below the closing comment on purpose: a+ * human who stated a rationale in prose ("out of scope") outranks the mechanical fact+ * that the implementing PR happened to have a conflict — the PR-failure only speaks+ * for the records a human left otherwise undiagnosed. Every refinement changes only+ * the reason token, never the outcome deriveOutcome already fixed, so none can move+ * the merge rate. The pass NEVER overrides the merged fallback (deriveOutcome runs+ * first and never reaches here for a merge), so the reasonless-close-reads-as-merged+ * gap the module header documents is untouched.** Deterministic and total: same inputs always yield the same token.*/-export function classifyRejection({ outcome = null, stateReason = null, labels = [], closingComment = null } = {}) {+export function classifyRejection({ outcome = null, stateReason = null, labels = [], closingComment = null, prFailure = null } = {}) {// Only a resolved, non-merged proposal has a rejection to explain.if (outcome !== 'rejected' && outcome !== 'abandoned') return null;@@ -299,7 +366,11 @@ export function classifyRejection({ outcome = null, stateReason = null, labels =const commentHit = classifyClosingComment(closingComment);if (commentHit) return commentHit;- // 4. The generic close reason, when the comment named nothing specific.+ // 4. The implementing-PR failure (#2748, deliverable 2) — only a member of+ // REJECTION_REASONS is honoured, so a caller can't inject a foreign token.+ if (prFailure && REJECTION_REASONS.includes(prFailure)) return prFailure;++ // 5. The generic close reason, when nothing more specific named the rationale.if (stateHit) return stateHit;return UNKNOWN_REJECTION_REASON;diff --git a/server/services/layeredIntelligenceRejections.test.js b/server/services/layeredIntelligenceRejections.test.jsindex de592fc81a..43cc89981f 100644--- a/server/services/layeredIntelligenceRejections.test.js+++ b/server/services/layeredIntelligenceRejections.test.js@@ -5,6 +5,8 @@ import {UNKNOWN_REJECTION_REASON,classifyRejection,classifyClosingComment,+ classifyPrFailure,+ isPrRefinableReason,formatRejectionReason,formatRejectionReasons,summarizeRejectionReasons@@ -185,6 +187,114 @@ describe('classifyRejection', () => {const fromComment = classifyRejection({ outcome: 'rejected', closingComment: 'out of scope' });expect(REJECTION_REASON_VALUES).toContain(fromComment);});++ describe('implementing-PR failure precedence (#2748, deliverable 2)', () => {+ it('refines a generic not_planned decline into the PR-failure token', () => {+ // The primary reachable case: an abandoned/rejected proposal whose implementing+ // PR failed CI. The bare not_planned says only THAT it was declined.+ expect(classifyRejection({+ outcome: 'rejected', stateReason: 'not_planned', prFailure: 'validation-failed'+ })).toBe('validation-failed');+ expect(classifyRejection({+ outcome: 'abandoned', prFailure: 'merge-conflict'+ })).toBe('merge-conflict');+ });++ it('diagnoses an otherwise-unknown close from the PR failure', () => {+ expect(classifyRejection({+ outcome: 'rejected', stateReason: null, labels: [], prFailure: 'merge-conflict'+ })).toBe('merge-conflict');+ });++ it('never overrides a human label or a specific close reason', () => {+ // A human wontfix / a duplicate close is a deliberate disposition; the mechanical+ // fact that the PR had a conflict must not outrank it.+ expect(classifyRejection({+ outcome: 'rejected', labels: ['wontfix'], prFailure: 'validation-failed'+ })).toBe('user-rejected');+ expect(classifyRejection({+ outcome: 'abandoned', stateReason: 'duplicate', prFailure: 'merge-conflict'+ })).toBe('duplicate');+ });++ it('sits BELOW the closing-comment rationale', () => {+ // A human who stated "out of scope" in prose outranks a mechanical PR conflict.+ expect(classifyRejection({+ outcome: 'rejected', stateReason: 'not_planned',+ closingComment: 'this is out of scope', prFailure: 'merge-conflict'+ })).toBe('scope-mismatch');+ });++ it('ignores a foreign / non-vocabulary prFailure token', () => {+ // Only a REJECTION_REASONS member is honoured, so a caller can't inject junk.+ expect(classifyRejection({+ outcome: 'rejected', stateReason: 'not_planned', prFailure: 'not-a-real-token'+ })).toBe('user-rejected');+ expect(classifyRejection({+ outcome: 'rejected', prFailure: 'not-a-real-token'+ })).toBe(UNKNOWN_REJECTION_REASON);+ });+ });+});++describe('classifyPrFailure (#2748, deliverable 2)', () => {+ it('returns null for a nullish or non-object input', () => {+ expect(classifyPrFailure(null)).toBeNull();+ expect(classifyPrFailure(undefined)).toBeNull();+ expect(classifyPrFailure('MERGED')).toBeNull();+ });++ it('never treats a merged PR as a failure', () => {+ // If it merged, the proposal is `merged` and there is nothing to diagnose.+ expect(classifyPrFailure({ state: 'MERGED', mergeStateStatus: 'DIRTY' })).toBeNull();+ expect(classifyPrFailure({ state: 'merged', statusCheckRollup: [{ conclusion: 'FAILURE' }] })).toBeNull();+ });++ it('reads a DIRTY merge state as a merge conflict, ahead of a failed check', () => {+ expect(classifyPrFailure({ state: 'CLOSED', mergeStateStatus: 'DIRTY' })).toBe('merge-conflict');+ // A conflicted branch is the more fundamental blocker, so it wins over a check fail.+ expect(classifyPrFailure({+ state: 'OPEN', mergeStateStatus: 'DIRTY', statusCheckRollup: [{ conclusion: 'FAILURE' }]+ })).toBe('merge-conflict');+ });++ it('reads a failing check verdict as validation-failed (CheckRun or StatusContext shape)', () => {+ expect(classifyPrFailure({ state: 'CLOSED', statusCheckRollup: [{ conclusion: 'SUCCESS' }, { conclusion: 'FAILURE' }] }))+ .toBe('validation-failed');+ // StatusContext rows carry `state`, not `conclusion`.+ expect(classifyPrFailure({ state: 'CLOSED', statusCheckRollup: [{ state: 'ERROR' }] })).toBe('validation-failed');+ expect(classifyPrFailure({ state: 'CLOSED', statusCheckRollup: [{ conclusion: 'TIMED_OUT' }] })).toBe('validation-failed');+ });++ it('returns null when checks all passed or are ambiguous (conservative)', () => {+ expect(classifyPrFailure({ state: 'CLOSED', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }] }))+ .toBeNull();+ // CANCELLED/SKIPPED/NEUTRAL are ambiguous (superseded/opt-out) → honest null.+ expect(classifyPrFailure({ state: 'CLOSED', statusCheckRollup: [{ conclusion: 'CANCELLED' }, { conclusion: 'SKIPPED' }] }))+ .toBeNull();+ });++ it('only ever yields a storable rejection token', () => {+ for (const view of [+ { state: 'CLOSED', mergeStateStatus: 'DIRTY' },+ { state: 'CLOSED', statusCheckRollup: [{ conclusion: 'FAILURE' }] }+ ]) {+ expect(REJECTION_REASONS).toContain(classifyPrFailure(view));+ }+ });+});++describe('isPrRefinableReason (#2748, deliverable 2)', () => {+ it('is true only for the generic decline and the unknown sentinel', () => {+ expect(isPrRefinableReason('user-rejected')).toBe(true);+ expect(isPrRefinableReason(UNKNOWN_REJECTION_REASON)).toBe(true);+ });++ it('is false for every diagnosis a more authoritative signal already made', () => {+ for (const r of ['duplicate', 'scope-mismatch', 'missing-context', 'quality-issue', 'merge-conflict', 'validation-failed', null]) {+ expect(isPrRefinableReason(r)).toBe(false);+ }+ });});describe('classifyClosingComment', () => {