Compare commits

..
147 Commits
Author SHA1 Message Date
John O'Keefe 2bec4e60bd test(pins): annotation lifecycles pin the restore GET, not just writes
Release / build-and-push (push) Successful in 5m11s
Answering the owner's round-trip question (highlight/note/progress
survives to the DB and restores on reopen) surfaced a gap: the
annotation lifecycle pins covered POST/PUT/DELETE but never the GET
list — the exact call web/src/reader/reader.ts makes when a book is
reopened. Every lifecycle now pins 'GET list restores the annotation':
the created row must come back by id with the update's fields applied
(highlights assert color, notes content, bookmarks title/cfi), proving
the DB write and the restore read through the same endpoint the UI
loads. Ran green in the rebuilt tests image.

Workflow note surfaced by this change: the tests service builds an
image (no source mount), so test edits need 'docker compose ... build
tests' (or run --build) before the filtered runner sees them — the
first run of the new subtest silently executed the stale image.
2026-11-02 18:29:54 -05:00
John O'Keefe dd963993eb fix(sync): scan events keep instance-wide fan-out as the sanctioned BroadcastToAll
Verifying the per-user chokepoint end to end surfaced a UI regression
it would have caused: web/src/header.ts runs the sitewide scan
indicator on scan_progress/scan_complete events in every browser, and
routing those to the triggering identity alone froze the indicator for
everyone else at its page-load state (active-summary stays the
load-time fallback, but live movement died). The source's own comment
declares the indicator sitewide by design, and scan payloads carry no
user data — job ids, file counts, progress percentages only.

Resolution honors both truths: BroadcastToAll is re-added as the ONE
sanctioned instance-wide fan-out, its doc comment making the decision
explicit (no user-derived data; anything carrying books, notes, or
annotations belongs in BroadcastToUser), and the two scan emitters use
it. TestBroadcastToAllReachesEveryone pins the exception alongside
TestBroadcastIsPerUser — audiences are now named decisions the
compiler and the tests both enforce.
2026-11-02 18:17:37 -05:00
John O'Keefe a431dfa10b fix(sync): websocket events are per-user — chokepoint the fan-out
Owner-flagged after the dev-docs audit: BroadcastProgressUpdate,
BroadcastAnnotationUpdate, and BroadcastConflictNotification fanned out
through the untargeted Broadcast, delivering one user's book progress,
conflict notices, and — worst — annotation payloads (which can carry
note/highlight text) to EVERY connected client on the instance. A
family-lens violation of exactly the kind the RLS move eliminated for
database reads: user B's client received events for user A's books,
including books in libraries hidden from B.

Fix is the RLS philosophy applied to the fan-out layer: enforcement at
one choke point. The untargeted Broadcast method and its channel/loop
machinery are deleted — BroadcastToUser is now the only door, and the
compiler forces every future emitter to name its audience instead of
relying on review. The three helpers take the acting user's ID; the
four sync call sites (progress.go x2, annotations.go x2) already had
the acting user in scope. Scan events were already per-triggering-
identity and collections already per-user — unchanged. Logging is
untouched: the only log line in the diff is the deleted method's own,
so docker logs remains the complete administrator audit trail.

TestBroadcastIsPerUser pins the invariant (alice's two devices receive
her three events; bob's client receives nothing — any message there is
a cross-user leak). Both websocket docs updated in the same commit:
the wire doc's fan-out section now states per-user delivery and the
chokepoint, and the gated endpoint doc's intro matches. Full make test
green.
2026-11-02 18:06:45 -05:00
John O'Keefe e957d385ec chore(devices): regenerate style.css after the modal move
The pairing input moved from the bottom of the Devices page into the
Add Device modal in d15f1155; that page was the sole user of the
mt-12 utility, so the rebuild Tailwind ran in make rebuild-app
afterwards purged the now-unused .mt-12 rule — 23 bytes lost, zero
selectors added or changed. Generated artifacts belong to the source
change that produced them and this one missed the commit; verified
the only delta is .mt-12 and that no source (web/src, templ, generated
files) references it any more.
2026-11-02 18:01:04 -05:00
John O'Keefe 06ec312863 fix(tests): uuid-suffixed websocket collection self-deletes
TestWebSocketUserScopedBroadcast creates "Admin Collection <uuid8>" on
the shared admin — deliberately NOT named with "test" or every run
would 409 on UNIQUE(user_id, name) against stranded past-run rows
(the comment in the test says exactly that), but it never deleted its
row, so the same runs accrued ten "Admin Collection" forever-rows the
name sweep can never touch. cleanupCollectionByID gives tests an
owner-scoped RLS-bridge delete-at-backstory: same minimal contract as
cleanupDeviceByIdentifier, for rows whose name must stay unique across
runs. Deleted the ten standing rows (owner-scoped, exactly what the
cleanup path does).

What CANNOT be swept, audited safe: the dev admin's real hand-made
collections (Saga reading-orders, Podcast 2, Smart Collection (Books))
carry no sweepable names; devices rely on identifier/token prefixes
tests own exclusively; the rls-phone hand account persists because the
transient-user sweep matches only @tests.bookhoard.internal /
@example.com emails.
2026-11-02 17:54:30 -05:00
John O'Keefe 7d88ec5184 fix(tests): test-created devices and fixture dirs now meet the cleanup contract
Test suites that attach devices to the SHARED admin (testuser, the live
dev account) escaped the harness sweeps whenever their names lacked
"test": createContractDeviceNamed named its devices by surface type
("koreader" — the web progress push adopts the device name as sync
source, so conflict tests drive a second named source without a
separate account), the reinstall regression test uses the web flow's
real "Reinstall Device" label, and opds_test.go's folders test named
its device "OPDS Folders Device". None had self-cleanup either, so
every suite run left 3 more rows on the dev account's device grid —
476 by the time anyone looked. TestDeviceSetup.CreateDevice also never
cleanup-registered, so any CURRENT or future helper-created device was
one rename away from the same leak.

Changes:
- TestDeviceSetup.CreateDevice self-deletes its row at test end
  (t.Cleanup): callers owe nothing to name hygiene any more.
- createContractDeviceNamed self-deletes likewise (contract-% prefix).
- device_test.go: core via cleanupDeviceByIdentifier on every device it
  attaches to the admin ("Reinstall Device" by unique identifier —
  the NAME is user-facing-labeled, sweeps must never torch it).
- Harness setup-time admin-device sweep gains the unambiguous harness
  patterns (dev_contract_* tokens, contract-%/opds-%/repro-reinstall-%
  identifiers) as the drift net; ran once with the rebuilt tests image
  and that sweep alone already purged the existing 476 rows.
- metadata_write_test.go now globs ALL test-metadata-write-* dirs in
  its RemoveAll instead of only its own pid's — killed runs left root-
  owned dirs on the user's uploads bind mount (7 found, deleted).

 audits: collections/saved-filters/libraries/sync_queue are clean;
 the only "test"-named media rows left are scans of the user's own
 on-disk test files (Test/, Bookhoard Test/, embedded " test" in two
 real books' metadata) — content, not suite debris.

Verified: filtered runs (contract/OPDS/reinstall/pairing/metadata)
green, zero device residue after the run, uploads mount clean.
2026-11-02 17:39:29 -05:00
John O'Keefe 0c31e9b88d fix(devices): pairing claim accepts urlencoded htmx form posts
The browser's Pair device button submits an application/x-www-form-
urlencoded <form> (htmx), but PairingCodeRequest/CancelRegistration-
Request carried only json: tags. Echo v5 routes form posts to the
'form:' binder, which maps by the form: struct tag exclusively — the
code arrived empty, normalized to "", and every browser claim failed
with the generic 'invalid pairing code' 400 even though the separate
lookup step (which reads c.FormValue directly, no struct) had just
resolved the same code. The API clients (plugin, Android, tests) post
JSON and were never affected.

Both request structs now carry dual form:/json: tags, matching the
auth.go convention. Adds TestPairingClaimAcceptsBrowserFormEncoding to
pin the form path: form-encoded lookup resolves, form-encoded claim
binds, device poll delivers credentials.

Found by the user clicking through the real Add Device modal; the
integration suite missed it because every prior claim test posted
application/json.
2026-11-02 17:12:15 -05:00
John O'Keefe d15f115505 fix(devices): pairing input moves into the Add Device modal
The pairing field sat at the bottom of the Devices page, below the
device grid — unreachable on any account with more than a screenful of
devices (the user's dev account has ~480 accumulated test devices;
scrolling 224k px to reach the field is a non-starter). The Add Device
button at the top of the page is where pairing intent already lives,
so the code input and Find device button now sit inside the Connect a
KOReader Device modal as instruction step 6, with the confirm card
swapping into the same modal (container keeps the pairing-lookup ids;
the htmx error-toast listener scopes to #add-device-modal now).

Verified live: modal renders the full instruction list + input, a
wrong code swaps the templ error partial inside the modal, and claim
still HX-Refreshes on success (modal state resets with the reload,
paired device appears in the grid).

ui-controls glossary where-fields and the COVERAGE row updated with
the control's new home.
2026-11-02 16:56:32 -05:00
John O'Keefe 5211edf264 docs(user): pairing-code flow for device setup guides
The setup guides walked the retired broadcast-list approve ("your device
appears under Pending Device Registrations — click Approve"), which no
longer exists. Both now describe the pairing-code flow: the e-reader
displays a 6-digit code, you type it into Pair a Device on your own
account, and only whoever holds the device can read the code — the
family-server gap that motivated the change. Adds a Pairing Code Not
Accepted troubleshooting case, refreshes the security practices
(claim only codes you can see on a device you are holding), and aligns
the remaining approval/pending wording throughout.
2026-11-02 16:11:31 -05:00
John O'Keefe 3e98fadb9f test(devices): integration coverage for the pairing-code flow
Replaces the reject-route test (behavior removed) with coverage of the
replacement flow, run against the shared dev DB per the doctrine:
fresh per-run regular user for deterministic claims, uuid-suffixed
identifiers so UNIQUE(device_identifier) stays clear across runs, and
device rows cascade away with the fresh user — testuser is untouched.

- TestPairingClaimHappyPath: lookup normalizes spaced digits, does not
  bind; claim binds to the claimer only; the device's status poll then
  delivers a token matching the stored row.
- TestPairingWrongCodeIsGenericAndNonDestructive: a miss answers the
  generic invalid-code error and leaves the real code claimable.
- TestPairingClaimBindsClaimerOnly: the admin account has no device
  row for another user's claim, and the used code answers 409.
- TestPairingReRegisterRetiresPriorCode: the old code and its
  registration UUID both die; the fresh code claims.
- TestPairingCancelByRegistrationUUID: cancel is idempotent, kills only
  its own registration (code and poll), and leaves a sibling
  registration untouched.
- TestPairingAttemptRateLimit: 13th lookup/claim attempt in a minute is
  refused with 429 (uses the fresh regular user — the limiter is
  process-global, so sibling tests sharing a token would otherwise
  pre-spend the budget).
- TestListPendingRegistrations now pins the invisibility invariant: a
  live registration appears in no account's pending list, total 0.
- TestRejectDeviceRegistrationRemoved pins the reject route's removal
  (404/405).
2026-11-02 16:11:25 -05:00
John O'Keefe fef79b1836 feat(devices): pair-a-device card replaces the pending registration list
The Devices page's Pending Device Registrations section (Approve/Reject
cards broadcast to every account) is replaced by an always-visible Pair
a Device field: type the 6-digit code shown on the registering e-reader,
a templ-rendered confirm card shows what will be bound, and confirming
claims the device to the signed-in account.

Rendering ownership (AGENTS.md): the confirm card and every lookup
outcome are templ partials (PairingLookupResult) swapped by htmx from a
new SSR route POST /devices/pairing/lookup — the server decides what UI
looks like, no JSON-built HTML. Errors render as content because htmx
only swaps 2xx bodies (the route is web-only; the JSON API keeps real
status codes), and one delegated htmx:responseError listener in
device-management.ts toasts the non-swap failure path.

The claim confirm button posts straight to /api/devices/claim; success
comes back as HX-Refresh (same pattern as token regeneration), so the
page reloads into the paired state. No new TS module is needed — plain
htmx attributes drive the whole flow.

Ride-alongs: the Add New Device modal loses the device-type select and
the kobo manual form (its post-register UX depended on the broadcast
list and silently produced an unclaimable registration; native Kobo
sync is still server-side-only and will get its own pairing UX when it
lands) — the modal is now a single Connect-a-KOReader-Device guide with
the pairing steps. PendingRegistrationData, convertPending, and the
pending plumbing in the page handler are gone with the section.
ui-controls.md glossary and tests/ui COVERAGE.md updated in the same
commit as the control rename, per the drift gates.
2026-11-02 16:11:15 -05:00
John O'Keefe 8fbacd9f46 feat(devices): pairing codes replace the registration broadcast
A pending device registration used to be announced to EVERY account's
Devices page, and whoever clicked Approve first bound the device — and
its freshly minted sync token — to their account. Worse, the pending
card displayed the registration UUID, which is also the bearer
credential on the unauthenticated /api/devices/register/status poll
channel: any family user who could see the list already held everything
needed to take the device. On a family server that is a
wrong-account-binding bug (accidental or deliberate); this commit
removes the class of problem rather than patching the race.

The new model is the Netflix/YouTube TV device flow: the registering
device displays a 6-digit pairing code, and the only person who can
read it — whoever holds the device — types it into THEIR account on the
Devices page. Possession of the device screen becomes the credential;
nothing is broadcast; the reject-on-someone-else's-behalf hole dies
with the list.

Server changes:
- POST /api/devices/register now mints pairing_code (crypto/rand,
  rejection-sampled for uniformity, collision-checked against live
  registrations) and retires prior unclaimed registrations with the
  same device_identifier, so re-registering leaves exactly one live
  attempt.
- POST /api/devices/claim (JWT) binds the registration behind a code to
  the caller's account, reusing the rotate-or-create approval logic
  factored out of ApproveDevice (shared bindRegistrationToUser helper;
  the Android self-approval route keeps working unchanged).
- POST /api/devices/claim/lookup (JWT) returns the confirm-card data
  without binding. Lookup and claim share a per-account budget (12
  attempts/min, DeviceRateLimiter gained a claim case) — the 1M-code
  space over a 5-minute TTL makes guessing infeasible without it.
- POST /api/devices/register/cancel lets the registering device end its
  own attempt (registration UUID bearer, idempotent, never touches a
  claimed registration).
- ListPendingRegistrations / GetPendingRegistrationsData are
  deprecated-by-emptiness: unclaimed registrations return to nobody.
- RejectDevice and its route are deleted — the broadcast list was its
  only consumer, and there is nothing left for anyone to reject.

Additive-only for pinned surfaces: the register response gains
pairing_code (Android DTO untouched), the four KOReader sync surfaces
and approve keep byte-identical shapes. contract_pins.md changelog
records the widening and the reject removal. Docs, schema registry, and
bruno mirrors move together per the drift gate; bruno_gen.go now keeps
hand-authored bruno/podcasts/ (API docs never existed for them, so the
next -update run would have swept them — latent landmine, defused).

Unit tests: code shape, live-collision avoidance, typed-code
normalization, and the resolve scopes (live/expired/claimed/miss).
2026-11-02 16:11:03 -05:00
John O'Keefe ab5c52c709 docs(dev): developer portal rewritten; tier definition closed in the standard
development.md was a bare link list whose 'implementation guides'
blurb still taught the pre-RLS visibility pattern. Now it's the
developer-tier portal: contributing/development.md as the start-here
(architecture/setup/testing — fresh and maintained), the gated API
reference with its per-area entry points and the openapi.yaml mirror,
the four protocol docs, the under-the-hood guides (RLS visibility,
scanner sidecars, calibre OPF, tag-normalization contract, Android
design), the standards (writing-ui-docs, glossary, contract pins),
and the gates enumerated — routes<->docs, Bruno parity, links, labels,
RLS invariant. writing-ui-docs.md's Developer-tier line closes the
open tone question: how-it-works, source-pinned, external software
linked not paraphrased.
2026-11-02 14:57:18 -05:00
John O'Keefe 35b210951a docs(dev): alpine-patterns rewritten around the CSP build
The March-era page had the right instincts (store state across swaps,
no manual DOM manipulation) but predated the @alpinejs/csp conversion
and never said the load-bearing fact: inline expressions are not
evaluated, so every x-data must reference an Alpine.data component —
which is why the whole attribute value is an expression and why
dynamic arguments go through JSONArg or data-attributes. Rewritten
with the banned list spelled out (inline handlers, hx-on*, js:
hx-vals, stray inline <script>) and each rule tied to the source that
enforces or embodies it (alpine.ts import, header.templ
whole-expression x-data, custom-section-builder data-attribute
pattern, bookPicker store as the living example). Every code sample
verified present in web/src.
2026-11-02 14:56:39 -05:00
John O'Keefe 4bd2788c7d docs(dev): library-visibility rewritten for the RLS era
The page still taught the pre-2026-10-29 app-side pattern —
visibleLibrarySet helpers, hand-rolled sqlc.narg('visible_library_ids')
clauses, per-endpoint 403 checks — which the RLS move made both wrong
and counterproductive: media_items, podcast_feeds, and collections are
now governed by row-level security filtered on the app.user_id GUC
that ScopedDB declares per statement. New media queries need NO
visibility plumbing; detached contexts RAISE unless the identity is
threaded (rls.WithUser); the NEVER list (session-scoped GUC, bypass
flags, superuser connections) and the auditors (TestRlsInvariant,
Playwright sweep, contract pins) are documented with the policy
mechanics they enforce. The series-per-library rule survives — it is
query semantics, not visibility filtering, and the policy makes
'visible' automatic under it.
2026-11-02 14:55:54 -05:00
John O'Keefe e40be80e78 docs(dev): websocket wire doc rewritten from source; endpoint doc ping claim fixed
The Feb-era 700-line page documented client->server JSON messages the
server never acted on (handleMessage logs only), a wrong ping/pong
exchange, and missed every message type added since. Rewritten tight
(~100 lines), every claim pinned: dual auth (JWT ?token= or device
Bearer header), initial_state on connect under the connecting
identity's RLS scope, the full 12-type message catalog (including
collection_updated, found per-user-targeted in the collections handler
and defined as a raw string outside the sync constants), WS-frame
keepalive (30s server ping, 90s read deadline — browsers answer
automatically), and the backpressure contract clients must honor:
bounded per-connection queues skip messages when full, so the socket
is a hint and REST refetch + fresh initial_state is the gap-healer.
Fan-out documented precisely: sync/scan events instance-wide,
collection events per-user.

Also corrected the gated endpoint doc (api/websocket/protocol.md):
its 'client sends {type:ping}, server responds pong' section
contradicted the handler; replaced with the true keepalive story.
Route pin untouched — the drift gates stay green.
2026-11-02 14:55:16 -05:00
John O'Keefe 8a40349fa1 docs(dev): delete developer/testing.md — contradicted current test doctrine
The Feb-era page described a wipe-all-test-users-per-run lifecycle,
which current doctrine explicitly forbids: the shared testuser is a
LIVE reader whose settings and history must survive every suite run,
cleanups are scoped preserve-lists, and hand-probes must be deleted.
Its recipes were also stale (no container runner, no pool rules, no
gates). The canonical home is docs/contributing/development.md
(architecture, setup, testing, project rules — kept fresh, 542 lines,
touched today), so the page was deleted rather than rewritten, with a
docRedirects entry sending old URLs there. No inbound doc links
existed.
2026-11-02 14:53:20 -05:00
John O'Keefe 51613566ac docs(user): koreader install delegated to KOReader's own documentation
Owner ruling: we support the plugin, not the software. The per-device
install walkthroughs (Kindle launcher paths, Kobo .adds layout,
PocketBook package steps) were prose-trusted third-party knowledge —
exactly the kind of content this project can't verify and shouldn't
half-cover, especially since real installs usually involve jailbreaks
and extra launchers. Replaced with an honest scope note (we can't tell
you how to modify your device) plus a link to the KOReader project's
official installation guide, verified live: github.com/koreader/
koreader#installation routes to per-model wiki pages (Android, Kindle,
Kobo, PocketBook, reMarkable, and more). The plugin sections (git-clone
install, server URL, registration, the full menu tree) are unchanged —
that's our side and stays pinned to plugin source.

Also fixed while grounding: the Mobileread forum link pointed at f=271
but KOReader's own README badges f=276 as their subforum; and the
resources section now carries their user-guide link (koreader.rocks/
user_guide) alongside installation.
2026-11-02 14:32:39 -05:00
John O'Keefe 0d4698c0de docs(admin): admin-guide front door + Administration area in the portal
The tenth and final page: the section directory with one-line coverage
per page, the fresh-instance quick path (libraries -> scan -> Base URL
-> users -> devices), and the when-something-looks-wrong triage table
mapping symptoms to pages. The portal (index.md) gains a For
Administrators area listing all nine admin pages; the user guide's
'being expanded separately' line becomes the done-state sentence.
Every control name quoted here exists in the glossary.
2026-11-02 14:17:13 -05:00
John O'Keefe 607e5a1708 docs(admin): settings page — every knob, what it does, and its range
The ninth page and the core of the owner's admin-docs brief: all 29
registry settings plus Base URL, documented setting-by-setting to the
admin tier — key, type, default, valid range, live-vs-restart, and
prose for what it does and what it means when that's confusing
(extractor-version as the gradual backfill lever vs. force rescan;
password rules apply at next set, never retroactively; tombstone TTL
as offline-device protection; rate limits as throttling behavior;
worker pool sizing honesty for small servers). Grouped exactly like
the page renders them, with the three save paths explained up front.
Ranges/defaults/flags from SettingDefaults; exclusion of the three
dedicated-UI keys from the tunables verified in the page handler.
Backfills the Settings links into dashboard.md and users.md now that
the target exists. Glossary gains Save Settings, Save Scan Settings,
both Tunable bucket headings, and Default Timezone.
2026-11-02 14:16:04 -05:00
John O'Keefe 39b0ab03fe docs(admin): users page — accounts, roles, last-admin guards
Eighth admin page. Documents the hidden-by-default create form (and why:
admin creation stays available with registration disabled — the form's
own design comment), live password requirements from active settings,
the card controls with their guards (last admin cannot be demoted or
deleted, dropdowns/buttons disable themselves with explanations), the
admin Edit User Profile modal (profile fields + role + Change Password
without current password — the admin-only difference), and delete
semantics (account + everything owned: devices, sessions, reading
data). Closes the loop on roles: admins get the Administration section;
users see only libraries visible to them, linking libraries.md for the
visibility story. Glossary gains + Create User and Edit User Profile.
(Settings referenced in prose only until that page lands — the first
amend of this commit briefly carried the same forward-link mistake the
dashboard page's amend fixed; pipefail is now the rule.)
2026-11-02 14:13:23 -05:00
John O'Keefe 535847477e docs(admin): all-podcasts page — the maintenance view
Seventh admin page. Documents the disk-usage sort (hogs surface first),
the header totals, each column's meaning (orphaned = no subscribers,
usually a departed user's feed), and the three actions with their real
semantics: Refresh (manual poll vs. the Settings→Podcasts interval),
Delete files (resets episodes to pending, re-download on demand, and
the non-obvious part quoted: a refresh will not re-materialize them),
Remove (instance-wide: rows + files + everyone's subscriptions, unlike
a user's own unsubscribe). Cross-links the user podcast guide for the
listening side. Glossary gains Delete files and a scoped Remove.
2026-11-02 14:12:46 -05:00
John O'Keefe aee1aafc74 docs(admin): hash conflicts page — the duplicate-content queue
Sixth admin page. Documents what creates conflict groups (scanner at
scan time + the hash backfill retroactively), the group card anatomy
(count badge, library + short SHA-256, per-copy rows with usage summary
highlighted when that copy holds reading data), and both resolutions
with verified semantics: Keep this copy (reparents the other copies'
children into the kept copy, deletes their catalog rows, records the
resolver — files on disk never touched, consistent with platform-wide
delete semantics) and Keep both (mark resolved, stop flagging, nothing
merged). Glossary gains Keep both and Keep this copy.
2026-11-02 14:12:10 -05:00
John O'Keefe 3e55ddd88a docs(admin): libraries page — the definition surface, with backlinks
Fifth admin page and the section's hub. Documents library creation
(name/description/type — type fixed at creation, verified in the edit
modal), the card's Force Rescan + Manage controls, and the full panel:
folders (add via Browse or manual path, shallow per-folder scan,
removal-unregisters-only semantics verified in DeleteLibraryFolder —
files and items untouched, archive lifecycle governs the rest; podcast
roots refuse hand scans), User Access visibility checkboxes (default-
allow, DB-enforced), the processing-issues link, and Delete Library's
exact destructive scope (records + reading data gone, files on disk
untouched). Ends with the at-a-glance scan table linking scanning.md.
Adds the Libraries backlinks to the processing-issues and archived
pages. Glossary gains Create Library, Manage, Edit Details, Delete
Library, View Archived, Purge Archived Now, Browse, User Access.
2026-11-02 14:11:25 -05:00
John O'Keefe ecb6a7385a docs(admin): archived items page — the missing-file lifecycle
Fourth admin page. Documents the two-consecutive-scans archive rule,
the history-preserving rationale, ARCHIVE_RETENTION_DAYS (default 90,
0 = manual-purge-only, verified in config.go), and the four actions with
verified semantics: Merge (progress/annotations/collections folded into
the active copy, per-user collisions keep the active copy — mirrors
hash-conflict resolution), Restore (immediate; re-archives if the file
is truly still gone), Delete (item + history, permanent), Purge All
Archived (the clean-slate button, confirm text quoted). Links to
scanning.md for why only library-wide scans archive. Glossary gains
Purge All Archived, Merge, and a scoped generic Delete entry.
2026-11-02 14:10:16 -05:00
John O'Keefe 88e3de606c docs(admin): processing issues page — per-library scan-failure ledger
Third admin page. Documents the severity stat cards (errors/warnings/
info, cards only appear when non-zero), the per-issue card fields, and
the three actions with their real semantics: Retry (per-item scanner
re-run — success closes the issue, failure surfaces the real error),
Retry all (sequential queue with done/total progress, deliberately not
a library-wide scan), Dismiss (warnings/info only, confirm-guarded;
errors cannot be dismissed). Links to scanning.md for the retry-vs-
library-scan distinction. Glossary gains Retry, Retry all, Dismiss.
2026-11-02 14:09:34 -05:00
John O'Keefe b3a8cbd582 fix(admin): library row button renamed 'Scan' -> 'Force Rescan', per owner
Owner ruling that closed the scan-semantics discussion: the code is
correct (per-library scan IS a force scan — hx-vals force:true since
706be09d), but the label hid that. Now the naming invariant holds
everywhere: anything with Force/Rescan in its name re-reads everything
in its scope; plain 'Scan' only exists at folder scope ('Scan this
folder', shallow) and in auto mode. Book-level Rescan verified as the
per-item force path (extractMetadata re-reads sidecars/tags regardless
of file size; recomputeHashInfo follows) — it is the documented answer
to 'I changed this book's sidecar'.

Glossary Scan entry replaced with Force Rescan (old label kept in also:),
scanning.md table + prose pick up the new label. Generated file
regenerated with the Dockerfile-pinned templ version from inside
templates/ so the diff is exactly the label strings.
2026-11-02 14:08:19 -05:00
John O'Keefe ed550fa914 docs(admin): dashboard page — stats, watcher, Quick Actions, scan panel
Second page of the admin tree. Documents the four-card stats grid with
what each number actually counts (instance-wide totals; Books = every
media item including podcast episodes), the File Watcher card's data
source (/api/scanner/watch/status, armed by Auto-Scan) and its
zero-libraries meaning, Force Rescan All Libraries with its real
mechanics (one job per library, skip-on-active, backfill tool vs.
routine shallow refresh), and the Scanning panel's live progress +
Cancel all scans. Links only to pages that exist (scanning.md); the
Settings reference stays prose until that page lands.

The real-tree nav test's Administration assertion loosens further: guide
leads, everything else strictly follows usabilityOrder — durable across
the remaining page landings. Also fixes the amend this commit replaces:
its first version briefly carried a forward link to the unwritten
settings.md (caught by the link gate, now removed) — the gate worked;
the && chain around go test let the bad commit through, which is exactly
why this amend exists.
2026-11-02 13:49:23 -05:00
John O'Keefe 89fc479bdb docs(admin): scanning page — the shallow vs. force taxonomy from source
First page of the admin tree, written to the new admin tier (what the
click actually does). Documents every scan surface with its verified
semantics: Force Rescan All Libraries (dashboard, force, all libraries,
one job each with skip-on-active), the per-library Scan button (ALSO a
force scan — hx-vals force:true since the button's birth commit 706be09d,
which corrects the owner's stated 'other scan buttons are shallow'
belief; flagged to the owner), Scan this folder (shallow, single-folder
scope, archive pass skipped for partial scans, podcast roots refused),
Auto-Scan + Scan Interval (the watcher + poll + startup triggers, all
shallow, default 60s range 1-3600), Processing Issues retry (per-item
sequential, deliberately not a library scan), and book-level Rescan /
Reset to Scanned. Plus the standing rules: one scan per library
(coalescing), background jobs with the dashboard progress panel, and
the two-consecutive-scans archive rule.

Glossary gains Scan and Scan this folder (same-commit rule for controls
cited in prose). The real-tree nav test's Administration assertion now
pins shape (Admin Guide, Libraries prefix + usabilityOrder subsequence)
instead of an exact slice, so pages landing one at a time don't churn it.
2026-11-02 13:47:40 -05:00
John O'Keefe 20754f15e2 docs(standard): admin tier defined; promises require owner approval
Two additions to the screenshot-free writing standard, both owner-
ruled during the admin-docs planning session:

- Tone by audience gains the Administration tier, ending the 'not yet
  decided' limbo for admin docs: plain language like the user docs, plus
  what every control actually does (semantics, cost, consequences)
  before the reader clicks, and per-setting what/does/means/range
  coverage. Calibration in one line: user = what you see, admin = what
  it does, developer = how it works. The Developer section keeps its
  separate tone discussion for the deferred dev-docs pass.

- New 'Promises need approval' section: no coming-soon / under-
  consideration / future-release language anywhere without the owner's
  explicit approval of that exact promise; speculative text found in the
  docs is reported, never quietly kept or quietly deleted. Provenance
  recorded (the 2026-11-02 device-promise removals; the Operations
  placeholders knowingly kept).
2026-11-02 13:40:34 -05:00
John O'Keefe bb141cdffc fix(admin): rename 'Scan All Libraries' to 'Force Rescan All Libraries'
Owner: the dashboard button's label under-promised what it does. The
action is a FORCE rescan (scanner.SetForce(true) via the scan worker):
every file re-read and re-extracted with original-scan semantics, hash
identifiers recomputed — the admin's backfill tool, per the scanner's
own source comments. The shallow scans (per-library button, per-folder
scan, processing-issues retry) deliberately skip unchanged files and
keep their 'Scan' labels; the naming now carries that distinction.

Subtitle updated to state the real semantics ('Re-reads every file and
re-extracts metadata and hashes — slow but thorough') instead of the
old 'Re-scan existing files and detect new items', which described the
shallow path. ui-controls.md gains the canonical glossary entry (old
label recorded under also: so anything still quoting it resolves); no
doc quoted the old label yet, so no doc edits were needed.
2026-11-02 13:39:52 -05:00
John O'Keefe 393a00e8dd docs(nav): Administration section lives in docs/admin/; sidebar ordered by usability
Two structural changes, one owner-approved plan:

- Move the admin guides out of docs/user/ into their own docs/admin/
  area — admin-guide.md becomes the Administration section landing page
  (pinned first), and the 32-line admin-library-management.md stub
  becomes admin/libraries.md, which the admin-docs build-out rebuilds
  into the real Libraries page next. Retired URLs 301 via a new
  docRedirects map in the docs HTTP handler (checked before .md
  canonicalization so even .md spellings one-hop to the new clean URL);
  the two inbound links (docs index, user-guide front door) updated.

- Sidebar direct items now sort by usabilityOrder — an explicit,
  per-section display order — instead of alphabetically: User Guide
  mirrors the 'Where to go' table on user-guide.md, Devices orders
  Android → KOReader → Kobo (alphabetically Kobo used to sort ahead of
  KOReader), and Administration pre-lists its planned pages so each
  lands in place as the admin build writes it. Unlisted docs fall back
  to alphabetical after the listed ones. Display-order only by
  construction: the URL-driven expand/highlight machinery keys on
  containsURL membership and never sees sort order — nav tests updated
  to pin the new orders plus a real-tree test
  (TestBuildNavigationUsabilityOrder) guarding all three sections.
2026-11-02 13:38:01 -05:00
John O'Keefe 7e2e1c4c60 docs: remove speculative promise language, de-brand Android design analogy
Owner rulings from the admin-docs planning session:

- sync-guide: dropped 'Kindle and reMarkable are under consideration' —
  no such plans exist, and promising support for proprietary device
  interfaces we will never build sets false expectations. Device posture
  stays as the table states it: web, Android app, KOReader anywhere
  (including jailbroken Kindle hardware), native Kobo the sole exception.
- calibre-integration: cut 'Custom Calibre Columns (Future)' + 'Stay
  tuned!' — unshipped-feature promises do not belong in docs; calibre
  integration is a by-product of the scanner's sidecar support, not a
  roadmap item. The features list describing Calibre itself stays (that
  is Calibre's promise, not ours).
- android-app: de-branded the two Kindle references per owner's legal
  caution — 'the Kindle app to Kindle cloud' analogy and 'quality bar is
  the Kindle app' are now 'any dedicated reader app to its server' / 'a
  first-class native reader app'; engineering substance unchanged.

Governance rule going forward (codified in writing-ui-docs.md in a
follow-up): no future-improvement or coming-soon language anywhere
without explicit owner approval; anything found gets reported, not
silently kept or silently removed.
2026-11-02 13:34:21 -05:00
John O'Keefe 2165829d0e fix(ux): confirm modal's Cancel/Confirm were dead on the promise-API path
Release / build-and-push (push) Successful in 3m29s
User report: the Purge Archived dialog ('Permanently delete all
archived items?...') opened, and Cancel did nothing — and Confirm
would have been equally dead, leaving the page stuck behind the
overlay until a reload.

Root cause: confirm.ts wired the modal's buttons ONLY inside the
htmx:confirm interceptor. confirmDialog() — the promise API used by
purgeArchivedItems, remove-account, and other TS call sites — never
wired them. So whenever a page's first confirm interaction came from
the promise path (no hx-confirm element clicked first), both buttons
had no listeners. The 2026-10-30 confirm_probe spec only exercised the
hx-confirm path, which is why it survived.

Fix: wireButtons() now runs at module init (the header renders before
deferred modules) and inside confirmDialog() — both idempotent via the
existing data-wired guard.

Pinned by tests/ui/promise_confirm_probe.spec.ts (no env gating): the
purge POST is route-intercepted, so the probe asserts Cancel closes
the modal and Confirm issues the guarded request without deleting any
dev data. hx-confirm path re-pinned green (confirm_probe with BH_FEED).
Verified manually at 390x844: open -> cancelWired=true -> Cancel
closes -> Confirm fires the intercepted request.
2026-11-02 11:24:55 -05:00
John O'Keefe 04e855e691 fix(ui): right slide-out sheet for oversized modals on phones; 360px fixes
Auditing at 360x760 (Firefox's smallest emulated device; Galaxy S25
class) — 390 was too generous a baseline — the Customize Dashboard
pop-up was the worst page in the app: its card measured 986px in a
760px viewport with no internal scroll, so Cancel/Save sat ~90px below
the fold on a fixed, non-scrolling overlay — unreachable.

New reusable shell: .app-modal-panel (input.css) renders a centered
dialog on desktop (>=640px, unchanged) and a full-height right
slide-out sheet on phones: h-dvh, rounded-l-2xl, slide-in animation
(replays on every open because the overlay toggles display), internal
scroll, overscroll containment. Overlay pairs with items-stretch /
justify-end below sm.

Converted the measured overflows:
- Customize Dashboard (986px): sheet + sticky header/footer, rows wrap
  with the Restore/toggle group right-aligned (ml-auto), titles
  truncate, System badge shrink-0.
- Collection create/edit (796px, cut at both ends at 360): sheet +
  sticky header/footer; edit modal shared the file.

Also at 360: admin-library's Archived buttons row (View Archived +
Purge Archived Now, 315px at x=49) inflated the page to 364px — now
flex-wrap. Collection-episodes shows a 1px sub-pixel rounding artifact
(vw=361) — left as-is, invisible.

Verified at 360x760: sheet geometry (footer bottom 739 < 760), rows
fit, desktop 1280 screenshot unchanged; full-route sweep at 360 shows
no page-level horizontal overflow beyond the two notes above.
2026-11-02 10:55:23 -05:00
John O'Keefe 3e8ac3b9b7 docs(user): koreader install is a git clone (git pull to update), per owner
Replaced the 'clone then copy to plugins/' phrasing with the actual
workflow: clone straight into the plugins folder (koreader/plugins,
.adds/koreader/plugins on Kobo), restart KOReader; updates are git pull
in bookhoard.koplugin + restart. Closes the last prose-trusted item in
the user-docs rebuild.
2026-11-02 10:42:49 -05:00
John O'Keefe 10a5ac88da docs(user): themes — drop the invented 'default light theme' tag, per owner
Lupine's '(default light theme)' tag had no basis anywhere: the string
exists only in the ThemeType union, and there is no light-default logic
in theme.ts or the Appearance panel. Platform-owner clarification:
Tokyo Night is the sole default (fresh install); the Dark/Light control
is a list filter with per-half counts, not a theme toggle. The page now
says exactly that, keeps the code-verified bits (mode filter opens on
your current theme's half via ThemeModeOf, checkmark indicator, counts)
and states the one-default rule plainly.
2026-11-02 10:39:09 -05:00
John O'Keefe 3feb608d26 docs(user): two more code-grounding fixes from the verification sweep
- sync-guide matching ladder was missing rung 8: Title only at 0.3
  confidence, last-resort after title+author+size (book_matching.go
  priorities 1-8, file-path priority handled at the API layer).
- library-browsing said the sort dropdown had 'more' options than it
  does: exactly five (Title A-Z/Z-A, Author A-Z, Date Added, Page
  Count).

Sweep results, all verified against source: themes.md 24+13=37 exact
(web/src/theme.ts union), reader-guide claims (corner zones, selection
copy, comics annotations disabled - bookmarks only) present in
web/src/reader/reader.ts, android-app.md strings (local-network
permission, login error table) in bookhoard-app source, calibre
dc:title/calibre:series parsing in media_scanner_calibre fixtures.
2026-11-02 10:28:45 -05:00
John O'Keefe 9b2d3da7e2 docs(user): koreader-setup — document the actual plugin menu from source
The guide documented setup and stopped. Everything after 'approved' was
undocumented: the real menu tree from bookhoard.koplugin main.lua is now
in the guide — one-tap actions (Push progress / Pull progress / Sync
rating, review & time now / Setup OPDS catalog / Device info /
Disconnect / Register device), Automatically push progress (DEFAULTS
OFF — the likely cause of 'sync not working after approval' reports),
Periodically sync every # pages (default 50), Sync mode
(Immediate/Checkpoint), Sync behavior (Sync to a newer state default
Prompt / to an older state default Never — the device-side side of
conflict handling), and the seven What to sync toggles (progress,
bookmarks, highlights, notes, ratings, review, reading time — all on by
default; the ratings/review/reading-time sync was entirely missing from
docs despite the six server endpoints).

Also fixed: Android 'coming later' line now points at the real app,
OPDS auto-registration verified in the approval poll (setupOPDS on
approved), expiry wording, and a troubleshooting entry for the
wifi-toggle permission message auto-sync can raise. Ground truth noted
in a source comment; verify against plugin source on plugin changes.
2026-11-02 10:23:52 -05:00
John O'Keefe 788e9463cf chore(web): delete dead linking module
The module could never execute against any real page:

- renderUnlinkedBooks targeted #unlinked-books-list, an id that exists
  in no template; the live /unlinked-books page is server-rendered by
  templates.UnlinkedBooks and driven by the Alpine unlinkedBooks
  component (web/src/unlinked_books.ts, setupEventDelegation) with its
  own CSP-safe wiring.
- showSuggestionsModal/hideMatchModal need #match-modal and
  #match-modal-content, which no template renders either.
- Its inline onclick handlers referenced window.showMatchModal, a
  function that was never defined anywhere.

Nothing imports it except main.ts's side-effect import, and no
template/Go/TS surface references its Alpine component registration,
containers, or globals (grepped templates/, internal/, web/src/).
Verified after removal: tsc, vp check, vitest (198), and /unlinked-books
plus dashboard/stats load with zero console errors, empty state and
Alpine component intact.
2026-11-02 10:23:43 -05:00
John O'Keefe ef4de7896a fix(csb): custom-section book picker search never worked — two latent bugs
Fine-toothed functional verification of the delegation work exposed that
the picker's book search has been dead since launch, for two
independent reasons:

- The builder fetched GET /api/books/search, a route no router has ever
  registered — every search 404'd (the CSP-dead onclick buttons on the
  results hid the failure). It now calls the unified JSON search the
  bookshelf uses (/api/media-items/search?q=&library_id=), maps its
  rows (id/title/author/cover_image_path) to the picker's BookInfo
  shape, and treats the endpoint's 404-with-results:[] as empty.

- Even with results, the picker container shared id=search-results with
  the header search dropdown (header.templ renders it on every page);
  getElementById returns the first match in tree order, so results were
  written into the invisible topbar dropdown. The picker container is
  now cs-search-results (templ + all three TS references).

Verified end-to-end at 390x844: select library -> search '1984' -> 3
results render -> click adds the selection chip -> chip x removes it.
Zero console errors.
2026-11-02 10:14:35 -05:00
John O'Keefe 12aab156f6 docs(user): sync-guide rebuild to today's platform; calibre guide de-API'd
sync-guide.md was 591 lines with good implementation-derived bones
(matching confidence table, universal locations, conflict flow) wrapped
around a stale device story: Android 'coming later' (the app exists and
self-registers), a deleted queue UI, invented UI (color status badges,
Auto-Resolve Future, Priority Sync buttons), placeholder support links,
an HTTPS-1.3 overclaim on LAN setups that are plain HTTP by design, and
a changelog promising the future. Rebuilt to ~140 lines, every claim
grounded: device table matches reality (web/Android/KOReader supported,
Kobo native server-complete with rollout pending), resolution
strategies as the API actually defines them (device / server /
highest_progress), offline queuing honestly scoped (Android queues;
server holds per-device queue; no dedicated queue UI today), reading
history on Progress page, RLS-era privacy wording, device limit 10
default admin-settable. Reader Sync Progress button verified.

calibre-integration.md: mostly current (sidecar-first model, Dublin
Core tables, Write-to-file section all kept); fixed the user-hostile
'POST /api/scanner/scan' instructions to point at the admin scan
controls, and dropped the yourusername placeholder repo links.
2026-11-02 10:12:41 -05:00
John O'Keefe c1a7648076 docs(user): reader audio section + kobo guide refresh to platform reality
reader-guide.md gains the audiobook/episode player section (seek,
prev/next episode, Bookmarks panel, Chapters list, Player settings with
autoplay/speed/resume-rewind overrides, Shortcuts dialog) — the player
existed with zero user docs.

kobo-setup.md drops the stale 'not available yet, actively being
developed' framing: the server side of native Kobo sync is implemented
and documented (sync/initialization endpoints, bookmark + markup sync,
shelf mappings, KEPUB sidecar config), so the guide now states exactly
that, keeps stock-firmware rollout as the honest remaining piece, and
keeps KOReader as the supported today-path.

ui-controls.md: Player settings / Shortcuts & interactions / Chapters /
Bookmarks entries (templ-entity fragments for ampersand labels).
2026-11-02 10:09:18 -05:00
John O'Keefe 9e2f216af5 docs(user): dashboard, browsing, profile rewrites + new podcasts guide; trash stubs
Ground-truthed against the templates this pass:
- dashboard.md: real section kinds (system shelves incl. Continue
  Series, user collections, custom sections via /custom-section
  builder), Customize Dashboard panel semantics (per-library, drag,
  switches, 10-50 items, Save Changes), Refresh, This Week widget,
  per-item Read/Listen and progress-conflict resolve actions. The old
  page listed a wrong shelf set and never mentioned custom sections.
- library-browsing.md: the file was secretly titled 'Saving Custom
  Filters' and covered nothing else. Now the browsing page: All Books
  toolbar (search, Sort, Filters -> drawer hand-off, Save/Load/Clear
  saved filters), book detail as hub, series pages, podcasts split.
- profile-guide.md: field table ground-truthed from profile_form.templ
  (username/email DO remain editable there), audio defaults (speed,
  resume rewind, keep awake), timezone rendering contract, both theme
  doors (7-pick select vs 37-theme Appearance panel), Change Password
  with live checks, Danger Zone/Remove My Account + last-admin rule.
- podcasts.md NEW: the Podcasts page had zero documentation. Subscribing
  (Add Feed -> RSS URL, library, back-catalog download, download order,
  Add & Subscribe), Continue/All Feeds, Download All, player + Play as
  Sequence cross-link.
- Trashed user-areas.md, frontend-guide.md, settings-guide.md: stubs
  whose planned content now exists as real pages (or duplicates
  profile-guide). user-guide.md rewritten as the plain-language front
  door with a go-here-when table; index.md rows updated to match.
- ui-controls.md: 10 new gate-checked entries for every newly cited
  control (Add & Subscribe via templ-entity fragment).
2026-11-02 10:07:28 -05:00
John O'Keefe ceed3ddeae fix(stats): Most Active card wrapped mid-token on narrow screens
'2026-11-01 (148 min)' broke as '(148 / min)' in the half-width stat
card. Date and minutes now render as stacked block lines — date,
minutes, weekday — so nothing splits across rows.
2026-11-02 09:46:58 -05:00
John O'Keefe 0673550d58 fix(admin): library rows collapse on phones — chips hid the name
Visual review of the first flex-wrap attempt: with the name block at
flex-1 (0 basis), the row never registered as overfull, so wrap never
fired and the shrink-0 chips still overprinted Scan/Manage. Dropping
flex-1 lets wrap trigger — but then the chips starved the name down to
'P…'. The type/folders chips are the least-important content in the
row: hidden below sm, so phones show icon + full name/description with
Scan/Manage on a second row; desktop keeps the single-line layout with
chips (>=640px unchanged).
2026-11-02 09:46:58 -05:00
John O'Keefe 71b171bf72 fix(csp): allow blob: stylesheets in style-src for the reader
Every /readers load logged a CSP violation: foliate-js injects its
reader-generated stylesheets as blob: URLs, and style-src only allowed
'self' 'unsafe-inline' — so the sheet was refused and selection/
highlight styling inside the reader rode on nothing.

blob: was already granted for img-src, font-src, and frame-src for
exactly this reader content; style-src now matches. The content is
app-generated at runtime (no cross-origin input), script-src is
untouched, and the strict script hash allow-list keeps its guarantee.

Pinned by TestThemeFlashGuardHashMatchesCSP (script-src only — the
style-src addition doesn't interact) and TestGoSourcesAreCSPSafe.
2026-11-02 09:31:58 -05:00
John O'Keefe 2df6f8e55c fix(ui): replace CSP-blocked inline handlers with delegated listeners
The hash-allow-list CSP refuses inline onclick=/onerror= attributes, so
three TS islands shipped dead controls:

- stats.ts rendered Most-Read/Longest covers with onerror= — every
  /stats load logged violations (5+ on the dev data) and the broken
  cover fallback never ran. Now: capture-phase error listeners on the
  three list containers (they persist across innerHTML swaps; error
  does not bubble but capture still reaches them).
- custom-section-builder.ts picker rows and selection chips used
  onclick= against window globals. Rows now carry data-book-id/title/
  author and chips data-remove-book; initCustomSectionBuilder wires one
  delegated click listener per container. window.addBookToSelection/
  removeBookFromSelection exports removed — no remaining references.
- linking.ts: the unlinked-books 'Link' button called
  window.showMatchModal, which never existed anywhere (doubly dead:
  missing global AND CSP-blocked); suggestion rows and Cancel used
  onclick= too. All now data-attribute driven through one document-level
  delegated listener; row Link opens the suggestions flow via
  getSuggestions(progressId), which fetches matches and opens the modal.

Verified: tsc --noEmit, vp check, vitest (198), manual modal flows.
2026-11-02 09:31:58 -05:00
John O'Keefe 88adf30aa9 fix(ui): mobile layout overflows across admin, reader, and book pages
Every fix is a minimal class-level change; desktop layouts are untouched
because each fixed row already fit on one line there.

- progress: CFI string is one unbreakable token — it inflated the page
  layout width to 398-501px (whole-page zoom-out on phones) and rendered
  debug-looking text edge to edge. min-w-0 + break-all lets it wrap.
- audio reader: settings strip min-content (~470px) exceeded the 390px
  viewport, clipping Skip/Sleep and — because the page ICB inflated —
  pushing the chapters drawer (w-full of the viewport) past the screen
  edge so its timestamps clipped too. flex-wrap fixes both symptoms.
- book detail edit-metadata modal footer: Rescan/Reset/Write-to-file row
  overflowed the modal; clipped buttons were unreachable. flex-wrap.
- bookshelf save-filter modal footer: three buttons overflowed both
  screen edges. flex-wrap.
- admin libraries: rows overprinted (badge chips shrink-0 vs actions
  shrink-0, no wrap) — 'manga⟳Scan▸1 folders⌄Manage'. flex-wrap stacks
  actions under the name on phones.
- admin podcasts: maintenance table forced a 892px page (44% zoom).
  overflow-x-auto on the card scrolls the table inside it instead.
- stats: 4-pill range row forced 421px; page permanently ~7% zoomed out.
  flex-wrap.
- podcast feed detail: label+select pairs now travel in their own flex
  pairs so flex-wrap can never split 'Order' from its select; ids and
  htmx change-triggers preserved.
- cosmetics: conflicts stat labels tracking-wide→normal (UNRESOLVED
  clipped), archived file path line-clamp-3, rules-page Smart badge
  wraps cleanly, dashboard View All shrink-0 nowrap (was wrapping to
  two lines).
2026-11-02 09:30:55 -05:00
John O'Keefe e3ca3426ba fix(auth): emit default_audio_speed unconditionally on the profile response
TestDocsMatchRoutes failed on users/get_profile.md: the example carries
default_audio_speed but the response struct tagged it omitempty, so the
gate's zero-value marshal never sees the key and reads the doc as
inventing it. The tag was semantically dead: the column is NOT NULL
DEFAULT 1.0 (schema.sql 44) and writes validate 0.25-4, so a stored 0
is out of domain and every real profile emits the field. Response-only
struct, no form-bind impact. The key was added to the doc example in
ef827a3a without a gate run - this is exactly the class of drift the
gate exists to catch; make test now passes again.
2026-11-02 08:56:37 -05:00
John O'Keefe 42b283480a docs: archive the screenshot-automation plan as rejected
The Playwright screenshot pipeline is not being built: screenshots are
the only doc format no gate can verify, they rot silently at every UI
change, and a redesign was the stated plan. Replaced by
docs/developer/writing-ui-docs.md (pattern-first text, exact quoted
labels enforced by TestUIControlLabels) — see that page for the full
reasoning. Body kept below unmodified for history.
2026-11-02 08:22:01 -05:00
John O'Keefe 913174cdf8 docs(gates): widen relative-link checker to all docs, repair the rot it finds
TestDocsRelativeLinks walked only docs/developer; widening it to all of
docs/ immediately surfaced the same class of rot the gate was built
for, outside its old reach:

- docs/index.md was the old monolith's landing page: linked the deleted
  api-reference.md, 10 directory-style area links, and escaped the docs
  tree to README/AGENTS/.env/compose. Rewritten as a portal whose every
  link resolves, with one representative endpoint doc per API area and
  pointers to the new writing-ui-docs.md standard.
- directory-style links in user stubs (devices/, ../operations/)
- case-mismatched links (Development.md) in contributing.md
- monolith-era pointer (API_REFERENCE.md, TROUBLESHOOTING.md) and
  escaped AGENTS.md links in contributing/development.md
- docs/development/calibre-opf-implementation.md double-up escapes, a
  link to the removed repo-root plan file (absorbed here), and a
  source-code hyperlink the docs site can't serve (now inline code)
- operations/operations.md linked three never-written guide pages as
  aspirational links - they stay plain text until pages exist

HANDS-OFF (project owner, 2026-11-02): docs/user/filters/** and
docs/user/searching-and-filtering.md are exempt as link sources so no
future checker failure can force edits to the filter documentation.
Files linking INTO them remain checked.
2026-11-02 08:21:47 -05:00
John O'Keefe bf4735f3ce docs(user): rewrite collections to the screenshot-free standard
The old page was stale in ways the standard now forbids: spatial
language ("top-right"), documented URL query params users should never
need, no mention of smart collections or podcast episodes, no hand-off
to the filter docs.

Ground-truthed against the templates: Static vs lightning-Smart type
choice, Books/Podcast episodes rules scope, Add Items picker ( Books /
Episodes tabs, Add Selected, Remove Selected), Edit Rules -> Filter
tree -> Apply to Collection, Play as Sequence with the listening-order
picker (Feed order / reversed / oldest / newest), Hide finished books
(reading-queue mode) and Show Up Next strip toggles, system shelves
(Continue Reading, Recently Added, Recently Read, Not Started, Continue
Series) and Restore System -> Restore.

Plain language per the user-docs tone contract: short sentences,
pattern-first (one shelf concept, four flavors), every step ends in an
outcome, rules taught by LINK to the filter guide (reference, never
restate). Every quoted control exists as a literal and is glossaried in
ui-controls.md (gate-checked).
2026-11-02 08:18:27 -05:00
John O'Keefe e07301f74a docs(standard): screenshot-free UI documentation standard + UI-label gate
The planned Playwright screenshot docs (SCREENSHOT_AUTOMATION.md) are
replaced by a text standard: screenshots rot silently and cannot be
gate-checked, while this UI's labels are server-rendered templ literals
that can. Layers: pattern-first prose (concepts survive redesigns) >
capability inventory > label->outcome flows > quoted labels > generated
references where a registry exists (filters/fields.md precedent). The
filter docs stay hands-off exemplars; user-doc tone is plain language by
contract, dev/admin tone explicitly deferred.

writing-ui-docs.md is the standard (page template, findability notes,
tone-by-audience, process rule: a UI change is not done until the docs
audit runs). ui-controls.md is the canonical control-label glossary the
docs quote from; TestUIControlLabels greps every entry against
templates/*.templ (source: ts override; also:-fragments for
Alpine-composed labels like the Match/Group header) so renames fail
make test in the same commit as the rename. Gate proven both ways: a
planted bogus label failed; restored set passes.
2026-11-02 08:18:19 -05:00
John O'Keefe fbdd4ab9f9 feat(audio-player): Resume Rewind select in the settings popover
Release / build-and-push (push) Successful in 4m43s
The player window could only change Skip and Speed; resume rewind
lived exclusively on the profile page. The user-facing settings now
match Speed's precedent — changeable from the player, saved to the
account, applied immediately.

The select mirrors the default-speed row (CSP-safe @change bound to
one Alpine method; templ emits the option list from the shared
ResumeRewindOptions allow-list and the :selected expression against
the live resumeRewind field). Applying updates the running player's
value first — the next open/unpause uses it with no reload — then
PUTs audio_resume_rewind_seconds to the profile endpoint as the
string wire shape the server binds. normalizeResumeRewind gates the
select's value through 0/5/10 before both steps.
2026-11-01 21:29:19 -05:00
John O'Keefe ef827a3a05 test(api): pin the resume-rewind contract
Release / build-and-push (push) Successful in 3m2s
TestAudioResumeRewind drives the whole surface against the shared dev
DB with the fresh per-test regular user (the live admin is never
touched; the fixture book lives in a test-named library that cascades
away): default 0, profile PUT "5" rides the chapters payload,
non-allow-listed values 400 without side effects, explicit "0"
resets everywhere, and an omitted JSON key leaves the column
untouched.

Changelog entry in docs/contract_pins.md (additive chapters key +
the profile field's string-shaped PUT, keep_screen_awake precedent)
and the get_profile.md example gains the preference keys.

Debug note for the next agent: the first runs here 401'd with
'Ghost session rejected' — NOT a harness or auth bug. The tests never
execute schema.sql; the shared dev DB gets its schema from the app
container's boot. The rebuilt tests image ran the new GetUser
(selecting audio_resume_rewind_seconds) against a DB whose schema
came from the old app image — every GetUser errored, and the
ghost-session guard turned that into 401s. Applying the schema.sql
ALTER to the dev DB (what the next app rebuild does anyway) turned
the suite green. Until make rebuild-app runs, the running app
container serves the old binary.
2026-11-01 19:38:08 -05:00
John O'Keefe 7b7ce39826 feat(audio-player): apply the resume-rewind setting on open and unpause
The chapters payload now carries resume_rewind_seconds (server-side
per-user setting); the player applies it at two events, each rewinding
once from where playback currently sits — never stacked:

- open-resume: restorePosition starts the rewind early from the saved
  spot (percentage and chapter+offset branches, clamped at the book
  start). Deep links (?loc=) stay exempt — an explicit jump is not a
  resume.
- unpause: a genuine pause→play steps back again (the re-orientation
  gap). Programmatic plays — post-restore autoplay and track-switch
  autoplays — set a suppress flag: their play event is the session
  start the open-rewind already positioned, not an unpause.

Math lives in audio-rewind.ts (pure, unit-tested) after the
audio-scrubber pattern; payload values gate through the 0/5/10
allow-list so stale or foreign servers degrade to exact resume.
2026-11-01 17:21:35 -05:00
John O'Keefe 9cf9e1d305 feat(api): expose and validate the audio resume rewind setting
GET/PUT /api/auth/profile now carries audio_resume_rewind_seconds
(always-present on the response: 0 is a real value, exact resume; the
request shape is the keep_screen_awake string precedent so the form
select can send an explicit 0=Off while JSON clients that omit it
leave the column untouched — a plain int with an omitempty contract
could not express 'set to off'). Strict allow-list {0,5,10}: the UI
offers exactly three choices and the API refuses everything else.

The audiobook chapters endpoint embeds resume_rewind_seconds in its
existing payload — it already loads the user row for playback speed,
so both players (web + Android, phone UI and the Android Auto service)
get the value with the fetch they perform anyway; zero extra round
trips.

Profile page gains the Resume Rewind select (Off / 5 s before /
10 s before) next to Default Playback Speed.
2026-11-01 17:19:58 -05:00
John O'Keefe daffe499eb feat(users): audio_resume_rewind_seconds column
Per-user resume rewind for the audiobook/podcast player: how many
seconds (0/5/10) before the saved position playback starts, both on
open-resume and again on every genuine unpause. Motivated by the car
startup case — exact resume loses the listener's place, and the
PlaybackRequestResolver path (phone UI, Android Auto, media buttons)
all funnel through one start position.

0 = exact resume (default), so the column is inert until the profile
page sets it. Follows the default_audio_speed / keep_screen_awake
precedent: idempotent ALTER in schema.sql (re-runs on every boot),
explicit GetUser SELECT, dedicated :exec update. Handler-side strict
allow-list {0,5,10} lands with the API slice.
2026-11-01 17:16:35 -05:00
John O'Keefe 0d613ba0e3 fix(docs): folder-index pages expand the sidebar and highlight — same rule for every page
The filter manual is the docs tree's first FOLDER-index page: it serves
at /docs/user/filters while its nav entry carries /index
(/docs/user/filters/index). The sidebar's two checks — group expansion
(containsURL) and active-link styling (docsNavClass) — compared URLs
EXACTLY, so the folder URL matched neither: no submenu expansion, no
highlight (2026-11-01 user report: "the left sidebar should open to
the submenu and highlight the page").

Fix is structural, not per-page: both checks normalize folder-index
URLs (a trailing /index is the same page as its directory), so EVERY
folder-index page — current and future — expands and highlights like
a file page. No per-page registration exists anywhere in the docs
system to redo: the sidebar derives from the docs tree, and this was
the one URL shape its equality rule missed.

Pins: navigation (section + group expand for the folder URL, group
present) and docsNavClass (folder URL highlights the Overview item,
normalization symmetric, file pages keep their highlight, no
cross-highlighting).
2026-11-01 16:34:25 -05:00
John O'Keefe a4dc03984c feat(docs): "?" help affordance on every filter mount + docs loader fixes
The filter manual (1ed1602e) was reachable only by knowing /docs
already existed — nothing in the UI pointed at it (the parked manual
plan's open decision). Every filter-builder mount now carries a "?"
in its header linking to the guide (opens in a new tab so drawer and
editor state survive): the All Books drawer and the collection rules
page — the two mounts sharing FilterBuilderRows. The docs home
indexes the manual (guide, cookbook, generated field reference).

Two docs-loader fixes surfaced by pinning this:
- Folder URLs resolve to their index page: /docs/user/filters now
  serves user/filters/index.md (the manual is a folder: guide +
  cookbook + generated reference); previously only root /docs had
  index handling.
- The docs folder path is resolved by walking upward (bounded):
  `go test` runs test binaries from the PACKAGE directory, so the
  relative "docs" path resolved to a folder that didn't exist there
  and every /docs route 404'd in tests while working in prod —
  found by the new pin, fixed so tests exercise the docs routes
  exactly as prod serves them.

Pins: TestFilterHelpAffordance (folder URL serves the guide; drawer
and rules pages carry the link). internal/docs suite + full suite
green (239s).
2026-11-01 16:22:35 -05:00
John O'Keefe 1ed1602e70 docs(filters): user manual — guide, cookbook, generated field reference
The filter manual (docs/user/filters/), folded in from the parked plan
now that the UI matches the backend (group ALL/ANY header toggle,
2344f568):

- index.md — the guide: the three homes of filters (drawer/saved
  filters, smart collections, dashboard sections), the books/episodes
  scope door, rule anatomy, value picking (chips with x, live counts
  under other rules), GROUPS via the new header toggle (+ the row
  chips as the fine-tuning tool), the live match count, today's
  defaults (reversed listening order, family-lens scoping,
  un-downloaded episodes), saving and shareable views.
- cookbook.md — seven exact-clicks recipes (born-reversed briefing,
  OR-across-authors, big-unread-fantasy, downloaded-unplayed,
  new-arrivals, dashboard shelf, shareable views). Every claim
  cross-checked against the generated reference — which caught the
  one wrong operator label in my first draft ("within last" vs the
  real "within the last"), the drift protection working as designed.
- fields.md — GENERATED from FilterFieldsPayload by
  TestFieldReferenceDocIsCurrent: the drift test fails the build if
  the registry ever changes without regenerating the docs (user
  decision: docs forced to match working code; FILTER_DOCS_REGEN=1
  regenerates).
- searching-and-filtering.md cross-links to the folder.
2026-11-01 15:46:34 -05:00
John O'Keefe 2344f5686a feat(filter-builder): the group header is the ALL/ANY switch
The group header ("MATCH"/"GROUP") was a dead label while the engine
honored group modes all along — buildGroupClause parenthesizes nested
groups and joins each by its own mode, and validation accepted
all/any from day one. The only thing missing was the UI: + Group
birthed ALL groups and no control anywhere could flip one, so the
user's target structures (GROUP(GROUP(... or ...) ...) — 3-level
mixed-mode nesting) were constructible only through the invisible
row-level chips, and standalone ANY-groups not at all (2026-11-01
user report: "MATCH cannot be clicked").

- The header is now the control: MATCH ALL ⇄ MATCH ANY (root — a
  synthetic header row, since the root was never projected and its
  mode was invisible too), GROUP ALL ⇄ GROUP ANY (nested). ANY is
  accented; aria-pressed carries the state. Labels are path-based
  (root reads Match, explicit groups read Group) instead of
  depth-based, which previously mislabeled top-level groups.
- The row-level chips are untouched — they mix AND/OR inside a group
  (A AND (B OR C)), which a global mode toggle cannot express; the
  header is the discoverable entry point, the chips the refinement.
- Dropdown audit (the "would it bug out" check): suggestTree is
  mode-generic — root-ANY drops group siblings, sibling ANY-groups
  survive into the constraint with their mode intact, empty groups
  never emit (no 400s) — now pinned. Deep-nesting Go pin: a 3-level
  mixed-mode tree evaluated through composed search + the suggestion
  endpoint (200, never the empty-group 400). 192 web tests green.
2026-11-01 15:43:52 -05:00
John O'Keefe 5fb80f82ed test(podcasts): the briefing acceptance plays the born-reversed order
Release / build-and-push (push) Successful in 3m32s
The §0-item-2 acceptance pin predates the chain-order system and
assumed the native default: it started the chain at feed position 1
and expected a forward hop. With the born-reversed default (d56031f3),
the page's first card is feed position 5 and the chain runs 5 → 1 —
the acceptance's MEANING is unchanged (play from the first card you
see, chained back-to-back within the live briefing set); the fixture
card it starts from flipped accordingly. Changelogged.

This was the only failure in the full-suite validation run (154s,
green) — the first whole-suite pass across today's four units
(chips, label endpoint, apply-path seed, born-reversed acceptance).
2026-11-01 13:55:49 -05:00
John O'Keefe 57bc0e9dd4 feat(collections): the rules-Apply path seeds the reversed default too
The creation seed (d56031f3) covered born-smart collections; a STATIC
collection that becomes smart through the rules editor's Apply landed
without any curated order — its dropdown stayed "Feed order" while
every other podcast smart collection opened reversed. Same decision,
same guardrails (2026-11-01 user approved closing this gap): a PUT
carrying an episodes-scope tree seeds chain_order=reverse only when
neither the request NOR the stored view_settings names one — a
deliberate native (client-sent or saved) is never clobbered, and
books-scope trees seed nothing.

Pins: apply-seeds-when-unordered, respects-stored-native,
respects-client-native (TestSmartCollectionBornReversed now covers
both seed paths); changelogged in contract_pins.
2026-11-01 13:44:23 -05:00
John O'Keefe 96a40f7d88 feat(filter): label endpoint names id values for client-held trees
The SSR embed (65f257f3) covers trees the server renders; one path
still fell through to the flawed fallback — applying a SAVED filter
from a cold bookshelf. That page was rendered before any filter
existed (nothing embedded), and the fallback reused the suggest facet,
whose rows are MEDIA-CONSTRAINED: "feed in [A,B,C] AND title contains
Chapter" labeled only the feeds with a matching episode (the exact
live repro from the original bug report).

- GET /api/filter/labels?field=X&ids=a,b,c resolves names straight
  from the entity tables via the shared ResolveFieldLabels core
  (extracted from FilterTreeLabels): no media join, no tree
  constraint. RLS/visibility ride the request identity — a
  zero-episode subscribed feed resolves its title (pinned; the facet
  path structurally could not), an unsubscribed feed id stays unnamed
  (pinned), non-id fields are 400 (pinned), ids cap at 100.
- Client: resolveIdLabels/resolveLabelsAsync use ONLY the endpoint;
  the quiet suggest-fetch mode is deleted (its only caller was the
  flawed fallback). The saved-filter apply flow resolves through the
  endpoint and rebuilds the chips bar when labels land — chips render
  raw ids only while the round trip is in flight, never stuck.
- 188 web tests green; Go endpoint pins + filter/episode slices green;
  contract_pins documents the endpoint and the fallback removal.
2026-11-01 13:40:25 -05:00
John O'Keefe a20741ccc9 feat(filter-builder): multi-pick values render as removable chips
The id-kind value cells (feed/library/collection/added_by) rendered
their picks as one comma-joined string inside a 9rem-wide input — you
saw the first label and nothing else, and reading 3-5 picks meant
scrolling inside a tiny box (worst on mobile, user request 2026-11-01).

Id-kind cells now render a chipbox: each picked value is a chip (label
truncated with a hover title, removable via an X button with a finger-
sized tap target), the box flex-wraps and grows vertically instead of
clipping, and the inline input stays at the end for typing/searching —
including the Backspace-on-empty-removes-last-chip affordance. Text/
number/date cells keep today's single input; the value menu is
unchanged (it never offers an already-picked value, so the chip X is
the faster removal path, not a new one).

Presentation only: the stored wire is still one comma-joined value per
rule; matching, menus, apply, and label resolution are untouched. Pins
moved from valueCellText (now text-cells-only) to the chip model
(idChipsFor/idDraftFor) and cover removal order, last-chip removal, and
Backspace; 187 web tests green.
2026-11-01 13:33:34 -05:00
John O'Keefe d56031f334 feat(collections): new podcast smart collections are BORN reversed
Per user request, same shape as 0e29eff7 — a default flip, no internal
logic changes: POST /api/collections with an episodes-scope filter_tree
now seeds view_settings.chain_order = "reverse" on the new row, so the
collection lands with "Feed order (reversed)" selected in the detail
header's dropdown and the chain/page order follows the stored value as
if picked. Books-scope smart collections and statics get nothing
seeded; an explicit client chain_order is never clobbered; existing
collections are untouched (the seed exists only at creation).

Pins: TestSmartCollectionBornReversed (episodes seeded, explicit keep,
books-scope and static no-seed); TestEpisodeCollectionsFilterTree's
native expectations flip to the born-reversed reality (changelogged).
One misplaced pin from 81e54f89 corrected: the API envelope's match
list is not chain-ordered and never was — order pins live on the SSR
page and reader chain.
2026-11-01 11:53:24 -05:00
John O'Keefe 0e29eff7b7 feat(podcasts): unset listening order defaults to reversed (audiobook-first)
The per-feed listening order — the Order dropdown on the podcast page
and player — resolved its UNSET state to "native": feed document order,
which runs newest-first for classic RSS. This platform is audiobook-
first, so native started every book at its LAST chapter (verified on
live data: 7th Son position 1 = Bonus Episode #2, positions descending
through the chapters).

The unset fallback flips to "reverse" at every resolution site of that
ONE setting — the podcast page's list + dropdown (podcastOrderForFeed),
the player's feed chain (reader.go), and the download queue
(orderOverrideFor) — so the dropdown shows reversed selected, the page
renders in that order, and play/download follow. Stored overrides are
untouched (native stays a valid savable choice); no ordering semantics
changed; collections are untouched.

Pins: the flipped native expectation is changelogged in contract_pins;
new pins cover the sequence config carrying reverse, feed position 1
playing last, and the page dropdown rendering reverse selected for an
unset feed.
2026-11-01 11:46:14 -05:00
John O'Keefe 65f257f377 fix(filter-builder): id labels resolve at render — refresh keeps names
Refresh showed raw uuids in id-kind value cells (feed/library/
collection/added_by). Two defects, one story:

1. Only ids persist in filter trees; the client's id→label cache dies
   with the page. The quiet re-resolution fetch reused the suggest
   facet, whose rows are MEDIA-CONSTRAINED (INNER JOIN media_items +
   the tree's sibling rules as a constraint) — so an id whose media
   doesn't match got no row and no label. Live repro: "feed in [A,B,C]
   AND title contains Chapter" labeled one feed of three (live-request
   evidence: 200 with total:1). A label is a property of the entity
   row, not of what currently matches.

   Fix: pages that render a tree resolve labels SERVER-SIDE at render
   and embed the map on the mount (data-id-labels) — the collection
   editor (stored tree) and the bookshelf (URL qf). New
   SearchService.FilterTreeLabels reads the entity tables with no
   media join and no tree constraint; scoping rides the request
   identity through the scoped handle (podcast_feeds/collections RLS —
   an invisible id resolves to nothing; pinned), libraries mirror the
   facet's visibility join. A feed with ZERO episodes resolves its
   title — pinned; that case was structurally impossible before.

2. The bookshelf drawer never hydrated at page load at all: the only
   load-time hydrate calls live in the PARENT's x-init
   (initBookshelf), and Alpine initializes parents before nested
   components — builderData() was null there, so hydrateFromForm
   no-oped and a URL-qf refresh left the drawer with an empty seeded
   rule while the grid stayed filtered. The drawer now hydrates in its
   OWN init when the mount carries no data-tree; the init-order
   contract is pinned in vitest (185/185).

The quiet suggest fetch remains only as a fallback for trees the SSR
never saw; embedded labels make it a no-op on refresh. Interactive
menus are untouched (their constrained, count-bearing behavior is
correct for choosing).

Pins: TestRulesPageEmbedsIdLabels (zero-episode feed labels at render,
bookshelf qf library label, hidden library NOT labeled);
filter/episode-tree/search-contract/RLS/playlist container slices
green; contract_pins entry documents the embed contract.
2026-11-01 10:44:48 -05:00
John O'Keefe c448fa438f fix(filter-builder): one operator name per field (Option A); drawer ids resolve on refresh
The is/in question, settled per user decision: they were exact
synonyms (feed's clause compiles is/is_not and in/not_in to the same
ANY), so the vocabulary collapses instead of being explained.

- Registry: feed's offered ops are in/isn't-in (+has/missing);
  legacyFieldOps keeps is/is_not ACCEPTED at parse forever — every
  stored tree and saved filter from before the collapse parses and
  evaluates unchanged. Library keeps is/isn't (its only names);
  collection's genuinely distinct operators are untouched.
- Client: id-kind cells are uniform — every operator on an id field
  accepts a set, so all id cells say "pick one or more" and accumulate
  picks. The per-operator placeholder/pick branching is gone (it also
  never fired: the registry types is as Values:"many").
- The drawer-refresh id fix rides along: hydrateFromForm now calls
  resolveIdLabels, so a page refresh with an active saved filter
  resolves stored ids to names in the bookshelf drawer (the collection
  rules page already did at init).

Pins: feed payload omits the synonyms while legacy feed is/is_not
trees parse (Go unit); uniform accumulate + placeholder (vitest);
menu-open regression and hydrate-resolution pins kept. Web 183/183;
services, filter + episode-tree + search/collections contract slices
green (full suite skipped per user — vocabulary + UI-layer change,
engine paths pinned by the targeted slices).
2026-11-01 01:16:20 -04:00
John O'Keefe 81e54f89b2 fix(collections): the order select re-orders the PAGE — visible order = play order
The detail header's listening-order select persisted fine and the
reader chain honored it, but the page's card list never applied
chain_order (it kept the composed query's title order) — so flipping
the select changed nothing visible, and Play as Sequence launches from
the FIRST CARD ON THE PAGE, making the played start (and the perceived
order) disagree with the curated setting (2026-11-01 user report on
the smart podcast page).

- Smart episode collections: the page's match list re-orders through
  OrderEpisodeMedia (the same OrderEpisodes comparator the sequence
  producer uses — §10 R2's single source of order truth) before card
  building. Books-scope matches keep title order.
- Static episode playlists: the sequence now honors the curated order
  too — native keeps the manual position order (SQL), reverse flips
  it, oldest/newest re-key on publication date with feed position as
  tiebreak. Previously statics ignored chain_order entirely while the
  select rendered on their pages.

Pins: native page order (feed positions) and the reverse flip
re-ordering the SSR cards, asserted in the curated-order subtest
alongside the existing reader-chain pins. Podcast/playlist/audiobook/
RLS/dashboard/contract slices green.
2026-11-01 00:49:04 -04:00
John O'Keefe 178b1f30c5 fix(filter-builder): menu opens to the whole list again; arity-aware cells
Regression from the id-label resolution (09f8f087): opening an id-kind
value menu carried the STORED ids as the typed filter, and the new
id-exact-match narrowed the menu to exactly the already-picked rows —
nothing else was visible, so "can't add more than one" (and clicking
the lone visible row unpicked it). The ids now ride as the typed
lookup ONLY in quiet mode (label resolution); a real menu open browses
(blank) or filters by the typed NAME draft.

The multi-value affordance is now ARITY-AWARE, per user request: the
op decides how many values the cell takes, and both the hint and the
pick behavior follow it — "in" says "pick one or more" and toggles
ids into the comma list; "is" says "pick one" and REPLACES the value.
Changing the operator updates the hint in place.

Pins: menu-open after a pick must not carry the stored ids (the
regression), one-arity pick replaces instead of toggling, and the
placeholder follows the op's arity. 38 filter-builder vitest cases;
web suite 183/183; container filter + episode-tree slices green.
2026-11-01 00:30:41 -04:00
John O'Keefe cce488b76f fix(filter-builder): multi-pick id values matched nothing; hint the multi boxes
Comma-joined multi-picks matched ZERO: clauseFeed/clauseLibrary/
clauseCollection parsed each rule value as ONE uuid, but the builder's
pick loop stores several picks as a single comma-joined value
(["id1,id2"]) — uuid.Parse failed on the joined string, the id list
came back empty, and "feeds in [A, B]" matched no episodes (one pick
worked, which is why the briefing recipe survived). parseUUIDValues
now splits every value on commas (trimming) before parsing, accepting
both the builder's joined shape and hand-written separate elements —
same leniency the suggest-side id lookup already has.

The multi-value cells now say so: id-kind value inputs get the
placeholder "pick one or more" (the only boxes on the page that accept
several values; every other cell replaces its value).

Pins: comma_joined_multi_feed_matches_both — a tree collection built
with the exact comma-joined wire the client sends, asserting BOTH
feeds' episodes match. Filter-builder vitest 35/35, container filter +
episode-tree slices green.
2026-11-01 00:20:31 -04:00
John O'Keefe 09f8f0875f fix(filter-builder): id labels survive Apply — stored ids resolve to names
The library cell reverted to the raw uuid after Apply: the apply flow
reloads the page, the SSR-preloaded tree re-ingests, and idLabels —
populated only by suggestion PICKS — starts empty, so valueCellText
falls back to the id. Same on any fresh load of a stored id-rule.

Two halves:

- Server: the id-source suggest query's typed filter (library/
  collection/added_by/feed) now also exact-matches a comma-separated
  ID list alongside the name ILIKE — so a suggest call with the stored
  ids returns their labeled rows. No new endpoint; the menu and the
  resolver share one surface.

- Client: fetchSuggestions gains a QUIET mode (fills idLabels, touches
  no menu state), id rows fall back to their stored ids as the typed
  lookup when no draft is present, and init() calls resolveIdLabels()
  after tree ingest — one quiet fetch per id-kind rule resolves every
  stored id to its name from the first paint after reload.

Pins: the Go side (suggest with a library's UUID returns the row with
the library NAME as display), the client side (resolveIdLabels fills
labels, the cell renders the name, no menu opens). 35 filter-builder
vitest cases green; container filter slice green.
2026-11-01 00:11:57 -04:00
John O'Keefe ed42111df1 fix(filter-builder): OR-aware suggest constraints (user correction)
The previous fix was too blunt: under OR it sent NO constraint tree at
all, so "library = ebooks" stopped narrowing the author menu the
moment an OR-connected author rule appeared. The user spec is subtler:

  library = ebooks AND (author = Lewis Carroll OR author = ?)
  → the menu shows EBOOK authors, with Lewis Carroll OFF the list.

suggestTree now walks root → edited rule and builds one conjunctive
chain:

- ALL-group siblings stay (AND narrows: the ebook scope persists);
- ANY-group siblings drop — they are independent alternatives under
  OR and must not narrow;
- EXCEPT a same-field ANY sibling, whose picked values NEGATE into
  the chain (contains → not_contains, is → is_not, in → not_in): the
  picked value leaves the menu, everything else in scope stays;
- an ALREADY-NEGATED sibling picks nothing to take off, so it drops
  rather than flipping positive (a positive flip would narrow);
- a field without a negation twin falls back to dropping;
- incomplete rules never constrain (not filters yet), and the edited
  rule itself never constrains its own menu.

Pins: the user's exact tree (ebook scope kept + Lewis Carroll negated
off), the root-OR variant (different-field sibling drops, same-field
negates), the twinless fallback, plus the existing AND/OR cases —
34 filter-builder vitest cases green, container filter slice green
(TestFilterSuggestionsUnderRules unaffected: the server contract is
unchanged, only which qf the client composes).
2026-10-31 23:48:04 -04:00
John O'Keefe c52b514036 chore: formatting sweep — vp fmt on drifted web files, templ regen
Pre-existing format drift in seven web/src files (blank-line and
indent normalization by vp fmt) plus templ generate normalization
across the generated _templ.go files; both swept up while committing
the filter-builder fix. No behavior changes.
2026-10-31 23:27:21 -04:00
John O'Keefe 28efaf3fe9 fix(filter-builder): id cells showed raw ids; OR mode starved the value menu
Two user-reported builder defects:

1. Id-kind value cells (library/collection/feed/added_by) rendered the
   stored UUIDs in the input box. The menu offered names (s.display)
   and picking stored the id correctly — but the cell bound
   rule.values.join(',') raw. The cell now renders through
   valueCellText: idLabels give the NAMES; typing drafts a name filter
   in idDrafts (the stored values stay ids — the clause matches ids —
   and are updated only by picking). Text/number/days cells are
   unchanged.

2. The value menu ignored the connective: fetchSuggestions always sent
   the sibling rules as the qf constraint, so with "Author contains
   Lewis Carroll" present, flipping to OR still starved the author
   menu down to Lewis Carroll. Under OR the siblings are independent
   alternatives — a new rule's candidates must not be narrowed by
   them. pathUnderAll now checks the edited rule's group path: under
   AND all the way up, siblings constrain as before (helpful
   narrowing); under any OR on the path, NO tree rides and the menu
   browses the whole scope.

Server contract unchanged — the suggest endpoint already treats a
missing qf as an unconstrained browse; the fix is client-side
mode-awareness. Pins: 6 new vitest cases (AND sends siblings, OR sends
none, id label display, draft typing never touches stored ids, pick
toggles + relabels, text passthrough).
2026-10-31 23:27:21 -04:00
John O'Keefe 7c7e282e79 feat(dashboard): custom-section builder saves again — the flagged tree migration
Archaeology, prompted by the user asking when it broke: the builder's
save NEVER worked. The page was born (2026-02-19, a92bf99a) posting
auto_assign_rules as a JSON-encoded STRING into an endpoint that has
bound []Rule since its creation (2026-01-31, 6495cc2c), plus fields
(manual_book_ids, match_type, library_id, show_on_dashboard) the
endpoint never accepted. The preview button hit a real endpoint, so
the page looked alive while Save always failed at request binding.
Verified live before this change: the page's exact payload 400'd
"invalid request" against the unmodified server.

The fix adapts the builder's payload at write time — the legacy rules
vocabulary converts to a filter tree (RulesToFilterTree restored from
the retirement commit as the single write path, unit test restored
with it):

- match_type seeds the converted tree's root mode (any default).
- manual_book_ids attach to the created collection after create
  (unparsable ids skipped — the AddBooks leniency).
- show_on_dashboard persists (new create field).
- Converted trees validate under ParseFilterTree: an unhonorable rule
  is a 400 at write naming the problem, never a stored 500 at render.

Dashboard sections: smart user sections now evaluate their tree LIVE —
GetUserCollectionItems merges stored membership with the composed
engine's matches (deduped, library-scoped, capped at the section
limit). This exposed a REAL production wiring bug: every production
NewDashboardService call omitted the search service, so tree
evaluation through the dashboard could never have worked (the test
harness wired it correctly — the gap was production-only and latent,
because nothing in the dashboard evaluated trees before this
migration). The dashboard handler and both inline sites now receive
the search service, and evaluation failures log instead of silently
emptying a section.

Supersedes the same-day loud-400 stance for the builder's payload
(contract_pins migration entry); custom-section-builder.md documents
the save contract; the create_collection API doc gains the adapted
fields. New TestCustomSectionBuilderSave/BadRule pin the payload →
tree → dashboard-render path end to end. Full container suite green
(155s).
2026-10-31 19:40:43 -04:00
John O'Keefe a86bdac87e refactor(collections): retire the legacy rules surface — tree-only storage
The pre-tree rules machinery is deleted: no row ever carried a rules
array or a non-default match mode (verified in the dev DB), the web
never read the envelope keys, and the Android app consumes none of it.
Dead code gets no documentation.

Removed:
- PUT /api/collections/:id/match-mode — endpoint, route, and the
  UpdateCollectionMatchMode query. The tree's root mode owns any|all.
- auto_assign_rules / rule_match_mode from every envelope
  (create/list/detail/update), from the create/update request shapes,
  and from the schema: both columns DROPPED (schema.sql carries
  idempotent DROP COLUMN IF EXISTS heals for existing DBs; sqlc
  regenerated).
- The rules CRUD service layer (AddRule/SetRuleEnabled/RemoveRule +
  validateRule + UpdateCollectionRulesJSON), ParseRules /
  EnabledRules / IsSmartCollection, RulesToFilterTree (+ the SSR
  preload branch), the legacy branch of EvaluateSmartMembership, and
  SmartEvalOptions.MatchMode. IsCollectionSmart = tree presence;
  create-path isSmart = collection_type=smart OR a filter_tree.

Kept (live consumers): POST /api/collections/preview still evaluates
rules payloads in memory (the custom-section builder's preview), and
include_auto stays on the list (the Android app sends it).

The custom-section builder's SAVE was already broken — its
stringified auto_assign_rules payload failed request binding (probed
live: 400 invalid request). Create now rejects that payload loudly
with a 400 naming the retirement, instead of silently creating a
hollow static section; custom-section-builder.md carries the flag.
The builder's tree migration remains the flagged follow-up.

Test-side (asymmetry rule — deleted behavior, deleted tests):
TestPodcastSmartCollections rewritten onto trees (mode lives in the
tree root), match-mode subtests and tree_wins_over_legacy_rules
deleted, TestRulesToFilterTree deleted, contract-pin envelope keys
retracted per the contract_pins 2026-10-31 retirement entry. Mirrors
hand-synced: openapi.yaml, bruno create/update, docs/api/*.md,
docs/schema.go, api.d.ts. Full container suite green (155s).
2026-10-31 19:06:48 -04:00
John O'Keefe ab98015190 feat(collections): RLS ownership enforcement at the DB layer
collections + collection_items join the RLS-governed tables, same
doctrine as the media_items family lens (2026-10-29). Policies route
through two PURE predicate functions (app_can_read_collection /
app_can_write_collection) that never query collections — no policy
recursion under FORCE RLS — so a future sharing model is one EXISTS
branch inside the functions, not a schema re-touch. Reads: owner or
admin; writes: owner, admin escape for SYSTEM collections only.

Why: the write path had no app-level ownership gate on Update/Delete/
AddBooks — any authenticated user could mutate another user's
collection by id. The DB is now the enforcement of record; existing
app-level gates (match-mode, reorder, view-settings) stay as
defense-in-depth.

Behavior changes (contract_pins 2026-10-31):
- cross-user GET detail: 200 -> 404 (row invisible)
- cross-user PUT update: silent success -> 404 (ErrNoRows mapping;
  service wrap fixed %v -> %w so errors.Is sees pgx.ErrNoRows)
- cross-user POST books: silent success -> 404
- cross-user DELETE: 204, now a true DB no-op
- anonymous sees nothing; admin persona unchanged

Bootstrap: registration seeds system collections BEFORE the JWT
exists — CreateDefaultCollectionsForUser declares the new user's
identity (rls.WithUser), the same fix mirrored in the test harness
(createDefaultCollectionsForUser owner-scoped; collection sweeps run
under the owner's identity).

Tests: new TestCollectionsRLS pins the cross-user matrix end-to-end
(404 detail/update/add/view-settings, 204 no-op delete, admin escape,
owner positive control, registration seeding under RLS). Harness
fixture writes to non-system collections now run as the row's OWNER
(scopeExecAs/ownerSeedCtx) — the admin write-escape covers system
rows only, and bare-ctx pool reads of collections see nothing.
Filter/playlist/audiobook/scan-state fixtures converted. Full
container suite green (159s).
2026-10-31 18:30:02 -04:00
John O'Keefe aaf57a66a2 fix(ui): cookie-authed users' writes silently stranded behind bearer gates
THE CLASS: the /api JWT middleware's TokenLookup is
"cookie:token,header:Authorization:Bearer" — the token cookie always
rides same-origin fetches, so a signed-in user never needs the
localStorage bearer. But a dozen call sites gated their fetch on
`localStorage.getItem("token")` and early-returned when absent. The
global 401 interceptor CLEARS that localStorage entry on any session
rotation/blip — after which every gated write silently did nothing:
theme changes reverted on reload (the reported "can no longer change
themes", on top of the interpolation bug d5dbaa48 fixed), chain-order
selects, collection deletion, Add-to-collection submits, filter
save/load/delete, conflict actions, linking actions, stats charts,
tag suggestions, device management, admin scanner actions — all dead
for perfectly authenticated cookie users.

Fix: storage.ts exports authHeaders() (bearer when present, cookie
carries otherwise) and every gate/header site now uses it — theme.ts,
collections.ts (htmx auth, doRemoveBook/doBulkRemove, setChainOrder),
bookPicker submit, filter_builder suggestions + match count,
collection-rules apply hook, bookshelf save/load/delete filter,
conflicts x4, linking x3, admin scanner actions + polls (requireToken
removed — its "Session expired" toast fired for cookie users too),
dashboard preferences/sections, custom-section-builder, header
scanner poll, stats x3, tag suggestions, profile delete-account
(which also wrongly redirected cookie users to /login), and
device-management x4. Reads keep their graceful-empty behavior; the
bearers still ride along when present.

Pinned: the knob-matrix theme spec now REMOVES localStorage.token and
asserts the theme PUT still fires (cookie-only) and the class flips —
the exact strand that started this.

Found by noticing the panel browser's Nord click switched the class
but produced no PUT: the persistence half was gated on a token the
401 interceptor had cleared.
2026-10-31 17:02:44 -04:00
John O'Keefe 744d33e13f fix(search): keep the empty-qf 400 at the wire
The empty-tree grammar relaxation (create-modal episodes seed) must not
leak into the search deep-link contract: qf={"mode":"all","children":[]}
as a QUERY would silently mean "match everything". The seed's meaning —
a rules-less collection matching nothing — lives in the stored tree and
its composers; the query entry point now rejects a rule-less tree
explicitly, preserving the pinned 400 that TestFilterQFValidationAndPrecedence
guards (the test caught the leak during this round's full-suite run).
2026-10-31 15:56:23 -04:00
John O'Keefe d6619cd0e1 test(ui): the knob matrix — every control the round-4 defects lived behind
Six specs driving the user-reported controls the way a human does,
encoding the sweep rules COVERAGE.md now states: menus/modals assert
VISIBILITY (never DOM text — hidden menus' text is why the 2026-10-30
panel sweep certified dead controls), geometry asserts the z-ladder
via elementFromPoint and viewport containment via boundingBox, every
click must produce an observable outcome (PUT fired, class flipped,
chip text swapped) and zero new console problems — the silent
CSP-throw family (theme buttons, connective chip, invisible op menu)
now fails a test instead of surviving to a user's mouse.

Covers: theme picker (interpolation regression from eb57b720),
pencil-glyph vs card-body contract, builder field menu / op menu
(full non-empty vocabulary) / connective both directions, the
Smart→Episodes create-modal seed, the picker overlay's ladder and
height, and the chain-order select's persistence round-trip.

Fixtures self-create/self-delete under test-prefixed names; localStorage
token + selectedLibrary=__all__ are seeded because the API login
establishes only the cookie; run the folder with --workers=1 (the login
route rate-limits and all suites share testuser — a parallel worker's
login revokes another's mid-run).
2026-10-31 15:40:21 -04:00
John O'Keefe 8aa66a30fc docs(api): sync mirrors with the retired rules CRUD and the chain-order endpoint
Three mirrors had drifted:

- The rules-endpoint retirement (4f71eda6) deleted the routes but not
  their mirrors: removed docs/developer/api/collections/
  {add_auto_assign_rule,remove_auto_assign_rule,test_rule,update_rule}
  .md + their bruno twins, and pruned /api/collections/test-rules,
  /{id}/rules, /{id}/rules/{ruleId} from the generated openapi spec
  (hand-edited — regenerating with -update would wipe hand-authored
  bruno suites that predate the docs mirrors).
- New endpoint PUT /api/collections/:id/view-settings gets a doc page
  + schema-registry entry + bruno mirror (repo convention: the route
  and its docs land together).
- 54 pre-existing TestDocsMatchRoutes failures: the media-item
  endpoints emit the 16 episode/download fields (source_feed_id,
  feed_position, download_state, enclosure_url, hosts/guests, …) and
  libraries emit purpose/allow_member_feeds, but the doc examples
  were never extended — the package only runs on the host, so the
  container suite never caught it. Examples now carry every key the
  handlers emit; internal/docs is fully green.
2026-10-31 15:40:21 -04:00
John O'Keefe 4410a994ef fix(ui): silence the two benign cancelled-transition rejections
Round-4 console hygiene: fast navigation rejects with "AbortError:
Transition was skipped" (the browser's MPA view transitions —
@view-transition navigation:auto — when a navigation interrupts a
running crossfade) and Alpine's x-transition hide rejects with
{isFromCancelledTransition: true} when a re-show supersedes an
out-phase. Both are races the user cannot lose anything in, but they
print console errors on every quick click — and the knob matrix's
zero-console-error tripwire (the thing that catches silent CSP death)
depends on a clean console. A narrow global gate swallows exactly
these two shapes; every other rejection still reports.
2026-10-31 15:40:21 -04:00
John O'Keefe aa9bd950f9 fix(collections): gate the chain-order endpoint by ownership
PUT /api/collections/:id/view-settings writes the row; it now demands
UserOwnsCollection like its sibling config mutations (SetMatchMode,
ReorderItems) — otherwise any signed-in user could flip another
user's curated listening order. Discovered while documenting the
endpoint: the sibling pattern exists precisely because the main
PUT/DELETE routes lack it (their gap is noted for follow-up, not
expanded here).
2026-10-31 15:40:21 -04:00
John O'Keefe 79b47c9680 fix(collections): Close/Cancel removed the hidden confirm dialog, not the modal
closeCollectionModal picked document.querySelector(".fixed.inset-0") —
the FIRST overlay in DOM order, which is the sitewide #confirm-modal
that the header renders (hidden, display:none, but present). The real
create/edit modal stayed open: every Close and Cancel click on the
collection modals did nothing. Caught by the knob-matrix spec — the
pencil-glyph case clicked Close and the Edit modal persisted.

The buttons now pass $el and the overlay OWNING the button is closed
(closest(".fixed.inset-0")), falling back to #modal-container's child
for non-Alpine callers. Both the collection create/edit modal and the
restore-system modal take the argument.
2026-10-31 15:40:21 -04:00
John O'Keefe 21142cae5f chore(router): remove the CHAINDBG probe — the curated-order path is browser-verified
The debug print served its purpose: the stale-binary native-order render
was an artifact of an incomplete rebuild, not code. Fresh container
resolves view_settings.chain_order and the chain plays in the curated
order (newest-first verified on a 23-episode feed with a date tie at the
tail, handled by the position tie-break).
2026-10-31 14:08:54 -04:00
John O'Keefe fd716a7dab fix(filters): the episodes-scope vocabulary buried the episode fields under book-only metadata
The scope door's first live test showed the episodes editor leading its
field menu with People (Author/Narrator/Contributor) and Publishing —
book-only fields that can never match an episode row — while the fields
the scope exists for (Feed, Downloaded, Played) sat below the fold.
Root cause: the registry's book fields carry no Scopes restriction
(nil = all scopes), a leftover from before the episode fields existed.

35 unambiguous book-only fields (people, publishing metadata, topics,
series/comics, identifiers, cover, reading-specific statuses) are now
tagged Scopes:books. Title, description, published dates, language,
file facts, explicit, the my-reading group (listening progress is
real), and collection stay dual-scope. Parse continues to accept the
hidden fields everywhere (their composed clauses simply match nothing
on episode rows) — this governs the AUTHORING surface, not the
grammar.

TestFilterParseValidation's empty-root rejection updated to the new
contract (empty root legal — the seed; nested empty groups still
invalid), and TestEpisodesScopeHidesBookOnlyFields pins both scopes'
vocabulary.
2026-10-31 13:58:42 -04:00
John O'Keefe 536fb4794c fix(collections): the create modal's seed POST 400'd — echo cannot bind a form string into an any-typed field
The first real-browser create of an Episodes-scope collection failed
with "invalid request": the modal's hx-post submits
application/x-www-form-urlencoded, and the form value for filter_tree
had to bind into CreateCollectionRequest.FilterTree (any) — echo's
form binder errors on any-typed fields instead of setting the string,
so every form carrying a tree 400'd before validation even ran. JSON
bodies (the save-filter bridge, the editor's Apply) were unaffected,
which is why no API-level or Go test caught it: only a browser posting
the real form shape exercised the transport.

Fix: the form variant binds a dedicated string field
(FilterTreeForm, form:"filter_tree") on both request structs while
FilterTree keeps the JSON tag; resolveTreePayload picks whichever
transport arrived and both ride the same parseRequestFilterTree
validation. Pinned by TestEpisodeCollectionsFormSeedCreate (form-encoded
seed → 201 → scope round-trips).
2026-10-31 13:52:40 -04:00
John O'Keefe cc0e9d7f91 feat(podcasts): the episodes authoring door + curated chain order
"Newest episodes from my selected podcasts" is now buildable in the UI,
end to end — the user could not find ANY podcast-related filter surface
because none existed: the New Collection modal could only create
book-scope smart collections, and the engine's episodes scope (item 3.1)
had no authoring door.

The scope door:
- The create modal's Smart card gains a Rules-scope segmented control
  (📚 Books / 🎧 Podcast episodes); the copy no longer claims smart
  means "match books by rules". Choosing Episodes seeds an EMPTY
  episodes tree ({"scope":"episodes","mode":"all","children":[]}) so the
  collection is born episode-scoped: the editor opens with the episode
  vocabulary (feed/downloaded/played/published date) and membership
  runs the episode engine from the first rule.
- ParseFilterTree now accepts an EMPTY ROOT (nested empty groups stay
  invalid) — the seed's legal shape. The root arrives at depth 1 by
  call convention, hence the depth>1 exemption.
- The composers define the empty-tree semantics: zero children matches
  NOTHING (ComposedLiveMedia/ComposedCount guards), mirroring
  EvaluateSmartCollection's zero-enabled-rules convention. Without the
  guard the composed query degrades to the bare scope head and a fresh
  collection would swallow every episode in scope — pinned by
  TestEpisodeCollectionsEmptySeedMatchesNothing (envelope book_count 0)
  and TestEmptyRootTreeSeedsEpisodesScope.

The curated chain order (plan §10 R2, user need: the briefing plays
NEWEST-first):
- view_settings.chain_order ("native"/"newest"/"oldest"/"reverse")
  stored on the collection — curated content, not a player-side knob.
- PUT /api/collections/:id/view-settings merges the key into the
  stored JSONB (a blind write would clobber the playlist toggles).
- buildSmartCollectionSequenceContext routes OrderEpisodes through
  handlers.CollectionChainOrder; the detail header's Play-as-Sequence
  gains the order select next to it (PlayCollectionButton), which
  PUTs and reloads. Pinned by chain_follows_the_curated_order
  (reverse flips the chain indexes and hops).

Caught by the new test, a latent clobber fixed: UpdateCollection
treated a NIL view_settings payload as "write NULL" — any edit that
carried no settings dropped every stored key (chain_order, playlist
toggles from API clients, imported provenance). Nil now means
untouched, the same convention filterTree already had.

Composer guards also cover ComposedCount, so the builder's live count
reads the same semantics. Tests: collectionChainOrder unit matrix,
empty-root parse unit pin, two integration pins (seed matches nothing;
curated order drives the chain and survives whole-map edits).
2026-10-31 13:39:24 -04:00
John O'Keefe d5dbaa48ea fix(ui): user-test round 4 — five browser-reported control defects
Every one of these was silent at the code level and loud in a real
browser; each fix carries its own tripwire (render pin, unit pin, or
CSP-safe rewrite) so the class cannot quietly return.

1. Theme picker dead since the CSP migration (eb57b720): the Appearance
   panel's theme buttons emitted `@click="selectTheme(opt.Name)"` as
   LITERAL text (templ gotcha #1 — quoted attribute values are never
   interpolated; `opt` is a Go loop var), so Alpine threw "Undefined
   variable: opt" on every click and no PUT /api/auth/theme ever fired.
   The wood-paneling sibling always used the correct expression form,
   which is why the panel half-worked. Fixed to the interpolated form;
   TestThemePickerHandlersAreInterpolated pins that real theme names
   reach the HTML and the raw identifier never does.

2. Filter-builder op dropdown "does nothing": the field ingest
   hardcoded `ops: []` into every field's meta while only mirroring the
   ops into the global label registry — opsFor() returned [] for EVERY
   field, so the op menu rendered zero items: an invisible menu, no
   console error (user tried author/publisher/title/subtitle, all
   equally dead). FieldMeta.ops is now the wire's op objects, opsFor()
   is a standalone exported helper, and opsForField unit tests pin the
   round-trip. Verified live: the field menu opens/closes while the op
   menu stayed shut, both with identical wiring — the difference was
   the data, not the wiring.

3. AND/OR connective chip dead: the chip carried an `if` STATEMENT in
   the Alpine attribute (`@click="if (row.chipClickable) ..."`) which
   the CSP build's evaluator rejects as a statement — the whole
   expression silently never ran. Moved the clickability check into a
   toggleConnective(row) component method; the attribute is now a plain
   method call.

4. Pencil vs card navigation race: navigateToCollection guarded with
   `event.target instanceof HTMLElement`, which is FALSE for the
   pencil glyph's SVGElement — a click landing on the glyph sailed past
   the guard and navigated while the htmx edit-modal request still
   fired (the reported "modal flashes, then the builder page"). The
   guard now uses target.closest("button") (works on SVGElement) and
   takes $event explicitly instead of the deprecated window.event.
   .icon-btn is already a 36px square, so no hit-area change needed.

5. Add Items modal under the sidebar + taller than the window: the
   picker overlay sat at z-50 UNDER the app-sidebar's z-60 (its left
   edge rendered beneath the nav), and the card had no height bound —
   header + tabs + filters + grid + footer overflow short windows with
   the footer unreachable (fixed overlay, no page scroll). The picker
   and create-modal overlays move to z-[65], both confirm dialogs to
   z-[70], and the picker card is now a flex column capped at
   max-h-[85vh] whose grids flex-fill (they grow on tall windows,
   shrink on short ones). The ladder is documented at .app-sidebar in
   input.css: sidebar 60 / overlays 65 / confirm 70 / toasts 9999.

Found by clicking every control the way a user does (panel clicks +
computed-style reads + screenshots) after the previous sweep trusted
DOM-text snapshots, which show hidden menus' text and cannot see
occlusion, stacking, or geometry at all.
2026-10-31 13:14:05 -04:00
John O'Keefe 8aec80cbb7 docs(ui): record the 2026-10-30 browser sweep against coverage notes
Marks the sweep-candidate list as executed (every knob driven in a real
browser), preserves the four defect classes the sweep fixed so the next
agent does not re-learn them the hard way, and pins the panel-vs-
Playwright limitation (value assignment without change events) that any
future automated spec of the htmx-triggered controls must work around.
2026-10-30 20:51:26 -04:00
John O'Keefe 94985adb5e fix(collections): browser-verification pass over the unified builder/editor
The real-browser sweep (the gotcha classes' native habitat — CSP refusals
fail SILENTLY at build/test time) found four defects, all in the item
3.3/3.4 surfaces:

- Shared builder rows used Alpine attribute expressions that the CSP
  parser rejects outright: backtick template literals in :style, the
  ?. optional chain in :placeholder/x-if, and an if-STATEMENT in a
  @click.outside. Rewritten as string concat plus two component methods
  (fieldIsDays, dismissSuggestions). Until this fix every drawer open
  threw a wall of "CSP Parser Error" console noise and the days-value
  affordance never rendered.
- "2 bookss match": the count noun is interpolated into "<n> <noun>s
  match", so callers must pass the SINGULAR ("book"/"item").
- The rules editor page received its fields/tree payloads from the
  route as already-JSON-encoded strings and wrapped them in JSONArg
  AGAIN — double-encoded, so JSON.parse yields a string and the editor
  loaded with NO vocabulary and NO prefill. The route now emits raw
  JSON into the data attributes (single encode).
- Apply was silently inert: the hook store round-trip used
  window.Alpine?.store (optional-chained, no-op when absent) and the
  Cancel/Apply block sat outside the builder island scope for part of
  the session. Both fixed via the imported Alpine instance and moving
  the buttons inside the island; Apply now PUTs the tree end-to-end
  (verified live: prefill → edit → apply → 201 → reload → membership).

Browser-verified clean (no fixes needed): picker scope tabs + episode
grid (?scope=episodes door), selection store across swaps, Add Selected
episode membership, library-switcher partial contract (episodes visible
under All Libraries, correctly filtered out under a book library — and
now never OFFERED as a switcher option), episode cards + reorder arrows
persisting position, collection-chain player (Ep N/M, prev/next carry
?queue=collection:, order control absent in collection mode and present
+ persistent in feed mode both in player and feed page), and the
empty-tree Apply guard (400 — a static collection can never be
promoted by accident).

Notes for the next reader of these lines: the OpenChamber panel's
browser.select sets select.value without dispatching change, so htmx
change-triggers must be exercised by real events (Playwright) rather
than the panel; and one 500 was observed on the player's leave-page
progress PUT — a request whose context the navigating browser cancels
mid-write, pre-existing and benign (the immediately following save
returned 200).
2026-10-30 20:50:55 -04:00
John O'Keefe 7bf5697c71 fix(podcasts): library switcher leaked literal "continue" and the podcasts option
The D13 podcast exclusion (9a148c23) was written as a templ
`if !IsBookLibrary(...) { continue }` — but templ markup control flow
has NO continue STATEMENT: codegen emitted the word as a TEXT node
(visible junk between options on every page's library subbar) and
rendered the podcasts option anyway, defeating the exclusion. The real
browser sweep caught what every Go/API test structurally cannot:
generated markup that renders wrong yet compiles clean.

Rewritten as an inverted guard (the idiomatic templ skip). New render
pin TestLibrarySwitcherExcludesPodcasts fails on both halves of the
original leak — the literal text AND the presence of the podcasts
option — so this codegen gotcha class stays tripped-wired.
2026-10-30 20:50:38 -04:00
John O'Keefe c54430c254 fix(podcasts): code-review pass over the session's UI surfaces
Findings from the systematic gotcha-class review before the browser
pass:

- The collection smart editor's Apply derived the collection NAME from
  document.title — which parses to "Smart Collection", RENAMING the
  collection on every apply. The server now renders the real name
  (data-collection-name) and the write path refuses to proceed without
  it.
- TestRenderingPartialsRender pinned the pre-episode-collections
  empty-state copy ("No books in this collection yet.") — updated to
  the shipped label ("Nothing in this collection yet."; collections
  hold episodes now).
- The deleted handler-local rule comparators (evaluateRule/
  compareValues — removed in item 3.4's single-evaluator refactor)
  left behind two unit-test files testing the duplicates; deleted.
  Their semantics remain covered at the service level
  (TestEvaluateRules_* over FieldMatches/EvaluateRules) and
  TestTextToString (which actually pins utils.PgTextString) stays.

Everything else reviewed clean against the gotcha classes: templ
whole-expression attrs, ?={ boolean attrs, JSONArg quoting in
x-init/data attrs, Alpine CSP store paths, htmx form-encoding, the
&#34; assert escaping, and the aria-label selector contract on the
player's reload listener.
2026-10-30 19:38:39 -04:00
John O'Keefe 94bd69d22d feat(filters): save current filter as smart collection — the bridge (item 3.5)
The bookshelf's save modal grows a second action: "Save as Collection"
POSTs the current (completed, scope-stamped) tree to
/api/collections — the same validated write path every tree
collection uses — and lands you on the new collection's page. The qf
engine then drives it everywhere: the shelf's live shelf-count, the
collections page, the replay chain for episode trees. The legacy
"Save Filter" (bookmark the wire params) stays as the sibling action.

This is the plan's bridge: a book search graduated into a live shelf
with one click, authored in the ONE filter system.
2026-10-30 19:25:02 -04:00
John O'Keefe 4f71eda6be feat(podcasts): the rules page retires — the collection builder IS the filter builder (item 3.4)
The smart-collection editor at /collections/:id/rules now hosts the
SAME builder island as All-Books (FilterBuilderRows — the rows markup
extracted into one shared templ both mounts render; the shared
filterBuilderExtra component). One vocabulary, one engine, one row UI;
the collection differences are exactly three: the payload is the
collection's scope (episode trees get the episode fields — books
trees hide them), Apply writes the tree to the collection (PUT
filter_tree through the validated write path), and a legacy rules
array preloads as its CONVERTED tree (RulesToFilterTree rendered
server-side) so the upgrade lands at the first Apply — read-compat
never mutates data silently.

Retired with the page: the per-rule CRUD endpoints and test-rules
(their handler bodies, routes, api-docs rows, and the dead collections.ts
island functions — the file's LIVE halves, the collection modal/navigate/
grid-refresh, stay; the dead rules half went). match-mode endpoint and
preview survive (legacy channel + the dashboard custom-section-builder,
flagged for its own migration). Contract-pin changelog documents the
deletions per the asymmetry rule.

The builder component gains collection mounts: scopeKey (the row
universe for counts/apply), data-tree prefill, treeJSON (the apply
wire with scope riding the top level), and an apply hook (the page
owns the write; All-Books never sets one). ensureReadyRule defaults to
the scope's first field instead of hardcoding author.

Tests migrated onto trees: TestSmartCollections' live-membership /
reject-mutations / include-auto / system-collection subtests now drive
TREE collections; the deleted-endpoint subtests die with them.
2026-10-30 19:22:17 -04:00
John O'Keefe eb68672390 feat(filters): one vocabulary, server-rendered — the TS mirror retires (item 3.3)
"One filter system to maintain" now holds at the presentation layer
too: the field/op list the builder renders comes from
services.FilterFieldsPayload(scope) — the Go registry's wire face,
scope-filtered and group-ordered — rendered into the bookshelf mount
as a data attribute (templates.JSONArg), ingested once by the Alpine
component. The registry carries operator presentation (labels,
negation, arity) in FilterOpWire alongside the grammar; per-field
value-cell semantics (valueKind) derive from the existing Kind.

The hardcoded TS mirror (OPS, op(), F(), TEXT_OPS/NUM_OPS/DATE_OPS,
FIELD_GROUPS, its known drift surface) is deleted; filter_builder.ts
now ingests the wire (ingestFilterFields — malformed payloads leave
empty menus rather than client-invented rows), and the field menu's
episode fields are HIDDEN on the All-Books page for free (the books
scope payload excludes them — the plan's "hide podcasts from the
rules on the all books page" is now structural, not enforced by a
second hand-kept list).

Unit tests ingest a minimal wire fixture (the payload shape is the
contract, not the mirror); vitest 167 green, tsc + vp clean.
2026-10-30 19:07:45 -04:00
John O'Keefe 6b2125a45a feat(podcasts): smart collections ride the unified filter engine — filter_tree column (item 3.2)
collections gains filter_tree JSONB (idempotent in-place; same qf DSL
as saved filters — the scope key included). IsCollectionSmart is the
ONE detection (tree OR legacy rules), and EvaluateSmartMembership is
the ONE evaluator: tree-bearing collections run the composed engine
via ComposedLiveMedia (full media rows, so the collection surfaces
keep their episode-card stamping, feed positions for the replay
chain, and the family lens rides the mandatory head), while legacy
rule arrays keep per-item FieldMatches until rewritten — one call
surface, two storage epochs. All smart surfaces (detail JSON, counts,
detail page, reader chain) dispatch through it; the search service is
injected into the collection subsystem (variadic — main.go builds one
shared instance; the test harness mirrors it).

Write path: CreateCollection/UpdateCollection accept the tree,
validated against the engine grammar at the HANDLER (an invalid tree
is a 400, never a stored render-time 500) and exposed in the envelope
(pin widened in TestContractPin_CollectionsJSON + changelog). Update
semantics: an edit form that doesn't send a tree keeps the stored one.

RulesToFilterTree converts legacy rules + match mode at upgrade time:
episode rules map mechanically (feed→in-list, played/downloaded→
booleans, published_within→published_date+within_days), tree root
mode absorbs rule_match_mode, episode rules force the episodes scope,
and legacy starts_with/ends_with fall back to contains (documented).

Read-compat by design: nothing is migrated at boot — legacy arrays
evaluate exactly as before until the collection is rewritten.

Pinned by TestRulesToFilterTree (unit conversion) +
TestEpisodeCollectionsFilterTree (a tree collection evaluates through
the engine, the chain follows the tree's live membership, invalid
trees 400 at write, the tree wins when legacy rules coexist, and an
edit without a tree keeps it).
2026-10-30 19:02:49 -04:00
John O'Keefe 56871b65ed feat(filters): scopes + episode fields — the engine becomes the single query system (item 3.1)
The qf tree gains an optional top-level `scope` ("books" default |
"episodes" — absent = books, so every existing saved tree and legacy
client stays valid). The row head is scope-aware AND this closes a
real leak: the composed engine's head had NO podcasts exclusion, so
episodes already surfaced on All-Books qf queries (plan §9 violation —
the sqlc flat head excluded them, the composed head didn't). Books
scope now says library_type_name <> 'podcasts'; episodes scope is
source = 'podcast_episode'.

The registry fields declare their scopes (the plan's "reusable
template with conditionals" = scope-driven rendering in 3.3): episode
fields declare exactly the episodes scope and the books scope REJECTS
them at parse (the "hide podcasts from the rules on the all books
page" rule enforced server-side); books fields inside episodes trees
are allowed and honestly no-op on NULLs.

New fields (the item-2.4 rule vocabulary expressed in SQL):
- feed — KindIdentifier over podcast_feeds (RLS-governed suggestion
  source and match; unsubscribed feeds match nothing, by the engine)
- downloaded — is_true/is_false on download_state = 'downloaded'
- played — THE canonical finished predicate (viewer progress >= 0.999,
  the hide_finished definition shared with item 2.4), reading_progress
  join per viewer
- published_date — clauseDateFactory like added_at, within_days
  default op (the published_within rule's SQL form)

Engine hygiene: the stray ComposedSearch SQL debug printf is gone.

Pinned by TestFilterScopeValidation (unit: scope grammar, books×
episode-field 400s, legacy no-scope trees) and
TestFilterScopesAndEpisodeFields (integration: books head excludes
podcasts including the 404-no-results contract, episodes head is
episodes only, feed-in/downloaded/played/published-date evaluate in
SQL against a subscribed-feed fixture with a played viewer).
2026-10-30 18:19:55 -04:00
John O'Keefe bc91ce68d4 test(pins): widen whitelist for the episode-collections JSON shapes (item 2 series)
TestContractPin_CollectionsJSON tripped on the additive keys the
episode-collections work introduced — the tripwire worked exactly as
designed (additive keys must be whitelisted here AND in
docs/contract_pins.md first).

- Collections envelope gains rule_match_mode (item 2.4): the
  smart-collection match semantics on GET /api/collections/:id.
- BookInfo gains four STABLE keys (item 2.3): is_episode,
  feed_title, download_state, hidden — dropped omitempty so every
  card surface emits the same key set (the viewer_percentage
  precedent; adapters that predate episode awareness emit zero
  values).

docs/contract_pins.md changelog entry written. Nothing removed,
nothing renamed.
2026-10-30 17:25:22 -04:00
John O'Keefe 962f9089e0 chore(db): querier interface picks up the UpdateCollectionViewSettings comment — generated side of cc56b9ef 2026-10-30 17:12:29 -04:00
John O'Keefe 69773ec307 feat(podcasts): smart collections play as a sequence — the Daily Fiction acceptance (item 2.5)
ACCEPTANCE (plan §0 item 2.5): "Daily Fiction" = feed ∈ {A} ∧ unplayed
∧ <7d matches exactly today's episodes, and PLAY = today's episodes
back-to-back. Two pieces were missing after item 2.4:

- The chain builder only read static membership (collection_items) — a
  smart collection has none. buildSmartCollectionSequenceContext now
  evaluates the rules LIVE for the requesting user (mode from the
  collection, family lens via the visible set) and chains the
  downloaded episode matches in NATIVE feed order — the collection's
  computed order is content (R1: never written back; OrderEpisodes is
  the order chokepoint per R3). A match that aged out of the briefing
  (played since, published beyond the window) falls back to the feed
  queue instead of breaking the page.
- The smart-detail branch rendered match cards as books: episode
  matches are now flagged (IsEpisode + download state) so they carry
  the play affordance and the header's Play-as-Sequence button;
  feed titles stay empty on smart cards for now (batch lookup is
  polish, not acceptance).

Pinned by TestPodcastSmartCollections' acceptance subtests: the
briefing starts at index 1/2 and chains into the second with the
queue param on both hops; the order control stays hidden (computed
order); a stale match falls back to the feed queue honestly.
2026-10-30 17:12:07 -04:00
John O'Keefe cc56b9ef2a fix(collections): UpdateCollectionViewSettings wrote a nonexistent updated_at column
The query said `SET view_settings = $2, updated_at = NOW()` but the
collections table has never had an updated_at column — every call
failed with 42703. The one caller (media_scanner's series-import
provenance write) discards the error, so the failure was silent:
imported-from-series view settings never persisted. Surfaced while
writing the sibling UpdateCollectionMatchMode query for item 2.4 (the
item-2.4 commit message prematurely claimed this fix — this is that
fix, for real).
2026-10-30 16:55:16 -04:00
John O'Keefe abb7c84833 feat(podcasts): smart episode collections — ALL/ANY match modes + episode rule fields (item 2.4)
The daily briefing needs AND: today's rules engine was OR-only. The
match semantics become a per-collection column
(collections.rule_match_mode, 'any' legacy default | 'all'), flipped on
its own endpoint (PUT /api/collections/:id/match-mode, owner-only —
nothing else on the row changes) and surfaced in the rules page as an
ANY/ALL toggle with matching copy.

Episode rule fields join the vocabulary (plan item 2.4): feed (the
multi-select rides the new `in` operator — comma-separated feed ids),
played (the canonical finished predicate — viewer progress ≥ 0.999,
same as hide_finished), downloaded, published_within (N days), plus
title/description contains. The rules candidate query now carries the
viewer's progress (LEFT JOIN reading_progress) so played/unplayed is
per-user, and TestRules/preview speak the SAME evaluator: the handler's
duplicated field switch is deleted and delegates to
CollectionService.FieldMatches — one vocabulary, one semantics.

Legitimate semantics note: in ANY mode `played:false` matches unplayed
BOOKS too (everything with no progress row) — correct per-rule
behavior, and exactly why the briefing mode exists.

Backward compatibility: every legacy row defaults to 'any' (the old
OR), UpdateCollection keeps the stored mode when the form doesn't send
one, and the evaluator treats absent data honestly (no date → no
match; no progress → unplayed).

Pinned by TestPodcastSmartCollections: the AND-mode briefing
(feed∈{A} ∧ unplayed ∧ <7d = exactly the new episode), OR-mode
widening, owner-only flips, the preview honoring the mode, and
downloaded/contains rules. Also fixes a latent bug the new query
surfaced: UpdateCollectionViewSettings referenced a nonexistent
updated_at column (never exercised until now — the new sibling query
was written without it).
2026-10-30 16:54:36 -04:00
John O'Keefe f68fb19afb test(ui): COVERAGE.md — episode-collection sweep candidates (item 2.3) 2026-10-30 16:18:47 -04:00
John O'Keefe adb93cba9e feat(podcasts): episode collections — picker scope, hint rows, the chain (item 2.3)
D11 lifts: podcast episodes (media_items rows) join collections, and
"Play collection as sequence" feeds the player from the collection's
order. No new tables — collection_items already carries ordered
membership (item 2.1 audit).

PICKER: the collection modal gains a Books/Episodes tab pair. The
episodes tab hits /api/media-items/search?scope=episodes — a dedicated
picker query (SearchEpisodesForPicker) whose visibility is entirely
RLS: the media_items subscription predicate drops unsubscribed feeds'
episodes, and the podcast_feeds join is governed the same way. The
books scope keeps its podcasts exclusion (plan §9) — this scope is the
only door in. Pending episodes are pickable (plan ahead; the detail
page shows them as not downloaded). Selection rides the existing
bookPicker store — ids never collide across scopes, and AddBooks works
unchanged on episode ids.

DETAIL: the All-Libraries membership view switches to
GetCollectionItemsDetailed — LEFT JOIN + per-row visibility. An
unsubscribed episode (or family-lens hidden book) survives as a
Hidden card rendered as an "Unavailable — remove entry" hint row
instead of silently vanishing; visible episodes render feed title,
download state, and a Play link. The library-scoped view keeps its
existing dashboard-query behavior (the switcher's contract is
untouched for books).

CHAIN: ?queue=collection:<id> on any reader URL makes
buildPodcastSequenceContext produce the COLLECTION context (§10 R2
same shape, source=collection): downloaded episodes in collection
order (positions are content — R1; no feed-order override), prev/next
URLs carrying the queue param so the chain survives hops, and
backToDetail landing on the collection page. Ownership gates the chain
— foreign/deleted ids fall back to the feed queue; the order control
stays hidden (2.2's source gate). The header's "Play as Sequence"
button starts from the first downloaded episode in list order.

Pinned by TestPodcastEpisodeCollections (7 subtests): RLS-scoped
picker + family-lens auditor case (subscribed episode in a hidden
library must not reach the picker), books-scope exclusion intact,
hint rows, chain carrying the queue param, start-from-first, foreign
fallback, and reorder driving the chain (the R4 primitive works on
episode ids unchanged).
2026-10-30 16:18:29 -04:00
John O'Keefe a90e7debfd feat(podcasts): queue context source + player order control — item 2.2
Foundation rule R2 (§10): the queue context is the only queue, and
every producer emits the same shape. PodcastSequenceContext gains
source (feed|collection), feed_id, and order; the feed producer sets
them now — the collection producer (2.3) slots into the same shape
without the player ever special-casing beyond showing/hiding controls.

The player header gains the FEED-mode order control next to the
"Ep N/M" counter: a dropdown (native/reverse/oldest/newest) plus a
one-click reverse button. Both PUT the existing per-user feed order
override — the SAME state the feed page writes, so flipping it in the
player updates the feed page's dropdown too. The control renders only
when source=feed: a collection queue's order is curated content
(R1), never a listening preference. Behavior is hx-put +
hx-swap="none" (response discarded) with a module-level
htmx:afterRequest listener in audio.ts reloading the page — the
server re-renders prev/next/index in the new order; templ decides
what it looks like, JS only triggers the round trip (CSP-clean, no
inline handlers).

Pinned by TestPodcastPlayerOrderControl: the config JSON carries
source/feed_id/order/episode_index; the control renders feed-mode;
an order override re-renders with the dropdown reflecting it (data-
json pins must match templ's &#34; attribute escaping).
2026-10-30 15:52:14 -04:00
John O'Keefe 7bf0b1257d feat(podcasts): widen reader_settings key ceiling — item 2.1 foundation
reader_settings.setting_key was VARCHAR(50), and the composite
podcast_order:<uuid> key already sits at exactly 50 chars — zero
headroom. The deferred queue-editor idea (plan §0 item 2b) and any
future per-feed/per-collection preference key would have been forced
to payload-stuff inside the order row by a column width. Composite
prefix:<uuid> keys are the norm now (§10 R5), so the ceiling widens
to VARCHAR(120): idempotent in-place ALTER (varchar widening is
metadata-only, no table rewrite), re-runs harmlessly on every boot
per the schema convention.

No new episode-membership tables: collection_items already carries
ordered playlist membership (position, A2c) against media_items,
which podcast episodes ARE — episodes join collections through the
existing table.

Pinned by TestReaderSettingsCompositeKeyHeadroom: a 57-char composite
key (the podcast_custom_order:<uuid> shape) upserts and reads back.
Under the old width this fails; sqlc codegen is byte-identical.
2026-10-30 15:29:34 -04:00
John O'Keefe f7ba4d24d6 style(web): main sidebar drops 16rem to 14rem (user review)
Release / build-and-push (push) Successful in 3m38s
The app-shell sidebar read as too wide against the content area.
--sidebar-w is the single source of truth for the shell geometry, so
one line moves all three consumers together: the .app-sidebar width,
the body:has(.app-sidebar) content offset, and the topbar's left
inset on desktop. No templ or JS change needed — nothing else pinned
16rem.

style.css is the regenerated tailwind build (build:css:prod), diff
limited to the one var; committed with its source per the generated-
artifacts rule.
2026-10-30 15:09:44 -04:00
John O'Keefe f47734dd7d fix(podcasts): generic media delete refuses episode rows (invariant 2)
The admin endpoint DELETE /api/media-items/:id predated podcasts and
would delete any media row — including podcast episodes — if hit
directly. Invariant 2 (absolute form, user decision 2026-10-30) says
episode rows are removed ONLY by whole-feed removal: "the feed should
match the XML until the entire feed is gone." The plan audit found
this endpoint was the one remaining surface that could violate it:
the poller, unsubscribe, and the admin file-deletion endpoints are
files-only, and the hash-conflict merge can't see episodes (they
never hash).

The guard sits right after the GetMediaItem read and BEFORE the
storage-down check, so a refused episode never touches storage
resolution. Same segregation pattern as the generic edit path
(D9/D10, UpdateMediaItem).

Pinned by TestDeleteMediaItemPodcastGuard: admin DELETE of an episode
→ 409 with the row surviving; a book delete through the same endpoint
→ 204 control.
2026-10-30 14:57:08 -04:00
John O'Keefe 5fee8bfb4a fix(admin): bulk delete swaps the episode list — Play → Download without reload
The bulk 'Delete selected files' button posted with hx-swap='none',
which makes htmx DISCARD the response — and the response is the
refreshed episode list partial. Rows (Play → Download, badges) stayed
stale until a manual refresh. Target the swap at #episode-list /
outerHTML like the Download All button; the afterSwap listeners then
reapply the (now-empty) selection and any active filter.
2026-10-30 14:13:39 -04:00
John O'Keefe 7d5bbd1177 feat(admin): multi-select episode file deletion — checkboxes on downloaded rows
The plan's per-EPISODE bulk select for the admin view (§0 item 8
follow-up — trimmed in the first admin-view commit; user called it
back). Admins now tick checkboxes on DOWNLOADED episode rows and delete
their files in one request:

- Checkbox per row, rendered ONLY for admins + downloaded episodes
  (nothing to delete otherwise), via the existing podcastDetail Alpine
  component: selection ids/count survive the list's htmx swaps
  (reapplied on afterSwap — same pattern as the text filter) and clear
  after a successful bulk delete.
- Toolbar segment outside #episode-list (survives swaps): 'N selected'
  + 'Delete selected files' (hx-include gathers the CHECKED boxes);
  disabled-looking at zero selection; hx-confirm states the
  re-materialization contract. CSP-safe method bindings only
  (bulkSelectionLabel/Class) — no ternaries in Alpine expressions.
- POST /feeds/:id/episodes/delete-files (admin): repeated
  episode-file-select keys parsed via ParseForm directly (never bound —
  repeated-key wire is another echo-bind gotcha); each id validated to
  belong to THIS feed, so a forged foreign id is refused while the real
  selections apply; rows reset to pending, files removed.
- Tests: bulk of two real ids + one forged id → deleted:2, files gone,
  rows pending; non-admin 403; all prior single/feed-level pins hold.
2026-10-30 14:06:54 -04:00
John O'Keefe 0741e98ea5 feat(admin): all-podcasts view — disk-first maintenance for every feed
§0 item 8 (Phase-4 item 1 pulled forward, user directive: maintenance
tooling ships WITH the features it maintains):

- /admin/podcasts (AdminMiddleware): every feed from EVERY user via the
  RLS admin escape (first-admin identity, poller/fetcher contract) —
  feed + host, library, subscriber count/names, downloaded/total, DISK
  USAGE, last fetch. Sorted disk DESC ('what's eating the disk'),
  totals header (feeds · episodes · bytes on disk).
- Per-feed actions: Refresh · Delete files (rows → pending, disk freed;
  confirms spell out the re-materialization contract) · Remove feed
  (rows + files for everyone — the same admin delete as the detail
  page). All confirms ride the global confirm modal.
- New sqlc: ListAllPodcastFeedsAdmin (correlated aggregates),
  ResetPodcastEpisodeFileDeleted / ResetPodcastFeedFilesDeleted —
  downloaded rows reset to pending with download-derived facts cleared
  (audio_metadata, chapter_count, cover, size, mime); file_path KEPT
  (fetch-maintained layout — a re-download lands on the same path).
  file deletion via the existing DeleteFeedFiles file-removal pattern
  (episode files + .cover.jpg siblings).
- Poll upsert never touches download_state, so deleted files STAY
  deleted — a feed refresh re-lists metadata but re-materializes
  nothing (pinned by TestAdminDeleteEpisodeFiles).
- Per-episode admin delete-file: POST /feeds/:id/episodes/:eid/
  delete-file (admin) — one episode's file gone, row pending, siblings
  untouched; HX swaps the episode list. (Found while testing: the
  handler first read c.Param("id") — the FEED's uuid — instead of
  :eid; the 404 'episode not found' trail led straight to it.)
- Tests: admin sees other users' feeds + subscriber names; regular
  users 403 on page AND actions; single + feed-level deletion reset
  rows/clear facts/delete files; refresh leaves pending rows pending.
- Admin nav gains 'Podcasts' under Administration.

Wrong-gotcha note for future agents: parseUUID on c.Param('id') inside
a /feeds/:id/episodes/:eid route resolves the FEED, not the episode.
2026-10-30 13:54:37 -04:00
John O'Keefe b293741eb1 feat(reader): podcast episode prev/next on the transport row's outer buttons
User design (round 3): one set of big buttons does the big navigation.
The outer prev/next step buttons were chapter-only even on podcasts,
while episode nav hid as small icons in the top-left cluster. Now:

- Podcasts (sequence context present): the outer buttons navigate
  EPISODES via goToPrev/goToNextEpisode (progress pushed before the
  hop); disabled ghost buttons at the first/last episode keep the row
  shape. Embedded-chapter jumps stay on the Chapter pill's list.
- Books: unchanged chapter stepping.
- Keyboard (h/l shortcuts) and hardware media keys (MediaTrackPrev/
  Next) funnel through stepChapter, which is now sequence-aware —
  headset next-track = next episode on podcasts.
- The top-left episode icons are gone; the 'Ep N/M' counter stays.
- Help-modal labels say 'chapter, or episode on podcasts'.

Same icons both modes (extracted audioStepPrev/NextIcon partials);
books are untouched — no sequence context, byte-identical behavior.
2026-10-30 12:46:36 -04:00
John O'Keefe ace9e57d27 fix(ui): hx-confirm interception actually worked — htmx 2 detail shape
User report: Remove Feed still used the browser dialog. Headless-proven
root cause (tests/ui/confirm_probe.spec.ts): the htmx:confirm handler
read evt.detail.element, which htmx 2 does not provide (its detail is
{ elt, question, issueRequest, ... }) — the handler returned at
'if (!elt) return' BEFORE preventDefault, so every hx-confirm sitewide
fell through to htmx's native confirm. The acbcc61a migration only ever
worked for direct confirmDialog() callers; hx-confirm interception was
dead on arrival against htmx 2 and no test watched the JS side.

Fix: read detail.question (htmx's own closest-attribute resolution of
hx-confirm); return without preventing default when absent. Probe
spec pins: click Remove Feed → #confirm-modal opens with the message,
cancel hides it, no dialog event fires.

Companion fixes in the same user-test round (one commit, one defect
family — templ boolean attributes + confirm-modal placement):
- Add-modal Download order never revealed: #podcast-download-all was
  nested in a wrapper div, so ':checked ~ .podcast-add-order' had no
  sibling relationship. Input, label, and order row are now siblings.
- Order/auto-download dropdowns always DISPLAYED the last option
  ('Newest first'/'Newest') whatever was saved: templ selected={ bool }
  emits selected="false" — presence selects, so every option was
  selected and the browser honored the last. Swept to selected?={...}
  across podcast_detail (14), book_detail_modals (10, incl. two
  always-checked checkboxes), collection_modal (2, same). Saves were
  correct all along; display only.
- Global confirm modal moved from SidebarSignIn (signed-out only!) into
  Header — signed-in pages had no #confirm-modal, so confirmDialog
  degraded to window.confirm even with a working interceptor.

Facet bar scale (user question): values now carry feed counts, sort
frequency-first, cap at 6 chips per group with a native <details>
'+N more' expander.

Probes: tests/ui/confirm_probe.spec.ts + add_order_probe.spec.ts
(live-server, BH_FEED-gated) — both pass against the dev instance.
2026-10-30 12:24:16 -04:00
John O'Keefe 2fd0828c06 fix(podcasts+ui): user-test round 3 — five browser-reported defects
1. Add-modal 'Download order' never revealed: the CSS sibling selector
   (#podcast-download-all:checked ~ .podcast-add-order) can't fire —
   the checkbox was nested inside a wrapper div, so the select row was
   no SIBLING of the input. Restructured: input, label, and order row
   are now siblings under one flex-wrap wrapper.

2. Order + auto-download dropdowns always displayed the LAST option
   ('Newest first'/'Newest') regardless of the saved value: templ's
   selected={ boolExpr } compiles to selected="false" — and the mere
   PRESENCE of the attribute selects the option, so every option was
   selected and the browser honored the last. Sweep to the boolean-
   attribute form selected?={...} (omits on false) across
   podcast_detail (14), book_detail_modals (10: manga type/reading
   direction selects + abridged/explicit checkboxes — same defect,
   always-checked), collection_modal (2: hide-finished/show-up-next
   always-checked). Values were SAVING correctly all along; this was
   pure display. audio_reader/collections :selected/:checked are
   Alpine bindings — unaffected.

3. Remove Feed (and every hx-confirm) still showed the browser dialog
   for signed-in users: the global confirm modal rendered at the end
   of SidebarSignIn — signed-IN pages have no SidebarSignIn, so no
   #confirm-modal existed and confirmDialog() degraded to
   window.confirm. Moved the modal into Header proper (rendered on
   every page, after </aside>).

4. Facet bar at scale: values now carry feed COUNTS, sort by frequency
   DESC then alphabetically, cap at 6 chips per group flat, and the
   rest collapse into a native <details> '+N more' expander — hundreds
   of hosts/tags degrade gracefully instead of a wall of chips.

Verified live on the dev instance (order select reflects the saved
override, override row persists, reveal fires, modal renders on
signed-in pages). Podcast + logout + media-pin suites green; vitest
167 green.
2026-10-30 12:03:44 -04:00
John O'Keefe 15f41e6fd4 test(pins): whitelist download_queue_pos on raw media rows (additive widening)
The contract pin caught the §0 item 4 column surfacing on media-list
raw sqlc rows — its job. Widened additively per doctrine: rawRowKeys +
docs/contract_pins.md changelog entry. NULL for scan rows and
never-queued episodes; nothing removed or renamed.
2026-10-30 10:40:34 -04:00
John O'Keefe 0da8e0cdf9 test(settings): cover the new float setting type in the defaults audit
TestSettingDefaults enumerates registry types; 'float' hit the unknown-
type branch. Added float validation (default parses, within [min,max])
mirroring the int case.
2026-10-30 10:31:02 -04:00
John O'Keefe b574df346a chore(podcasts): drop the dead QueueFeedDownloads wrapper
All callers moved to QueueFeedDownloadsAs in the item-5 commit; the
no-override shim had no remaining callers.
2026-10-30 10:29:45 -04:00
John O'Keefe f0f1eb6e8f feat(podcasts): hide played/downloaded toggle + episode text filter
Pocket Casts steal pulled forward from Phase 4 (§0 item 6): the episode
list gains a client-side 'Filter episodes…' box and a 'Hide
played/downloaded' toggle. Pure presentation — rows carry templ-rendered
data-* attributes (downloaded, listen-pct, search text); the filter
toggles DOM visibility with the 99.5% finishedThreshold. The toolbar
lives OUTSIDE #episode-list so its state survives the list's polling
swaps, and an htmx:afterSwap listener re-applies the active filter to
freshly swapped rows. No query change, no server round trip, no new JS
rendering surface (Alpine component method, CSP-safe).
2026-10-30 10:28:31 -04:00
John O'Keefe 5c545534c2 feat(podcasts): Download All queues in the LISTENING order + add-modal order dropdown
Download All previously queued in feed-native order — 'getting the
last chapter first doesn't help me'. Now the queue follows the feed's
effective listening order (§0 item 5b): QueueFeedDownloadsAs reads the
CALLER's order override and runs episodes through services.OrderEpisodes
(same helper as the sequence/reader/page surfaces — the consolidation
from item 5a landed with the reverse-order commit). Queue tickets
(SEQUENCE-stamped, item 4) make that enqueue order the claim order, so
chapters land in the order you'll actually listen.

Add modal (§0 item 5c): with 'Download all episodes now' checked, a
'Download order' select appears (pure-CSS :checked sibling reveal — no
JS island, CSP-clean). Its choice is the feed's INITIAL order override
(reader_settings upsert; 'feed' = no row) AND the queue order for the
initial batch. Per-book by design: the override IS the download order.

Test TestPodcastAddModalDownloadOrder: add with download_all+reverse →
the override row exists AND persisted tickets run position 3→1. Tickets
are asserted (not live queued rows) because the shared dev server's
worker legitimately races this test's queue — tickets survive every
state flip.
2026-10-30 10:26:00 -04:00
John O'Keefe 0f3c4a8cec feat(podcasts): concurrent download pool — fair share, tickets, admin tunables
Replaces the sequential worker with a download-manager-style pool
(§0 item 4). Model: the user's connection is the limit; semantics are
fair-share ACROSS feeds, not goroutine-per-book (a global FIFO would
make Book B wait behind Book A's 100 files).

- Atomic claim: GetNextQueuedEpisode + SetPodcastEpisodeDownloading
  was a read-then-write race under concurrency; ClaimQueuedPodcastEpisode
  converts queued→downloading in ONE guarded statement (two claimants,
  one winner — the loser gets ErrNoRows). SetPodcastEpisodeDownloading
  retired.
- Queue tickets: download_queue_pos BIGINT fed by a Postgres SEQUENCE
  stamped at enqueue — the enqueue loop's ordering IS the claim order
  (the foundation §0 item 5 builds on; previously all rows in a batch
  shared one updated_at, so within-feed order was arbitrary).
- Pool: up to podcast_download_concurrency (default 4, live range 1–16)
  claim-loop goroutines per drain round; the setting re-reads every
  round so admin changes take effect without restart.
- Fair share: claim prefers the feed least-recently-served
  (pickFeedToServe; never-served first), earliest ticket within a feed —
  books proceed in parallel while chapters land in order (start
  listening while the rest download).
- Bandwidth: shared token bucket across all workers
  (podcast_download_speed_mbps, default 0 = unlimited); take() reserves
  bandwidth and callers sleep outside the lock.
- Settings: new float setting type end to end (registry defaults +
  clamping, save validation, admin UI number-with-step input) + the two
  schema seeds; worker wires the registry via SetSettings (tests run on
  registered defaults).
- Tests: unit coverage for the bucket reservation math + fair-share
  pick; integration TestPodcastDownloadPool pins ticket order = enqueue
  order, claim exclusivity, and a full 3-episode pool drain.

Dev-DB note: the column/sequence/settings were applied live (idempotent
DDL, same statements the schema runs at next boot) since the running
container predates them.
2026-10-30 10:12:43 -04:00
John O'Keefe e3675536aa feat(podcasts): reverse order — position DESC, date-agnostic; single order helper
The 'Oldest first' order sorts by PUB DATE, which breaks on Scribl's
migrated podiobooks feeds (messy/all-equal dates). New order value
'reverse' = feed position DESC with a date-DESC tiebreak — dates are
not involved, so nothing can break.

- services.OrderEpisodes: THE single order source of truth (§0 items
  3+5a). The four surfaces (sequence JSON, reader chain context, SSR
  page list) previously carried three near-identical handwritten
  comparators — all now route through one generic helper. The SSR page
  list gains a SortDate key (lexical 2006-01-02) so the pub-date
  tiebreak is actually chronological; the old comparator compared
  'Jan 2, 2006' display strings alphabetically (latent drift bug).
- Dropdown becomes four options: Feed order / Feed order (reversed) /
  Oldest first (pub date) / Newest first (pub date).
- Serial suggestion button renamed 'Reverse feed order' (sets reverse,
  not oldest) and its response out-of-band-swaps the order select
  (PodcastOrderSelectOOB — same mechanism as Download All's policy
  select), so the dropdown mirrors the server state immediately.
- Validation: oneof=native reverse oldest newest everywhere.
- Tests: reverse binds via the form wire; messy-dates sequence
  returns 3,2,1; existing reorder-safety stays green.
2026-10-30 09:15:03 -04:00
John O'Keefe 7c7c08748e fix(podcasts): download_all binds on every wire — FlexBool + flip log
Reproduced the §0 item 2 suspect: echo v5 bool-binds form values via
strconv.ParseBool, which accepts "true"/"1" but REJECTS the
browser-native <input type=checkbox> value "on" — and a bind failure
kills the WHOLE AddFeed request (400 "invalid request"), not just
the checkbox. The add modal posts urlencoded (htmx), so any
checkbox-serialization that emits "on" made Download All silently
unusable.

Fix: FlexBool (encoding.TextUnmarshaler-style UnmarshalParam) binds
download_all permissively on every wire — "true"/"on"/"yes"/"checked"
=> true, explicit false/0/off => false, ABSENCE (unchecked box on any
wire) => false; JSON bool binding is native and unaffected. Tolerates
the exact wires htmx and browsers emit.

AddFeed's subscription flip now logs "[PODCAST] flip ... <feed> —
user" so the live flip is provable in app logs (user suspected it
never fired).

Integration test TestPodcastDownloadAllFormEncoding pins the urlencoded
wire (what htmx actually sends): true + on both flip the caller's
policy to 'all', an unchecked add leaves the default.
2026-10-30 09:06:41 -04:00
John O'Keefe cdf81f6cf4 fix(podcasts): page-load polls during downloads; indeterminate bar slides
A fresh detail-page load while downloads were active rendered the
NON-polling episode container (PollingEpisodeList was only reachable
via the /episodes partial route after Refresh), so the page froze
until the user refreshed manually. PodcastDetailPage now picks the
variant the same way the route does — HasActiveDownloads selects the
every-2s poll container.

Also: the indeterminate progress bar (feeds without Content-Length,
e.g. Scribl) used animate-pulse, which fades in place and reads as
frozen; replaced with a sliding shimmer keyframe
(.podcast-progress-indeterminate, 33% sliver, translating -100% ->
300%) in input.css. The live MB counter stays.

§0 item 1.
2026-10-30 08:53:35 -04:00
John O'Keefe 7ea84043fa fix(auth): logout actually signs out — clear the HttpOnly session cookie
Release / build-and-push (push) Successful in 3m9s
Logout wiped localStorage but never cleared the token cookie (HttpOnly —
only a server response can) and never called the logout API, leaving the
refresh token live for 30 days and every cookie-authenticated SSR page
accessible: the fake-signout bug. Reproduced on prod and dev; unrelated
to RLS (it sits behind authentication) and long-standing.

- /api/auth/logout now ALWAYS clears the session cookie (Set-Cookie
  empty + Max-Age=-1, HttpOnly/Path/SameSite mirroring login) — even a
  malformed body must sign the browser out; refresh-token revocation
  unchanged.
- The header logout button (and the rules-page copy) now POST to the
  API with the stored refresh token BEFORE clearing local state and
  redirecting — best effort: local cleanup never blocks on API failure.
- toast 401 handler fixed: it cleared 'refreshToken' but storage uses
  'refresh_token' — the real key.
- Regression test TestLogoutClearsSession: real login → logout →
  response deletes the cookie; logged-out refresh token can't mint
  access tokens; body-less logout still clears.

Also carries regenerated artifacts from the confirm-modal and
episode-list work (header_templ/podcast_detail_templ/style.css).
2026-10-29 22:01:32 -04:00
John O'Keefe 253d8d0e8e feat(podcasts+ops): Apple launcher-scheme feeds + visible build stamp
Release / build-and-push (push) Successful in 3m29s
Apple scheme normalization (follow-up to the Scribl discussion): Add
Feed accepts the launcher spellings podcast pages ship next to plain
RSS — itpc://, podcasts://, feed:// — and rewrites them to the https
feed URL they wrap (scheme match case-insensitive). http stays and the
guard still rejects it. Unit-pinned.

Build stamp (stale-container drift guard): the 2026-10-29 podcast
session lost an hour to a container running a build that predated the
feature. version.Commit rides ldflags from a GIT_COMMIT build arg; the
dev compose passes git rev-parse --short HEAD via the Makefile; the
app logs 'Bookhoard <ver> (commit <hash>)' at boot and /api/health
reports it — the UI and the repo can no longer silently diverge.
2026-10-29 20:12:39 -04:00
John O'Keefe acbcc61ae4 feat(ui): global confirm modal — browser dialogs retired sitewide (issues #5/#4/#7)
ONE styled modal answers every hx-confirm in the app: a body-level
htmx:confirm interceptor (web/src/confirm.ts, canonical htmx pattern)
preventDefaults and shows the dialog, issuing the request on Confirm.
Nine hx-confirm call sites upgrade without touching them. The modal
lives in the header partial so every page has it; confirmDialog() is
exported for JS call sites and degrades to the native dialog if the
header is absent (bare layouts).

Migrated the five window.confirm sites (admin.ts ×3, book-detail.ts ×2)
to the same promise API.

Podcast feed detail (issues #4/#7): the unsubscribe copy is
role-aware — non-admins get 'Unsubscribe from this feed?' with silent
retention (file state is admin knowledge); an admin who is the LAST
subscriber gets a three-choice modal instead: Unsubscribe (files kept,
the D6 default — sliding-window feeds make purge unrecoverable) /
Remove feed + files / Cancel. Admins with co-subscribers keep the
files-note confirm.
2026-10-29 20:12:30 -04:00
John O'Keefe 30766020c8 feat(podcasts): real-time episode list — byte progress bars, direct swaps (issues #1/#3)
WHY: downloads needed manual refreshes to see progress; the 204 +
HX-Trigger event indirection missed its listener, and the worker
buffered whole enclosures so no progress existed to show.

- Worker streams enclosures to disk through a counting loop (64KiB
  chunks, scheme/redirect/size guards preserved) with an in-memory
  per-episode progress snapshot (received/total; total from
  Content-Length, seeded by the feed's declared length). Deliberately
  transient — the DB row state remains the durable truth.
- Episode-list renderer seam: the router injects a closure into
  PodcastHandler (handlers can't import templates — MediaDetail cycle)
  so htmx download/retry/Download All/refresh/order/policy actions
  answer with the REFRESHED partial directly (200, hx-target=
  #episode-list) — no events to miss. Non-HX callers keep JSON; tests
  without a renderer keep 204+trigger.
- Polling tightens to 2s while downloads are active; downloading rows
  render a percentage bar + MB counter (quote-free inline style per
  templ gotcha #8) or an indeterminate bar when the server sends no
  length.
- Issue #3: Download All (button AND the add-feed checkbox) flips the
  CALLER's subscription policy to 'all' — per-user, never global (D6:
  files shared, policies not) — and the auto-download select
  out-of-band-swaps so the dropdown shows what the user is getting.
  They can turn it down afterwards; the flip is honest communication,
  not coercion (user-approved 2026-10-29).

PINs: Download All with HX answers 200 + episode-list + oob select and
flips newest → all; add-feed download_all sets policy all.
2026-10-29 20:12:19 -04:00
John O'Keefe ffc80f7ba7 fix(podcasts): page search hits episode titles/descriptions (issue #8)
WHY: the /podcasts search box filtered feed CARDS only (title, display
name, host, publisher, feed description). D14's episode search existed
only as the /api/podcasts/search endpoint and was never wired into the
page — searching 'Quarter' (present only in episode titles) cleared the
grid while 'Trader' (feed metadata) survived.

The page query now consults SearchMyPodcastEpisodes (subscription-scoped
via RLS — the caller's identity) when a query is present; a feed
surfaces when its OWN metadata OR any of its episodes matches, with an
'N matching episode(s)' badge on the card.

PIN: SSR test with a needle that exists only in an episode title — the
feed must surface with the match count.
2026-10-29 19:49:39 -04:00
John O'Keefe c753780817 fix(podcasts): order selector validation — bind the htmx form wire format (issue #2)
WHY: htmx sends non-GET requests urlencoded by default; the SetFeedOrder
request struct only carried a json tag, so the binder left Order empty
and 'required' fired — the exact error the order dropdown AND the
Serial-suggestion button produced (hx-vals JSON also arrives
form-encoded). One form tag fixes both controls.

Regression test drives the exact wire format: urlencoded PUT with
order=oldest/native → 200, empty/invalid → 400.
2026-10-29 19:45:46 -04:00
John O'Keefe 8d9fb0046c refactor(podcasts): drop the dead downloadRoot param on upsertEpisode
FilePath is library-relative (the pinned layout resolves at download
time via the library folders); the parameter never carried a value.
2026-10-29 18:22:09 -04:00
John O'Keefe 5c10bbb90e test(podcasts): reorder-safety pin — progress survives position renumbering (task 2.6)
Invariant 3: progress anchors on the episode row (guid identity +
chapter/offset), never the ordinal. Renumbering feed_position (the
fetcher's per-fetch renumber case) leaves the progress row untouched
and the sequence membership stable — downloaded-only with no gaps.
2026-10-29 18:17:51 -04:00
John O'Keefe 49b0b6eeb9 test(podcasts): integration suite + RLS auditor + contract widening (task 1.10)
cmd/server/tests/podcast_test.go — six suites, the shared-dev-DB
doctrine (test*-named libraries, cascading cleanup, no binary
fixtures):

- TestPodcastRLSSurfaces: THE AUDITOR (invariant 13) — non-subscriber
  404 on feed detail + SSR page (existence leak), episodes absent from
  generic media reads, admin escape, subscriber visibility, then the
  hidden-library flip hiding an already-subscribed feed (the feed
  policy's library-visibility join). Seeding runs as the FIRST ADMIN —
  the seed identity has neither subscription nor users row, so podcast
  INSERT..RETURNING (SELECT policy under FORCE) 42501s for it;
  production pods run as exactly that admin (invariant 12). All direct
  row probes read through the admin scope for the same reason.
- TestPodcastAddFeedFlow: member add + subscribe + metadata-only
  upsert; duplicate-URL dedupe (no second row); allow_member_feeds
  gate (member 403 / admin 201 / subscribe-still-allowed).
- TestPodcastShrunkenFeedRetention: feed purges an episode from the
  XML, both rows persist (upsert-without-delete pin, D14).
- TestPodcastEditSegregation: generic edit 400 + write-to-file refusal
  for episodes; control book edit unaffected.
- TestPodcastDownloadWorker (ffmpeg-generated tone at runtime): file
  lands at <download-root>/<feed-slug>/NNNN-…, audio_metadata probed;
  re-download of a downloaded episode never re-fetches (idempotency
  pin, enclosure-hit counted); dead enclosure → failed + persisted
  reason + metadata intact. Fetch/SSRF tests swap the client via
  SetPodcastHTTPClientForTests (the production client refuses
  loopback httptest servers by design — the real client gets its own
  negative test in services).
- TestPodcastScannerExclusion: SetFolders on a podcasts library root
  yields zero scanner folders (invariant 4 pin) — MediaScanner
  .FolderCount() accessor added.

Unit: internal/services/podcast_rss_test.go — namespace-aware parsing
fixture (three XML namespaces, fallback chains, hosts/guests),
duration spellings, RFC-822 variants, explicit variants, slug/path
layout, enclosure-extension selection, stripHTML, and the SSRF matrix
(private/loopback/link-local/multicast/mapped-v6 blocked; a loopback
httptest server PROVES the production client refuses it).

suites green: full integration run 161s / 0 failures; vitest 12 files
163 tests.

Contract widening: TestContractPin_MediaListBothBranches' raw-row
allowlist gains the 15 podcast episode columns (additive; documented in
docs/contract_pins.md — inert defaults on scan rows). Bruno: bruno/
podcasts/ mirrors the §8 endpoints (12 requests) + Bookhoard env vars.
tests/ui/COVERAGE.md rows 18-23: podcasts pages/lifecycle/RLS/chain —
Playwright sweep pending.
2026-10-29 18:09:35 -04:00
John O'Keefe 28420d56ed feat(podcasts): chain playback + Continue section — sequence mode in the web player (phase 2 core)
D7 chain-by-default, delivered with minimal player surgery:

- ReaderMetadata gains PodcastSequence: the neighboring DOWNLOADED
  episodes in the caller's effective order (D5 override applied,
  feed-native fallback; computed in the reader route for
  source='podcast_episode' items — RLS already scoped the reads; gaps
  never enter the chain, invariant 6). ?single=1 escapes chaining (the
  'play single episode' affordance).
- Audio reader renders the sequence into body[data-json]
  (AudioReaderConfigJSON — books produce the identical shape minus the
  sequence key, so the reader path is unchanged for them) and an
  'Ep N/M' indicator + prev/next episode controls in the header.
- audio.ts: the last-track 'ended' handler chains into the next
  episode's reader page (final progress push precedes navigation);
  back button exits episodes to their feed page. Books are untouched —
  no sequence context, zero behavior change. Day-one chaining is
  page-navigation based (progress persists; position restores).

Continue aggregation (2.5): GetPodcastContinueForUser (in-progress
episodes, most-recent-first, ≥95% excluded) feeds a Continue section
on /podcasts — sorted most recently listened, cards show 'Ep N · title'
— ahead of All Feeds. Cards prefer the continue line over the
description.
2026-10-29 16:25:44 -04:00
John O'Keefe 2235b00c59 feat(podcasts): web UI — /podcasts page, feed detail, download lifecycle (task 1.9)
Rendering ownership holds throughout: every piece of server data is
templ-rendered; htmx swaps partials; the only TS is the Add-Feed modal
toggle + error surfacing (pure client-local state, bundled via
web/src/podcasts.ts with automatic bundle-hash stamping).

Sidebar: /podcasts nav entry (D13, between Series and Collections),
gated by a ShowPodcastsNav flag resolved centrally in
getTemplateUserWithTheme (one indexed COUNT — same class of
per-request lookup as the live-user guard). New 'podcast' icon.

/podcasts: header + Add Feed modal (htmx post → HX-Redirect to the
feed page; inline error surfacing on failure), subscription-scoped
search + facet bar (host/tag/language — server-side GET filters, no
JS), grid cards with download counts / new-episodes / complete /
explicit badges. Empty states for no-library (admin creates it first)
and no-subscriptions.

Feed detail: hero (artwork, host/publisher, tags, fetch state), action
row — Download All, Refresh, ORDER SELECTOR (D5 override), serial
one-click oldest-first suggestion (never silent), auto-download policy
select (D6), Unsubscribe (files retained), admin Remove Feed — gap
banner (D8 count), and the EPISODE LIST with the full lifecycle inline
(D8/D19): pending greyed + Download button (every non-downloaded
episode has one), queued/downloading pulse, failed RED + reason text +
Retry (same endpoint). The list is a self-refreshing partial: re-fetch
on the podcast:changed HX-Trigger and polls every 4s ONLY while the
server says downloads are active (it renders the polling variant).

API endpoints grew HX awareness: 204 + HX-Trigger podcast:changed (or
HX-Redirect for add/unsubscribe/remove) — the sanctioned Go-handler
response channels; JSON callers keep JSON. AddFeed result exposes the
fetch-error text for the redirect.

Dates render in the requesting user's timezone (D17) via
utils.FormatTimeInTimezone; episodes play through the existing
/readers/{id} audio reader (episodes ARE audiobook items — no new
player code day one). CSP tripwire (templates/csp_source_test.go)
passes: no inline scripts, no on*= handlers, no hx-on/js: vals.
2026-10-29 16:17:55 -04:00
John O'Keefe 54d7d6e7a1 feat(podcasts): edit segregation — feed metadata is fetcher-owned (task 1.8)
D9/D10: users never edit podcast episode metadata. Three gates:

- Generic edit endpoint (UpdateMediaItem) rejects source=
  'podcast_episode' items with 400 — the next fetch refresh would
  clobber any edit anyway, and the fetcher is the sole metadata writer.
- Write-to-file (MetadataWriter.WriteMetadataToFile) refuses podcast
  episodes for the same reason (tag write-back for downloaded episodes
  is a named Phase-4 item needing its own iTunes-tag mapping).
- The book-detail page hides the admin Edit affordance for
  podcasts-type items (direct-URL visits), and the metadata-editor
  modal's field list has no podcast fields by construction (fixed
  templ field list) — episodes render read-only via /podcasts
  surfaces.
2026-10-29 16:05:03 -04:00
John O'Keefe 45b1152a15 feat(podcasts): API endpoints — add/list/detail, subscriptions, downloads, sequence, search (task 1.7)
The §8 surface, wired through main.go → router.Config →
/api/podcasts (JWT). Scoping is the engine's (D20): lookups outside the
caller's scope simply return no rows → 404; the only Go-level checks
are explicit-argument authorization (AddFeed's library +
allow_member_feeds gate) and the admin role on feed deletion.

Endpoints: POST/GET /feeds (add: fetch+parse+upsert+subscribe, optional
download_all; list: subscriptions + episode counts + facet values
computed in Go — feed counts are tens), GET /feeds/:id (detail with
download states + gap count), PUT/DELETE /subscription (the ONLY
user-writable podcast state, D9; unsubscribe retains files per D6),
POST /refresh, POST /episodes/:eid/download (+ episode_ids[] bulk and
eid='all' = Download All, exactly the non-downloaded set),
PUT /order (D5 per-user override in the reader_settings KV —
podcast_order:<feed_id>; 'native' deletes the row so default and
explicit choice are indistinguishable), GET /sequence (effective order
— override applied, native fallback — DOWNLOADED-only with the gap
list; this payload powers web chain mode and, per §15, the future
media3 queue), GET /search (subscription-scoped feed + episode search
covering un-downloaded and historical rows, D14), DELETE /feeds/:id
(admin; best-effort file removal, cascade deletes rows).

Gap definition (countGaps): an un-downloaded episode with a downloaded
episode AFTER it in list order — the D8 'middle episodes missing'
banner condition.
2026-10-29 16:03:35 -04:00
John O'Keefe a6723e6ac8 feat(podcasts): feed poller + podcast_poll_interval_seconds setting (task 1.6)
One ticker re-reading its interval from the settings registry each
cycle (live tunable — the cache stays honest because writes go through
the settings API path, AGENTS.md gotcha #2). Per tick: list feeds
(first-admin identity, invariant 12), skip is_complete feeds (back
off; explicit refresh still works), poll each (conditional GET via
stored validators), and apply the subscriber auto-download policy
union after each successful fetch so new episodes queue without
waiting a tick.

Schema/registry: podcast_poll_interval_seconds (default 3600s, floor
300s, category podcasts) — seeded with ON CONFLICT DO NOTHING per the
idempotency rule.
2026-10-29 16:03:22 -04:00
John O'Keefe 4288a86b2d feat(podcasts): download worker — state machine, idempotency, policy union (task 1.5)
One sequential worker (day one) over a DB-backed queue
(download_state='queued' IS the worklist — the episode list always
renders truth, D8/D19). State machine: pending → queued → downloading
→ downloaded | failed (+ download_error + download_attempts).

Idempotency: downloaded re-request is a no-op; a file already on disk
that probes cleanly re-marks the row without re-fetching
(crash-between-move-and-update reconciliation). Retry: manual path
resets attempts (human override), auto policies re-queue up to
maxAutoDownloadAttempts=5 then stay failed until a human retries.

Pipeline: enclosure fetch (same SSRF/size guards as the fetcher) →
.part temp → declared-size pre-check → MIME/size validation (empty /
over-cap / content-sniff refuses non-audio) → ffprobe reconcile +
embedded-cover extraction (scanner machinery reuse: runFFProbe,
extractEmbeddedAudioCover, AudioMetadataPayload) → atomic rename →
SUCCESS-ONLY row update (invariant 7: a failure never clears existing
episode data).

Policy union (D6): subscriber policies per feed — 'all' → everything
missing; 'newest N' → the N tail positions; 'off' contributes nothing;
auto-retry budget respected at queue time. DeleteFeedFiles for the
admin-only removal path (episode files + cover siblings + artwork).
2026-10-29 16:03:22 -04:00
John O'Keefe 85a9873a75 feat(podcasts): RSS fetcher — parse, SSRF guards, upsert-without-delete (task 1.4)
The fetcher is the SOLE writer of feed/episode metadata (D9). Three
files, no new deps (stdlib encoding/xml + net/http):

podcast_rss.go — RSS 2.0 + iTunes + Podcasting-2.0 structs. iTunes
fields are namespace-qualified in tags (local names collide with core
RSS: title/subtitle/author/summary/explicit/image/duration);
podcast:* fields match on local name (collision-free, tolerant of both
declared namespace URIs). Description/author fallback chains per §5;
itunes:duration parses seconds/HH:MM:SS/MM:SS/prose; pubDate accepts
the RFC-822/1123 spellings feeds actually emit.

podcast_http.go — the security boundary for user-supplied URLs:
https-only on every hop (CheckRedirect), private/loopback/link-local/
multicast IP ranges blocked at DIAL time (Dialer.Control sees the
RESOLVED address — DNS rebinding into 127.0.0.1 is refused at the
socket), 10-redirect cap, hard body caps (25MiB feeds / 20MiB artwork /
1GiB enclosures), no proxy.

podcast_service.go — fetch → parse → upsert. Episodes upsert
metadata-only keyed on (source_feed_id, episode_guid); rows for items
that vanish from the XML are NEVER deleted (D14 search covers
historical episodes). itunes:new-feed-url + permanent HTTP redirects
rewrite feed_url in place (row/subscriptions/episodes stay put);
podcast:guid dedupe reuses the canonical row instead of forking.
Artwork downloads feed-level under <feed-slug>/artwork.<ext>.
AddFeed authorizes ONLY on explicit arguments (library visible +
allow_member_feeds for non-admins — the D20 scoping model); detached
work runs under the first-admin identity via adminCtx (invariant 12).
Feed layout: <download-root>/<feed-slug>/<pos:04d>-<slug>.<ext> so
ServeFile/Range streaming resolve unchanged.
2026-10-29 16:03:22 -04:00
John O'Keefe 9a148c2344 feat(podcasts): generic-surface exclusions — podcasts never render as books (task 1.3)
§9 / D3 / D13 / D15 / D16: podcasts-type libraries are excluded from
every generic book surface. Under RLS these are pure UX/type filters
(engine already hides other users' episodes); their job is preventing
episode grids in surfaces designed for books. The discriminator is the
denormalized media_items.library_type_name (IS DISTINCT FROM 'podcasts'
— NULL rows predate the column and stay visible).

SQL (queries.sql, marked '-- podcasts exclusion (plan §9)'):
ListMediaItems/ListMediaItemsSorted (All Books) · SearchMediaItems +
SearchMediaItemsUnified (generic search) · FacetCountsUnderFilters (all
14 arms) + the six Search*Values facet-suggestion queries ·
GetDistinctSeries + Count (series pages) · GetLibraryItems (collections
picker) · dashboard system sections (Continue Reading / Recently Added
/ Recently Read / Not Started) · GetPopularBooks + GetTopBooksByMinutes
(book rankings must not rank episodes).

Go: statistics summary counts episodes' sessions into time-spent (D15
keeps that) but skips them in BooksActive/BooksFinished — an episode is
not a book. OPDS filters podcasts libraries via one helper at all 7
library-walk sites (D16).

Templ: LibrarySwitcher skips podcasts entries and TotalMediaCount
excludes them — presentation-layer filter so every switcher consumer
(dashboard, collections, custom-section builder) is correct at once
(D13); podcasts surface via /podcasts only.
2026-10-29 15:44:48 -04:00
John O'Keefe c0e6993273 feat(podcasts): scanner exclusion — podcasts libraries are feed-managed (task 1.2)
WHY: podcast download roots hold fetcher-written episode files; the FS
walker must never discover them (invariant 4) — a walk would double-
ingest episodes as scanner items and fight the fetcher's sole-writer
rule (D9). Every scan/watch path funnels through MediaScanner.SetFolders
(StartScanner, ScanLibrary jobs incl. scoped single-folder scans,
watch mode), so the filter lives there once: folders resolving to a
podcasts-type library are dropped before registration, with a log line.

Belt and braces: ScanLibrary's per-folder scope refuses purpose='podcast'
folders explicitly (400) — the panel-level path that bypasses type
resolution. AddLibraryFolder now derives purpose from the library type
('podcast' for podcasts libraries, enforced single download root;
'scan' default elsewhere), so folder purpose and library type cannot
diverge through the API.
2026-10-29 15:38:45 -04:00
John O'Keefe 0b7ad0f376 feat(podcasts): schema, RLS policy extension, sqlc queries — feed core foundations
Podcast integration task 1.1 (plan: podcast-integration.md §6/§8, D20).

WHY: podcasts are a new first-class media domain — RSS feeds users
subscribe to personally, with episodes as media_items rows so progress,
stats and the audio player work unchanged. Visibility is per-user
(strict: only your subscriptions), which after the RLS migration
(2026-10-29) belongs in the POLICIES, not Go helpers.

Schema (idempotent — schema.sql re-executes every boot):
- 'podcasts' library type seeded (ON CONFLICT DO NOTHING, ARRAY[]::TEXT[]
  cast required — bare ARRAY[] 42802s under ON_ERROR_STOP)
- podcast_feeds: per-library feed entity (UNIQUE(library_id, feed_url)),
  full RSS/iTunes/Podcasting-2.0 metadata inventory, conditional-GET
  validators, is_complete poll backoff
- podcast_subscriptions: the ONLY user-writable podcast state (display
  name, auto-download policy); deliberately UNGOVERNED — it IS the read
  policy's lookup table
- media_items episode columns: source/source_feed_id/episode_guid/
  feed_position/season/episode/enclosure_url/declared_duration/
  transcript_url/chapters_url/hosts/guests + download state machine
  (pending|queued|downloading|downloaded|failed + error + attempts),
  all partial-indexed so scan rows never touch them
- libraries.allow_member_feeds (first per-library knob); library_folders
  .purpose ('podcast' download roots, scanner-skipped)

RLS (inside the labeled policy block):
- p_media_items_visible gains the podcast-episode subscription predicate
  + admin escape (source IS DISTINCT FROM 'podcast_episode' guard keeps
  scan rows on the cheap path); unset identity still fails loud
- podcast_feeds governed identically: library-visibility join AND
  subscriber-or-admin SELECT; permissive write stand-ins (mandatory at
  ENABLE time; fetcher/worker declare first-admin, add-feed upsert uses
  ON CONFLICT DO UPDATE RETURNING so creators never need SELECT on
  foreign rows)
- Verified against dev DB: migration identity sees nothing, admin sees
  all, member sees feeds/episodes only post-subscribe (probed in a
  rolled-back tx — no rows persisted)

sqlc: 30 new queries (feed upsert/CRUD, subscriptions, episode
upsert-with-write-after-success-guard, download state transitions,
poller worklist, subscription-scoped search) — no visibility clauses
anywhere, per the D20 scoping model.
2026-10-29 15:36:11 -04:00
324 changed files with 32531 additions and 9248 deletions

No files matched your search

+1
View File
@@ -87,3 +87,4 @@ session-*.md
# see docs/contributing/development.md → Media fixtures)
internal/services/testdata/
test-results
.openchamber/
+11
View File
@@ -145,6 +145,17 @@ every user sees every library unless an admin hides one) is enforced by
new pages/controls go into `tests/ui/COVERAGE.md`). Item-scoped
gates may answer 404 as well as 403 (row invisible vs Go-level
check — contract_pins 2026-10-29).
- **Collections RLS (2026-10-31)**: `collections` and
`collection_items` are governed too — predicates
`app_can_read_collection` / `app_can_write_collection`, PURE over
their arguments (never query `collections`, so no policy recursion
under FORCE RLS). Reads: owner-or-admin; writes: owner, admin escape
for SYSTEM collections only. Future sharing = one EXISTS branch
inside the predicate functions, no policy migration. Registration
seeding declares the new user's identity (`rls.WithUser` in
`CreateDefaultCollectionsForUser` — the JWT does not exist yet);
test-harness writes to non-system collections must run as the row's
OWNER (`scopeExecAs`/`ownerSeedCtx`, not the admin handle).
History: 2026-10-13 (`431fec0`) the series/media listing surfaces
leaked hidden libraries; **2026-10-29 enforcement moved to RLS** — the
+3 -1
View File
@@ -41,12 +41,14 @@ RUN npm run build:ts
# Declared after `COPY . .` so a version bump only invalidates this layer.
# The release workflow passes the git tag, e.g. APP_VERSION=v1.5.
ARG APP_VERSION=dev
# Short commit hash of the built source (stale-container drift guard).
ARG GIT_COMMIT=none
# Build Go binary (cached unless Go files or generated code changes)
RUN --mount=type=cache,target=/root/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux go build -installsuffix cgo \
-ldflags "-X bookhoard/internal/version.Version=${APP_VERSION}" \
-ldflags "-X bookhoard/internal/version.Version=${APP_VERSION} -X bookhoard/internal/version.Commit=${GIT_COMMIT}" \
-o main ./cmd/server
# Materialize the Go module cache into an image layer so the test-runner
+4
View File
@@ -11,6 +11,10 @@ endif
# Override with: CONTAINER_RUNTIME=podman make rebuild-app
CONTAINER_RUNTIME ?= $(shell command -v docker 2>/dev/null || command -v podman 2>/dev/null)
# Build stamp (stale-container drift guard): the rebuilt image carries
# the source commit; the app logs it at boot and /api/health reports it.
GIT_COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
# Dev compose stack: base prod file merged with the dev override (local build + tests).
# Prod deploy does NOT use this — it runs plain `docker compose` against the base file only.
COMPOSE := $(CONTAINER_RUNTIME) compose -f docker-compose.yml -f docker-compose.dev.yml
+9 -1
View File
@@ -1,6 +1,14 @@
# Screenshot Automation Plan for Bookhoard Documentation
> **Status**: Ready to implement when frontend is complete
> **Status**: REJECTED / ARCHIVED (2026-11-02) — not implementing.
> **Superseded by**: [docs/developer/writing-ui-docs.md](docs/developer/writing-ui-docs.md) —
> Bookhoard docs are written screenshot-free from now on. Why: screenshots go
> stale silently (no gate can diff pixels against the UI), die on every
> redesign, and are unverifiable; the UI is server-rendered so exact labels are
> greppable and gate-checked instead (`TestUIControlLabels`). The prose
> standard teaches patterns that survive re-layouts. Kept below unmodified for
> history.
>
> **Last Updated**: 2026-02-03
This document outlines the complete plan for automatically generating screenshots for Bookhoard documentation using Playwright.
@@ -1,41 +0,0 @@
info:
name: Add Auto-Assign Rule
type: http
seq: 1
http:
method: POST
url: '{{base_url}}/api/collections/{{collection_id}}/rules'
auth: inherit
body:
type: json
data: |-
{
"field": "genre",
"operator": "equals",
"value": "Science Fiction",
"priority": 1,
"enabled": true
}
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
runtime:
scripts:
- type: tests
code: |-
test("status is 201", function() {
expect(res.status).to.eql(201);
});
docs:
content: |-
# Add Auto-Assign Rule
`POST /api/collections/:id/rules` — auth: jwt.
Canonical reference: docs/developer/api/collections/add_auto_assign_rule.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Bulk Add Books
type: http
seq: 2
seq: 1
http:
method: POST
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Bulk Assign Books
type: http
seq: 3
seq: 2
http:
method: POST
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Bulk Remove Books
type: http
seq: 4
seq: 3
http:
method: POST
+1 -2
View File
@@ -1,7 +1,7 @@
info:
name: Create Collection
type: http
seq: 5
seq: 4
http:
method: POST
@@ -16,7 +16,6 @@ http:
"color": "#00FF00",
"icon": "📖",
"collection_type": "static",
"auto_assign_rules": [],
"view_settings": { "kobo": { "view_mode": "grid" } }
}
settings:
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Create Shelf Mapping
type: http
seq: 6
seq: 5
http:
method: POST
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Delete Collection
type: http
seq: 7
seq: 6
http:
method: DELETE
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Delete Shelf Mapping
type: http
seq: 8
seq: 7
http:
method: DELETE
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Collection
type: http
seq: 9
seq: 8
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Book Collections
type: http
seq: 10
seq: 9
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: List Collections
type: http
seq: 11
seq: 10
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Preview Collection
type: http
seq: 12
seq: 11
http:
method: POST
@@ -1,31 +0,0 @@
info:
name: Remove Auto-Assign Rule
type: http
seq: 13
http:
method: DELETE
url: '{{base_url}}/api/collections/{{collection_id}}/rules/{{rule_id}}'
auth: inherit
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
runtime:
scripts:
- type: tests
code: |-
test("status is 204", function() {
expect(res.status).to.eql(204);
});
docs:
content: |-
# Remove Auto-Assign Rule
`DELETE /api/collections/:id/rules/:ruleId` — auth: jwt.
Canonical reference: docs/developer/api/collections/remove_auto_assign_rule.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Reorder Collection Items
type: http
seq: 14
seq: 12
http:
method: PUT
+29
View File
@@ -0,0 +1,29 @@
info:
name: Set Collection Chain Order
type: http
seq: 13
http:
method: PUT
url: '{{base_url}}/api/collections/{{collection_id}}/view-settings'
auth: inherit
body:
type: json
data: |-
{
"chain_order": "newest"
}
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
docs:
content: |-
# Set Collection Chain Order
`PUT /api/collections/:id/view-settings` — auth: jwt.
Canonical reference: docs/developer/api/collections/set_chain_order.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
-48
View File
@@ -1,48 +0,0 @@
info:
name: Test Rule
type: http
seq: 15
http:
method: POST
url: '{{base_url}}/api/collections/test-rules'
auth: inherit
body:
type: json
data: |-
{
"rules": [
{
"field": "genre",
"operator": "equals",
"value": "Science Fiction"
},
{
"field": "author",
"operator": "contains",
"value": "Asimov"
}
]
}
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
docs:
content: |-
# Test Rule
`POST /api/collections/test-rules` — auth: jwt.
Canonical reference: docs/developer/api/collections/test_rule.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
+1 -2
View File
@@ -1,7 +1,7 @@
info:
name: Update Collection
type: http
seq: 16
seq: 14
http:
method: PUT
@@ -15,7 +15,6 @@ http:
"description": "Updated description",
"color": "#33CCFF",
"icon": "📚",
"auto_assign_rules": [],
"view_settings": { "hide_finished": true },
"hide_finished": ["true"],
"show_up_next": ["true"]
-29
View File
@@ -1,29 +0,0 @@
info:
name: Update Collection Rule
type: http
seq: 17
http:
method: PUT
url: '{{base_url}}/api/collections/{{collection_id}}/rules/{{rule_id}}'
auth: inherit
body:
type: json
data: |-
{
"enabled": false
}
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
docs:
content: |-
# Update Collection Rule
`PUT /api/collections/:id/rules/:ruleId` — auth: jwt.
Canonical reference: docs/developer/api/collections/update_rule.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
@@ -1,12 +1,18 @@
info:
name: Reject Device Registration
name: Cancel Device Registration
type: http
seq: 16
seq: 3
http:
method: POST
url: '{{base_url}}/api/devices/reject/{{registration_id}}'
url: '{{base_url}}/api/devices/register/cancel'
auth: inherit
body:
type: json
data: |-
{
"registration_id": "550e8400-e29b-41d4-a716-446655440000"
}
settings:
encodeUrl: true
timeout: 0
@@ -23,9 +29,9 @@ runtime:
docs:
content: |-
# Reject Device Registration
# Cancel Device Registration
`POST /api/devices/reject/:registration_id` — auth: jwt.
`POST /api/devices/register/cancel` — auth: none.
Canonical reference: docs/developer/api/devices/reject_device_registration.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
Canonical reference: docs/developer/api/devices/cancel_device_registration.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
+37
View File
@@ -0,0 +1,37 @@
info:
name: Claim Device (Pairing Code)
type: http
seq: 4
http:
method: POST
url: '{{base_url}}/api/devices/claim'
auth: inherit
body:
type: json
data: |-
{
"pairing_code": "583912"
}
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
docs:
content: |-
# Claim Device (Pairing Code)
`POST /api/devices/claim` — auth: jwt.
Canonical reference: docs/developer/api/devices/claim_device.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Clear Shelf
type: http
seq: 3
seq: 5
http:
method: DELETE
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Delete Device
type: http
seq: 4
seq: 6
http:
method: DELETE
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Download Sidecar Config
type: http
seq: 5
seq: 7
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Device
type: http
seq: 6
seq: 8
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Device Collection Mappings
type: http
seq: 7
seq: 9
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Device / Check Registration Status
type: http
seq: 8
seq: 10
http:
method: POST
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Shelf
type: http
seq: 9
seq: 11
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Get Device Sidecar Config
type: http
seq: 10
seq: 12
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Link Book
type: http
seq: 11
seq: 13
http:
method: POST
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: List User Devices
type: http
seq: 12
seq: 14
http:
method: GET
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: List Pending Device Registrations:<|end|><|start|><|start|>assistant to=edit<|channel|>analysis <|constrain|>xml<|message|><rfl:parameter name="path">
type: http
seq: 13
seq: 15
http:
method: GET
+37
View File
@@ -0,0 +1,37 @@
info:
name: Look Up Pairing Code
type: http
seq: 16
http:
method: POST
url: '{{base_url}}/api/devices/claim/lookup'
auth: inherit
body:
type: json
data: |-
{
"pairing_code": "583912"
}
settings:
encodeUrl: true
timeout: 0
followRedirects: true
maxRedirects: 5
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
docs:
content: |-
# Look Up Pairing Code
`POST /api/devices/claim/lookup` — auth: jwt.
Canonical reference: docs/developer/api/devices/lookup_pairing_code.md (docs site → Developer → API). This request is GENERATED from that doc; edit the doc, then run the drift test with -update.
type: text/markdown
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Regenerate Device Token
type: http
seq: 14
seq: 17
http:
method: PUT
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Register Device
type: http
seq: 15
seq: 18
http:
method: POST
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Remove from Shelf
type: http
seq: 17
seq: 19
http:
method: DELETE
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Update Device
type: http
seq: 18
seq: 20
http:
method: PUT
+1 -1
View File
@@ -1,7 +1,7 @@
info:
name: Update Device Collection Mapping
type: http
seq: 19
seq: 21
http:
method: PUT
+10
View File
@@ -60,3 +60,13 @@ variables:
name: book_sha256
- secret: true
name: book_uuid
- secret: true
name: podcasts_library_id
- name: podcast_feed_url
value: https://example.com/feed.xml
- secret: true
name: podcast_feed_id
- secret: true
name: podcast_episode_id
- name: podcast_search_query
value: episode
+30
View File
@@ -0,0 +1,30 @@
info:
name: Add Podcast Feed
type: http
seq: 1
http:
method: POST
url: '{{base_url}}/api/podcasts/feeds'
auth: inherit
body:
type: json
data: |-
{
"library_id": "{{podcasts_library_id}}",
"url": "{{podcast_feed_url}}",
"download_all": false
}
settings:
encodeUrl: true
timeout: 30000
followRedirects: true
maxRedirects: 5
runtime:
scripts:
- type: tests
code: |-
test("status is 201", function() {
expect(res.status).to.eql(201);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Delete Feed (admin; ?files=false keeps files)
type: http
seq: 12
http:
method: DELETE
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Download All (every non-downloaded episode)
type: http
seq: 8
http:
method: POST
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/episodes/all/download'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 202", function() {
expect(res.status).to.eql(202);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Download / Retry Episode (idempotent state machine)
type: http
seq: 7
http:
method: POST
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/episodes/{{podcast_episode_id}}/download'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 202", function() {
expect(res.status).to.eql(202);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Feed Detail (episodes + download states)
type: http
seq: 3
http:
method: GET
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200 (404 would be scoping/RLS)", function() {
expect(res.status).to.eql(200);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: List My Podcast Feeds
type: http
seq: 2
http:
method: GET
url: '{{base_url}}/api/podcasts/feeds'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Manual Refresh (poll one feed)
type: http
seq: 6
http:
method: POST
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/refresh'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Effective Sequence (override applied, downloaded-only, gaps)
type: http
seq: 9
http:
method: GET
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/sequence'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+23
View File
@@ -0,0 +1,23 @@
info:
name: Set Order Override (native | oldest | newest)
type: http
seq: 10
http:
method: PUT
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/order'
auth: inherit
body:
type: json
data: |-
{
"order": "oldest"
}
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Subscription-scoped Search (covers un-downloaded + historical)
type: http
seq: 11
http:
method: GET
url: '{{base_url}}/api/podcasts/search?q={{podcast_search_query}}'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+17
View File
@@ -0,0 +1,17 @@
info:
name: Unsubscribe (files retained)
type: http
seq: 5
http:
method: DELETE
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/subscription'
auth: inherit
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+25
View File
@@ -0,0 +1,25 @@
info:
name: Update Subscription (display name + auto-download)
type: http
seq: 4
http:
method: PUT
url: '{{base_url}}/api/podcasts/feeds/{{podcast_feed_id}}/subscription'
auth: inherit
body:
type: json
data: |-
{
"display_name": "My Serialized Feed",
"auto_download": "newest",
"auto_download_count": 3
}
runtime:
scripts:
- type: tests
code: |-
test("status is 200", function() {
expect(res.status).to.eql(200);
});
+20 -3
View File
@@ -10,6 +10,7 @@ import (
"bookhoard/internal/router"
"bookhoard/internal/services"
"bookhoard/internal/sync"
"bookhoard/internal/version"
"bookhoard/templates"
"context"
"log"
@@ -33,6 +34,7 @@ func (cv *CustomValidator) Validate(i interface{}) error {
}
func main() {
log.Printf("Bookhoard %s (commit %s) starting", version.Version, version.Commit)
cfg := config.LoadConfig()
dbPool, err := pgxpool.New(context.Background(), cfg.DatabaseURL())
@@ -168,15 +170,27 @@ func main() {
opdsHandler := handlers.NewOPDSHandler(queries, libraryService, conversionService)
opdsHandler.SetSettings(registry)
collectionHandler := handlers.NewCollectionHandler(queries, libraryService, connManager)
dashboardService := services.NewDashboardService(queries)
dashboardHandler := handlers.NewDashboardHandler(queries)
// One composed-engine service shared by search AND the collection
// subsystem (item 3.2): tree-driven smart collections evaluate
// through the unified engine.
collectionSearchService := services.NewSearchService(queries, scopedDB)
collectionHandler := handlers.NewCollectionHandler(queries, libraryService, connManager, collectionSearchService)
dashboardService := services.NewDashboardService(queries, collectionSearchService)
dashboardHandler := handlers.NewDashboardHandler(queries, collectionSearchService)
seriesHandler := handlers.NewSeriesHandler(queries)
filtersHandler := handlers.NewFiltersHandler(queries)
mediaHandler := handlers.NewMediaHandler(queries, scopedDB, libraryService, progressService, annotationService)
matchingHandler := handlers.NewMatchingHandler(queries, connManager)
jobsHandler := handlers.NewJobsHandler(queries, worker)
// Podcast subsystem: fetcher service + concurrent download worker
// (§0 item 4: pool, fair share, admin tunables) + poller. One
// instance trio per server (per-feed locks dedupe).
podcastService := services.NewPodcastService(queries)
podcastWorker := services.NewPodcastDownloadWorker(queries, podcastService)
podcastWorker.SetSettings(registry)
podcastHandler := handlers.NewPodcastHandler(queries, podcastService, podcastWorker)
e := echo.New()
// Set up validator
@@ -237,6 +251,9 @@ func main() {
CollectionHandler: collectionHandler,
FiltersHandler: filtersHandler,
DashboardHandler: dashboardHandler,
PodcastHandler: podcastHandler,
PodcastService: podcastService,
PodcastWorker: podcastWorker,
DashboardService: dashboardService,
SeriesHandler: seriesHandler,
OPDSHandler: opdsHandler,
+4 -2
View File
@@ -659,12 +659,14 @@ func TestAudiobookFolderSidecarEditDetected(t *testing.T) {
require.NoError(t, os.WriteFile(sidecar, []byte(`{"title":"Sidecar Real Titlz","series":["Sidecar Saga (Reading Order) #1"]}`), 0o644))
scanTestFolder(t, setup, admin, folder)
var collCount int
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
// Owner-scoped read: collections RLS (2026-10-31) hides rows from
// the pool session's SeedIdentity.
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(admin),
`SELECT COUNT(*) FROM collections WHERE name = 'Sidecar Saga (Reading Order)' AND user_id = $1`, admin,
).Scan(&collCount))
require.Equal(t, 1, collCount, "reading-order sidecar edit creates the collection for an existing book")
scanTestFolder(t, setup, admin, folder)
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(admin),
`SELECT COUNT(*) FROM collections WHERE name = 'Sidecar Saga (Reading Order)' AND user_id = $1`, admin,
).Scan(&collCount))
require.Equal(t, 1, collCount, "rescan is idempotent — no duplicate collection")
+127
View File
@@ -0,0 +1,127 @@
package main
import (
"bytes"
"testing"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Collections RLS (2026-10-31): ownership enforcement moved to the DB
// layer (p_collections_* + parent-checked collection_items policies in
// schema.sql, predicates app_can_read/write_collection). The API surface
// answers invisibility with 404 — including the write endpoints that
// had NO app-level gate (Update/AddBooks, the flagged gap). Admin keeps
// the escape; system collections stay per-user; registration still
// seeds them (the seeding identity fix in
// CreateDefaultCollectionsForUser is regression-pinned here).
func TestCollectionsRLS(t *testing.T) {
setup := setupTestServer(t)
ownerToken := setup.RegularToken // user A: the harness regular user
adminToken := setup.Token
marker := fmt.Sprintf("rls%d", time.Now().UnixNano()%100000)
// User B: a second regular user via registration. The register
// endpoint is rate-limited — exactly one call. The response's
// access_token is B's identity for every probe below.
regEmail := fmt.Sprintf("%s@tests.bookhoard.internal", marker)
regBody := fmt.Sprintf(
`{"email":%q,"username":%q,"password":"Test@Pass123!"}`,
regEmail, "rlsb"+marker)
regResp, err := http.Post(setup.Server.URL+"/api/auth/register",
"application/json", bytes.NewReader([]byte(regBody)))
require.NoError(t, err)
require.Equal(t, http.StatusCreated, regResp.StatusCode,
"registration must succeed — including the system-collection seeding that now runs under the new user's RLS identity")
var reg struct {
Token string `json:"access_token"`
}
require.NoError(t, json.NewDecoder(regResp.Body).Decode(&reg))
require.NotEmpty(t, reg.Token)
otherToken := reg.Token
_ = regResp.Body.Close()
// B's registration seeded B's OWN system collections — visible in
// B's list (this is the registration-seeding identity fix, live).
code, body := podcastAuthed(t, setup, otherToken, "GET", "/api/collections", "")
require.Equal(t, http.StatusOK, code)
assert.Contains(t, string(body), "Continue Reading",
"registration seeded the new user's system collections under RLS")
// A creates the target collection.
code, body = podcastAuthed(t, setup, ownerToken, "POST", "/api/collections",
`{"name":"test RLS Owner ` + marker + `"}`)
require.Equal(t, http.StatusCreated, code, "%s", string(body))
var coll struct {
ID string `json:"id"`
}
require.NoError(t, json.Unmarshal(body, &coll))
t.Cleanup(func() {
podcastAuthed(t, setup, ownerToken, "DELETE", "/api/collections/"+coll.ID, "")
})
// ── B (non-owner) probes A's collection: invisible = 404 ──
code, _ = podcastAuthed(t, setup, otherToken, "GET", "/api/collections/"+coll.ID, "")
require.Equal(t, http.StatusNotFound, code, "detail-by-id is RLS-invisible cross-user")
code, body = podcastAuthed(t, setup, otherToken, "GET", "/api/collections", "")
require.Equal(t, http.StatusOK, code)
assert.NotContains(t, string(body), "test RLS Owner "+marker,
"the list query stays user-scoped")
code, body = podcastAuthed(t, setup, otherToken, "PUT", "/api/collections/"+coll.ID,
`{"name":"renamed by B"}`)
require.Equal(t, http.StatusNotFound, code,
"update of an RLS-invisible row answers 404 (was: ungated success): %s", string(body))
code, body = podcastAuthed(t, setup, otherToken, "POST", "/api/collections/"+coll.ID+"/books",
`{"book_ids":[]}`)
require.Equal(t, http.StatusNotFound, code,
"AddBooks on an RLS-invisible collection answers 404 (the flagged ungated-write gap, closed at the DB)")
code, body = podcastAuthed(t, setup, otherToken, "PUT",
"/api/collections/"+coll.ID+"/view-settings", `{"chain_order":"newest"}`)
require.Equal(t, http.StatusNotFound, code,
"chain-order write on an invisible collection answers 404")
code, _ = podcastAuthed(t, setup, otherToken, "DELETE", "/api/collections/"+coll.ID, "")
require.Equal(t, http.StatusNoContent, code,
"DELETE touches no rows under RLS (silent no-op — no destructive action)")
// The no-op delete lied about nothing: A still owns the collection.
code, body = podcastAuthed(t, setup, ownerToken, "GET", "/api/collections/"+coll.ID, "")
require.Equal(t, http.StatusOK, code, "owner retains the collection after B's failed delete")
// ── admin escape: sees everything, as with media ──
code, _ = podcastAuthed(t, setup, adminToken, "GET", "/api/collections/"+coll.ID, "")
require.Equal(t, http.StatusOK, code, "admin persona sees collections (policy escape)")
// ── B's ownership works: B renames B's OWN system collection ──
// (positive control — B is not locked out of what B owns)
code, body = podcastAuthed(t, setup, otherToken, "GET", "/api/collections", "")
require.Equal(t, http.StatusOK, code)
var list struct {
Collections []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"collections"`
}
require.NoError(t, json.Unmarshal(body, &list))
var bSystem string
for _, c := range list.Collections {
if c.Name == "Continue Reading" {
bSystem = c.ID
break
}
}
require.NotEmpty(t, bSystem, "B owns the seeded system collections")
code, body = podcastAuthed(t, setup, otherToken, "PUT", "/api/collections/"+bSystem,
`{"name":"Continue Reading"}`)
require.Contains(t, []int{http.StatusOK, http.StatusCreated}, code,
"owner mutation of an OWN collection still works: %s", string(body))
}
+95 -140
View File
@@ -56,36 +56,6 @@ func smartGetCollection(t *testing.T, setup *TestServerSetup, token, collectionI
return result
}
func smartPostRule(t *testing.T, setup *TestServerSetup, token, collectionID, field, operator, value string, enabled *bool) *http.Response {
t.Helper()
payload := map[string]interface{}{
"field": field,
"operator": operator,
"value": value,
}
if enabled != nil {
payload["enabled"] = *enabled
}
body, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections/"+collectionID+"/rules", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
return resp
}
func smartDecodeRuleID(t *testing.T, resp *http.Response) string {
t.Helper()
defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body)
var result map[string]interface{}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result))
rule := result["rule"].(map[string]interface{})
return rule["id"].(string)
}
// Data helpers -----------------------------------------------------------
func smartCreateLibraryAndBooks(t *testing.T, setup *TestServerSetup, userID uuid.UUID, titlesByGenre map[string]string) (libraryID string, bookIDs []string) {
t.Helper()
ctx := context.Background()
@@ -145,81 +115,83 @@ func TestSmartCollections(t *testing.T) {
setup := setupTestServer(t)
adminID := getTestUserID(t, setup.DB)
t.Run("FirstRuleConvertsCollectionToSmart_LiveMembership", func(t *testing.T) {
t.Run("TreeCollectionLiveMembership", func(t *testing.T) {
// The unified engine (item 3.2): a collection created WITH a
// books-scope tree evaluates LIVE — stored links are ignored,
// only tree matches render.
_, bookIDs := smartCreateLibraryAndBooks(t, setup, adminID, map[string]string{
"Smart SF Book One": "Science Fiction",
"Smart SF Book Two": "Science Fiction",
"Smart FANT Book": "Fantasy",
})
_ = bookIDs
// Rule evaluation ignores stored links: a static collection's own
// added item must NOT show up once the collection is smart.
collID := smartCreateCollection(t, setup, setup.Token, "Test Smart Live "+uuid.NewString()[:8], "static")
// Add one hand-picked book (a Fantasy one that the smart rule
// will not match — so it must vanish from the render).
addBody, _ := json.Marshal(map[string]interface{}{"book_ids": []string{bookIDs[2]}})
addReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections/"+collID+"/books", bytes.NewBuffer(addBody))
addReq.Header.Set("Content-Type", "application/json")
addReq.Header.Set("Authorization", "Bearer "+setup.Token)
addResp, err := http.DefaultClient.Do(addReq)
tree := map[string]interface{}{
"scope": "books", "mode": "all",
"children": []map[string]interface{}{
{"field": "genre", "op": "is", "values": []string{"Science Fiction"}},
},
}
body, _ := json.Marshal(map[string]interface{}{
"name": "Test Smart Tree " + uuid.NewString()[:8],
"filter_tree": tree,
})
req, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+setup.Token)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusNoContent, addResp.StatusCode)
_ = addResp.Body.Close()
staticDetail := smartGetCollection(t, setup, setup.Token, collID)
assert.Equal(t, false, staticDetail["is_smart"])
assert.Equal(t, float64(1), staticDetail["book_count"], "static collection shows its stored link")
resp := smartPostRule(t, setup, setup.Token, collID, "genre", "equals", "Science Fiction", nil)
require.Equal(t, http.StatusCreated, resp.StatusCode)
var created struct {
ID string `json:"id"`
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&created))
_ = resp.Body.Close()
t.Cleanup(func() {
del, _ := http.NewRequest("DELETE", setup.Server.URL+"/api/collections/"+created.ID, nil)
del.Header.Set("Authorization", "Bearer "+setup.Token)
_, _ = http.DefaultClient.Do(del)
})
smartDetail := smartGetCollection(t, setup, setup.Token, collID)
assert.Equal(t, true, smartDetail["is_smart"], "rules presence derives the type")
assert.Equal(t, float64(2), smartDetail["book_count"], "live rule matches only")
memberTitles := smartLibraryTitleSet(t, smartDetail)
detail := smartGetCollection(t, setup, setup.Token, created.ID)
assert.Equal(t, true, detail["is_smart"], "tree presence derives the type")
memberTitles := smartLibraryTitleSet(t, detail)
assert.True(t, memberTitles["Smart SF Book One"])
assert.True(t, memberTitles["Smart SF Book Two"])
assert.False(t, memberTitles["Smart FANT Book"], "hand-picked link is ignored under smart evaluation (v1 no hybrid)")
})
t.Run("DisabledRuleExcludedFromLiveSet", func(t *testing.T) {
smartCreateLibraryAndBooks(t, setup, adminID, map[string]string{
"Smart Diss Book": "Science Fiction",
})
collID := smartCreateCollection(t, setup, setup.Token, "Test Smart Disabled "+uuid.NewString()[:8], "smart")
resp := smartPostRule(t, setup, setup.Token, collID, "genre", "equals", "Science Fiction", nil)
require.Equal(t, http.StatusCreated, resp.StatusCode)
ruleID := smartDecodeRuleID(t, resp)
assert.Equal(t, float64(1), smartGetCollection(t, setup, setup.Token, collID)["book_count"])
// Disable: membership drops to zero at once.
falseFlag := false
dBody, _ := json.Marshal(map[string]interface{}{"enabled": falseFlag})
dReq, _ := http.NewRequest("PUT", setup.Server.URL+"/api/collections/"+collID+"/rules/"+ruleID, bytes.NewBuffer(dBody))
dReq.Header.Set("Content-Type", "application/json")
dReq.Header.Set("Authorization", "Bearer "+setup.Token)
dResp, err := http.DefaultClient.Do(dReq)
require.NoError(t, err)
require.Equal(t, http.StatusOK, dResp.StatusCode)
_ = dResp.Body.Close()
assert.Equal(t, float64(0), smartGetCollection(t, setup, setup.Token, collID)["book_count"], "disabled rules never match")
assert.False(t, memberTitles["Smart FANT Book"], "the tree's AND governs membership live")
})
t.Run("SmartCollectionsRejectMembershipMutations", func(t *testing.T) {
smartCreateLibraryAndBooks(t, setup, adminID, map[string]string{
"Smart Guard Book": "Science Fiction",
})
collID := smartCreateCollection(t, setup, setup.Token, "Test Smart Guard "+uuid.NewString()[:8], "smart")
resp := smartPostRule(t, setup, setup.Token, collID, "genre", "equals", "Science Fiction", nil)
tree := map[string]interface{}{
"scope": "books", "mode": "all",
"children": []map[string]interface{}{
{"field": "genre", "op": "is", "values": []string{"Science Fiction"}},
},
}
body, _ := json.Marshal(map[string]interface{}{
"name": "Test Smart Guard " + uuid.NewString()[:8],
"filter_tree": tree,
})
req, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+setup.Token)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusCreated, resp.StatusCode)
var created struct {
ID string `json:"id"`
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&created))
_ = resp.Body.Close()
collID := created.ID
t.Cleanup(func() {
del, _ := http.NewRequest("DELETE", setup.Server.URL+"/api/collections/"+collID, nil)
del.Header.Set("Authorization", "Bearer "+setup.Token)
_, _ = http.DefaultClient.Do(del)
})
addBody, _ := json.Marshal(map[string]interface{}{"book_ids": []string{uuid.NewString()}})
addReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections/"+collID+"/books", bytes.NewBuffer(addBody))
@@ -238,53 +210,10 @@ func TestSmartCollections(t *testing.T) {
_ = removeResp.Body.Close()
})
t.Run("RemoveLastRuleRevertsToStatic", func(t *testing.T) {
smartCreateLibraryAndBooks(t, setup, adminID, map[string]string{
"Smart Back Book": "Science Fiction",
})
collID := smartCreateCollection(t, setup, setup.Token, "Test Smart Revert "+uuid.NewString()[:8], "smart")
resp := smartPostRule(t, setup, setup.Token, collID, "tags", "contains", "no-such-tag", nil)
require.Equal(t, http.StatusCreated, resp.StatusCode)
ruleID := smartDecodeRuleID(t, resp)
smartDetail := smartGetCollection(t, setup, setup.Token, collID)
assert.Equal(t, true, smartDetail["is_smart"])
delReq, _ := http.NewRequest("DELETE", setup.Server.URL+"/api/collections/"+collID+"/rules/"+ruleID, nil)
delReq.Header.Set("Authorization", "Bearer "+setup.Token)
delResp, err := http.DefaultClient.Do(delReq)
require.NoError(t, err)
require.Equal(t, http.StatusOK, delResp.StatusCode)
_ = delResp.Body.Close()
staticDetail := smartGetCollection(t, setup, setup.Token, collID)
assert.Equal(t, false, staticDetail["is_smart"], "removing the last rule reverts to static")
// Membership mutations work again on the reverted static.
addBody, _ := json.Marshal(map[string]interface{}{"book_ids": []string{uuid.NewString()}})
addReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections/"+collID+"/books", bytes.NewBuffer(addBody))
addReq.Header.Set("Content-Type", "application/json")
addReq.Header.Set("Authorization", "Bearer "+setup.Token)
addResp, err := http.DefaultClient.Do(addReq)
require.NoError(t, err)
assert.Equal(t, http.StatusNoContent, addResp.StatusCode)
_ = addResp.Body.Close()
})
t.Run("RuleValidationAndSystemCollections", func(t *testing.T) {
collID := smartCreateCollection(t, setup, setup.Token, "Test Smart Valid "+uuid.NewString()[:8], "static")
resp := smartPostRule(t, setup, setup.Token, collID, "not_a_field", "equals", "x", nil)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
_ = resp.Body.Close()
resp = smartPostRule(t, setup, setup.Token, collID, "genre", "equals", "Science Fiction", nil)
require.Equal(t, http.StatusCreated, resp.StatusCode)
_ = resp.Body.Close()
// System collections may never carry rules.
colls, err := setup.DB.GetCollectionsByUser(context.Background(), pgtype.UUID{Bytes: [16]byte(adminID), Valid: true})
t.Run("SystemCollectionsBlockedFromTheEditor", func(t *testing.T) {
// System collections may never carry rules/trees — the editor
// route refuses them (item 3.4: the page IS the editor).
colls, err := setup.DB.GetCollectionsByUser(ownerSeedCtx(pgtype.UUID{Bytes: [16]byte(adminID), Valid: true}), pgtype.UUID{Bytes: [16]byte(adminID), Valid: true})
require.NoError(t, err)
var systemID string
for _, c := range colls {
@@ -295,20 +224,46 @@ func TestSmartCollections(t *testing.T) {
}
require.NotEmpty(t, systemID, "admin user should have system collections")
sysResp := smartPostRule(t, setup, setup.Token, systemID, "genre", "equals", "x", nil)
require.Equal(t, http.StatusBadRequest, sysResp.StatusCode)
_ = sysResp.Body.Close()
req, _ := http.NewRequest("GET", setup.Server.URL+"/collections/"+systemID+"/rules", nil)
req.Header.Set("Authorization", "Bearer "+setup.Token)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body)
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"system collections never render the smart editor")
})
t.Run("CollectionsListRespectsIncludeAutoWithLiveCounts", func(t *testing.T) {
_, _ = smartCreateLibraryAndBooks(t, setup, adminID, map[string]string{
"Smart List Book": "Science Fiction",
})
collID := smartCreateCollection(t, setup, setup.Token, "Test Smart List "+uuid.NewString()[:8], "smart")
resp := smartPostRule(t, setup, setup.Token, collID, "genre", "equals", "Science Fiction", nil)
require.Equal(t, http.StatusCreated, resp.StatusCode)
_ = resp.Body.Close()
tree := map[string]interface{}{
"scope": "books", "mode": "all",
"children": []map[string]interface{}{
{"field": "genre", "op": "is", "values": []string{"Science Fiction"}},
},
}
body, _ := json.Marshal(map[string]interface{}{
"name": "Test Smart List " + uuid.NewString()[:8],
"filter_tree": tree,
})
req2, _ := http.NewRequest("POST", setup.Server.URL+"/api/collections", bytes.NewBuffer(body))
req2.Header.Set("Content-Type", "application/json")
req2.Header.Set("Authorization", "Bearer "+setup.Token)
resp2, err := http.DefaultClient.Do(req2)
require.NoError(t, err)
require.Equal(t, http.StatusCreated, resp2.StatusCode)
var created struct {
ID string `json:"id"`
}
require.NoError(t, json.NewDecoder(resp2.Body).Decode(&created))
_ = resp2.Body.Close()
collID := created.ID
t.Cleanup(func() {
del, _ := http.NewRequest("DELETE", setup.Server.URL+"/api/collections/"+collID, nil)
del.Header.Set("Authorization", "Bearer "+setup.Token)
_, _ = http.DefaultClient.Do(del)
})
// Default list (the Android app's read): smart collections hidden.
req, _ := http.NewRequest("GET", setup.Server.URL+"/api/collections", nil)
+54 -5
View File
@@ -168,7 +168,13 @@ func createContractDeviceNamed(t *testing.T, setup *TestServerSetup, name, devic
DeviceMetadata: []byte("{}"),
})
require.NoError(t, err, "Should create sync device")
_ = device
// Self-delete at test end: the contract helper attaches to the
// SHARED admin (the web progress push adopts the device name, so
// conflict tests drive a second named source without a separate
// account) and names it for its surface — "koreader" passes every
// name-based sweep, so without this the row survived forever (294
// of them ended up on the dev account's device grid).
t.Cleanup(func() { _ = setup.DB.DeleteDevice(context.Background(), device.ID) })
return token
}
@@ -459,6 +465,8 @@ var bookInfoKeys = []string{
"media_item_id", "title", "author", "cover_image_path",
"has_conflict", "format_group", "badge",
"viewer_percentage", "library_name",
// Episode-collections extras (2.3 widening, every surface emits):
"is_episode", "feed_title", "download_state", "hidden",
}
func collectionURL(setup *TestServerSetup, id string) string {
@@ -498,8 +506,9 @@ func TestContractPin_CollectionsJSON(t *testing.T) {
// payload; docs/contract_pins.md changelog).
envelopeKeys := []string{
"id", "user_id", "name", "description", "color", "icon",
"auto_assign_rules", "view_settings", "books", "book_count",
"view_settings", "books", "book_count",
"is_smart", "created_at", "up_next",
"filter_tree", // item-3.2 widening (docs/contract_pins.md)
}
t.Run("user collection with library_id (badged branch)", func(t *testing.T) {
@@ -562,11 +571,14 @@ func TestContractPin_CollectionsJSON(t *testing.T) {
assertArrayItemShape(t, "collection books[] (no library)", books, bookInfoKeys, bookInfoKeys)
})
t.Run("smart collection (rules branch)", func(t *testing.T) {
t.Run("smart collection (tree branch)", func(t *testing.T) {
resp := doReq(t, "POST", setup.Server.URL+"/api/collections", map[string]interface{}{
"name": fmt.Sprintf("Test Contract Smart %d", time.Now().UnixNano()),
"auto_assign_rules": []map[string]interface{}{
{"id": "rule-1", "field": "genre", "operator": "equals", "value": "Science Fiction", "priority": 5},
"filter_tree": map[string]interface{}{
"scope": "books", "mode": "any",
"children": []map[string]interface{}{
{"field": "genre", "op": "is", "values": []string{"Science Fiction"}},
},
},
}, setup.Token)
defer resp.Body.Close()
@@ -752,6 +764,19 @@ func TestContractPin_MediaListBothBranches(t *testing.T) {
"tags_search", "contributors_search", "narrators_search", "file_sha256",
"opf_identifier", "opf_uuid", "hash_confidence", "library_name",
"library_type_name_2",
// Podcast episode columns (2026-10-29 additive widening — plan
// podcast-integration.md tasks 1.1/1.10): columns on
// media_items, NULL for scan rows. See docs/contract_pins.md
// changelog.
"source", "source_feed_id", "episode_guid", "feed_position",
"season_number", "episode_number", "enclosure_url",
"declared_duration_seconds", "transcript_url", "chapters_url",
"hosts", "guests", "download_state", "download_error",
"download_attempts",
// §0 item 4 (2026-10-30 additive widening): the download pool's
// queue ticket — SEQUENCE-stamped at enqueue, NULL for scan rows
// and never-queued episodes. See docs/contract_pins.md changelog.
"download_queue_pos",
}
resolvedKeys := []string{
"id", "library_id", "title", "subtitle", "author", "authors", "isbn", "description",
@@ -1189,6 +1214,30 @@ func pinAnnotationLifecycle(t *testing.T, setup *TestServerSetup, fx contractFix
require.NoError(t, json.Unmarshal(raw, &body2))
assertResponseShape(t, "annotation "+kind+" update", body2, rowKeys, rowKeys)
// The restore half of the round trip: what the reader fetches
// when the book is reopened must return the persisted annotation
// with the update applied — written to the DB, read back through
// the same list endpoint the UI loads on open.
t.Run(kind+" GET list restores the annotation", func(t *testing.T) {
resp3 := doReq(t, "GET", annotationURL(setup.Server.URL, fx.itemID, kind, ""), nil, setup.RegularToken)
defer resp3.Body.Close()
require.Equal(t, http.StatusOK, resp3.StatusCode, "list must stay 200")
var list []map[string]interface{}
require.NoError(t, json.NewDecoder(resp3.Body).Decode(&list))
var found map[string]interface{}
for _, row := range list {
if row["id"] == id {
found = row
break
}
}
require.NotNil(t, found, "created %s must come back in the list that restores a reopened book", kind)
updates, _ := updateBody.(map[string]interface{})
for key, want := range updates {
assert.Equal(t, want, found[key], "%s field must round-trip from the DB on restore", key)
}
})
t.Run(kind+" DELETE response", func(t *testing.T) {
resp3 := doReq(t, "DELETE", annotationURL(setup.Server.URL, fx.itemID, kind, id), nil, setup.RegularToken)
defer resp3.Body.Close()
@@ -0,0 +1,157 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"bookhoard/internal/database"
)
// The custom-section builder's save, end to end (2026-10-31 tree
// migration). The page posts the legacy rules vocabulary — rules as a
// JSON-encoded ARRAY inside a STRING (it has done so since the page was
// written, 2026-02-19; the save never once bound successfully before
// the migration) — plus match_type, hand-picked book ids, and the
// dashboard pin. The server converts the rules to a filter tree at
// write time, attaches the manual picks, and the dashboard section
// renders stored membership + the tree's live matches, deduped.
func TestCustomSectionBuilderSave(t *testing.T) {
setup := setupTestServer(t)
adminToken := setup.Token
regToken := setup.RegularToken
marker := fmt.Sprintf("csb%d", time.Now().UnixNano()%100000)
libID := createTestLibraryWithFolder(t, setup.Server, adminToken, "test CSB Library "+marker, true)
libUUID, err := uuid.Parse(libID)
require.NoError(t, err)
// Two items the title rule matches, one it doesn't. Alpha is ALSO
// hand-picked — the section must render it once, not twice.
makeItem := func(title string) uuid.UUID {
id, cerr := setup.DB.CreateMediaItem(seedCtx(), database.CreateMediaItemParams{
LibraryID: pgtype.UUID{Bytes: libUUID, Valid: true},
Title: title,
Authors: []string{"CSB Author"},
FilePath: fmt.Sprintf("/tmp/csb/%s-%s.epub", marker, strings.ReplaceAll(title, " ", "-")),
FileSize: pgtype.Int8{Int64: 128, Valid: true},
MimeType: pgtype.Text{String: "application/epub+zip", Valid: true},
})
require.NoError(t, cerr)
out, perr := uuid.FromBytes(id.ID.Bytes[:])
require.NoError(t, perr)
return out
}
alpha := makeItem("CSBRULE Alpha")
_ = makeItem("CSBRULE Beta")
manual := makeItem("CSB Manual Pick")
require.NotZero(t, alpha)
// The EXACT payload shape the builder page posts.
payload := fmt.Sprintf(`{
"library_id": %q,
"name": "test CSB Section %s",
"icon": "📚",
"description": "built by the custom-section builder",
"show_on_dashboard": true,
"auto_assign_rules": %[3]s,
"manual_book_ids": [%q, %q],
"match_type": "all"
}`, libID, marker,
`"[{\"field\":\"title\",\"operator\":\"contains\",\"value\":\"CSBRULE\"}]"`,
alpha.String(), manual.String())
code, body := podcastAuthed(t, setup, regToken, "POST", "/api/collections", payload)
require.Equal(t, http.StatusCreated, code, "%s", string(body))
var coll struct {
ID string `json:"id"`
}
require.NoError(t, json.Unmarshal([]byte(body), &coll))
collID := coll.ID
require.NotEmpty(t, collID)
t.Cleanup(func() {
podcastAuthed(t, setup, regToken, "DELETE", "/api/collections/"+collID, "")
})
// The converted tree round-trips: root mode from match_type, the
// rule as a qf child, and the collection IS smart with no
// collection_type sent.
code, body = podcastAuthed(t, setup, regToken, "GET", "/api/collections/"+collID, "")
require.Equal(t, http.StatusOK, code)
var detail struct {
IsSmart bool `json:"is_smart"`
FilterTree struct {
Mode string `json:"mode"`
Children []struct {
Field string `json:"field"`
Op string `json:"op"`
Values []string `json:"values"`
} `json:"children"`
} `json:"filter_tree"`
}
require.NoError(t, json.Unmarshal([]byte(body), &detail))
assert.True(t, detail.IsSmart, "converted rules make the collection smart")
assert.Equal(t, "all", detail.FilterTree.Mode, "match_type seeds the tree's root mode")
require.Len(t, detail.FilterTree.Children, 1)
assert.Equal(t, "title", detail.FilterTree.Children[0].Field)
assert.Equal(t, []string{"CSBRULE"}, detail.FilterTree.Children[0].Values)
// The dashboard section renders stored membership + live matches,
// deduped: Alpha (rule + manual), Beta (rule), Manual (manual).
code, body = podcastAuthed(t, setup, regToken, "GET",
"/api/dashboard/sections?library_id="+libID, "")
require.Equal(t, http.StatusOK, code, "%s", string(body))
var dash struct {
Sections []struct {
Title string `json:"title"`
CollectionID string `json:"collection_id"`
Items []struct {
Title string `json:"title"`
} `json:"items"`
} `json:"sections"`
}
require.NoError(t, json.Unmarshal([]byte(body), &dash))
var section *struct {
Title string `json:"title"`
CollectionID string `json:"collection_id"`
Items []struct {
Title string `json:"title"`
} `json:"items"`
}
for i := range dash.Sections {
if dash.Sections[i].CollectionID == collID {
section = &dash.Sections[i]
break
}
}
require.NotNil(t, section, "the custom section renders on the dashboard: %s", string(body))
titles := map[string]int{}
for _, it := range section.Items {
titles[it.Title]++
}
assert.Equal(t, 1, titles["CSBRULE Alpha"], "rule-matched AND hand-picked renders exactly once")
assert.Equal(t, 1, titles["CSBRULE Beta"], "rule match rides the tree")
assert.Equal(t, 1, titles["CSB Manual Pick"], "manual picks are attached")
assert.Len(t, section.Items, 3, "nothing else leaks into the section")
}
// TestCustomSectionBuilderBadRule pins the adapter's rejection path: a
// rule the engine cannot honor is a 400 that names the field, never a
// stored 500 at render time.
func TestCustomSectionBuilderBadRule(t *testing.T) {
setup := setupTestServer(t)
regToken := setup.RegularToken
code, body := podcastAuthed(t, setup, regToken, "POST", "/api/collections",
`{"name":"test CSB Bad `+fmt.Sprint(time.Now().UnixNano())+`","auto_assign_rules":"[{\"field\":\"not_a_field\",\"operator\":\"contains\",\"value\":\"x\"}]"}`)
assert.Equal(t, http.StatusBadRequest, code, "%s", string(body))
assert.Contains(t, string(body), "section rule")
}
+315
View File
@@ -0,0 +1,315 @@
package main
// Pairing-code flow integration tests. The register response mints a
// 6-digit code shown on the registering device's screen; the person
// holding the device types it into THEIR account (POST /api/devices/claim).
// This replaces the retired broadcast-list approve, where
// first-click-wins let any account claim (or reject) a device it could
// see but not name.
//
// Devices claimed here land on the fresh per-run regular user, so the
// harness cascade removes them; identifiers are uuid-suffixed to stay
// clear of the UNIQUE(device_identifier) index across runs.
import (
"bookhoard/internal/database"
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// registerPairingDevice initiates a registration and returns its decoded
// response (registration_id, pairing_code, ...).
func registerPairingDevice(t *testing.T, setup *TestServerSetup, identifier string) map[string]interface{} {
t.Helper()
regRequest := map[string]interface{}{
"device_name": "Test Pairing Device",
"device_type": "koreader",
"device_identifier": identifier,
}
regBody, _ := json.Marshal(regRequest)
req := httptest.NewRequest("POST", "/api/devices/register", bytes.NewReader(regBody))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusCreated, rec.Code, "Should initiate registration")
var regResponse map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &regResponse)
return regResponse
}
// pollRegistrationStatus hits the device-side status endpoint (no auth —
// the registration UUID is the bearer).
func pollRegistrationStatus(t *testing.T, setup *TestServerSetup, registrationID string) (int, map[string]interface{}) {
t.Helper()
body, _ := json.Marshal(map[string]string{"registration_id": registrationID})
req := httptest.NewRequest("POST", "/api/devices/register/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
var resp map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &resp)
return rec.Code, resp
}
func pairingCodeBody(code string) []byte {
body, _ := json.Marshal(map[string]string{"pairing_code": code})
return body
}
// pairingLookupOrClaim POSTs to the given claim-family endpoint with the
// given bearer token and returns status + decoded body.
func pairingLookupOrClaim(t *testing.T, setup *TestServerSetup, path, token, code string) (int, map[string]interface{}) {
t.Helper()
req := httptest.NewRequest("POST", path, bytes.NewReader(pairingCodeBody(code)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
var resp map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &resp)
return rec.Code, resp
}
// wrongPairingCode derives a code guaranteed to differ from the target's
// digits (rotate each digit +1 mod 10).
func wrongPairingCode(code string) string {
rotated := make([]byte, len(code))
for i := 0; i < len(code); i++ {
rotated[i] = byte('0' + (int(code[i]-'0')+1)%10)
}
return string(rotated)
}
// pairingFormRequest POSTs urlencoded form data — the Content-Type the
// browser's htmx forms actually send — with a Bearer token.
func pairingFormRequest(t *testing.T, setup *TestServerSetup, path, token, body string) (int, map[string]interface{}) {
t.Helper()
req := httptest.NewRequest("POST", path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
var resp map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &resp)
return rec.Code, resp
}
// TestPairingClaimAcceptsBrowserFormEncoding pins the htmx path: the
// confirm card claims via a urlencoded <form>, so echo v5 routes the
// Content-Type to the `form:` binder, which maps by `form:` struct tag
// only. (Regression: PairingCodeRequest shipped with a json-only tag,
// leaving the code empty and every browser claim failing with 400 —
// "how did lookup find the device if the code is wrong?") The JSON path
// stays pinned by the tests above; this covers the form twin.
func TestPairingClaimAcceptsBrowserFormEncoding(t *testing.T) {
setup := setupTestServer(t)
identifier := fmt.Sprintf("pairing-form-%s", uuid.New().String())
reg := registerPairingDevice(t, setup, identifier)
code := reg["pairing_code"].(string)
// Form-encoded lookup (the same call the API-side confirm card makes).
status, resp := pairingFormRequest(t, setup, "/api/devices/claim/lookup",
setup.RegularToken, "pairing_code="+code)
require.Equal(t, http.StatusOK, status, "form-encoded lookup must resolve the live code")
assert.Equal(t, "Test Pairing Device", resp["device_name"])
// Form-encoded claim — exactly what the browser's Pair device
// button sends (urlencoded hidden input, not JSON).
status, resp = pairingFormRequest(t, setup, "/api/devices/claim",
setup.RegularToken, "pairing_code="+code)
require.Equal(t, http.StatusOK, status, "form-encoded claim must bind the device")
assert.Equal(t, true, resp["approved"])
// The device's own poll delivers credentials — binding really happened.
pollStatus, pollResp := pollRegistrationStatus(t, setup, reg["registration_id"].(string))
require.Equal(t, http.StatusOK, pollStatus)
assert.Equal(t, "approved", pollResp["status"])
}
func TestPairingClaimHappyPath(t *testing.T) {
setup := setupTestServer(t)
identifier := fmt.Sprintf("pairing-happy-%s", uuid.New().String())
reg := registerPairingDevice(t, setup, identifier)
code, ok := reg["pairing_code"].(string)
require.True(t, ok, "register response must carry pairing_code")
require.Len(t, code, 6, "pairing code must be 6 digits")
for _, d := range code {
require.GreaterOrEqual(t, d, '0')
require.LessOrEqual(t, d, '9')
}
// Lookup first — the confirm card's data, without binding.
status, resp := pairingLookupOrClaim(t, setup, "/api/devices/claim/lookup", setup.RegularToken, " "+code[:3]+" "+code[3:])
require.Equal(t, http.StatusOK, status, "lookup should resolve the live code (spaces normalized)")
assert.Equal(t, "Test Pairing Device", resp["device_name"])
assert.NotEmpty(t, resp["expires_in"])
// Still pending — lookup must not have bound anything.
pollStatus, pollResp := pollRegistrationStatus(t, setup, reg["registration_id"].(string))
require.Equal(t, http.StatusOK, pollStatus)
assert.Equal(t, "pending", pollResp["status"])
// Claim as the fresh regular user (deterministic account per doctrine).
status, resp = pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code)
require.Equal(t, http.StatusOK, status, "claim should bind the device")
assert.Equal(t, true, resp["approved"])
// The device's own poll now delivers credentials.
pollStatus, pollResp = pollRegistrationStatus(t, setup, reg["registration_id"].(string))
require.Equal(t, http.StatusOK, pollStatus)
assert.Equal(t, "approved", pollResp["status"])
token, ok := pollResp["auth_token"].(string)
require.True(t, ok, "approved poll must deliver the auth token")
require.NotEmpty(t, token)
// The device row belongs to the claimer, and the poll-delivered token
// matches the stored row.
devices, err := setup.DB.ListDevicesByUser(context.Background(),
pgtype.UUID{Bytes: [16]byte(getRegularUserID(t, setup.DB)), Valid: true})
require.NoError(t, err)
var found *database.Devices
for i := range devices {
if devices[i].DeviceIdentifier == identifier {
found = &devices[i]
}
}
require.NotNil(t, found, "device row must exist under the claimer")
assert.Equal(t, token, found.AuthToken, "poll-delivered token must match the stored row")
}
func TestPairingWrongCodeIsGenericAndNonDestructive(t *testing.T) {
setup := setupTestServer(t)
reg := registerPairingDevice(t, setup, fmt.Sprintf("pairing-miss-%s", uuid.New().String()))
code := reg["pairing_code"].(string)
// A wrong code fails with the generic message — no hint whether any
// registration is waiting.
status, resp := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, wrongPairingCode(code))
require.Equal(t, http.StatusBadRequest, status)
assert.Equal(t, "invalid pairing code", resp["error"])
// The miss must not have killed or claimed the real registration.
status, resp = pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code)
require.Equal(t, http.StatusOK, status, "the correct code must still claim after a miss")
assert.Equal(t, true, resp["approved"])
}
func TestPairingClaimBindsClaimerOnly(t *testing.T) {
setup := setupTestServer(t)
identifier := fmt.Sprintf("pairing-scope-%s", uuid.New().String())
reg := registerPairingDevice(t, setup, identifier)
code := reg["pairing_code"].(string)
// The regular user claims it.
status, _ := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code)
require.Equal(t, http.StatusOK, status)
// The admin (a different account) has no such device — and cannot
// re-claim the now-used code either.
adminDevices, err := setup.DB.ListDevicesByUser(context.Background(),
pgtype.UUID{Bytes: [16]byte(getTestUserID(t, setup.DB)), Valid: true})
require.NoError(t, err)
for _, d := range adminDevices {
assert.NotEqual(t, identifier, d.DeviceIdentifier,
"device must be bound to the claimer, not to every account")
}
status, resp := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.Token, code)
assert.Equal(t, http.StatusConflict, status, "an already-used code must not bind again")
assert.Contains(t, resp["error"], "already used")
}
func TestPairingReRegisterRetiresPriorCode(t *testing.T) {
setup := setupTestServer(t)
identifier := fmt.Sprintf("pairing-retry-%s", uuid.New().String())
reg1 := registerPairingDevice(t, setup, identifier)
reg2 := registerPairingDevice(t, setup, identifier)
code1, ok := reg1["pairing_code"].(string)
require.True(t, ok)
code2, ok := reg2["pairing_code"].(string)
require.True(t, ok)
require.NotEqual(t, code1, code2, "each registration mints its own code")
// The retired attempt is gone from both the code and UUID channels.
status, _ := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code1)
assert.Equal(t, http.StatusBadRequest, status, "retired code must not claim")
pollStatus, _ := pollRegistrationStatus(t, setup, reg1["registration_id"].(string))
assert.Equal(t, http.StatusNotFound, pollStatus, "retired registration must not poll")
// The fresh code claims fine.
status, resp := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code2)
require.Equal(t, http.StatusOK, status)
assert.Equal(t, true, resp["approved"])
}
func TestPairingCancelByRegistrationUUID(t *testing.T) {
setup := setupTestServer(t)
cancelled := registerPairingDevice(t, setup, fmt.Sprintf("pairing-cancel-%s", uuid.New().String()))
kept := registerPairingDevice(t, setup, fmt.Sprintf("pairing-keep-%s", uuid.New().String()))
// Cancel only the first attempt — bearer is its own registration UUID.
body, _ := json.Marshal(map[string]string{"registration_id": cancelled["registration_id"].(string)})
req := httptest.NewRequest("POST", "/api/devices/register/cancel", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, "cancel should succeed")
// Cancelled: code dead, status poll gone.
code1 := cancelled["pairing_code"].(string)
status, _ := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code1)
assert.Equal(t, http.StatusBadRequest, status, "cancelled code must not claim")
pollStatus, _ := pollRegistrationStatus(t, setup, cancelled["registration_id"].(string))
assert.Equal(t, http.StatusNotFound, pollStatus, "cancelled registration must not poll")
// Idempotent: cancelling again is still a 200.
req = httptest.NewRequest("POST", "/api/devices/register/cancel", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec = httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code, "cancel must be idempotent")
// The other registration is untouched by its neighbour's cancel.
code2 := kept["pairing_code"].(string)
status, resp := pairingLookupOrClaim(t, setup, "/api/devices/claim", setup.RegularToken, code2)
require.Equal(t, http.StatusOK, status, "cancel must scope to its own registration only")
assert.Equal(t, true, resp["approved"])
}
func TestPairingAttemptRateLimit(t *testing.T) {
setup := setupTestServer(t)
// The regular user is fresh per setup, so the limiter key
// (userID|ip) is this test's alone — the budget cannot have been
// pre-spent by sibling tests sharing the process-global limiter.
// Burn the budget with bad lookups (12/min); the 13th attempt must
// be refused before the code check.
for i := 0; i < 12; i++ {
code := fmt.Sprintf("%06d", i*7919+13)
status, _ := pairingLookupOrClaim(t, setup, "/api/devices/claim/lookup", setup.RegularToken, code)
require.Equal(t, http.StatusBadRequest, status, "attempt %d should fail as a plain miss", i+1)
}
status, resp := pairingLookupOrClaim(t, setup, "/api/devices/claim/lookup", setup.RegularToken, "999999")
assert.Equal(t, http.StatusTooManyRequests, status, "13th attempt must hit the budget")
assert.Contains(t, resp["error"], "too many")
}
+44 -14
View File
@@ -19,6 +19,9 @@ import (
func TestDeviceRegistrationFlow(t *testing.T) {
setup := setupTestServer(t)
// Approved through the shared admin's session; the row must not
// outlive the test (name hygiene alone should never carry it).
cleanupDeviceByIdentifier(t, setup, "kindle-test-hw-id-12345")
// Step 1: Initiate device registration
regRequest := map[string]interface{}{
@@ -208,6 +211,7 @@ func TestDeviceAuthentication(t *testing.T) {
// Create a device directly in the database
userID := getTestUserID(t, setup.DB)
cleanupDeviceByIdentifier(t, setup, "test-device-123")
deviceToken := fmt.Sprintf("dev_%s", uuid.New().String())
_, err := setup.DB.CreateDevice(context.Background(), database.CreateDeviceParams{
@@ -237,10 +241,25 @@ func TestDeviceAuthentication(t *testing.T) {
func TestListPendingRegistrations(t *testing.T) {
setup := setupTestServer(t)
req := httptest.NewRequest("GET", "/api/devices/pending", nil)
req.Header.Set("Authorization", "Bearer "+setup.Token)
// A live registration must NOT appear in any account's pending list:
// the broadcast is what let any user claim (or reject) someone else's
// device. Pairing codes replaced it — see device_pairing_test.go.
regRequest := map[string]interface{}{
"device_name": "Broadcast Test Device",
"device_type": "koreader",
"device_identifier": fmt.Sprintf("broadcast-test-%s", uuid.New().String()),
}
regBody, _ := json.Marshal(regRequest)
req := httptest.NewRequest("POST", "/api/devices/register", bytes.NewReader(regBody))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusCreated, rec.Code, "Should initiate registration")
req = httptest.NewRequest("GET", "/api/devices/pending", nil)
req.Header.Set("Authorization", "Bearer "+setup.Token)
rec = httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code, "Should list pending registrations")
@@ -248,8 +267,9 @@ func TestListPendingRegistrations(t *testing.T) {
json.Unmarshal(rec.Body.Bytes(), &response)
pending, ok := response["pending_registrations"].([]interface{})
assert.True(t, ok, "Should have pending_registrations array")
assert.NotNil(t, pending, "Pending registrations should not be nil")
require.True(t, ok, "Should have pending_registrations array")
assert.Empty(t, pending, "Unclaimed registrations must be invisible to every account")
assert.Equal(t, float64(0), response["total"], "Total must stay zero while a registration is live")
}
// Regression test for the "approve returns 500 after app reinstall" bug:
@@ -263,6 +283,10 @@ func TestApproveDeviceReapprovalRotatesToken(t *testing.T) {
userID := getTestUserID(t, setup.DB)
identifier := fmt.Sprintf("repro-reinstall-%s", uuid.New().String())
// Self-delete: the row is named "Reinstall Device" — the web
// reinstall flow's own label — so the name-based sweeps can never
// safely touch it. The identifier is this test's fixture alone.
cleanupDeviceByIdentifier(t, setup, identifier)
registerAndApprove := func() string {
regRequest := map[string]interface{}{
@@ -336,6 +360,9 @@ func TestApproveDeviceReapprovalRotatesToken(t *testing.T) {
func TestApproveDeviceRegistration(t *testing.T) {
setup := setupTestServer(t)
// Approved through the shared admin's session; the row must not
// outlive the test (name hygiene alone should never carry it).
cleanupDeviceByIdentifier(t, setup, "test-approval-12345")
regRequest := map[string]interface{}{
"device_name": "Test Device for Approval",
@@ -370,13 +397,18 @@ func TestApproveDeviceRegistration(t *testing.T) {
assert.True(t, approveResponse["approved"].(bool), "Should confirm approval")
}
func TestRejectDeviceRegistration(t *testing.T) {
// TestRejectDeviceRegistrationRemoved pins the removal: the reject route is
// gone because unclaimed registrations are invisible since pairing codes
// took over — there is nothing left for anyone to reject. See
// device_pairing_test.go for the replacement flow (cancel by the
// registering device itself).
func TestRejectDeviceRegistrationRemoved(t *testing.T) {
setup := setupTestServer(t)
regRequest := map[string]interface{}{
"device_name": "Test Device for Rejection",
"device_type": "koreader",
"device_identifier": "test-rejection-12345",
"device_identifier": fmt.Sprintf("test-rejection-%s", uuid.New().String()),
}
regBody, _ := json.Marshal(regRequest)
@@ -385,25 +417,23 @@ func TestRejectDeviceRegistration(t *testing.T) {
rec := httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusCreated, rec.Code, "Should initiate device registration")
require.Equal(t, http.StatusCreated, rec.Code, "Should initiate device registration")
var regResponse map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &regResponse)
registrationID, ok := regResponse["registration_id"].(string)
assert.True(t, ok, "Should have registration_id")
require.True(t, ok, "Should have registration_id")
req = httptest.NewRequest("POST", fmt.Sprintf("/api/devices/reject/%s", registrationID), nil)
req.Header.Set("Authorization", "Bearer "+setup.Token)
rec = httptest.NewRecorder()
setup.Server.Config.Handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code, "Should reject device registration")
var rejectResponse map[string]interface{}
json.Unmarshal(rec.Body.Bytes(), &rejectResponse)
assert.Equal(t, "device registration rejected", rejectResponse["message"], "Should confirm rejection message")
// 404 = no route, 405 = path-shaped collision without POST — either
// proves the reject surface is gone.
assert.True(t, rec.Code == http.StatusNotFound || rec.Code == http.StatusMethodNotAllowed,
"Reject route must not exist (registration invisible, nothing to reject); got %d", rec.Code)
}
func TestRegenerateDeviceToken_Success(t *testing.T) {
+218 -8
View File
@@ -295,6 +295,115 @@ func TestFilterComposedSemantics(t *testing.T) {
assert.Equal(t, []string{"Sem Tide"}, got, "published_year at_least")
}
// TestFilterScopesAndEpisodeFields pins item 3.1: the books scope
// excludes podcasts (the leak the composed head used to have), the
// episodes scope is episodes only, episode fields evaluate in SQL
// (feed-in, downloaded, played, published-date-within), and episode
// fields are 400s in books trees.
func TestFilterScopesAndEpisodeFields(t *testing.T) {
setup := setupTestServer(t)
t.Cleanup(func() { _ = setup.Close() })
regUUID := getRegularUserID(t, setup.DB)
builderFixtureLib(t, setup, regUUID, "Scope")
// Podcasts library + a subscribed feed with three downloaded
// episodes: two fresh/unplayed, one played (~finished) — the
// played-rule fixture.
feedLib, _ := createPodcastsLibrary(t, setup, "test Scope Podcasts")
feed, err := setup.DB.CreatePodcastFeed(adminSeedCtx(t, setup), database.CreatePodcastFeedParams{
LibraryID: feedLib.ID,
FeedUrl: "https://feed.invalid/scope-probe.xml",
Title: "Scope Probe Feed",
})
require.NoError(t, err)
epFresh := upsertTestEpisode(t, setup, feed, "scope-fresh", "Scope Fresh Episode", 1)
epPlayed := upsertTestEpisode(t, setup, feed, "scope-played", "Scope Played Episode", 2)
upsertTestEpisode(t, setup, feed, "scope-pending", "Scope Pending Episode", 3)
subscribeRaw(t, setup, regUUID, feed.ID)
adminScopeExec(t, setup, adminCtxValue(t, setup), `
UPDATE media_items SET download_state = 'downloaded', file_size = 1000,
date_published = CURRENT_DATE WHERE id IN ($1, $2)`, epFresh.ID, epPlayed.ID)
adminScopeExec(t, setup, adminCtxValue(t, setup), `
INSERT INTO reading_progress (media_item_id, user_id, percentage)
VALUES ($1, $2, 1.0) ON CONFLICT (media_item_id, user_id)
DO UPDATE SET percentage = 1.0`, epPlayed.ID, regUUID)
feedID := uuid.UUID(feed.ID.Bytes).String()
qfScoped := func(scope string, children ...map[string]interface{}) url.Values {
b, _ := json.Marshal(map[string]interface{}{"scope": scope, "mode": "all", "children": children})
return url.Values{"qf": {string(b)}}
}
const booksScope = "books"
const episodesScope = "episodes"
search := func(p url.Values) []string {
rows := p
status, body := qfSearch(t, setup, setup.RegularToken, rows)
// 404 is the endpoint's pinned no-results contract — an empty set.
require.Contains(t, []int{http.StatusOK, http.StatusNotFound}, status, "qf must parse: %v", rows)
return qfTitles(t, body)
}
t.Run("books_scope_excludes_podcasts", func(t *testing.T) {
// An exact-ish title hits BOTH a book fixture ("Scope Tide") and
// the episode fixture if the head leaks; books scope must return
// the book, never the episodes.
got := search(qfScoped(booksScope, qfRule("title", "is", "Scope Tide")))
assert.Equal(t, []string{"Scope Tide"}, got, "books scope returns the book")
got = search(qfScoped(booksScope, qfRule("title", "is", "Scope Fresh Episode")))
assert.Empty(t, got,
"books scope must never return podcast episodes (the composed-head leak is CLOSED)")
})
t.Run("episodes_scope_is_episodes_only", func(t *testing.T) {
got := search(qfScoped(episodesScope, qfRule("title", "is", "Scope Fresh Episode")))
assert.Equal(t, []string{"Scope Fresh Episode"}, got,
"episodes scope: only episodes — books drop")
})
t.Run("episode_rules_evaluate_in_sql", func(t *testing.T) {
got := search(qfScoped(episodesScope,
qfRule("feed", "in", feedID)))
assert.ElementsMatch(t, []string{"Scope Fresh Episode", "Scope Played Episode", "Scope Pending Episode"},
got, "feed-in matches every episode of the feed (download state is a separate rule)")
got = search(qfScoped(episodesScope,
qfRule("downloaded", "is_true")))
assert.ElementsMatch(t, []string{"Scope Fresh Episode", "Scope Played Episode"},
got, "downloaded:true drops the pending episode")
got = search(qfScoped(episodesScope,
qfRule("played", "is_false"),
qfRule("downloaded", "is_true")))
assert.ElementsMatch(t, []string{"Scope Fresh Episode"}, got,
"played:false + downloaded = the unplayed playable episode (viewer progress)")
got = search(qfScoped(episodesScope,
qfRule("played", "is_true")))
assert.ElementsMatch(t, []string{"Scope Played Episode"}, got,
"played:true matches the finished episode")
got = search(qfScoped(episodesScope,
qfRule("published_date", "within_days", "7"),
qfRule("downloaded", "is_true")))
assert.ElementsMatch(t, []string{"Scope Fresh Episode", "Scope Played Episode"},
got, "published-within includes the dated episodes")
})
t.Run("episode_fields_are_400_in_books_scope", func(t *testing.T) {
p := qfScoped(booksScope, qfRule("played", "is_true"))
req, _ := http.NewRequest("GET", setup.Server.URL+"/api/media-items/search?"+p.Encode(), nil)
req.Header.Set("Authorization", "Bearer "+setup.RegularToken)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode,
"episode-only fields are rejected in books trees at parse time")
})
}
func TestFilterUserRelativeFields(t *testing.T) {
setup := setupTestServer(t)
t.Cleanup(func() { _ = setup.Close() })
@@ -346,12 +455,17 @@ func TestFilterUserRelativeFields(t *testing.T) {
aID, wickID, aID, tideID)
var collID pgtype.UUID
err := setup.DBPool.QueryRow(context.Background(),
// Seed as the OWNER (collections RLS, 2026-10-31): the insert
// predicate wants actor == owner, and the item/cleanup writes want
// the same identity — the admin write-escape covers SYSTEM rows only.
err := database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(aID),
`INSERT INTO collections (user_id, name) VALUES ($1, $2) RETURNING id`,
aID, fmt.Sprintf("Test Builder Coll %d", time.Now().UnixNano())).Scan(&collID)
require.NoError(t, err)
t.Cleanup(func() { _ = setup.DB.DeleteCollection(ctx, collID) })
seedExec(t, setup.DBPool,
t.Cleanup(func() {
scopeExecAs(t, setup, aID, `DELETE FROM collections WHERE id = $1`, collID)
})
scopeExecAs(t, setup, aID,
`INSERT INTO collection_items (collection_id, media_item_id) VALUES ($1,$2)`, collID, tideID)
titlesFor := func(token string, qf string) []string {
@@ -433,7 +547,6 @@ func TestFilterSuggestionsUnderRules(t *testing.T) {
libUUID, _ := builderFixtureLib(t, setup, userID, "Sug")
// Add a second distinct author+genre pair (trigram-disjoint).
ctx := context.Background()
_, err := setup.DB.CreateMediaItem(seedCtx(), database.CreateMediaItemParams{
LibraryID: pgtype.UUID{Bytes: libUUID, Valid: true},
Title: "Sug Dune",
@@ -537,6 +650,16 @@ func TestFilterSuggestionsUnderRules(t *testing.T) {
}
assert.True(t, found, "the visible library is offered")
// ID LOOKUP (2026-11-01): typing a stored ID resolves its label —
// the builder's post-Apply reload path resolves stored ids to names
// through this same call.
status, results = suggest("library", libUUID.String(), "")
require.Equal(t, http.StatusOK, status)
require.NotEmpty(t, results, "the id lookup returns its row")
assert.Equal(t, libUUID.String(), results[0]["value"])
disp, _ := results[0]["display"].(string)
assert.Contains(t, disp, "Test Builder", "the id resolves to the library NAME")
// BROWSE the library field UNDER rules (the blank-typed click): the
// id-source query must not choke on the unused typed parameter and
// must list exactly the library holding the surviving books.
@@ -561,16 +684,21 @@ func TestFilterSuggestionsUnderRules(t *testing.T) {
// offered with the surviving count; zero-match containers never are.
userA := getRegularUserID(t, setup.DB)
var collID pgtype.UUID
err = setup.DBPool.QueryRow(context.Background(),
// Seed as the OWNER (collections RLS, 2026-10-31) — same identity
// rule as the first seeding site in this file.
ownerID := pgtype.UUID{Bytes: [16]byte(userA), Valid: true}
err = database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(ownerID),
`INSERT INTO collections (user_id, name) VALUES ($1, $2) RETURNING id`,
pgtype.UUID{Bytes: [16]byte(userA), Valid: true},
ownerID,
fmt.Sprintf("Test Builder Sug Coll %d", time.Now().UnixNano())).Scan(&collID)
require.NoError(t, err)
t.Cleanup(func() { _ = setup.DB.DeleteCollection(ctx, collID) })
t.Cleanup(func() {
scopeExecAs(t, setup, ownerID, `DELETE FROM collections WHERE id = $1`, collID)
})
var tideID pgtype.UUID
err = setup.DBPool.QueryRow(context.Background(), `SELECT id FROM media_items WHERE title = $1`, "Sug Tide").Scan(&tideID)
require.NoError(t, err)
seedExec(t, setup.DBPool,
scopeExecAs(t, setup, ownerID,
`INSERT INTO collection_items (collection_id, media_item_id) VALUES ($1, $2)`, collID, tideID)
status, results = suggest("collection", " ", "")
@@ -775,3 +903,85 @@ func TestFilterFlatEquivalence(t *testing.T) {
require.Equal(t, statusFlat, statusTree, "same result status")
assert.ElementsMatch(t, qfTitles(t, flatRows), qfTitles(t, treeRows))
}
// ---- deep group nesting (2026-11-01 group ALL/ANY header toggle): ----
// the UI can now produce 3+-level mixed-mode trees; pin the engine's
// parenthesized evaluation for the user's target structure
// GROUP(GROUP(Field and (Field or Field)) or GROUP(Field and Field and
// (Field or Field)) and GROUP(Field)) — plus a suggestion request
// carrying a nested-any constraint (the mode-aware menu under real
// nesting) — must be 200, never the empty-group 400.
func TestFilterDeepGroupNesting(t *testing.T) {
setup := setupTestServer(t)
t.Cleanup(func() { _ = setup.Close() })
userID := getRegularUserID(t, setup.DB)
libUUID, _ := builderFixtureLib(t, setup, userID, "Deep")
titles := func(qf string) []string {
p := url.Values{"library_id": {libUUID.String()}, "qf": {qf}}
status, rows := qfSearch(t, setup, setup.RegularToken, p)
require.Contains(t, []int{http.StatusOK, http.StatusNotFound}, status)
return qfTitles(t, rows)
}
// root ALL[
// ANY[ ALL[fantasy, ANY[>=250p, abridged]] , ALL[Dar, >=500p] ],
// author not_contains Quill
// ]
// => Tide (fantasy + 300p), Wick (Dar + 700p); Fen dies at the root
// AND (Quill); Stone fails branch A (history) and branch B (Voss).
deep := map[string]interface{}{
"mode": "all",
"children": []interface{}{
map[string]interface{}{
"mode": "any",
"children": []interface{}{
map[string]interface{}{
"mode": "all",
"children": []interface{}{
qfRule("genre", "is", "fantasy"),
map[string]interface{}{
"mode": "any",
"children": []interface{}{
qfRule("page_count", "at_least", "250"),
qfRule("abridged", "is_true"),
},
},
},
},
map[string]interface{}{
"mode": "all",
"children": []interface{}{
qfRule("author", "contains", "Dar"),
qfRule("page_count", "at_least", "500"),
},
},
},
},
qfRule("author", "not_contains", "Quill"),
},
}
deepJSON, merr := json.Marshal(deep)
require.NoError(t, merr)
got := titles(string(deepJSON))
assert.ElementsMatch(t, []string{"Deep Tide", "Deep Wick"}, got,
"3-level mixed-mode nesting evaluates parenthesized")
// The same shape riding the SUGGEST endpoint (the mode-aware menu's
// constraint) — nested any must be a 200, never the empty-group 400.
p := url.Values{
"library_id": {libUUID.String()},
"author": {""},
"limit": {"20"},
"qf": {string(deepJSON)},
}
req, _ := http.NewRequest("GET", setup.Server.URL+"/api/media-items/search?"+p.Encode(), nil)
req.Header.Set("Authorization", "Bearer "+setup.RegularToken)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusOK, resp.StatusCode,
"a nested-any constraint rides the suggestion endpoint cleanly: %s", p.Encode())
}
+9 -1
View File
@@ -438,7 +438,15 @@ func TestMetadataWriteToFile(t *testing.T) {
assert.Equal(t, "Comic Series", series)
})
// Sweep ALL generations of the fixture dirs, not just this
// process's: a killed run never reaches its RemoveAll, and the stale
// root-owned dirs then sit on the user's bind mount forever (seven
// of them were found in uploads/ in Nov 2026, one per past run —
// each surviving run's cleanup skipped them by pid).
matches, _ := filepath.Glob(filepath.Join(uploadsDir, "test-metadata-write-*"))
t.Cleanup(func() {
_ = os.RemoveAll(filepath.Join(uploadsDir, fmt.Sprintf("test-metadata-write-%d", os.Getpid())))
for _, dir := range matches {
_ = os.RemoveAll(dir)
}
})
}
+13 -6
View File
@@ -13,6 +13,8 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"bookhoard/internal/database"
)
// A2c end-to-end: an ABS sidecar whose series array mixes a real series and
@@ -67,13 +69,14 @@ func TestPlaylistCollectionsEndToEnd(t *testing.T) {
require.NotEmpty(t, foundPath)
// (b) The playlist collection exists with provenance, dashboard pin,
// and the item at reading position 7.
// and the item at reading position 7. Owner-scoped read: collections
// RLS (2026-10-31) hides the row from the pool session's SeedIdentity.
adminUUIDStr := adminID.String()
var collID uuid.UUID
var collName, collDesc string
var showOnDashboard bool
var viewSettingsRaw []byte
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(adminID),
`SELECT id, name, description, show_on_dashboard, view_settings
FROM collections WHERE user_id = $1 AND name = 'The Tagged Saga (Reading Order)'`,
adminID).Scan(&collID, &collName, &collDesc, &showOnDashboard, &viewSettingsRaw))
@@ -85,7 +88,9 @@ func TestPlaylistCollectionsEndToEnd(t *testing.T) {
var position *int32
var itemCount int
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
// Owner-scoped reads: collections RLS (2026-10-31) — items ride the
// parent's readability, so the pool session's SeedIdentity sees none.
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(adminID),
`SELECT ci.position, COUNT(*) OVER () FROM collection_items ci
WHERE ci.collection_id = $1`, collID).Scan(&position, &itemCount))
require.Equal(t, 1, itemCount)
@@ -96,11 +101,11 @@ func TestPlaylistCollectionsEndToEnd(t *testing.T) {
// (c) Rescan: no duplicate collection, no duplicate membership.
scanTestFolder(t, setup, adminID, folder)
var collectionCount, membershipCount int
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(adminID),
`SELECT COUNT(*) FROM collections WHERE user_id = $1 AND name = 'The Tagged Saga (Reading Order)'`,
adminID).Scan(&collectionCount))
require.Equal(t, 1, collectionCount)
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(adminID),
`SELECT COUNT(*) FROM collection_items WHERE collection_id = $1`, collID).Scan(&membershipCount))
require.Equal(t, 1, membershipCount)
@@ -131,7 +136,9 @@ func TestPlaylistCollectionsEndToEnd(t *testing.T) {
// (e) hide_finished + Up Next + completion marker.
// Flip the collection's flag on, mark the single item finished for the
// admin, and the dashboard section becomes Complete with no items.
_, err = setup.DBPool.Exec(context.Background(),
// Owner-or-admin UPDATE policy: run as ADMIN (collections RLS,
// 2026-10-31).
adminScopeExec(t, setup, adminCtxValue(t, setup),
`UPDATE collections SET view_settings = view_settings || '{"hide_finished": true}'::jsonb WHERE id = $1`, collID)
require.NoError(t, err)
_, err = setup.DBPool.Exec(context.Background(),
File diff suppressed because it is too large. Load diff
+123
View File
@@ -0,0 +1,123 @@
package main
// Resume rewind (per-user server setting): seconds before the saved
// position the audiobook/podcast player starts (0 = exact resume).
// Contract: the profile endpoint owns reads/writes with a strict
// 0/5/10 allow-list (the request shape is the keep_screen_awake string
// precedent — the form select must be able to send an explicit Off),
// and the chapters payload carries the value so every client (web +
// Android, incl. the Auto service) gets it with its existing fetch.
// All writes ride the fresh per-test regular user — the shared admin
// account is never touched (AGENTS doctrine). Fixture book lives in a
// test-named library that cascades away with the library delete.
import (
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func TestAudioResumeRewind(t *testing.T) {
setup := setupTestServer(t)
t.Cleanup(func() { _ = setup.Close() })
admin, _ := moveTestAdminID(t, setup)
libID, folder := audioTestLibrary(t, setup, fmt.Sprintf("Test Resume Rewind %d", time.Now().UnixNano()))
t.Cleanup(func() { deleteLibraries(t, setup, libID) })
// 664 Hz tone: not the shared helper's 440 or the speed test's 552,
// so the scanner's content dedup never skips this book.
writeTestTrackTone(t, filepath.Join(folder, "Rewind Book", "01 one.mp3"), 664)
scanTestFolder(t, setup, admin, folder)
var bookPath string
for _, item := range listLibraryAudioItems(t, setup, libID) {
if strings.Contains(filepath.ToSlash(item.FilePath), "Rewind Book") && bookPath == "" {
bookPath = item.FilePath
}
}
require.NotEmpty(t, bookPath, "Rewind Book item must exist")
book, found := findAudioItemByPath(t, setup, libID, bookPath)
require.True(t, found)
bookID := uuid.UUID(book.ID.Bytes)
client := &http.Client{}
token := setup.RegularToken
authed := func(method, url, body string) (*http.Response, func()) {
var req *http.Request
if body == "" {
req, _ = http.NewRequest(method, url, nil)
} else {
req, _ = http.NewRequest(method, url, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
require.NoError(t, err)
return resp, func() { _ = resp.Body.Close() }
}
getPayload := func(itemID uuid.UUID) (rewind int) {
resp, closer := authed("GET", setup.Server.URL+"/api/media-items/"+itemID.String()+"/chapters", "")
defer closer()
require.Equal(t, http.StatusOK, resp.StatusCode)
var data struct {
ResumeRewindSeconds int `json:"resume_rewind_seconds"`
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&data))
return data.ResumeRewindSeconds
}
getProfileRewind := func() int {
resp, closer := authed("GET", setup.Server.URL+"/api/auth/profile", "")
defer closer()
require.Equal(t, http.StatusOK, resp.StatusCode)
var profile struct {
AudioResumeRewind int `json:"audio_resume_rewind_seconds"`
}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&profile))
return profile.AudioResumeRewind
}
t.Run("defaults to off (exact resume)", func(t *testing.T) {
require.Equal(t, 0, getProfileRewind())
require.Equal(t, 0, getPayload(bookID))
})
t.Run("profile PUT selects 5 and rides the chapters payload", func(t *testing.T) {
resp, closer := authed("PUT", setup.Server.URL+"/api/auth/profile", `{"audio_resume_rewind_seconds":"5"}`)
defer closer()
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Equal(t, 5, getProfileRewind())
require.Equal(t, 5, getPayload(bookID))
})
t.Run("non-allow-listed values are rejected and change nothing", func(t *testing.T) {
for _, body := range []string{`{"audio_resume_rewind_seconds":"7"}`, `{"audio_resume_rewind_seconds":"-5"}`, `{"audio_resume_rewind_seconds":"abc"}`} {
resp, closer := authed("PUT", setup.Server.URL+"/api/auth/profile", body)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
closer()
}
require.Equal(t, 5, getProfileRewind())
})
t.Run("explicit off resets to 0 everywhere", func(t *testing.T) {
resp, closer := authed("PUT", setup.Server.URL+"/api/auth/profile", `{"audio_resume_rewind_seconds":"0"}`)
defer closer()
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Equal(t, 0, getProfileRewind())
require.Equal(t, 0, getPayload(bookID))
})
t.Run("JSON clients that omit the key leave it untouched", func(t *testing.T) {
resp, closer := authed("PUT", setup.Server.URL+"/api/auth/profile", `{"timezone":"UTC"}`)
defer closer()
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Equal(t, 0, getProfileRewind())
})
}
+3 -2
View File
@@ -207,12 +207,13 @@ func TestScanManifestLifecycle(t *testing.T) {
require.NoError(t, os.WriteFile(opfPath, []byte(`{"title":"Manifesu Book","series":["Lifecycle Saga (Reading Order) #1"]}`), 0644))
scanTestFolder(t, setup, admin, folder)
var collCount int
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
// Owner-scoped read: collections RLS (2026-10-31).
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(admin),
`SELECT COUNT(*) FROM collections WHERE name = 'Lifecycle Saga (Reading Order)' AND user_id = $1`, admin,
).Scan(&collCount))
assert.Equal(t, 1, collCount, "reading-order sidecar added to an existing book creates its collection")
scanTestFolder(t, setup, admin, folder)
require.NoError(t, setup.DBPool.QueryRow(context.Background(),
require.NoError(t, database.NewScopedDB(setup.DBPool).QueryRow(ownerSeedCtx(admin),
`SELECT COUNT(*) FROM collections WHERE name = 'Lifecycle Saga (Reading Order)' AND user_id = $1`, admin,
).Scan(&collCount))
assert.Equal(t, 1, collCount, "rescan is idempotent — no duplicate collection")
+103 -10
View File
@@ -96,6 +96,43 @@ type TestServerSetup struct {
closed bool
}
// cleanupDeviceByIdentifier deletes any devices rows carrying the given
// identifier at test end. API-register tests need this instead of a
// token-based delete: the status poll is single-use, so a row created
// through register+approve changes tokens mid-test — the stable
// identity is UNIQUE(device_identifier). Use for every device a test
// attaches to the SHARED admin (testuser); See the DOCTRINE comment in
// setupTestServer — rows that survive their test pile up on the live
// dev account's device grid.
func cleanupDeviceByIdentifier(t *testing.T, setup *TestServerSetup, identifier string) {
t.Cleanup(func() {
_, _ = setup.DBPool.Exec(context.Background(),
"DELETE FROM devices WHERE device_identifier = $1", identifier)
})
}
// cleanupCollectionByID deletes one collections row at test end, scoped
// through the RLS bridge to its owner — collections RLS (2026-10-31)
// makes unscoped writes invisible (no-op). Use for a collection a test
// attaches to the shared admin whose name CANNOT carry the "test"
// marker the setup-time name sweep keys on (uuid-suffixed uniqueness
// against stale UNIQUE(user_id, name) rows from past runs). Rows that
// survive their test also get stranded forever — the 10 accumulated
// "Admin Collection <uuid>" rows were exactly this.
func cleanupCollectionByID(t *testing.T, setup *TestServerSetup, ownerID [16]byte, collectionID string) {
t.Cleanup(func() {
cid, err := uuid.Parse(collectionID)
if err != nil {
t.Logf("cleanupCollectionByID: unparsable id %q — %v", collectionID, err)
return
}
scope := rls.WithUser(context.Background(), pgtype.UUID{Bytes: ownerID, Valid: true})
if err := setup.DB.DeleteCollection(scope, pgtype.UUID{Bytes: cid, Valid: true}); err != nil {
t.Logf("cleanupCollectionByID: delete failed for %s — %v", collectionID, err)
}
})
}
// Close cleans up all resources in the correct order
func (s *TestServerSetup) Close() error {
s.mu.Lock()
@@ -329,6 +366,22 @@ func seedCtx() context.Context {
return rls.WithUser(context.Background(), rls.SeedIdentity)
}
// ownerSeedCtx returns a context carrying a fixture user's identity,
// for seeding rows OWNED by that user. Collections RLS (2026-10-31):
// the write predicates want actor == owner for non-system rows (the
// admin write-escape covers SYSTEM collections only), and reads under
// the pool session's SeedIdentity see nothing.
func ownerSeedCtx(userID pgtype.UUID) context.Context {
return rls.WithUser(context.Background(), userID)
}
// scopeExecAs is adminScopeExec's generic form: raw SQL under ANY
// declared identity. Use it (with the row's OWNER) for fixture writes
// to non-system collections — see ownerSeedCtx.
func scopeExecAs(t *testing.T, setup *TestServerSetup, userID pgtype.UUID, sql string, args ...any) {
adminScopeExec(t, setup, userID, sql, args...)
}
// seedExec runs a raw statement against the pool under the seed
// identity. The bare pool bypasses ScopedDB (nothing reads the ctx for
// the GUC), so governed tables need the identity declared manually
@@ -356,7 +409,12 @@ func uuidToPGType(u uuid.UUID) pgtype.UUID {
// createDefaultCollectionsForUser creates the 4 default system collections for a user
func createDefaultCollectionsForUser(t *testing.T, db *database.Queries, userID pgtype.UUID) {
ctx := context.Background()
// Owner-scoped seeding: the collections RLS policies (2026-10-31)
// need an acting identity, and the harness seeds before any JWT —
// the same bootstrap fix as CreateDefaultCollectionsForUser in
// internal/handlers/auth.go. Owner == actor, so SELECT sees the
// rows, the INSERT passes, and the heal-UPDATE passes.
ctx := rls.WithUser(context.Background(), userID)
// Canonical Title-case names — the same list the registration seed
// (CreateDefaultCollectionsForUser) and RestoreSystemCollection use.
// A stale kebab-case copy lived here once and duplicated every
@@ -460,6 +518,13 @@ func (s *TestDeviceSetup) CreateDevice(t *testing.T, deviceName, deviceType, dev
})
require.NoError(t, err, "Should create device")
// Devices created through this helper self-delete at test end, so
// callers owe nothing to name hygiene: setupDeviceTest attaches to
// the SHARED admin, which the harness deliberately never deletes —
// unqualified rows would pile up on the live dev account forever
// (the "OPDS Folders Device" graveyard was exactly this gap).
t.Cleanup(func() { _ = s.DB.DeleteDevice(context.Background(), device.ID) })
deviceUUID, err := uuid.FromBytes(device.ID.Bytes[0:16])
require.NoError(t, err, "Should parse device ID")
@@ -596,10 +661,13 @@ func setupTestServer(t *testing.T) *TestServerSetup {
worker := services.NewWorker(3, connManager)
services.WorkerInstance = worker
jobsHandler := handlers.NewJobsHandler(queries, worker)
collectionHandler := handlers.NewCollectionHandler(queries, libraryService, connManager)
// One composed-engine service for search AND the collection
// subsystem (item 3.2 — mirrors main.go).
collectionSearchService := services.NewSearchService(queries, scopedDB)
collectionHandler := handlers.NewCollectionHandler(queries, libraryService, connManager, collectionSearchService)
filtersHandler := handlers.NewFiltersHandler(queries)
dashboardService := services.NewDashboardService(queries)
dashboardHandler := handlers.NewDashboardHandler(queries)
dashboardService := services.NewDashboardService(queries, collectionSearchService)
dashboardHandler := handlers.NewDashboardHandler(queries, collectionSearchService)
statisticsService := services.NewStatisticsService(queries)
statsHandler := handlers.NewStatsHandler(statisticsService)
seriesHandler := handlers.NewSeriesHandler(queries)
@@ -610,6 +678,14 @@ func setupTestServer(t *testing.T) *TestServerSetup {
conversionService := services.NewConversionService(queries, getCachePath())
opdsHandler := handlers.NewOPDSHandler(queries, libraryService, conversionService)
// Podcast subsystem (mirrors main.go wiring): fetcher service +
// download worker + handler. The poller is NOT started in tests
// (no background ticks against the shared dev DB); the worker loop
// only drains when a test queues work.
podcastService := services.NewPodcastService(queries)
podcastWorker := services.NewPodcastDownloadWorker(queries, podcastService)
podcastHandler := handlers.NewPodcastHandler(queries, podcastService, podcastWorker)
// Create Echo instance
e := echo.New()
@@ -672,6 +748,9 @@ func setupTestServer(t *testing.T) *TestServerSetup {
// hands the kobo/kepub CFI converter a typed-nil (kobo markup
// panic-recovered as 500s in TestProgressWeb_KoboIntegration).
LibraryService: libraryService,
PodcastHandler: podcastHandler,
PodcastService: podcastService,
PodcastWorker: podcastWorker,
}
router.RegisterRoutes(routerConfig)
@@ -758,11 +837,15 @@ func setupTestServer(t *testing.T) *TestServerSetup {
// run's creates die on UNIQUE(user_id, name) — the "collections
// 500-panic" rot. System collections are skipped (permanent rows).
// Same convention as the library pass: names containing "test".
adminColls, cerr := queries.GetCollectionsByUser(ctx, pgtype.UUID{Bytes: adminUUID, Valid: true})
// Swept under the OWNER's identity: collections RLS (2026-10-31)
// makes unscoped reads return nothing, which would silently turn
// this cleanup into a no-op.
adminScope := rls.WithUser(ctx, pgtype.UUID{Bytes: adminUUID, Valid: true})
adminColls, cerr := queries.GetCollectionsByUser(adminScope, pgtype.UUID{Bytes: adminUUID, Valid: true})
if cerr == nil {
for _, coll := range adminColls {
if !coll.IsSystemCollection.Bool && strings.Contains(strings.ToLower(coll.Name), "test") {
queries.DeleteCollection(ctx, coll.ID)
queries.DeleteCollection(adminScope, coll.ID)
}
}
}
@@ -770,9 +853,17 @@ func setupTestServer(t *testing.T) *TestServerSetup {
// Same passes for test DEVICES (identifier/name containing "test")
// and test SAVED FILTERS (name containing "test"): both accumulated
// across runs and poisoned later runs (duplicate identifiers, 409s,
// non-empty "initially empty" assertions).
// non-empty "initially empty" assertions). The second half of the
// device predicate catches test suites that attach to the shared
// admin with surface-specific names ("koreader" from the contract
// pins, "OPDS Folders Device", "Reinstall Device") — every suite
// now also self-deletes its rows, this is the drift safety net:
// dev_contract_% auth tokens, contract-% / opds-folders-% /
// repro-reinstall-% identifiers are unambiguously harness-owned.
_, derr := dbPool.Exec(ctx,
"DELETE FROM devices WHERE user_id = $1 AND (device_identifier ILIKE '%test%' OR device_name ILIKE '%test%')",
"DELETE FROM devices WHERE user_id = $1 AND (device_identifier ILIKE '%test%' OR device_name ILIKE '%test%' "+
"OR device_identifier ILIKE 'contract-%' OR device_identifier ILIKE 'opds-folders-%' OR device_identifier ILIKE 'repro-reinstall-%' "+
"OR auth_token LIKE 'dev_contract_%')",
adminUUID)
if derr != nil {
t.Logf("device cleanup failed: %v", derr)
@@ -836,11 +927,13 @@ func setupTestServer(t *testing.T) *TestServerSetup {
// Same pass for test-created COLLECTIONS (the "collections
// 500-panic" rot: they lingered forever and poisoned later runs).
adminColls, cerr := queries.GetCollectionsByUser(ctx, pgtype.UUID{Bytes: adminUUID, Valid: true})
// Owner-scoped for the same RLS reason as the setup sweep.
adminScope := rls.WithUser(ctx, pgtype.UUID{Bytes: adminUUID, Valid: true})
adminColls, cerr := queries.GetCollectionsByUser(adminScope, pgtype.UUID{Bytes: adminUUID, Valid: true})
if cerr == nil {
for _, coll := range adminColls {
if !coll.IsSystemCollection.Bool && strings.Contains(strings.ToLower(coll.Name), "test") {
queries.DeleteCollection(ctx, coll.ID)
queries.DeleteCollection(adminScope, coll.ID)
}
}
}
+4
View File
@@ -241,6 +241,10 @@ func TestWebSocketUserScopedBroadcast(t *testing.T) {
err = json.NewDecoder(collectionResp.Body).Decode(&collectionResult)
require.NoError(t, err)
collectionID := collectionResult["id"].(string)
// The uuid suffix keeps the name off every run's UNIQUE(user_id,name),
// which also keeps it out of the name-based cleanup sweep — self-delete
// instead (owner-scoped, exactly who created it).
cleanupCollectionByID(t, setup, getTestUserID(t, setup.DB), collectionID)
// Create a test book via API
bookID := createTestMediaItemID(t, setup)
+356 -6
View File
@@ -18,7 +18,8 @@ INSERT INTO library_types (name, description, allowed_extensions) VALUES
('ebooks', 'Ebook files including EPUB, PDF, MOBI, etc.', ARRAY['.epub', '.pdf', '.mobi', '.azw', '.azw3', '.txt', '.rtf', '.doc', '.docx', '.lit', '.fb2', '.pdb']),
('comics', 'Comic book archives and image formats', ARRAY['.cbz', '.cbr', '.cb7', '.cbt', '.epub', '.pdf']),
('manga', 'Manga files including archives and image folders', ARRAY['.cbz', '.cbr', '.epub', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.avif', '.tiff', '.tif']),
('audiobooks', 'Audiobook files; m4b first, breadth formats registered from day one', ARRAY['.m4b', '.m4a', '.mp3', '.flac'])
('audiobooks', 'Audiobook files; m4b first, breadth formats registered from day one', ARRAY['.m4b', '.m4a', '.mp3', '.flac']),
('podcasts', 'RSS podcast/feed libraries: feeds subscribe-and-download; the scanner never walks these folders', ARRAY[]::TEXT[])
ON CONFLICT (name) DO NOTHING;
-- Create users table
@@ -47,6 +48,14 @@ ALTER TABLE users ADD COLUMN IF NOT EXISTS default_audio_speed REAL NOT NULL DEF
-- mid-session. On by default; the profile page's On/Off dropdown owns it.
ALTER TABLE users ADD COLUMN IF NOT EXISTS keep_screen_awake BOOLEAN NOT NULL DEFAULT TRUE;
-- Audio resume rewind: seconds before the saved position the
-- audiobook/podcast player starts (on open-resume AND again on every
-- genuine unpause — the re-orientation gap, never stacked). Strict
-- allow-list 0/5/10 enforced handler-side; 0 = exact resume. The
-- profile page's dropdown owns it; the chapters payload carries it to
-- every client (web + Android, incl. the car path).
ALTER TABLE users ADD COLUMN IF NOT EXISTS audio_resume_rewind_seconds INT NOT NULL DEFAULT 0;
-- Create system_settings table
CREATE TABLE IF NOT EXISTS system_settings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -99,7 +108,11 @@ INSERT INTO system_settings (setting_key, setting_value, description, setting_ty
('sync_queue_interval_seconds', '5', 'How often the sync queue flushes', 'int', '1', '3600', TRUE, 'sync'),
('sync_queue_batch_size', '50', 'Maximum items processed per sync queue flush', 'int', '1', '10000', TRUE, 'sync'),
('worker_pool_size', '3', 'Number of background worker goroutines', 'int', '1', '100', TRUE, 'performance'),
('worker_queue_cap', '100', 'Background worker job queue capacity', 'int', '1', '10000', TRUE, 'performance')
('worker_queue_cap', '100', 'Background worker job queue capacity', 'int', '1', '10000', TRUE, 'performance'),
-- podcasts
('podcast_poll_interval_seconds', '3600', 'How often to poll podcast feeds for new episodes (seconds; complete feeds back off)', 'int', '300', '604800', FALSE, 'podcasts'),
('podcast_download_concurrency', '4', 'Podcast episode downloads in flight server-wide (the connection is the limit; fair-share spreads them across feeds)', 'int', '1', '16', FALSE, 'podcasts'),
('podcast_download_speed_mbps', '0', 'Shared bandwidth cap for podcast downloads in megabits/second (0 = unlimited)', 'float', '0', '10000', FALSE, 'podcasts')
ON CONFLICT (setting_key) DO NOTHING;
-- Create refresh_tokens table
@@ -1336,7 +1349,9 @@ CREATE TABLE IF NOT EXISTS collections (
description TEXT,
color VARCHAR(7),
icon VARCHAR(50),
auto_assign_rules JSONB,
-- The unified filter tree (plan item 3.2): when present the qf
-- engine drives membership; see FilterTree. NULL = static.
filter_tree JSONB,
view_settings JSONB,
show_on_dashboard BOOLEAN DEFAULT false,
query_type TEXT DEFAULT 'filter',
@@ -1352,12 +1367,23 @@ CREATE TABLE IF NOT EXISTS collections (
-- the row id (and everything referencing it) never churn.
ALTER TABLE collections ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
-- Legacy rules-array columns RETIRED (2026-10-31): the unified filter
-- tree is the only smart-membership storage. No production row ever
-- carried a rules array or a non-default match mode (verified), so the
-- columns drop clean; the DROPs are the idempotent heal for databases
-- created before this change.
ALTER TABLE collections DROP COLUMN IF EXISTS auto_assign_rules;
ALTER TABLE collections DROP COLUMN IF EXISTS rule_match_mode;
-- Smart collections in the UNIFIED filter engine (plan item 3.2): the
-- qf tree (same DSL as saved filters, See FilterTree). NULL = static.
ALTER TABLE collections ADD COLUMN IF NOT EXISTS filter_tree JSONB;
CREATE INDEX IF NOT EXISTS idx_collections_user_id ON collections(user_id);
-- Index for dashboard queries
CREATE INDEX IF NOT EXISTS idx_collections_dashboard ON collections(user_id, show_on_dashboard, priority)
WHERE show_on_dashboard = true;
-- Create user_dashboard_preferences table
CREATE TABLE IF NOT EXISTS user_dashboard_preferences (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -1623,12 +1649,19 @@ CREATE INDEX IF NOT EXISTS idx_dictionary_word ON dictionary_cache(word);
CREATE TABLE IF NOT EXISTS reader_settings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
setting_key VARCHAR(50) NOT NULL,
setting_key VARCHAR(120) NOT NULL,
setting_value JSONB NOT NULL,
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(user_id, setting_key)
);
-- Key-width headroom (podcast plan §10 R5, item 2.1): the composite
-- `podcast_order:<uuid>` key sits at exactly 50 chars, and future
-- per-feed/per-collection preference keys must not be forced to
-- payload-stuff by a column width. Widening a varchar is metadata-only
-- (no table rewrite); idempotent on every boot.
ALTER TABLE reader_settings ALTER COLUMN setting_key TYPE VARCHAR(120);
CREATE INDEX IF NOT EXISTS idx_reader_settings_user ON reader_settings(user_id);
-- PDF bookmarks (custom user bookmarks)
@@ -1878,6 +1911,137 @@ CREATE INDEX IF NOT EXISTS idx_hash_conflicts_status ON hash_conflicts(status);
-- Widen for databases created before the resolution format settled (no-op otherwise)
ALTER TABLE hash_conflicts ALTER COLUMN resolution TYPE VARCHAR(50);
-- ============================================================
-- PODCASTS / RSS FEEDS
-- Plan: ~/.opencode/plan/podcast-integration.md (§6).
-- Feeds are per-library entities (UNIQUE(library_id, feed_url)); users
-- subscribe personally (podcast_subscriptions). Episodes are
-- media_items rows with source='podcast_episode' — per-episode
-- progress/stats for free — grouped by source_feed_id. Visibility is
-- RLS-enforced (see the policy block at the end of this file): an
-- episode/feed row is SELECT-visible only to subscribers of the feed
-- and to admins. The fetcher/download worker is the SOLE writer of
-- feed/episode metadata; users own only their subscription row and the
-- reader_settings order override. ALL DDL IDEMPOTENT: schema.sql
-- re-executes on EVERY boot.
-- ============================================================
-- First per-library boolean knob (plain column, not KV): when false,
-- only admins may add feeds to the library (members keep subscribe
-- rights to existing feeds).
ALTER TABLE libraries ADD COLUMN IF NOT EXISTS allow_member_feeds BOOLEAN NOT NULL DEFAULT TRUE;
-- Folder purpose: 'scan' (default; the FS walker's root) vs 'podcast'
-- (a podcasts library's download root — scanner skips it wholesale,
-- belt-and-braces on top of the library-type skip).
ALTER TABLE library_folders ADD COLUMN IF NOT EXISTS purpose VARCHAR(20) NOT NULL DEFAULT 'scan';
CREATE TABLE IF NOT EXISTS podcast_feeds (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
library_id UUID NOT NULL REFERENCES libraries(id) ON DELETE CASCADE,
feed_url TEXT NOT NULL,
-- podcast:guid — the feed's canonical identity; dedupes across URL
-- migrations (fetcher honors itunes:new-feed-url + redirects).
podcast_guid TEXT,
title VARCHAR(500) NOT NULL,
description TEXT,
-- Channel itunes:author (semantically the host) and itunes:owner.
host VARCHAR(500),
publisher VARCHAR(500),
owner_name VARCHAR(500),
owner_email VARCHAR(500),
language VARCHAR(50),
tags TEXT[] DEFAULT '{}',
explicit BOOLEAN NOT NULL DEFAULT FALSE,
artwork_path VARCHAR(500),
-- itunes:type: 'serial' | 'episodic'
feed_type VARCHAR(20),
-- podcast:medium: 'audiobook' | 'podcast' | 'music' | ...
medium VARCHAR(20),
-- itunes:complete: poller backs off once the publisher ends the feed.
is_complete BOOLEAN NOT NULL DEFAULT FALSE,
-- Conditional-GET validators (opaque; echoed verbatim).
etag VARCHAR(500),
last_modified VARCHAR(500),
last_fetched_at TIMESTAMPTZ,
last_build_date TIMESTAMPTZ,
created_by_admin_id UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(library_id, feed_url)
);
CREATE INDEX IF NOT EXISTS idx_podcast_feeds_library ON podcast_feeds(library_id);
CREATE INDEX IF NOT EXISTS idx_podcast_feeds_guid ON podcast_feeds(podcast_guid);
-- User-owned subscription row: the ONLY podcast state a user writes.
-- display_name NULL renders as the feed title. auto_download:
-- 'off' | 'all' | 'newest' (+ auto_download_count for newest N).
CREATE TABLE IF NOT EXISTS podcast_subscriptions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
feed_id UUID NOT NULL REFERENCES podcast_feeds(id) ON DELETE CASCADE,
display_name VARCHAR(500),
auto_download VARCHAR(20) NOT NULL DEFAULT 'off',
auto_download_count INT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(user_id, feed_id)
);
CREATE INDEX IF NOT EXISTS idx_podcast_subs_user ON podcast_subscriptions(user_id);
CREATE INDEX IF NOT EXISTS idx_podcast_subs_feed ON podcast_subscriptions(feed_id);
-- Episode columns (NULL for scan-sourced items). See the plan §5 for
-- the full RSS/iTunes/Podcasting-2.0 field mapping — existing columns
-- (title, subtitle, description, authors, explicit, date_published,
-- cover_image_path, file_size, mime_type, language, genre/tags) carry
-- the shared fields; only genuinely podcast-only storage lives here.
ALTER TABLE media_items
ADD COLUMN IF NOT EXISTS source VARCHAR(20) NOT NULL DEFAULT 'scan',
ADD COLUMN IF NOT EXISTS source_feed_id UUID REFERENCES podcast_feeds(id) ON DELETE CASCADE,
-- Stable reorder-proof addressing key (invariant 3): progress
-- anchors on guid, never ordinal.
ADD COLUMN IF NOT EXISTS episode_guid TEXT,
-- Native order as of the latest fetch (renumbered per fetch).
ADD COLUMN IF NOT EXISTS feed_position INTEGER,
ADD COLUMN IF NOT EXISTS season_number INTEGER,
ADD COLUMN IF NOT EXISTS episode_number INTEGER,
ADD COLUMN IF NOT EXISTS enclosure_url TEXT,
-- itunes:duration claim (often HH:MM:SS or prose); display until
-- ffprobe reconciles after download.
ADD COLUMN IF NOT EXISTS declared_duration_seconds INTEGER,
ADD COLUMN IF NOT EXISTS transcript_url TEXT,
ADD COLUMN IF NOT EXISTS chapters_url TEXT,
ADD COLUMN IF NOT EXISTS hosts TEXT[] DEFAULT '{}',
ADD COLUMN IF NOT EXISTS guests TEXT[] DEFAULT '{}',
-- Download state machine: pending | queued | downloading |
-- downloaded | failed (+ reason text + attempt count). The episode
-- list renders this inline (D8/D19) — never Processing Issues.
ADD COLUMN IF NOT EXISTS download_state VARCHAR(20) NOT NULL DEFAULT 'pending',
ADD COLUMN IF NOT EXISTS download_error TEXT,
ADD COLUMN IF NOT EXISTS download_attempts INT NOT NULL DEFAULT 0,
-- Monotonic queue ticket (Postgres SEQUENCE nextval at enqueue
-- time): the download pool claims in ticket order, so the enqueue
-- loop's ordering IS the download order (effective listening order
-- — §0 items 4/5). NULL for rows never queued.
ADD COLUMN IF NOT EXISTS download_queue_pos BIGINT;
-- Queue ticket source: atomic across concurrent enqueues (per-feed
-- locks serialize within a feed; the sequence covers across feeds).
CREATE SEQUENCE IF NOT EXISTS podcast_queue_seq;
-- Identity + ordering + worker-worklist indexes (all partial: scan
-- rows never touch these columns).
CREATE UNIQUE INDEX IF NOT EXISTS idx_media_items_feed_guid
ON media_items(source_feed_id, episode_guid) WHERE source_feed_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_media_items_feed_pos
ON media_items(source_feed_id, feed_position) WHERE source_feed_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_media_items_feed_undownloaded
ON media_items(source_feed_id) WHERE source_feed_id IS NOT NULL AND download_state <> 'downloaded';
CREATE INDEX IF NOT EXISTS idx_media_items_queue
ON media_items(download_queue_pos) WHERE source = 'podcast_episode' AND download_state = 'queued';
-- ============================================================
-- RLS: PER-USER LIBRARY VISIBILITY (ONE SOURCE OF TRUTH)
-- Plan: ~/.opencode/plan/server-rls-library-visibility.md REV 2.
@@ -1912,6 +2076,13 @@ ALTER TABLE media_items FORCE ROW LEVEL SECURITY;
-- semantics — row absent -> visible; row true -> visible; row false
-- -> hidden. No new index needed: library_visibility's
-- UNIQUE(user_id, library_id) constraint already indexes the join.
-- PODCAST EPISODES (plan D20): source='podcast_episode' rows carry the
-- ADDITIONAL subscription predicate — visible only to subscribers of
-- source_feed_id, or to admins (admins manage feeds regardless of
-- subscription; the escape also satisfies background jobs, which
-- declare a first-admin identity). Scan rows pass unchanged via the
-- IS DISTINCT FROM guard — the predicate costs them one NULL compare.
-- Unset identity FAILS LOUD, never fails open (see the block header).
CREATE POLICY p_media_items_visible ON media_items
FOR SELECT
USING (
@@ -1922,6 +2093,19 @@ CREATE POLICY p_media_items_visible ON media_items
AND lv.library_id = media_items.library_id
AND lv.is_visible = false
)
AND (
media_items.source IS DISTINCT FROM 'podcast_episode'
OR EXISTS (
SELECT 1 FROM podcast_subscriptions s
WHERE s.user_id = current_setting('app.user_id')::uuid
AND s.feed_id = media_items.source_feed_id
)
OR EXISTS (
SELECT 1 FROM users u
WHERE u.id = current_setting('app.user_id')::uuid
AND u.role = 'admin'
)
)
);
-- WRITE policies: PERMISSIVE STAND-INS for the deferred scoped write
@@ -1942,7 +2126,173 @@ CREATE POLICY p_media_items_update ON media_items
CREATE POLICY p_media_items_delete ON media_items
FOR DELETE USING (true);
-- Other tables: NONE. collection_items reaches media only via INNER
-- Other tables: collection_items reaches media only via INNER
-- JOIN media_items (the join drops filtered rows). collections
-- metadata (book_count) is a separate counts question — plan A13.
-- PODCAST FEEDS (plan D20): governed the same way. SELECT-visible to
-- subscribers of the feed (their subscription IS the grant — this is
-- the predicate's lookup table, podcast_subscriptions itself stays
-- UNGOVERNED) plus the library-visibility join (a hidden library
-- hides its feeds too), and to admins. WRITE policies are permissive
-- stand-ins for the same reason as media_items above: mandatory at
-- ENABLE time, and the fetcher/worker (first-admin identity) plus the
-- add-feed upsert (ON CONFLICT DO UPDATE needs no separate SELECT)
-- cover every legitimate writer.
DROP POLICY IF EXISTS p_podcast_feeds_visible ON podcast_feeds;
DROP POLICY IF EXISTS p_podcast_feeds_insert ON podcast_feeds;
DROP POLICY IF EXISTS p_podcast_feeds_update ON podcast_feeds;
DROP POLICY IF EXISTS p_podcast_feeds_delete ON podcast_feeds;
ALTER TABLE podcast_feeds ENABLE ROW LEVEL SECURITY;
ALTER TABLE podcast_feeds FORCE ROW LEVEL SECURITY;
CREATE POLICY p_podcast_feeds_visible ON podcast_feeds
FOR SELECT
USING (
current_setting('app.user_id') IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM library_visibility lv
WHERE lv.user_id = current_setting('app.user_id')::uuid
AND lv.library_id = podcast_feeds.library_id
AND lv.is_visible = false
)
AND (
EXISTS (
SELECT 1 FROM podcast_subscriptions s
WHERE s.user_id = current_setting('app.user_id')::uuid
AND s.feed_id = podcast_feeds.id
)
OR EXISTS (
SELECT 1 FROM users u
WHERE u.id = current_setting('app.user_id')::uuid
AND u.role = 'admin'
)
)
);
CREATE POLICY p_podcast_feeds_insert ON podcast_feeds
FOR INSERT WITH CHECK (true);
CREATE POLICY p_podcast_feeds_update ON podcast_feeds
FOR UPDATE USING (true) WITH CHECK (true);
CREATE POLICY p_podcast_feeds_delete ON podcast_feeds
FOR DELETE USING (true);
-- podcast_subscriptions: UNGOVERNED, deliberately — it IS the read
-- policy's lookup table, and a user must always see their own
-- subscription rows (subscribe -> visibility is a single INSERT).
-- ============================================================
-- ── collections + collection_items (2026-10-31): ownership at the DB ──
-- layer, same doctrine as media_items/podcast_feeds above. The
-- predicates live in FUNCTIONS (not inline) so a future sharing model
-- edits exactly one place: add the share-table EXISTS branch inside
-- app_can_read_collection / app_can_write_collection. The functions are
-- PURE over their arguments — they never query collections — so the
-- policies cannot recurse, FORCE RLS safe. Reads are authenticated-
-- allow (household-readable: any signed-in identity, SeedIdentity
-- harness included); WRITES are owner-or-admin — that is the
-- enforcement of record for Update/Delete/AddBooks, which have no
-- app-level gate.
-- ===========================================================
CREATE OR REPLACE FUNCTION app_is_admin() RETURNS BOOLEAN
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, public AS $$
SELECT EXISTS (
SELECT 1 FROM users u
WHERE u.id = NULLIF(current_setting('app.user_id', true), '')::uuid
AND u.role = 'admin'
);
$$;
CREATE OR REPLACE FUNCTION app_can_read_collection(
p_collection_id UUID, p_owner UUID
) RETURNS BOOLEAN
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, public AS $$
SELECT NULLIF(current_setting('app.user_id', true), '') IS NOT NULL
AND (
p_owner = current_setting('app.user_id', true)::uuid
OR app_is_admin()
-- FUTURE SHARING slot: OR EXISTS (
-- SELECT 1 FROM collection_shares cs
-- WHERE cs.collection_id = p_collection_id
-- AND cs.shared_with_user_id = current_setting('app.user_id', true)::uuid)
);
$$;
CREATE OR REPLACE FUNCTION app_can_write_collection(
p_collection_id UUID, p_owner UUID, p_system BOOLEAN
) RETURNS BOOLEAN
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, public AS $$
SELECT NULLIF(current_setting('app.user_id', true), '') IS NOT NULL
AND (
p_owner = current_setting('app.user_id', true)::uuid
OR (COALESCE(p_system, false) AND app_is_admin())
-- FUTURE SHARING slot: OR EXISTS (
-- SELECT 1 FROM collection_shares cs
-- WHERE cs.collection_id = p_collection_id
-- AND cs.shared_with_user_id = current_setting('app.user_id', true)::uuid
-- AND cs.permission IN ('edit'))
);
$$;
ALTER TABLE collections ENABLE ROW LEVEL SECURITY;
ALTER TABLE collections FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS p_collections_select ON collections;
CREATE POLICY p_collections_select ON collections
FOR SELECT USING (app_can_read_collection(id, user_id));
DROP POLICY IF EXISTS p_collections_insert ON collections;
CREATE POLICY p_collections_insert ON collections
FOR INSERT WITH CHECK (
user_id = NULLIF(current_setting('app.user_id', true), '')::uuid
OR app_is_admin()
);
DROP POLICY IF EXISTS p_collections_update ON collections;
CREATE POLICY p_collections_update ON collections
FOR UPDATE
USING (app_can_write_collection(id, user_id, is_system_collection))
WITH CHECK (app_can_write_collection(id, user_id, is_system_collection));
DROP POLICY IF EXISTS p_collections_delete ON collections;
CREATE POLICY p_collections_delete ON collections
FOR DELETE USING (app_can_write_collection(id, user_id, is_system_collection));
ALTER TABLE collection_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE collection_items FORCE ROW LEVEL SECURITY;
-- Items ride their PARENT's accessibility: the collections SELECT
-- policy auto-applies inside these EXISTS subqueries.
DROP POLICY IF EXISTS p_collection_items_select ON collection_items;
CREATE POLICY p_collection_items_select ON collection_items
FOR SELECT USING (EXISTS (
SELECT 1 FROM collections c
WHERE c.id = collection_items.collection_id
));
DROP POLICY IF EXISTS p_collection_items_insert ON collection_items;
CREATE POLICY p_collection_items_insert ON collection_items
FOR INSERT WITH CHECK (EXISTS (
SELECT 1 FROM collections c
WHERE c.id = collection_items.collection_id
AND app_can_write_collection(c.id, c.user_id, c.is_system_collection)
));
DROP POLICY IF EXISTS p_collection_items_update ON collection_items;
CREATE POLICY p_collection_items_update ON collection_items
FOR UPDATE
USING (EXISTS (
SELECT 1 FROM collections c
WHERE c.id = collection_items.collection_id
AND app_can_write_collection(c.id, c.user_id, c.is_system_collection)
))
WITH CHECK (EXISTS (
SELECT 1 FROM collections c
WHERE c.id = collection_items.collection_id
AND app_can_write_collection(c.id, c.user_id, c.is_system_collection)
));
DROP POLICY IF EXISTS p_collection_items_delete ON collection_items;
CREATE POLICY p_collection_items_delete ON collection_items
FOR DELETE USING (EXISTS (
SELECT 1 FROM collections c
WHERE c.id = collection_items.collection_id
AND app_can_write_collection(c.id, c.user_id, c.is_system_collection)
));
+2
View File
@@ -12,6 +12,8 @@ services:
build:
context: .
dockerfile: ./Dockerfile
args:
GIT_COMMIT: ${GIT_COMMIT:-none}
# Integration Tests - runs against containerized app and db (dev only)
tests:
+54
View File
@@ -0,0 +1,54 @@
<!-- Ground truth: the Administration section itself (docs/admin/), the app
sidebar's Administration group (templates/header.templ: Dashboard,
Libraries, Podcasts, Hash Conflicts, Users, Settings), and the
per-page ground-truth comments in this directory. This page is a
directory; the pages it links to carry their own source pins. -->
# Admin Guide
Everything an instance administrator runs lives in this section. Like the
rest of Bookhoard's docs, pages tell you what to click — but admin pages
add the layer users don't need: **what each control actually does** before
you click it, what it costs, and what it changes. (The calibration, if
you're curious: *user docs = what you see, admin docs = what it does,
developer docs = how it works*.)
## The Administration section
| Page | What it covers |
| --- | --- |
| [Dashboard](dashboard.md) | The `/admin` landing page: stats, file-watcher status, **Force Rescan All Libraries**, live scan progress |
| [Libraries](libraries.md) | Creating libraries, folders, per-user visibility, per-library scans, deletion semantics |
| [Processing Issues](library-processing-issues.md) | Per-library ledger of items the scanner couldn't process — Retry, Retry all, Dismiss |
| [Archived Items](archived-items.md) | The missing-file lifecycle: two-strikes archiving, Merge/Restore/Delete, retention |
| [Podcasts](podcasts.md) | The all-feeds maintenance view: disk usage, refresh, delete files, remove for everyone |
| [Hash Conflicts](hash-conflicts.md) | Byte-identical duplicates and their resolution (merge reading data or keep both) |
| [Users](users.md) | Accounts, roles, password resets, the last-admin guards |
| [Settings](settings.md) | Every server-wide setting: key, default, range, what it does, restart or live |
| [Scanning](scanning.md) | The deep-dive: shallow vs. force, and what every scan button actually does |
The app's own sidebar shows the first six as the **Administration** group;
Processing Issues and Archived Items hang off the Libraries page.
## If you're setting up a fresh instance
The shortest sane path, in order:
1. **[Libraries](libraries.md)** → Create Library, add its folders
2. Let the initial scan populate it (or **Force Rescan** to be sure)
3. **[Settings](settings.md)** → set the **Base URL** to the address other
devices will use, and check **Auto-Scan** is on
4. **[Users](users.md)** → create accounts (or leave public registration
on), set roles
5. Point devices at the server — the [device guides](../user/user-guide.md)
walk each one
## When something looks wrong
- Books vanished from the library? [Archived Items](archived-items.md) —
they're almost certainly there, history intact.
- A book's metadata is stale or wrong? Open the book → **Rescan**
(re-extracts that one item, sidecars included).
- Duplicates? [Hash Conflicts](hash-conflicts.md).
- A scan didn't pick up your changes? [Scanning](scanning.md) explains
which scans skip unchanged files — and which never do.
+53
View File
@@ -0,0 +1,53 @@
<!-- Ground truth: templates/admin_archived.templ (page copy, Merge/
Restore/Delete row actions, Purge All Archived, retention sentence),
internal/config/config.go (ARCHIVE_RETENTION_DAYS, default 90, 0 =
manual purge only), internal/handlers/media.go (MergeArchivedMediaItem
— reading progress/annotations/collections merge, per-user collisions
keep the active copy), templates/admin_library.templ (entry banner).
Re-verify against these when the page changes. -->
# Archived Items
Archived items are books whose files went missing from disk. Bookhoard
doesn't delete them on the first absence: a library-wide scan that can't
find a file marks the item missing, and only when the file is still absent
for **two consecutive scans** does the item move to the archive. Until
then — or after — the reader's history is preserved, so a file that comes
back (or a move the scanner detects automatically) restores the item with
its reading data intact.
You reach this page from the [Libraries](libraries.md) page, which shows
an **Archived items** banner with the count whenever anything is archived.
## What the page shows
A table of every archived item: book title and author, the file path that
went missing, its library, and a status column. When the list is empty you
get the good news instead: "Nothing is archived or missing. All clear."
## Retention
By default archived items are **permanently deleted after 90 days**
(configured with the `ARCHIVE_RETENTION_DAYS` environment variable; set it
to `0` to keep archived items until you purge them by hand). The page
header states your instance's current rule.
## Actions
| Action | What it actually does |
| --- | --- |
| **Merge** (only when a matching active book exists) | Folds this archived copy's reading data — progress, annotations, collections — into the active copy and removes the archived entry. If the same user has reading data on both copies, the active copy's data wins. This is the right choice when the duplicate is a leftover twin and the real book lives on. |
| **Restore** | Puts the item back into the libraries immediately. If the file is genuinely still gone, the next scan archives it again — useful when you know the file just came back or is about to. |
| **Delete** | Deletes the item **and its reading history** permanently. No archive, no undo. |
### Purge All Archived
The header button wipes every archived item at once — permanently, reading
history included (a confirm dialog says exactly that). It exists for the
"clean slate" moments; per-item **Delete** is the scalpel.
## Related
- [Scanning](scanning.md) — how scans decide what's missing, and why only
library-wide scans (shallow or force) archive; a single-folder scan
never marks its sibling folders' items missing.
+72
View File
@@ -0,0 +1,72 @@
<!-- Ground truth: templates/admin.templ (stats grid, File Watcher card,
Quick Actions, Scanning panel), internal/router/frontend.go (/admin
handler), internal/router/admin_library.go (getAdminStats),
web/src/admin.ts (scanAllLibraries one-job-per-library, watch status
fetch, progress rows), internal/handlers/scanner.go (watch status,
coalescing 409). Re-verify against these when the page changes. -->
# Admin Dashboard
The dashboard at `/admin` is the admin landing page: a four-number health
check, the file-watcher status, and the place where library-wide scans are
launched and watched.
## The stats grid
Four counts, straight from the database, refreshed on every page load:
| Card | What the number counts |
| --- | --- |
| **Libraries** | Every library — book, comic, audiobook, and podcast libraries alike |
| **Books** | Every item across all of them: books, comics, audiobooks, and podcast episodes |
| **Users** | Every account on the instance |
| **Devices** | Every registered sync device (Android, KOReader, Kobo) |
These are instance-wide totals — they don't filter by what any individual
user can see.
## File Watcher
The **File Watcher** card shows how many libraries are currently under
live watch for file changes. The watcher exists when **Auto-Scan** is
enabled on the Settings page; the number updates on page load.
- Watching **0** libraries usually means auto-scan is off — turn it on in
[Settings](settings.md) → Scanning, and the watcher arms on the next
server start.
- Watched libraries get shallow scans as files change, plus a periodic
poll on the scan interval — see [Scanning](scanning.md) for exactly what
those do.
## Quick Actions
### Force Rescan All Libraries
The big one. This is a **force rescan of every library**: each file is
re-read and re-extracted with the scanner's current parsing, and hash
identifiers are recomputed — nothing unchanged is skipped. Use it as the
backfill tool after mass edits or scanner improvements; don't use it as a
routine refresh (that's what the watcher and [per-library
scans](scanning.md) are for, which skip unchanged files).
Mechanically it starts **one scan job per library** and reports per
library: started, or skipped because that library already had a scan
running (only one scan per library can run at a time).
### Manage Libraries
A shortcut to [Libraries](libraries.md), where folders, access, and
per-library scans live.
## The Scanning panel
Whenever scans are running, a **Scanning Libraries** panel appears with a
live progress row per library (progress bar, current file counts, and a
per-library cancel button), plus:
- **Cancel all scans** — stops every queued or running scan job
- The close button — hides the panel; scans keep running without it
The panel appears for any scan — the dashboard's own force rescan, or one
started from the Libraries page. Progress updates live while the page is
open; the jobs themselves run on the server either way.
+56
View File
@@ -0,0 +1,56 @@
<!-- Ground truth: templates/admin_hash_conflicts.templ (cards, actions,
confirms), internal/handlers/hash_conflicts.go (ResolveHashConflict:
keep_all marks resolved; keep reparents children to the kept copy,
deletes the other catalog rows, records who resolved), internal/
services/media_scanner.go (recordHashConflictIfAny), internal/services/
hash_backfill.go (backfill-created conflicts). Re-verify against these
when the page changes. -->
# Hash Conflicts
Hash Conflicts is the duplicate-content queue: groups of catalog items
whose files are **byte-identical** (same SHA-256) but stored at more than
one path in the same library. The scanner flags these as it goes — and
the hash backfill job flags them retroactively for content that predates
hash tracking — so both fresh scans and old libraries surface their
duplicates here.
Duplicates usually mean the same book was copied into two folders, or a
library was reorganized and both the old and new copies got scanned. The
harm is quiet but real: split reading histories, double-counted library
stats, and two entries for one book.
## What a conflict looks like
One card per group: a **Duplicate content** heading, a badge with the
copy count, the library and a short fingerprint of the shared hash, and
one row per copy — title, author, full path, file size, and a usage
summary that's **highlighted when that copy holds reading data** (someone
has actually read it).
## Resolving a group
Two outcomes, both confirm-guarded:
### Keep this copy
Per-copy button. Keeps the copy you chose and folds the **other copies'
reading data into it** (their catalog rows are removed; the underlying
files on disk are never touched — this platform's deletes act on the
catalog, not your files). The row-level usage summaries exist precisely
so you can pick the copy that already carries the reading history.
### Keep both
The group-level button, for duplicates that are intentional. It records
the resolution and stops flagging this group — every copy stays in the
catalog exactly as it is, nothing merged, nothing removed.
After either choice the card is replaced with the outcome, and the group
never comes back (unless the same duplicate situation re-arises from a
*new* scan, which creates a fresh group).
## When the page is empty
"No content duplicates detected." — the queue drains from the top; groups
appear as scans and the backfill find them.
+108
View File
@@ -0,0 +1,108 @@
<!-- Ground truth: templates/admin_library.templ (page, modals, panel,
delete-library warnings), internal/router/admin_library.go (create/
edit/delete, folders, browse, visibility endpoints), internal/router/
library.go (per-library scan route), internal/services/library_service.go
(DeleteLibraryFolder removes the mapping only; SetLibraryVisibility),
templates/utils.go (hxValsFolderScan), templates/admin_archived.templ.
Re-verify against these when the page changes. -->
# Libraries
The Libraries page is where a Bookhoard instance is defined: what
libraries exist, which folders on the server they read from, who can see
them, and how they get scanned. Everything here is admin-only — regular
users just see the result.
## Creating a library
**Create Library** opens a modal with three fields:
- **Library Name** (required) — what users see in their sidebar
- **Description** (optional)
- **Library Type** (required) — book, comic, audiobook, podcast; the type
drives how the scanner parses files and how the reader presents them
A library with no folders can't scan — add at least one folder (below)
before expecting anything to appear in it.
## The library card
Each library renders as a card: name, description, a type chip, a folder
count, and two controls:
- **Force Rescan** — starts a force scan of this one library: every file
re-read and re-extracted, hashes recomputed. This is the heavy,
thorough pass ([Scanning](scanning.md) explains force vs. shallow and
when each is worth it). If a scan is already running for the library,
the click tells you instead of stacking a second one.
- **Manage** — opens the library's panel, where everything else lives.
## The library panel
### Folders
Folders are the server-side directories the scanner walks. Each one shows
its path with two icon actions: **Scan this folder** (a shallow scan
scoped to just that folder's subtree — the quick "I just dropped files
here" button) and remove-from-library (confirm-guarded).
Adding one: type a path, or click **Browse** to walk the server's
filesystem in a modal (up with `..`, into a folder by clicking it,
**Select This Folder** to fill the input), then **Add**.
Two things worth knowing:
- **Removing a folder only unregisters it.** The mapping is deleted;
files on disk and existing catalog items are untouched. If no remaining
folder covers those files, later library-wide scans will treat them as
missing — the [Archived Items](archived-items.md) lifecycle takes over,
history kept.
- **Podcast download folders are feed-managed.** The scanner refuses to
scan them by hand; the podcast feed system owns their contents.
### User Access
One checkbox per user. Checked (the default) means the library is visible
to them; unchecking hides it from their browsing, apps, and OPDS —
enforced in the database, so every listing obeys. Hiding a library never
destroys anything: the user simply can't see it.
### Processing issues
When the library has items the scanner couldn't process, a link here
shows the count and leads to its
[Processing Issues](library-processing-issues.md) page.
### Edit Details and Delete Library
**Edit Details** changes the name and description. The library type is
fixed at creation — it can't be edited later.
**Delete Library** is the destructive one, and its confirm dialog says
precisely what it does:
- **Permanently removed, no archive or undo:** the library, its folder
mappings, and all book records — with their reading progress,
highlights, notes, bookmarks, and ratings.
- **Not touched:** media files on disk. Delete the library, keep the
files; re-create the library later and scan them fresh (with empty
reading history).
## The archived banner
When any library has archived (missing-file) items, this page shows a
banner with the total count and two shortcuts: **View Archived** (the
[Archived Items](archived-items.md) page) and **Purge Archived Now** (the
same permanent wipe the archived page's Purge All Archived performs).
## Every scan entry point, at a glance
| Where | Control | Kind |
| --- | --- | --- |
| This page, library card | **Force Rescan** | Force, this library |
| This page, folder row | **Scan this folder** | Shallow, that folder |
| Admin dashboard | **Force Rescan All Libraries** | Force, everything |
| Settings → Scanning | **Auto-Scan** | Shallow, automatic |
| A book's page | **Rescan** | Force, that one item |
Full semantics for each: [Scanning](scanning.md).
+62
View File
@@ -0,0 +1,62 @@
<!-- Ground truth: templates/admin_processing_issues.templ (stats cards,
Retry all queue, per-issue Retry/Dismiss, severity badges),
internal/handlers/processing_issues.go (RetryProcessingIssue — success
closes the issue, failure returns the real error; resolve path),
internal/router/library.go (issue routes), the deliberately-not-a-
library-rescan design comment in the template. Re-verify against these
when the page changes. -->
# Processing Issues
Processing Issues is each library's ledger of items the scanner could not
fully process — a corrupt file, an unsupported format, metadata that
wouldn't parse. It is per-library: you reach it from that library's panel
on the [Libraries](libraries.md) page (the link only appears when the
library has issues).
## What's on the page
Three count cards — **Errors**, **Warnings**, **Info** — show how many
open issues sit at each severity (a card only appears when that severity
has issues). Below them, one card per issue showing:
- the item's **title** and a plain-language **description** of what went
wrong
- **Type**, **Format**, **File** (full path), and **Library** type
- a severity badge: red for errors, amber for warnings, neutral for info
## Fixing an issue
### Retry
Runs that one item back through the scanner. This is a per-item scan —
the item's file is re-read and re-extracted exactly like a book-page
[Rescan](scanning.md), not a pass over the library. If it succeeds, the
issue closes itself; if it fails again, the page shows the *real* error,
so you know why it still fails instead of staring at a stale complaint.
### Retry all
Queues every issue currently on the page and works through them **one at
a time** — the button shows progress as "done / total" while the queue
drains. This is deliberately not a whole-library scan: fixing a handful of
bad files never re-reads the good ones. Per-issue **Retry** buttons are
disabled while the queue is running.
When the queue finishes, the page refreshes itself from the server —
closed issues disappear, still-failing ones stay with fresh error text.
### Dismiss
Closes an issue without re-processing — for warnings and info items you've
looked at and judged fine (a confirm dialog guards the click). **Errors
cannot be dismissed**: they must be fixed and successfully retried. The
Dismiss button simply doesn't exist on an error card.
## How issues get here and leave
The scanner creates an issue whenever it fails to process an item during a
scan. Issues leave the page three ways: a successful **Retry** (or any
later scan that processes the item cleanly), a **Dismiss** you chose for a
warning or info item, or the file's problem being fixed on disk and the
next scan handling the item cleanly.
+51
View File
@@ -0,0 +1,51 @@
<!-- Ground truth: templates/admin_podcasts.templ (table, actions, orphaned
badge, header totals, design comment: sorted by disk usage), internal/
router/frontend.go (/admin/podcasts handler), podcast polling/download
settings in internal/database/settings_registry.go (SettingsDefaults,
Podcasts group). Re-verify against these when the page changes. -->
# All Podcasts
This is the maintenance view for the podcast subsystem: **every feed from
every user**, sorted by disk usage, so the biggest disk hogs surface
first. (The listening side — subscribing, playing, downloading episodes —
lives in the [user podcast guide](../user/podcasts.md); this page is
about running the thing.)
## The header totals
Above the table: how many feeds exist, how many episodes are downloaded
versus total, and how much disk the downloads occupy instance-wide.
## The table
One row per feed:
| Column | Meaning |
| --- | --- |
| **Feed** | Title (links to its podcast page) and host |
| **Library** | Which library holds it |
| **Subscribers** | How many users subscribe (hover for names). **orphaned** means nobody does — usually a departed user's feed |
| **Downloaded** | Episodes on disk / episodes the feed has published |
| **Disk** | Space the downloaded files occupy |
| **Last fetch** | When the feed was last checked for new episodes |
## Actions, per feed
- **Refresh** — checks the feed for new episodes right now, instead of
waiting for the automatic poll (its interval lives in Settings →
Podcasts).
- **Delete files** (only when episodes are downloaded) — frees the disk
and resets those episodes to *pending*. They re-download on demand when
someone plays them. The confirm says the important part: **a feed
refresh will not re-materialize them** — deleting files is safe and
reversible by playback, not by refresh.
- **Remove** — the admin delete: removes the feed, its episode rows, its
downloaded files, and everyone's subscriptions. This is instance-wide
(the confirm says so); a user removing their own subscription from the
listening side only affects that user.
## When the page is empty
"No podcast feeds exist yet." — feeds appear when users add them (or when
you do, from the podcast section of the app).
+89
View File
@@ -0,0 +1,89 @@
<!-- Ground truth: internal/handlers/scanner.go (ScanLibrary, StartScanner,
per-folder validation, coalescing), internal/services/media_scanner.go
(forceRescan semantics, steady-skip path, watcher/poll/initial
triggers, enqueueLibraryScan force:false), internal/services/worker.go
(SetForce), templates/admin.templ + web/src/admin.ts (dashboard
button, one job per library), templates/admin_library.templ +
templates/utils.go (per-library Scan force:true, per-folder scan),
templates/admin_settings.templ (Auto-Scan, Scan Interval).
Re-verify against these when scanning behavior changes. -->
# Scanning
Scanning is how Bookhoard's server reads your library folders and keeps the
catalog in step with the files on disk. This page covers every scan an
admin can trigger, what each one actually does, and what it costs — so you
can pick the right one before clicking.
## The one distinction: shallow vs. force
Every scan is one of two kinds:
- **Shallow** (the default). The scanner walks the folder and skips any
file whose size and modification time are unchanged since it was last
seen. New and changed files get processed; untouched files cost nothing.
Fast, and the right choice for day-to-day keeping-up.
- **Force**. Nothing is skipped. Every file is re-read and re-extracted
with the scanner's current parsing, and each item's hash identifiers
(the SHA-256 fingerprints used for duplicate detection and device book
matching) are recomputed. This is the backfill tool: run it after
scanner improvements you want applied to already-scanned books, after
mass edits in Calibre or on disk, or when metadata looks stale anywhere
in a library. It is deliberately slow on big libraries.
## Every scan control, and what it does
| Control | Where | Kind | Scope |
| --- | --- | --- | --- |
| **Force Rescan All Libraries** | Admin dashboard → Quick Actions | Force | Every library |
| **Force Rescan** (library row) | Admin → Libraries | Force | That library |
| **Scan this folder** (folder-row icon) | Admin → Libraries → a library's panel | Shallow | That folder's subtree |
| **Auto-Scan** + **Scan Interval (seconds)** | Admin → Settings → Scanning | Shallow | Every library |
| **Retry** / **Retry all** | Admin → Libraries → Processing Issues | Per-item | Failed items only |
| **Rescan** / **Reset to Scanned** | A book's detail page | Per-item | That one item |
The details behind the table:
- **Force Rescan All Libraries** loops over every library and starts a
force scan job for each. Libraries that already have a scan running are
left alone — the button reports which libraries started and which were
skipped because a scan was already in flight.
- **Force Rescan** on a library row is the same force rescan, scoped to
that one library. It shares the dashboard button's semantics exactly.
- **Scan this folder** is the only folder-sized scan, and the only shallow
one an admin triggers by hand: unchanged files are skipped, and only
that folder's subtree is walked. Because a partial scan can't vouch for
what it didn't look at, it never marks items from the library's *other*
folders as missing. Podcast download folders refuse this button — they
are managed by the feed system, not the scanner.
- **Auto-Scan** arms the two automatic triggers, both shallow: a
filesystem watcher that fires as files change, and a periodic poll that
runs every **Scan Interval (seconds)** (default 60, allowed 1–3600).
The same shallow pass also runs once at startup when auto-scan is on.
- **Retry** and **Retry all** on a library's Processing Issues page send
failed items back through the scanner one at a time — deliberately not
a library-wide scan, so fixing a few bad files never re-reads the whole
library.
- **Rescan** on a book's page re-extracts that item from its file and
recomputes its hashes. **Reset to Scanned** clears your manual metadata
edits first, so what lands is purely what the scanner derives from the
file.
## Rules worth knowing
- **One scan per library at a time.** Starting a second scan for a library
that already has one pending or running is refused — the dashboard
tells you a scan is active rather than stacking a duplicate. The
automatic triggers skip silently instead.
- **Scans run in the background.** The dashboard's Scanning panel shows
per-library progress while jobs run; **Cancel all scans** stops the ones
still queued or running, and you can keep working meanwhile.
- **Missing files archive after two consecutive scans.** When a
library-wide scan (shallow or force) can't find a file twice in a row,
the item is archived — reading history is kept in case the file comes
back. The Archived Items page in this section manages the results.
- **Metadata comes from the files themselves.** The scanner reads sidecar
files (Calibre's `metadata.opf` in particular), embedded tags, and
filenames — [Calibre Integration](../user/calibre-integration.md) covers
the sidecar story. What a scan extracts is exactly what a force rescan
re-extracts.
+234
View File
@@ -0,0 +1,234 @@
<!-- Ground truth: templates/admin_settings.templ (page structure, save
buttons, live/restart buckets), internal/database/settings_registry.go
(SettingDefaults: keys, types, defaults, min/max, restart flags,
groups — the source of truth), internal/handlers/system_settings.go
(ApplySetting validates type+bounds then reloads; UpdateScanSettings
validates 1-3600), internal/router/frontend.go (settings page handler,
dedicatedUI exclusion list). Re-verify against these when settings
change — a new key lands in SettingDefaults AND schema.sql AND here. -->
# System Settings
The Settings page is every server-wide knob in one place. Each setting
below lists its **key** (the name shown on the page and stored in the
database), its **default**, its **valid range**, and whether it applies
live or needs a restart.
## How saving works
The page has three separate save paths, each with its own button:
- **Save Settings** (top card) — commits the Base URL and Default
Timezone together.
- **Save Scan Settings** — commits the two scanning controls.
- A per-row **Save** for each tunable setting — you change one value and
save exactly that one.
Live tunables apply immediately. The restart bucket saves your value
right away but only takes effect the next time the server restarts — the
page marks that bucket in amber so it can't be missed. Invalid values are
refused with an error; nothing silently clamps.
---
## Base URL
**base_url** — string, no default. The public URL of your Bookhoard
instance (e.g. `https://books.example.com`). This is the address Bookhoard
hands out to devices and OPDS clients — device sync, OPDS, and API
endpoint references are built from it — so it must be the URL your other
machines can actually reach, not `localhost`. The **URL Paths** card
underneath shows the three addresses derived from it (`/opds`, `/api`,
`/api/sync`) as a sanity check.
## System Defaults
**default_timezone** — string, default `UTC`. The timezone used for any
user who hasn't picked their own (each user's profile can override it).
This governs how the server renders dates and times for that user —
history, stats day boundaries, timestamps. The dropdown offers a fixed
list of zones.
## Scanning
Two of these live in their own card with **Save Scan Settings**; the last
two appear among the Live tunables under a "Scanning" heading. All four
are documented together here.
**auto_scan_enabled** — bool, default on. **Auto-Scan** in the UI. The
system-wide switch for automatic scanning: when on, a filesystem watcher
fires scans as files change, a periodic poll runs on the interval below,
and a shallow scan runs at startup. When off, libraries only change when
you scan them by hand. See [Scanning](scanning.md) for shallow vs. force.
**scan_poll_interval_seconds** — int, default `60`, range 1–3600.
**Scan Interval (seconds)** in the UI. How often the automatic poll
re-checks every library for changes. Lower is more responsive, higher is
less background work; every tick is a shallow scan, so unchanged files
cost almost nothing.
**auto_playlist_collections** — bool, default on. Live tunable. When a
book's sidecar metadata marks its series as a *reading order*, Bookhoard
automatically creates a collection that gathers the series in reading
order. Turn it off to stop creating these during future scans (existing
collections stay).
**scan_extractor_version** — int, default `1`, range 1–1000000. Live
tunable. The parser version stamped on each book's scan manifest. This is
the gradual backfill lever: raise it after a scanner improvement, and
books scanned under the older parser get re-extracted a bounded batch per
scan until all are caught up — no manual force rescan required. Leave it
alone unless you know a parser change shipped; don't set it far ahead of
the real version.
## Session
**session_duration_seconds** — int, default `604800` (7 days), range 300
(5 minutes)–31536000 (1 year). How long a login session stays valid.
Shorter is safer for shared machines; longer means fewer re-logins on
personal devices.
## Password Quality
Five settings that together define every new password — set at
registration, created by an admin, or changed by a user. Existing
passwords are never retroactively invalidated; the rules apply when a
password is next set.
**password_min_length** — int, default `8`, range 1–128. Minimum
character count.
**password_require_upper** — bool, default on. At least one uppercase
letter (A-Z).
**password_require_lower** — bool, default on. At least one lowercase
letter (a-z).
**password_require_number** — bool, default on. At least one digit (0-9).
**password_require_special** — bool, default on. At least one special
character.
The Users page's create form and the change-password form build their
live requirement checklists from these exact values.
## Public Registration
**registration_enabled** — bool, default on. Whether visitors can create
their own accounts from the sign-up page. Off, the instance is
invite-by-admin: accounts are created only from the
[Users](users.md) page (admins can always create accounts).
## OPDS Catalog
Page-size controls for the OPDS catalog (what apps like KOReader use to
browse your library over the network).
**opds_default_page_size** — int, default `50`, range 1–500. How many
entries a catalog page contains when the client doesn't ask for a
specific size.
**opds_max_page_size** — int, default `200`, range 1–1000. The ceiling
on what a client may request — a protection against one app asking for
enormous pages.
## Device Rate Limits
Per-device request ceilings, per minute, by kind of request. These
protect the server from a misbehaving or runaway device; a device that
hits its limit is throttled until the minute rolls over. Defaults are
sized for normal reading — raise them for very large libraries whose
initial device sync needs more headroom.
**device_rate_sync_per_min** — int, default `60`, range 1–10000. Sync
requests per minute (annotations, bookmarks, reading-state sync).
**device_rate_progress_per_min** — int, default `120`, range 1–10000.
Progress updates per minute (position saves as you read).
**device_rate_metadata_per_min** — int, default `30`, range 1–10000.
Metadata requests per minute.
## Annotation Retention
**annotation_tombstone_ttl_days** — int, default `30`, range 1–3650.
When an annotation (highlight, note, bookmark) is deleted, it isn't
destroyed instantly — a tombstone records the deletion so every other
device learns about it on their next sync. After this many days the
tombstone is purged for good. Longer is safer if some of your devices
stay offline for weeks; shorter reclaims rows sooner.
## Conversion Cache
**conversion_cache_ttl_hours** — int, default `24`, range 1–720. How
long converted files (Kobo-optimized KEPUB, for example) are kept cached
after conversion. Longer saves repeat conversion work at the cost of
disk; the conversion is regenerated when the cache entry expires.
## Auth Rate Limiting
*Restart required.*
**auth_rate_limit_per_min** — int, default `10`, range 1–10000. Global
cap on authentication requests per minute — the brute-force damper on
the login endpoints, server-wide. Raise it only if legitimate logins are
being throttled (many users behind one NAT, for example).
## Login Lockout
*Restart required.* Two settings that work as a pair: after
**login_max_attempts** consecutive failed attempts, that account waits
**login_lockout_minutes** before accepting more tries.
**login_max_attempts** — int, default `5`, range 1–100.
**login_lockout_minutes** — int, default `15`, range 1–10080 (up to one
week).
## Sync Queue
*Restart required.* Device-originated sync changes flow through a
background queue instead of being written the instant they arrive.
**sync_queue_interval_seconds** — int, default `5`, range 1–3600. How
often the queue flushes.
**sync_queue_batch_size** — int, default `50`, range 1–10000. The
maximum number of queued items processed per flush.
## Worker Pool
*Restart required.* Background jobs — scans, sync-queue flushes, and
other async work — run on a fixed pool of workers.
**worker_pool_size** — int, default `3`, range 1–100. How many jobs run
concurrently. More workers chew through queued work faster at the cost
of CPU and database load; on a small home server, more is not better.
**worker_queue_cap** — int, default `100`, range 1–10000. How many jobs
may wait in line when every worker is busy. Work offered beyond the cap
is refused rather than queued — a large force rescan of many libraries
wants headroom here.
## Podcasts
How often feeds are checked and how downloads behave server-wide.
**podcast_poll_interval_seconds** — int, default `3600` (one hour),
range 300 (5 minutes)–604800 (one week). How often Bookhoard checks
feeds for new episodes. Feeds marked *complete* (podcasts that have
ended) back off instead of being checked hourly forever.
**podcast_download_concurrency** — int, default `4`, range 1–16. Episode
downloads in flight server-wide; fair-share scheduling spreads them
across feeds so one feed can't hog the slots.
**podcast_download_speed_mbps** — float, default `0` (unlimited), range
0–10000. A shared bandwidth cap, in megabits per second, across all
podcast downloads — useful when the server's connection is also serving
readers.
## About
The version of Bookhoard this server is running. Worth checking before
filing a problem — and after an update, to confirm the new build landed.
+65
View File
@@ -0,0 +1,65 @@
<!-- Ground truth: templates/admin_users.templ (create form, user cards,
last-admin guards), templates/profile_form.templ + profile_modal.templ
(admin edit fields), internal/router/auth.go (admin user endpoints),
internal/router/frontend.go (profile-modal route), user delete cascade
(reading data is owned by the account and goes with it). Re-verify
against these when the page changes. -->
# Users
User Management is where accounts are created, roles are assigned, and
accounts are removed. Changes here are immediate — there is no approval
flow.
## Creating an account
**+ Create User** opens the creation form (it stays hidden until clicked,
so the page doesn't shout account creation at you — and so admins can
still create accounts even when public self-registration is switched off
in [Settings](settings.md) → Public Registration).
Fields: **Username** (3–50 characters), **Email**, **Password** plus a
confirm, optional **First name** / **Last name**, and a **Role** of User
or Admin. The **Password Requirements** list is generated from the
password rules currently configured in Settings — the same rules users
face when changing their own passwords — and the **Create User** button
stays disabled until everything validates.
## The user cards
Every account renders as a card: username (with a **You** badge on your
own), email, the creation date shown in your timezone, and the controls:
### Role
A dropdown — **User** or **Admin** — that applies the moment you change
it. One guard exists: the **last admin cannot be demoted** (the dropdown
disables itself with that explanation while only one admin exists).
Admins see and use the entire Administration section — libraries,
scans, settings, this page.
### Edit
Opens an **Edit User Profile** modal with the same fields the user
controls on their own profile — username, email, first/last name,
**Theme**, **Default Playback Speed**, **Resume Rewind** — plus the Role
dropdown, and a **Change Password** section. The admin version doesn't
ask for the user's current password (only the user's own profile does).
### Delete
Removes the account permanently — and with it everything the account
owns: devices, sessions, and reading data (progress, annotations,
collections). The confirm dialog makes the irreversibility explicit.
Same last-admin guard as the role dropdown: the final admin cannot be
deleted.
## Roles, briefly
- **User** — browses, reads, listens, syncs devices; sees only the
libraries visible to them (visibility is set per-library on the
[Libraries](libraries.md) page).
- **Admin** — everything a user has, plus the Administration section:
libraries and scanning, users, system settings, hash conflicts,
podcasts maintenance.
+324
View File
@@ -443,3 +443,327 @@ Both answers are gated: 403 (Go-level explicit-library checks remain on
listing endpoints) and 404 (row-level invisibility — no existence leak).
Pins asserting 403 on item-scoped content endpoints widen to accept
{403, 404}. Listing/scoped endpoints keep the strict 403 contract.
## 2026-10-29 — Podcast episode columns join media_items (additive widening)
The podcast integration (plan podcast-integration.md tasks 1.1/1.10) adds
fifteen nullable/no-null-default columns to `media_items` — they surface in
raw sqlc rows ONLY (`library-scoped list emits raw sqlc rows`), never in the
resolved unscoped map:
`source` ('scan' default), `source_feed_id`, `episode_guid`, `feed_position`,
`season_number`, `episode_number`, `enclosure_url`,
`declared_duration_seconds`, `transcript_url`, `chapters_url`, `hosts`,
`guests`, `download_state`, `download_error`, `download_attempts`.
Scan-sourced rows carry the inert defaults ('scan' / NULLs / 'pending');
raw-row consumers that filter `source='scan'` (scanner paths) are unaffected.
Nothing removed, nothing renamed.
## 2026-10-30 — download_queue_pos joins media_items (additive widening)
§0 item 4 of podcast-integration.md: the download pool's monotonic
queue ticket. `download_queue_pos BIGINT` (NULL for scan rows and
never-queued episodes) is stamped from the `podcast_queue_seq` SEQUENCE
at enqueue time so claim order = enqueue order (the effective listening
order). Raw-row pins (TestContractPin_MediaListBothBranches →
rawRowKeys) whitelist the key. Nothing removed, nothing renamed.
## 2026-10-30 — episode collections (additive widening, plan item 2/2.3/2.4)
Two shapes widen, both ADDITIVE — nothing removed, nothing renamed:
- **Collections envelope** (`GET /api/collections/:id` → envelopeKeys)
gains `rule_match_mode` (smart-collection match semantics, 'any'
legacy default | 'all'). Static collections emit the default value.
- **BookInfo** (every card surface → bookInfoKeys) gains four STABLE
keys — `is_episode`, `feed_title`, `download_state`, `hidden` — the
episode-collections extras. Adapters that predate episode awareness
emit their zero values (`false`/`""`), matching the
viewer_percentage precedent (nil-representable, key always present).
## 2026-10-30 — collections envelope gains filter_tree (additive widening, item 3.2)
`GET /api/collections/:id` adds `filter_tree` to the envelope: the
unified filter tree when the smart collection carries one (item 3.2 —
tree-driven membership), `null` for legacy/static collections. The
tree is the same qf DSL as saved filters (`{scope?, mode, children}`).
Nothing removed, nothing renamed.
## 2026-10-30 — rules endpoints RETIRED (filter-system unification, item 3.4)
The per-rule CRUD endpoints and the preview endpoint are DELETED — the
unified filter tree (item 3.2) is the only smart-membership authoring
surface, and the rules PAGE is now the filter builder in the
collection's scope:
- `POST /api/collections/:id/rules`, `PUT/DELETE
/api/collections/:id/rules/:ruleId` — gone (legacy rule arrays still
EVALUATE until the collection is rewritten; conversions run at the
builder's first Apply via RulesToFilterTree).
- `POST /api/collections/test-rules` — gone (the builder's live count
via /api/media-items/filter-count replaces the preview).
- `POST /api/collections/preview` STAYS (the dashboard
custom-section-builder still consumes it — flagged for its own
migration, not silently broken).
- Legacy compatibility KEPT: `auto_assign_rules` still round-trips in
the collections envelope; `PUT /api/collections/:id/match-mode`
still serves rules-array collections.
Test-side deletions follow the asymmetry rule: subtests exercising the
deleted endpoints are gone; their surviving SEMANTICS are pinned in
their tree form (TestSmartCollections rewritten on trees,
TestEpisodeCollectionsFilterTree, TestPodcastSmartCollections).
## 2026-10-31 — collections RLS: cross-user detail/writes tighten to 404/no-op
`collections` and `collection_items` joined the RLS-governed tables
(policies `p_collections_*` / `p_collection_items_*`, predicates
`app_can_read_collection` / `app_can_write_collection` — the same
doctrine as the media_items family lens, 2026-10-29). Contract
changes:
- `GET /api/collections/:id` for another user's collection: was 200
(by-id readability), now 404 (row invisible).
- `PUT /api/collections/:id` cross-user: was ungated success (no
app-level ownership check), now 404 — the RLS update touches no
rows, and the handler maps ErrNoRows to 404.
- `POST /api/collections/:id/books` cross-user: was ungated, now 404
(rejectSmartMutation's GetCollectionData is RLS-invisible).
- `DELETE /api/collections/:id` cross-user: still 204, but now a true
DB-level no-op (zero rows deleted) instead of an app-level free hit.
- `PUT /api/collections/:id/view-settings` cross-user: 404 (the owner
gate stays as defense-in-depth; the DB is enforcement of record).
- `PUT .../match-mode` and `.../items/order` keep their app-level 403
gates; the DB now backs them.
- Reads: owner or admin (policy escape); non-owner non-admin users see
nothing, anonymous included. Future sharing rides the predicate
functions — one EXISTS branch in app_can_read/write_collection, no
policy migration.
Test-side: TestCollectionsRLS pins the cross-user matrix end-to-end;
fixture writes to non-system collections run as the row's OWNER
(scopeExecAs/ownerSeedCtx) because the admin write-escape covers
system collections only.
## 2026-10-31 — legacy collection rules surface RETIRED (tree-only storage)
The pre-tree rules machinery is gone — no production row ever carried a
rules array or a non-default match mode (verified in the dev DB), the
web never reads the envelope keys, and the Android app consumes none of
it. Deletions:
- `PUT /api/collections/:id/match-mode` — endpoint retired (it had no
doc page). The tree's root `mode` owns any|all semantics now.
- Envelope: `auto_assign_rules` and `rule_match_mode` are REMOVED from
the create/list/detail/update payloads. This entry retracts the
2026-10-30 pins that listed them. `collection_type` and `is_smart`
stay.
- Request: `auto_assign_rules`/`rule_match_mode` are no longer accepted
on create/update. A create carrying `auto_assign_rules` answers 400
naming the retirement — the custom-section builder's legacy save
(already failing to bind, verified live) fails loudly instead of
silently creating a hollow static section.
- Storage: the `collections.auto_assign_rules` and
`collections.rule_match_mode` columns are DROPPED (idempotent
`DROP COLUMN IF EXISTS` in schema.sql).
- Service: the rules CRUD layer (AddRule/SetRuleEnabled/RemoveRule +
validateRule + the UpdateCollectionRulesJSON query),
ParseRules/EnabledRules/IsSmartCollection, RulesToFilterTree (+ the
SSR preload branch), and the legacy branch of EvaluateSmartMembership
are deleted. IsCollectionSmart = tree presence.
KEPT (live consumers): `POST /api/collections/preview` still accepts
`rules` and evaluates them in memory (the custom-section builder's
preview button); `include_auto` on the list stays (the Android app
sends it). The builder's SAVE remains the flagged §12 tree migration.
## 2026-10-31 — custom-section builder save: the flagged tree migration lands
Supersedes the same-day retirement entry's loud-400 stance for the
builder's payload. `POST /api/collections` now ACCEPTS the builder's
shape and adapts it at write time:
- `auto_assign_rules` (JSON-encoded array — string or bare) converts to
a filter tree via the restored `RulesToFilterTree`; converted trees
validate under `ParseFilterTree`, so an unhonorable rule is a 400 at
write naming the problem.
- `match_type` seeds the tree's root mode (`any` default).
- `manual_book_ids` attach to the created collection after create
(unparsable ids skipped — the AddBooks leniency).
- `show_on_dashboard` persists (new create field).
- `library_id` remains selection context only (not stored).
Dashboard sections: smart user sections evaluate their tree LIVE —
`GetUserCollectionItems` merges stored membership with the composed
engine's matches (deduped, library-scoped, capped at the section
limit). This exposed and fixed a real wiring bug: every production
`NewDashboardService` call omitted the search service, so tree
evaluation through the dashboard could never work (the test harness
wired it correctly — the gap was production-only). The dashboard
handler and both inline sites now receive it, and evaluation failures
log instead of silently emptying a section.
## 2026-11-01 — feed operator vocabulary collapsed (Option A): one name per semantic
The feed field's menu offered `is`/`isn't` alongside `in`/`isn't in` —
exact synonyms (the clause compiles both pairs to the same `ANY`). The
MENUS now offer `in`/`isn't in` (+ has/missing) only. This is an
offered-vocabulary narrowing, not a parse change:
- Stored trees and saved filters carrying `feed is X` / `feed is_not X`
PARSE AND EVALUATE FOREVER (`legacyFieldOps` accepts the synonyms at
validation — the stored wire is never invalidated).
- The fields payload (the client's operator menus) no longer carries
the duplicates.
- Client id-cells are uniform: every operator on an id-valued field
accepts a set, so all id cells say "pick one or more" and accumulate
picks — no per-operator placeholder/pick distinction to explain.
## 2026-11-01 — id labels resolve at render (SSR embed): refresh keeps names
Pages that render a filter tree embed the tree's id→name map at render
time (`data-id-labels` on the builder mount) — the collection editor
(stored tree) and the bookshelf (URL `qf`). Before this, refresh showed
raw uuids: only ids persist in trees; the client's id→label cache dies
with the page, and the quiet suggest fetch reused the MEDIA-CONSTRAINED
facet, so an id whose media doesn't match the tree's sibling rules got
no row and no label (live repro: `feed in [A,B,C] AND title contains
Chapter` labeled one feed of three — two feeds had no "Chapter"
episodes).
- `SearchService.FilterTreeLabels` reads the ENTITY tables (no media
join, no tree constraint): podcast_feeds and collections are
RLS-governed through the scoped handle (invisible ids resolve to
nothing); libraries mirror the facet's visibility join; added_by is a
plain username lookup. A zero-episode feed resolves its title —
pinned (TestRulesPageEmbedsIdLabels), as is the hidden-library
non-resolution.
- The bookshelf drawer also HYDRATES at component init now (no
data-tree mount → read the form): the parent's x-init
(initBookshelf) runs BEFORE the nested builder component exists
(Alpine initializes parents first), so its builderData() call was
null and a URL-qf refresh left the drawer with an empty seeded rule
while the grid stayed filtered. Init-order contract pinned in
filter_builder.test.ts.
- The quiet suggest fetch remains only as a fallback for trees the SSR
never saw (client-side apply flows); embedded labels make it a no-op
on refresh.
## 2026-11-01 — unset podcast order defaults to reversed (audiobook-first)
The per-feed listening order (the D5 `podcast_order:<feedID>` KV shown
in the Order dropdown) resolved its UNSET state to "native" — feed
document order, which runs newest-first for classic RSS, so an
audiobook feed played its LAST chapter first. The unset default is now
`reverse` at every resolution site of that one setting: the podcast
page list + dropdown (`podcastOrderForFeed`), the player's feed chain
(reader.go), and the download worker (`orderOverrideFor`).
- Stored overrides are untouched: anyone who picked an order keeps it
(native remains a valid, savable choice).
- No ordering semantics changed — `OrderEpisodes` and the four-option
vocabulary are as they were; only the unset fallback flipped.
- Pinned: the player sequence config carries `"order":"reverse"` and
feed position 1 plays LAST for an unset feed; the podcast page's
dropdown renders `reverse` selected (TestPodcastPlayerOrderControl,
replacing the former native pin).
## 2026-11-01 — new podcast smart collections are BORN reversed
`POST /api/collections` with an EPISODES-scope `filter_tree` seeds
`view_settings.chain_order = "reverse"` on the new row (merge semantics:
an explicit client `chain_order` is never clobbered). The dropdown's
default selection and the chain/page behavior come from the STORED
value — no resolution-logic changes; books-scope smart collections and
statics get nothing seeded; existing collections are untouched.
Pinned (TestSmartCollectionBornReversed): episodes seed, explicit-keep,
books-scope no-seed, static no-seed; TestEpisodeCollectionsFilterTree's
born-reversed chain/page pins replace the former native expectations
(which changelog here per the expectation-change rule). One misplaced
pin from 81e54f89 was corrected while flipping: the API envelope's
match list is NOT chain-ordered and never was — order pins live on the
SSR page and the reader chain.
## 2026-11-01 — label endpoint replaces the suggest-facet fallback
`GET /api/filter/labels?field=X&ids=a,b,c` names id-kind filter values
from their source tables (entity rows only — no media join, no tree
constraint; visibility/RLS ride the request identity). Non-id fields
are a 400; ids truncate at the same 100 cap the SSR embed uses.
The client's label resolution (`resolveIdLabels`/`resolveLabelsAsync`)
now uses ONLY this endpoint. The former fallback — the quiet suggest
fetch through the MEDIA-CONSTRAINED facet — is deleted: it labeled only
the ids whose media matched the tree's sibling rules (the live feed
repro), which mattered exactly where the SSR embed can't reach:
applying a SAVED filter from a cold bookshelf. The apply flow now
resolves through the endpoint and rebuilds the chips bar when labels
land. Pinned (TestFilterLabelsEndpoint): a zero-episode feed resolves
its title, comma-joined ids resolve together, an unsubscribed feed id
stays unnamed (RLS), non-id fields are 400.
## 2026-11-01 — the rules-Apply path seeds the reversed default too
PUT /api/collections/:id carrying an EPISODES-scope filter_tree seeds
`chain_order = "reverse"` when neither the request nor the stored
view_settings names one — the creation seed's twin: a static collection
becoming smart lands with the same default a born-smart one gets.
Explicit values (client-sent or stored — e.g. a deliberate native)
are never clobbered. Pinned (TestSmartCollectionBornReversed):
apply-seeds-when-unordered, respects stored native, respects client
native.
TestPodcastSmartCollections' acceptance pin updated with the same flip:
the briefing acceptance now starts from the page's FIRST card (feed
position 5 — the born-reversed default's book order) and chains into
feed position 1. The acceptance meaning is unchanged: play from what
you see, chained back-to-back within the live briefing set.
## 2026-11-01 — audio resume rewind setting
- `GET /api/media-items/:id/chapters` gained one ADDITIVE response key:
`resume_rewind_seconds` (int, the requesting user's setting; 0 for
anonymous). Existing keys unchanged. The web player and the Android
app both gate the value through the 0/5/10 allow-list, so servers
without the key (absent → 0) degrade to exact resume.
- `GET /api/auth/profile` now always carries
`audio_resume_rewind_seconds` (int, never omitted — 0 is a real
value, exact resume). `PUT /api/auth/profile` accepts the key as the
keep_screen_awake-style STRING ("0"/"5"/"10") so the profile form's
select can send an explicit Off; JSON clients that omit it leave the
column untouched, and anything outside {0,5,10} is 400.
Pinned (TestAudioResumeRewind): default 0, PUT "5" rides the
chapters payload, non-allow-listed rejections change nothing,
explicit "0" resets everywhere, omitted key leaves it untouched.
## 2026-11-02 — pairing codes replace the registration broadcast
- `POST /api/devices/register` gained one ADDITIVE response key:
`pairing_code` (string, 6 digits) — the claim credential the
registering device displays. Existing keys (`registration_id`,
`auth_url`, `qr_code`, `expires_in`, `poll_interval`,
`setup_instructions`) unchanged, so the Android app's DTO is
untouched. Request parse set unchanged.
- The four pinned KOReader sync surfaces (progress push/pull, library,
bookmarks push) and the Kobo surfaces are byte-identical — pairing
codes only touch the registration/approval path, never sync.
- `GET /api/devices/pending` keeps its response SHAPE but is
deprecated-by-emptiness: unclaimed registrations return to no
account (the broadcast was the first-approve-wins hole). The keys
`registrations`, `pending_registrations`, `total` still emit.
- New unpinned surfaces (no prior shape to freeze):
`POST /api/devices/claim` (pairing-code → bind to caller's account;
HTMX callers get `HX-Refresh` instead of JSON),
`POST /api/devices/claim/lookup` (confirm-card data, no binding),
`POST /api/devices/register/cancel` (the registering device ends its
own attempt; registration UUID bearer).
- `POST /api/devices/reject/:registration_id` REMOVED — the broadcast
list was its only consumer; unclaimed registrations are invisible by
design, so there is nothing left for anyone to reject. Removal
recorded here per rule 4 (user-approved plan; the route was the
theft vector's cleanup half).
- `GET /api/devices/approve/:registration_id` (Android self-approval)
keeps its response shape; the registration UUID is now only ever
known to the device that created it, since no list publishes it.
+3 -3
View File
@@ -4,7 +4,7 @@ Welcome to the Bookhoard contributing documentation. This section contains guide
## 🚀 Getting Started
- **[Development Guide](Development.md)** - Development workflow and architecture
- **[Development Guide](development.md)** - Development workflow and architecture
- Architecture overview
- Directory structure
- Local development setup
@@ -14,7 +14,7 @@ Welcome to the Bookhoard contributing documentation. This section contains guide
## 📋 Project Guidelines
- **[AGENTS.md](../../AGENTS.md)** - Agent/development rules
- **[AGENTS.md](../contributing/contributing.md)** - Development rules and standards live in the Contributing portal
- Critical prohibitions
- Mandatory requirements
- Error recovery protocol
@@ -22,7 +22,7 @@ Welcome to the Bookhoard contributing documentation. This section contains guide
## 🤝 How to Contribute
We welcome contributions! Please see our [Development Guide](Development.md) for information on:
We welcome contributions! Please see our [Development Guide](development.md) for information on:
- Setting up your development environment
- Understanding the codebase
+12 -3
View File
@@ -287,6 +287,15 @@ Test-created data rules (harness cleanup depends on them): users use
`@tests.bookhoard.internal` / `@example.com` emails, libraries and
collections carry "test"-prefixed names, and cleanups delete test
libraries (cascades handle the rest) rather than table-wide deletes.
Devices attach to the per-run regular user when it doesn't matter, or
self-delete via `TestDeviceSetup.CreateDevice` / `createContractDevice`
/ `cleanupDeviceByIdentifier` when they attach to the shared admin —
names lacking "test" (device-type names like "koreader", the
"Reinstall Device" label) escaped the name sweeps for weeks and piled
476 rows onto the live dev account; every suite now cleans its own
rows at test end, with the harness sweep's identifier/token patterns
(`contract-%`, `opds-folders-%`, `repro-reinstall-%`,
`dev_contract_*`) as the drift net.
### Media Fixtures (audio/books)
@@ -510,9 +519,9 @@ DEBUG=true
## 📚 Additional Resources
- [AGENTS.md](../../AGENTS.md) - Agent/development rules
- [API Reference](../API_REFERENCE.md) - Complete API documentation
- [Troubleshooting](../TROUBLESHOOTING.md) - Deployment issues
- [Development rules and standards](contributing.md) - Contributing portal
- [API Reference](../developer/api/api-reference.md) - Split endpoint docs, indexed from its overview
- [Troubleshooting](../operations/troubleshooting.md) - Deployment issues
- [Go Documentation](https://go.dev/doc/)
- [Echo Framework](https://echo.labstack.com/docs)
- [pgx Documentation](https://pgx.github.io/pgx/)
+94 -83
View File
@@ -1,92 +1,103 @@
# Alpine.js Patterns in Bookhoard
## Book Picker Modal Pattern (SSR + HTMX + Alpine.store)
For modals that need state persistence across HTMX swaps:
### TypeScript
<!-- Ground truth: web/src/alpine.ts (the @alpinejs/csp build — this is
load-bearing for every rule below), component registrations across
web/src (Alpine.data in admin.ts, api.ts, audio.ts, book-detail.ts,
bookPicker.ts), the bookPicker store (web/src/bookPicker.ts), the
dynamic-attribute patterns in templates/header.templ
(x-data="sidebarShell('…')" whole-expression values) and
web/src/custom-section-builder.ts (data-attributes instead of inline
handlers — the CSP build refuses them). Re-verify when the frontend
stack changes. -->
# Alpine.js patterns in Bookhoard
Bookhoard's Alpine runs the **`@alpinejs/csp` build** — the CSP build, so
the app's `script-src` can stay a hash allow-list with no
`'unsafe-eval'`. That single fact dictates most of this page: inline
JavaScript in HTML is not evaluated, so everything expressive lives in
registered TypeScript components.
## Rule one: components are registered, not inlined
Every `x-data` references a component registered with `Alpine.data` in
`web/src` — the attribute value is the component name (optionally with
arguments), never an object literal:
```typescript
// web/src/admin.ts
Alpine.data("admin", () => ({ /* state + methods */ }));
```
```html
<!-- templates/admin.templ -->
<body x-data="admin" class="theme-tokyo-night">
```
Arguments work, but the **whole attribute value must be the expression**
— templ does not interpolate `{ expr }` inside quoted attribute values,
so `x-data="sidebarShell('{ col.ID }')"` would ship a literal `{ col.ID }`
to the browser:
```html
<div x-data={ "sidebarShell('" + string(mode) + "')" }>
```
Free-text arguments that could contain quotes go through
`templates.JSONArg`, never string concatenation.
## Stores: state that survives htmx swaps
Alpine's reactivity is DOM-local; when htmx swaps a node, its `x-data`
state dies with it. State that must survive swaps lives in a store —
`web/src/bookPicker.ts` is the canonical example:
```typescript
// web/src/bookPicker.ts
Alpine.store("bookPicker", {
isOpen: false,
selectedBooks: new Set<string>(),
open() {
this.isOpen = true;
this.selectedBooks.clear();
this.loadBooks();
},
close() {
this.isOpen = false;
this.selectedBooks.clear();
},
toggleBook(id: string) {
if (this.selectedBooks.has(id)) {
this.selectedBooks.delete(id);
} else {
this.selectedBooks.add(id);
}
// Trigger reactivity
this.selectedBooks = new Set(this.selectedBooks);
},
isSelected(id: string): boolean {
return this.selectedBooks.has(id);
},
get selectedCount(): number {
return this.selectedBooks.size;
}
open() { /* … */ },
toggleBook(id: string) { /* … */ },
});
Template
<!-- Open button -->
```
```html
<button @click="$store.bookPicker.open()">Add Books</button>
<!-- Modal -->
<div x-show="$store.bookPicker.isOpen"
x-transition
@click.self="$store.bookPicker.close()"
style="display: none;">
<!-- Search with HTMX -->
<input @input.debounce.300ms="searchBooks($el.value)"
hx-get="/api/media-items/filtered"
hx-target="#book-picker-grid"
hx-include="#filter-form" />
<!-- Book grid with checkboxes -->
<div id="book-picker-grid" x-init="loadBooks()">
<!-- Server returns HTML with checkboxes -->
</div>
<!-- Selected count -->
<span x-text="$store.bookPicker.selectedCount"></span>
<!-- Submit -->
<button @click="$store.bookPicker.submit()">Add Selected</button>
</div>
Key Principles
- ✅ Alpine.store persists state across HTMX DOM swaps
- ✅ Server returns HTML with checkbox :checked attributes
- ✅ No client-side rendering or manual DOM manipulation
- ✅ HTMX handles dynamic content updates
- ✅ Alpine manages UI state only
Dropdown Pattern (Local x-data)
<span x-text="$store.bookPicker.selectedBooks.size"></span>
```
The server returns HTML (checked checkboxes included); the store tracks
selection across swaps; nobody rebuilds markup from JSON.
## Local state: plain `x-data` on the smallest element
Ephemeral UI (a dropdown, a panel toggle) needs no store and no
round-trip:
```html
<div x-data="{ dropdownOpen: false }">
<button @click="dropdownOpen = !dropdownOpen">Toggle</button>
<div x-show="dropdownOpen"
@click.outside="dropdownOpen = false"
x-transition
style="display: none;">
<!-- Dropdown content -->
</div>
<div x-show="dropdownOpen" @click.outside="dropdownOpen = false">…</div>
</div>
Best Practices
- ✅ State lives in template (x-data)
- ✅ UI updates automatically (x-show)
- ✅ No manual DOM manipulation in TypeScript
- ✅ Pure business logic only in TypeScript functions
- ✅ Use Alpine.store for global state
- ✅ Use local x-data for component state
- ✅ Use x-init for setup only (no data fetch for SSR pages)
- ❌ Never use classList in TypeScript
- ❌ Never use getElementById for show/hide
- ❌ Never fetch data in x-init (for SSR pages)
```
## The banned list — all enforced by the CSP build
- **No inline handlers**, in any form: `onclick=`, `onerror=`,
templ-brace variants — hash-mode CSP refuses them unconditionally.
Rows generated in TypeScript carry `data-*` attributes and bind
listeners after swap (see `custom-section-builder.ts`).
- **No `hx-on*` attributes and no `js:`-prefixed `hx-vals`** — both
evaluate strings, which the CSP build cannot do. Plain JSON `hx-vals`
only (`templates/utils.go` has the helper).
- **No inline `<script>` outside `theme_flash_guard.templ`** (the one
sanctioned pre-paint script); everything else bundles from `web/src`.
## Division of labor
The full ownership rule lives in
[Writing UI documentation without screenshots](writing-ui-docs.md) and
the repo's AGENTS.md: **templ decides what things look like; TypeScript
decides what shows.** Content derived from server data is rendered by
templ (fetch a partial with `htmx.ajax` when it changes); TypeScript
handles pure client-local state — open/closed panels, validation,
toasts. `classList`/`getElementById` show-hide from TypeScript is a
defect, not a shortcut.
+2 -2
View File
@@ -1,6 +1,6 @@
# Android App — Design & Roadmap
This document describes the planned native Android client for Bookhoard: a thin, offline-first reading app that treats the Bookhoard server as its backend. The relationship is the same as the audiobookshelf app to an audiobookshelf server, or the Kindle app to Kindle cloud — the server owns the library, sync, and conflict resolution; the app is a dedicated, mobile-first reading frontend with its own UI, designed independently of the web interface.
This document describes the planned native Android client for Bookhoard: a thin, offline-first reading app that treats the Bookhoard server as its backend. The relationship is the same as any dedicated reader app to its server: the server owns the library, sync, and conflict resolution; the app is a dedicated, mobile-first reading frontend with its own UI, designed independently of the web interface.
**Status**: Planning / pre-development
**Companion repo**: `bookhoard-app` (separate repository, AGPL-3.0)
@@ -32,7 +32,7 @@ This document describes the planned native Android client for Bookhoard: a thin,
### Why native Android
- The quality bar is the Kindle app. Page-turn latency, text layout fidelity, PDF rendering (`PdfRenderer`), and comic/manga image pipelines are platform-level strengths — and they are the *hard* parts in a WebView, not the easy parts.
- The quality bar is a first-class native reader app. Page-turn latency, text layout fidelity, PDF rendering (`PdfRenderer`), and comic/manga image pipelines are platform-level strengths — and they are the *hard* parts in a WebView, not the easy parts.
- Android-first removes the "share one codebase across two platforms simultaneously" constraint that motivates hybrid stacks.
- Solo, AI-assisted development compresses the cost of native (code volume), while native's failure modes (well-documented platform APIs) are far easier to debug — alone or with AI — than cross-framework bridge/plugin bugs.
- The target audience is the self-hosted community, best reached via GitHub Releases and F-Droid rather than app-store optimization.
+5 -3
View File
@@ -144,9 +144,11 @@ See [Device Registration & Sync](devices/get_devices.md)
- GET /api/devices/:id - Get device
- PUT /api/devices/:id - Update device
- DELETE /api/devices/:id - Delete device
- GET /api/devices/pending - List pending registrations (admin)
- GET /api/devices/approve/:registration_id - Approve registration (admin)
- POST /api/devices/reject/:registration_id - Reject registration (admin)
- GET /api/devices/pending - List pending registrations (always empty — pairing codes replaced the broadcast list)
- GET /api/devices/approve/:registration_id - Approve registration by UUID (Android self-approval path)
- POST /api/devices/claim - Claim a registration by its pairing code ([Pairing codes](devices/claim_device.md))
- POST /api/devices/claim/lookup - Resolve a pairing code without binding ([Lookup](devices/lookup_pairing_code.md))
- POST /api/devices/register/cancel - The registering device cancels its own pairing attempt ([Cancel](devices/cancel_device_registration.md))
- POST /api/devices/:id/shelves - Add to shelf (Kobo; used by native Kobo sync, coming soon)
- GET /api/devices/:id/shelves - Get shelf contents
- DELETE /api/devices/:id/shelves - Remove from shelf
@@ -1,89 +0,0 @@
---
method: POST
path: /api/collections/:id/rules
auth: jwt
area: collections
---
<!-- source: internal/handlers/collections.go:877 CollectionHandler.AddRule -->
# Add Auto-Assign Rule
Add an automatic book assignment rule to a collection.
**Endpoint**: `POST /api/collections/{id}/rules`
**Auth**: Required
**Content-Type**: `application/json`
## Path Parameters
| Parameter | Type | Required | Description |
| --------- | ------------- | -------- | --------------- |
| id | string (UUID) | Yes | Collection UUID |
## Request Body
| Field | Type | Required | Description |
| -------- | ------------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| field | string | Yes | Field to match on (genre, author, series, language, publisher, copyright_year, tags) |
| operator | string | Yes | Comparison operator (equals, not_equals, contains, not_contains, starts_with, ends_with, greater_than, less_than) |
| value | string/number | Yes | Value to compare against |
| priority | integer | No | Rule priority (1 = highest, default: 1) |
| enabled | boolean | No | Whether rule is active (default: true) |
### Supported Fields
| Field | Type | Description |
| -------------- | ------ | ------------------------------------- |
| genre | string | Book genre |
| author | string | Book author |
| series | string | Book series name |
| language | string | Book language |
| publisher | string | Publisher name |
| copyright_year | number | Publication year (numeric comparison) |
| tags | string | Book tags |
### Supported Operators
| Operator | Type | Description |
| ------------ | ------ | ------------------------------------- |
| equals | all | Exact match |
| not_equals | all | Not equal |
| contains | string | Contains substring (case-insensitive) |
| not_contains | string | Does not contain |
| starts_with | string | Starts with (case-insensitive) |
| ends_with | string | Ends with (case-insensitive) |
| greater_than | number | Greater than |
| less_than | number | Less than |
### Example Request
```json example-request
{
"field": "genre",
"operator": "equals",
"value": "Science Fiction",
"priority": 1,
"enabled": true
}
```
## Response (201 Created)
```json example-response
{
"collection_id": null,
"is_smart": null,
"rule": null
}
```
## Error Responses
| Code | Description |
| ---- | ----------------------------------- |
| 400 | Invalid request (validation failed) |
| 401 | Authentication required |
| 404 | Collection not found |
| 500 | Internal server error |
## Try It Out
@@ -23,7 +23,6 @@ Creating a collection whose name already exists for the user returns **409**.
"color": "#00FF00",
"icon": "📖",
"collection_type": "static",
"auto_assign_rules": [],
"view_settings": { "kobo": { "view_mode": "grid" } }
}
```
@@ -39,7 +38,6 @@ Creating a collection whose name already exists for the user returns **409**.
"color": "#00FF00",
"icon": "📖",
"collection_type": "static",
"auto_assign_rules": null,
"view_settings": { "kobo": { "view_mode": "grid" } },
"book_count": 0,
"created_at": "2026-10-24 13:57:01.81234 +0000 UTC"
@@ -57,20 +55,13 @@ RFC3339. Treat it as display text; do not parse it as an ISO timestamp.
| description | string | no | |
| color | string | no | hex color, e.g. `"#FF5733"` |
| icon | string | no | emoji |
| collection_type | string | no | `"static"` (default) or `"smart"`; also implied by non-empty `auto_assign_rules` |
| auto_assign_rules | array | no | rule objects, see below |
| collection_type | string | no | `"static"` (default) or `"smart"`; also implied by a `filter_tree` |
| view_settings | object | no | per-device display preferences |
### Auto-assign rule object
| Field | Type | Required | Notes |
| ----- | ---- | -------- | ----- |
| id | string | no | rule id |
| field | string | yes | one of `genre`, `series`, `author`, `language`, `publisher`, `copyright_year`, `tags` |
| operator | string | yes | one of `equals`, `not_equals`, `contains`, `not_contains`, `starts_with`, `ends_with`, `greater_than`, `less_than` |
| value | string | yes | value to compare against |
| priority | number | no | 1-10; higher values take precedence |
| enabled | boolean | no | absent = enabled (rules written before this field existed keep matching) |
| filter_tree | object | no | the unified filter tree (qf DSL); presence makes the collection smart |
| auto_assign_rules | string \| array | no | custom-section-builder payload — converted to `filter_tree` at write (see custom-section-builder doc) |
| match_type | string | no | builder payload: `any` (default) or `all` — seeds the converted tree's root mode |
| manual_book_ids | string\[\] | no | builder payload: attached to the collection after create |
| show_on_dashboard | boolean | no | pins the collection as a dashboard section |
## Errors
@@ -27,7 +27,6 @@ GET /api/collections/550e8400-e29b-41d4-a716-446655440000
"description": "Books I want to read soon",
"color": "#00FF00",
"icon": "📖",
"auto_assign_rules": null,
"view_settings": { "kobo": { "view_mode": "grid" } },
"books": [],
"book_count": 0,
@@ -57,8 +56,8 @@ GET /api/collections/550e8400-e29b-41d4-a716-446655440000
| description | string | |
| color | string | |
| icon | string | |
| auto_assign_rules | array \| null | |
| view_settings | object | |
| filter_tree | object \| null | the unified filter tree (qf DSL); null = static |
| books | array | book cards in this collection |
| book_count | number | length of `books` |
| is_smart | boolean | |
@@ -29,7 +29,6 @@ GET /api/collections?include_auto=true&sort_by=name
"description": "Books I want to read soon",
"color": "#00FF00",
"icon": "📖",
"auto_assign_rules": null,
"created_at": "2026-10-24 13:57:01.81234 +0000 UTC",
"book_count": 12,
"is_smart": false
@@ -65,7 +64,6 @@ GET /api/collections?include_auto=true&sort_by=name
| description | string | |
| color | string | |
| icon | string | |
| auto_assign_rules | array \| null | raw rules JSON; non-null implies smart |
| created_at | string | Go `time.String()` format |
| book_count | number | live count; respects `library_id` for smart collections |
| is_smart | boolean | |
@@ -1,46 +0,0 @@
---
method: DELETE
path: /api/collections/:id/rules/:ruleId
auth: jwt
area: collections
---
<!-- source: internal/handlers/collections.go:960 CollectionHandler.RemoveRule -->
# Remove Auto-Assign Rule
Remove an automatic book assignment rule from a collection.
**Endpoint**: `DELETE /api/collections/{collectionId}/rules/{ruleId}`
**Auth**: Required
**Content-Type**: `application/json`
## Path Parameters
| Parameter | Type | Required | Description |
| ------------ | ------------- | -------- | --------------- |
| collectionId | string (UUID) | Yes | Collection UUID |
| ruleId | string (UUID) | Yes | Rule UUID |
## Response (204 No Content)
Rule deleted successfully. No response body.
```json example-response
{
"collection_id": "550e8400-e29b-41d4-a716-446655440000",
"is_smart": true
}
```
`is_smart` reflects the collection state AFTER removal — removing the
last rule converts a smart collection back to static.
## Error Responses
| Code | Description |
| ---- | ---------------------------- |
| 401 | Authentication required |
| 404 | Collection or rule not found |
| 500 | Internal server error |
## Try It Out
@@ -0,0 +1,48 @@
---
method: PUT
path: /api/collections/:id/view-settings
auth: jwt
area: collections
---
<!-- source: internal/handlers/collections.go CollectionHandler.SetCollectionChainOrder -->
# Set Collection Chain Order
Sets the curated listening order for the collection's episode sequence
(plan §10 R2): the chain producer (`buildSmartCollectionSequenceContext`)
plays `Play as Sequence` in this order. The key merges into the
collection's `view_settings` JSONB — playlist toggles that share the
document survive the write. Owner-only.
## Example request
```json example-request
{
"chain_order": "newest"
}
```
## Example response
```json example-response
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"chain_order": "newest",
"view_settings": { "chain_order": "newest" }
}
```
## Fields
| Field | Type | Required | Notes |
| ----- | ---- | -------- | ----- |
| chain_order | string | Yes | One of `native`, `newest`, `oldest`, `reverse`; `native`/empty removes the stored key |
## Errors
| Status | Body | When |
| ------ | ---- | ---- |
| 400 | `{"error": "invalid collection id"}` | malformed id |
| 400 | `{"error": "chain_order must be one of: native, newest, oldest, reverse"}` | unknown order |
| 404 | `{"error": "collection not found"}` | unknown id |
| 401 / 403 | — | missing JWT / not the owner |
@@ -1,79 +0,0 @@
---
method: POST
path: /api/collections/test-rules
auth: jwt
area: collections
---
<!-- source: internal/handlers/collections.go:996 CollectionHandler.TestRules -->
# Test Rule
Test which books would match given rules without saving.
**Endpoint**: `POST /api/collections/test-rules`
**Auth**: Required
**Content-Type**: `application/json`
## Request Body
| Field | Type | Required | Description |
| ----- | ----- | -------- | ----------------------------- |
| rules | array | Yes | Array of rule objects to test |
### Rule Object
| Field | Type | Required | Description |
| -------- | ------------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| field | string | Yes | Field to match on (genre, author, series, language, publisher, copyright_year, tags) |
| operator | string | Yes | Comparison operator (equals, not_equals, contains, not_contains, starts_with, ends_with, greater_than, less_than) |
| value | string/number | Yes | Value to compare against |
### Example Request
```json example-request
{
"rules": [
{
"field": "genre",
"operator": "equals",
"value": "Science Fiction"
},
{
"field": "author",
"operator": "contains",
"value": "Asimov"
}
]
}
```
## Response (200 OK)
```json example-response
{
"matches": [
{
"media_item_id": "660e8400-e29b-41d4-a716-446655440000",
"title": "Foundation",
"author": "Isaac Asimov",
"cover_image_path": "/covers/foundation.jpg",
"match_reason": "Matched rule: genre equals Science Fiction"
}
],
"total": 42
}
```
## Use Case
Test rules before creating a collection to verify correct book matching. This endpoint shows which books would be added without actually modifying any collections.
## Error Responses
| Code | Description |
| ---- | ----------------------------------- |
| 400 | Invalid request (validation failed) |
| 401 | Authentication required |
| 500 | Internal server error |
## Try It Out
@@ -24,7 +24,6 @@ set `view_settings.hide_finished` / `view_settings.show_up_next` directly.
"description": "Updated description",
"color": "#33CCFF",
"icon": "📚",
"auto_assign_rules": [],
"view_settings": { "hide_finished": true },
"hide_finished": ["true"],
"show_up_next": ["true"]
@@ -41,7 +40,6 @@ set `view_settings.hide_finished` / `view_settings.show_up_next` directly.
"description": "Updated description",
"color": "#33CCFF",
"icon": "📚",
"auto_assign_rules": null,
"view_settings": { "hide_finished": true, "show_up_next": true },
"created_at": "2026-10-24 13:57:01.81234 +0000 UTC"
}
@@ -57,8 +55,8 @@ set `view_settings.hide_finished` / `view_settings.show_up_next` directly.
| description | string | no | |
| color | string | no | |
| icon | string | no | |
| auto_assign_rules | array | no | replaces the whole rule set (rule object shape: see Create Collection) |
| view_settings | object | no | merged into stored settings |
| filter_tree | object | no | replaces the stored filter tree (omitting it keeps the stored one) |
| hide_finished | array | no | single-element string array `["true"]`/`["false"]`; merged into view_settings |
| show_up_next | array | no | same shape as `hide_finished` |
@@ -1,45 +0,0 @@
---
method: PUT
path: /api/collections/:id/rules/:ruleId
auth: jwt
area: collections
---
<!-- source: internal/handlers/collections.go:922 CollectionHandler.UpdateRule (SetRuleEnabled) -->
# Update Collection Rule
Despite the route name, this endpoint **toggles a rule's enabled state only**.
It does not update the rule's field/operator/value — rules are replaced wholesale
via [Create Collection](create_collection.md) (`auto_assign_rules`) or added via
the rules endpoint.
## Example request
```json example-request
{
"enabled": false
}
```
## Example response
```json example-response
{
"collection_id": "550e8400-e29b-41d4-a716-446655440000",
"is_smart": true
}
```
## Request fields
| Field | Type | Required | Notes |
| ----- | ---- | -------- | ----- |
| enabled | boolean | yes | toggles the rule on/off |
## Errors
| Status | Body | When |
| ------ | ---- | ---- |
| 400 | `{"error": "invalid collection id"}` / `{"error": "rule id required"}` / `{"error": "invalid request"}` | malformed |
| 404 | `{"error": "rule not found"}` | no such rule |
| 500 | `{"error": "..."}` | unexpected server error |
@@ -68,6 +68,15 @@ Creates a new custom collection with filter rules and/or manual book selection.
**Request Body:**
**Save contract (2026-10-31 tree migration):** the rules array travels
as a JSON-encoded string and the server converts it to a filter tree at
write time — `match_type` seeds the tree's root mode (`any` default),
`manual_book_ids` attach to the created collection, and
`show_on_dashboard` persists. `library_id` is selection context only
(sections scope to the dashboard's active library at render). Invalid
rules are a 400 at write naming the problem; the section renders stored
picks + the tree's live matches, deduped.
```json
{
"name": "My Custom Section",
@@ -0,0 +1,42 @@
---
method: POST
path: /api/devices/register/cancel
auth: none
area: devices
---
<!-- source: internal/handlers/devices.go DeviceHandler.CancelRegistration -->
# Cancel Device Registration
Let the REGISTERING device end its own pairing attempt — the plugin calls this
when the user dismisses its waiting dialog. The `registration_id` is the
bearer credential (same trust as the status poll): a device can only ever
cancel its own registration, and already-claimed registrations are left alone
so their token delivery to the device is never disrupted. Idempotent: the
response is the same whether or not the registration still exists.
**Endpoint**: `POST /api/devices/register/cancel`
**Auth**: Not required (registration UUID bearer, like the status poll)
**Content-Type**: `application/json`
## Request Body
| Field | Type | Required | Description |
| --------------- | ------ | -------- | ------------------------------ |
| registration_id | string | Yes | UUID from the register response |
### Example Request
```json example-request
{
"registration_id": "550e8400-e29b-41d4-a716-446655440000"
}
```
## Response (200 OK)
```json example-response
{
"message": "registration cancelled"
}
```
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff. Show more