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: drill into a health-trend snapshot from the editorial sparkline (#1630)
[._.]/ Adam Eivyb02510152946
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex dcced186b8..2e0368dbdd 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,7 @@## Editorial checks+- **[issue-1630] Click a point on the editorial health-trend sparkline to drill into that revision — what was open then, and what changed since the prior run.** The score sparkline in the Editorial Health panel was read-only: you could watch the line dip after an edit pass but not see *why*. Every recorded revision is now a clickable point. Selecting one opens a drill-down showing that snapshot's score (with its delta vs the previous revision) and its open-finding breakdown by severity and category, plus a per-dimension diff against the prior revision — which severities, categories, and checks rose (regressed, in red) or fell (improved, in green), biggest change first. The first recorded revision says there's nothing to compare yet; a revision recorded before per-check tracking shipped omits the per-check diff rather than inventing an all-new baseline. (`client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/lib/editorialHealth.js`, `server/services/pipeline/editorialScore.js`)- **[issue-1625] The reading-level check now reports per-scene variance, not just a single whole-corpus number.** `style.reading-level` measured one Flesch–Kincaid grade for the entire series and flagged drift from the style-guide target — but a single average hides the modulation a skilled writer uses (a quiet introspective scene reads lower, an action scene higher) and conceals a lone scene that swings far outside the intended band. The check now also splits the manuscript into scenes (reusing the shared `splitScenes` divider parser — markdown headings including the stitcher's `# Issue N`, and centered rules like `***`), measures each, and flags any scene whose grade falls outside the target **band** (`target ± sceneTolerance`), reporting the widest swings first. Three new per-series knobs join the existing whole-corpus tolerance: **per-scene band tolerance** (default 4 — wider than the corpus tolerance since scenes legitimately modulate), **minimum scene words to measure** (default 120 — short fragments are too noisy for a reliable FK estimate), and **max per-scene findings** (default 5 — so a long manuscript can't flood the review). The original whole-corpus finding is unchanged, and a single-scene manuscript reports only that — so existing series behavior is preserved. (`server/lib/editorial/checkRegistry.js`)- **[issue-1622] The adverb, passive-voice, and repeated-gesture copy-edit checks are now series-tunable like their word-list siblings.** Clichés, said-bookisms, filter words, crutch words, hedge words, and gestures already accepted a house-style allowlist and an extra-words list, but `prose.adverbs` and `prose.passive-voice` didn't expose theirs (repeated-gestures already did). Now all three carry the same config: `prose.adverbs` gains an **extra-adverbs** list so a series can flag the real adverbs the `-ly` heuristic misses ("fast", "well", "hard"); `prose.passive-voice` gains a **house-style allowlist** (participles to never flag — archaic/adjectival "-ed" forms like "blessed", "beloved") and an **extra-participles** list (series-specific irregular participles the heuristic misses, e.g. "begun", "hewn"). A historical-fiction series can now whitelist archaic forms and a comedic series can mute gesture repetition without code changes. Additive config with empty-string defaults — existing series are unaffected. (`server/lib/editorial/proseTics.js`, `server/lib/editorial/checkRegistry.js`)- **[issue-1624] A new editorial check flags objects whose narrative weight is out of proportion to their prominence.** The existing `objects.*` checks are presence tests — is a significant object attached to someone, is an interaction motivated, does an attachment's origin contradict its character — but none asked whether an object's *weight* matches how much the plot actually leans on it. The new `objects.weight-proportionality` check (series-scope, LLM, default-on) weighs each object's prominence in the prose against the depth of backstory and significance the story invests in it, and flags two failures: **over-weighted** (a minor object handed a disproportionate backstory — "a one-line locket with a three-issue origin") and **under-established** (a prominent or decisive object resting on no lineage — "an heirloom that resolves the finale, never set up"). It reads the stitched manuscript plus the canon object↔character attachment summary, judging the *proportion* rather than the absolute amount, and carries each object's established weight across manuscript chunks so a backstory planted early is weighed against a payoff that lands late. Stays distinct from `objects.unmotivated-interaction` (a single unmotivated beat) and `objects.backstory-consistency` (a contradicted origin) — the gap here is the over- or under-writing of plot machinery. Ships the prompt + stage-config for fresh installs and a boot migration (143) so existing installs seed the stage. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-object-weight-proportionality.md`, `scripts/migrations/143-editorial-object-weight-proportionality-stage.js`)diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsxindex 6efbe527a2..a6e67057fe 100644--- a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx@@ -16,14 +16,16 @@*/import { useCallback, useEffect, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';-import { Activity, Loader2, TrendingUp, TrendingDown } from 'lucide-react';+import { Activity, Loader2, TrendingUp, TrendingDown, X } from 'lucide-react';import toast from '../../ui/Toast';import { getEditorialHealth, setEditorialReadinessGate } from '../../../services/api';import { FINDING_FILTER_PARAMS, FINDINGS_TRIAGE_ANCHOR_ID } from '../../../lib/editorialChecks';+import { timeAgo } from '../../../utils/formatters';import {scoreBand,deltaDisplay,sparklineGeometry,+ snapshotDiff,orderedCategories,orderedChecks,checkCountSeries,@@ -51,18 +53,80 @@ function SeverityBreakdown({ openBySeverity }) {);}-function Sparkline({ points }) {+// The score sparkline (#1316), with clickable revision points (#1630): each+// recorded snapshot is a focusable dot the user can select to drill into that+// revision's open-finding breakdown + diff vs the prior run. `selectedIndex`+// indexes into the SAME filtered point list the panel passes (geometry drops+// non-finite scores), so the panel can map a clicked dot back to its snapshot.+// Clicking the active dot deselects (toggle). When `onSelect` is absent the+// sparkline is static (no interactive dots) for read-only callers.+function Sparkline({ points, selectedIndex = null, onSelect }) {const { points: poly, coords } = sparklineGeometry(points, { width: 140, height: 32, pad: 3 });if (!poly) return <span className="text-[11px] text-gray-600">Run editorial checks to start the trend</span>;- const last = coords[coords.length - 1];+ const lastIndex = coords.length - 1;+ const interactive = typeof onSelect === 'function';return (<svg viewBox="0 0 140 32" width={140} height={32} className="h-8 w-[140px] max-w-full overflow-visible" role="img" aria-label="Editorial health score trend"><polyline points={poly} fill="none" stroke="currentColor" strokeWidth="1.5" className="text-port-accent" />- <circle cx={last.x} cy={last.y} r="2.5" className="fill-port-accent" />+ {!interactive ? (+ <circle cx={coords[lastIndex].x} cy={coords[lastIndex].y} r="2.5" className="fill-port-accent" />+ ) : coords.map((c, i) => {+ const active = i === selectedIndex;+ const isLast = i === lastIndex;+ const select = () => onSelect(active ? null : i);+ return (+ <circle+ key={i}+ cx={c.x}+ cy={c.y}+ r={active ? 3.5 : isLast ? 2.5 : 2}+ role="button"+ tabIndex={0}+ aria-pressed={active}+ aria-label={`Revision ${i + 1} of ${coords.length}, score ${c.score}${active ? ' (selected)' : ''}`}+ onClick={select}+ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); select(); } }}+ className={`cursor-pointer outline-none transition-all ${active ? 'fill-port-warning' : isLast ? 'fill-port-accent' : 'fill-port-accent/50 hover:fill-port-accent'}`}+ >+ <title>{`Revision ${i + 1} · score ${c.score}`}</title>+ </circle>+ );+ })}</svg>);}+// One row of the snapshot diff (#1630): a changed bucket rendered as+// `label from→to` with improvement (count dropped) in success-green and+// regression (count rose) in error-red. `labelFor` resolves the raw bucket key+// to a human label (severity name, category, or check label).+function SnapshotDiffRow({ row, labelFor }) {+ const improved = row.delta < 0;+ return (+ <li className="flex items-center justify-between gap-2 text-[11px]">+ <span className="min-w-0 truncate text-gray-300" title={labelFor(row.key)}>{labelFor(row.key)}</span>+ <span className={`flex shrink-0 items-center gap-0.5 ${improved ? 'text-port-success' : 'text-port-error'}`}>+ {improved ? <TrendingDown size={11} /> : <TrendingUp size={11} />}+ {row.from}→{row.to}+ </span>+ </li>+ );+}++// A labelled diff section (severity / category / check) — renders nothing when+// the dimension has no changes so a clean revision stays compact.+function SnapshotDiffSection({ title, rows, labelFor }) {+ if (!rows?.length) return null;+ return (+ <div>+ <span className="block text-[10px] uppercase tracking-wide text-gray-600">{title}</span>+ <ul className="mt-0.5 space-y-0.5">+ {rows.map((row) => <SnapshotDiffRow key={row.key} row={row} labelFor={labelFor} />)}+ </ul>+ </div>+ );+}+// 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.@@ -119,6 +183,11 @@ export default function EditorialHealthPanel({const [loading, setLoading] = useState(false);const [savingGate, setSavingGate] = useState(false);const [showIssues, setShowIssues] = useState(false);+ // Which trend snapshot the user drilled into (#1630): an index into the+ // filtered trend points, or null for no selection. Reset whenever the series+ // or the underlying data refreshes so a stale index can't point at a snapshot+ // that shifted (a new run prepends/appends points).+ const [selectedSnapshot, setSelectedSnapshot] = useState(null);// Make the breakdown rows navigable (#1606): clicking a category/check deep-links// the triage filter (shared `f`-prefixed URL params) and scrolls the findings@@ -174,6 +243,10 @@ export default function EditorialHealthPanel({// the panel mid-view.useEffect(() => { setHealth(null); }, [seriesId]);useEffect(() => { load(seriesId); }, [seriesId, refreshKey, load]);+ // Drop any snapshot drill-down when the data behind the trend changes — a new+ // run shifts the point indices, so a held selection would point at the wrong+ // (or a now-absent) revision (#1630).+ useEffect(() => { setSelectedSnapshot(null); }, [seriesId, refreshKey]);const onGateChange = (gate) => {setSavingGate(true);@@ -228,6 +301,19 @@ export default function EditorialHealthPanel({.filter((p) => p.open > 0).sort((a, b) => a.score - b.score);+ // Snapshot drill-down (#1630): clicking a sparkline dot selects a revision.+ // The sparkline geometry drops non-finite-score points, so filter the points+ // the SAME way here — the selected index then maps 1:1 onto the rendered dots.+ // Clamp the held selection so a refresh that shrank the trend can't strand the+ // drill-down on an out-of-range index.+ const trendPoints = points.filter((p) => Number.isFinite(p?.score));+ const selectedValid = selectedSnapshot != null+ && selectedSnapshot >= 0 && selectedSnapshot < trendPoints.length;+ const selectedPoint = selectedValid ? trendPoints[selectedSnapshot] : null;+ const selectedPrev = selectedValid && selectedSnapshot > 0 ? trendPoints[selectedSnapshot - 1] : null;+ const selectedDiff = selectedPoint ? snapshotDiff(selectedPoint, selectedPrev) : null;+ const snapshotCategories = selectedPoint ? orderedCategories(selectedPoint.openByCategory) : [];+return (<section className="space-y-3 rounded-lg border border-port-border bg-port-card p-3"><div className="flex items-center justify-between gap-2">@@ -260,10 +346,88 @@ export default function EditorialHealthPanel({</div><div className="sm:text-right"><span className="block text-[10px] uppercase tracking-wide text-gray-600">Score trend</span>- <span className="text-port-accent"><Sparkline points={health.trend?.points} /></span>+ <span className="text-port-accent">+ <Sparkline+ points={trendPoints}+ selectedIndex={selectedValid ? selectedSnapshot : null}+ onSelect={setSelectedSnapshot}+ />+ </span>+ {trendPoints.length > 1 ? (+ <span className="block text-[10px] text-gray-600 sm:text-right">Click a point to see what changed</span>+ ) : null}</div></div>+ {/* Snapshot drill-down (#1630) — the selected revision's open-finding+ breakdown + a diff against the prior revision. */}+ {selectedPoint && selectedDiff ? (+ <div className="rounded-md border border-port-accent/40 bg-port-accent/5 p-2.5">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <span className="block text-[10px] uppercase tracking-wide text-gray-500">+ Revision {selectedSnapshot + 1} of {trendPoints.length}+ {selectedPoint.at ? ` · ${timeAgo(selectedPoint.at)}` : ''}+ </span>+ <div className="mt-0.5 flex items-baseline gap-2">+ <span className={`text-lg font-bold ${scoreBand(selectedPoint.score).tone}`}>{selectedPoint.score}</span>+ <span className="text-[11px] text-gray-500">/ 100</span>+ {selectedDiff.scoreDelta != null && selectedDiff.scoreDelta !== 0 ? (+ <span className={`text-[11px] ${selectedDiff.scoreDelta > 0 ? 'text-port-success' : 'text-port-error'}`} title="Score change since the previous revision">+ {deltaDisplay(selectedDiff.scoreDelta).text}+ </span>+ ) : null}+ {Number.isFinite(selectedPoint.open) ? (+ <span className="text-[11px] text-gray-500">· {selectedPoint.open} open</span>+ ) : null}+ </div>+ </div>+ <button+ type="button"+ onClick={() => setSelectedSnapshot(null)}+ aria-label="Close snapshot detail"+ title="Close snapshot detail"+ className="shrink-0 rounded p-0.5 text-gray-500 transition-colors hover:bg-port-border/50 hover:text-gray-300"+ >+ <X size={13} />+ </button>+ </div>++ {/* This revision's open-finding breakdown. */}+ <div className="mt-2 border-t border-port-border/60 pt-2">+ <span className="block text-[10px] uppercase tracking-wide text-gray-600">Open findings this revision</span>+ <div className="mt-1"><SeverityBreakdown openBySeverity={selectedPoint.openBySeverity} /></div>+ {snapshotCategories.length ? (+ <ul className="mt-1 flex flex-wrap gap-x-2 gap-y-0.5">+ {snapshotCategories.map(({ category, count }) => (+ <li key={category} className="text-[11px] text-gray-400">+ <span className="text-gray-300">{category}</span> <span className="text-gray-500">{count}</span>+ </li>+ ))}+ </ul>+ ) : null}+ </div>++ {/* What changed vs the previous revision. */}+ <div className="mt-2 border-t border-port-border/60 pt-2">+ <span className="block text-[10px] uppercase tracking-wide text-gray-600">Changed since previous revision</span>+ {!selectedDiff.hasPrevious ? (+ <p className="mt-0.5 text-[11px] text-gray-500">First recorded revision — nothing to compare against yet.</p>+ ) : (selectedDiff.bySeverity.length || selectedDiff.byCategory.length || selectedDiff.byCheck?.length) ? (+ <div className="mt-1 space-y-1.5">+ <SnapshotDiffSection title="By severity" rows={selectedDiff.bySeverity} labelFor={(k) => SEVERITY_LABELS[k] || k} />+ <SnapshotDiffSection title="By category" rows={selectedDiff.byCategory} labelFor={(k) => k} />+ <SnapshotDiffSection title="By check" rows={selectedDiff.byCheck} labelFor={labelForCheck} />+ </div>+ ) : (+ <p className="mt-0.5 flex items-center gap-1 text-[11px] text-port-success">+ <TrendingDown size={11} className="rotate-180" /> No open-finding counts changed since the previous revision.+ </p>+ )}+ </div>+ </div>+ ) : null}+{/* Readiness gate control — also drives the autopilot convergence gate. */}<div className="flex flex-wrap items-center gap-2 border-t border-port-border/60 pt-2.5"><label htmlFor="eh-gate" className="text-[11px] text-gray-500">Ready when:</label>diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsxindex e470bb6c04..348569a0b3 100644--- a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx@@ -236,4 +236,54 @@ describe('EditorialHealthPanel', () => {fireEvent.click(screen.getByTitle('Filter findings to Cast economy'));await waitFor(() => expect(params()).toContain('fcheck=roster.economy'));});++ // Snapshot drill-down (#1630): clicking a sparkline point shows that revision's+ // open-finding breakdown + a diff vs the previous revision.+ const trendHealth = (over = {}) => health({+ trend: {+ points: [+ { score: 70, open: 5, at: '2026-06-01T00:00:00Z', openBySeverity: { high: 1, medium: 1, low: 3 }, openByCategory: { continuity: 3, pacing: 2 }, openByCheck: { 'continuity.x': 3 } },+ { score: 83, open: 3, at: '2026-06-02T00:00:00Z', openBySeverity: { high: 0, medium: 1, low: 2 }, openByCategory: { continuity: 1, pacing: 2 }, openByCheck: { 'continuity.x': 1 } },+ ],+ regressions: [],+ checkRegressions: [],+ delta: 13,+ },+ ...over,+ });++ it('drills into a snapshot when a sparkline point is clicked (#1630)', async () => {+ getEditorialHealth.mockResolvedValue(trendHealth());+ renderPanel({ seriesId: 'ser-1', checksById: { 'continuity.x': { label: 'Continuity X' } } });+ await screen.findByText('83');+ // No drill-down until a point is selected.+ expect(screen.queryByText('Changed since previous revision')).toBeNull();+ // Select the latest revision (revision 2 of 2).+ fireEvent.click(screen.getByRole('button', { name: /Revision 2 of 2, score 83/ }));+ expect(await screen.findByText('Changed since previous revision')).toBeTruthy();+ expect(screen.getByText('Open findings this revision')).toBeTruthy();+ // continuity dropped 3→1 since the prior revision — shown in both the+ // category and the per-check diff rows.+ expect(screen.getAllByText('3→1').length).toBeGreaterThanOrEqual(1);+ // The resolved check label appears in the By-check diff.+ expect(screen.getByText('Continuity X')).toBeTruthy();+ });++ it('notes the first revision has nothing to compare against (#1630)', async () => {+ getEditorialHealth.mockResolvedValue(trendHealth());+ renderPanel({ seriesId: 'ser-1' });+ await screen.findByText('83');+ fireEvent.click(screen.getByRole('button', { name: /Revision 1 of 2, score 70/ }));+ expect(await screen.findByText(/First recorded revision/)).toBeTruthy();+ });++ it('closes the snapshot drill-down (#1630)', async () => {+ getEditorialHealth.mockResolvedValue(trendHealth());+ renderPanel({ seriesId: 'ser-1' });+ await screen.findByText('83');+ fireEvent.click(screen.getByRole('button', { name: /Revision 2 of 2/ }));+ await screen.findByText('Changed since previous revision');+ fireEvent.click(screen.getByRole('button', { name: 'Close snapshot detail' }));+ await waitFor(() => expect(screen.queryByText('Changed since previous revision')).toBeNull());+ });});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex ad3f9aeb93..9008710e40 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; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; 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; `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. |+| `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); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); 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.jsindex 0bd6297ba4..1104871d6f 100644--- a/client/src/lib/editorialHealth.js+++ b/client/src/lib/editorialHealth.js@@ -107,6 +107,63 @@ export function checkCountSeries(points = [], checkId) {});}+/**+ * Diff two open-finding-count maps (`{ bucket: count }`) into a sorted list of+ * CHANGED buckets (#1630). A bucket absent from one side counts as 0 there, so a+ * newly-opened bucket reads `from: 0` and a fully-resolved one reads `to: 0`.+ * Only buckets whose count actually changed are returned — an unchanged bucket+ * carries no signal. Sorted by the magnitude of the change (largest first), then+ * bucket name, so the biggest regressions/fixes lead. Returns+ * `[{ key, from, to, delta }]` where `delta < 0` is an improvement (fewer+ * findings) and `delta > 0` a regression.+ */+export function diffCountMaps(current = {}, previous = {}) {+ const cur = current && typeof current === 'object' ? current : {};+ const prev = previous && typeof previous === 'object' ? previous : {};+ const keys = new Set([...Object.keys(cur), ...Object.keys(prev)]);+ const rows = [];+ for (const key of keys) {+ const to = Number.isFinite(cur[key]) ? cur[key] : 0;+ const from = Number.isFinite(prev[key]) ? prev[key] : 0;+ if (to === from) continue;+ rows.push({ key, from, to, delta: to - from });+ }+ return rows.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || a.key.localeCompare(b.key));+}++/**+ * Build the drill-down view for a single trend snapshot (#1630): its own+ * open-finding breakdown plus a per-dimension diff against the PREVIOUS+ * snapshot, so clicking a sparkline point can answer "what changed since the+ * prior run?". `previous` is null for the first recorded revision (nothing to+ * compare — `hasPrevious: false`, all deltas null/empty).+ *+ * Per-check telemetry is null-aware (mirrors `checkCountSeries`/`computeTrend`):+ * if EITHER snapshot lacks the `openByCheck` map (recorded before per-check+ * tracking shipped), `byCheck` is `null` ("no telemetry to diff") rather than a+ * misleading all-zero baseline that would flag every open check as new.+ *+ * @param {object} point — the selected snapshot (a `trend.points[i]`)+ * @param {object|null} previous — the snapshot one revision earlier, or null+ * @returns {{ hasPrevious, scoreDelta, openDelta, bySeverity, byCategory, byCheck }|null}+ */+export function snapshotDiff(point, previous = null) {+ if (!point || typeof point !== 'object') return null;+ const prev = previous && typeof previous === 'object' ? previous : null;+ const numDelta = (cur, old) =>+ prev && Number.isFinite(cur) && Number.isFinite(old) ? cur - old : null;+ const canDiffChecks = point.openByCheck && typeof point.openByCheck === 'object'+ && (!prev || (prev.openByCheck && typeof prev.openByCheck === 'object'));+ return {+ hasPrevious: !!prev,+ scoreDelta: numDelta(point.score, prev?.score),+ openDelta: numDelta(point.open, prev?.open),+ bySeverity: diffCountMaps(point.openBySeverity, prev?.openBySeverity),+ byCategory: diffCountMaps(point.openByCategory, prev?.openByCategory),+ byCheck: canDiffChecks ? diffCountMaps(point.openByCheck, prev?.openByCheck) : null,+ };+}+/*** Project a non-negative count series into SVG polyline coordinates within a* `width × height` box, normalized to the series' own max (unlikediff --git a/client/src/lib/editorialHealth.test.js b/client/src/lib/editorialHealth.test.jsindex da456e8917..eb398a051e 100644--- a/client/src/lib/editorialHealth.test.js+++ b/client/src/lib/editorialHealth.test.js@@ -7,6 +7,8 @@ import {orderedChecks,checkCountSeries,countSparklineGeometry,+ diffCountMaps,+ snapshotDiff,} from './editorialHealth.js';describe('scoreBand', () => {@@ -148,3 +150,80 @@ describe('countSparklineGeometry', () => {expect(countSparklineGeometry([]).last).toBeNull();});});++describe('diffCountMaps', () => {+ it('reports only the buckets whose count changed', () => {+ const rows = diffCountMaps({ a: 2, b: 1, c: 3 }, { a: 5, b: 1, c: 0 });+ // b unchanged (1→1) is dropped; a dropped 5→2, c rose 0→3+ expect(rows.map((r) => r.key).sort()).toEqual(['a', 'c']);+ const a = rows.find((r) => r.key === 'a');+ expect(a).toMatchObject({ from: 5, to: 2, delta: -3 });+ const c = rows.find((r) => r.key === 'c');+ expect(c).toMatchObject({ from: 0, to: 3, delta: 3 });+ });++ it('treats a bucket absent on one side as 0', () => {+ const rows = diffCountMaps({ added: 4 }, { removed: 2 });+ expect(rows.find((r) => r.key === 'added')).toMatchObject({ from: 0, to: 4, delta: 4 });+ expect(rows.find((r) => r.key === 'removed')).toMatchObject({ from: 2, to: 0, delta: -2 });+ });++ it('sorts by magnitude of change descending, then key', () => {+ const rows = diffCountMaps({ big: 10, small: 2, tie: 1 }, { big: 0, small: 0, tie: 0, ties: 1 });+ expect(rows.map((r) => r.key)).toEqual(['big', 'small', 'tie', 'ties']);+ });++ it('tolerates null/non-object maps', () => {+ expect(diffCountMaps(null, undefined)).toEqual([]);+ expect(diffCountMaps({ a: 1 }, null)).toEqual([{ key: 'a', from: 0, to: 1, delta: 1 }]);+ });+});++describe('snapshotDiff', () => {+ const point = {+ score: 80, open: 3,+ openBySeverity: { high: 0, medium: 1, low: 2 },+ openByCategory: { continuity: 1, pacing: 2 },+ openByCheck: { 'continuity.x': 1, 'pacing.y': 2 },+ };+ const prev = {+ score: 70, open: 5,+ openBySeverity: { high: 1, medium: 1, low: 3 },+ openByCategory: { continuity: 3, pacing: 2 },+ openByCheck: { 'continuity.x': 3, 'pacing.y': 2 },+ };++ it('returns null for a missing point', () => {+ expect(snapshotDiff(null)).toBeNull();+ });++ it('diffs every dimension against the previous snapshot', () => {+ const d = snapshotDiff(point, prev);+ expect(d.hasPrevious).toBe(true);+ expect(d.scoreDelta).toBe(10);+ expect(d.openDelta).toBe(-2);+ // severity: high 1→0, low 3→2 changed; medium unchanged+ expect(d.bySeverity.map((r) => r.key).sort()).toEqual(['high', 'low']);+ // category: continuity 3→1 changed; pacing unchanged+ expect(d.byCategory).toEqual([{ key: 'continuity', from: 3, to: 1, delta: -2 }]);+ // check: continuity.x 3→1 changed; pacing.y unchanged+ expect(d.byCheck).toEqual([{ key: 'continuity.x', from: 3, to: 1, delta: -2 }]);+ });++ it('marks the first revision as having no previous (null deltas)', () => {+ const d = snapshotDiff(point, null);+ expect(d.hasPrevious).toBe(false);+ expect(d.scoreDelta).toBeNull();+ expect(d.openDelta).toBeNull();+ // breakdown still computed as a pure first-revision delta (everything new)+ expect(d.byCategory.find((r) => r.key === 'continuity')).toMatchObject({ from: 0, to: 1 });+ });++ it('returns byCheck:null when either snapshot lacks per-check telemetry', () => {+ const noChecks = { ...point, openByCheck: null };+ expect(snapshotDiff(point, noChecks).byCheck).toBeNull();+ expect(snapshotDiff(noChecks, prev).byCheck).toBeNull();+ // severity/category still diff even without per-check telemetry+ expect(snapshotDiff(noChecks, prev).bySeverity.length).toBeGreaterThan(0);+ });+});diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.jsindex 678571c812..d25d980625 100644--- a/server/services/pipeline/editorialScore.js+++ b/server/services/pipeline/editorialScore.js@@ -424,6 +424,7 @@ export function computeTrend(snapshots) {score: s.score,open: s.open,openBySeverity: s.openBySeverity,+ openByCategory: s.openByCategory,openByCheck: s.openByCheck,}));const latest = list[list.length - 1] || null;diff --git a/server/services/pipeline/editorialScore.test.js b/server/services/pipeline/editorialScore.test.jsindex ebedd59f45..ce9343f0e0 100644--- a/server/services/pipeline/editorialScore.test.js+++ b/server/services/pipeline/editorialScore.test.js@@ -168,6 +168,17 @@ describe('computeTrend', () => {expect(trend.previous.open).toBe(5);});+ it('carries each point\'s per-category open counts for the snapshot drill-down (#1630)', () => {+ const trend = computeTrend([+ snap('2026-06-01T00:00:00Z', 90, 3, { continuity: 1, pacing: 2 }),+ snap('2026-06-02T00:00:00Z', 70, 5, { continuity: 4, pacing: 1 }),+ ]);+ expect(trend.points.map((p) => p.openByCategory)).toEqual([+ { continuity: 1, pacing: 2 },+ { continuity: 4, pacing: 1 },+ ]);+ });+it('flags a category that regressed (got worse) between the two latest snapshots', () => {const trend = computeTrend([snap('2026-06-01T00:00:00Z', 90, 3, { continuity: 1, pacing: 2 }),