Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
984e594006 | ||
|
|
f49e6e4648 | ||
|
|
105cc082ea | ||
|
|
0a3ee0791f | ||
|
|
0da0a9f16c | ||
|
|
75bae2556c | ||
|
|
48f63dd763 |
@@ -42,30 +42,45 @@ jobs:
|
|||||||
echo "📊 Validating requirement traceability..."
|
echo "📊 Validating requirement traceability..."
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Parse JSON
|
# Denominators come from docs/requirements.md at run time — NEVER
|
||||||
|
# hardcode them here. This step previously divided by frozen literals
|
||||||
|
# (UR/39, IR/24, DR/48, JA/3, total 114) while the file had grown to
|
||||||
|
# 211 requirements, so it reported 158% coverage and the threshold
|
||||||
|
# below could never trip. See docs/specs/traceability-gate-repair.md.
|
||||||
TOTAL_TRACES=$(jq '.totalTraces' traces-report.json)
|
TOTAL_TRACES=$(jq '.totalTraces' traces-report.json)
|
||||||
UR=$(jq '.byType.UR | length' traces-report.json)
|
COVERED=$(jq '.coverage.covered' traces-report.json)
|
||||||
IR=$(jq '.byType.IR | length' traces-report.json)
|
TOTAL_REQS=$(jq '.coverage.total' traces-report.json)
|
||||||
DR=$(jq '.byType.DR | length' traces-report.json)
|
COVERAGE=$(jq '.coverage.percent' traces-report.json)
|
||||||
JA=$(jq '.byType.JA | length' traces-report.json)
|
|
||||||
|
|
||||||
# Print coverage report
|
|
||||||
echo "✅ TRACES Found: $TOTAL_TRACES"
|
echo "✅ TRACES Found: $TOTAL_TRACES"
|
||||||
echo ""
|
echo ""
|
||||||
echo "📋 Coverage Summary:"
|
echo "📋 Coverage Summary (traced / defined):"
|
||||||
echo " User Requirements (UR): $UR / 39 ($(( UR * 100 / 39 ))%)"
|
for T in UR IR DR JA; do
|
||||||
echo " Integration Requirements (IR): $IR / 24 ($(( IR * 100 / 24 ))%)"
|
TRACED=$(jq --arg t "$T" '[.byType[$t][] | select(. != null)] | length' traces-report.json)
|
||||||
echo " Development Requirements (DR): $DR / 48 ($(( DR * 100 / 48 ))%)"
|
DEFINED=$(jq --arg t "$T" '.defined[$t]' traces-report.json)
|
||||||
echo " Jellyfin API Requirements (JA): $JA / 3 ($(( JA * 100 / 3 ))%)"
|
echo " $T: $TRACED / $DEFINED"
|
||||||
|
done
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
COVERED=$((UR + IR + DR + JA))
|
|
||||||
TOTAL_REQS=114
|
|
||||||
COVERAGE=$((COVERED * 100 / TOTAL_REQS))
|
|
||||||
|
|
||||||
echo "📈 Overall Coverage: $COVERED / $TOTAL_REQS ($COVERAGE%)"
|
echo "📈 Overall Coverage: $COVERED / $TOTAL_REQS ($COVERAGE%)"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
|
# Traced IDs that requirements.md does not define (typo, or a deleted
|
||||||
|
# requirement). These do not count toward coverage.
|
||||||
|
ORPHANED=$(jq -c '.coverage.orphaned' traces-report.json)
|
||||||
|
if [ "$ORPHANED" != "[]" ]; then
|
||||||
|
echo "⚠️ Traced but not defined in requirements.md: $ORPHANED"
|
||||||
|
echo ""
|
||||||
|
fi
|
||||||
|
|
||||||
|
# A ratio above 100% means the computation is broken — the exact
|
||||||
|
# condition that hid the stale-denominator bug. Fail loudly.
|
||||||
|
if [ "$COVERAGE" -gt 100 ]; then
|
||||||
|
echo "❌ ERROR: Coverage ($COVERAGE%) exceeds 100% — the gate is miscomputing."
|
||||||
|
echo " Orphaned IDs: $ORPHANED"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
# Check minimum threshold
|
# Check minimum threshold
|
||||||
MIN_THRESHOLD=50
|
MIN_THRESHOLD=50
|
||||||
if [ "$COVERAGE" -lt "$MIN_THRESHOLD" ]; then
|
if [ "$COVERAGE" -lt "$MIN_THRESHOLD" ]; then
|
||||||
|
|||||||
@@ -183,8 +183,14 @@ and [docs/build-release.md](docs/build-release.md).
|
|||||||
backend expand it. Single-type presentation (`itemType: "Movie"`, "this page
|
backend expand it. Single-type presentation (`itemType: "Movie"`, "this page
|
||||||
shows albums") is fine; a *category → set of types* mapping in `src/` is a leak.
|
shows albums") is fine; a *category → set of types* mapping in `src/` is a leak.
|
||||||
`bun run check:boundary` is the tripwire; the real gate is the spec's layer
|
`bun run check:boundary` is the tripwire; the real gate is the spec's layer
|
||||||
assignment. See [scoped-search-boundary.md](docs/specs/scoped-search-boundary.md)
|
assignment. The canonical example lives in Rust:
|
||||||
for the incident this rule came from.
|
`SearchScope::item_types()` in `repository/types.rs` expands an opaque scope the
|
||||||
|
frontend sends. See [scoped-search-boundary.md](docs/specs/scoped-search-boundary.md)
|
||||||
|
for the incident this rule came from — note the tripwire missed that leak for
|
||||||
|
months because the mapping was assigned to a named const rather than written
|
||||||
|
inline at the query, so **a green `check:boundary` is not proof**; it flags
|
||||||
|
item-type array literals only, not run-time-built sets or `switch`/`||`
|
||||||
|
taxonomy.
|
||||||
|
|
||||||
## Writing specs
|
## Writing specs
|
||||||
|
|
||||||
|
|||||||
+7
-3
@@ -117,9 +117,13 @@ RUN cd src-tauri && cargo fetch && cd .. && \
|
|||||||
|
|
||||||
# Desktop packaging stages build FROM the unified registry builder image (see the
|
# Desktop packaging stages build FROM the unified registry builder image (see the
|
||||||
# BUILDER_IMAGE ARG at the top), which already carries every packaging tool
|
# BUILDER_IMAGE ARG at the top), which already carries every packaging tool
|
||||||
# (rpm/file for Linux, mingw-w64 + nsis + the x86_64-pc-windows-gnu rust target
|
# (rpm/file for Linux, cargo-xwin + nsis + the x86_64-pc-windows-msvc rust
|
||||||
# for Windows). ONE source of dependency truth, shared with CI — no per-stage
|
# target for Windows). ONE source of dependency truth, shared with CI — no
|
||||||
# apt/rustup here.
|
# per-stage apt/rustup here.
|
||||||
|
#
|
||||||
|
# NOTE: Windows uses the MSVC target via cargo-xwin, NOT mingw/GNU — the GNU
|
||||||
|
# toolchain cannot bundle an NSIS installer from Linux. See
|
||||||
|
# scripts/build-windows-cross.sh.
|
||||||
|
|
||||||
# Linux desktop packaging environment (deb + rpm; Arch is Dockerfile.arch).
|
# Linux desktop packaging environment (deb + rpm; Arch is Dockerfile.arch).
|
||||||
# Thin layer over the builder — the actual build runs at container-run time on
|
# Thin layer over the builder — the actual build runs at container-run time on
|
||||||
|
|||||||
@@ -220,7 +220,7 @@ Internal architecture, components, and application logic.
|
|||||||
| DR-060 | Multi-server store and active-account selection: save/get/delete server, save/get user, set/get active user (per-server), active-session resolution | Storage | UR-047 | Partial (store done; server-switcher UI pending) |
|
| DR-060 | Multi-server store and active-account selection: save/get/delete server, save/get user, set/get active user (per-server), active-session resolution | Storage | UR-047 | Partial (store done; server-switcher UI pending) |
|
||||||
| DR-061 | Episode Focus View: episode hero followed *immediately* by the "More Episodes" strip — a forward-biased window (~3 before / ~6 after) around the current episode, spanning season boundaries in series order, with the current episode present and badged, per-card resume progress and watched state, and click-to-swap focus (no playback) | UI | UR-048 | Done |
|
| DR-061 | Episode Focus View: episode hero followed *immediately* by the "More Episodes" strip — a forward-biased window (~3 before / ~6 after) around the current episode, spanning season boundaries in series order, with the current episode present and badged, per-card resume progress and watched state, and click-to-swap focus (no playback) | UI | UR-048 | Done |
|
||||||
| DR-062 | Detail-page section ordering: continuation content precedes discovery content — Episode Focus View renders hero → episode strip → cast → similar; Series renders hero → seasons/episodes → cast → similar | UI | UR-048 | Done |
|
| DR-062 | Detail-page section ordering: continuation content precedes discovery content — Episode Focus View renders hero → episode strip → cast → similar; Series renders hero → seasons/episodes → cast → similar | UI | UR-048 | Done |
|
||||||
| DR-063 | Search scope resolver mapping the originating route to an `includeItemTypes` set (All / Music / Movies / TV), defaulting to All for Home, `/library`, and the search tab | UI | UR-049 | Implemented |
|
| DR-063 | Search scope taxonomy owned by Rust: `SearchScope` (All / Music / Movies / TV) crosses IPC as an opaque enum and `SearchScope::item_types()` expands it to Jellyfin item types, resolved once in `repository_search` before the cache and server paths diverge so online and offline filter identically; `All` expands to *no* filter rather than the union of the other scopes (which would drop People and folders). The frontend maps the originating route to a scope (`resolveSearchScope`, presentation) and never names an item type for search | Backend | UR-049 | Implemented |
|
||||||
| DR-064 | Scope chip row rendered under the search bar on both the search page and the in-library header search: preselected from context, horizontally scrollable, re-runs the search preserving the query on change | UI | UR-049 | Implemented |
|
| DR-064 | Scope chip row rendered under the search bar on both the search page and the in-library header search: preselected from context, horizontally scrollable, re-runs the search preserving the query on change | UI | UR-049 | Implemented |
|
||||||
| DR-065 | Thread `SearchOptions.includeItemTypes` through `library.search()` so the global/header search honours scope (backend online + offline paths already support it) | UI | UR-049 | Implemented |
|
| DR-065 | Thread `SearchOptions.includeItemTypes` through `library.search()` so the global/header search honours scope (backend online + offline paths already support it) | UI | UR-049 | Implemented |
|
||||||
| DR-066 | Persisted search result group order with a drag-and-drop settings list, keyboard-accessible reordering, a shipped default (see DR-091 for the current group set and order), and empty-group omission | Settings | UR-050 | Implemented |
|
| DR-066 | Persisted search result group order with a drag-and-drop settings list, keyboard-accessible reordering, a shipped default (see DR-091 for the current group set and order), and empty-group omission | Settings | UR-050 | Implemented |
|
||||||
@@ -247,6 +247,8 @@ Internal architecture, components, and application logic.
|
|||||||
| DR-090 | Relevance ranking in Rust (`domain/search_rank.rs`): results sort by match position (prefix → word-start → mid-word substring → no name match) then by media kind (containers before their contents), stably so the backend's own relevance breaks ties. Applied in `repository_search` to both the instant cache result and the merged cache+server union, so the list does not reshuffle when server results land | Backend | UR-060 | Done |
|
| DR-090 | Relevance ranking in Rust (`domain/search_rank.rs`): results sort by match position (prefix → word-start → mid-word substring → no name match) then by media kind (containers before their contents), stably so the backend's own relevance breaks ties. Applied in `repository_search` to both the instant cache result and the merged cache+server union, so the list does not reshuffle when server results land | Backend | UR-060 | Done |
|
||||||
| DR-091 | Search result groups split TV into separate Shows and Episodes groups and add a People group (default order: Shows → Episodes → Movies → Songs → Albums → Artists → People); a stored `tvShows` order from before the split expands in place to shows+episodes so an upgrading user keeps their arrangement | UI | UR-060 | Done |
|
| DR-091 | Search result groups split TV into separate Shows and Episodes groups and add a People group (default order: Shows → Episodes → Movies → Songs → Albums → Artists → People); a stored `tvShows` order from before the split expands in place to shows+episodes so an upgrading user keeps their arrangement | UI | UR-060 | Done |
|
||||||
| DR-092 | Video tap gestures resolve in `tapGestures.ts` (pure, unit-tested) rather than inline in `VideoPlayer.svelte`: `registerTap` returns `pending` for a first tap — the component defers `togglePlayPause` behind a `DOUBLE_TAP_WINDOW_MS` (300 ms) timer that a second tap cancels — or `seek` (+30 s right / −10 s left) for a second tap inside the window; a consumed second tap resets the state so a third tap starts fresh, and a swipe cancels the pending tap. The compatibility `click` the browser synthesizes after a touch tap is filtered in `handleVideoClick` so it cannot bypass the deferral. `resolveSeekTarget` converts the delta to the absolute position the facade requires, clamped to `[0, duration]` and chained off a still-in-flight `pendingSeekTarget` so back-to-back skips accumulate instead of all resolving against a not-yet-updated position | UI | UR-061 | Done |
|
| DR-092 | Video tap gestures resolve in `tapGestures.ts` (pure, unit-tested) rather than inline in `VideoPlayer.svelte`: `registerTap` returns `pending` for a first tap — the component defers `togglePlayPause` behind a `DOUBLE_TAP_WINDOW_MS` (300 ms) timer that a second tap cancels — or `seek` (+30 s right / −10 s left) for a second tap inside the window; a consumed second tap resets the state so a third tap starts fresh, and a swipe cancels the pending tap. The compatibility `click` the browser synthesizes after a touch tap is filtered in `handleVideoClick` so it cannot bypass the deferral. `resolveSeekTarget` converts the delta to the absolute position the facade requires, clamped to `[0, duration]` and chained off a still-in-flight `pendingSeekTarget` so back-to-back skips accumulate instead of all resolving against a not-yet-updated position | UI | UR-061 | Done |
|
||||||
|
| DR-094 | Frontend boundary tripwire (`scripts/check-frontend-boundary.sh`) detects Jellyfin item-type array literals **anywhere** in `src/` rather than only inline at an `includeItemTypes:` query site, so a category→type mapping cannot evade the check by being assigned to a named const (the evasion that let the `scoped-search` leak pass CI); requires two adjacent type literals so single-type presentation and `item.type ===` inspection stay legal, and caps the allowlist to force taxonomy into Rust instead of accumulating exceptions | Tooling | - | Done |
|
||||||
|
| DR-093 | Traceability coverage gate derives its requirement denominators from `requirements.md` at run time rather than hardcoded literals: `countDefinedRequirements` counts an ID only where it leads a markdown table row (ignoring the "Traces To" column and prose) and deduplicates IDs listed both in the definition tables and in the §3 traceability matrix; `computeCoverage` reports the *intersection* of traced and defined IDs so an ID traced in code but absent from `requirements.md` is surfaced as `orphaned` instead of inflating the ratio past 100%. UT/IT test identifiers are excluded as a separate taxonomy. CI and `bun run traces:coverage` share this computation and fail on both a sub-threshold and an impossible >100% result | Tooling | - | Done |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,215 @@
|
|||||||
|
# Spec: Harden the frontend boundary tripwire
|
||||||
|
|
||||||
|
**Status:** Implemented
|
||||||
|
**Requirements:** DR-094
|
||||||
|
**UX spec:** n/a — developer tooling.
|
||||||
|
**Supersedes / revises:** revises the detection rule in
|
||||||
|
[scripts/check-frontend-boundary.sh](../../scripts/check-frontend-boundary.sh);
|
||||||
|
the boundary *policy* in [scoped-search-boundary.md](scoped-search-boundary.md)
|
||||||
|
is unchanged.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`bun run check:boundary` passes on a tree that contains the exact leak it was
|
||||||
|
built to catch. It matches a multi-type array only when written **inline at the
|
||||||
|
query site**, so assigning the same array to a named const evades it entirely —
|
||||||
|
which is how [searchScope.ts](../../src/lib/utils/searchScope.ts) has kept a
|
||||||
|
category→item-type mapping through every green CI run. This spec broadens the
|
||||||
|
match to item-type array literals anywhere in `src/`, and resolves the handful
|
||||||
|
of legitimate hits that broadening surfaces.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
The current pattern is anchored to the `includeItemTypes:` key:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PATTERN='includeItemTypes:[[:space:]]*\[[^]]*,[^]]*\]'
|
||||||
|
```
|
||||||
|
|
||||||
|
The live leak is not written that way:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// src/lib/utils/searchScope.ts:29 — invisible to the tripwire
|
||||||
|
const SCOPE_ITEM_TYPES = { music: ["MusicAlbum", "MusicArtist", "Audio", "Playlist"], … };
|
||||||
|
```
|
||||||
|
|
||||||
|
The taxonomy and the query are one indirection apart, and the grep only sees the
|
||||||
|
query. The script's own header is admirably honest that it is "a TRIPWIRE, NOT A
|
||||||
|
PROOF" — but the gap here is not a subtle judgment call it was designed to
|
||||||
|
defer to human review. It is the *crudest form* of the violation, one `const`
|
||||||
|
away from the shape it does match, in the very file the founding incident was
|
||||||
|
written about.
|
||||||
|
|
||||||
|
Broadening the pattern to any item-type array literal finds it, with a
|
||||||
|
manageable number of other hits (measured, not estimated):
|
||||||
|
|
||||||
|
| Site | Verdict |
|
||||||
|
|------|---------|
|
||||||
|
| `searchScope.ts:30,32` | 🔴 The leak. Removed by [scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md). |
|
||||||
|
| `PersonDetailView.svelte:30` | Already allowlisted, with a recorded reason. |
|
||||||
|
| `DownloadedBrowse.svelte:95` | Borderline — `["MusicAlbum","Series","Season","BoxSet"].includes(item.type)` as an "is this a container?" predicate. |
|
||||||
|
| `GenericMediaListPage.svelte:298` | Borderline — `["MusicAlbum","MusicArtist","Audio","Playlist"].includes(config.itemType)` as a music-styling predicate. |
|
||||||
|
| 6 hits in `*.test.ts` | Excluded; tests legitimately name types. |
|
||||||
|
|
||||||
|
Four non-test sites total. This is a tractable change, not a boil-the-ocean one.
|
||||||
|
|
||||||
|
## Layer assignment
|
||||||
|
|
||||||
|
Tooling only — no application logic, nothing crosses IPC. The two borderline
|
||||||
|
*application* sites do get a layer decision, below.
|
||||||
|
|
||||||
|
| Logic / responsibility | Layer | Why it belongs there |
|
||||||
|
|------------------------|-------|----------------------|
|
||||||
|
| Detecting item-type array literals in `src/` | Build tooling (`scripts/`) | Static analysis of repo source; belongs beside the existing check. |
|
||||||
|
| "Is this item a container?" (`DownloadedBrowse`) | **Rust** (recommended) | Containers-vs-leaves is Jellyfin structure, and the set grows when Jellyfin adds a container type — the litmus test's "yes". Prefer a `MediaItem.isContainer` boolean from the backend over a type-set predicate in a component. |
|
||||||
|
| "Is this music content?" (`GenericMediaListPage`) | **Frontend, allowlisted** | Selects a grid *style*. It reads `config.itemType`, a value the page already declares about itself, and changes only if the UI is redesigned — the litmus test's "no". Single-type presentation is explicitly not the target of the rule. |
|
||||||
|
|
||||||
|
`DownloadedBrowse` defaults to Rust per the checklist's borderline rule; see
|
||||||
|
Out of scope for why the migration itself is deferred rather than bundled.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### 1. Broaden the pattern
|
||||||
|
|
||||||
|
Replace the key-anchored pattern with one matching an array literal of two or
|
||||||
|
more known Jellyfin item types, wherever it appears:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Two or more adjacent item-type string literals inside a bracket.
|
||||||
|
TYPES='Movie|Series|Episode|Audio|MusicAlbum|MusicArtist|MusicVideo|Season|BoxSet|Playlist|Book|AudioBook|Video|Person|Folder|CollectionFolder|TvChannel|LiveTvChannel'
|
||||||
|
PATTERN="\[[[:space:]]*\"($TYPES)\"[[:space:]]*,[[:space:]]*\"($TYPES)\""
|
||||||
|
```
|
||||||
|
|
||||||
|
Properties worth stating, because each is a deliberate trade:
|
||||||
|
|
||||||
|
- **Not anchored to any key**, so a named const, a function return, a `Record`
|
||||||
|
value, or an inline query all match equally.
|
||||||
|
- **Requires two adjacent type literals**, preserving the existing and correct
|
||||||
|
carve-out that single-type presentation (`itemType: "Movie"`) is legitimate.
|
||||||
|
- **Requires string literals**, so `item.type === "Audio"` (display inspection)
|
||||||
|
still does not match.
|
||||||
|
- **Explicit type list**, not `[A-Z][a-z]+`, so arbitrary string arrays
|
||||||
|
(`["High","Low"]`, `["Songs","Albums"]`) do not produce noise.
|
||||||
|
|
||||||
|
Keep `grep -rInE`, the `*.test.*` exclusion, and the allowlist mechanism as they
|
||||||
|
are — all three work.
|
||||||
|
|
||||||
|
### 2. Resolve the surfaced sites
|
||||||
|
|
||||||
|
- `PersonDetailView.svelte` — already allowlisted; entry unchanged.
|
||||||
|
- `GenericMediaListPage.svelte` — **add to the allowlist** with the reason from
|
||||||
|
the layer table (grid styling over a self-declared `itemType`).
|
||||||
|
- `DownloadedBrowse.svelte` — **add to the allowlist with a `TODO` naming the
|
||||||
|
preferred fix** (backend `isContainer`). An allowlist entry that records a
|
||||||
|
known-borderline decision is honest; silently broadening the pattern to miss
|
||||||
|
it would not be.
|
||||||
|
- `searchScope.ts` — **not allowlisted.** It is the leak, and
|
||||||
|
[scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md)
|
||||||
|
deletes it.
|
||||||
|
|
||||||
|
### 3. 🔴 Sequencing
|
||||||
|
|
||||||
|
**This spec must land after Stage 1 of
|
||||||
|
[scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md).**
|
||||||
|
Hardening the tripwire first turns `master` red on a violation with no fix
|
||||||
|
available, and the only ways out are reverting the hardening or allowlisting the
|
||||||
|
leak — the second of which is exactly how a boundary rule dies.
|
||||||
|
|
||||||
|
### 4. Keep the allowlist honest
|
||||||
|
|
||||||
|
The script already warns that a growing allowlist means the boundary is eroding.
|
||||||
|
This change takes it from 1 entry to 3, which is close to that line. Add a hard
|
||||||
|
cap so drift is caught mechanically rather than by whoever notices:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
MAX_ALLOWLIST=4
|
||||||
|
if [ "${#ALLOWLIST[@]}" -gt "$MAX_ALLOWLIST" ]; then
|
||||||
|
echo "❌ Allowlist has ${#ALLOWLIST[@]} entries (max $MAX_ALLOWLIST)."
|
||||||
|
echo " Push taxonomy into Rust instead of appending here."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
The cap is deliberately just above the current count: the next exception forces
|
||||||
|
a conversation instead of a one-line append.
|
||||||
|
|
||||||
|
### 5. Restate the limits
|
||||||
|
|
||||||
|
The header's "tripwire, not a proof" caveat stays and gets sharper. The broadened
|
||||||
|
pattern still cannot see:
|
||||||
|
|
||||||
|
- a type set built at run time (`[...musicTypes, "Playlist"]`),
|
||||||
|
- types split across variables (`const A = "Audio"; [A, B]`),
|
||||||
|
- taxonomy expressed as a `switch` or chained `||` rather than an array.
|
||||||
|
|
||||||
|
The spec-review checklist remains the real gate. This raises the floor; it does
|
||||||
|
not close the class.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- **Migrating `DownloadedBrowse` to a backend `isContainer` flag.** It touches
|
||||||
|
`MediaItem`, `bindings.ts`, and the offline path — its own spec. Allowlisted
|
||||||
|
with a TODO here so it is recorded, not forgotten.
|
||||||
|
- The scoped-search fix itself — [scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md).
|
||||||
|
- Detecting the run-time-construction cases listed above.
|
||||||
|
- Extending the check to Rust or Kotlin (the rule is about `src/`).
|
||||||
|
- Changing the boundary *policy* in CLAUDE.md.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] With `searchScope.ts` reverted to its leaking form, `bun run check:boundary`
|
||||||
|
**fails** and names `src/lib/utils/searchScope.ts`. This is the criterion
|
||||||
|
that proves the fix — verify it explicitly before landing.
|
||||||
|
- [ ] On the post-fix tree, `bun run check:boundary` passes.
|
||||||
|
- [ ] A newly introduced `const X = ["Movie", "Series"]` in any non-test `src/`
|
||||||
|
file fails the check (regression test for the const-indirection evasion).
|
||||||
|
- [ ] `itemType: "Movie"` and `item.type === "Audio"` do **not** trip the check.
|
||||||
|
- [ ] `["High", "Low"]` and other non-item-type arrays do **not** trip it.
|
||||||
|
- [ ] Test files are still excluded (the 6 known test hits stay silent).
|
||||||
|
- [ ] The allowlist has exactly 3 entries, each with a written reason; a 5th
|
||||||
|
entry fails the check via `MAX_ALLOWLIST`.
|
||||||
|
- [ ] The script header still states it is a tripwire, not a proof, and names the
|
||||||
|
evasions it cannot see.
|
||||||
|
- [ ] `bun run check` and `bun run test` pass.
|
||||||
|
- [ ] `bun run test:all` passes.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
The script is bash and has no test harness. Verify by construction — each is a
|
||||||
|
temporary edit, run, revert:
|
||||||
|
|
||||||
|
1. Reintroduce the `SCOPE_ITEM_TYPES` const → **must fail**.
|
||||||
|
2. Add `const T = ["Movie","Series"]` to a scratch `.svelte` file → **must fail**.
|
||||||
|
3. Add the same to a `.test.ts` file → **must pass** (exclusion holds).
|
||||||
|
4. Add `itemType: "Movie"` → **must pass**.
|
||||||
|
5. Add a 5th allowlist entry → **must fail** on the cap.
|
||||||
|
|
||||||
|
Record the five results in the PR description. A grep-based gate that has never
|
||||||
|
been observed failing is indistinguishable from one that cannot fail — which is
|
||||||
|
the precise condition this whole spec exists to correct.
|
||||||
|
|
||||||
|
## TRACES
|
||||||
|
|
||||||
|
Allocate in `requirements.md`:
|
||||||
|
|
||||||
|
- **DR-094** — "Frontend boundary tripwire detects Jellyfin item-type array
|
||||||
|
literals anywhere in `src/` (not only inline at an `includeItemTypes:` query
|
||||||
|
site), so a category→type mapping cannot evade the check via a named const;
|
||||||
|
allowlist is capped to force taxonomy into Rust rather than accumulating
|
||||||
|
exceptions." Category: Tooling. Status: Done on merge.
|
||||||
|
|
||||||
|
Shell scripts carry no `TRACES:` comment convention in this repo; reference
|
||||||
|
DR-094 in the script header comment instead.
|
||||||
|
|
||||||
|
## Notes for the implementer
|
||||||
|
|
||||||
|
- A parallel Claude session may be active in this repo — `git diff` before
|
||||||
|
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||||
|
- **Land after Stage 1 of the scoped-search fix** — see §3. This is the one
|
||||||
|
ordering constraint that will break `master` if ignored.
|
||||||
|
- Test the regex against the current tree *before* committing:
|
||||||
|
`grep -rInE "$PATTERN" src/ | grep -v '\.test\.'` should return exactly the
|
||||||
|
four sites in the Motivation table.
|
||||||
|
- The `TYPES` list will need occasional extension as Jellyfin adds types.
|
||||||
|
That is acceptable for a tripwire — an unlisted type produces a false
|
||||||
|
negative, never a false positive, so the check degrades safely.
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
# Spec: Build provenance (git describe + build profile)
|
||||||
|
|
||||||
|
**Status:** Proposed
|
||||||
|
**Requirements:** new DR-093 (build provenance surfaced in-app and in logs); no UR — this is a diagnostic capability, not a user feature
|
||||||
|
**UX spec:** n/a — adds an About block to Settings; no new flow
|
||||||
|
**Supersedes / revises:** —
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Make every build say exactly what it is. Today a running JellyTau reports no
|
||||||
|
version at all — not in the UI, not in the logs — and the only version string in
|
||||||
|
the tree is the hand-maintained `0.2.0` duplicated across three files.
|
||||||
|
|
||||||
|
This adds a `build.rs`-generated provenance string (`git describe` + short SHA +
|
||||||
|
dirty flag + debug/release profile), exposes it over IPC, and renders it in a new
|
||||||
|
Settings › About block. It also removes one of the three hand-bumped version
|
||||||
|
files.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
The concrete problem: when a user reports "the equalizer does nothing on my
|
||||||
|
device" — which is a live risk for v0.2.0, whose Android audio settings are not
|
||||||
|
yet device-verified — there is currently no way to tell which build they are
|
||||||
|
running. Tag? Master? A local debug build from three weeks ago? The bug report
|
||||||
|
cannot distinguish them.
|
||||||
|
|
||||||
|
Two smaller irritations this also fixes:
|
||||||
|
|
||||||
|
- **Debug builds masquerade as releases.** `0.2.0` is `0.2.0` whether it came
|
||||||
|
from a tagged release or `bun run tauri dev`.
|
||||||
|
- **Three files carry the version.** `package.json`, `src-tauri/Cargo.toml` and
|
||||||
|
`src-tauri/tauri.conf.json` must be bumped in lockstep; the release checklist
|
||||||
|
exists partly to stop them drifting.
|
||||||
|
|
||||||
|
### What this deliberately does *not* do
|
||||||
|
|
||||||
|
**The canonical version stays hand-bumped in `Cargo.toml`.** Cargo requires a
|
||||||
|
literal semver string at manifest-parse time and cannot derive it from git. The
|
||||||
|
same is true of `tauri.conf.json`. Attempting to source the *release* version
|
||||||
|
from a tag trades a scripted, reviewable bump for a fragile build-time
|
||||||
|
dependency that breaks in exactly the environment we care most about (CI, in
|
||||||
|
Docker, from a shallow clone).
|
||||||
|
|
||||||
|
So: **the release version is authored; the build provenance is derived.** They
|
||||||
|
answer different questions — "what release is this?" versus "what commit is this
|
||||||
|
binary actually built from?" — and only the second benefits from git.
|
||||||
|
|
||||||
|
## Layer assignment
|
||||||
|
|
||||||
|
| Logic / responsibility | Layer | Why it belongs there |
|
||||||
|
|------------------------|-------|----------------------|
|
||||||
|
| Capturing git describe / SHA / dirty state at compile time | Rust (`build.rs`) | Only the Rust build has a compile step that can shell out to git and bake the result into the binary. A frontend equivalent would report the *dev server's* state, not the shipped binary's. |
|
||||||
|
| Degrading to a sentinel when git is unavailable | Rust (`build.rs`) | Build-environment concern. Must never fail the build — CI runs in Docker from a shallow clone. |
|
||||||
|
| Release version (`0.2.0`) | Rust (`Cargo.toml`, authored) | Domain fact about the product, not derivable from the environment. |
|
||||||
|
| Deciding *what a build is* (release / dev / dirty) | Rust | Domain classification. The frontend must not infer "this is a dev build" from a string shape — it renders what it is told. |
|
||||||
|
| Rendering the About block, copy-to-clipboard | Frontend | Pure presentation. |
|
||||||
|
|
||||||
|
Borderline row: the release/dev/dirty classification could be done in the
|
||||||
|
frontend by pattern-matching the describe string. It goes to Rust because that is
|
||||||
|
a *rule about what constitutes a release build*, and it would have to change if
|
||||||
|
the tagging scheme changed — the litmus test in the template puts that in Rust.
|
||||||
|
Send a typed enum, not a string for the frontend to parse.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### `build.rs`
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn main() {
|
||||||
|
emit_build_provenance();
|
||||||
|
tauri_build::build()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_build_provenance() {
|
||||||
|
let describe = std::process::Command::new("git")
|
||||||
|
.args(["describe", "--tags", "--always", "--dirty"])
|
||||||
|
.output()
|
||||||
|
.ok()
|
||||||
|
.filter(|o| o.status.success())
|
||||||
|
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||||
|
.map(|s| s.trim().to_string())
|
||||||
|
.unwrap_or_else(|| "unknown".to_string());
|
||||||
|
|
||||||
|
println!("cargo:rustc-env=JELLYTAU_GIT_DESCRIBE={describe}");
|
||||||
|
|
||||||
|
// Rebuild when HEAD moves or a ref is written, so the string does not go
|
||||||
|
// stale across commits. Guarded: these paths do not exist in a git-less
|
||||||
|
// source tarball, and emitting rerun-if-changed for a missing path would
|
||||||
|
// force a rebuild every time.
|
||||||
|
for p in [".git/HEAD", ".git/refs"] {
|
||||||
|
if std::path::Path::new("../").join(p).exists() {
|
||||||
|
println!("cargo:rerun-if-changed=../{p}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
🔴 **`build.rs` must never fail the build.** Every git call is
|
||||||
|
`.ok()`-swallowed; a missing git binary, a shallow clone, or a source tarball all
|
||||||
|
yield `"unknown"`. A build that breaks because git is absent would be a worse bug
|
||||||
|
than the one this fixes.
|
||||||
|
|
||||||
|
Note the `../` prefixes: `build.rs` runs with CWD at `src-tauri/`, so the repo's
|
||||||
|
`.git` is one level up.
|
||||||
|
|
||||||
|
### The provenance type
|
||||||
|
|
||||||
|
```rust
|
||||||
|
/// TRACES: DR-093
|
||||||
|
#[derive(specta::Type, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct BuildInfo {
|
||||||
|
/// Authored release version (Cargo.toml).
|
||||||
|
pub version: String,
|
||||||
|
/// `git describe --tags --always --dirty`, or "unknown".
|
||||||
|
pub git_describe: String,
|
||||||
|
/// What kind of build this is — classified in Rust, not inferred by the UI.
|
||||||
|
pub kind: BuildKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TRACES: DR-093
|
||||||
|
#[derive(specta::Type, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub enum BuildKind {
|
||||||
|
/// Built from a clean, exactly-tagged commit in release mode.
|
||||||
|
Release,
|
||||||
|
/// Release-mode build that is not on a clean tag (e.g. master, or dirty).
|
||||||
|
Untagged,
|
||||||
|
/// debug_assertions build.
|
||||||
|
Development,
|
||||||
|
/// Git state unavailable at build time.
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Classification:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let kind = if cfg!(debug_assertions) {
|
||||||
|
BuildKind::Development
|
||||||
|
} else if describe == "unknown" {
|
||||||
|
BuildKind::Unknown
|
||||||
|
} else if describe.contains('-') { // "v0.2.0-3-gcb79a37" or "...-dirty"
|
||||||
|
BuildKind::Untagged
|
||||||
|
} else {
|
||||||
|
BuildKind::Release
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Command
|
||||||
|
|
||||||
|
```rust
|
||||||
|
/// TRACES: DR-093
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn get_build_info() -> BuildInfo { … }
|
||||||
|
```
|
||||||
|
|
||||||
|
No parameters, so the camelCase param rule does not apply; the struct fields do
|
||||||
|
need `#[serde(rename_all = "camelCase")]` (above). Regenerate `bindings.ts`.
|
||||||
|
|
||||||
|
Also log the provenance once at startup, next to the existing init logging —
|
||||||
|
that is what makes a user-submitted log file self-identifying, which is most of
|
||||||
|
the value.
|
||||||
|
|
||||||
|
### Settings › About
|
||||||
|
|
||||||
|
A new block at the bottom of `src/routes/settings/+page.svelte`, rendering
|
||||||
|
version, describe string, and a badge for non-release builds. One
|
||||||
|
copy-to-clipboard button that yields a paste-ready block for bug reports:
|
||||||
|
|
||||||
|
```
|
||||||
|
JellyTau 0.2.0 (v0.2.0-3-gcb79a37-dirty, development)
|
||||||
|
linux x86_64
|
||||||
|
```
|
||||||
|
|
||||||
|
Platform/arch come from the existing Tauri APIs; do not shell out.
|
||||||
|
|
||||||
|
### Removing one version file
|
||||||
|
|
||||||
|
`tauri.conf.json`'s `"version"` field can be omitted, in which case Tauri falls
|
||||||
|
back to the Cargo version. That takes the bump from three files to two.
|
||||||
|
|
||||||
|
**Verify before adopting**: confirm the Android `versionName`/`versionCode` and
|
||||||
|
the NSIS installer version still resolve correctly with the field absent —
|
||||||
|
Android packaging in particular reads the Tauri config. If either regresses,
|
||||||
|
keep the field and drop this part; it is a convenience, not the point of the
|
||||||
|
spec.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- Deriving the *release* version from git tags (see Motivation).
|
||||||
|
- A build-time timestamp. It defeats reproducible builds and adds little over
|
||||||
|
the commit SHA.
|
||||||
|
- CI provenance/attestation, SBOM, signing.
|
||||||
|
- Displaying the Jellyfin server version (separate concern, already available
|
||||||
|
from `/System/Info`).
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] `cargo build` succeeds with git absent, from a shallow clone, and from a source tarball with no `.git` — yielding `"unknown"` in each case, never a build failure.
|
||||||
|
- [ ] A tagged clean release build reports `BuildKind::Release`; `bun run tauri dev` reports `Development`; a dirty tree reports `Untagged` (release mode) with `-dirty` in the describe string.
|
||||||
|
- [ ] The describe string changes after a new commit without a manual `cargo clean` (rerun-if-changed works).
|
||||||
|
- [ ] Provenance is logged once at startup.
|
||||||
|
- [ ] Settings › About renders version + describe + build-kind badge, with working copy-to-clipboard.
|
||||||
|
- [ ] 🔴 CI checkouts that build a shippable artifact set `fetch-depth: 0`, or their artifacts are knowingly stamped `unknown`. Currently only `publish-docs.yml` sets it; `build-release.yml` has five checkouts and `build-and-test.yml` two, all of which would report `unknown` as-is.
|
||||||
|
- [ ] **No toolchain installed in CI** — git is already present in the builder image; nothing new is added.
|
||||||
|
- [ ] `bun run check`, `bun run test`, `bun run check:boundary` pass.
|
||||||
|
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||||
|
- [ ] `bindings.ts` regenerated.
|
||||||
|
- [ ] DR-093 allocated in `requirements.md`; new code carries `// TRACES:`.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
**Rust**: the classification is pure and must be extracted from the command as
|
||||||
|
`classify_build(describe: &str, debug: bool) -> BuildKind` so it can be tested
|
||||||
|
directly. Cover: `"v0.2.0"` → `Release`; `"v0.2.0-3-gcb79a37"` → `Untagged`;
|
||||||
|
`"v0.2.0-dirty"` → `Untagged`; `"unknown"` → `Unknown`; `debug = true` → always
|
||||||
|
`Development` regardless of describe.
|
||||||
|
|
||||||
|
`build.rs` itself is not unit-testable. Verify its failure path manually by
|
||||||
|
building with `PATH` stripped of git, and from a `git archive` tarball — both
|
||||||
|
must succeed with `"unknown"`.
|
||||||
|
|
||||||
|
**Frontend**: assert the About block renders each `BuildKind` correctly, and that
|
||||||
|
it renders the backend-supplied kind rather than re-deriving it from the string
|
||||||
|
(a test that passes a `Release` kind with a `-dirty` describe and asserts the
|
||||||
|
badge follows the *kind* would catch that regression).
|
||||||
|
|
||||||
|
## TRACES
|
||||||
|
|
||||||
|
- `build.rs` provenance emission → `// TRACES: | DR-093`
|
||||||
|
- `BuildInfo` / `BuildKind` / `classify_build` → `// TRACES: | DR-093`
|
||||||
|
- `get_build_info` command → `// TRACES: | DR-093`
|
||||||
|
- Settings About block → `// TRACES: | DR-093`
|
||||||
|
- `classify_build` tests → `UT-BUILD-1`
|
||||||
|
- Allocate **DR-093** in `requirements.md` ("Build provenance: git describe and
|
||||||
|
build profile surfaced in-app and in logs"). Next free DR at time of writing
|
||||||
|
is DR-093.
|
||||||
|
|
||||||
|
## Notes for the implementer
|
||||||
|
|
||||||
|
- Do the `build.rs` + command + logging first; the About UI is the smaller half
|
||||||
|
and the logging alone delivers most of the diagnostic value.
|
||||||
|
- The `fetch-depth: 0` change is the easiest part to forget and the one that
|
||||||
|
makes CI artifacts useless if missed — it is why that acceptance box is
|
||||||
|
flagged. Weigh it per workflow: test-only jobs do not need it.
|
||||||
|
- Do not add a build timestamp "while you are in there" — see Out of scope.
|
||||||
|
- A parallel Claude session may be active — `git diff` before "repairing"
|
||||||
|
unexpected changes.
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
# Spec: Enforce the unified player boundary
|
||||||
|
|
||||||
|
**Status:** Proposed
|
||||||
|
**Requirements:** DR-095 (new); relates to UR-005 and the unified-player-boundary
|
||||||
|
principle in CLAUDE.md and [02-svelte-frontend.md](../architecture/02-svelte-frontend.md)
|
||||||
|
**UX spec:** n/a — refactor, no user-visible change.
|
||||||
|
**Supersedes / revises:** n/a
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
The stated principle is that UI controls playback **only** through
|
||||||
|
`playerController` ([src/lib/player/index.ts](../../src/lib/player/index.ts)),
|
||||||
|
never by calling `commands.player*` directly. There are **52 direct call sites
|
||||||
|
outside** that facade. This spec routes the genuine playback-control calls
|
||||||
|
through the facade, narrows the principle's wording so it stops forbidding
|
||||||
|
things it never meant to forbid, and adds the lint rule that keeps it true —
|
||||||
|
because this rule is the one design principle in the audit with **no automated
|
||||||
|
check at all**, and it is also the one that drifted furthest.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
Direct `commands.player*` usage outside `src/lib/player/`, by file:
|
||||||
|
|
||||||
|
| File | Sites |
|
||||||
|
|---|---|
|
||||||
|
| [queue.ts](../../src/lib/stores/queue.ts) | 10 |
|
||||||
|
| [player/[id]/+page.svelte](../../src/routes/player/[id]/+page.svelte) | 9 |
|
||||||
|
| [VideoPlayer.svelte](../../src/lib/components/player/VideoPlayer.svelte) | 8 |
|
||||||
|
| [settings/+page.svelte](../../src/routes/settings/+page.svelte) | 5 |
|
||||||
|
| [sleepTimer.ts](../../src/lib/stores/sleepTimer.ts) / [auth.ts](../../src/lib/stores/auth.ts) / [autoplay.ts](../../src/lib/api/autoplay.ts) | 4 each |
|
||||||
|
| [preload.ts](../../src/lib/services/preload.ts) | 3 |
|
||||||
|
| [library/[id]](../../src/routes/library/[id]/+page.svelte), [playerEvents.ts](../../src/lib/services/playerEvents.ts), [playbackMode.ts](../../src/lib/stores/playbackMode.ts) | 1–2 each |
|
||||||
|
|
||||||
|
These are **not** equivalent violations, and treating them as one number is why
|
||||||
|
the rule has been easy to ignore. Three distinct groups:
|
||||||
|
|
||||||
|
**(a) Genuine violations — playback control with a facade method that already
|
||||||
|
exists.** `playerStop` ×6, `playerPlayTracks` ×4, `playerSeek` ×2,
|
||||||
|
`playerPlayAlbumTrack` ×2, `playerNext`, `playerPrevious`, `playerSkipTo`,
|
||||||
|
`playerToggleShuffle`, `playerCycleRepeat`, `playerRemoveFromQueue`,
|
||||||
|
`playerMoveInQueue`, `playerAddTrackById`, `playerAddTracksByIds`,
|
||||||
|
`playerSetSubtitleTrack`, `playerPlayItem`. The facade exposes `stop()`,
|
||||||
|
`seek()`, `next()`, `previous()`, `skipTo()`, `toggleShuffle()`,
|
||||||
|
`cycleRepeat()`, `removeFromQueue()`, `moveInQueue()`, `addTrackById()`,
|
||||||
|
`addTracksByIds()`, `setSubtitleTrack()`, `playTracks()`, `playAlbumTrack()`,
|
||||||
|
`playItem()` — every one of these has a facade equivalent that is simply not
|
||||||
|
being called. `queue.ts` is the starkest case: it imports `commands` directly
|
||||||
|
and re-implements ten methods the facade already provides.
|
||||||
|
|
||||||
|
**(b) Playback control with no facade method.** `playerPlayQueue`,
|
||||||
|
`playerGetQueue`, `playerGetStatus`, `playerEnterBackgroundAudio`,
|
||||||
|
`playerExitBackgroundAudio`, `playerSetSleepTimer`, `playerCancelSleepTimer`,
|
||||||
|
`playerPlayNextEpisode`, `playerCancelAutoplayCountdown`. In scope for the
|
||||||
|
principle, but currently *impossible* to comply with — the facade has no surface
|
||||||
|
for them. A rule that cannot be followed is not being broken so much as it is
|
||||||
|
unfinished.
|
||||||
|
|
||||||
|
**(c) Not playback control.** `playerConfigureJellyfin` ×3,
|
||||||
|
`playerDisableJellyfin`, `playerGet/SetAudioSettings`,
|
||||||
|
`playerGet/SetVideoSettings`, `playerGetEqPresets`,
|
||||||
|
`playerGet/SetAutoplaySettings`, `playerGet/SetCacheConfig`,
|
||||||
|
`playerPreloadUpcoming`. These are configuration and lifecycle calls that happen
|
||||||
|
to live under the `player_` command prefix. The principle is about *who is
|
||||||
|
authoritative for playback state* — settings CRUD isn't that.
|
||||||
|
|
||||||
|
The audit's read: the rule as written is violated 52 times, which makes real
|
||||||
|
drift indistinguishable from acceptable usage, and that ambiguity is what lets
|
||||||
|
group (a) persist. Note also that the principle **is** well-honoured where it
|
||||||
|
matters most — the read side is clean, with UI reading state exclusively from
|
||||||
|
the facade's re-exported stores. The write side is what drifted.
|
||||||
|
|
||||||
|
## Layer assignment
|
||||||
|
|
||||||
|
Frontend-internal refactor. No domain logic moves and nothing new crosses IPC —
|
||||||
|
the same Rust commands are called, through one module instead of many.
|
||||||
|
|
||||||
|
| Logic / responsibility | Layer | Why it belongs there |
|
||||||
|
|------------------------|-------|----------------------|
|
||||||
|
| Playback command dispatch (adapter routing: native vs HTML5) | Frontend — `src/lib/player/` **only** | Presentation-layer plumbing, but must be centralised: the facade picks between the native backend and the HTML5 `<video>` adapter. A caller bypassing it silently skips that routing. |
|
||||||
|
| Playback *authority* (position, pause, rate, track changes) | **Rust / the player** | Unchanged. The player is authoritative; UI is a consumer. This spec does not touch that direction. |
|
||||||
|
| Queue mutation commands | Frontend facade → Rust | Rust owns queue state; the facade is the single call path to it. |
|
||||||
|
| Player settings CRUD (EQ, video, autoplay, cache) | Frontend, **outside** the facade | Configuration, not playback control — read/written on a settings page with no adapter routing. Explicitly carved out below. |
|
||||||
|
| Backend→frontend event handling | `playerEvents.ts` | Already correct. It is the facade's own plumbing, not a bypassing consumer. |
|
||||||
|
|
||||||
|
No Jellyfin taxonomy is involved, so no boundary-leak risk.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### 1. Narrow the principle to what it actually means
|
||||||
|
|
||||||
|
Amend CLAUDE.md and [02-svelte-frontend.md](../architecture/02-svelte-frontend.md):
|
||||||
|
|
||||||
|
> **Unified player boundary.** UI controls **playback** — transport, queue
|
||||||
|
> mutation, track selection, playback initiation — *only* through
|
||||||
|
> `playerController`. Player **configuration** commands (`player_*_settings`,
|
||||||
|
> `player_configure_jellyfin`, `player_*_cache_config`, `player_preload_upcoming`)
|
||||||
|
> are ordinary IPC and may be called directly from settings surfaces.
|
||||||
|
|
||||||
|
This is a clarification, not a relaxation: it makes group (c) explicitly fine so
|
||||||
|
that a violation count means something. A rule with 52 nominal violations, most
|
||||||
|
of them acceptable, provides no signal.
|
||||||
|
|
||||||
|
### 2. Fill the facade gaps (group b)
|
||||||
|
|
||||||
|
Add to `playerController`, each a thin pass-through preserving current
|
||||||
|
behaviour:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
playQueue, getQueue, getStatus,
|
||||||
|
enterBackgroundAudio, exitBackgroundAudio,
|
||||||
|
setSleepTimer, cancelSleepTimer,
|
||||||
|
playNextEpisode, cancelAutoplayCountdown,
|
||||||
|
```
|
||||||
|
|
||||||
|
Do this **first** — group (a) cannot be fully migrated while callers still need
|
||||||
|
a direct import for a neighbouring call, and a file that imports `commands` for
|
||||||
|
one reason will keep using it for others.
|
||||||
|
|
||||||
|
### 3. Migrate group (a)
|
||||||
|
|
||||||
|
Mechanical: replace `commands.playerX(...)` with `playerController.x(...)`.
|
||||||
|
Highest-value first: `queue.ts` (10 sites, all direct facade equivalents), then
|
||||||
|
`player/[id]/+page.svelte`, `VideoPlayer.svelte`, `sleepTimer.ts`,
|
||||||
|
`playbackMode.ts`, `library/[id]/+page.svelte`.
|
||||||
|
|
||||||
|
Two sites need care rather than substitution:
|
||||||
|
|
||||||
|
- **`playerEvents.ts`** (`playerOnPlaybackEnded`, `playerStop` in the error
|
||||||
|
path). This module *is* the facade's event plumbing — the counterpart to
|
||||||
|
`index.ts`, inside the boundary conceptually though not by directory. Treat
|
||||||
|
`src/lib/services/playerEvents.ts` as **inside** the boundary and exempt it,
|
||||||
|
rather than making it call the facade that calls back into it. Record this in
|
||||||
|
the lint config with the reason.
|
||||||
|
- **`VideoPlayer.svelte`** — registers its own adapter via `setActiveAdapter`.
|
||||||
|
Its `playerStop`/`playerPlayItem` calls interact with adapter lifecycle, and
|
||||||
|
CLAUDE.md's gotcha ("no lifecycle calls after an `await` in `onMount`") applies.
|
||||||
|
Migrate this file **last and on its own**, so an Android seek regression is
|
||||||
|
bisectable to one commit.
|
||||||
|
|
||||||
|
### 4. Add the lint rule (the part that makes it stick)
|
||||||
|
|
||||||
|
The audit's finding was that principles with working checks held up and
|
||||||
|
principles without them drifted. This principle has no check. Add
|
||||||
|
`scripts/check-player-boundary.sh`, wired as `bun run check:player-boundary` and
|
||||||
|
into `test-all.sh`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Playback-control commands that MUST go through the facade.
|
||||||
|
CONTROL='player(Play|Pause|Toggle|Stop|Seek|Next|Previous|SkipTo|ToggleShuffle|CycleRepeat|RemoveFromQueue|MoveInQueue|SetVolume|ToggleMute|SetSubtitleTrack|SeekVideo|SwitchAudioTrack|PlayTracks|PlayAlbumTrack|PlayItem|PlayQueue|AddTrackById|AddTracksByIds|GetQueue|GetStatus|EnterBackgroundAudio|ExitBackgroundAudio|SetSleepTimer|CancelSleepTimer|PlayNextEpisode|CancelAutoplayCountdown|OnPlaybackEnded)'
|
||||||
|
|
||||||
|
# Inside the boundary: the facade and its event plumbing.
|
||||||
|
EXEMPT='^src/lib/player/|^src/lib/services/playerEvents\.ts$'
|
||||||
|
```
|
||||||
|
|
||||||
|
Flag `commands.$CONTROL` in non-test `src/` files outside `EXEMPT`. Config
|
||||||
|
commands are deliberately absent from the list, matching §1 — so the check
|
||||||
|
encodes the narrowed rule rather than the aspirational one.
|
||||||
|
|
||||||
|
An ESLint `no-restricted-syntax` rule would give better editor feedback, but the
|
||||||
|
project has no ESLint config; a shell check matches the existing
|
||||||
|
`check:boundary` precedent and adds no dependency.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- Changing playback *behaviour* — pure refactor.
|
||||||
|
- The one-directional state principle (audited clean; UI reads from facade
|
||||||
|
stores only).
|
||||||
|
- Moving settings CRUD behind the facade (§1 explicitly carves it out).
|
||||||
|
- Introducing ESLint.
|
||||||
|
- Refactoring `VideoPlayer.svelte`'s 2079 lines generally, beyond its facade
|
||||||
|
call sites.
|
||||||
|
- The `commands.player*` calls **inside** `src/lib/player/` — that is the
|
||||||
|
facade doing its job.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] `playerController` exposes the group-(b) methods listed in §2.
|
||||||
|
- [ ] `grep -rn "commands\.player" src/ --include='*.ts' --include='*.svelte' | grep -v '^src/lib/player/' | grep -v 'playerEvents\.ts' | grep -v '\.test\.' | grep -v bindings.ts`
|
||||||
|
returns **only** configuration commands per §1 — no transport, queue, or
|
||||||
|
playback-initiation call.
|
||||||
|
- [ ] `queue.ts` no longer imports `commands` from bindings.
|
||||||
|
- [ ] `bun run check:player-boundary` exists, is wired into `test-all.sh`, and
|
||||||
|
passes.
|
||||||
|
- [ ] The check **fails** when a `commands.playerStop()` is added to a non-exempt
|
||||||
|
file — verify explicitly, as with the other gates in this batch.
|
||||||
|
- [ ] The check does **not** fail on `commands.playerSetAudioSettings()` in
|
||||||
|
`settings/+page.svelte` (the §1 carve-out works).
|
||||||
|
- [ ] CLAUDE.md and `02-svelte-frontend.md` carry the narrowed wording, including
|
||||||
|
the config carve-out and the `playerEvents.ts` exemption with its reason.
|
||||||
|
- [ ] **No behavioural change**: audio and video playback, queue reorder,
|
||||||
|
shuffle/repeat, sleep timer, background audio, and autoplay all behave as
|
||||||
|
before on **both Linux and Android**.
|
||||||
|
- [ ] Android seek and `onMount` lifecycle still correct after the
|
||||||
|
`VideoPlayer.svelte` migration (the known-fragile path).
|
||||||
|
- [ ] `bun run check` and `bun run test` pass.
|
||||||
|
- [ ] `bun run check:boundary` passes.
|
||||||
|
- [ ] Changed code carries `// TRACES:` comments.
|
||||||
|
- [ ] No Rust change, so no `bindings.ts` regeneration.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
**Frontend** (`bun run test`):
|
||||||
|
- Extend the existing facade tests to cover each new group-(b) method: it
|
||||||
|
forwards to the right command with the right arguments, and routes to the
|
||||||
|
active adapter where applicable.
|
||||||
|
- `queue.ts` tests: assert calls land on `playerController`, not `commands`. Mock
|
||||||
|
the facade — a test that mocks `commands` would pass either way and guard
|
||||||
|
nothing.
|
||||||
|
- Keep `tauriIntegration.test.ts` and the other IPC param-naming tests green;
|
||||||
|
they cover the camelCase rule this refactor must not disturb.
|
||||||
|
|
||||||
|
**Manual** (no automated coverage for these paths):
|
||||||
|
- Linux: play/pause/seek/next/prev, queue reorder, shuffle, repeat, sleep timer,
|
||||||
|
transcoded video (HLS), background audio enter/exit.
|
||||||
|
- Android: the same, plus lockscreen/MediaSession controls, and **seek after
|
||||||
|
entering the player** — the specific regression CLAUDE.md warns about.
|
||||||
|
|
||||||
|
Because this is a pure refactor, the strongest signal is that no test *changes
|
||||||
|
expectation*. A test needing its assertions rewritten means behaviour moved —
|
||||||
|
investigate rather than update it.
|
||||||
|
|
||||||
|
## TRACES
|
||||||
|
|
||||||
|
Allocate in `requirements.md`:
|
||||||
|
|
||||||
|
- **DR-095** — "UI playback control is routed exclusively through the
|
||||||
|
`playerController` facade (`src/lib/player/`), with `playerEvents.ts` inside
|
||||||
|
the boundary as its event plumbing and player *configuration* commands
|
||||||
|
explicitly outside it; enforced by `scripts/check-player-boundary.sh`."
|
||||||
|
Category: Player. Traces to UR-005. Status: Done on merge.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/lib/player/index.ts
|
||||||
|
// TRACES: UR-005 | DR-095
|
||||||
|
```
|
||||||
|
|
||||||
|
New facade tests take `@req-test: UT-089` onward (next free UT is **UT-089**;
|
||||||
|
coordinate if landing alongside the sibling specs, which draw from the same
|
||||||
|
pool).
|
||||||
|
|
||||||
|
## Notes for the implementer
|
||||||
|
|
||||||
|
- A parallel Claude session may be active in this repo — `git diff` before
|
||||||
|
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||||
|
- **Order matters**: §2 (fill gaps) → §3 (migrate, `VideoPlayer.svelte` last and
|
||||||
|
alone) → §4 (add the check). Adding the check first turns `master` red.
|
||||||
|
- 🔴 **`VideoPlayer.svelte`**: no lifecycle calls after an `await` in `onMount` —
|
||||||
|
it flips to HTML5 mode and breaks Android seek. Do not let a mechanical
|
||||||
|
substitution introduce an `await` before a lifecycle call.
|
||||||
|
- The facade's `requireHandle()` may throw where a raw `commands` call did not.
|
||||||
|
Check each migrated call site's error handling rather than assuming the
|
||||||
|
try/catch still covers the same cases.
|
||||||
|
- `playbackMode.ts` interacts with remote-mode routing (`play_on_session` vs
|
||||||
|
local MPV). Verify remote casting still works after migrating its
|
||||||
|
`playerPlayTracks` call.
|
||||||
|
- This spec is deliberately the *lowest* priority of the audit batch: it is the
|
||||||
|
largest diff and the only one carrying real regression risk, while the
|
||||||
|
traceability gate is a few lines and restores a dead safety net.
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
# Spec: Remove the broken `check-req-coverage.sh`
|
||||||
|
|
||||||
|
**Status:** Implemented
|
||||||
|
**Requirements:** supports DR-093 (see [traceability-gate-repair.md](traceability-gate-repair.md))
|
||||||
|
**UX spec:** n/a — developer tooling.
|
||||||
|
**Supersedes / revises:** n/a
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`scripts/check-req-coverage.sh` is broken, orphaned, and actively misleading: it
|
||||||
|
reports `Total Requirements: 1`, zeros in every category, and then prints
|
||||||
|
**"✨ All requirements have implementations!"**. Nothing references it — not CI,
|
||||||
|
not `package.json`, not the docs. This spec deletes it, with a narrowly-scoped
|
||||||
|
alternative (repair it) documented and rejected below.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
Running it today produces:
|
||||||
|
|
||||||
|
```
|
||||||
|
Category Breakdown:
|
||||||
|
UR: 0 requirements
|
||||||
|
IR: 0 requirements
|
||||||
|
DR: 0 requirements
|
||||||
|
JA: 0 requirements
|
||||||
|
|
||||||
|
Summary:
|
||||||
|
Total Requirements: 1
|
||||||
|
✅ Fully Implemented: 0 (0%)
|
||||||
|
|
||||||
|
✨ All requirements have implementations!
|
||||||
|
```
|
||||||
|
|
||||||
|
Every number is wrong (the real totals are UR 61, IR 29, DR 89, JA 32), and the
|
||||||
|
concluding message is the *opposite* of a warning — a developer running this to
|
||||||
|
sanity-check coverage is told everything is fine.
|
||||||
|
|
||||||
|
This is worse than having no script. It is a trap, and it sits in `scripts/`
|
||||||
|
next to tools that do work, with nothing marking it as dead.
|
||||||
|
|
||||||
|
Verification that it is genuinely orphaned:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ grep -rn "check-req-coverage" . --include='*.yml' --include='*.json' \
|
||||||
|
--include='*.sh' --include='*.md' | grep -v node_modules
|
||||||
|
(no output)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Layer assignment
|
||||||
|
|
||||||
|
Developer tooling only; no application logic and nothing crosses the IPC
|
||||||
|
boundary.
|
||||||
|
|
||||||
|
| Logic / responsibility | Layer | Why it belongs there |
|
||||||
|
|------------------------|-------|----------------------|
|
||||||
|
| Requirement-coverage reporting | Build tooling — `extract-traces.ts` | One tool should own coverage analysis. A second, divergent implementation is how the two answers ("1 requirement" vs "211") came to disagree unnoticed. |
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
**Delete `scripts/check-req-coverage.sh`.**
|
||||||
|
|
||||||
|
Coverage reporting is owned by [scripts/extract-traces.ts](../../scripts/extract-traces.ts),
|
||||||
|
which is correct, is what CI runs, and gains a first-class local coverage mode
|
||||||
|
in [traceability-gate-repair.md](traceability-gate-repair.md):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun run traces:coverage # the supported way to check coverage locally
|
||||||
|
```
|
||||||
|
|
||||||
|
Then check the sibling scripts for the same rot. `scripts/` also contains
|
||||||
|
`check-test-coverage.sh` and `find-req-implementations.sh`, neither of which is
|
||||||
|
referenced from `package.json`. An unreferenced script is never run and so rots
|
||||||
|
silently — that is the actual failure mode being fixed here, and fixing only the
|
||||||
|
one instance found by audit leaves the others to be rediscovered later.
|
||||||
|
|
||||||
|
### Findings (investigation, 2026-07)
|
||||||
|
|
||||||
|
All three scripts turned out to share a **single root cause**, and all three are
|
||||||
|
deleted:
|
||||||
|
|
||||||
|
| Script | Defect |
|
||||||
|
|---|---|
|
||||||
|
| `check-req-coverage.sh` | Reads `README.md`, which has held **zero** requirement rows since they moved to `docs/requirements.md` → `total_reqs=1`, every category 0, "✨ All requirements have implementations!" Also greps `src-tauri/` unscoped. |
|
||||||
|
| `check-test-coverage.sh` | Greps `src-tauri/` unscoped — including **40 GB** of `target/` build artifacts. Hangs indefinitely; produces no output at all. |
|
||||||
|
| `find-req-implementations.sh` | Same unscoped `src-tauri/` grep. Same hang. |
|
||||||
|
|
||||||
|
So none of them were subtly wrong — two could never terminate, and the third
|
||||||
|
inverted its own conclusion.
|
||||||
|
|
||||||
|
They were nonetheless *salvageable*: scoping the greps to `src-tauri/src` and
|
||||||
|
repointing at `docs/requirements.md` would be a few lines, and the `@req:` /
|
||||||
|
`@req-test:` tags they read are still present in the tree (**146** and **76**
|
||||||
|
occurrences).
|
||||||
|
|
||||||
|
**Decision: delete all three anyway.** The tags are an undocumented parallel
|
||||||
|
convention — `@req:` appears in no doc, and CLAUDE.md describes only `TRACES:`.
|
||||||
|
Repairing the scripts would re-establish a second traceability system to keep in
|
||||||
|
sync with the first, which is the same two-sources-of-truth condition that let
|
||||||
|
"1 requirement" and "211 requirements" coexist unnoticed. `TRACES:` plus the
|
||||||
|
repaired coverage engine ([traceability-gate-repair.md](traceability-gate-repair.md))
|
||||||
|
already cover this ground.
|
||||||
|
|
||||||
|
The existing `@req:` / `@req-test:` comments are left in place: they are
|
||||||
|
harmless as prose, several encode genuinely useful test intent, and stripping
|
||||||
|
222 comments across the tree is a large diff with no functional gain. They are
|
||||||
|
simply no longer read by any tool.
|
||||||
|
|
||||||
|
### Alternative considered: repair rather than delete
|
||||||
|
|
||||||
|
Rejected. The script's output format duplicates what `traces:markdown` already
|
||||||
|
generates, it has no tests, no caller, and no documented purpose distinct from
|
||||||
|
`extract-traces.ts`. Repairing it recreates the two-sources-of-truth condition
|
||||||
|
that produced the contradiction. If a shell-based coverage check is ever wanted,
|
||||||
|
it should shell out to `traces:json` and `jq` rather than re-parse
|
||||||
|
`requirements.md` independently.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- The CI workflow denominators — [traceability-gate-repair.md](traceability-gate-repair.md).
|
||||||
|
- Any change to `extract-traces.ts`'s output (that spec owns it).
|
||||||
|
- Auditing scripts that *are* referenced from `package.json` — they run
|
||||||
|
regularly and would fail visibly.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] `scripts/check-req-coverage.sh` no longer exists.
|
||||||
|
- [ ] `grep -rn "check-req-coverage" .` (excluding `node_modules` and this spec)
|
||||||
|
returns nothing — no dangling reference in CI, docs, or `package.json`.
|
||||||
|
- [ ] `scripts/check-test-coverage.sh` and `find-req-implementations.sh` have each
|
||||||
|
been run and either wired into `package.json` or deleted; the decision and
|
||||||
|
reason are recorded in `scripts/README.md`. **Outcome: all three deleted —
|
||||||
|
see Findings.**
|
||||||
|
- [ ] `scripts/README.md` documents `bun run traces:coverage` as the supported
|
||||||
|
way to check requirement coverage locally.
|
||||||
|
- [ ] `bun run test:all` passes (confirms nothing invoked the deleted script).
|
||||||
|
- [ ] `bun run check` and `bun run test` pass.
|
||||||
|
- [ ] `bun run check:boundary` passes.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
No unit tests — this is a deletion. Verification is the grep in the acceptance
|
||||||
|
criteria plus a green `bun run test:all`, which exercises the script paths that
|
||||||
|
actually run.
|
||||||
|
|
||||||
|
## TRACES
|
||||||
|
|
||||||
|
No new requirement. The deletion is covered by **DR-093**
|
||||||
|
([traceability-gate-repair.md](traceability-gate-repair.md)), which establishes
|
||||||
|
`extract-traces.ts` as the single owner of coverage reporting. Note the removal
|
||||||
|
in that DR's text when both land.
|
||||||
|
|
||||||
|
## Notes for the implementer
|
||||||
|
|
||||||
|
- A parallel Claude session may be active in this repo — `git diff` before
|
||||||
|
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||||
|
- Land this **after** or alongside [traceability-gate-repair.md](traceability-gate-repair.md),
|
||||||
|
so `bun run traces:coverage` exists before the broken script is removed and
|
||||||
|
developers are never left without a coverage command.
|
||||||
|
- Check `docs/traceability-ci.md` and `docs/traces-quick-ref.md` for prose
|
||||||
|
references to the deleted script; the grep above covers `.md`, but read the
|
||||||
|
surrounding sentence rather than deleting the line mechanically.
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
# Spec: Land the scoped-search boundary fix (implementation)
|
||||||
|
|
||||||
|
**Status:** Stage 1 Implemented — Stage 2 (result-side grouping) outstanding
|
||||||
|
**Requirements:** UR-049, UR-050 | DR-063, DR-066, DR-067 (existing — no new IDs)
|
||||||
|
**UX spec:** n/a — zero user-visible change is the point (see Acceptance criteria).
|
||||||
|
**Supersedes / revises:** implements [scoped-search-boundary.md](scoped-search-boundary.md),
|
||||||
|
which specified this fix but was never built. That spec remains the **design
|
||||||
|
authority**; this one is the delivery plan and status correction.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
[scoped-search-boundary.md](scoped-search-boundary.md) diagnosed a domain-taxonomy
|
||||||
|
leak, specified the fix in full detail, and became the justification for the
|
||||||
|
project's boundary rule in CLAUDE.md, the `check:boundary` tripwire, and the
|
||||||
|
spec-review checklist. **The fix was never implemented.** The leak it describes
|
||||||
|
is still live in `main`. This spec exists to close that gap and to correct the
|
||||||
|
record — the codebase currently enforces a rule against a violation it still
|
||||||
|
contains.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
The mapping the rule forbids is present and in use:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// src/lib/utils/searchScope.ts:29-32
|
||||||
|
const SCOPE_ITEM_TYPES: Record<Exclude<SearchScope, "all">, string[]> = {
|
||||||
|
music: ["MusicAlbum", "MusicArtist", "Audio", "Playlist"],
|
||||||
|
movies: ["Movie"],
|
||||||
|
tv: ["Series", "Episode"],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
This is not dead code. [library.ts:262](../../src/lib/stores/library.ts#L262)
|
||||||
|
calls `scopeItemTypes(scope)` and puts the result straight into
|
||||||
|
`options.includeItemTypes`. Meanwhile there is **no `SearchScope` anywhere in
|
||||||
|
`src-tauri/`**:
|
||||||
|
|
||||||
|
```console
|
||||||
|
$ grep -rn "SearchScope" src-tauri/src --include='*.rs'
|
||||||
|
(no output)
|
||||||
|
```
|
||||||
|
|
||||||
|
Three things make this the highest-value item found in the design-principles
|
||||||
|
audit:
|
||||||
|
|
||||||
|
1. **The rule's own founding incident is unremediated.** CLAUDE.md cites this
|
||||||
|
spec as "the incident this rule came from." A rule whose originating
|
||||||
|
violation is still shipping is not credible.
|
||||||
|
2. **The tripwire cannot see it.** `bun run check:boundary` passes — it greps for
|
||||||
|
a multi-type array literal *at the query site*, and this one is assigned to a
|
||||||
|
named const and dereferenced elsewhere. Broadening the tripwire is specified
|
||||||
|
separately in [boundary-tripwire-hardening.md](boundary-tripwire-hardening.md);
|
||||||
|
note that hardening it **without** landing this fix would turn `master` red.
|
||||||
|
3. **The spec's own acceptance criterion fails today.** "Adding a hypothetical
|
||||||
|
new type to a scope requires editing only Rust" — adding a type to the Music
|
||||||
|
scope right now requires editing `searchScope.ts`.
|
||||||
|
|
||||||
|
## Layer assignment
|
||||||
|
|
||||||
|
Unchanged from [scoped-search-boundary.md](scoped-search-boundary.md) §Design;
|
||||||
|
restated so this spec is reviewable on its own.
|
||||||
|
|
||||||
|
| Logic / responsibility | Layer | Why it belongs there |
|
||||||
|
|------------------------|-------|----------------------|
|
||||||
|
| Scope → Jellyfin item types (`music` → `MusicAlbum`, `MusicArtist`, `Audio`, `Playlist`) | **Rust** | Domain vocabulary. Changes if Jellyfin adds/renames an item type — the litmus test's "yes" case. This is the leak being fixed. |
|
||||||
|
| Result item → search group bucketing | **Rust** | Same taxonomy, result side. Classifying a `MediaItem` as a Song vs Album is Jellyfin vocabulary, not layout. |
|
||||||
|
| `All` sends no filter at all (≠ union of enumerated types) | **Rust** | A query-shaping rule with a correctness consequence (Person/folder results would be silently dropped). Belongs with the expansion it qualifies. |
|
||||||
|
| Group display order, labels, reordering, persistence | Frontend | Pure presentation — changes only if the UI is redesigned. Explicitly retained frontend-side. |
|
||||||
|
| `resolveSearchScope(pathname)` — route → initial scope | Frontend | Routing/navigation, no Jellyfin vocabulary. Stays exactly as-is. |
|
||||||
|
| Chip labels (`SCOPE_LABELS`), scope order (`SEARCH_SCOPES`) | Frontend | Display strings over an opaque enum. |
|
||||||
|
| `GROUP_SCOPE` (which group belongs to which scope) | **Delete** | Borderline taxonomy, made redundant: once Rust filters by scope, out-of-scope groups arrive empty and drop via the empty-omit rule. Borderline defaults to Rust; here it defaults to *gone*. |
|
||||||
|
|
||||||
|
The `SearchScope` and `SearchGroupId` **types** come to the frontend from
|
||||||
|
generated `bindings.ts`. Naming an opaque enum variant is not taxonomy; knowing
|
||||||
|
what item types it expands to is.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
**Follow [scoped-search-boundary.md](scoped-search-boundary.md) §Design as
|
||||||
|
written** — `SearchScope` enum + `item_types()` in `repository/types.rs`,
|
||||||
|
`SearchOptions.scope`, `SearchGroupId`/`SearchGroup`/`GroupedSearchResult`,
|
||||||
|
scope-wins precedence, `All` → `None` → no filter. It is not restated here;
|
||||||
|
duplicating it would create two drifting copies of the same design.
|
||||||
|
|
||||||
|
This spec adds only the delivery sequencing that the original left implicit.
|
||||||
|
|
||||||
|
### Staging: land it in two reviewable pieces
|
||||||
|
|
||||||
|
The original bundles the query side and the result side into one change. That is
|
||||||
|
a large diff touching Rust types, `bindings.ts`, the store, and a component, with
|
||||||
|
the `search-event` dual-payload hazard in the middle. Split it:
|
||||||
|
|
||||||
|
**Stage 1 — query side (closes the leak).**
|
||||||
|
`SearchScope` enum, `SearchOptions.scope`, command resolves scope →
|
||||||
|
`include_item_types` in Rust, `library.ts` sends `{ scope }`, delete
|
||||||
|
`SCOPE_ITEM_TYPES` and `scopeItemTypes()`. Result grouping stays as it is.
|
||||||
|
|
||||||
|
After Stage 1 the actual boundary violation is gone and
|
||||||
|
[boundary-tripwire-hardening.md](boundary-tripwire-hardening.md) can land safely.
|
||||||
|
|
||||||
|
**Stage 2 — result side.** `SearchGroupId`/`SearchGroup`/`GroupedSearchResult`,
|
||||||
|
Rust bucketing, both payloads converted, `composeSearchGroups()` shrunk,
|
||||||
|
`GROUP_ITEM_TYPES`/`groupItemTypes()`/`GROUP_SCOPE` deleted.
|
||||||
|
|
||||||
|
Both stages are required for the original spec's acceptance criteria to pass;
|
||||||
|
Stage 1 alone leaves `GROUP_ITEM_TYPES` in the frontend. **Stage 1 is not a
|
||||||
|
stopping point** — it is a review boundary. Do not mark the parent spec
|
||||||
|
Implemented until Stage 2 lands.
|
||||||
|
|
||||||
|
### Stage 1 — delivered (July 2026)
|
||||||
|
|
||||||
|
- `SearchScope` enum + `item_types()` in [repository/types.rs](../../src-tauri/src/repository/types.rs);
|
||||||
|
`All` → `None` → no filter.
|
||||||
|
- `SearchOptions.scope` with `resolve_scope()`; scope wins over
|
||||||
|
`include_item_types`, which stays for the non-search `get_items` callers.
|
||||||
|
- `repository_search` resolves the scope **once, before** the cache/server split,
|
||||||
|
so both phases filter identically.
|
||||||
|
- `SCOPE_ITEM_TYPES` and `scopeItemTypes()` deleted; `searchScope.ts` now
|
||||||
|
re-exports `SearchScope` from the generated bindings instead of a hand-written
|
||||||
|
union.
|
||||||
|
- [library.ts](../../src/lib/stores/library.ts) sends `{ scope }`.
|
||||||
|
- 8 Rust tests (`search_scope_tests`); the frontend suite now asserts the
|
||||||
|
*opaque scope* is sent rather than an item-type list.
|
||||||
|
|
||||||
|
Verified: adding `"AudioBook"` to the Music scope changed **zero** files under
|
||||||
|
`src/` — the criterion that failed before this work.
|
||||||
|
|
||||||
|
**Stage 2 remains open**: `GROUP_ITEM_TYPES` / `groupItemTypes()` (result-side
|
||||||
|
bucketing, single-type-per-group) are still in `searchScope.ts`, and both search
|
||||||
|
payloads still carry a flat `MediaItem[]` rather than `GroupedSearchResult`.
|
||||||
|
|
||||||
|
### 🔴 The `search-event` dual payload (Stage 2)
|
||||||
|
|
||||||
|
The original flags this as "the single largest part of the change and the
|
||||||
|
easiest to half-do." Restating because it is the one thing that silently breaks:
|
||||||
|
search resolves **twice** — the command returns instant cache results, then the
|
||||||
|
merged cache+server union arrives via `search-event`. Both payloads must carry
|
||||||
|
`GroupedSearchResult`. Convert one and the UI flickers between shapes as server
|
||||||
|
results land.
|
||||||
|
|
||||||
|
Write the failing test for the *event* payload first — the command return is the
|
||||||
|
obvious half, the event is the half that gets forgotten.
|
||||||
|
|
||||||
|
### Note on `SearchOptions.scope` and specta
|
||||||
|
|
||||||
|
`SearchOptions` is already `#[serde(rename_all = "camelCase")]` with
|
||||||
|
`skip_serializing_if = "Option::is_none"`. Add `scope: Option<SearchScope>`
|
||||||
|
following that pattern so `All`/absent omits the key. Regenerate `bindings.ts`
|
||||||
|
— `SearchOptions` there is currently
|
||||||
|
`{ limit?, includeItemTypes?, searchTerm? }` and must gain `scope?`. Never
|
||||||
|
hand-edit it.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- Redesigning anything in [scoped-search-boundary.md](scoped-search-boundary.md).
|
||||||
|
If implementation shows the design wrong, revise **that** spec, don't fork it.
|
||||||
|
- Online/offline `include_item_types` **filtering** — already correct; only the
|
||||||
|
source of the type list moves.
|
||||||
|
- Ranking within or across groups (DR-090 territory).
|
||||||
|
- Chip UX, scope persistence, group-order persistence — unchanged.
|
||||||
|
- The two lesser type-set sites in `DownloadedBrowse.svelte` and
|
||||||
|
`GenericMediaListPage.svelte`, handled in
|
||||||
|
[boundary-tripwire-hardening.md](boundary-tripwire-hardening.md).
|
||||||
|
- Broadening the tripwire itself — same sibling spec.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
Inherits every criterion from [scoped-search-boundary.md](scoped-search-boundary.md)
|
||||||
|
§Acceptance criteria. Additionally:
|
||||||
|
|
||||||
|
- [ ] `grep -rn "SearchScope" src-tauri/src --include='*.rs'` returns matches —
|
||||||
|
the enum exists in Rust (it does not today).
|
||||||
|
- [ ] `grep -n "SCOPE_ITEM_TYPES\|scopeItemTypes\|GROUP_ITEM_TYPES\|groupItemTypes" src/lib/utils/searchScope.ts`
|
||||||
|
returns nothing.
|
||||||
|
- [ ] `grep -rn "scopeItemTypes" src/` returns nothing — including the
|
||||||
|
`library.ts` import and call site.
|
||||||
|
- [ ] `SearchOptions` in `bindings.ts` includes `scope`; regenerated, not
|
||||||
|
hand-edited.
|
||||||
|
- [ ] **Behaviour is byte-identical for the user**: same scoping, same groups,
|
||||||
|
same order, same empty-group omission, offline included. This spec is a
|
||||||
|
pure refactor — any visible change is a defect.
|
||||||
|
- [ ] `All` scope sends no `includeItemTypes` (asserted in a Rust test, not by
|
||||||
|
inspection).
|
||||||
|
- [ ] Adding a type to the Music scope requires editing **only** Rust —
|
||||||
|
demonstrate by making the edit and confirming no `src/` file changes.
|
||||||
|
- [ ] `scoped-search-boundary.md` status flips to **Implemented**, and
|
||||||
|
`scoped-search.md`'s "frontend only, no Rust changes" framing gets a
|
||||||
|
banner pointing at the corrected design.
|
||||||
|
- [ ] `bun run check` and `bun run test` pass.
|
||||||
|
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||||
|
- [ ] `bun run check:boundary` passes.
|
||||||
|
- [ ] Changed code carries `// TRACES:` comments (IDs below).
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Follow [scoped-search-boundary.md](scoped-search-boundary.md) §Testing. Emphases:
|
||||||
|
|
||||||
|
**Rust** (`cargo test`):
|
||||||
|
- `SearchScope::item_types()` per scope; `All` → `None`.
|
||||||
|
- Scope resolution happens **before** the online/offline split, so both paths
|
||||||
|
get the same filter — a regression here is invisible until someone searches
|
||||||
|
offline.
|
||||||
|
- `scope` set + `include_item_types` set → scope wins (the documented
|
||||||
|
precedence; assert it rather than trusting the doc).
|
||||||
|
- Stage 2: mixed `Vec<MediaItem>` buckets correctly; unknown types dropped;
|
||||||
|
canonical group order; **the `search-event` payload is the grouped shape**.
|
||||||
|
|
||||||
|
**Frontend** (`bun run test`):
|
||||||
|
- `resolveSearchScope()` tests in `searchScope.test.ts` must pass **unchanged** —
|
||||||
|
they cover the part that is not moving, and are the regression net proving the
|
||||||
|
refactor didn't disturb routing.
|
||||||
|
- `library.ts` sends `{ scope }` and never `includeItemTypes` for search.
|
||||||
|
- `composeSearchGroups()` over fixture `SearchGroup[]` with no `.type`
|
||||||
|
inspection in the implementation.
|
||||||
|
|
||||||
|
**Offline parity:** run a scoped search with the server unreachable and confirm
|
||||||
|
identical grouping. The offline repository path honours `include_item_types`
|
||||||
|
independently, and this is the case most likely to be missed.
|
||||||
|
|
||||||
|
## TRACES
|
||||||
|
|
||||||
|
No new requirement IDs — this implements existing ones. Retag as the code moves:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// src-tauri/src/repository/types.rs
|
||||||
|
/// TRACES: UR-049 | DR-063
|
||||||
|
pub enum SearchScope { … }
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/lib/utils/searchScope.ts — keep the file header; it retains
|
||||||
|
// resolveSearchScope + group-order presentation logic.
|
||||||
|
// TRACES: UR-049, UR-050 | DR-063, DR-066, DR-067
|
||||||
|
```
|
||||||
|
|
||||||
|
Update DR-063's text in `requirements.md` to state that scope expansion is owned
|
||||||
|
by Rust, so the requirement stops describing the leaked design. New Rust tests
|
||||||
|
take `@req-test: UT-089` onward (next free UT is **UT-089**).
|
||||||
|
|
||||||
|
## Notes for the implementer
|
||||||
|
|
||||||
|
- A parallel Claude session may be active in this repo — `git diff` before
|
||||||
|
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||||
|
- **Read [scoped-search-boundary.md](scoped-search-boundary.md) first.** This
|
||||||
|
spec is deliberately thin on design; that one is the authority.
|
||||||
|
- Sequence with the sibling specs: **Stage 1 here → then
|
||||||
|
[boundary-tripwire-hardening.md](boundary-tripwire-hardening.md)**. Hardening
|
||||||
|
the tripwire first turns `master` red on a known-unfixed violation.
|
||||||
|
- `git log --oneline -- docs/specs/scoped-search-boundary.md` is worth a look
|
||||||
|
before starting — understanding why the fix stalled may surface a constraint
|
||||||
|
the spec didn't record.
|
||||||
|
- The user-visible-change count for this spec is zero. If QA reports a
|
||||||
|
difference in search results, that is a bug in the refactor, not an
|
||||||
|
improvement.
|
||||||
@@ -8,8 +8,14 @@
|
|||||||
> is being moved into Rust. The **user-facing behaviour and UX in this spec are
|
> is being moved into Rust. The **user-facing behaviour and UX in this spec are
|
||||||
> unchanged**; only where the scope→item-type mapping and result bucketing live
|
> unchanged**; only where the scope→item-type mapping and result bucketing live
|
||||||
> changes. Read the boundary spec before touching search code.
|
> changes. Read the boundary spec before touching search code.
|
||||||
|
>
|
||||||
|
> **Progress:** the scope→item-type mapping now lives in Rust
|
||||||
|
> (`SearchScope::item_types()`); the frontend sends an opaque scope. Result-side
|
||||||
|
> bucketing (`GROUP_ITEM_TYPES`) is still frontend-side — see
|
||||||
|
> [scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md)
|
||||||
|
> §Stage 2.
|
||||||
|
|
||||||
**Status:** Implemented (boundary revision pending — see banner above)
|
**Status:** Implemented (boundary revision: query side done, result side pending)
|
||||||
**Scope:** Frontend only. No Rust changes required. *(Revised — see banner.)*
|
**Scope:** Frontend only. No Rust changes required. *(Revised — see banner.)*
|
||||||
**Requirements:** UR-049 → DR-063, DR-064, DR-065; UR-050 → DR-066, DR-067
|
**Requirements:** UR-049 → DR-063, DR-064, DR-065; UR-050 → DR-066, DR-067
|
||||||
(see [requirements.md](../requirements.md)).
|
(see [requirements.md](../requirements.md)).
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
# Spec: Repair the traceability coverage gate
|
||||||
|
|
||||||
|
**Status:** Implemented
|
||||||
|
**Requirements:** DR-093 → supports the traceability practice described in CLAUDE.md
|
||||||
|
**UX spec:** n/a — developer tooling, no user-facing surface.
|
||||||
|
**Supersedes / revises:** n/a
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
The CI traceability gate has been passing unconditionally for an unknown length
|
||||||
|
of time because it divides traced-requirement counts by **hardcoded denominators
|
||||||
|
that no longer match [requirements.md](../requirements.md)**. It currently
|
||||||
|
reports **158% overall coverage** (and `JA 24 / 3 = 800%`), so the 50% threshold
|
||||||
|
is mathematically unreachable and the job cannot fail. This spec makes the gate
|
||||||
|
derive its denominators from `requirements.md` at run time, so it reports the
|
||||||
|
real number (**85%** today) and can actually fail again.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
`.gitea/workflows/traceability-check.yml` hardcodes `UR/39, IR/24, DR/48, JA/3`
|
||||||
|
and `TOTAL_REQS=114`. The real counts are **UR 61, IR 29, DR 89, JA 32 — 211
|
||||||
|
total**. Requirements were added over time; the divisors were never updated.
|
||||||
|
|
||||||
|
The consequence is not a cosmetic reporting bug. The gate is the *only*
|
||||||
|
automated defence for the traceability practice, and it is dead:
|
||||||
|
|
||||||
|
```
|
||||||
|
CI today: 181 / 114 = 158% → threshold 50% can never trip
|
||||||
|
Reality: 181 / 211 = 85% → healthy, but unguarded
|
||||||
|
```
|
||||||
|
|
||||||
|
Coverage could collapse to 30% and CI would still print a green
|
||||||
|
"✅ Coverage is acceptable". An audit of the design principles found that every
|
||||||
|
principle with a *working* automated check is in good shape, and the ones that
|
||||||
|
drifted are exactly the ones whose checks were broken or too narrow — this is
|
||||||
|
the clearest instance.
|
||||||
|
|
||||||
|
A second, related defect is handled in a sibling spec: `scripts/check-req-coverage.sh`
|
||||||
|
is separately broken and orphaned (see
|
||||||
|
[req-coverage-script-removal.md](req-coverage-script-removal.md)).
|
||||||
|
|
||||||
|
## Layer assignment
|
||||||
|
|
||||||
|
This spec touches only CI/build tooling — no application logic crosses the
|
||||||
|
Rust/Svelte boundary. The table is filled in for completeness.
|
||||||
|
|
||||||
|
| Logic / responsibility | Layer | Why it belongs there |
|
||||||
|
|------------------------|-------|----------------------|
|
||||||
|
| Counting requirement IDs defined in `requirements.md` | Build tooling (`scripts/`) | Neither runtime layer; it is repo metadata analysis. Belongs beside `extract-traces.ts`, not in the workflow YAML, so it is runnable and testable locally. |
|
||||||
|
| Counting *traced* requirement IDs | Build tooling — existing `extract-traces.ts` | Already implemented and correct; this spec consumes it rather than duplicating it. |
|
||||||
|
| Threshold policy (the 50% number) | CI workflow | Deployment policy, not analysis. Keeping it in YAML lets it be tuned without touching the script. |
|
||||||
|
|
||||||
|
No frontend or Rust logic is added, so no taxonomy leak is possible.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### 1. Denominators come from `requirements.md`, not literals
|
||||||
|
|
||||||
|
`requirements.md` defines requirements in markdown tables with a stable leading
|
||||||
|
cell, e.g.:
|
||||||
|
|
||||||
|
```
|
||||||
|
| DR-001 | Player state machine (idle, loading, …) | Player | UR-005 | Done |
|
||||||
|
| UR-002 | Access media when online or offline | High | Done |
|
||||||
|
```
|
||||||
|
|
||||||
|
Extend [scripts/extract-traces.ts](../../scripts/extract-traces.ts) to also emit
|
||||||
|
the *defined* counts, so one tool owns both sides of the fraction and CI does no
|
||||||
|
arithmetic on stale literals. Add a `defined` key to the JSON report:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{
|
||||||
|
"byType": { "UR": [...], "IR": [...], "DR": [...], "JA": [...] }, // traced (existing)
|
||||||
|
"defined": { "UR": 61, "IR": 29, "DR": 89, "JA": 32 }, // NEW
|
||||||
|
"coverage": { "covered": 181, "total": 211, "percent": 85 }, // NEW
|
||||||
|
"requirements": { ... }, // existing
|
||||||
|
"totalTraces": 318, "totalFiles": …, "timestamp": "…" // existing
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Parsing rule for a *defined* requirement: a line in `docs/requirements.md`
|
||||||
|
matching `^\|\s*(UR|IR|DR|JA)-\d{3}\s*\|` — the ID must be the table's first
|
||||||
|
cell. This deliberately does **not** count IDs mentioned in the `Traces To`
|
||||||
|
column or in prose, which is why a naive `grep -o` over the whole file
|
||||||
|
overcounts.
|
||||||
|
|
||||||
|
`defined` counts IDs that exist in the spec; `byType` counts IDs that appear in
|
||||||
|
a `TRACES:` comment somewhere in the source. Coverage is
|
||||||
|
`|byType ∩ defined| / |defined|`.
|
||||||
|
|
||||||
|
> **Intersection, not raw length.** A `TRACES:` comment naming an ID that
|
||||||
|
> `requirements.md` does not define (a typo, or a requirement later deleted)
|
||||||
|
> must **not** inflate the numerator — that is how a ratio exceeds 100% in the
|
||||||
|
> first place. Such IDs are reported separately as `orphaned` so they get fixed
|
||||||
|
> rather than silently counted or silently dropped.
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
"orphaned": ["DR-097"] // traced in code but not defined in requirements.md
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. The workflow consumes the computed number
|
||||||
|
|
||||||
|
Replace the arithmetic in `.gitea/workflows/traceability-check.yml` (lines
|
||||||
|
46–76) with reads of the precomputed fields:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
COVERAGE=$(jq '.coverage.percent' traces-report.json)
|
||||||
|
COVERED=$(jq '.coverage.covered' traces-report.json)
|
||||||
|
TOTAL_REQS=$(jq '.coverage.total' traces-report.json)
|
||||||
|
|
||||||
|
for T in UR IR DR JA; do
|
||||||
|
TRACED=$(jq --arg t "$T" '.byType[$t] | length' traces-report.json)
|
||||||
|
DEFINED=$(jq --arg t "$T" '.defined[$t]' traces-report.json)
|
||||||
|
echo " $T: $TRACED / $DEFINED"
|
||||||
|
done
|
||||||
|
|
||||||
|
MIN_THRESHOLD=50
|
||||||
|
[ "$COVERAGE" -lt "$MIN_THRESHOLD" ] && { echo "❌ …"; exit 1; }
|
||||||
|
```
|
||||||
|
|
||||||
|
No hardcoded denominator survives anywhere in the workflow.
|
||||||
|
|
||||||
|
### 3. A self-check so this cannot silently rot again
|
||||||
|
|
||||||
|
The root cause was a number that drifted with nothing watching it. Add a
|
||||||
|
guard that fails the job on an arithmetically impossible result:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
if [ "$COVERAGE" -gt 100 ]; then
|
||||||
|
echo "❌ Coverage > 100% — the gate is miscomputing; orphaned IDs: $(jq -c '.orphaned' traces-report.json)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
A >100% reading is now a hard failure rather than a green tick.
|
||||||
|
|
||||||
|
### 4. Local parity
|
||||||
|
|
||||||
|
Add a script so the gate is runnable outside CI:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
"traces:coverage": "bun run scripts/extract-traces.ts --format coverage"
|
||||||
|
```
|
||||||
|
|
||||||
|
Prints the same table CI prints and exits non-zero below threshold.
|
||||||
|
|
||||||
|
### Threshold
|
||||||
|
|
||||||
|
Keep `MIN_THRESHOLD=50` in this spec. Real coverage is 85%, so raising the bar
|
||||||
|
is tempting, but doing it in the same change that repairs the gate conflates
|
||||||
|
"restore the safety net" with "tighten the policy" — if the build then fails, it
|
||||||
|
is ambiguous which change caused it. Ratcheting is deliberately deferred to
|
||||||
|
follow-up work once the honest number has been observed on `master` for a few
|
||||||
|
builds.
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- Raising `MIN_THRESHOLD` above 50 (see above).
|
||||||
|
- Fixing/removing `scripts/check-req-coverage.sh` — [req-coverage-script-removal.md](req-coverage-script-removal.md).
|
||||||
|
- Adding TRACES comments to raise the actual coverage number.
|
||||||
|
- Changing the `TRACES:` comment format or the extractor's parsing of it.
|
||||||
|
- The PR "modified files missing TRACES" step (lines 78–126), which is advisory
|
||||||
|
by design and stays advisory.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] `bun run traces:json` emits `defined`, `coverage`, and `orphaned` keys.
|
||||||
|
- [ ] `coverage.total` equals the count of requirement IDs defined in
|
||||||
|
`requirements.md` (**211** at time of writing), not a literal.
|
||||||
|
- [ ] `coverage.percent` reports **85** (±1 for rounding) on the current tree —
|
||||||
|
i.e. the honest number, not 158.
|
||||||
|
- [ ] No hardcoded requirement denominator (`39`, `24`, `48`, `3`, `114`) remains
|
||||||
|
in `.gitea/workflows/traceability-check.yml`. Verify:
|
||||||
|
`grep -nE '/ *(39|24|48|3|114)\b' .gitea/workflows/traceability-check.yml`
|
||||||
|
returns nothing.
|
||||||
|
- [ ] Adding a new requirement row to `requirements.md` **lowers** reported
|
||||||
|
coverage until it is traced (proves the denominator is live).
|
||||||
|
- [ ] A `TRACES:` comment naming an undefined ID appears in `orphaned` and does
|
||||||
|
**not** raise `coverage.percent`.
|
||||||
|
- [ ] The job fails if coverage is forced below 50% (test by temporarily raising
|
||||||
|
`MIN_THRESHOLD` to 99 locally) — proving the gate can fail again.
|
||||||
|
- [ ] The job fails if coverage computes >100%.
|
||||||
|
- [ ] `bun run check` and `bun run test` pass.
|
||||||
|
- [ ] `bun run check:boundary` passes.
|
||||||
|
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||||
|
- [ ] No Rust types changed, so no `bindings.ts` regeneration needed.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
`extract-traces.ts` currently has no test coverage. Add
|
||||||
|
`scripts/extract-traces.test.ts` (vitest) over fixture strings rather than the
|
||||||
|
live `requirements.md`, so the tests do not change meaning as requirements are
|
||||||
|
added:
|
||||||
|
|
||||||
|
- **UT:** counts a well-formed table row as a defined requirement.
|
||||||
|
- **UT:** does **not** count an ID appearing only in the `Traces To` column or
|
||||||
|
in prose — the specific overcounting bug this parse rule avoids.
|
||||||
|
- **UT:** coverage is the intersection — a traced-but-undefined ID lands in
|
||||||
|
`orphaned` and does not inflate the numerator.
|
||||||
|
- **UT:** coverage of an empty trace set is 0%, not a divide-by-zero.
|
||||||
|
- **UT:** all-traced fixture reports exactly 100%, never above.
|
||||||
|
|
||||||
|
CI behaviour is verified by the acceptance criteria above (the forced-failure
|
||||||
|
check is the important one — a gate nobody has watched fail is not known to
|
||||||
|
work).
|
||||||
|
|
||||||
|
## TRACES
|
||||||
|
|
||||||
|
Allocate in `requirements.md`:
|
||||||
|
|
||||||
|
- **DR-093** — "Traceability coverage gate derives requirement denominators from
|
||||||
|
`requirements.md` at run time (not hardcoded literals), computes coverage as
|
||||||
|
the intersection of traced and defined IDs, reports IDs traced but undefined
|
||||||
|
as orphaned, and fails on an impossible >100% result." Category: Tooling.
|
||||||
|
Status: Done on merge.
|
||||||
|
|
||||||
|
Tag:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// scripts/extract-traces.ts
|
||||||
|
// TRACES: | DR-093
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests carry `@req-test: UT-089 …` onward (next free UT is **UT-089**).
|
||||||
|
|
||||||
|
## Notes for the implementer
|
||||||
|
|
||||||
|
- A parallel Claude session may be active in this repo — run `git diff` before
|
||||||
|
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||||
|
- **Do not add tooling to the CI image for this.** `jq` and `bun` are already in
|
||||||
|
`jellytau-builder`; this spec needs nothing else. Installing a system package
|
||||||
|
in a workflow step violates the hard CI rule in CLAUDE.md.
|
||||||
|
- Keep `traces:json`'s existing keys intact — `release-notes.ts` and
|
||||||
|
`traces:markdown` consume the same report, and the CI workflow uploads it as
|
||||||
|
an artifact. This is an additive change.
|
||||||
|
- The `head -50 docs/traceability.md` and artifact-upload steps are unaffected.
|
||||||
|
- Expect the first green build after this change to print a *lower* number than
|
||||||
|
before (85% vs 158%). That is the fix working, not a regression.
|
||||||
+26
-12
@@ -43,14 +43,26 @@ Extracts all TRACES comments from:
|
|||||||
|
|
||||||
### 2. Coverage Thresholds
|
### 2. Coverage Thresholds
|
||||||
The workflow checks:
|
The workflow checks:
|
||||||
- **Minimum overall coverage:** 50% (57+ requirements traced)
|
- **Minimum overall coverage:** 50%
|
||||||
- **Requirements by type:**
|
|
||||||
- UR (User): 23+ of 39
|
|
||||||
- IR (Integration): 5+ of 24
|
|
||||||
- DR (Development): 28+ of 48
|
|
||||||
- JA (Jellyfin API): 0+ of 3
|
|
||||||
|
|
||||||
If coverage drops below threshold, the workflow **fails** and blocks merge.
|
Denominators are **derived from `docs/requirements.md` at run time** — they are
|
||||||
|
never hardcoded here or in the workflow. Run `bun run traces:coverage` for the
|
||||||
|
current per-type breakdown; any number written into this document is a snapshot
|
||||||
|
that will drift.
|
||||||
|
|
||||||
|
> **Why this matters.** The workflow used to divide by frozen literals
|
||||||
|
> (UR/39, IR/24, DR/48, JA/3, total 114) while `requirements.md` had grown past
|
||||||
|
> 200. It reported **158%** coverage, so the 50% threshold was unreachable and
|
||||||
|
> the job could not fail regardless of how far coverage dropped. See
|
||||||
|
> [specs/traceability-gate-repair.md](specs/traceability-gate-repair.md).
|
||||||
|
|
||||||
|
Coverage is the *intersection* of traced and defined IDs: an ID that appears in
|
||||||
|
a `TRACES:` comment but is not defined in `requirements.md` is reported as
|
||||||
|
**orphaned** and does not count toward coverage. UT/IT test identifiers are a
|
||||||
|
separate taxonomy and are excluded entirely.
|
||||||
|
|
||||||
|
The workflow **fails** and blocks merge if coverage drops below 50% — or if it
|
||||||
|
computes above 100%, which can only mean the gate is miscounting.
|
||||||
|
|
||||||
### 3. Modified File Checking
|
### 3. Modified File Checking
|
||||||
On pull requests, the workflow:
|
On pull requests, the workflow:
|
||||||
@@ -153,11 +165,13 @@ cat docs/traceability.md
|
|||||||
## Coverage Goals
|
## Coverage Goals
|
||||||
|
|
||||||
### Current Status
|
### Current Status
|
||||||
- Overall: 51% (56/114)
|
|
||||||
- UR: 59% (23/39)
|
Run `bun run traces:coverage` — it prints the live figure and exits non-zero
|
||||||
- IR: 21% (5/24)
|
below threshold. Numbers are deliberately not pinned here; the previous snapshot
|
||||||
- DR: 58% (28/48)
|
in this section (51%, 56/114) was stale by roughly 100 requirements and was what
|
||||||
- JA: 0% (0/3)
|
made the broken CI arithmetic look plausible for so long.
|
||||||
|
|
||||||
|
As of July 2026 overall coverage is ~86% (182/212).
|
||||||
|
|
||||||
### Targets
|
### Targets
|
||||||
- **Short term** (Sprint): Maintain ≥50% overall
|
- **Short term** (Sprint): Maintain ≥50% overall
|
||||||
|
|||||||
+22
-5
@@ -1,15 +1,15 @@
|
|||||||
# Code Traceability Matrix
|
# Code Traceability Matrix
|
||||||
|
|
||||||
**Generated:** 7/28/2026, 10:39:16 PM
|
**Generated:** 7/28/2026, 11:52:49 PM
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
- **Total Files Scanned:** 299
|
- **Total Files Scanned:** 302
|
||||||
- **Total TRACES Found:** 318
|
- **Total TRACES Found:** 322
|
||||||
- **Requirements Covered:**
|
- **Requirements Covered:**
|
||||||
- User Requirements (UR): 58
|
- User Requirements (UR): 58
|
||||||
- Integration Requirements (IR): 15
|
- Integration Requirements (IR): 15
|
||||||
- Development Requirements (DR): 84
|
- Development Requirements (DR): 85
|
||||||
- Jellyfin API Requirements (JA): 24
|
- Jellyfin API Requirements (JA): 24
|
||||||
|
|
||||||
## Requirements by Type
|
## Requirements by Type
|
||||||
@@ -26,7 +26,7 @@ IR-003, IR-004, IR-009, IR-010, IR-011, IR-012, IR-013, IR-014, IR-015, IR-020,
|
|||||||
|
|
||||||
### Development Requirements (DR)
|
### Development Requirements (DR)
|
||||||
```
|
```
|
||||||
DR-001, DR-002, DR-003, DR-004, DR-005, DR-006, DR-007, DR-009, DR-010, DR-011, DR-012, DR-013, DR-014, DR-015, DR-016, DR-017, DR-018, DR-020, DR-021, DR-022, DR-023, DR-024, DR-025, DR-026, DR-027, DR-028, DR-029, DR-030, DR-032, DR-033, DR-034, DR-035, DR-036, DR-037, DR-038, DR-039, DR-040, DR-041, DR-043, DR-044, DR-045, DR-047, DR-048, DR-049, DR-050, DR-051, DR-052, DR-053, DR-054, DR-055, DR-056, DR-057, DR-058, DR-059, DR-060, DR-061, DR-062, DR-063, DR-064, DR-065, DR-066, DR-067, DR-068, DR-069, DR-070, DR-074, DR-075, DR-076, DR-077, DR-078, DR-079, DR-080, DR-081, DR-082, DR-083, DR-084, DR-085, DR-086, DR-087, DR-088, DR-089, DR-090, DR-091, DR-092
|
DR-001, DR-002, DR-003, DR-004, DR-005, DR-006, DR-007, DR-009, DR-010, DR-011, DR-012, DR-013, DR-014, DR-015, DR-016, DR-017, DR-018, DR-020, DR-021, DR-022, DR-023, DR-024, DR-025, DR-026, DR-027, DR-028, DR-029, DR-030, DR-032, DR-033, DR-034, DR-035, DR-036, DR-037, DR-038, DR-039, DR-040, DR-041, DR-043, DR-044, DR-045, DR-047, DR-048, DR-049, DR-050, DR-051, DR-052, DR-053, DR-054, DR-055, DR-056, DR-057, DR-058, DR-059, DR-060, DR-061, DR-062, DR-063, DR-064, DR-065, DR-066, DR-067, DR-068, DR-069, DR-070, DR-074, DR-075, DR-076, DR-077, DR-078, DR-079, DR-080, DR-081, DR-082, DR-083, DR-084, DR-085, DR-086, DR-087, DR-088, DR-089, DR-090, DR-091, DR-092, DR-093
|
||||||
```
|
```
|
||||||
|
|
||||||
### Jellyfin API Requirements (JA)
|
### Jellyfin API Requirements (JA)
|
||||||
@@ -1881,6 +1881,23 @@ JA-001, JA-002, JA-003, JA-004, JA-005, JA-007, JA-010, JA-011, JA-012, JA-016,
|
|||||||
- **Line:** 10
|
- **Line:** 10
|
||||||
- **Context:** `Unknown`
|
- **Context:** `Unknown`
|
||||||
|
|
||||||
|
### DR-093
|
||||||
|
|
||||||
|
**Locations:** 4 file(s)
|
||||||
|
|
||||||
|
- **File:** [`scripts/extract-traces.ts`](scripts/extract-traces.ts#L216)
|
||||||
|
- **Line:** 216
|
||||||
|
- **Context:** `Unknown`
|
||||||
|
- **File:** [`scripts/extract-traces.ts`](scripts/extract-traces.ts#L246)
|
||||||
|
- **Line:** 246
|
||||||
|
- **Context:** `Unknown`
|
||||||
|
- **File:** [`scripts/extract-traces.ts`](scripts/extract-traces.ts#L278)
|
||||||
|
- **Line:** 278
|
||||||
|
- **Context:** `Unknown`
|
||||||
|
- **File:** [`scripts/extract-traces.ts`](scripts/extract-traces.ts#L387)
|
||||||
|
- **Line:** 387
|
||||||
|
- **Context:** `function generateJson(data: TracesData): string {`
|
||||||
|
|
||||||
### JA-001
|
### JA-001
|
||||||
|
|
||||||
**Locations:** 1 file(s)
|
**Locations:** 1 file(s)
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "jellytau",
|
"name": "jellytau",
|
||||||
"version": "0.2.0",
|
"version": "0.2.1",
|
||||||
"description": "",
|
"description": "",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "bun@1.3.5",
|
"packageManager": "bun@1.3.5",
|
||||||
@@ -36,6 +36,7 @@
|
|||||||
"traces": "bun run scripts/extract-traces.ts",
|
"traces": "bun run scripts/extract-traces.ts",
|
||||||
"traces:json": "bun run scripts/extract-traces.ts --format json",
|
"traces:json": "bun run scripts/extract-traces.ts --format json",
|
||||||
"traces:markdown": "bun run scripts/extract-traces.ts --format markdown > docs/traceability.md",
|
"traces:markdown": "bun run scripts/extract-traces.ts --format markdown > docs/traceability.md",
|
||||||
|
"traces:coverage": "bun run scripts/extract-traces.ts --format coverage",
|
||||||
"release:notes": "bun run scripts/release-notes.ts"
|
"release:notes": "bun run scripts/release-notes.ts"
|
||||||
},
|
},
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
+17
-1
@@ -69,13 +69,29 @@ Extract requirement IDs (TRACES) from source code and generate a traceability ma
|
|||||||
bun run traces # Generate markdown report
|
bun run traces # Generate markdown report
|
||||||
bun run traces:json # Generate JSON report
|
bun run traces:json # Generate JSON report
|
||||||
bun run traces:markdown # Save to docs/traceability.md
|
bun run traces:markdown # Save to docs/traceability.md
|
||||||
|
bun run traces:coverage # Coverage gate — exits non-zero below 50%
|
||||||
```
|
```
|
||||||
|
|
||||||
The script scans all TypeScript, Svelte, and Rust files looking for `TRACES:` comments and generates a comprehensive mapping of:
|
The script scans all TypeScript, Svelte, and Rust files (plus `scripts/`)
|
||||||
|
looking for `TRACES:` comments and generates a comprehensive mapping of:
|
||||||
- Which code files implement which requirements
|
- Which code files implement which requirements
|
||||||
- Line numbers and code context
|
- Line numbers and code context
|
||||||
- Coverage summary by requirement type (UR, IR, DR, JA)
|
- Coverage summary by requirement type (UR, IR, DR, JA)
|
||||||
|
|
||||||
|
**`bun run traces:coverage` is the supported way to check requirement coverage
|
||||||
|
locally** — it runs the same computation CI does. Coverage denominators are
|
||||||
|
derived from `docs/requirements.md` at run time; they are never hardcoded. An ID
|
||||||
|
that appears in a `TRACES:` comment but is not defined in `requirements.md` is
|
||||||
|
reported as *orphaned* and does not count toward coverage (see DR-093).
|
||||||
|
|
||||||
|
> **Removed:** `check-req-coverage.sh`, `check-test-coverage.sh`, and
|
||||||
|
> `find-req-implementations.sh` were deleted in July 2026. They read an
|
||||||
|
> undocumented `@req:` tag convention parallel to `TRACES:`, grepped `src-tauri/`
|
||||||
|
> unscoped (hanging on ~40 GB of `target/` artifacts), and in one case reported
|
||||||
|
> "all requirements implemented" from an empty result set. `extract-traces.ts` is
|
||||||
|
> the single source of truth for requirement coverage. See
|
||||||
|
> [docs/specs/req-coverage-script-removal.md](../docs/specs/req-coverage-script-removal.md).
|
||||||
|
|
||||||
Example TRACES comment in code:
|
Example TRACES comment in code:
|
||||||
```typescript
|
```typescript
|
||||||
// TRACES: UR-005, UR-026 | DR-029
|
// TRACES: UR-005, UR-026 | DR-029
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Boundary tripwire: flag domain-taxonomy leaks in the Svelte frontend.
|
# Boundary tripwire: flag domain-taxonomy leaks in the Svelte frontend.
|
||||||
#
|
#
|
||||||
|
# Implements DR-094 (see docs/requirements.md).
|
||||||
|
#
|
||||||
# The project rule (CLAUDE.md, docs/architecture/02-svelte-frontend.md) is that
|
# The project rule (CLAUDE.md, docs/architecture/02-svelte-frontend.md) is that
|
||||||
# the frontend is presentation-only and the Rust backend owns domain logic —
|
# the frontend is presentation-only and the Rust backend owns domain logic —
|
||||||
# including Jellyfin's item-type *taxonomy* (what the category "Music" means as a
|
# including Jellyfin's item-type *taxonomy* (what the category "Music" means as a
|
||||||
@@ -9,18 +11,29 @@
|
|||||||
#
|
#
|
||||||
# ⚠️ This is a TRIPWIRE, NOT A PROOF. A grep cannot distinguish taxonomy-as-policy
|
# ⚠️ This is a TRIPWIRE, NOT A PROOF. A grep cannot distinguish taxonomy-as-policy
|
||||||
# (a leak) from taxonomy-as-display (legitimate: "is this a music card?"). It
|
# (a leak) from taxonomy-as-display (legitimate: "is this a music card?"). It
|
||||||
# targets the one machine-detectable signature of the leak class — a *query* that
|
# targets the machine-detectable signature of the leak class and defers
|
||||||
# names a multi-type category — and defers everything subtler to the human
|
# everything subtler to the human spec-review checklist
|
||||||
# spec-review checklist (docs/specs/SPEC-REVIEW-CHECKLIST.md). A clean run here
|
# (docs/specs/SPEC-REVIEW-CHECKLIST.md). A clean run here does not mean the
|
||||||
# does not mean the boundary is respected; it means the crudest violation isn't
|
# boundary is respected; it means the crudest violation isn't present.
|
||||||
# present.
|
|
||||||
#
|
#
|
||||||
# What it flags: an `includeItemTypes: [ ... , ... ]` array literal with two or
|
# What it flags: an array literal naming two or more Jellyfin item types,
|
||||||
# more types — i.e. the frontend deciding that a *category* maps to a *set* of
|
# ANYWHERE in src/ — i.e. the frontend deciding that a *category* maps to a *set*
|
||||||
# Jellyfin types, which is domain knowledge the backend should own. Single-type
|
# of Jellyfin types, which is domain knowledge the backend should own.
|
||||||
# query arrays (`includeItemTypes: ["Movie"]`) are a page saying "I show movies"
|
# Single-type arrays (`includeItemTypes: ["Movie"]`) are a page saying "I show
|
||||||
# and are allowed. Type *inspection* (`item.type === "Audio"`) is display logic
|
# movies" and are allowed. Type *inspection* (`item.type === "Audio"`) is display
|
||||||
# and is not matched.
|
# logic and is not matched.
|
||||||
|
#
|
||||||
|
# 🔴 What it still CANNOT see (do not read a green run as proof):
|
||||||
|
# - a type set built at run time: [...musicTypes, "Playlist"]
|
||||||
|
# - types split across variables: const A = "Audio"; [A, B]
|
||||||
|
# - taxonomy as control flow: switch (t) { case "Audio": … }
|
||||||
|
# t === "Audio" || t === "MusicAlbum"
|
||||||
|
# - an item type absent from ITEM_TYPES below (false negative by design)
|
||||||
|
#
|
||||||
|
# This check was hardened in July 2026 after the audit found it passing on the
|
||||||
|
# very leak it was written for: the original pattern was anchored to
|
||||||
|
# `includeItemTypes:` at the query site, so assigning the same array to a named
|
||||||
|
# const evaded it entirely. See docs/specs/boundary-tripwire-hardening.md (DR-094).
|
||||||
#
|
#
|
||||||
# Escaping a genuine exception: add the file+reason to the ALLOWLIST below.
|
# Escaping a genuine exception: add the file+reason to the ALLOWLIST below.
|
||||||
|
|
||||||
@@ -28,7 +41,7 @@ set -euo pipefail
|
|||||||
|
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
# Files permitted to contain a multi-type includeItemTypes query, with the reason.
|
# Files permitted to contain a multi-type item-type array, with the reason.
|
||||||
# Keep this SHORT. A growing allowlist means the boundary is eroding — that is a
|
# Keep this SHORT. A growing allowlist means the boundary is eroding — that is a
|
||||||
# signal to push taxonomy into Rust, not to keep appending here.
|
# signal to push taxonomy into Rust, not to keep appending here.
|
||||||
ALLOWLIST=(
|
ALLOWLIST=(
|
||||||
@@ -36,8 +49,31 @@ ALLOWLIST=(
|
|||||||
# two-type filmography query with no category-configuration behind it. Tracked
|
# two-type filmography query with no category-configuration behind it. Tracked
|
||||||
# as acceptable pending any person-scope work; revisit if it grows.
|
# as acceptable pending any person-scope work; revisit if it grows.
|
||||||
"src/lib/components/library/PersonDetailView.svelte"
|
"src/lib/components/library/PersonDetailView.svelte"
|
||||||
|
|
||||||
|
# Grid styling predicate over `config.itemType`, a value the page already
|
||||||
|
# declares about itself. Selects a *look*, issues no query, and would only
|
||||||
|
# change if the UI were redesigned — presentation, not taxonomy-as-policy.
|
||||||
|
"src/lib/components/library/GenericMediaListPage.svelte"
|
||||||
|
|
||||||
|
# "Is this item a container?" predicate for downloads browsing.
|
||||||
|
# BORDERLINE — leans domain: the container set grows when Jellyfin adds a
|
||||||
|
# container type. TODO: replace with a backend-supplied `MediaItem.isContainer`
|
||||||
|
# flag and remove this entry. Tracked in
|
||||||
|
# docs/specs/boundary-tripwire-hardening.md §Out of scope.
|
||||||
|
"src/lib/components/downloads/DownloadedBrowse.svelte"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Hard cap so erosion is caught mechanically rather than by whoever notices.
|
||||||
|
# Deliberately just above the current count: the next exception forces a
|
||||||
|
# conversation instead of a one-line append.
|
||||||
|
MAX_ALLOWLIST=4
|
||||||
|
|
||||||
|
if [[ "${#ALLOWLIST[@]}" -gt "$MAX_ALLOWLIST" ]]; then
|
||||||
|
echo "❌ Allowlist has ${#ALLOWLIST[@]} entries (max $MAX_ALLOWLIST)."
|
||||||
|
echo " Push taxonomy into Rust instead of appending here."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
is_allowed() {
|
is_allowed() {
|
||||||
local file="$1"
|
local file="$1"
|
||||||
for allowed in "${ALLOWLIST[@]}"; do
|
for allowed in "${ALLOWLIST[@]}"; do
|
||||||
@@ -46,11 +82,28 @@ is_allowed() {
|
|||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# Multi-element includeItemTypes array: `includeItemTypes: [ <x> , <y> ... ]`.
|
# Two or more adjacent Jellyfin item-type string literals inside a bracket.
|
||||||
# The comma inside the brackets is what makes it multi-type.
|
#
|
||||||
PATTERN='includeItemTypes:[[:space:]]*\[[^]]*,[^]]*\]'
|
# NOT anchored to `includeItemTypes:` — that was the original rule, and it missed
|
||||||
|
# the real leak: `searchScope.ts` assigned the same array to a named const and
|
||||||
|
# dereferenced it one indirection away from the query, so the grep never saw it
|
||||||
|
# while CI stayed green. Matching the array literal itself catches a const, a
|
||||||
|
# Record value, a function return, and an inline query alike.
|
||||||
|
#
|
||||||
|
# Deliberate limits:
|
||||||
|
# - requires TWO adjacent types, so single-type presentation
|
||||||
|
# (`itemType: "Movie"`) stays legal — the rule targets *category* taxonomy;
|
||||||
|
# - requires string literals, so `item.type === "Audio"` (display inspection)
|
||||||
|
# does not match;
|
||||||
|
# - uses an explicit type list rather than a generic capitalised-word pattern,
|
||||||
|
# so unrelated string arrays (`["High","Low"]`) produce no noise.
|
||||||
|
#
|
||||||
|
# An item type missing from this list is a false *negative*, never a false
|
||||||
|
# positive — the check degrades safely as Jellyfin adds types.
|
||||||
|
ITEM_TYPES='Movie|Series|Episode|Audio|MusicAlbum|MusicArtist|MusicVideo|Season|BoxSet|Playlist|Book|AudioBook|Video|Person|Folder|CollectionFolder|TvChannel|LiveTvChannel'
|
||||||
|
PATTERN="\[[[:space:]]*\"($ITEM_TYPES)\"[[:space:]]*,[[:space:]]*\"($ITEM_TYPES)\""
|
||||||
|
|
||||||
echo "🔎 Checking frontend for domain-taxonomy leaks (multi-type query arrays)…"
|
echo "🔎 Checking frontend for domain-taxonomy leaks (item-type array literals)…"
|
||||||
|
|
||||||
# Collect hits, excluding tests and the allowlist.
|
# Collect hits, excluding tests and the allowlist.
|
||||||
violations=""
|
violations=""
|
||||||
@@ -69,9 +122,11 @@ done < <(grep -rInE "$PATTERN" src/ 2>/dev/null || true)
|
|||||||
|
|
||||||
if [[ -n "$violations" ]]; then
|
if [[ -n "$violations" ]]; then
|
||||||
echo ""
|
echo ""
|
||||||
echo "❌ Frontend boundary violation: a multi-type includeItemTypes query defines"
|
echo "❌ Frontend boundary violation: an item-type array literal defines a"
|
||||||
echo " a category in the presentation layer. That taxonomy belongs in Rust —"
|
echo " category in the presentation layer. That taxonomy belongs in Rust —"
|
||||||
echo " send an opaque scope and let the backend expand it to item types."
|
echo " send an opaque scope/enum and let the backend expand it to item types"
|
||||||
|
echo " (see SearchScope::item_types() in src-tauri/src/repository/types.rs)."
|
||||||
|
echo " Assigning the array to a const does not make it presentation."
|
||||||
echo " See docs/specs/scoped-search-boundary.md and CLAUDE.md."
|
echo " See docs/specs/scoped-search-boundary.md and CLAUDE.md."
|
||||||
echo ""
|
echo ""
|
||||||
echo "$violations" | sed 's/^/ /'
|
echo "$violations" | sed 's/^/ /'
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# Requirements Coverage Checker
|
|
||||||
# Extracts @req tags from codebase and compares with README.md
|
|
||||||
#
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
REQUIREMENTS_FILE="README.md"
|
|
||||||
SOURCE_DIRS="src-tauri/ src/"
|
|
||||||
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
echo " Requirements Coverage Report"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Extract requirement IDs from README.md (UR-, IR-, DR-, JA-)
|
|
||||||
echo "📊 Scanning requirements from $REQUIREMENTS_FILE..."
|
|
||||||
requirements=$(grep -E "^\| (UR|IR|DR|JA)-[0-9]+" "$REQUIREMENTS_FILE" | \
|
|
||||||
sed -E 's/^\| ([A-Z]+-[0-9]+).*/\1/' | \
|
|
||||||
sort -u)
|
|
||||||
|
|
||||||
total_reqs=$(echo "$requirements" | wc -l)
|
|
||||||
implemented=0
|
|
||||||
partial=0
|
|
||||||
planned=0
|
|
||||||
missing=0
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Category Breakdown:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
|
|
||||||
for category in UR IR DR JA; do
|
|
||||||
cat_count=$(echo "$requirements" | grep "^$category-" | wc -l)
|
|
||||||
printf "%-4s %3d requirements\n" "$category:" "$cat_count"
|
|
||||||
done
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Implementation Status:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
|
|
||||||
for req in $requirements; do
|
|
||||||
# Count full implementations
|
|
||||||
full_count=$(grep -r "@req: $req" $SOURCE_DIRS 2>/dev/null | grep -v "@req-partial" | grep -v "@req-planned" | wc -l)
|
|
||||||
|
|
||||||
# Count partial implementations
|
|
||||||
partial_count=$(grep -r "@req-partial: $req" $SOURCE_DIRS 2>/dev/null | wc -l)
|
|
||||||
|
|
||||||
# Count planned
|
|
||||||
planned_count=$(grep -r "@req-planned: $req" $SOURCE_DIRS 2>/dev/null | wc -l)
|
|
||||||
|
|
||||||
if [ "$full_count" -gt 0 ]; then
|
|
||||||
echo "✅ $req: $full_count implementation(s)"
|
|
||||||
((implemented++))
|
|
||||||
elif [ "$partial_count" -gt 0 ]; then
|
|
||||||
echo "🔶 $req: $partial_count partial implementation(s)"
|
|
||||||
((partial++))
|
|
||||||
elif [ "$planned_count" -gt 0 ]; then
|
|
||||||
echo "📋 $req: Planned (not yet implemented)"
|
|
||||||
((planned++))
|
|
||||||
else
|
|
||||||
echo "❌ $req: No implementation found"
|
|
||||||
((missing++))
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Summary:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
printf "Total Requirements: %3d\n" "$total_reqs"
|
|
||||||
printf "✅ Fully Implemented: %3d (%.0f%%)\n" "$implemented" "$(echo "scale=0; $implemented * 100 / $total_reqs" | bc)"
|
|
||||||
printf "🔶 Partially Implemented: %3d (%.0f%%)\n" "$partial" "$(echo "scale=0; $partial * 100 / $total_reqs" | bc)"
|
|
||||||
printf "📋 Planned: %3d (%.0f%%)\n" "$planned" "$(echo "scale=0; $planned * 100 / $total_reqs" | bc)"
|
|
||||||
printf "❌ Missing: %3d (%.0f%%)\n" "$missing" "$(echo "scale=0; $missing * 100 / $total_reqs" | bc)"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Exit code based on missing critical requirements
|
|
||||||
if [ "$missing" -gt 0 ]; then
|
|
||||||
echo "⚠️ Warning: $missing requirements have no implementation"
|
|
||||||
exit 1
|
|
||||||
else
|
|
||||||
echo "✨ All requirements have implementations!"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# Test Coverage Report
|
|
||||||
# Links test requirements to implementations
|
|
||||||
#
|
|
||||||
|
|
||||||
echo "Test Coverage Report"
|
|
||||||
echo "===================="
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
test_reqs=$(grep -rh "@req-test:" src-tauri/ 2>/dev/null | \
|
|
||||||
sed 's/.*@req-test: \([A-Z][A-Z]-[0-9]*\).*/\1/' | \
|
|
||||||
sort -u)
|
|
||||||
|
|
||||||
total_tests=0
|
|
||||||
covered=0
|
|
||||||
uncovered=0
|
|
||||||
|
|
||||||
for req in $test_reqs; do
|
|
||||||
test_count=$(grep -r "@req-test: $req" src-tauri/ 2>/dev/null | wc -l)
|
|
||||||
impl_count=$(grep -r "@req: $req" src-tauri/ src/ 2>/dev/null | wc -l)
|
|
||||||
|
|
||||||
((total_tests++))
|
|
||||||
|
|
||||||
if [ "$test_count" -gt 0 ] && [ "$impl_count" -gt 0 ]; then
|
|
||||||
echo "✅ $req: $test_count test(s), $impl_count implementation(s)"
|
|
||||||
((covered++))
|
|
||||||
elif [ "$impl_count" -eq 0 ]; then
|
|
||||||
echo "⚠️ $req: $test_count test(s) but no implementation"
|
|
||||||
((uncovered++))
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Summary:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
printf "Total Test Requirements: %3d\n" "$total_tests"
|
|
||||||
printf "✅ With Implementation: %3d (%.0f%%)\n" "$covered" "$(echo "scale=0; $covered * 100 / $total_tests" | bc)"
|
|
||||||
printf "⚠️ No Implementation: %3d (%.0f%%)\n" "$uncovered" "$(echo "scale=0; $uncovered * 100 / $total_tests" | bc)"
|
|
||||||
echo ""
|
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
/**
|
||||||
|
* Tests for the traceability coverage computation.
|
||||||
|
*
|
||||||
|
* These run over fixture strings rather than the live docs/requirements.md, so
|
||||||
|
* their meaning does not drift as requirements are added.
|
||||||
|
*
|
||||||
|
* Background: the CI gate divided traced-requirement counts by hardcoded
|
||||||
|
* denominators (UR/39, IR/24, DR/48, JA/3, total 114) that had fallen out of
|
||||||
|
* date, reporting 158% coverage and making the 50% threshold unreachable. These
|
||||||
|
* tests pin the parsing and arithmetic that replace those literals.
|
||||||
|
*
|
||||||
|
* @req-test: UT-089 - Requirement definitions parsed from requirements.md
|
||||||
|
* @req-test: UT-090 - Coverage is the intersection of traced and defined IDs
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { countDefinedRequirements, computeCoverage } from "./extract-traces";
|
||||||
|
|
||||||
|
describe("countDefinedRequirements", () => {
|
||||||
|
it("counts a well-formed table row as a defined requirement", () => {
|
||||||
|
const md = `
|
||||||
|
| ID | Requirement | Priority | Status |
|
||||||
|
|----|-------------|----------|--------|
|
||||||
|
| UR-001 | Run the app on multiple platforms | High | In Progress |
|
||||||
|
| UR-002 | Access media when online or offline | High | Done |
|
||||||
|
`;
|
||||||
|
const defined = countDefinedRequirements(md);
|
||||||
|
expect(defined.UR).toBe(2);
|
||||||
|
expect(defined.DR).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not count IDs that appear only in the Traces To column", () => {
|
||||||
|
// The bug this rule avoids: a naive grep for /DR-\d{3}/ over the whole file
|
||||||
|
// counts DR-001 here as "defined", inflating the denominator with IDs that
|
||||||
|
// are merely referenced.
|
||||||
|
const md = `
|
||||||
|
| DR-001 | Player state machine | Player | UR-005 | Done |
|
||||||
|
| DR-002 | MediaItem struct | Player | UR-003, UR-004 | Done |
|
||||||
|
`;
|
||||||
|
const defined = countDefinedRequirements(md);
|
||||||
|
expect(defined.DR).toBe(2);
|
||||||
|
// UR-005/UR-003/UR-004 are referenced, never defined here.
|
||||||
|
expect(defined.UR).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not count IDs mentioned in prose", () => {
|
||||||
|
const md = `
|
||||||
|
Some prose explaining that UR-005 relates to DR-001 and JA-002.
|
||||||
|
|
||||||
|
| UR-005 | Control media playback | High | Done |
|
||||||
|
`;
|
||||||
|
const defined = countDefinedRequirements(md);
|
||||||
|
expect(defined.UR).toBe(1);
|
||||||
|
expect(defined.DR).toBe(0);
|
||||||
|
expect(defined.JA).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deduplicates an ID listed in both the spec table and the traceability matrix", () => {
|
||||||
|
// requirements.md lists every UR twice: once in §1 (definition) and again in
|
||||||
|
// §3 (traceability matrix), both as a leading table cell. Counting rows
|
||||||
|
// instead of unique IDs double-counts the UR denominator (121 vs 61).
|
||||||
|
const md = `
|
||||||
|
| UR-005 | Control media playback | High | Done |
|
||||||
|
| UR-006 | Browse the library | High | Done |
|
||||||
|
|
||||||
|
### Traceability Matrix
|
||||||
|
|
||||||
|
| UR-005 | - | DR-001, DR-005, DR-009 |
|
||||||
|
| UR-006 | - | DR-012 |
|
||||||
|
`;
|
||||||
|
const defined = countDefinedRequirements(md);
|
||||||
|
expect(defined.UR).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("collects the defined ID set, not just counts", () => {
|
||||||
|
const md = `
|
||||||
|
| UR-001 | A | High | Done |
|
||||||
|
| DR-050 | B | Player | UR-001 | Done |
|
||||||
|
`;
|
||||||
|
const defined = countDefinedRequirements(md);
|
||||||
|
expect(defined.ids.has("UR-001")).toBe(true);
|
||||||
|
expect(defined.ids.has("DR-050")).toBe(true);
|
||||||
|
expect(defined.ids.has("UR-999")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("computeCoverage", () => {
|
||||||
|
const defined = {
|
||||||
|
UR: 2,
|
||||||
|
IR: 0,
|
||||||
|
DR: 2,
|
||||||
|
JA: 0,
|
||||||
|
total: 4,
|
||||||
|
ids: new Set(["UR-001", "UR-002", "DR-001", "DR-002"]),
|
||||||
|
};
|
||||||
|
|
||||||
|
it("computes coverage as traced ∩ defined over defined", () => {
|
||||||
|
const traced = ["UR-001", "DR-001"];
|
||||||
|
const cov = computeCoverage(traced, defined);
|
||||||
|
expect(cov.covered).toBe(2);
|
||||||
|
expect(cov.total).toBe(4);
|
||||||
|
expect(cov.percent).toBe(50);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not let a traced-but-undefined ID inflate the numerator", () => {
|
||||||
|
// This is how a ratio exceeds 100%: a TRACES comment naming a typo'd or
|
||||||
|
// deleted requirement counted as covered.
|
||||||
|
const traced = ["UR-001", "DR-001", "DR-097"];
|
||||||
|
const cov = computeCoverage(traced, defined);
|
||||||
|
expect(cov.covered).toBe(2);
|
||||||
|
expect(cov.percent).toBe(50);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports traced-but-undefined IDs as orphaned so they get fixed", () => {
|
||||||
|
const traced = ["UR-001", "DR-097", "JA-404"];
|
||||||
|
const cov = computeCoverage(traced, defined);
|
||||||
|
expect(cov.orphaned).toEqual(["DR-097", "JA-404"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has no orphans when every traced ID is defined", () => {
|
||||||
|
const cov = computeCoverage(["UR-001", "UR-002"], defined);
|
||||||
|
expect(cov.orphaned).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores UT/IT test IDs entirely — they are a separate taxonomy", () => {
|
||||||
|
// UT/IT are defined in §4 of requirements.md, not among the four
|
||||||
|
// requirement types. Treating them as orphans buries real typos in ~60
|
||||||
|
// lines of noise, and counting them would corrupt the ratio.
|
||||||
|
const cov = computeCoverage(["UR-001", "UT-088", "IT-017"], defined);
|
||||||
|
expect(cov.orphaned).toEqual([]);
|
||||||
|
expect(cov.covered).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports 0% rather than dividing by zero for an empty trace set", () => {
|
||||||
|
const cov = computeCoverage([], defined);
|
||||||
|
expect(cov.covered).toBe(0);
|
||||||
|
expect(cov.percent).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports 0% rather than NaN when nothing is defined", () => {
|
||||||
|
const empty = { UR: 0, IR: 0, DR: 0, JA: 0, total: 0, ids: new Set<string>() };
|
||||||
|
const cov = computeCoverage([], empty);
|
||||||
|
expect(cov.percent).toBe(0);
|
||||||
|
expect(Number.isNaN(cov.percent)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports exactly 100% when all defined requirements are traced, never above", () => {
|
||||||
|
const traced = ["UR-001", "UR-002", "DR-001", "DR-002"];
|
||||||
|
const cov = computeCoverage(traced, defined);
|
||||||
|
expect(cov.percent).toBe(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores duplicate traced IDs", () => {
|
||||||
|
const traced = ["UR-001", "UR-001", "UR-001"];
|
||||||
|
const cov = computeCoverage(traced, defined);
|
||||||
|
expect(cov.covered).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("live requirements.md", () => {
|
||||||
|
it("parses the real file to the counts the CI gate must use", () => {
|
||||||
|
// Guards the specific regression: CI hardcoded UR/39, IR/24, DR/48, JA/3
|
||||||
|
// (total 114) while the real file had grown to 211. Update these numbers
|
||||||
|
// deliberately when requirements are added — that edit is the signal the
|
||||||
|
// denominator is live rather than frozen.
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
// import.meta.dir is Bun-only; derive from import.meta.url under vitest.
|
||||||
|
const here = path.dirname(new URL(import.meta.url).pathname);
|
||||||
|
const md = fs.readFileSync(
|
||||||
|
path.resolve(here, "../docs/requirements.md"),
|
||||||
|
"utf-8"
|
||||||
|
);
|
||||||
|
const defined = countDefinedRequirements(md);
|
||||||
|
|
||||||
|
expect(defined.UR).toBe(61);
|
||||||
|
expect(defined.IR).toBe(29);
|
||||||
|
expect(defined.DR).toBe(91);
|
||||||
|
expect(defined.JA).toBe(32);
|
||||||
|
expect(defined.total).toBe(213);
|
||||||
|
});
|
||||||
|
});
|
||||||
+181
-4
@@ -34,11 +34,20 @@ interface TracesData {
|
|||||||
DR: string[];
|
DR: string[];
|
||||||
JA: string[];
|
JA: string[];
|
||||||
};
|
};
|
||||||
|
/** Requirements *defined* in requirements.md — the coverage denominators. */
|
||||||
|
defined?: { UR: number; IR: number; DR: number; JA: number; total: number };
|
||||||
|
coverage?: CoverageResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Repo root, derived from this script's location (scripts/ -> repo root).
|
// Repo root, derived from this script's location (scripts/ -> repo root).
|
||||||
// Must NOT be hardcoded to a developer's machine, or CI checkouts see no files.
|
// Must NOT be hardcoded to a developer's machine, or CI checkouts see no files.
|
||||||
const BASE_DIR = path.resolve(import.meta.dir, "..");
|
//
|
||||||
|
// `import.meta.dir` is a Bun extension and is undefined when this module is
|
||||||
|
// imported by vitest (which runs it as an ordinary ESM module), so fall back to
|
||||||
|
// import.meta.url — this file must stay importable for extract-traces.test.ts.
|
||||||
|
const SCRIPT_DIR =
|
||||||
|
import.meta.dir ?? path.dirname(new URL(import.meta.url).pathname);
|
||||||
|
const BASE_DIR = path.resolve(SCRIPT_DIR, "..");
|
||||||
|
|
||||||
const TRACES_PATTERN = /TRACES:\s*([^\n]+)/gi;
|
const TRACES_PATTERN = /TRACES:\s*([^\n]+)/gi;
|
||||||
const REQ_ID_PATTERN = /([A-Z]{2})-(\d{3})/g;
|
const REQ_ID_PATTERN = /([A-Z]{2})-(\d{3})/g;
|
||||||
@@ -50,7 +59,10 @@ function extractRequirementIds(tracesString: string): string[] {
|
|||||||
|
|
||||||
function getAllSourceFiles(): string[] {
|
function getAllSourceFiles(): string[] {
|
||||||
const baseDir = BASE_DIR;
|
const baseDir = BASE_DIR;
|
||||||
const patterns = ["src", "src-tauri/src"];
|
// `scripts` is scanned too: build tooling implements requirements (e.g.
|
||||||
|
// DR-093, the coverage engine itself) and would otherwise be invisible to the
|
||||||
|
// very matrix it generates.
|
||||||
|
const patterns = ["src", "src-tauri/src", "scripts"];
|
||||||
const files: string[] = [];
|
const files: string[] = [];
|
||||||
|
|
||||||
function walkDir(dir: string) {
|
function walkDir(dir: string) {
|
||||||
@@ -192,6 +204,109 @@ function extractTraces(): TracesData {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Coverage: how many *defined* requirements are actually traced.
|
||||||
|
//
|
||||||
|
// The denominators MUST be derived from requirements.md, never hardcoded. The
|
||||||
|
// CI gate previously divided by frozen literals (UR/39, IR/24, DR/48, JA/3,
|
||||||
|
// total 114) while the real file had grown to 211 requirements, so it reported
|
||||||
|
// 158% coverage and the 50% threshold became unreachable — the gate could not
|
||||||
|
// fail. See docs/specs/traceability-gate-repair.md.
|
||||||
|
//
|
||||||
|
// TRACES: | DR-093
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export interface DefinedRequirements {
|
||||||
|
UR: number;
|
||||||
|
IR: number;
|
||||||
|
DR: number;
|
||||||
|
JA: number;
|
||||||
|
total: number;
|
||||||
|
ids: Set<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CoverageResult {
|
||||||
|
covered: number;
|
||||||
|
total: number;
|
||||||
|
percent: number;
|
||||||
|
/** Traced in code but not defined in requirements.md (typo, or deleted req). */
|
||||||
|
orphaned: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A requirement is *defined* only where its ID is the leading cell of a markdown
|
||||||
|
* table row: `| DR-001 | … |`.
|
||||||
|
*
|
||||||
|
* This deliberately ignores IDs in the "Traces To" column and in prose — a
|
||||||
|
* naive scan for /DR-\d{3}/ counts those as definitions and inflates the
|
||||||
|
* denominator. IDs are deduplicated because requirements.md lists each UR twice
|
||||||
|
* (once in §1 as a definition, again in §3's traceability matrix), which would
|
||||||
|
* otherwise double the UR count from 61 to 121.
|
||||||
|
*
|
||||||
|
* TRACES: | DR-093
|
||||||
|
*/
|
||||||
|
export function countDefinedRequirements(markdown: string): DefinedRequirements {
|
||||||
|
const ids = new Set<string>();
|
||||||
|
const ROW_ID = /^\|\s*(UR|IR|DR|JA)-(\d{3})\s*\|/;
|
||||||
|
|
||||||
|
for (const line of markdown.split("\n")) {
|
||||||
|
const match = line.match(ROW_ID);
|
||||||
|
if (match) ids.add(`${match[1]}-${match[2]}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const countOf = (type: string) =>
|
||||||
|
[...ids].filter((id) => id.startsWith(`${type}-`)).length;
|
||||||
|
|
||||||
|
return {
|
||||||
|
UR: countOf("UR"),
|
||||||
|
IR: countOf("IR"),
|
||||||
|
DR: countOf("DR"),
|
||||||
|
JA: countOf("JA"),
|
||||||
|
total: ids.size,
|
||||||
|
ids,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Coverage is the *intersection* of traced and defined IDs over defined IDs.
|
||||||
|
*
|
||||||
|
* Using the raw traced count as the numerator is what lets a ratio exceed 100%:
|
||||||
|
* a TRACES comment naming a requirement that no longer exists would count as
|
||||||
|
* covered. Those IDs are reported as `orphaned` so they get fixed rather than
|
||||||
|
* silently counted or silently dropped.
|
||||||
|
*
|
||||||
|
* TRACES: | DR-093
|
||||||
|
*/
|
||||||
|
export function computeCoverage(
|
||||||
|
tracedIds: string[],
|
||||||
|
defined: DefinedRequirements
|
||||||
|
): CoverageResult {
|
||||||
|
// Only the four *requirement* types participate in coverage. UT/IT are test
|
||||||
|
// identifiers defined in §4 of requirements.md — a different taxonomy, and
|
||||||
|
// flagging them as orphans would bury real typos in ~60 lines of noise.
|
||||||
|
const isRequirement = (id: string) => /^(UR|IR|DR|JA)-\d{3}$/.test(id);
|
||||||
|
|
||||||
|
const traced = new Set(tracedIds.filter(isRequirement));
|
||||||
|
const covered = [...traced].filter((id) => defined.ids.has(id));
|
||||||
|
const orphaned = [...traced].filter((id) => !defined.ids.has(id)).sort();
|
||||||
|
|
||||||
|
return {
|
||||||
|
covered: covered.length,
|
||||||
|
total: defined.total,
|
||||||
|
percent:
|
||||||
|
defined.total === 0
|
||||||
|
? 0
|
||||||
|
: Math.round((covered.length / defined.total) * 100),
|
||||||
|
orphaned,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read requirements.md from the repo and count what it defines. */
|
||||||
|
export function readDefinedRequirements(): DefinedRequirements {
|
||||||
|
const reqPath = path.join(BASE_DIR, "docs", "requirements.md");
|
||||||
|
return countDefinedRequirements(fs.readFileSync(reqPath, "utf-8"));
|
||||||
|
}
|
||||||
|
|
||||||
function generateMarkdown(data: TracesData): string {
|
function generateMarkdown(data: TracesData): string {
|
||||||
let md = `# Code Traceability Matrix
|
let md = `# Code Traceability Matrix
|
||||||
|
|
||||||
@@ -265,8 +380,56 @@ function generateJson(data: TracesData): string {
|
|||||||
return JSON.stringify(data, null, 2);
|
return JSON.stringify(data, null, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Main
|
/**
|
||||||
const args = Bun.argv.slice(2);
|
* Human-readable coverage report; exits non-zero below the threshold so this is
|
||||||
|
* runnable as a local gate (`bun run traces:coverage`), not just in CI.
|
||||||
|
*
|
||||||
|
* TRACES: | DR-093
|
||||||
|
*/
|
||||||
|
function reportCoverage(data: TracesData, minThreshold: number): number {
|
||||||
|
const defined = data.defined!;
|
||||||
|
const cov = data.coverage!;
|
||||||
|
|
||||||
|
const definedIds = readDefinedRequirements().ids;
|
||||||
|
|
||||||
|
console.log("📋 Requirement coverage (traced / defined):");
|
||||||
|
for (const type of ["UR", "IR", "DR", "JA"] as const) {
|
||||||
|
const traced = data.byType[type].filter((id) => definedIds.has(id)).length;
|
||||||
|
console.log(` ${type}: ${traced} / ${defined[type]}`);
|
||||||
|
}
|
||||||
|
console.log("");
|
||||||
|
console.log(`📈 Overall: ${cov.covered} / ${cov.total} (${cov.percent}%)`);
|
||||||
|
|
||||||
|
if (cov.orphaned.length > 0) {
|
||||||
|
console.log("");
|
||||||
|
console.log(
|
||||||
|
`⚠️ Traced but not defined in requirements.md: ${cov.orphaned.join(", ")}`
|
||||||
|
);
|
||||||
|
console.log(" Fix the TRACES comment or add the requirement.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A ratio above 100% means the computation is broken (the condition that hid
|
||||||
|
// the stale-denominator bug for so long). Fail loudly rather than report it.
|
||||||
|
if (cov.percent > 100) {
|
||||||
|
console.log("");
|
||||||
|
console.log(`❌ Coverage > 100% — the gate is miscomputing.`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cov.percent < minThreshold) {
|
||||||
|
console.log("");
|
||||||
|
console.log(`❌ Coverage (${cov.percent}%) is below minimum (${minThreshold}%)`);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("");
|
||||||
|
console.log(`✅ Coverage is acceptable (${cov.percent}% >= ${minThreshold}%)`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main — guarded so this module stays importable from extract-traces.test.ts.
|
||||||
|
if (import.meta.main) {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
const format = args.includes("--format")
|
const format = args.includes("--format")
|
||||||
? args[args.indexOf("--format") + 1]
|
? args[args.indexOf("--format") + 1]
|
||||||
: "markdown";
|
: "markdown";
|
||||||
@@ -274,8 +437,21 @@ const format = args.includes("--format")
|
|||||||
console.error("🔍 Extracting TRACES from codebase...");
|
console.error("🔍 Extracting TRACES from codebase...");
|
||||||
const data = extractTraces();
|
const data = extractTraces();
|
||||||
|
|
||||||
|
const defined = readDefinedRequirements();
|
||||||
|
const allTraced = Object.keys(data.requirements);
|
||||||
|
data.defined = {
|
||||||
|
UR: defined.UR,
|
||||||
|
IR: defined.IR,
|
||||||
|
DR: defined.DR,
|
||||||
|
JA: defined.JA,
|
||||||
|
total: defined.total,
|
||||||
|
};
|
||||||
|
data.coverage = computeCoverage(allTraced, defined);
|
||||||
|
|
||||||
if (format === "json") {
|
if (format === "json") {
|
||||||
console.log(generateJson(data));
|
console.log(generateJson(data));
|
||||||
|
} else if (format === "coverage") {
|
||||||
|
process.exit(reportCoverage(data, 50));
|
||||||
} else {
|
} else {
|
||||||
console.log(generateMarkdown(data));
|
console.log(generateMarkdown(data));
|
||||||
}
|
}
|
||||||
@@ -283,3 +459,4 @@ if (format === "json") {
|
|||||||
console.error(
|
console.error(
|
||||||
`\n✅ Complete! Found ${data.totalTraces} TRACES across ${data.totalFiles} files`
|
`\n✅ Complete! Found ${data.totalTraces} TRACES across ${data.totalFiles} files`
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# Find all files implementing a specific requirement
|
|
||||||
#
|
|
||||||
# Usage: ./find-req-implementations.sh UR-004
|
|
||||||
#
|
|
||||||
|
|
||||||
if [ $# -eq 0 ]; then
|
|
||||||
echo "Usage: $0 <REQUIREMENT_ID>"
|
|
||||||
echo "Example: $0 UR-004"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
REQ_ID=$1
|
|
||||||
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
echo " Implementations of $REQ_ID"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Full implementations
|
|
||||||
echo "Full Implementations:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
grep -rn "@req: $REQ_ID" src-tauri/ src/ 2>/dev/null | \
|
|
||||||
grep -v "@req-partial" | \
|
|
||||||
grep -v "@req-planned" | \
|
|
||||||
sed 's/src-tauri\/src\///' | \
|
|
||||||
sed 's/src\///' || echo " (none)"
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Partial implementations
|
|
||||||
echo "Partial Implementations:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
grep -rn "@req-partial: $REQ_ID" src-tauri/ src/ 2>/dev/null | \
|
|
||||||
sed 's/src-tauri\/src\///' | \
|
|
||||||
sed 's/src\///' || echo " (none)"
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Planned
|
|
||||||
echo "Planned Implementations:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
grep -rn "@req-planned: $REQ_ID" src-tauri/ src/ 2>/dev/null | \
|
|
||||||
sed 's/src-tauri\/src\///' | \
|
|
||||||
sed 's/src\///' || echo " (none)"
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
|
|
||||||
# Tests
|
|
||||||
echo "Test Cases:"
|
|
||||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
|
||||||
grep -rn "@req-test: $REQ_ID" src-tauri/ 2>/dev/null | \
|
|
||||||
sed 's/src-tauri\/src\///' || echo " (none)"
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
+8
-1
@@ -7,7 +7,7 @@ echo "🧪 Running all tests..."
|
|||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
echo "📦 Running frontend tests..."
|
echo "📦 Running frontend tests..."
|
||||||
bun run test
|
bun run test --run
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "🦀 Running Rust tests..."
|
echo "🦀 Running Rust tests..."
|
||||||
@@ -15,5 +15,12 @@ cd src-tauri
|
|||||||
cargo test
|
cargo test
|
||||||
cd ..
|
cd ..
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "🚧 Checking architectural gates..."
|
||||||
|
# Boundary tripwire (DR-094): no Jellyfin taxonomy in the presentation layer.
|
||||||
|
bun run check:boundary
|
||||||
|
# Traceability coverage (DR-093): fails below 50%, or above 100% (miscount).
|
||||||
|
bun run traces:coverage
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "✅ All tests passed!"
|
echo "✅ All tests passed!"
|
||||||
|
|||||||
Generated
+1
-1
@@ -1994,7 +1994,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jellytau"
|
name = "jellytau"
|
||||||
version = "0.2.0"
|
version = "0.2.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "jellytau"
|
name = "jellytau"
|
||||||
version = "0.2.0"
|
version = "0.2.1"
|
||||||
description = "A Tauri App"
|
description = "A Tauri App"
|
||||||
authors = ["you"]
|
authors = ["you"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|||||||
@@ -395,7 +395,12 @@ pub struct SearchUpdateEvent {
|
|||||||
pub result: SearchResult,
|
pub result: SearchResult,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Search for items
|
/// Search for items.
|
||||||
|
///
|
||||||
|
/// Resolves `SearchOptions::scope` into concrete Jellyfin item types before
|
||||||
|
/// dispatching, so scope taxonomy stays in Rust.
|
||||||
|
///
|
||||||
|
/// TRACES: UR-049, UR-050 | DR-063
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn repository_search(
|
pub async fn repository_search(
|
||||||
@@ -408,6 +413,16 @@ pub async fn repository_search(
|
|||||||
) -> Result<SearchResult, String> {
|
) -> Result<SearchResult, String> {
|
||||||
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
||||||
|
|
||||||
|
// Expand the opaque scope into item types HERE — once, before the cache and
|
||||||
|
// server paths diverge — so both phases filter identically. Doing it later
|
||||||
|
// (or in only one path) makes offline results disagree with online ones.
|
||||||
|
// The frontend sends `scope` and never names a Jellyfin item type for
|
||||||
|
// search; see docs/specs/scoped-search-boundary.md.
|
||||||
|
let options = options.map(|mut o| {
|
||||||
|
o.resolve_scope();
|
||||||
|
o
|
||||||
|
});
|
||||||
|
|
||||||
// Phase 1: instant local results from the cache (downloaded content) so the
|
// Phase 1: instant local results from the cache (downloaded content) so the
|
||||||
// UI can render immediately while the server is still being queried.
|
// UI can render immediately while the server is still being queried.
|
||||||
let mut cache_result = repo
|
let mut cache_result = repo
|
||||||
|
|||||||
@@ -294,6 +294,53 @@ pub struct GetItemsOptions {
|
|||||||
pub genres: Option<Vec<String>>,
|
pub genres: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An opaque search scope the frontend selects; Rust owns what it *means*.
|
||||||
|
///
|
||||||
|
/// The expansion table below is Jellyfin domain vocabulary: it changes when
|
||||||
|
/// Jellyfin adds or renames an item type, never when the UI is redesigned. It
|
||||||
|
/// previously lived in the frontend (`searchScope.ts`), which is the boundary
|
||||||
|
/// leak documented in docs/specs/scoped-search-boundary.md. The frontend now
|
||||||
|
/// sends the enum and never names an item type in connection with search.
|
||||||
|
///
|
||||||
|
/// TRACES: UR-049 | DR-063
|
||||||
|
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub enum SearchScope {
|
||||||
|
All,
|
||||||
|
Music,
|
||||||
|
Movies,
|
||||||
|
Tv,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SearchScope {
|
||||||
|
/// The Jellyfin item types this scope requests, or `None` for `All`.
|
||||||
|
///
|
||||||
|
/// `All` returns `None` rather than the union of every listed type on
|
||||||
|
/// purpose: an explicit `includeItemTypes` list filters out anything not
|
||||||
|
/// named in it, so a union would silently drop People, folders and any type
|
||||||
|
/// nobody enumerated. Callers must omit the filter entirely on `None`.
|
||||||
|
///
|
||||||
|
/// TRACES: UR-049 | DR-063
|
||||||
|
pub fn item_types(self) -> Option<Vec<String>> {
|
||||||
|
match self {
|
||||||
|
SearchScope::All => None,
|
||||||
|
SearchScope::Music => Some(
|
||||||
|
["MusicAlbum", "MusicArtist", "Audio", "Playlist"]
|
||||||
|
.into_iter()
|
||||||
|
.map(String::from)
|
||||||
|
.collect(),
|
||||||
|
),
|
||||||
|
SearchScope::Movies => Some(vec!["Movie".to_string()]),
|
||||||
|
SearchScope::Tv => Some(
|
||||||
|
["Series", "Episode"]
|
||||||
|
.into_iter()
|
||||||
|
.map(String::from)
|
||||||
|
.collect(),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Options for search queries
|
/// Options for search queries
|
||||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
|
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
@@ -304,6 +351,28 @@ pub struct SearchOptions {
|
|||||||
pub include_item_types: Option<Vec<String>>,
|
pub include_item_types: Option<Vec<String>>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub search_term: Option<String>,
|
pub search_term: Option<String>,
|
||||||
|
/// Opaque scope selected by the UI. When set it **wins** over
|
||||||
|
/// `include_item_types`, which remains for the non-search `get_items`
|
||||||
|
/// callers that legitimately request a single concrete type.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub scope: Option<SearchScope>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SearchOptions {
|
||||||
|
/// Expand `scope` into `include_item_types` in place.
|
||||||
|
///
|
||||||
|
/// Call this once, in the search command, *before* dispatching to the
|
||||||
|
/// cache and server paths — both already honour `include_item_types`, and
|
||||||
|
/// resolving in one place keeps online and offline results identical.
|
||||||
|
///
|
||||||
|
/// TRACES: UR-049 | DR-063
|
||||||
|
pub fn resolve_scope(&mut self) {
|
||||||
|
if let Some(scope) = self.scope {
|
||||||
|
// `All` yields None, which clears the filter — the correct
|
||||||
|
// behaviour, not an omission.
|
||||||
|
self.include_item_types = scope.item_types();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Playback information
|
/// Playback information
|
||||||
@@ -455,6 +524,131 @@ impl MeaningfulContent for PlaylistCreatedResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod search_scope_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Music expands to the four Jellyfin types that make up the category.
|
||||||
|
///
|
||||||
|
/// This table is the domain vocabulary that used to live in the frontend
|
||||||
|
/// (`searchScope.ts`'s `SCOPE_ITEM_TYPES`) — the boundary leak that
|
||||||
|
/// docs/specs/scoped-search-boundary.md was written about.
|
||||||
|
///
|
||||||
|
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||||
|
#[test]
|
||||||
|
fn music_scope_expands_to_music_item_types() {
|
||||||
|
assert_eq!(
|
||||||
|
SearchScope::Music.item_types(),
|
||||||
|
Some(vec![
|
||||||
|
"MusicAlbum".to_string(),
|
||||||
|
"MusicArtist".to_string(),
|
||||||
|
"Audio".to_string(),
|
||||||
|
"Playlist".to_string(),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||||
|
#[test]
|
||||||
|
fn movies_scope_expands_to_movie_only() {
|
||||||
|
assert_eq!(
|
||||||
|
SearchScope::Movies.item_types(),
|
||||||
|
Some(vec!["Movie".to_string()])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||||
|
#[test]
|
||||||
|
fn tv_scope_expands_to_series_and_episode() {
|
||||||
|
assert_eq!(
|
||||||
|
SearchScope::Tv.item_types(),
|
||||||
|
Some(vec!["Series".to_string(), "Episode".to_string()])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `All` must send NO filter — not the union of the other scopes.
|
||||||
|
///
|
||||||
|
/// Sending a union would silently drop every type nobody enumerated
|
||||||
|
/// (Person, folders, …), which an explicit `includeItemTypes` list filters
|
||||||
|
/// out. This is why `item_types()` returns Option rather than Vec.
|
||||||
|
///
|
||||||
|
/// @req-test: UT-090 - All scope sends no item-type filter
|
||||||
|
#[test]
|
||||||
|
fn all_scope_sends_no_filter() {
|
||||||
|
assert_eq!(SearchScope::All.item_types(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scope wins over an explicitly supplied include_item_types.
|
||||||
|
///
|
||||||
|
/// @req-test: UT-091 - Scope takes precedence over include_item_types
|
||||||
|
#[test]
|
||||||
|
fn resolve_scope_overrides_include_item_types() {
|
||||||
|
let mut options = SearchOptions {
|
||||||
|
include_item_types: Some(vec!["Movie".to_string()]),
|
||||||
|
scope: Some(SearchScope::Music),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
options.resolve_scope();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
options.include_item_types,
|
||||||
|
Some(vec![
|
||||||
|
"MusicAlbum".to_string(),
|
||||||
|
"MusicArtist".to_string(),
|
||||||
|
"Audio".to_string(),
|
||||||
|
"Playlist".to_string(),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `All` clears any include_item_types so no filter reaches the query.
|
||||||
|
///
|
||||||
|
/// @req-test: UT-090 - All scope sends no item-type filter
|
||||||
|
#[test]
|
||||||
|
fn resolve_all_scope_clears_include_item_types() {
|
||||||
|
let mut options = SearchOptions {
|
||||||
|
include_item_types: Some(vec!["Movie".to_string()]),
|
||||||
|
scope: Some(SearchScope::All),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
options.resolve_scope();
|
||||||
|
|
||||||
|
assert_eq!(options.include_item_types, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With no scope set, include_item_types passes through untouched — the
|
||||||
|
/// non-search `getItems` callers rely on this.
|
||||||
|
///
|
||||||
|
/// @req-test: UT-091 - Scope takes precedence over include_item_types
|
||||||
|
#[test]
|
||||||
|
fn resolve_without_scope_preserves_include_item_types() {
|
||||||
|
let mut options = SearchOptions {
|
||||||
|
include_item_types: Some(vec!["MusicAlbum".to_string()]),
|
||||||
|
scope: None,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
options.resolve_scope();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
options.include_item_types,
|
||||||
|
Some(vec!["MusicAlbum".to_string()])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frontend sends the enum as camelCase over IPC.
|
||||||
|
///
|
||||||
|
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||||
|
#[test]
|
||||||
|
fn scope_deserializes_from_camel_case() {
|
||||||
|
let options: SearchOptions =
|
||||||
|
serde_json::from_str(r#"{"scope": "music", "limit": 10}"#).unwrap();
|
||||||
|
assert!(matches!(options.scope, Some(SearchScope::Music)));
|
||||||
|
|
||||||
|
let all: SearchOptions = serde_json::from_str(r#"{"scope": "all"}"#).unwrap();
|
||||||
|
assert!(matches!(all.scope, Some(SearchScope::All)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "jellytau",
|
"productName": "jellytau",
|
||||||
"version": "0.2.0",
|
"version": "0.2.1",
|
||||||
"identifier": "com.dtourolle.jellytau",
|
"identifier": "com.dtourolle.jellytau",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "bun run dev",
|
"beforeDevCommand": "bun run dev",
|
||||||
|
|||||||
+25
-2
@@ -1290,7 +1290,12 @@ async repositoryGetGenres(handle: string, parentId: string | null) : Promise<Gen
|
|||||||
return await TAURI_INVOKE("repository_get_genres", { handle, parentId });
|
return await TAURI_INVOKE("repository_get_genres", { handle, parentId });
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* Search for items
|
* Search for items.
|
||||||
|
*
|
||||||
|
* Resolves `SearchOptions::scope` into concrete Jellyfin item types before
|
||||||
|
* dispatching, so scope taxonomy stays in Rust.
|
||||||
|
*
|
||||||
|
* TRACES: UR-049, UR-050 | DR-063
|
||||||
*/
|
*/
|
||||||
async repositorySearch(handle: string, query: string, options: SearchOptions | null, requestId: number) : Promise<SearchResult> {
|
async repositorySearch(handle: string, query: string, options: SearchOptions | null, requestId: number) : Promise<SearchResult> {
|
||||||
return await TAURI_INVOKE("repository_search", { handle, query, options, requestId });
|
return await TAURI_INVOKE("repository_search", { handle, query, options, requestId });
|
||||||
@@ -2517,11 +2522,29 @@ failed: number }
|
|||||||
/**
|
/**
|
||||||
* Options for search queries
|
* Options for search queries
|
||||||
*/
|
*/
|
||||||
export type SearchOptions = { limit?: number | null; includeItemTypes?: string[] | null; searchTerm?: string | null }
|
export type SearchOptions = { limit?: number | null; includeItemTypes?: string[] | null; searchTerm?: string | null;
|
||||||
|
/**
|
||||||
|
* Opaque scope selected by the UI. When set it **wins** over
|
||||||
|
* `include_item_types`, which remains for the non-search `get_items`
|
||||||
|
* callers that legitimately request a single concrete type.
|
||||||
|
*/
|
||||||
|
scope?: SearchScope | null }
|
||||||
/**
|
/**
|
||||||
* Search result with pagination
|
* Search result with pagination
|
||||||
*/
|
*/
|
||||||
export type SearchResult = { items: MediaItem[]; totalRecordCount: number }
|
export type SearchResult = { items: MediaItem[]; totalRecordCount: number }
|
||||||
|
/**
|
||||||
|
* An opaque search scope the frontend selects; Rust owns what it *means*.
|
||||||
|
*
|
||||||
|
* The expansion table below is Jellyfin domain vocabulary: it changes when
|
||||||
|
* Jellyfin adds or renames an item type, never when the UI is redesigned. It
|
||||||
|
* previously lived in the frontend (`searchScope.ts`), which is the boundary
|
||||||
|
* leak documented in docs/specs/scoped-search-boundary.md. The frontend now
|
||||||
|
* sends the enum and never names an item type in connection with search.
|
||||||
|
*
|
||||||
|
* TRACES: UR-049 | DR-063
|
||||||
|
*/
|
||||||
|
export type SearchScope = "all" | "music" | "movies" | "tv"
|
||||||
/**
|
/**
|
||||||
* Security status info
|
* Security status info
|
||||||
*/
|
*/
|
||||||
|
|||||||
+10
-10
@@ -5,7 +5,7 @@ import { writable, derived } from "svelte/store";
|
|||||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||||
import type { Library, MediaItem, SearchResult, Genre } from "$lib/api/types";
|
import type { Library, MediaItem, SearchResult, Genre } from "$lib/api/types";
|
||||||
import type { SearchOptions } from "$lib/api/bindings";
|
import type { SearchOptions } from "$lib/api/bindings";
|
||||||
import { scopeItemTypes, type SearchScope } from "$lib/utils/searchScope";
|
import type { SearchScope } from "$lib/utils/searchScope";
|
||||||
import { auth } from "./auth";
|
import { auth } from "./auth";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -227,12 +227,13 @@ function createLibraryStore() {
|
|||||||
/**
|
/**
|
||||||
* Search the library, optionally narrowed to a scope.
|
* Search the library, optionally narrowed to a scope.
|
||||||
*
|
*
|
||||||
* `scope` is additive and defaults to `all`, which sends no
|
* The scope is sent **opaque**; Rust expands it into Jellyfin item types
|
||||||
* `includeItemTypes` at all — see scopeItemTypes() for why that differs from
|
* (`SearchScope::item_types()`) before the cache and server paths diverge, so
|
||||||
* listing every type. Both the online and offline repository paths already
|
* online and offline results filter identically. `all` resolves to no filter
|
||||||
* honour the filter.
|
* at all — not the union of the other scopes, which would drop People and
|
||||||
|
* folders.
|
||||||
*
|
*
|
||||||
* TRACES: UR-049 | DR-065
|
* TRACES: UR-049 | DR-063, DR-065
|
||||||
*/
|
*/
|
||||||
async function search(query: string, scope: SearchScope = "all") {
|
async function search(query: string, scope: SearchScope = "all") {
|
||||||
// Bump the request id for every call (including clears) so any in-flight
|
// Bump the request id for every call (including clears) so any in-flight
|
||||||
@@ -259,10 +260,9 @@ function createLibraryStore() {
|
|||||||
// Phase 1: the command resolves with instant local-cache results. The
|
// Phase 1: the command resolves with instant local-cache results. The
|
||||||
// merged (cache + server) union arrives later via the `search-event`
|
// merged (cache + server) union arrives later via the `search-event`
|
||||||
// listener above, tagged with this same requestId.
|
// listener above, tagged with this same requestId.
|
||||||
const itemTypes = scopeItemTypes(scope);
|
// Send the opaque scope; Rust expands it to item types. The frontend
|
||||||
const options: SearchOptions = { limit: 10000 };
|
// never names a Jellyfin item type in connection with search.
|
||||||
// Omit the key entirely for the `all` scope rather than sending null.
|
const options: SearchOptions = { limit: 10000, scope };
|
||||||
if (itemTypes) options.includeItemTypes = itemTypes;
|
|
||||||
|
|
||||||
const result = await Promise.race([
|
const result = await Promise.race([
|
||||||
repo.search(query, options, requestId),
|
repo.search(query, options, requestId),
|
||||||
|
|||||||
@@ -32,35 +32,43 @@ describe("library.search scoping", () => {
|
|||||||
library.clearSearch();
|
library.clearSearch();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("omits includeItemTypes entirely for the default (all) scope", async () => {
|
// The frontend sends the OPAQUE scope and never names a Jellyfin item type.
|
||||||
|
// Expansion (music → MusicAlbum/MusicArtist/Audio/Playlist) is asserted in
|
||||||
|
// Rust — see `search_scope_tests` in src-tauri/src/repository/types.rs.
|
||||||
|
// Asserting item types here would mean the frontend knows the taxonomy again,
|
||||||
|
// which is the leak docs/specs/scoped-search-boundary.md exists to prevent.
|
||||||
|
|
||||||
|
it("sends the default (all) scope and never an item-type list", async () => {
|
||||||
await library.search("office");
|
await library.search("office");
|
||||||
|
|
||||||
const options = searchMock.mock.calls[0][1];
|
const options = searchMock.mock.calls[0][1];
|
||||||
|
expect(options.scope).toBe("all");
|
||||||
expect(options).not.toHaveProperty("includeItemTypes");
|
expect(options).not.toHaveProperty("includeItemTypes");
|
||||||
expect(options.limit).toBe(10000);
|
expect(options.limit).toBe(10000);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forwards music item types when scoped to music", async () => {
|
it("sends the opaque scope when scoped to music", async () => {
|
||||||
await library.search("office", "music");
|
await library.search("office", "music");
|
||||||
|
|
||||||
expect(searchMock.mock.calls[0][1].includeItemTypes).toEqual([
|
const options = searchMock.mock.calls[0][1];
|
||||||
"MusicAlbum",
|
expect(options.scope).toBe("music");
|
||||||
"MusicArtist",
|
expect(options).not.toHaveProperty("includeItemTypes");
|
||||||
"Audio",
|
|
||||||
"Playlist",
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forwards tv item types when scoped to tv", async () => {
|
it("sends the opaque scope when scoped to tv", async () => {
|
||||||
await library.search("office", "tv");
|
await library.search("office", "tv");
|
||||||
|
|
||||||
expect(searchMock.mock.calls[0][1].includeItemTypes).toEqual(["Series", "Episode"]);
|
const options = searchMock.mock.calls[0][1];
|
||||||
|
expect(options.scope).toBe("tv");
|
||||||
|
expect(options).not.toHaveProperty("includeItemTypes");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("forwards movie item types when scoped to movies", async () => {
|
it("sends the opaque scope when scoped to movies", async () => {
|
||||||
await library.search("office", "movies");
|
await library.search("office", "movies");
|
||||||
|
|
||||||
expect(searchMock.mock.calls[0][1].includeItemTypes).toEqual(["Movie"]);
|
const options = searchMock.mock.calls[0][1];
|
||||||
|
expect(options.scope).toBe("movies");
|
||||||
|
expect(options).not.toHaveProperty("includeItemTypes");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("stores results and the query on success", async () => {
|
it("stores results and the query on success", async () => {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
resolveSearchScope,
|
resolveSearchScope,
|
||||||
searchRouteUrl,
|
searchRouteUrl,
|
||||||
shouldNavigateToSearch,
|
shouldNavigateToSearch,
|
||||||
scopeItemTypes,
|
|
||||||
type SearchGroupId,
|
type SearchGroupId,
|
||||||
} from "./searchScope";
|
} from "./searchScope";
|
||||||
|
|
||||||
@@ -62,25 +61,12 @@ describe("resolveSearchScope", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("scopeItemTypes", () => {
|
// NOTE: the former `scopeItemTypes` suite moved to Rust — see
|
||||||
it("omits the key entirely for the all scope", () => {
|
// `search_scope_tests` in src-tauri/src/repository/types.rs. The scope →
|
||||||
// `all` must send no includeItemTypes — an explicit union would silently
|
// item-type expansion is domain vocabulary and is no longer reachable from the
|
||||||
// drop types nobody enumerated (Person, folders).
|
// frontend, so testing it here would mean re-introducing the leak to test it.
|
||||||
expect(scopeItemTypes("all")).toBeUndefined();
|
// The "fresh array" test is gone because `item_types()` returns an owned Vec,
|
||||||
});
|
// making the aliasing bug it guarded structurally impossible.
|
||||||
|
|
||||||
it("maps each narrow scope to its item types", () => {
|
|
||||||
expect(scopeItemTypes("music")).toEqual(["MusicAlbum", "MusicArtist", "Audio", "Playlist"]);
|
|
||||||
expect(scopeItemTypes("movies")).toEqual(["Movie"]);
|
|
||||||
expect(scopeItemTypes("tv")).toEqual(["Series", "Episode"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns a fresh array callers cannot mutate into the table", () => {
|
|
||||||
const first = scopeItemTypes("movies")!;
|
|
||||||
first.push("Series");
|
|
||||||
expect(scopeItemTypes("movies")).toEqual(["Movie"]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("normalizeGroupOrder", () => {
|
describe("normalizeGroupOrder", () => {
|
||||||
it("returns the default for missing or non-array input", () => {
|
it("returns the default for missing or non-array input", () => {
|
||||||
|
|||||||
@@ -8,7 +8,11 @@
|
|||||||
//
|
//
|
||||||
// TRACES: UR-049, UR-050 | DR-063, DR-066, DR-067
|
// TRACES: UR-049, UR-050 | DR-063, DR-066, DR-067
|
||||||
|
|
||||||
export type SearchScope = "all" | "music" | "movies" | "tv";
|
// Sourced from Rust via the generated bindings — the backend owns what a scope
|
||||||
|
// *means* (which Jellyfin item types it covers). Naming an opaque variant is
|
||||||
|
// presentation; knowing its expansion is domain vocabulary and stays in Rust.
|
||||||
|
export type { SearchScope } from "$lib/api/bindings";
|
||||||
|
import type { SearchScope } from "$lib/api/bindings";
|
||||||
|
|
||||||
export const SEARCH_SCOPES: readonly SearchScope[] = ["all", "music", "movies", "tv"];
|
export const SEARCH_SCOPES: readonly SearchScope[] = ["all", "music", "movies", "tv"];
|
||||||
|
|
||||||
@@ -19,29 +23,11 @@ export const SCOPE_LABELS: Record<SearchScope, string> = {
|
|||||||
tv: "TV",
|
tv: "TV",
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
// NOTE: the scope → Jellyfin item-type mapping deliberately does NOT live here.
|
||||||
* Jellyfin item types requested for each scope.
|
// It is domain vocabulary and lives in Rust (`SearchScope::item_types()` in
|
||||||
*
|
// repository/types.rs); the frontend sends the opaque scope and the backend
|
||||||
* `all` is deliberately absent: sending no `includeItemTypes` is *not* the same
|
// expands it. Re-introducing a `{ music: ["MusicAlbum", …] }` table in this file
|
||||||
* as sending the union of the lists below — types nobody enumerated here
|
// is the boundary leak documented in docs/specs/scoped-search-boundary.md.
|
||||||
* (Person, folders, …) would be filtered out by an explicit list.
|
|
||||||
*/
|
|
||||||
const SCOPE_ITEM_TYPES: Record<Exclude<SearchScope, "all">, string[]> = {
|
|
||||||
music: ["MusicAlbum", "MusicArtist", "Audio", "Playlist"],
|
|
||||||
movies: ["Movie"],
|
|
||||||
tv: ["Series", "Episode"],
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Item types to send with a scoped search, or `undefined` for the `all` scope
|
|
||||||
* so the caller omits the key entirely.
|
|
||||||
*
|
|
||||||
* TRACES: UR-049 | DR-063
|
|
||||||
*/
|
|
||||||
export function scopeItemTypes(scope: SearchScope): string[] | undefined {
|
|
||||||
if (scope === "all") return undefined;
|
|
||||||
return [...SCOPE_ITEM_TYPES[scope]];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve the scope a search started from a given route should default to.
|
* Resolve the scope a search started from a given route should default to.
|
||||||
|
|||||||
+3
-1
@@ -8,7 +8,9 @@ export default defineConfig({
|
|||||||
globals: true,
|
globals: true,
|
||||||
environment: "jsdom",
|
environment: "jsdom",
|
||||||
setupFiles: ["./src/test/setup-globals.ts", "./src/test/setup.ts"],
|
setupFiles: ["./src/test/setup-globals.ts", "./src/test/setup.ts"],
|
||||||
include: ["src/**/*.{test,spec}.{js,ts}"],
|
// `scripts/` is included so build tooling (the traceability coverage
|
||||||
|
// engine) is covered by the normal suite rather than only by CI.
|
||||||
|
include: ["src/**/*.{test,spec}.{js,ts}", "scripts/**/*.{test,spec}.{js,ts}"],
|
||||||
coverage: {
|
coverage: {
|
||||||
provider: "v8",
|
provider: "v8",
|
||||||
reporter: ["text", "json", "html"],
|
reporter: ["text", "json", "html"],
|
||||||
|
|||||||
Reference in New Issue
Block a user