Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: credential a tool-free code review through the provider's bootstrap wrap
[._.]/ Adam Eivy3fad8c0eed02
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsxindex 61767e783d..521f74d3fd 100644--- a/client/src/components/cos/ReviewerPicker.jsx+++ b/client/src/components/cos/ReviewerPicker.jsx@@ -273,9 +273,7 @@ export default function ReviewerPicker({if (providerReviewUnsupported?.[token]) {return {label: "can't review",- 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.`+ 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.`};}return null;diff --git a/client/src/components/providers/ProviderCredentialBootstraps.jsx b/client/src/components/providers/ProviderCredentialBootstraps.jsxindex 9b084b1ee8..f529ce849e 100644--- a/client/src/components/providers/ProviderCredentialBootstraps.jsx+++ b/client/src/components/providers/ProviderCredentialBootstraps.jsx@@ -83,7 +83,7 @@ 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>+ <FormField label="Review credential command" hint="Optional, tool-free reviews only — for an app that PRINTS credentials instead of running the harness; leave it empty and the wrap above credentials the review. 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>diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsxindex a8126cfe2f..184376598c 100644--- a/client/src/components/providers/ProviderForm.jsx+++ b/client/src/components/providers/ProviderForm.jsx@@ -737,7 +737,9 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose/></FormField><p className="text-xs text-gray-500">- Used for tool-free reviews only; the wrap form is never used there.+ Optional, and only for tool-free reviews. Leave it empty unless this app+ PRINTS credentials instead of running the harness itself — a review already+ runs through the wrap above, so an ordinary bootstrap app needs nothing here.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.diff --git a/server/lib/README.md b/server/lib/README.mdindex 33d28dc7f3..2bafbd766b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -276,10 +276,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. || `agentApiToken.js` | `AGENT_API_TOKEN_ENV` (`PORTOS_API_TOKEN`) + `AGENT_API_AUTH_CURL_ARG` — the name of the loopback session token PortOS injects into a spawned agent's environment (`services/agentApiAuth.js`) and the quoted `curl` argument that spends it, so the prompt builders writing agent-facing `curl` snippets and the spawn sites injecting the variable cannot drift. `agentApiCurl({ apiBase, path, payload })` and `agentApiAuthNote({ alsoCovering })` assemble the whole call and the paragraph that must travel with it — one shape for every agent-facing API call in the tree, after two hand-written copies had already drifted on whether the install "gates" or "may gate" `/api/*` (it is opt-in and off by default). Pure, zero-import. || `localReviewBridge.js` | `LOCAL_REVIEW_BRIDGE_SCRIPT` — absolute path of `server/scripts/run-local-code-review.mjs`, the stdin bridge into the local-review service (same reviewers and `timeoutMs` forwarding as `POST /api/code-review/local`, no HTTP and so no instance-password gate). Shared by the two prompt builders that hand it to agents, so renaming the script cannot break one while the other keeps working. |-| `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. |+| `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. `isPublicReviewRestrictedProfile` covers both postures; `isPublicReviewNoToolProfile` / `isPublicReviewActionsProfile` separate them for the callers whose rule differs by posture (credential-bootstrap wrapping, child-env allowlist). || `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` | 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. |+| `credentialBootstrap.js` | resolveBootstrapEnv(provider, { safetyProfile }) runs an optional `envCommand` argv only for a no-tool review, parses KEY=value output without evaluation, and caches credentials in memory for one minute — the alternative for a bootstrap that PRINTS credentials rather than exec'ing the harness; a record that only names the wrap form is credentialed by the wrap and gets `{}`. 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. The `sandboxed-actions` posture is never wrapped — it executes contributor-supplied code inside a sandbox spelled entirely in the recipe's argv, so nothing may sit in front of the harness and rewrite it; the `no-tool` postures (the tool-free reviewer among them) ARE wrapped, because spawned bare they carry no credential at all (#7720). The split 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/agentExecutionProfiles.js b/server/lib/agentExecutionProfiles.jsindex e09ff6408b..ca9c3a58e0 100644--- a/server/lib/agentExecutionProfiles.js+++ b/server/lib/agentExecutionProfiles.js@@ -58,3 +58,13 @@ export function isPublicReviewNoToolProfile(profile) {export function isPublicReviewRestrictedProfile(profile) {return publicReviewPostureForProfile(profile) !== null;}++/**+ * True only for the posture that may EXECUTE contributor-supplied code — the+ * actions stage. A caller whose rule differs between the two postures keys on+ * this rather than on `isPublicReviewRestrictedProfile`; see+ * `applyCredentialBootstrap`.+ */+export function isPublicReviewActionsProfile(profile) {+ return publicReviewPostureForProfile(profile) === PUBLIC_REVIEW_ACTIONS_POSTURE;+}diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex 5f0fc36413..7ce21c05bc 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -164,13 +164,15 @@ export function runCliProviderPrompt(args = {}) {// `resolveCliSpawn` also applies a credential-bootstrap wrap// (credentialBootstrap.js) when configured — applied AFTER// prepareCliPrompt (above), which still keys prompt-delivery convention- // off the harness's own command, not the bootstrap CLI's — and never under- // a public-review `safetyProfile`, whose enforced recipe is the sandbox.+ // off the harness's own command, not the bootstrap CLI's. This is the+ // tool-free reviewer's spawn too, and it IS wrapped: a reviewer spawned+ // bare carries no credential at all (#7720). Only the `sandboxed-actions`+ // `safetyProfile` skips the wrap — see credentialBootstrap.js.const { command: spawnCommand, args: wrappedArgs, wrapped } = resolveCliSpawn(provider, provider.command, spawnArgs, childEnv, { safetyProfile });// A bootstrap-wrapped child is a supervising WRAPPER, not the harness, so// the timeout kill below has to signal the whole process group or it leaves// the harness running past the run (#7496). False for every unwrapped- // spawn — including a public-review posture, which is never wrapped.+ // spawn — including the `sandboxed-actions` posture, which is never wrapped.const processGroup = needsProcessGroup(wrapped);const child = spawn(spawnCommand, wrappedArgs, {cwd: effectiveCwd,diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.jsindex dd583e7a74..e113d88b09 100644--- a/server/lib/cliProviderRun.test.js+++ b/server/lib/cliProviderRun.test.js@@ -15,6 +15,28 @@ const { resolveBootstrapEnv } = await import('./credentialBootstrap.js');const cli = (id, extra = {}) => ({ id, type: 'cli', command: id, enabled: true, models: [], ...extra });+// A harness that reports what it actually received, and a stand-in for a real+// minting wrapper: it execs \`<harness> <args...>\` with a credential in the+// child's environment, exactly as \`<bootstrap> run <harness> -- <args>\` does at+// a shell.+async function writeBootstrapFixture(dir) {+ const { writeFile } = await import('node:fs/promises');+ const { join } = await import('node:path');+ 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), auth: process.env.ANTHROPIC_AUTH_TOKEN || null, wrapperToken: process.env.EXAMPLE_WRAPPER_TOKEN || null })));', { mode: 0o755 });+ const bootstrap = join(dir, 'token-cli');+ await writeFile(bootstrap, [+ '#!/usr/bin/env node',+ 'const { spawn } = require("child_process");',+ 'const [, , mode, harness, ...rest] = process.argv;',+ 'if (mode !== "run") { process.exit(64); }',+ 'const args = rest[0] === "--" ? rest.slice(1) : rest;',+ 'const child = spawn(harness, args, { stdio: "inherit", env: { ...process.env, EXAMPLE_WRAPPER_TOKEN: "example-wrapper-token" } });',+ 'child.on("exit", (code) => process.exit(code ?? 1));',+ ].join('\n'), { mode: 0o755 });+ return { command, bootstrap };+}+describe('pickCliProvider', () => {const providers = {'claude-code': cli('claude-code', { defaultModel: 'claude-opus-4-7', models: ['claude-opus-4-7', 'claude-haiku-4-5'] }),@@ -127,24 +149,51 @@ describe('runCliProviderPrompt', () => {expect(child.forgeToken).toBeNull();});- it.skipIf(process.platform === 'win32')('runs the enforced no-tool recipe on the harness itself, never through a configured credential bootstrap', async () => {- const { mkdtemp, writeFile, rm } = await import('node:fs/promises');+ // #7720: the tool-free reviewer spawn IS credential-bootstrap-wrapped, and+ // both halves of that have to hold at once — the harness must receive the+ // enforced recipe unchanged THROUGH the wrapper, and it must receive the+ // credential the wrapper mints, which a bare spawn could never give it.+ // Spawned bare, a bootstrap-only record answers "no matching provider is+ // authenticated" and the review gate waits out a round that never completes.+ it.skipIf(process.platform === 'win32')('runs the enforced no-tool recipe THROUGH the credential bootstrap, so the reviewer starts authenticated', async () => {+ const { mkdtemp, rm } = await import('node:fs/promises');const { tmpdir } = await import('node:os');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), 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 { command, bootstrap } = await writeBootstrapFixture(dir);+ const provider = { ...cli('example-claude'), command,+ credentialBootstrap: { command: bootstrap, args: ['run'], argsSeparator: '--' } };+ const result = await runCliProviderPrompt({+ provider, model: 'pinned-model', prompt: 'untrusted diff', cwd: dir, safetyProfile: 'public-review-gate',+ }).finally(() => rm(dir, { recursive: true, force: true }));+ expect(result.error).toBeUndefined();+ const child = JSON.parse(result.text);+ expect(child.args).toEqual(expect.arrayContaining(['--restricted', '--tools', '', '--model', 'pinned-model']));+ // The wrapper is an intermediary, not a way around the recipe.+ expect(child.args).not.toContain('--dangerously-skip-permissions');+ expect(child.wrapperToken).toBe('example-wrapper-token');+ });++ // The other credential shape: a bootstrap that PRINTS assignments rather than+ // exec'ing the harness. `resolveBootstrapEnv` materializes them separately —+ // the command never sees the prompt or the enforced argv — and only recognized+ // auth keys survive `buildCliChildEnv`.+ it.skipIf(process.platform === 'win32')('also delivers credentials a bootstrap prints rather than execs', async () => {+ const { mkdtemp, rm } = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const dir = await mkdtemp(join(tmpdir(), 'review-cli-bootstrap-env-'));+ const { command, bootstrap } = await writeBootstrapFixture(dir);+ const provider = { ...cli('example-claude'), command, credentialBootstrap: { command: bootstrap, args: ['run'], argsSeparator: '--',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, 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');+ const child = JSON.parse(result.text);+ expect(child.args).toEqual(expect.arrayContaining(['--restricted', '--tools', '']));+ expect(child.auth).toBe('example-token');});it('rejects a missing command without spawning', async () => {diff --git a/server/lib/credentialBootstrap.js b/server/lib/credentialBootstrap.jsindex 5f8e96cba9..218b5809a5 100644--- a/server/lib/credentialBootstrap.js+++ b/server/lib/credentialBootstrap.js@@ -34,12 +34,31 @@* through the leaf below), and the readiness probes (`providerPrerequisites.js`,* the toolkit's `testProvider`).*- * A public-review posture (`isPublicReviewRestrictedProfile`) is NEVER- * wrapped, at any site: the vendor's enforced no-tool/sandboxed recipe IS the- * sandbox, and its argv and env allowlists are both defeated by handing the- * recipe to a user-configured binary that mints and re-injects a credential.- * The skip lives here rather than at each call site so a new spawn site can't- * forget it.+ * The `sandboxed-actions` posture (`isPublicReviewActionsProfile`) is NEVER+ * wrapped, at any site. That stage EXECUTES contributor-supplied code inside+ * the vendor's own maintained sandbox, and the sandbox is spelled entirely in+ * the recipe's argv — so an intermediary free to rewrite that argv before the+ * harness ever sees it is the one place the wrap could turn a screened patch+ * loose on the machine. It fails closed.+ *+ * The `no-tool` postures ARE wrapped, and must be (#7720). A reasoning-only+ * stage spawned bare runs with NO credential: it falls through to whatever+ * ambient vendor auth the machine happens to have — none, for a bootstrap-only+ * record — and the harness answers "no matching provider is authenticated",+ * which a review gate reads as a transient outage and waits out forever (the+ * stall #7660 exists to prevent). The wrap is also how a credential reaches+ * that stage at all: the bootstrap mints it into the environment of the child+ * IT spawns, downstream of the allowlist `buildCliChildEnv` already applied, so+ * PortOS's env boundary is untouched. Nothing about that posture is+ * argv-enforced in a way a credential minter threatens — its threat model is+ * "the model must not reach tools" — and the bootstrap binary is the operator's+ * own configuration, exactly as `provider.command` (which the posture already+ * spawns) is. `resolveBootstrapEnv` below stays available for a bootstrap that+ * PRINTS credentials rather than exec'ing the harness; it is an alternative to+ * the wrap for those records, not a precondition for a review.+ *+ * Both halves of that split live here rather than at each call site so a new+ * spawn site can't forget either one.** Wrapping also changes TEARDOWN, so every site that spawns a long-lived child* here owes a second thing: the direct child is then the WRAPPER, and nothing@@ -50,7 +69,7 @@** The argv SHAPE is composed one layer down, by the dependency-free* `aiToolkit/internal/credentialBootstrap.js` leaf (which documents why it sits- * there); this module adds the public-review skip, the Windows resolution, and+ * there); this module adds the posture split above, the Windows resolution, and* the teardown half above.** Imports only `bufferedSpawn.js`, `agentExecutionProfiles.js` (both of which@@ -64,7 +83,7 @@ import { IS_WIN32, resolveWindowsExecutable, prepareWindowsSafeSpawn, prepareCliimport { execFile } from './childProcess.js';import { tmpdir } from 'node:os';import { withSpawnCwdEnv } from './spawnCwd.js';-import { isPublicReviewNoToolProfile, isPublicReviewRestrictedProfile } from './agentExecutionProfiles.js';+import { isPublicReviewNoToolProfile, isPublicReviewActionsProfile } from './agentExecutionProfiles.js';import { composeBootstrapSpawn, hasCredentialBootstrap } from './aiToolkit/internal/credentialBootstrap.js';export { hasCredentialBootstrap };@@ -75,9 +94,14 @@ 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.+ * Materialize credentials independently of a review, for a bootstrap that+ * PRINTS `KEY=value` assignments rather than exec'ing the harness itself. 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.+ *+ * Optional: a record that only names the ordinary wrap form is credentialed by+ * the wrap (see module doc), and returns `{}` here. Nothing about a review+ * requires an `envCommand`.*/export async function resolveBootstrapEnv(provider, { safetyProfile = null } = {}) {const argv = provider?.credentialBootstrap?.envCommand;@@ -127,14 +151,16 @@ export async function resolveBootstrapEnv(provider, { safetyProfile = null } = {* command this returns.** The shape it composes — and why `harnessId` and `argsSeparator` exist — is- * documented on `composeBootstrapSpawn`. What this adds is the safety skip: a- * public-review posture is returned UNWRAPPED.+ * documented on `composeBootstrapSpawn`. What this adds is the safety skip: the+ * `sandboxed-actions` posture, and only it, is returned UNWRAPPED (see module+ * doc). A `no-tool` posture wraps like any other spawn, because a+ * reasoning-only stage spawned bare has no credential at all.** @param {{credentialBootstrap?: {command: string, args?: string[], harnessId?: string, argsSeparator?: string}}|null|undefined} provider* @param {string} command - the harness binary PortOS would otherwise spawn* @param {string[]} [args] - the harness's own argv* `wrapped` reports whether the wrap actually applied — including the- * public-review skip, so a posture that is deliberately NOT wrapped also keeps+ * actions-posture skip, so a posture that is deliberately NOT wrapped also keeps* the unwrapped teardown. It matters for process teardown, not argv: once a* bootstrap CLI sits in front of the harness, the direct child PortOS holds is* the WRAPPER, and `<bootstrap> run <harness> -- <args>` is the shape of a@@ -142,14 +168,14 @@ export async function resolveBootstrapEnv(provider, { safetyProfile = null } = {* harness running. See `needsProcessGroup` (#7496).** @param {{safetyProfile?: string|null}} [options] - the run's execution- * profile; a public-review posture is returned unwrapped (see module doc)+ * profile; the `sandboxed-actions` posture is returned unwrapped (see module doc)* @returns {{command: string, args: string[], wrapped: boolean}}*/export function applyCredentialBootstrap(provider, command, args, { safetyProfile = null } = {}) {- // A restricted posture composes against NO provider rather than short-circuiting,+ // The skipped posture composes against NO provider rather than short-circuiting,// so argv normalization — and the `wrapped` flag teardown keys on — is stated// in exactly one place.- return composeBootstrapSpawn(isPublicReviewRestrictedProfile(safetyProfile) ? null : provider, command, args);+ return composeBootstrapSpawn(isPublicReviewActionsProfile(safetyProfile) ? null : provider, command, args);}/**@@ -170,9 +196,9 @@ export function applyCredentialBootstrap(provider, command, args, { safetyProfil* tree-wide rather than group-based, so the hole does not exist there.* - `detached: true` on Windows opens a new console window per spawn.*- * False for an unwrapped spawn — including a public-review posture, which is- * never wrapped — so nothing changes for those: the harness is the direct child- * there and today's per-pid signal is exact.+ * False for an unwrapped spawn — including the `sandboxed-actions` posture,+ * which is never wrapped — so nothing changes for those: the harness is the+ * direct child there and today's per-pid signal is exact.** @param {boolean} wrapped - the `wrapped` flag from applyCredentialBootstrap/resolveCliSpawn* @param {boolean} [isWin32] - injectable for tests; defaults to the real platformdiff --git a/server/lib/credentialBootstrap.test.js b/server/lib/credentialBootstrap.test.jsindex 8b313c2e48..a99d276034 100644--- a/server/lib/credentialBootstrap.test.js+++ b/server/lib/credentialBootstrap.test.js@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';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';+import { PUBLIC_REVIEW_EXECUTION_PROFILE, PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from './agentExecutionProfiles.js';+import { PRIVATE_SECURITY_EXECUTION_PROFILE } from './privateSecurityPolicy.js';vi.mock('./bufferedSpawn.js', async (importOriginal) => ({...(await importOriginal()),@@ -88,31 +89,53 @@ describe('credentialBootstrap', () => {});});- // A public-review posture's enforced recipe IS the sandbox: handing it to a- // user-configured binary defeats both its argv and env allowlists. The skip is- // keyed on the profile here, at the one point every spawn site goes through.+ // The two public-review postures split here, and the split is the security+ // boundary: the actions stage EXECUTES contributor-supplied code inside a+ // sandbox spelled entirely in the recipe's argv, so nothing may sit in front+ // of the harness and rewrite it; the no-tool stages reason only, and spawned+ // bare they carry no credential at all (#7660, #7720).describe('public-review postures', () => {const provider = { credentialBootstrap: { command: 'token-cli', args: ['run'] } };- it.each([PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE])(- 'never wraps a %s spawn, even with a bootstrap configured', (safetyProfile) => {- // `wrapped: false` matters as much as the argv here: an unwrapped- // posture must also keep the unwrapped TEARDOWN, so the enforced recipe- // is never spawned detached into a process group of its own (#7496).+ it('never wraps a sandboxed-actions spawn, even with a bootstrap configured', () => {+ const safetyProfile = PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;+ // `wrapped: false` matters as much as the argv here: an unwrapped+ // posture must also keep the unwrapped TEARDOWN, so the enforced recipe+ // is never spawned detached into a process group of its own (#7496).+ expect(applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile })).toEqual({+ command: 'claude',+ args: ['--restricted'],+ wrapped: false,+ });+ expect(resolveCliSpawn(provider, 'claude', ['--restricted'], process.env, { safetyProfile })).toEqual({+ command: 'claude',+ args: ['--restricted'],+ wrapped: false,+ });+ expect(needsProcessGroup(+ applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile }).wrapped,+ false,+ )).toBe(false);+ });++ // A tool-free reviewer spawned bare falls through to ambient vendor auth —+ // none, for a bootstrap-only record — and the harness answers "no matching+ // provider is authenticated", which the review gate waits out as an outage.+ // The wrap is what gives it a credential, and the enforced recipe rides+ // through the wrapper to the harness unchanged.+ it.each([PUBLIC_REVIEW_EXECUTION_PROFILE, PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PRIVATE_SECURITY_EXECUTION_PROFILE])(+ 'wraps a %s spawn so the reviewer starts authenticated', (safetyProfile) => {expect(applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile })).toEqual({- command: 'claude',- args: ['--restricted'],- wrapped: false,- });- expect(resolveCliSpawn(provider, 'claude', ['--restricted'], process.env, { safetyProfile })).toEqual({- command: 'claude',- args: ['--restricted'],- wrapped: false,+ command: 'token-cli',+ args: ['run', 'claude', '--restricted'],+ wrapped: true,});+ // The wrapper is now the direct child, so the run's timeout/cancel has+ // to reach the harness behind it (#7496).expect(needsProcessGroup(applyCredentialBootstrap(provider, 'claude', ['--restricted'], { safetyProfile }).wrapped,false,- )).toBe(false);+ )).toBe(true);});it('still wraps an ordinary (profile-less or unknown-profile) spawn', () => {diff --git a/server/lib/reviewerConfig.js b/server/lib/reviewerConfig.jsindex 5f7d482443..fa32957d44 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', 'REVIEWER_BOOTSTRAP_UNSUPPORTED']);+export const REVIEWER_CONFIG_FAULT_CODES = Object.freeze(['NO_MODEL', 'REVIEWER_UNAVAILABLE', 'REVIEWER_UNSUPPORTED']);/*** What an agent does with a review that could not return a verdict: say so indiff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex b5c1dc82b3..b5268002e6 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -319,11 +319,12 @@ export function buildTuiSpawnConfig(provider, model, {safetyProfile,tui: true,});- // Public-review postures never get credential-bootstrap-wrapped — the- // enforced recipe above IS the sandbox. `applyCredentialBootstrap` owns- // that skip (keyed on `safetyProfile`), so `spawnCommand`/`spawnArgs` come- // back identical to `command`/`args` and every branch of this function- // returns the same shape.+ // A `sandboxed-actions` posture never gets credential-bootstrap-wrapped —+ // the enforced recipe above IS the sandbox there, and it is spelled entirely+ // in argv. A `no-tool` posture IS wrapped, because spawned bare it would+ // carry no credential at all (#7720). `applyCredentialBootstrap` owns that+ // split (keyed on `safetyProfile`); either way this branch returns the same+ // shape as every other, with `command`/`args` still naming the harness.const { command: spawnCommand, args: spawnArgs } = applyCredentialBootstrap(provider, recipe.command, recipe.args, { safetyProfile });return {command: recipe.command,diff --git a/server/services/codeReview.js b/server/services/codeReview.jsindex 638e70d936..70af30013f 100644--- a/server/services/codeReview.js+++ b/server/services/codeReview.js@@ -533,11 +533,12 @@ 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.' }- }+ // A credential-bootstrap record needs no branch of its own. The spawn below+ // runs under a `no-tool` profile, which `applyCredentialBootstrap` wraps like+ // any other, so the bootstrap CLI mints the credential into the harness it+ // execs and the reviewer starts authenticated (#7720). A record that instead+ // PRINTS its credentials supplies them through `resolveBootstrapEnv`; neither+ // form is a reason to refuse the reviewer at selection time.return { transport: 'cli' }}diff --git a/server/services/codeReview.providers.test.js b/server/services/codeReview.providers.test.jsindex f3f59da09e..2d09805fd8 100644--- a/server/services/codeReview.providers.test.js+++ b/server/services/codeReview.providers.test.js@@ -101,24 +101,36 @@ 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' } };+ // #7720: a bootstrap-credentialed harness has a maintained no-tool recipe and+ // must be usable as a reviewer, not refused at selection time. The record+ // reaches the CLI spawn with its `credentialBootstrap` intact — that is what+ // `applyCredentialBootstrap` wraps under the gate's no-tool profile, so the+ // bootstrap mints the credential into the harness it execs. A record that+ // instead PRINTS assignments supplies them through `bootstrapEnv`, which the+ // wrap does not replace.+ it('runs a bootstrap reviewer on the wrap alone, and passes minted env when the record prints one', async () => {+ const cli = { ...provider, type: 'cli', command: 'claude', credentialBootstrap: { command: 'example-wrapper', args: ['run'] } };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();+ runCliProviderPrompt.mockResolvedValue({ text: 'NO FINDINGS', partial: false });+ expect(await getProviderReviewUnsupported()).toEqual({});+ expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({ ok: true, findings: 'NO FINDINGS' });+ expect(runCliProviderPrompt).toHaveBeenCalledWith(expect.objectContaining({+ provider: expect.objectContaining({ credentialBootstrap: cli.credentialBootstrap }),+ bootstrapEnv: {},+ safetyProfile: 'public-review-gate',+ }));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',}));+ // A credential command that FAILS is still a failed review, not a silent+ // spawn with no credential.cli.credentialBootstrap.envCommand = [process.execPath, '-e', 'console.error("example-secret"); process.exit(1)'];runCliProviderPrompt.mockClear();expect(await runLocalCodeReview({ backend, diff: 'example diff' })).toMatchObject({diff --git a/server/services/compositeProviders.test.js b/server/services/compositeProviders.test.jsindex 83ea944675..c4c76ccf57 100644--- a/server/services/compositeProviders.test.js+++ b/server/services/compositeProviders.test.js@@ -53,7 +53,7 @@ const { buildTuiInvocation } = await import('../lib/tuiHandshake.js');const { buildTuiShellLaunch } = await import('../lib/tuiShellLaunch.js');const { buildCliChildEnv } = await import('../lib/cliChildEnv.js');const { applyCredentialBootstrap, needsProcessGroup, resolveCliSpawn } = await import('../lib/credentialBootstrap.js');-const { PUBLIC_REVIEW_EXECUTION_PROFILES } = await import('../lib/agentExecutionProfiles.js');+const { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE, PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } = await import('../lib/agentExecutionProfiles.js');const { createRunnerService } = await import('../lib/aiToolkit/runner.js');const { createProviderStatusService } = await import('../lib/aiToolkit/providerStatus.js');const { allowedModesFor } = await import('../lib/callerModePolicy.js');@@ -189,7 +189,7 @@ describe('materializeComposite — the run paths', () => {expect(buildCliArgs(provider)).toEqual(expect.arrayContaining(['--oss', '--local-provider', 'lmstudio']));});- it('claude.cli@anthropic+corp-auth: the bootstrap app wraps the spawn, and a public-review posture spawns claude unwrapped', () => {+ it('claude.cli@anthropic+corp-auth: the bootstrap app wraps the spawn, including a tool-free review but never the actions stage', () => {const provider = record('claude.cli@anthropic+corp-auth');expect(provider.credentialBootstrap).toEqual({ command: 'corp-auth', args: ['run'], harnessId: 'claude-code', argsSeparator: '--' });const args = buildCliArgs(provider);@@ -202,8 +202,16 @@ describe('materializeComposite — the run paths', () => {expect(needsProcessGroup(spawn.wrapped, false)).toBe(true);expect(needsProcessGroup(spawn.wrapped, true)).toBe(false);- const restricted = applyCredentialBootstrap(provider, provider.command, args, { safetyProfile: PUBLIC_REVIEW_EXECUTION_PROFILES[0] });- expect(restricted).toEqual({ command: 'claude', args, wrapped: false });+ // A tool-free reviewer still gets the wrap — spawned bare it would have no+ // credential at all and the review gate would wait out a round that can+ // never answer (#7720). The enforced recipe rides through unchanged.+ const reviewer = applyCredentialBootstrap(provider, provider.command, args, { safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE });+ expect(reviewer).toEqual({ command: 'corp-auth', args: ['run', 'claude-code', '--', ...args], wrapped: true });+ // The actions stage is the one posture that fails closed: it EXECUTES the+ // screened patch inside a sandbox spelled entirely in that argv, so nothing+ // may sit in front of the harness and rewrite it.+ const actions = applyCredentialBootstrap(provider, provider.command, args, { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE });+ expect(actions).toEqual({ command: 'claude', args, wrapped: false });});it('carries the harness by name into the effort ladder, so a bootstrap-wrapped spawn still offers its rungs', async () => {