Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: configure larger-model fallback for oversized PR review issues

[._.]/ Adam Eivya6dcae76e6af
diff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
index a7a954e060..13f39efef1 100644
--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.jsx
@@ -149,14 +149,15 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
)}
<div className="space-y-3">
{stages.map((stage, i) => {
- const stageProvider = providers?.find(p => p.id === stage.providerId);
const role = needsSecurityModelPolicy
? (prReviewerStageRole(stage) || (i === 0 ? 'security' : i === 1 ? 'eligibility' : 'actions'))
: null;
const isSecurityStage = role === 'security';
+ const selection = isSecurityStage ? stage.largeInputFallback || {} : stage;
+ const stageProvider = providers?.find(p => p.id === selection.providerId);
// PR roles reassert the server's no-tool contract even for legacy
// profiles or position-only stages. Other pipelines keep their profile.
- const posture = isSecurityStage ? null : stagePublicReviewPosture(role ? { ...stage, role } : stage);
+ const posture = isSecurityStage ? (stage.largeInputFallback ? PUBLIC_REVIEW_NO_TOOL_POSTURE : null) : stagePublicReviewPosture(role ? { ...stage, role } : stage);
const isNoToolStage = posture === PUBLIC_REVIEW_NO_TOOL_POSTURE;
const isActionsStage = Boolean(posture) && !isNoToolStage;
const eligibleProviders = posture ? eligibleProvidersFor(providers, selectionPolicies[posture]) : null;
@@ -172,13 +173,24 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
}));
const stageModels = posture && localBackend && (isNoToolStage || localStageModels.length > 0)
? localStageModels
- : effortAwareModelOptions(stageProvider, stage.model);
+ : effortAwareModelOptions(stageProvider, selection.model);
const selectionPolicy = posture ? selectionPolicies[posture] : undefined;
- const stageProviderId = stage.providerId || '';
- const stageModel = stage.model || '';
- const stageEffort = stage.effort || '';
+ const stageProviderId = selection.providerId || '';
+ const stageModel = selection.model || '';
+ const stageEffort = selection.effort || '';
- const updateStage = (field, value) => handleStageUpdate(i, field, value || null);
+ const updateStage = (field, value) => {
+ if (!isSecurityStage) return handleStageUpdate(i, field, value || null);
+ const fallback = { ...selection };
+ if (value) fallback[field] = value;
+ else delete fallback[field];
+ if (field === 'providerId') {
+ delete fallback.model;
+ delete fallback.effort;
+ }
+ if (field === 'model' && !effortSurvivingModel(stageProvider, value, fallback.effort)) delete fallback.effort;
+ return handleStageUpdate(i, 'largeInputFallback', fallback);
+ };
return (
<div key={i} className="bg-port-card border border-port-border rounded-lg p-3">
<div className="flex items-center gap-2 mb-3">
@@ -186,7 +198,7 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
{stage.readOnly && (
<span className="text-[10px] px-1 py-0.5 bg-gray-600/30 text-gray-400 rounded">read-only</span>
)}
- {isNoToolStage && (
+ {isNoToolStage && !isSecurityStage && (
<span className="text-[10px] px-1 py-0.5 bg-port-accent/15 text-port-accent rounded">{role === 'actions' ? 'tool-free review' : 'tool-free gate'}</span>
)}
{isActionsStage && (
@@ -207,7 +219,22 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
</p>
</div>
)}
- {!isSecurityStage && (
+ {isSecurityStage && (
+ <div className="my-3">
+ <ToggleSwitch
+ enabled={Boolean(stage.largeInputFallback)}
+ onChange={() => handleStageUpdate(i, 'largeInputFallback', stage.largeInputFallback ? null : {})}
+ disabled={updating}
+ ariaLabel="Enable larger-model fallback for oversized linked issues"
+ size="sm"
+ />
+ <p className="text-xs text-gray-400 mt-2">Larger-model fallback for oversized linked issues. Choose a provider and a model with enough context for the complete PR and issues. Issues over 8,000 characters (up to 65,536 each) use this selection for the eligibility gate and final review. Security screening still runs on all content; flagged or incomplete input stays blocked.</p>
+ {stage.largeInputFallback && (!selection.providerId || !selection.model) && (
+ <p className="text-xs text-port-warning mt-2">Select both a provider and a model to enable fallback runs.</p>
+ )}
+ </div>
+ )}
+ {(!isSecurityStage || stage.largeInputFallback) && (
<ProviderModelSelector
loading={!providersLoaded}
providers={providers || []}
@@ -218,10 +245,10 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
onModelChange={(model) => updateStage('model', model)}
effort={stageEffort}
onEffortChange={(effort) => updateStage('effort', effort)}
- emptyProviderOption={posture
+ emptyProviderOption={isSecurityStage ? 'Select fallback provider' : posture
? 'First eligible provider on this install'
: 'Default (task-level)'}
- emptyModelOption={posture ? 'Use provider default model' : 'Default (task-level)'}
+ emptyModelOption={isSecurityStage ? 'Select larger model' : posture ? 'Use provider default model' : 'Default (task-level)'}
alwaysShowModel
selectionPolicy={selectionPolicy}
disabled={updating}
@@ -235,7 +262,7 @@ export default function PipelineStageConfig({ taskType, config, providers, provi
<Link to="/ai" className="underline hover:text-port-accent">Settings → Providers</Link>.
</p>
)}
- {isNoToolStage && eligibleProviders?.length > 0 && (
+ {isNoToolStage && !isSecurityStage && eligibleProviders?.length > 0 && (
<p className="text-xs text-gray-500 mt-2">
{localModelsLoading
? 'Loading installed local model capability reports…'
diff --git a/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx b/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
index 27bb8913d1..4f0dabdb9b 100644
--- a/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
+++ b/client/src/components/cos/tabs/schedule/PipelineStageConfig.test.jsx
@@ -119,6 +119,17 @@ describe('PipelineStageConfig — pr-reviewer', () => {
expect(screen.queryByText(/applies only the screened patch/)).not.toBeInTheDocument();
});
+ it('configures and clears the larger-model fallback through the standard picker', async () => {
+ const fallbackStages = STAGES.map((stage, index) => index === 0 ? { ...stage, largeInputFallback: { providerId: 'claude-ollama' } } : stage);
+ const onUpdate = renderStages(fallbackStages);
+ fireEvent.change(screen.getAllByLabelText('Model')[0], { target: { value: 'safe-model' } });
+ await waitFor(() => expect(onUpdate).toHaveBeenCalledWith('pr-reviewer', expect.objectContaining({
+ taskMetadata: { pipeline: { stages: [expect.objectContaining({ largeInputFallback: { providerId: 'claude-ollama', model: 'safe-model' } }), ...STAGES.slice(1)] } },
+ })));
+ fireEvent.click(screen.getByRole('switch', { name: 'Enable larger-model fallback for oversized linked issues' }));
+ await waitFor(() => expect(onUpdate).toHaveBeenLastCalledWith('pr-reviewer', { taskMetadata: { pipeline: { stages: STAGES } } }));
+ });
+
it('removes the optional actions stage without changing the mandatory gate', async () => {
const onUpdate = renderStages();
fireEvent.click(screen.getByRole('switch', { name: 'Enable final code review and actions' }));
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 77ecdaf89f..ee2c8da494 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -715,6 +715,12 @@ function safePipelinePrecondition(raw) {
return { [keys[0]]: path };
}
+const largeInputFallbackSchema = z.object({
+ providerId: z.string().trim().min(1).max(200).optional(),
+ model: z.string().trim().min(1).max(200).optional(),
+ effort: z.enum(EFFORT_LEVELS).optional(),
+}).strict();
+
function sanitizePipelineStage(raw) {
if (!isPlainObject(raw)) return null;
const clean = Object.create(null);
@@ -726,6 +732,11 @@ function sanitizePipelineStage(raw) {
if (!value || value.length > maxLength) return null;
clean[field] = value;
}
+ if (Object.hasOwn(raw, 'largeInputFallback') && raw.largeInputFallback !== null) {
+ const fallback = largeInputFallbackSchema.safeParse(raw.largeInputFallback);
+ if (!fallback.success) return null;
+ clean.largeInputFallback = fallback.data;
+ }
if (Object.prototype.hasOwnProperty.call(raw, 'role')) {
if (!PIPELINE_STAGE_ROLES.includes(raw.role)) return null;
clean.role = raw.role;
diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.js
index 56a34a72c6..60eb7faa10 100644
--- a/server/lib/cosValidation.test.js
+++ b/server/lib/cosValidation.test.js
@@ -78,6 +78,12 @@ describe('cosValidation pipeline stage metadata', () => {
precondition: { fileExists: 'screened-input.json' },
};
+ it('round-trips the optional large-input fallback and rejects malformed pins', () => {
+ const largeInputFallback = { providerId: 'large-provider', model: 'large-model', effort: 'high' };
+ expect(sanitizeTaskMetadata({ pipeline: { stages: [{ ...validStage, largeInputFallback }] } }).pipeline.stages[0].largeInputFallback).toEqual(largeInputFallback);
+ expect(sanitizeTaskMetadata({ pipeline: { stages: [{ ...validStage, largeInputFallback: { model: 123 } }] } })).toBeNull();
+ });
+
it('keeps the validated stage contract and drops unknown fields', () => {
expect(sanitizeTaskMetadata({
pipeline: {
diff --git a/server/lib/modelAbuseGuard.js b/server/lib/modelAbuseGuard.js
index 0b67d1670c..fa55c80c9c 100644
--- a/server/lib/modelAbuseGuard.js
+++ b/server/lib/modelAbuseGuard.js
@@ -214,7 +214,11 @@ const normalizeIssueNumbers = (value) => Array.isArray(value)
// prose.
export const LINKED_ISSUE_MAX_COUNT = 10;
export const LINKED_ISSUE_TITLE_MAX_CHARS = 300;
-export const LINKED_ISSUE_BODY_MAX_CHARS = 8_000;
+// Above the standard budget, pr-reviewer requires an explicit larger-model
+// fallback. Normalization retains the bounded full text for screening, snapshots
+// and freshness checks; it must not clip back to the standard budget on read.
+export const LINKED_ISSUE_STANDARD_BODY_MAX_CHARS = 8_000;
+export const LINKED_ISSUE_BODY_MAX_CHARS = 65_536;
/**
* The intent evidence for one PR: the open issues it links, reduced to number,
@@ -237,7 +241,7 @@ export function normalizeLinkedIssues(value) {
number,
title: title.slice(0, LINKED_ISSUE_TITLE_MAX_CHARS),
body: body.slice(0, LINKED_ISSUE_BODY_MAX_CHARS),
- truncated: title.length > LINKED_ISSUE_TITLE_MAX_CHARS || body.length > LINKED_ISSUE_BODY_MAX_CHARS,
+ truncated: raw.truncated === true || title.length > LINKED_ISSUE_TITLE_MAX_CHARS || body.length > LINKED_ISSUE_BODY_MAX_CHARS,
});
}
return issues.sort((a, b) => a.number - b.number).slice(0, LINKED_ISSUE_MAX_COUNT);
diff --git a/server/lib/modelAbuseGuard.test.js b/server/lib/modelAbuseGuard.test.js
index f8c4e052ad..900244d8a7 100644
--- a/server/lib/modelAbuseGuard.test.js
+++ b/server/lib/modelAbuseGuard.test.js
@@ -246,6 +246,14 @@ describe('linked-issue intent evidence', () => {
expect(normalizeLinkedIssues(null)).toEqual([]);
});
+ it('keeps oversized intent intact across normalization and detects edits past the old limit', () => {
+ const issues = [{ number: 101, title: 'Feature', body: `${'x'.repeat(9000)}original` }];
+ expect(linkedIssueIntentContent(normalizeLinkedIssues(issues))).toContain(issues[0].body);
+ expect(linkedIssueIntentFingerprint(issues)).not.toBe(linkedIssueIntentFingerprint([{ ...issues[0], body: `${'x'.repeat(9000)}changed` }]));
+ const clipped = normalizeLinkedIssues([{ ...issues[0], body: 'x'.repeat(LINKED_ISSUE_BODY_MAX_CHARS + 1) }]);
+ expect(normalizeLinkedIssues(clipped)[0].truncated).toBe(true);
+ });
+
it('fingerprints the exact screened text, and reports no evidence as null', () => {
const issues = [{ number: 101, title: 'Crash on empty import', body: 'Importing an empty file throws.' }];
const content = linkedIssueIntentContent(issues);
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 858352f1e6..68feae5fe7 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -663,7 +663,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// upgrades.
// v8 = provider:<id> reviewers. Older peers drop these identities and could
// execute a task without its required review. Gate only task synchronization.
- cosTasks: 8,
+ // v9 = strict large-input PR review fallback pins and complete linked issue
+ // evidence. Older peers may clip that evidence or substitute a smaller model.
+ cosTasks: 9,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index 43ef3483aa..04e1fbd924 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -106,6 +106,10 @@ async function resolvePublicReviewAgentProvider(task, posture) {
return { ok: false, permanent: true, error: resolved.error, providerId: task.metadata?.provider || undefined };
}
const { provider } = resolved;
+ const strictFallback = task.metadata?.pipeline?.securityScan?.usedLargeInputFallback === true;
+ if (strictFallback && !resolved.pinHonored) {
+ return { ok: false, permanent: true, error: 'Configured large-input review fallback provider is unavailable' };
+ }
if (task.metadata?.provider && !resolved.pinHonored) {
emitLog('warn', `Public-review stage provider ${task.metadata.provider} is not eligible for the ${posture} posture — using ${provider.id}`, {
taskId: task.id,
@@ -129,6 +133,9 @@ async function resolvePublicReviewAgentProvider(task, posture) {
// pass-throughs (see its doc comment).
const honorPin = pinnedForThisProvider && modelPinIsOffered(provider, pinnedModel);
const pinRejected = pinnedForThisProvider && !honorPin;
+ if (strictFallback && !honorPin) {
+ return { ok: false, permanent: true, error: 'Configured large-input review fallback model is unavailable' };
+ }
// Strip a pin that will NOT be honored, BEFORE model selection.
// `selectModelForTask` returns `metadata.model` verbatim as its
// highest-priority answer, so leaving it on the task defeats both guards
diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.js
index 6d0213abcb..3f817c39b8 100644
--- a/server/services/agentProviderResolution.test.js
+++ b/server/services/agentProviderResolution.test.js
@@ -395,6 +395,17 @@ describe('resolveAgentProviderAndModel — public-review stages', () => {
expect(getAllProviders).not.toHaveBeenCalled();
});
+ it('never substitutes an unavailable large-input fallback provider or model', async () => {
+ const pipeline = { securityScan: { usedLargeInputFallback: true } };
+ getAllProviders.mockResolvedValue({ providers: [{ ...CLAUDE, models: ['available-model'] }], activeProvider: null });
+ expect(await resolveAgentProviderAndModel(gateTask({ pipeline, provider: 'missing', model: 'large-model' })))
+ .toMatchObject({ ok: false, permanent: true });
+ expect(await resolveAgentProviderAndModel(gateTask({ pipeline, provider: CLAUDE.id, model: 'missing-model' })))
+ .toMatchObject({ ok: false, permanent: true });
+ expect(await resolveAgentProviderAndModel(gateTask({ pipeline, provider: CLAUDE.id, model: 'available-model' })))
+ .toMatchObject({ ok: true, selectedModel: 'available-model' });
+ });
+
it('ignores a stage pin that is not eligible for the posture', async () => {
getAllProviders.mockResolvedValue({ providers: [OPENCODE, CLAUDE], activeProvider: null });
const r = await resolveAgentProviderAndModel(gateTask({ provider: 'opencode' }));
diff --git a/server/services/modelAbuseGuard.materialize.test.js b/server/services/modelAbuseGuard.materialize.test.js
index ce786e85dc..8178a01769 100644
--- a/server/services/modelAbuseGuard.materialize.test.js
+++ b/server/services/modelAbuseGuard.materialize.test.js
@@ -32,6 +32,7 @@ const pullRequests = [{
headSha,
title: 'docs: example change',
body: '',
+ linkedIssues: [{ number: 101, title: 'Complete requirement', body: `${'Acceptance criterion. '.repeat(900)}Final requirement.` }],
// Trailing newline already stripped, as the gh wrapper's stdout trim leaves it.
diff: 'diff --git a/README.md b/README.md\n--- a/README.md\n+++ b/README.md\n@@ -1 +1 @@\n-old\n+example',
}];
@@ -50,6 +51,7 @@ describe('materializing the screened public-review snapshot', () => {
expect(await materializePublicReviewInput({ scanKey, workspacePath: workspace })).toBe(true);
const input = JSON.parse(await readFile(join(workspace, PUBLIC_REVIEW_INPUT_FILENAME), 'utf8'));
expect(input.pullRequests.map((pr) => pr.number)).toEqual([42]);
+ expect(input.pullRequests[0].linkedIssues[0]).toEqual({ ...pullRequests[0].linkedIssues[0], truncated: false });
expect((await stat(join(workspace, PUBLIC_REVIEW_INPUT_FILENAME))).mode & 0o222).toBe(0);
expect(await materializePublicReviewPatches({ scanKey, workspacePath: workspace, allowedPullRequestNumbers: [42] })).toBe(true);
diff --git a/server/services/prReviewerPipeline.js b/server/services/prReviewerPipeline.js
index 0a4144b8b4..f7d6edde66 100644
--- a/server/services/prReviewerPipeline.js
+++ b/server/services/prReviewerPipeline.js
@@ -223,7 +223,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta
const stages = metadata.pipeline?.stages;
const securityStage = stages?.[0];
- const nextStage = stages?.[1];
+ let nextStage = stages?.[1];
if (!securityStage || !nextStage) {
const reason = 'pipeline-misconfigured';
emitLog('warn', `Skipping pr-reviewer for ${app.name}: ${reason} — security pipeline requires an eligibility gate`, { appId: app.id, analysisType: taskType });
@@ -277,6 +277,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta
const scan = await runPrReviewerSecurityScan({
app,
target,
+ largeInputFallback: securityStage.largeInputFallback,
});
const reports = securityScanReports(scan);
if (!scan.ok && !reports.length) {
@@ -285,6 +286,16 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta
return { skipped: true, reason };
}
+ if (scan.ok && scan.usedLargeInputFallback) {
+ // A configured fallback replaces the reasoning stages only. The complete
+ // evidence has already passed the same mandatory security boundary.
+ const fallback = securityStage.largeInputFallback;
+ metadata.pipeline.stages = stages.map((stage, index) => index === 0 ? stage : {
+ ...stage, providerId: fallback.providerId, model: fallback.model, effort: fallback.effort || null,
+ });
+ nextStage = metadata.pipeline.stages[1];
+ }
+
const status = !scan.ok ? 'unavailable' : (scan.passed ? 'passed' : 'findings');
const snapshotWritten = await writePublicReviewInputSnapshot({
scanKey: scan.scanKey || scanKey,
@@ -322,6 +333,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta
previousStageAgentId: null,
previousStageOutput: reviewOutput,
securityScan: {
+ usedLargeInputFallback: scan.usedLargeInputFallback === true,
completed: scan.ok,
status,
code: scan.code || null,
@@ -368,6 +380,7 @@ export async function runPrReviewerSecurityPreflight(taskType, app, metadata, ta
metadata.provider = nextStage.providerId;
metadata.providerId = nextStage.providerId;
}
+ if (scan.usedLargeInputFallback) delete metadata.effort;
if (nextStage.effort) metadata.effort = nextStage.effort;
const nextStageReadOnly = nextStage.readOnly ?? false;
const taskDefaults = metadata.pipeline.taskDefaults || {};
diff --git a/server/services/prReviewerPipeline.test.js b/server/services/prReviewerPipeline.test.js
index 6c0fe1d6d4..b60a26d4ea 100644
--- a/server/services/prReviewerPipeline.test.js
+++ b/server/services/prReviewerPipeline.test.js
@@ -517,6 +517,24 @@ describe('runPrReviewerSecurityPreflight', () => {
expect(securityMock.runPrReviewerSecurityScan).not.toHaveBeenCalled();
});
+ it('uses the configured fallback for both reasoning stages after complete screening', async () => {
+ listed(externalPr(12, HEAD_12));
+ securityMock.runPrReviewerSecurityScan.mockResolvedValue(scanResult({ usedLargeInputFallback: true }));
+ const metadata = preflightMetadata();
+ const fallback = { providerId: 'large-provider', model: 'large-model' };
+ metadata.pipeline.stages[0].largeInputFallback = fallback;
+ metadata.pipeline.stages.push({ role: 'actions', providerId: 'old-provider', model: 'old-model', effort: 'high' });
+ metadata.effort = 'high';
+ await runPrReviewerSecurityPreflight('pr-reviewer', APP, metadata, null, schedule());
+ expect(securityMock.runPrReviewerSecurityScan).toHaveBeenCalledWith(expect.objectContaining({ largeInputFallback: fallback }));
+ expect(metadata).toMatchObject({ provider: fallback.providerId, model: fallback.model });
+ expect(metadata.effort).toBeUndefined();
+ expect(metadata.pipeline.stages.slice(1)).toEqual([
+ expect.objectContaining({ ...fallback, effort: null }), expect.objectContaining({ ...fallback, effort: null }),
+ ]);
+ expect(metadata.pipeline.securityScan.usedLargeInputFallback).toBe(true);
+ });
+
it('writes a synthetic stage-0 result that hands only safe PRs to the gate and applies the next stage as a real hand-off would', async () => {
listed(externalPr(12, HEAD_12), externalPr(13, HEAD_13));
const reports = [report(12, HEAD_12, true), report(13, HEAD_13, false)];
diff --git a/server/services/prReviewerSecurity.js b/server/services/prReviewerSecurity.js
index 2a8877c396..c39e37ee3f 100644
--- a/server/services/prReviewerSecurity.js
+++ b/server/services/prReviewerSecurity.js
@@ -19,6 +19,7 @@ import {
MODEL_ABUSE_GUARD,
MODEL_ABUSE_GUARD_MAX_INPUT_CHARS,
LINKED_ISSUE_MAX_COUNT,
+ LINKED_ISSUE_STANDARD_BODY_MAX_CHARS,
linkedIssueIntentContent,
linkedIssueIntentFingerprint,
modelAbuseContentFingerprint,
@@ -294,12 +295,18 @@ const reportFor = (pr, diff, verdict) => ({
* or malformed verdict fails closed; reports collected before that point remain
* generic and are useful to the human-facing status view only.
*/
-export async function runPrReviewerSecurityScan({ app, target = null } = {}) {
+export async function runPrReviewerSecurityScan({ app, target = null, largeInputFallback = null } = {}) {
const resolvedTarget = target || await listExternalOpenPullRequests(app);
if (!resolvedTarget.ok) return resolvedTarget;
const scanKey = securityScanFingerprint(resolvedTarget);
if (!scanKey) return failure('security-scan-target-unidentifiable');
+ const requiresLargeInputFallback = resolvedTarget.prs.some(pr =>
+ pr.linkedIssues?.some(issue => issue.body.length > LINKED_ISSUE_STANDARD_BODY_MAX_CHARS));
+ if (requiresLargeInputFallback && (!largeInputFallback?.providerId || !largeInputFallback?.model)) {
+ return failure('security-scan-linked-issue-too-large', { scanKey });
+ }
+
const reviewedPrs = [];
const reviewInputs = [];
let hasFindings = false;
@@ -373,6 +380,7 @@ export async function runPrReviewerSecurityScan({ app, target = null } = {}) {
reviewedPrs,
reports: reviewedPrs,
reviewInputs,
+ usedLargeInputFallback: requiresLargeInputFallback,
};
}
diff --git a/server/services/prReviewerSecurity.test.js b/server/services/prReviewerSecurity.test.js
index f91a0fb1be..c52257703d 100644
--- a/server/services/prReviewerSecurity.test.js
+++ b/server/services/prReviewerSecurity.test.js
@@ -103,6 +103,24 @@ describe('pr-reviewer model-abuse preflight', () => {
])
})
+ it('screens and retains complete oversized intent only with an explicit fallback', async () => {
+ const body = `${'Requirement. '.repeat(800)}Final acceptance criterion.`
+ const target = {
+ ok: true, repoFullName: 'example/repo', repoSpec: 'github.com/example/repo', defaultBranch: 'main',
+ prs: [{ number: 12, title: 'Update', body: '', headRefOid: 'a'.repeat(40), linkedIssues: [{ number: 101, title: 'Feature', body }] }],
+ }
+ execGhMock.mockResolvedValue('diff --git a/example b/example\n+change')
+ expect(await runPrReviewerSecurityScan({ target })).toMatchObject({ ok: false, code: 'security-scan-linked-issue-too-large' })
+ expect(runModelAbuseScanMock).not.toHaveBeenCalled()
+ const result = await runPrReviewerSecurityScan({ target, largeInputFallback: { providerId: 'large-provider', model: 'large-model' } })
+ expect(result).toMatchObject({ ok: true, passed: true, usedLargeInputFallback: true })
+ expect(runModelAbuseScanMock.mock.calls[0][0].content).toContain(body)
+ expect(result.reviewInputs[0].linkedIssues[0].body).toBe(body)
+ runModelAbuseScanMock.mockResolvedValue(guardVerdict(false))
+ const blocked = await runPrReviewerSecurityScan({ target, largeInputFallback: { providerId: 'large-provider', model: 'large-model' } })
+ expect(blocked).toMatchObject({ ok: true, passed: false, reviewInputs: [] })
+ })
+
it('refuses linked requirements that were clipped before screening', async () => {
const result = await runPrReviewerSecurityScan({ app, target: {
ok: true, repoFullName: 'example/repo', repoSpec: 'github.com/example/repo', defaultBranch: 'main',