Skip to content

feat(songs): store a song's audio duration, extracted on upload - #1202

Merged
sydevs-bot merged 9 commits into
mainfrom
claude/feat-1195-songs-duration
Nov 18, 2026
Merged

sydevs-bot merged 9 commits into
mainfrom
claude/feat-1195-songs-duration

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A song now stores the length of its uploaded audio in whole seconds, so a playlist row can show it.
  • The extractor Meditations already had moves to src/lib/audio/, with its 50-minute cap as a caller's option.
  • A re-runnable operator backfill gives every song stored before this change a duration.

Change outline

Contract — what songs stores and serves

 songs                                          src/collections/Songs/Songs.ts
   hooks.beforeChange
     restrictUploadToAdmin
+    extractAudioDuration()                     # no cap: a song is an album track
     autoSetIncludeForMeditationsOnCreate
   fields
     title, album, tags
+    duration: number, read-only, seconds       # ALTER TABLE songs ADD COLUMN duration numeric
     includeForMeditations, fileMetadata

A client that asks for it gets it — GET /api/songs?select[duration]=true — which is how
sydevs/WeMeditateWeb#252 reads it. No endpoint changed.

Files — where the extractor lives now

 src/collections/Meditations/hooks/
-├── extractAudioDuration.ts   # the hook, with a hard-coded 50-minute cap
 └── …

 src/lib/audio/
+└── duration.ts                 # readAudioDuration(buffer | stream) + extractAudioDuration({ maxMinutes })

 scripts/
+├── backfill-song-durations.ts  # the CLI
+└── song-durations.ts           # its routine — a one-time backfill, retired in one deletion

Songs importing the hook where it sat would be the cross-owner import src/AGENTS.md rule 4
prohibits, and two consumers is what tests/unit/lib-boundary.spec.ts requires of a module under
src/lib/. The backfill has one caller and is not app code, so it sits beside its CLI instead.

Behaviour — what each caller does with audio it cannot measure

 extractAudioDuration({ maxMinutes })           src/lib/audio/duration.ts
   no req.file → return data unchanged
   readAudioDuration(buffer, req.file.mimetype)
     throws        → warn, return data unchanged   # a save must not fail over metadata
     no duration   → return data unchanged
     over the cap  → throw                         # only where a caller passes one
   data.duration = whole seconds

 backfillSongDurations(payload, { dryRun })     scripts/song-durations.ts
   find songs where duration does not exist, trashed rows included
   no filename              → skipped, "no audio file"
   fetch(getR2Url(filename)), 60 s bound
     not ok / no body / unparseable → skipped, with the reason
     no duration stated             → skipped, "audio states no duration"
   update the row, unless dryRun

The hook holds the uploaded bytes already; the backfill holds a response, so
readAudioDuration takes either and parseWebStream stops at the format block rather than
pulling a whole track across the network.

Preview

Songs set admin.hidden: true, which unregisters their own routes — /admin/collections/songs/<id>
404s. The join on an album is the way in: open the album, then each song from its Songs list.

  • Album 1017001 — Fixture Stillness — its two tracks now differ: Fixture Opening Breath reads 42 s, Fixture Held Note 9 s. They shared one audio file before this branch, so matching durations would have proved nothing.
  • Album 1017003 — Fixture Morning Light — Fixture Damaged Interlude (no duration) carries a real MPEG header with no duration behind it, so its Duration field is blank and the save still succeeded. That blankness is the fixture's point, not a defect.
  • Meditation 1015001 — unchanged: meditations still extract a duration, and still refuse audio past 50 minutes.

Contract impact

src/payload-types.ts gains Song.duration. sydevs/WeMeditateWeb#252 is the consumer and
carries the matching Blocked by: line; the dispatcher re-syncs the copied types after this
merges.

Migration

  • New migration: src/migrations/20261118_181435_add_songs_duration.ts
  • Impact: one ADD COLUMN "duration" numeric on songs. No rename, no data touched. Songs
    configures no versions, so there is no version table to carry it.
  • Reversible: yes — down drops the column, and nothing but this branch reads it.

Test results

  • Lean gate: ✓ .claude/skills/pr-prep/check.sh — lint, format, typecheck, typecheck:tests, 3796 unit tests
  • Targeted specs: ✓ song-duration, meditation-duration, fixture-load, albums, meditation-songs (43 cases)
  • Build: N/A — Railway builds the preview

Every new assertion was watched failing first: unmounting the Songs hook reddens three cases in
song-duration.int.spec.ts, moving the cap to 100 minutes reddens the Meditations case, and
dropping the backfill's response.ok check reddens its skip case.

Manual verification

  1. Open each preview link above and check the stored duration against the file.
  2. GET /api/songs?select[title]=true&select[duration]=true&depth=0&limit=5 on the preview, with a client key — each row carries a number.
  3. The backfill runs against a real database and is not exercised on the preview. pnpm tsx scripts/backfill-song-durations.ts is a dry run that writes nothing; --force writes.

Notes for reviewer

Three design calls worth your eye, each raised by the review pass and kept deliberately:

  • fileMetadata is not where this went. The ticket settles it — only the storage adapters and
    seed importers write that column, and a stored, typed number is what a client can select.
    Video duration does arrive through fileMetadata (the Stream adapter writes it), so audio and
    video now answer "how long is this" two ways. Moving audio into the R2 adapter's handleUpload
    would unify them for all eight upload collections; it is a bigger change than this ticket, and
    files, user-choices and song-tags get no duration until someone makes it.
  • The column and its hook are declared separately, rather than by one audioDurationField()
    factory. A field-level beforeChange runs after every collection hook (feat(events): enforce one lifecycle table for events and submissions #1121), which would put
    the write after cacheMeditationNodeWeights — and that hook computes weights against the
    duration the save is about to store. A factory declaring only the column would be a middle
    layer, so neither form was taken.
  • The cap stayed an option on the shared extractor, per the ticket, rather than becoming a
    refusal Meditations owns. It is now MAX_MEDITATION_MINUTES in Meditations.ts, unexported,
    and the Lemonfox timeout comment points at that name and file rather than at a literal.

Dismissed with reasons: a concurrent backfill loop (sequential is fine at this catalogue size,
and it keeps the dry-run report in id order); folding tests/unit/music-metadata.spec.ts into the
new spec (it is pre-existing and pins the library itself, WAV included); and generalising the
backfill to any collection (nothing asks for it yet).

Security review ran — the diff touches src/collections/*/hooks/ — and found nothing. The only
new outbound call composes its host from CLOUDFLARE_R2_DELIVERY_URL and its path from a
slugified R2 key, and the routine is reachable only from the operator script.

Detail

Why a second fixture audio file. All five fixture songs shared fixture-audio.mp3, so every
song would have shown 42 s whether extraction worked or not. fixture-audio-short.mp3 is 9 s,
18 KB, generated silence.

Why tests/files/audio-51m.mp3 is 4 KB. music-metadata reads an MP3's length from the Xing
header in the first frame, so a 51-minute file truncated to 4 KB still states 51 minutes. The case
it supports pins maxMinutes: 50 on Meditations, which the unit lane cannot see.

Fixture pre-mortem. The new entries assume songs accepts audio/mpeg and that Payload sniffs
the bytes rather than trusting the declared type. Checked against src/collections/Songs/Songs.ts
(upload.mimeTypes) and node_modules/payload/dist/uploads/checkFileRestrictions.js — a file that
sniffs as text is refused whatever its extension, which is why fixture-audio-no-duration.mp3
carries a real MPEG frame header — it parses, and states no duration.

Closes #1195


Generated by Claude Code

A Song stored no duration, so every playlist row in the music library on
wemeditate.com rendered `0:00` (sydevs/WeMeditateWeb#252 reads the field
and waits on this). Meditations already extracted one from the uploaded
buffer; the machinery was one collection away from reuse.

`extractAudioDuration` moves out of `src/collections/Meditations/hooks/`
into `src/lib/audio/duration.ts` and becomes a factory taking the cap as
an option — Meditations passes 50 minutes, Songs passes none, because
that cap is a meditation rule. Importing it from Songs where it sat would
have been the cross-owner import `src/AGENTS.md` rule 4 prohibits, and
two consumers is what `lib-boundary` requires of a module under
`src/lib/`.

`readAudioDuration` splits out of it so the backfill parses the same way
the hook does, with each caller deciding what an unparseable file means:
the hook warns and leaves the save alone, the backfill reports the row
and carries on.

The hook fires on an upload, so songs stored before it carry no duration.
`backfillSongDurations` reads each one's stored audio and writes the
length it states, behind `scripts/backfill-song-durations.ts` — dry run
by default, `--force` writes, and a song that already holds a duration is
never fetched.

Two fixture audio files land with it: all five fixture songs shared one
file, so identical durations would have proved nothing, and one song now
carries a real MPEG header with no duration in it, which is what a
corrupt upload looks like to a reviewer.

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

Review pass over the branch.

The backfill downloaded each whole track to read a header. `readAudioDuration`
now takes a stream as well as a buffer, so `parseWebStream` stops at the format
block and the rest of the body is never pulled; the response's own content-type
goes with it, and a stalled transfer is bounded rather than hanging an
operator's run for ever. Its result drops `scanned`, which was always
`written.length + skipped.length`, and splits the two row shapes so a row
carries either a duration or a reason, never both. A missing
`CLOUDFLARE_R2_DELIVERY_URL` is one failure before the loop rather than the
same skip reason repeated per song, and the script exits through
`exitAfterFlush`, which is what keeps a few hundred lines of report from being
truncated on a pipe.

Meditations' 50 minutes becomes `MAX_MEDITATION_MINUTES`, so the Lemonfox
timeout comment points at a name that can be grepped rather than at a literal
inside a 600-line config.

The int spec's two hand-mocked hook cases went: the unit spec covers them
without a schema bootstrap. Its own upload helper went with them, in favour of
`testData.createSong` and a copy of the corrupt sample under `tests/files/`,
which is where test audio lives. The backfill spec reads its audio from there
too; `audio-duration.spec.ts` keeps reading `src/fixture/files/`, because what
a reviewer sees on each fixture song is exactly what it asserts.

The corrupt fixture song now says so in its title, so a reviewer opening the
preview can tell a deliberate blank duration from the defect this fixes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjWAgPrgD8ZLRKq8E68
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1202 November 18, 2026 18:38 Destroyed
@railway-app

railway-app Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated
SahajCloud 😴 Sleeping (View Logs) Web Nov 18, 2026 at 9:41 pm UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot

sydevs-bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 21:08Z resolve-conflicts · attempt 1 · session · done
  • 21:08Z resolve-conflicts · attempt 1 · session
  • 19:46Z address-review · attempt 1 · session · done
  • 19:46Z address-review · attempt 1 · session
  • 19:04Z address-review · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 18, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 Adversarial review

The diff is the ticket and no larger: one moved extractor, one column, one hook, one migration, one backfill. It also removes two hook cases from the int lane into tests/unit/audio-duration.spec.ts, where they belong. The ladder found nothing to fold away — readAudioDuration has two callers taking different inputs, and backfillSongDurations is the thin-wrapper shape lib-boundary.spec.ts exempts by name.

The contract holds. Song.duration is additive, and WeMeditateWeb composes its own select for songs (server/content-index.ts:68), so the consumer gains the field by adding one key. "No endpoint changed" is correct.

All three findings are claims the diff's own evidence contradicts. None is a design problem.

Findings

  • should-fix src/fixture/songs.ts:8 — "unreadable" is wrong in four places. The file parses; it states no duration.
  • should-fix src/collections/Songs/Songs.ts:109 — the editor-facing description says "every save". The hook reads only on an upload.
  • consider src/collections/Meditations/Meditations.ts:116 — MAX_MEDITATION_MINUTES is exported, and nothing imports it.

What was checked

Read whole on the branch: duration.ts, backfillSongDurations.ts, the script, Songs.ts, both new specs, fixture/songs.ts, albums.ts, content-ids.ts. Ladder walked on readAudioDuration, the backfill routine, the new constant, both fixture audio files. Consumer side followed into WeMeditateWeb server/content-index.ts and sahajcloud-client.ts. getR2Url's unset branch checked against urlFields.ts:101. Migration read: one ADD COLUMN, down drops it. All three preview links answer ON_HOST, and ids 1017001, 1017003 and 1015001 each exist under src/fixture/, showing what each line claims. This checkout has no node_modules, so nothing needing one was asserted.

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


Generated by Claude Code

Comment thread src/fixture/songs.ts Resolved
Comment thread src/collections/Songs/Songs.ts Resolved
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 18, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 18, 2026
The file starts `ff fb 90 00`, a valid MPEG frame header, and
`readAudioDuration` resolves `undefined` for it rather than throwing. Only
`Buffer.from('not audio')` is unparseable anywhere in this branch, so
"unreadable" named a branch these bytes never take.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYNtutVUAzXq8hd6qB
The hook returns early when `req.file` is absent, so a save uploading no
file reads nothing and keeps the stored value. The description claimed
every save, and it reaches both the admin panel and the generated type's
JSDoc.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYNtutVUAzXq8hd6qB
Nothing imports `MAX_MEDITATION_MINUTES`, and the cap is Meditations' own.
The Lemonfox timeout comment names its file beside the symbol, so the
breadcrumb survives the constant being private.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYNtutVUAzXq8hd6qB
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1202 November 18, 2026 19:10 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Addressed all three review findings. Each is its own commit, and each thread carries the detail.

The branch was already on the current main, so no merge was needed. Lean gate green (3796 unit tests), plus song-duration, fixture-load and meditation-duration (22 cases). Body refreshed where the rename made it false.

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


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 18, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review November 18, 2026 19:21
@sydevs-bot
sydevs-bot requested a review from Ardnived November 18, 2026 19:21
@sydevs-bot
sydevs-bot enabled auto-merge November 18, 2026 19:21
@sydevs-bot sydevs-bot moved this from Pending to Awaiting in SYDevelopers Technical Roadmap Nov 18, 2026
Comment thread scripts/song-durations.ts Resolved
Comment thread src/collections/Songs/Songs.ts Resolved
Comment thread src/collections/Songs/Songs.ts Resolved
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 18, 2026
sydevs-bot and others added 2 commits November 18, 2026 19:50
A one-time backfill left in src/lib/ is app code nothing in the app calls,
and retiring it would need a PR of its own. Beside its CLI it is one
deletion, and the unit spec still covers it there — the shape
challenge-mounts.ts and preview-domain-plan.ts already use.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjWD6khx11V4rCcXh7D
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1202 November 18, 2026 19:55 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Four threads answered — two adopted, two answered with the code.

Merged current main in (clean). Lean gate green — 3796 unit tests — plus song-duration and meditation-duration (15 cases).

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


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 18, 2026
Ardnived
Ardnived previously approved these changes Nov 18, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Pending in SYDevelopers Technical Roadmap Nov 18, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 18, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 18, 2026
Both sides added a migration, so `src/migrations/index.ts` conflicted. Both
are kept, in timestamp order — they are independent.

The data-only migration main added re-stamps the previous migration's
snapshot, and after this merge the previous migration is this branch's. Its
`.json` is re-copied from `20261118_181435_add_songs_duration.json` for that
reason. Left as main wrote it, it is the newest snapshot by timestamp and
states no `songs.duration`, so the next `migrate:create` on main re-emits
`ALTER TABLE "songs" ADD COLUMN "duration"` — the replay that aborts a boot
migration (#566). Watched it emit exactly that, then verified a probe writes
nothing against the re-stamped snapshot.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXaZcpX2oGt8egpGWS
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1202 November 18, 2026 21:15 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged main in. One conflict: src/migrations/index.ts, where both sides added a migration. Both are kept, in timestamp order — they are independent.

One change the diff does not explain. The data-only migration main added (20261118_210000_wm_web_new_tab_one_key) carries a re-stamped copy of the previous migration's snapshot, and after this merge the previous migration is this branch's. Its .json is re-copied from 20261118_181435_add_songs_duration.json.

Left as main wrote it, that file is the newest snapshot by timestamp and states no songs.duration, so the next migrate:create on main re-emits ALTER TABLE "songs" ADD COLUMN "duration" — the replay that aborts a boot migration (#566). I watched it emit exactly that with main's copy in place, then confirmed a probe writes nothing against the re-stamped one.

Lean gate green (3813 unit tests). song-duration, meditation-duration, fixture-load, meditation-songs and main's expire-events pass on the merged tree (66 cases).

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


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 18, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1202 — befe7512 Deployed Nov 18, 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(songs): store a song's audio duration, extracted on upload

3 participants