Repository navigation
feat(apiv2): pilot five operations on Huma with the web contract harness [api-v2 phase 3] - #941
Conversation
The v2 listener served only discovery; the Phase 3 pilot needs v2
operations that call the same business logic as their v1 handlers
without duplicating it or changing v1 bytes.
This adds the first pilot operation, GET /api/v2/system/setup
(getSetupStatus, public), answered from the same account count v1
GET /auth/setup uses, and the seams the remaining pilot operations
share:
- handlers.APIError carries a v1 handler decision (status, code,
message, optional field) so one extracted function can serve both
surfaces; writeAPIError renders it in the v1 {error, message} shape.
- The v1 DTO types the pilot mirrors are exported (UserView,
ProfileView, ProfileUpdateRequest, AdminUserView, EffectivePolicyView)
with their JSON tags untouched.
- AuthHandler.NeedsSetup/CurrentUser, ProgressHandler.ListProgress,
ProfileHandler.UpdateProfile and AdminHandler.ListAdminUsers hold the
business logic the v1 handlers previously inlined; the v1 handlers
now call them.
- canManageHousehold is split so the PIN verifier is injectable: v1
keeps checking X-Profile-Token, v2 will read the viewer scope.
- apiv2.Dependencies gains Accounts, Progress, Profiles and AdminUsers;
an unwired service answers 503 dependency_unavailable.
- Operation.ProfileOptional lets a profile_scoped operation accept an
absent X-Profile-Id, matching v1 groups that run viewer access
without RequireProfile.
- contractspec's lint reads the OpenAPI 3.1 type array form so
nullable members do not fail the spec lint.
- The route inventory row for /api/v2/* only changes its handler
expression text; the listener shape is unchanged.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
GET /api/v2/account/me (getCurrentUser, class authenticated) returns the caller's login account with no profile involved: id as an opaque ID, role as the admin/user enum, permissions never null, download_allowed from the effective policy, and impersonation as an optional nested object present only while an administrator acts as the account. It calls AuthHandler.CurrentUser, the function v1 GET /auth/me now calls, so both surfaces read the same user and policy sources. Tests cover the happy path, impersonation, 401 without and with an expired session, the undeclared-query 422, and a store failure rendered as internal_error without detail. Co-Authored-By: Claude Fable 5.1 <[email protected]>
GET /api/v2/progress (listProgress, class profile_scoped) lists the
acting profile's watch progress with the query the contract ratifies:
status (enum in_progress, completed), library_id (opaque ID), limit
(default 50, max 200) and an opaque cursor, returning {items, page}.
offset and since are refused with the foundation unknown-parameter
422; the v1 ?since= delta pull stays on v1 and is a separate later
operation.
The cursor is HMAC-bound to the operation, the account and profile,
the status and library filters and the updated_at ordering, so a
cursor presented against another filter or profile is the
invalid_cursor 400. It calls ProgressHandler.ListProgress, the
function v1 GET /progress now calls, including the viewer-access and
library filters, and asks for one extra row to decide has_more.
Tests cover the happy path and filter pass-through, cursor paging and
binding, every validation failure, the profile-header 422, the locked
and unknown profile denials, 401, and a store failure.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
PATCH /api/v2/profiles/{id} (updateProfile, class profile_scoped with
an optional X-Profile-Id, as v1 PUT /profiles/{id}) applies a
household profile update with the contract's PATCH semantics: an
omitted member is unchanged, an explicit null clears a member that
admits clearing (avatar, pin, max_content_rating, the three languages,
max_playback_quality) and is a type failure on any other member, and
an unknown member is rejected. The three string enums
(quality_preference, subtitle_mode, max_playback_quality) are declared
so the spec carries them; allowed_library_ids are opaque IDs.
It calls ProfileHandler.UpdateProfile, the function v1 now calls, with
the same authorization: an administrator or the verified primary
profile manages the household, and any other caller may change only
its own active profile's playback preferences. A PIN-locked primary
profile counts as verified when the viewer-access gate resolved it as
such, the check v1 performs against X-Profile-Token itself. Domain
decisions map onto problem types: 404 not_found, 409 conflict, 403
permission_denied, the profile_verification_required type clients
branch on, and a rejected member as a 422 naming it. It is not
If-Match protected (optimistic concurrency is opt-in and not yet
encoded); the mutation is naturally idempotent.
Tests cover the happy path and command shape, omitted versus null
versus value, null on a non-nullable member, bad enums, an unknown
member, a malformed body, every decision mapping, 401, a locked
declared profile, and the demo-mode refusal.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
GET /api/v2/admin/users (listAdminUsers, class acting_admin,
demo-restricted) returns every login account as {items: [...]}, a
bounded collection with no page object. Each item mirrors the v1
administrator view with v2 wire types: ids as opaque IDs, role as the
admin/user enum, per-account policy overrides as nullable members
(null inherits the access group's value, and library_ids keeps null
distinct from an empty allowlist), the nested effective policy with
non-null arrays, created_at/updated_at as UTC millisecond instants and
last_active_at as a nullable instant.
It calls AdminHandler.ListAdminUsers, the function v1 GET
/admin/users now calls. Tests cover the happy path with the null/time/
enum fields asserted byte-for-byte, the primary-profile header, 401,
the non-admin and non-primary-profile 403s, the undeclared-query 422,
a store failure, and the unwired-service 503.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Names the repeated literals the linter flagged on the pilot's touched lines (the JSON null literal, the profile-header error location, the max_playback_quality member, the existing bad_request code) and makes the PATCH null check's decode-failure branch explicit instead of a swallowed error. No behavior change. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The Phase 2 fixture set only covered getSystemInfo and the generic envelope failures, so native harnesses had nothing to vendor for the pilot slice. Every pilot operation now has an ok fixture generated through the real router with the pilot fakes, plus the class-denial and validation-failure cases the generic fixtures did not already cover: the missing X-Profile-Id header and the rejected v1 offset parameter on listProgress, explicit null on a non-clearable member on updateProfile, and permission_denied for a member on listAdminUsers. fixtureDeps now builds on pilotDeps with a fixed cursor key so the next_cursor in list_progress_ok is stable across runs; the new cases are appended after the existing ones because request ids follow case order. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The pilot operations are served on /api/v2 but the ledger still listed
their v1 rows as proposed with no v2 target, so nothing tied the ledger to
what the server registers. The five rows (auth/setup, auth/me, progress/,
profiles/{id}, admin/users) now name their v2 method, path, and operation
id, are review_state ratified, and carry a note recording each
v1/contract divergence: PUT became PATCH with omitted-vs-null semantics,
offset pagination became limit plus opaque cursor with the v1 ?since=
delta pull deferred to a later section, the admin list is wrapped in
{items}, and ids/instants/enums follow the v2 wire representation.
contractledger now decodes the v2 target and
TestRatifiedOperationsExistInSpec checks every named operation against
the committed openapi.json at the same method and path, so a ratified row
can never point at an operation the server does not serve.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The contract described the foundation and the fixture rules but nothing named the five pilot operations or what each proves, so a later section author had to reconstruct it from the code. A "Pilot slice" subsection under "Client contract adoption" now lists the operations, their v1 origins, the class each proves, and the two findings every later section inherits: PATCH omitted-vs-null semantics enforced from the raw body, and limit-plus-cursor pagination replacing offset (with the v1 ?since= delta pull deferred to its own operation). Co-Authored-By: Claude Fable 5.1 <[email protected]>
The three new listProgress fixture cases pushed the literal to four occurrences and golangci-lint's goconst flagged it on the branch's lines. The id is now a package constant shared by the operation registration, the cursor scope, and the fixture cases; no behavior or artifact changes. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The web app had no typed view of the v2 contract. This pins openapi-typescript 7.13.0 exactly and adds `pnpm run generate:apiv2` (web/scripts/generate-apiv2.mjs), which reads contracts/api/v2/openapi.json and writes two prettier-formatted artifacts under web/src/api/v2/: schema.ts (paths, components, operations) and operations.ts (the runtime `METHOD /path` -> operationId map the request boundary will use to label errors). Both are committed. `make apiv2-web-types` regenerates; `make verify-apiv2-web-types` regenerates into a temp dir and byte-compares, failing with a ::error:: line naming the fix. The verify target runs in the Web CI job next to verify-settings-bindings-web, which is the job that has pnpm. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The web app needed one place that binds a v2 operation's method, path, parameters, body, and responses to the generated contract types. `v2(...)` in web/src/api/v2/request.ts selects an operation by its `METHOD /path` literal and infers path params, query, JSON body, and the 2xx response from the openapi-typescript `paths` type; the operation id is read from the generated operations map to label errors. Documented non-2xx responses decode to a typed RFC 9457 Problem and throw V2ProblemError (operation id, parsed problem, problem identifier). A body that is not JSON or not a problem document throws V2TransportError; a failed fetch rejects with the network error itself. A 403 profile_verification_required drops the active PIN the same way v1 does. Success values carry a phantom brand (`V2<T>`, a unique symbol) so a v1 type from web/src/api/types.ts cannot satisfy a v2 parameter by structural coincidence; web/src/api/v2/testing.ts brands hand-built fixtures for tests only. The bearer, refresh-then-retry-once, profile, and device header loop moved out of apiResponseInternal into fetchWithSession, which both the v1 client and the v2 boundary call; v1 status and body handling is unchanged and client.test.ts still passes. Every v2 request sends Accept: application/json plus X-Silo-Client / X-Silo-Client-Version (the bundle version injected by vite.config.ts), matching the fixture headers. Tests decode the committed fixtures, the 401/422/406/415 problems, an HTML body, a network failure, the refresh-and-retry path, and a type-level proof that v1 types are rejected. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The four v1 call sites in the pilot now go through `v2(...)`:
- hooks/useAuth.tsx: setup discovery reads GET /api/v2/system/setup and
the session's current user reads GET /api/v2/account/me. The session
keeps its `User` shape because login, signup, and restore still answer
on v1; userFromAccount projects the v2 account (string id) onto it.
- hooks/queries/progress.ts: useProgressList calls GET /api/v2/progress
with a typed query (status, limit 20, optional library_id). The hook
now returns the v2 collection: `items` instead of `progress`, plus
`page`. useContinueWatching, the playback progress cache, and
ContinueWatchingCard were updated to the v2 entry type rather than
cast.
- hooks/queries/profiles.ts: useUpdateProfile sends PATCH
/api/v2/profiles/{id} with the v2 ProfileUpdate body. The editor builds
that body with buildProfileUpdateFromDraft: a cleared avatar, rating,
quality ceiling, or PIN goes on the wire as null; an unchanged PIN is
omitted; library ids are strings. profileFromV2 projects the response
onto the `Profile` shape the list and session still read from v1.
- hooks/queries/admin/users.ts: useAdminUsers reads GET
/api/v2/admin/users and maps `items` onto the `AdminUser` shape the
admin pages share with the v1 detail and mutation hooks (string ids to
numbers, null last_active_at to omitted).
Tests cover the PATCH body's null-versus-omitted members and the
AuthProvider mocks the v2 boundary for setup discovery.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The useContinueWatching test stubbed the progress list with the v1 `progress` array; the hook now reads the v2 `items` member. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Adds a no-restricted-syntax override scoped to web/src/api/v2/ and the four migrated files that rejects `api<T>(...)`, `apiWithProfileRequestContext<T>(...)`, and `as` assertions to any identifier ending in Response or Request, so a migrated file cannot fall back to asserting a response shape instead of inferring it from the contract. The rule was proven against a throwaway probe file (all three forms flagged) that is not committed. The v1 calls that remain in those files (login, signup, providers, profile list/create/avatar, admin user detail/devices/impersonate) stay on v1 but state their type through a return or variable annotation. The boundary's success type is renamed V2Response -> V2Result so the rule's `*Response` pattern reads cleanly. Co-Authored-By: Claude Fable 5.1 <[email protected]>
quality_preference, subtitle_mode, and max_playback_quality are copied from the v1 profile view unnormalized and storage is unvalidated (the schema default for quality_preference is "1080p"), so the read model's declared enums could be violated by served bodies. Keep the PATCH request enums strict; document the canonical values on the read fields and note that older profiles may carry other stored values. Ledger note and contract doc updated; regenerated OpenAPI and the system-info fixture digest. Adds a test serving a stored "1080p" preference. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…hemas No pilot operation carried a request or response example; the fixtures directory was the only worked example. Add huma example tags to every scalar member of the pilot structs (account, progress, profiles, admin users, setup status) so the OpenAPI document renders examples inline. Examples are fictional and consistent with the committed fixtures. Regenerated openapi.json, the system-info fixture digest, and the web schema types; the change is additive. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…n restore
getCurrentUser is a pilot operation, but two web call sites still used
the v1 path: OAuthComplete called api<User>("/auth/me") after the code
exchange, and restoreUserSession (used by useAuth's impersonation
recovery) fetched /api/v1/auth/me. Both now go through the v2 boundary.
OAuthComplete calls v2("GET /api/v2/account/me") mapped through
userFromAccount, which moves from useAuth.tsx to api/v2/account.ts so
both callers share it. restoreUserSession moves next to it and keeps
its refresh-then-retry-once semantics with the v2 URL both times,
decoding through the new exported decodeV2Response so problem
documents surface as V2ProblemError. The ESLint contract restriction
now covers OAuthComplete.tsx; the local OAuth code-exchange type is
renamed so the *Response cast rule keeps guarding contract types.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The determinism test forbade any "example"/"examples" key as a proxy for build-specific content. The pilot schemas now carry fictional, fixture-shaped examples on purpose, so the check keeps only the needles that catch real leaks (local paths, localhost). Co-Authored-By: Claude Fable 5.1 <[email protected]>
The pilot artifact still had 21 scalar schema members and all 8 operation parameters without examples: SystemInfo, SystemInfoLinks, PageInfo, Problem, ProblemError, the permissions and library-id array items, the X-Profile-Id header, the updateProfile path id, and the listProgress query parameters. Struct fields and huma input fields carry `example` tags; slice fields use a JSON array literal so the array itself gets an example. Array items get theirs from the element type's Schema(): ID now declares "1", and a new Permission string type (plain string on the wire, no client-visible change) declares "marker_edit". The documented X-Profile-Id header carries its example directly. Values are fictional and match the committed fixtures; no type, nullability, enum or JSON name changed, so the contract diff is additive. The regenerated artifact changed the contract digest, so get_system_info_ok.json and the generated web types are refreshed with it. Co-Authored-By: Claude Fable 5.1 <[email protected]>
verify-apiv2-fixtures-siblings compared every server fixture against the sibling checkouts, so a client that deliberately vendors only the fixtures it consumes (the plan's "selected fixtures, not the full spec") always read as stale. Compare only the files the sibling holds, require each to match the server byte-for-byte, and check the sibling's index.json against the server index filtered to those names. Name the example permission once so goconst stays quiet on the Permission schema. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Team Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17380cbca5
ℹ️ 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".
Quick104
left a comment
There was a problem hiding this comment.
Three additional findings from the review of 17380cbca. The existing comments already cover filtered progress pagination, offset cursor ordering, and impersonation recovery.
Validation passed for internal/apiv2, internal/contractledger, internal/contractspec, and the full internal/api/handlers suite. Web findings were verified against callers and server validation; web tests were not run because the isolated checkout lacks dependencies.
…swers 401 initializeAuthSession fetches the current user over v2 now, so a stale impersonated session fails with a V2ProblemError rather than an ApiClientError. The recovery predicate only knew the v1 error type, so the preserved administrator session was never restored and the user was signed out. Accept a 401 Problem as recoverable too; the impersonation-end request still runs over v1 and keeps its ApiClientError path. Reported by Codex on #941. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 970a11b9fa
ℹ️ 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".
The progress listing paginated by numeric offset over ORDER BY updated_at
DESC, a set that reorders while playback heartbeats land, so pages skipped
or repeated rows and equal timestamps had no defined order.
Add UserStore.ListProgressPage: the same status predicate and hidden-item
exclusion as ListProgress, ordered by (updated_at DESC, media_item_id DESC)
and resuming strictly after a ProgressKey. Postgres compares and sorts on
date_trunc('second', updated_at) because the key string the store hands out
is whole seconds; SQLite spells the row comparison out as
`updated_at < ? OR (updated_at = ? AND media_item_id < ?)`. Both stores
share one SELECT/WHERE constant per backend instead of three copies.
ProgressHandler.ListProgressPage is the seam for the v2 listing: it fetches
limit+1 raw rows, applies the access and library filters, and keeps
fetching after the last raw row until it holds limit+1 matches or the store
runs dry, so has_more is decided on rows the viewer can see. v1
HandleListProgress keeps the offset path unchanged.
A storetest conformance case pins the order, the strict resume and the
tiebreak for both backends; the Postgres run is gated on
SILO_TEST_DATABASE_URL like its neighbours.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
… has
PATCH /api/v2/profiles/{id} documented a response map the listener did
not match: it omitted the 408 the body-read deadline produces and the 409
v1 UpdateProfile answers a taken name with, while advertising an
application/octet-stream request body that mediaTypeGuard rejects with
415 (Huma documents the RawBody member updateProfile reads for its
omitted-versus-null rule). The allowed_library_ids loop also accepted a
repeated identifier, which aborted the store's primary-key insert and
surfaced as a 500 for schema-valid input.
408 joins ImpliedStatuses under hasBody, so every body-carrying
operation documents it and the contractspec lint demands it; 409 is
declared on updateProfile's own Errors. An OnAddOperation hook in the
shared humaConfig strips request media types structuredMediaTypeOK
rejects, so the generator and the served router agree. A duplicate
library identifier is now a 422 validation_failed on
body.allowed_library_ids. The octet-stream removal is approved in
breaking-approvals.json for the pre-1.0 pilot; the regenerated artifact,
system-info fixture digest and web types are committed with the change.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
listProgress asked the store for limit+1 rows at an offset and then dropped rows outside the viewer's access scope or the requested library, so any dropped row made the page look final: next_cursor was omitted while older matching rows existed, and a library-filtered Continue Watching row could stay partial or empty. The cursor was also an offset over a set that reorders during playback, against the contract's requirement that cursors bind to the effective sort with a unique tiebreaker. The cursor now carries the (updated_at, media_item_id) of the last emitted entry, scoped to sort "-updated_at,-media_item_id" with media_item_id as the tiebreaker, and the handler calls the new ListProgressPage seam, which decides has_more after the filters run. Rows filtered out between two emitted rows are re-read and re-dropped on the next page; nothing is skipped or repeated. Tests cover a library filter that drops rows yet still pages to the end with no gaps or duplicates, equal timestamps across a page boundary, a row whose updated_at advances between pages, and cursors from a different filter or profile being rejected. The list_progress_ok fixture's next_cursor changes shape; the OpenAPI document and web types do not. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Against the PR base (42ea446) updateProfile is a new endpoint, so the octet-stream request representation never existed in a published artifact and the diff tool rejects the approval as matching no change. It was added while diffing against an intermediate commit of this branch. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74fe2b4ac9
ℹ️ 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".
…ng or failing The updateProfile body lowered a present, non-null "" PIN to the same "" sentinel as null, so the store silently removed the PIN although the contract says only null clears it. A PIN longer than 72 bytes exceeded bcrypt's input limit and surfaced as a 500 from both stores. validatePIN now runs before the body is lowered onto the v1 request: "" and > 72 bytes answer 422 validation_failed at body.pin (out_of_range), with "PIN must not be empty" / "PIN must be at most 72 bytes". The schema also carries minLength 1 / maxLength 72 (rune-counted by Huma; the byte bound is enforced in code). The OpenAPI artifact, its fixture digest, and the generated web types are regenerated. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s policy A cursor was bound to account and profile only. When the viewer's library access or content-rating ceiling changed between pages, the old cursor still validated and rows that had just become visible but sort before the key were skipped without any signal. CursorScope.Security for the access-filtered listProgress collection now also carries viewerScopeDigest(ctx): sha256 (first 16 hex chars) of the policy revision, sorted allowed and disabled library IDs, and the content-rating ceiling, "none" when no scope resolved. A policy change therefore yields the invalid-cursor 400 through Cursors.Decode and the client restarts pagination. The helper sits next to CursorScope so later access-filtered operations reuse it; api-contract.md and the list_progress_ok fixture (its next_cursor signature) are updated. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c9e5a4e376
ℹ️ 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".
…tener really emits Three gaps between the served v2 pilot and its OpenAPI document, found in review of #941: - getSetupStatus is public but answers 503 dependency_unavailable when the account service is not wired; ImpliedStatuses added 503 only to gated classes. Operation gains ServiceBacked, exported to the document as x-silo-service-backed, and ImpliedStatuses implies 503 for it. All five pilot handlers set it; the document and discovery operations do not. - Viewer access answers 404 for an unknown X-Profile-Id before the handler runs, but 404 was implied only by a path parameter. Every profile-resolving class now implies it. - A PIN-locked profile resolves only with X-Profile-Token, which the document never declared. Every profile-resolving operation now documents it as an optional header. The contractspec lint reads the new extension and follows ImpliedStatuses, with seeded failures for both new rules. Regenerated openapi.json, the web types and the get_system_info_ok fixture (contract digest only). Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 706166d9f5
ℹ️ 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".
The v1 admin account listing loads every account in one query, and the v2 pilot reused that seam, so listAdminUsers had no bound on a multi-user deployment. Add UserRepository.ListPage (id > $1 ORDER BY id ASC LIMIT $2) and an AdminHandler.ListAdminUsersPage seam that fetches limit+1 rows after the key and reports has_more. The policy and last-activity enrichment moves into adminUserViews, shared by both seams, so v1 ListAdminUsers keeps its output unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]>
listAdminUsers returned every account as a bare {items} collection. The
contract reserves that shape for small, naturally bounded collections;
accounts on a multi-user deployment are not bounded.
The operation now takes limit (default 50, maximum 200) and cursor, and
answers with the shared Paginated envelope (page.next_cursor,
page.has_more). The cursor is a keyset on account id ascending, bound to
the operation and the acting admin's account; offset is refused as an
unknown query parameter, matching listProgress.
The list_admin_users_ok fixture uses limit=1 so has_more and next_cursor
are exercised, and list_admin_users_offset_rejected covers the 422.
OpenAPI, fixtures, and web types are regenerated; the pilot table, the
pagination note in api-contract.md, and the migration ledger row record
the change.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
listAdminUsers is now cursor paginated, and the admin screens render, filter, and pick from the full account list. useAdminUsers walks the listing at the 200-row maximum until the server reports has_more=false, so those screens keep seeing every account. The new test pins the two-page walk: no cursor on the first request, the returned cursor on the second, and the walk stopping on the last page. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… and nil-versus-empty allowlists
access.Scope distinguishes an unrestricted profile (AllowedLibraryIDs nil,
LibrariesRestricted false) from one restricted to nothing (AllowedLibraryIDs
empty, LibrariesRestricted true), but viewerScopeDigest serialized both id
lists as "" and omitted LibrariesRestricted. On stores that do not bump
PolicyRevision for that change, a cursor minted under the narrower policy
kept verifying after access widened, so rows that became visible before the
key were skipped.
The canonical digest input now carries LibrariesRestricted ("1"/"0") and
serializes a nil id list as "-" versus "" for an empty one. The
list_progress_ok fixture's next_cursor signature moves because the digest
input changed; the payload is unchanged.
TestListProgressCursorBoundToViewerPolicy now covers restricted-empty to
unrestricted under the same PolicyRevision, empty versus nil allowlists,
and the restriction flag on its own.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
… on updateProfile Two updateProfile hardening fixes that landed intertwined and are committed together so every commit builds: Unknown library identifiers: a positive id for a nonexistent library passed validation and reached the store, where Postgres violated user_profile_allowed_libraries_library_id_fkey (500) and SQLite persisted a dangling id. apiv2.Dependencies.Libraries (ExistingIDs, implemented by catalog.FolderRepository) is consulted after the duplicate check; unknown ids return 422 validation_failed at body.allowed_library_ids, a missing dependency returns 503, and an empty list skips the lookup. API-key PIN bypass: the verifier accepted scope.ProfileVerified, which the viewer-access middleware sets for API-key tokens through SkipPINVerification, so a non-admin unscoped key could change another profile's restrictions or clear the primary PIN without verifying it. The resolver now records PINVerificationSkipped and the v2 verifier requires a real verification, matching v1's verifyProfileToken (a login session plus a valid X-Profile-Token). TestMiddlewareParity gains the API-key cases. Reported by Codex and the maintainer on #941. Co-Authored-By: Claude Fable 5.1 <[email protected]>
apiKeyScopeRoutes named only the /api/v1/admin/users patterns for auth.ScopeAdminUsers, so an admin API key scoped to admin:users was refused with 403 on GET /api/v2/admin/users while the same request on v1 succeeded. The allowlist is written against the public URL surface, so each v2 operation has to be listed as it lands. Add the v2 listAdminUsers path (pagination lives in the query string, which the path match does not see) and cover it in TestAPIKeyScopesAllow: allowed for admin:users, denied for the access-groups scope, and the v2 collection POST and profile PATCH stay denied. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…teProfile The PATCH members quality_preference and subtitle_mode carried inferred request enums (auto/original and auto/always/off) that no client honours: web onboarding offers auto/1080p/4k, the Android editors send 2160p/1080p/720p and default/forced_only, and Apple onboarding forwards 1080p/4k. v1 never validated either column and nothing server-side reads quality_preference beyond storage, so the strict enum broke every client that migrated to v2 for no gain. Replace both enums with maxLength 32 and document them as free-form until the vocabulary is ratified (#135), listing the values seen today. max_playback_quality keeps its enum: the server owns those constants. Update the pilot-slice paragraph, the updateProfile ledger note, the generated openapi.json, web schema, and the system-info fixture digest. TestUpdateProfileValidation now bounds length instead of the enum and checks that "1080p" and "forced_only" reach the store unchanged. The profile_management code becomes a constant to satisfy goconst. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… resolver too 300c17d added Scope.PINVerificationSkipped so the v2 updateProfile verifier can refuse an API key standing in for a locked primary's PIN, but only the legacy access resolver set it. Deployments running the policy engine use policy.ViewerResolver, which left the flag false and would have let the bypass through; TestResolveViewerScopeParity caught the divergence. Set it from the same facts (verified, PIN-locked, SkipPINVerification) and teach the parity harness to expect it. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Problem
Phase 2 (#936) shipped the Huma foundation for
/api/v2with two operations and no consumer. Before converting hundreds of routes, the program needs one small slice that proves the whole chain end to end: server operation, generated spec, deterministic fixtures, migration ledger, and a typed client boundary in the bundled web app, with Apple and Android decoding the same fixtures offline.Solution
Five pilot operations, chosen against the plan's six criteria (public discovery, authenticated account, profile-scoped read with query parameters, validated JSON mutation, admin/policy-protected, representative null/time/enum fields), excluding playback and uploads:
getSetupStatusGET /api/v2/system/setupGET /api/v1/auth/setup{needs_setup}shapegetCurrentUserGET /api/v2/account/meGET /api/v1/auth/meroleenum, nullableimpersonationlistProgressGET /api/v2/progressGET /api/v1/progress/limit+ opaquecursorreplaceoffset;offset/sincerejected with 422; the?since=delta pull stays on v1 for a later sectionupdateProfilePATCH /api/v2/profiles/{id}PUT /api/v1/profiles/{id}nullclears where the field admits clearing, otherwise 422; strict request enums; noIf-Match(optimistic concurrency is still "Not yet encoded", #882)listAdminUsersGET /api/v2/admin/usersGET /api/v1/admin/users{items}; UTC-ms instants; web-only consumerv1 stays byte-identical. Each v2 handler calls a seam extracted from the v1 handler (
CurrentUser,ListProgress,UpdateProfile,ListAdminUsers); the v1 handlers now call the same seams. The five ledger rows areratifiedwith v2 targets and a note per divergence;contractledgergainsTestRatifiedOperationsExistInSpec. Nine new fixtures cover the ok path, the class denial, and one validation failure per operation. Every pilot scalar and parameter carries a fictional example inopenapi.json.Web harness.
openapi-typescript7.13.0 pinned;web/src/api/v2/schema.tsgenerated and committed withmake apiv2-web-types/verify-apiv2-web-types(wired into the CI web job).v2("METHOD /path")inweb/src/api/v2/request.tsinfers params, body, and success type from the generatedpathstype and throwsV2ProblemErrorforapplication/problem+json. An ESLintno-restricted-syntaxrule forbidsapi<...>(andas ...Responseat the migrated call sites. The five pilot call sites (useAuth, OAuthComplete, progress, profiles, admin users, impersonation restore) use v2 only;grep -rn "/auth/me" web/srcreturns nothing.Why this shape. PATCH with omitted-vs-null is the contract's mutation rule (api-contract.md "Wire data representation"); cursor pagination is the contract's collection rule. Both surfaced as the pilot's template findings and are recorded in the new "Pilot slice" subsection of
docs/architecture/api-contract.md.Plan: Phase 3 of the API v2 / Huma implementation plan (in the #135 checkpoint comments). Companion PRs: Silo-Server/silo-apple#253 and Silo-Server/silo-android#294, both pinning this branch's fixtures at
17380cbca.Review history
A 3-lens blind review (contract parity, client conformance, update-server behavior) returned 5 major, 0 blocking. All five were verified against source and fixed:
Profileenum tags could be violated by legacy stored values (quality_preferencedefaults to1080pin the schema; v1 never validated it). Read enums dropped, PATCH enums kept, ledger note added.openapi.json. Examples added to every schema scalar, array item, and parameter (coverage script: 30 missing → 0).TestGenerateOpenAPIIsDeterministicno longer forbids theexampleskey; its/Users/,/home/,localhostneedles stay./auth/meover v1 inOAuthComplete.tsxand inrestoreUserSession(production caller: impersonation recovery). Both moved to the v2 boundary inweb/src/api/v2/account.ts.Validation
Full CONTRIBUTING gate on
17380cbca(27 steps):make embed-stub,go build,gofmt,go vet,golangci-lint --new-from-merge-base=origin/main(0 issues),make lint-router-recovery,make test-go,verify-route-inventory,verify-migration-ledger,verify-scenario-catalogs,verify-offline-routes,verify-apiv2-openapi,verify-apiv2-contract(additive),verify-apiv2-fixtures,verify-apiv2-web-types,verify-apiv2-fixtures-siblings(against the companion client branches),verify-settings-bindings-all,verify-playback-fixtures,verify-local-paths,actionlint,pnpm run lint,pnpm run format:check,pnpm run build,make test-web, clean tree. All PASS.One flake observed on the first gate run:
TestRestartSegmentLocked_UsesResolvedCopyAnchorAndManifestNumberininternal/transcodenode(untouched by this branch) failed once with "manifest is empty" and passed on-count=3and on the full rerun.verify-apiv2-fixtures-siblingspreviously compared every server fixture against the sibling checkouts, so a client that vendors only what it consumes always read as stale. It now compares the files the sibling holds and checks the siblingindex.jsonagainst the server index filtered to those names.Risks
Operation.ProfileOptional(profile_scoped withoutRequireProfile) mirrors the v1/profilesgroup; whether v2 should be stricter is a API v2 program epic: /api/v2 contract reset on Huma, bounded bridge, v1 retirement at 1.0 #135 ratification question, not settled here.quality_preferenceenum values (auto,original) are inferred from client usage; there is no server constant. Legacy stored values are served unchanged.apiv2.Permissionis a named string type so array items can carry an example; it is a plain string on the wire andstring[]in the generated TypeScript.Follow-up
?since=delta pull for progress becomes its own operation in the watch-state section.web/src/api/types.tsentries as more consumers move to v2.Related issue: #135
AI Disclosure
claude-fable-5-1[1m]) for orchestration, all implementers, and all review agents🤖 Generated with Claude Code