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: share review completion budgets and candidate coverage (#13291)

[._.]/ Adam Eivy98cfa8458be3
diff --git a/server/lib/codeReviewBatches.js b/server/lib/codeReviewBatches.js
index df4ecdcb9e..bb1c50b4e9 100644
--- a/server/lib/codeReviewBatches.js
+++ b/server/lib/codeReviewBatches.js
@@ -24,6 +24,15 @@ export const reviewContextCapacityFailure = () => ({
error: 'The selected reviewer refused the input because it exceeds its context capacity.',
});
+/** Reserve one actual completion immediately before dispatch (including retries). */
+export function takeCodeReviewCallBudget(budget, fallbackMs) {
+ if (!budget) return fallbackMs;
+ const remainingMs = budget.deadline - Date.now();
+ if (remainingMs <= 0 || budget.calls >= budget.maxCalls) return null;
+ budget.calls++;
+ return remainingMs;
+}
+
/** 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.
@@ -41,8 +50,8 @@ function diffFiles(diff) {
* 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();
+export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, maxBatchBytes = CODE_REVIEW_BATCH_BYTES, maxBatches = CODE_REVIEW_MAX_BATCHES, startedAt = Date.now(), runBatch }) {
+ const budget = { deadline: startedAt + budgetMs, budgetMs, calls: 0, maxCalls: maxBatches };
const files = diffFiles(diff);
const queue = [];
for (const file of files) {
@@ -55,13 +64,13 @@ export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, max
const reviewed = new Set();
const batches = [];
const findings = [];
- let calls = 0;
+ let cleanFindings = 'No findings.';
let failure = null;
let identity = {};
while (queue.length) {
const batch = queue.shift();
- const remainingMs = budgetMs - (Date.now() - started);
- if (remainingMs <= 0 || calls >= maxBatches) {
+ const remainingMs = budget.deadline - Date.now();
+ if (remainingMs <= 0 || budget.calls >= maxBatches) {
failure ||= { code: 'REVIEW_BUDGET_EXHAUSTED' };
break;
}
@@ -71,8 +80,7 @@ export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, max
continue;
}
const input = batch.files.map(file => file.diff).join('');
- calls++;
- const result = await runBatch(input, remainingMs);
+ const result = await runBatch(input, remainingMs, budget);
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 });
@@ -82,7 +90,7 @@ export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, max
continue;
}
if (!result.ok) {
- failure ||= capacity ? reviewContextCapacityFailure() : { code: result.code || 'REVIEW_BATCH_FAILED' };
+ failure ||= capacity ? reviewContextCapacityFailure() : { code: result.code || 'REVIEW_BATCH_FAILED', error: result.error, diagnostics: result.diagnostics };
// An input-specific capacity refusal does not prevent reviewing other files.
// Other failures stop spending, preserving any earlier actionable findings.
if (!capacity) break;
@@ -90,24 +98,26 @@ export async function runCodeReviewBatches({ diff, headSha = null, budgetMs, max
}
for (const file of batch.files) reviewed.add(file.id);
if (result.verdict === 'findings') findings.push(result.findings);
+ else cleanFindings = 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,
+ batches, calls: budget.calls, maxBatches, budgetMs,
};
return {
...identity, ok: complete, coverage,
- ...(findings.length ? { verdict: 'findings', findings: findings.join('\n\n') } : complete ? { verdict: 'clean', findings: 'No findings.' } : {}),
+ ...(findings.length ? { verdict: 'findings', findings: findings.join('\n\n') } : complete ? { verdict: 'clean', findings: cleanFindings } : {}),
...(!complete ? {
code: failure?.code || 'REVIEW_INCOMPLETE',
+ ...(failure?.diagnostics ? { diagnostics: failure.diagnostics } : {}),
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.',
+ : failure?.error || 'A review batch returned no usable verdict; review coverage is incomplete.',
} : {}),
};
}
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index bc262ff7cc..9d800f91ec 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -12,7 +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 { CODE_REVIEW_BATCH_BYTES, CODE_REVIEW_MAX_BATCHES, runCodeReviewBatches, takeCodeReviewCallBudget, isReviewContextCapacityFailure, reviewContextCapacityFailure } from '../lib/codeReviewBatches.js'
import { effortLevelsForProvider } from '../lib/providerModels.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readResponseJson } from '../lib/readResponseJson.js'
@@ -900,11 +900,11 @@ const SERVED_MODEL_PROBE_TIMEOUT_MS = 5_000
*
* @returns {Promise<{model: string|null, reason: string|null}>}
*/
-async function resolveServedModel(backend, baseUrl) {
+async function resolveServedModel(backend, baseUrl, timeoutMs = SERVED_MODEL_PROBE_TIMEOUT_MS) {
// Back to the `/v1` root the probe wants, through the shared normalizer rather
// than a re-typed suffix — the caller collapsed it to the host root for the
// chat-completions path.
- const probe = await probeOpenAiModels(normalizeOpenAiBaseUrl(baseUrl), { timeoutMs: SERVED_MODEL_PROBE_TIMEOUT_MS })
+ const probe = await probeOpenAiModels(normalizeOpenAiBaseUrl(baseUrl), { timeoutMs })
.catch((err) => ({ reachable: false, models: null, error: err.message }))
if (!probe.reachable) return { model: null, reason: `${backend} is not reachable (${probe.error || 'no response'})` }
if (!Array.isArray(probe.models)) return { model: null, reason: `${backend} did not report which models it is serving` }
@@ -978,7 +978,7 @@ async function loadReviewProvider(backend) {
// 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 }) {
+async function runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit = true, cwd: reviewCwd, isolateFromCheckout = false, allowUnconfined = false, providerSnapshot = null, reviewBudget = 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
@@ -999,6 +999,8 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
if (!timeoutExplicit) budgetMs = getRemoteCodeReviewTimeoutMs(provider)
if (!model) return { ok: false, code: 'NO_MODEL', error: 'Select a model for the reviewer provider.' }
const { callProviderAISimple } = await import('./aiProvider.js')
+ budgetMs = takeCodeReviewCallBudget(reviewBudget, budgetMs)
+ if (budgetMs === null) return { ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', error: 'The configured review budget is exhausted.' }
result = await callProviderAISimple({ ...provider, apiKey: provider.apiKey, timeout: budgetMs, fallbackProvider: null }, model,
prompt, { max_tokens: 8192, allowModelRecovery: false })
} else {
@@ -1020,7 +1022,9 @@ async function runConfiguredProviderCompletion({ backend, model: pinnedModel, me
result = await Promise.resolve().then(async () => {
const { resolveBootstrapEnv } = await import('../lib/credentialBootstrap.js')
const bootstrapEnv = await resolveBootstrapEnv(provider, { safetyProfile })
- return runCliProviderPrompt({ provider, model, prompt, cwd, timeoutMs, bootstrapEnv, exactPins: true,
+ const remainingMs = takeCodeReviewCallBudget(reviewBudget, timeoutMs)
+ if (remainingMs === null) return { error: 'The configured review budget is exhausted.', code: 'REVIEW_BUDGET_EXHAUSTED' }
+ return runCliProviderPrompt({ provider, model, prompt, cwd, timeoutMs: remainingMs, bootstrapEnv, exactPins: true,
safetyProfile, codeReview: true })
}).catch(() => ({ error: 'Reviewer credential setup or execution failed.' }))
.finally(() => isolatedCwd && rm(isolatedCwd, { recursive: true, force: true }))
@@ -1079,13 +1083,13 @@ 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, providerSnapshot = 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, reviewBudget = null }) {
if (isProviderReviewer(backend)) {
- const result = await runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit, cwd, isolateFromCheckout, allowUnconfined, providerSnapshot })
+ const result = await runConfiguredProviderCompletion({ backend, model: pinnedModel, messages, userMessage, systemPromptFor, effort, timeoutMs, timeoutExplicit, cwd, isolateFromCheckout, allowUnconfined, providerSnapshot, reviewBudget })
if (result.ok || !Number.isFinite(diffSizeBytes) || !isTimeoutFailure(result.error)) return result
return {
...result,
- error: localCodeReviewTimeoutError({ backend, timeoutMs: result.timeoutMs ?? timeoutMs, diffSizeBytes, phase: result.stallPhase || 'reviewer-process' }),
+ error: localCodeReviewTimeoutError({ backend, timeoutMs: reviewBudget?.budgetMs ?? result.timeoutMs ?? timeoutMs, diffSizeBytes, phase: result.stallPhase || 'reviewer-process' }),
}
}
if (!isLocalLlmReviewer(backend)) {
@@ -1105,7 +1109,9 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
// by `backend:model`.
let model = pinnedModel
if (!model || typeof model !== 'string') {
- const served = await resolveServedModel(backend, baseUrl)
+ const probeTimeoutMs = reviewBudget ? Math.min(SERVED_MODEL_PROBE_TIMEOUT_MS, reviewBudget.deadline - Date.now()) : SERVED_MODEL_PROBE_TIMEOUT_MS
+ if (probeTimeoutMs <= 0) return { ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', error: 'The configured review budget is exhausted.' }
+ const served = await resolveServedModel(backend, baseUrl, probeTimeoutMs)
if (!served.model) {
// `code` so a caller can tell a config gap from a reviewer that ran and
// failed (a 4xx vs the 502 bucket) without matching on the message text.
@@ -1121,14 +1127,18 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
let effortUnsupported = requestedEffort ? await modelRejectsThinking(backend, model) : false
let resolvedEffort = effortUnsupported ? null : requestedEffort
- let attempt = await sendChatCompletion(baseUrl, { model, messages, timeoutMs }, resolvedEffort)
+ let remainingMs = takeCodeReviewCallBudget(reviewBudget, timeoutMs)
+ if (remainingMs === null) return { ok: false, backend, model, code: 'REVIEW_BUDGET_EXHAUSTED', error: 'The configured review budget is exhausted.' }
+ let attempt = await sendChatCompletion(baseUrl, { model, messages, timeoutMs: remainingMs }, resolvedEffort)
if (!attempt.ok && attempt.status === 400 && resolvedEffort && /does not support thinking/i.test(attempt.text || '')) {
console.log(`⏭️ ${backend} model ${model} ignores reasoning_effort — retried without it`)
thinkingUnsupportedModels.set(thinkingCacheKey(backend, model), true)
resolvedEffort = null
effortUnsupported = true
- attempt = await sendChatCompletion(baseUrl, { model, messages, timeoutMs }, null)
+ remainingMs = takeCodeReviewCallBudget(reviewBudget, timeoutMs)
+ if (remainingMs === null) return { ok: false, backend, model, code: 'REVIEW_BUDGET_EXHAUSTED', error: 'The configured review budget is exhausted.' }
+ attempt = await sendChatCompletion(baseUrl, { model, messages, timeoutMs: remainingMs }, null)
}
if (!attempt.ok) {
@@ -1138,7 +1148,7 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
backend,
model,
error: Number.isFinite(diffSizeBytes) && isTimeoutFailure(attempt.error)
- ? localCodeReviewTimeoutError({ backend, timeoutMs, diffSizeBytes, phase: 'no-response' })
+ ? localCodeReviewTimeoutError({ backend, timeoutMs: reviewBudget?.budgetMs ?? timeoutMs, diffSizeBytes, phase: 'no-response' })
: `${backend} ${attempt.error}`,
}
}
@@ -1154,7 +1164,7 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
backend,
model,
error: Number.isFinite(diffSizeBytes) && isTimeoutFailure(err)
- ? localCodeReviewTimeoutError({ backend, timeoutMs, diffSizeBytes, phase: 'response-body' })
+ ? localCodeReviewTimeoutError({ backend, timeoutMs: reviewBudget?.budgetMs ?? timeoutMs, diffSizeBytes, phase: 'response-body' })
: `${backend} response failed: ${err.message}`,
}
}
@@ -1226,21 +1236,16 @@ export async function runLocalCodeReview(options = {}) {
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 startedAt = Date.now()
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 runCodeReviewBatches({ diff, headSha, budgetMs, maxBatchBytes, maxBatches, startedAt,
+ runBatch: async (batch, remainingMs, reviewBudget) => {
const result = await runSingleCodeReview({ ...options, model: selectedModel, effort: selectedEffort, diff: batch,
- timeoutMs: remainingMs, toolFree: true, providerSnapshot })
+ timeoutMs: remainingMs, toolFree: batch !== diff || Buffer.byteLength(diff) > maxBatchBytes || options.toolFree, providerSnapshot, reviewBudget })
selectedModel ||= result.model
return result
},
@@ -1248,7 +1253,7 @@ export async function runLocalCodeReview(options = {}) {
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 } = {}) {
+async function runSingleCodeReview({ backend, model, diff, effort = null, timeoutMs = undefined, baseUrl = null, cwd = null, toolFree = false, kind = null, providerSnapshot = null, reviewBudget = null } = {}) {
if (!isToolFreeReviewer(backend)) {
return { ok: false, error: `Unsupported reviewer backend: ${backend}` }
}
@@ -1282,10 +1287,11 @@ async function runSingleCodeReview({ backend, model, diff, effort = null, timeou
isolateFromCheckout: kind === 'claim-review' || toolFree,
allowUnconfined: true,
providerSnapshot,
+ reviewBudget,
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 (isReviewContextCapacityFailure(result)) return { ...reviewContextCapacityFailure(), backend, model: result.model || 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 ec235d3d73..86ec628004 100644
--- a/server/services/codeReview.providers.test.js
+++ b/server/services/codeReview.providers.test.js
@@ -233,7 +233,7 @@ describe('configured provider reviewers', () => {
for (const failure of [{ error: `${diagnostic} Synthetic vendor advice follows.` }, { error: 'Synthetic log prelude'.repeat(30), stderr: diagnostic }, { stderr: diagnostic, text: '', partial: false }, { stderr: diagnostic, text: 'incomplete', partial: true }]) {
runCliProviderPrompt.mockResolvedValue({ ...failure, stderr: `${diagnostic}\nsynthetic-private-path-or-credential` });
const result = await runLocalCodeReview({ backend, diff: 'example diff' });
- expect(result).toEqual({ ok: false, code: 'REVIEWER_COMMAND_PERMISSION_DENIED', error: expect.stringContaining('supported tool-free vendor configuration') });
+ expect(result).toMatchObject({ ok: false, code: 'REVIEWER_COMMAND_PERMISSION_DENIED', error: expect.stringContaining('supported tool-free vendor configuration') });
expect(isReviewerConfigFault(result.code)).toBe(true);
expect(JSON.stringify(result)).not.toContain('synthetic-private');
}
@@ -251,6 +251,7 @@ describe('configured provider reviewers', () => {
expect(result.error).toContain(error.includes('timed out') ? 'timed out after 1000ms' : error);
expect(isReviewerConfigFault(result.code)).toBe(false);
expect(result).not.toHaveProperty('findings');
+ expect(result.coverage).toMatchObject({ complete: false, remainingFiles: [0] });
});
// #7720: a bootstrap-credentialed harness has a maintained no-tool recipe and
@@ -367,6 +368,8 @@ describe('configured provider reviewers', () => {
});
it('gives a remote API reviewer its own timeout budget instead of the local diff-size formula', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100);
+ try {
const diff = 'x'.repeat(42 * 1024);
const budgetOf = () => callProviderAISimple.mock.calls.at(-1)[0].timeout;
@@ -384,6 +387,7 @@ describe('configured provider reviewers', () => {
await runLocalCodeReview({ backend, diff, timeoutMs: 5_000 });
expect(budgetOf()).toBe(5_000);
+ } finally { clock.mockRestore(); }
});
it('names the effective remote budget and the diff size in a timeout failure', async () => {
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index 25bf65baea..f19765952e 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -964,7 +964,7 @@ describe('codeReview helpers', () => {
// 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))
+ .mockResolvedValueOnce(mockTextResponse('Prompt is too long /private/local/path', { ok: false, status: 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 } })
@@ -980,8 +980,38 @@ describe('codeReview helpers', () => {
expect(result.findings).toContain('Preserve the finding.')
})
+ it('subdivides a below-threshold refusal without resetting the exact-input or call budget', async () => {
+ const sections = ['a.js', 'b.js'].map(name => fileDiff(name, 200))
+ global.fetch = vi.fn().mockResolvedValueOnce(mockTextResponse('Prompt is too long', { ok: false, status: 400 })).mockResolvedValue(completion('No findings.'))
+ const result = await runLocalCodeReview({ ...batchOptions, maxBatches: 3, diff: sections.join('') })
+ expect(result).toMatchObject({ ok: true, verdict: 'clean', coverage: { headSha, complete: true, reviewedFiles: [0, 1], calls: 3, maxBatches: 3 } })
+ expect(global.fetch).toHaveBeenCalledTimes(3)
+ })
+
+ it('counts the compatibility retry as a completion and charges probe time before dispatch', async () => {
+ global.fetch = vi.fn().mockResolvedValue(mockTextResponse('does not support thinking', { ok: false, status: 400 }))
+ const result = await runLocalCodeReview({ ...batchOptions, model: 'retry-budget-model', maxBatches: 1, diff: fileDiff('a.js', 100) })
+ expect(result).toMatchObject({ ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', coverage: { calls: 1, remainingFiles: [0] } })
+ expect(global.fetch).toHaveBeenCalledTimes(1)
+ let now = 100
+ const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
+ try {
+ global.fetch = vi.fn(async () => { now += 101; return mockJsonResponse({ data: [{ id: 'served-model' }] }) })
+ const probed = await runLocalCodeReview({ backend: 'mtplx', diff: fileDiff('a.js', 100), timeoutMs: 100 })
+ expect(probed).toMatchObject({ ok: false, code: 'REVIEW_BUDGET_EXHAUSTED', coverage: { calls: 0 } })
+ expect(global.fetch).toHaveBeenCalledTimes(1)
+ } finally { clock.mockRestore() }
+ })
+
+ it('binds ordinary single-batch clean results to the supplied candidate and immutable input', async () => {
+ const diff = fileDiff('ordinary.js', 100)
+ const result = await runLocalCodeReview({ ...batchOptions, diff })
+ expect(result).toMatchObject({ ok: true, verdict: 'clean', coverage: { headSha, complete: true, reviewedFiles: [0], remainingFiles: [], calls: 1 } })
+ expect(result.coverage.diffSha256).toMatch(/^[a-f0-9]{64}$/)
+ })
+
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))
+ global.fetch = vi.fn().mockResolvedValue(mockTextResponse('Prompt is too long /private/local/path', { ok: false, status: 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')
@@ -1115,7 +1145,7 @@ describe('codeReview helpers', () => {
})
it('posts to the backend chat-completions endpoint and returns the response content', async () => {
const r = await runLocalCodeReview({ backend: 'ollama', model: 'codellama', diff: 'diff --git a b' })
- expect(r).toEqual({ ok: true, backend: 'ollama', model: 'codellama', effort: null, verdict: 'clean', findings: 'No findings.' })
+ expect(r).toMatchObject({ ok: true, backend: 'ollama', model: 'codellama', effort: null, verdict: 'clean', findings: 'No findings.' })
expect(global.fetch).toHaveBeenCalledTimes(1)
const [url, init] = global.fetch.mock.calls[0]
expect(url).toMatch(/\/v1\/chat\/completions$/)