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
address review (codex): keep the PR target scoped and stop offering dead actions
Adam Eivya633d5630534
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsxindex 5a0b43907a..2290e54cd6 100644--- a/client/src/components/apps/tabs/PullRequestsTab.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx@@ -287,12 +287,13 @@ export default function PullRequestsTab({ appId, appName }) {already: `pr-reviewer is already queued for ${forgeLabel} #${pullRequest.number}`,});- // pr-reviewer's model-abuse preflight reads the forge through `gh`, so the- // targeted review button is meaningless on a GitLab remote. The server refuses- // it there anyway; hiding it keeps the row from offering a guaranteed failure.- const rowActions = [+ // pr-reviewer covers only GitHub PRs opened by someone else against the default+ // branch, and the server answers every other row with 409. `reviewEligible` is+ // the server's own verdict per row, so the button appears exactly where it can+ // work rather than offering a guaranteed failure.+ const rowActionsFor = pullRequest => [{ kind: 'resolve', onQueue: handleResolve },- ...(data?.forge === 'github' ? [{ kind: 'review', onQueue: handleReview }] : []),+ ...(pullRequest.reviewEligible ? [{ kind: 'review', onQueue: handleReview }] : []),];if (loading && !data) return <BrailleSpinner text="Loading pull requests" />;@@ -335,9 +336,9 @@ export default function PullRequestsTab({ appId, appName }) {<p>Resolve and merge queues a PortOS agent to inspect feedback, fix the branch, wait for checks, and merge when the forge allows it. It uses the configured Code Review Defaults.</p>- {data?.forge === 'github' && (+ {(data?.pullRequests || []).some(pullRequest => pullRequest.reviewEligible) && (<p>- PR review points the <span className="font-mono">pr-reviewer</span> scheduled task at this one request instead of letting it sweep every open contributor PR. It covers requests opened by someone else against the default branch, and its security scan still holds the review behind approval.+ PR review points the <span className="font-mono">pr-reviewer</span> scheduled task at this one request instead of letting it sweep every open contributor PR. It appears only on requests it can review — opened by someone else against the default branch — and its security scan still holds the review behind approval.</p>)}</div>@@ -428,7 +429,7 @@ export default function PullRequestsTab({ appId, appName }) {</div><div className="shrink-0 lg:pt-0.5 flex flex-wrap items-start gap-2">- {rowActions.map(({ kind, onQueue }) => {+ {rowActionsFor(pullRequest).map(({ kind, onQueue }) => {const { label, Icon, title } = ACTION_KINDS[kind];const actionStatus = actions[kind][pullRequest.number]?.status;if (actionStatus && actionStatus !== 'queuing') {diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsxindex 55d7ff8dfb..871e54ef74 100644--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx@@ -40,6 +40,7 @@ const PULL_REQUEST = {mergeStateStatus: 'DIRTY',mergeable: 'CONFLICTING',labels: ['bug'],+ reviewEligible: true,checks: [{ name: 'unit', status: 'SUCCESS', url: null },{ name: 'lint', status: 'SUCCESS', url: null },@@ -232,8 +233,8 @@ describe('PullRequestsTab', () => {expect(screen.queryByRole('button', { name: /PR review/ })).not.toBeInTheDocument();});- it('omits the pr-reviewer action on a GitLab remote', async () => {- api.getAppPullRequests.mockResolvedValue({ ...okPayload([PULL_REQUEST]), forge: 'gitlab' });+ it('omits the pr-reviewer action on a row the server marked ineligible', async () => {+ api.getAppPullRequests.mockResolvedValue(okPayload([{ ...PULL_REQUEST, reviewEligible: false }]));await renderTab();diff --git a/server/routes/apps/pullRequests.js b/server/routes/apps/pullRequests.jsindex ecf5fad379..09a15faffa 100644--- a/server/routes/apps/pullRequests.js+++ b/server/routes/apps/pullRequests.js@@ -22,7 +22,11 @@ import { resolveReviewLoopOptions } from '../../services/codeReview.js';import { getAllTasks } from '../../services/cos.js';import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';import { listAppPullRequests } from '../../services/appPullRequests.js';-import { listExternalOpenPullRequests } from '../../services/prReviewerSecurity.js';+import {+ isReviewablePullRequest,+ listExternalOpenPullRequests,+ resolvePrReviewerTargetScope,+} from '../../services/prReviewerSecurity.js';import { getOnDemandRequests, triggerOnDemandTask } from '../../services/taskSchedule.js';import { loadApp } from './shared.js';@@ -82,12 +86,31 @@ async function readActiveTasks() {// is queued through the on-demand lane, so without these a row would show no// action at all between the click and the generator's next cycle — and a page// refresh in that window would offer the button again.+//+// `null` means UNREADABLE, which is not the same as "nothing queued": collapsing+// the two would let the review route miss an existing request and queue a+// duplicate scan of the same public PR. The POST fails closed on it; the GET,+// which only paints a button, degrades to showing no queued action.async function readPendingOnDemandRequests() {const requests = await getOnDemandRequests().catch(err => {console.error(`❌ app-pull-requests: could not read on-demand requests: ${err.message}`);- return [];+ return null;+ });+ return Array.isArray(requests) ? requests : null;+}++// Per-row pr-reviewer eligibility, resolved from the SAME facts the security+// preflight filters on. Without it the tab would paint a Review button on every+// GitHub row, including the ones the route answers with 409 — an action that is+// guaranteed to fail. Only worth the extra `gh repo view` when the forge is+// GitHub; every other forge is ineligible by construction.+async function resolveReviewEligibility(app, result) {+ if (result.forge !== 'github') return () => false;+ const scope = await resolvePrReviewerTargetScope(app).catch(err => {+ console.error(`❌ app-pull-requests: could not resolve pr-reviewer scope: ${err.message}`);+ return null;});- return Array.isArray(requests) ? requests : [];+ return pullRequest => isReviewablePullRequest(scope, pullRequest);}function actionFor(pullRequest, tasks, appId) {@@ -99,7 +122,7 @@ function actionFor(pullRequest, tasks, appId) {function reviewActionFor(pullRequest, tasks, requests, appId) {const task = tasks?.find(candidate => isReviewTaskFor(candidate, appId, pullRequest));if (task) return { taskId: task.id, status: task.status };- const queued = requests.find(request => isReviewRequestFor(request, appId, pullRequest));+ const queued = requests?.find(request => isReviewRequestFor(request, appId, pullRequest));return queued ? { taskId: null, status: 'pending' } : null;}@@ -114,7 +137,11 @@ async function listWithActionState(app) {const pullRequests = Array.isArray(result?.pullRequests) ? result.pullRequests : [];if (!pullRequests.length || result.transient) return { result, tasks: null };- const [tasks, requests] = await Promise.all([readActiveTasks(), readPendingOnDemandRequests()]);+ const [tasks, requests, reviewEligible] = await Promise.all([+ readActiveTasks(),+ readPendingOnDemandRequests(),+ resolveReviewEligibility(app, result),+ ]);return {result: {...result,@@ -122,6 +149,7 @@ async function listWithActionState(app) {...pullRequest,agentAction: actionFor(pullRequest, tasks, app.id),reviewAction: reviewActionFor(pullRequest, tasks, requests, app.id),+ reviewEligible: reviewEligible(pullRequest),})),},tasks,@@ -270,18 +298,30 @@ router.post('/:id/pull-requests/:number/review', loadApp, asyncHandler(async (recontext: { reason: target.code || 'security-scan-target-unavailable' },});}- if (!target.prs.some(candidate => candidate.number === number)) {+ const pullRequest = target.prs.find(candidate => candidate.number === number);+ if (!pullRequest) {throw new ServerError(`Pull request #${number} is not reviewable — PR review covers open GitHub pull requests against the default branch that were opened by someone else`,{ status: 409, code: 'PULL_REQUEST_NOT_REVIEWABLE' },);}+ // The security scan fingerprints the PR set by head commit, and the reader+ // normalizes an unusable `headRefOid` to null. Accepting one anyway would+ // return 202 for a run the preflight then drops on a null fingerprint — the UI+ // would show a queued review that can never start.+ if (!pullRequest.headRefOid) {+ throw new ServerError(+ `Pull request #${number} has no resolvable head commit, so its content cannot be safety-screened`,+ { status: 502, code: 'PULL_REQUEST_CONTEXT_UNAVAILABLE' },+ );+ }const [tasks, requests] = await Promise.all([readActiveTasks(), readPendingOnDemandRequests()]);- // Fail CLOSED on an unreadable task store, matching /resolve: `reviewActionFor`- // reads a null task list as "no run in flight", so queueing anyway would spend a- // second model-abuse scan and code review on a public PR already being reviewed.- if (tasks === null) {+ // Fail CLOSED on unreadable task or on-demand state, matching /resolve:+ // `reviewActionFor` reads either as "no run in flight", so queueing anyway would+ // spend a second model-abuse scan and code review on a public PR already being+ // reviewed.+ if (tasks === null || requests === null) {throw new ServerError('Could not inspect existing CoS actions before queueing this review', {status: 503,code: 'AGENT_ACTION_UNAVAILABLE',diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.jsindex 4db8b15dba..e406647c36 100644--- a/server/routes/apps/pullRequests.test.js+++ b/server/routes/apps/pullRequests.test.js@@ -18,8 +18,10 @@ vi.mock('../../services/codeReview.js', () => ({vi.mock('../../services/agentWorktreeCleanup.js', () => ({spawnReviewLoopFollowUp: vi.fn(),}));-vi.mock('../../services/prReviewerSecurity.js', () => ({+vi.mock('../../services/prReviewerSecurity.js', async (importOriginal) => ({+ ...(await importOriginal()),listExternalOpenPullRequests: vi.fn(),+ resolvePrReviewerTargetScope: vi.fn(),}));vi.mock('../../services/taskSchedule.js', () => ({getOnDemandRequests: vi.fn(),@@ -31,7 +33,7 @@ import { listAppPullRequests } from '../../services/appPullRequests.js';import { getAllTasks } from '../../services/cos.js';import { resolveReviewLoopOptions } from '../../services/codeReview.js';import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';-import { listExternalOpenPullRequests } from '../../services/prReviewerSecurity.js';+import { listExternalOpenPullRequests, resolvePrReviewerTargetScope } from '../../services/prReviewerSecurity.js';import { getOnDemandRequests, triggerOnDemandTask } from '../../services/taskSchedule.js';const APP = { id: 'app-001', name: 'Widget', repoPath: '/repo', workTracker: 'auto' };@@ -39,7 +41,9 @@ const PULL_REQUEST = {number: 17,title: 'Fix the save path',url: 'https://github.com/acme/widget/pull/17',+ author: 'alice',headBranch: 'fix/save-path',+ baseBranch: 'main',};const listResult = () => ({@@ -86,6 +90,13 @@ describe('app pull-request routes', () => {defaultBranch: 'main',prs: [{ number: 17, authorLogin: 'alice', headRefOid: 'a'.repeat(40) }],});+ resolvePrReviewerTargetScope.mockResolvedValue({+ ok: true,+ repoSpec: 'acme/widget',+ repoFullName: 'acme/widget',+ defaultBranch: 'main',+ selfLogin: 'bob',+ });getOnDemandRequests.mockResolvedValue([]);triggerOnDemandTask.mockResolvedValue({ id: 'demand-abc', taskType: 'pr-reviewer', appId: 'app-001', targetPullRequest: 17 });});@@ -244,6 +255,68 @@ describe('app pull-request routes', () => {expect(response.body.pullRequests[0].reviewAction).toEqual({ taskId: null, status: 'pending' });});+ it('marks a contributor PR against the default branch as pr-reviewer eligible', async () => {+ const response = await request(app).get('/api/apps/app-001/pull-requests');++ expect(response.body.pullRequests[0].reviewEligible).toBe(true);+ });++ it('marks the operator\'s own PR as ineligible so the row offers no failing action', async () => {+ listAppPullRequests.mockResolvedValue({+ ...listResult(),+ pullRequests: [{ ...PULL_REQUEST, author: 'bob' }],+ });++ const response = await request(app).get('/api/apps/app-001/pull-requests');++ expect(response.body.pullRequests[0].reviewEligible).toBe(false);+ });++ it('marks a PR against a non-default base as ineligible', async () => {+ listAppPullRequests.mockResolvedValue({+ ...listResult(),+ pullRequests: [{ ...PULL_REQUEST, baseBranch: 'release' }],+ });++ const response = await request(app).get('/api/apps/app-001/pull-requests');++ expect(response.body.pullRequests[0].reviewEligible).toBe(false);+ });++ it('marks every row ineligible when the pr-reviewer scope cannot be resolved', async () => {+ resolvePrReviewerTargetScope.mockResolvedValue({ ok: false, code: 'security-scan-forge-unreachable' });++ const response = await request(app).get('/api/apps/app-001/pull-requests');++ expect(response.body.pullRequests[0].reviewEligible).toBe(false);+ });++ it('refuses a target whose head commit cannot be fingerprinted', async () => {+ listExternalOpenPullRequests.mockResolvedValue({+ ok: true,+ repoSpec: 'acme/widget',+ repoFullName: 'acme/widget',+ defaultBranch: 'main',+ prs: [{ number: 17, authorLogin: 'alice', headRefOid: null }],+ });++ const response = await request(app).post('/api/apps/app-001/pull-requests/17/review');++ expect(response.status).toBe(502);+ expect(response.body.code).toBe('PULL_REQUEST_CONTEXT_UNAVAILABLE');+ expect(triggerOnDemandTask).not.toHaveBeenCalled();+ });++ it('fails closed when the on-demand queue cannot be read before queueing a review', async () => {+ getOnDemandRequests.mockRejectedValue(new Error('schedule unreadable'));++ const response = await request(app).post('/api/apps/app-001/pull-requests/17/review');++ expect(response.status).toBe(503);+ expect(response.body.code).toBe('AGENT_ACTION_UNAVAILABLE');+ expect(triggerOnDemandTask).not.toHaveBeenCalled();+ });+it('queues a pr-reviewer run scoped to one request', async () => {const response = await request(app).post('/api/apps/app-001/pull-requests/17/review');diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 18cd6dcc96..a35d0b8f7c 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2441,9 +2441,16 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nulet nextType;let selectionReason;+ // A stolen on-demand request may be SCOPED to one PR (the PRs/MRs tab's+ // per-row pr-reviewer trigger). Carrying it is not optional: the generator+ // reads no target as "sweep every external PR", so dropping it here would+ // silently promote the user's one-row click into a full-repo review — the+ // same widening the perpetual-refill skip guards against on the other side.+ let targetPullRequest = null;if (appRequests.length > 0) {const request = appRequests[0];+ targetPullRequest = request.targetPullRequest ?? null;await taskSchedule.clearOnDemandRequest(request.id);// Only a human "Run" may clear the drain's brakes (park state, dispatch// count); the policy lives in applyOnDemandRunResets so this idle-review@@ -2491,7 +2498,8 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu// spawn; the per-type generator does not record execution itself.const task = await generateManagedAppImprovementTaskForType(nextType, app, state, {ignoreTaskId,- deferPerpetualDispatch: true+ deferPerpetualDispatch: true,+ targetPullRequest});// Idle-review can steal a queued on-demand request for this app. That// request is still a user Run — apply the same consent as Priority 0.diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex e0a49143bd..618dfb47ca 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -327,7 +327,10 @@ describe('both on-demand engines apply consent before addTask', () => {it('idle-review steal path consents when it drains an on-demand request', () => {const start = GEN_SRC.indexOf('async function generateManagedAppImprovementTask(app, state');expect(start).toBeGreaterThan(-1);- const body = GEN_SRC.slice(start, start + 3500);+ // Slice to the end of the function, not a fixed byte window: the consent line+ // sits at the bottom of a body that grows, so a magic number makes an+ // unrelated comment above it read as a missing consent call.+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return task;', start));expect(body).toMatch(/selectionReason === 'on-demand'\) applyOnDemandConsent\(task\)/);});});@@ -1870,6 +1873,15 @@ describe('pr-reviewer security preflight wiring', () => {expect(body).toContain('metadata.targetPullRequest = targetPullRequest');});+ it('carries a stolen on-demand request\'s PR target through the idle-review path', () => {+ const start = GEN_SRC.indexOf('const appRequests = onDemandRequests.filter(');+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return task;', start));+ // The idle tier can consume a queued on-demand request instead of Priority 0.+ // Dropping the target there re-widens a one-row click into a full sweep.+ expect(body).toContain('targetPullRequest = request.targetPullRequest ?? null');+ expect(body).toMatch(/generateManagedAppImprovementTaskForType\([\s\S]*?targetPullRequest\n/);+ });+it('keeps a targeted run distinguishable from the sweep in the duplicate guard', () => {expect(GEN_SRC).toContain('function scopeDescriptionToPullRequest(description, metadata)');const genStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');diff --git a/server/services/prReviewerSecurity.js b/server/services/prReviewerSecurity.jsindex c253b4f443..b63a4ddfd2 100644--- a/server/services/prReviewerSecurity.js+++ b/server/services/prReviewerSecurity.js@@ -33,7 +33,16 @@ const safeText = (value, max) => typeof value === 'string' ? value.slice(0, max)* Find every currently-open PR from an external human contributor. This is a* public-metadata operation only; it does not fetch a branch or run code.*/-export async function listExternalOpenPullRequests(app) {+/**+ * The three facts that decide which of a repo's open PRs pr-reviewer may target:+ * the `gh` repo selector, the default branch it reviews against, and the login+ * whose own PRs are excluded. Split out of `listExternalOpenPullRequests` so a+ * caller that already HAS the PR rows — the PRs/MRs tab, deciding whether to+ * offer its per-row Review action — can answer "is this row reviewable?" from+ * the same source of truth instead of re-listing every PR or re-deriving the+ * rule and drifting from it.+ */+export async function resolvePrReviewerTargetScope(app) {const origin = await getOriginInfo(app?.repoPath).catch(() => null);const repoSpec = githubRepoSpec(origin);if (!repoSpec) return failure('security-scan-not-a-github-repo');@@ -51,9 +60,38 @@ export async function listExternalOpenPullRequests(app) {const selfLogin = await getSelfLogin(githubApiHost(origin.host));if (!selfLogin) return failure('security-scan-self-login-unavailable');+ return {+ ok: true,+ repoSpec,+ repoFullName: origin.fullName,+ defaultBranch: defaultBranch.trim(),+ selfLogin,+ };+}++/**+ * Whether one already-listed PR row is a pr-reviewer target, per a resolved+ * scope. Mirrors exactly what `listExternalOpenPullRequests` keeps — open+ * against the default branch, opened by someone other than the signed-in+ * account — so a UI gated on this and the route's authoritative check agree.+ */+export function isReviewablePullRequest(scope, pullRequest) {+ const author = pullRequest?.author;+ return scope?.ok === true+ && pullRequest?.baseBranch === scope.defaultBranch+ && typeof author === 'string'+ && author.length > 0+ && author.toLowerCase() !== String(scope.selfLogin).toLowerCase();+}++export async function listExternalOpenPullRequests(app) {+ const scope = await resolvePrReviewerTargetScope(app);+ if (!scope.ok) return scope;+ const { repoSpec, repoFullName, defaultBranch, selfLogin } = scope;+const raw = await execGh(['pr', 'list', '--repo', repoSpec,- '--base', defaultBranch.trim(), '--state', 'open',+ '--base', defaultBranch, '--state', 'open','--limit', String(SECURITY_SCAN_MAX_OPEN_PRS),'--json', 'number,author,url,headRefOid,updatedAt,title,body',]).catch(() => null);@@ -85,8 +123,8 @@ export async function listExternalOpenPullRequests(app) {return {ok: true,repoSpec,- repoFullName: origin.fullName,- defaultBranch: defaultBranch.trim(),+ repoFullName,+ defaultBranch,prs: prs.filter((pr) => String(pr.authorLogin).toLowerCase() !== String(selfLogin).toLowerCase()),};}