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

give spawned agents a loopback API token so their own curl snippets stop 401ing

[._.]/ Adam Eivy552a75a7da5e
diff --git a/AGENTS.md b/AGENTS.md
index 51c48567d9..c535fc8a22 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -35,7 +35,7 @@ npm run test:db # DB-backed suites → portos_test ONLY (see Se
**Authentication and HTTPS exist, but are OPT-IN and OFF by default.** Do not assume they are absent:
-- **Auth** — an optional instance password (`server/services/auth.js`, enforced by `server/services/authGate.js`) gates all of `/api/*` and `/data/*` when set, with a small always-public set (`/api/auth/status`, `/api/system/health`). Peers reach a password-gated instance via a per-peer Basic credential on the peer record, attached to every outbound hop by `peerFetch` (`server/lib/peerHttpClient.js`).
+- **Auth** — an optional instance password (`server/services/auth.js`, enforced by `server/services/authGate.js`) gates all of `/api/*` and `/data/*` when set, with a small always-public set (`/api/auth/status`, `/api/system/health`). Peers reach a password-gated instance via a per-peer Basic credential on the peer record, attached to every outbound hop by `peerFetch` (`server/lib/peerHttpClient.js`). **A PortOS-spawned agent authenticates with `PORTOS_API_TOKEN`** — a loopback session token the server mints and injects into the agent's environment (`server/services/agentApiAuth.js`). Any `curl` you write against this install's own API carries `-H "Authorization: Bearer ${PORTOS_API_TOKEN:-}"`; a bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is down. The variable is empty when no password is set (the gate ignores it) and is never given to a public-content review stage.
- **HTTPS** — provisioned by `npm run setup:cert`; `:5555` flips to TLS with a loopback-only HTTP mirror on `:5553`. Peer hops set `rejectUnauthorized: false` ("Tailnet is the trust boundary"): between two tailnet nodes WireGuard supplies mutual auth, but a non-tailnet peer (plain LAN IP / non-`.ts.net` host, see `peerRequiresTailscale()`) gets no server authentication.
Because both are off by default, **never treat "the password is set" as an available guarantee** — gate on it explicitly, or design for the default posture. **PII must not ride the federation layer at all** — ADR [privacy records machine-local](docs/decisions/2026-08-08-privacy-records-machine-local.md). That governs *records* and *status/capability payloads*. The only carve-outs are a submitted job body carrying the conditioning an allowlisted peer is asked to render — the prompt (ADR [federated visual prompts](docs/decisions/2026-08-20-federated-visual-prompts.md)) and, under the same gate, lyrics and conditioning images (ADR [conditioning crosses to an allowlisted peer](docs/decisions/2026-08-22-federated-media-input-assets.md), which also records what stays refused: model weights and multi-step chain state) — explicit Eidoverse guest conversations, where submitted world-chat messages and live replies may cross an enabled registered peer under guest admission and the independent default-off Mind travel grant (ADR [Eidoverse guest chat](docs/decisions/2026-09-05-eidoverse-guest-chat.md)) — and an explicitly promoted Eidoverse foundation's promote envelope, which a registered outbound-enabled peer may pull, style-free and re-verified on both ends (ADR [federated Eidoverse foundations](docs/decisions/2026-09-18-federated-eidoverse-foundations.md)). No private records, secrets, automatic conversation-history exports, or record-bearing status payloads are authorized by those exceptions.
diff --git a/docs/features/agent-context.md b/docs/features/agent-context.md
index d50ee6e748..f3e07303de 100644
--- a/docs/features/agent-context.md
+++ b/docs/features/agent-context.md
@@ -20,6 +20,8 @@ The route checks the TCP socket address, not forwarding headers, and accepts onl
The normal PortOS authentication gate runs before this route. If an instance password is enabled, the MCP client must also send a valid PortOS session, Bearer token, or Basic credential.
+A CoS agent spawned by PortOS already holds one: the server mints a loopback session token and injects it as `PORTOS_API_TOKEN` (`server/services/agentApiAuth.js`), so an agent authenticates with `-H "Authorization: Bearer ${PORTOS_API_TOKEN:-}"` on any PortOS API call. The variable is empty when no instance password is set, and it is never given to a public-content review stage.
+
This first transport is intentionally stateless: it emits no MCP session identifier, accepts JSON responses to POST, and returns `405` for GET/DELETE on the MCP endpoint. It implements protocol version `2025-11-25` and recognizes the compatible `2025-03-26` and `2025-06-18` request headers.
## Disclosure profiles and scopes
diff --git a/server/lib/README.md b/server/lib/README.md
index 5ddfe7e502..9050584ea8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -270,6 +270,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `openAiChatStream.js` | `iterateOpenAiChat(...)` → normalized async content/reasoning chunks and `streamOpenAiChat(...)` → the streamed text — one streaming `POST {base}/chat/completions` against any OpenAI-compatible endpoint; both own timeout/abort composition, retries, parsing, backpressure, and reader cleanup. `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by Ask (`services/askService.js`), `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record), and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
| `callerModePolicy.js` | The one caller EXECUTION-MODE policy: `CALLER_MODE_POLICIES` (`agent-harness`, `cli-harness`, `direct-api`, `any-text`) plus `resolveCallerModePolicy` / `allowedModesFor` / `callerModeRejection` / `isCallerModeEligible` / `filterCallerModeEligible`. Answers "may THIS caller run on THAT route mode?" for an explicit pin, `activeProvider` inheritance and every fallback candidate alike — `allowedModesFor()` is what rides on `requestCapabilities.allowedModes` into the toolkit's `getFallbackProvider`. Pure and dependency-light so the out-of-process autofixer can import it; `enabled`/benched state, prerequisites and text-transport consent stay with their existing owners. Unknown never becomes true: a record with no executable mode, and a required model capability with no positive evidence, are both refused. |
| `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. Pure. |
+| `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. |
| `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. |
diff --git a/server/lib/agentApiToken.js b/server/lib/agentApiToken.js
new file mode 100644
index 0000000000..5c495bd496
--- /dev/null
+++ b/server/lib/agentApiToken.js
@@ -0,0 +1,23 @@
+/**
+ * The name of the loopback API credential PortOS hands its own agents, and the
+ * `curl` argument that spends it — one source of truth for the two halves,
+ * which live far apart: the spawn sites that inject the variable
+ * (`services/agentApiAuth.js` and the three env-composition sites) and the
+ * prompt builders that write the `curl` snippets an agent copy-pastes.
+ *
+ * Pure and dependency-free so a prompt section can name the credential without
+ * pulling the auth/settings subtree into its import closure.
+ */
+
+export const AGENT_API_TOKEN_ENV = 'PORTOS_API_TOKEN';
+
+/**
+ * Attached to every agent-facing `curl` against this install's own API.
+ *
+ * Emitted unconditionally: a prompt is built without asking whether the
+ * instance password is set, an install with auth OFF ignores the empty bearer
+ * the `:-` default produces, and an install with auth ON needs the header on
+ * every call or the request is a bare `401 AUTH_REQUIRED`. The whole value is
+ * one quoted argument, so a token is never word-split.
+ */
+export const AGENT_API_AUTH_CURL_ARG = `-H "Authorization: Bearer \${${AGENT_API_TOKEN_ENV}:-}"`;
diff --git a/server/lib/index.js b/server/lib/index.js
index f317dc83c9..e1350ccc29 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -168,6 +168,8 @@ export * as childProcess from './childProcess.js';
export * from './callerModePolicy.js';
export * from './cliChildEnv.js';
export * from './agentExecutionProfiles.js';
+export * from './agentApiToken.js';
+export * from './localReviewBridge.js';
export * from './agentCompletionMode.js';
export * from './localEndpoint.js';
export * from './cliProviderArgs.js';
diff --git a/server/lib/localReviewBridge.js b/server/lib/localReviewBridge.js
new file mode 100644
index 0000000000..cd34362892
--- /dev/null
+++ b/server/lib/localReviewBridge.js
@@ -0,0 +1,17 @@
+import { join } from 'path';
+import { PATHS } from './fileUtils.js';
+
+/**
+ * Absolute path of the stdin bridge into the local-review service
+ * (`server/scripts/run-local-code-review.mjs`): same reviewers, same
+ * `timeoutMs` forwarding as `POST /api/code-review/local`, but no HTTP and so
+ * no instance-password gate.
+ *
+ * Two prompt builders hand it to agents — the CoS claim procedure
+ * (`services/cosTaskPrompts.js`) drives every tool-free reviewer through it, and
+ * the review-loop section (`services/promptSections/reviewLifecycle.js`) names
+ * it as the fallback when the gated endpoint answers 401. Resolved once here so
+ * moving or renaming the script cannot break one prompt while the other keeps
+ * working. Each caller applies its own `shellQuote`.
+ */
+export const LOCAL_REVIEW_BRIDGE_SCRIPT = join(PATHS.root, 'server/scripts/run-local-code-review.mjs');
diff --git a/server/services/agentApiAuth.js b/server/services/agentApiAuth.js
new file mode 100644
index 0000000000..20f0a2006e
--- /dev/null
+++ b/server/services/agentApiAuth.js
@@ -0,0 +1,88 @@
+/**
+ * The loopback API credential a CoS agent runs with.
+ *
+ * PortOS's optional instance password gates every `/api/*` path (`authGate.js`),
+ * and it is the recommended posture — it is what keeps a tailnet/LAN neighbour
+ * off this install. Agents, though, get no browser cookie, and
+ * `auth-sessions.json` stores only token HASHES, so nothing in the environment
+ * can be turned back into a credential. The result was that every canned `curl`
+ * PortOS hands its own agents — the local-LLM reviewer endpoint, the review
+ * challenge protocol, the MCP agent-context endpoint — answered
+ * `401 AUTH_REQUIRED` on a password-protected install, which reads to the agent
+ * as "the reviewer is broken" rather than "you were never given a credential".
+ *
+ * So mint one session token for agent use and hand it over as
+ * `PORTOS_API_TOKEN`. This widens no boundary: an agent already runs shell on
+ * the machine that owns the session store and could call `createSession()`
+ * itself. The instance PASSWORD is never exposed — only a session token, which
+ * the user can revoke wholesale by rotating the password or logging out
+ * everywhere. One token is shared by every agent rather than minted per spawn,
+ * so the session store does not grow a record per run.
+ */
+import { authEvents, createSession, isAuthEnabled, verifySession } from './auth.js';
+import { isPublicReviewRestrictedProfile } from '../lib/agentExecutionProfiles.js';
+import { createSingleFlight } from '../lib/singleFlight.js';
+// The variable name is shared with the prompt builders that write the agent's
+// `curl` snippets — see lib/agentApiToken.js.
+import { AGENT_API_TOKEN_ENV } from '../lib/agentApiToken.js';
+
+// Re-mint with a day of life left rather than handing a long agent run a token
+// that expires mid-flight. Sessions live 30 days, so this refreshes ~monthly.
+const REFRESH_MARGIN_MS = 24 * 60 * 60 * 1000;
+
+let cached = null;
+// One in-flight mint shared by a burst of concurrent spawns — otherwise a
+// parallel dispatch writes a session record per agent.
+let minting = createSingleFlight();
+
+// A password rotation (and an explicit log-out-everywhere) drops every session,
+// including this one. Forget it immediately so the next spawn mints a live token
+// instead of handing out one the gate will reject.
+authEvents.on('sessions:revoked-all', () => { cached = null; });
+
+/**
+ * Still valid AND not about to expire. `verifySession` is a Map lookup against
+ * the already-loaded session store, so re-checking on every spawn is cheap — and
+ * it is what catches a session store that was cleared out from under us (a
+ * restored backup, a hand-edited `auth-sessions.json`).
+ */
+const isUsable = async (entry) => !!entry
+ && entry.expiresAt - Date.now() > REFRESH_MARGIN_MS
+ && await verifySession(entry.token);
+
+/**
+ * The env overlay a spawning agent gets, layered in beside the other credential
+ * overlays (`resolveForgeTokenEnv`'s `GH_TOKEN`, the Claude settings env).
+ *
+ * A public-review stage gets NOTHING: its input is contributor-controlled text,
+ * so it must never hold a credential to this install's API. `buildCliChildEnv`'s
+ * allowlist would strip the variable anyway; returning early means the token is
+ * never minted for that stage to begin with.
+ *
+ * @param {object} [options]
+ * @param {string|null} [options.safetyProfile] - the spawn's execution profile
+ * @returns {Promise<object>} `{ PORTOS_API_TOKEN }`, or `{}` when this install
+ * has no instance password (the disabled gate ignores the empty bearer the
+ * agent's curls then send), the stage is public-content, or the mint failed
+ */
+export async function resolveAgentApiEnv({ safetyProfile = null } = {}) {
+ if (isPublicReviewRestrictedProfile(safetyProfile)) return {};
+ if (!await isAuthEnabled()) return {};
+ if (await isUsable(cached)) return { [AGENT_API_TOKEN_ENV]: cached.token };
+ const minted = await minting.run(AGENT_API_TOKEN_ENV, () => createSession()
+ .then(({ token, expiresAt }) => {
+ cached = { token, expiresAt };
+ return cached;
+ })
+ // A failed mint must not take the spawn down with it: the agent still runs,
+ // its API calls just answer 401 as they did before the token existed.
+ .catch((err) => {
+ console.error(`❌ Failed to mint the agent API token: ${err.message}`);
+ return null;
+ }));
+ return minted ? { [AGENT_API_TOKEN_ENV]: minted.token } : {};
+}
+
+export const __testing = {
+ reset: () => { cached = null; minting = createSingleFlight(); },
+};
diff --git a/server/services/agentApiAuth.test.js b/server/services/agentApiAuth.test.js
new file mode 100644
index 0000000000..c580daf57c
--- /dev/null
+++ b/server/services/agentApiAuth.test.js
@@ -0,0 +1,101 @@
+/**
+ * The loopback credential agents spend on this install's own API.
+ *
+ * The failure this exists to prevent is silent in both directions: hand out no
+ * token on a password-protected install and every canned agent `curl` is a
+ * `401` the agent reads as a broken endpoint; hand one out to a public-content
+ * stage and contributor-controlled text is running with a credential to the
+ * whole API. Both are asserted here, along with the reuse contract — a parallel
+ * dispatch must not write one session record per agent — and the revocation
+ * path, since a stale token fails exactly like having none.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+const authEvents = new EventEmitter();
+const isAuthEnabled = vi.fn();
+const createSession = vi.fn();
+const verifySession = vi.fn();
+
+vi.mock('./auth.js', () => ({
+ authEvents,
+ isAuthEnabled: (...args) => isAuthEnabled(...args),
+ createSession: (...args) => createSession(...args),
+ verifySession: (...args) => verifySession(...args),
+}));
+
+const { resolveAgentApiEnv, __testing } = await import('./agentApiAuth.js');
+
+const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
+const session = (token) => ({ token, expiresAt: Date.now() + THIRTY_DAYS_MS });
+
+describe('resolveAgentApiEnv', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __testing.reset();
+ isAuthEnabled.mockResolvedValue(true);
+ verifySession.mockResolvedValue(true);
+ createSession.mockImplementation(async () => session('tok-1'));
+ });
+
+ it('mints a session token for the agent when the install has an instance password', async () => {
+ await expect(resolveAgentApiEnv()).resolves.toEqual({ PORTOS_API_TOKEN: 'tok-1' });
+ });
+
+ it('hands out no token when no instance password is set — the gate lets the call through anyway', async () => {
+ isAuthEnabled.mockResolvedValue(false);
+
+ await expect(resolveAgentApiEnv()).resolves.toEqual({});
+ expect(createSession).not.toHaveBeenCalled();
+ });
+
+ it('never gives a public-content stage a credential to this install', async () => {
+ await expect(resolveAgentApiEnv({ safetyProfile: 'public-review' })).resolves.toEqual({});
+ await expect(resolveAgentApiEnv({ safetyProfile: 'public-review-actions' })).resolves.toEqual({});
+ expect(createSession).not.toHaveBeenCalled();
+ });
+
+ it('reuses one token across spawns, including a concurrent burst', async () => {
+ const [first, second] = await Promise.all([resolveAgentApiEnv(), resolveAgentApiEnv()]);
+ const third = await resolveAgentApiEnv();
+
+ expect(first).toEqual({ PORTOS_API_TOKEN: 'tok-1' });
+ expect(second).toEqual({ PORTOS_API_TOKEN: 'tok-1' });
+ expect(third).toEqual({ PORTOS_API_TOKEN: 'tok-1' });
+ expect(createSession).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-mints after a password rotation drops every session', async () => {
+ await resolveAgentApiEnv();
+ createSession.mockImplementation(async () => session('tok-2'));
+ authEvents.emit('sessions:revoked-all');
+
+ await expect(resolveAgentApiEnv()).resolves.toEqual({ PORTOS_API_TOKEN: 'tok-2' });
+ expect(createSession).toHaveBeenCalledTimes(2);
+ });
+
+ it('re-mints when the session store no longer knows the cached token', async () => {
+ await resolveAgentApiEnv();
+ verifySession.mockResolvedValue(false);
+ createSession.mockImplementation(async () => session('tok-3'));
+
+ await expect(resolveAgentApiEnv()).resolves.toEqual({ PORTOS_API_TOKEN: 'tok-3' });
+ });
+
+ it('re-mints a token that would expire inside a long agent run', async () => {
+ createSession.mockImplementationOnce(async () => ({ token: 'tok-expiring', expiresAt: Date.now() + 60_000 }));
+ await resolveAgentApiEnv();
+ createSession.mockImplementation(async () => session('tok-fresh'));
+
+ await expect(resolveAgentApiEnv()).resolves.toEqual({ PORTOS_API_TOKEN: 'tok-fresh' });
+ });
+
+ it('spawns without a token when minting fails', async () => {
+ createSession.mockRejectedValue(new Error('settings.json is unreadable'));
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(resolveAgentApiEnv()).resolves.toEqual({});
+ expect(consoleError).toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 405aba26b8..b877aafa69 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -38,6 +38,7 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { buildVendorSpawnConfig } from '../lib/providerVendors.js';
import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
import { resolveForgeTokenEnv } from './forgeAuth.js';
+import { resolveAgentApiEnv } from './agentApiAuth.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
@@ -198,11 +199,16 @@ export async function spawnDirectly({
// entirely when the provider supplies its own GH_TOKEN/GITHUB_TOKEN so its
// explicit credential wins (gh prefers GH_TOKEN, so injecting one would shadow a
// provider GITHUB_TOKEN).
- const [claudeSettingsEnv, forgeTokenEnv] = isPublicReviewRestrictedProfile(safetyProfile)
- ? [{}, {}]
+ // A third rides alongside: the loopback PortOS session token this agent's own
+ // `curl` snippets need when the install has an instance password set (see
+ // agentApiAuth.js). It is `{}` when auth is off, and never resolved for a
+ // public-content stage.
+ const [claudeSettingsEnv, forgeTokenEnv, agentApiEnv] = isPublicReviewRestrictedProfile(safetyProfile)
+ ? [{}, {}, {}]
: await Promise.all([
isClaudeCliProvider(provider) ? getClaudeSettingsEnv() : Promise.resolve({}),
providerSuppliesGithubToken(provider) ? Promise.resolve({}) : resolveForgeTokenEnv(cwd),
+ resolveAgentApiEnv({ safetyProfile }),
]);
// Shared composition (provider.envVars + OpenCode models map + PWD pin +
@@ -212,7 +218,7 @@ export async function spawnDirectly({
// final PATH so a `--dangerously-skip-permissions` agent can't `pm2 kill` the
// shared daemon.
const childEnv = buildCliChildEnv({
- before: { ...forgeTokenEnv, ...claudeSettingsEnv },
+ before: { ...forgeTokenEnv, ...claudeSettingsEnv, ...agentApiEnv },
provider,
model,
cwd,
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 84b91cf5b8..b0e72e7197 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -52,6 +52,10 @@ vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn().mockResolved
// pulling in the real worktreeManager → instances module graph. Default: no
// owner-matched account → empty overlay (ambient gh auth untouched).
vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+// The loopback PortOS API token the agent's own `curl`s spend — mocked for the
+// same reason: the real one reads settings.json to learn whether this install
+// has an instance password.
+vi.mock('./agentApiAuth.js', () => ({ resolveAgentApiEnv: vi.fn().mockResolvedValue({}) }));
vi.mock('./agentFinalization.js', () => ({
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn(),
@@ -1062,6 +1066,26 @@ describe('stream error containment', () => {
await spawnPromise.catch(() => {});
});
+ // The agent's own prompt hands it `curl`s against this install's API, which is
+ // gated whenever an instance password is set. The token is the only way an
+ // agent — which holds no browser cookie — can answer that gate.
+ it('injects the loopback PortOS API token into the spawn env', async () => {
+ const { resolveAgentApiEnv } = await import('./agentApiAuth.js');
+ vi.mocked(resolveAgentApiEnv).mockResolvedValueOnce({ PORTOS_API_TOKEN: 'portos-session-token' });
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+ await new Promise((r) => setTimeout(r, 10)); // let the resolveAgentApiEnv await settle
+
+ expect(spawn).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ env: expect.objectContaining({ PORTOS_API_TOKEN: 'portos-session-token' }) }),
+ );
+
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ });
+
it('spawns a Creative Director task in an isolated scratch cwd, not the PortOS root (#4650)', async () => {
const { creativeDirectorScratchCwd } = await import('../lib/spawnCwd.js');
const args = {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 325fd203f3..8e3cf1f704 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -79,6 +79,7 @@ import { releaseAppReviewMarker } from './appActivity.js';
import { ensureInstanceId } from './instanceIdentity.js';
import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';
import { resolveForgeTokenEnv } from './forgeAuth.js';
+import { resolveAgentApiEnv } from './agentApiAuth.js';
import { runnerAgents, pausedAgents, consumePausedAgentExit, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
import { isUpdateInProgress } from './updateChecker.js';
@@ -984,9 +985,14 @@ export async function spawnViaRunner(agentId, task, opts) {
// account — see resolveForgeTokenEnv; `{}` when there's no owner match). Skip
// the token probe when the provider supplies its own GH_TOKEN/GITHUB_TOKEN so
// its explicit credential wins.
- const [claudeSettingsEnv, forgeTokenEnv] = await Promise.all([
+ // ...plus the loopback PortOS session token the agent's own `curl` snippets
+ // need on a password-protected install (agentApiAuth.js); `{}` when auth is
+ // off. The runner rebuilds its child env from ITS ambient environment, so like
+ // GH_TOKEN this has to ride the explicit delta below or the agent never sees it.
+ const [claudeSettingsEnv, forgeTokenEnv, agentApiEnv] = await Promise.all([
isClaudeCliProvider(provider) ? getClaudeSettingsEnv() : Promise.resolve({}),
providerSuppliesGithubToken(provider) ? Promise.resolve({}) : resolveForgeTokenEnv(workspacePath),
+ resolveAgentApiEnv(),
]);
// The runner can reject the spawn outright — a command missing from its
@@ -1022,7 +1028,7 @@ export async function spawnViaRunner(agentId, task, opts) {
// injected `--model ollama/<id>` is accepted (#2243/#2190 — this path was
// the site that sweep originally missed).
envVars: composeProviderEnv({
- before: { ...forgeTokenEnv, ...claudeSettingsEnv },
+ before: { ...forgeTokenEnv, ...claudeSettingsEnv, ...agentApiEnv },
provider,
model,
}),
diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.js
index 5059ebd11b..ac2a56f231 100644
--- a/server/services/agentLifecycle.spawnViaRunner.test.js
+++ b/server/services/agentLifecycle.spawnViaRunner.test.js
@@ -68,6 +68,9 @@ vi.mock('./cos.js', () => ({
}));
vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+// The runner rebuilds its child env from ITS own process.env, so a credential
+// only reaches the agent through the explicit delta this spawn POSTs.
+vi.mock('./agentApiAuth.js', () => ({ resolveAgentApiEnv: vi.fn().mockResolvedValue({}) }));
vi.mock('./agentCliSpawning.js', () => ({
buildCliSpawnConfig: vi.fn(),
@@ -411,3 +414,27 @@ it('records an AMBIGUOUS handoff as unaccepted-but-unknown, never as a refusal',
expect(new Set(ids).size).toBe(1);
});
});
+
+describe('spawnViaRunner — credentials in the env delta', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ runnerAgents.clear();
+ });
+
+ // The runner is a separate long-lived PM2 process that composes its child env
+ // from its own environment, so anything the agent needs but the server holds —
+ // the repo-owner GH_TOKEN, and now the loopback PortOS session token its own
+ // prompt's `curl`s spend — has to ride this POSTed delta or the agent never
+ // sees it (#7660 follow-on: every such call was a 401 on a gated install).
+ it('POSTs the loopback PortOS API token to the runner', async () => {
+ const { resolveAgentApiEnv } = await import('./agentApiAuth.js');
+ vi.mocked(resolveAgentApiEnv).mockResolvedValueOnce({ PORTOS_API_TOKEN: 'portos-session-token' });
+ vi.mocked(spawnAgentViaRunner).mockResolvedValueOnce({ pid: 4242 });
+
+ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());
+
+ expect(spawnAgentViaRunner).toHaveBeenCalledWith(expect.objectContaining({
+ envVars: expect.objectContaining({ PORTOS_API_TOKEN: 'portos-session-token' }),
+ }));
+ });
+});
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index e9a3351e7f..2317b3b9c0 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -890,10 +890,15 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'
// What is still worth pinning HERE is the wiring: that spawnViaRunner routes
// through the shared composer and feeds it the right inputs.
describe('agentLifecycle — runner OpenCode Ollama env (#2243 / #2190)', () => {
+ // Bounded by the NEXT top-level declaration rather than a character count: a
+ // fixed window silently shrinks as the function grows a comment, and the
+ // assertions below then fail on text that is still there (and would keep
+ // passing on a line that had drifted into the following function).
const runnerBody = () => {
const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnViaRunner');
expect(fnStart, 'spawnViaRunner must exist').toBeGreaterThan(-1);
- return AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 4000);
+ const nextExport = AGENT_LIFECYCLE_SRC.indexOf('\nexport ', fnStart + 1);
+ return AGENT_LIFECYCLE_SRC.slice(fnStart, nextExport > -1 ? nextExport : undefined);
};
it('source: composes the runner envVars through the shared composeProviderEnv', () => {
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 6fe75145aa..b5c1dc82b3 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -82,6 +82,7 @@ import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { buildCliChildEnv, composeProviderEnv } from '../lib/cliChildEnv.js';
import { cliProviderAuthDescriptor } from '../lib/processEnv.js';
+import { resolveAgentApiEnv } from './agentApiAuth.js';
import { ensureOllamaAgentContext } from './ollamaAgentContext.js';
import { isOllamaBackedProvider } from './providers.js';
import { shellHasLiveChild } from '../lib/shellLivenessProbe.js';
@@ -148,6 +149,7 @@ export async function createAgentTuiSession({
tuiConfig,
cwd,
forgeTokenEnv = {},
+ agentApiEnv = {},
doneSentinelPath = null,
useDurableRunner = false,
safetyProfile = null,
@@ -168,9 +170,14 @@ export async function createAgentTuiSession({
// shell, so the operator's rc file can no longer run between this allowlist
// and the provider and re-export whatever it likes (#6159). The ordinary
// branch is a DELTA: `createShellSession` unions it onto `buildSafeEnv`.
+ // The credential overlay both branches start from: the repo-owner GH_TOKEN and
+ // the loopback PortOS API token (agentApiAuth.js). Both are resolved by the
+ // caller and both are `{}` for a public-content stage, whose allowlist would
+ // strip them regardless.
+ const credentialEnv = { ...forgeTokenEnv, ...agentApiEnv };
const env = restricted
- ? buildCliChildEnv({ before: forgeTokenEnv, provider, model, cwd, guard: true, safetyProfile })
- : { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() };
+ ? buildCliChildEnv({ before: credentialEnv, provider, model, cwd, guard: true, safetyProfile })
+ : { ...composeProviderEnv({ before: credentialEnv, provider, model }), ...agentGuardEnv() };
// How this session identifies itself in the Shell UI and the session registry.
// Identical for all three spawn shapes below — an attached human sees the same
// tab whichever one opened the PTY.
@@ -1606,6 +1613,12 @@ export async function spawnTuiAgent({
? {}
: await git.resolveForgeTokenEnv(cwd);
+ // The loopback PortOS session token this agent's own `curl` snippets need when
+ // the install has an instance password set (agentApiAuth.js). `buildSafeEnv`
+ // allowlist-filters the inherited env for a login-shell PTY, so like GH_TOKEN
+ // it only reaches the agent by riding the explicit delta below.
+ const agentApiEnv = await resolveAgentApiEnv({ safetyProfile });
+
// Ollama-backed harnesses talk to the daemon directly, so their context
// window is whatever Ollama loaded the model at — no per-request `num_ctx`
// reaches them. Hold the daemon at the provider's configured window (or warn
@@ -1645,6 +1658,7 @@ export async function spawnTuiAgent({
tuiConfig,
cwd,
forgeTokenEnv,
+ agentApiEnv,
doneSentinelPath,
useDurableRunner,
safetyProfile,
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index e68a0295ed..4913614109 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -108,6 +108,13 @@ vi.mock('./agentState.js', async (importOriginal) => ({
unregisterSpawnedAgent: vi.fn(),
}));
+// The loopback API token the agent's own PortOS `curl`s spend. The real one
+// reads settings.json to decide whether an instance password is set; this suite
+// only cares that whatever it returns reaches the PTY env.
+vi.mock('./agentApiAuth.js', () => ({
+ resolveAgentApiEnv: vi.fn().mockResolvedValue({}),
+}));
+
vi.mock('./git.js', () => ({
getDiff: vi.fn().mockResolvedValue('diff content here'),
// No owner-matched gh account by default → empty overlay (ambient auth kept).
@@ -860,6 +867,29 @@ describe('spawnTuiAgent runtime', () => {
await completeDone;
});
+ // Same reason as GH_TOKEN above, different credential: `buildSafeEnv`
+ // allowlists the inherited env, so the loopback PortOS session token only
+ // reaches the agent by riding this explicit delta. Without it every canned
+ // `curl` in the agent's own prompt is a 401 on a password-protected install.
+ it('passes the loopback PortOS API token into the TUI session env', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+ const { resolveAgentApiEnv } = await import('./agentApiAuth.js');
+ vi.mocked(resolveAgentApiEnv).mockResolvedValueOnce({ PORTOS_API_TOKEN: 'portos-session-token' });
+
+ runSpawn({ workspacePath: '/tmp/ws' });
+ await flushMicrotasks();
+
+ expect(shellService.createShellSession).toHaveBeenCalledWith(
+ null,
+ expect.objectContaining({ env: expect.objectContaining({ PORTOS_API_TOKEN: 'portos-session-token' }) }),
+ );
+
+ await capturedOnExit({ exitCode: 0, killed: false });
+ await completeDone;
+ });
+
// #6062 — the attachable Stage 3. The PTY child must get the SAME allowlisted
// environment its headless sibling would; a TUI Stage 3 running with the
// server's own inherited environment would be a real regression, not a
diff --git a/server/services/authGate.test.js b/server/services/authGate.test.js
index 4d4cb22f4a..378e2edf9a 100644
--- a/server/services/authGate.test.js
+++ b/server/services/authGate.test.js
@@ -173,6 +173,43 @@ describe('authGate middleware', () => {
expect(result.called).toBe(true);
});
+ // The whole point of the agent token: a CoS agent holds no browser cookie, so
+ // the credential PortOS injects into its environment has to satisfy this gate
+ // or every canned `curl` in its own prompt is a 401 it reads as a dead
+ // endpoint. Minted through the real service against the real gate — the two
+ // halves are wired far apart (spawn env vs. Express middleware).
+ it('accepts the loopback token PortOS mints for its own agents', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'correct-horse' });
+ const { resolveAgentApiEnv } = await import('./agentApiAuth.js');
+ const { PORTOS_API_TOKEN } = await resolveAgentApiEnv();
+ const { authGate } = await import('./authGate.js');
+
+ const result = await runGate(authGate, {
+ path: '/api/code-review/local',
+ headers: { authorization: `Bearer ${PORTOS_API_TOKEN}` },
+ });
+
+ expect(PORTOS_API_TOKEN).toBeTruthy();
+ expect(result.called).toBe(true);
+ });
+
+ // …and the `${PORTOS_API_TOKEN:-}` default in those prompts is not a bypass:
+ // an agent that never received a token is still refused.
+ it('refuses the empty bearer an unprovisioned agent would send', async () => {
+ const auth = await import('./auth.js');
+ await auth.setPassword({ newPassword: 'correct-horse' });
+ const { authGate } = await import('./authGate.js');
+
+ const result = await runGate(authGate, {
+ path: '/api/code-review/local',
+ headers: { authorization: 'Bearer ' },
+ });
+
+ expect(result.called).toBe(false);
+ expect(result.res.statusCode).toBe(401);
+ });
+
it('lets static client paths through when auth is on', async () => {
const auth = await import('./auth.js');
await auth.setPassword({ newPassword: 'correct-horse' });
diff --git a/server/services/cosTaskPrompts.js b/server/services/cosTaskPrompts.js
index c629edaf58..411b6940d1 100644
--- a/server/services/cosTaskPrompts.js
+++ b/server/services/cosTaskPrompts.js
@@ -5,10 +5,9 @@
* and persistence remain in cosTaskGenerator.js.
*/
-import { join } from 'path';
import { CLAIM_OVERRIDE_CONTEXT_MAX_CHARS, buildReviewerEffortNote, isToolFreeReviewer } from '../lib/validation.js';
-import { PATHS } from '../lib/fileUtils.js';
import { shellQuote } from '../lib/shellQuote.js';
+import { LOCAL_REVIEW_BRIDGE_SCRIPT } from '../lib/localReviewBridge.js';
export function normalizeWorkItemRef(ref) {
const raw = String(ref ?? '').trim().replace(/^#/, '');
@@ -116,7 +115,7 @@ export function buildLocalReviewerInstructions(reviewers, reviewerModels = {}, r
'git fetch origin "$DEFAULT_BRANCH" >/dev/null 2>&1',
'git diff "origin/$DEFAULT_BRANCH...HEAD"',
].join('\n');
- const reviewScript = shellQuote(join(PATHS.root, 'server/scripts/run-local-code-review.mjs'));
+ const reviewScript = shellQuote(LOCAL_REVIEW_BRIDGE_SCRIPT);
const ingressReviewer = localReviewers[0];
const ingressPinned = {
kind: 'claim-comments',
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt
index 95ca988a00..953260ee3e 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt
@@ -12,7 +12,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -35,7 +35,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -45,8 +45,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt
index 26857f3c87..42a27dd9bc 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt
@@ -17,7 +17,7 @@ A previous agent finished implementing the work for source task **task-example**
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -40,7 +40,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -53,8 +53,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
index e496c4a590..c229c45e71 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt
@@ -12,7 +12,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -35,7 +35,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):
@@ -50,8 +50,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
index dee765dc2e..641353b41b 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt
@@ -17,7 +17,7 @@ A previous agent finished implementing the work for source task **task-example**
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -40,7 +40,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):
@@ -58,8 +58,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt
index 8cf395277c..ebda2788a2 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt
@@ -12,7 +12,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -35,7 +35,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -45,8 +45,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt
index 4d8306e835..68fa90a249 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt
@@ -17,7 +17,7 @@ A previous agent finished implementing the work for source task **task-example**
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -40,7 +40,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -53,8 +53,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt
index d1dfa819ac..18c002ce0b 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt
@@ -12,7 +12,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -35,7 +35,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):
@@ -49,8 +49,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt
index e0d63c8e29..6c34cface9 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt
@@ -17,7 +17,7 @@ A previous agent finished implementing the work for source task **task-example**
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -40,7 +40,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):
@@ -57,8 +57,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
index 9d29afde7d..fbb4f5ba49 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt
@@ -23,8 +23,9 @@ A previous agent finished task **task-example** and opened **PR https://github.c
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt
index 03075250ab..7c809ba402 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt
@@ -20,7 +20,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -43,7 +43,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -53,8 +53,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt
index bb6a798b17..e029a003c6 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt
@@ -25,7 +25,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -48,7 +48,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -61,8 +61,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
index d6a5262441..1d80fca345 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt
@@ -20,7 +20,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -43,7 +43,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published and the required comment was posted, so leave it open, report that the required review is pending, and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.
@@ -59,8 +59,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
index 0f1626f77e..4fc902bbb9 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt
@@ -25,7 +25,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`; on GitHub `gh pr diff 42` also works). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -48,7 +48,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `gh pr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as PR reviewer (`gh pr edit 42 --add-reviewer <user>`, drop the `@`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published and the required comment was posted, so leave it open, report that the required review is pending, and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.
@@ -67,8 +67,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt
index 6cffa611cc..dd5e8ce155 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt
@@ -20,7 +20,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -43,7 +43,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -53,8 +53,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt
index 85a9341b82..987e2848a5 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt
@@ -25,7 +25,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -48,7 +48,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.
@@ -61,8 +61,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt
index 612e5271bd..713e982ba3 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt
@@ -20,7 +20,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -43,7 +43,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published and the required comment was posted, so leave it open, report that the required review is pending, and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.
@@ -58,8 +58,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt
index 19a87ebeeb..dcc09087ab 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt
@@ -25,7 +25,7 @@ When the local phase satisfies the stop condition, skip the PR-side phase and re
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -48,7 +48,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `glab mr diff 42 | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. **@github reviewers**: request `@example-user` as MR reviewer using the GitLab project UI or API, then inspect `glab mr view 42` for their review and address any findings; their approval gates the merge.
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`, fail closed if it is missing, and source it. If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path; the PR/MR was already published and the required comment was posted, so leave it open, report that the required review is pending, and return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge. Accept only `clean` or `partial`; any other or missing status, or a `LOCAL_REVIEWED_HEAD_SHA` that does not equal `$(git rev-parse HEAD)`, fails closed.
@@ -66,8 +66,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
PR Details:
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt
index 82cdcbba0d..756fe80b96 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt
@@ -15,7 +15,7 @@ This runs as **step 3 of the Completion Workflow above**, against the committed
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff origin/main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(git diff origin/main...HEAD | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(git diff origin/main...HEAD | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -38,7 +38,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. Username reviewers will be requested after the PR/MR is published.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `git diff origin/main...HEAD | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. Username reviewers will be requested after the PR/MR is published.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), then re-run the same local reviewer. Do NOT push or open a PR/MR yet.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the local reviewer list is exhausted (or the stop mode triggers), record `LOCAL_OVERALL_STATUS`: use `review-blocked` only when a required reviewer could not produce a verdict because of an availability, quota/provider, timeout, transport, malformed, empty, or no-verdict failure; never use it for substantive findings, failed tests/build, unpushed fixes, or state/publication failures, and do not self-review. Set `LOCAL_STOP_TRIGGERED=true` when the configured stop condition actually fired on a qualifying verdict, including when that verdict came from the final local reviewer; set it false for list exhaustion, an inconclusive result, or `review-blocked`. The configured reviewer positions are zero-based: `mtplx`=0, `ollama`=1, `copilot`=2, `codex`=3, `@example-user`=4. When a qualifying verdict triggers the configured stop condition, set `LOCAL_STOP_TRIGGERED=true` and `LOCAL_STOP_INDEX` to that triggering local reviewer's position; when the list exhausts without a qualifying stop or a result is inconclusive, set `LOCAL_STOP_TRIGGERED=false` and `LOCAL_STOP_INDEX=-1`. Compute `LOCAL_PHASE_COMMITS=$(git rev-list "$LOCAL_PHASE_START_SHA..HEAD" --count)`; if a qualifying stop fired, retain the triggering reviewer's `LOCAL_REVIEWER_COMMITS` as `LOCAL_STOP_REVIEW_COMMITS`, otherwise set `LOCAL_STOP_REVIEW_COMMITS=-1`. Record `LOCAL_REVIEWED_HEAD_SHA=$(git rev-parse HEAD)`. Persist all phase state for later shell calls in the worktree-private Git state file: `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`; then run `printf 'LOCAL_PHASE_START_SHA=%s\nLOCAL_OVERALL_STATUS=%s\nLOCAL_STOP_TRIGGERED=%s\nLOCAL_STOP_INDEX=%s\nLOCAL_STOP_REVIEW_COMMITS=%s\nLOCAL_PHASE_COMMITS=%s\nLOCAL_REVIEWED_HEAD_SHA=%s\n' "$LOCAL_PHASE_START_SHA" "$LOCAL_OVERALL_STATUS" "$LOCAL_STOP_TRIGGERED" "$LOCAL_STOP_INDEX" "$LOCAL_STOP_REVIEW_COMMITS" "$LOCAL_PHASE_COMMITS" "$LOCAL_REVIEWED_HEAD_SHA" > "$LOCAL_REVIEW_STATE_FILE"`. A `review-blocked` state is a completed local phase that permits publication but blocks the merge gate; the publication step posts the required comment. If that write fails, do NOT push or open the PR/MR. For a final-reviewer stop, follow the same phase-level gate below: `on-clean` requires `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS=0`, while `on-findings` requires `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS>0`; a `partial` status is already a qualifying stop. Return to the Completion Workflow and continue with the push and PR/MR creation step when all executed required reviewers are clean and optional reviewers are clean or inconclusive, when `LOCAL_OVERALL_STATUS=partial` records a qualifying configured stop-mode short-circuit, or when `LOCAL_OVERALL_STATUS=review-blocked` records only reviewer unavailability. Do NOT push or open the PR/MR before this local phase is complete.
@@ -46,8 +46,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, stop without pushing or opening a PR/MR. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to the PR/MR creation step; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt
index 82cdcbba0d..756fe80b96 100644
--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt
+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt
@@ -15,7 +15,7 @@ This runs as **step 3 of the Completion Workflow above**, against the committed
1. For EACH reviewer in order — `ollama` → `copilot` → `codex` → `@example-user` — run a full review-and-fix sub-loop before advancing to the next. **copilot**: request a Copilot review when you reach its turn (poll every 5–15s, max 5 min/round), then re-request on later rounds. **codex**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or `git diff origin/main...HEAD`). When invoking a reviewer with a pinned model or reasoning effort, pass it: `codex --model gpt-5.6-sol -c model_reasoning_effort=high …`. Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags. **ollama**: POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.
```bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(git diff origin/main...HEAD | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(git diff origin/main...HEAD | jq -Rs '{ backend: "ollama", diff: . }' | curl -sS -X POST http://127.0.0.1:5555/api/code-review/local -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -38,7 +38,7 @@ else
cat "${REVIEW_RESPONSE}.findings"
fi
```
-Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. Username reviewers will be requested after the PR/MR is published.
+Only a successfully extracted `.findings` value is the review text; treat it like any other reviewer's findings. An `HTTP 401` is not a review result — it means this install has an instance password and the `PORTOS_API_TOKEN` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: `git diff origin/main...HEAD | jq -Rs '{ backend: "ollama", diff: . }' | node /portos/server/scripts/run-local-code-review.mjs > "$REVIEW_RESPONSE"`, then extract `.findings` from it exactly as above. This run pins settings for `ollama` → `"model": "qwen3-coder"` — add those keys to the JSON body (`jq -Rs '{ backend: "ollama", model: "…", diff: . }'`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk. Username reviewers will be requested after the PR/MR is published.
2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), then re-run the same local reviewer. Do NOT push or open a PR/MR yet.
3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.
4. When the local reviewer list is exhausted (or the stop mode triggers), record `LOCAL_OVERALL_STATUS`: use `review-blocked` only when a required reviewer could not produce a verdict because of an availability, quota/provider, timeout, transport, malformed, empty, or no-verdict failure; never use it for substantive findings, failed tests/build, unpushed fixes, or state/publication failures, and do not self-review. Set `LOCAL_STOP_TRIGGERED=true` when the configured stop condition actually fired on a qualifying verdict, including when that verdict came from the final local reviewer; set it false for list exhaustion, an inconclusive result, or `review-blocked`. The configured reviewer positions are zero-based: `mtplx`=0, `ollama`=1, `copilot`=2, `codex`=3, `@example-user`=4. When a qualifying verdict triggers the configured stop condition, set `LOCAL_STOP_TRIGGERED=true` and `LOCAL_STOP_INDEX` to that triggering local reviewer's position; when the list exhausts without a qualifying stop or a result is inconclusive, set `LOCAL_STOP_TRIGGERED=false` and `LOCAL_STOP_INDEX=-1`. Compute `LOCAL_PHASE_COMMITS=$(git rev-list "$LOCAL_PHASE_START_SHA..HEAD" --count)`; if a qualifying stop fired, retain the triggering reviewer's `LOCAL_REVIEWER_COMMITS` as `LOCAL_STOP_REVIEW_COMMITS`, otherwise set `LOCAL_STOP_REVIEW_COMMITS=-1`. Record `LOCAL_REVIEWED_HEAD_SHA=$(git rev-parse HEAD)`. Persist all phase state for later shell calls in the worktree-private Git state file: `LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"`; then run `printf 'LOCAL_PHASE_START_SHA=%s\nLOCAL_OVERALL_STATUS=%s\nLOCAL_STOP_TRIGGERED=%s\nLOCAL_STOP_INDEX=%s\nLOCAL_STOP_REVIEW_COMMITS=%s\nLOCAL_PHASE_COMMITS=%s\nLOCAL_REVIEWED_HEAD_SHA=%s\n' "$LOCAL_PHASE_START_SHA" "$LOCAL_OVERALL_STATUS" "$LOCAL_STOP_TRIGGERED" "$LOCAL_STOP_INDEX" "$LOCAL_STOP_REVIEW_COMMITS" "$LOCAL_PHASE_COMMITS" "$LOCAL_REVIEWED_HEAD_SHA" > "$LOCAL_REVIEW_STATE_FILE"`. A `review-blocked` state is a completed local phase that permits publication but blocks the merge gate; the publication step posts the required comment. If that write fails, do NOT push or open the PR/MR. For a final-reviewer stop, follow the same phase-level gate below: `on-clean` requires `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS=0`, while `on-findings` requires `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS>0`; a `partial` status is already a qualifying stop. Return to the Completion Workflow and continue with the push and PR/MR creation step when all executed required reviewers are clean and optional reviewers are clean or inconclusive, when `LOCAL_OVERALL_STATUS=partial` records a qualifying configured stop-mode short-circuit, or when `LOCAL_OVERALL_STATUS=review-blocked` records only reviewer unavailability. Do NOT push or open the PR/MR before this local phase is complete.
@@ -46,8 +46,9 @@ Only a successfully extracted `.findings` value is the review text; treat it lik
**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.
**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:
```bash
-curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
+curl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'
```
+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.
A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, stop without pushing or opening a PR/MR. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to the PR/MR creation step; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.
### CLI Reviewer Procedure (codex)
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index 134181ffa3..7910c3311d 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -7,6 +7,8 @@ import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';
import { detectForgeCli } from '../../lib/gitForge.js';
import { shellQuote } from '../../lib/shellQuote.js';
import { localApiBaseUrl } from '../../lib/networkExposure.js';
+import { AGENT_API_AUTH_CURL_ARG } from '../../lib/agentApiToken.js';
+import { LOCAL_REVIEW_BRIDGE_SCRIPT } from '../../lib/localReviewBridge.js';
import { INLINE_REVIEW_LOOP_STEP } from './constants.js';
import { normalizeForgeCli } from './forge.js';
@@ -304,6 +306,14 @@ function resolveReviewRoster(metadata, { reviewerPositions = [] } = {}) {
* port when this install booted with HTTPS (where the API port is TLS-only and
* a plain-HTTP curl would fail at the transport layer), the API port otherwise.
*
+ * `/api/*` is gated when the install has an instance password set, which is the
+ * recommended posture — so the request carries the loopback session token PortOS
+ * injects into the agent's environment (`services/agentApiAuth.js`). Without it
+ * every one of these reviews came back `401 AUTH_REQUIRED`, which reads as a
+ * broken reviewer. A 401 nonetheless (a run spawned before the token existed, a
+ * rotated password) is not a review verdict: the prose points the agent at the
+ * auth-independent stdin bridge, the same service without the gate.
+ *
* A pinned local-LLM model can't ride the endpoint's server-side default: that
* reads the GLOBAL settings scalar and has never seen this task. So when the
* user pinned one on the reviewer's row, name it in the request body — `model`
@@ -352,7 +362,7 @@ function buildLocalLlmInvocation({ localLlmBackends, reviewerModelMap, reviewerE
const invocation = `POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it.${backendNote}
\`\`\`bash
REVIEW_RESPONSE=$(mktemp)
-HTTP_STATUS=$(${diffCommand} | jq -Rs '{ backend: "${backendToken}", diff: . }' | curl -sS -X POST ${apiBase}/api/code-review/local -H 'Content-Type: application/json' -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
+HTTP_STATUS=$(${diffCommand} | jq -Rs '{ backend: "${backendToken}", diff: . }' | curl -sS -X POST ${apiBase}/api/code-review/local -H 'Content-Type: application/json' ${AGENT_API_AUTH_CURL_ARG} -d @- -o "$REVIEW_RESPONSE" -w '%{http_code}') || {
echo "Local reviewer failed: request transport error" >&2
STATUS=cli-error
exit 1
@@ -375,7 +385,7 @@ else
cat "\${REVIEW_RESPONSE}.findings"
fi
\`\`\`
-Only a successfully extracted \`.findings\` value is the review text; treat it like any other reviewer's findings.${pinNote.length
+Only a successfully extracted \`.findings\` value is the review text; treat it like any other reviewer's findings. An \`HTTP 401\` is not a review result — it means this install has an instance password and the \`PORTOS_API_TOKEN\` in your environment is missing or stale. Re-run the SAME request body (with whatever keys this run pins) through the auth-independent bridge — the same service without the gate — before recording any status: \`${diffCommand} | jq -Rs '{ backend: "${backendToken}", diff: . }' | node ${shellQuote(LOCAL_REVIEW_BRIDGE_SCRIPT)} > "$REVIEW_RESPONSE"\`, then extract \`.findings\` from it exactly as above.${pinNote.length
? ` This run pins settings for ${pinNote.join(', ')} — add those keys to the JSON body (\`jq -Rs '{ ${pinJq} }'\`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk.`
: ''}`;
return { backendToken, invocation };
@@ -822,8 +832,9 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const challengeProtocolNote = [
'**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:',
'```bash',
- `curl -sS -X POST ${apiBase}/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,
+ `curl -sS -X POST ${apiBase}/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' ${AGENT_API_AUTH_CURL_ARG} -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,
'```',
+ `Keep that \`Authorization\` header on every PortOS API call you make, including the \`/resolve\` POST below: this install gates \`/api/*\` behind its instance password, and \`$PORTOS_API_TOKEN\` is the session token PortOS put in your environment for exactly this. A bare \`401 AUTH_REQUIRED\` means the header was dropped, not that the endpoint is unavailable.`,
`A \`409\` (\`CHALLENGE_EXHAUSTED\` = the one challenge is spent, or \`CHALLENGE_BUDGET_EXHAUSTED\` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, ${phase.challengeBlockedText(forge)}. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → \`POST .../challenge/resolve\` with \`{"outcome":"upheld"}\` and continue to ${phase.challengeContinueText}; confirmed → fix it, or send \`{"outcome":"escalated"}\` to hand the dispute to the user.` + (hasLocalLlm ? ` For a local reviewer you may instead POST \`{"recheck":{"backend":"${localLlmBackendToken}","diff":"<unified diff>"}}\` and let the server re-run it and auto-derive the outcome.` : ''),
].join('\n');
// Per-reviewer round caps. This prompt drives the loop in PROSE (it isn't
diff --git a/server/services/promptSections/reviewLifecycle.test.js b/server/services/promptSections/reviewLifecycle.test.js
index c63fdb2c16..47585f0688 100644
--- a/server/services/promptSections/reviewLifecycle.test.js
+++ b/server/services/promptSections/reviewLifecycle.test.js
@@ -79,6 +79,30 @@ describe('reviewLifecycle reviewer invocation details', () => {
expect(section).toContain('Substitute the active reviewer name');
});
+ // Both commands hit `/api/*`, which the optional instance password gates. An
+ // agent holds no browser cookie, so without the injected session token every
+ // review came back `401 AUTH_REQUIRED` and read as a broken reviewer (#7660
+ // follow-on). The whole header is one quoted argument so a token can never be
+ // word-split, and the `:-` default keeps the command valid on an install with
+ // no password set.
+ it('spends the injected loopback session token on both agent curl commands', () => {
+ const section = buildReviewLoopFollowUpSection(metadata);
+ const authHeader = '-H "Authorization: Bearer ${PORTOS_API_TOKEN:-}"';
+
+ expect(section).toContain(`/api/code-review/local -H 'Content-Type: application/json' ${authHeader}`);
+ expect(section).toContain(`/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' ${authHeader}`);
+ });
+
+ // A 401 is an absent credential, not a reviewer verdict — recording it as one
+ // would block the merge on an outage that does not exist. The bridge runs the
+ // same service over stdin with no gate.
+ it('points a 401 at the auth-independent review bridge instead of a verdict', () => {
+ const section = buildReviewLoopFollowUpSection(metadata);
+
+ expect(section).toContain('An `HTTP 401` is not a review result');
+ expect(section).toContain('server/scripts/run-local-code-review.mjs');
+ });
+
// `opencode run -m <provider/model>`: rendering `--model` here had agents
// probing for a flag OpenCode does not document.
it('renders each CLI reviewer\'s own model flag', () => {
diff --git a/server/services/promptSections/reviewLifecycleMatrix.test.js b/server/services/promptSections/reviewLifecycleMatrix.test.js
index 7e1fa8921b..7ad5049e76 100644
--- a/server/services/promptSections/reviewLifecycleMatrix.test.js
+++ b/server/services/promptSections/reviewLifecycleMatrix.test.js
@@ -29,6 +29,15 @@ vi.mock('../../lib/networkExposure.js', () => ({
localApiBaseUrl: () => 'http://127.0.0.1:5555',
}));
+// The 401 fallback names the auth-independent review bridge by absolute path,
+// which is whatever directory this install was cloned into. Pin the checkout
+// root for the same reason the origin above is pinned — and so no contributor's
+// home directory can ride a snapshot update into the repository.
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, root: '/portos' } };
+});
+
import { buildReviewLoopFollowUpSection } from './reviewLifecycle.js';
const SNAP = (name) => `./__snapshots__/reviewLoopMatrix/${name}.txt`;