Skip to content

fix(access): scope meditation edits to the editor's language - #999

Merged
sydevs-bot merged 38 commits into
mainfrom
claude/fix-980-meditation-locale-writes
Oct 27, 2026
Merged

sydevs-bot merged 38 commits into
mainfrom
claude/fix-980-meditation-locale-writes

Conversation

@sydevs-bot

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

Copy link
Copy Markdown
Contributor

Summary

  • A per-locale meditations-editor can no longer write a meditation in another language.
  • Closes the duplicate route too, which states no language and clones the source's.
  • POST :id/transcribe is scoped the same way — the one door a Where does not reach (review, 2026-10-26).
  • Version history follows the same scope, derived rather than written.
  • A top-level column named locale IS the document's own language — that is the whole opt-in, with nothing declared per collection and no list anywhere (review, 2026-10-26).
  • Two columns were renamed to keep that true: Clients.locale → Clients.language (review, 2026-10-25) and imports.locale → imports.uploadLocale (review, 2026-10-26).
  • Joined, docs only: src/migrations/AGENTS.md's outcome table had no row for the rename prompt refusing a redirected stdin, which is what this push's migration hit.

Change outline

The access layer gains one more narrowing, in the same place as the two it already has: the grant decides whether, this decides which rows. A hook covers the create the access function cannot answer for. Both halves live in src/plugins/access/localeScopedWrites.ts, beside regionSubtreeAccess.ts, and reach a collection because that collection carries a top-level locale field at all — no collection wires a hook or an access rule, and none declares anything either.

Behaviour — createAccessConfig's per-operation access function

 access[operation]({ req, id, data })           src/plugins/access/accessConfigs.ts
   hasPermission({ …, locale: roleScopeFromLocale(req.locale) })
   granted →
     read + client + drafts           → { _status: 'published' }
     write + manager + regions|events → scopeRegionSubtreeWrite(…)
+    write + manager + locale-scoped  → scopeLocaleWrite(operation, locale, data)
+      create → data.locale absent, or equal to the role's locale   # boolean
+      update | delete → { locale: { equals: <the role's locale> } } # Where
     user-submissions + manager       → managerSubmissionScope(user.id)
     else → true
   denied → the document-manager fallback, else false

Flow — the two moments a create's language can arrive

The access gate runs before the field pass, so it can only answer for a create that states a language. duplicate states none and then clones the source document's.

 createOperation(data)                          node_modules/payload/…/create.js
   executeAccess({ data }, access.create)
     scopeLocaleWrite('create', 'fr', …)
       data.locale stated → must equal 'fr'     # refused here, one layer early
-      data.locale absent → allowed, and the default was assumed to fill it
+      data.locale absent → allowed; nothing is known yet
   beforeValidate — FIELDS                      # the language exists only from here
     getFallbackValue(locale)                   # fills an `undefined` value only
       duplicate     → cloned from the SOURCE doc    # NOT the default
       ordinary create → defaultValue ⇒ req.locale
+  beforeValidate — COLLECTION                  # appended by accessPlugin
+    restrictCreateToRequestLocale               src/plugins/access/localeScopedWrites.ts
+      no top-level `locale` column → stands down
+      non-admin manager + data.locale !== req.locale → 403   # the complete rule
   beforeChange …

The one door a Where does not reach — POST :id/transcribe

main added POST /api/meditations/:id/transcribe after this branch opened (#984, #1011). It proves meditations: update in req.locale and then reads the meditation and writes meditation-transcripts with overrideAccess, so the access function's clause reaches none of it — the grant this PR narrows everywhere else stayed collection-wide there alone, and a fr-only editor could delete an en meditation's transcript and buy a new paid run.

 meditationTranscribe(req)               src/collections/Meditations/endpoints/transcribe.ts
   requireManagerPermission(meditations, update)  # a grant, in req.locale — never a language
   findByID(id, { overrideAccess: true })
+  isOutsideWritableLocale(req, meditation.locale) → 403
   phase / cooldown refusals                      # 409, 429
   initTransaction → delete the old transcript, create the next

The refusal sits ahead of every other refusal and ahead of the transaction, so a refused caller reaches no delete, no create and no queued run — a case asserts the previous transcript is still the one that was there. isOutsideWritableLocale is the predicate restrictCreateToRequestLocale already needed, so the comparison has one home rather than two.

The Transcript tab hides the Transcribe-again button on the same condition (mayTranscribeLocale) — a button that can only answer 403 is what the access layer avoided for Save. Mirrored there rather than imported: the module owning the refusal pulls payload in with it, and the tab is a 'use client' component.

Scope — which collections this reaches

The reviewer's second call on 2026-10-26 was to make the rule the column's name, document it, and delete the machinery that asked each collection to declare its meaning. So nothing declares anything:

-Meditations.locale   custom: localeColumn('document-language')   # declared, per field
-imports.locale       custom: localeColumn('unrelated')
-                     undeclared → scoped by nothing, and the int guard goes red
+Meditations.locale            # a top-level `locale` column, so the writes are scoped
+imports.uploadLocale          # the admin locale of an upload — renamed, so it is not one (#912)
+clients.language              # a service's preferred language — renamed on 2026-10-25
 Lectures.subtitles[].locale   # a row key inside an array — no top-level rule reaches it

isLocaleScopedCollection is now one flattenedFields.some(field => field.name === 'locale'), and with it go localeColumn, LocaleColumnMeaning, localeColumnMeaning, the undeclared verdict and the WeakMap that memoized the declaration walk. The module is 113 lines, down from 160.

The rename is what makes the documented rule true. imports.locale was the one counterexample — the admin locale an upload happened in, which says nothing about who may write the row — so a presence rule would have scoped that collection the day it took a write grant. It is uploadLocale now, by the same argument that renamed Clients.locale two rounds ago, and docs/rules/access.md states the invariant where a field author meets it: never spell a column locale unless it is the document's own language.

A new column could still arrive, so the int guard changes question rather than going away: role-based-access.int.spec.ts walks the booted config and names every collection carrying a top-level locale — meditations alone — so a second one reds the suite until someone confirms the column really is a language. It needs the booted config because imports is plugin-created and so absent from the src/collections barrel.

Renames — two columns that were not document languages

Neither collection is localized, and both columns read as Payload's localization locale, which is what drew three review rounds asking whether the scoped set could be derived from the column's presence. It can — once the names tell the truth.

-clients.locale               enum_clients_locale
+clients.language             enum_clients_language
-_clients_v.version_locale    enum__clients_v_version_locale
+_clients_v.version_language  enum__clients_v_version_language
 _clients_v.published_locale  # Payload's own localization column — untouched
-imports.locale               varchar, no index, no enum type
+imports.upload_locale        # the admin locale at the upload, read by the import job alone

Both migrations are hand-written, and that is the point. Payload's generator adds the new column and drops the old one, which blanks the value on every row already in the database — every service's configured language, and the locale of any import still pending at the deploy, which would then create its classes in the default language instead of the uploader's. ALTER TABLE … RENAME COLUMN carries the values across, and for clients ALTER TYPE … RENAME TO carries the enum: both member lists are byte-identical either side (183 codes, same order — only the field's name changed), so nothing is retyped and no row is recast. Neither column carries an index. Each generated .json snapshot records the same end state a rename produces and is kept as generated; a probe db:migrations:create on the result writes no files, so the chain is clean.

Types — the scope a Where is built from

roleScopeFromLocale's body only ever returned a locale code; its declared type made every caller write an unreachable branch for the one member it cannot return.

-roleScopeFromLocale(locale: string | undefined): RoleScope | undefined   # RoleScope = LocaleCode | 'union'
+roleScopeFromLocale(locale: string | undefined): LocaleCode | undefined

RoleScope stays the parameter type of a permission check, where a caller may still state 'union' deliberately (admin nav visibility).

Preview

Verifying this by hand needs a per-locale editor and two meditations, and a fresh Railway preview carries neither — this repo configures no previewUrl.seed, so there is nothing to run. Data: not seeded yet. The links open the right screens; creating the records is step 1 of Manual verification below.

  • Managers list — where the French-only editor is created; the admin locale selector is top right
  • Meditations list — empty on a new preview
  • Services list — the renamed field is Language, in the Sahaj Atlas collapsible

Test results

  • Lean gate: ✓ pnpm lint, pnpm format:check, tsc --noEmit, tsc -p tsconfig.test.json, 229 files / 2935 unit tests (77 s)
  • Targeted specs: role-based-access, event-imports and meditations — 132 passed
  • Migrations: migration-validator 4 pass / 1 warn on the new one — the warn is RENAME, which is the change
  • Security review: no exploitable path. It read both halves of this push and traced the presence rule end to end: nothing request-controlled reaches the verdict (both call sites pass booted-config flattenedFields), meditations still answers true through its unnamed tab, the duplicate hook is still attached to every collection, and the change's net direction is more scoping rather than less — an undeclared column used to be scoped by nothing. It enumerated the collections carrying a top-level locale three independent ways (grep, the generated types, the booted config) and found only meditations, and diffed the new snapshot against the previous one across every table: the sole difference anywhere is imports.locale becoming imports.upload_locale.
  • Build: N/A — Railway builds the preview

Each guard was watched failing. With the access branch disabled, 7 of the 12 cases go red; the 5 that stay green are the controls for what must not change — the editor's own-language update and create, the Create button's capability check, an admin in either locale, and narrators. With only the beforeValidate hook unwired, exactly one case goes red, on expected 200 to be 403. This push watched the new invariant guard: with imports.uploadLocale spelled locale again it reds on ['imports', 'meditations'] against ['meditations'], which is the whole protection the declaration used to give.

Manual verification

  1. Sign in as an admin. Create a manager with type: manager holding meditations-editor in French only — roles is per locale, so switch the admin locale selector to French before ticking it. Create two meditations, one with the admin in English and one in French.
  2. Sign in as that editor. Payload lands them in French, the only locale they hold a role in.
  3. Open the English meditation by its URL (/admin/collections/meditations/<en id>). No Save button, and no History tab.
  4. Open the French meditation. Save works, and its History tab lists its versions.
  5. Still as that editor, use Duplicate on the English meditation. It is refused, and no new meditation appears in English.
  6. The transcribe door. Upload a recording to each meditation as an admin, so each has a Transcript tab. As the French editor, open the English meditation's Transcript tab: no Transcribe-again button, in any phase. POST /api/meditations/<en id>/transcribe?locale=fr answers 403 and the existing transcript is untouched. On the French meditation the button is there and works.
  7. As an admin, edit the English meditation with the admin in French. It still saves, and its Transcribe-again button is still offered.
  8. A class import is untouched by any of this. As an Atlas manager with the admin in French, upload a CSV: the classes are created in French, as before — the column it reads is uploadLocale now, and imports writes are scoped by region, never by language.
  9. Both renames carry data. On an environment with existing rows — not a fresh preview — set a service's Language and leave an import pending, deploy, and confirm each value is still there: the migrations rename the columns rather than replacing them. pnpm payload migrate:down puts each back under locale.

Notes for reviewer

  • The open thread is where the file goes. The simplification is built; what is left is three things that are not classification — the access clause, the create hook, and the predicate transcribe shares with it — so "eliminate the file" is a choice between keeping it and splitting those across accessConfigs.ts and a hook-named module. Your call on that thread; nothing is built for either.
  • create answers with a boolean on purpose. executeAccess treats any object as a grant, so a Where there would allow every language.
  • An absent locale has to pass the access gate, or the collection-level capability check — which carries no data at all — would hide the Create button from every per-locale editor. A case pins that it stays true.
  • The create arm is defence in depth, not a forced split. restrictCreateToRequestLocale is the complete rule: the field pass fills only an undefined value (beforeValidate/promise.js:182), so a stated locale reaches the hook untouched and is refused there too. The arm is kept because an access config scoping update and delete but not create reads as an oversight to the next reader, and it refuses a stated language one layer earlier. Nothing depends on it alone.
  • A refused single-document update is a 403, not a 404. updateByID reports a Where policy that matched nothing as a refusal. Read off node_modules/payload/dist/collections/operations/updateByID.js, not assumed.
  • The hook runs on every collection's create and now asks a one-line question. The verdict is no longer memoized: a WeakMap earned its place while the answer cost a walk for a declaration, and a field.name === 'locale' comparison over the same flattened list does not.
  • One ordering coupling is worth knowing before the list ever widens. In createAccessConfig the locale branch returns before the user-submissions one, so a top-level locale column on that collection would replace managerSubmissionScope's row restriction with a language clause. No such column exists, and the int guard reds the day one does — its docblock carries this, since that guard is where somebody will be deciding.
  • One thing deliberately left permissive, and why. isOutsideWritableLocale refuses nothing over an absent or non-string language, and scopeLocaleWrite's create arm already allows data.locale == null — the Create-button reason above. So a draft create stating locale: null could in principle land a language-less row that any editor's transcribe call then passes. Nothing is built for it: locale is required, so the row can never be published; access: { update: () => false } means it can never be promoted to a real language; filterMeditationsByLocale hides it and the update clause does not match it, so not even its author can edit it. It grants no authority over any other language's content. Say if you want it closed anyway — the place would be the create hook refusing an absent value, not widening the predicate the endpoint also calls.
  • Neither rename is visible to any consumer's code. WeMeditateWeb and SahajAtlasWeb both commit a copy of payload-types.ts, which audit-contracts resyncs on merge, but neither repo reads either field: SahajAtlasWeb's ClientSchema deliberately omits clients.language and strips it on parse, and imports is restricted and in no project, so no client key has ever seen it. One downstream touch-up remains, and it is prose only: that schema's comment and its spec name the field locale, which stops being SahajCloud's spelling the moment this merges. Not filed as its own PR yet, because it would make SahajAtlasWeb wrong in the meantime — it is correct until this lands.
  • A brief window serves the old names. Railway applies the migrations in-process on boot and keeps the previous container until the new one is healthy, so the old deploy can read clients.locale and imports.locale for a few seconds after each is gone. The first has one reader, an operator script, and the admin degrades to a blank select. The second is read only by the import job, and only for a run queued inside that window, which would write its classes in the default language rather than the uploader's.
  • The hook is appended after a collection's own beforeValidate hooks, not before them, so it reads whatever they settled on.
  • A local-API case cannot prove a per-locale role. testData.createManager returns the document as its create locale read it, so user: carries a flat roles array that extractRoles grants in every locale — only the auth strategy hydrates the per-locale record. The cases that turn on holding a role in one locale and not another go through REST, and the suite docblock says so.
  • Not in this PR, per the ticket: the duplicate narrators the Czech editors created (ids 25–28) still need an admin to merge or delete by hand.
  • tests/PERF.md's pinned unit-lane counts are refreshed here: 229 files / 2935 tests. This push removed three unit cases with the declaration they covered, and PERF.md is the single writer of every tier figure.
Detail

Why the access layer and not a hook, for the main fix. docs/rules/access.md makes the collection access config the one answer to "who may write this row", and withDerivedGrants reads update to derive readVersions — so version history follows with no second edit. A hook alone would have left the admin edit view rendering a Save button that fails only on submit, and would have had to be mirrored for the versions read. The beforeValidate hook is what makes the create rule complete: it is the only one of the two that can see a locale the field pass filled.

Why reads are untouched. filterMeditationsByLocale already appends { locale: { equals: req.locale } } to find and count, and deliberately skips writes — which is the gap this closes. Its versions-read guard (#745) is why the derived readVersions translates the clause onto version. rather than declining it.

Why the flattened list is still the only shape. The declaration is gone but the hazard it was read with is not: sanitization splices every container that adds no path of its own — a row, a collapsible, an unnamed tab or group — straight into the top level, and Meditations.locale sits inside an unnamed tab. A walk over the raw fields would have to reproduce that rule to agree with a query, and reproducing it once missed an unnamed group: the column scoped at the access layer, the collection left without the create hook, and the duplicate bypass reopened. Both callers hand over flattenedFields, so there is no copy of Payload's rule to keep.

Fixture pre-mortem. Meditations.frames composes jsonFieldValidation with "at least one frame on update", so a frameless fixture fails validation before any case reaches its assertion — which is how the first run of this suite failed. Verified against the live field in src/collections/Meditations/Meditations.ts; both fixture meditations now carry a frame. The other assumptions were checked the same way: en and fr are configured in src/lib/locales/index.ts, and meditations-editor grants create and update on meditations in src/plugins/access/config/roles.ts.

Why each rename needed a hand-written migration, in full. The drizzle prompt that decides rename-vs-create cannot be answered by a non-TTY run, and scripts/migrate-create-pty.py answers it with the highlighted default, which is create — two prompts for this one, one for UP and one for DOWN, eight for the clients rename. That is the right default when a change really is a drop plus an add, and the wrong one here, so the DDL was replaced and each snapshot kept. src/migrations/AGENTS.md is where that trade is written down. Worth noting for the second one: pnpm db:migrations:create exited 0 with no files written, having printed the prompt, which the outcome table had no row for — the nearest one is silent CLI death, whose signal says "no output". /dev/null is an EOF the prompt reads as an abort, so the documented hang needs no stdin at all. Both outcomes are rows now.

Review findings dismissed, with reasons. A review pass proposed trimming four cases as redundant: the fr-only update refusal, the ?locale=en REST half, half the admin case, and the narrator case. Each is kept — each is a stated acceptance criterion on the ticket, and the ?locale=en half is the only case proving the hydrated per-locale roles deny at the layer above this one.

Write paths swept. The collection registers three endpoints (Meditations.ts:113): lectures and songs are get, and transcribe is the post this branch scopes. The rest: meditation-transcripts carries no write grant in any role; cascadeFrameNodeChange's db.updateOne is reachable only from a frames write, which no role grants; the transcription job runs admin-only. Bulk PATCH /api/meditations?where=…, the trash path and version restore all combine this Where through Payload's own operations. The security pass re-ran the sweep across every permission-gated endpoint in the repo: the only other one is frames/by-narrator, and frames and narrators are shared across languages and carry no locale column, so no comparison is owed there.

What the renames do not reach. managersOnlyFieldAccess was never on Clients.language and still is not — it sits in the Sahaj Atlas collapsible, which carries no field lock either side. RESTRICTED_COLLECTIONS names clients and imports by slug, so restriction is unaffected. No select under src/ names either field, and neither field's type or options changed, so no new value is accepted anywhere. imports.uploadLocale keeps the collection's own access.update: () => false, and its beforeChange stamp still overwrites the column on create, so a caller-supplied value cannot survive.

The base merge. Four conflicts, all the unit-lane counts and the prose around them. Both sides' rows are kept in tests/PERF.md: main's two 2026-10-23 sessions came from #1014, so they take the PR labelling this branch introduced and the numbering follows the dates. Tier 1's slowest per-edit selection takes main's wording — it re-measured the widest selection at 8.7 s on the 3 specs naming @/payload.config, the spec main added, which beats this branch's 8.0 s importGraph figure, and that target is held to the slowest measurement rather than the newest.

Closes #980

A meditation is one language, in its hidden `locale` select, but
`meditations-editor` is granted per locale and the grant it carries names
none. So the collection-wide grant let a French or Czech editor open an
English meditation by its URL and rewrite its label, narrator, thumbnail,
type, music tag and frames for every English listener. Two French and two
Czech managers hold the role on production.

`scopeMeditationWrite` narrows a non-admin manager's write to the locale
`hasPermission` already evaluated their role in, so the answer is the
language this request's roles came from rather than the one the document
claims. `update` and `delete` return a `Where`, which `updateByID` reports
as 403 when it matches nothing. `create` has to answer with a boolean,
because `executeAccess` reads a `Where` as a grant and an object there
would allow every language.

Version history follows without an edit: `withDerivedGrants` derives
`readVersions` from `update` and translates the clause onto
`version.locale`. Reads are untouched — `filterMeditationsByLocale`
already scopes `find` and `count`, and skipping writes is why this gap
existed. Narrators keep their unscoped grant, since every language draws
on the same ones.

The fixtures carry a frame each: `Meditations.frames` demands at least one
on every update, so a frameless meditation fails validation before any of
these cases reaches its assertion. Checked against the live field, not
assumed. Six of the ten cases go red with the branch disabled; the four
that stay green are the controls for what must not change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014S9XqDjmUMJo5H5Eq5VGes
Where the rule lives, what each operation answers, and the three things it
leaves alone — reads, narrators, and admins. The collections guide's
Meditations locale section says writes are scoped elsewhere, since the
hook it describes deliberately skips them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014S9XqDjmUMJo5H5Eq5VGes
`access.create` runs before the field pass that fills `locale`, so an absent
one has to pass there — and `duplicate` sends an empty `data`, then clones
the SOURCE document's locale rather than taking the default, because
`getFallbackValue` prefers `siblingDoc` over `defaultValue`. So a French
editor could `POST /api/meditations/<english id>/duplicate` and land a new
English meditation in the app's English catalogue, editable by nobody but an
admin. The access scoping cannot see it: the language does not exist in
`data` when the gate runs.

`restrictCreateToRequestLocale` checks the filled value in `beforeValidate`,
the first point the language is known. One rule for each of the two moments
a create's language can arrive, rather than two copies of one rule — the
same split as `restrictUploadToAdmin`, which guards `req.file` in a hook
because a file is not a field.

Found by the branch's own review pass, which two lenses reached
independently. The case fails with the hook unwired and nothing else does.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014S9XqDjmUMJo5H5Eq5VGes
Its body only ever returns `LocaleCode | undefined` — its own docblock says
so with a ⚠ — while the declared `RoleScope` made every caller that scopes a
`Where` on the answer write an unreachable `'union'` branch and guess what
one would mean. Declaring the narrower type deletes that branch at the
source. `RoleScope` stays the parameter type of a permission check, where a
caller may still state `'union'` deliberately.

Also `incoming == null` for the two-sided null check, the spelling 20-odd
sites in `src/` already use, and a comment on `meditations-editor`'s grant
saying it is locale-scoped elsewhere — the convention `atlas-manager`
already set eleven lines below it, and the misreading that produced #980.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014S9XqDjmUMJo5H5Eq5VGes
The suite's own create helper had grown a second copy of the meditations
upload contract — the raw `Buffer`, the browser's mimetype spelling, the
label generator. `testData.createMeditation` takes an `as` bag instead, so a
spec asserting who may create one passes a user rather than rebuilding the
upload. Its `locale` is the REQUEST locale, which this collection keeps
separate from the document's own `locale` field: a spec about who may write
which language needs the two to differ.

The bilingual case now runs over REST. `createManager` returns the document
as its create locale read it, so `user:` on a local-API call carries a FLAT
`roles` array that `extractRoles` grants in every locale — only the auth
strategy hydrates the per-locale record. The case would have passed with the
French-only editor substituted, which the docblock now states so the next
reader picks the right route.

The duplicate case counts English meditations either side of the attempt
rather than matching a fixture label a sibling case rewrites when it fails.
And `meditations.int.spec.ts` said this derivation was unconditional and
pinned no `Where` translation; it is conditional now, and that case pins it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014S9XqDjmUMJo5H5Eq5VGes
The section said writes are scoped without naming the one create the access
function cannot answer for. Says which two moments a create's language can
arrive, and which guard owns each.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014S9XqDjmUMJo5H5Eq5VGes
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 20, 2026
@sydevs-bot

sydevs-bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 23:49Z address-review · attempt 1 · session · done
  • 23:49Z address-review · attempt 1 · session
  • 20:36Z resolve-conflicts · attempt 1 · session · done
  • 20:36Z resolve-conflicts · attempt 1 · session
  • 20:02Z address-review · attempt 1 · session · done

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

@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 fix is the size of the ticket: writes narrow in the one place the other two narrowings already live, and reads, narrators and admins stay untouched. The duplicate route is a second hole the ticket missed, and the hook that closes it is forced — access.create is handed data alone, so it cannot see duplicateFromID. Two reservations, neither blocking: the create arm of the access function looks redundant with that hook, and one story is now told four times across code and docs.

Findings

  • consider — accessConfigs.ts:118 — the create arm may refuse nothing the hook does not.
  • consider — restrictCreateToRequestLocale.ts:11 — four copies of the duplicate carve-out.
  • consider — testData.ts:631 — two spellings of the fixture's locale.

What was checked

  • #980 against the diff: every acceptance criterion has a case. The two extras — the duplicate guard, the roleScopeFromLocale narrowing — are each forced by the fix.
  • Read whole: accessConfigs.ts, the new hook, Meditations.ts (locale required, defaults to the admin locale, update: () => false), roles.ts (only meditations-editor writes meditations).
  • Payload internals read, not assumed: create.js runs access, then field beforeValidate, then collection beforeValidate; duplicate.js calls createOperation with data: {}; getFallbackValue prefers siblingDoc over defaultValue; updateByID throws Forbidden on a where policy matching nothing.
  • No consumer contract touched: no payload-types.ts, no responseTypes.ts, client roles unaffected.
  • Both ## Preview links answer 404, so the preview is still building. The body already states the data is unseeded.

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


Generated by Claude Code

Comment thread src/plugins/access/accessConfigs.ts Resolved
Comment thread tests/utils/testData.ts Resolved
@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 20, 2026
The same story was told four times: docs/rules/access.md, this JSDoc, the
hook's, and src/collections/AGENTS.md. Both JSDocs keep the rule and the
non-obvious why, and point at the doc that owns the rest.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016V71DUvxB8FmxCJTYQNn85
A stated locale survives the field pass, so restrictCreateToRequestLocale
sees it too and the split is not a necessity. Says why the access arm stays
anyway, so nothing reads as load-bearing that is not.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016V71DUvxB8FmxCJTYQNn85
The `as` spread re-set `locale` after the line above had resolved it, so
`{ locale: undefined }` would have blanked the computed value. Destructures
it out instead.

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

Copy link
Copy Markdown
Contributor Author

Addressed all three review threads, on 1961db8. The base merged clean (053f8e7, no conflicts).

Adopted

Kept, with the framing fixed

Gate: lint, both typechecks, 2642 unit tests, then role-based-access + meditations int specs — 103 passed. Every changed line under src/ is a comment, so the security-review paths carry no executable change.

🤖 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 20, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review October 20, 2026 18:47
@sydevs-bot
sydevs-bot requested a review from Ardnived October 20, 2026 18:47
@sydevs-bot
sydevs-bot enabled auto-merge October 20, 2026 18:47
@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 20, 2026
…tion-locale-writes

#1007 split the two largest guides, moving the Meditations locale section
out of src/collections/AGENTS.md and into src/collections/Meditations/AGENTS.md.
This branch had extended that section in its old home with the write-scoping
bullet, so the two edits landed on the same lines.

Took main's split in src/collections/AGENTS.md and carried the bullet into the
new guide, keeping both: the detail lives where #1007 put it, and the #980
breadcrumb survives. The rest of the section was identical on both sides.

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

Copy link
Copy Markdown
Contributor Author

Merged main in. One conflict, in src/collections/AGENTS.md: #1007 moved the Meditations locale section into src/collections/Meditations/AGENTS.md, while this branch extended that section in its old home.

Took main's split, and carried the write-scoping bullet into the new guide — the detail lives where #1007 put it, and the #980 breadcrumb survives. The rest of the section was identical on both sides.

No code conflicted: main's three code edits since the last merge are comment-only pointer updates, and touch no file this branch changes. docs/rules/access.md auto-merged, and this branch's new section sits intact after the region-subtree one.

Lean gate green — lint, both typechecks, 2653 unit tests. role-based-access + meditations re-run together, 103 passed.

🤖 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 20, 2026
227 files / 2917 tests on the merged tree, the lane in 53.54 s inside the
gate. Main's #1014 added two spec files and this push's declaration cases
added nineteen tests; PERF.md is the single writer of every tier figure, so
its four consumers move with it.

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

Copy link
Copy Markdown
Contributor Author

Built A and pushed d3ec179.

Answered — classifying every top-level locale. Each column declares its meaning at the field: Meditations.locale is document-language, imports.locale 'unrelated'. The slug set is gone, and the int guard reds until every such column declares one. Added to #980 as a criterion.

Merged main (21c8a91). Four conflicts, all unit-lane counts; one real choice — Tier 1's widest per-edit selection takes main's 8.7 s over this branch's 8.0 s, since that target holds to the slowest measurement.

The security sweep caught one of mine: the walk skipped an unnamed group, which Payload flattens to the top level — scoped, but with no create hook, so duplicate reopened.

Gate green: 227 / 2917, plus 132 integration cases.

Still yours — whether :id/transcribe refuses a meditation outside the editor's locale.

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


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting 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. awaiting labels Oct 25, 2026
Three conflicts, all the unit-lane counts again. #1034 added a unit spec
and re-measured, so neither side's figures described the merged tree.

The counts are re-measured here rather than picked: 228 files and 2924
tests, from two runs of the lane on the merged tree. PERF.md is the single
writer, so AGENTS.md, tests/AGENTS.md and docs/rules/testing-reqs.md all
take the same pair.

main's new session row is kept under the PR labelling this branch
introduced, and the numbering follows the dates. The gate's warm figure
takes main's 112 s over this branch's 103 s — the target is held to the
slowest measurement.

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

Copy link
Copy Markdown
Contributor Author

Merged main (#1034). Three conflicts, all the unit-lane counts again.

Neither side described the merged tree — #1034 added a unit spec and re-measured, this branch had re-measured its own — so the lane was re-measured here instead of picking a side: 228 files / 2924 tests. PERF.md is the single writer, so AGENTS.md, tests/AGENTS.md and docs/rules/testing-reqs.md all take that pair.

main's new session row is kept, relabelled #1034 under the PR labelling this branch introduced; the numbering follows the dates. The gate's warm figure takes main's 112 s over this branch's 103 s — that target is held to the slowest measurement, not the newest.

Lean gate green (128 s). admin-route-config and role-based-access int specs pass, 82 cases.

🤖 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 26, 2026
@Ardnived

Copy link
Copy Markdown
Contributor

@sydevs-bot revise and go with option 1 for this comment: #999 (comment)

ie. Add scoping for the transcribe endpoint

@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 26, 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 collection half is the size of its ticket and sits in the right layer, beside the two narrowings already there. The field declaration and the Clients rename are the reviewer's own asks. Nothing is smuggled in.

But the PR does not close the hole its ticket opens with. POST /api/meditations/:id/transcribe, which main added after this branch opened, still reads meditations: update with no language condition, so the grant this PR narrows everywhere else stays collection-wide at one door. Option 1 was chosen today and nothing is built for it.

The declaration mechanism is sound. Its one weak seam is that it hand-copies Payload's flattening rule, which already cost a duplicate bypass once this push.

Findings

  • blocker — src/plugins/access/config/roles.ts:33 — the transcribe endpoint reads this grant unscoped.
  • should-fix — src/plugins/access/accessPlugin.ts:96 — the raw-fields walk duplicates Payload's own rule.
  • should-fix — PR body, § Detail — "The two meditation endpoints are GET only" is stale. There are three, and the third is the blocker.

What was checked

  • #980 against the diff: every criterion has a case, the two (review, …) ones included. Twelve cases, none reaching transcribe.
  • Read whole: localeScopedWrites.ts, accessConfigs.ts, accessPlugin.ts, transcribe.ts, RetryTranscript.tsx, the rename migration.
  • Meditations declares no managers or manager field, so the document-manager fallback is not a second write path around the scope.
  • Its three endpoints, registered at Meditations.ts:113: lectures and songs are get, transcribe is post.
  • All three ## Preview links answer 404, so the preview is still building.

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


Generated by Claude Code

Comment thread src/plugins/access/config/roles.ts Resolved
Comment thread src/plugins/access/accessPlugin.ts Resolved
`main` added `POST /api/meditations/:id/transcribe` after this branch opened
(#984, #1011). It proves `meditations: update` in `req.locale` and then reads
the meditation and writes `meditation-transcripts` with `overrideAccess`, so
the access function's `Where` reaches none of it — the grant this branch
narrows everywhere else stayed collection-wide at that one door, and a
`fr`-only editor could delete an `en` meditation's transcript and buy a new
paid run.

The handler now compares the row's own language, before the 409s and before
the transaction that deletes the previous transcript. `isOutsideWritableLocale`
is the predicate `restrictCreateToRequestLocale` already needed, so the
comparison has one home rather than two: a non-admin manager whose
`req.locale` differs from the document's language is refused, and the admin
bypass answers first as it does for a write.

The Transcript tab hides Transcribe-again on the same condition. A button that
can only answer 403 is what the access layer avoided for Save. The predicate
is mirrored in `transcriptModel.ts` rather than imported: the module owning
the refusal pulls `payload` in with it, and the tab is a `'use client'`
component.

Both halves watched failing. With the refusal disarmed the new int case reads
`expected 200 to be 403`; with the control's gate removed the tab case offers
a button on a French meditation. The existing "admits them in theirs" case now
uses a French meditation, since an `en` row with `?locale=fr` is the refusal
this adds.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J5xLK465nuE74yP41pduBW
`localeColumnMeaning` answered for two readers over two shapes:
`accessPlugin` handed it a collection's raw `fields` to decide whether to
attach the create hook, and `createAccessConfig` handed it the booted
`flattenedFields` on a write. The raw half had to reproduce Payload's
flattening rule — which containers add no path of their own — to agree with a
query, and the int guard shares the function, so it cannot see that copy
drift.

Reproducing it already cost something once on this branch: narrowed to rows
and collapsibles, the walk scoped an unnamed group's column at the access
layer and left the collection without the create hook, which is the
`duplicate` bypass again.

So the hook attaches to every collection and asks `collection.flattenedFields`
itself, standing down unless that list declares `document-language`. The walk
takes the flattened shape and nothing else, and its container descent is gone
with the rule it was reproducing. One reader, one shape.

The stand-down was watched failing: removed, the new unit case refuses a
create on a collection whose column is `'unrelated'`. `role-based-access`,
`meditations`, `event-imports`, `meditation-transcription` and
`meditation-transcripts` int specs pass, 170 cases.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J5xLK465nuE74yP41pduBW
228 files / 2929 tests, the lane at 56.6 and 57.0 s in two gate runs. This
push added five unit cases and no spec file. PERF.md is the single writer of
every tier figure, so its three consumers take the same pair.

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

Copy link
Copy Markdown
Contributor Author

Built option 1 and pushed 9f0702f, 66b9658, 5f90518. Base already merged, nothing behind main.

Adopted — the transcribe endpoint reads this grant unscoped. The handler compares the row's own language before the 409s and before the transaction, so a refused caller reaches no delete and no paid run. The Transcript tab hides the button on the same condition.

Adopted — the raw-fields walk duplicates Payload's own rule. The hook attaches everywhere and asks flattenedFields itself. One reader, no copy to track.

The stale § Detail sweep is corrected: three endpoints, not two.

Security review: no exploitable path. Every odd req.locale is already denied by the gate ahead of the comparison.

Gate green: 228 / 2929, plus 170 integration cases.

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


Generated by Claude Code

Five conflicts, four of them the pinned unit-lane counts and one an import
list. Both sides' additions are kept everywhere.

- `src/plugins/eventImport/importCollection.ts`: both sides added an import.
  This branch classifies `imports.locale` as `'unrelated'` (#912); main's
  #1013 declares the collection's retention windows. Both are used.
- `src/migrations/index.ts`: both sides registered a migration. Ordered by
  timestamp, so #1013's `20261024_161437` precedes this branch's
  `20261025_195340`.
- `tests/PERF.md`: both sides' session rows are kept, ordered by date, under
  the PR labelling this branch introduced, so main's #1013 and #1034 rows
  take it too. Ordinals follow the dates.
- `docs/rules/testing-reqs.md`, `tests/AGENTS.md`: the counts differed only
  because each side added a spec file. Measured on the merged tree instead:
  229 files / 2938 tests, 59.58 s on 4 cores.

A sixth change the merge could not report. #1013's
`20261021_152406_retention_registry` lands behind this branch's newer
`20261025_195340`, so the newest snapshot still named the three replaced task
slugs and `migrate:create` re-emitted both `task_slug` enum rebuilds — without
the `DELETE`s that migration runs before it casts, which would abort the boot
migration on the first legacy row. `20261026_204230_merge_1013_main_snapshot`
keeps only its snapshot, the third time this branch has healed the chain that
way.

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

Copy link
Copy Markdown
Contributor Author

Merged main. Five conflicts, every one additive — both sides are kept.

One change the merge could not report. #1013's 20261021_152406_retention_registry lands behind this branch's newer 20261025_195340, so migrate:create re-emitted both task_slug enum rebuilds — without the DELETEs that migration runs before it casts, which would abort the boot migration on the first legacy row. 20261026_204230_merge_1013_main_snapshot keeps only its snapshot.

Gate green: lint, format:check, both typechecks, 229 files / 2938 unit tests.

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


Generated by Claude Code

`imports.locale` is the admin locale an upload happened in, which the job
writes its classes in (#912). It says nothing about who may write the row — so
it was the one counterexample to the rule the reviewer asked for: that a
top-level column named `locale` IS a document's own language. Renaming it is
what makes that rule true of the whole config, as the same rename made it true
of `Clients.language` earlier on this branch.

The migration renames the column rather than dropping and adding it, which is
what drizzle's own default would do — blanking the locale of every import
already stored, so a run still pending at the deploy would create its classes
in the default language instead of the uploader's. `varchar` either side, no
index and no enum type, so nothing is retyped.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gME9vapmFgfep9i7PYxi2
The declaration machinery is gone: `localeColumn`, `LocaleColumnMeaning`,
`localeColumnMeaning` and the undeclared verdict, with the two `custom:`
declarations and the memo over them. A collection is locale-scoped when it
carries a top-level `locale` field at all, which `isLocaleScopedCollection`
answers in one line off `flattenedFields`.

That turns the rule into an invariant the names carry, so it is written down
where a field author will meet it: never spell a column `locale` unless it is
the document's own language. `Clients.language` and `imports.uploadLocale` are
the two that were renamed to keep it true, and the one hazard the declaration
was defending against — a column meaning something else acquiring the scope
silently — is now impossible to introduce without renaming something.

A new column could still arrive, so the int guard moves from "declares a
meaning" to "is one of these": it names every collection carrying the column,
`meditations` alone today, and reds when another appears. Watched failing with
`imports.uploadLocale` spelled `locale` again — `['imports', 'meditations']`
against `['meditations']`. Its docblock now also carries what confirming such a
column costs: the locale branch returns before the `user-submissions` one in
`createAccessConfig`, so a `locale` column there would replace that
collection's row restriction with a language clause.

The WeakMap verdict cache goes with the walk it was caching. It existed because
reading a declaration off the field list cost a descent; a name comparison over
the same list does not.

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

Copy link
Copy Markdown
Contributor Author

Pushed 4c80a12 and 1d4fb7b. The branch was already level with main, so no merge.

Adopted — the declaration is gone. A collection is locale-scoped when it carries a top-level locale field, and docs/rules/access.md states that as the invariant. localeColumn, the meaning type, the undeclared verdict and the memo over them are gone: 113 lines, down from 160. imports.locale became uploadLocale, which is what makes the documented rule true — it was the one counterexample. The int guard now names the collections carrying the column, meditations alone, and reds when another appears.

Asked, same thread left open — the file is not eliminated. Three things are left, none of them classification: the access clause, the create hook duplicate needs, and the predicate transcribe shares. A keeps the file; B splits them across accessConfigs.ts and a hook-named module.

Gate green: 229 files / 2935 unit, 132 int. Security review found no exploitable path.

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


Generated by Claude Code

`timeout 300 pnpm db:migrations:create <name> --skip-empty < /dev/null` exited
**0**, wrote nothing, and printed the rename-vs-create prompt. The outcome
table had no row for that: the nearest one is "silent CLI death", whose signal
says "no output", and following it sends a run down the escalation ladder
instead of to `scripts/migrate-create-pty.py`, which answers the prompt in one
re-run. Observed on this branch's second rename.

The cause is the redirect the table itself prescribes: `/dev/null` is an EOF
the prompt's TUI reads as an abort, so the hang the section documents is what
happens with no stdin, not with that command. Both outcomes are stated now,
each with its signal.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gME9vapmFgfep9i7PYxi2
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.

fix(access): scope meditation edits to the editor's language

3 participants