Skip to content

feat(meditations): add /api/meditations/:id/lectures endpoint - #324

Merged
Ardnived merged 6 commits into
mainfrom
feat/322-meditation-lectures-endpoint
Apr 28, 2026
Merged

Ardnived merged 6 commits into
mainfrom
feat/322-meditation-lectures-endpoint

Conversation

@Ardnived

Copy link
Copy Markdown
Contributor

Summary

  • Adds GET /api/meditations/:id/lectures — context-aware lecture-clip
    selection that ranks clips by topical overlap between the meditation's
    on-screen subtle system nodes and each lecture's subtleSystemNodes.
    Optional userChoice query param restricts candidates to clips whose
    parent lecture has that user-choice in its userChoices hasMany.
  • Caches per-meditation weights as a subtleSystemNodeWeights JSON
    field on Meditations, kept in sync by afterChange hooks on both
    Meditations (frames/duration changes) and Frames (subtleSystemNode
    repointing). Loop-prevented via context.skipRecomputeNodeWeights.
  • Schema-only migration with a backfill loop (per the design discussion
    in feat(meditations): GET /api/meditations/:id/lectures — context-aware lecture-clip selection #322 — eager backfill so read-heavy callers hit warm caches from
    day one).
  • Reuses LectureClipPlayerData / mergeSubtitles / resolveThumbnailUrl
    via a new shared src/lib/lectureClipShape.ts so both the new endpoint
    and /api/lectures/for-audience consume one shape contract.

Closes #322

Test Results

  • Unit/Integration tests: 592 passed (38 files), 0 skipped
    • 9 new pure-helper tests (computeMeditationNodeWeights)
    • 10 new endpoint integration tests (meditation-lectures.int.spec.ts)
    • 2 new shape-sync assertions on the api-explorer (audience param sync
      • clip-only $ref + path/optional-param shape)
  • E2E tests: not applicable (no UI changes)
  • Build: ✓ Success
  • Pre-existing failures fixed: none — main was clean

Test plan

  • pnpm payload migrate — applies cleanly locally; backfill writes
    weights for every existing meditation
  • curl 'http://localhost:3000/api/meditations/<id>/lectures?limit=10&pathProgress=...&meditationsPerWeek=...&totalMeditationsViewed=...&totalLecturesViewed=...'
    → returns clips sorted descending by overlap weight
  • Add &userChoice=<id> → only clips whose parent lecture has that
    user-choice
  • Add &excludedLectureClipIds=<id1>,<id2> → those IDs absent from
    results
  • Edit a meditation's frames in admin → subtleSystemNodeWeights
    reflects the change
  • Repoint a frame's subtleSystemNode in admin → all referencing
    meditations' weights update

🤖 Generated with Claude Code

Ardnived and others added 6 commits April 28, 2026 21:03
Adds a context-aware lecture-clip selection endpoint that ranks clips
by topical overlap between the meditation's frames and each lecture's
subtleSystemNodes. Optional userChoice gate restricts to clips whose
parent lecture is tagged with that user-choice.

- New `subtleSystemNodeWeights` JSON cache field on Meditations
- Recompute hooks on Meditations (frames/duration change) and Frames
  (subtleSystemNode change) keep the cache in sync; loop-prevented via
  context.skipRecomputeNodeWeights
- Endpoint reuses LectureClipPlayerData/mergeSubtitles/resolveThumbnailUrl
  via a new shared module src/lib/lectureClipShape.ts
- Pure helper computeMeditationNodeWeights for testability
- OpenAPI shim entry for the new endpoint

Closes #322 (partial — migration + tests follow)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Schema-only ALTER TABLE for `meditations.subtle_system_node_weights`
plus the versions companion. Augments the generated migration with a
backfill loop that walks every meditation, computes weights via
recomputeWeightsForMeditation, and persists — so read-heavy callers hit
warm caches from day one instead of paying per-meditation lazy-compute
on first request.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…, OpenAPI shim

- 9 unit tests for the pure computeMeditationNodeWeights helper covering
  the timeline window logic, null/unpopulated frame handling, zero-window
  frames, and duration edge cases.
- 10 integration tests for the endpoint: deterministic ordering by
  weight, userChoice gate, excludedLectureClipIds, audience filtering,
  404, lazy fallback, Frames cascade hook, response shape.
- Extends the api-explorer audience-param-sync test to cover the new
  path, and adds focused assertions for the path id, optional
  userChoice/excludedLectureClipIds params, and the single-$ref
  (clip-only) response shape.

Hook tweaks discovered while writing tests:
- Drop the redundant `operation === 'create'` short-circuit on the
  Meditation afterChange hook — the diff guard already detects new
  frames, and firing on bare creates tripped the `frames` field's
  required-on-update validator.
- Skip the recompute when the meditation has no frames (would be a no-op
  anyway).
- Cascade hook on Frames now fetches full meditation docs (not just
  `frames`) so `recomputeWeightsForMeditation` has access to `duration`.
- Endpoint passes `locale: req.locale ?? 'en'` to clip + parent finds so
  localized fields resolve consistently across HTTP and direct-handler
  test calls.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… from review

- Frames cascade: drop the limit:1000 cap on the meditation scan; use
  limit:0 + pagination:false to match the rest of this PR so frames shared
  by many meditations don't silently skip the recompute.
- Endpoint: log findByID errors before returning 404 — non-NotFound DB
  errors now reach the logger / Sentry instead of being masked.
- Endpoint: drop the lazy-persist side-effect; the migration backfill plus
  the afterChange hooks keep the cache fresh, so a missing cache falls
  through to an ad-hoc compute and the GET stays side-effect-free.
- Endpoint: cache extractID(clip.lecture) per clip; remove the redundant
  locale:'all' on findByID (filterMeditationsByLocale already skips
  findByID, so the arg has no effect).
- Hooks: tighten frame-id handling to number[]; SQLite auto-increment is
  always numeric in this codebase.
- Drop the backwards-compat re-export block in lecturesForAudience.ts;
  tests now import shape helpers directly from @/lib/lectureClipShape.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e endpoint slug

Endpoint:
- Rename `/api/meditations/:id/lectures` → `/api/meditations/:id/related-lecture-clips`
  for a more explicit, consumer-facing URL.
- Read topical tags from `clip.subtleSystemNodes` (replace mode) instead
  of `parent.subtleSystemNodes`. Clips with no tags get weight 0 and are
  excluded — gives editors per-clip control over ranking.

Schema:
- Add `subtleSystemNodes` hasMany relationship to LectureClips. Schema-only
  migration (no backfill) — existing clips start untagged and surface only
  after editors tag them.
- Lecture-level `subtleSystemNodes` stays for admin browsing; it's just
  no longer read by the meditation-lectures endpoint.

Refactors:
- Co-locate `computeMeditationNodeWeights` (and its `FrameWithNode` type)
  inside `meditationHooks.ts`; delete the stand-alone lib file. Single
  consumer + test, so co-location matches the codebase convention.
- Simplify the OpenAPI description on the renamed endpoint to focus on
  consumer behavior (what to pass, what comes back) instead of the
  internal weighting / userChoices / tie-break implementation details.

Tests pass: 106 in the affected suites; lint + tsc clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Ardnived
Ardnived merged commit 296c935 into main Apr 28, 2026
@Ardnived
Ardnived deleted the feat/322-meditation-lectures-endpoint branch April 28, 2026 15:51
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.

feat(meditations): GET /api/meditations/:id/lectures — context-aware lecture-clip selection

1 participant