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

feat: enable bootstrap credentials for tool-free code reviews (#7720)

[._.]/ Adam Eivye0bed4ae6ecf
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsx
index 521f74d3fd..61767e783d 100644
--- a/client/src/components/cos/ReviewerPicker.jsx
+++ b/client/src/components/cos/ReviewerPicker.jsx
@@ -273,7 +273,9 @@ export default function ReviewerPicker({
if (providerReviewUnsupported?.[token]) {
return {
label: "can't review",
- title: `${labelFor(token)} has no enforced tool-free review transport on this machine, so a review round would never complete. Switch the provider to its API mode, or pick a reviewer harness that supports one.`
+ title: providerReviewUnsupported[token] === 'REVIEWER_BOOTSTRAP_UNSUPPORTED'
+ ? 'Configure a review credential command in this provider’s credential bootstrap settings.'
+ : `${labelFor(token)} has no enforced tool-free review transport on this machine, so a review round would never complete. Switch the provider to its API mode, or pick a reviewer harness that supports one.`
};
}
return null;
diff --git a/client/src/components/providers/ProviderCredentialBootstraps.jsx b/client/src/components/providers/ProviderCredentialBootstraps.jsx
index 8e02c7f8e2..9b084b1ee8 100644
--- a/client/src/components/providers/ProviderCredentialBootstraps.jsx
+++ b/client/src/components/providers/ProviderCredentialBootstraps.jsx
@@ -29,7 +29,7 @@ import { SERVICE_SLUG_RE } from '../../../../server/lib/serviceDefinitions.js';
const SLUG_PATTERN = SERVICE_SLUG_RE.source.slice(1, -1);
const EMPTY_DRAFT = Object.freeze({
- slug: '', label: '', command: '', args: '', argsSeparator: '', setupCommand: '', harnessNames: {},
+ slug: '', label: '', command: '', args: '', envCommand: '', argsSeparator: '', setupCommand: '', harnessNames: {},
});
/** A stored app as the form edits it: argv as one space-separated line. */
@@ -38,6 +38,7 @@ const draftFromApp = (slug, app) => ({
label: app.label || '',
command: app.command || '',
args: Array.isArray(app.args) ? app.args.join(' ') : '',
+ envCommand: app.envCommand?.join('\n') || '',
argsSeparator: app.argsSeparator || '',
setupCommand: app.setupCommand || '',
harnessNames: { ...(app.harnessNames || {}) },
@@ -53,6 +54,7 @@ function appFromDraft(draft) {
label: draft.label.trim(),
command: draft.command.trim(),
...(args.length > 0 ? { args } : {}),
+ ...(draft.envCommand.trim() ? { envCommand: draft.envCommand.split('\n').filter(line => line.trim()) } : {}),
...(draft.argsSeparator.trim() ? { argsSeparator: draft.argsSeparator.trim() } : {}),
...(draft.setupCommand.trim() ? { setupCommand: draft.setupCommand.trim() } : {}),
...(Object.keys(harnessNames).length > 0 ? { harnessNames } : {}),
@@ -81,6 +83,9 @@ function BootstrapForm({ draft, editing, harnesses, busy, onChange, onSubmit, on
<FormField label="Arguments" hint="Space-separated, before the harness name" compact>
<input id="bootstrap-args" type="text" value={draft.args} onChange={set('args')} className={INPUT_CLASS} placeholder="run" />
</FormField>
+ <FormField label="Review credential command" hint="Tool-free reviews only; wrapper is never used there. Executable then one argument per line; prints KEY=value credentials, never shell code or JSON. Cached for one minute. Keep secrets out of argv." compact>
+ <textarea id="bootstrap-env-command" value={draft.envCommand} onChange={set('envCommand')} rows={3} className={INPUT_CLASS} placeholder={'corp-auth\nprint-env'} />
+ </FormField>
<FormField label="Args separator" hint="Inserted between the harness name and its own args, e.g. --" compact>
<input id="bootstrap-separator" type="text" value={draft.argsSeparator} onChange={set('argsSeparator')} className={INPUT_CLASS} placeholder="--" />
</FormField>
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index abc3abbe8a..a8126cfe2f 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -102,6 +102,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
tuiPromptDelayMs: provider?.tuiPromptDelayMs || 2500,
credentialBootstrapSetupCommand: provider?.credentialBootstrap?.setupCommand || '',
credentialBootstrapCommand: provider?.credentialBootstrap?.command || '',
+ credentialBootstrapEnvCommand: provider?.credentialBootstrap?.envCommand?.join('\n') || '',
credentialBootstrapArgs: provider?.credentialBootstrap?.args?.join(' ') || '',
credentialBootstrapHarnessId: provider?.credentialBootstrap?.harnessId || '',
credentialBootstrapArgsSeparator: provider?.credentialBootstrap?.argsSeparator || '',
@@ -470,6 +471,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
...(formData.credentialBootstrapSetupCommand.trim() ? { setupCommand: formData.credentialBootstrapSetupCommand.trim() } : {}),
command: bootstrapCommand,
args: argList(formData.credentialBootstrapArgs),
+ ...(formData.credentialBootstrapEnvCommand.trim()
+ ? { envCommand: formData.credentialBootstrapEnvCommand.split('\n').filter(line => line.trim()) } : {}),
...(formData.credentialBootstrapHarnessId.trim() ? { harnessId: formData.credentialBootstrapHarnessId.trim() } : {}),
...(formData.credentialBootstrapArgsSeparator.trim() ? { argsSeparator: formData.credentialBootstrapArgsSeparator.trim() } : {}),
}
@@ -477,6 +480,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
}
delete data.credentialBootstrapSetupCommand;
delete data.credentialBootstrapCommand;
+ delete data.credentialBootstrapEnvCommand;
delete data.credentialBootstrapArgs;
delete data.credentialBootstrapHarnessId;
delete data.credentialBootstrapArgsSeparator;
@@ -722,6 +726,23 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
/>
</FormField>
</div>
+ <FormField label="Review credential command (optional)" compact>
+ <textarea
+ id="provider-bootstrap-env-command"
+ value={formData.credentialBootstrapEnvCommand}
+ onChange={(e) => setFormData(prev => ({ ...prev, credentialBootstrapEnvCommand: e.target.value }))}
+ placeholder={'token-cli\nprint-env'}
+ rows={3}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </FormField>
+ <p className="text-xs text-gray-500">
+ Used for tool-free reviews only; the wrap form is never used there.
+ Enter the executable, then one argument per line (no shell quoting).
+ It must print KEY=value lines for provider authentication; JSON and other lines are ignored.
+ Only recognized provider credentials and API endpoints are passed to the reviewer.
+ Credentials are cached in memory for one minute. Do not put secrets in command arguments.
+ </p>
<p className="text-xs text-gray-500">
For a CLI that provisions its own short-lived credential (e.g. a token for a proxy) and then
runs the harness itself. <strong>Setup Command</strong> is a one-time step shown to you —
diff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsx
index a40a5f1247..b622b9c700 100644
--- a/client/src/components/providers/ProviderForm.test.jsx
+++ b/client/src/components/providers/ProviderForm.test.jsx
@@ -106,6 +106,7 @@ describe('ProviderForm', () => {
fireEvent.change(screen.getByLabelText('Setup Command'), { target: { value: 'npm install -g @your-org/token-cli' } });
fireEvent.change(screen.getByLabelText('Bootstrap Command'), { target: { value: 'token-cli' } });
fireEvent.change(screen.getByLabelText('Bootstrap Args'), { target: { value: 'run' } });
+ fireEvent.change(screen.getByLabelText('Review credential command (optional)'), { target: { value: 'token-cli\nprint-env\naccount with spaces' } });
fireEvent.change(screen.getByLabelText('Harness ID (optional)'), { target: { value: 'claude-code' } });
fireEvent.change(screen.getByLabelText('Args Separator (optional)'), { target: { value: '--' } });
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
@@ -115,6 +116,7 @@ describe('ProviderForm', () => {
setupCommand: 'npm install -g @your-org/token-cli',
command: 'token-cli',
args: ['run'],
+ envCommand: ['token-cli', 'print-env', 'account with spaces'],
harnessId: 'claude-code',
argsSeparator: '--',
},
diff --git a/server/lib/README.md b/server/lib/README.md
index b2f3fe25ad..33d28dc7f3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -279,7 +279,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
| `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `release-flow`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. |
| `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. |
-| `credentialBootstrap.js` | Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static `apiKey` PortOS stores — a `provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? }` record. `hasCredentialBootstrap(provider)` and `applyCredentialBootstrap(provider, command, args)` (pure) return the command+args PortOS should actually spawn: `<command> <args...> <harnessId ?? command> [<argsSeparator>] <args...>` — the bootstrap CLI in front of the harness invocation, naming the harness as `harnessId` when the bootstrap CLI uses its own identifier rather than the binary name, and inserting `argsSeparator` (e.g. `--`) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. `resolveCliSpawn(provider, command, args, childEnv)` composes that with Windows shim resolution (`bufferedSpawn.js`) for the three headless spawn sites that repeated the same sequence (`runner.js`, `cliProviderRun.js`, `visionCli.js`) — the argv analog of why `cliChildEnv.js`'s `buildCliChildEnv` exists. Every call site keeps resolving `provider.command`/`args` unchanged for vendor detection, prompt-delivery convention, and the TUI's own ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call — plus anything that observes the launching shell or PATH (missing-binary detection, readiness probes), which must read the SPAWNED pair. A public-review posture is never wrapped (the enforced recipe is the sandbox); the skip lives in the helper, keyed on `safetyProfile`. The pure argv composition lives in `aiToolkit/internal/credentialBootstrap.js` (`composeBootstrapSpawn` / `hasCredentialBootstrap`, dependency-free), re-exported through here so the vendored toolkit's own catalog probes compose the same shape without importing out. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. Both also return `wrapped`, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: `needsProcessGroup(wrapped)` says whether to spawn `detached` and kill with `{ processGroup: true }` (POSIX only — Windows' `taskkill /T` is already tree-wide), and `processGroupKillable(child, processGroup)` adapts a child for the aiToolkit runner's external-run registry, whose vendored `killProcessTree` has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. `trackDetachedGroup(child, processGroup)` / `signalDetachedGroups(signal, logFailure)` are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at `npm start`) from orphaning one. |
+| `credentialBootstrap.js` | resolveBootstrapEnv(provider, { safetyProfile }) runs optional envCommand argv only for no-tool review, parses KEY=value output without evaluation, and caches credentials in memory for one minute. Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static `apiKey` PortOS stores — a `provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? }` record. `hasCredentialBootstrap(provider)` and `applyCredentialBootstrap(provider, command, args)` (pure) return the command+args PortOS should actually spawn: `<command> <args...> <harnessId ?? command> [<argsSeparator>] <args...>` — the bootstrap CLI in front of the harness invocation, naming the harness as `harnessId` when the bootstrap CLI uses its own identifier rather than the binary name, and inserting `argsSeparator` (e.g. `--`) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. `resolveCliSpawn(provider, command, args, childEnv)` composes that with Windows shim resolution (`bufferedSpawn.js`) for the three headless spawn sites that repeated the same sequence (`runner.js`, `cliProviderRun.js`, `visionCli.js`) — the argv analog of why `cliChildEnv.js`'s `buildCliChildEnv` exists. Every call site keeps resolving `provider.command`/`args` unchanged for vendor detection, prompt-delivery convention, and the TUI's own ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call — plus anything that observes the launching shell or PATH (missing-binary detection, readiness probes), which must read the SPAWNED pair. A public-review posture is never wrapped (the enforced recipe is the sandbox); the skip lives in the helper, keyed on `safetyProfile`. The pure argv composition lives in `aiToolkit/internal/credentialBootstrap.js` (`composeBootstrapSpawn` / `hasCredentialBootstrap`, dependency-free), re-exported through here so the vendored toolkit's own catalog probes compose the same shape without importing out. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. Both also return `wrapped`, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: `needsProcessGroup(wrapped)` says whether to spawn `detached` and kill with `{ processGroup: true }` (POSIX only — Windows' `taskkill /T` is already tree-wide), and `processGroupKillable(child, processGroup)` adapts a child for the aiToolkit runner's external-run registry, whose vendored `killProcessTree` has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. `trackDetachedGroup(child, processGroup)` / `signalDetachedGroups(signal, logFailure)` are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at `npm start`) from orphaning one. |
| `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. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. |
| `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. |
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 43ef82d15c..77463cb734 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -237,6 +237,7 @@ export const providerSchema = z.object({
setupCommand: z.string().trim().max(500).optional(),
command: z.string().trim().min(1).max(200),
args: z.array(z.string().max(200)).max(20).optional(),
+ envCommand: z.array(z.string().min(1).max(500)).min(1).max(21).optional(),
// What PortOS names the harness AS, when calling the bootstrap CLI — some
// wrapper CLIs use their own identifier for a harness rather than its
// binary name (e.g. `claude-code` where `command` is the binary `claude`).
diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.js
index 1000fb34ba..27daae27af 100644
--- a/server/lib/cliChildEnv.js
+++ b/server/lib/cliChildEnv.js
@@ -270,6 +270,16 @@ function allowlistEnv(env, keys) {
};
}
+// Only explicit bootstrap output may supply these credentials. Never overlay
+// arbitrary output: PATH, NODE_OPTIONS, config files and tool settings could
+// replace the enforced recipe even though its argv remained unchanged.
+const BOOTSTRAP_REVIEW_AUTH_KEYS = new Set([
+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',
+ 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE',
+ 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENAI_API_KEY',
+ 'XAI_API_KEY', 'GROK_API_KEY', 'KIMI_API_KEY', 'MOONSHOT_API_KEY', 'CURSOR_API_KEY',
+]);
+
export function buildPublicReviewCliEnv(env = {}) {
return allowlistEnv(env, PUBLIC_REVIEW_ENV_KEYS);
}
@@ -319,6 +329,7 @@ export function buildPublicReviewActionsCliEnv(env = {}) {
* Pass it whenever the spawn names a cwd — omitting it silently reopens #3193,
* which is why `spawnCwd.test.js` only counts a call carrying `cwd` as a pin.
* @param {object|null} [options.extra] - see `composeProviderEnv`.
+ * @param {object|null} [options.bootstrapEnv] - Explicit credential-command output; only recognized auth keys pass, only in an opted-in no-tool review.
* @param {boolean} [options.guard=false] - prepend the pm2 guard shim onto the
* final `PATH` so an unrestricted agent can't `pm2 kill` the shared daemon.
* Only the agent-spawning sites opt in; the Run Prompt / fire-and-collect
@@ -333,6 +344,7 @@ export function buildCliChildEnv({
cwd,
extra = null,
guard = false,
+ bootstrapEnv = null,
safetyProfile = null,
} = {}) {
const composed = withSpawnCwdEnv(
@@ -346,6 +358,11 @@ export function buildCliChildEnv({
? buildPublicReviewActionsCliEnv(composed)
: composed;
+ if (isPublicReviewNoToolProfile(safetyProfile) && provider?.credentialBootstrap?.envCommand) {
+ Object.assign(env, Object.fromEntries(Object.entries(bootstrapEnv || {})
+ .filter(([key, value]) => BOOTSTRAP_REVIEW_AUTH_KEYS.has(key) && typeof value === 'string')));
+ }
+
// CLAUDECODE is set when PortOS itself runs inside Claude Code; passing it
// through would make a spawned Claude CLI think it's nested in that session.
delete env.CLAUDECODE;
diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.js
index 1b863defda..52bc3d59a9 100644
--- a/server/lib/cliChildEnv.test.js
+++ b/server/lib/cliChildEnv.test.js
@@ -755,3 +755,19 @@ describe('no spawn site rebuilds the CLI child env by hand', () => {
).toEqual([]);
});
});
+
+it('admits only opted-in bootstrap auth in no-tool mode and strips it from actions', () => {
+ const provider = { command: 'claude', credentialBootstrap: { command: 'token-cli', envCommand: ['token-cli', 'env'] } };
+ const bootstrapEnv = { ANTHROPIC_AUTH_TOKEN: 'example-token', ANTHROPIC_BASE_URL: 'https://api.example.com',
+ PATH: '/untrusted', NODE_OPTIONS: '--require=untrusted', OPENCODE_CONFIG_CONTENT: '{}', GH_TOKEN: 'example-forge-token' };
+ const options = { baseEnv: { PATH: '/safe' }, provider, bootstrapEnv, cwd: '/scratch' };
+ const noTool = buildCliChildEnv({ ...options, safetyProfile: PUBLIC_REVIEW_EXECUTION_PROFILE });
+ expect(noTool.ANTHROPIC_AUTH_TOKEN).toBe('example-token');
+ expect(noTool.ANTHROPIC_BASE_URL).toBe('https://api.example.com');
+ expect(noTool.PATH).toBe('/safe');
+ for (const key of ['NODE_OPTIONS', 'OPENCODE_CONFIG_CONTENT', 'GH_TOKEN']) expect(noTool).not.toHaveProperty(key);
+ const actions = buildCliChildEnv({ ...options, safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE });
+ expect(actions).not.toHaveProperty('ANTHROPIC_AUTH_TOKEN');
+ expect(actions).not.toHaveProperty('ANTHROPIC_BASE_URL');
+ expect(buildCliChildEnv({ ...options, provider: { command: 'claude' }, safetyProfile: PUBLIC_REVIEW_EXECUTION_PROFILE })).not.toHaveProperty('ANTHROPIC_AUTH_TOKEN');
+});
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index d93a9a2cf4..5f0fc36413 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -103,11 +103,12 @@ export function pickCliProvider(providers, config = {}) {
* @param {number} [args.timeoutMs] - SIGTERM after this many ms (default 300000)
* @param {(chunk: string, stream: 'stdout'|'stderr') => void} [args.onData] - live output callback
* @param {NodeJS.ProcessEnv} [args.baseEnv] - base env for the child (default process.env); the shared child-env composer filters inherited variables. Explicit provider.envVars still overlays it.
+ * @param {object|null} [args.bootstrapEnv] - Credential-command output for an opted-in tool-free review; filtered by buildCliChildEnv.
* @param {string} [args.safetyProfile] - Optional maintained no-tool profile. Refuses unsupported providers and extra argv; both argv and environment use the same profile.
* @returns {Promise<{ text: string, exitCode: number, stderr: string, partial: boolean, stderrTail: string } | { error: string, exitCode?: number, stderr?: string, stderrTail?: string }>}
*/
export function runCliProviderPrompt(args = {}) {
- const { provider, model = null, prompt, cwd, extraArgs = [], timeoutMs = 300000, onData, baseEnv = process.env, safetyProfile = null } = args;
+ const { provider, model = null, prompt, cwd, extraArgs = [], timeoutMs = 300000, onData, baseEnv = process.env, safetyProfile = null, bootstrapEnv = null } = args;
if (!provider?.command) {
return Promise.resolve({ error: 'Provider has no command configured' });
@@ -149,6 +150,7 @@ export function runCliProviderPrompt(args = {}) {
const effectiveCwd = cwd || process.cwd();
const childEnv = buildCliChildEnv({
baseEnv,
+ bootstrapEnv,
provider: effectiveProvider,
cwd: effectiveCwd,
safetyProfile,
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index c3521c94f7..dd583e7a74 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -11,6 +11,7 @@ vi.mock('./bufferedSpawn.js', async (importOriginal) => {
const { pickCliProvider, runCliProviderPrompt } = await import('./cliProviderRun.js');
const { resolveWindowsExecutable } = await import('./bufferedSpawn.js');
+const { resolveBootstrapEnv } = await import('./credentialBootstrap.js');
const cli = (id, extra = {}) => ({ id, type: 'cli', command: id, enabled: true, models: [], ...extra });
@@ -132,15 +133,18 @@ describe('runCliProviderPrompt', () => {
const { join } = await import('node:path');
const dir = await mkdtemp(join(tmpdir(), 'review-cli-bootstrap-'));
const command = join(dir, 'claude');
- await writeFile(command, '#!/usr/bin/env node\nprocess.stdin.resume(); process.stdin.on("end", () => process.stdout.write(JSON.stringify({ args: process.argv.slice(2) })));', { mode: 0o755 });
+ await writeFile(command, '#!/usr/bin/env node\nprocess.stdin.resume(); process.stdin.on("end", () => process.stdout.write(JSON.stringify({ args: process.argv.slice(2), auth: process.env.ANTHROPIC_AUTH_TOKEN })));', { mode: 0o755 });
// The bootstrap binary does not exist: had the wrap applied, this spawn
// would ENOENT instead of reaching the harness script above.
- const provider = { ...cli('example-claude'), command, credentialBootstrap: { command: join(dir, 'token-cli-missing'), args: ['run'] } };
+ const provider = { ...cli('example-claude'), command, credentialBootstrap: { command: join(dir, 'token-cli-missing'), args: ['run'],
+ envCommand: [process.execPath, '-e', 'console.log("ANTHROPIC_AUTH_TOKEN=example-token")'] } };
+ const bootstrapEnv = await resolveBootstrapEnv(provider, { safetyProfile: 'public-review-gate' });
const result = await runCliProviderPrompt({
- provider, model: 'pinned-model', prompt: 'untrusted diff', cwd: dir, safetyProfile: 'public-review-gate',
+ provider, bootstrapEnv, model: 'pinned-model', prompt: 'untrusted diff', cwd: dir, safetyProfile: 'public-review-gate',
}).finally(() => rm(dir, { recursive: true, force: true }));
expect(result.error).toBeUndefined();
expect(JSON.parse(result.text).args).toEqual(expect.arrayContaining(['--restricted', '--tools', '']));
+ expect(JSON.parse(result.text).auth).toBe('example-token');
});
it('rejects a missing command without spawning', async () => {
diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.js
index 39c083540b..5f8e96cba9 100644
--- a/server/lib/credentialBootstrap.js
+++ b/server/lib/credentialBootstrap.js
@@ -60,12 +60,65 @@
* the AI toolkit or the data layer.
*/
-import { IS_WIN32, resolveWindowsExecutable, prepareWindowsSafeSpawn, killProcessTree } from './bufferedSpawn.js';
-import { isPublicReviewRestrictedProfile } from './agentExecutionProfiles.js';
+import { IS_WIN32, resolveWindowsExecutable, prepareWindowsSafeSpawn, prepareCliSpawn, killProcessTree } from './bufferedSpawn.js';
+import { execFile } from './childProcess.js';
+import { tmpdir } from 'node:os';
+import { withSpawnCwdEnv } from './spawnCwd.js';
+import { isPublicReviewNoToolProfile, isPublicReviewRestrictedProfile } from './agentExecutionProfiles.js';
import { composeBootstrapSpawn, hasCredentialBootstrap } from './aiToolkit/internal/credentialBootstrap.js';
export { hasCredentialBootstrap };
+// Credentials are memory-only and expire after one minute. Key by the record
+// and its configuration so editing a command or account cannot reuse old auth.
+const bootstrapEnvCache = new Map();
+const BOOTSTRAP_ENV_TTL_MS = 60_000;
+
+/**
+ * Materialize credentials independently of a review. The command gets neither
+ * the prompt nor the enforced harness argv. Only no-tool callers may opt in;
+ * sandboxed actions must never acquire these credentials.
+ */
+export async function resolveBootstrapEnv(provider, { safetyProfile = null } = {}) {
+ const argv = provider?.credentialBootstrap?.envCommand;
+ if (!argv) return {};
+ if (!isPublicReviewNoToolProfile(safetyProfile)) {
+ throw new Error('Bootstrap credentials are available only for tool-free reviews.');
+ }
+ if (!Array.isArray(argv) || !argv.length || argv.some(value => typeof value !== 'string' || !value || value.includes('\0'))) {
+ throw new Error('Invalid bootstrap credential command.');
+ }
+ const key = JSON.stringify([provider.id, argv, provider.envVars]);
+ const now = Date.now();
+ for (const [cachedKey, entry] of bootstrapEnvCache) {
+ if (entry.expires <= now) bootstrapEnvCache.delete(cachedKey);
+ }
+ const cached = bootstrapEnvCache.get(key);
+ if (cached) return { ...cached.env };
+ const cwd = tmpdir();
+ const childEnv = withSpawnCwdEnv({ ...process.env, ...provider.envVars }, cwd);
+ const spawnConfig = prepareCliSpawn(argv[0], argv.slice(1), childEnv);
+ const env = await new Promise((resolve, reject) => {
+ // execFile never evaluates output or invokes a shell. Bound runtime and
+ // output, and never propagate stderr/stdout or the command in an error.
+ execFile(spawnConfig.command, spawnConfig.args, {
+ cwd, env: childEnv,
+ shell: false, timeout: 15_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
+ }, (error, stdout) => {
+ if (error) return reject(new Error('Bootstrap credential command failed.'));
+ const entries = String(stdout).split(/\r?\n/).flatMap(line => {
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)=([^\0\r\n]*)$/.exec(line);
+ return match ? [[match[1], match[2]]] : [];
+ });
+ resolve(Object.fromEntries(entries));
+ });
+ });
+ if (!Object.keys(env).length) throw new Error('Bootstrap credential command returned no environment assignments.');
+ if (bootstrapEnvCache.size >= 128) bootstrapEnvCache.delete(bootstrapEnvCache.keys().next().value);
+ bootstrapEnvCache.set(key, { env, expires: Date.now() + BOOTSTRAP_ENV_TTL_MS });
+ return { ...env };
+}
+
/**
* The command+args PortOS should actually spawn for this provider: the
* bootstrap CLI in front of the harness invocation when configured, or the
diff --git a/server/lib/credentialBootstrap.test.js b/server/lib/credentialBootstrap.test.js
index d1fc587b30..8b313c2e48 100644
--- a/server/lib/credentialBootstrap.test.js
+++ b/server/lib/credentialBootstrap.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
-import { hasCredentialBootstrap, applyCredentialBootstrap, resolveCliSpawn, needsProcessGroup, processGroupKillable, trackDetachedGroup, signalDetachedGroups, resetDetachedGroupsForTests } from './credentialBootstrap.js';
+import * as childProcess from './childProcess.js';
+import { resolveBootstrapEnv, hasCredentialBootstrap, applyCredentialBootstrap, resolveCliSpawn, needsProcessGroup, processGroupKillable, trackDetachedGroup, signalDetachedGroups, resetDetachedGroupsForTests } from './credentialBootstrap.js';
import { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from './agentExecutionProfiles.js';
vi.mock('./bufferedSpawn.js', async (importOriginal) => ({
@@ -296,3 +297,37 @@ describe('credentialBootstrap', () => {
});
});
});
+
+describe('resolveBootstrapEnv', () => {
+ afterEach(() => vi.restoreAllMocks());
+ const profile = { safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE };
+ const record = (id, script) => ({ id, credentialBootstrap: {
+ command: 'never-run-wrapper', envCommand: [process.execPath, '-e', script],
+ } });
+
+ it('parses assignments literally and keeps cached credentials isolated from callers and configuration changes', async () => {
+ const spawn = vi.spyOn(childProcess, 'execFile');
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1000);
+ const output = ['ANTHROPIC_AUTH_TOKEN=example-token', 'INVALID LINE', 'export BAD=value', 'LITERAL=$(do-not-run)=value', 'EMPTY=', '1BAD=value', '{"KEY":"value"}'].join('\n');
+ const provider = record('cache-example', 'console.log(' + JSON.stringify(output) + ')');
+ const first = await resolveBootstrapEnv(provider, profile);
+ expect(first).toEqual({ ANTHROPIC_AUTH_TOKEN: 'example-token', LITERAL: '$(do-not-run)=value', EMPTY: '' });
+ first.ANTHROPIC_AUTH_TOKEN = 'mutated';
+ expect((await resolveBootstrapEnv(provider, profile)).ANTHROPIC_AUTH_TOKEN).toBe('example-token');
+ expect(spawn).toHaveBeenCalledTimes(1);
+ clock.mockReturnValue(62000);
+ await resolveBootstrapEnv(provider, profile);
+ expect(spawn).toHaveBeenCalledTimes(2);
+ const changed = record(provider.id, 'console.log("ANTHROPIC_AUTH_TOKEN=changed")');
+ expect((await resolveBootstrapEnv(changed, profile)).ANTHROPIC_AUTH_TOKEN).toBe('changed');
+ expect(spawn).toHaveBeenCalledTimes(3);
+ });
+
+ it('rejects actions before executing and never exposes failed command output', async () => {
+ const provider = record('failure-example', 'console.error("example-private-value"); process.exit(1)');
+ await expect(resolveBootstrapEnv(provider, { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE })).rejects.toThrow('only for tool-free');
+ await expect(resolveBootstrapEnv(provider, profile)).rejects.toThrow(/^Bootstrap credential command failed\.$/);
+ await expect(resolveBootstrapEnv(record('empty-example', 'console.log("not an assignment")'), profile)).rejects.toThrow('no environment assignments');
+ expect(await resolveBootstrapEnv({ credentialBootstrap: { command: 'never-run-wrapper' } }, profile)).toEqual({});
+ });
+});
diff --git a/server/lib/providerPresets.js b/server/lib/providerPresets.js
index 0d5d98d15e..e257486870 100644
--- a/server/lib/providerPresets.js
+++ b/server/lib/providerPresets.js
@@ -155,6 +155,7 @@ const bootstrapShape = (bootstrap, harness) => (bootstrap?.command ? {
args: Array.isArray(bootstrap.args) ? [...bootstrap.args] : [],
harnessId: bootstrap.harnessId ?? harness.recipe?.command ?? null,
argsSeparator: bootstrap.argsSeparator ?? '',
+ envCommand: bootstrap.envCommand ?? null,
} : null);
/**
@@ -184,6 +185,7 @@ export const bootstrapInputFor = (slug, app) => ({
command: app.command,
...(Array.isArray(app.args) ? { args: [...app.args] } : {}),
...(app.argsSeparator ? { argsSeparator: app.argsSeparator } : {}),
+ ...(app.envCommand ? { envCommand: [...app.envCommand] } : {}),
...(app.harnessNames ? { harnessNames: { ...app.harnessNames } } : {}),
});
diff --git a/server/lib/providerPresets.test.js b/server/lib/providerPresets.test.js
index 25d0298c9b..23d7e874fb 100644
--- a/server/lib/providerPresets.test.js
+++ b/server/lib/providerPresets.test.js
@@ -86,11 +86,11 @@ describe('materializeDerivedPreset', () => {
});
it('writes the bootstrap app as the inline object the spawner reads, and drops a stale inline one', () => {
- const app = { label: 'Corp', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } };
+ const app = { label: 'Corp', command: 'corp-auth', args: ['run'], argsSeparator: '--', envCommand: ['corp-auth', 'env'], harnessNames: { claude: 'claude-code' } };
const anthropic = resolveServiceInstance({ definitionId: 'anthropic', slug: 'anthropic', credentialVia: 'bootstrap' });
const record = claudePreset({ serviceId: 'anthropic', credentialBootstrapId: 'corp-auth', credentialBootstrap: { setupCommand: 'brew install corp', command: 'old' } });
const { record: derived } = materializeDerivedPreset({ record, harness: harnessById('claude'), instance: anthropic, bootstrap: bootstrapInputFor('corp-auth', app) });
- expect(derived.credentialBootstrap).toEqual({ setupCommand: 'brew install corp', command: 'corp-auth', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' });
+ expect(derived.credentialBootstrap).toEqual({ setupCommand: 'brew install corp', command: 'corp-auth', args: ['run'], harnessId: 'claude-code', argsSeparator: '--', envCommand: ['corp-auth', 'env'] });
const without = materializeDerivedPreset({ record: { ...record, credentialBootstrapId: undefined }, harness: harnessById('claude'), instance: { ...anthropic, credentialVia: 'stored', credentials: { apiKey: 'k' } } }).record;
expect(without).not.toHaveProperty('credentialBootstrap');
expect(without).not.toHaveProperty('credentialBootstrapId');
diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.js
index 387daedbce..ec4980ecef 100644
--- a/server/lib/providerRouteRecipes.js
+++ b/server/lib/providerRouteRecipes.js
@@ -501,6 +501,7 @@ export function materializeRouteOutcome({
// binary PortOS spawns — `resolveCliSpawn` reads it unchanged.
harnessId: bootstrap.harnessNames?.[harness.id] ?? recipe.command,
...(bootstrap.argsSeparator ? { argsSeparator: bootstrap.argsSeparator } : {}),
+ ...(bootstrap.envCommand ? { envCommand: [...bootstrap.envCommand] } : {}),
};
}
return { record, error: null };
diff --git a/server/lib/reviewerConfig.js b/server/lib/reviewerConfig.js
index fa32957d44..5f7d482443 100644
--- a/server/lib/reviewerConfig.js
+++ b/server/lib/reviewerConfig.js
@@ -55,7 +55,7 @@ export const isToolFreeReviewer = (value) => LOCAL_LLM_REVIEWERS.includes(value)
* service producing the codes read the SAME list, without the route pulling in
* the review service's closure to do it.
*/
-export const REVIEWER_CONFIG_FAULT_CODES = Object.freeze(['NO_MODEL', 'REVIEWER_UNAVAILABLE', 'REVIEWER_UNSUPPORTED']);
+export const REVIEWER_CONFIG_FAULT_CODES = Object.freeze(['NO_MODEL', 'REVIEWER_UNAVAILABLE', 'REVIEWER_UNSUPPORTED', 'REVIEWER_BOOTSTRAP_UNSUPPORTED']);
/**
* What an agent does with a review that could not return a verdict: say so in
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f948a57a66..dde51e8d25 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -567,6 +567,7 @@ export const providerSchema = z.object({
setupCommand: z.string().trim().max(500).optional(),
command: z.string().trim().min(1).max(200),
args: z.array(z.string().max(200)).max(20).optional(),
+ envCommand: z.array(z.string().min(1).max(500)).min(1).max(21).optional(),
harnessId: z.string().trim().min(1).max(100).optional(),
argsSeparator: z.string().trim().max(20).optional(),
}).strict().nullable().optional(),
@@ -2282,6 +2283,7 @@ export const credentialBootstrapSchema = z.object({
label: z.string().trim().min(1).max(100),
command: z.string().trim().min(1).max(200),
args: z.array(z.string().max(200)).max(20).optional(),
+ envCommand: z.array(z.string().min(1).max(500)).min(1).max(21).optional(),
argsSeparator: z.string().trim().max(20).optional(),
setupCommand: z.string().trim().max(500).optional(),
harnessNames: z.partialRecord(z.enum(PROVIDER_HARNESS_IDS), z.string().trim().min(1).max(100)).optional(),
diff --git a/server/lib/validation.providerRef.test.js b/server/lib/validation.providerRef.test.js
index cd6c55a257..f462b04c6d 100644
--- a/server/lib/validation.providerRef.test.js
+++ b/server/lib/validation.providerRef.test.js
@@ -8,6 +8,7 @@ import { describe, expect, it } from 'vitest';
import { presetProviderIdSchema, providerRefFieldSchema, providerRefSchema } from './zodCompat.js';
import {
appUpdateSchema,
+ providerSchema as hostProviderSchema,
credentialBootstrapsSettingsSchema,
featureProviderConfigSchema,
harnessSettingsSchema,
@@ -100,8 +101,18 @@ describe('the settings slices behind composition', () => {
expect(harnessSettingsSchema.safeParse({ pi: { enabled: true, extra: 1 } }).success).toBe(false);
});
+ it('preserves environment argv in both provider schemas and rejects malformed commands', () => {
+ const bootstrap = { command: 'token-cli', envCommand: ['token-cli', 'print-env', 'account with spaces'] };
+ for (const schema of [hostProviderSchema, providerSchema]) {
+ expect(schema.partial().parse({ credentialBootstrap: bootstrap }).credentialBootstrap).toEqual(bootstrap);
+ for (const envCommand of [[], '', [''], [5]]) {
+ expect(schema.partial().safeParse({ credentialBootstrap: { ...bootstrap, envCommand } }).success).toBe(false);
+ }
+ }
+ });
+
it('credentialBootstraps: slug-keyed apps with the inline bootstrap limits and a harness-keyed name map', () => {
- const app = { label: 'Corp auth', command: 'corp-auth', args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } };
+ const app = { label: 'Corp auth', command: 'corp-auth', envCommand: ['corp-auth', 'env'], args: ['run'], argsSeparator: '--', harnessNames: { claude: 'claude-code' } };
expect(credentialBootstrapsSettingsSchema.safeParse({ 'corp-auth': app }).success).toBe(true);
expect(credentialBootstrapsSettingsSchema.safeParse({ 'Corp Auth': app }).success).toBe(false);
expect(credentialBootstrapsSettingsSchema.safeParse({ 'corp-auth': { ...app, command: '' } }).success).toBe(false);
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 03238eb4ac..638e70d936 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -533,6 +533,11 @@ export async function resolveProviderReviewTransport(provider) {
error: 'This provider has no enforced tool-free review transport. Select its API mode or a supported reviewer harness.',
}
}
+ const { hasCredentialBootstrap } = await import('../lib/credentialBootstrap.js')
+ if (hasCredentialBootstrap(provider) && !provider.credentialBootstrap.envCommand?.length) {
+ return { transport: null, code: 'REVIEWER_BOOTSTRAP_UNSUPPORTED',
+ error: 'Configure a bootstrap environment command to use this provider for tool-free reviews.' }
+ }
return { transport: 'cli' }
}
@@ -578,9 +583,13 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
// No repository context or project-level CLI settings are exposed. The
// shared recipe and environment composer enforce the no-tool posture.
const cwd = await mkdtemp(join(tmpdir(), 'portos-review-'))
- result = await Promise.resolve().then(() => runCliProviderPrompt({ provider, model, prompt, cwd, timeoutMs,
- safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
- })).finally(() => rm(cwd, { recursive: true, force: true }))
+ result = await Promise.resolve().then(async () => {
+ const { resolveBootstrapEnv } = await import('../lib/credentialBootstrap.js')
+ const bootstrapEnv = await resolveBootstrapEnv(provider, { safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE })
+ return runCliProviderPrompt({ provider, model, prompt, cwd, timeoutMs, bootstrapEnv,
+ safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE })
+ }).catch(() => ({ error: 'Reviewer credential setup or execution failed.' }))
+ .finally(() => rm(cwd, { recursive: true, force: true }))
if (result.partial) return { ok: false, error: 'Reviewer exited before completing its response.' }
if (!result.error && result.streamFormat === 'stream-json') {
const { safeJSONLParse } = await import('../lib/jsonIo.js')
diff --git a/server/services/codeReview.providers.test.js b/server/services/codeReview.providers.test.js
index 8378232c53..f3f59da09e 100644
--- a/server/services/codeReview.providers.test.js
+++ b/server/services/codeReview.providers.test.js
@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { access } from 'node:fs/promises';
import { codeReviewSettingsSchema, sanitizeTaskMetadata } from '../lib/cosValidation.js';
import { resolveReviewerConfig, buildReviewWithArgs, isReviewerConfigFault } from '../lib/reviewerConfig.js';
-import { buildLocalReviewerInstructions } from './cosTaskPrompts.js';
vi.mock('./settings.js', () => ({ getSettings: vi.fn(), settingsEvents: { on: vi.fn() } }));
vi.mock('./providers.js', () => ({ getProviderById: vi.fn(), listProviders: vi.fn() }));
@@ -52,6 +51,7 @@ describe('configured provider reviewers', () => {
expect(task.reviewerModels).toEqual({ [backend]: 'pinned-coder', codex: 'example-cloud-model' });
expect(task.optionalReviewers).toEqual([backend]);
expect(task.reviewerMaxRounds).toEqual({ [backend]: 1 });
+ const { buildLocalReviewerInstructions } = await import('./cosTaskPrompts.js');
const instructions = buildLocalReviewerInstructions(task.reviewers, task.reviewerModels);
expect(instructions).toContain(backend);
expect(instructions).toContain('pinned-coder');
@@ -101,6 +101,32 @@ describe('configured provider reviewers', () => {
expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false });
});
+ it('requires a credential command for bootstrap reviewers and passes minted env to a completed review', async () => {
+ const cli = { ...provider, type: 'cli', command: 'claude', credentialBootstrap: { command: 'never-run-wrapper' } };
+ getProviderById.mockResolvedValue(cli);
+ listProviders.mockResolvedValue([cli]);
+ expect(await getProviderReviewUnsupported()).toEqual({ [backend]: 'REVIEWER_BOOTSTRAP_UNSUPPORTED' });
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: false, code: 'REVIEWER_BOOTSTRAP_UNSUPPORTED' });
+ expect(isReviewerConfigFault('REVIEWER_BOOTSTRAP_UNSUPPORTED')).toBe(true);
+ expect(runCliProviderPrompt).not.toHaveBeenCalled();
+
+ cli.credentialBootstrap.envCommand = [process.execPath, '-e', 'console.log("ANTHROPIC_AUTH_TOKEN=example-minted-token")'];
+ expect(await getProviderReviewUnsupported()).toEqual({});
+ runCliProviderPrompt.mockResolvedValue({ text: 'NO FINDINGS', partial: false });
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: true, findings: 'NO FINDINGS' });
+ expect(runCliProviderPrompt).toHaveBeenCalledWith(expect.objectContaining({
+ bootstrapEnv: { ANTHROPIC_AUTH_TOKEN: 'example-minted-token' },
+ safetyProfile: 'public-review-gate',
+ }));
+
+ cli.credentialBootstrap.envCommand = [process.execPath, '-e', 'console.error("example-secret"); process.exit(1)'];
+ runCliProviderPrompt.mockClear();
+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({
+ ok: false, error: 'Reviewer credential setup or execution failed.',
+ });
+ expect(runCliProviderPrompt).not.toHaveBeenCalled();
+ });
+
it('refuses an unsupported effort before invoking the provider', async () => {
getProviderById.mockResolvedValue({ ...provider, type: 'tui', command: 'codex', defaultModel: 'gpt-6-astra' });
expect(await runLocalCodeReview({ backend, effort: 'minimal', diff: 'example diff' })).toMatchObject({ ok: false, error: expect.stringContaining('reasoning effort') });