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): fail-closed health gate, snapshot every run, shared openBlockers, per-issue drill-down, stale-response guard, delta needs 2 points (#1316)
Adam Eivy230548450290
diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsxindex ab1e1bef34..99819ed842 100644--- a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx@@ -14,7 +14,7 @@* convergence gate too). Refetches when `refreshKey` changes (e.g. after a run* completes), so the score reflects the freshest review.*/-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { Activity, Loader2, TrendingUp, TrendingDown } from 'lucide-react';import toast from '../../ui/Toast';import { getEditorialHealth, setEditorialReadinessGate } from '../../../services/api';@@ -62,16 +62,24 @@ export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {const [health, setHealth] = useState(null);const [loading, setLoading] = useState(false);const [savingGate, setSavingGate] = useState(false);+ const [showIssues, setShowIssues] = useState(false);++ // Guard against a stale response: switching series (or a fast refresh) can let+ // an older fetch resolve last and render the wrong series' health. Only the+ // latest requested series is allowed to write state.+ const activeSeriesRef = useRef(seriesId);+ useEffect(() => { activeSeriesRef.current = seriesId; }, [seriesId]);const load = useCallback((id) => {if (!id) { setHealth(null); return; }setLoading(true);// getEditorialHealth has no silent option here — request() toasts on failure;- // just clear + swallow so the panel degrades to its empty state.+ // just clear + swallow so the panel degrades to its empty state. Every state+ // write is gated on the series still being current (stale-response race).getEditorialHealth(id)- .then((h) => setHealth(h && typeof h === 'object' ? h : null))- .catch(() => setHealth(null))- .finally(() => setLoading(false));+ .then((h) => { if (activeSeriesRef.current === id) setHealth(h && typeof h === 'object' ? h : null); })+ .catch(() => { if (activeSeriesRef.current === id) setHealth(null); })+ .finally(() => { if (activeSeriesRef.current === id) setLoading(false); });}, []);useEffect(() => { load(seriesId); }, [seriesId, refreshKey, load]);@@ -100,7 +108,16 @@ export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {const delta = deltaDisplay(health.trend?.delta);const regressions = Array.isArray(health.trend?.regressions) ? health.trend.regressions : [];const categories = orderedCategories(health.openByCategory);- const hasTrend = (health.trend?.points || []).length > 0;+ const points = health.trend?.points || [];+ const hasTrend = points.length > 0;+ // The delta compares the two most recent revisions — only meaningful with ≥2+ // points (a single revision has nothing to compare against).+ const hasDelta = points.length >= 2;+ // Per-issue drill-down (#1316): issues carrying at least one open finding,+ // worst-scoring first. The series-scoped (null issueNumber) bucket renders last.+ const issueRows = (Array.isArray(health.perIssue) ? health.perIssue : [])+ .filter((p) => p.open > 0)+ .sort((a, b) => a.score - b.score);return (<section className="space-y-3 rounded-lg border border-port-border bg-port-card p-3">@@ -121,7 +138,7 @@ export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {<div className="flex items-baseline gap-2"><span className={`text-3xl font-bold ${band.tone}`}>{health.score}</span><span className="text-xs text-gray-500">/ 100 · {band.label}</span>- {hasTrend ? (+ {hasDelta ? (<span className={`flex items-center gap-0.5 text-xs ${delta.tone}`} title="Change since the previous revision">{delta.text}</span>@@ -180,11 +197,43 @@ export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {) : null}{/* A clean run that improved on the prior revision gets a positive note. */}- {!regressions.length && hasTrend && (health.trend?.delta || 0) > 0 ? (+ {!regressions.length && hasDelta && (health.trend?.delta || 0) > 0 ? (<p className="flex items-center gap-1 text-[11px] text-port-success"><TrendingDown size={11} className="rotate-180" /> No category regressed since the previous revision.</p>) : null}++ {/* Per-issue drill-down — which issues carry the open findings. */}+ {issueRows.length ? (+ <div className="border-t border-port-border/60 pt-2.5">+ <button+ type="button"+ onClick={() => setShowIssues((v) => !v)}+ className="text-[10px] uppercase tracking-wide text-gray-500 hover:text-gray-300"+ aria-expanded={showIssues}+ >+ By issue ({issueRows.length}) {showIssues ? '▾' : '▸'}+ </button>+ {showIssues ? (+ <ul className="mt-1.5 space-y-1">+ {issueRows.map((p) => {+ const b = scoreBand(p.score);+ return (+ <li key={p.issueNumber ?? 'series'} className="flex items-center justify-between gap-2 text-[11px]">+ <span className="text-gray-300">+ {p.issueNumber != null ? `Issue ${p.issueNumber}` : 'Series-wide'}+ </span>+ <span className="flex items-center gap-2 text-gray-500">+ <SeverityBreakdown openBySeverity={p.openBySeverity} />+ <span className={`font-medium ${b.tone}`}>{p.score}</span>+ </span>+ </li>+ );+ })}+ </ul>+ ) : null}+ </div>+ ) : null}</section>);}diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsxindex 185e98e111..b9b0d9bee2 100644--- a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx@@ -82,4 +82,32 @@ describe('EditorialHealthPanel', () => {rerender(<EditorialHealthPanel seriesId="ser-1" refreshKey={1} />);await waitFor(() => expect(getEditorialHealth).toHaveBeenCalledTimes(2));});++ it('hides the delta when there is only one trend point (nothing to compare)', async () => {+ getEditorialHealth.mockResolvedValue(health({+ trend: { points: [{ score: 83 }], regressions: [], delta: 0 },+ }));+ render(<EditorialHealthPanel seriesId="ser-1" />);+ await screen.findByText('83');+ // The "+0/0" delta chip should not render for a single revision.+ expect(screen.queryByTitle('Change since the previous revision')).toBeNull();+ });++ it('renders the per-issue drill-down (issues with open findings, worst first)', async () => {+ getEditorialHealth.mockResolvedValue(health({+ perIssue: [+ { issueNumber: 1, score: 95, open: 1, openBySeverity: { high: 0, medium: 0, low: 1 } },+ { issueNumber: 2, score: 60, open: 2, openBySeverity: { high: 1, medium: 0, low: 0 } },+ { issueNumber: 3, score: 100, open: 0, openBySeverity: { high: 0, medium: 0, low: 0 } },+ ],+ }));+ render(<EditorialHealthPanel seriesId="ser-1" />);+ await screen.findByText('83');+ // Two issues carry open findings (issue 3 is clean → excluded); expand.+ const toggle = screen.getByText(/By issue \(2\)/);+ fireEvent.click(toggle);+ expect(await screen.findByText('Issue 2')).toBeTruthy();+ expect(screen.getByText('Issue 1')).toBeTruthy();+ expect(screen.queryByText('Issue 3')).toBeNull();+ });});diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 651338f6f9..9ff977849b 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -417,14 +417,19 @@ export async function runEditorialChecks(seriesId, options = {}) {// dismissed findings suppressed per-check. Skip entirely on cancellation — a// canceled run emits a `canceled` terminal event and must not mutate the// review with partial findings collected before the abort.- if (findings.length && !canceled) {- const review = await seedReviewFromFindings(seriesId, findings, { runId, mode: 'merge' });- // Record a revision-trend snapshot (#1316): this run is a revision boundary,- // so snapshot the post-seed open-finding counts for the health-trend ledger.- // Pass the just-merged comments so the ledger doesn't re-read the review file.- // Best-effort — a ledger write must never fail the check run (it's telemetry).+ if (!canceled) {+ // Seed only when there are findings (merge dedups); but record a revision-trend+ // snapshot for EVERY non-canceled run (#1316) — a run is a revision boundary,+ // and a CLEAN run (0 new findings, or fixes that closed prior ones) is exactly+ // the improving point the trend should capture. When findings were seeded we+ // pass the just-merged comments (no re-read); otherwise recordTrendSnapshot+ // reads the current review itself. Best-effort — a ledger write must never+ // fail the check run (it's telemetry).+ const review = findings.length+ ? await seedReviewFromFindings(seriesId, findings, { runId, mode: 'merge' })+ : null;const gate = readReadinessGate(settings) || undefined;- await recordTrendSnapshot(seriesId, { runId, gate, comments: review.comments }).catch((err) => {+ await recordTrendSnapshot(seriesId, { runId, gate, comments: review?.comments }).catch((err) => {console.error(`⚠️ editorial trend snapshot failed — series=${String(seriesId).slice(0, 12)} ${err.message}`);});}diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.jsindex 486a654c3b..b083a7b558 100644--- a/server/services/pipeline/editorialScore.js+++ b/server/services/pipeline/editorialScore.js@@ -97,6 +97,29 @@ export function scoreFromOpen(openBySeverity) {return Math.max(0, Math.min(100, 100 - penalty));}+// A finding is OPEN unless explicitly accepted (fixed) or dismissed (waived) —+// the store defaults an unknown/absent status to 'open', so anything else counts+// as a live blocker (can't under-count). Shared so the scorer and the autopilot+// gate's residual filter agree on what "open" means.+export const isOpenFinding = (comment) =>+ comment?.status !== 'accepted' && comment?.status !== 'dismissed';++/**+ * The OPEN findings that block a given readiness gate — the residual a caller+ * (e.g. the autopilot gate) surfaces when a series isn't "ready". Mirrors+ * `computeHealth`'s open-detection + severity normalization exactly so the+ * blocker list can never disagree with the `ready` verdict. Returns [] for the+ * 'none' gate (nothing blocks).+ */+export function openBlockers(comments, gate = DEFAULT_READINESS_GATE) {+ const g = resolveReadinessGate(gate);+ if (g === 'none') return [];+ const blocking = g === 'noOpenHighOrMedium' ? new Set(['high', 'medium']) : new Set(['high']);+ return (Array.isArray(comments) ? comments : []).filter(+ (c) => c && typeof c === 'object' && isOpenFinding(c) && blocking.has(normalizeSeverity(c.severity)),+ );+}+// Tally one finding into an accumulator. OPEN findings drive the score +// breakdowns; accepted/dismissed are counted only for context (resolved totals).function tally(acc, comment) {@@ -104,8 +127,8 @@ function tally(acc, comment) {const status = comment?.status;if (status === 'accepted') { acc.accepted += 1; return; }if (status === 'dismissed') { acc.dismissed += 1; return; }- // Treat any non-accepted/dismissed status (incl. legacy/absent) as open — the- // store defaults unknown statuses to 'open', so this can't under-count blockers.+ // Any non-accepted/dismissed status (incl. legacy/absent) is open — see+ // isOpenFinding; this can't under-count blockers.const sev = normalizeSeverity(comment?.severity);acc.open += 1;acc.openBySeverity[sev] += 1;diff --git a/server/services/pipeline/editorialScore.test.js b/server/services/pipeline/editorialScore.test.jsindex 95de3a0400..42cf8f4bfe 100644--- a/server/services/pipeline/editorialScore.test.js+++ b/server/services/pipeline/editorialScore.test.js@@ -5,6 +5,8 @@ import {scoreFromOpen,isReadyUnderGate,resolveReadinessGate,+ isOpenFinding,+ openBlockers,computeHealth,computeTrend,__testing,@@ -55,6 +57,38 @@ describe('readiness gate', () => {});});+describe('isOpenFinding / openBlockers', () => {+ it('treats anything but accepted/dismissed as open', () => {+ expect(isOpenFinding({ status: 'open' })).toBe(true);+ expect(isOpenFinding({})).toBe(true); // absent status+ expect(isOpenFinding({ status: 'accepted' })).toBe(false);+ expect(isOpenFinding({ status: 'dismissed' })).toBe(false);+ });++ it('openBlockers matches computeHealth open-detection + severity normalization', () => {+ const comments = [+ { severity: 'high', issueNumber: 1 }, // no status → open+ open('medium', { issueNumber: 1 }),+ open('low', { issueNumber: 2 }),+ { status: 'accepted', severity: 'high' },+ { status: 'open', severity: 'weird' }, // unknown → normalizes to medium+ ];+ // noOpenHigh: only the high (and nothing else) blocks.+ expect(openBlockers(comments, 'noOpenHigh').map((c) => c.severity)).toEqual(['high']);+ // noOpenHighOrMedium: high + both mediums (incl. the normalized 'weird').+ expect(openBlockers(comments, 'noOpenHighOrMedium')).toHaveLength(3);+ // none: nothing blocks.+ expect(openBlockers(comments, 'none')).toEqual([]);+ });++ it('the blocker list can never disagree with computeHealth.ready', () => {+ const comments = [open('high', { issueNumber: 1 })];+ const health = computeHealth(comments, 'noOpenHigh');+ const blockers = openBlockers(comments, 'noOpenHigh');+ expect(health.ready).toBe(blockers.length === 0);+ });+});+describe('computeHealth', () => {it('rolls up open findings, ignoring accepted/dismissed in the score', () => {const comments = [diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 0dc0b42851..ebc8476536 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -91,7 +91,7 @@ import * as volumeBeatsRunner from './volumeBeatsRunner.js';import * as autoRunner from './autoRunner.js';import { seedReviewFromFindings, getReview } from './manuscriptReview.js';import { runEditorialChecks, buildEditorialCheckPlan } from './editorial/checkRunner.js';-import { computeHealth } from './editorialScore.js';+import { computeHealth, openBlockers } from './editorialScore.js';import { getSettings } from '../settings.js';import { readReadinessGate } from '../../lib/editorial/index.js';import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';@@ -670,8 +670,13 @@ async function runEditorialHealthGate(sId, record) {if (record.cancelRequested) return { canceled: true };const settings = await getSettings().catch(() => null);const gate = readReadinessGate(settings) || undefined;- const review = await getReview(sId).catch(() => ({ comments: [] }));- const health = computeHealth(review.comments || [], gate);+ // Do NOT swallow a getReview error into an empty review — that would fail OPEN+ // (the gate would pass on a corrupt/unreadable store and let the run proceed to+ // visuals without verifying health). Let it bubble to the coordinator's+ // top-level catch, which records a clean `error` terminal state.+ const review = await getReview(sId);+ const comments = review.comments || [];+ const health = computeHealth(comments, gate);broadcast(sId, {type: 'verify:round', scope: 'editorialHealth', round: 1,findings: health.open, blocking: health.ready ? 0 : health.open, score: health.score,@@ -680,11 +685,9 @@ async function runEditorialHealthGate(sId, record) {record.runState.editorialHealthReady = true;return {};}- // Not clean — surface the open blockers (the gate-relevant severities) as the- // residual the pause records, so the human sees exactly what's left.- const blockers = (review.comments || []).filter(- (c) => c.status === 'open' && (gate === 'noOpenHighOrMedium' ? ARC_BLOCKING.has(c.severity) : EDITORIAL_BLOCKING.has(c.severity)),- );+ // Not clean — surface the open blockers (via the shared helper, so the residual+ // can't disagree with computeHealth's `ready` verdict) for the human triage.+ const blockers = openBlockers(comments, gate);return { pause: true, reason: `editorial health not clean (score ${health.score}, ${health.open} open finding(s))`, residual: blockers };}