Skip to content

feat: emailed invitations, claim + household setup, and server-driven onboarding tour - #501

Merged
Quick104 merged 10 commits into
mainfrom
t3code/email-invites-and-user-onboarding
Jul 28, 2026
Merged

Quick104 merged 10 commits into
mainfrom
t3code/email-invites-and-user-onboarding

Conversation

@Quick104

@Quick104 Quick104 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Getting someone onto a Silo server today means handing them an invite code out-of-band, then having them invent a username, retype their email and the code on /signup — and the admin still has to edit the user afterward to scope access. Once in, they land on an empty home screen with no idea Silo has watch together, requests, watchlist arrivals, or taste-based recommendations.

Part of #215 (the "magic invite links" scope item).

What this adds

Server + web implementation of the full journey — invite → claim → household → tour — per docs/superpowers/specs/2026-07-27-invitations-and-onboarding-design.md (spec, plan, and HTML mockups are in the first commit).

Invitations (feat(invitations), feat(web): invitation admin tab…)

  • invitations table — single-use claim token (SHA-256 at rest) bound to one email, carrying pre-bound role / access group / library IDs. No users row until accept; a partial unique index makes resend-supersedes atomic. Status is derived from timestamps.
  • internal/invitations — repo, service, branded email via the shared internal/mail sender. SMTP off → create still succeeds and returns the claim URL for manual delivery.
  • Endpoints — admin GET/POST /admin/invitations, POST .../{id}/resend, DELETE .../{id}; public GET /invitations/{token} + POST .../accept, rate-limited beside login/signup. Unknown/expired/revoked/used tokens are indistinguishable. Accept returns the signup-shaped login response.
  • Email-as-username login fallback — LocalProvider.Authenticate retries the email column when the username lookup misses and the input parses as a bare address. Both columns are citext UNIQUE over one identity space, so no ambiguity; plain-username logins take the exact pre-change path.
  • Web — Admin → Users → Invitations tab (compose with access group/libraries/note, list, resend, revoke, copy-link fallback when SMTP is off); /invite/:token claim page (one field: password); /household-setup "Who's watching?" screen reusing the existing ProfileEditorDialog — profiles, PINs, kids presets all through the existing /profiles endpoint, zero new backend.

Onboarding tour (feat(onboarding), feat(web): first-run feature tour)

  • GET /onboarding/flow?surface=web|phone|tv — ordered step manifest, filtered server-side: disabled features (requests / watch together / recommendations / notifications) produce no step, surface=tv drops text-entry steps, child profiles never see the requests stop. Copy lives in Go — a wording fix is a deploy, not three app-store releases. Clients skip unknown step kinds by contract.
  • setting_choice steps carry an explicit write target (profile_field / setting / device_setting) because playback quality is a profile column, not a settings key. The tour writes through the same APIs the settings screens use — no parallel persistence.
  • Per-profile completion state in the user store: SQLite schema v14 (profile_onboarding) plus a Postgres twin (user_profile_onboarding), keyed (profile_id, tour_id) with monotonic completed/skipped timestamps. Finishing on one device silences all others; a later progress write can never un-complete.
  • Web tour — TourHost modal over Home via an OnboardingGate; skip always one click; ends by handing off to the existing taste-seed picker (whose gate now waits for the tour). Replay entry in Settings → Personalize. show_tour=false invitations convert to a server-side skip on first profile.

Verified end-to-end in a real browser

Full stack (fresh pgvector/pg18 + cmd/silo + Vite): admin creates invitation → claim URL → password → /household-setup → Continue → tour overlays Home → picked 1080p in the quality step → walked to handoff → landed on /taste-seed. Then confirmed server-side: the profile's quality_preference is 1080p and /onboarding/state shows done:true with completed_at set. Second accept of the same token → 409; email login ([email protected]) works. Screenshots captured at every step (claim card, household tiles, tour welcome/quality steps, admin invitations list) — reproducible with the steps above; happy to attach to the PR thread.

Verification

$ go build ./...                                              # OK
$ go test ./internal/invitations/ ./internal/auth/ ./internal/ratelimit/ \
    ./internal/onboarding/ ./internal/userdb/ ./internal/userstore/...
ok  (all)
$ golangci-lint run ./internal/invitations/... ./internal/onboarding/...
0 issues.
$ cd web && pnpm run lint        # 0 errors (warnings pre-existing)
$ cd web && pnpm run format:check # clean
$ make verify-local-paths         # PASS

Both migrations verified up/down/up against a fresh container; userdb v13→v14 upgrade covered by migrate_v14_test.go.

Pre-existing failures unrelated to this PR: repo-wide make lint findings in untouched packages; TestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion fails identically on clean main (f235524).

Risks / follow-up

  • The login fallback touches every user's auth path — additive, tested, but review-worthy.
  • Accept's account-create and row-claim span two stores; a lost race surfaces as 409 with the account existing (documented in the service).
  • Client repos (silo-android, silo-apple) follow as separate PRs per the plan — deep-link claim, native household setup, and surface=phone|tv tour renderers against the contract this PR freezes.

AI Disclosure

  • Tool(s): Claude Code
  • Model(s): claude-fable-5
  • Involvement: fully AI-generated
  • Adversarial review: reviewed each phase's diff before commit. Found and fixed: (1) inviter identity originally trusted from the request — now re-read from the DB in the service; (2) tour state nearly landed in user_settings, which is account-scoped — one profile finishing would have silenced the whole household; moved to a per-profile table on both backends; (3) a redirect race on the claim page where the fresh session's auto profile-select bounced users past /household-setup — caught by the browser run, fixed with an accepted-flag and an explicit done-marker; (4) TourHost originally called a state-mutating finish during render for empty manifests — moved to an effect. Accepted tradeoff: household-setup done-flag is per-browser localStorage (cleared on each fresh accept), acceptable because the screen is a convenience entrance, not access control.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added emailed invitations with admin creation, resend, revoke, status tracking, and secure claim links.
    • Added invitation acceptance with password setup, automatic account login, and optional household setup.
    • Added onboarding tours tailored to web, mobile, TV, feature availability, and profile type.
    • Added progress tracking, completion persistence, and the ability to replay the feature tour.
    • Added administrative invitation management and manual claim-link copying when email is unavailable.
  • Documentation

    • Added design mockups, implementation plans, and specifications for invitations and onboarding.

Admins can invite a specific person by email: the invitation pre-binds
role, access group, and library access, and the invitee only chooses a
password. Their email address becomes their username, so login gains an
email fallback (username lookup first, email column only on miss for
inputs that parse as a bare address).

- invitations table: single-use token (SHA-256 at rest) bound to one
  address; a partial unique index makes resend-supersedes atomic; no
  users row exists until accept, so a typo'd address can't squat a
  username. Status is derived from timestamps, not stored.
- internal/invitations: repository, service, and branded email through
  the shared internal/mail sender. When SMTP is off the claim URL is
  returned for manual delivery instead of failing.
- Admin endpoints /admin/invitations (list/create/resend/revoke) beside
  the existing invite-codes routes; public claim endpoints
  /invitations/{token} (+/accept) rate-limited with the other auth
  endpoints. Unknown/expired/revoked/used tokens are indistinguishable.
- Accept returns the same login response shape as signup, so clients
  reuse their session plumbing.

Spec: docs/superpowers/specs/2026-07-27-invitations-and-onboarding-design.md
Plan: docs/superpowers/plans/2026-07-27-invitations-and-onboarding.md
Part of #215

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 02b1a502-9ed3-478c-98a2-e5c38d36cebc

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/email-invites-and-user-onboarding

Comment @coderabbitai help to get the list of available commands.

Quick104 and others added 3 commits July 27, 2026 22:27
- Admin → Users gains an Invitations tab: compose (email, role, access
  group, libraries, note, first-profile and tour toggles), list with
  derived status, resend, revoke. When the server has no SMTP the create
  response's claim URL is surfaced for copy-paste instead of a fake
  success.
- /invite/:token claim page: everything but the password was decided at
  send time, so it asks for exactly one thing and lands the user signed
  in. Expired/used links get an explanatory card, not a 404.
- /household-setup ("Who's watching?"): profile tiles plus the existing
  ProfileEditorDialog, all through the existing /profiles endpoint —
  no new backend. "Just me for now" is a first-class exit.

Part of #215

Co-Authored-By: Claude Fable 5 <[email protected]>
GET /onboarding/flow returns the ordered first-run tour for this server
and profile: steps for disabled features (requests, watch together,
recommendations, notifications) are filtered out server-side, surface=tv
drops steps needing text entry, and child profiles never see stops they
can't act on. Copy lives in Go, so a wording fix is a deploy — clients
render step kinds they know and skip unknown ones by contract.

setting_choice steps name an explicit write target (profile_field /
setting / device_setting) because playback quality is a profile column,
not a settings key — the tour writes through the same APIs the settings
screens use.

Per-profile completion state lives in the user store (SQLite schema v14
+ a Postgres twin table), keyed by (profile_id, tour_id) with monotonic
completed/skipped timestamps: finishing on one device silences every
other; a later progress write can never un-complete.

Part of #215

Co-Authored-By: Claude Fable 5 <[email protected]>
TourHost renders the server manifest as a modal overlay on Home: unknown
step kinds are skipped silently (the forward-compat contract), progress
posts per step, and setting_choice steps write real values through the
existing profile/settings mutations — by the last step the account is
genuinely configured. Skip is always one click and recorded server-side,
so no other device re-prompts. The tour ends by handing off to the
existing taste-seed picker, which now waits for the tour to finish
before its own redirect. Settings → Personalize gains a replay entry.

An invitation sent with show_tour=false plants a local hint that the
gate converts into a server-side skip for the first profile.

Part of #215

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104 Quick104 changed the title feat(invitations): add emailed pre-provisioned invitations feat: emailed invitations, claim + household setup, and server-driven onboarding tour Jul 27, 2026
Quick104 and others added 6 commits July 27, 2026 23:47
The Docker web build runs `tsc -b`, which applies the project's
noUncheckedIndexedAccess; the bounds check didn't narrow steps[next].
Look the step up once and branch on its presence instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
The tour overlay rendered inside the app layout, where an ancestor
creates a fixed-position containing block — inset-0 pinned to the
content pane, leaving the sidebar completely un-scrimmed. Portal the
dialog to <body> so the scrim truly covers the viewport, and raise the
backdrop blur from sm (4px) to xl (24px) so card titles and nav labels
aren't legible through it.

Co-Authored-By: Claude Fable 5 <[email protected]>
"Same movie, different couches" never said what the feature is called.
Every feature card now leads with the name the sidebar actually uses —
Watch Party, Requests, Watchlist, Calendar, Notifications — and says
where to find it, so the tour teaches vocabulary, not just concepts.
Server-side copy, so all three clients pick this up with no release.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two new web-only feature cards near the end of the tour:

- "Take Silo with you" — native apps for iPhone/iPad/Apple TV and
  Android/Android TV, with outbound TestFlight and Play Store links.
  Steps gain an additive links field (label + url) that older clients
  ignore; the web TourHost renders them as external-link buttons.
- "Already use a Jellyfin app? It works here" — Infuse/VidHub/Findroid/
  Swiftfin connect via the Jellyfin API. Gated on
  jellyfin_compat.enabled (default-on, so unset counts as enabled;
  only an explicit "false" hides it).

Both steps are web-only: the apps card is pointless inside the apps it
advertises, and TV can't open store links. surface=phone/tv manifests
skip them, covered by tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
Verified every step at 1600px, 390px, and 320px with an automated
overflow check. Fixes it found:

- Link buttons (apps step) now wrap and truncate instead of extending
  past the card edge.
- The footer wraps at very narrow widths, so the handoff step's wide
  primary button drops to its own line rather than overflowing.
- Progress pips hide on phones — decorative, and they crowded the
  Back/Next buttons.
- The card scrolls within 85dvh so a tall step never pins its buttons
  off-screen on landscape phones.

Co-Authored-By: Claude Fable 5 <[email protected]>
The apps step's plain outline buttons now render as store badges: the
Apple or Google Play mark with a store eyebrow (TestFlight beta /
Google Play) over the platform label — the familiar app-store badge
idiom. The brand is inferred from the link's host on the client, so
the server contract stays icon-free and non-store links keep the plain
external-link button. Labels drop the parenthesized store name the
eyebrow now carries.

Verified at 1600px and 390px with the overflow sweep: none.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 marked this pull request as ready for review July 28, 2026 02:00

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2dfe4eec1e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +5 to +8
const onboardingKeys = {
flow: () => ["onboarding", "flow"] as const,
state: () => ["onboarding", "state"] as const,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope onboarding cache keys to the active profile

Both queries use global keys even though their responses are profile-specific. After switching profiles, React Query can reuse the previous profile's done state and filtered flow for five minutes; for example, a completed parent profile suppresses the tour for a new child profile, while the reverse can show an adult flow to the child. Include the active profile ID in both keys so each household profile gets its own cached state and manifest.

AGENTS.md reference: AGENTS.md:L42-L44

Useful? React with 👍 / 👎.

Comment thread internal/auth/provider.go
Comment on lines 76 to +79
user, err := p.users.GetByUsername(ctx, creds.Username)
if err != nil && IsNotFound(err) && looksLikeEmail(creds.Username) {
user, err = p.users.GetByEmail(ctx, creds.Username)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve cross-column collisions before email login

The username and email columns have separate unique constraints, so an existing account may have username [email protected] while another account owns that email. In that allowed state, the username lookup succeeds and prevents the email fallback, causing the email owner's password to be checked against the wrong account and potentially logging into that account if the passwords coincide. Either enforce uniqueness across both identifier columns or explicitly detect and reject ambiguous matches before enabling email login.

Useful? React with 👍 / 👎.

Comment thread web/src/lib/onboarding.ts
* localStorage flags only bridge the moments before a profile exists.
*/

const TOUR_SUPPRESSED_KEY = "onboarding_tour_suppressed";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Scope the tour-suppression hint to the invited account

This fixed localStorage key is shared by every account using the browser. If a no-tour invite is accepted but the user closes the flow or signs out before reaching Home, the key remains; the next account to sign in with an unfinished profile will have its onboarding state permanently marked skipped. Store the intended account/profile identity with the hint, or persist the invitation's choice server-side during acceptance.

AGENTS.md reference: AGENTS.md:L42-L44

Useful? React with 👍 / 👎.

Comment on lines +39 to +43
onSuccess: (data) => {
if (data.email_sent) {
toast.success("Invitation resent — the old link no longer works");
}
queryClient.invalidateQueries({ queryKey: adminKeys.invitations() });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Surface the replacement link when resend cannot email

When SMTP is disabled, the resend endpoint succeeds with email_sent: false and the only copy of the new raw token in claim_url, but this success handler discards that URL. Because resend has already revoked the old token, clicking the button leaves the admin with no usable link to deliver and the recipient's previous link stops working. Preserve the response and show the same copy-link UI used after initial creation.

Useful? React with 👍 / 👎.

-- Pre-bound access, applied verbatim at accept time.
role text NOT NULL DEFAULT 'user'
CONSTRAINT invitations_role_check CHECK (role IN ('user', 'admin')),
access_group_id bigint REFERENCES public.access_groups(id) ON DELETE SET NULL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve invitation restrictions when deleting access groups

If a non-default access group is deleted while an invitation is pending, this action silently changes its access_group_id to NULL. Acceptance then treats NULL as no explicit group and assigns the current default group, which may grant substantially broader library and policy access than the admin pre-bound when sending the invitation. Block deletion while pending invitations reference the group, revoke those invitations, or otherwise preserve the intended restrictions instead of converting them to the default.

Useful? React with 👍 / 👎.

Comment on lines +207 to +214
switch {
case err == nil:
result.EmailSent = true
case errors.Is(err, mail.ErrNotConfigured):
// Degrade gracefully: the admin copies the link instead.
default:
return nil, fmt.Errorf("send invitation email: %w", err)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Roll back or expose invitations after SMTP delivery errors

For a configured SMTP server that times out or rejects delivery, the invitation has already been committed before this branch returns an error and hides the claim URL. The caller receives a failed request even though a live, inaccessible invitation now exists; on resend, the previously usable token has also already been revoked. Either undo the new invitation without losing the prior one or return the created invitation and claim URL as a manual-delivery fallback.

Useful? React with 👍 / 👎.

Comment on lines +41 to +43
result, err := h.service.Lookup(r.Context(), chi.URLParam(r, "token"))
if err != nil {
writeError(w, http.StatusNotFound, "not_found", "This invitation is invalid or has expired")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return server errors for failed invitation lookups

Every lookup error is converted to an invalid-token 404, including database connection, query, and scan failures from GetByTokenHash. During a database outage, valid invitees are therefore told their links expired, and operational failures are hidden from clients and monitoring. Return the indistinguishable 404 only for the not-found/not-claimable lifecycle errors and use a 500 for persistence failures.

Useful? React with 👍 / 👎.

Comment on lines +174 to +177
{step.title && <h2 className="text-xl font-bold tracking-tight sm:text-2xl">{step.title}</h2>}
{step.body && (
<p className="text-muted-foreground mt-2.5 text-sm leading-relaxed">{step.body}</p>
)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Render feature-card route actions

The current Watch Party and Requests feature cards include route and action_label, but StepBody renders only their title, body, settings, and external links. Those advertised in-app actions are therefore absent from the tour even though the server manifest and TypeScript contract provide them. Render a route button for feature cards so these current steps can perform their intended actions.

Useful? React with 👍 / 👎.

Comment on lines +171 to +174
linkBase := s.linkBase(ctx)
if linkBase == "" {
return nil, ErrNoLinkBase
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Allow manual links without a configured public URL

On the common self-hosted configuration where both notifications.email.external_url and the optional SILO_PUBLIC_URL are unset, this branch rejects creation before a token is minted. That makes the advertised SMTP-off manual-delivery path unavailable precisely when it is needed, even though the web client knows the current origin and could use a relative claim URL. Return a relative link or derive the request origin rather than requiring a separately configured public URL.

Useful? React with 👍 / 👎.

Comment thread internal/api/router.go
Comment on lines +739 to +742
Notifications: func(ctx context.Context) bool {
// The in-app inbox always exists; the step is about the
// wider system, so require a configured delivery channel.
return settingsRepo != nil && mail.NewSMTPSender(settingsRepo).Enabled(ctx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate the calendar card on every advertised capability

This gate checks only SMTP, although the card advertises both Calendar and Notifications and notification delivery can be provided by web or native push without SMTP. Consequently, a push-enabled server hides a usable notifications feature, while any SMTP-enabled movie-only server advertises a release calendar even when it has no scheduled content. Include configured push channels and actual calendar availability in the gate, or split the combined card into independently gated steps.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Nitpick comments (3)
internal/onboarding/steps.go (1)

110-120: 🩺 Stability & Availability | 🔵 Trivial

TestFlight link is a beta distribution mechanism, not a stable production URL.

The iOS/tvOS onboarding link points to a TestFlight public join link rather than an App Store URL. TestFlight public links can hit the 10,000-tester cap or expire, silently breaking this step for new users with no server-side signal. Since this copy is meant to be long-lived server content (per the file's own "a wording fix is a deploy, not three client releases" rationale), consider tracking a follow-up to swap this for the App Store link once available, or monitor tester-cap/expiry.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/onboarding/steps.go` around lines 110 - 120, Track a follow-up for
the iPhone & Apple TV link in the StepIDApps onboarding configuration: replace
the temporary TestFlight URL with the stable App Store URL once available, or
establish monitoring for TestFlight capacity and expiry until then. Keep the
existing link label and Android link unchanged.
web/src/pages/InviteClaim.tsx (1)

139-162: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: enforce the 8-character minimum client-side.

Server-side validation presumably rejects short passwords, but the UI never surfaces this until submit fails; adding minLength={8} mirrors the "at least 8 characters" hint shown here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/InviteClaim.tsx` around lines 139 - 162, Add minLength={8} to
both PasswordInput components in the InviteClaim password fields, preserving the
existing validation and the displayed minimum-length hint for password and
confirm-password inputs.
internal/auth/provider.go (1)

46-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated "is this a bare email address" validation. Both sites independently trim the input, call net/mail.ParseAddress, and check the parsed address equals the original string. As per coding guidelines, internal/**/*.go should "extract shared logic instead of duplicating it."

  • internal/auth/provider.go#L46-L55: keep looksLikeEmail as-is, but move it (or a shared equivalent) to a small common location both packages can import.
  • internal/invitations/service.go#L136-L140: replace the inline netmail.ParseAddress + exact-match check with a call to the shared helper instead of re-implementing it.

As per coding guidelines, "Place new backend code in the package that owns the behavior rather than in catch-all helpers; extract shared logic instead of duplicating it."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/auth/provider.go` around lines 46 - 55, The bare-email validation is
duplicated across authentication and invitations. Move or extract the logic from
looksLikeEmail in internal/auth/provider.go into a shared package both consumers
can import, preserving its trimming, parsing, and exact-match behavior; then
replace the inline validation in internal/invitations/service.go lines 136-140
with the shared helper call.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/handlers/onboarding.go`:
- Around line 59-64: Update the isChild resolution in the onboarding handler to
distinguish lookup failures from a valid non-child profile: handle and log
errors from storeProvider.ForUser and store.GetProfile using the handler’s
existing logging/error flow, and prevent the onboarding request from silently
continuing with isChild=false when either lookup fails. Preserve the current
profile.IsChild assignment for successful lookups.

In `@internal/onboarding/onboarding_test.go`:
- Around line 38-43: In the onboarding flow test, add an explicit non-empty
assertion immediately after calling stepIDs(flow) and before indexing ids[0] or
ids[len(ids)-1]. Keep the existing first- and last-step assertions unchanged so
an empty flow fails with a clear test error instead of panicking.
- Around line 70-74: Update the TV flow assertion in the test’s iteration over
flow.Steps to check step.needsInput instead of comparing step.Kind with
KindSettingChoice. Keep the existing failure message context and ensure every
step requiring input is rejected.

In `@migrations/sql/20260727212045_invitations.sql`:
- Around line 22-24: Update the invited_by foreign-key constraint in the
invitations migration to use restrictive delete behavior instead of ON DELETE
CASCADE, preserving invitation records and preventing user deletion while
related invitations exist. Keep invited_by required and leave the
access_group_id and accepted_user_id constraints unchanged.

In `@migrations/sql/20260727220010_profile_onboarding.sql`:
- Around line 8-19: Update the user_profile_onboarding table definition to add a
composite foreign key from (user_id, profile_id) to
public.user_profiles(user_id, id) with ON DELETE CASCADE, while preserving the
existing user_id foreign key and primary key.

In `@web/src/components/onboarding/OnboardingGate.tsx`:
- Around line 33-40: Update the suppression effect in OnboardingGate so
clearTourSuppressed and setDismissed run only after the progress skip mutation
succeeds. Use the mutation’s success-aware API or callback around
progress.mutate, while preserving the existing tour_id and skipped payload and
leaving the early-return conditions unchanged.

In `@web/src/components/onboarding/TourHost.tsx`:
- Around line 65-89: Update finish and advance in TourHost so local UI
completion, dismissal, navigation, and step advancement occur only after the
corresponding progress.mutate request succeeds; handle mutation failures without
marking the tour complete locally. Preserve the existing payloads and behavior
on successful mutations, including the final-step completion and handoff route.
- Line 1: The onboarding progress mutations in TourHost’s finish/advance
handlers and OnboardingGate’s skip flow update local state before persistence
succeeds; switch these flows to await the mutation (using the existing async
mutation API) and handle failures without advancing, navigating, or clearing
suppression. Ensure finish only calls onDone/navigation after success, advance
does not permanently advance failed last-step tracking, and skip only calls
clearTourSuppressed/setDismissed after a successful write.
- Around line 264-291: Update SettingControl.save so the optimistic
setValue(next) is rolled back when updateProfile.mutate or setSetting.mutate
fails. Capture the previous value before updating, add each mutation’s onError
callback to restore it, and preserve the existing success behavior for profile
updates and setting mutations.

In `@web/src/hooks/queries/admin/invitations.ts`:
- Around line 34-49: The resend flow drops the replacement claim link when SMTP
is disabled. In web/src/hooks/queries/admin/invitations.ts lines 34-49, keep the
built-in success toast but allow the mutation call-site callback to handle the
non-email case; in web/src/pages/admin-settings/InvitationsTab.tsx lines
124-133, update the resend.mutate call to inspect data.claim_url when
data.email_sent is false and surface a copyable/manual link using the existing
CreateInvitationForm pattern.

---

Nitpick comments:
In `@internal/auth/provider.go`:
- Around line 46-55: The bare-email validation is duplicated across
authentication and invitations. Move or extract the logic from looksLikeEmail in
internal/auth/provider.go into a shared package both consumers can import,
preserving its trimming, parsing, and exact-match behavior; then replace the
inline validation in internal/invitations/service.go lines 136-140 with the
shared helper call.

In `@internal/onboarding/steps.go`:
- Around line 110-120: Track a follow-up for the iPhone & Apple TV link in the
StepIDApps onboarding configuration: replace the temporary TestFlight URL with
the stable App Store URL once available, or establish monitoring for TestFlight
capacity and expiry until then. Keep the existing link label and Android link
unchanged.

In `@web/src/pages/InviteClaim.tsx`:
- Around line 139-162: Add minLength={8} to both PasswordInput components in the
InviteClaim password fields, preserving the existing validation and the
displayed minimum-length hint for password and confirm-password inputs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 20b7f6a6-9287-4b15-8656-882698a09fda

📥 Commits

Reviewing files that changed from the base of the PR and between 1a784a1 and 2dfe4ee.

📒 Files selected for processing (42)
  • docs/design/invite-onboarding.html
  • docs/superpowers/plans/2026-07-27-invitations-and-onboarding.md
  • docs/superpowers/specs/2026-07-27-invitations-and-onboarding-design.md
  • internal/api/handlers/admin_invitations.go
  • internal/api/handlers/invitations.go
  • internal/api/handlers/onboarding.go
  • internal/api/router.go
  • internal/auth/provider.go
  • internal/auth/provider_test.go
  • internal/invitations/email.go
  • internal/invitations/email_test.go
  • internal/invitations/repository.go
  • internal/invitations/service.go
  • internal/invitations/service_test.go
  • internal/models/invitation.go
  • internal/onboarding/onboarding.go
  • internal/onboarding/onboarding_test.go
  • internal/onboarding/steps.go
  • internal/ratelimit/ratelimit.go
  • internal/userdb/migrate.go
  • internal/userdb/migrate_v14_test.go
  • internal/userdb/onboarding.go
  • internal/userdb/schema.go
  • internal/userdb/sqlitestore.go
  • internal/userstore/pgstore/onboarding.go
  • internal/userstore/store.go
  • internal/userstore/types.go
  • migrations/sql/20260727212045_invitations.sql
  • migrations/sql/20260727220010_profile_onboarding.sql
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/onboarding/OnboardingGate.tsx
  • web/src/components/onboarding/TourHost.tsx
  • web/src/hooks/queries/admin/invitations.ts
  • web/src/hooks/queries/keys.ts
  • web/src/hooks/queries/onboarding.ts
  • web/src/lib/onboarding.ts
  • web/src/pages/AdminUsers.tsx
  • web/src/pages/HouseholdSetup.tsx
  • web/src/pages/InviteClaim.tsx
  • web/src/pages/admin-settings/InvitationsTab.tsx
  • web/src/pages/settings/PersonalizeSettings.tsx

Comment on lines +59 to +64
isChild := false
if store, err := h.storeProvider.ForUser(r.Context(), userID); err == nil {
if profile, err := store.GetProfile(r.Context(), profileID); err == nil && profile != nil {
isChild = profile.IsChild
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Errors when resolving isChild are silently swallowed, defaulting to "not a child."

If ForUser or GetProfile errors (e.g., transient store failure), isChild stays false and the child profile gets the unfiltered flow (including the requests step) with no logged signal that the lookup failed.

🩹 Proposed fix
 	isChild := false
-	if store, err := h.storeProvider.ForUser(r.Context(), userID); err == nil {
-		if profile, err := store.GetProfile(r.Context(), profileID); err == nil && profile != nil {
-			isChild = profile.IsChild
-		}
-	}
+	if store, err := h.storeProvider.ForUser(r.Context(), userID); err == nil {
+		if profile, err := store.GetProfile(r.Context(), profileID); err == nil && profile != nil {
+			isChild = profile.IsChild
+		} else if err != nil {
+			slog.Warn("onboarding: failed to resolve profile for child check", "error", err)
+		}
+	} else {
+		slog.Warn("onboarding: failed to resolve user store for child check", "error", err)
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
isChild := false
if store, err := h.storeProvider.ForUser(r.Context(), userID); err == nil {
if profile, err := store.GetProfile(r.Context(), profileID); err == nil && profile != nil {
isChild = profile.IsChild
}
}
isChild := false
if store, err := h.storeProvider.ForUser(r.Context(), userID); err == nil {
if profile, err := store.GetProfile(r.Context(), profileID); err == nil && profile != nil {
isChild = profile.IsChild
} else if err != nil {
slog.Warn("onboarding: failed to resolve profile for child check", "error", err)
}
} else {
slog.Warn("onboarding: failed to resolve user store for child check", "error", err)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/handlers/onboarding.go` around lines 59 - 64, Update the isChild
resolution in the onboarding handler to distinguish lookup failures from a valid
non-child profile: handle and log errors from storeProvider.ForUser and
store.GetProfile using the handler’s existing logging/error flow, and prevent
the onboarding request from silently continuing with isChild=false when either
lookup fails. Preserve the current profile.IsChild assignment for successful
lookups.

Comment on lines +38 to +43
ids := stepIDs(flow)
if ids[0] != StepIDWelcome {
t.Errorf("first step = %q, want welcome", ids[0])
}
if ids[len(ids)-1] != StepIDHandoffTaste {
t.Errorf("last step = %q, want handoff-taste", ids[len(ids)-1])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fail clearly when the flow is empty.

A regression yielding no steps panics on ids[0]; assert len(ids) > 0 first so the test reports the broken flow contract.

Proposed fix
  ids := stepIDs(flow)
+ if len(ids) == 0 {
+   t.Fatal("flow has no steps")
+ }
  if ids[0] != StepIDWelcome {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ids := stepIDs(flow)
if ids[0] != StepIDWelcome {
t.Errorf("first step = %q, want welcome", ids[0])
}
if ids[len(ids)-1] != StepIDHandoffTaste {
t.Errorf("last step = %q, want handoff-taste", ids[len(ids)-1])
ids := stepIDs(flow)
if len(ids) == 0 {
t.Fatal("flow has no steps")
}
if ids[0] != StepIDWelcome {
t.Errorf("first step = %q, want welcome", ids[0])
}
if ids[len(ids)-1] != StepIDHandoffTaste {
t.Errorf("last step = %q, want handoff-taste", ids[len(ids)-1])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/onboarding/onboarding_test.go` around lines 38 - 43, In the
onboarding flow test, add an explicit non-empty assertion immediately after
calling stepIDs(flow) and before indexing ids[0] or ids[len(ids)-1]. Keep the
existing first- and last-step assertions unchanged so an empty flow fails with a
clear test error instead of panicking.

Comment on lines +70 to +74
for _, step := range flow.Steps {
if step.Kind == KindSettingChoice {
t.Errorf("TV surface got setting_choice step %q", step.ID)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the actual TV filtering contract.

FlowFor filters on step.needsInput, not KindSettingChoice; assert step.needsInput so this test catches every unsupported TV input step.

Proposed fix
  for _, step := range flow.Steps {
-   if step.Kind == KindSettingChoice {
-     t.Errorf("TV surface got setting_choice step %q", step.ID)
+   if step.needsInput {
+     t.Errorf("TV surface got input-requiring step %q", step.ID)
    }
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for _, step := range flow.Steps {
if step.Kind == KindSettingChoice {
t.Errorf("TV surface got setting_choice step %q", step.ID)
}
}
for _, step := range flow.Steps {
if step.needsInput {
t.Errorf("TV surface got input-requiring step %q", step.ID)
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/onboarding/onboarding_test.go` around lines 70 - 74, Update the TV
flow assertion in the test’s iteration over flow.Steps to check step.needsInput
instead of comparing step.Kind with KindSettingChoice. Keep the existing failure
message context and ensure every step requiring input is rejected.

Comment on lines +22 to +24
-- Lifecycle. Status (pending/accepted/expired/revoked) is derived from
-- these timestamps at read time; there is no status column to drift.
invited_by bigint NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

invited_by cascade-deletes invitations, undermining the audit trail.

invited_by is NOT NULL REFERENCES ... ON DELETE CASCADE, unlike access_group_id/accepted_user_id in this same table which use SET NULL. If the inviting admin's user row is ever deleted, every invitation they sent is deleted too — including already-accepted ones, which erases the very audit trail the feature is designed to preserve (per the design mockup: "Accepted rows link straight to the created user, so the invite list doubles as an audit trail"). It also silently revokes any of that admin's still-outstanding pending invites.

🛡️ Proposed fix: restrict instead of cascade
     invited_by        bigint NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
+    -- Preserve the invitation as an audit trail even if the inviting admin
+    -- is later deleted; use SET NULL (with a nullable column) if losing the
+    -- inviter reference but keeping the row is preferred instead.
-    invited_by        bigint NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
+    invited_by        bigint NOT NULL REFERENCES public.users(id) ON DELETE RESTRICT,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-- Lifecycle. Status (pending/accepted/expired/revoked) is derived from
-- these timestamps at read time; there is no status column to drift.
invited_by bigint NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
-- Lifecycle. Status (pending/accepted/expired/revoked) is derived from
-- these timestamps at read time; there is no status column to drift.
-- Preserve the invitation as an audit trail even if the inviting admin
-- is later deleted; use SET NULL (with a nullable column) if losing the
-- inviter reference but keeping the row is preferred instead.
invited_by bigint NOT NULL REFERENCES public.users(id) ON DELETE RESTRICT,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@migrations/sql/20260727212045_invitations.sql` around lines 22 - 24, Update
the invited_by foreign-key constraint in the invitations migration to use
restrictive delete behavior instead of ON DELETE CASCADE, preserving invitation
records and preventing user deletion while related invitations exist. Keep
invited_by required and leave the access_group_id and accepted_user_id
constraints unchanged.

Comment on lines +8 to +19
CREATE TABLE IF NOT EXISTS user_profile_onboarding (
user_id INTEGER NOT NULL,
profile_id TEXT NOT NULL,
tour_id TEXT NOT NULL,
last_step TEXT NOT NULL DEFAULT '',
completed_at TEXT,
skipped_at TEXT,
updated_at TEXT NOT NULL,
PRIMARY KEY (user_id, profile_id, tour_id),
CONSTRAINT user_profile_onboarding_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for a Postgres profiles table definition and how other profile-scoped
# tables reference profile_id (FK pattern) to confirm intended behavior.
rg -n "profile_id" migrations/sql -g '*.sql' -A2 -B2 | rg -n "REFERENCES|CREATE TABLE"

Repository: Silo-Server/silo-server

Length of output: 10768


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- user_profiles references ---'
rg -n "CREATE TABLE .*user_profiles|REFERENCES .*user_profiles|FOREIGN KEY .*profile_id|profile_id\)" migrations/sql -g '*.sql' -A3 -B3

echo
echo '--- onboarding migration ---'
sed -n '1,80p' migrations/sql/20260727220010_profile_onboarding.sql

Repository: Silo-Server/silo-server

Length of output: 24753


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- user_profiles table definition ---'
sed -n '900,980p' migrations/sql/001_schema.sql

echo
echo '--- profile delete references in SQL migrations ---'
rg -n "DELETE FROM .*user_profiles|DROP TABLE .*user_profiles|ON DELETE CASCADE|user_profiles" migrations/sql -g '*.sql' -A2 -B2 | sed -n '1,220p'

echo
echo '--- profile delete references in Go ---'
rg -n "Delete.*profile|delete.*profile|user_profiles|profile_id" internal -g '*.go' -A2 -B2 | sed -n '1,260p'

Repository: Silo-Server/silo-server

Length of output: 41174


Add a composite profile FK — profile_id should also reference public.user_profiles(user_id, id) ON DELETE CASCADE; otherwise deleting a profile can leave orphaned onboarding rows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@migrations/sql/20260727220010_profile_onboarding.sql` around lines 8 - 19,
Update the user_profile_onboarding table definition to add a composite foreign
key from (user_id, profile_id) to public.user_profiles(user_id, id) with ON
DELETE CASCADE, while preserving the existing user_id foreign key and primary
key.

Comment on lines +33 to +40
useEffect(() => {
if (!suppressed || !state.data) return;
progress.mutate({ tour_id: state.data.tour_id, skipped: true });
clearTourSuppressed();
setDismissed(true);
// progress is a stable mutation handle; state.data is covered by `suppressed`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [suppressed]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Suppress→skip conversion doesn't check mutation outcome.

progress.mutate here is fire-and-forget; clearTourSuppressed()/setDismissed(true) run immediately regardless of whether the skip was actually persisted. See consolidated comment (shared with TourHost.tsx) for the broader pattern across onboarding-progress call sites.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/onboarding/OnboardingGate.tsx` around lines 33 - 40,
Update the suppression effect in OnboardingGate so clearTourSuppressed and
setDismissed run only after the progress skip mutation succeeds. Use the
mutation’s success-aware API or callback around progress.mutate, while
preserving the existing tour_id and skipped payload and leaving the early-return
conditions unchanged.

@@ -0,0 +1,343 @@
import { useCallback, useEffect, useMemo, useState } from "react";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Onboarding-progress mutations are fire-and-forget across both files — local "tour finished/skipped" state advances before the server write is confirmed. Both sites call useOnboardingProgress().mutate(...) and then immediately update local UI/gating state without an onError/await, so a failed request leaves the client believing the tour is done/skipped while the server still has done: false.

  • web/src/components/onboarding/TourHost.tsx#L65-89: in finish(), don't call onDone()/navigate() until the mutation resolves (e.g., via mutateAsync + try/catch, or an onSettled/onError that reverts dismissed and retries/surfaces the failure); advance() has the same gap for last_step tracking, though it self-heals on the next successful write.
  • web/src/components/onboarding/OnboardingGate.tsx#L33-40: don't call clearTourSuppressed()/setDismissed(true) until the skip mutation succeeds, so a failed write leaves the local suppress flag intact for a later retry instead of silently dropping the skip intent.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/onboarding/TourHost.tsx` at line 1, The onboarding
progress mutations in TourHost’s finish/advance handlers and OnboardingGate’s
skip flow update local state before persistence succeeds; switch these flows to
await the mutation (using the existing async mutation API) and handle failures
without advancing, navigating, or clearing suppression. Ensure finish only calls
onDone/navigation after success, advance does not permanently advance failed
last-step tracking, and skip only calls clearTourSuppressed/setDismissed after a
successful write.

Comment on lines +65 to +89
const finish = useCallback(
(opts: { skipped: boolean; route?: string }) => {
progress.mutate({
tour_id: flow.tour_id,
last_step: step?.id ?? "",
completed: !opts.skipped,
skipped: opts.skipped,
});
onDone();
if (opts.route) {
navigate(opts.route);
}
},
[progress, flow.tour_id, step, onDone, navigate],
);

const advance = useCallback(() => {
const nextStep = steps[index + 1];
if (!nextStep) {
finish({ skipped: false });
return;
}
progress.mutate({ tour_id: flow.tour_id, last_step: nextStep.id });
setIndex(index + 1);
}, [index, steps, finish, progress, flow.tour_id]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

finish()/advance() don't wait for or check the progress mutation before updating local UI state.

finish() calls onDone() (and navigate() for handoff steps) immediately after firing progress.mutate, without confirming the write succeeded. On a failed request the tour is dismissed locally as if completed/skipped, but the server still reports done: false, so the tour can reappear in a later session despite the user believing they finished it. See consolidated comment for the related site in OnboardingGate.tsx.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/onboarding/TourHost.tsx` around lines 65 - 89, Update
finish and advance in TourHost so local UI completion, dismissal, navigation,
and step advancement occur only after the corresponding progress.mutate request
succeeds; handle mutation failures without marking the tour complete locally.
Preserve the existing payloads and behavior on successful mutations, including
the final-step completion and handoff route.

Comment on lines +264 to +291
function SettingControl({ step }: { step: OnboardingStep }) {
const spec = step.setting!;
const { profile, selectProfile } = useAuth();
const updateProfile = useUpdateProfile();
const setSetting = useSetSetting();

const currentValue =
spec.target === "profile_field" && profile
? ((profile as unknown as Record<string, unknown>)[spec.key] as string | undefined)
: undefined;
const [value, setValue] = useState<string>(currentValue || spec.default || "");

function save(next: string) {
setValue(next);
if (spec.target === "profile_field") {
if (!profile) return;
updateProfile.mutate(
{ id: profile.id, body: { [spec.key]: next } },
{
onSuccess: (updated) => selectProfile(updated, getProfileToken() ?? undefined),
},
);
return;
}
// "setting" and "device_setting" share the user-settings mutation shape;
// device scope only differs in endpoint, handled by the settings hook.
setSetting.mutate({ key: spec.key, value: next });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

SettingControl.save() optimistically updates local value with no rollback on mutation failure.

setValue(next) runs before updateProfile.mutate/setSetting.mutate resolve, and neither call has an onError. If the write fails, the control still shows the newly "selected" option even though it wasn't persisted — contradicting the intent that "by the end of the tour the account is genuinely configured."

🩹 Proposed fix sketch
   function save(next: string) {
-    setValue(next);
     if (spec.target === "profile_field") {
       if (!profile) return;
       updateProfile.mutate(
         { id: profile.id, body: { [spec.key]: next } },
         {
-          onSuccess: (updated) => selectProfile(updated, getProfileToken() ?? undefined),
+          onSuccess: (updated) => {
+            selectProfile(updated, getProfileToken() ?? undefined);
+            setValue(next);
+          },
         },
       );
       return;
     }
-    setSetting.mutate({ key: spec.key, value: next });
+    setSetting.mutate(
+      { key: spec.key, value: next },
+      { onSuccess: () => setValue(next) },
+    );
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function SettingControl({ step }: { step: OnboardingStep }) {
const spec = step.setting!;
const { profile, selectProfile } = useAuth();
const updateProfile = useUpdateProfile();
const setSetting = useSetSetting();
const currentValue =
spec.target === "profile_field" && profile
? ((profile as unknown as Record<string, unknown>)[spec.key] as string | undefined)
: undefined;
const [value, setValue] = useState<string>(currentValue || spec.default || "");
function save(next: string) {
setValue(next);
if (spec.target === "profile_field") {
if (!profile) return;
updateProfile.mutate(
{ id: profile.id, body: { [spec.key]: next } },
{
onSuccess: (updated) => selectProfile(updated, getProfileToken() ?? undefined),
},
);
return;
}
// "setting" and "device_setting" share the user-settings mutation shape;
// device scope only differs in endpoint, handled by the settings hook.
setSetting.mutate({ key: spec.key, value: next });
}
function SettingControl({ step }: { step: OnboardingStep }) {
const spec = step.setting!;
const { profile, selectProfile } = useAuth();
const updateProfile = useUpdateProfile();
const setSetting = useSetSetting();
const currentValue =
spec.target === "profile_field" && profile
? ((profile as unknown as Record<string, unknown>)[spec.key] as string | undefined)
: undefined;
const [value, setValue] = useState<string>(currentValue || spec.default || "");
function save(next: string) {
if (spec.target === "profile_field") {
if (!profile) return;
updateProfile.mutate(
{ id: profile.id, body: { [spec.key]: next } },
{
onSuccess: (updated) => {
selectProfile(updated, getProfileToken() ?? undefined);
setValue(next);
},
},
);
return;
}
// "setting" and "device_setting" share the user-settings mutation shape;
// device scope only differs in endpoint, handled by the settings hook.
setSetting.mutate(
{ key: spec.key, value: next },
{ onSuccess: () => setValue(next) },
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/onboarding/TourHost.tsx` around lines 264 - 291, Update
SettingControl.save so the optimistic setValue(next) is rolled back when
updateProfile.mutate or setSetting.mutate fails. Capture the previous value
before updating, add each mutation’s onError callback to restore it, and
preserve the existing success behavior for profile updates and setting
mutations.

Comment on lines +34 to +49
export function useResendInvitation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) =>
api<SendInvitationResponse>(`/admin/invitations/${id}/resend`, { method: "POST" }),
onSuccess: (data) => {
if (data.email_sent) {
toast.success("Invitation resent — the old link no longer works");
}
queryClient.invalidateQueries({ queryKey: adminKeys.invitations() });
},
onError: (err) => {
toast.error(err instanceof Error ? err.message : "Failed to resend invitation");
},
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Resend's SMTP-disabled fallback silently drops the claim link. useResendInvitation's onSuccess only acts when email_sent is true, and its call site never passes a handler for the false case — so resending on a server without SMTP configured invalidates the old link and gives the admin no way to retrieve the new one, unlike the create flow which shows a copyable link.

  • web/src/hooks/queries/admin/invitations.ts#L34-L49: keep the built-in toast for the success case, but stop relying on it as the only feedback path.
  • web/src/pages/admin-settings/InvitationsTab.tsx#L124-L133: pass an onSuccess callback at the resend.mutate(inv.id, { onSuccess }) call site that checks data.claim_url when !data.email_sent and surfaces it (e.g., a toast with a copy action, or reusing the same manual-link UI pattern as CreateInvitationForm).
📍 Affects 2 files
  • web/src/hooks/queries/admin/invitations.ts#L34-L49 (this comment)
  • web/src/pages/admin-settings/InvitationsTab.tsx#L124-L133
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/hooks/queries/admin/invitations.ts` around lines 34 - 49, The resend
flow drops the replacement claim link when SMTP is disabled. In
web/src/hooks/queries/admin/invitations.ts lines 34-49, keep the built-in
success toast but allow the mutation call-site callback to handle the non-email
case; in web/src/pages/admin-settings/InvitationsTab.tsx lines 124-133, update
the resend.mutate call to inspect data.claim_url when data.email_sent is false
and surface a copyable/manual link using the existing CreateInvitationForm
pattern.

@Quick104
Quick104 merged commit 271a2e1 into main Jul 28, 2026
23 checks passed
@Quick104
Quick104 deleted the t3code/email-invites-and-user-onboarding branch July 28, 2026 02:58
RXWatcher added a commit to RXWatcher/silo-server that referenced this pull request Jul 29, 2026
Upstream Silo-Server#501 added GetOnboardingState/UpsertOnboardingState to
userstore.UserStore without extending this stub, so the access package
no longer compiles under test on main.

Co-Authored-By: Claude Fable 5 <[email protected]>
RXWatcher added a commit to RXWatcher/silo-server that referenced this pull request Jul 29, 2026
Same upstream gap as the access resolver stub: Silo-Server#501 extended
userstore.UserStore without updating these test doubles.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Aug 20, 2026
Upstream Silo-Server#501 added GetOnboardingState/UpsertOnboardingState to
userstore.UserStore without extending this stub, so the access package
no longer compiles under test on main.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 pushed a commit to RXWatcher/silo-server that referenced this pull request Aug 20, 2026
Same upstream gap as the access resolver stub: Silo-Server#501 extended
userstore.UserStore without updating these test doubles.

Co-Authored-By: Claude Fable 5 <[email protected]>
JonahMMay added a commit to Prairie-Server/prairie-server that referenced this pull request Aug 28, 2026
* fix(watchsync): redact undeclared connection secrets

Connection config fields absent from a schema's declared sets are classified
as secrets fail-closed, but the fault-redaction list collected only declared
secret fields. A plugin echoing such a value in a fault returned it in the
clear. Redact every flattened secret value instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(watchsync): record per-connection provider setup

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(deps): drop stale plugin SDK checksums

go mod tidy removes the v0.13.1 hash pair left behind by the v0.13.2 bump.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(audiobooks): gate enrichment on identity, not cover art

The audiobook enrichment sweep had been permanently idle. Eligibility
required an empty poster_path, but the scanner extracts embedded cover
art from audiobook files, so every item had a poster before enrichment
ever looked at it. Cover presence says nothing about whether an item was
identified, and using it as the "already enriched" proxy meant the
predicate matched nothing.

On production this selected 0 rows while 5,712 audiobooks held no
provider ID at all -- 5,710 of them carrying a scanner-supplied poster.
The metadata providers had enriched 42 items in total; the 235,780 ASINs
in the library came from file scan, not from a provider. The 5-minute
trigger kept firing and finding nothing, so the gap could never drain.

Key both claimBatch and HasPendingItems on the absence of any row in
media_item_provider_ids instead. Sized against production this makes
5,682 items eligible rather than the 240,857 that dropping the poster
clause alone would have queued against Audible.

last_refreshed IS NULL is retained as the retry bound, and it is load
bearing: enrichItem stamps it on a clean no-match but deliberately
withholds it on provider error, so unmatchable items are attempted once
while transient failures still come back.

Adds DB-backed tests for both predicates, including the exact row the
regression hid (cover art present, no identity). Both fail against the
old predicate and pass against the new one. Neither query had any test
coverage before, which is how this survived.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): require a credible title match before accepting a provider result

Enrichment took results[0] from every search provider unconditionally.
Search backends rank by their own relevance and answer nearly every
query with something, so a provider's best guess became the item's
permanent identity -- and enrichment stamps last_refreshed on success
and never revisits, so a wrong acceptance is a permanent mislabel:
another book's cover, overview and narrator.

Measured rather than assumed. Twenty unidentified production audiobooks
were queried against the iTunes audiobook search: 19 returned a result
and roughly a quarter of those top hits were wrong -- either a different
volume of the right series ("The OP MC 8: God of Winning" answered by
"God of Winning: The OP MC, Book 1") or an unrelated title sharing one
common word ("Star Force Origins" answered by "The Achilles Trap").

Adds metadata.BestMatch, which scores candidates against the title we
hold on disk and returns nothing when none is credible -- callers treat
that as a no-match instead of falling back to the top row. Scoring is
word-set overlap (Dice) because the differences that matter are whole
words added or dropped: an author prefix, a series parenthetical, an
"(Unabridged)" suffix. A volume disagreement is fatal regardless of
overlap, since same-series wrong-volume pairs share nearly every word.

Wired into all three call sites that had the flaw: audiobooks, ebooks
and manga. Ebooks scores against item.Title rather than the outgoing
query, which is deliberately cleaned before it is sent.

Calibrated on the real probe pairs, kept as the test fixtures: correct
matches score >= 0.88, wrong ones <= 0.44, threshold 0.50. A test
asserts the two populations stay separated so a future tweak that
narrows the gap fails here rather than in production.

Three ebook fixtures needed a title on their SearchResult. They were
passing a result with no name at all, which the gate rejects; one of
them (SkipsProviderIDOwnedByAnotherItem) would otherwise have kept
passing for the wrong reason, never reaching the ownership check it
exists to cover.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): drop stopwords when scoring title similarity

Validating the gate against the full 20-title production probe caught a
false accept it should have blocked. "All the Lies 1-3 - All the Lies:
The Complete Trilogy" was matched to "The Sentinel: The Complete Jane
Harper Trilogy: The Jane Harper Trilogy, Books 1-3" at 0.56, over the
0.50 threshold.

Both are "Books 1-3" boxed sets of unrelated series, and the score came
almost entirely from words that carry no identity: "the" three times,
plus "complete", "trilogy" and the 1 and 3 of the volume range. Neither
title's actual subject contributed. Excluding a small stopword set takes
the pair to 0.42, where it belongs, and leaves every correct match in
the sample above threshold.

The exclusion is skipped when it would leave fewer than two words to
compare, so titles that are mostly stopwords ("A Man in Full") still
have something to match on rather than scoring 0 against everything.

Rescored against all 20 probe pairs: 12 accepted, 7 rejected, 1 had no
answer. Every rejection is a genuine mismatch -- two wrong-volume pairs
of the right series, two unrelated titles, this boxed set, a bare common
noun, and a same-series different-book pair. Blind results[0] acceptance
would have taken 19 of these, roughly 6 of them wrong.

Fixtures now carry the untruncated provider strings, since the truncated
ones scored differently from what production actually returns -- which
is why the first version of this test passed while the real pair failed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(ebooks): search the bare title and disambiguate volumes after the search

cleanEbookSearchTitle unwrapped a trailing series marker -- brackets
removed, words kept -- so "Icarus (Realm Book 3)" went out as "Icarus
Realm Book 3". The reasoning was that the volume number is what tells
sibling volumes apart, and dropping it would make every entry in a
series search as the bare series name and collapse onto one work.

That held only while enrichment accepted results[0] blindly. It is no
longer true: metadata.BestMatch scores candidates against the raw
item.Title, which still carries "(Realm Book 3)", and treats a volume
disagreement as fatal. The disambiguator never needed to be in the
query -- it needed to be in the check, and now it is.

Meanwhile the unwrapped form was not disambiguating the search, it was
breaking it. "Realm Book 3" is retail furniture that no provider
catalogue indexes, so the query matched nothing at all.

Measured on 40 parked no_match ebooks that carry a series parenthetical,
with both query forms produced by this function and both result sets
scored by the real gate:

  what the server sends today : Open Library answered  3, accepted  0
  after this change           : Open Library answered 29, accepted 14

14 recovered, 0 lost. The gap between 29 answered and 14 accepted is the
scoring gate rejecting results that came back but are not the book --
15 wrong identities that blind results[0] would have stamped
permanently.

Scope, so the number is not read as more than it is: 23,802 of the
110,556 parked no_match ebooks (21.5%) carry a trailing series
parenthetical, so this reaches about a fifth of the backlog. The other
78.5% fail for reasons this does not touch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): make title normalisation Unicode-aware

Found reviewing this branch's own diff. normaliseTitle stripped via
[^a-z0-9] after lowercasing, which is ASCII-only. Every non-Latin title
reduced to the empty string, so TitleScore returned 0 and BestMatch
rejected it -- including against an identical title. "進撃の巨人" scored
0.00 against itself. Accented Latin fared little better:
"Blåbærsyltetøy" became "bl b rsyltet y".

That would have been a hard regression for non-English content, and a
quiet one: those items previously matched by accident, because
results[0] was accepted without any check at all. Manga is the obvious
exposure, but the library carries Danish and Norwegian ebooks too.

Strips [^\p{L}\p{N}]+ instead, so letters and digits in any script
survive. Tests cover Japanese, Russian and Danish titles matching
themselves and rejecting different titles in the same script.

For scripts that do not space their words, a whole title normalises to
one token, so Dice gives 1 on an exact match and 0 otherwise, with
containment carrying near-misses. Coarse, but correct, and strictly
better than what it replaces. minContainmentLen stays byte-measured,
now documented as deliberate: for ASCII it is the character count the
threshold was calibrated on, and for multi-byte scripts it is more
permissive, which is right because a four-character CJK title is
specific in a way that "Bitcoin" is not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): fold numerals, break ties on year, and stop cross-provider ID mixing

Follow-ups to the match gate, each closing a hole the first pass left.

Numeral folding. Providers and rippers disagree freely on form:
"Slaughterhouse 5" against "Slaughterhouse-Five" scored exactly at the
threshold and matched only by luck, and a "Part II" volume never agreed
with "Part 2" -- which the volume rule then read as a disagreement and
rejected outright. Spelled and Roman numerals now fold to digits before
scoring, capped at 30 so single letters like "X" and "I" stay letters
("Malcolm X" must not become "Malcolm 10").

Year as a tiebreak, never a gate. For books a year gap is weak evidence:
an audiobook edition of a 1994 novel is routinely dated by its recording
decades later, so rejecting on it would discard correct matches
wholesale. It only decides between candidates already tied on title.

Cross-provider agreement. Each provider was scored independently and
every accepted match was merged into one ID map, so two providers could
each clear the bar while naming different books and leave the item
holding IDs for two works -- worse than either answer alone, because
afterwards the wrong ID is indistinguishable from the right one. The
first accepted title is now the reference and later providers must agree
with it.

Ownership guard for audiobooks and manga. FindContentIDByProviderIDs
appeared three times in the ebook enricher and nowhere in the other two,
so sibling volumes resolving to one provider work all claimed the same
ID with nothing noticing -- the exact collapse the ebook code guards
against, and manga is the most exposed, with series running to dozens of
near-identical titles. Ported including the "don't claim an ID we
couldn't verify is free" path that retries rather than stamping
terminally.

Rejections now log at Info. During a backlog drain the rejection rate is
what separates "threshold too strict" from "providers answering badly",
and that cannot be read from a log level nobody enables.

The threshold is overridable via SILO_METADATA_MATCH_MIN_SCORE so it can
be retuned against a live library without a rebuild; out-of-range values
are ignored rather than obeyed, since a typo'd 0 would accept everything.

Acceptance is now strictly above the threshold rather than at it: a
two-word title sharing one word with a two-word candidate scores exactly
0.5, which is the weakest possible evidence, not a match. Nothing correct
is lost -- the worst true match in the calibration sample scores 0.86.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): verify the author after fetching, not just the title

Title scoring cannot separate two different books that share a title,
and for books that is not a rare edge -- generic titles recur constantly
across authors, so the gate would accept the wrong one on nothing more
than a title agreement.

The obvious fix is unavailable: the plugin contract's SearchResult
carries title, year, overview, image and provider IDs, and no author at
all. Checking it at search time would mean changing the SDK proto and
every plugin implementing it.

It is available one step later. Enrichment already calls GetMetadata on
the accepted match, and MetadataResult.People carries the credits, so
the author is verified after the fetch: a positive contradiction is
recorded as a no-match rather than written. Wired into all three
enrichers.

Absence is never disagreement. An item with no author, or a provider
returning no credits, passes -- most of this library is missing one or
the other, and treating that as a conflict would reject far more good
matches than bad ones. Only a name that actively contradicts rejects.

Name comparison allows for how the same person gets credited: surname
plus first initial (which survives middle names and
initials-vs-full-first-name), the "King, Stephen" reversal, and one form
contained in another ("Iain Banks" within "Iain M. Banks"). Non-author
credits are ignored, so a narrator neither confirms nor contradicts
authorship.

Diacritics ARE folded for names and deliberately are NOT for titles.
Providers transliterate people inconsistently -- "Émile Zola" and "Emile
Zola" are one person, and without folding they disagreed on their first
initial and the match was rejected. Titles are different: "Blåbær" and
"Blabaer" are not reliably the same work, and folding there would erase
a real distinction.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* feat(audiobooks): give enrichment its own state table

Audiobook enrichment recorded its outcome in exactly one place:
media_items.last_refreshed. That stamp had to mean "matched",
"genuinely unmatchable" and "the provider was down that minute" all at
once, so a bad afternoon on a provider burned the item exactly as
terminally as a real no-match, with no attempt count, no error class and
no backoff. Ebooks have ebook_enrichment_state and manga has
manga_enrichment_state; audiobooks had nothing.

The new table sits deliberately between those two. It is not the full
ebook lease queue: audiobook sweeps run from a single task-manager
goroutine and claimBatch takes no row locks, so claim_token/lease_until
would be machinery with nothing to coordinate. It is more than the manga
table, which counts failures and nothing else.

last_refreshed stays authoritative for eligibility, so the migration
changes no behaviour by itself. What changes is that the sweep now skips
items parked for a later retry, and records why each item is where it
is.

Failures are classified, because the distinction is the one the ebook
backlog lost: 90,721 rows there carry outcome='no_match' with attempts=0
and an empty error class, which is why a rate-limited sweep on
2026-07-20 is indistinguishable from 90,721 genuine misses. Here a
failure records a class and parks a retry WITHOUT setting an outcome --
it has not reached a terminal state. Rate limiting backs off hardest
(retrying into a closed window is what turns a throttle into a backlog)
and permanent failures park far out rather than never, since "permanent"
is a classification and classifications are sometimes wrong.

attempts always increments, including on terminal rows, so "never tried"
and "tried and gave up" stay distinguishable.

Bookkeeping never fails the enrichment it describes: a state write error
is logged and swallowed, since last_refreshed remains the authoritative
signal and losing a state row costs reporting detail, not correctness.

Seven DB-backed tests, run against a migrated throwaway Postgres rather
than assumed: the two covering the parked-retry predicate fail with the
predicate removed and pass with it, so they guard something real.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): close four review findings on the match gate

All four verified by reproduction before fixing; none were false
positives.

NFC-normalise before tokenising. A decomposed accent (e + U+0301) is a
combining mark to the punctuation strip and vanished, while the composed
spelling kept its letter, so two byte-level spellings of "Café" scored 0
against each other and an identical title was rejected.

A wrong-volume primary can no longer be rescued by its alias. Aliases
are often the bare series name; "Dungeon In My Closet, Book 5" was
accepted for a volume-2 item through its generic "Dungeon In My Closet"
alias, persisting IDs for the wrong book. A volume stated on the primary
title that contradicts the item's now disqualifies the whole result.

The ebook series-noise test requires volume syntax, not a marker word.
Bare "book" matched anywhere, so "(The Book Thief)" -- a title, not
furniture -- was stripped from the query. The parenthetical is now only
dropped for "Book 4" / "#3" / bare-number / bare-year shapes.

The scheduler-mirror test asserts its own fixture was claimed rather
than that the claimed set is non-empty, which unrelated rows in a shared
test database could satisfy.

Also consolidates the two identical providerIDOwnerLookup interfaces
(ebooks, manga) onto metadata.ProviderIDOwnerLookup per the repo rule
against duplicated contracts.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(audiobooks): make failure recording atomic and UTF-8 safe

Two review findings on the state store, both real.

RecordFailure was two round trips: an upsert incrementing attempts, then
an update parking next_attempt_at. Anything landing between them -- a
cancelled context, a dropped connection, a concurrent RecordOutcome on
the same row -- left the item with an incremented attempts count but no
backoff at all, immediately re-claimable against the very provider that
just failed; or let a terminal outcome be resurrected as a parked retry.
Now a single upsert computes min(step * attempts, cap) on the
post-increment attempts value inside the statement, so there is no
partial-write window rather than a transaction hiding one. retryAfterFor
remains as the Go mirror of the same math, built on shared
backoffParams so the two cannot drift.

The cause truncation cut at a byte index, which can split a multi-byte
rune; Postgres rejects invalid UTF-8, which would have silently failed
the entire failure/backoff write for that call -- the exact no-backoff
state the atomicity fix removes. Truncation now passes through
strings.ToValidUTF8, with a DB-backed regression test whose 500-byte
boundary lands mid-rune.

Also reverts four pre-existing files (abs/, podcastfeed/) that an
overly broad gofmt -w swept into the branch; they are not part of this
change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK

* fix(metadata): harden book enrichment admission

Part of #510

* fix(ebooks): count real no_match cycles and escalate their retry horizon

Complete() zeroed attempts on every outcome, so a row bulk-stamped
no_match without a lookup was indistinguishable from one that failed
five real attempts, and every no_match returned on the same flat 30-day
horizon forever — permanently unmatchable titles (cover-scan artifacts,
bare file numbers) consumed the same daily recycler quota as books that
were never actually tried.

- failures now counts consecutive no_match completions (success resets)
- the no_match horizon doubles per prior failure, capped at 8x:
  30d, 60d, 120d, 240d
- retail edition suffixes are stripped from search queries — anything
  ending in Edition(s)/Classics, Kindle Single, A Novel — the same
  reasoning as the series-marker rule: providers index the work, not
  the storefront packaging. (Illustrated)/(Annotated) still survive.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(access): implement onboarding methods on the resolver stub store

Upstream #501 added GetOnboardingState/UpsertOnboardingState to
userstore.UserStore without extending this stub, so the access package
no longer compiles under test on main.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(jellycompat): implement onboarding methods on progress stub stores

Same upstream gap as the access resolver stub: #501 extended
userstore.UserStore without updating these test doubles.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(ebooks): promote ebooks resolved from complete local metadata

enrichClaimedItem returned EnrichmentOutcomeSuccess for items whose
embedded metadata already satisfied every field enrichment would fetch,
without ever running the status promotion. That was the only terminal
outcome to skip it: no_match, author-mismatch, and provider success all
reach stampLastRefreshed, the sole writer of status 'pending' -> 'matched'.

Those items therefore kept media_items.status = 'pending' permanently and
were counted by the library "unmatched" tile. On prod this is 43,653 of
the 44,014 reported unmatched items (99.2%) — every one of them with
outcome='success', last_refreshed IS NULL, matched_at IS NULL, and title,
author, overview and cover all populated. Rescanning cannot clear them,
because the short-circuit fires again and the queue re-parks the row.

last_refreshed is deliberately left untouched: it gates the admin
quick-refresh sweep, and no provider was consulted here, so these items
must stay eligible for a later refresh that could attach a provider
identity.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(docker): keep agent scratch dirs out of the build context

.claude carries gitignored worktrees and caches that reached 2.8GB locally,
and .superpowers is similar. Neither is needed to build the image, but
.dockerignore did not exclude them, so both were shipped to the daemon as
build context (and rsync'd to deploy hosts).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(rebase): preserve current-main formatting

* fix(metadata): harden book enrichment backlog

* chore(metadata): satisfy changed-lines lint

* test(audiobooks): cover provider error precedence

* feat(auth): scoped API keys and admin user API hygiene

Scoped API keys: an sa_ key may now carry an allowlist of scopes
(admin:users, admin:access-groups:read). A scoped key is refused on every
route its scopes do not name — including the Jellyfin-compat surface and
plugin access — so an integration credential (e.g. a billing system doing
user provisioning) no longer needs a full-power admin key. Empty scopes
keep the existing behavior. Scopes narrow, never grant: role checks still
apply to the owning user.

Admin user API hygiene:
- POST /admin/users maps a duplicate username/email to 409 duplicate
  instead of an opaque 500, so clients can distinguish a lost-response
  retry from a genuine server error.
- DELETE /admin/users/{id} maps a missing user to 404, making terminate
  retries idempotent from the client's point of view.
- POST /admin/users accepts access_group_id (the repository already
  supported it), removing the create-then-update window where a new user
  briefly sat under the default access group.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(access): inherit/override user policy resolution

User policy fields move from "strictest of user and group wins" to
inherit/override: NULL on the user row means "inherit the access group's
value"; a set value is an explicit per-user override that replaces the
group value in either direction — grant or restrict. A group saying "no
downloads" no longer forbids granting downloads to one of its members,
and a member's cap above the group's now wins instead of being clamped.

- users: max_streams, max_transcodes, max_playback_quality,
  transcode_allowed, audio_transcode_allowed, download_allowed,
  download_transcode_allowed, library_ids become nullable (NULL =
  inherit); new nullable requests_allowed. Numeric 0 becomes an explicit
  "unlimited" override instead of a delegation sentinel.
- access_groups: gain transcode_allowed / audio_transcode_allowed so
  every user field has a group value to inherit.
- resolution collapses to effective = user.field ?? group.field ??
  permissive no-group default; permissions keep the allowed_permissions
  intersection mask. All enforcement reads go through the resolver,
  including the previously raw fallbacks (items/sections/libraries
  library scope, legacy permission middleware, /auth/me and login
  download_allowed, requests gate — which now honors a user override).
- downloads package no longer launders effective policy back into
  models.User; checks take a resolved PolicyUser.
- admin user API: PUT accepts explicit null per policy field to clear an
  override back to inherit (tri-state), GET reports stored overrides
  (null = inherited) plus a resolved effective_policy block; access-group
  API carries the two new gates.
- migration maps old delegate values (0 / '' / true) to NULL and keeps
  restrictive values as overrides, so existing behavior is preserved
  except the deliberate cap-above-group change.
- web admin: user forms get per-field Inherit/Override controls showing
  the inherited effective value, saves send explicit null for inherited
  fields (no more silent pinning on save), the user overview shows
  effective values with override provenance, and the access-group editor
  gains the video/audio transcoding toggles.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(access): review fixes for inherit/override reporting

Findings from the adversarial review of c025a6e6:

- An explicit empty library_ids override ([] = no libraries) round-trips
  as [] in admin responses instead of collapsing to null (inherit), so an
  admin open+save no longer silently deletes a deny-all override.
- effective_policy now fails closed: a failed access-group lookup returns
  500 instead of silently rendering a group-restricted user against the
  permissive no-group default.
- Migration maps a pre-existing NULL download gate (the columns were
  always nullable) to inherit instead of inventing an explicit deny
  override, and the down block documents its inherent lossiness for
  explicit permissive overrides.
- web: updating an access group invalidates user queries so effective
  values and inherit hints refresh; changing the group inside the user
  edit dialog degrades inherit hints to generic labels instead of showing
  the old group's values; the invitation form labels null library scope
  as inherit-from-group rather than 'All libraries'.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web): refine featured hero metadata

* fix(access): close scoped-key escalation and policy review findings

Scoped API keys: an admin:users key could create or take over an admin
account and log in for an unscoped JWT. Scoped actors may no longer
assign the admin role or change credentials on an existing admin.
Self-service POST /api/v1/api-keys now honours `scopes` instead of
silently dropping them, and GET /api/v1/api-keys/scopes advertises
the catalog for feature detection.

Policy resolution: download_transcode_allowed was the one column whose
old default was false, so the migration froze every account as an
explicit deny; it now maps false to inherit, NoGroupPolicy matches the
old default, and Down restores the correct default. Legacy negative
caps map to inherit instead of unlimited. Ungrouped users no longer
query the group store, home sections and item filters fail closed on
a policy error like /libraries, the legacy metadata gate resolves
inherited libraries, and the requests service no longer has a dead
group-only fallback.

Web admin: inherit hints follow the selected group on both tabs and on
the create form, Override no longer seeds 0 (= unlimited), an empty
limit box cannot be saved as 0, the effective panel shows the
group-intersected permissions and the audio-transcode row, and the
access-group copy describes inherit/override.

Cleanups: one tri-state decoder, generic clonePtr, shared cap
validator, table-driven user Update, single policy field table in the
web form, orphaned UserTranscodeLimitField removed, unused
OverrideSources removed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs: streamline project and contribution guidance

* docs: link support section from README header

* docs: address review feedback

* docs: clarify adversarial review disclosure

* docs: fix review findings and tighten prose across PR #683

Corrections:
- downloads-api §4.11: proxy_delivery means the routes are mounted, not that
  requests redirect; artifact relay applies to /downloads/{id}/file only.
- docker.md: give a real pg_dump backup (live data-dir copies are torn),
  restart postgres+silo together, explain long migrations vs the healthcheck,
  mention --migrate-status/--migrate-down-to, state compat ports are on by
  default.
- AGENTS.md: align "Related issue" wording with the PR template; point the
  pre-PR gate at CONTRIBUTING instead of carrying a second list.
- .env.example: leave POSTGRES_PASSWORD commented so the quick-start append
  is the only definition.
- Issue forms: drop the required Adversarial review field; restore the
  fabricated-report block warning in the bug-report intro.
- feature-changelog: add the missing entry for proxy delivery (#607).

Consolidation:
- One pre-submission gate (CONTRIBUTING), one quick start (docker.md), one
  go.work paragraph (DEVELOPMENT), one AI disclosure block wording.
- README drops the duplicated quick start, tag table, doc index, and filler.
- PR template checklist reduced to the two items its sections don't cover.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(catalog): move the person photo triple as a unit during enrichment

Address review findings on the credit-enrichment artwork guard.

photo_path, photo_source_path, and photo_thumbhash describe one image, but
each column was gated on its own value. A credit carries a photo URL and never
a source path, so replacing the "-" no-photo sentinel rewrote photo_path while
leaving the previous source URL in place. photo_source_path is what
UpdatePhotoIfSourceMatches keys the image-cache handshake on and what
EnqueueExistingProviderArtwork downloads from, so the finished job landed the
*old* image on the row, under the old image's thumbhash. All three columns now
move together under one decision taken on photo_path.

Deferring every replacement to the full person refresh also stranded people
with no tmdb/imdb/tvdb id: FindRefreshCandidates skips them, so nothing would
ever revisit a photo URL that had gone dead. The guard now protects cached
artwork specifically rather than any populated value — an empty column, the "-"
sentinel, and an uncached provider URL stay replaceable. "Not a cached key" is
the same LIKE '%://%' test the artwork GC trigger and the image cache sweep
use, so displacing a URL still queues nothing for deletion. Replacement
requires a genuinely different path, so re-scanning an unchanged credit remains
a no-op.

Tests: the SQL-shape test now matches whole generated clauses instead of loose
fragments, so a mis-wired column fails it, and the Postgres-backed test no
longer calls t.Fatalf on the parent T from inside a subtest. New cases cover
the stale-source binding, uncached-URL replacement, and the unchanged-credit
no-op. The behavioral coverage still needs SILO_TEST_DATABASE_URL, which CI
does not set.

Also build the batch enrichment SQL once instead of per batch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(contrib): require a readability prose pass and vendor the unslop skill

AI-written PR and issue bodies routinely arrive padded with filler and
promotional framing that costs review time. Vendor the unslop skill into
.claude/skills/ so contributors' agents pick it up in-repo, and add a
Prose pass section to docs/ai-contributions.md making the pass an
expectation. Worded explicitly as readability, not concealment: it may
not alter facts, pasted output, or logs, and disclosure still applies.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(access): ungroup accounts promoted to admin

Create already leaves admins ungrouped because playback and catalog
policy is role-blind. Update did not: promoting a Default Group member
kept that group's stream cap and library list. Drop the group on
promote, reject assigning one to an existing admin, and ignore an
explicit group on admin create.

Co-authored-by: Quick <[email protected]>

* fix(access): make admin accounts ungrouped everywhere

Review follow-up for the promote-clears-group fix. The rule now has one
write-side owner and one read-side guard instead of five copies:

- UserRepository.Update clears the group on promote and lands a demoted
  admin on the default group unless the write names one, so an ex-admin
  never becomes an uncapped non-admin.
- access.EffectivePolicyForUser ignores any group an admin row still
  carries (GroupApplies), covering every write path and pre-existing data.
- A data migration clears admins grouped before this rule and bumps their
  policy revision.
- PUT /admin/users/{id} rejects role=admin + access_group_id with 422
  whether the role is echoed or not, matching POST /admin/users; the
  handler no longer pre-clears the group itself.
- Invitations reject admin + access_group_id at send (422) instead of
  storing a group that accept silently drops.
- Web forms derive access_group_id=null for admins at submit; the detail
  form no longer wipes the picked group on a role toggle.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(access): enforce admin ungrouping atomically and in list responses

Review follow-up:

- A group written without a role change is resolved against the row's
  current role inside the UPDATE, so a write racing a promotion cannot
  leave an admin grouped; the migration also adds a
  users_admin_ungrouped CHECK constraint as the durable backstop.
- GET /admin/users applies the same GroupApplies guard as the detail and
  auth endpoints, so a legacy grouped admin row never reports group
  ceilings anywhere.
- Regression test for toggling the role to admin and back keeping the
  picked group.
- Lint: spelling, wasted assignment.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(access): stage the admin-ungrouped constraint and clear pending admin invitations

Review follow-up:

- Drop the CHECK constraint from this release's migration: in a rolling
  upgrade, previous-version nodes still promote without clearing the
  group and the constraint would surface as a 500. The repository's
  in-statement CASE and the read-side guard already hold the invariant;
  add the constraint once every writer is on this version.
- The migration also clears the group on still-pending admin invitations
  created before this rule, so they advertise what accept will do.
- Both user forms preview the no-group policy while Admin is selected
  instead of the retained group's ceilings.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web): smooth detail action interactions

Co-authored-by: OpenAI Codex (GPT-5) <[email protected]>

* test(web): cover detail interaction variants

Co-authored-by: OpenAI Codex (GPT-5) <[email protected]>

* feat(playback): add header-authenticated media transport

* feat(playback): negotiate bounded software decode

* fix(web): scale poster overlays with card width

* fix(web): scale poster overlay shadows

* fix(web): prevent detail action hover repaints

* fix(web): keep detail action hover compositor-only

* fix(web): preserve disabled action affordance

* fix(abs): key the login rate limiter on the transport peer

clientip.Middleware overwrites r.RemoteAddr with the header-derived viewer
address whenever the TCP peer is a trusted proxy, which includes Docker's
bridge. Mounting it on the ABS listener therefore defeated the login limiter's
deliberate RemoteAddr-only keying: an attacker behind any reverse proxy could
rotate X-Forwarded-For and buy a fresh burst bucket per request.

The middleware now preserves the pre-overwrite peer address in the request
context, and the limiter reads that instead. Anything else that must key on an
address a client cannot forge should do the same.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(jellycompat): key stream telemetry on the upstream playback session

Compat attached observations under PlaybackSession.ID while the proxy,
nodesessions and playback_sessions_sync all key on playback.Session.ID, and
BuildGlobalView merges by exact SessionID string. One Jellyfin viewing therefore
showed as two merged sessions — a byte-less compat twin and the proxy record
carrying the traffic — and every compat session looked telemetry_only in parity.

Compat now attaches only under UpstreamSessionID. A play session does not learn
that id until ensureUpstreamPlayback/ensureTranscodeManifest has run, so the
pre-side-effect attach is a no-op on a session's first request and the handler
attaches again the moment the id exists, still before any byte is written. A
provisional key was rejected deliberately: it recreates exactly the ghost session
this fixes, and a session whose id did not exist a moment ago cannot have a
pending cut against it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(streamtelemetry): make Truncated recoverable and hold early realtime state

Three defects in the process-local registry, all found by review:

Truncated was sticky for the process lifetime. drop() set it and nothing ever
cleared it, so one transient capacity burst pinned the merged view's Complete
to false until a restart and made a later real truncation indistinguishable. It
now decays over Freshness — the same horizon BuildGlobalView uses to decide a
publisher is current — while the monotonic Dropped* counters keep the permanent
record.

SetRealtimeConnection was a no-op when the session did not exist yet. That is
the normal client ordering: the control socket opens as soon as a sessionId
exists, before the first media route is hit, so RealtimeConnectionAlive stayed
false for the whole of every live session. State for an unknown session is now
held per shard, applied when an attach creates the session, capacity-bounded
against the session budget, and pruned by the sweep.

The distributed cross-checks compared an env-supplied value against the DEFAULT
of the other knob, so setting one variable disabled distributed mode and blamed
a variable the operator never set. Knobs left at their defaults now move to
satisfy the invariant; only a pair pinned to genuinely inconsistent values is an
error, and only the variables actually set are named.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(httpstream): give every ReadFrom slice a full stall window

The bumpStep throttle was written for the 32 KB Write path, where one
SetWriteDeadline per chunk would be wasteful. Applying it to ReadFrom slices
buys nothing — a slice is already bounded at 4 MiB — and costs correctness: a
slice completing less than a step after the last bump got no refresh, so the
next one started with as little as window-step remaining. The real guaranteed
floor was ~203 kbit/s, not the 186 kbit/s the constant and both design documents
promise, and a client sustaining the documented rate was reaped as stalled.

Slices now bump unconditionally, before the first as well as between each, which
is what the pre-CopyChunked loop did. Costs at most one syscall per 4 MiB.

The existing deadline tests construct the writer with step=0 and so never
exercised the throttle; the two added here fail on the unfixed code.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(proxy): credit the egress meter often enough to measure slow viewers

meteredResponseWriter previously hid io.ReaderFrom on purpose, so every byte
reached egressMeter.Add through a ~32 KB Write. Forwarding ReadFrom restored
sendfile but moved crediting to once per completed 4 MiB slice, which a
200-500 kbit/s direct-play viewer takes 60-170 s to fill. RateKbps averages over
60 s, so those streams read as zero for most samples: /api/v1/status
under-reports committed egress and nodepool's effectiveEgressKbps can admit
sessions onto a saturated proxy.

Metered slices are now 256 KiB — a credit every 4-10 s at those rates, well
inside the window, and still 8x more per sendfile call than the Write path it
replaced. Slice size here is a rate-fidelity constraint, not a tuning knob.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(downloads): roll the direct-download deadline and carry the profile

handleDirectDownload passed the raw ResponseWriter to ServeDirect, so unlike the
sibling /downloads/{id}/file it had no rolling deadline and the API server's
absolute 120 s WriteTimeout truncated any original large enough to take longer.
Excluding the route from compression made it one unbounded sendfile, so the
whole body now rides on that single deadline.

redirectDirectDownload hardcoded an empty profile id in both the proxy redirect
and the telemetry attach, while the local branch two lines away reads the real
one. Proxy-served traffic was therefore missing from per-profile attribution in
telemetry, in the stream token claim and in the node session.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(streamtelemetry): fold ranged transfers, guard delta publishes, split conflicts

Transfers were one record per HTTP request keyed by observation id, so ranged
byte routes — audiobook file reads, download resumes, ebook fetches — could
exhaust MaxTransfers within one retention window while RequestCount, the field
that exists to count exactly this, stayed pinned at 1. A transfer is now one
subject pouring one file over one route, and overlapping requests fold into it.

A delta publish rewrites only changed fields and assumed the Redis hash still
held the rest. An eviction, an out-of-band DEL, a replica failover or a lapsed
PExpire drops it with no error, leaving under-reported sessions for up to
FullResyncEvery publishes. An HLEN inside the same transaction now catches the
mismatch and forces the next publish full, self-healing in one sweep.

recordConflicts appended started_at_replaced without setting
hasIdentityConflict, so the exported flag could disagree with the exported list.
A pure authority upgrade that confirms the recorded instant now records nothing
at all — it is not a conflict and should never have consumed the budget — and a
replacement that moves the value sets both.

Also documents two limitations rather than half-fixing them: clock skew is only
detectable for a publisher running ahead, since the roster score is the
publisher's own clock; and observedWriter.ReadFrom samples the cut flag once,
which the enforcement change that first calls cut.Store has to make uniform
across h1 and h2.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(httpstream): one ForwardReadFrom helper for all nine wrappers

Nine ResponseWriter wrappers across five packages hand-rolled the same tail:
assert the inner writer's io.ReaderFrom, CopyChunked through it, fall back to
io.Copy over WriterOnly. Because io.Copy finds ReaderFrom by direct assertion
and never through Unwrap, this forwarding is mandatory on every media-route
wrapper — so a fix to it had to be re-applied nine times and a missed site
silently dropped to the fallback, losing zero-copy sendfile along with that
wrapper's byte accounting.

Behavior is unchanged; each call site keeps its own chunk size and record
callback.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(streamtelemetry): share viewer-IP, env and client-info helpers

Four families built the same clientip-then-RemoteAddr fallback chain inline
while streamtelemetry already had it unexported; a fix to it (IPv6 handling,
say) would have had to land in four places or the families would report
different viewer addresses into the same merged view. Exported as ViewerIP and
adopted everywhere.

envEnabled was the ninth independent "is this env var truthy" parser in the
tree, each accepting slightly different spellings. Adds internal/envutil and
adopts it in both telemetry packages; the remaining copies should migrate as
the code around them is touched.

checkVersion re-parsed every record into a throwaway header struct before
unmarshalling it again into a wire type that already carries the version, so a
merged-view rebuild — measured at ~347 ms for 50 000 sessions, nearly all
decode — did the JSON work twice.

ConfigFromEnv ran twice at startup because the view cache re-read the
environment just to get ViewTTL, logging any invalid variable twice; it now
takes the TTL off the registry that already parsed it.

playbackClientInfoFromRequest wrapped PlaybackClientInfoFromRequest wrapped
playback.ClientInfoFromRequest — three names, one body. Callers now use the
playback package directly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: document the admin stream-telemetry parity endpoint

CLAUDE.md requires a docs/*-api.md entry and a changelog entry for a
client-visible API change. No admin-API document existed — the ~20 sibling
routes in the same router block are undocumented too — so this adds one, scoped
honestly to what it covers, with the full response shape for
GET /api/v1/admin/stream-telemetry/parity and the caveats an operator needs to
read a report correctly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: distill the streaming write-deadline design into architecture

PR #675 pruned docs/superpowers and the shipped design artifacts, distilling the
durable content into docs/architecture first. The streaming write-deadline
document was deleted on main under that rollup while this branch was extending
its writer-chain conformance section, which is the whole of the conflict between
the two.

This carries the durable half forward on main's own pattern: the invariants a
future change has to respect — the rolling-deadline contract, why slice size is a
correctness constraint rather than a knob, the two rules every ResponseWriter
wrapper on a media route must follow, the one-limiter sendfile trap, why chi's
compressor is bypassed rather than repaired, and how conformance is actually
verified. The one-shot half — the 2026-07-09 debugging session, the per-file
application table, the rollout plan, the silo-apple follow-up list — goes with
the deletion.

Also records the two rules this branch's review turned up: the bump throttle
belongs to Write and never to a ReadFrom slice, and the proxy egress meter has
the same shape of constraint at a different value.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore: ignore skill secrets and state paths

- Ignore `.secrets` and `.state` paths regardless of whether they are files or directories

* feat(playback): tokenless V3 playback, DV7 client transforms, admin transcode honesty

Playback protocol V3:
- Tokenless playback: header-authenticated media with signed stream URL
  reconstruction, sticky per-attempt feature set, and tokenless subtitle
  delivery (playback_v3, resolver, transcode manager, protocol_v3).
- Downloads and auth updates supporting the same flow; access-group clause
  coverage for repository queries.

Admin activity honesty:
- Plumb target_audio_channels end to end (new migration, session sync,
  reconciler, admin session payload, web types) so a transcode target
  renders its real output layout ("AAC 5.1"), falling back to the bare
  codec when unknown - never the source channel count.
- Rename the "Audio SW" chip to "Audio Transcode"; it labels a plan
  decision (video copied, audio transcoded), not a client capability.

Client counterpart: silo-apple branch t3code/replace-custom-engine-aether
(AetherEngine player). This server branch is required for that client -
AetherEngine playback negotiation (tokenless media, DV Profile 7
client-transform grants) does not work against older servers.

Co-Authored-By: Claude Fable 5 <[email protected]>

* perf(metadata): bulk persist seasons and episodes

* test(metadata): fix localized fixture spelling

* perf(web): reduce detail interaction latency

* test(metadata): adapt query-count coverage to upstream API

* fix(playback): regenerate conformance matrix for software_video_decode_v1

make verify-playback-fixtures failed on CI because one matrix entry was
missing the new server feature string.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: address latency review feedback

* fix(downloads): apply the coarse resolution ceiling when the detailed bounds walk cannot run

With detailed video_decode evidence and sparse probe metadata, Resolve
skipped both the per-decoder bounds walk and the flat max_resolution
ceiling, approving original-quality downloads beyond the device ceiling.
Sparse metadata now fails closed to the flat contract, ceiling included;
complete metadata keeps letting a validated detailed entry override the
coarse ceiling.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(playback): restore proxy and transcode-node egress for header-authenticated media

header_authenticated_media_v1 kept every media byte on the API server
because proxies could only authenticate from the signed URL token that
mode removes. A new attempt-sticky opt-in, authorized_media_origins_v1,
restores distributed egress without putting a credential back in any URL:

- Plans for an attempt that negotiated both features may return absolute,
  credential-free proxy URLs (/stream/v3/{session_id} family) for direct
  play, progressive remux, and node-executed HLS.
- The proxy is told what to serve out of band: the API writes the session
  recipe to a Redis proxy-grant store (silo:proxygrant:, sibling of the
  noderecipe handoff), overwritten on replan and revoked on session stop,
  abort, and uncommitted-transport rollback.
- The proxy authenticates the caller itself: bearer JWT against the live
  signing secret plus the same auth_sessions liveness check the API runs,
  then ownership against the grant. Revoking a login stops proxy playback
  immediately. Node-relay tokens are minted proxy-side and never reach
  the client.
- RecipeCard now carries DVProfile/AudioOnly so a grant-served remux
  reproduces the exact bytes the token path would have.
- The progressive-remux escalation to HLS now applies only when no proxy
  origin is available; grant-write failure falls back to the API origin
  under the same local_transcode_fallback gate as the no-origins mode.

Header-auth-only clients and deployments without a proxy pool keep the
current API-local behavior unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): address automated review findings on tokenless proxy egress

- Preserve the displaced proxy grant across a replan and restore it on
  rollback, so a failed replacement no longer 404s the restored plan's
  proxy URL; revoke the grant when a proxy-egress attempt commits onto a
  transport the API serves itself (identity, relay, or local transcode).
- Gate the progressive-remux escalation on a usable grant store as well as
  configured proxies: a process that can never authorize proxy egress
  escalates to HLS instead of refusing forever, while transient proxy
  ineligibility keeps the legacy retryable refusal.
- Advertise target_audio_channels in the admin sessions capability
  endpoint so independently deployed clients can feature-detect it.
- Reject an unrecognized video_evidence value on flat download payloads
  instead of silently resolving from flat claims.
- Handle SessionUnauthorized defensively in the stream and jellycompat
  serve switches (unreachable today; prevents a nil dereference if the
  caller invariants ever drift).
- Document the tokenless replica-affinity constraint in the protocol spec.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): survive transcode-node restarts on tokenless attempts and stop charging unused proxies

- A header-authenticated remote transcode published no stream token, so
  after a transcode-node restart neither the client nor the API relay had
  a recipe to forward and playback 404ed until a replan. The API now
  writes the transport's recipe card to the shared noderecipe store
  (keyed by transport id, like the jellycompat handoff), and the node's
  reconstruct path falls back to the store when no X-Silo-Stream-Token is
  present — the token was a recipe source, never the route's
  authorization. Recipes are deleted on every deliberate teardown
  (transport replacement, rollback, session stop/abort); the TTL only
  backstops a crashed API process.
- When a start reserved a proxy+transcode pair but published a URL the
  proxy does not serve (unwritable egress grant, or the legacy no-token
  fallback), the planner kept charging the proxy's job slot and estimated
  bandwidth until the reservation aged out. New ReleaseSessionProxy drops
  only the proxy half; the transcode node keeps its charge because it is
  running the job.
- The proxy-grant store interface is renamed recipeCardStoreV3 and shared
  by both handler fields, since it now carries two key spaces.

Co-Authored-By: Claude Fable 5 <[email protected]>

* test(transcodenode): check CloseProcess error in tokenless reconstruct test

golangci-lint errcheck failed CI on the new changed line.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(streamtelemetry): enrol tokenless /stream/v3 proxy routes

The merge left the five credential-free grant routes registered but
unclassified, so bytes served through authorized_media_origins_v1 were
invisible to stream telemetry. Enrol them:

- Declare GET+HEAD /stream/v3/{session_id} (playback), GET+HEAD
  .../master.m3u8 (manifest) and GET .../segment/{name} (playback), all
  viewer egress and capability-relevant, and wrap each registration in
  observeProxy.
- Give them CanonicalSessionKey "verified_media_grant" rather than the
  "verified_stream_token" the proxyRoute helper hardcodes. The field is
  descriptive — it is only compared in sameDeclaration and emitted into the
  route manifest, and no code branches on its value — but these routes prove
  entitlement with a Redis grant plus the caller's own bearer token, never a
  stream token, so labelling them otherwise would be false.
- Attach the viewer in relayGrantToTranscodeNode, the single path both grant
  transcode handlers take. The proxy->node hop itself stays internal_relay.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(streamtelemetry): enable by default and derive distributed mode from redis

Stream telemetry measured nothing on a fresh install: both switches were
opt-in, so the parity comparison every P1 threshold depends on only ever ran
where someone had already read the design doc. Observation is process-local,
off the hot path and bounded, so the safer default is on.

SILO_STREAM_TELEMETRY_ENABLED now defaults to true and is a per-process kill
switch; SILO_STREAM_TELEMETRY_FAMILIES still narrows observation or drops one
misbehaving family without losing the rest. SILO_STREAM_TELEMETRY_DISTRIBUTED
is no longer a flag the operator has to keep in sync with their topology:
unset, the mode follows whether Redis is configured, so a single-container
install stays on LocalStore and a cluster merges. Setting it pins the mode
either way, and a rejected distributed configuration pins it off so the
derivation cannot re-enable exactly what was just refused.

Both switches read a set-but-unparseable value as false rather than as the
default (envutil.BoolDefault). For a default-on flag that means a typo in the
kill switch turns telemetry OFF, which is the fail-safe direction: the
operator was reaching for "stop observing", and a mistyped disable that
quietly left the feature running is the failure that costs them.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(streamtelemetry): observe every route family by default

The staged per-family rollout set (native, proxy, transcode_node) is removed
by owner decision: SILO_STREAM_TELEMETRY_FAMILIES left unset now observes all
five declared families (native, jellycompat, proxy, abs, transcode_node)
instead of a curated subset. The variable stays as a narrowing/kill knob —
naming it takes families away rather than staging them in.

Adds streamtelemetry.AllFamilies as the single canonical family list so
ObservesFamily and ObservedFamilies don't hand-duplicate it, updates the
design doc's family-gate section and env table to match present-tense
behavior (keeping the original staged-rollout narrative as history), and
updates the feature changelog to say every family is observed out of the box.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(scanner): persist H.264 copy-safety verdicts and move analysis off browse paths

The multi-PPS copy-safety scan ran on media-page load and was forgotten on
every restart, re-reading the opening seconds of every browsed H.264 file —
painfully slow on remote storage. The verdict is now persisted on media_files
(self-validating against file size+mtime, so in-place rewrites invalidate it
without writer coordination), the scan window drops from 15s to 5s, browse
pages never trigger the scan (EnsureProbeOnly), and concurrent first scans
share one ffmpeg via singleflight. The lazy path stays fail-closed and
stateless on errors.

Related issue: N/A — narrow fix

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(playback): optimistic remux race with server-initiated plan invalidation

When an H.264 file's copy-safety verdict is unknown, playback no longer
blocks on the bitstream scan: the planner issues the remux optimistically,
the scan runs behind the plan, and an unsafe verdict withdraws it. Sessions
that negotiated the new plan_invalidated_v1 feature get a pushed
plan_invalidated realtime command and switch via their normal
failure_recovery replan; everything else — including today's mobile apps —
is stopped and recovers onto a transcode through the persisted verdict.
Watch pages and playback start now never wait on the scan. jellycompat
sessions are exempt: their route selection does not consult the verdict yet.

Web client implements the feature; Apple/Android follow-ups tracked in their
repos.

Related issue: #135

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): sweep sessions that register after a copy-unsafe verdict lands

The async scan can beat the start path by milliseconds: a plan is decided,
the verdict persists before the session is registered, and the notifier's
immediate pass finds nothing — leaving the session on a condemned remux
route with no second look (observed live on dev: plan at t, verdict at
t+4ms, playback restarting on corrupt output). VideoCopyUnsafe now schedules
one file-wide sweep after the settle window that considers only sessions the
immediate pass never saw.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): harden copy-safety invalidation against review findings

Four fixes from PR review: the web client defers a plan_invalidated that
races an in-flight replan adoption instead of no-opping it; a race scan that
finds another replica already persisted an unsafe verdict still notifies its
own sessions; stopping a session now interrupts an in-flight progressive
remux response (previously only the client could end it — ffmpeg was bound
solely to the request context); and background scans are capped at four
concurrent ffmpeg processes globally.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): validate realtime command ownership before consuming it

Review fixes: a realtime result naming another session's command is now
rejected before the tracker deadline is canceled or the record dropped; the
concurrent-scan test waits on observable state (a gated fake ffmpeg) instead
of a fixed sleep; changelog wording no longer overclaims verdict permanence.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): close copy-safety races in replan commits, transport stops, and reconstruction

Review round two: sessions the notifier could not classify mid-replan-commit
stay eligible for the post-settle sweep instead of being marked handled;
WatchTransportStop returns an already-closed channel for a session stopped
before registration; reconstructing a video stream-copy transport (progressive
or HLS) now consults the persisted verdict, closing the replica-failover hole
where a condemned remux could be re-served with nothing left to withdraw it;
and a verdict whose database write failed is memoized as unpersisted and the
write retried on later requests without rerunning ffmpeg.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): gate copy-unsafe revivals before reconstruction and per file generation

Round three review fixes: the reconstruction verdict gate moves ahead of
session registration in loadTranscodeServeSession, so refused revivals cover
the remote-node proxy branch and can no longer poison stream admission with a
leaked session; a failed local scan re-reads the row and applies a verdict
another replica persisted concurrently; and the scan singleflight is keyed by
file generation (id+size+mtime) so a replaced file cannot consume the old
generation's verdict.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(playback): re-engage the copy-safety race on revival and close generation races

Round four review fixes, closed as one gap: a video stream-copy transport
revived or replanned while the verdict was unknown or unpersisted never
re-engaged the race machinery. KnownCopySafetyVerdict answers from memo then
row (retrying an unpersisted write, never running ffmpeg); both revival paths
consult it and kick the racer when nothing condemns the card; and a race
request arriving mid-scan queues one follow-up pass instead of being dropped.
Verdict writes are now conditional on the scanned file generation so a slow
old-generation scan can neither overwrite the replacement's verdict nor
notify its sessions. The web client scopes its adoption-settle wait to the
load sequence that owns the session, so a hung superseded start cannot stall
an invalidation past the command deadline. Test hygiene: atomic node-hit
counter, observable wait instead of a sleep.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(playback): let original players manage HDR

Accept delivery-scoped client claims for Aether-managed dynamic range and selected audio on original HTTP while retaining packaged-output gates and the existing behavior for clients that do not claim support.

* fix(catalog): reject disabled dual-library items

* chore(catalog): satisfy changed-lines lint

* fix(sections): enforce disabled episode hydration scope

* fix(scanner): scope file reconciliation to changed path

* fix(scanner): unify present-state repair and drop dead extras sync call

Review follow-ups for the file-scoped reconciliation:

- Collapse syncPresentLibraryState and syncPresentFileState into one
  syncPresentState implementation with an optional exact-path scope, so the
  two variants cannot drift. The folder-wide entry point emits the same SQL
  as before; the episode-membership statement is unified on the sibling-join
  shape so first_seen_at always aggregates over all of an episode's active
  files.
- Run the four repair statements in a single transaction instead of four
  autocommit round-trips, so a crash mid-repair cannot leave a row with its
  links cleared but its memberships unrestored.
- Remove the syncPresentFileState call in the extras-conversion branch: the
  preceding Upsert already nulls the row's content/episode links, making
  every statement a no-op there. The membership cleanup at that site comes
  from the unchanged reconcileLibraryMemberships call.
- Drop the redundant COALESCE inside GREATEST in the series denorm bump.
- Extend the regression test to drive both scopes through the unified body,
  including dangling content link repair.

Co…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant