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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: auto-invoke challenge protocol from the review loop + reviewer re-check on resolution (#2471)
Adam Eivy7b50cab8f0c8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0e8d54be52..b5c77e6902 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,8 @@- **A CoS sub-agent can now challenge a wrong reviewer rejection instead of silently fixing it or getting blocked (#2441).** When a review-loop reviewer rejects work — common with noisy local/CLI reviewers — the task can be parked in a new `challenged` status with the worker's case attached (`reason` + optional `evidence` + which `reviewer` is disputed) via `POST /api/cos/tasks/:id/challenge`. Disputes are bounded to exactly one per task (a second is refused with `409 CHALLENGE_EXHAUSTED`), so an agent can't loop forever. Resolving via `POST /api/cos/tasks/:id/challenge/resolve` either **overturns** the rejection (`upheld` → task re-queues to pending) or **escalates** the unresolved dispute to the single PortOS user (`escalated` → task blocked with a `challenge-escalation` reason AND an approval-required arbitration task filed into `COS-TASKS.md`) — surfacing a sustained disagreement rather than quietly fixing or blocking. The full challenge trio (case + resolution + count) rides task metadata, so it round-trips the TASKS.md store, is auditable in the CoS task UI, and federates + converges across sync peers: `challenged` is wired into the claim-aware merge rank (above `in_progress`, below the terminal states), the peer-sync wire status vocab, and a `cosTasks` schema bump (v1→v2) so an older peer gently pauses cos-task sync instead of choking on the unknown status. Partial slice of the Conductor↔CoS challenge protocol — the automatic reviewer re-check and the agent-side auto-invocation land in a follow-up.+- **The challenge protocol now auto-invokes from the review loop and can resolve by an automatic reviewer re-check (#2471, follow-up to #2470).** The two deferred halves of the challenge slice land: (1) the review-loop follow-up prompt (`agentPromptBuilder.js`, both the compact and verbose paths) now teaches the CoS sub-agent the **challenge protocol** — when a reviewer raises a BLOCKING finding the agent has strong, specific evidence is a false positive, it disputes it exactly once via `POST /api/cos/tasks/:id/challenge` (threading in the disputed reviewer) instead of silently "fixing" it or accepting a false block, then re-checks and resolves; (2) `POST /api/cos/tasks/:id/challenge/resolve` now accepts a `recheck: { backend, model?, diff }` object as an alternative to a manual `outcome` — the resolver re-runs the disputed local-LLM reviewer (`lmstudio`/`ollama`) against the current diff and **auto-derives** the verdict from its fresh findings via a new pure `classifyRecheckOutcome()` helper (the `## Blocking` section is the only merge-gating signal, so a surviving blocking finding sustains the rejection → `escalated`, and a clean/`No findings.`/non-blocking result overturns it → `upheld`), so a cheap confirm/overturn pass runs before falling back to user escalation. The schema requires exactly one of `outcome` or `recheck`; an unreachable reviewer or unusable findings returns `502 RECHECK_FAILED` rather than silently escalating. CLI reviewers (claude/codex) are re-run by the follow-up agent itself, which then resolves with an explicit outcome. Richer inline CoS-UI challenge/resolve controls and unifying the one-shot cap with `MAX_TOTAL_SPAWNS` remain deferred.+- **The dashboard's Quick Image widget now offers custom output dimensions and no longer shows a blank size dropdown for off-preset sizes (#2437).** The quick widget had its own inline resolution `<select>` over the universal presets and never gained the **Custom…** option added to the full Image Gen page, so its size picker was inconsistent — and a remix/off-preset size (any width/height not on the preset list) rendered a blank dropdown because no matching `<option>` existed. It now reuses the shared `ResolutionField` control, so selecting **Custom…** reveals Width/Height inputs (any edge 64–3840px, total ≤ 8,294,400px, matching the server's `imageEdgeSchema` + pixel cap), and an off-preset size auto-opens those inputs with the exact dimensions visible instead of collapsing to a blank select. No behavior change to the presets themselves.- **Duplicated child-process stream/discovery helpers converged into shared lib modules (#2392).** Three hand-copied "split a stdout/stderr chunk stream into lines with a carry buffer" implementations (`ytdlpAudioImport.js`, `videoDownload.js`, `hfDownload.js`) had already drifted — only hfDownload's copy flushed the final unterminated line. They now share `server/lib/streamLines.js#createLineReader(onLine, {splitRe?, maxCarry?})`, which carries the partial trailing line across chunks, exposes a `flush()` for the last newline-less line (so the two yt-dlp paths stop dropping it — and skip the flush on cancel so a partial marker can't fire a stray progress frame), clamps the carry buffer against a newline-less runaway stream, and takes a `splitRe: /[\r\n]+/` option for bare-`\r` torch/tqdm progress redraws. The four bare-`\r` progress-splitter siblings (`midiRuntime.js`, `videoGen.js`, `music.js` install-log routes, and `pythonSetup.js#streamSpawn`) are converged onto the same reader with that option, so a progress line split across a chunk boundary is no longer torn. Separately, the inline `which`/`where` PATH probes in `ytdlp.js`, `ffmpeg.js` (×2), `pythonSetup.js`, and voice `bootstrap.js` are replaced by a single `whichFirst(name)` in `server/lib/processEnv.js` (Malloc-stripped env, 5s timeout, first-line result). The vendored `aiToolkit/providers.js` copy is intentionally left alone (self-contained by design). Behavior-preserving; both new helpers are unit-tested.diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex e4f1d791bf..2ead33ead8 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -276,15 +276,35 @@ export const challengeTaskSchema = z.object({reviewer: z.enum(REVIEWER_VALUES).optional(),});-// Resolution of a parked challenge (#2441). `outcome` mirrors CHALLENGE_OUTCOMES-// in server/services/cosChallenge.js (source of truth; a parity test keeps them-// in lockstep). `upheld` overturns the rejection (task → pending); `escalated`-// surfaces the unresolved dispute to the user (task → blocked + arbitration task).+// Automatic re-check request (#2471). Instead of a human `outcome`, the resolver+// re-runs a local-LLM reviewer against the current diff and derives the verdict+// from its fresh findings (classifyRecheckOutcome in cosChallenge.js). `model` is+// optional — falls back to the Code Review Defaults for the backend. Only the+// in-process local reviewers are supported here; CLI reviewers (claude/codex) are+// re-run by the follow-up agent itself, which then resolves with an explicit+// `outcome`.+export const challengeRecheckSchema = z.object({+ backend: z.enum(LOCAL_LLM_REVIEWERS),+ model: z.string().trim().min(1).optional(),+ diff: z.string().min(1).max(500_000),+});++// Resolution of a parked challenge (#2441, #2471). Either the caller supplies an+// explicit `outcome` (manual verdict) OR a `recheck` object (auto re-run a+// reviewer and derive the verdict) — exactly one, never both. `outcome` mirrors+// CHALLENGE_OUTCOMES in server/services/cosChallenge.js (source of truth; a parity+// test keeps them in lockstep). `upheld` overturns the rejection (task → pending);+// `escalated` surfaces the unresolved dispute to the user (task → blocked ++// arbitration task).export const resolveChallengeSchema = z.object({- outcome: z.enum(['upheld', 'escalated']),+ outcome: z.enum(['upheld', 'escalated']).optional(),+ recheck: challengeRecheckSchema.optional(),note: z.string().trim().max(5000).optional(),resolvedBy: z.string().trim().max(200).optional(),-});+}).refine(+ (v) => (v.outcome != null) !== (v.recheck != null),+ { message: 'Provide exactly one of `outcome` or `recheck`.', path: ['outcome'] },+);// =============================================================================// LOOP SCHEMASdiff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex b3d65704b8..6d907c610a 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -335,16 +335,21 @@ router.post('/tasks/:id/challenge', asyncHandler(async (req, res) => {res.json(result);}));-// POST /api/cos/tasks/:id/challenge/resolve - Resolve a parked challenge (#2441).-// `upheld` overturns the rejection (→ pending); `escalated` surfaces the+// POST /api/cos/tasks/:id/challenge/resolve - Resolve a parked challenge (#2441,+// #2471). Provide EITHER an explicit `outcome` (manual verdict) OR a `recheck`+// object (auto re-run a local reviewer against the current diff and derive the+// verdict). `upheld` overturns the rejection (→ pending); `escalated` surfaces the// unresolved dispute to the user (→ blocked + arbitration task).router.post('/tasks/:id/challenge/resolve', asyncHandler(async (req, res) => {const { id } = req.params;- const { outcome, note, resolvedBy } = validateRequest(resolveChallengeSchema, req.body);- const result = await cos.resolveTaskChallenge(id, { outcome, note, resolvedBy });+ const { outcome, recheck, note, resolvedBy } = validateRequest(resolveChallengeSchema, req.body);+ const result = recheck+ ? await cos.resolveTaskChallengeWithRecheck(id, { recheck, resolvedBy })+ : await cos.resolveTaskChallenge(id, { outcome, note, resolvedBy });if (result?.error) {const status = result.code === 'NOT_FOUND' ? 404- : result.code === 'NOT_CHALLENGED' ? 409 : 400;+ : result.code === 'NOT_CHALLENGED' ? 409+ : result.code === 'RECHECK_FAILED' ? 502 : 400;throw new ServerError(result.error, { status, code: result.code || 'RESOLVE_FAILED' });}res.json(result);diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 7b00624b0c..511c02b353 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -378,6 +378,18 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,? 'Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself.': 'The system did NOT pre-request a reviewer because no Copilot review leads the order — you must request/invoke each configured reviewer yourself against the PR diff.';const repeatedCommentsNote = '**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.';+ // Challenge protocol (#2471): auto-invoke the bounded worker↔reviewer dispute+ // from the review loop. When a reviewer's BLOCKING finding is a false positive,+ // the agent disputes it once via POST /challenge instead of silently complying+ // or accepting a false block, then RE-CHECKS (re-run reviewer) to overturn or+ // escalate. One challenge per task (409 CHALLENGE_EXHAUSTED on a second).+ const challengeProtocolNote = [+ '**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:',+ '```bash',+ `curl -sS -X POST http://localhost:5555/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,+ '```',+ 'A `409 CHALLENGE_EXHAUSTED` means the one challenge is spent — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.' + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),+ ].join('\n');const extraNotes = [stopModeNote, applyNote].filter(Boolean);if (verbose) {@@ -405,6 +417,8 @@ ${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}${repeatedCommentsNote}+${challengeProtocolNote}+PR Details:- **URL**: ${prUrl}- **Branch**: \`${prBranch}\`@@ -436,7 +450,9 @@ ${rprBody ? `\n### /do:rpr Reference (full procedure)\n\nWhen following the proc'6. Exit — do NOT run `/do:push` or open a new PR.','','**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',- repeatedCommentsNote+ repeatedCommentsNote,+ '',+ challengeProtocolNote].filter(Boolean).join('\n');}diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 4ee1b903f2..5cbbaa080b 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -492,6 +492,11 @@ describe('buildLightContextPrompt', () => {// (the lone default needs no flag).expect(prompt).toMatch(/Reviewers \(in order\)\*\*: `copilot`/);expect(prompt).not.toMatch(/--review-with/);+ // Challenge protocol (#2471): the auto-invoke instructions + the challenge+ // endpoint for THIS source task must be present in the review-loop section.+ expect(prompt).toMatch(/Challenge protocol/);+ expect(prompt).toMatch(/api\/cos\/tasks\/task-src-1\/challenge/);+ expect(prompt).toMatch(/challenge\/resolve/);});it('threads a non-default reviewer (claude) into the follow-up block via --review-with', () => {diff --git a/server/services/cos.js b/server/services/cos.jsindex 2d4510f31e..38a132e465 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -54,8 +54,8 @@ export { runHealthCheck, getHealthStatus };// backward compat with `import * as cos` and the cos route handlers. The store// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /// dequeueNextTask so the spawn-side logic stays here, not in the store.-import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge } from './cosTaskStore.js';-export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge };+import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck } from './cosTaskStore.js';+export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck };import { ensureInstanceId } from './instances.js';import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';diff --git a/server/services/cosChallenge.js b/server/services/cosChallenge.jsindex 433f0d964f..8f1212290e 100644--- a/server/services/cosChallenge.js+++ b/server/services/cosChallenge.js@@ -100,3 +100,33 @@ export function buildChallengeResolutionPatch({ outcome, note, resolvedBy, now =if (typeof resolvedBy === 'string' && resolvedBy.trim()) resolution.resolvedBy = resolvedBy.trim();return { challengeResolution: resolution };}++/**+ * Classify a re-check reviewer's fresh findings into a resolution outcome (#2471).+ *+ * When a challenge is resolved by re-running a reviewer against the current diff+ * (rather than a human verdict), the merge-gating signal is the reviewer's+ * `## Blocking` section — nits/recommended never block a merge, so only a+ * surviving blocking finding sustains the original rejection. The local-LLM+ * reviewer emits the exact `No findings.` sentinel for a fully clean diff+ * (see codeReview.js CODE_REVIEW_SYSTEM_PROMPT) and a `## Blocking` header only+ * when it still has a blocking objection.+ *+ * - `upheld` → the rejection is overturned (no blocking finding survives) → work re-queues.+ * - `escalated` → a blocking finding still stands → surface the dispute to the user.+ *+ * Returns `null` for unusable input (non-string / empty) so the caller can treat+ * a failed re-check as an error rather than silently escalating (or overturning)+ * on no signal — the sentinel-vs-empty rule, not `.length` truthiness.+ */+export function classifyRecheckOutcome(findings) {+ if (typeof findings !== 'string') return null;+ const trimmed = findings.trim();+ if (!trimmed) return null;+ // Exact clean sentinel — the diff is clean across all severities.+ if (/^no findings\.?$/i.test(trimmed)) return 'upheld';+ // A surviving `## Blocking` section is the only thing that gates a merge.+ if (/^\s*#{1,6}\s*blocking\b/im.test(trimmed)) return 'escalated';+ // Findings present, but nothing under Blocking — nothing gates the merge.+ return 'upheld';+}diff --git a/server/services/cosChallenge.test.js b/server/services/cosChallenge.test.jsindex 152a6429d7..7241397ae6 100644--- a/server/services/cosChallenge.test.js+++ b/server/services/cosChallenge.test.js@@ -7,6 +7,7 @@ import {canChallenge,buildChallengePatch,buildChallengeResolutionPatch,+ classifyRecheckOutcome,} from './cosChallenge.js';import { resolveChallengeSchema } from '../lib/cosValidation.js';@@ -86,6 +87,47 @@ describe('cosChallenge', () => {});});+ describe('classifyRecheckOutcome', () => {+ it('overturns (upheld) on the clean sentinel', () => {+ expect(classifyRecheckOutcome('No findings.')).toBe('upheld');+ expect(classifyRecheckOutcome(' no findings ')).toBe('upheld');+ });++ it('escalates when a blocking section survives', () => {+ expect(classifyRecheckOutcome('## Blocking\n- foo.js:1 leaks a handle')).toBe('escalated');+ expect(classifyRecheckOutcome('Some preamble\n### Blocking\n- bar')).toBe('escalated');+ });++ it('overturns when only non-blocking (recommended/nits) findings remain', () => {+ expect(classifyRecheckOutcome('## Recommended\n- rename x\n\n## Nits\n- spacing')).toBe('upheld');+ });++ it('returns null for unusable input so the caller treats it as a failed re-check', () => {+ expect(classifyRecheckOutcome('')).toBeNull();+ expect(classifyRecheckOutcome(' ')).toBeNull();+ expect(classifyRecheckOutcome(null)).toBeNull();+ expect(classifyRecheckOutcome(undefined)).toBeNull();+ });+ });++ describe('resolveChallengeSchema recheck branch (#2471)', () => {+ it('accepts a recheck object without an explicit outcome', () => {+ expect(resolveChallengeSchema.safeParse({ recheck: { backend: 'ollama', diff: 'd' } }).success).toBe(true);+ });++ it('rejects supplying both outcome and recheck', () => {+ expect(resolveChallengeSchema.safeParse({ outcome: 'upheld', recheck: { backend: 'ollama', diff: 'd' } }).success).toBe(false);+ });++ it('rejects supplying neither outcome nor recheck', () => {+ expect(resolveChallengeSchema.safeParse({ note: 'nothing' }).success).toBe(false);+ });++ it('rejects a non-local reviewer backend in recheck', () => {+ expect(resolveChallengeSchema.safeParse({ recheck: { backend: 'codex', diff: 'd' } }).success).toBe(false);+ });+ });+describe('constants / parity', () => {it('caps disputes at exactly one per task', () => {expect(MAX_CHALLENGES_PER_TASK).toBe(1);diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 0776a2d726..5321a59663 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -21,7 +21,8 @@ import { loadState, withStateLock, ROOT_DIR } from './cosState.js';import { cosEvents } from './cosEvents.js';import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';import { mergeTaskLists } from './cosTaskMerge.js';-import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';+import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';+import { runLocalCodeReview, getCodeReviewDefaults } from './codeReview.js';// First non-empty line of a string. Used by addTask dedup: stored descriptions// are flattened to a single line by generateTasksMarkdown, so the comparison@@ -695,3 +696,47 @@ export async function resolveTaskChallenge(taskId, { outcome, note, resolvedBy }cosEvents.emit('task:challenge-resolved', { taskId, taskType: resolvedType, outcome });return updated;}++/**+ * Resolve a parked challenge by AUTOMATIC reviewer re-check (#2471). Instead of a+ * human verdict, re-run the disputed (or a second) local-LLM reviewer against the+ * current diff and derive the outcome from its fresh findings — a blocking finding+ * that survives sustains the rejection (→ escalated); nothing blocking overturns it+ * (→ upheld). This is the cheap confirm/overturn pass that runs BEFORE falling back+ * to user escalation, closing the gap #2470 left ("this slice resolves manually").+ *+ * Only the in-process local reviewers (`lmstudio`/`ollama`) are re-run here; CLI+ * reviewers are re-run by the follow-up agent itself, which then calls the manual+ * `resolveTaskChallenge` path with an explicit outcome.+ *+ * @returns the updated task, or `{ error, code }` on not-found / not-challenged /+ * RECHECK_FAILED (reviewer unreachable or no usable findings).+ */+export async function resolveTaskChallengeWithRecheck(taskId, { recheck, resolvedBy } = {}, taskType = 'user', { now = Date.now() } = {}) {+ const task = await getTaskById(taskId);+ if (!task) return { error: 'Task not found', code: 'NOT_FOUND' };+ if (task.status !== 'challenged') {+ return { error: 'Task is not under challenge', code: 'NOT_CHALLENGED' };+ }+ const backend = recheck?.backend;+ // Model: explicit override wins, else the Code Review Defaults for this backend.+ let model = recheck?.model;+ if (!model) {+ const defaults = await getCodeReviewDefaults().catch(() => null);+ model = backend === 'ollama' ? defaults?.ollamaModel : defaults?.lmstudioModel;+ }+ console.log(`⚖️ Re-checking challenge on ${taskId} via ${backend}${model ? ` (${model})` : ''}`);+ const review = await runLocalCodeReview({ backend, model, diff: recheck?.diff });+ if (!review?.ok) {+ return { error: `Re-check failed: ${review?.error || 'unknown reviewer error'}`, code: 'RECHECK_FAILED' };+ }+ const outcome = classifyRecheckOutcome(review.findings);+ if (!outcome) {+ return { error: 'Re-check returned no usable findings', code: 'RECHECK_FAILED' };+ }+ const verdict = outcome === 'upheld'+ ? `no blocking findings survived (${backend})`+ : `a blocking finding still stands (${backend})`;+ const note = `Auto re-check by ${backend}${model ? ` (${model})` : ''}: ${verdict}.`;+ return resolveTaskChallenge(taskId, { outcome, note, resolvedBy: resolvedBy || `recheck:${backend}` }, taskType, { now });+}diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 39215d6d40..658f213c64 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -17,7 +17,11 @@ import { dirname, join } from 'path';const mock = vi.hoisted(() => ({files: new Map(),state: null,- events: []+ events: [],+ // Controls the mocked codeReview.js for resolveTaskChallengeWithRecheck (#2471).+ review: { ok: true, findings: 'No findings.' },+ reviewDefaults: { lmstudioModel: 'default-lmstudio', ollamaModel: 'default-ollama' },+ reviewCalls: []}));// existsSync is driven by the in-memory file map; readFileSync stays real so@@ -48,6 +52,11 @@ vi.mock('./cosEvents.js', () => ({cosEvents: { emit: (name, payload) => mock.events.push({ name, payload }) }}));+vi.mock('./codeReview.js', () => ({+ runLocalCodeReview: vi.fn(async (opts) => { mock.reviewCalls.push(opts); return mock.review; }),+ getCodeReviewDefaults: vi.fn(async () => mock.reviewDefaults)+}));+import {firstLine,PRIORITY_VALUES,@@ -63,7 +72,8 @@ import {approveTask,mergePeerTasks,challengeTask,- resolveTaskChallenge+ resolveTaskChallenge,+ resolveTaskChallengeWithRecheck} from './cosTaskStore.js';const USER_FILE = '/root/TASKS.md';@@ -77,6 +87,9 @@ beforeEach(() => {mock.files = new Map();mock.state = baseState();mock.events = [];+ mock.review = { ok: true, findings: 'No findings.' };+ mock.reviewDefaults = { lmstudioModel: 'default-lmstudio', ollamaModel: 'default-ollama' };+ mock.reviewCalls = [];});describe('cosTaskStore.firstLine', () => {@@ -651,3 +664,46 @@ describe('cosTaskStore.challengeTask / resolveTaskChallenge (#2441)', () => {expect(result.code).toBe('INVALID_OUTCOME');});});++describe('cosTaskStore.resolveTaskChallengeWithRecheck (#2471)', () => {+ async function seedChallenged(reviewer = 'ollama') {+ const created = await addTask({ description: 'work under dispute' }, 'user');+ await challengeTask(created.id, { reason: 'reviewer misread the diff', reviewer });+ return created.id;+ }++ it('overturns (→ pending) when the re-check finds nothing blocking', async () => {+ const id = await seedChallenged();+ mock.review = { ok: true, findings: 'No findings.' };+ const resolved = await resolveTaskChallengeWithRecheck(id, { recheck: { backend: 'ollama', diff: 'diff --git a b' } });+ expect(resolved.status).toBe('pending');+ expect(resolved.metadata.challengeResolution.outcome).toBe('upheld');+ expect(resolved.metadata.challengeResolution.note).toContain('ollama');+ // The recheck used the Code Review Defaults model when none was passed.+ expect(mock.reviewCalls[0].model).toBe('default-ollama');+ });++ it('escalates (→ blocked) when the re-check still reports a blocking finding', async () => {+ const id = await seedChallenged('lmstudio');+ mock.review = { ok: true, findings: '## Blocking\n- foo.js:10 still broken' };+ const resolved = await resolveTaskChallengeWithRecheck(id, { recheck: { backend: 'lmstudio', model: 'coder-7b', diff: 'diff' } });+ expect(resolved.status).toBe('blocked');+ expect(resolved.metadata.challengeResolution.outcome).toBe('escalated');+ expect(mock.reviewCalls[0].model).toBe('coder-7b');+ });++ it('returns RECHECK_FAILED when the reviewer is unreachable', async () => {+ const id = await seedChallenged();+ mock.review = { ok: false, error: 'ollama request failed: ECONNREFUSED' };+ const result = await resolveTaskChallengeWithRecheck(id, { recheck: { backend: 'ollama', diff: 'diff' } });+ expect(result.code).toBe('RECHECK_FAILED');+ });++ it('refuses to re-check a task that is not under challenge', async () => {+ const created = await addTask({ description: 'not disputed' }, 'user');+ const result = await resolveTaskChallengeWithRecheck(created.id, { recheck: { backend: 'ollama', diff: 'diff' } });+ expect(result.code).toBe('NOT_CHALLENGED');+ // No wasted reviewer call for a non-challenged task.+ expect(mock.reviewCalls.length).toBe(0);+ });+});