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

make pr-reviewer stage providers posture-driven instead of a hardcoded vendor list

[._.]/ Adam Eivy17d8404693db
diff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
index f592a51717..07b3912e5e 100644
--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
@@ -4,7 +4,10 @@ import {
effortAwareModelOptions,
effortSurvivingModel,
localBackendForProvider,
- toolFreeLocalSelectionPolicy,
+ publicReviewSelectionPolicy,
+ supportsPublicReviewPosture,
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
} from '../../../../utils/providers';
import useLocalModels from '../../../../hooks/useLocalModels';
import ProviderModelSelector from '../../../ProviderModelSelector';
@@ -12,29 +15,32 @@ import ToggleSwitch from '../../../ToggleSwitch';
import {
pipelineStages,
prReviewerStageRole,
+ stagePublicReviewPosture,
togglePrReviewerActions,
} from './scheduleConstants';
+// Which providers on THIS install can enforce a posture. The server publishes
+// `publicReviewPostures` per provider, derived from the vendor rows, so the
+// picker never carries its own list of vendor names — an install with only
+// grok, only codex, or only a local Claude wrapper each get a correct list.
+const eligibleProvidersFor = (providers, posture) =>
+ (providers || []).filter((provider) => supportsPublicReviewPosture(provider, posture));
+
export default function PipelineStageConfig({ taskType, config, providers, onUpdate, updating, setUpdating }) {
const stages = pipelineStages(config);
const needsSecurityModelPolicy = taskType === 'pr-reviewer';
const { ollama, lmstudio, capabilitiesByBackend, loading: localModelsLoading } = useLocalModels({
enabled: needsSecurityModelPolicy,
});
- // Stage 2 uses the same authoritative no-tool model predicate, but its
- // provider is a maintained local Claude wrapper rather than a direct HTTP
- // backend. The server-derived marker is the provider-side capability gate;
- // the shared policy still requires a local installed model with text
- // capability and no `tools` capability.
- const publicReviewSelectionPolicy = useMemo(
- () => toolFreeLocalSelectionPolicy(capabilitiesByBackend, {
- providerPredicate: (provider) => provider?.publicReviewSupported === true,
- }),
- [capabilitiesByBackend],
- );
- const publicReviewActionsSelectionPolicy = useMemo(() => ({
- provider: (provider) => provider?.publicReviewActionsSupported === true,
- }), []);
+ // One policy per posture. The provider half is server-derived; the model half
+ // adds the authoritative no-tool capability check only for a local runtime,
+ // which is the only place PortOS can probe it.
+ const selectionPolicies = useMemo(() => ({
+ [PUBLIC_REVIEW_NO_TOOL_POSTURE]: publicReviewSelectionPolicy(PUBLIC_REVIEW_NO_TOOL_POSTURE, capabilitiesByBackend),
+ [PUBLIC_REVIEW_ACTIONS_POSTURE]: publicReviewSelectionPolicy(PUBLIC_REVIEW_ACTIONS_POSTURE, capabilitiesByBackend),
+ }), [capabilitiesByBackend]);
+
+ const hasActionsStage = stages.some((stage) => prReviewerStageRole(stage) === 'actions');
const handlePrReviewerActionsToggle = async (enabled) => {
setUpdating(true);
@@ -91,18 +97,18 @@ export default function PipelineStageConfig({ taskType, config, providers, onUpd
<div>
<p className="text-sm font-medium text-white">Run final code review and actions</p>
<p className="text-xs text-gray-400 mt-1">
- When enabled, a configured sandbox-capable reviewer applies only the screened patch, runs local tests, and returns a structured review for the deterministic GitHub coordinator. It is nested here, not a separate scheduled task.
+ When enabled, a sandbox-capable reviewer applies only the screened patch, runs local tests, and returns a structured review for the deterministic GitHub coordinator. It is nested here, not a separate scheduled task.
</p>
</div>
<ToggleSwitch
- enabled={stages.some((stage) => prReviewerStageRole(stage) === 'actions')}
- onChange={() => handlePrReviewerActionsToggle(!stages.some((stage) => prReviewerStageRole(stage) === 'actions'))}
+ enabled={hasActionsStage}
+ onChange={() => handlePrReviewerActionsToggle(!hasActionsStage)}
disabled={updating}
ariaLabel="Enable final code review and actions"
size="sm"
/>
</div>
- {!stages.some((stage) => prReviewerStageRole(stage) === 'actions') && (
+ {!hasActionsStage && (
<p className="text-xs text-port-warning mt-2">
Disabled runs stop after the tool-free eligibility gate; no PR comments, issue filing, CI triggers, or merge actions occur.
</p>
@@ -116,24 +122,27 @@ export default function PipelineStageConfig({ taskType, config, providers, onUpd
? (prReviewerStageRole(stage) || (i === 0 ? 'security' : i === 1 ? 'eligibility' : 'actions'))
: null;
const isSecurityStage = role === 'security';
- const isEligibilityStage = role === 'eligibility';
- const isActionsStage = role === 'actions';
+ // The posture is read off the stage's own execution profile, so a
+ // custom pipeline that reuses one of these profiles gets the same
+ // gating without being a pr-reviewer stage.
+ const posture = isSecurityStage ? null : stagePublicReviewPosture(stage);
+ const isNoToolStage = posture === PUBLIC_REVIEW_NO_TOOL_POSTURE;
+ const isActionsStage = Boolean(posture) && !isNoToolStage;
+ const eligibleProviders = posture ? eligibleProvidersFor(providers, posture) : null;
const localBackend = localBackendForProvider(stageProvider);
const localModelIds = localBackend === 'ollama' ? ollama : localBackend === 'lmstudio' ? lmstudio : [];
- // Keep the richer capability object on each local option so the shared
- // policy does not need a second lookup. The status hook's ids are the
- // installed-model source of truth; a provider's stale catalog is never
- // enough to make a model eligible for a security scan.
- const stageModels = isEligibilityStage
+ // A LOCAL provider's installed-model list is the source of truth (its
+ // stored catalog is stale, and only an installed model has a probeable
+ // capability report). Every other provider uses its own catalog, so a
+ // cloud CLI stage can pick any model that provider offers.
+ const stageModels = isNoToolStage && localBackend
? localModelIds.map(id => ({
id,
name: id,
capabilities: capabilitiesByBackend?.[localBackend]?.[id],
}))
: effortAwareModelOptions(stageProvider, stage.model);
- const selectionPolicy = isEligibilityStage
- ? publicReviewSelectionPolicy
- : isActionsStage ? publicReviewActionsSelectionPolicy : undefined;
+ const selectionPolicy = posture ? selectionPolicies[posture] : undefined;
const stageProviderId = stage.providerId || '';
const stageModel = stage.model || '';
const stageEffort = stage.effort || '';
@@ -146,7 +155,7 @@ export default function PipelineStageConfig({ taskType, config, providers, onUpd
{stage.readOnly && (
<span className="text-[10px] px-1 py-0.5 bg-gray-600/30 text-gray-400 rounded">read-only</span>
)}
- {isEligibilityStage && (
+ {isNoToolStage && (
<span className="text-[10px] px-1 py-0.5 bg-port-accent/15 text-port-accent rounded">tool-free gate</span>
)}
{isActionsStage && (
@@ -177,27 +186,33 @@ export default function PipelineStageConfig({ taskType, config, providers, onUpd
onModelChange={(model) => updateStage('model', model)}
effort={stageEffort}
onEffortChange={(effort) => updateStage('effort', effort)}
- emptyProviderOption={isEligibilityStage
- ? 'Select enforced local review provider (required)'
- : isActionsStage ? 'Select sandbox-capable CLI (required)' : 'Default (task-level)'}
- emptyModelOption={isEligibilityStage
- ? 'Select installed no-tool model (required)'
- : isActionsStage ? 'Use provider default model' : 'Default (task-level)'}
+ emptyProviderOption={posture
+ ? 'First eligible provider on this install'
+ : 'Default (task-level)'}
+ emptyModelOption={posture ? 'Use provider default model' : 'Default (task-level)'}
alwaysShowModel
selectionPolicy={selectionPolicy}
disabled={updating}
/>
)}
- {isEligibilityStage && (
+ {posture && eligibleProviders?.length === 0 && (
+ <p className="text-xs text-port-warning mt-2">
+ No enabled AI provider on this install can enforce the{' '}
+ {isActionsStage ? 'sandboxed-actions' : 'tool-free'} posture, so this stage will not run.
+ Enable a supported CLI provider in{' '}
+ <Link to="/ai" className="underline hover:text-port-accent">Settings → Providers</Link>.
+ </p>
+ )}
+ {isNoToolStage && eligibleProviders?.length > 0 && (
<p className="text-xs text-gray-500 mt-2">
{localModelsLoading
? 'Loading installed local model capability reports…'
- : 'The Eligibility Gate accepts only the maintained local Claude wrapper and an installed text model whose runtime reports no tool-calling capability. It returns only a binary allowlist; the final stage never receives rejected content.'}
+ : `Tool-free stage. Eligible on this install: ${eligibleProviders.map((p) => p.name || p.id).join(', ')}. A local model must additionally report no tool-calling capability; a cloud model is held tool-free by the provider's own enforced flags. Leave the provider unset to use the first eligible one. It returns only a binary allowlist; the final stage never receives rejected content.`}
</p>
)}
- {isActionsStage && (
+ {isActionsStage && eligibleProviders?.length > 0 && (
<p className="text-xs text-gray-500 mt-2">
- Final review accepts only a configured direct CLI with a maintained sandbox (for example, Codex or Antigravity). PortOS passes the selected provider, model, and thinking effort through that provider&apos;s safe recipe, with no explicit GitHub/forge credential or configuration overlays; the deterministic coordinator owns comments, issue filing, CI triggers, and merges.
+ {`Sandboxed stage. Eligible on this install: ${eligibleProviders.map((p) => p.name || p.id).join(', ')}. PortOS passes the selected provider, model, and thinking effort through that provider's maintained sandbox recipe, with no forge credential or configuration overlays; the deterministic coordinator owns comments, issue filing, CI triggers, and merges.`}
</p>
)}
</div>
@@ -208,7 +223,7 @@ export default function PipelineStageConfig({ taskType, config, providers, onUpd
{needsSecurityModelPolicy
? 'Stage 1 screens complete public content with a managed classifier; only cleared content reaches the tool-free Eligibility Gate, and only eligible PRs reach the optional sandboxed final review. Stages are nested, not independently scheduled.'
: 'Each stage runs as a separate agent inside this pipeline; stages are not scheduled independently.'}
- {' Configure different providers per stage (e.g., Codex for review, Claude for implementation).'}
+ {' Configure a different provider, model, and thinking effort per stage.'}
</p>
</div>
);
diff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
index 7844f174c3..0fda45e235 100644
--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
@@ -140,3 +140,47 @@ describe('PipelineStageConfig — pr-reviewer', () => {
}));
});
});
+
+// The refactor's core promise: the picker's eligible set comes from the
+// server-published `publicReviewPostures` on each provider, so an install with
+// none of the vendors the old copy named still configures both stages.
+describe('PipelineStageConfig — posture-driven eligibility', () => {
+ const profiledStages = [
+ STAGES[0],
+ { ...STAGES[1], executionProfile: 'public-review-gate', providerId: '', model: '' },
+ { ...STAGES[2], executionProfile: 'public-review-actions', providerId: '', model: '' },
+ ];
+
+ const renderWith = (installProviders) => render(
+ <MemoryRouter>
+ <PipelineStageConfig
+ taskType="pr-reviewer"
+ config={{ taskMetadata: { pipeline: { stages: profiledStages } } }}
+ providers={installProviders}
+ onUpdate={vi.fn().mockResolvedValue(undefined)}
+ updating={false}
+ setUpdating={() => {}}
+ />
+ </MemoryRouter>,
+ );
+
+ it('offers a grok-only install its own provider for BOTH stages', () => {
+ renderWith([
+ { id: 'grok-cli', name: 'Grok', type: 'cli', command: 'grok', models: ['grok-4'], publicReviewPostures: ['no-tool', 'sandboxed-actions'] },
+ { id: 'opencode', name: 'OpenCode', type: 'cli', command: 'opencode', models: ['x'], publicReviewPostures: [] },
+ ]);
+ const providerSelects = screen.getAllByLabelText('Provider');
+ expect([...providerSelects[0].options].map((o) => o.value)).toEqual(['', 'grok-cli']);
+ expect([...providerSelects[1].options].map((o) => o.value)).toEqual(['', 'grok-cli']);
+ // A non-local provider's own catalog is selectable — the installed-local
+ // model list only applies where PortOS can probe capabilities.
+ expect(screen.getAllByText(/Eligible on this install: Grok/).length).toBe(2);
+ });
+
+ it('warns instead of silently offering nothing when a stage has no eligible provider', () => {
+ renderWith([
+ { id: 'claude-ollama', name: 'Local Claude', type: 'cli', command: 'claude', endpoint: 'http://127.0.0.1:11434', models: ['safe-model'], publicReviewPostures: ['no-tool'] },
+ ]);
+ expect(screen.getByText(/No enabled AI provider on this install can enforce the sandboxed-actions posture/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.js
index 70b122980a..e7d8454c58 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js
@@ -1,4 +1,8 @@
// Shared constants and pure helpers for the CoS Schedule tab subcomponents.
+import {
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
+} from '../../../../utils/providers';
import { timeUntil } from '../../../../utils/formatters';
import { describeCron } from '../../../../utils/cronHelpers';
@@ -64,6 +68,32 @@ export function prReviewerStageRole(stage) {
}[stage?.promptKey] || null;
}
+// A stage declares an execution PROFILE; the profile maps to the enforceable
+// POSTURE a provider must have a maintained recipe for. Mirrors
+// `server/lib/agentExecutionProfiles.js` so the picker offers exactly the
+// providers the server would accept at spawn time — and so neither side names
+// a vendor. The Security Scan is a managed server-side classifier and has no
+// posture, so it has no provider picker at all.
+export const STAGE_EXECUTION_PROFILE_POSTURES = Object.freeze({
+ 'public-review': PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ 'public-review-gate': PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ 'public-review-actions': PUBLIC_REVIEW_ACTIONS_POSTURE,
+});
+
+// Role fallback for a stage persisted before profiles were stored: the server
+// reasserts the profile on the next dispatch, but the picker has to gate
+// correctly on what is on disk right now.
+const PR_REVIEWER_ROLE_POSTURES = Object.freeze({
+ eligibility: PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ actions: PUBLIC_REVIEW_ACTIONS_POSTURE,
+});
+
+export function stagePublicReviewPosture(stage) {
+ return STAGE_EXECUTION_PROFILE_POSTURES[stage?.executionProfile]
+ || PR_REVIEWER_ROLE_POSTURES[prReviewerStageRole(stage)]
+ || null;
+}
+
// The optional final stage is deliberately defined as a complete posture, not
// just a display label. The server sanitizes and reasserts the same contract;
// this copy lets the schedule UI add it without manufacturing a weaker stage.
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 012677dcec..56b6d6c667 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -41,7 +41,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` / `isHttpsUrl` (safe-href checks), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
| `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. Also `migrateLegacyNavPath(path, commands)` — maps a stored path onto the CURRENT path of the page that used to answer to it, driven by each command's own `previousPaths` (declared in `server/lib/navManifest.js` beside the page that moved, shipped whole in the palette manifest). A pin is a stored route path, so without it a moved page's pin stops matching the manifest and the sidebar row silently vanishes on update. |
-| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isCodexSubscriptionProvider` (subscription readiness is keyed on the `codex` command, never an editable id), `isAntigravityProvider`, `isLaunchableTuiProvider` — a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt; shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree — `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` (an OpenCode wrapper front-ending a hosted OpenAI-compatible gateway — `orcarouter`, `openrouter` — which inherits its API key at spawn time from the sibling API provider whose id equals the gateway id; reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; keep the three copies in lockstep), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). `TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, and `toolFreeLocalSelectionPolicy` share the fail-closed local/text/no-tools filter used by security-sensitive provider/model/effort pickers. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
+| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isCodexSubscriptionProvider` (subscription readiness is keyed on the `codex` command, never an editable id), `isAntigravityProvider`, `isLaunchableTuiProvider` — a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt; shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree — `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` (an OpenCode wrapper front-ending a hosted OpenAI-compatible gateway — `orcarouter`, `openrouter` — which inherits its API key at spawn time from the sibling API provider whose id equals the gateway id; reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; keep the three copies in lockstep), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). `TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, and `toolFreeLocalSelectionPolicy` share the fail-closed local/text/no-tools filter used by security-sensitive provider/model/effort pickers. `PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, and `publicReviewSelectionPolicy` are the pr-reviewer counterpart (mirror of server `agentExecutionProfiles.js`): a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can enforce — no vendor is named on either side. Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
| `systemCapabilities` | Server-annotated hardware compatibility helpers: preserve model/provider choices when compatibility is unknown, and hide only entries whose `hardwareCompatibility.state` is definitively `unavailable`. |
| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 3f0e446dd5..47217096e5 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -257,6 +257,49 @@ export const toolFreeLocalSelectionPolicy = (
),
});
+// The two enforceable public-review postures. MIRROR of
+// `server/lib/agentExecutionProfiles.js`; a pr-reviewer stage names a posture
+// and the server publishes each provider's `publicReviewPostures` on
+// `GET /api/providers`, so no vendor is ever named on either side.
+export const PUBLIC_REVIEW_NO_TOOL_POSTURE = 'no-tool';
+export const PUBLIC_REVIEW_ACTIONS_POSTURE = 'sandboxed-actions';
+
+/**
+ * Whether the SERVER says this provider can enforce `posture`. Falls back to
+ * the older per-posture booleans so a browser talking to a peer/older server
+ * still renders a correct picker instead of an empty one.
+ */
+export const supportsPublicReviewPosture = (provider, posture) => {
+ if (Array.isArray(provider?.publicReviewPostures)) return provider.publicReviewPostures.includes(posture);
+ return posture === PUBLIC_REVIEW_ACTIONS_POSTURE
+ ? provider?.publicReviewActionsSupported === true
+ : provider?.publicReviewSupported === true;
+};
+
+/**
+ * Selection policy for a pr-reviewer stage.
+ *
+ * Provider eligibility is entirely server-derived. Model eligibility adds the
+ * authoritative no-tool capability check only where PortOS can actually probe
+ * it — a LOCAL runtime behind the provider. A cloud model is not probeable, so
+ * the vendor's enforced argv (`--restricted --tools ''`, `--sandbox read-only`,
+ * `--permission-mode plan`) is what denies it tools, and every model the
+ * provider lists stays selectable.
+ */
+export const publicReviewSelectionPolicy = (posture, capabilitiesByBackend = {}) => ({
+ provider: (provider) => supportsPublicReviewPosture(provider, posture),
+ model: (model, provider) => {
+ if (!supportsPublicReviewPosture(provider, posture)) return false;
+ if (posture !== PUBLIC_REVIEW_NO_TOOL_POSTURE || !localBackendForProvider(provider)) return true;
+ return isToolFreeLocalModelForProvider(
+ model,
+ provider,
+ capabilitiesByBackend,
+ () => true,
+ );
+ },
+});
+
/**
* Retain an existing non-runnable pin so a saved job can still be edited and
* cleared, while limiting new agent-job selections to runnable providers.
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 83be00ef35..e66b152bb7 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -19,6 +19,10 @@ import {
isToolFreeLocalProvider,
isToolFreeLocalModel,
toolFreeLocalSelectionPolicy,
+ publicReviewSelectionPolicy,
+ supportsPublicReviewPosture,
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
localToolUseHint,
withToolUseOptionLabel,
localBackendForProvider,
@@ -1905,3 +1909,45 @@ describe('isPrivateNetworkEndpoint', () => {
});
// @vitest-environment node
+
+describe('publicReviewSelectionPolicy', () => {
+ const LOCAL_CLAUDE = {
+ id: 'claude-ollama',
+ type: 'cli',
+ command: 'claude',
+ endpoint: 'http://127.0.0.1:11434',
+ publicReviewPostures: ['no-tool'],
+ };
+ const GROK = { id: 'grok-cli', type: 'cli', command: 'grok', publicReviewPostures: ['no-tool', 'sandboxed-actions'] };
+ const CAPS = { ollama: { 'safe-model': ['chat'], 'tool-model': ['chat', 'tools'] } };
+
+ it('reads eligibility from the server-published postures, not a vendor list', () => {
+ expect(supportsPublicReviewPosture(GROK, PUBLIC_REVIEW_ACTIONS_POSTURE)).toBe(true);
+ expect(supportsPublicReviewPosture(LOCAL_CLAUDE, PUBLIC_REVIEW_ACTIONS_POSTURE)).toBe(false);
+ expect(supportsPublicReviewPosture({ id: 'x', type: 'cli', publicReviewPostures: [] }, PUBLIC_REVIEW_NO_TOOL_POSTURE)).toBe(false);
+ });
+
+ it('falls back to the legacy booleans so an older server still renders a picker', () => {
+ expect(supportsPublicReviewPosture({ id: 'legacy', publicReviewSupported: true }, PUBLIC_REVIEW_NO_TOOL_POSTURE)).toBe(true);
+ expect(supportsPublicReviewPosture({ id: 'legacy', publicReviewActionsSupported: true }, PUBLIC_REVIEW_ACTIONS_POSTURE)).toBe(true);
+ expect(supportsPublicReviewPosture({ id: 'legacy' }, PUBLIC_REVIEW_NO_TOOL_POSTURE)).toBe(false);
+ });
+
+ // The probe only exists for a local runtime; a cloud model is held tool-free
+ // by the provider's own enforced argv, so filtering it out would leave the
+ // picker empty on an install with no local backend.
+ it('applies the no-tool capability probe to a local model only', () => {
+ const policy = publicReviewSelectionPolicy(PUBLIC_REVIEW_NO_TOOL_POSTURE, CAPS);
+ expect(policy.model('safe-model', LOCAL_CLAUDE)).toBe(true);
+ expect(policy.model('tool-model', LOCAL_CLAUDE)).toBe(false);
+ expect(policy.model('unprobed-model', LOCAL_CLAUDE)).toBe(false);
+ expect(policy.model('grok-4', GROK)).toBe(true);
+ });
+
+ it('never accepts a model on a provider that cannot enforce the posture', () => {
+ const policy = publicReviewSelectionPolicy(PUBLIC_REVIEW_ACTIONS_POSTURE, CAPS);
+ expect(policy.provider(LOCAL_CLAUDE)).toBe(false);
+ expect(policy.model('safe-model', LOCAL_CLAUDE)).toBe(false);
+ expect(policy.model('grok-4', GROK)).toBe(true);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 3ff20b6230..4440363efb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -189,7 +189,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
| `openAiChatStream.js` | `iterateOpenAiChat(...)` → normalized async content/reasoning chunks and `streamOpenAiChat(...)` → the streamed text — one streaming `POST {base}/chat/completions` against any OpenAI-compatible endpoint; both own timeout/abort composition, retries, parsing, backpressure, and reader cleanup. `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by Ask (`services/askService.js`), `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record), and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: filters the inherited base to runtime essentials/provider auth, then layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
-| `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. `PUBLIC_REVIEW_EXECUTION_PROFILE` identifies the restricted local classifier, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE` the tool-free eligibility reasoner, and `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE` the sandboxed direct-Codex final reviewer. |
+| `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (`PUBLIC_REVIEW_EXECUTION_PROFILE`, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE`, `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE`); `publicReviewPostureForProfile` maps it to the enforceable POSTURE a provider must carry a maintained recipe for (`no-tool` or `sandboxed-actions`), which is how a pipeline stage stays vendor-agnostic. |
| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
diff --git a/server/lib/agentExecutionProfiles.js b/server/lib/agentExecutionProfiles.js
index 9cbb2035dd..060451bafc 100644
--- a/server/lib/agentExecutionProfiles.js
+++ b/server/lib/agentExecutionProfiles.js
@@ -15,12 +15,44 @@ export const PUBLIC_REVIEW_EXECUTION_PROFILE = 'public-review';
export const PUBLIC_REVIEW_GATE_EXECUTION_PROFILE = 'public-review-gate';
export const PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE = 'public-review-actions';
+/**
+ * The two enforceable postures behind those profiles. A posture is what a
+ * VENDOR declares a maintained recipe for; a profile is what a STAGE declares
+ * it needs. Keeping them separate is what lets a stage be configured onto any
+ * enabled provider whose vendor row declares the posture, instead of the
+ * pipeline naming specific vendors.
+ *
+ * - `no-tool` — reasoning only. No filesystem writes, no command
+ * execution, no network/MCP tools, no forge credentials.
+ * - `sandboxed-actions` — may apply the already-screened patch and run local
+ * tests inside the vendor's own maintained sandbox.
+ * Still no forge credentials: the deterministic
+ * coordinator owns every GitHub mutation.
+ */
+export const PUBLIC_REVIEW_NO_TOOL_POSTURE = 'no-tool';
+export const PUBLIC_REVIEW_ACTIONS_POSTURE = 'sandboxed-actions';
+export const PUBLIC_REVIEW_POSTURES = Object.freeze([
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+]);
+
+const PROFILE_POSTURES = Object.freeze({
+ [PUBLIC_REVIEW_EXECUTION_PROFILE]: PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ [PUBLIC_REVIEW_GATE_EXECUTION_PROFILE]: PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ [PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE]: PUBLIC_REVIEW_ACTIONS_POSTURE,
+});
+
+export const PUBLIC_REVIEW_EXECUTION_PROFILES = Object.freeze(Object.keys(PROFILE_POSTURES));
+
+/** The posture a stage's execution profile requires, or null for an ordinary task. */
+export function publicReviewPostureForProfile(profile) {
+ return PROFILE_POSTURES[profile] || null;
+}
+
export function isPublicReviewNoToolProfile(profile) {
- return profile === PUBLIC_REVIEW_EXECUTION_PROFILE
- || profile === PUBLIC_REVIEW_GATE_EXECUTION_PROFILE;
+ return publicReviewPostureForProfile(profile) === PUBLIC_REVIEW_NO_TOOL_POSTURE;
}
export function isPublicReviewRestrictedProfile(profile) {
- return isPublicReviewNoToolProfile(profile)
- || profile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;
+ return publicReviewPostureForProfile(profile) !== null;
}
diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.js
index 58e9666ff3..80f9ad62b5 100644
--- a/server/lib/cliChildEnv.js
+++ b/server/lib/cliChildEnv.js
@@ -148,8 +148,8 @@ export function buildPublicReviewCliEnv(env = {}) {
)));
}
-// Stage 3 is allowed to use the Codex CLI's workspace sandbox for repository
-// inspection and tests, but it must never inherit forge credentials, SSH
+// The actions stage is allowed to use its vendor's own workspace sandbox for
+// repository inspection and tests, but it must never inherit forge credentials, SSH
// configuration, cloud-provider keys, or arbitrary provider env vars. This is
// deliberately a second strict allowlist rather than a blocklist: a new secret
// added to the server or provider environment must not silently become visible
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 4ce1f29d70..0efc74d85a 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -16,6 +16,7 @@ import { ANTIGRAVITY_COMMAND } from './antigravity.js';
import { CURSOR_COMMAND } from './cursor.js';
import { isValidSlashdoCommand } from './slashdoInvocation.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
+import { PUBLIC_REVIEW_EXECUTION_PROFILES } from './agentExecutionProfiles.js';
import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';
import { recurrenceRuleSchema } from './recurrenceValidation.js';
import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';
@@ -1704,7 +1705,9 @@ export const PIPELINE_STAGE_BEHAVIOR_FLAGS = [
// boundary and which provider posture is safe; generic pipelines may omit the
// role and continue to use their existing promptKey-only behavior.
export const PIPELINE_STAGE_ROLES = ['security', 'eligibility', 'actions'];
-export const PIPELINE_EXECUTION_PROFILES = ['public-review', 'public-review-gate', 'public-review-actions'];
+// Re-exported, not restated: a new profile must be legal to persist the moment
+// it is declared, or the sanitizer silently rejects the stage that uses it.
+export const PIPELINE_EXECUTION_PROFILES = PUBLIC_REVIEW_EXECUTION_PROFILES;
const PIPELINE_STAGE_BOOLEAN_FIELDS = [
'readOnly', 'managed', 'useWorktree', 'openPR', 'simplify', 'reviewLoop',
diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.js
index aec1d4f40a..f5766a6aa9 100644
--- a/server/lib/providerVendors.js
+++ b/server/lib/providerVendors.js
@@ -85,7 +85,12 @@ import {
prepareAntigravityPrompt,
resolveAntigravityModelAndEffort,
} from './antigravity.js';
-import { isGrokCommand, ensureGrokTuiArgs, ensureGrokHeadlessArgs, prepareGrokPromptFile } from './grok.js';
+import {
+ isGrokCommand,
+ ensureGrokTuiArgs,
+ ensureGrokHeadlessArgs,
+ prepareGrokPromptFile,
+} from './grok.js';
import { isKimiCommand, ensureKimiTuiArgs, ensureKimiHeadlessArgs, prepareKimiPrompt } from './kimi.js';
import {
CURSOR_COMMAND,
@@ -93,19 +98,26 @@ import {
ensureCursorTuiArgs,
ensureCursorHeadlessArgs,
} from './cursor.js';
-import { isLocalInstanceEndpoint } from './localEndpoint.js';
import {
isPublicReviewNoToolProfile,
+ publicReviewPostureForProfile,
PUBLIC_REVIEW_EXECUTION_PROFILE,
PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+ PUBLIC_REVIEW_POSTURES,
} from './agentExecutionProfiles.js';
export {
isPublicReviewNoToolProfile,
+ publicReviewPostureForProfile,
PUBLIC_REVIEW_EXECUTION_PROFILE,
PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+ PUBLIC_REVIEW_POSTURES,
} from './agentExecutionProfiles.js';
/**
@@ -158,15 +170,30 @@ function codexSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreads
return { command: provider?.command || CODEX_COMMAND, args, stdinMode: 'prompt' };
}
+// Codex's own sandbox modes are the enforcement here, not the prompt. Both
+// public-review recipes build argv from scratch and never forward
+// `provider.args`: a saved `--dangerously-bypass-approvals-and-sandbox` in a
+// user's provider config would otherwise turn a screened review into an
+// unrestricted session.
+function codexPublicReviewSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreads }) {
+ return codexPublicReviewArgs(provider, { effectiveModel, effort, maxConcurrentThreads }, ['--sandbox', 'read-only']);
+}
+
function codexPublicReviewActionsSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreads }) {
// `workspace-write` is intentionally the narrowest Codex sandbox that can
// apply a supplied patch and run local tests; `--approve-for-me` only
// suppresses interactive confirmations inside that sandbox. Never replace
// these with the unrestricted bypass used by the ordinary coding-agent path.
- const args = [
- 'exec',
+ return codexPublicReviewArgs(provider, { effectiveModel, effort, maxConcurrentThreads }, [
'--sandbox', 'workspace-write',
'--approve-for-me',
+ ]);
+}
+
+function codexPublicReviewArgs(provider, { effectiveModel, effort, maxConcurrentThreads }, postureArgs) {
+ const args = [
+ 'exec',
+ ...postureArgs,
'--ephemeral',
'--ignore-user-config',
...buildCodexStartupArgs(),
@@ -179,15 +206,25 @@ function codexPublicReviewActionsSpawnArgs(provider, { effectiveModel, effort, m
return { command: provider?.command || CODEX_COMMAND, args, stdinMode: 'prompt' };
}
-function antigravityPublicReviewActionsSpawnArgs(provider, { effectiveModel, effort }) {
- // Antigravity's explicit terminal sandbox is the maintained action posture for
- // this vendor. `accept-edits` permits the reviewer to apply the screened patch
- // and run tests without granting the unrestricted permission bypass used by
- // ordinary coding tasks. Provider args are intentionally not copied here:
- // saved args could turn a safe profile back into an unrestricted session.
+// Antigravity's `--sandbox` is its maintained terminal-restriction posture and
+// `--mode` picks what the session may do inside it: `plan` cannot edit at all,
+// `accept-edits` may apply the screened patch and run tests. Provider args are
+// intentionally not copied: saved args could turn a safe profile back into an
+// unrestricted session. `--print` carries the prompt as its VALUE (see
+// antigravity.js) — `prepareAntigravityPrompt` relocates it to the end of the
+// argv at spawn time, which is why it is safe to append flags after it here.
+function antigravityPublicReviewSpawnArgs(provider, ctx) {
+ return antigravityPublicReviewArgs(provider, ctx, 'plan');
+}
+
+function antigravityPublicReviewActionsSpawnArgs(provider, ctx) {
+ return antigravityPublicReviewArgs(provider, ctx, 'accept-edits');
+}
+
+function antigravityPublicReviewArgs(provider, { effectiveModel, effort } = {}, mode) {
const args = [
'--sandbox',
- '--mode', 'accept-edits',
+ '--mode', mode,
'--disable-slash-commands',
'--print',
];
@@ -196,6 +233,33 @@ function antigravityPublicReviewActionsSpawnArgs(provider, { effectiveModel, eff
return { command: provider?.command || ANTIGRAVITY_COMMAND, args, stdinMode: 'prompt' };
}
+// Grok exposes both halves of the contract as first-class flags:
+// `--permission-mode plan` is its read-only mode, `--tools ''` empties the
+// built-in tool allowlist, and `--sandbox <profile>` applies its own
+// filesystem/network sandbox (`workspace` is grok's built-in profile). The
+// safety flags are seeded as the BASE args so `ensureGrokHeadlessArgs` sees a
+// permission posture already pinned and does not append its usual
+// `--permission-mode bypassPermissions`.
+function grokPublicReviewSpawnArgs(provider, ctx) {
+ return grokPublicReviewArgs(provider, ctx, ['--permission-mode', 'plan', '--tools', '']);
+}
+
+function grokPublicReviewActionsSpawnArgs(provider, ctx) {
+ return grokPublicReviewArgs(provider, ctx, ['--sandbox', 'workspace', '--permission-mode', 'acceptEdits']);
+}
+
+function grokPublicReviewArgs(provider, { effectiveModel, effort } = {}, postureArgs) {
+ const args = ensureGrokHeadlessArgs([
+ ...postureArgs,
+ '--no-subagents',
+ '--disable-web-search',
+ ], effectiveModel);
+ args.push(...buildEffortArgs(effort, provider, args, effectiveModel));
+ // `ensureGrokHeadlessArgs` appends the GROK_STDIN_PROMPT_PATH prompt-file
+ // sentinel that `prepareGrokPromptFile` rewrites on Windows; keep it present.
+ return { command: provider?.command || 'grok', args, stdinMode: 'prompt' };
+}
+
const CODEX = {
id: 'codex',
idFragment: 'codex',
@@ -205,8 +269,18 @@ const CODEX = {
tuiArgs: ensureCodexTuiArgs,
cliArgs: codexCliArgs,
spawnArgs: codexSpawnArgs,
- publicReviewActionsSpawnArgs: codexPublicReviewActionsSpawnArgs,
- publicReviewActionsProvider: (provider) => provider?.type === 'cli' && isCodexCommand(provider?.command),
+ publicReview: {
+ // The CLI id and the TUI id share one binary, so both reach the same
+ // enforced recipe when a stage selects them.
+ [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
+ spawnArgs: codexPublicReviewSpawnArgs,
+ matchProvider: (provider) => isCodexCommand(provider?.command) || provider?.id === CODEX_CLI_ID || provider?.id === 'codex-tui',
+ },
+ [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
+ spawnArgs: codexPublicReviewActionsSpawnArgs,
+ matchProvider: (provider) => provider?.type === 'cli' && isCodexCommand(provider?.command),
+ },
+ },
};
// ─── antigravity ────────────────────────────────────────────────────────────
@@ -227,8 +301,16 @@ const ANTIGRAVITY = {
cliArgs: antigravityCliArgs,
preparePrompt: prepareAntigravityPrompt,
spawnArgs: defaultSpawnArgs(antigravityCliArgs, ANTIGRAVITY_COMMAND),
- publicReviewActionsSpawnArgs: antigravityPublicReviewActionsSpawnArgs,
- publicReviewActionsProvider: (provider) => provider?.type === 'cli' && isAntigravityCommand(provider?.command),
+ publicReview: {
+ [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
+ spawnArgs: antigravityPublicReviewSpawnArgs,
+ matchProvider: (provider) => provider?.type === 'cli' && isAntigravityCommand(provider?.command),
+ },
+ [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
+ spawnArgs: antigravityPublicReviewActionsSpawnArgs,
+ matchProvider: (provider) => provider?.type === 'cli' && isAntigravityCommand(provider?.command),
+ },
+ },
};
// ─── opencode ───────────────────────────────────────────────────────────────
@@ -269,6 +351,16 @@ const GROK = {
tuiArgs: ensureGrokTuiArgs,
cliArgs: grokCliArgs,
spawnArgs: defaultSpawnArgs(grokCliArgs, 'grok'),
+ publicReview: {
+ [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
+ spawnArgs: grokPublicReviewSpawnArgs,
+ matchProvider: (provider) => provider?.type === 'cli' && isGrokCommand(provider?.command),
+ },
+ [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
+ spawnArgs: grokPublicReviewActionsSpawnArgs,
+ matchProvider: (provider) => provider?.type === 'cli' && isGrokCommand(provider?.command),
+ },
+ },
};
// ─── kimi ───────────────────────────────────────────────────────────────────
@@ -386,12 +478,6 @@ const CLAUDE_PUBLIC_REVIEW_ARGS = [
'--bare',
];
-function isLocalClaudePublicReviewProvider(provider) {
- if (provider?.type !== 'cli' || provider?.ollamaBacked !== true || !isClaudeCommand(provider?.command)) return false;
- const endpoint = provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || 'http://localhost:11434';
- return isLocalInstanceEndpoint(endpoint);
-}
-
function claudePublicReviewArgs(provider, {
effectiveModel,
effort,
@@ -406,9 +492,10 @@ function claudePublicReviewArgs(provider, {
];
if (systemPromptFile) args.push('--append-system-prompt-file', systemPromptFile);
if (effectiveModel) {
- // This profile is local-only. Do not consult the host's Bedrock settings or
- // ambient environment while constructing its model id: a server started in
- // Bedrock mode must not turn a local Ollama model into a cloud model name.
+ // Pass the stage's model id through VERBATIM. Do not consult the host's
+ // Bedrock settings or ambient environment while constructing it: this
+ // profile is reachable from an Ollama-backed Claude wrapper, and a server
+ // started in Bedrock mode must not turn a local model into a cloud one.
args.push('--model', effectiveModel);
}
const safeArgs = applyLeanClaudeArgs(provider, args, provider?.command || 'claude');
@@ -431,8 +518,17 @@ const CLAUDE = {
matchCommand: () => true,
cliArgs: claudeCliArgs,
spawnArgs: claudeSpawnArgs,
- publicReviewSpawnArgs: claudePublicReviewArgs,
- publicReviewProvider: isLocalClaudePublicReviewProvider,
+ publicReview: {
+ // Claude is the historical always-true fallback row, so its posture
+ // matcher must positively identify the binary — an unknown command must
+ // never inherit claude's flag set. There is deliberately no
+ // sandboxed-actions recipe: Claude Code has no OS-level sandbox flag, only
+ // permission modes, so it fails closed for the actions stage.
+ [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
+ spawnArgs: claudePublicReviewArgs,
+ matchProvider: (provider) => provider?.type === 'cli' && isClaudeCommand(provider?.command),
+ },
+ },
};
/**
@@ -458,23 +554,25 @@ function matchesProvider(vendor, provider) {
return vendor.matchCliProvider ? vendor.matchCliProvider(provider) : vendor.matchCommand(provider?.command);
}
-function matchesPublicReviewProvider(vendor, provider) {
- if (!matchesProvider(vendor, provider)) {
- // The normal Codex provider matcher intentionally distinguishes the CLI
- // id from the TUI id. The safety profile must recognize both because they
- // share the same binary and receive the same read-only posture.
- if (vendor.id === 'codex' && (provider?.id === 'codex-tui' || isCodexCommand(provider?.command))) return true;
- return false;
- }
- // Claude is the historical fallback row. It is safe only when the selected
- // provider actually launches Claude; an unknown command must never inherit
- // Claude's safe argv by accident.
- if (vendor.id === 'claude') {
- return typeof vendor.publicReviewProvider === 'function'
- ? vendor.publicReviewProvider(provider)
- : false;
+/**
+ * The vendor recipe enforcing `posture` for `provider`, or null when this
+ * install has no maintained recipe for that pairing.
+ *
+ * Eligibility is DECLARED by the vendor row, never named by the caller: a
+ * pipeline stage asks for a posture and every enabled provider whose vendor
+ * declares it is a legal choice. That is what lets an install with only grok
+ * (or only a local Claude wrapper) configure the same stages an install with
+ * codex configures. A row's matcher must positively identify the binary —
+ * claude's `matchCommand` is unconditionally true (it is the historical
+ * fallback row), so an unknown command must never inherit its argv.
+ */
+export function publicReviewRecipe(provider, posture) {
+ if (!PUBLIC_REVIEW_POSTURES.includes(posture)) return null;
+ for (const vendor of PROVIDER_VENDORS) {
+ const recipe = vendor.publicReview?.[posture];
+ if (recipe?.spawnArgs && recipe.matchProvider(provider)) return recipe;
}
- return true;
+ return null;
}
/**
@@ -496,7 +594,7 @@ export function inferTuiCommand(id) {
/** `applyCommandDefaults` (tuiHandshake.js): TUI posture-flag dispatch. */
export function applyCommandDefaults(command, args, { safetyProfile = null } = {}) {
- if (safetyProfile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE) {
+ if (publicReviewPostureForProfile(safetyProfile) === PUBLIC_REVIEW_ACTIONS_POSTURE) {
throw new Error('The public-review-actions profile requires a supported direct CLI sandbox');
}
const vendor = PROVIDER_VENDORS.find((v) => (
@@ -539,62 +637,55 @@ export function buildVendorCliArgs(provider, baseArgs, { model, effort }) {
* before this registry existed (see file header).
*/
export function buildVendorSpawnConfig(provider, ctx) {
- const publicReviewActions = ctx?.safetyProfile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;
- const vendor = PROVIDER_VENDORS.find((v) => v.spawnArgs && (
- publicReviewActions
- ? v.publicReviewActionsSpawnArgs && matchesPublicReviewActionsProvider(v, provider)
- : isPublicReviewNoToolProfile(ctx?.safetyProfile)
- ? matchesPublicReviewProvider(v, provider)
- : matchesProvider(v, provider)
- ));
- if (publicReviewActions) {
- if (!vendor?.publicReviewActionsSpawnArgs) {
- throw new Error(`Provider '${provider?.id || provider?.command || 'unknown'}' has no enforced public-review-actions posture`);
- }
- return vendor.publicReviewActionsSpawnArgs(provider, ctx);
- }
- if (isPublicReviewNoToolProfile(ctx?.safetyProfile)) {
- if (!vendor?.publicReviewSpawnArgs) {
- throw new Error(`Provider '${provider?.id || provider?.command || 'unknown'}' has no enforced public-review posture`);
+ const posture = publicReviewPostureForProfile(ctx?.safetyProfile);
+ if (posture) {
+ const recipe = publicReviewRecipe(provider, posture);
+ if (!recipe) {
+ throw new Error(`Provider '${provider?.id || provider?.command || 'unknown'}' has no enforced ${posture} public-review posture`);
}
- return vendor.publicReviewSpawnArgs(provider, ctx);
+ return recipe.spawnArgs(provider, ctx);
}
+ const vendor = PROVIDER_VENDORS.find((v) => v.spawnArgs && matchesProvider(v, provider));
return vendor.spawnArgs(provider, ctx);
}
-function matchesPublicReviewActionsProvider(vendor, provider) {
- return typeof vendor.publicReviewActionsProvider === 'function'
- && vendor.publicReviewActionsProvider(provider);
-}
-
/**
- * Whether a provider has a maintained, enforced read-only public-content
- * execution recipe for the requested transport. Unknown vendors fail closed.
+ * Every public-review posture this provider can actually be configured for,
+ * in `PUBLIC_REVIEW_POSTURES` order. This is the value the schedule UI reads to
+ * offer a stage's eligible providers, so it must stay derived from the vendor
+ * rows rather than from a hardcoded list of vendor names.
+ *
+ * Interactive (TUI) sessions and API/custom providers have no maintained
+ * recipe: a generic read-only prompt is not enforcement, so they fail closed.
*/
-export function supportsPublicReviewProvider(provider, { tui = false } = {}) {
- // Interactive sessions and API/custom providers do not have a maintained
- // no-tools recipe here. Public contributor content is intentionally routed
- // only through the non-interactive Claude recipe below; callers must fail
- // closed instead of treating a generic read-only prompt as enforcement.
- if (tui || provider?.type !== 'cli') return false;
- const vendor = PROVIDER_VENDORS.find((v) => (
- v.publicReviewSpawnArgs
- && matchesPublicReviewProvider(v, provider)
- ));
- return Boolean(vendor);
+export function publicReviewPosturesForProvider(provider, { tui = false } = {}) {
+ if (tui || provider?.type !== 'cli') return [];
+ return PUBLIC_REVIEW_POSTURES.filter((posture) => Boolean(publicReviewRecipe(provider, posture)));
}
/**
- * Whether a provider can run the final public-review stage. This is restricted
- * to direct CLI vendors with an explicit maintained filesystem/terminal sandbox
- * recipe; TUI/API transports and arbitrary custom commands fail closed.
+ * Vendor ids that declare a maintained recipe for `posture`, for naming what a
+ * user could install when nothing on their machine qualifies. Derived from the
+ * rows so the suggestion cannot go stale when a vendor gains or loses a recipe.
*/
-export function supportsPublicReviewActionsProvider(provider, { tui = false } = {}) {
+export function publicReviewCapableVendorIds(posture) {
+ return PROVIDER_VENDORS.filter((vendor) => vendor.publicReview?.[posture]?.spawnArgs).map((vendor) => vendor.id);
+}
+
+/** Whether `provider` has a maintained, enforced recipe for one posture. */
+export function supportsPublicReviewPosture(provider, posture, { tui = false } = {}) {
if (tui || provider?.type !== 'cli') return false;
- return PROVIDER_VENDORS.some((vendor) => (
- vendor.publicReviewActionsSpawnArgs
- && matchesPublicReviewActionsProvider(vendor, provider)
- ));
+ return Boolean(publicReviewRecipe(provider, posture));
+}
+
+/** Whether a provider can run a tool-free public-content stage. */
+export function supportsPublicReviewProvider(provider, options) {
+ return supportsPublicReviewPosture(provider, PUBLIC_REVIEW_NO_TOOL_POSTURE, options);
+}
+
+/** Whether a provider can run the sandboxed final public-review stage. */
+export function supportsPublicReviewActionsProvider(provider, options) {
+ return supportsPublicReviewPosture(provider, PUBLIC_REVIEW_ACTIONS_POSTURE, options);
}
/**
diff --git a/server/lib/providerVendors.publicReview.test.js b/server/lib/providerVendors.publicReview.test.js
index c7429d29ba..1fabe5b8e6 100644
--- a/server/lib/providerVendors.publicReview.test.js
+++ b/server/lib/providerVendors.publicReview.test.js
@@ -1,7 +1,14 @@
import { describe, expect, it } from 'vitest';
-import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE, PUBLIC_REVIEW_EXECUTION_PROFILE } from './agentExecutionProfiles.js';
+import {
+ PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
+ PUBLIC_REVIEW_EXECUTION_PROFILE,
+ PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
+ PUBLIC_REVIEW_ACTIONS_POSTURE,
+ PUBLIC_REVIEW_NO_TOOL_POSTURE,
+} from './agentExecutionProfiles.js';
import {
buildVendorSpawnConfig,
+ publicReviewPosturesForProvider,
supportsPublicReviewProvider,
supportsPublicReviewActionsProvider,
} from './providerVendors.js';
@@ -17,51 +24,37 @@ const localClaude = {
ANTHROPIC_AUTH_TOKEN: 'local-only',
},
};
+const codex = { id: 'codex-cli', type: 'cli', command: 'codex', models: ['gpt-5.6'] };
+const antigravity = { id: 'antigravity-cli', type: 'cli', command: 'agy', models: ['gemini-3.6-flash-high'] };
+const grok = { id: 'grok-cli', type: 'cli', command: 'grok' };
-describe('public-review provider profile', () => {
- it('supports only the maintained local non-interactive Claude wrapper', () => {
- expect(supportsPublicReviewProvider(localClaude)).toBe(true);
- expect(supportsPublicReviewProvider({ ...localClaude, type: 'tui' })).toBe(false);
- expect(supportsPublicReviewProvider({ ...localClaude, ollamaBacked: false })).toBe(false);
- expect(supportsPublicReviewProvider({
- ...localClaude,
- envVars: { ANTHROPIC_BASE_URL: 'https://api.anthropic.com' },
- })).toBe(false);
- expect(supportsPublicReviewProvider({
- ...localClaude,
- command: 'claude',
- type: 'api',
- })).toBe(false);
+describe('public-review provider postures', () => {
+ // The whole point of the posture table: eligibility is DECLARED per vendor,
+ // so an install that has only one of these can still configure every stage.
+ it('derives each provider’s eligible postures from its vendor row', () => {
+ expect(publicReviewPosturesForProvider(codex)).toEqual([PUBLIC_REVIEW_NO_TOOL_POSTURE, PUBLIC_REVIEW_ACTIONS_POSTURE]);
+ expect(publicReviewPosturesForProvider(antigravity)).toEqual([PUBLIC_REVIEW_NO_TOOL_POSTURE, PUBLIC_REVIEW_ACTIONS_POSTURE]);
+ expect(publicReviewPosturesForProvider(grok)).toEqual([PUBLIC_REVIEW_NO_TOOL_POSTURE, PUBLIC_REVIEW_ACTIONS_POSTURE]);
+ // Claude Code has permission modes but no OS-level sandbox flag, so it is
+ // deliberately tool-free-only and fails closed for the actions stage.
+ expect(publicReviewPosturesForProvider(localClaude)).toEqual([PUBLIC_REVIEW_NO_TOOL_POSTURE]);
});
- it('supports direct CLI providers with maintained action sandboxes', () => {
- const codex = {
- id: 'codex-cli',
- type: 'cli',
- command: 'codex',
- models: ['gpt-5.6'],
- };
- expect(supportsPublicReviewActionsProvider(codex)).toBe(true);
- expect(supportsPublicReviewActionsProvider({ ...codex, type: 'tui' })).toBe(false);
- expect(supportsPublicReviewActionsProvider({ ...codex, type: 'api' })).toBe(false);
- expect(supportsPublicReviewActionsProvider({ ...codex, command: 'other-agent' })).toBe(false);
-
- const antigravity = {
- id: 'antigravity-cli',
- type: 'cli',
- command: 'agy',
- models: ['gemini-3.6-flash-high'],
- };
- expect(supportsPublicReviewActionsProvider(antigravity)).toBe(true);
- expect(supportsPublicReviewActionsProvider({ ...antigravity, type: 'tui' })).toBe(false);
- expect(supportsPublicReviewActionsProvider({ ...antigravity, type: 'api' })).toBe(false);
- expect(supportsPublicReviewActionsProvider({ ...antigravity, command: 'other-agent' })).toBe(false);
+ it('fails closed for transports and vendors with no maintained recipe', () => {
+ // A TUI session and an HTTP api provider have no enforced argv at all.
+ expect(publicReviewPosturesForProvider({ ...codex, type: 'tui' }, { tui: true })).toEqual([]);
+ expect(publicReviewPosturesForProvider({ ...codex, type: 'api' })).toEqual([]);
+ // An unknown command must never inherit claude's always-true fallback row.
+ expect(publicReviewPosturesForProvider({ id: 'custom', type: 'cli', command: 'custom-agent' })).toEqual([]);
+ // opencode/kimi/cursor have no maintained no-tool or sandbox recipe yet.
+ expect(publicReviewPosturesForProvider({ id: 'opencode', type: 'cli', command: 'opencode' })).toEqual([]);
+ expect(supportsPublicReviewProvider({ id: 'kimi', type: 'cli', command: 'kimi' })).toBe(false);
+ expect(supportsPublicReviewActionsProvider(localClaude)).toBe(false);
});
it('builds the final reviewer with the bounded Codex sandbox and no provider args', () => {
const config = buildVendorSpawnConfig({
- id: 'codex-cli',
- type: 'cli',
+ ...codex,
command: '/opt/example/bin/codex',
args: ['--dangerously-bypass-approvals-and-sandbox', '--mcp-config', 'unsafe.json'],
}, {
@@ -79,10 +72,19 @@ describe('public-review provider profile', () => {
expect(config.args).not.toContain('unsafe.json');
});
+ it('builds the Codex gate stage read-only rather than workspace-write', () => {
+ const config = buildVendorSpawnConfig(codex, {
+ effectiveModel: 'gpt-5.6',
+ safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
+ });
+ expect(config.args).toEqual(expect.arrayContaining(['exec', '--sandbox', 'read-only']));
+ expect(config.args).not.toContain('workspace-write');
+ expect(config.args).not.toContain('--approve-for-me');
+ });
+
it('builds the final reviewer with the bounded Antigravity sandbox and selected effort', () => {
const config = buildVendorSpawnConfig({
- id: 'antigravity-cli',
- type: 'cli',
+ ...antigravity,
command: '/opt/example/bin/agy',
args: ['--dangerously-skip-permissions', '--model', 'unsafe-model'],
models: ['gemini-3.6-flash-low', 'gemini-3.6-flash-high'],
@@ -96,15 +98,43 @@ describe('public-review provider profile', () => {
'--sandbox', '--mode', 'accept-edits', '--disable-slash-commands',
'--model', 'gemini-3.6-flash', '--effort', 'high',
]));
+ expect(config.args).not.toContain('plan');
expect(config.args).not.toContain('--dangerously-skip-permissions');
expect(config.args).not.toContain('unsafe-model');
});
- it('rejects the action profile for every provider without a maintained sandbox', () => {
+ it('builds the Antigravity gate stage in plan mode, which cannot edit', () => {
+ const config = buildVendorSpawnConfig(antigravity, { safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE });
+ expect(config.args).toEqual(expect.arrayContaining(['--sandbox', '--mode', 'plan', '--disable-slash-commands']));
+ expect(config.args).not.toContain('accept-edits');
+ });
+
+ it('builds grok’s two postures from its own permission-mode and sandbox flags', () => {
+ const gate = buildVendorSpawnConfig({ ...grok, args: ['--always-approve'] }, {
+ effectiveModel: 'grok-4',
+ safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
+ });
+ expect(gate.args).toEqual(expect.arrayContaining([
+ '--permission-mode', 'plan', '--tools', '', '--no-subagents', '--disable-web-search',
+ '--model', 'grok-4',
+ ]));
+ // A saved auto-approval posture must not survive into the screened run.
+ expect(gate.args).not.toContain('--always-approve');
+ expect(gate.args).not.toContain('bypassPermissions');
+ expect(gate.args).not.toContain('--sandbox');
+
+ const actions = buildVendorSpawnConfig(grok, { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE });
+ expect(actions.args).toEqual(expect.arrayContaining([
+ '--sandbox', 'workspace', '--permission-mode', 'acceptEdits',
+ ]));
+ expect(actions.args).not.toContain('plan');
+ });
+
+ it('rejects the action profile for a provider with no maintained sandbox', () => {
expect(() => buildVendorSpawnConfig(localClaude, {
effectiveModel: 'safe-model',
safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
- })).toThrow(/public-review-actions posture/);
+ })).toThrow(/no enforced sandboxed-actions public-review posture/);
});
it('builds a fresh no-tool argv and ignores dangerous saved provider args', () => {
@@ -131,24 +161,30 @@ describe('public-review provider profile', () => {
expect(config.args).not.toContain('--disallowedTools');
});
- it('fails closed instead of assigning the profile to cloud or unknown providers', () => {
+ it('fails closed instead of assigning a posture to an unknown command', () => {
expect(() => buildVendorSpawnConfig({
- id: 'claude-cloud',
+ id: 'custom-agent',
type: 'cli',
- command: 'claude',
- envVars: { ANTHROPIC_BASE_URL: 'https://api.anthropic.com' },
+ command: 'custom-agent',
}, {
- effectiveModel: 'cloud-model',
+ effectiveModel: 'model',
safetyProfile: PUBLIC_REVIEW_EXECUTION_PROFILE,
- })).toThrow(/no enforced public-review posture/);
+ })).toThrow(/no enforced no-tool public-review posture/);
+ });
- expect(() => buildVendorSpawnConfig({
- id: 'custom-agent',
+ it('holds a cloud Claude to the same enforced no-tool argv as the local wrapper', () => {
+ // Public PR content is public, so the posture — not the model's location —
+ // is the control. The argv is what denies tools either way.
+ const config = buildVendorSpawnConfig({
+ id: 'claude-code',
type: 'cli',
- command: 'custom-agent',
+ command: 'claude',
+ envVars: { ANTHROPIC_BASE_URL: 'https://api.anthropic.com' },
}, {
- effectiveModel: 'model',
+ effectiveModel: 'claude-sonnet-5',
safetyProfile: PUBLIC_REVIEW_EXECUTION_PROFILE,
- })).toThrow(/no enforced public-review posture/);
+ });
+ expect(config.args).toEqual(expect.arrayContaining(['--restricted', '--tools', '', '--permission-mode', 'plan']));
+ expect(config.args).toContain('claude-sonnet-5');
});
});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index b0dd0a9904..408d454b35 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -37,7 +37,7 @@ import {
} from '../services/codexAppServer.js';
import { runLocalRuntimeSetup, SETUP_ACTIONS } from '../services/localRuntimeSetup.js';
import { localEndpointPort, localRuntimeForProvider } from '../lib/localProviderRuntime.js';
-import { supportsPublicReviewProvider, supportsPublicReviewActionsProvider } from '../lib/providerVendors.js';
+import { publicReviewPosturesForProvider, PUBLIC_REVIEW_NO_TOOL_POSTURE, PUBLIC_REVIEW_ACTIONS_POSTURE } from '../lib/providerVendors.js';
import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';
import {
captureSystemCapabilities,
@@ -146,10 +146,15 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
// Derived on read from the raw provider. This is an explicit capability of
// the maintained public-review recipe, not a client-side guess based on a
// provider name or a user-writable `args` list.
+ // `publicReviewPostures` is the value the schedule UI filters on, so a stage
+ // offers exactly the providers this install can actually enforce. The two
+ // booleans are derived from it and kept for existing consumers.
+ const publicReviewPostures = publicReviewPosturesForProvider(provider, { tui: provider?.type === 'tui' });
return sanitizeProvider({
...decorated,
- publicReviewSupported: supportsPublicReviewProvider(provider, { tui: provider?.type === 'tui' }),
- publicReviewActionsSupported: supportsPublicReviewActionsProvider(provider, { tui: provider?.type === 'tui' }),
+ publicReviewPostures,
+ publicReviewSupported: publicReviewPostures.includes(PUBLIC_REVIEW_NO_TOOL_POSTURE),
+ publicReviewActionsSupported: publicReviewPostures.includes(PUBLIC_REVIEW_ACTIONS_POSTURE),
});
};
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index db0e6e9644..d78f08d1af 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -30,6 +30,7 @@ import { resolveReviewLoopOptions } from './codeReview.js';
import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';
import { resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
import { resolveOwnsPrWorkflow } from '../lib/slashdoInvocation.js';
+import { isPublicReviewRestrictedProfile } from '../lib/agentExecutionProfiles.js';
const ROOT_DIR = PATHS.root;
@@ -83,6 +84,21 @@ export async function handlePipelineProgression(task, agentId, success) {
const nextStage = stages[nextStageIndex];
+ // A restricted execution profile must never be INHERITED across a stage
+ // boundary — the profile is what selects the provider posture and the
+ // stripped child environment, so carrying the previous stage's value would
+ // run the next stage under the wrong contract (or, if cleared, under none at
+ // all while still holding untrusted public content). A pipeline that has
+ // entered a restricted profile and whose next stage declares none fails
+ // closed rather than handing that content to an unrestricted agent.
+ if (isPublicReviewRestrictedProfile(task.metadata?.executionProfile) && !nextStage.executionProfile) {
+ await updateTask(task.id, {
+ metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'failed', stageResults: updatedResults } }
+ }, task.taskType);
+ emitLog('warn', `⛔ Pipeline ${pipeline.id} stage ${nextStageIndex} declares no execution profile after a restricted stage`, { pipelineId: pipeline.id });
+ return;
+ }
+
// Check next stage's precondition before advancing
if (nextStage.precondition && task.metadata.repoPath) {
const check = checkStagePrecondition(nextStage, task.metadata.repoPath);
@@ -129,6 +145,10 @@ export async function handlePipelineProgression(task, agentId, success) {
nextTask.metadata.providerId = nextStage.providerId;
}
if (nextStage.effort) nextTask.metadata.effort = nextStage.effort;
+ // The profile, unlike the pins above, is SET-OR-CLEARED (see the guard at the
+ // top of the hand-off): each stage runs under exactly the contract it
+ // declares, never the previous stage's.
+ nextTask.metadata.executionProfile = nextStage.executionProfile || null;
// Apply per-stage overrides for agent behavior flags
const stageReadOnly = nextStage.readOnly ?? false;
const taskDefaults = pipeline.taskDefaults || {};
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index 873a0bf334..850213b899 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -137,6 +137,52 @@ describe('handlePipelineProgression', () => {
// two disagree, PortOS fires `gh pr create` on a branch that already has a PR
// ("a pull request already exists" preserves the worktree as a false-positive
// failure), or conversely never opens the PR the agent was told not to open.
+// The execution profile selects the provider POSTURE and the stripped child
+// environment. Inheriting the previous stage's value (or silently clearing it)
+// would run a stage holding untrusted public content under the wrong contract.
+describe('handlePipelineProgression — execution profile hand-off', () => {
+ const publicReviewPipeline = (stages) => runningPipeline({ currentStage: 0, stages });
+
+ it('sets the next stage\'s own profile rather than inheriting the previous one', async () => {
+ const task = {
+ id: 't',
+ taskType: 'user',
+ metadata: {
+ executionProfile: 'public-review-gate',
+ pipeline: publicReviewPipeline([
+ { name: 'Eligibility Gate', executionProfile: 'public-review-gate' },
+ { name: 'Code Review & Actions', executionProfile: 'public-review-actions' },
+ ]),
+ },
+ };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(addTask.mock.calls[0][0].metadata.executionProfile).toBe('public-review-actions');
+ });
+
+ it('fails the pipeline closed rather than advancing a restricted run into an unprofiled stage', async () => {
+ const task = {
+ id: 't',
+ taskType: 'user',
+ metadata: {
+ executionProfile: 'public-review-gate',
+ pipeline: publicReviewPipeline([
+ { name: 'Eligibility Gate', executionProfile: 'public-review-gate' },
+ { name: 'Unprofiled' },
+ ]),
+ },
+ };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(addTask).not.toHaveBeenCalled();
+ expect(updateTask.mock.calls[0][1].metadata.pipeline.status).toBe('failed');
+ });
+
+ it('leaves an ordinary pipeline unprofiled', async () => {
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline() } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(addTask.mock.calls[0][0].metadata.executionProfile).toBeNull();
+ });
+});
+
describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', () => {
const prTask = { id: 't', taskType: 'user', metadata: { openPR: true } };
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 83174c156f..8c1feb14c6 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -62,11 +62,8 @@ import { cliProviderAuthDescriptor } from '../lib/processEnv.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
-import { supportsPublicReviewProvider, supportsPublicReviewActionsProvider } from '../lib/providerVendors.js';
-import {
- isPublicReviewNoToolProfile,
- PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
-} from '../lib/agentExecutionProfiles.js';
+import { supportsPublicReviewPosture, publicReviewPostureForProfile, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';
+import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';
import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';
import { materializePublicReviewInput, materializePublicReviewPatches, readPublicReviewInputSnapshot, validatePublicReviewModel } from './modelAbuseGuard.js';
import { releaseAppReviewMarker } from './appActivity.js';
@@ -422,9 +419,10 @@ async function runAgentSpawn(task) {
const { provider, selectedModel, modelSelection } = resolution;
const isTui = isTuiProvider(provider);
const executionProfile = task.metadata?.executionProfile;
- const publicReviewNoTools = isPublicReviewNoToolProfile(executionProfile);
+ const publicReviewPosture = publicReviewPostureForProfile(executionProfile);
+ const publicReviewNoTools = publicReviewPosture === PUBLIC_REVIEW_NO_TOOL_POSTURE;
const publicReviewActions = executionProfile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;
- const publicReview = publicReviewNoTools || publicReviewActions;
+ const publicReview = Boolean(publicReviewPosture);
if (publicReview) {
const scanBlock = publicReviewScanBlock(task);
if (scanBlock) {
@@ -462,29 +460,18 @@ async function runAgentSpawn(task) {
return null;
}
}
- if (publicReviewActions && !supportsPublicReviewActionsProvider(provider, { tui: isTui })) {
- const reason = `Provider '${provider?.id || provider?.command || 'unknown'}' has no enforced sandboxed public-review actions mode`;
+ // One posture check for both stages. Eligibility is declared by the vendor
+ // row and re-asserted HERE, at spawn time, because a schedule or API
+ // payload can be edited without the browser: the picker is a convenience,
+ // never the enforcement.
+ if (!supportsPublicReviewPosture(provider, publicReviewPosture, { tui: isTui })) {
+ const reason = `Provider '${provider?.id || provider?.command || 'unknown'}' has no enforced ${publicReviewPosture} public-content review mode`;
await updateTask(task.id, {
status: 'blocked',
metadata: {
...task.metadata,
blockedReason: reason,
- blockedCategory: 'public-review-actions-provider-unsupported',
- blockedAt: new Date().toISOString(),
- },
- }, task.taskType || 'user').catch(() => {});
- await cleanupOnError(reason);
- cosEvents.emit('agent:error', { taskId: task.id, error: reason });
- return null;
- }
- if (publicReviewNoTools && !supportsPublicReviewProvider(provider, { tui: isTui })) {
- const reason = `Provider '${provider?.id || provider?.command || 'unknown'}' has no enforced read-only public-content review mode`;
- await updateTask(task.id, {
- status: 'blocked',
- metadata: {
- ...task.metadata,
- blockedReason: reason,
- blockedCategory: 'public-review-provider-unsupported',
+ blockedCategory: publicReviewActions ? 'public-review-actions-provider-unsupported' : 'public-review-provider-unsupported',
blockedAt: new Date().toISOString(),
},
}, task.taskType || 'user').catch(() => {});
@@ -493,7 +480,7 @@ async function runAgentSpawn(task) {
return null;
}
if (publicReviewNoTools) {
- const modelPolicy = await validatePublicReviewModel({ provider, model: selectedModel });
+ const modelPolicy = await validatePublicReviewModel({ provider, model: selectedModel, posture: PUBLIC_REVIEW_NO_TOOL_POSTURE });
if (!modelPolicy.ok) {
const reason = `Public review model is unavailable or not tool-free (${modelPolicy.code})`;
await updateTask(task.id, {
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 7cbf30ed46..33c323c43e 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -312,7 +312,7 @@ describe('agentLifecycle — guard wiring', () => {
expect(AGENT_LIFECYCLE_SRC).toMatch(/if \(scanBlock\) \{[\s\S]*?status: 'blocked'/);
expect(AGENT_LIFECYCLE_SRC).toMatch(/expected fail-closed safety outcome/);
const gateStart = AGENT_LIFECYCLE_SRC.indexOf('const scanBlock = publicReviewScanBlock(task)');
- const gateEnd = AGENT_LIFECYCLE_SRC.indexOf('if (publicReviewActions && !supportsPublicReviewActionsProvider', gateStart);
+ const gateEnd = AGENT_LIFECYCLE_SRC.indexOf('if (!supportsPublicReviewPosture(provider, publicReviewPosture', gateStart);
expect(gateEnd).toBeGreaterThan(gateStart);
expect(AGENT_LIFECYCLE_SRC.slice(gateStart, gateEnd)).not.toContain("cosEvents.emit('agent:error'");
});
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index 3d41ad5fdd..eb0e4966a8 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -17,6 +17,7 @@ import { emitLog } from './cosEvents.js';
import { getActiveProvider, getAllProviders, getProviderById } from './providers.js';
import { isProviderAvailable, getFallbackProvider, getProviderStatus } from './providerStatus.js';
import { selectModelForTask } from './agentModelSelection.js';
+import { publicReviewPostureForTask, resolvePublicReviewProvider } from './publicReviewProviderSelection.js';
/**
* Resolve the provider + model for a task.
@@ -28,6 +29,56 @@ import { selectModelForTask } from './agentModelSelection.js';
* >}
*/
export async function resolveAgentProviderAndModel(task) {
+ // A public-review stage is resolved against the POSTURE it declares, not the
+ // usual pin → active → fallback chain: the ordinary chain is allowed to swap
+ // onto any healthy provider, and swapping untrusted contributor content onto
+ // a provider with no enforced posture is exactly what must not happen. The
+ // eligible set comes from this install's own enabled providers, so a stage
+ // configured on a machine that only has grok resolves to grok.
+ const publicReviewPosture = publicReviewPostureForTask(task);
+ if (publicReviewPosture) return resolvePublicReviewAgentProvider(task, publicReviewPosture);
+ return resolveOrdinaryProviderAndModel(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.
+ */
+async function resolvePublicReviewAgentProvider(task, posture) {
+ const resolved = await resolvePublicReviewProvider({
+ posture,
+ pinnedProviderId: task.metadata?.provider || null,
+ });
+ if (!resolved.ok) {
+ return { ok: false, permanent: true, error: resolved.error, providerId: task.metadata?.provider || undefined };
+ }
+ const { provider } = resolved;
+ 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,
+ });
+ }
+ // A model pin only survives when it was chosen FOR this provider; otherwise
+ // fall back to the provider's own default rather than handing one vendor's
+ // model id to another (the failure mode documented in the ordinary path).
+ const modelSelection = await selectModelForTask(task, provider);
+ const pinnedModel = task.metadata?.model;
+ const selectedModel = pinnedModel && task.metadata?.provider === provider.id
+ ? pinnedModel
+ : (modelSelection.model || provider.defaultModel || null);
+ emitLog('info', `Public-review stage (${posture}) resolved to provider ${provider.id}${selectedModel ? ` model ${selectedModel}` : ''}`, {
+ taskId: task.id,
+ providerId: provider.id,
+ model: selectedModel,
+ });
+ return { ok: true, provider, selectedModel, modelSelection };
+}
+
+async function resolveOrdinaryProviderAndModel(task) {
// A task can pin a specific provider via metadata.provider (e.g. a CoS job's
// per-job AI override). Resolve it BEFORE the active-provider availability
// gate so a pinned-but-healthy provider isn't blocked when the *active*
diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.js
index 507b856b17..93de1f7d29 100644
--- a/server/services/agentProviderResolution.test.js
+++ b/server/services/agentProviderResolution.test.js
@@ -340,3 +340,61 @@ describe('resolveAgentProviderAndModel', () => {
expect(r.selectedModel).toBe('heavy-x');
});
});
+
+// ─── public-review stages ───────────────────────────────────────────────────
+//
+// A public-review stage must NOT go through the ordinary pin → active →
+// fallback chain: that chain can swap onto any healthy provider, and running
+// untrusted contributor content on a provider with no enforced posture is the
+// exact failure this branch exists to prevent. These pin that the eligible set
+// comes from the install's own enabled providers instead.
+describe('resolveAgentProviderAndModel — public-review stages', () => {
+ const CODEX = { id: 'codex-cli', type: 'cli', command: 'codex' };
+ const GROK = { id: 'grok-cli', type: 'cli', command: 'grok' };
+ const OPENCODE = { id: 'opencode', type: 'cli', command: 'opencode' };
+ const gateTask = (metadata = {}) => ({
+ id: 'task-pr',
+ metadata: { executionProfile: 'public-review-gate', ...metadata },
+ });
+
+ it('resolves onto the only eligible provider an install actually has', async () => {
+ getAllProviders.mockResolvedValue({ providers: [OPENCODE, GROK], activeProvider: { id: 'opencode' } });
+ const r = await resolveAgentProviderAndModel(gateTask());
+ expect(r).toMatchObject({ ok: true, provider: { id: 'grok-cli' } });
+ // Never consults the ordinary fallback chain.
+ expect(getFallbackProvider).not.toHaveBeenCalled();
+ });
+
+ it('ignores a stage pin that is not eligible for the posture', async () => {
+ getAllProviders.mockResolvedValue({ providers: [OPENCODE, CODEX], activeProvider: null });
+ const r = await resolveAgentProviderAndModel(gateTask({ provider: 'opencode' }));
+ expect(r).toMatchObject({ ok: true, provider: { id: 'codex-cli' } });
+ });
+
+ it('keeps a model pin only on the provider it was chosen for', async () => {
+ getAllProviders.mockResolvedValue({ providers: [CODEX, 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.
+ await expect(resolveAgentProviderAndModel(gateTask({ provider: 'opencode', model: 'grok-4' })))
+ .resolves.toMatchObject({ provider: { id: 'codex-cli' }, selectedModel: 'm-default' });
+ });
+
+ it('blocks PERMANENTLY when no enabled provider can enforce the posture', async () => {
+ getAllProviders.mockResolvedValue({ providers: [OPENCODE], activeProvider: { id: 'opencode' } });
+ const r = await resolveAgentProviderAndModel(gateTask());
+ expect(r.ok).toBe(false);
+ expect(r.permanent).toBe(true);
+ expect(r.error).toMatch(/no-tool/);
+ });
+
+ it('requires the sandboxed posture for the actions stage, not merely a CLI', async () => {
+ const LOCAL_CLAUDE = { id: 'claude-ollama', type: 'cli', command: 'claude', ollamaBacked: true };
+ getAllProviders.mockResolvedValue({ providers: [LOCAL_CLAUDE], activeProvider: { id: 'claude-ollama' } });
+ // Claude has a no-tool recipe but no sandbox recipe.
+ await expect(resolveAgentProviderAndModel({ id: 't', metadata: { executionProfile: 'public-review-gate' } }))
+ .resolves.toMatchObject({ ok: true, provider: { id: 'claude-ollama' } });
+ await expect(resolveAgentProviderAndModel({ id: 't', metadata: { executionProfile: 'public-review-actions' } }))
+ .resolves.toMatchObject({ ok: false, permanent: true });
+ });
+});
diff --git a/server/services/modelAbuseGuard.js b/server/services/modelAbuseGuard.js
index 44b8a3717c..146ff27e3f 100644
--- a/server/services/modelAbuseGuard.js
+++ b/server/services/modelAbuseGuard.js
@@ -37,7 +37,7 @@ import {
} from '../lib/modelAbuseGuard.js';
import { findCachedRepoFiles } from '../lib/hfCache.js';
import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
-import { supportsPublicReviewProvider } from '../lib/providerVendors.js';
+import { supportsPublicReviewPosture, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';
import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
import { detectVenvBasePythonSync, createVenv, installPackages } from '../lib/pythonSetup.js';
import { safeChildProcessOptions } from '../lib/processEnv.js';
@@ -135,24 +135,39 @@ function normalizePublicReviewInputs(pullRequests) {
}
/**
- * Revalidate the Stage 2 model at spawn time.
+ * Revalidate a public-review stage's provider + model at spawn time.
*
* The picker is only a convenience boundary: schedules and API payloads can
- * be edited without the browser. A public-content review therefore cannot
- * rely on a provider/model choice that was previously accepted by the UI.
- * Require the maintained local Claude wrapper, an actually installed Ollama
- * model, and an authoritative text capability report with no `tools` entry.
- * Unknown, stale, or unprobeable capability state is rejected.
+ * be edited without the browser. A public-content stage therefore cannot rely
+ * on a provider/model choice that was previously accepted by the UI.
+ *
+ * Two independent controls apply, and which one is authoritative depends on
+ * where the model runs:
+ *
+ * - Every provider must carry a maintained vendor recipe for the requested
+ * posture. That argv (codex `--sandbox read-only`, grok
+ * `--permission-mode plan --tools ''`, claude `--restricted --tools ''`, …)
+ * is what actually denies tools to a CLOUD model, which PortOS cannot probe.
+ * - A LOCAL runtime can be probed, so it gets the stricter check it always
+ * had: the model must be installed and its authoritative capability report
+ * must contain no `tools` entry. Unknown or unprobeable state fails closed.
+ *
+ * A model id is required only where PortOS picks one. Vendors that select
+ * their own model (grok, antigravity) legitimately run with no `--model` pin.
*/
-export async function validatePublicReviewModel({ provider, model } = {}) {
- if (!supportsPublicReviewProvider(provider)) {
+export async function validatePublicReviewModel({ provider, model, posture = PUBLIC_REVIEW_NO_TOOL_POSTURE } = {}) {
+ if (!supportsPublicReviewPosture(provider, posture)) {
return publicReviewModelFailure('public-review-provider-unsupported');
}
const modelId = typeof model === 'string' ? model.trim() : '';
- if (!modelId) return publicReviewModelFailure('public-review-model-required');
-
const runtime = localRuntimeForProvider(provider);
- if (!runtime || runtime.kind !== 'ollama') {
+ if (!runtime) return { ok: true, model: modelId || null, runtime: null };
+
+ // Local runtimes are probeable, so the capability report is authoritative
+ // and a model id is mandatory — there is no server-side default to fall back
+ // to for an Ollama/LM Studio wrapper.
+ if (!modelId) return publicReviewModelFailure('public-review-model-required');
+ if (runtime.kind !== 'ollama') {
return publicReviewModelFailure('public-review-runtime-unsupported');
}
diff --git a/server/services/modelAbuseGuard.test.js b/server/services/modelAbuseGuard.test.js
index 6ea217e901..c2684c1c17 100644
--- a/server/services/modelAbuseGuard.test.js
+++ b/server/services/modelAbuseGuard.test.js
@@ -48,10 +48,17 @@ describe('validatePublicReviewModel', () => {
await expect(validatePublicReviewModel({ provider: LOCAL_CLAUDE, model: 'safe-model' }))
.resolves.toMatchObject({ ok: false, code: 'public-review-model-not-tool-free' });
+ // A vendor with no maintained recipe for the posture is rejected before
+ // any model probing — that check, not the model's location, is the gate.
await expect(validatePublicReviewModel({
- provider: { ...LOCAL_CLAUDE, envVars: { ANTHROPIC_BASE_URL: 'https://api.example.com' } },
+ provider: { ...LOCAL_CLAUDE, command: 'custom-agent' },
model: 'safe-model',
})).resolves.toMatchObject({ ok: false, code: 'public-review-provider-unsupported' });
+ await expect(validatePublicReviewModel({
+ provider: LOCAL_CLAUDE,
+ model: 'safe-model',
+ posture: 'sandboxed-actions',
+ })).resolves.toMatchObject({ ok: false, code: 'public-review-provider-unsupported' });
});
it('rejects missing model selection and an unavailable catalog', async () => {
diff --git a/server/services/publicReviewProviderSelection.js b/server/services/publicReviewProviderSelection.js
new file mode 100644
index 0000000000..5b58d618fd
--- /dev/null
+++ b/server/services/publicReviewProviderSelection.js
@@ -0,0 +1,88 @@
+/**
+ * Public-review provider selection.
+ *
+ * A pr-reviewer stage declares the POSTURE it needs (`no-tool` for the
+ * screening/eligibility stages, `sandboxed-actions` for the optional final
+ * review). It never names a vendor. This module turns that posture into a
+ * concrete provider by intersecting the install's own enabled AI providers
+ * with the vendor rows that declare a maintained recipe for the posture.
+ *
+ * That indirection is the point: an install with only grok, only a local
+ * Claude wrapper, or only codex configures the same three stages. Adding a
+ * vendor recipe in `providerVendors.js` makes it selectable everywhere at once
+ * — here, in the schedule UI, and at spawn time — with no list of vendor names
+ * to keep in sync.
+ *
+ * Ordinary provider fallback is deliberately NOT reused: falling back off an
+ * eligible provider onto an ineligible one would run untrusted public content
+ * through a provider with no enforced posture. A stage with no eligible
+ * provider fails closed instead.
+ */
+
+import { getAllProviders } from './providers.js';
+import { isProviderAvailable } from './providerStatus.js';
+import {
+ publicReviewCapableVendorIds,
+ publicReviewPostureForProfile,
+ supportsPublicReviewPosture,
+} from '../lib/providerVendors.js';
+
+/** The posture a task's execution profile requires, or null for a normal task. */
+export function publicReviewPostureForTask(task) {
+ return publicReviewPostureForProfile(task?.metadata?.executionProfile);
+}
+
+const isEnabled = (provider) => provider?.enabled !== false;
+
+/**
+ * Every configured provider that could run `posture` on this install, in the
+ * provider list's own order. `enabled: false` providers are excluded — the
+ * user has switched them off — but momentarily-unavailable ones are kept so a
+ * rate-limited provider still shows as a legal choice in the picker.
+ *
+ * @param {string} posture
+ * @param {{ providers?: object[] }} [options]
+ * @returns {Promise<object[]>}
+ */
+export async function eligiblePublicReviewProviders(posture, { providers = null } = {}) {
+ const list = providers || (await getAllProviders()).providers || [];
+ return list.filter((provider) => (
+ isEnabled(provider)
+ && supportsPublicReviewPosture(provider, posture, { tui: provider?.type === 'tui' })
+ ));
+}
+
+/**
+ * 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
+ * all (so a stage stays configured through a transient rate limit rather than
+ * silently swapping vendors).
+ *
+ * @param {{ posture: string, pinnedProviderId?: string|null, activeProviderId?: string|null }} args
+ * @returns {Promise<{ ok: true, provider: object, pinHonored: boolean }
+ * | { ok: false, code: string, error: string }>}
+ */
+export async function resolvePublicReviewProvider({ posture, pinnedProviderId = null, activeProviderId = null } = {}) {
+ 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 });
+ if (eligible.length === 0) {
+ return {
+ ok: false,
+ code: 'public-review-no-eligible-provider',
+ error: `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 = active
+ || eligible.find((provider) => isProviderAvailable(provider.id))
+ || eligible[0];
+ return { ok: true, provider: chosen, pinHonored: false };
+}
diff --git a/server/services/publicReviewProviderSelection.test.js b/server/services/publicReviewProviderSelection.test.js
new file mode 100644
index 0000000000..2dd6deefd8
--- /dev/null
+++ b/server/services/publicReviewProviderSelection.test.js
@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getAllProviders = vi.fn();
+const isProviderAvailable = vi.fn(() => true);
+
+vi.mock('./providers.js', () => ({ getAllProviders }));
+vi.mock('./providerStatus.js', () => ({ isProviderAvailable }));
+
+const {
+ eligiblePublicReviewProviders,
+ publicReviewPostureForTask,
+ resolvePublicReviewProvider,
+} = await import('./publicReviewProviderSelection.js');
+
+const CODEX = { id: 'codex-cli', type: 'cli', command: 'codex' };
+const GROK = { id: 'grok-cli', type: 'cli', command: 'grok' };
+const LOCAL_CLAUDE = { id: 'claude-ollama', type: 'cli', command: 'claude', ollamaBacked: true };
+const OPENCODE = { id: 'opencode', type: 'cli', command: 'opencode' };
+const OLLAMA_API = { id: 'ollama', type: 'api' };
+
+const seed = (providers, activeProvider = null) => {
+ getAllProviders.mockResolvedValue({ providers, activeProvider });
+};
+
+describe('publicReviewPostureForTask', () => {
+ it('maps a stage execution profile to its posture and ignores ordinary tasks', () => {
+ expect(publicReviewPostureForTask({ metadata: { executionProfile: 'public-review-gate' } })).toBe('no-tool');
+ expect(publicReviewPostureForTask({ metadata: { executionProfile: 'public-review-actions' } })).toBe('sandboxed-actions');
+ expect(publicReviewPostureForTask({ metadata: {} })).toBeNull();
+ expect(publicReviewPostureForTask(undefined)).toBeNull();
+ });
+});
+
+describe('eligiblePublicReviewProviders', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ // The regression this uniquely catches: an install without codex/antigravity
+ // must still surface its own providers rather than an empty list.
+ it('returns this install’s own eligible providers, not a fixed vendor list', async () => {
+ seed([GROK, OPENCODE, OLLAMA_API]);
+ expect((await eligiblePublicReviewProviders('no-tool')).map((p) => p.id)).toEqual(['grok-cli']);
+ expect((await eligiblePublicReviewProviders('sandboxed-actions')).map((p) => p.id)).toEqual(['grok-cli']);
+ });
+
+ it('excludes providers the user has switched off', async () => {
+ seed([{ ...CODEX, enabled: false }, LOCAL_CLAUDE]);
+ expect((await eligiblePublicReviewProviders('no-tool')).map((p) => p.id)).toEqual(['claude-ollama']);
+ });
+
+ it('keeps a momentarily-unavailable provider selectable', async () => {
+ isProviderAvailable.mockReturnValue(false);
+ seed([CODEX]);
+ expect((await eligiblePublicReviewProviders('no-tool')).map((p) => p.id)).toEqual(['codex-cli']);
+ });
+});
+
+describe('resolvePublicReviewProvider', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ isProviderAvailable.mockReturnValue(true);
+ });
+
+ it('honors an eligible stage pin over the active provider', async () => {
+ seed([CODEX, GROK], { id: 'codex-cli' });
+ await expect(resolvePublicReviewProvider({ posture: 'no-tool', pinnedProviderId: 'grok-cli' }))
+ .resolves.toMatchObject({ ok: true, pinHonored: true, provider: { id: 'grok-cli' } });
+ });
+
+ it('drops an INELIGIBLE pin instead of running the stage on it', async () => {
+ seed([OPENCODE, CODEX], { id: 'opencode' });
+ const resolved = await resolvePublicReviewProvider({ posture: 'sandboxed-actions', pinnedProviderId: 'opencode' });
+ expect(resolved).toMatchObject({ ok: true, pinHonored: false, provider: { id: 'codex-cli' } });
+ });
+
+ it('prefers an available provider over an unavailable earlier one', async () => {
+ isProviderAvailable.mockImplementation((id) => id === 'grok-cli');
+ seed([CODEX, GROK]);
+ await expect(resolvePublicReviewProvider({ posture: 'no-tool' }))
+ .resolves.toMatchObject({ provider: { id: 'grok-cli' } });
+ });
+
+ it('still resolves when every eligible provider is momentarily unavailable', async () => {
+ isProviderAvailable.mockReturnValue(false);
+ seed([CODEX]);
+ await expect(resolvePublicReviewProvider({ posture: 'no-tool' }))
+ .resolves.toMatchObject({ ok: true, provider: { id: 'codex-cli' } });
+ });
+
+ it('fails closed with an actionable reason when nothing on this install qualifies', async () => {
+ seed([OPENCODE, OLLAMA_API]);
+ const resolved = await resolvePublicReviewProvider({ posture: 'sandboxed-actions' });
+ expect(resolved.ok).toBe(false);
+ expect(resolved.code).toBe('public-review-no-eligible-provider');
+ expect(resolved.error).toMatch(/sandboxed-actions/);
+ });
+});