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: filter/search/sort controls for editorial findings triage (#1600)
[._.]/ Adam Eivy2a090b9846ef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b90b480266..03d9460c9c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -57,6 +57,8 @@## Editorial checks+- **[issue-1600] The findings triage list now has filter, search, and sort controls so a large batch can be triaged strategically instead of scrolling a flat list.** Past ~50 findings the per-check list grew unwieldy with no way to focus on, say, just the high-severity open findings from one problematic check. A new toolbar above the list filters by **severity**, **status** (open / accepted / dismissed), **category** (check scope), **check**, and **issue**, plus a free-text **search** over each finding's problem/location and a **sort** order (scope & check, severity, issue, or status — sorting both the findings within each group and the groups themselves). The toolbar only ever offers facets that actually exist in the current findings (a single-value facet is hidden), each surviving group's open/total + severity counts are recomputed so the headers never lie about what's shown, and an empty result shows a clear-filters affordance. Every selection persists in the page URL query (`?fsev=`, `?fstatus=`, `?fscope=`, `?fcheck=`, `?fissue=`, `?fq=`, `?fsort=`), so a filtered view — "high-severity open findings on Issue 5, sorted by severity" — is deep-linkable per the repo's linkable-routes convention. The filter/sort logic lives in pure, unit-tested helpers (`deriveFindingFacets` / `applyFindingsView` in `editorialChecks.js`). (`client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `client/src/lib/editorialChecks.js`)+- **[issue-1599] The findings triage list now does bulk accept / dismiss — select findings across checks and resolve the whole batch in one action.** The inline accept/dismiss flow (#1598) still resolved one finding at a time, so clearing a noisy run meant clicking through dozens of rows individually. Every open finding now carries a **checkbox**, each check group has a **select-all** header checkbox (with a tri-state "some selected" look), and once anything is selected a **sticky action bar** replaces the count line with **Accept N** / **Dismiss N** / **Clear**. *Accept* applies only the selected findings that carry an applicable fix (the count reflects that subset); *Dismiss* resolves the entire selection. The batch runs sequentially so the accept endpoint's manuscript-section writes don't race on the shared file, each result updates the list + health panel reactively per the repo's optimistic-UI convention, and resolved findings drop out of the selection automatically. A per-finding failure is counted and surfaced in one summary toast (open those in the editor) rather than aborting the rest of the batch. (`client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`)- **[issue-1598] The findings triage list now previews, accepts, and dismisses a check finding inline — no deep-link into the manuscript editor per finding.** The Editorial Checks findings list only ever showed a finding's problem statement; to see (let alone apply) its suggested fix you had to open the manuscript editor one finding at a time, which made batch review impractical — 50 findings meant 50 context switches. Each open finding with a suggested fix now expands a **collapsed before/after diff** right in the triage row (reusing the manuscript card's `InlineDiff` and edit helpers, so the preview matches exactly what the editor would apply), with inline **Accept** and **Dismiss** buttons that apply or resolve the finding without leaving the page and update the list + health panel reactively. Heavier edits — rewriting the replacement text, cherry-picking individual edits within a multi-edit fix — still deep-link into the editor via an "Open in the editor" link. (`client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `client/src/pages/PipelineEditorialChecks.jsx`)diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsxindex 36bdd53ad3..915cb059b7 100644--- a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx@@ -14,10 +14,18 @@* bar bulk-accepts the selected findings that have an applicable fix and/or* bulk-dismisses the selection — each result reactively updates local state.*/-import { Link } from 'react-router-dom';-import { ChevronDown, ChevronRight, ExternalLink, History, Check, X, Loader2, GitCompareArrows } from 'lucide-react';+import { Link, useSearchParams } from 'react-router-dom';+import { ChevronDown, ChevronRight, ExternalLink, History, Check, X, Loader2, GitCompareArrows, Search } from 'lucide-react';import { useEffect, useMemo, useRef, useState } from 'react';-import { groupFindingsByCheck, findingManuscriptLink, openFindingsTotal } from '../../../lib/editorialChecks';+import {+ groupFindingsByCheck,+ findingManuscriptLink,+ openFindingsTotal,+ deriveFindingFacets,+ applyFindingsView,+ normalizeFindingSort,+ FINDING_SORT_OPTIONS,+} from '../../../lib/editorialChecks';import { fixEditsOf, selectedEditsFor } from '../manuscript/ManuscriptCommentCard';import InlineDiff from '../../ui/InlineDiff';import toast from '../../ui/Toast';@@ -34,6 +42,17 @@ const STATUS_TONE = {accepted: 'text-emerald-400 line-through',dismissed: 'text-gray-600 line-through',};+const SEVERITY_LABELS = { high: 'High', medium: 'Medium', low: 'Low' };+const STATUS_LABELS = { open: 'Open', accepted: 'Accepted', dismissed: 'Dismissed' };+const SEVERITY_FILTER_ORDER = ['high', 'medium', 'low'];+const STATUS_FILTER_ORDER = ['open', 'accepted', 'dismissed'];++// URL params that persist the triage filters/sort (#1600). `f`-prefixed so they+// never collide with the page's own `series` / `custom` params.+const FILTER_PARAMS = { severity: 'fsev', status: 'fstatus', scope: 'fscope', check: 'fcheck', issue: 'fissue', query: 'fq', sort: 'fsort' };+const ALL_FILTER_PARAMS = Object.values(FILTER_PARAMS);+const parseSet = (raw) => new Set((raw || '').split(',').map((s) => s.trim()).filter(Boolean));+const serializeSet = (set) => [...set].join(',');// A check-sourced finding that's still open — the only findings that are// selectable / bulk-actionable. Named once so the predicate lives in one place.@@ -336,10 +355,188 @@ function BulkActionBar({ seriesId, selected, onCommentChange, onClear }) {);}+// A small multi-select toggle chip used for severity / status facets.+function FilterChip({ active, onClick, label, dotClass }) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={active}+ className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] transition-colors ${+ active+ ? 'border-port-accent/60 bg-port-accent/20 text-gray-100'+ : 'border-port-border text-gray-400 hover:text-gray-200 hover:border-port-accent/40'+ }`}+ >+ {dotClass ? <span className={`h-1.5 w-1.5 rounded-full ${dotClass}`} /> : null}+ {label}+ </button>+ );+}++// Filter + search + sort toolbar (#1600). Reads/writes the page URL so a triage+// view (e.g. "high-severity open findings on Issue 5, sorted by severity") is+// deep-linkable. Single-pick selects for scope/check/issue (potentially many),+// multi-select chips for the small severity/status facets, a free-text search,+// and the sort order — only facets actually present in the findings are offered.+function FindingsToolbar({ facets, filters, sort, setParam, toggleInParam, onClear, activeCount }) {+ return (+ <div className="space-y-2 rounded-lg border border-port-border bg-port-card p-2.5">+ <div className="flex flex-wrap items-center gap-2">+ <div className="relative min-w-[10rem] flex-1">+ <Search size={13} className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-gray-500" />+ <label htmlFor="ec-find-search" className="sr-only">Search findings</label>+ <input+ id="ec-find-search"+ type="search"+ value={filters.query}+ onChange={(e) => setParam('query', e.target.value)}+ placeholder="Search problem / location…"+ className="w-full rounded border border-port-border bg-port-bg py-1 pl-7 pr-2 text-xs text-gray-200 placeholder:text-gray-600 focus:border-port-accent focus:outline-none"+ />+ </div>+ <div className="flex items-center gap-1.5">+ <label htmlFor="ec-find-sort" className="text-[10px] text-gray-500">Sort</label>+ <select+ id="ec-find-sort"+ value={sort}+ onChange={(e) => setParam('sort', e.target.value)}+ className="rounded border border-port-border bg-port-bg px-1.5 py-1 text-xs text-gray-200 focus:border-port-accent focus:outline-none"+ >+ {FINDING_SORT_OPTIONS.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}+ </select>+ </div>+ {activeCount > 0 ? (+ <button+ type="button"+ onClick={onClear}+ className="inline-flex items-center gap-1 rounded border border-port-border px-1.5 py-1 text-[10px] text-gray-400 hover:text-white hover:border-port-accent/40"+ >+ <X size={11} /> Clear {activeCount}+ </button>+ ) : null}+ </div>++ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">+ {facets.severities.size > 1 ? (+ <span className="flex flex-wrap items-center gap-1">+ <span className="text-[10px] uppercase tracking-wide text-gray-600">Severity</span>+ {SEVERITY_FILTER_ORDER.filter((s) => facets.severities.has(s)).map((s) => (+ <FilterChip+ key={s}+ active={filters.severities.has(s)}+ onClick={() => toggleInParam('severity', s)}+ label={SEVERITY_LABELS[s]}+ dotClass={SEVERITY_DOT[s]}+ />+ ))}+ </span>+ ) : null}+ {facets.statuses.size > 1 ? (+ <span className="flex flex-wrap items-center gap-1">+ <span className="text-[10px] uppercase tracking-wide text-gray-600">Status</span>+ {STATUS_FILTER_ORDER.filter((s) => facets.statuses.has(s)).map((s) => (+ <FilterChip+ key={s}+ active={filters.statuses.has(s)}+ onClick={() => toggleInParam('status', s)}+ label={STATUS_LABELS[s]}+ />+ ))}+ </span>+ ) : null}+ {facets.scopes.length > 1 ? (+ <span className="flex items-center gap-1">+ <label htmlFor="ec-find-scope" className="text-[10px] uppercase tracking-wide text-gray-600">Category</label>+ <select+ id="ec-find-scope"+ value={[...filters.scopes][0] || ''}+ onChange={(e) => setParam('scope', e.target.value)}+ className="max-w-[9rem] rounded border border-port-border bg-port-bg px-1.5 py-1 text-xs text-gray-200 focus:border-port-accent focus:outline-none"+ >+ <option value="">All</option>+ {facets.scopes.map((s) => <option key={s.scope} value={s.scope}>{s.label}</option>)}+ </select>+ </span>+ ) : null}+ {facets.checks.length > 1 ? (+ <span className="flex items-center gap-1">+ <label htmlFor="ec-find-check" className="text-[10px] uppercase tracking-wide text-gray-600">Check</label>+ <select+ id="ec-find-check"+ value={[...filters.checkIds][0] || ''}+ onChange={(e) => setParam('check', e.target.value)}+ className="max-w-[11rem] truncate rounded border border-port-border bg-port-bg px-1.5 py-1 text-xs text-gray-200 focus:border-port-accent focus:outline-none"+ >+ <option value="">All</option>+ {facets.checks.map((c) => <option key={c.id} value={c.id}>{c.label}</option>)}+ </select>+ </span>+ ) : null}+ {facets.issues.length > 1 ? (+ <span className="flex items-center gap-1">+ <label htmlFor="ec-find-issue" className="text-[10px] uppercase tracking-wide text-gray-600">Issue</label>+ <select+ id="ec-find-issue"+ value={[...filters.issues][0] || ''}+ onChange={(e) => setParam('issue', e.target.value)}+ className="max-w-[9rem] rounded border border-port-border bg-port-bg px-1.5 py-1 text-xs text-gray-200 focus:border-port-accent focus:outline-none"+ >+ <option value="">All</option>+ {facets.issues.map((i) => <option key={i.key} value={i.key}>{i.label}</option>)}+ </select>+ </span>+ ) : null}+ </div>+ </div>+ );+}+export default function EditorialFindingsTriage({ seriesId, comments = [], checksById = {}, onCommentChange }) {const groups = useMemo(() => groupFindingsByCheck(comments, checksById), [comments, checksById]);const [selectedIds, setSelectedIds] = useState(() => new Set());+ // ---- Filter / search / sort, persisted in the URL so a view is deep-linkable+ // (#1600). Facets are derived from the full (unfiltered) groups so options never+ // vanish as you narrow; the toolbar only ever offers facets that exist. ----+ const [searchParams, setSearchParams] = useSearchParams();+ const facets = useMemo(() => deriveFindingFacets(groups), [groups]);+ const sort = normalizeFindingSort(searchParams.get(FILTER_PARAMS.sort));+ const filters = useMemo(() => ({+ severities: parseSet(searchParams.get(FILTER_PARAMS.severity)),+ statuses: parseSet(searchParams.get(FILTER_PARAMS.status)),+ scopes: parseSet(searchParams.get(FILTER_PARAMS.scope)),+ checkIds: parseSet(searchParams.get(FILTER_PARAMS.check)),+ issues: parseSet(searchParams.get(FILTER_PARAMS.issue)),+ query: searchParams.get(FILTER_PARAMS.query) || '',+ }), [searchParams]);+ const activeFilterCount = filters.severities.size + filters.statuses.size+ + filters.scopes.size + filters.checkIds.size + filters.issues.size+ + (filters.query ? 1 : 0);++ // Write a single facet param (empty value clears it), preserving every other+ // param the page owns. `replace` so filtering doesn't pile up history entries.+ const setParam = (key, value) => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (value) next.set(FILTER_PARAMS[key], value); else next.delete(FILTER_PARAMS[key]);+ return next;+ }, { replace: true });+ // Toggle one token in a comma-list (multi-select) param.+ const toggleInParam = (key, token) => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ const set = parseSet(prev.get(FILTER_PARAMS[key]));+ if (set.has(token)) set.delete(token); else set.add(token);+ if (set.size) next.set(FILTER_PARAMS[key], serializeSet(set)); else next.delete(FILTER_PARAMS[key]);+ return next;+ }, { replace: true });+ const clearFilters = () => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ ALL_FILTER_PARAMS.forEach((p) => next.delete(p));+ return next;+ }, { replace: true });++ const view = useMemo(() => applyFindingsView(groups, filters, sort), [groups, filters, sort]);+// Selection only ever holds open findings — once a finding is accepted/dismissed// (here or in the editor) drop it so the bar's counts never count resolved ones.const openIds = useMemo(@@ -380,8 +577,18 @@ export default function EditorialFindingsTriage({ seriesId, comments = [], check);}const totalOpen = openFindingsTotal(groups);+ const shownOpen = openFindingsTotal(view);return (<div className="space-y-2">+ <FindingsToolbar+ facets={facets}+ filters={filters}+ sort={sort}+ setParam={setParam}+ toggleInParam={toggleInParam}+ onClear={clearFilters}+ activeCount={activeFilterCount}+ />{selectedComments.length > 0 ? (<BulkActionBarseriesId={seriesId}@@ -390,9 +597,18 @@ export default function EditorialFindingsTriage({ seriesId, comments = [], checkonClear={clearSelection}/>) : (- <p className="text-[11px] text-gray-500">{totalOpen} open finding{totalOpen === 1 ? '' : 's'} across {groups.length} check{groups.length === 1 ? '' : 's'}</p>+ <p className="text-[11px] text-gray-500">+ {activeFilterCount > 0+ ? `${shownOpen} of ${totalOpen} open finding${totalOpen === 1 ? '' : 's'} shown · ${view.length} of ${groups.length} check${groups.length === 1 ? '' : 's'}`+ : `${totalOpen} open finding${totalOpen === 1 ? '' : 's'} across ${groups.length} check${groups.length === 1 ? '' : 's'}`}+ </p>)}- {groups.map((g) => (+ {view.length === 0 ? (+ <p className="rounded-lg border border-dashed border-port-border p-4 text-center text-xs text-gray-500">+ No findings match the current filters. <button type="button" onClick={clearFilters} className="text-port-accent hover:underline">Clear filters</button>.+ </p>+ ) : null}+ {view.map((g) => (<CheckGroupkey={g.checkId}seriesId={seriesId}diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsxindex c41bf39d20..f7ec3f4a45 100644--- a/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.test.jsx@@ -188,4 +188,60 @@ describe('EditorialFindingsTriage', () => {// Two open findings selected (the dismissed one is not selectable).expect(screen.getByText('2 selected')).toBeTruthy();});++ // ---- Filter / search / sort (#1600) ----+ const twoCheckChecks = {+ 'naming.dissimilar-names': { label: 'Character name dissimilarity', scope: 'series', kind: 'deterministic' },+ 'pacing.scene-drag': { label: 'Scene pacing drag', scope: 'scene', kind: 'llm' },+ };+ const twoCheckComments = () => [+ { id: 'n1', checkId: 'naming.dissimilar-names', status: 'open', severity: 'high', issueNumber: 1, problem: 'Confusable names' },+ { id: 'p1', checkId: 'pacing.scene-drag', status: 'open', severity: 'low', issueNumber: 2, problem: 'Sagging middle' },+ { id: 'p2', checkId: 'pacing.scene-drag', status: 'dismissed', severity: 'low', issueNumber: 2, problem: 'Resolved drag' },+ ];+ const renderTwoCheck = (initialEntries = ['/']) => render(+ <MemoryRouter initialEntries={initialEntries}>+ <EditorialFindingsTriage seriesId="ser-1" checksById={twoCheckChecks} comments={twoCheckComments()} />+ </MemoryRouter>,+ );++ it('filters findings by severity via a toolbar chip (#1600)', () => {+ renderTwoCheck();+ // Both findings visible up front.+ expect(screen.getByText('Confusable names')).toBeTruthy();+ expect(screen.getByText('Sagging middle')).toBeTruthy();+ // Toggle the High severity chip — only the high-severity finding remains.+ fireEvent.click(screen.getByRole('button', { name: 'High', pressed: false }));+ expect(screen.getByText('Confusable names')).toBeTruthy();+ expect(screen.queryByText('Sagging middle')).toBeNull();+ });++ it('filters findings by the free-text search box (#1600)', () => {+ renderTwoCheck();+ fireEvent.change(screen.getByLabelText('Search findings'), { target: { value: 'sagging' } });+ expect(screen.getByText('Sagging middle')).toBeTruthy();+ expect(screen.queryByText('Confusable names')).toBeNull();+ });++ it('filters by check via the Check select (#1600)', () => {+ renderTwoCheck();+ fireEvent.change(screen.getByLabelText('Check'), { target: { value: 'naming.dissimilar-names' } });+ expect(screen.getByText('Confusable names')).toBeTruthy();+ expect(screen.queryByText('Sagging middle')).toBeNull();+ });++ it('honors filters supplied via the URL query so a view is deep-linkable (#1600)', () => {+ renderTwoCheck(['/?fsev=low']);+ expect(screen.getByText('Sagging middle')).toBeTruthy();+ expect(screen.queryByText('Confusable names')).toBeNull();+ });++ it('shows a no-match state with a clear-filters affordance when filters exclude everything (#1600)', () => {+ renderTwoCheck(['/?fq=zzzznomatch']);+ expect(screen.getByText(/No findings match the current filters/i)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /clear filters/i }));+ // Clearing restores the findings.+ expect(screen.getByText('Confusable names')).toBeTruthy();+ expect(screen.getByText('Sagging middle')).toBeTruthy();+ });});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 718948a92b..ad3f9aeb93 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -102,7 +102,7 @@ grep -i "what you want to do" client/src/lib/README.md| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. || `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. |+| `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. || `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`. |diff --git a/client/src/lib/editorialChecks.js b/client/src/lib/editorialChecks.jsindex a8726baf3b..8dec4b1254 100644--- a/client/src/lib/editorialChecks.js+++ b/client/src/lib/editorialChecks.js@@ -105,3 +105,145 @@ export function findingManuscriptLink(seriesId, comment) {: base;return comment?.id ? `${path}?comment=${encodeURIComponent(comment.id)}` : path;}++// ---- Findings triage filtering + sorting (#1600). Pure so the page and its+// unit tests share them; the component owns the URL-param plumbing. ----++const FINDING_SEVERITY_RANK = Object.freeze({ high: 0, medium: 1, low: 2 });+const FINDING_STATUS_RANK = Object.freeze({ open: 0, accepted: 1, dismissed: 2 });+const severityRank = (s) => (s in FINDING_SEVERITY_RANK ? FINDING_SEVERITY_RANK[s] : 2);+const statusRank = (s) => (s in FINDING_STATUS_RANK ? FINDING_STATUS_RANK[s] : 99);+const normSeverity = (c) => (c?.severity in FINDING_SEVERITY_RANK ? c.severity : 'low');+const normStatus = (c) => (c?.status === 'accepted' || c?.status === 'dismissed' ? c.status : 'open');++/** The issue facet key for a finding: its issue number as a string, or `none` for series-wide. */+export const findingIssueKey = (comment) =>+ (Number.isInteger(comment?.issueNumber) ? String(comment.issueNumber) : 'none');++/** Sort options offered in the triage toolbar. `id` is what persists in the URL. */+export const FINDING_SORT_OPTIONS = Object.freeze([+ { id: 'scope', label: 'Scope & check' },+ { id: 'severity', label: 'Severity' },+ { id: 'issue', label: 'Issue' },+ { id: 'status', label: 'Status' },+]);+const FINDING_SORT_IDS = Object.freeze(FINDING_SORT_OPTIONS.map((o) => o.id));+/** Coerce an arbitrary `sort` value to a known option id (default `scope`). */+export const normalizeFindingSort = (sort) => (FINDING_SORT_IDS.includes(sort) ? sort : 'scope');++/**+ * Enumerate the filter facets actually present in the current findings, so the+ * toolbar only offers values that exist. Takes the already-grouped findings+ * (groups carry the resolved scope + check label). Returns+ * `{ severities:Set, statuses:Set, scopes:[{scope,label}], checks:[{id,label}], issues:[{key,label}] }`+ * with checks ordered as the groups are (scope→label) and issues numeric-ascending+ * with the series-wide bucket last.+ */+export function deriveFindingFacets(groups = []) {+ const severities = new Set();+ const statuses = new Set();+ const scopes = new Map();+ const checks = [];+ const issues = new Map();+ for (const g of groups) {+ if (!scopes.has(g.scope)) scopes.set(g.scope, scopeLabel(g.scope));+ checks.push({ id: g.checkId, label: g.label });+ for (const c of g.comments) {+ severities.add(normSeverity(c));+ statuses.add(normStatus(c));+ const key = findingIssueKey(c);+ if (!issues.has(key)) issues.set(key, key === 'none' ? 'Series-wide' : `Issue ${c.issueNumber}`);+ }+ }+ const issueList = [...issues.entries()]+ .map(([key, label]) => ({ key, label }))+ .sort((a, b) => {+ if (a.key === 'none') return 1;+ if (b.key === 'none') return -1;+ return Number(a.key) - Number(b.key);+ });+ return {+ severities,+ statuses,+ scopes: [...scopes.entries()].map(([scope, label]) => ({ scope, label })),+ checks,+ issues: issueList,+ };+}++// A single comment passes the comment-level filters (severity/status/issue/query).+// Scope + check are group-level and filtered separately.+function commentPassesFilters(c, filters) {+ const { severities, statuses, issues, query } = filters;+ if (severities?.size && !severities.has(normSeverity(c))) return false;+ if (statuses?.size && !statuses.has(normStatus(c))) return false;+ if (issues?.size && !issues.has(findingIssueKey(c))) return false;+ if (query) {+ const hay = `${c.problem || ''} ${c.location || ''}`.toLowerCase();+ if (!hay.includes(query.toLowerCase())) return false;+ }+ return true;+}++// Recompute a group's open/total/severity counts + stale tally from a filtered+// comment subset so the header reflects what's actually shown (never lies).+function recountGroup(group, comments) {+ const counts = emptyCounts();+ let open = 0;+ let stale = 0;+ for (const c of comments) {+ if (normStatus(c) === 'open') {+ open += 1;+ counts[normSeverity(c)] += 1;+ if (c.stale) stale += 1;+ }+ }+ return { ...group, comments, open, total: comments.length, counts, stale };+}++function sortComments(comments, sort) {+ if (sort === 'scope') return comments;+ const cmp = {+ severity: (a, b) => severityRank(normSeverity(a)) - severityRank(normSeverity(b))+ || statusRank(normStatus(a)) - statusRank(normStatus(b)),+ status: (a, b) => statusRank(normStatus(a)) - statusRank(normStatus(b))+ || severityRank(normSeverity(a)) - severityRank(normSeverity(b)),+ issue: (a, b) => {+ const an = Number.isInteger(a.issueNumber) ? a.issueNumber : Infinity;+ const bn = Number.isInteger(b.issueNumber) ? b.issueNumber : Infinity;+ return an - bn || severityRank(normSeverity(a)) - severityRank(normSeverity(b));+ },+ }[sort];+ // Stable sort over a copy so the original grouping order is the tiebreak.+ return comments+ .map((c, i) => [c, i])+ .sort((a, b) => cmp(a[0], b[0]) || a[1] - b[1])+ .map(([c]) => c);+}++function sortGroups(groups, sort) {+ if (sort !== 'severity') return groups; // groups already arrive scope→label ordered+ // Surface the checks with the most severe open findings first.+ const weight = (g) => g.counts.high * 100 + g.counts.medium * 10 + g.counts.low;+ return [...groups].sort((a, b) => weight(b) - weight(a) || b.open - a.open);+}++/**+ * Apply the toolbar's filters + sort to the grouped findings. Drops groups whose+ * scope/check is filtered out or that have no comment matching the comment-level+ * filters, recomputes each surviving group's counts, sorts findings within each+ * group, then orders the groups. `filters` carries Sets for severities, statuses,+ * scopes, checkIds, issues plus a `query` string; any empty/absent facet is "all".+ */+export function applyFindingsView(groups = [], filters = {}, sort = 'scope') {+ const view = normalizeFindingSort(sort);+ const out = [];+ for (const g of groups) {+ if (filters.scopes?.size && !filters.scopes.has(g.scope)) continue;+ if (filters.checkIds?.size && !filters.checkIds.has(g.checkId)) continue;+ const matched = g.comments.filter((c) => commentPassesFilters(c, filters));+ if (!matched.length) continue;+ out.push(recountGroup(g, sortComments(matched, view)));+ }+ return sortGroups(out, view);+}diff --git a/client/src/lib/editorialChecks.test.js b/client/src/lib/editorialChecks.test.jsindex ac7a99f1ce..bd6ed1abfc 100644--- a/client/src/lib/editorialChecks.test.js+++ b/client/src/lib/editorialChecks.test.js@@ -5,6 +5,10 @@ import {openFindingsTotal,findingManuscriptLink,scopeLabel,+ deriveFindingFacets,+ applyFindingsView,+ normalizeFindingSort,+ findingIssueKey,} from './editorialChecks.js';const checks = [@@ -101,3 +105,115 @@ describe('scopeLabel', () => {expect(scopeLabel('')).toBe('Other');});});++const findingsFixture = () => [+ { id: 'a1', checkId: 'pacing', status: 'open', severity: 'high', issueNumber: 2, problem: 'Slow open', location: 'p1' },+ { id: 'a2', checkId: 'pacing', status: 'dismissed', severity: 'low', issueNumber: 2, problem: 'Old note' },+ { id: 'b1', checkId: 'naming', status: 'open', severity: 'medium', issueNumber: 1, problem: 'Confusable names' },+ { id: 'b2', checkId: 'naming', status: 'open', severity: 'low', issueNumber: null, problem: 'Series-wide naming' },+];+const fixtureRows = {+ pacing: { label: 'Pacing', scope: 'scene' },+ naming: { label: 'Naming', scope: 'series' },+};+const groupsFixture = () => groupFindingsByCheck(findingsFixture(), fixtureRows);++describe('findingIssueKey', () => {+ it('keys by issue number, bucketing series-wide findings under "none"', () => {+ expect(findingIssueKey({ issueNumber: 5 })).toBe('5');+ expect(findingIssueKey({ issueNumber: null })).toBe('none');+ expect(findingIssueKey({})).toBe('none');+ });+});++describe('normalizeFindingSort', () => {+ it('passes through known sort ids and defaults unknown to scope', () => {+ expect(normalizeFindingSort('severity')).toBe('severity');+ expect(normalizeFindingSort('issue')).toBe('issue');+ expect(normalizeFindingSort('bogus')).toBe('scope');+ expect(normalizeFindingSort(undefined)).toBe('scope');+ });+});++describe('deriveFindingFacets', () => {+ it('enumerates only the facets present, ordering checks scope→label and issues numeric-then-none', () => {+ const f = deriveFindingFacets(groupsFixture());+ expect([...f.severities].sort()).toEqual(['high', 'low', 'medium']);+ expect([...f.statuses].sort()).toEqual(['dismissed', 'open']);+ // scene (Pacing) sorts before series (Naming) per CHECK_SCOPE_ORDER.+ expect(f.checks.map((c) => c.id)).toEqual(['pacing', 'naming']);+ expect(f.scopes.map((s) => s.scope)).toEqual(['scene', 'series']);+ expect(f.issues.map((i) => i.key)).toEqual(['1', '2', 'none']);+ expect(f.issues.find((i) => i.key === 'none').label).toBe('Series-wide');+ });+});++describe('applyFindingsView', () => {+ it('returns all groups unchanged when no filters are active', () => {+ const view = applyFindingsView(groupsFixture(), {}, 'scope');+ expect(view.map((g) => g.checkId)).toEqual(['pacing', 'naming']);+ expect(view.reduce((n, g) => n + g.comments.length, 0)).toBe(4);+ });++ it('filters by severity and recomputes the group counts to match', () => {+ const view = applyFindingsView(groupsFixture(), { severities: new Set(['high']) }, 'scope');+ expect(view).toHaveLength(1);+ expect(view[0].checkId).toBe('pacing');+ expect(view[0].comments.map((c) => c.id)).toEqual(['a1']);+ expect(view[0].open).toBe(1);+ expect(view[0].total).toBe(1);+ expect(view[0].counts).toEqual({ high: 1, medium: 0, low: 0 });+ });++ it('filters by status (open only) dropping resolved findings', () => {+ const view = applyFindingsView(groupsFixture(), { statuses: new Set(['open']) }, 'scope');+ const ids = view.flatMap((g) => g.comments.map((c) => c.id));+ expect(ids).toEqual(['a1', 'b1', 'b2']);+ });++ it('filters by scope (category) and by check id', () => {+ const byScope = applyFindingsView(groupsFixture(), { scopes: new Set(['series']) }, 'scope');+ expect(byScope.map((g) => g.checkId)).toEqual(['naming']);+ const byCheck = applyFindingsView(groupsFixture(), { checkIds: new Set(['pacing']) }, 'scope');+ expect(byCheck.map((g) => g.checkId)).toEqual(['pacing']);+ });++ it('filters by issue, including the series-wide "none" bucket', () => {+ const issue2 = applyFindingsView(groupsFixture(), { issues: new Set(['2']) }, 'scope');+ expect(issue2.flatMap((g) => g.comments.map((c) => c.id))).toEqual(['a1', 'a2']);+ const seriesWide = applyFindingsView(groupsFixture(), { issues: new Set(['none']) }, 'scope');+ expect(seriesWide.flatMap((g) => g.comments.map((c) => c.id))).toEqual(['b2']);+ });++ it('matches the free-text query against problem and location, case-insensitively', () => {+ const view = applyFindingsView(groupsFixture(), { query: 'confusable' }, 'scope');+ expect(view.flatMap((g) => g.comments.map((c) => c.id))).toEqual(['b1']);+ const byLocation = applyFindingsView(groupsFixture(), { query: 'P1' }, 'scope');+ expect(byLocation.flatMap((g) => g.comments.map((c) => c.id))).toEqual(['a1']);+ });++ it('sorts findings within a group by severity (high→low) when sort=severity', () => {+ const view = applyFindingsView(groupsFixture(), { checkIds: new Set(['naming']) }, 'severity');+ expect(view[0].comments.map((c) => c.id)).toEqual(['b1', 'b2']); // medium before low+ });++ it('sorts groups by most-severe open findings first when sort=severity', () => {+ // pacing has a high open finding; naming's most severe open is medium.+ const view = applyFindingsView(groupsFixture(), {}, 'severity');+ expect(view.map((g) => g.checkId)).toEqual(['pacing', 'naming']);+ });++ it('sorts findings by issue number with series-wide last when sort=issue', () => {+ const view = applyFindingsView(groupsFixture(), { checkIds: new Set(['naming']) }, 'issue');+ expect(view[0].comments.map((c) => c.id)).toEqual(['b1', 'b2']); // issue 1 before series-wide+ });++ it('combines filters (AND semantics across facets)', () => {+ const view = applyFindingsView(+ groupsFixture(),+ { statuses: new Set(['open']), severities: new Set(['low']) },+ 'scope',+ );+ expect(view.flatMap((g) => g.comments.map((c) => c.id))).toEqual(['b2']);+ });+});