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
fix: honor local PR review routing and enable CI-gated auto-merge
[._.]/ Adam Eivy95385908d0f5
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsxindex 71434a200d..5c15606565 100644--- a/client/src/components/apps/tabs/PullRequestsTab.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx@@ -138,8 +138,8 @@ export default function PullRequestsTab({ appId, appName }) {const actionsRef = useRef(emptyActions());const requestRef = useRef(0);- // Page-level provider/model/effort pin for every Resolve & merge / PR review- // click on this tab — initially the active provider and configured model.+ // Resolve & merge defaults to the active provider. PR review follows its+ // saved stages unless the user explicitly enables the eligibility override.// Auto remains available for server-side routing. Mirrors the Issues// tab's "Run with" picker: a session convenience, never persisted.const {@@ -147,6 +147,7 @@ export default function PullRequestsTab({ appId, appName }) {setSelectedProviderId, setSelectedModel} = useProviderModels({ filter: enabledProcessProviderFilter, allowDefault: true, preselectDefaults: true, silent: true, withEffort: true });const [effort, setEffort] = useState('');+ const [overrideReviewProvider, setOverrideReviewProvider] = useState(false);// One writer for the whole `{ kind: { number: action } }` bag so the ref the// socket handler reads and the state React renders can never disagree.@@ -318,7 +319,7 @@ export default function PullRequestsTab({ appId, appName }) {});const handleReview = pullRequest => queueAction('review', pullRequest, {- call: () => api.reviewAppPullRequest(appId, pullRequest.number, providerSettings),+ call: () => api.reviewAppPullRequest(appId, pullRequest.number, overrideReviewProvider ? providerSettings : {}),queued: `Queued the pr-reviewer task for ${forgeLabel} #${pullRequest.number}`,already: `pr-reviewer is already queued for ${forgeLabel} #${pullRequest.number}`,});@@ -374,7 +375,7 @@ export default function PullRequestsTab({ appId, appName }) {</p>{(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 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.+ 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 uses the providers saved on its review stages. The security scan must pass before either review stage runs.</p>)}</div>@@ -401,6 +402,13 @@ export default function PullRequestsTab({ appId, appName }) {</div></div>+ <div className="text-xs text-gray-400">+ <input id="override-pr-review-provider" type="checkbox" checked={overrideReviewProvider}+ onChange={event => setOverrideReviewProvider(event.target.checked)} className="mr-2" />+ <label htmlFor="override-pr-review-provider">Use Run with for PR review eligibility</label>+ <p className="mt-1">Off by default to preserve your scheduled providers. The final code review keeps its own stage settings.</p>+ </div>+{error && (<Banner tone="error" size="md" icon={AlertTriangle}>Couldn't load pull requests — {error}diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsxindex 8cecc23849..46524c7691 100644--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx@@ -136,7 +136,7 @@ describe('PullRequestsTab', () => {));});- it('carries the same provider/model pin into a PR review run', async () => {+ it('preserves scheduled review stages unless the user explicitly enables the override', async () => {api.getProviders.mockResolvedValue({providers: [{id: 'claude', name: 'Claude', type: 'cli', enabled: true,@@ -152,10 +152,30 @@ describe('PullRequestsTab', () => {fireEvent.click(screen.getByRole('button', { name: /PR review/ }));await waitFor(() => expect(api.reviewAppPullRequest).toHaveBeenCalledWith(- 'app-1', 17, { provider: 'claude', model: 'claude-opus-5', effort: undefined },+ 'app-1', 17, {},));});+ it('passes an explicitly enabled eligibility provider override', async () => {+ api.getProviders.mockResolvedValue({+ providers: [{+ id: 'claude', name: 'Claude', type: 'cli', enabled: true,+ models: ['claude-opus-5', 'claude-sonnet-5'], defaultModel: 'claude-sonnet-5',+ }],+ });+ await renderTab();++ await screen.findByText('Fix the save path');+ fireEvent.change(await screen.findByLabelText('Provider'), { target: { value: 'claude' } });+ fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'claude-opus-5' } });++ fireEvent.click(screen.getByLabelText('Use Run with for PR review eligibility'));+ fireEvent.click(screen.getByRole('button', { name: /PR review/ }));++ await waitFor(() => expect(api.reviewAppPullRequest).toHaveBeenCalledWith(+ 'app-1', 17, { provider: 'claude', model: 'claude-opus-5', effort: undefined },+ ));+ });it('queues a review-loop resolve action and shows its task state', async () => {await renderTab();@@ -283,7 +303,7 @@ describe('PullRequestsTab', () => {fireEvent.click(await screen.findByRole('button', { name: /PR review/ }));await waitFor(() => expect(api.reviewAppPullRequest).toHaveBeenCalledWith(- 'app-1', 17, { provider: undefined, model: undefined, effort: undefined },+ 'app-1', 17, {},));expect(await screen.findByRole('link', { name: /PR review: Queued/ })).toBeInTheDocument();// The resolve action is a separate lane and must stay offered.diff --git a/docs/features/messages-security.md b/docs/features/messages-security.mdindex 750540a595..2ef4446882 100644--- a/docs/features/messages-security.md+++ b/docs/features/messages-security.md@@ -23,6 +23,12 @@ The GitHub role split does not change explicitly configured Jira or existing GitPR review does not execute contributor tests or apply patches in its default stages. Read-only filesystem access and a disposable worktree are not equivalent to denying tools or isolating malicious code. A provider must expose an actual maintained recipe for the requested posture; unsupported stage pins must be corrected in schedule settings. A screening pass never grants broader permissions.+PR review stage provider/model pins are strict: disabled, unsupported or unavailable selections stop the review rather than switching to a subscription provider or a different model. Local classifier setup/runtime failures and review provider/model failures raise a notification and queue a deduplicated CoS investigation. Investigation prompts contain only server-owned diagnostics, never contributor text, model output or transport errors. A malicious-content finding is not an infrastructure incident.++The PR page follows the saved stage providers by default. Its **Use Run with for PR review eligibility** checkbox explicitly overrides only the eligibility stage for that invocation; the final review keeps its own stage settings. Stage-specific settings take precedence over broader schedule/app defaults. The shared Abuse Guard text API selection does not replace these PR stage selections: Stage 1 always uses the dedicated local classifier, while stages 2 and 3 use the providers configured in **CoS > Schedule > PR Reviewer**.++After an approval, the deterministic coordinator merges a green, mergeable PR or requests GitHub auto-merge while CI is pending. The enable-only GraphQL mutation names the reviewed head SHA, so it cannot authorize a different commit or immediately bypass pending checks on an unprotected repository. A rejected auto-merge request raises a notification and retains the approval for the existing bounded merge poller.+## Configure an installOpen **Models > LLMs > Abuse Guard** (`/models/llms/abuse`). Install the classifier explicitly, then choose an enabled text API provider and model for shared analysis. Use a local API endpoint for private messages. The page exposes shared policy defaults and source overrides; a failed or incomplete installation offers a repair path. Opening the page and reading status never runs inference or downloads a model.diff --git a/server/services/agentLifecycle.blockAndBail.test.js b/server/services/agentLifecycle.blockAndBail.test.jsindex 32e67396eb..17c5adcc40 100644--- a/server/services/agentLifecycle.blockAndBail.test.js+++ b/server/services/agentLifecycle.blockAndBail.test.js@@ -1,3 +1,6 @@+const reportInfrastructureFailure = vi.hoisted(() => vi.fn(async () => null));+vi.mock('./reviewInfrastructureFailure.js', () => ({ reportReviewInfrastructureFailure: reportInfrastructureFailure }));+/*** Every spawn-eligibility gate in `runAgentSpawn`, driven through the real* `spawnAgentForTask` boundary.@@ -453,7 +456,7 @@ describe('runAgentSpawn gates — public-review actions eligibility', () => {describe('runAgentSpawn gates — public-review provider posture', () => {// Unlike the two gates above, an unsupported provider IS an operator-visible// misconfiguration, so this one does raise an investigator.- it('blocks an unsupported provider AND emits agent:error', async () => {+ it('blocks an unsupported provider and queues only a trusted infrastructure diagnosis', async () => {vi.mocked(resolveAgentProviderAndModel).mockResolvedValue({ok: true, provider: OPENCODE_TUI, selectedModel: 'qwen', modelSelection: {},});@@ -472,7 +475,8 @@ describe('runAgentSpawn gates — public-review provider posture', () => {expect(update.status).toBe('blocked');expect(metadata.blockedCategory).toBe('public-review-provider-unsupported');expect(metadata.blockedReason).toContain("Provider 'opencode-tui'");- expect(agentErrors()).toEqual([{ taskId: task.id, error: metadata.blockedReason }]);+ expect(agentErrors()).toEqual([]);+ expect(reportInfrastructureFailure).toHaveBeenCalledWith({ code: metadata.blockedCategory, task });expect(markerReleasedFor(APP)).toBe(true);});});@@ -497,7 +501,8 @@ describe('runAgentSpawn gates — public-review model policy', () => {expect(update.status).toBe('blocked');expect(metadata.blockedCategory).toBe('public-review-model-not-installed');expect(metadata.blockedReason).toContain('public-review-model-not-installed');- expect(agentErrors()).toEqual([{ taskId: task.id, error: metadata.blockedReason }]);+ expect(agentErrors()).toEqual([]);+ expect(reportInfrastructureFailure).toHaveBeenCalledWith({ code: metadata.blockedCategory, task });expect(markerReleasedFor(APP)).toBe(true);});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex fd084ffbc8..93543b4bd2 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -267,7 +267,7 @@ async function runAgentSpawn(task) {* claim and start the task, then have its live `in_progress` record clobbered* to `blocked` — which outranks `in_progress` in the claim-aware merge.*/- const blockAndBail = async ({ reason, category, emit = 'agent:error', emitPayload = {}, persist = true }) => {+ const blockAndBail = async ({ reason, category, infrastructureCode, emit = 'agent:error', emitPayload = {}, persist = true }) => {if (persist) {await updateTask(task.id, {status: 'blocked',@@ -280,6 +280,16 @@ async function runAgentSpawn(task) {}, task.taskType || 'user').catch(() => {});}await cleanupOnError(reason);+ if (emit === 'agent:error' && publicReviewPostureForProfile(task.metadata?.executionProfile) === PUBLIC_REVIEW_NO_TOOL_POSTURE+ && (infrastructureCode || category?.startsWith('public-review-model-') || category === 'public-review-provider-unsupported')) {+ const { reportReviewInfrastructureFailure } = await import('./reviewInfrastructureFailure.js');+ await reportReviewInfrastructureFailure({ code: infrastructureCode || category, task }).catch(() => {+ emitLog('warn', 'Could not report PR review infrastructure failure', { taskId: task.id });+ });+ // The generic agent:error handler copies task context into an investigator.+ // This boundary reports only trusted diagnostics through the safe producer.+ emit = 'warn-log';+ }if (emit === 'agent:error') {cosEvents.emit('agent:error', { taskId: task.id, error: reason, ...emitPayload });} else if (emit === 'warn-log') {@@ -416,6 +426,7 @@ async function runAgentSpawn(task) {// Transient failures skip the block and stay pending to retry.return blockAndBail({reason: resolution.error,+ infrastructureCode: resolution.infrastructureCode,category: PROVIDER_CONFIG_BLOCKED_CATEGORY,persist: resolution.permanent,emitPayload: {diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 0baeaad6d0..0998d31ebe 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -679,7 +679,7 @@ describe('runAgentSpawn source — one block-and-bail epilogue', () => {const blockWrites = RUN_SPAWN_BODY.match(/status: 'blocked'/g) || [];expect(blockWrites.length, 'only blockAndBail may persist a blocked status').toBe(1);expect(RUN_SPAWN_BODY).toMatch(- /const blockAndBail = async \(\{ reason, category, emit = 'agent:error', emitPayload = \{\}, persist = true \}\) => \{/+ /const blockAndBail = async \(\{ reason, category, infrastructureCode, emit = 'agent:error', emitPayload = \{\}, persist = true \}\) => \{/);});@@ -691,7 +691,7 @@ describe('runAgentSpawn source — one block-and-bail epilogue', () => {it('persists the block BEFORE releasing the lease', () => {const start = RUN_SPAWN_BODY.indexOf('const blockAndBail =');expect(start, 'blockAndBail must exist').toBeGreaterThan(-1);- const body = RUN_SPAWN_BODY.slice(start, start + 1200);+ const body = RUN_SPAWN_BODY.slice(start, RUN_SPAWN_BODY.indexOf('\n };', start));const persistIdx = body.indexOf("status: 'blocked'");const cleanupIdx = body.indexOf('await cleanupOnError(reason)');expect(persistIdx).toBeGreaterThan(-1);@@ -705,7 +705,7 @@ describe('runAgentSpawn source — one block-and-bail epilogue', () => {// respawn is a standing decision and raises neither. Both are one word now.it('supports the three announcement modes the gates actually differ on', () => {const start = RUN_SPAWN_BODY.indexOf('const blockAndBail =');- const body = RUN_SPAWN_BODY.slice(start, start + 1200);+ const body = RUN_SPAWN_BODY.slice(start, RUN_SPAWN_BODY.indexOf('\n };', start));expect(body).toMatch(/if \(emit === 'agent:error'\) \{/);expect(body).toMatch(/\} else if \(emit === 'warn-log'\) \{/);expect(body).toMatch(/emitLog\('warn', `Public review withheld for task \$\{task\.id\}: \$\{category\}`/);diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.jsindex 04e1fbd924..ffcd0d4de6 100644--- a/server/services/agentProviderResolution.js+++ b/server/services/agentProviderResolution.js@@ -93,9 +93,8 @@ export async function resolveAgentProviderAndModel(task) {/*** Provider + model for a public-review stage. A stage's own provider/model/* effort pins (`metadata.provider` / `metadata.model`, set by the pipeline- * hand-off from the stage config) are honored when the pin is still eligible;- * otherwise the install's own eligible set decides, and an install with none- * fails PERMANENTLY so the task surfaces instead of re-dispatching forever.+ * hand-off from the stage config) are honored or fail permanently with a+ * configuration diagnosis. Only unpinned stages use the install's eligible set.*/async function resolvePublicReviewAgentProvider(task, posture) {const resolved = await resolvePublicReviewProvider({@@ -103,22 +102,16 @@ async function resolvePublicReviewAgentProvider(task, posture) {pinnedProviderId: task.metadata?.provider || null,});if (!resolved.ok) {- return { ok: false, permanent: true, error: resolved.error, providerId: task.metadata?.provider || undefined };+ return { ok: false, permanent: true, error: resolved.error, infrastructureCode: resolved.code, providerId: task.metadata?.provider || undefined };}const { provider } = resolved;const strictFallback = task.metadata?.pipeline?.securityScan?.usedLargeInputFallback === true;if (strictFallback && !resolved.pinHonored) {- return { ok: false, permanent: true, error: 'Configured large-input review fallback provider is unavailable' };- }- if (task.metadata?.provider && !resolved.pinHonored) {- emitLog('warn', `Public-review stage provider ${task.metadata.provider} is not eligible for the ${posture} posture — using ${provider.id}`, {- taskId: task.id,- providerId: provider.id,- });+ return { ok: false, permanent: true, infrastructureCode: 'public-review-provider-pin-unavailable', error: 'Configured large-input review fallback provider is unavailable' };}// A model pin only survives when it was chosen FOR this provider AND that- // provider still offers it; otherwise fall back to the provider's own default- // rather than handing one vendor's model id to another (the failure mode+ // provider still offers it; otherwise stop instead of silently+ // selecting another model or handing one vendor's model id to another (the failure mode// documented in the ordinary path). Matching the provider alone is not// enough: a stage pin outlives edits to that provider's own `models` list,// and a retired id reaches the CLI as a model it cannot serve, so the stage@@ -133,30 +126,15 @@ async function resolvePublicReviewAgentProvider(task, posture) {// pass-throughs (see its doc comment).const honorPin = pinnedForThisProvider && modelPinIsOffered(provider, pinnedModel);const pinRejected = pinnedForThisProvider && !honorPin;- if (strictFallback && !honorPin) {- return { ok: false, permanent: true, error: 'Configured large-input review fallback model is unavailable' };+ if (pinRejected || (strictFallback && !honorPin)) {+ return { ok: false, permanent: true, providerId: provider.id, infrastructureCode: 'public-review-model-pin-unavailable', error: 'The selected PR review model is unavailable. Review stopped without model or provider fallback; check the stage settings.' };}- // Strip a pin that will NOT be honored, BEFORE model selection.- // `selectModelForTask` returns `metadata.model` verbatim as its- // highest-priority answer, so leaving it on the task defeats both guards- // above: a REJECTED pin came straight back while the warning below promised a- // default the run never used, and a pin belonging to a DIFFERENT provider- // (`pinnedForThisProvider` false, after the posture swap above chose someone- // else) was handed to the new provider — the exact cross-vendor leak this- // function's header says it prevents. Both are the same "will not be honored"- // case, so both strip here.+ // A model-only pin with no provider cannot be transferred to an inferred+ // provider. Tier requests and unpinned stages keep ordinary model selection.const modelSelection = await selectModelForTask(pinnedModel && !isTierRequest && !honorPin ? { ...task, metadata: { ...task.metadata, model: null } } : task,provider,);- if (pinRejected) {- emitLog('warn', `Public-review stage model "${pinnedModel}" is not offered by provider "${provider.id}" — using its default instead`, {- taskId: task.id,- requestedModel: pinnedModel,- providerId: provider.id,- validModels: provider.models,- });- }const selectedModel = honorPin? pinnedModel: (modelSelection.model || provider.defaultModel || null);diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.jsindex 3f817c39b8..37367a0b30 100644--- a/server/services/agentProviderResolution.test.js+++ b/server/services/agentProviderResolution.test.js@@ -406,10 +406,10 @@ describe('resolveAgentProviderAndModel — public-review stages', () => {.toMatchObject({ ok: true, selectedModel: 'available-model' });});- it('ignores a stage pin that is not eligible for the posture', async () => {+ it('blocks an unsupported stage pin without selecting another provider', async () => {getAllProviders.mockResolvedValue({ providers: [OPENCODE, CLAUDE], activeProvider: null });const r = await resolveAgentProviderAndModel(gateTask({ provider: 'opencode' }));- expect(r).toMatchObject({ ok: true, provider: { id: 'claude-code' } });+ expect(r).toMatchObject({ ok: false, permanent: true, infrastructureCode: 'public-review-provider-pin-unavailable' });});// `selectModelForTask`'s real precedence: `task.metadata.model` wins outright@@ -427,19 +427,16 @@ describe('resolveAgentProviderAndModel — public-review stages', () => {getAllProviders.mockResolvedValue({ providers: [CLAUDE, GROK], activeProvider: null });await expect(resolveAgentProviderAndModel(gateTask({ provider: 'grok-cli', model: 'grok-4' }))).resolves.toMatchObject({ provider: { id: 'grok-cli' }, selectedModel: 'grok-4' });- // Pinned for a DIFFERENT provider — falls back to that provider's own model.- // The posture swap above landed on claude-code, and grok's model id must not- // ride along with it; leaving the pin on the task let `selectModelForTask`- // hand it straight back, so the swap silently kept the foreign model.+ // An unsupported provider pin must never route the model to another vendor.await expect(resolveAgentProviderAndModel(gateTask({ provider: 'opencode', model: 'grok-4' })))- .resolves.toMatchObject({ provider: { id: 'claude-code' }, selectedModel: 'm-default' });+ .resolves.toMatchObject({ ok: false, permanent: true });});// A stage pin outlives edits to the provider's own model list: the live// pr-reviewer gate sat pinned to an id its provider no longer offered, so// every run spawned a CLI that could not serve the model, produced no// output, and was retried — matching the provider is not enough on its own.- it('drops a model pin the matching provider no longer offers', async () => {+ it('blocks a model pin the matching provider no longer offers', async () => {const CURATED = { id: 'grok-cli', type: 'cli', command: 'grok', models: ['grok-4'], defaultModel: 'grok-4' };getAllProviders.mockResolvedValue({ providers: [CURATED], activeProvider: null });@@ -447,9 +444,9 @@ describe('resolveAgentProviderAndModel — public-review stages', () => {await expect(resolveAgentProviderAndModel(gateTask({ provider: 'grok-cli', model: 'grok-4' }))).resolves.toMatchObject({ provider: { id: 'grok-cli' }, selectedModel: 'grok-4' });- // Retired from the list → the provider's own selection wins instead.+ // Retired from the list → stop without choosing a different model.await expect(resolveAgentProviderAndModel(gateTask({ provider: 'grok-cli', model: 'grok-3-retired' })))- .resolves.toMatchObject({ provider: { id: 'grok-cli' }, selectedModel: 'm-default' });+ .resolves.toMatchObject({ ok: false, permanent: true, infrastructureCode: 'public-review-model-pin-unavailable' });});// The drop above has to survive model selection, which is where it used to@@ -464,7 +461,7 @@ describe('resolveAgentProviderAndModel — public-review stages', () => {getAllProviders.mockResolvedValue({ providers: [CURATED], activeProvider: null });const r = await resolveAgentProviderAndModel(gateTask({ provider: 'grok-cli', model: 'grok-3-retired' }));- expect(r.selectedModel).toBe('grok-4');+ expect(r).toMatchObject({ ok: false, permanent: true, infrastructureCode: 'public-review-model-pin-unavailable' });});// A LOCAL runtime's `models` array is a cached snapshot of what the daemondiff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex d9e720d85c..8b11b2857f 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2546,11 +2546,19 @@ function applyProviderModelPins(metadata, interval, appPin, hookOverride, reques}applyOneProviderPin(metadata, appPin);applyOneProviderPin(metadata, hookOverride);+ // A pipeline's current stage is more specific than the whole-task defaults.+ // Stage 0 may already have advanced through a server-owned preflight.+ const stage = metadata.pipeline?.stages?.[metadata.pipeline.currentStage ?? 0];+ if (stage) {+ applyOneProviderPin(metadata, stage);+ if (stage.providerId) delete metadata.effort;+ if (stage.effort) metadata.effort = stage.effort;+ }// Most specific: an explicit per-request pin (e.g. one "PR review" click from// the Pull Requests tab), applied last so it wins over every configured pin// above. A public-review posture still gates the final provider to its own- // eligible set at spawn time (resolveAgentProviderAndModel) — an ineligible- // pin here is dropped with a warning there, same as any other stored pin.+ // eligible set at spawn time (resolveAgentProviderAndModel). An unsupported+ // pin blocks instead of granting permission to spend on another provider.applyOneProviderPin(metadata, { providerId: requestOverride?.provider || null, model: requestOverride?.model || null });if (requestOverride?.effort) {metadata.effort = requestOverride.effort;diff --git a/server/services/cosTaskGenerator.providerPin.test.js b/server/services/cosTaskGenerator.providerPin.test.jsindex 1db7514a13..2ae98005e8 100644--- a/server/services/cosTaskGenerator.providerPin.test.js+++ b/server/services/cosTaskGenerator.providerPin.test.js@@ -136,3 +136,19 @@ describe('per-app provider/model pin on a task type with no buildTaskInput hook'expect(task.metadata.model).toBe('sonnet');});});+++describe('pipeline stage provider precedence', () => {+ it('preserves the stage local route over broader schedule and app pins', async () => {+ getTaskIntervalMock.mockResolvedValue({ type: 'weekly', providerId: 'opencode-tui', model: 'broad', effort: 'high', taskMetadata: {+ pipeline: { stages: [{ name: 'Local stage', promptKey: 'ux', providerId: 'claude-cli', model: 'local-model', effort: 'low' }] },+ } });+ getAppTaskTypeOverridesMock.mockResolvedValue({ ux: { providerId: 'opencode-tui', model: 'app-model' } });+ const task = await generate();+ expect(task.metadata).toMatchObject({ provider: 'claude-cli', providerId: 'claude-cli', model: 'local-model', effort: 'low' });+ const overridden = await generateManagedAppImprovementTaskForType('ux', APP, STATE, {+ skipPreconditions: true, providerOverride: { provider: 'opencode-tui', model: 'explicit-model', effort: 'high' },+ });+ expect(overridden.metadata).toMatchObject({ provider: 'opencode-tui', model: 'explicit-model', effort: 'high' });+ });+});diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.jsindex 36c04c9ce2..a676a68dca 100644--- a/server/services/issueWatcher.js+++ b/server/services/issueWatcher.js@@ -573,7 +573,7 @@ async function readPullRequest(ctx, number) {// a fork's head branch actually lives, which is what lets the remediation// agent's worktree attach to it at all (#6064). `assignees` keeps that// assignment idempotent across scheduled sweeps.- '--json', 'number,title,body,url,state,isDraft,author,assignees,labels,files,additions,deletions,baseRefName,baseRefOid,headRefName,headRefOid,isCrossRepository,maintainerCanModify,headRepository,headRepositoryOwner,mergeable,mergeStateStatus,statusCheckRollup',+ '--json', 'id,number,title,body,url,state,isDraft,author,assignees,labels,files,additions,deletions,baseRefName,baseRefOid,headRefName,headRefOid,isCrossRepository,maintainerCanModify,headRepository,headRepositoryOwner,mergeable,mergeStateStatus,statusCheckRollup',], ctx);}@@ -605,6 +605,27 @@ async function approveHeldWorkflowRuns(ctx, pr) {return approved;}+// Use the enable-only API, not `gh pr merge --auto`: the latter can merge+// immediately when the repository has no required checks, even while our own+// observed CI is pending. Pin the mutation to the exact reviewed commit.+async function enableReviewedPullRequestAutoMerge(ctx, pr) {+ if (!pr.id || !/^[a-f0-9]{40}$/i.test(pr.headRefOid)) return false;+ const query = `mutation($input: EnablePullRequestAutoMergeInput!) {+ enablePullRequestAutoMerge(input: $input) {+ pullRequest { headRefOid autoMergeRequest { enabledAt } }+ }+ }`;+ const raw = await runGh([+ ...apiArgs(ctx, 'graphql', { method: 'POST' }), '--input', '-',+ ], ctx, JSON.stringify({ query, variables: { input: {+ pullRequestId: pr.id, expectedHeadOid: pr.headRefOid, mergeMethod: 'MERGE',+ } } })).catch(() => null);+ const response = raw === null ? null : safeJSONParse(raw, null, { logError: false });+ const enabled = response?.data?.enablePullRequestAutoMerge?.pullRequest;+ return !response?.errors?.length && enabled?.headRefOid === pr.headRefOid+ && Boolean(enabled?.autoMergeRequest?.enabledAt);+}+function sameNumberList(left, right) {const a = Array.isArray(left) ? left : [];const b = Array.isArray(right) ? right : [];@@ -1441,6 +1462,11 @@ export async function processTaskOutput({ appId, success, payload, task, require}) !== PR_HANDBACK.NONE) handedBack += 1;continue;}+ if (!await eligibilityStillCurrent()) continue;+ const autoMergeEnabled = await enableReviewedPullRequestAutoMerge(ctx, pr);+ if (!autoMergeEnabled) {+ await notifyPendingApproval(app, pr, 'The review approved this commit, but GitHub did not enable auto-merge. Check repository auto-merge settings and branch requirements. The approval remains in the pending merge queue.');+ }approvals = mergeApproval(approvals, {number: pr.number,headSha: pr.headRefOid,@@ -1449,6 +1475,7 @@ export async function processTaskOutput({ appId, success, payload, task, requireeligibilityFacts: target.eligibilityFacts,url: pr.url,ciPolicy: decision.ciPolicy,+ autoMergeEnabled,rebaseRequired: false,noChecksObserved: checkRollup.length === 0,reviewedAt: new Date().toISOString(),diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.jsindex d890fcf66e..102904fcc3 100644--- a/server/services/issueWatcher.test.js+++ b/server/services/issueWatcher.test.js@@ -88,6 +88,7 @@ const DIFF = [function pullRequest(overrides = {}) {return {+ id: 'PR_node_7',number: 7,title: 'Contributor update',body: 'A small change',@@ -111,9 +112,10 @@ function pullRequest(overrides = {}) {}function installDefaultGhMock({- pr = pullRequest(), issueRows = [[]], commentRows = [[]], reviews = [[]], issueDetails = {}, heldRuns = [],+ pr = pullRequest(), issueRows = [[]], commentRows = [[]], reviews = [[]], issueDetails = {}, heldRuns = [], autoMergeError = false,} = {}) {execGhMock.mockImplementation(async (args) => {+ if (args.includes('graphql')) return JSON.stringify(autoMergeError ? { errors: [{ message: 'Not permitted' }] } : { data: { enablePullRequestAutoMerge: { pullRequest: { headRefOid: pr.headRefOid, autoMergeRequest: { enabledAt: '2026-09-11T18:00:00Z' } } } } });if (args[0] === 'api' && args.includes('user')) return JSON.stringify({ login: 'owner' });if (args[0] === 'api' && args.some((arg) => String(arg).includes('/actions/runs?'))) return JSON.stringify({ workflow_runs: heldRuns });if (args[0] === 'api' && args.some((arg) => String(arg).includes('/actions/runs/'))) return '';@@ -887,6 +889,24 @@ describe('processTaskOutput', () => {expect(mergePrMock).not.toHaveBeenCalled();});+ it.each([false, true])('requests head-pinned auto-merge for pending CI and reports rejection (%s)', async autoMergeError => {+ installDefaultGhMock({ pr: pullRequest({ statusCheckRollup: [{ status: 'IN_PROGRESS' }] }), autoMergeError });+ const result = await processTaskOutput({ appId: APP.id, success: true, task: { metadata }, payload: {+ issueComments: [], pullRequests: [{ number: 7, headSha: 'a'.repeat(40), verdict: 'approve', summary: 'Reviewed.', findings: [], rebaseRequired: false, ciPolicy: 'required' }],+ } });+ expect(result).toMatchObject({ reviewed: 1, merged: 0 });+ expect(mergePrMock).not.toHaveBeenCalled();+ const mutation = execGhMock.mock.calls.find(([args]) => args.includes('graphql'));+ expect(mutation).toBeDefined();+ expect(JSON.parse(mutation[2].input)).toMatchObject({ variables: { input: {+ pullRequestId: 'PR_node_7', expectedHeadOid: 'a'.repeat(40), mergeMethod: 'MERGE',+ } } });+ expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toEqual([+ expect.objectContaining({ number: 7, autoMergeEnabled: !autoMergeError }),+ ]);+ if (autoMergeError) expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({ description: expect.stringContaining('did not enable auto-merge') }));+ });+it('waits one scheduled observation before treating absent CI as skippable', async () => {installDefaultGhMock({ pr: pullRequest({ statusCheckRollup: [] }) });mergePrMock.mockResolvedValue({ success: true });diff --git a/server/services/prReviewerPipeline.js b/server/services/prReviewerPipeline.jsindex f7d6edde66..b616780a9c 100644--- a/server/services/prReviewerPipeline.js+++ b/server/services/prReviewerPipeline.js@@ -279,6 +279,10 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, tatarget,largeInputFallback: securityStage.largeInputFallback,});+ if (!scan.ok) {+ const { reportReviewInfrastructureFailure } = await import('./reviewInfrastructureFailure.js');+ await reportReviewInfrastructureFailure({ code: scan.code, task: { metadata: { app: app.id } } }).catch(() => {});+ }const reports = securityScanReports(scan);if (!scan.ok && !reports.length) {const reason = scan.code || 'security-scan-not-passed';diff --git a/server/services/prReviewerPipeline.test.js b/server/services/prReviewerPipeline.test.jsindex b60a26d4ea..245210a878 100644--- a/server/services/prReviewerPipeline.test.js+++ b/server/services/prReviewerPipeline.test.js@@ -1,5 +1,8 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+const reportInfrastructureFailure = vi.hoisted(() => vi.fn(async () => null));+vi.mock('./reviewInfrastructureFailure.js', () => ({ reportReviewInfrastructureFailure: reportInfrastructureFailure }));+const issueWatcherMock = vi.hoisted(() => ({isTaskOutputPayload: vi.fn((payload) => Boolean(payload?.issueComments || payload?.pullRequests)),processTaskOutput: vi.fn(),@@ -411,6 +414,7 @@ describe('runPrReviewerSecurityPreflight', () => {}beforeEach(() => {+ reportInfrastructureFailure.mockClear();securityMock.listExternalOpenPullRequests.mockReset();securityMock.runPrReviewerSecurityScan.mockReset();securityMock.securityScanFingerprint.mockReset().mockReturnValue('scan-key-1');@@ -418,6 +422,15 @@ describe('runPrReviewerSecurityPreflight', () => {taskStoreMock.getCosTasks.mockReset().mockResolvedValue({ tasks: [] });});+ it('stops a broken local guard and queues infrastructure diagnosis without forwarding the PR', async () => {+ listed(externalPr(12, HEAD_12));+ securityMock.runPrReviewerSecurityScan.mockResolvedValue({ ok: false, code: 'security-guard-not-ready' });+ const result = await runPrReviewerSecurityPreflight('pr-reviewer', APP, preflightMetadata(), null, schedule());+ expect(result).toMatchObject({ skipped: true, reason: 'security-guard-not-ready' });+ expect(reportInfrastructureFailure).toHaveBeenCalledWith({ code: 'security-guard-not-ready', task: { metadata: { app: APP.id } } });+ expect(guardMock.writePublicReviewInputSnapshot).not.toHaveBeenCalled();+ });+it('passes every other task type straight through', async () => {const metadata = {};await expect(runPrReviewerSecurityPreflight('claim-work', APP, metadata, null, schedule())).resolves.toEqual({ skipped: false });diff --git a/server/services/publicReviewProviderSelection.js b/server/services/publicReviewProviderSelection.jsindex 083400f9e6..244bcf1ec2 100644--- a/server/services/publicReviewProviderSelection.js+++ b/server/services/publicReviewProviderSelection.js@@ -57,8 +57,9 @@ export async function eligiblePublicReviewProviders(posture, { providers = null* Resolve the provider a public-review stage should run on.** Preference order — a pin the user set on the stage wins whenever it is still- * eligible, then the install's active provider, then the first eligible- * provider that is currently available, then the first eligible provider at+ * eligible. An explicit unavailable/ineligible pin blocks; it never authorizes+ * another provider. Unpinned stages use the install's active provider, then the+ * first eligible provider that is currently available, then the first eligible provider at* all (so a stage stays configured through a transient rate limit rather than* silently swapping vendors).*@@ -70,6 +71,16 @@ export async function resolvePublicReviewProvider({ posture, pinnedProviderId =if (!posture) return { ok: false, code: 'public-review-posture-missing', error: 'No public-review posture requested' };const { providers = [], activeProvider } = await getAllProviders();const eligible = await eligiblePublicReviewProviders(posture, { providers });+ const pinned = pinnedProviderId ? eligible.find((provider) => provider.id === pinnedProviderId) : null;+ if (pinnedProviderId && !pinned) {+ return { ok: false, code: 'public-review-provider-pin-unavailable',+ error: `The selected PR review provider cannot enforce the ${posture} stage or is disabled/missing. Review stopped; no provider fallback was used. Check the stage provider in CoS > Schedule.` };+ }+ if (pinned && !isProviderAvailable(pinned.id)) {+ return { ok: false, code: 'public-review-provider-unavailable',+ error: 'The selected PR review provider is unavailable. Review stopped without provider fallback; investigate its runtime and configuration before retrying.' };+ }+ if (pinned) return { ok: true, provider: pinned, pinHonored: true };if (eligible.length === 0) {return {ok: false,@@ -79,9 +90,6 @@ export async function resolvePublicReviewProvider({ posture, pinnedProviderId =: `No enabled AI provider on this install has a maintained '${posture}' public-review posture. Add or enable one of these CLI providers in Settings > Providers: ${publicReviewCapableVendorIds(posture).join(', ')}.`,};}- const pinned = pinnedProviderId ? eligible.find((provider) => provider.id === pinnedProviderId) : null;- if (pinned) return { ok: true, provider: pinned, pinHonored: true };-const activeId = activeProviderId || activeProvider?.id || activeProvider || null;const active = activeId ? eligible.find((provider) => provider.id === activeId) : null;const chosen = activediff --git a/server/services/publicReviewProviderSelection.test.js b/server/services/publicReviewProviderSelection.test.jsindex 0d20373dda..de13297b8a 100644--- a/server/services/publicReviewProviderSelection.test.js+++ b/server/services/publicReviewProviderSelection.test.js@@ -69,16 +69,29 @@ describe('resolvePublicReviewProvider', () => {.resolves.toMatchObject({ ok: true, pinHonored: true, provider: { id: 'grok-cli' } });});- it('drops an INELIGIBLE pin instead of running the stage on it', async () => {+ it('blocks an ineligible pin instead of spending on another provider', async () => {seed([OPENCODE, GROK], { id: 'opencode' });const resolved = await resolvePublicReviewProvider({ posture: 'no-tool', pinnedProviderId: 'opencode' });- expect(resolved).toMatchObject({ ok: true, pinHonored: false, provider: { id: 'grok-cli' } });+ expect(resolved).toMatchObject({ ok: false, code: 'public-review-provider-pin-unavailable' });});- it('rejects a worktree-only actions pin and selects an enforced provider', async () => {+ it('blocks a worktree-only actions pin instead of choosing a subscription provider', async () => {seed([OPENCODE, CODEX], { id: 'codex-cli' });const resolved = await resolvePublicReviewProvider({ posture: 'sandboxed-actions', pinnedProviderId: 'opencode' });- expect(resolved).toMatchObject({ ok: true, pinHonored: false, provider: { id: 'codex-cli' } });+ expect(resolved).toMatchObject({ ok: false, code: 'public-review-provider-pin-unavailable' });+ });++ it.each([{ ...LOCAL_CLAUDE, enabled: false }, { ...LOCAL_CLAUDE, id: 'renamed' }])('blocks a disabled or missing local pin', async local => {+ seed([local, GROK], { id: 'grok-cli' });+ expect(await resolvePublicReviewProvider({ posture: 'no-tool', pinnedProviderId: LOCAL_CLAUDE.id }))+ .toMatchObject({ ok: false, code: 'public-review-provider-pin-unavailable' });+ });++ it('blocks an unavailable local pin even when a subscription provider is healthy', async () => {+ seed([LOCAL_CLAUDE, GROK], { id: 'grok-cli' });+ isProviderAvailable.mockImplementation(id => id === 'grok-cli');+ expect(await resolvePublicReviewProvider({ posture: 'no-tool', pinnedProviderId: LOCAL_CLAUDE.id }))+ .toMatchObject({ ok: false, code: 'public-review-provider-unavailable' });});it('prefers an available provider over an unavailable earlier one', async () => {diff --git a/server/services/reviewInfrastructureFailure.js b/server/services/reviewInfrastructureFailure.jsnew file mode 100644index 0000000000..894ec85f00--- /dev/null+++ b/server/services/reviewInfrastructureFailure.js@@ -0,0 +1,70 @@+/**+ * Infrastructure failures are operator work, never a reason to send public+ * content to another provider. Only server-owned failure codes cross into the+ * investigation queue; no PR text, model output, or transport errors do.+ */+import { investigationFingerprint } from '../lib/investigationTasks.js';++const DIAGNOSES = Object.freeze({+ 'public-review-provider-pin-unavailable': 'The selected PR review provider is missing, disabled, or cannot enforce a tool-free review.',+ 'public-review-provider-unavailable': 'The selected PR review provider is unavailable.',+ 'public-review-no-eligible-provider': 'No enabled provider can enforce the requested PR review mode.',+ 'public-review-model-pin-unavailable': 'The selected PR review model is unavailable on its configured provider.',+ 'public-review-provider-unsupported': 'The selected provider cannot enforce a tool-free PR review.',+ 'public-review-model-required': 'The local PR review stage has no selected model.',+ 'public-review-runtime-unsupported': 'The selected local runtime cannot run this PR review stage.',+ 'public-review-model-catalog-unavailable': 'The local model catalog could not be read.',+ 'public-review-model-not-installed': 'The selected local review model is not installed.',+ 'public-review-model-not-tool-free': 'The selected local model cannot perform a tool-free review.',+ 'public-review-model-unsupported': 'The selected local model could not be validated for PR review.',+ 'security-guard-input-failed': 'The local abuse classifier could not receive its input.',+ 'security-guard-not-ready': 'The local abuse classifier is not ready.',+ 'security-guard-process-failed': 'The local abuse classifier process failed.',+ 'security-guard-timeout': 'The local abuse classifier timed out.',+ 'security-guard-verdict-invalid': 'The local abuse classifier returned an invalid verdict.',+});++let reportTail = Promise.resolve();++export function reportReviewInfrastructureFailure({ code, task } = {}) {+ if (typeof code !== 'string' || !Object.hasOwn(DIAGNOSES, code)) return Promise.resolve(null);+ const run = reportTail.then(() => reportFailure(code, task));+ reportTail = run.catch(() => {});+ return run;+}++async function reportFailure(code, task) {+ const { fileInvestigationTask, readAllTasksFlat, investigationCircuitOpen } = await import('./investigationTaskProducer.js');+ const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');+ const fingerprint = investigationFingerprint({ category: code, kind: 'review-infrastructure', scope: task?.metadata?.app });+ const backlog = await readAllTasksFlat().catch(() => null);+ let investigation = backlog?.find(candidate =>+ ['pending', 'in_progress', 'challenged', 'blocked'].includes(candidate.status)+ && candidate.metadata?.investigationFingerprint === fingerprint) || null;+ if (backlog && !investigation && !investigationCircuitOpen()) {+ // No affectedTasks: repairing infrastructure must not automatically replay+ // stale contributor evidence. Retry PR review through a fresh security scan.+ const filed = await fileInvestigationTask({+ fingerprint,+ priority: 'HIGH',+ description: `[Auto] Investigate PR review infrastructure [${fingerprint}]++${DIAGNOSES[code]}++Inspect the installed Abuse Guard and PR review stage settings, provider routing, runtime readiness and model availability. Reproduce with a trusted synthetic canary, repair the cause, and verify the configured local route. Do not fetch contributor content or read the failed review transcript. Do not replace the selected route with a subscription provider, disable screening, or loosen tool restrictions. Report the diagnosis and validation to the user. After repair, PR review must be retried through a fresh security scan.`,+ }).catch(() => null);+ investigation = filed?.task || null;+ }+ const incident = investigation?.id || code;+ if (!await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'reviewInfrastructureIncident', incident)) {+ await addNotification({+ type: NOTIFICATION_TYPES.AGENT_WARNING,+ priority: PRIORITY_LEVELS.HIGH,+ title: 'PR review infrastructure needs attention',+ description: `${DIAGNOSES[code]} Review stopped without provider fallback. ${investigation ? 'An investigation is queued in CoS.' : 'The investigation could not be queued; check the CoS queue and retry.'}`,+ link: '/cos',+ metadata: { reviewInfrastructureIncident: incident, failureCode: code },+ });+ }+ return investigation;+}diff --git a/server/services/reviewInfrastructureFailure.test.js b/server/services/reviewInfrastructureFailure.test.jsnew file mode 100644index 0000000000..969e3fde2d--- /dev/null+++ b/server/services/reviewInfrastructureFailure.test.js@@ -0,0 +1,51 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ create: vi.fn(), read: vi.fn(), circuit: vi.fn(), add: vi.fn(), exists: vi.fn() }));+vi.mock('./investigationTaskProducer.js', () => ({ fileInvestigationTask: mocks.create, readAllTasksFlat: mocks.read, investigationCircuitOpen: mocks.circuit }));+vi.mock('./notifications.js', () => ({+ addNotification: mocks.add, exists: mocks.exists,+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' }, PRIORITY_LEVELS: { HIGH: 'high' },+}));+import { reportReviewInfrastructureFailure } from './reviewInfrastructureFailure.js';++beforeEach(() => {+ vi.clearAllMocks();+ mocks.create.mockResolvedValue({ task: { id: 'investigation-1' } });+ mocks.read.mockResolvedValue([]);+ mocks.circuit.mockReturnValue(false);+ mocks.exists.mockResolvedValue(false);+});++describe('review infrastructure diagnosis', () => {+ it('queues a trusted diagnosis and user notification without copying external evidence', async () => {+ const task = { id: 'task-1', description: 'UNTRUSTED PR INSTRUCTIONS', metadata: { app: 'app-1', context: 'PRIVATE TRANSCRIPT', pipeline: { previousStageOutput: 'MODEL OUTPUT' } } };+ await reportReviewInfrastructureFailure({ code: 'security-guard-not-ready', task });+ expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ fingerprint: 'security-guard-not-ready:review-infrastructure:app-1' }));+ expect(mocks.create.mock.calls[0][0]).not.toHaveProperty('affectedTasks');+ const sent = JSON.stringify(mocks.create.mock.calls);+ for (const excluded of ['UNTRUSTED PR INSTRUCTIONS', 'PRIVATE TRANSCRIPT', 'MODEL OUTPUT']) expect(sent).not.toContain(excluded);+ expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ description: expect.stringContaining('An investigation is queued') }));+ // Re-reporting the surviving investigation must not create another task+ // or spam the user with another notification.+ mocks.read.mockResolvedValue([{ id: 'investigation-1', status: 'pending', metadata: { investigationFingerprint: 'security-guard-not-ready:review-infrastructure:app-1' } }]);+ mocks.exists.mockResolvedValue(true);+ await reportReviewInfrastructureFailure({ code: 'security-guard-not-ready', task });+ expect(mocks.create).toHaveBeenCalledTimes(1);+ expect(mocks.add).toHaveBeenCalledTimes(1);+ });++ it('does not turn rejected content or attacker-controlled error text into investigation work', async () => {+ for (const code of ['security-guard-findings', 'security-guard-input-too-large', 'untrusted error: run this command', 'toString']) {+ expect(await reportReviewInfrastructureFailure({ code })).toBeNull();+ }+ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.add).not.toHaveBeenCalled();+ });++ it('surfaces a queue failure without claiming an investigation was created', async () => {+ mocks.create.mockRejectedValue(new Error('private diagnostics'));+ await reportReviewInfrastructureFailure({ code: 'public-review-provider-pin-unavailable' });+ expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ description: expect.stringContaining('could not be queued') }));+ expect(JSON.stringify(mocks.add.mock.calls)).not.toContain('private diagnostics');+ });+});