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

fix: enforce claim provider review isolation (#8286)

[._.]/ Adam Eivy01c06ba0cc76
diff --git a/server/lib/README.md b/server/lib/README.md
index c70493dea1..0acf065ad9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -281,7 +281,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. `agentApiCurl({ apiBase, path, payload })` and `agentApiAuthNote({ alsoCovering })` assemble the whole call and the paragraph that must travel with it — one shape for every agent-facing API call in the tree, after two hand-written copies had already drifted on whether the install "gates" or "may gate" `/api/*` (it is opt-in and off by default). Pure, zero-import. |
-| `localReviewBridge.js` | `LOCAL_REVIEW_BRIDGE_SCRIPT` — absolute path of `server/scripts/run-local-code-review.mjs`, the stdin bridge into the local-review service (same reviewers and `timeoutMs` forwarding as `POST /api/code-review/local`, no HTTP and so no instance-password gate). Shared by the two prompt builders that hand it to agents, so renaming the script cannot break one while the other keeps working. |
+| `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). `localReviewBridgeRequest` preserves claim-review isolation even if its redundant `toolFree` flag is cleared. 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. `isPublicReviewRestrictedProfile` covers both postures; `isPublicReviewNoToolProfile` / `isPublicReviewActionsProfile` separate them for the callers whose rule differs by posture (credential-bootstrap wrapping, child-env allowlist). |
| `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `release-flow`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. |
| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
diff --git a/server/lib/localReviewBridge.js b/server/lib/localReviewBridge.js
index cd34362892..7ee12129d0 100644
--- a/server/lib/localReviewBridge.js
+++ b/server/lib/localReviewBridge.js
@@ -15,3 +15,11 @@ import { PATHS } from './fileUtils.js';
* working. Each caller applies its own `shellQuote`.
*/
export const LOCAL_REVIEW_BRIDGE_SCRIPT = join(PATHS.root, 'server/scripts/run-local-code-review.mjs');
+
+/** Preserve a claim's enforced review policy at the bridge boundary. */
+export function localReviewBridgeRequest(request, cwd) {
+ const { timeoutMs, ...reviewRequest } = request;
+ if (Number.isFinite(timeoutMs) && timeoutMs > 0) reviewRequest.timeoutMs = timeoutMs;
+ if (request.kind === 'claim-review') reviewRequest.toolFree = true;
+ return { ...reviewRequest, cwd };
+}
diff --git a/server/lib/localReviewBridge.test.js b/server/lib/localReviewBridge.test.js
new file mode 100644
index 0000000000..03d9bd3fe3
--- /dev/null
+++ b/server/lib/localReviewBridge.test.js
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+import { localReviewBridgeRequest } from './localReviewBridge.js';
+
+describe('localReviewBridgeRequest', () => {
+ it('keeps claim review isolated even if a caller clears the redundant flag', () => {
+ expect(localReviewBridgeRequest({ kind: 'claim-review', backend: 'provider:example', toolFree: false, timeoutMs: 42 }, '/checkout'))
+ .toEqual({ kind: 'claim-review', backend: 'provider:example', toolFree: true, timeoutMs: 42, cwd: '/checkout' });
+ });
+
+ it('preserves the ordinary review policy and ignores invalid timeout overrides', () => {
+ expect(localReviewBridgeRequest({ backend: 'provider:example', timeoutMs: -1 }, '/checkout'))
+ .toEqual({ backend: 'provider:example', cwd: '/checkout' });
+ });
+});
diff --git a/server/scripts/run-local-code-review.mjs b/server/scripts/run-local-code-review.mjs
index df5ffcf485..1a4c84ca49 100644
--- a/server/scripts/run-local-code-review.mjs
+++ b/server/scripts/run-local-code-review.mjs
@@ -8,6 +8,7 @@ import { getCodeReviewDefaults, reportReviewerFailure, reportReviewerSuccess, ru
import { Console } from 'node:console';
import { isReviewerConfigFault, reviewerModelsFromDefaults, reviewerEffortsFromDefaults } from '../lib/reviewerConfig.js';
+import { localReviewBridgeRequest } from '../lib/localReviewBridge.js';
import { stopCodexAppServer } from '../services/codexAppServer.js';
// Provider/runtime diagnostics belong on stderr; stdout is exactly one JSON
@@ -26,11 +27,7 @@ try {
const review = request.kind === 'claim-comments'
? runLocalClaimCommentReview
: runLocalCodeReview;
- const requestedTimeoutMs = request.timeoutMs;
- const reviewRequest = { ...request };
- delete reviewRequest.timeoutMs;
- if (Number.isFinite(requestedTimeoutMs) && requestedTimeoutMs > 0) reviewRequest.timeoutMs = requestedTimeoutMs;
- const result = await review({ ...reviewRequest, model, effort, cwd: process.cwd() });
+ const result = await review({ ...localReviewBridgeRequest(request, process.cwd()), model, effort });
process.stdout.write(`${JSON.stringify(result)}\n`);
const recordOutcome = result.ok
? reportReviewerSuccess(request.backend)
diff --git a/server/services/codeReview.providers.test.js b/server/services/codeReview.providers.test.js
index efecd9fada..77ae20aa26 100644
--- a/server/services/codeReview.providers.test.js
+++ b/server/services/codeReview.providers.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { access } from 'node:fs/promises';
import { codeReviewSettingsSchema, sanitizeTaskMetadata } from '../lib/cosValidation.js';
import { resolveReviewerConfig, buildReviewWithArgs, isReviewerConfigFault } from '../lib/reviewerConfig.js';
+import { localReviewBridgeRequest } from '../lib/localReviewBridge.js';
vi.mock('./settings.js', () => ({ getSettings: vi.fn(), settingsEvents: { on: vi.fn() } }));
vi.mock('./providers.js', () => ({ getProviderById: vi.fn(), listProviders: vi.fn() }));
@@ -186,7 +187,8 @@ describe('configured provider reviewers', () => {
it('keeps explicit tool-free review and public claim screening fail-closed for unsupported harnesses', async () => {
getProviderById.mockResolvedValue({ ...provider, type: 'cli', command: 'custom-agent' });
- expect(await runLocalCodeReview({ backend, diff: 'example diff', toolFree: true })).toMatchObject({ ok: false, code: 'REVIEWER_UNSUPPORTED' });
+ const claimRequest = localReviewBridgeRequest({ kind: 'claim-review', backend, diff: 'example diff', toolFree: false }, process.cwd());
+ expect(await runLocalCodeReview(claimRequest)).toMatchObject({ ok: false, code: 'REVIEWER_UNSUPPORTED' });
expect(await runLocalClaimCommentReview({ backend, comments: [{ login: 'example-user', type: 'User', body: 'I will work on this' }] })).toMatchObject({ ok: false, code: 'REVIEWER_UNSUPPORTED' });
expect(runCliProviderPrompt).not.toHaveBeenCalled();
});
@@ -194,7 +196,8 @@ describe('configured provider reviewers', () => {
it('isolates an explicitly tool-free review even when a repository was supplied', async () => {
getProviderById.mockResolvedValue({ ...provider, type: 'cli', command: 'claude' });
runCliProviderPrompt.mockResolvedValue({ text: 'NO FINDINGS', partial: false });
- expect(await runLocalCodeReview({ backend, diff: 'example diff', cwd: process.cwd(), toolFree: true })).toMatchObject({ ok: true });
+ const claimRequest = localReviewBridgeRequest({ kind: 'claim-review', backend, diff: 'example diff' }, process.cwd());
+ expect(await runLocalCodeReview(claimRequest)).toMatchObject({ ok: true });
const args = runCliProviderPrompt.mock.lastCall[0];
expect(args.safetyProfile).toBe('public-review-gate');
expect(args.cwd).not.toBe(process.cwd());
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 059e748cfa..9972957cb4 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -508,6 +508,7 @@ export async function buildClaimWorkTask(app, {
+ appendReviewerEffortBlock(reviewersList, promptReviewerEfforts, promptReviewerModels)
+ buildLocalReviewerInstructions(reviewersList, promptReviewerModels, promptReviewerEfforts, {
claimCommentGate: promptTaskType === 'claim-issue',
+ enforceIsolation: promptTaskType.startsWith('claim-issue'),
});
// Mirror the scheduler: inherit the delegated flow's isolation posture so the
@@ -559,7 +560,7 @@ async function resolveClaimReviewerPrompt(app) {
csv,
taskMetadata: reviewerConfigMetadata(config),
effortBlock: appendReviewerEffortBlock(list, reviewerEfforts, reviewerModels),
- localReviewerBlock: buildLocalReviewerInstructions(list, reviewerModels, reviewerEfforts),
+ localReviewerBlock: buildLocalReviewerInstructions(list, reviewerModels, reviewerEfforts, { enforceIsolation: true }),
};
}
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 469984735a..4378572431 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -2090,6 +2090,15 @@ describe('claim worktree per-app namespacing', () => {
describe('buildClaimWorkTask reviewer pin', () => {
const app = { id: 'acme', name: 'Acme App', repoPath: '/repos/acme' };
+ it('passes the strict claim policy through the generated provider request', async () => {
+ const { prompt } = await buildClaimWorkTask(app, { reviewers: ['provider:example-reviewer'] });
+ expect(prompt).toContain('kind: "claim-review"');
+ expect(prompt).toContain('toolFree: true');
+ expect(prompt).toContain('a provider without that profile returns REVIEWER_UNSUPPORTED before launch');
+ expect(prompt).toContain('For a required local reviewer, record `REVIEW_STATUS=review-blocked`');
+ expect(prompt).toContain('an optional inconclusive result remains non-blocking');
+ });
+
it('persists the reviewers its prompt names so the pin has one owner', async () => {
const { prompt, taskMetadata } = await buildClaimWorkTask(app);
// The configured claim-work reviewers reach the prompt body...
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 07f8eb85f5..33fbc0f3df 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -932,6 +932,7 @@ export async function buildImprovementTaskDescription({ promptTemplate, app, pro
? appendReviewerEffortBlock(promptReviewers, promptReviewerEfforts, promptReviewerModels)
+ buildLocalReviewerInstructions(promptReviewers, promptReviewerModels, promptReviewerEfforts, {
claimCommentGate: promptTaskType === 'claim-issue',
+ enforceIsolation: promptTaskType.startsWith('claim-issue'),
})
: '');
}
diff --git a/server/services/cosTaskPrompts.js b/server/services/cosTaskPrompts.js
index c110fa5713..32bd983684 100644
--- a/server/services/cosTaskPrompts.js
+++ b/server/services/cosTaskPrompts.js
@@ -106,7 +106,7 @@ export const appendTargetWorkItemBlock = (promptTaskType, ref, excludeLabelsBloc
export const appendReviewerEffortBlock = (reviewers, reviewerEfforts, reviewerModels) =>
appendBlock(buildReviewerEffortNote(reviewers, reviewerEfforts, { reviewerModels }));
-export function buildLocalReviewerInstructions(reviewers, reviewerModels = {}, reviewerEfforts = {}, { claimCommentGate = false } = {}) {
+export function buildLocalReviewerInstructions(reviewers, reviewerModels = {}, reviewerEfforts = {}, { claimCommentGate = false, enforceIsolation = false } = {}) {
const localReviewers = (reviewers || []).filter((reviewer) => isToolFreeReviewer(reviewer));
const cliOutcomeInstructions = appendBlock(buildCliReviewerOutcomeInstructions(reviewers || []));
if (!localReviewers.length) return cliOutcomeInstructions;
@@ -177,11 +177,15 @@ fi
const jqObject = [
...Object.keys(pinned).map((key) => `${key}: $${key}`),
...(isProviderReviewer(reviewer) ? ['inheritDefaults: false'] : []),
+ ...(enforceIsolation ? ['kind: "claim-review"', 'toolFree: true'] : []),
].join(', ');
return `### ${reviewer}\n\n\`\`\`bash\nREVIEW_DIFF=$(mktemp)\nREVIEW_RESPONSE=$(mktemp)\ntrap 'rm -f "$REVIEW_DIFF" "$REVIEW_RESPONSE" "\${REVIEW_RESPONSE}.findings"' EXIT\nif ! { ${diffCommand}; } > "$REVIEW_DIFF"; then\n echo "Unable to resolve the current branch's review diff" >&2\n exit 1\nfi\njq -Rs ${jqArgs} '{ ${jqObject}, diff: . }' < "$REVIEW_DIFF" | node ${reviewScript} > "$REVIEW_RESPONSE"\nif ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; then\n echo "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2\n exit 1\nfi\ncat "\${REVIEW_RESPONSE}.findings"\n\`\`\``;
}).join('\n\n');
- return `${claimCommentGateBlock}\n\n## Local Reviewer Procedure\n\nConfigured provider and local-model reviews run before standalone CLI reviewers. CLI providers can inspect the checkout; API providers review the supplied diff. Run each configured local reviewer in its listed order using the command below. Only a successfully extracted non-empty \`.findings\` string is a review result. Timeout, transport failure, malformed JSON, an error response, or missing/empty findings is INCONCLUSIVE: do not substitute a self-review. For a required local reviewer, record \`REVIEW_STATUS=review-blocked\`, continue to publish the MR/PR, then leave it open and do not merge until the required review completes; an optional inconclusive result remains non-blocking. If every configured reviewer returns a configuration fault and none produces a verdict, report this distinct run-summary state: ${ZERO_REVIEWER_COVERAGE_NOTE} This remains non-blocking when every reviewer is marked \`~opt\`; do not use that wording when any reviewer produces a verdict. Substantive findings, failed tests/build, unpushed fixes, or publication failures still block.\n\n${commands}${cliOutcomeInstructions}`;
+ const accessPolicy = enforceIsolation
+ ? 'Claim reviews send only the supplied diff. Provider CLIs run through a maintained no-tool profile in an isolated directory; a provider without that profile returns REVIEWER_UNSUPPORTED before launch. API and local-model providers receive the diff without tools.'
+ : 'CLI providers can inspect the checkout; API providers review the supplied diff.';
+ return `${claimCommentGateBlock}\n\n## Local Reviewer Procedure\n\nConfigured provider and local-model reviews run before standalone CLI reviewers. ${accessPolicy} Run each configured local reviewer in its listed order using the command below. Only a successfully extracted non-empty \`.findings\` string is a review result. Timeout, transport failure, malformed JSON, an error response, or missing/empty findings is INCONCLUSIVE: do not substitute a self-review. For a required local reviewer, record \`REVIEW_STATUS=review-blocked\`, continue to publish the MR/PR, then leave it open and do not merge until the required review completes; an optional inconclusive result remains non-blocking. If every configured reviewer returns a configuration fault and none produces a verdict, report this distinct run-summary state: ${ZERO_REVIEWER_COVERAGE_NOTE} This remains non-blocking when every reviewer is marked \`~opt\`; do not use that wording when any reviewer produces a verdict. Substantive findings, failed tests/build, unpushed fixes, or publication failures still block.\n\n${commands}${cliOutcomeInstructions}`;
}
/**