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: preserve code review coverage across context-sized batches (#13291)

[._.]/ Adam Eivyfb026f6d90b1
diff --git a/server/lib/README.md b/server/lib/README.md
index 917faa879b..0812e7d946 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -978,3 +978,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `runwayCatalogSnapshot.js` | Shared Runway model catalog capabilities and cached model selection. |
| `runwaySpecialVideoModels.js` | Aleph 2 video-edit and Act-Two character-performance capabilities, schema compatibility and request validation. |
+
+| `codeReviewBatches.js` | File-boundary code-review batching with byte-exact diff hashes, candidate revision, reviewed/remaining file identifiers, bounded calls and one shared wall-clock budget. Preserves validated findings when coverage is incomplete and classifies explicit context-capacity refusals without retaining vendor event streams. |
diff --git a/server/lib/codeReviewBatches.js b/server/lib/codeReviewBatches.js
new file mode 100644
index 0000000000..df4ecdcb9e
--- /dev/null
+++ b/server/lib/codeReviewBatches.js
@@ -0,0 +1,113 @@
+import { createHash } from 'node:crypto';
+
+// A conservative transport bound, not a claim about any model's token window.
+// A file that cannot fit stays explicitly unreviewed; its contents are never cut.
+export const CODE_REVIEW_BATCH_BYTES = 128 * 1024;
+export const CODE_REVIEW_MAX_BATCHES = 64;
+
+const digest = text => createHash('sha256').update(text).digest('hex');
+
+/** Explicit vendor capacity refusals only; never infer an auth/config fault. */
+export function isReviewContextCapacityFailure(result) {
+ // Successful JSON verdicts may legitimately discuss context-capacity bugs.
+ // Classify structured errors or plain vendor refusals, never their quoted text.
+ const plain = value => typeof value === 'string' && !/^[\s]*[\[{`]/.test(value) ? value : null;
+ return [result?.error, result?.error?.message,
+ result?.error || result?.partial ? result?.stderr : null,
+ plain(result?.text), plain(result?.content)].some(value =>
+ typeof value === 'string' && /prompt is too long|context[_ ](?:length[_ ]exceeded|window[_ ]exceeded)|maximum context length|exceeds? (?:the |your )?(?:model.s? )?(?:context|input) (?:window|limit|length)|input (?:is )?too (?:long|large)/i.test(value));
+}
+
+export const reviewContextCapacityFailure = () => ({
+ ok: false,
+ code: 'REVIEW_CONTEXT_CAPACITY',
+ error: 'The selected reviewer refused the input because it exceeds its context capacity.',
+});
+
+/** Keep byte-exact file sections, including quoted/renamed/binary headers.
+ * Headers are opaque git file identifiers, not paths for filesystem access.
+ * A non-git unified diff remains one indivisible section.
+ */
+function diffFiles(diff) {
+ const starts = [...diff.matchAll(/^diff --git .+$/gm)].map(match => match.index);
+ if (!starts.length) return [{ id: 0, file: null, diff, bytes: Buffer.byteLength(diff) }];
+ return starts.map((start, id) => {
+ const section = diff.slice(id === 0 ? 0 : start, starts[id + 1] ?? diff.length);
+ return { id, file: diff.slice(start, diff.indexOf('\n', start) < 0 ? diff.length : diff.indexOf('\n', start)), diff: section, bytes: Buffer.byteLength(section) };
+ });
+}
+
+/** One review round, with one shared wall-clock/call budget and immutable input.
+ * runBatch MUST return a validated verdict; transport success is insufficient.
+ * Optional/required policy and iteration limits remain with the caller.
+ */
+export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, maxBatchBytes = CODE_REVIEW_BATCH_BYTES, maxBatches = CODE_REVIEW_MAX_BATCHES, runBatch }) {
+ const started = Date.now();
+ const files = diffFiles(diff);
+ const queue = [];
+ for (const file of files) {
+ const last = queue.at(-1);
+ if (last && last.bytes + file.bytes <= maxBatchBytes) {
+ last.files.push(file);
+ last.bytes += file.bytes;
+ } else queue.push({ files: [file], bytes: file.bytes });
+ }
+ const reviewed = new Set();
+ const batches = [];
+ const findings = [];
+ let calls = 0;
+ let failure = null;
+ let identity = {};
+ while (queue.length) {
+ const batch = queue.shift();
+ const remainingMs = budgetMs - (Date.now() - started);
+ if (remainingMs <= 0 || calls >= maxBatches) {
+ failure ||= { code: 'REVIEW_BUDGET_EXHAUSTED' };
+ break;
+ }
+ if (batch.bytes > maxBatchBytes) {
+ failure ||= reviewContextCapacityFailure();
+ batches.push({ files: batch.files.map(file => file.id), outcome: 'context_capacity', attempted: false });
+ continue;
+ }
+ const input = batch.files.map(file => file.diff).join('');
+ calls++;
+ const result = await runBatch(input, remainingMs);
+ identity = { ...identity, ...Object.fromEntries(['backend', 'model', 'effort', 'effortUnsupported'].filter(key => result[key] !== undefined).map(key => [key, result[key]])) };
+ const capacity = isReviewContextCapacityFailure(result) || result.code === 'REVIEW_CONTEXT_CAPACITY';
+ batches.push({ files: batch.files.map(file => file.id), diffSha256: digest(input), outcome: result.ok ? result.verdict : capacity ? 'context_capacity' : 'inconclusive', attempted: true });
+ if (capacity && batch.files.length > 1) {
+ const middle = Math.ceil(batch.files.length / 2);
+ queue.unshift(...[batch.files.slice(0, middle), batch.files.slice(middle)].map(parts => ({ files: parts, bytes: parts.reduce((sum, file) => sum + file.bytes, 0) })));
+ continue;
+ }
+ if (!result.ok) {
+ failure ||= capacity ? reviewContextCapacityFailure() : { code: result.code || 'REVIEW_BATCH_FAILED' };
+ // An input-specific capacity refusal does not prevent reviewing other files.
+ // Other failures stop spending, preserving any earlier actionable findings.
+ if (!capacity) break;
+ continue;
+ }
+ for (const file of batch.files) reviewed.add(file.id);
+ if (result.verdict === 'findings') findings.push(result.findings);
+ }
+ const complete = reviewed.size === files.length;
+ const coverage = {
+ headSha, diffSha256: digest(diff), complete,
+ files: files.map(({ id, file, bytes }) => ({ id, file, bytes })),
+ reviewedFiles: [...reviewed], remainingFiles: files.filter(file => !reviewed.has(file.id)).map(file => file.id),
+ batches, calls, maxBatches, budgetMs,
+ };
+ return {
+ ...identity, ok: complete, coverage,
+ ...(findings.length ? { verdict: 'findings', findings: findings.join('\n\n') } : complete ? { verdict: 'clean', findings: 'No findings.' } : {}),
+ ...(!complete ? {
+ code: failure?.code || 'REVIEW_INCOMPLETE',
+ error: failure?.code === 'REVIEW_CONTEXT_CAPACITY'
+ ? 'The selected reviewer could not cover every file within its context capacity; review coverage is incomplete.'
+ : failure?.code === 'REVIEW_BUDGET_EXHAUSTED'
+ ? 'The configured review budget ended before every file received a verdict; review coverage is incomplete.'
+ : 'A review batch returned no usable verdict; review coverage is incomplete.',
+ } : {}),
+ };
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index 0dbd896eac..8e181fcec9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -965,3 +965,5 @@ export * from './runwayCatalogSnapshot.js';
export * from './runwaySpecialVideoModels.js';
export * from './issueClaimEvidence.js';
+
+export * from './codeReviewBatches.js';
diff --git a/server/routes/codeReview.js b/server/routes/codeReview.js
index f66079b31a..3864674d83 100644
--- a/server/routes/codeReview.js
+++ b/server/routes/codeReview.js
@@ -1,3 +1,4 @@
+import { CODE_REVIEW_BATCH_BYTES, CODE_REVIEW_MAX_BATCHES } from '../lib/codeReviewBatches.js'
import { Router } from 'express'
import { z } from 'zod'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
@@ -32,6 +33,9 @@ const localReviewRequestSchema = z.object({
toolFree: z.boolean().optional(),
diff: z.string().min(1, 'diff must be non-empty'),
timeoutMs: z.number().int().positive().max(600000).optional(),
+ headSha: z.string().regex(/^[a-f0-9]{40,64}$/).optional(),
+ maxBatchBytes: z.number().int().min(1024).max(CODE_REVIEW_BATCH_BYTES).optional(),
+ maxBatches: z.number().int().min(1).max(CODE_REVIEW_MAX_BATCHES).optional(),
}).strict().superRefine((body, ctx) => {
// Blank is "not pinned", not "invalid" — same fallback the sibling `model` field
// gets from `body.model || configured` below, and what this route's header
@@ -118,6 +122,9 @@ router.post('/local', asyncHandler(async (req, res) => {
cwd: body.cwd,
toolFree: body.toolFree,
timeoutMs: body.timeoutMs,
+ headSha: body.headSha,
+ maxBatchBytes: body.maxBatchBytes,
+ maxBatches: body.maxBatches,
})
if (!result.ok) {
await reportReviewerFailure(body.backend, result)
@@ -128,7 +135,9 @@ router.post('/local', asyncHandler(async (req, res) => {
throw new ServerError(result.error || 'Code review failed', {
status: isReviewerConfigFault(result.code) ? 400 : 502,
context: { backend: result.backend, model: result.model,
- ...(result.code === 'MALFORMED_REVIEW' ? { code: result.code, diagnostics: result.diagnostics } : {}) }
+ ...(result.code === 'MALFORMED_REVIEW' ? { code: result.code, diagnostics: result.diagnostics } : {}),
+ ...(result.coverage ? { code: result.code, coverage: result.coverage,
+ ...(result.verdict === 'findings' ? { verdict: result.verdict, findings: result.findings } : {}) } : {}) }
})
}
await reportReviewerSuccess(body.backend)
diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.js
index 59bcc3a90e..3f18af18d4 100644
--- a/server/routes/codeReview.test.js
+++ b/server/routes/codeReview.test.js
@@ -299,6 +299,16 @@ describe('POST /api/code-review/local', () => {
expect(codeReviewSvc.reportReviewerSuccess).not.toHaveBeenCalled()
})
+ it('preserves incomplete coverage and actionable findings through the HTTP boundary', async () => {
+ const coverage = { headSha: 'a'.repeat(40), complete: false, reviewedFiles: [0], remainingFiles: [1] }
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({ ok: false, backend: 'ollama', model: 'm', code: 'REVIEW_CONTEXT_CAPACITY', coverage, verdict: 'findings', findings: 'Repair the persisted write.', error: 'Context capacity prevented complete coverage.' })
+ const res = await request(makeApp()).post('/api/code-review/local').send({ backend: 'ollama', model: 'm', diff: 'example', headSha: coverage.headSha, maxBatches: 2, maxBatchBytes: 1024 })
+ expect(res.status).toBe(502)
+ expect(res.body.context).toMatchObject({ code: 'REVIEW_CONTEXT_CAPACITY', coverage, verdict: 'findings', findings: 'Repair the persisted write.' })
+ expect(codeReviewSvc.runLocalCodeReview).toHaveBeenCalledWith(expect.objectContaining({ headSha: coverage.headSha, maxBatches: 2, maxBatchBytes: 1024 }))
+ expect(codeReviewSvc.reportReviewerSuccess).not.toHaveBeenCalled()
+ })
+
it('returns 200 with findings on success', async () => {
codeReviewSvc.runLocalCodeReview.mockResolvedValue({
ok: true,
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 0ccd4b7ddb..bc262ff7cc 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -12,6 +12,7 @@
* has to fit inside the agent's `curl` step.
*/
+import { CODE_REVIEW_BATCH_BYTES, CODE_REVIEW_MAX_BATCHES, runCodeReviewBatches, isReviewContextCapacityFailure, reviewContextCapacityFailure } from '../lib/codeReviewBatches.js'
import { effortLevelsForProvider } from '../lib/providerModels.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readResponseJson } from '../lib/readResponseJson.js'
@@ -103,6 +104,9 @@ export async function reportReviewerFailure(reviewer, error, now = Date.now()) {
const isQuota = explicitReason === 'quota' || (!isTimeoutFailure(message) && isReviewerQuotaFailure(result))
const isExplicitUnavailable = explicitReason === 'unavailable'
+ // Input limits are not provider health, quota, or configuration failures.
+ if (['REVIEW_CONTEXT_CAPACITY', 'REVIEW_BUDGET_EXHAUSTED', 'REVIEW_INCOMPLETE', 'REVIEW_BATCH_FAILED'].includes(code)) return false
+
const isProvider = isProviderReviewer(reviewer)
if (!isConfigFault && !isMalformed && !isQuota && !isExplicitUnavailable && !isProvider) {
@@ -958,20 +962,24 @@ function reviewMessages({ messages, userMessage, systemPromptFor }, workspace) {
: messages
}
-// Resolve the exact record the user selected. Never fall back to the active
-// provider, another account, or a replacement model for a pinned reviewer.
-async function runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit = true, cwd: reviewCwd, isolateFromCheckout = false, allowUnconfined = false }) {
+async function loadReviewProvider(backend) {
const { getProviderById } = await import('./providers.js')
const { getAIToolkitInstance } = await import('../lib/aiToolkitState.js')
const providerId = backend.slice('provider:'.length)
// The auth-independent claim bridge has no server bootstrap. Use the same
// provider-store reader there without starting a server or creating runners.
- let provider = getAIToolkitInstance()
+ return getAIToolkitInstance()
? await getProviderById(providerId)
: await import('../lib/aiToolkit/providers.js').then(async ({ createProviderService }) => {
const { PATHS } = await import('../lib/paths.js')
return createProviderService({ dataDir: PATHS.data }).getProviderById(providerId)
})
+}
+
+// Resolve the exact record the user selected. Never fall back to the active
+// provider, another account, or a replacement model for a pinned reviewer.
+async function runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit = true, cwd: reviewCwd, isolateFromCheckout = false, allowUnconfined = false, providerSnapshot = null }) {
+ let provider = providerSnapshot || await loadReviewProvider(backend)
const transport = await resolveProviderReviewTransport(provider, { allowUnconfined })
// A missing/disabled record is refused here, but an unsupported HARNESS is
// refused at the branch below instead — a pinned effort the provider's model
@@ -1028,6 +1036,7 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
error: 'The headless reviewer required command permission. Use a compatible non-interactive review transport or supported tool-free vendor configuration.',
}
}
+ if (isReviewContextCapacityFailure(result)) return { ...reviewContextCapacityFailure(), backend, model, effort }
if (result.partial) {
const errorMsg = result.stderr?.trim() || result.text?.trim() || 'Reviewer exited before completing its response.'
return {
@@ -1051,6 +1060,7 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
}
}
}
+ if (isReviewContextCapacityFailure(result)) return { ...reviewContextCapacityFailure(), backend, model, effort }
if (result.error || !result.text?.trim()) {
const errorText = result.error || result.stderr || result.text || 'Reviewer returned no content.'
return {
@@ -1069,9 +1079,9 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
return { ok: true, backend, model, effort: effort || provider.effort || null, content: result.text.trim(), finishReason: normalizeReviewFinishReason(result.finishReason), responseLengthChars: result.text.length }
}
-async function runReviewerCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit = true, baseUrl: requestedBaseUrl = null, cwd, isolateFromCheckout = false, allowUnconfined = false, diffSizeBytes = null }) {
+async function runReviewerCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit = true, baseUrl: requestedBaseUrl = null, cwd, isolateFromCheckout = false, allowUnconfined = false, diffSizeBytes = null, providerSnapshot = null }) {
if (isProviderReviewer(backend)) {
- const result = await runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit, cwd, isolateFromCheckout, allowUnconfined })
+ const result = await runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit, cwd, isolateFromCheckout, allowUnconfined, providerSnapshot })
if (result.ok || !Number.isFinite(diffSizeBytes) || !isTimeoutFailure(result.error)) return result
return {
...result,
@@ -1199,18 +1209,54 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
* no such mode never receives it: it runs in a scratch directory instead.
* @param {boolean} [opts.toolFree] - Run a CLI reviewer in a scratch cwd
* instead of `opts.cwd`, whatever its mode.
+ * @param {string} [opts.headSha] - Caller-supplied exact candidate SHA. Coverage
+ * always includes the immutable diff SHA-256, even for legacy callers without a SHA.
+ * @param {number} [opts.maxBatchBytes] - Whole-file input bound, at most 128 KiB.
+ * @param {number} [opts.maxBatches] - Provider-call budget within this one review
+ * round, at most 64. All batches share timeoutMs; reviewer rounds and optional
+ * policy are still enforced by the review-loop caller.
* @param {string} [opts.kind] - `claim-review` always uses a scratch cwd;
* enforced vendor isolation is preferred but is not a transport requirement.
*/
-export async function runLocalCodeReview({ backend, model, diff, effort = null, timeoutMs = undefined, baseUrl = null, cwd = null, toolFree = false, kind = null } = {}) {
+export async function runLocalCodeReview(options = {}) {
+ const { backend, model, diff, effort, timeoutMs, headSha = null, maxBatchBytes = CODE_REVIEW_BATCH_BYTES, maxBatches = CODE_REVIEW_MAX_BATCHES } = options
+ if (!Number.isSafeInteger(maxBatchBytes) || maxBatchBytes < 1024 || maxBatchBytes > CODE_REVIEW_BATCH_BYTES
+ || !Number.isSafeInteger(maxBatches) || maxBatches < 1 || maxBatches > CODE_REVIEW_MAX_BATCHES
+ || (headSha !== null && !/^[a-f0-9]{40,64}$/.test(headSha))) {
+ return { ok: false, error: 'Invalid review batching limits or candidate revision.' }
+ }
+ if (typeof diff !== 'string' || !diff.trim() || !isToolFreeReviewer(backend)) return runSingleCodeReview(options)
+ if (Buffer.byteLength(diff) <= maxBatchBytes) {
+ const result = await runSingleCodeReview(options)
+ if (result.code !== 'REVIEW_CONTEXT_CAPACITY') return result
+ // A refusal on a smaller diff is explicit; do not spend another review round.
+ return runCodeReviewBatches({ diff, headSha, budgetMs: effectiveLocalCodeReviewTimeout(timeoutMs, diff), maxBatchBytes, maxBatches: 1, runBatch: async () => result })
+ }
+ const providerSnapshot = isProviderReviewer(backend) ? await loadReviewProvider(backend) : null
+ let selectedModel = model || providerSnapshot?.defaultModel
+ const selectedEffort = effort ?? providerSnapshot?.effort ?? null
+ const budgetMs = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs
+ : providerSnapshot && (await resolveProviderReviewTransport(providerSnapshot, { allowUnconfined: true })).transport === 'api' ? getRemoteCodeReviewTimeoutMs(providerSnapshot) : getLocalCodeReviewTimeoutMs(diff)
+ const result = await runCodeReviewBatches({ diff, headSha, budgetMs, maxBatchBytes, maxBatches,
+ runBatch: async (batch, remainingMs) => {
+ const result = await runSingleCodeReview({ ...options, model: selectedModel, effort: selectedEffort, diff: batch,
+ timeoutMs: remainingMs, toolFree: true, providerSnapshot })
+ selectedModel ||= result.model
+ return result
+ },
+ })
+ return { backend, model: selectedModel, effort: selectedEffort, ...result }
+}
+
+async function runSingleCodeReview({ backend, model, diff, effort = null, timeoutMs = undefined, baseUrl = null, cwd = null, toolFree = false, kind = null, providerSnapshot = null } = {}) {
if (!isToolFreeReviewer(backend)) {
return { ok: false, error: `Unsupported reviewer backend: ${backend}` }
}
// No model pre-check here: an unpinned model is resolved from what the backend
// is serving inside `runReviewerCompletion`, and a second copy of the
// guard would reject the recoverable case before that ever ran.
- const trimmedDiff = typeof diff === 'string' ? diff.trim() : ''
- if (!trimmedDiff) {
+ const trimmedDiff = typeof diff === 'string' ? diff : ''
+ if (!trimmedDiff.trim()) {
return { ok: false, error: 'Empty diff — nothing to review.' }
}
@@ -1235,9 +1281,11 @@ export async function runLocalCodeReview({ backend, model, diff, effort = null,
cwd,
isolateFromCheckout: kind === 'claim-review' || toolFree,
allowUnconfined: true,
+ providerSnapshot,
systemPromptFor: buildCodeReviewSystemPrompt,
userMessage: { role: 'user', content: `Review this PR diff:\n\n${fence}diff\n${trimmedDiff}\n${fence}` },
})
+ if (isReviewContextCapacityFailure(result)) return { ...reviewContextCapacityFailure(), backend, model, effort }
if (!result.ok) return result
const { verdict, reason } = normalizeCodeReviewVerdict(result.content)
if (!verdict) return {
diff --git a/server/services/codeReview.providers.test.js b/server/services/codeReview.providers.test.js
index 091b59c9d2..ec235d3d73 100644
--- a/server/services/codeReview.providers.test.js
+++ b/server/services/codeReview.providers.test.js
@@ -77,6 +77,27 @@ describe('configured provider reviewers', () => {
expect(resolveReviewerConfig({ reviewerModels: {} }, defaults, defaults.reviewers).reviewerModels).toEqual({});
});
+ it.each([false, true])('batches an exact candidate with one frozen provider configuration and shared budget (optional=%s)', async optional => {
+ const config = resolveReviewerConfig({}, pickCodeReviewDefaults({ codeReview: {
+ reviewers: [backend], optionalReviewers: optional ? [backend] : [], reviewerMaxRounds: { [backend]: 1 },
+ } }), [backend]);
+ const section = name => `diff --git a/${name} b/${name}\n+${'x'.repeat(700)}\n`;
+ const original = { ...provider, timeout: 456789 };
+ getProviderById.mockResolvedValueOnce(original).mockResolvedValue({ ...provider, defaultModel: 'replacement', endpoint: 'https://replacement.example' });
+ const result = await runLocalCodeReview({ backend, maxBatchBytes: 1024, diff: section('a.js') + section('b.js'), headSha: 'b'.repeat(40) });
+ expect(result).toMatchObject({ ok: true, model: 'default-coder', coverage: { headSha: 'b'.repeat(40), complete: true, calls: 2, budgetMs: 456789 } });
+ expect(getProviderById).toHaveBeenCalledTimes(1);
+ expect(callProviderAISimple).toHaveBeenCalledTimes(2);
+ for (const [usedProvider, model, , options] of callProviderAISimple.mock.calls) {
+ expect(usedProvider).toMatchObject({ endpoint: original.endpoint, fallbackProvider: null });
+ expect(usedProvider.timeout).toBeLessThanOrEqual(original.timeout);
+ expect(model).toBe('default-coder');
+ expect(options).toMatchObject({ allowModelRecovery: false });
+ }
+ expect(config.optionalReviewers).toEqual(optional ? [backend] : []);
+ expect(config.reviewerMaxRounds[backend]).toBe(1);
+ });
+
it.each([false, true])('keeps malformed verdicts inconclusive for required/optional provider policy (optional=%s)', async optional => {
const config = resolveReviewerConfig({}, pickCodeReviewDefaults({ codeReview: {
reviewers: [backend], optionalReviewers: optional ? [backend] : [],
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index 845af3ab7e..25bf65baea 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -901,6 +901,94 @@ describe('codeReview helpers', () => {
expect(r.error).toMatch(/Unsupported reviewer backend/)
})
+ // These service-boundary regressions catch lost coverage/findings and extra
+ // provider spending; no test invokes a paid provider or live local daemon.
+ const fileDiff = (name, size = 700) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1 +1 @@\n-old\n+${'x'.repeat(size)}\n`
+ const headSha = 'a'.repeat(40)
+ const batchOptions = { backend: 'lmstudio', model: 'pinned', effort: 'high', maxBatchBytes: 1024, headSha }
+ const findingReply = JSON.stringify({ verdict: 'findings', findings: [{ severity: 'blocking', location: 'a.js:1', outcome: 'Record can be lost.', fix: 'Serialize the write.' }] })
+ const completion = content => mockJsonResponse({ choices: [{ message: { content } }] })
+
+ it('reviews an oversized diff exactly once per whole file under the same model, effort and candidate', async () => {
+ const sections = [fileDiff('a.js'), fileDiff('b.js'), fileDiff('renamed file.js')]
+ global.fetch = vi.fn().mockResolvedValue(completion('No findings.'))
+ const result = await runLocalCodeReview({ ...batchOptions, diff: sections.join('') })
+ expect(result).toMatchObject({ ok: true, model: 'pinned', effort: 'high', verdict: 'clean', coverage: {
+ headSha, complete: true, reviewedFiles: [0, 1, 2], remainingFiles: [], calls: 3,
+ } })
+ expect(result.coverage.files.map(file => file.bytes).reduce((a, b) => a + b)).toBe(Buffer.byteLength(sections.join('')))
+ expect(result.coverage.diffSha256).toMatch(/^[a-f0-9]{64}$/)
+ expect(global.fetch).toHaveBeenCalledTimes(3)
+ global.fetch.mock.calls.forEach(([, init], i) => {
+ const body = JSON.parse(init.body)
+ expect(body).toMatchObject({ model: 'pinned', reasoning_effort: 'high' })
+ expect(body.messages[1].content).toContain(sections[i].trim())
+ expect(body.messages[1].content).not.toContain(sections[(i + 1) % 3].trim())
+ })
+ })
+
+ it('preserves completed findings when a later batch has no validated verdict', async () => {
+ global.fetch = vi.fn().mockResolvedValueOnce(completion(findingReply)).mockResolvedValueOnce(completion(''))
+ const result = await runLocalCodeReview({ ...batchOptions, diff: ['a.js', 'b.js', 'c.js'].map(name => fileDiff(name)).join('') })
+ expect(result).toMatchObject({ ok: false, verdict: 'findings', coverage: { complete: false, reviewedFiles: [0], remainingFiles: [1, 2], calls: 2 } })
+ expect(result.findings).toContain('Record can be lost.')
+ expect(global.fetch).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not grant another iteration budget to each batch or call after the shared deadline', async () => {
+ let now = 100
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
+ try {
+ global.fetch = vi.fn(async () => { now += 101; return completion(findingReply) })
+ const result = await runLocalCodeReview({ ...batchOptions, timeoutMs: 100, diff: fileDiff('a.js') + fileDiff('b.js') })
+ expect(result).toMatchObject({ ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', verdict: 'findings', coverage: { reviewedFiles: [0], remainingFiles: [1], calls: 1, budgetMs: 100 } })
+ expect(global.fetch).toHaveBeenCalledTimes(1)
+ } finally { clock.mockRestore() }
+ global.fetch = vi.fn().mockResolvedValue(completion('No findings.'))
+ const capped = await runLocalCodeReview({ ...batchOptions, maxBatches: 1, diff: fileDiff('a.js') + fileDiff('b.js') })
+ expect(capped).toMatchObject({ ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', coverage: { remainingFiles: [1], calls: 1 } })
+ expect(capped).not.toHaveProperty('verdict')
+ })
+
+ it('accounts for an indivisible oversized file without sending or silently trimming it', async () => {
+ global.fetch = vi.fn().mockResolvedValue(completion('No findings.'))
+ const result = await runLocalCodeReview({ ...batchOptions, diff: fileDiff('huge.js', 2000) + fileDiff('small.js') })
+ expect(result).toMatchObject({ ok: false, code: 'REVIEW_CONTEXT_CAPACITY', coverage: { reviewedFiles: [1], remainingFiles: [0], calls: 1 } })
+ expect(result).not.toHaveProperty('verdict')
+ expect(global.fetch).toHaveBeenCalledTimes(1)
+ expect(JSON.parse(global.fetch.mock.calls[0][1].body).messages[1].content).not.toContain('huge.js')
+ })
+
+ it('subdivides a vendor context refusal only at file boundaries and removes raw diagnostics', async () => {
+ // Two 450-byte files fit the conservative bound together; a third forces
+ // the batching path. The vendor has a smaller effective context window.
+ const sections = ['a.js', 'b.js', 'c.js'].map(name => fileDiff(name, 350))
+ global.fetch = vi.fn()
+ .mockResolvedValueOnce(mockTextResponse('Prompt is too long /private/local/path', 400))
+ .mockResolvedValue(completion('No findings.'))
+ const result = await runLocalCodeReview({ ...batchOptions, diff: sections.join('') })
+ expect(result).toMatchObject({ ok: true, verdict: 'clean', coverage: { complete: true, reviewedFiles: [0, 1, 2], remainingFiles: [], calls: 4 } })
+ expect(result.coverage.batches[0]).toMatchObject({ files: [0, 1], outcome: 'context_capacity' })
+ expect(JSON.stringify(result)).not.toContain('/private/local/path')
+ })
+
+ it('keeps valid findings about context errors actionable rather than classifying their quoted text as refusal', async () => {
+ const content = JSON.stringify({ verdict: 'findings', findings: [{ severity: 'recommended', location: 'review.js:1', outcome: 'Prompt is too long is currently misclassified.', fix: 'Preserve the finding.' }] })
+ global.fetch = vi.fn().mockResolvedValue(completion(content))
+ const result = await runLocalCodeReview({ ...batchOptions, diff: fileDiff('a.js') + fileDiff('b.js') })
+ expect(result).toMatchObject({ ok: true, verdict: 'findings', coverage: { complete: true } })
+ expect(result.findings).toContain('Preserve the finding.')
+ })
+
+ it('identifies a single-file context refusal without treating it as provider health or a clean verdict', async () => {
+ global.fetch = vi.fn().mockResolvedValue(mockTextResponse('Prompt is too long /private/local/path', 400))
+ const result = await runLocalCodeReview({ ...batchOptions, diff: fileDiff('a.js') })
+ expect(result).toMatchObject({ ok: false, code: 'REVIEW_CONTEXT_CAPACITY', coverage: { complete: false, remainingFiles: [0] } })
+ expect(result).not.toHaveProperty('verdict')
+ expect(JSON.stringify(result)).not.toContain('/private/local/path')
+ expect(await reportReviewerFailure('provider:example', result)).toBe(false)
+ })
+
describe('with no model pinned', () => {
// A single-model daemon (MTPLX, llama.cpp — or LM Studio with one model
// loaded) answers "which model?" unambiguously, so an unset