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
address review (codex): reliable fix path + incomplete-review + dry-run gating
[._.]/ Adam Eivy96171b6e10b9
diff --git a/client/src/components/pipeline/SeriesReviewPanel.jsx b/client/src/components/pipeline/SeriesReviewPanel.jsxindex 8e8550a093..7d20d79098 100644--- a/client/src/components/pipeline/SeriesReviewPanel.jsx+++ b/client/src/components/pipeline/SeriesReviewPanel.jsx@@ -13,8 +13,9 @@ import {getPipelineSeriesReviewStatus,cancelPipelineSeriesReview,pipelineSeriesReviewSseUrl,- startPipelineAutopilot,- pipelineAutopilotSseUrl,+ startPipelineSeriesFix,+ getPipelineSeriesFixStatus,+ pipelineSeriesFixSseUrl,getPipelineSeries,listPipelineIssues,} from '../../services/api';@@ -26,8 +27,8 @@ const SEVERITY_STYLES = {};const RUN_ENDED = new Set(['complete', 'canceled', 'error']);-// The autopilot fix run also has a terminal `paused` state (budget / findings).-const FIX_RUN_ENDED = new Set(['complete', 'canceled', 'error', 'paused']);+// The fix run's terminal frames: `rejected` = the cos gate/budget refused it.+const FIX_RUN_ENDED = new Set(['complete', 'canceled', 'error', 'rejected']);// One-line label for a review SSE frame (mirrors AutopilotPanel's frameLabel,// scoped to this flow's steps).@@ -53,15 +54,16 @@ function reviewFrameLabel(f) {}}-// Compact label for the autopilot fix run (the fix path reuses the autopilot-// orchestrator's SSE; we only need a terse "still working" line here).+// Compact label for the per-finding fix run.function fixFrameLabel(f) {if (!f) return 'Working…';switch (f.type) {case 'start': return 'Starting fixes…';- case 'step:start': return 'Fixing…';- case 'paused': return `Paused — ${f.reason || 'needs review'}`;- case 'complete': return 'Fixes complete';+ case 'fix:start': return `Fixing ${f.issueNumber != null ? `#${f.issueNumber} ` : ''}finding…`;+ case 'fix:done': return 'Applied a fix…';+ case 'fix:skip': return 'Skipped an unanchorable finding…';+ case 'complete': return `Fixed ${f.fixed ?? 0} of ${f.total ?? 0}`;+ case 'rejected': return 'Fixing unavailable';case 'canceled': return 'Fixing canceled';case 'error': return `Fixing failed — ${f.error}`;default: return 'Fixing…';@@ -113,7 +115,7 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpdapipelineSeriesReviewSseUrl, [seriesId], { enabled: reviewing },);const { latest: fixLatest } = usePipelineProgress(- pipelineAutopilotSseUrl, [seriesId], { enabled: fixing },+ pipelineSeriesFixSseUrl, [seriesId], { enabled: fixing },);const loadVerdict = useCallback(async () => {@@ -132,6 +134,9 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpdagetPipelineSeriesReviewStatus(seriesId, { silent: true }).then((s) => { if (!canceled && s?.active) setReviewing(true); }).catch(() => null);+ getPipelineSeriesFixStatus(seriesId, { silent: true })+ .then((s) => { if (!canceled && s?.active) { setConfirmDismissed(true); setFixing(true); } })+ .catch(() => null);return () => { canceled = true; };}, [seriesId, loadVerdict]);@@ -150,18 +155,30 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda}}, [reviewing, reviewLatest, loadVerdict]);- // Fix run ended — refresh series + issues, re-run nothing (the user re-reviews- // when ready).+ // Fix run ended — refresh series + issues. The applied fixes changed the+ // manuscript + accepted the findings, so the stored verdict is now stale;+ // clear it so the panel returns to the review action and the user re-reviews+ // to confirm (a fresh review is an explicit LLM action, never auto-fired).useEffect(() => {if (!fixing || !fixLatest || !FIX_RUN_ENDED.has(fixLatest.type)) return;if (fixRunIdRef.current && fixLatest.runId && fixLatest.runId !== fixRunIdRef.current) return;setFixing(false);- getPipelineSeries(seriesId, { silent: true }).then((s) => { if (s) onSeriesUpdateRef.current?.(s); }).catch(() => null);- listPipelineIssues(seriesId, { silent: true }).then((is) => onIssuesUpdateRef.current?.(Array.isArray(is) ? is : [])).catch(() => null);- if (fixLatest.type === 'complete') toast.success('Fixes complete — re-review when ready');- else if (fixLatest.type === 'paused') toast.warning(`Fixing paused — ${fixLatest.reason || 'needs review'}`);- else if (fixLatest.type === 'canceled') toast.success('Fixing canceled');- else toast.error(fixLatest.error || 'Fixing failed');+ if (fixLatest.type === 'complete') {+ getPipelineSeries(seriesId, { silent: true }).then((s) => { if (s) onSeriesUpdateRef.current?.(s); }).catch(() => null);+ listPipelineIssues(seriesId, { silent: true }).then((is) => onIssuesUpdateRef.current?.(Array.isArray(is) ? is : [])).catch(() => null);+ setReview(null);+ setConfirmDismissed(false);+ const fixed = fixLatest.fixed ?? 0;+ toast.success(`Fixed ${fixed} of ${fixLatest.total ?? 0} — re-review to confirm${fixLatest.budgetStopped ? ' (stopped: daily budget reached)' : ''}`);+ } else if (fixLatest.type === 'rejected') {+ toast.error(fixLatest.mode === 'dry-run'+ ? 'Fixing is preview-only right now (CoS auto-run is in dry-run) — set it to execute to apply fixes.'+ : (fixLatest.reason || 'Autonomous fixing is disabled — set the CoS auto-run domain to execute.'));+ } else if (fixLatest.type === 'canceled') {+ toast.success('Fixing canceled');+ } else {+ toast.error(fixLatest.error || 'Fixing failed');+ }}, [fixing, fixLatest, seriesId]);const runReview = useCallback(async () => {@@ -184,23 +201,18 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpdaconst startFix = useCallback(async () => {setFixStarting(true);- // Reuse the existing autopilot orchestrator's revision cycle — no second- // orchestrator. It reuses the cos-domain autonomy gate + budget + SSE.- // Scope to editorial fixing: includeVisual:false so "Fix these issues" never- // silently kicks off comic-art / teaser rendering (large unexpected spend) —- // it iterates the story, not the visual production run.- const res = await startPipelineAutopilot(seriesId, { revisionEnabled: true, includeVisual: false }, { silent: true })- .catch((err) => {- // cos domain off → 409; degrade gracefully (review still works read-only).- toast.error(err?.message || 'Autonomous fixing is disabled — set the CoS auto-run domain to dry-run or execute.');- return null;- });+ // Patch each open finding at its anchor via the per-finding manuscriptFix+ // machinery (server-side, cos-execute-gated + budgeted). Not the autopilot —+ // that only auto-resolves completeness findings, so it can't fix the+ // editorial-check findings this review surfaced.+ const res = await startPipelineSeriesFix(seriesId, {}, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Could not start fixing'); return null; });setFixStarting(false);if (!res) return;fixRunIdRef.current = res.runId || null;setConfirmDismissed(true);setFixing(true);- toast.success('Fixing started — iterating the weakest issues');+ toast.success('Fixing started — patching findings at their anchors');}, [seriesId]);if (!seriesId) return null;@@ -305,6 +317,15 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda) : null}</div>+ {/* Incomplete-review warning — a requested check errored, so this+ verdict is not trustworthy as "ready" (P2). */}+ {review.checksErrored > 0 ? (+ <p className="text-[11px] text-port-warning flex items-center gap-1.5">+ <AlertTriangle size={12} />+ {review.checksErrored} editorial check(s) errored (e.g. a provider was unavailable) — this review is incomplete; re-run before trusting it.+ </p>+ ) : null}+{/* Findings grouped by where they'd be patched */}{groups.length ? (<div className="space-y-2">@@ -357,7 +378,7 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpdatype="button"onClick={startFix}disabled={fixStarting || !canFix}- title={canFix ? 'Iterate the weakest issues via the autopilot revision cycle' : 'Autonomous fixing is disabled — set the CoS auto-run domain to dry-run or execute'}+ title={canFix ? 'Patch each finding at its anchor via the per-finding manuscript fixer' : 'Auto-fixing needs the CoS auto-run domain set to execute'}className="inline-flex items-center gap-1 px-2.5 py-1 rounded text-xs font-medium text-port-accent border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40">{fixStarting ? <Loader2 size={12} className="animate-spin" /> : <Wrench size={12} />} Fix these issues@@ -365,7 +386,9 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda</div>{!canFix ? (<p className="w-full text-[11px] text-gray-500 mt-1">- Auto-fixing is off (CoS auto-run domain is disabled). You can still open each finding above and fix it manually.+ {fixAvail?.mode === 'dry-run'+ ? 'Auto-fixing is preview-only right now (CoS auto-run is in dry-run — it makes no changes). Set it to execute, or open each finding above and fix it manually.'+ : 'Auto-fixing is off (CoS auto-run domain is disabled). You can still open each finding above and fix it manually.'}</p>) : null}</div>diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 1fb6c57951..d3cc770e1a 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -986,6 +986,29 @@ export const cancelPipelineSeriesReview = (seriesId, options = {}) =>export const pipelineSeriesReviewSseUrl = (seriesId) =>`/api/pipeline/series/${encodeURIComponent(seriesId)}/review/progress`;+// Fix the reviewed findings where best patched (anchored per-finding+// manuscriptFix loop, cos-execute-gated server-side). { runId, alreadyRunning,+// sseUrl } — subscribe via pipelineSeriesFixSseUrl, re-fetch the verdict on+// `complete`. Optional { commentIds } scopes the fix to specific findings.+export const startPipelineSeriesFix = (seriesId, opts = {}, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review/fix`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...options,+ });++export const getPipelineSeriesFixStatus = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review/fix/status`, options);++export const cancelPipelineSeriesFix = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review/fix/cancel`, {+ method: 'POST',+ ...options,+ });++export const pipelineSeriesFixSseUrl = (seriesId) =>+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/review/fix/progress`;+// ---- Canon descriptive-integrity (production readiness) ----// Read-only: which canon nouns appear where they'd be drawn but lack a// description (blocking visual production).diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.jsindex 4cab37d7bd..b85f14e238 100644--- a/server/routes/pipeline/editorial.js+++ b/server/routes/pipeline/editorial.js@@ -276,6 +276,45 @@ router.post('/series/:id/review/cancel', asyncHandler(async (req, res) => {res.json({ canceled: seriesReview.cancelSeriesReview(req.params.id) });}));+// Fix the reviewed findings where best patched, via the anchored per-finding+// manuscriptFix machinery (NOT a second orchestrator). Fails closed on the+// cos-domain gate + budget inside the service; progress streams over SSE.+// Optional `commentIds` scopes the fix to specific findings (else all open).+const seriesFixRunSchema = z.object({+ commentIds: z.array(z.string().min(1).max(120)).max(500).optional(),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++router.post('/series/:id/review/fix', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesFixRunSchema, req.body ?? {});+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const result = seriesReview.startSeriesFixRun(req.params.id, {+ commentIds: body.commentIds,+ providerOverride: body.providerId,+ modelOverride: body.model,+ });+ res.json({+ ...result,+ sseUrl: `/api/pipeline/series/${req.params.id}/review/fix/progress`,+ });+}));++router.get('/series/:id/review/fix/progress', (req, res) => {+ const attached = seriesReview.attachFixClient(req.params.id, res);+ if (!attached) {+ throw new ServerError('No active series fix for this series', { status: 404 });+ }+});++router.get('/series/:id/review/fix/status', (req, res) => {+ res.json({ active: seriesReview.isSeriesFixActive(req.params.id) });+});++router.post('/series/:id/review/fix/cancel', asyncHandler(async (req, res) => {+ res.json({ canceled: seriesReview.cancelSeriesFix(req.params.id) });+}));+// ---------------------------------------------------------------------------// Editorial checks (#1284) — registry-driven editorial review.// ---------------------------------------------------------------------------diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.jsindex d3379cb6b9..9d105d89ed 100644--- a/server/routes/pipeline/editorial.test.js+++ b/server/routes/pipeline/editorial.test.js@@ -60,12 +60,17 @@ vi.mock('../../services/pipeline/editorialScore.js', async (importOriginal) => (// param-validation + series-resolve wiring without running the composed passes.const startSeriesReviewRun = vi.fn(() => ({ runId: 'rev-1', alreadyRunning: false }));const getSeriesReview = vi.fn(async () => ({ review: { seriesId: 'ser-1', verdict: 'issues', findings: [] }, fix: { mode: 'execute', canFix: true } }));+const startSeriesFixRun = vi.fn(() => ({ runId: 'fix-1', alreadyRunning: false }));vi.mock('../../services/pipeline/seriesReview.js', () => ({startSeriesReviewRun: (...a) => startSeriesReviewRun(...a),getSeriesReview: (...a) => getSeriesReview(...a),attachClient: vi.fn(() => false),isSeriesReviewActive: vi.fn(() => false),cancelSeriesReview: vi.fn(() => true),+ startSeriesFixRun: (...a) => startSeriesFixRun(...a),+ attachFixClient: vi.fn(() => false),+ isSeriesFixActive: vi.fn(() => false),+ cancelSeriesFix: vi.fn(() => true),}));const editorialRoutes = (await import('./editorial.js')).default;@@ -83,6 +88,7 @@ beforeEach(() => {getVoiceFingerprint.mockClear();startSeriesReviewRun.mockClear();getSeriesReview.mockClear();+ startSeriesFixRun.mockClear();});describe('Holistic "Review this series" (#2664)', () => {@@ -128,6 +134,22 @@ describe('Holistic "Review this series" (#2664)', () => {expect(res.status).toBe(200);expect(res.body.active).toBe(false);});++ it('POST /series/:id/review/fix starts the fix run and returns its SSE url', async () => {+ const res = await request(app)+ .post('/api/pipeline/series/ser-1/review/fix')+ .send({ commentIds: ['mrc-1', 'mrc-2'] });+ expect(res.status).toBe(200);+ expect(res.body.runId).toBe('fix-1');+ expect(res.body.sseUrl).toBe('/api/pipeline/series/ser-1/review/fix/progress');+ expect(startSeriesFixRun).toHaveBeenCalledWith('ser-1', expect.objectContaining({ commentIds: ['mrc-1', 'mrc-2'] }));+ });++ it('POST /series/:id/review/fix 404s for a missing series (no fix started)', async () => {+ const res = await request(app).post('/api/pipeline/series/missing/review/fix').send({});+ expect(res.status).toBe(404);+ expect(startSeriesFixRun).not.toHaveBeenCalled();+ });});describe('GET /api/pipeline/series/:id/voice-fingerprint (#2194)', () => {diff --git a/server/services/pipeline/seriesReview.js b/server/services/pipeline/seriesReview.jsindex edc5a6bd14..3dafea0bb1 100644--- a/server/services/pipeline/seriesReview.js+++ b/server/services/pipeline/seriesReview.js@@ -41,6 +41,7 @@ import { getDomainMode } from '../../lib/domainAutonomy.js';import { readReadinessGate, mergeSeverityWeights } from '../../lib/editorial/index.js';import { loadState } from '../cosState.js';import { getSettings } from '../settings.js';+import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';import { getSeries } from './series.js';import { listIssues } from './issues.js';import { judgeFoundation, DEFAULT_FOUNDATION_THRESHOLD } from './foundationJudge.js';@@ -48,6 +49,7 @@ import { runEditorialChecks } from './editorial/checkRunner.js';import { getSeriesHealth, isOpenFinding, DEFAULT_READINESS_GATE } from './editorialScore.js';import { checkSeriesCanonReadiness } from './canonReadiness.js';import { getReview, seedReviewFromFindings } from './manuscriptReview.js';+import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';// The stage whose provider/model pins the free-text-feedback routing call, so a// user observation about the manuscript is judged on the SAME provider the arc@@ -79,16 +81,19 @@ const SEVERITY_RANK = { high: 0, medium: 1, low: 2 };/*** The single 'ready' | 'issues' verdict. A series is only "ready to move* forward" when the editorial-health readiness gate is clean AND the foundation- * clears the quality threshold AND every drawn noun is described (canon ready).- * Any of those failing → 'issues'. Pure.+ * clears the quality threshold AND every drawn noun is described (canon ready)+ * AND no requested editorial check errored out (an unevaluated check means the+ * review is incomplete — it must never read as 'ready'). Any of those failing →+ * 'issues'. Pure.*/-export function computeReviewVerdict({ health, foundation, canon, threshold = DEFAULT_FOUNDATION_THRESHOLD } = {}) {+export function computeReviewVerdict({ health, foundation, canon, threshold = DEFAULT_FOUNDATION_THRESHOLD, checksErrored = 0 } = {}) {const healthReady = health?.ready === true;const foundationReady = !foundation || !Number.isFinite(foundation.weightedScore)? true: foundation.weightedScore >= threshold;const canonReady = canon?.ready !== false;- return healthReady && foundationReady && canonReady ? 'ready' : 'issues';+ const checksClean = !(Number(checksErrored) > 0);+ return healthReady && foundationReady && canonReady && checksClean ? 'ready' : 'issues';}/**@@ -263,7 +268,13 @@ export async function runSeriesReview(seriesId, {signal,onProgress,}).catch((err) => { console.error(`⚠️ series-review editorial checks failed — series=${seriesId.slice(0, 12)} ${err.message}`); return { findings: [], perCheck: [], canceled: false }; });- onProgress({ type: 'step:complete', kind: 'editorialChecks', findingCount: checks?.findings?.length ?? 0 });+ // A check that threw (e.g. an unavailable LLM provider) is caught internally by+ // the runner and surfaced in perCheck as `{ checkId, error }` — that dimension+ // was never evaluated, so it must block a 'ready' verdict (P2).+ const erroredCheckIds = (Array.isArray(checks?.perCheck) ? checks.perCheck : [])+ .filter((p) => p && p.error).map((p) => p.checkId);+ const checksErrored = erroredCheckIds.length;+ onProgress({ type: 'step:complete', kind: 'editorialChecks', findingCount: checks?.findings?.length ?? 0, errored: checksErrored });if (aborted() || checks?.canceled) return null;// 4. Canon readiness (deterministic — no LLM).@@ -283,7 +294,7 @@ export async function runSeriesReview(seriesId, {const threshold = Number.isFinite(settings?.pipelineEditorialChecks?.foundationThreshold)? settings.pipelineEditorialChecks.foundationThreshold: DEFAULT_FOUNDATION_THRESHOLD;- const verdict = computeReviewVerdict({ health, foundation, canon, threshold });+ const verdict = computeReviewVerdict({ health, foundation, canon, threshold, checksErrored });const result = {seriesId,@@ -302,6 +313,10 @@ export async function runSeriesReview(seriesId, {: null,findings,findingCount: findings.length,+ // Requested checks that errored out this run (never evaluated) — surfaced so+ // the UI can warn that a 'ready'-looking review is actually incomplete (P2).+ checksErrored,+ erroredCheckIds,hadFeedback: !!(feedback && String(feedback).trim()),};await saveSnapshot(result);@@ -334,14 +349,79 @@ export async function getSeriesReview(seriesId) {}/**- * Whether the autopilot-driven fix path can run right now, from the cos-domain- * autonomy mode. `off` → review is read-only, fixing disabled (graceful- * degrade); `dry-run`/`execute` → fixing available.+ * Whether the fix path can run right now, from the cos-domain autonomy mode.+ * Only `execute` applies fixes: `off` disables fixing (review stays read-only),+ * and `dry-run` is a plan-only preview that performs NO writes — so it must NOT+ * report the fix as available (P3), or the UI would claim "fixes complete" after+ * a no-op. The client renders a mode-specific reason for both non-execute cases.*/export async function getFixAvailability() {const state = await loadState().catch(() => ({ config: {} }));const mode = getDomainMode(state?.config, 'cos');- return { mode, canFix: mode !== 'off' };+ return { mode, canFix: mode === 'execute' };+}++// ---------------------------------------------------------------------------+// Fix path (P1) — patch findings where best patched via the EXISTING per-finding+// manuscriptFix machinery, in a simple bulk loop.+//+// This deliberately does NOT start Series Autopilot: the autopilot's editorial+// step only auto-resolves manuscript-COMPLETENESS findings, so the editorial-+// CHECK findings this review surfaces stay open, the editorial-health gate+// pauses on them, and the revision cycle is never reached — a full-autopilot run+// can't actually fix the findings the review flagged. Looping+// generateManuscriptFix → acceptManuscriptFix over each open finding patches it+// at its anchor (the finding's `anchorQuote`/issue/stage), which is precisely+// "fix where best patched." It is not a second orchestrator — it reuses the+// per-finding fixers under the same cos-domain gate + budget the autopilot uses.+// ---------------------------------------------------------------------------++/**+ * Bulk-fix a series' open findings through the anchored per-finding fixer. Fails+ * closed on the cos autonomy gate (only `execute` writes) + the daily budget.+ * Findings whose fix can't be anchored are skipped (never mis-applied). Emits+ * progress via `onProgress`. Returns `{ fixed, skipped, total }` or, when gated+ * off, `{ rejected: true, mode | reason }`.+ */+export async function runSeriesFix(seriesId, { commentIds, providerOverride, modelOverride, signal, onProgress = () => {} } = {}) {+ assertValidSeriesId(seriesId);+ // Autonomy gate — mirror the autopilot start route (fail closed).+ const { mode } = await getFixAvailability();+ if (mode !== 'execute') return { rejected: true, mode };+ const budget = await getDomainBudgetStatus('cos');+ if (!budget.withinBudget) return { rejected: true, reason: `daily cos ${budget.exceeded} budget reached` };++ const review = await getReview(seriesId).catch(() => ({ comments: [] }));+ let open = collectReviewFindings(review.comments);+ if (Array.isArray(commentIds) && commentIds.length) {+ const wanted = new Set(commentIds);+ open = open.filter((f) => wanted.has(f.commentId));+ }++ let fixed = 0;+ let skipped = 0;+ let budgetStopped = false;+ for (const f of open) {+ if (signal?.aborted) break;+ // Re-check the budget before each fix (each generate is one cos action).+ const b = await getDomainBudgetStatus('cos');+ if (!b.withinBudget) { budgetStopped = true; break; }+ onProgress({ type: 'fix:start', commentId: f.commentId, severity: f.severity, issueNumber: f.issueNumber });+ const gen = await generateManuscriptFix(seriesId, { commentId: f.commentId, providerOverride, modelOverride })+ .catch((err) => { console.error(`⚠️ series-fix generate failed — comment=${String(f.commentId).slice(0, 12)} ${err.message}`); return null; });+ await recordDomainUsage('cos', { actions: 1 });+ const fix = gen?.fix;+ const hasEdits = fix && ((Array.isArray(fix.edits) && fix.edits.length > 0) || (fix.find && typeof fix.replace === 'string'));+ if (!hasEdits) { skipped += 1; onProgress({ type: 'fix:skip', commentId: f.commentId, reason: 'no anchored fix' }); continue; }+ // acceptManuscriptFix throws when the anchor can't be located — treat as a+ // skip (never a mis-applied edit).+ const applied = await acceptManuscriptFix(seriesId, { commentId: f.commentId, find: fix.find, replace: fix.replace, edits: fix.edits })+ .catch((err) => { console.error(`⚠️ series-fix apply failed — comment=${String(f.commentId).slice(0, 12)} ${err.message}`); return null; });+ if (applied) { fixed += 1; onProgress({ type: 'fix:done', commentId: f.commentId }); }+ else { skipped += 1; onProgress({ type: 'fix:skip', commentId: f.commentId, reason: 'could not anchor' }); }+ }+ console.log(`🔧 series fix — series=${seriesId.slice(0, 12)} fixed=${fixed} skipped=${skipped}/${open.length}${budgetStopped ? ' (budget-stopped)' : ''}`);+ return { fixed, skipped, total: open.length, budgetStopped };}// ---------------------------------------------------------------------------@@ -380,4 +460,43 @@ export const attachClient = (seriesId, res) => runner.attachClient(seriesId, resexport const isSeriesReviewActive = (seriesId) => runner.isActive(seriesId);export const cancelSeriesReview = (seriesId) => runner.cancel(seriesId);-export const __testing = { runs: runner.runs };+// Separate runner instance for the fix pass, so a review and a fix are tracked+// independently per series (distinct keys are the same seriesId, but distinct+// runner maps — a review SSE and a fix SSE never collide).+const fixRunner = createSseRunner({ logLabel: 'series fix' });++export function startSeriesFixRun(seriesId, options = {}) {+ return fixRunner.start(seriesId, async ({ runId, signal, record, broadcast }) => {+ broadcast({ type: 'start', runId });+ const result = await runSeriesFix(seriesId, {+ commentIds: options.commentIds,+ providerOverride: options.providerOverride,+ modelOverride: options.modelOverride,+ signal,+ onProgress: (event) => broadcast({ ...event, runId }),+ });+ if (result?.rejected) {+ broadcast({ type: 'rejected', runId, mode: result.mode || null, reason: result.reason || null, rejectedAt: nowIso() });+ return;+ }+ if (record.cancelRequested) {+ broadcast({ type: 'canceled', runId, canceledAt: nowIso() });+ return;+ }+ broadcast({+ type: 'complete',+ runId,+ fixed: result.fixed,+ skipped: result.skipped,+ total: result.total,+ budgetStopped: result.budgetStopped === true,+ completedAt: nowIso(),+ });+ });+}++export const attachFixClient = (seriesId, res) => fixRunner.attachClient(seriesId, res);+export const isSeriesFixActive = (seriesId) => fixRunner.isActive(seriesId);+export const cancelSeriesFix = (seriesId) => fixRunner.cancel(seriesId);++export const __testing = { runs: runner.runs, fixRuns: fixRunner.runs };diff --git a/server/services/pipeline/seriesReview.test.js b/server/services/pipeline/seriesReview.test.jsindex 9b9d39423a..2744220869 100644--- a/server/services/pipeline/seriesReview.test.js+++ b/server/services/pipeline/seriesReview.test.js@@ -52,6 +52,24 @@ describe('computeReviewVerdict', () => {canon: { ready: true },})).toBe('ready');});++ it("is 'issues' when a requested check errored (review incomplete, must not read ready)", () => {+ expect(computeReviewVerdict({+ health: { ready: true },+ foundation: { weightedScore: 9 },+ canon: { ready: true },+ checksErrored: 1,+ })).toBe('issues');+ });++ it('is unaffected when zero checks errored', () => {+ expect(computeReviewVerdict({+ health: { ready: true },+ foundation: { weightedScore: 9 },+ canon: { ready: true },+ checksErrored: 0,+ })).toBe('ready');+ });});describe('collectReviewFindings', () => {