Skip to content

feat(lectures): include per-lecture userChoices in the /for-audience feed - #727

Merged
sydevs-bot merged 6 commits into
mainfrom
claude/feat-lecture-user-choices
Sep 7, 2026
Merged

sydevs-bot merged 6 commits into
mainfrom
claude/feat-lecture-user-choices

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • /api/lectures/for-audience and /api/meditations/{id}/related-lectures now return each lecture's userChoices as { id, title }, with the title localized to the request locale.
  • WeMeditateWeb's contentIndexCard already reads doc.userChoices and degrades to a plain grid without it, so the filter pills light up with no change on that side.
  • user-choices becomes a cacheable, purgeable slug. Both feeds embed its titles, so a rename now invalidates them instead of leaving stale labels at the edge.

Changes

  • src/lib/lectures/lectureShape.ts — userChoices on LecturePlayerData, the shapeUserChoices projection, and LECTURE_FEED_POPULATE
  • src/collections/{Lectures/endpoints/forAudience,Meditations/endpoints/lectures}.ts — pass the populate bound, tag user-choices
  • src/plugins/cache/policy.ts — user-choices joins CACHE_TTLS at the 600s default
  • src/plugins/openapi/customEndpoints.ts — the LecturePlayerData schema, now pinned by a spec

Preview

Contract impact

Additive on a shape two repos consume. LecturePlayerData is hand-written here, not generated, so nothing needs regenerating downstream.

Migration

None. No field config changed — jsonSchema, columns and relationships are untouched.

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (125 files, 1613 tests)
  • Targeted integration specs: ✓ 112 across lectures-for-audience (49), meditation-lectures (32), lectures (31) on the first round; ✓ 80 across the first two re-run on 0601358.
  • Build: N/A — Railway builds the preview

Every new assertion was confirmed failing first, at the site that causes it:

Defect reintroduced Goes red
userChoices dropped from LECTURE_FEED_SELECT the two expectedKeys pins
populate: LECTURE_FEED_POPULATE dropped from all three reads strips everything but title…
shapeUserChoices drops an unpopulated id keeps an unpopulated id…, preserves the order…
shapeLecture never calls shapeUserChoices 2 wiring cases
a clip reads metadataSource.userChoices the clip case
the endpoint's find pins locale: 'en' resolves the title for the request locale
userChoices dropped from the OpenAPI required list marks userChoices required…
the user-choices cache tag dropped tags the response with user-choices…

Two of those rows exist because the first version of this PR did not have them, and an adversarial pass found both:

  • Unwiring shapeUserChoices from shapeLecture left all 1608 unit tests green. A pure helper's spec cannot see whether its caller calls it.
  • Deleting the populate bound from every call site also left everything green. The specs that named it asserted the constant's own literal value, which only fails when someone edits the constant. Both change-detectors are gone, replaced by one case that reads with the real bound and asserts the stripped fields are absent.

Manual verification

  1. Admin → Lectures → assign one or more user choices to a lecture that has an audience.
  2. curl -H "Authorization: clients API-Key <key>" "$URL/api/lectures/for-audience?audiences=<id>&limit=20" — that lecture carries userChoices: [{ id, title }], and a lecture with none carries [].
  3. Repeat with &locale=fr on a user choice that has a French title — the title changes, the id does not.
  4. Rename a user choice, then re-request the feed — the new title appears rather than the cached one. Needs CLOUDFLARE_ZONE_ID + CLOUDFLARE_CACHE_PURGE_TOKEN set, otherwise TTL is the invalidation path.

Notes for reviewer

  • user-choices joining CACHE_TTLS is the judgement call here. It was the smallest fix that keeps cacheHeaders.ts's "never outlives its freshest input" promise — a slug outside that map is not a CacheableSlug, so the feeds could not tag it at all. Two intended side effects, both beyond these endpoints: GET /api/user-choices becomes cacheable, and every user-choices write now fires a Cloudflare tag purge (CACHEABLE_SLUGS drives the purge hooks). DEPLOYMENT.md records that the live Cloudflare Cache Rule need not list the slug, and that leaving it out just keeps that one read DYNAMIC. This paragraph replaces the inline comment review asked to delete.
  • The feed's row type is Required<Pick<UserChoice, 'id' | 'title'>>, not the bare Pick review suggested. UserChoice declares title?, so Pick alone makes the key optional while the OpenAPI schema marks it required. Aliased once as FeedUserChoice rather than inlined at both sites.
  • A clip reports its own memberships, never its parent's — unlike metadata and fullLectureId, which a clip does inherit. A clip is assigned to a user choice independently, so inheriting would report a membership no editor set. Say if you want the opposite.
  • An unpopulated id becomes { id, title: null } rather than being dropped. Both callers read at depth: 2 so it should not arise, but dropping the row would report the lecture as belonging to no user choice — indistinguishable from the truth.
  • A security review ran (the diff touches src/collections/*/endpoints/) and returned no finding. It confirmed both wemeditate-* client roles can already read /api/user-choices directly, so {id, title} is not new information to them.
Detail

Review round 0601358. All three comments applied. LectureUserChoice deleted in favour of the generated interface, per the rule src/types/AGENTS.md carries and #659 enforced. shapeUserChoices keeps its behaviour and loses the bulk — comment from 11 lines to 6, and the flatMap guard dropped as unreachable, since Lecture['userChoices'] types every element and both callers are TypeScript. The CACHE_TTLS comment removed.

The function itself stays, and the reason is worth recording: the built-in review was reaching for is populate, which this PR already uses — LECTURE_FEED_POPULATE narrows a populated row to { id, title } at the read, so nothing is picked in the helper. What remains is collapsing the two shapes a hasMany returns, ids at depth 0 and documents at depth ≥ 1, for which Payload has no helper.

Why populate and not defaultPopulate. docs/rules/endpoints.md named only defaultPopulate for narrowing a relationship's fields. That would narrow user-choices for every reader, including the admin. The bound belongs to these two feeds, so it goes on the read. id survives it — buildFindManyArgs hard-sets columns = { id: true } whenever a select is present — which is what lets the related-lectures ranking loop keep comparing uc.id.

What the bound is actually worth, since the first version got this wrong. It is not the #541 N+1, and profiling it as one finds nothing: population goes through payloadDataLoader, which batches the whole pool into a single find, so the waste scales with the number of distinct user choices rather than with pool size. What it prevents is a wide row — user-choices' two join fields (children, and lectures at defaultLimit: 100), the upload columns, the virtual URL field, and four localized relationships. The comment on the constant now says this, because the wrong story invites the next reader to conclude the bound is decorative and delete it.

CANDIDATE_SELECT lost a line. related-lectures spread userChoices: true explicitly; it now inherits it from LECTURE_FEED_SELECT, since the feed shape returns it. The ranking loop reads the same documents.

One thing the bound does not cover. A clip's nested fullLecture parent hydrates its own userChoices a level down, which shapeLecture discards. That is a second batched round trip, not a per-row one, and narrowing it would need Lectures.defaultPopulate — a global change for a local saving. Recorded in the comment rather than fixed.

A pre-existing gap the security review surfaced, filed nowhere yet. requireActiveClient gates on "published clients user" and not on project. sahaj-atlas-client cannot read /api/user-choices directly, yet can call /for-audience — which already hands it the whole lecture feed. This change widens that by two public display fields rather than opening it. Say if you want a ticket.

Unrelated churn kept out. A test run regenerated src/payload-types.ts with SUPPORTED_TIMEZONES reordered. That is #722, now fixed in #728 — @vvo/tzdb sorts by current UTC offset, and Chile entered DST on 2026-09-06, one day after the committed snapshot was written.

Closes #526

🤖 Written by the sydevs autonomous loop — see what this is

🤖 Generated with Claude Code

https://claude.ai/code/session_01YPw1LL76jc2JT8K47fkHzN

…feed

WeMeditateWeb's content-index block SSR-loads the lecture feed once, since
the SahajCloud API key is server-only, then filters client-side. It cannot
render UserChoice filter pills, because the feed carries no per-lecture
membership. `contentIndexCard` already reads `doc.userChoices` and degrades
to a plain grid without it.

`LecturePlayerData` gains `userChoices: { id, title }[]`. `title` is
localized on `user-choices`, and neither endpoint's `find` passes a locale
of its own, so it resolves against the request's locale.

Three things worth naming:

- `userChoices` moves onto `LECTURE_FEED_SELECT` rather than the
  related-lectures ranking spread, since both endpoints return it now. The
  ranking loop reads the same documents and only compares `id`.
- `LECTURE_FEED_POPULATE` bounds a populated row to its title. `user-choices`
  is an upload collection with a virtual URL field and several localized
  fields — unbounded, selecting the relationship pulls all of them for every
  lecture in the candidate pool, which is the N+1 shape #541 closed one level
  up.
- A clip reports its own memberships, never its parent's. A clip is assigned
  independently, so inheriting would report a membership no editor set.

Every new assertion was confirmed failing first, at the site that causes it:

| Defect reintroduced | Goes red |
| --- | --- |
| `userChoices` dropped from `LECTURE_FEED_SELECT` | `selects userChoices…` |
| `LECTURE_FEED_POPULATE` widened past `title` | `bounds a populated user-choice…` |
| `shapeUserChoices` filters out unpopulated ids | 2 helper cases |
| `shapeLecture` never calls `shapeUserChoices` | 2 wiring cases |
| a clip reads `metadataSource.userChoices` | the clip case |
| the endpoint's find pins `locale: 'en'` | `resolves the title for the request locale` |

The fourth row is why the wiring cases exist. Unwiring the helper left all
1608 unit tests green — a pure helper's spec cannot see whether its caller
calls it.

Fixture pre-mortem: the unit fixture assumes a full lecture's `type` is
`'full'` (the only value `shapeLecture` branches on is `'clip'`) and that it
owns its own `metadata`. Checked against
`src/collections/Lectures/Lectures.ts` and `src/lib/lectures/lectureShape.ts`.

Closes #526

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YPw1LL76jc2JT8K47fkHzN
… emits

`customEndpoints.ts` already said to keep this schema in lockstep with
`LecturePlayerData` in `src/lib/lectures/lectureShape.ts`. Only a comment
said so, so adding a field to one and forgetting the other drifted silently.
`additionalProperties: false` does not catch it either — nothing validates a
response against this schema at runtime.

Three cases pin the property set, `userChoices` being required, and a
user-choice row's own two fields. Confirmed failing first: dropping
`userChoices` from the schema's `required` list turns the second red.

The property list is the same one `lectures-for-audience.int.spec.ts` and
`meditation-lectures.int.spec.ts` pin against a real response, so the two
ends now have to move together.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YPw1LL76jc2JT8K47fkHzN
…es them

`cacheHeaders.ts` promises a custom endpoint's response "never outlives its
freshest input". The previous commit broke that promise: both lecture feeds
now embed a user choice's localized `title`, but `user-choices` was not a
`CacheableSlug`, so the responses could not tag it and its writes fired no
purge hook. Renaming a user choice left stale labels at the edge for the
full 300s/600s TTL.

`user-choices` joins `CACHE_TTLS` at the 600s default — display metadata,
renamed rarely — and all three responses tag it. The derived TTL does not
move, since `resolveTtl` takes the lowest and `audiences` is still 300s.
Adding the slug also makes the built-in `GET /api/user-choices` read
cacheable, which is the same published-only public metadata by the same
rule.

Confirmed failing first: dropping the tag from `forAudience.ts` turns the
new `tags the response with user-choices` case red.

Two smaller fixes from the same review:

- `tests/int/lectures-for-audience.int.spec.ts`'s #541 N+1 regression case
  passed `select: LECTURE_FEED_SELECT` with no `populate`. With `userChoices`
  now in that select, it was hydrating user-choices unbounded and no longer
  reproducing what the endpoints do.
- The `LECTURE_FEED_POPULATE` comment said "~8 localized fields". There are
  five. It now names what is actually stripped, and records that `id`
  survives the bound — which is what the ranking loop depends on.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YPw1LL76jc2JT8K47fkHzN
…bounds

- `docs/rules/endpoints.md` listed only `defaultPopulate` as the way to narrow
  a relationship's fields. A read's own `populate` is the other, and it is what
  this change uses — the bound belongs to the lecture feeds, not to every
  reader of `user-choices`.
- `DEPLOYMENT.md` enumerates the live Cloudflare Cache Rule's slug list, which
  is now narrower than `CACHE_TTLS`. Says why, so nobody "fixes" the mismatch
  by caching a read nobody asked to cache.
- `docs/architecture.md` and `tests/COVERAGE.md` name the new field and what
  covers it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YPw1LL76jc2JT8K47fkHzN
@railway-app

railway-app Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-727 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 7, 2026 at 6:39 pm UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-727 September 7, 2026 17:32 Destroyed
An adversarial review pass found the bound had no behavioural coverage:
deleting `populate: LECTURE_FEED_POPULATE` from all three reads left the
whole suite green. The two specs that named it asserted the constant's own
value, which fails only when someone edits the constant — and then the fix
is to edit the expectation.

Both change-detectors are gone. In their place, one integration case reads
with the real select and populate and asserts a populated user choice keeps
`id` and `title` while `lectures`, `children`, `url` and `filename` are all
absent. Confirmed failing first: dropping the populate argument from every
call site turns exactly that case red, and nothing else.

`related-lectures` gained the same gap in reverse — it pinned the response
key set and never the value, on the endpoint that also reads `userChoices`
for ranking. One case now asserts a real id and title there.

Three smaller items from the same review:

- **The `LECTURE_FEED_POPULATE` comment was wrong about the cost.** It called
  the unbounded read "the same N+1 shape" as #541. It is not: population goes
  through `payloadDataLoader`, which batches the whole pool into one `find`,
  so the waste scales with distinct user choices, not with pool size. The
  comment now says what the bound is really worth — `user-choices`' two
  `join` fields, one of them at `defaultLimit: 100` — and warns that
  profiling it as an N+1 will find nothing. A wrong story invites the next
  reader to conclude the bound is decorative and delete it.
- `shapeUserChoices` guards a non-object entry. Payload cannot produce one,
  but the function is exported and its doc block invites other callers;
  `{ id: undefined }` would serialize to a row missing the `id` the OpenAPI
  schema marks required.
- `as const` → `satisfies PopulateType`, matching `LECTURE_FEED_SELECT` two
  lines above, so the guarantee is local to the declaration.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YPw1LL76jc2JT8K47fkHzN
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-727 September 7, 2026 17:36 Destroyed
@sydevs-bot
sydevs-bot marked this pull request as ready for review September 7, 2026 17:48
Comment thread src/lib/lectures/lectureShape.ts Resolved
Comment thread src/lib/lectures/lectureShape.ts Resolved
Comment thread src/plugins/cache/policy.ts Resolved
@github-project-automation github-project-automation Bot moved this from In progress to Changes requested in SYDevelopers Technical Roadmap Sep 7, 2026
@Ardnived Ardnived removed the awaiting label Sep 7, 2026
…ted type

Review asked for three things on #727. All three applied.

`LectureUserChoice` is gone. The row type now derives from the generated
`UserChoice`, per the rule `src/types/AGENTS.md` already carries and #659
enforced: delete the hand-written alias, use the generated interface.

`Pick<UserChoice, 'id' | 'title'>` alone would have loosened it. `UserChoice`
declares `title?: string | null`, so `Pick` makes the key optional, while the
OpenAPI schema for these rows marks `title` required. `Required<Pick<…>>`
keeps the key mandatory and its value nullable, which is what both the
endpoint and the schema already promise.

`shapeUserChoices` keeps its job but loses most of its bulk. The comment
restated what `LECTURE_FEED_POPULATE` already does, and the function's own
`flatMap` existed for a guard against a non-object row — unreachable, since
`Lecture['userChoices']` types every element as `number | UserChoice` and both
callers are TypeScript. It is a `map` over the two shapes Payload can return,
with the depth-0 id case kept: an unpopulated id becomes `{ id, title: null }`
rather than being dropped, because dropping it reports the lecture as
belonging to no user-choice at all.

Confirmed still covered: replacing that branch with `[]` turns
`keeps an unpopulated id…` and `preserves the order…` red.

The `user-choices` entry in `CACHE_TTLS` loses its three-line comment. The
reasoning lives in the PR body and on the ticket.

Gate green: lint, typecheck, typecheck:tests, 1613 unit tests. Targeted
integration: 80 across `lectures-for-audience` and `meditation-lectures`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011WhkKoQTCGvJymk1XySE9r
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-727 September 7, 2026 18:36 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

All three review comments applied. 0601358.

  • LectureUserChoice is deleted. The row type derives from the generated interface — Required<Pick<UserChoice, 'id' | 'title'>>. Pick alone would relax title to optional, and the OpenAPI schema marks it required.
  • shapeUserChoices keeps its behaviour and loses the bulk: comment down from 11 lines to 6, and the flatMap guard gone as unreachable (Lecture['userChoices'] types every element, and both callers are TypeScript).
  • The CACHE_TTLS comment is gone.

On the built-in: it is populate, already used here. LECTURE_FEED_POPULATE narrows a populated row to { id, title } at the read, so nothing is picked. What remains is collapsing the two shapes a hasMany returns — ids at depth 0, documents at depth ≥ 1. The depth-0 branch stays: dropping an unpopulated id reports the lecture as belonging to no user-choice. Removing it turns two specs red.

Gate green: lint, typecheck, typecheck:tests, 1613 unit tests. Integration: 80 across two int specs.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot
sydevs-bot requested a review from Ardnived September 7, 2026 18:38
@Ardnived Ardnived removed the awaiting label Sep 7, 2026
@sydevs-bot
sydevs-bot merged commit fee0f50 into main Sep 7, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from Changes requested to Done in SYDevelopers Technical Roadmap Sep 7, 2026
sydevs-bot pushed a commit that referenced this pull request Sep 7, 2026
Brings #727 (per-lecture userChoices in the /for-audience feed) onto this
branch after its squash-merge, so the next review round reads current code.

One conflict, in `src/lib/lectures/lectureShape.ts`: both sides rewrote the
`@/payload-types` import. This branch adds `LectureMetadata` (the generated
interface it exists to adopt); main adds `UserChoice` and the `FeedUserChoice`
alias. Both are kept — the two changes are additive and independent.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XmzSzbuPBtmPwBnsFuaoPk
sydevs-bot pushed a commit that referenced this pull request Sep 7, 2026
Brings #727 onto this branch after its squash-merge.

The one conflict was `src/payload-types.ts`, the generated file this PR exists
to stabilize. Resolved by regenerating with `pnpm generate:types` rather than by
hand — which reproduced this branch's version byte for byte, the property the PR
adds.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XmzSzbuPBtmPwBnsFuaoPk
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…ted type

Review asked for three things on #727. All three applied.

`LectureUserChoice` is gone. The row type now derives from the generated
`UserChoice`, per the rule `src/types/AGENTS.md` already carries and #659
enforced: delete the hand-written alias, use the generated interface.

`Pick<UserChoice, 'id' | 'title'>` alone would have loosened it. `UserChoice`
declares `title?: string | null`, so `Pick` makes the key optional, while the
OpenAPI schema for these rows marks `title` required. `Required<Pick<…>>`
keeps the key mandatory and its value nullable, which is what both the
endpoint and the schema already promise.

`shapeUserChoices` keeps its job but loses most of its bulk. The comment
restated what `LECTURE_FEED_POPULATE` already does, and the function's own
`flatMap` existed for a guard against a non-object row — unreachable, since
`Lecture['userChoices']` types every element as `number | UserChoice` and both
callers are TypeScript. It is a `map` over the two shapes Payload can return,
with the depth-0 id case kept: an unpopulated id becomes `{ id, title: null }`
rather than being dropped, because dropping it reports the lecture as
belonging to no user-choice at all.

Confirmed still covered: replacing that branch with `[]` turns
`keeps an unpopulated id…` and `preserves the order…` red.

The `user-choices` entry in `CACHE_TTLS` loses its three-line comment. The
reasoning lives in the PR body and on the ticket.

Gate green: lint, typecheck, typecheck:tests, 1613 unit tests. Targeted
integration: 80 across `lectures-for-audience` and `meditation-lectures`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011WhkKoQTCGvJymk1XySE9r
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
Brings #727 (per-lecture userChoices in the /for-audience feed) onto this
branch after its squash-merge, so the next review round reads current code.

One conflict, in `src/lib/lectures/lectureShape.ts`: both sides rewrote the
`@/payload-types` import. This branch adds `LectureMetadata` (the generated
interface it exists to adopt); main adds `UserChoice` and the `FeedUserChoice`
alias. Both are kept — the two changes are additive and independent.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XmzSzbuPBtmPwBnsFuaoPk

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-727 — 06013582 Deployed Sep 7, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

feat(lectures): include per-lecture userChoices in the /for-audience feed

3 participants