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): scope implementing-PR ref to the issue's repo; stop re-reading settled PR failures

[._.]/ Adam Eivya06f457758e0
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index eb5bf21a43..e038cde3e9 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -2105,24 +2105,60 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =
// 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),
+ // PR's state when it holds a number here. Scoped to the issue's own repo (parsed
+ // from its url) so a cross-repo closing PR can't resolve to the wrong number.
+ implementingPr: extractImplementingPr(i.closedByPullRequestsReferences, repoSlugFromUrl(i.url || i.web_url)),
slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')
}))
};
}
+/**
+ * Parse an `owner/repo` slug (lower-cased for case-insensitive compare) from a GitHub
+ * issue/PR URL — `https://HOST/owner/repo/(issues|pull)/N` — host-agnostic so it works
+ * on github.com and Enterprise. Returns null when the shape doesn't match.
+ */
+export function repoSlugFromUrl(url) {
+ if (typeof url !== 'string') return null;
+ const m = url.match(/^https?:\/\/[^/]+\/([^/]+)\/([^/]+)\/(?:issues|pull)\/\d+/);
+ return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;
+}
+
+/**
+ * The `owner/repo` a `closedByPullRequestsReferences` entry belongs to — from its
+ * structured `repository { owner { login }, name }`, falling back to parsing its `url`.
+ * Null when neither is present. Lower-cased to match `repoSlugFromUrl`.
+ */
+function refRepoSlug(ref) {
+ const owner = ref?.repository?.owner?.login;
+ const name = ref?.repository?.name;
+ if (typeof owner === 'string' && typeof name === 'string') return `${owner}/${name}`.toLowerCase();
+ return repoSlugFromUrl(ref?.url);
+}
+
/**
* 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.
+ *
+ * `selfRepo` (the issue's own `owner/repo`) scopes the match: the reconciler later runs
+ * `gh pr view <number>` in the issue's checkout, so a reference from a DIFFERENT repo
+ * (a cross-repo/fork PR that closed the issue) would resolve to the wrong PR number in
+ * cwd's repo — or none — and mis-diagnose the rejection. So a ref whose repo is known
+ * and differs from `selfRepo` is skipped. When `selfRepo` is unknown or a ref carries
+ * no repo, it is accepted (same-repo is the overwhelmingly common case for an LI
+ * proposal implemented in its own repo), preserving prior behavior.
*/
-export function extractImplementingPr(refs) {
+export function extractImplementingPr(refs, selfRepo = null) {
if (!Array.isArray(refs)) return null;
+ const self = typeof selfRepo === 'string' ? selfRepo.toLowerCase() : null;
for (let i = refs.length - 1; i >= 0; i -= 1) {
const n = refs[i]?.number;
- if (Number.isInteger(n) && n > 0) return n;
+ if (!Number.isInteger(n) || n <= 0) continue;
+ const refRepo = refRepoSlug(refs[i]);
+ if (self && refRepo && refRepo !== self) continue;
+ return n;
}
return null;
}
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index ab5e626974..c123515239 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -65,6 +65,7 @@ import {
listForgeIssues,
extractClosingComment,
extractImplementingPr,
+ repoSlugFromUrl,
readImplementingPrState,
listBlockingIssues,
fileProposalToForge,
@@ -1950,6 +1951,32 @@ describe('forge I/O (injected exec)', () => {
expect(extractImplementingPr([{ number: 0 }, { number: -3 }])).toBeNull();
});
+ it('extractImplementingPr skips a cross-repo reference when the issue repo is known (codex P2)', () => {
+ const refs = [
+ { number: 55, repository: { owner: { login: 'someone' }, name: 'other-repo' } },
+ { number: 56, repository: { owner: { login: 'atomantic' }, name: 'PortOS' } }
+ ];
+ // Same-repo ref wins even though the cross-repo one is later in the list.
+ expect(extractImplementingPr(refs, 'atomantic/PortOS')).toBe(56);
+ // A ref from another repo alone is rejected — `gh pr view 55` in cwd would read the
+ // wrong PR. Falls through to null rather than mis-diagnosing.
+ expect(extractImplementingPr([refs[0]], 'atomantic/PortOS')).toBeNull();
+ // Repo match is case-insensitive (GitHub slugs are).
+ expect(extractImplementingPr([{ number: 57, url: 'https://github.com/Atomantic/portos/pull/57' }], 'atomantic/PortOS')).toBe(57);
+ // Unknown self-repo, or a ref with no repo info, degrades to accepting (same-repo
+ // is the common case) — preserves prior behavior.
+ expect(extractImplementingPr(refs, null)).toBe(56);
+ expect(extractImplementingPr([{ number: 58 }], 'atomantic/PortOS')).toBe(58);
+ });
+
+ it('repoSlugFromUrl parses owner/repo from an issue or PR URL, host-agnostic', () => {
+ expect(repoSlugFromUrl('https://github.com/atomantic/PortOS/issues/2748')).toBe('atomantic/portos');
+ expect(repoSlugFromUrl('https://github.com/owner/repo/pull/5')).toBe('owner/repo');
+ expect(repoSlugFromUrl('https://github.example.com/org/proj/issues/9')).toBe('org/proj');
+ expect(repoSlugFromUrl('https://github.com/owner/repo')).toBeNull();
+ expect(repoSlugFromUrl(null)).toBeNull();
+ });
+
it('readImplementingPrState parses gh pr view, and is gh-only (#2748)', async () => {
const exec = vi.fn().mockResolvedValue({
code: 0,
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index 0ab6111869..cb2c1ca297 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -23,7 +23,7 @@ import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
import { createCollectionStore } from '../lib/collectionStore.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 { classifyRejection, classifyPrFailure, isPrRefinableReason, isPrFailureReason, 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
@@ -380,9 +380,20 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date
// 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 });
+ if (isPrFailureReason(r.rejectionReason)) {
+ // Already diagnosed from THIS PR on a prior tick, and the free signals still
+ // don't supersede it — a new authoritative label/close-reason would have made
+ // the free classification specific (not refinable), taking the branch above.
+ // Keep the settled diagnosis instead of re-spawning `gh pr view` on every tick
+ // for the record's whole 30-day retention (codex P2). Preserving it here (rather
+ // than just skipping the fetch) also stops the write-guard below from downgrading
+ // the stored PR token back to the generic free reason.
+ rejectionReason = r.rejectionReason;
+ } else {
+ 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,
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index b86c1da9a8..8e437b02ff 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -549,6 +549,45 @@ describe('reconcileOutcomes', () => {
expect((await rowsBySlug())['boom'].rejectionReason).toBe('user-rejected');
});
+ it('does NOT re-read the PR once a record is already settled to a PR-failure token (codex P2)', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'settled' }, store);
+ const issue = { slug: 'settled', state: 'closed', stateReason: 'not_planned', implementingPr: 910, closedAt: '2026-07-01T00:00:00Z' };
+ // First tick: the generic decline is refined to validation-failed via the PR read.
+ const firstRead = vi.fn().mockResolvedValue({ state: 'CLOSED', statusCheckRollup: [{ conclusion: 'FAILURE' }] });
+ await reconcileOutcomes({ appId: 'app-1', cli: 'gh', readPrState: firstRead, existingIssues: [issue] }, store);
+ expect(firstRead).toHaveBeenCalledTimes(1);
+ expect((await rowsBySlug())['settled'].rejectionReason).toBe('validation-failed');
+
+ // Second tick (same generic free signal, same ref): the settled PR diagnosis is
+ // kept WITHOUT re-spawning gh pr view, and the record is not rewritten/downgraded.
+ const secondRead = vi.fn().mockResolvedValue({ state: 'CLOSED', statusCheckRollup: [{ conclusion: 'FAILURE' }] });
+ const updated = await reconcileOutcomes({ appId: 'app-1', cli: 'gh', readPrState: secondRead, existingIssues: [issue] }, store);
+ expect(secondRead).not.toHaveBeenCalled();
+ expect(updated).toBe(0);
+ expect((await rowsBySlug())['settled'].rejectionReason).toBe('validation-failed');
+ });
+
+ it('lets a newly-added authoritative label supersede a settled PR-failure token', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'relabelled' }, store);
+ const firstRead = vi.fn().mockResolvedValue({ state: 'OPEN', mergeStateStatus: 'DIRTY' });
+ await reconcileOutcomes({
+ appId: 'app-1', cli: 'gh', readPrState: firstRead,
+ existingIssues: [{ slug: 'relabelled', state: 'closed', stateReason: 'not_planned', implementingPr: 911, closedAt: '2026-07-01T00:00:00Z' }]
+ }, store);
+ expect((await rowsBySlug())['relabelled'].rejectionReason).toBe('merge-conflict');
+
+ // A human later adds a `duplicate` label: the free classification is now specific
+ // (not refinable), so the PR read is skipped and the label wins over the PR token.
+ const secondRead = vi.fn();
+ const updated = await reconcileOutcomes({
+ appId: 'app-1', cli: 'gh', readPrState: secondRead,
+ existingIssues: [{ slug: 'relabelled', state: 'closed', stateReason: 'not_planned', labels: ['duplicate'], implementingPr: 911, closedAt: '2026-07-01T00:00:00Z' }]
+ }, store);
+ expect(secondRead).not.toHaveBeenCalled();
+ expect(updated).toBe(1);
+ expect((await rowsBySlug())['relabelled'].rejectionReason).toBe('duplicate');
+ });
+
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.
diff --git a/server/services/layeredIntelligenceRejections.js b/server/services/layeredIntelligenceRejections.js
index 66cdc03ca2..ecc0bdea4a 100644
--- a/server/services/layeredIntelligenceRejections.js
+++ b/server/services/layeredIntelligenceRejections.js
@@ -241,6 +241,18 @@ export function classifyPrFailure(prView) {
return null;
}
+// The REJECTION_REASONS subset that classifyPrFailure produces (#2748, deliverable 2).
+// Once a record carries one of these it was already diagnosed from its implementing
+// PR's state, so re-reading that PR on a later reconcile can only reproduce the same
+// token — the reconciler consults this to STOP re-spawning `gh pr view` for an
+// already-settled PR diagnosis on every scheduler tick across the 30-day retention.
+export const PR_FAILURE_REASONS = ['merge-conflict', 'validation-failed'];
+
+/** Whether `reason` is a PR-state-derived diagnosis (merge-conflict / validation-failed). */
+export function isPrFailureReason(reason) {
+ return PR_FAILURE_REASONS.includes(reason);
+}
+
// 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