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

feat: per-check finding-count trend tracking in the editorial health panel (#1597)

[._.]/ Adam Eivy371c6bfcd17f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 40826289b6..67bcaad1c0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -55,6 +55,8 @@
## Editorial checks
+- **[issue-1597] The editorial health panel now tracks each *check* over time, not just the overall score — a per-check finding-count sparkline that shows whether a given check is improving or regressing run-over-run.** The revision-trend ledger already snapshotted the open-finding counts by severity and category after every editorial-checks / completeness run, so the panel could draw an overall score sparkline and flag categories that regressed — but there was no way to see, say, whether the filter-word count is dropping draft-over-draft or whether name-similarity findings are creeping up as you add characters. Each trend snapshot now also records the open-finding count **per check**, and the Editorial Health panel renders an **Open by check** breakdown: every check with open findings, its current count, a magnitude sparkline of that check's count across the recorded revisions (normalized to its own peak), and a regression flag (`1→4`) when a check got worse since the previous revision. Check ids resolve to their human catalog labels (falling back to the raw id for a since-deleted custom check), and the list caps at the eight worst checks with a "+N more" note so a noisy run can't blow out the panel. Per-check counts are additive, install-local telemetry — snapshots recorded before this shipped simply start accumulating per-check history from the first run after upgrade. (`server/services/pipeline/editorialScore.js`, `client/src/lib/editorialHealth.js`, `client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/pages/PipelineEditorialChecks.jsx`)
+
- **[issue-1593] The passive-voice check now ignores intentional passive — predicate-adjective states and weather/setting mood images — so it flags far fewer false positives.** `prose.passive-voice` is a cheap be-verb + past-participle heuristic, and the heuristic alone can't tell weak agentive passive ("the door was opened") from passive constructions writers use on purpose: a predicate-adjective state of being ("she was exhausted", "he was determined") isn't an action done to the subject at all, and a setting/weather mood image ("the sky was streaked with red", "the room was bathed in light") is deliberate atmosphere, not flabby prose. Both used to inflate the per-1000-word passive rate and push otherwise-clean sections over the threshold. A context-tuning pass now classifies each candidate `weak` / `stative` / `mood` and, by default, counts only genuine weak passive toward the density score — an explicit "by <agent>" ("she was exhausted *by the climb*") still always counts as weak. The cheap heuristic stays the base tier: a new **Suppress intentional passive** toggle (on by default) can be turned off per series to fall back to counting every be-verb + participle. (`server/lib/editorial/proseTics.js`, `server/lib/editorial/checkRegistry.js`)
- **[issue-1581] A new editorial check catches timeline and canon contradictions — a dead character who reappears alive, an age that contradicts the bible, an impossible chronology.** PortOS had no editorial check for internal contradictions against canon and the story's own timeline, so a character killed in issue 3 who walks back in alive in issue 6, an age the prose contradicts (the bible says 16, the page says "in her 30s"), or a journey that takes eight days but is dated to day two could slip through to the reader — the kind of mistake that's nearly impossible to catch by eye once an arc spans months of drafting. The new **Timeline / canon contradiction** check (`continuity.timeline-contradiction`) reconciles the stitched manuscript against the **continuity-bible facts ledger** (the ground-truth ages, dates & elapsed time, locations, and world rules already extracted by the continuity bible), the canon character facts (age, role, status, description), the reverse-outline scene ordering (for chronology), and the authored per-character arcs — flagging each contradiction with the two facts that conflict and a verbatim anchor. It runs across the whole manuscript — carrying each character's last-known state (alive/dead, age, location) forward between chunks so a death-then-resurrection that spans chapters is actually visible — and degrades to a prose-only scan when no canon or outline exists. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking plot-breaking contradictions high-severity per finding. Its findings go stale (and re-run) when any source it reads drifts — including the continuity-bible ledger — via the new `continuityBible` editorial source. (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `data.reference/prompts/stages/pipeline-editorial-timeline-contradiction.md`, `scripts/migrations/129-editorial-timeline-contradiction-stage.js`)
diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx
index 406930ad4c..49cf0a2729 100644
--- a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx
+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx
@@ -23,6 +23,9 @@ import {
deltaDisplay,
sparklineGeometry,
orderedCategories,
+ orderedChecks,
+ checkCountSeries,
+ countSparklineGeometry,
SEVERITY_ORDER,
SEVERITY_LABELS,
READINESS_GATE_LABELS,
@@ -58,7 +61,27 @@ function Sparkline({ points }) {
);
}
-export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {
+// Per-check finding-count sparkline (#1597) — a small magnitude curve of one
+// check's open-finding count across the recorded revisions, normalized to its
+// own peak. A single recorded revision renders just the endpoint dot.
+function CheckSparkline({ counts }) {
+ const { points: poly, coords, last } = countSparklineGeometry(counts, { width: 64, height: 18, pad: 2 });
+ if (!poly || !last) return <span className="inline-block w-16" aria-hidden="true" />;
+ return (
+ <svg viewBox="0 0 64 18" width={64} height={18} className="h-[18px] w-16 shrink-0 overflow-visible" role="img" aria-label="Finding count trend for this check">
+ {coords.length > 1 ? (
+ <polyline points={poly} fill="none" stroke="currentColor" strokeWidth="1.25" className="text-gray-500" />
+ ) : null}
+ <circle cx={last.x} cy={last.y} r="2" className="fill-port-accent" />
+ </svg>
+ );
+}
+
+// Cap the rendered per-check rows so a noisy run can't blow out the panel; the
+// remainder is surfaced as a "+N more" note rather than silently dropped.
+const MAX_CHECK_ROWS = 8;
+
+export default function EditorialHealthPanel({ seriesId, refreshKey = 0, checksById = {} }) {
const [health, setHealth] = useState(null);
const [loading, setLoading] = useState(false);
const [savingGate, setSavingGate] = useState(false);
@@ -114,6 +137,18 @@ export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {
const regressions = Array.isArray(health.trend?.regressions) ? health.trend.regressions : [];
const categories = orderedCategories(health.openByCategory);
const points = health.trend?.points || [];
+ // Per-check breakdown + finding-count sparklines (#1597). Resolve each check's
+ // human label from the page's catalog (falls back to the raw id), and pair it
+ // with its count series across the recorded revisions + any regression flag.
+ const checkRegressions = Array.isArray(health.trend?.checkRegressions) ? health.trend.checkRegressions : [];
+ const labelForCheck = (id) => checksById?.[id]?.label || id;
+ const allChecks = orderedChecks(health.openByCheck, labelForCheck);
+ const checkRows = allChecks.slice(0, MAX_CHECK_ROWS).map((c) => ({
+ ...c,
+ counts: checkCountSeries(points, c.checkId),
+ regressed: checkRegressions.find((r) => r.checkId === c.checkId) || null,
+ }));
+ const hiddenCheckCount = Math.max(0, allChecks.length - checkRows.length);
// 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;
@@ -200,6 +235,32 @@ export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {
</div>
) : null}
+ {/* Per-check breakdown + finding-count sparklines (#1597) — is each check
+ improving (count dropping) or regressing run-over-run? */}
+ {checkRows.length ? (
+ <div className="border-t border-port-border/60 pt-2.5">
+ <span className="block text-[10px] uppercase tracking-wide text-gray-600">Open by check</span>
+ <ul className="mt-1 space-y-1">
+ {checkRows.map(({ checkId, label, count, counts, regressed }) => (
+ <li key={checkId} className="flex items-center gap-2 text-[11px] text-gray-400">
+ <span className="min-w-0 flex-1 truncate text-gray-300" title={label}>{label}</span>
+ {regressed ? (
+ <span className="flex shrink-0 items-center gap-0.5 text-port-error" title={`Regressed: ${regressed.from} → ${regressed.to} since the previous revision`}>
+ <TrendingUp size={11} />
+ {regressed.from}→{regressed.to}
+ </span>
+ ) : null}
+ <span className="w-5 shrink-0 text-right text-gray-500">{count}</span>
+ <CheckSparkline counts={counts} />
+ </li>
+ ))}
+ </ul>
+ {hiddenCheckCount ? (
+ <p className="mt-1 text-[10px] text-gray-600">+{hiddenCheckCount} more check{hiddenCheckCount === 1 ? '' : 's'} with open findings</p>
+ ) : null}
+ </div>
+ ) : null}
+
{/* A clean run that improved on the prior revision gets a positive note. */}
{!regressions.length && hasDelta && (health.trend?.delta || 0) > 0 ? (
<p className="flex items-center gap-1 text-[11px] text-port-success">
diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx
index b9b0d9bee2..533c631a5e 100644
--- a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx
+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx
@@ -93,6 +93,43 @@ describe('EditorialHealthPanel', () => {
expect(screen.queryByTitle('Change since the previous revision')).toBeNull();
});
+ it('renders the per-check breakdown with resolved labels, counts and a regression flag (#1597)', async () => {
+ getEditorialHealth.mockResolvedValue(health({
+ openByCheck: { 'naming.dissimilar-names': 2, 'roster.economy': 1 },
+ trend: {
+ points: [
+ { score: 70, openByCheck: { 'naming.dissimilar-names': 1 } },
+ { score: 83, openByCheck: { 'naming.dissimilar-names': 2, 'roster.economy': 1 } },
+ ],
+ regressions: [],
+ checkRegressions: [{ checkId: 'naming.dissimilar-names', from: 1, to: 2 }],
+ delta: 13,
+ },
+ }));
+ const checksById = {
+ 'naming.dissimilar-names': { label: 'Name dissimilarity' },
+ 'roster.economy': { label: 'Cast economy' },
+ };
+ render(<EditorialHealthPanel seriesId="ser-1" checksById={checksById} />);
+ await screen.findByText('83');
+ expect(screen.getByText('Open by check')).toBeTruthy();
+ // Labels resolved from the catalog, sorted by count desc.
+ expect(screen.getByText('Name dissimilarity')).toBeTruthy();
+ expect(screen.getByText('Cast economy')).toBeTruthy();
+ // The regressed check shows its from→to flag.
+ expect(screen.getByText('1→2')).toBeTruthy();
+ });
+
+ it('falls back to the raw checkId when the catalog has no label for it', async () => {
+ getEditorialHealth.mockResolvedValue(health({
+ openByCheck: { 'custom.orphan': 1 },
+ trend: { points: [{ score: 83, openByCheck: { 'custom.orphan': 1 } }], regressions: [], checkRegressions: [], delta: 0 },
+ }));
+ render(<EditorialHealthPanel seriesId="ser-1" />);
+ await screen.findByText('83');
+ expect(screen.getByText('custom.orphan')).toBeTruthy();
+ });
+
it('renders the per-issue drill-down (issues with open findings, worst first)', async () => {
getEditorialHealth.mockResolvedValue(health({
perIssue: [
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9cba899deb..718948a92b 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -103,7 +103,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |
-| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |
+| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |
| `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
| `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |
diff --git a/client/src/lib/editorialHealth.js b/client/src/lib/editorialHealth.js
index 27396a0c3d..c2b33e8b62 100644
--- a/client/src/lib/editorialHealth.js
+++ b/client/src/lib/editorialHealth.js
@@ -63,3 +63,62 @@ export function orderedCategories(openByCategory = {}) {
.map(([category, count]) => ({ category, count }))
.sort((a, b) => b.count - a.count || a.category.localeCompare(b.category));
}
+
+/**
+ * Order an openByCheck map into `[{ checkId, label, count }]` sorted by count
+ * desc then label (#1597). Drops zero/empty buckets. `labelFor` resolves a
+ * checkId to its human label (the catalog row's `label`); it falls back to the
+ * raw checkId so a finding from a since-deleted custom check still renders.
+ */
+export function orderedChecks(openByCheck = {}, labelFor = (id) => id) {
+ const label = typeof labelFor === 'function' ? labelFor : (id) => id;
+ return Object.entries(openByCheck || {})
+ .filter(([, count]) => Number.isFinite(count) && count > 0)
+ .map(([checkId, count]) => ({ checkId, count, label: label(checkId) || checkId }))
+ .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
+}
+
+/**
+ * Extract a single check's open-finding count across the trend points (#1597),
+ * oldest→newest, as a plain number array. A point with no entry for the check
+ * contributes 0 (the check found nothing that revision), so the series length
+ * always matches the point count — the sparkline shows the check climbing from /
+ * settling to zero rather than dropping points.
+ */
+export function checkCountSeries(points = [], checkId) {
+ const list = Array.isArray(points) ? points : [];
+ return list.map((p) => {
+ const c = p?.openByCheck?.[checkId];
+ return Number.isFinite(c) ? c : 0;
+ });
+}
+
+/**
+ * Project a non-negative count series into SVG polyline coordinates within a
+ * `width × height` box, normalized to the series' own max (unlike
+ * `sparklineGeometry`'s fixed 0–100 axis): the largest count sits at the top,
+ * 0 at the bottom, so a per-check finding count reads as "spiked then dropped".
+ * A flat or all-zero series renders as a baseline. Returns
+ * `{ points: "x,y …", coords: [{x,y,count}], last, max }`; an empty series
+ * yields empty geometry (the caller renders a placeholder).
+ */
+export function countSparklineGeometry(values = [], { width = 80, height = 20, pad = 2 } = {}) {
+ const list = Array.isArray(values) ? values.filter((v) => Number.isFinite(v)) : [];
+ if (!list.length) return { points: '', coords: [], last: null, max: 0 };
+ const innerW = Math.max(1, width - pad * 2);
+ const innerH = Math.max(1, height - pad * 2);
+ const span = Math.max(1, list.length - 1);
+ const max = Math.max(0, ...list);
+ const coords = list.map((count, i) => {
+ const x = pad + (list.length === 1 ? innerW : (i / span) * innerW);
+ // count=max → top (pad); count=0 (or all-zero series) → bottom (height-pad).
+ const y = pad + (max > 0 ? 1 - count / max : 1) * innerH;
+ return { x: Math.round(x * 10) / 10, y: Math.round(y * 10) / 10, count };
+ });
+ return {
+ points: coords.map((c) => `${c.x},${c.y}`).join(' '),
+ coords,
+ last: coords[coords.length - 1],
+ max,
+ };
+}
diff --git a/client/src/lib/editorialHealth.test.js b/client/src/lib/editorialHealth.test.js
index 8bafa9b711..e1a0593dbd 100644
--- a/client/src/lib/editorialHealth.test.js
+++ b/client/src/lib/editorialHealth.test.js
@@ -4,6 +4,9 @@ import {
deltaDisplay,
sparklineGeometry,
orderedCategories,
+ orderedChecks,
+ checkCountSeries,
+ countSparklineGeometry,
} from './editorialHealth.js';
describe('scoreBand', () => {
@@ -71,3 +74,68 @@ describe('orderedCategories', () => {
expect(orderedCategories({})).toEqual([]);
});
});
+
+describe('orderedChecks', () => {
+ it('sorts by count desc then label, resolving ids to labels and dropping zero buckets', () => {
+ const labels = { 'naming.dissimilar-names': 'Name dissimilarity', 'roster.economy': 'Cast economy' };
+ expect(orderedChecks(
+ { 'naming.dissimilar-names': 1, 'roster.economy': 3, 'comic.prose-sync': 0 },
+ (id) => labels[id],
+ )).toEqual([
+ { checkId: 'roster.economy', count: 3, label: 'Cast economy' },
+ { checkId: 'naming.dissimilar-names', count: 1, label: 'Name dissimilarity' },
+ ]);
+ });
+
+ it('falls back to the raw checkId when no label resolves (deleted custom check)', () => {
+ expect(orderedChecks({ 'custom.gone': 2 })).toEqual([
+ { checkId: 'custom.gone', count: 2, label: 'custom.gone' },
+ ]);
+ // A non-function labelFor is tolerated (falls back to the id).
+ expect(orderedChecks({ 'custom.gone': 2 }, null)[0].label).toBe('custom.gone');
+ });
+
+ it('returns empty for an empty/absent map', () => {
+ expect(orderedChecks()).toEqual([]);
+ expect(orderedChecks({})).toEqual([]);
+ });
+});
+
+describe('checkCountSeries', () => {
+ it('extracts one check count across points, defaulting absent points to 0', () => {
+ const points = [
+ { openByCheck: { 'a': 3 } },
+ { openByCheck: { 'a': 1, 'b': 2 } },
+ { openByCheck: { 'b': 2 } },
+ ];
+ expect(checkCountSeries(points, 'a')).toEqual([3, 1, 0]);
+ expect(checkCountSeries(points, 'b')).toEqual([0, 2, 2]);
+ });
+
+ it('returns empty for empty/absent points', () => {
+ expect(checkCountSeries([], 'a')).toEqual([]);
+ expect(checkCountSeries(undefined, 'a')).toEqual([]);
+ });
+});
+
+describe('countSparklineGeometry', () => {
+ it('normalizes to its own max — peak at top, zero at bottom', () => {
+ const { coords, max, last } = countSparklineGeometry([0, 4, 2], { width: 100, height: 20, pad: 0 });
+ expect(max).toBe(4);
+ expect(coords[0].y).toBe(20); // 0 → bottom
+ expect(coords[1].y).toBe(0); // 4 (max) → top
+ expect(last.count).toBe(2);
+ });
+
+ it('renders an all-zero series as a flat baseline (no divide-by-zero)', () => {
+ const { coords, max } = countSparklineGeometry([0, 0], { width: 100, height: 20, pad: 0 });
+ expect(max).toBe(0);
+ expect(coords.every((c) => c.y === 20)).toBe(true);
+ });
+
+ it('yields empty geometry for an empty series', () => {
+ expect(countSparklineGeometry([]).points).toBe('');
+ expect(countSparklineGeometry(undefined).coords).toEqual([]);
+ expect(countSparklineGeometry([]).last).toBeNull();
+ });
+});
diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsx
index a23b4c18ed..9293103b99 100644
--- a/client/src/pages/PipelineEditorialChecks.jsx
+++ b/client/src/pages/PipelineEditorialChecks.jsx
@@ -524,7 +524,7 @@ export default function PipelineEditorialChecks() {
<p className="rounded-lg border border-dashed border-port-border p-4 text-center text-xs text-gray-500">Select a series to view its findings.</p>
) : (
<>
- <EditorialHealthPanel seriesId={seriesId} refreshKey={healthRefresh} />
+ <EditorialHealthPanel seriesId={seriesId} refreshKey={healthRefresh} checksById={checksById} />
{loadingFindings ? (
<p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading findings…</p>
) : (
diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.js
index b083a7b558..74e4196b1f 100644
--- a/server/services/pipeline/editorialScore.js
+++ b/server/services/pipeline/editorialScore.js
@@ -227,6 +227,14 @@ function sanitizeSnapshot(raw) {
const byCat = raw.openByCategory && typeof raw.openByCategory === 'object' ? raw.openByCategory : {};
const openByCategory = {};
for (const [k, v] of Object.entries(byCat)) if (Number.isFinite(v)) openByCategory[k] = v;
+ // Per-check open counts (#1597). Additive + local-only telemetry: snapshots
+ // recorded before this shipped simply lack the map (defaults to {}), so the
+ // per-check trend starts accumulating from the first run after upgrade — no
+ // schema bump needed (older readers ignore the field; this reader tolerates
+ // its absence).
+ const byCheck = raw.openByCheck && typeof raw.openByCheck === 'object' ? raw.openByCheck : {};
+ const openByCheck = {};
+ for (const [k, v] of Object.entries(byCheck)) if (Number.isFinite(v)) openByCheck[k] = v;
return {
runId: typeof raw.runId === 'string' ? raw.runId : null,
at,
@@ -235,6 +243,7 @@ function sanitizeSnapshot(raw) {
open: Number.isFinite(raw.open) ? raw.open : (openBySeverity.high + openBySeverity.medium + openBySeverity.low),
openBySeverity,
openByCategory,
+ openByCheck,
};
}
@@ -294,6 +303,7 @@ export async function recordTrendSnapshot(seriesId, { runId = null, gate = DEFAU
open: health.open,
openBySeverity: health.openBySeverity,
openByCategory: health.openByCategory,
+ openByCheck: health.openByCheck,
};
return queueLedgerWrite(seriesId, async () => {
const ledger = await readLedger(seriesId);
@@ -319,14 +329,31 @@ export async function recordTrendSnapshot(seriesId, { runId = null, gate = DEFAU
// Trend / regression projection (pure).
// ---------------------------------------------------------------------------
+// Per-bucket regressions: every key whose open count is higher in `latest` than
+// in `previous` (a bucket absent from `previous` counts as 0 prior). Shared by
+// the per-category and per-check (#1597) regression projections so the two can
+// never disagree on what "regressed" means. Returns `[{ [keyName], from, to }]`
+// sorted by the size of the increase, descending.
+function regressionsBetween(latest, previous, mapField, keyName) {
+ const out = [];
+ if (!latest || !previous) return out;
+ for (const [key, to] of Object.entries(latest[mapField] || {})) {
+ const from = previous[mapField]?.[key] || 0;
+ if (to > from) out.push({ [keyName]: key, from, to });
+ }
+ return out.sort((a, b) => (b.to - b.from) - (a.to - a.from));
+}
+
/**
* Project a ledger's snapshots into a trend view: the score/open time-series
- * plus per-category REGRESSIONS (a category whose open-finding count rose
- * between the two most recent snapshots — i.e. it got WORSE after an edit pass).
- * Pure so the route + UI + tests share one definition.
+ * (each point also carrying its per-severity, per-category, and per-check open
+ * counts so the UI can build per-bucket sparklines) plus per-category and
+ * per-check REGRESSIONS (a bucket whose open-finding count rose between the two
+ * most recent snapshots — i.e. it got WORSE after an edit pass). Pure so the
+ * route + UI + tests share one definition.
*
* @param {Array} snapshots — the ledger's snapshots (chronological, oldest first)
- * @returns {{ points: [], regressions: [], latest, previous, delta }}
+ * @returns {{ points: [], regressions: [], checkRegressions: [], latest, previous, delta }}
*/
export function computeTrend(snapshots) {
const list = Array.isArray(snapshots) ? snapshots.map(sanitizeSnapshot).filter(Boolean) : [];
@@ -336,22 +363,15 @@ export function computeTrend(snapshots) {
score: s.score,
open: s.open,
openBySeverity: s.openBySeverity,
+ openByCheck: s.openByCheck,
}));
const latest = list[list.length - 1] || null;
const previous = list.length >= 2 ? list[list.length - 2] : null;
// Score delta between the two most recent revisions (positive = improving).
const delta = latest && previous ? latest.score - previous.score : 0;
- // Per-category regressions: a category whose open count is higher in `latest`
- // than in `previous`. Categories absent from `previous` count as 0 prior.
- const regressions = [];
- if (latest && previous) {
- for (const [category, to] of Object.entries(latest.openByCategory || {})) {
- const from = previous.openByCategory?.[category] || 0;
- if (to > from) regressions.push({ category, from, to });
- }
- regressions.sort((a, b) => (b.to - b.from) - (a.to - a.from));
- }
- return { points, regressions, latest, previous, delta };
+ const regressions = regressionsBetween(latest, previous, 'openByCategory', 'category');
+ const checkRegressions = regressionsBetween(latest, previous, 'openByCheck', 'checkId');
+ return { points, regressions, checkRegressions, latest, previous, delta };
}
/**
diff --git a/server/services/pipeline/editorialScore.test.js b/server/services/pipeline/editorialScore.test.js
index 42cf8f4bfe..213b71374a 100644
--- a/server/services/pipeline/editorialScore.test.js
+++ b/server/services/pipeline/editorialScore.test.js
@@ -187,9 +187,45 @@ describe('computeTrend', () => {
const trend = computeTrend([]);
expect(trend.points).toEqual([]);
expect(trend.regressions).toEqual([]);
+ expect(trend.checkRegressions).toEqual([]);
expect(trend.delta).toBe(0);
expect(trend.latest).toBeNull();
});
+
+ // Per-check trend tracking (#1597).
+ const snapWithChecks = (at, openByCheck) => ({
+ runId: `run-${at}`, at, score: 100 - Object.values(openByCheck).reduce((a, b) => a + b, 0),
+ ready: false, open: Object.values(openByCheck).reduce((a, b) => a + b, 0),
+ openBySeverity: { high: 0, medium: 0, low: 0 }, openByCategory: {}, openByCheck,
+ });
+
+ it('carries the per-check open counts on each point so the UI can build per-check sparklines', () => {
+ const trend = computeTrend([
+ snapWithChecks('2026-06-01T00:00:00Z', { 'naming.dissimilar-names': 3 }),
+ snapWithChecks('2026-06-02T00:00:00Z', { 'naming.dissimilar-names': 1, 'roster.economy': 2 }),
+ ]);
+ expect(trend.points.map((p) => p.openByCheck)).toEqual([
+ { 'naming.dissimilar-names': 3 },
+ { 'naming.dissimilar-names': 1, 'roster.economy': 2 },
+ ]);
+ });
+
+ it('flags a check that regressed (more findings) between the two latest snapshots', () => {
+ const trend = computeTrend([
+ snapWithChecks('2026-06-01T00:00:00Z', { 'naming.dissimilar-names': 1, 'roster.economy': 2 }),
+ snapWithChecks('2026-06-02T00:00:00Z', { 'naming.dissimilar-names': 4, 'roster.economy': 1 }),
+ ]);
+ // naming worsened 1→4 (regressed); roster improved 2→1 (not a regression).
+ expect(trend.checkRegressions).toEqual([{ checkId: 'naming.dissimilar-names', from: 1, to: 4 }]);
+ });
+
+ it('treats a check absent in the prior snapshot as 0 prior (newly-failing check counts as a regression)', () => {
+ const trend = computeTrend([
+ snapWithChecks('2026-06-01T00:00:00Z', { 'naming.dissimilar-names': 1 }),
+ snapWithChecks('2026-06-02T00:00:00Z', { 'naming.dissimilar-names': 1, 'comic.prose-sync': 2 }),
+ ]);
+ expect(trend.checkRegressions).toEqual([{ checkId: 'comic.prose-sync', from: 0, to: 2 }]);
+ });
});
describe('ledger sanitization', () => {
@@ -197,13 +233,21 @@ describe('ledger sanitization', () => {
const ledger = __testing.sanitizeLedger({
snapshots: [
null,
- { at: '2026-06-01T00:00:00Z', score: 90, openBySeverity: { high: 'x', medium: 2 }, openByCategory: { a: 1, b: 'nope' } },
+ { at: '2026-06-01T00:00:00Z', score: 90, openBySeverity: { high: 'x', medium: 2 }, openByCategory: { a: 1, b: 'nope' }, openByCheck: { 'check.a': 2, 'check.b': 'nope' } },
{ score: 50 }, // no `at` → dropped
],
}, 'ser-abc');
expect(ledger.snapshots).toHaveLength(1);
expect(ledger.snapshots[0].openBySeverity).toEqual({ high: 0, medium: 2, low: 0 });
expect(ledger.snapshots[0].openByCategory).toEqual({ a: 1 });
+ expect(ledger.snapshots[0].openByCheck).toEqual({ 'check.a': 2 });
expect(ledger.seriesId).toBe('ser-abc');
});
+
+ it('defaults openByCheck to {} for a pre-#1597 snapshot that predates per-check tracking', () => {
+ const ledger = __testing.sanitizeLedger({
+ snapshots: [{ at: '2026-05-01T00:00:00Z', score: 88, openBySeverity: { high: 0, medium: 1, low: 0 }, openByCategory: { naming: 1 } }],
+ }, 'ser-old');
+ expect(ledger.snapshots[0].openByCheck).toEqual({});
+ });
});