Skip to content

feat(meditations): transcribe a recording when it is added - #968

Merged
sydevs-bot merged 28 commits into
mainfrom
claude/feat-953-meditation-transcription
Oct 17, 2026
Merged

sydevs-bot merged 28 commits into
mainfrom
claude/feat-953-meditation-transcription

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A meditation's recording is transcribed by itself when it is added. Replacing one deletes the old transcript and asks for a new one, so no text produced from a recording nobody can hear can read as current.
  • The transcript row is the request: creating one queues the run, so no row can exist that transcribes nothing, and no caller can create one that does.
  • Reads come off meditations.transcript, a native join. There are no custom endpoints, and whoever may read a recording may read its transcript — including the narrowing that makes that sentence true for a client key (below).
  • status and error are derived from the retained job row, not stored. A finished job row now survives its run, swept weekly by CleanupJobs.
  • src/lib/retention/sweep.ts is the one definition of a retention sweep, shared by CleanupJobs and PurgeSubmissions. feat(admin): a generic job-stage edit view #960 recorded that engine as blocked on a one-consumer rule; this PR supplies the second consumer.
  • src/migrations/AGENTS.md now says how to answer drizzle's rename-vs-create prompt without a person. That guidance is what left this branch's own migration unwritten for a day.

The access narrowing (the former blocker, now closed)

A client API key read the transcript of a meditation it cannot read. Measured on c0cf3bc: a draft meditation returned 0 rows at meditations for a wemeditate-web-client key, and 1 row at meditation-transcripts.

The published-only clause and the trash filter are both per collection (accessConfigs.ts). meditations carries drafts and trash; meditation-transcripts carries neither, so the implicit project read this PR granted was unconstrained. segments is the full spoken text, and audioFilename is a public R2 key.

Option A is built (5e578b9), chosen on the measurement @Ardnived asked for. The question was whether option B — keeping clients off the collection — would still reach the transcript through the join. It would not: sanitizeJoinQuery runs the joined collection's own read and sets the join to false when it denies (payload/dist/database/sanitizeJoinQuery.js:14-22), so B takes the join field with it.

So a client read of meditation-transcripts is narrowed to its parent's state — { 'meditation._status': { equals: 'published' }, 'meditation.deletedAt': { exists: false } } — in CLIENT_PARENT_STATE_SCOPES beside the published-only clause it extends. Three things about it:

  • It is spelled against the parent relationship, not a resolved id list, because the same clause is combined into the join query on every meditation read.
  • A live-preview request is exempt, for the same reason the published-only clause beside it is.
  • A row whose meditation a hard delete has nulled matches neither key, so no client reads an orphan.

Change outline

This is the design the review settled, not the one the branch opened with. All of @Ardnived's threads are answered and landed; the four columns they replaced (status, outdated, stalled, error) are gone, as are both endpoints and the outdated machinery.

Flow — a recording is added, replaced, and re-transcribed

Two hooks, one per collection, and neither knows what the other does.

 create meditation with audio                    src/collections/Meditations/Meditations.ts
   beforeChange: extractAudioDuration
+  afterChange: syncMeditationTranscript         # the row follows the recording, and only it
+    filename unchanged → return
+    row exists for ANOTHER recording → delete it
+    create { meditation, audioFilename, language: doc.locale }

 replace the audio
+  afterChange: syncMeditationTranscript         # delete, then create — no second hook
+    the old cues go with the row                # misleading, not history

 a new transcript row                            src/collections/MeditationTranscripts/
+  afterChange: queueTranscription               # the row IS the request
+    operation !== 'create' → return             # the job write-back re-enters here
+    row created WITH cues → return              # a seed import, not a request
+    jobs.queue(task, { req })                   # inside the caller's transaction
+    update row.job = job.id                     # the job row did not exist until now
+    runQueueSoon({ afterCommit: true })

Reads — a join field, and no endpoint

- GET  /api/meditations/:id/transcript     # gone, with transcriptAccess and toTranscriptView
- POST /api/meditations/:id/transcript     # gone — a row's existence is the request
+ meditations.transcript                   # a native join, defaultLimit: 1
+ meditation-transcripts out of RESTRICTED_COLLECTIONS, into the two projects
+   that carry `meditations` — one permission, not a second one to hold
+ a client's read of it narrowed to the recording's own state (above)

#249's virtualJoinField workaround does not apply: it covers a join onto a localized relationship, and meditation-transcripts localizes nothing. The atlas project carries images and files, not meditations, so its key still reads neither — the spec asserts both directions.

Status — derived, never stored

 meditation-transcripts
+  job          relationship → payload-jobs, maxDepth: 0, admin.hidden
-  status       stored column
-  outdated     stored column
-  stalled      stored column
-  error        stored column
+  status       virtual, afterRead → deriveTranscriptStatus(segments, job)
+                 cues present            → completed   # a job can finish having written none
+                 no job row              → failed      # the queue write never landed
+                 job.hasError            → failed
+                 job.completedAt         → failed
+                 else                    → processing
+  error        virtual, afterRead → the job's own message

segments is no longer a state to tell apart: a replaced recording takes its row with it, so cues on a row are always that row's recording's.

The task throws now rather than writing a failed row (retries: 0, so nothing re-runs). The throw is what the derived status reads — catching it into a row would be a second statement of the same failure, and the one that goes stale. JobStageView (#972) gates the row on status: 'processing', with staleAfterMs: TRANSCRIPTION_STALL_MS releasing a run lost to a restart.

The job row is read through loadTranscriptJob, which narrows an id-or-row with extractID from payload/shared rather than a hand-rolled guard. It cannot be read off a populated relationship instead: field hooks run before population (payload/dist/fields/hooks/afterRead/index.js:57-58 awaits every field promise, then the population promises), so data.job is the bare id in the hook at any ?depth= — and maxDepth: 0 means the field never populates anywhere, which is what keeps an admin-only job row out of a client's answer. A join field cannot replace the read either: payload-jobs carries no relationship field, so a join has no on to name.

Job rows are retained, and swept weekly — through one engine

 payload.config.ts
-  deleteJobOnComplete: true          # dropped the row exactly when a reader needs it
+  deleteJobOnComplete: false         # global: every queue's rows now survive

+src/jobs/CleanupJobs/                # the other half — nothing else bounds the table
+  Sundays 05:00 UTC on `nightly`, after the 02:00–04:00 sweeps already there
+  sweeps: completed, or errored with no retry left, older than 7 days
+  never sweeps a queued row          # old because its waitUntil has not arrived

+src/lib/retention/sweep.ts           # what BOTH sweeps share, and nothing more
+  the cutoff, the dry-run branch, a delete whose partial failure is logged
+  beforeDelete                       # where the `users` orphan sweep reads first
-  PurgeSubmissions' own purge()      # its body was those three things

#960 settled that engine's shape and recorded it as blocked. Rule 4 puts a cross-owner module in src/lib/, and lib-boundary.spec.ts fails a src/lib/ module with exactly one consumer — which PurgeSubmissions was on main. CleanupJobs is the second, so the engine lands with the sweep that unblocks it rather than waiting on #912. What is not shared stays in each task: the slug, the schedule, the output shape, and the users orphan sweep, which payload-jobs has no analogue for.

Files

 src/collections/
 ├── MeditationTranscripts/
+│   ├── hooks/queueTranscription.ts  # a new row is a request
+│   └── status.ts                    # deriveTranscriptStatus, transcriptJobError
 ├── Meditations/
+│   └── hooks/syncMeditationTranscript.ts
 └── UserSubmissions/
-    ├── screeningQueue.ts            # its body was the string 'screening' once runQueueSoon existed
+    └── hooks/queueScreening.ts      # renamed, to match queueTranscription (review)
 src/jobs/
+├── TranscribeMeditation/            # the task, and its lemonfox/ client + languages
+└── CleanupJobs/                     # one window, swept through the shared engine
 src/lib/
+├── jobs/runQueueSoon.ts             # queue + kick, `afterCommit` instead of a delay
+└── retention/sweep.ts               # the one definition of a retention sweep
 src/plugins/access/
+└── accessConfigs.ts                 # CLIENT_PARENT_STATE_SCOPES — a child row's reach
+                                     #   ends where its parent's does

Two reads the review asked for went the other way, and are gone rather than moved: Meditations/findMeditationRecording.ts and MeditationTranscripts/view.ts each wrapped one Payload call, so each call now sits in the file that makes it.

The migration for the rewrite

20261017_102331_transcript_job_relationship adds job_id with its foreign key and index, drops status, outdated and error, and drops the now-unused enum_meditation_transcripts_status. The down reverses all four.

Until it landed, the preview booted on the old schema and every meditation save 500'd on the missing job_id column — which is what the smoke lane's meditations.e2e.spec.ts was reporting. No other lane can see it: push: true syncs the schema in dev and in both test lanes, so only a Railway boot replays this chain.

It was written unattended after all. drizzle's rename-vs-create prompt reads keypresses from a terminal, not from stdin, so --skip-empty < /dev/null and a piped newline both leave it unanswered — but over a pty it takes the highlighted default. That default is create column, which is correct here: the three dropped columns are drops, not renames. The prompt fires once per ambiguous column and again for the DOWN statements, four times in all. src/migrations/AGENTS.md now carries this, in place of the "hand it to a person" row that sent the last run away.

No migration is owed for the four review rounds above, the access narrowing included. Nothing in any of them adds a column, an enum label or a table — the retention engine moves code, the hook rename moves a file, and the narrowing is a Where built at request time.

Two earlier migrations are already on the branch, and neither touches a table, a column or a row — each adds a task-slug enum label, which is what registering a task needs:

  • src/migrations/20261016_081411_transcribe_meditation_task.ts
  • src/migrations/20261017_002341_cleanup_jobs_task.ts
  • Reversible: no — PostgreSQL cannot drop an enum label, so each down is a no-op. An unused label costs nothing

Preview

Data: not seeded yet. A preview carries no content, so the links above open on whatever you upload. The preview inherits the live Lemonfox key, which no local run has — this is the only place a real transcript can be produced.

Phases

  • The Lemonfox connection, the environment variable, the queue entry, and the unit specs
  • The one request writer, runQueueSoon, the view helpers, and the task
  • Both meditations hooks, both endpoints, OpenAPI and docs
  • The integration suite, and the review pass over the whole branch
  • The review's data-model rewrite: the join field, delete-on-replace, derived status, retained job rows
  • The migration for that rewrite
  • The second review round: the two thin reads removed, the hook renamed, one retention engine
  • The third round: the one open decision answered, and main merged in
  • The fourth round: the id guard replaced with extractID, the join-field question answered
  • The fifth round: the access narrowing, measured rather than guessed — option A, with its spec

Test results

  • Lean gate on 5e578b9: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (2565 passed, 196 files)
  • Targeted on 5e578b9: meditation-transcripts · role-based-access · meditation-transcription — 85 passed
  • The leak spec is committed now, and was watched red against the branch without the narrowing: all three rows — a draft recording's, a trashed recording's and a published one's — came back to a wemeditate-web-client key. The editor read in the same case is the control, so a narrowing that denied everyone fails it
  • ⚠ That spec also changed a fixture. _status defaults to draft, so testData.createMeditation produced drafts, and the existing access case asserted a client read that the narrowing now refuses. The fixture publishes by default; without that, the case would have gone green for the wrong reason
  • job-retention.spec.ts asserts the window rather than the constant beside it, watched red against a bare-date window — which would sweep a queued row
  • CI was red on 3e8f08a for one assertion, fixed in fce88ad: it kept the vendor's { text, start, end } key names while converting the values to milliseconds. The column stores subtitleCue — { content, startTimeMs, endTimeMs }
  • CI was red on fce88ad for the smoke lane alone — meditations.e2e.spec.ts, a 500 on create against a preview with no job_id column. The migration above is the fix
  • Build: N/A — Railway builds the preview

Manual verification

  1. On the preview, sign in as PREVIEW_ADMIN_EMAIL and upload a short recording to a new meditation.
  2. GET /api/meditations/<id>?depth=1 reaches transcript.status: "completed" with timed segments within a few minutes. This is the only check no automated lane can make — the vendor is mocked everywhere else, and LEMONFOX_API_KEY is empty in both test lanes so no run can spend a real key.
  3. Replace that recording and save. The old row is gone and a new one is processing for the new recording — there is no window in which the previous recording's cues read as current.
  4. A save that does not touch the recording leaves the row alone.

Notes for reviewer

  • One thread is open, and it is not a blocker: whether the job row can be read off a populated relationship. Answered with evidence rather than code — field hooks run before population, and maxDepth: 0 never populates — and left for @Ardnived to settle. Everything else is answered and resolved.
  • The fifth round closed the access blocker. The question was a fact, not a preference, so it was measured: under option B the join field would have gone dark, because sanitizeJoinQuery disables a join whose collection refuses the reader. Option A is what keeps "whoever may read a recording may read its transcript" true in both directions.
  • ⚠ /security-review did not run over this last push, which matches its trigger paths (src/plugins/access/). The run's lease ran out. The change is one branch, gated on req.user?.collection === 'clients' and keyed by collection slug, that replaces a true with a Where — it can only narrow, and no other caller class reaches it. Worth a sweep anyway before merge.
  • Whether the job-row read generalises was decided as option 1: loadTranscriptJob stays in status.ts, because a src/lib/ home with one consumer fails the same lib-boundary.spec.ts rule feat(admin): a generic job-stage edit view #960 hit. refactor(jobs): move the job-row read into src/lib/jobs/jobStatus.ts #983 makes the move once a second consumer clears that gate, blocked by feat(events): CSV class import as a Payload collection driven by jobs #907.
  • The task throws; it writes no failure. retries: 0, so nothing re-runs, and the throw is exactly what deriveTranscriptStatus reads off the job row.
  • status: 'failed' covers one case that is not a vendor failure: a job that completed having written no cues, because its recording was replaced mid-flight. The row it would have filled is already deleted in that case.
  • A row created with cues queues nothing (queueTranscription). That is what keeps seeds/meditation-transcripts/ from paying to re-transcribe the whole library, and the seed spec pins it.
  • job is written back in a second update, because the job row does not exist until the hook runs. That update re-enters the hook as update, which the first guard returns on.
  • A web-translator can read a transcript, unchanged: meditation-transcripts sits in the two projects that carry meditations, which is the same implicit project read a recording already had (docs/rules/access.md). The narrowing is a client clause and touches no manager.
  • Two findings filed rather than folded in: refactor(endpoints): one manager-permission gate, instead of three copies #969, the hand-rolled manager + per-locale endpoint gate — both endpoints here are gone, so requireTranscriptAccess went with them, while UserSubmissions/endpoints/review.ts and Frames/endpoints/byNarrator.ts still carry one. And refactor(jobs): move the job-row read into src/lib/jobs/jobStatus.ts #983, above.
  • The docs commit carries one caveat worth a look. An unattended session can only run what .claude/settings.json allows, and that file is a protected path — so the pty recipe needs an allowlist entry added attended before the next unattended run can use it.
  • Cleared by the fourth round's /security-review sweep and worth recording: maxDepth: 0 on job is enforced in relationshipPopulationPromise, so no ?depth= or ?populate= can populate a job row; transcriptJobError extracts only message, so no stack, input or log is exposed; no non-admin role holds create/update on meditation-transcripts, so job cannot be repointed; the only reachable error strings are our own or Lemonfox returned <status>: …, never a credential; and the vendor host is a hardcoded constant with audioFilename required to equal the meditation's own filename.
Detail

src/payload-types.ts moves for three reasons: the two task slugs, the meditations.transcript join, and the transcript row's own field set (the job relationship in, the four columns out). No column was added by hand — child 1 (#957) shipped the table.

Fixture pre-mortem. The integration suite mocks @/lib/lemonfox/transcribe, so it can drive a completed run and cannot make a paid call. The vendor body shape it claims — { segments: [{ text, start, end }] } in seconds — was verified against the one normaliser, which is the real code under those assertions. getR2Url is mocked too: CLOUDFLARE_R2_DELIVERY_URL is unset in the lane, so the real one answers undefined and the task would refuse every run before reaching the vendor.

The cue shape is the seam the CI failure was on. The vendor answers seconds under { text, start, end }; the column stores milliseconds under subtitleCue's { content, startTimeMs, endTimeMs }, closed with z.strictObject so no unknown key lands. One shape, so a player reading a transcript and one reading subtitles read the same cue (#957).

Every assertion was watched red first, against the defect it exists for: the stale-recording re-check dropped, the replaced recording's row left in place, the status derived from a column instead of the job row, a row created with cues queueing a run anyway, the normaliser's throw swallowed, the afterChange hook unwired, the task writing the meditation document, and now the client's unconstrained read of a child row.

extractID reads .id unguarded, so both call sites keep their own null check. loadTranscriptJob takes number | { id: number } | null | undefined rather than unknown; queueTranscription keeps Number(null) for a row whose meditation the foreign key has nulled.

The dry run costs one more query per window than it did, in PurgeSubmissions only. Its purge() returned the find's own docs.length; the engine counts. A dry run is an operator action, so the shared branch was worth the query.

REQUEST_TIMEOUT_MS stays at 5 minutes. #941's notes flag it against Cloudflare's 125 s proxy read timeout. That bound governs a request arriving through our zone at the origin; this is an outbound call from the Railway container to api.lemonfox.ai, made by a queued job with no HTTP client waiting on it.

The transcription queue fires at :03, :18, :33 and :48, which collides with no existing tick — two queues on one minute lose a lastScheduledRun to each other's write of payload-jobs-stats, and tests/unit/job-schedules.spec.ts enforces the stagger. CleanupJobs schedules onto nightly, whose tick is :00, at 05:00 on Sundays.

Cross-meditation dedupe is deliberately absent. The two published pairs that carry identical transcripts carry different recordings under different R2 keys, so no filename or row comparison can relate them.

Closes #953

🤖 Generated with Claude Code

https://claude.ai/code/session_01UkUssf3fUgPxg3zb5rSKa4

`src/lib/lemonfox/` rather than inside the transcription job: a job
folder's supporting code is private to that job (`src/AGENTS.md` rule 2),
and #941 wants the same connection for Path Step intro subtitles. Placing
it here serves every answer that goal's open question 3 can reach, so this
child decides nothing for it.

Two files, because `lib-boundary` counts consumers. `transcribe.ts` has
two under `src/` — the task, and the writer that must know whether
transcription is available before it promises one. `languages.ts` has one,
`transcribe.ts` next door, which is inside `src/lib/` and so exempt.

Lifted from the closed `claude/feat-881-meditation-transcripts`, with the
request changed twice:

- No `timestamp_granularities[]`. Nothing stores word timings since #957.
- The locale is mapped inside the client, so no caller repeats it.

`REQUEST_TIMEOUT_MS` stays at 5 minutes. #941's notes flag it against
Cloudflare's 125 s proxy read timeout; that bound governs a request
arriving through our zone at the origin, and this is an outbound call from
the container made by a queued job with nothing waiting on it.

`LEMONFOX_API_KEY` is optional, as every other third-party key here is. An
empty value counts as unset, and `vitest.config.mts` sets it empty so no
run can spend a real one.

The `transcription` queue's autoRun fires at :03, :18, :33 and :48, which
collides with no existing tick — two queues on one minute lose a
`lastScheduledRun` to each other's write of `payload-jobs-stats`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MK7jeN7KBvhP2yUt4usdgF
`requestTranscription` is the only place a request is written, so the
automatic enqueue and the endpoint cannot drift. It reads the row, returns
an in-flight request for the current recording untouched, and otherwise
writes `queued` and queues `transcribeMeditation` with `req` — inside the
caller's transaction, so a rolled-back write leaves no orphaned job.

Three departures from the closed `claude/feat-881-meditation-transcripts`:

- **No `sample` provider.** The branch answered a missing key with
  invented text outside production. #897 line 13 forbids exactly that, and
  #957 removed `sample` from `TRANSCRIPT_PROVIDERS`. With no key the writer
  writes `failed` with `TRANSCRIPTION_UNAVAILABLE_ERROR` and queues
  nothing — queueing a job certain to fail is dishonest latency.
- **`segments` survive a request.** The branch cleared them, on the
  invariant that segments belong to the recording the row names. Line 9
  keeps the old transcript readable until the new one is ready, so
  `audioFilename` names the request and `segments` the last *completed*
  run. The task's stale-recording guard is unaffected.
- **The task returns a `failed` row instead of rethrowing.** `retries: 0`,
  so an escaping throw left the row `processing` until the stall bound —
  the "spins forever" state line 10 forbids. The normaliser's own throw on
  a body with no timestamped speech is inside that catch.

`language` is written on every row, the no-key one included: #957 makes it
required, and the glossary hook returns the text uncorrected without it.
It is the meditation's own `locale`, which both callers already read.

`toTranscriptView` reads the stored `outdated` column rather than comparing
filenames — a comparison means nothing where a preview key prefixes them.

`runQueueSoon` generalises the screening kick, which becomes a one-line
wrapper over it. That keeps both at two consumers, so `lib-boundary`
passes, and `delayMs` is why the wrapper stays: a hook must wait for its
own commit, the endpoint is wrapped in no transaction.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MK7jeN7KBvhP2yUt4usdgF
The two behaviours #897 line 9 distinguishes, as two hooks on
`meditations`:

- `enqueueMeditationTranscription` (afterChange) fires where audio was
  added and there was none — the 2026-10-12 Decision, "by itself when a
  recording is added, with a button to redo it".
- `markTranscriptOutdated` (beforeChange) fires on a replacement and marks
  the row, inside that same save. Not at render: line 9 asks for the mark
  at the moment of replacement, and a filename comparison means nothing
  where a preview key prefixes them. It queues nothing — re-transcribing
  would destroy the text line 9 keeps readable.

Both write only `meditation-transcripts`. Nothing here touches the
meditation document (line 12): it keeps three versions behind drafts, so a
write would burn one and could publish an unfinished draft.

`markTranscriptOutdated` sits beside `extractAudioDuration` in the
beforeChange chain, which is the hook that already proves `req.file` is
readable there.

The two endpoints are manager-only and delegate every row write to
`requestTranscription`, so a double click queues one job. Both gate on the
**request** locale: a manager's roles are per locale, so a request naming
none resolves to the default and silently refuses anyone whose role lives
elsewhere (#701). The docblocks say the caller must send `?locale=`,
because that rule is written for the caller.

Neither goes in `CUSTOM_ENDPOINT_PATHS` or `docs/rules/openapi.md`: those
are owed to a public, client-facing endpoint, and the precedent for a
manager-only one is `POST /api/user-submissions/:id/review`, deliberately
absent. `meditation-transcripts` joins `ALWAYS_HIDDEN_COLLECTIONS`.

⚠ Two independent tiers now hide that collection — this list, and its
absence from every project (#957) — so the filter cases cannot catch either
one's removal alone. The new membership case is a direct assertion for
that reason, and it was watched red.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MK7jeN7KBvhP2yUt4usdgF
`tests/int/meditation-transcription.int.spec.ts` — 20 cases, deliberately a
different file from #957's `meditation-transcripts.int.spec.ts`, which
covers what the table itself enforces.

The vendor is mocked at `@/lib/lemonfox/transcribe`, so the suite drives a
completed run and cannot make a paid call. `getR2Url` is mocked too:
`CLOUDFLARE_R2_DELIVERY_URL` is unset in the lane, so the real one answers
`undefined` and the task would refuse every run before reaching the vendor.

Every assertion was watched red first, against the defect it exists for:
the `?locale=` scope dropped, the stale-recording re-check dropped,
`segments` cleared on a redo, `outdated` derived at render, the no-key path
writing placeholder text, the normaliser's throw escaping the task, the
afterChange hook unwired, the in-flight dedupe dropped, and the task
writing the meditation document.

Three states the API cannot reach, and how each is seeded:

- A **stalled** row is aged through `payload.db.updateOne`, because
  `payload.update` stamps `updatedAt` itself.
- A meditation with **no recording** is seeded through the db layer in both
  rows. Payload refuses a create with no file and `restrictUploadToAdmin`
  refuses to clear one, and the `latest: true` version row is the half that
  matters: `findMeditationRecording` reads the draft, so seeding the main
  row alone leaves the endpoint reading the recording and the case passes
  for the wrong reason — the trap `tests/utils/storeInvalidEvent.ts`
  already records.
- Each fixture meditation carries a frame, because `Meditations.frames`
  refuses an **update** that leaves none, so a recording could not
  otherwise be replaced.

⚠ #957's suite needed adapting, and two of its cases were vacuous without
it: an upload now writes a transcript row, `meditation` is unique, so the
two cases asserting a refusal were refused by that constraint rather than
by the rule under test — green, and testing nothing.

Two findings worth keeping, both from watching a case fail:

- A `web-translator` **reads** a transcript. That is implicit project read
  (`docs/rules/access.md`), not a hole this endpoint opens, and the POST
  still refuses them because transcribing is an `update`. The GET and the
  POST diverge there and nothing else in the suite would show it.
- An API client has to be called with its own API key. A `managers` session
  minted for its id refuses for the wrong reason — `clients` sets
  `disableLocalStrategy` and holds no session at all.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MK7jeN7KBvhP2yUt4usdgF
Findings from /simplify's four lenses. Behaviour is unchanged except where
noted.

- **`runQueueSoon` takes the fact, not a number.** `delayMs` made every
  caller choose a delay, so 2000 was written in three places and threaded
  through `requestTranscription`'s signature. It is now `afterCommit`, and
  the constant and its reasoning live once, beside the mechanism.
- **`runScreeningQueueAfterCommit` is deleted.** After the generalisation
  its whole body was the string `'screening'`, and its docblock had already
  moved. Its two callers call `runQueueSoon` directly.
- **The job no longer restates the recording read.** It was a byte-for-byte
  copy of the read this branch had just factored out, comment included.
  `findMeditationRecording` also moves out of the transcripts folder to
  `src/collections/Meditations/`, which is the collection whose document it
  reads — a cross-owner read parked in one owner's folder is what
  `src/AGENTS.md` rule 4 forbids. The two reads now run in parallel; neither
  feeds the other.
- **`markTranscriptOutdated` is a row-writer beside `requestTranscription`.**
  The hook reached across and updated `meditation-transcripts` inline, which
  made "one writer owns the row" untrue the moment it was written. The hook
  keeps the detection — whether a save replaces audio is `meditations`'
  knowledge — and is renamed `outdateTranscriptOnReplace` so the trigger and
  the write do not share a name.
- **`TRANSCRIPTION_UNAVAILABLE_ERROR` moves to `@/lib/lemonfox/transcribe`**,
  beside the predicate that answers for it. The job was importing the
  collection's writer — and through it the whole queue-kick machinery — to
  agree on one string.
- **The task writes `status`, `provider` and `segments` only.** It was
  re-clearing `error` and `outdated`, which `requestTranscription` is the
  only party able to set, so the row's column ownership was unreadable.
- **`lemonfoxLanguage` reduces a locale through `baseLanguage`**, the one
  spelling of that (#957), instead of a second `Intl.Locale` parse — and it
  takes a `LocaleCode`, so the try/catch for a malformed one goes with it.
  The vendor's accepted-name list stays the vendor's: deriving it from
  `LOCALES` would make a twentieth locale silently send a name Lemonfox
  refuses. A case now pins that every locale we offer maps to an accepted
  name, which is the property that catches that.
- **Two unused clock parameters go**, with the view-building that
  `isTranscriptionActive` did to read two booleans.
- **The re-entrancy guard goes.** Nothing in the enqueue path writes
  `meditations`, and the line below it already made a second pass a no-op.
- **`seedLatestVersion` is extracted** from `storeInvalidEvent`, so the
  version-row trap it documents has one implementation rather than two.

Dismissed, with reasons:

- Bound `findTranscriptRow` with a `select`. The row's `segments` are read
  2–3 times per job run and once per replacement, which for a 126-recording
  library is not worth a second code path a reader can lose `segments`
  through.
- Fold the task's final re-read into a `where`-form update. The repo has no
  such update today, and introducing one for this costs more than the read.
- Hand `requestTranscription` a pre-fetched row so the POST parallelises its
  two reads. That is a parameter one of two callers varies, to save one
  round trip on a button press.
- Drop `draft: true` from the GET's existence check. It would need a second
  recording read whose only difference is a flag, and the 404 the GET owes
  child 4 is what that read buys.
- Derive `afterCommit` from `req.transactionID` instead of asking. The
  derivation is unverifiable here — `runQueueSoon` is suppressed under
  `NODE_ENV=test`, so no spec could catch it being wrong.
- Move `normalizeLemonfoxResponse` beside the client. It is #957's module,
  placed with the collection because two writers share it, and moving it is
  #941's decision rather than this child's.
- Extract the manager + per-locale permission gate into `@/lib/endpoints`.
  It is the third copy and worth doing, but it refactors two other
  collections' endpoints — filed rather than folded in.

/security-review ran over the diff and found nothing: the gate is the first
statement of both handlers, `roleScopeFromLocale` refuses `all` and `union`,
every `overrideAccess` write is scoped to the gated meditation, the key is
never logged or stored, and the vendor URL's host and scheme come from server
environment.

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

railway-app Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

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

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

@sydevs-bot

sydevs-bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running
CI fix 3

recent dispatches
  • 18:48Z address-review · attempt 1 · session · done
  • 18:48Z address-review · attempt 1 · session
  • 18:24Z address-review · attempt 1 · session · done
  • 18:24Z address-review · attempt 1 · session
  • 16:39Z address-review · attempt 1 · session · done

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

The branch registers the `transcribeMeditation` task but shipped no
migration, so `enum_payload_jobs_task_slug` has no such label on any
database that applies this chain. The afterChange hook queues the task
inside the create, so every meditation create on the preview answered
400 `22P02 invalid input value for enum ... "transcribeMeditation"`, and
`tests/e2e/meditations.e2e.spec.ts` was the only lane that could see it:
`push: !isProduction` syncs the schema for dev and both test lanes, so
the unit and integration suites never replay the migration chain.

Generated, not hand-written. The delta is the two `ALTER TYPE ... ADD
VALUE` statements and nothing else — the snapshot differs from
20261015_070852's by exactly that label in the two task-slug enums.

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

Copy link
Copy Markdown
Contributor Author

Registering a task adds a label to enum_payload_jobs_task_slug, so this branch did need a migration. Without it the preview's database refused every meditation create with 22P02 invalid input value for enum ... "transcribeMeditation", raised while the afterChange hook queued the job.

20261016_081411_transcribe_meditation_task adds that label to both task-slug enums and nothing else. Pushed as ae49317.

Two things worth keeping:

  • The Detail block's No migration line is stale. It is the one claim in the body to ignore.
  • Only the smoke lane could see this. push: !isProduction syncs the schema for dev and both test lanes, so neither replays the migration chain.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 16, 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

This tracks #953 closely. Every module placement, the dropped sample provider, the stored outdated column and the stale-run guards are the ticket's own, and both deviations from it delete a layer rather than add one — afterCommit replaces a caller-chosen delayMs, and screeningQueue.ts is gone rather than kept as a wrapper. Twelve new modules, each one the ticket names.

One thing does not hold. outdated is cleared when a transcription is requested, not when one completes, so a failed redo leaves the previous recording's text labelled current — the contract child 4 is being built against.

Findings

  • blocker — requestTranscription.ts:49 clears outdated before the new transcript exists. Thread on that line.
  • consider — MeditationTranscripts.ts:79, outside this diff, still says segments is "cleared to null when a new transcription is requested". This PR reverses that invariant, so the comment describes a system that is gone.

What was checked

Read whole: requestTranscription.ts, view.ts, TranscribeMeditation.ts, both meditations hooks, the three endpoint files, runQueueSoon.ts, lemonfox/{transcribe,languages}.ts, findMeditationRecording.ts. Compared against #953 §1–§9 and its Interfaces, and against #957's collection on main for the outdated, language and segments columns.

Verified by grep over src, scripts, seeds: runQueueSoon has 3 importers and lemonfox/transcribe 2, so lib-boundary passes with KNOWN_SINGLE_CONSUMER untouched; sampleResponse.ts is gone; and the only collection: 'meditations' references in the new code are a hasPermission argument and a findByID read — no write.

Preview: /admin/login answers 200 and GET /api/meditations/1/transcript?locale=en answers 403 anonymously, so both endpoints are mounted.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 16, 2026
sydevs-bot pushed a commit that referenced this pull request Oct 16, 2026
The closed list's stated reason did not hold. `enqueueingFiles()` derives
the set per call, so the driven-queue case below already covers a third
site — unlike `SCHEDULED_TASKS`, whose sweep the comment borrowed the
argument from and which genuinely is hand-written.

What it did do is pin two paths that #968 makes three, so whichever of
the two PRs landed second went red — the one outcome the body claimed
could not happen.

Non-vacuity is what the case is for, and a count says it without naming
anything: `jobs.queue(` is matched as text, so a rename upstream or a
narrower `sourceFiles` would empty the set and quietly pass every
assertion derived from it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RGyh1sT84oQC5g8opVK8V8
`requestTranscription` cleared `outdated` when a transcription was
requested, so a redo after a replacement that then failed left the row
`failed`, `outdated: false`, carrying the previous recording's
`segments` — the GET reported the old transcript as the current one,
which is the contract child 4 is built against.

#953 §5 and its Interfaces both define the column as true "from the
moment the recording is replaced until a run for the current recording
completes", and §2 already has the task write `outdated: false` on
success. The writer's own clear made that write a no-op, so only the
request-time one had to go: the column defaults false, so a first row
and the no-key `failed` row are unaffected.

The redo case asserted the flip it should have refused. Two cases join
it: a failed redo keeps the old cues labelled as the old recording's,
and a completed run for the new recording clears the mark. All three
were watched red — the first two against the request-time clear, the
third against dropping the task's.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WF43x5niA7v7AdGaSFeqmY
The comment said `segments` is "cleared to `null` when a new
transcription is requested". This branch reversed that invariant so the
previous recording's text stays readable, so the comment described a
system that is gone while still explaining why the type is nullable.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WF43x5niA7v7AdGaSFeqmY
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-968 October 16, 2026 08:45 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Adopted both review findings. Pushed 98a81df.

  • blocker — outdated cleared before the new transcript existed. 8797d0b drops that line and clears the column in the task's completing write instead, so a failed redo can no longer label the previous recording's text as current. Spec line 335 asserted the flip; it now asserts the mark holds, with a failed-redo case and a completion case beside it. All three watched red.
  • consider — MeditationTranscripts.ts:79 described the segments invariant this branch reverses. 98a81df states why the type is nullable without the gone rule.

Body refreshed: the outdated column line, the task's write, Manual verification step 4, a ## Migration section, and the stale No migration line the fix-ci run flagged.

Gate green: lint, typecheck, typecheck:tests, test:unit (2433). meditation-transcription 22 · meditation-transcripts 7 · meditations 24.

🤖 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 Oct 16, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review October 16, 2026 08:59
@sydevs-bot
sydevs-bot requested a review from Ardnived October 16, 2026 08:59
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Oct 17, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Pushed bdfc5f9 — a base merge. The one open thread needed no code.

Ran: the lean gate on the merged head — lint, both typechecks, 2565 unit specs. Not run: /security-review — this push adds no code, so it matches none of its trigger paths.

Every thread on this PR is now resolved.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 17, 2026
Two hand-rolled guards did what `extractID` from `payload/shared` already
does, and the repo was already importing it in `ContentIndexBlock`. The
null check stays, because `extractID` reads `.id` unguarded.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ASR4cqCex3ynhNHLJwt4Eh
Prose is the only thing that stops the next hand-rolled copy, and two grew in
one PR without it.

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

@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.

1 question for the reviewer, one per thread.

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


Generated by Claude Code

Comment thread src/plugins/access/config/projects.ts Resolved
@sydevs-bot

sydevs-bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed c0cf3bc. Two threads answered — and the sweep found a live leak.

⚠ A client key reads the transcript of a meditation it cannot read. Measured: a draft meditation is 0 rows at meditations for a wemeditate-web-client key, and 1 row at meditation-transcripts. The published-only and trash filters are per collection; this one has neither. Question thread on projects.ts, two options, neither built — both are access-plugin edits.

  • The id guard: extractID from payload/shared. A second copy had grown in queueTranscription; both gone. 2bfd316. Resolved
  • A join field for the job read: nothing to join on — payload-jobs has no relationship field. Left open
  • src/collections/AGENTS.md now names extractID. c0cf3bc

Ran: lint, both typechecks, 2565 unit specs, three int suites (28).

The body now leads with the blocker, and its Phases carry an unticked box for the narrowing.

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


Generated by Claude Code

A client key read the transcript of a meditation it cannot read. The
published-only clause and Payload's trash filter are both per collection;
`meditation-transcripts` carries neither drafts nor `deletedAt`, so the
implicit project read #968 granted was unconstrained. `segments` is the
full spoken text and `audioFilename` is a public R2 key.

Option A of the question thread, chosen on the measurement the reviewer
asked for: `sanitizeJoinQuery` combines the joined collection's own `read`
result into the join, and disables the join outright when that result is
`false`. So option B — keeping clients off the collection — would have
taken the join field with it, and the join read is the whole point.

The clause is spelled against the parent relationship, so it rides the
join query too rather than resolving an id list per read.

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

Copy link
Copy Markdown
Contributor Author

Pushed 5e578b9 — the blocker is fixed. Option A, on the measurement you asked for.

  • Would B reach the transcript through the join? No. sanitizeJoinQuery runs the joined collection's own read and disables the join when it denies (database/sanitizeJoinQuery.js:14-22), so B takes the join field with it. A is built: a client read is narrowed to meditation._status: published and no meditation.deletedAt. Resolved
  • The populated job relationship: field hooks run before population (afterRead/index.js:57-58), and maxDepth: 0 never populates. Left open
  • A live-preview request is exempt, like the published-only clause beside it
  • The leak spec is committed now, watched red: draft, trashed and published rows all leaked

Ran: lint, both typechecks, 2565 unit specs, three int suites (85). Not run: /security-review — no lease left. The change only narrows, from one branch gated on clients.

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


Generated by Claude Code

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-968 — 5e578b9c Deployed Oct 17, 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(meditations): transcribe a recording when it is added

3 participants