Skip to content

feat(access): derive manager roles from region, event and page listings - #1074

Merged
Ardnived merged 27 commits into
mainfrom
claude/feat-1068-derive-atlas-roles
Nov 5, 2026
Merged

Ardnived merged 27 commits into
mainfrom
claude/feat-1068-derive-atlas-roles

Conversation

@sydevs-bot

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

Copy link
Copy Markdown
Contributor

Summary

  • Who manages an Atlas region or event is now read off the listing on every request: atlas-manager is gone, replaced by derived atlas-region-manager and atlas-event-manager.
  • Writing Regions.managers or Events.manager hands out one of those roles, so both fields take a field-level lock, and a manager's proposal reads narrow per role.
  • Joined, because criterion 2 needs them: three places refused a save the manager was entitled to make — the region picker, the events re-home guard, and the regions re-parent guard.
  • A proposal's responsible region moved out of a JSON column into an indexed one, so the narrowed read above is one IN rather than ~3,000 jsonb_path_exists predicates (review thread, option B).
  • That JSON column, regionHint, is now dropped outright (review thread, option B again). routingRegion says who reviews a proposal and region where an accepted one is created; an Accept with Region cleared is refused on that field rather than falling back to intake's match.
  • A third derived role, page-editor, for anyone listed on a page's Page Editors. It places them in We Meditate Web and grants image and file uploads; their own pages still reach them through document-level access.
  • The Managers Roles select now shows a derived role as a chip nothing can remove, in place of a footer row in the Permissions table — RolesField, a new custom field component.
  • Joined: admin.style and admin.width reach that select, through one mergeFieldStyles helper both custom selects call rather than a copy each (review thread).
  • main is merged in (feat(api): let an admin block a submitter, and purge spam sign-ups #1060, feat(events): a Registrations tab for the event's own manager #1073, feat(atlas): repeatable re-sync pipeline, with the data kept out of git #1079). Neither derived role reads users (Registrants): a manager reads their event's registrants on its Registrations view (feat(events): a Registrations tab for the event's own manager #1073), and a contact's sender address arrives in its delivery mail. Both read with overrideAccess.

Change outline

The main change is where a role comes from: nothing stores the derived roles — the two Atlas ones and page-editor.

Flow — resolving a request's roles

 hasPermission({ user, collection, operation, locale })   src/plugins/access/permissions.ts
   bypassPermissions(user, …)                             # admin / inactive / self, unchanged
-  extractRoles(user.roles, scope)
-    array        → return it                             # clients
-    no scope     → []
-    'union'      → every locale's
-    a LocaleCode → that locale's
+  extractRoles(user, scope)
+    storedRoles(user.roles, scope)                       # the four branches above, unchanged
+    no scope                 → stop here                 # ?locale=all resolves nothing
+    not a `managers` caller  → stop here                 # allowlist; a client carries no join
+    virtualRoles(user)                                   src/plugins/access/config/roles.ts
+      for each role declaring `virtual: { join }`
+        user[join].docs non-empty → that role
   per role: implicit project read, then the permission table

Contract — the role table

 ROLES                                                src/plugins/access/config/roles.ts
-  'atlas-manager'                   assignable in Managers.roles
-    regions   create, update
-    events    create, update, delete
-    users     read
-    imports   create
-    managers  read
-    user-submissions  read, update
+  'atlas-region-manager'            virtual: { join: 'managedRegions' }
+    regions   create, update
+    events    create, update, delete
+    imports   create
+    managers  read
+    user-submissions  read, update
+  'atlas-event-manager'             virtual: { join: 'managedEvents' }
+    events    update, delete
+    user-submissions  read, update
+  'page-editor'                     virtual: { join: 'managedPages' }     project: wemeditate-web
+    images    create
+    files     create                # no `pages`: a role grant is every page; the listed
+                                    # ones reach them through documentManagers.ts

getRoleOptions now throws on a role declaring virtual, at config build, so no select can offer a value nothing reads and nothing removes. getRoleLabel is the new way to name a held one.

Contract — who may write a manager field

A listing is a role, so writing one is a delegation. Payload strips a refused field rather than erroring, so a PATCH naming it succeeds with the value unchanged. Pages.managers was already admin-only on update, so page-editor needed no new lock; a spec now pins that a listed editor cannot add anyone.

 Regions.managers                                     src/collections/Regions/Regions.ts
+  access.update: regionManagersFieldAccess           # admin, or a region manager whose subtree holds this row (its own id)
 Events.manager                                       src/collections/Events/Events.ts
+  access.update: eventManagerFieldAccess             # …or holds the event's stored `region`. An assignee: refused.

Behaviour — which submissions a manager reads

-managerSubmissionScope(userId)                        src/plugins/access/accessConfigs.ts
+managerSubmissionScope(req)
   or:
     contact rows whose form.recipient is this manager          # unchanged
-    every proposal
+    atlas-event-manager → proposal AND event.manager == user
+    atlas-region-manager → proposal AND any of
+      event.region    in resolveOwnedRegionIds(req)
+      region          in …
+      routingRegion   in …                                     # one indexed IN

A net narrowing: the old clause was a bare type == proposal, every proposal in the system.

routingRegion is new, and load-bearing rather than a cache of region. A proposal for a city the atlas does not hold yet has no region — an event must sit in a city or venue — and deliverProposal mails its state or country manager, who would otherwise be unable to read the row they were asked to review. It holds the deepest level intake matched, at whatever level, so the clause reaches that row with one indexed comparison.

 resolveProposalRegion (beforeValidate, create)        src/collections/UserSubmissions/hooks/
   match location + address mapboxIds against regions.mapboxId
   region = venue ?? city                                       # unchanged — the Accept target
-  regionHint = { country, state, anchorRegion }
+  routingRegion = venue ?? city ?? state ?? country            # the review target

 submissionRegionId(submission)                        lifecycle/mergeProposal.ts
-  region ?? regionHint.anchorRegion
+  region                                                       # cleared → Accept refused on Region

 submissionRoutingRegionId(submission)
-  region ?? regionHint.anchorRegion ?? regionHint.state ?? regionHint.country
+  region ?? routingRegion                                      # a reviewer's correction still wins

 user_submissions.region_hint                          dropped — 20261105_181908_retire_region_hint

Behaviour — three refusals of an unchanged value

All three have the same shape: the subtree rule was applied to a value the caller merely repeated, and Payload's admin posts the whole document. An event assignee owns no region at all, and a region manager's own top region sits under a parent above their subtree — so each could open the document and never save it.

 ownedRegionFilterOptions({ req }, keepCurrent?)        src/plugins/access/regionSubtreeAccess.ts
+  keepCurrent — the posted region id, passed by the field — not already owned → stays selectable

 scopeRegionSubtreeWrite — events update/delete
-  posted region outside the subtree → refuse
   load the stored row
+  posted region differs from stored AND outside the subtree → refuse
   stored region in the subtree, or manager == user → allow
+  bulk update (no one row) → keep the strict test

 scopeRegionSubtreeWrite — regions update
   row in the subtree?
+  posted parent is null or owned → allow
+  else → allow only if it equals the stored parent      # one read, only here
+  bulk update (no one row) → keep the strict test

Behaviour — the admin locale selector is deliberately unchanged

An earlier revision widened it, and the review settled that as option B: revert. A derived role is held in every configured locale, but nothing either Atlas role grants carries a localized field — regions and events declare none, and an event's title is one non-localized value — so a second admin language would open no content the first does. A manager whose only role is derived lands on English.

role-based-access.int.spec.ts reads that premise off the booted config rather than trusting it, so a localized field on either collection reds the suite instead of leaving this answer quietly wrong.

page-editor lands on English too, though pages is localized. That is a decision, not the same argument: a page assignment names no language, so another locale comes from a stored role.

Components — the Roles select

A derived role is held and cannot be assigned, so it has to be visible where an admin looks for a role. That is the select itself, not a table below it.

 Managers.roles admin.components                       src/collections/Managers/Managers.ts
+  Field:      RolesField                              src/components/admin/RolesField/
   afterInput: [PermissionsTable]

 RolesField
   ReactSelect, composed — Payload's SelectInput forwards no react-select props,
   so no built-in can mark one chip apart from another
   chips = virtualRoles(useDocumentInfo().savedDocumentData) then useField<RoleSlug[]>()
     a derived chip is dashed, has no remove button, and a note names it
     derived first, because Backspace removes the last chip
   storedRoles strips every derived chip from each change   # the whole guarantee
   admin.style / admin.width → helpers/mergeFieldStyles     # one spelling, shared with
                                                            # StringSelectField

 PermissionsTable (afterInput)                         src/components/admin/PermissionsTable.tsx
-  useField<RoleSlug[]>()                               # the stored roles alone
+  useField<RoleSlug[]>()  +  virtualRoles(useDocumentInfo().savedDocumentData)
   collection → operations rows
   tfoot
     "Project Access"

Preview

Sign in with PREVIEW_ADMIN_EMAIL. Data: not seeded yet — previewUrl.seed is unset for this repo, so a preview starts with only its admin. The three links below are where to create what the change shows; the steps are in Manual verification.

  • Managers list — the Roles select no longer offers an Atlas role
  • Regions list — list a manager on one, then open their manager record for the derived chip in the Roles select
  • Events list — assign a manager to one, then sign in as them: the Manager field is read-only and the event still saves
  • Pages list — list a manager under a page's Page Editors, then open their manager record for the Page Editor chip

Email previews

The invitation's Atlas scenarios changed shape — an Atlas manager now has no role row, only responsibilities — so the previews are here even though the diff touches neither src/emails/ nor src/plugins/email/. The change reaches them through src/plugins/login/grantSummary.ts.

Migration

Three migrations with DDL, plus one snapshot resync from the main merge.

20261102_213524_derive_atlas_roles.ts

  • Impact: managers_roles loses every atlas-manager row, and enum_managers_roles is rebuilt without the value. No other table or column changes; it is the only user of that enum.
  • Reversible: yes, lossily. down rebuilds the enum with the value and inserts one en row per manager listed on a region. The role was assigned by hand and is now derived, so nothing records who held it.

⚠ Two counts to run against production before merging, because the grant moves from a column to a listing in both directions:

-- Loses write access on deploy: held the role, listed on no region.
SELECT count(*) FROM managers m
 WHERE EXISTS (SELECT 1 FROM managers_roles r WHERE r.parent_id = m.id AND r.value = 'atlas-manager')
   AND NOT EXISTS (SELECT 1 FROM regions_rels x WHERE x.path = 'managers' AND x.managers_id = m.id);

-- Gains the role on deploy: listed, never assigned it. The atlas seed lists 495
-- managers across 646 regions, so expect this to be large.
SELECT count(DISTINCT managers_id) FROM regions_rels WHERE path = 'managers' AND managers_id IS NOT NULL;
SELECT count(DISTINCT manager_id) FROM events WHERE manager_id IS NOT NULL;

The first set needs a region listing before deploy. The second is the ticket's intent — the listing is the role — but it is worth confirming the listed set is the set meant to hold these grants, since the importer populated some of those rows as contact information.

Both hand edits to the generated migration are measured, not assumed, against a throwaway Postgres, and src/migrations/AGENTS.md now records the pair:

  • The generator's own up throws invalid input value for enum enum_managers_roles: "atlas-manager" on a surviving row, so the DELETE has to come first. Reproduced.
  • down rebuilds the enum rather than ALTER TYPE … ADD VALUE, because Postgres answers unsafe use of new value "atlas-manager" when the same transaction inserts with it — and a migration runs in one. Reproduced.

20261104_180154_routing_region.ts (new)

  • Impact: user_submissions gains routing_region_id — one nullable integer, an FK to regions with ON DELETE set null, and a btree index. No other table or column changes.
  • Reversible: yes. down drops the index, the constraint and the column. Nothing else held the value.

⚠ It carries a hand-added backfill, and the column is useless without one. The access clause stops reading regionHint in the same change, so a proposal routed only by the hint — one above a city the atlas does not hold — would become unreadable by the very manager deliverProposal mailed it to. src/migrations/AGENTS.md says to surface a backfill-in-migration rather than decide it; option B named it, so it is here.

Measured against a throwaway Postgres over eight rows, not reasoned about. Two guards are load-bearing, because either failure would abort the boot migration and crash-loop the deploy rather than report anything:

Row Backfilled to
region set, hint set too region — it wins
no region, anchorRegion set the anchor
no region, state + country only the state — the row the column exists for
no region, country only the country
hint names a region since deleted NULL — EXISTS guard, no FK violation
hint holds text where the schema declares an int NULL — jsonb_typeof guard, no failed cast
nothing to route by NULL
a contact row untouched

20261105_181908_retire_region_hint.ts (new)

  • Impact: user_submissions loses region_hint, a JSON column. No other table or column changes.
  • Order: after 20261104_180154_routing_region, whose backfill is the last reader of the column. Timestamp order guarantees it.
  • Reversible: lossily. down restores an empty jsonb column. Nothing reads the old keys: .state and .country had no reader, and .anchorRegion was only the Accept fallback for a cleared Region, which is now refused instead.

20261104_185158_snapshot_resync.ts (new, no DDL)

  • Impact: none. up and down are empty; the .json beside it is the point.
  • Why: 20261104_180154_routing_region.json predates the main merge, so migrate:create on the merged tree re-emitted main's DDL — users.blocked_at / blocked_reason and the sender_email drop, every statement already shipped by 20261101_202242_block_submitter and 20261103_215150_submitter_identity. That is the out-of-order snapshot trap (feat(regions): country slug = ISO alpha-2 code #566): the generated snapshot is kept, the duplicate DDL emptied, as src/migrations/AGENTS.md prescribes. A second migrate:create probe writes no files.
  • Order: the four migrations from both sides are listed by timestamp. main's and this branch's touch disjoint columns, so production (which has main's) and this preview (which has this branch's) can apply the rest in either order.

Test results

  • Lean gate: ✓ .claude/skills/pr-prep/check.sh — lint, format, typecheck, typecheck:tests, 238 unit files / 3065 tests, 120 s
  • Targeted specs: ✓ the full integration lane earlier in the PR, plus the five the ticket names re-run after each change and after merging main
  • After the previous review round: ✓ the lean gate, plus role-based-access, user-submissions-access, atlas-submission-routing and user-submissions-review-lifecycle — 4 files / 154 tests
  • The critic round on 494d856: ✓ the lean gate again. No integration spec covers the admin field component, so the unit lane is the whole local answer.
  • After merging main: ✓ the lean gate — 238 unit files / 3069 tests. 13 integration specs (the twelve this PR touches, plus block-user from main): 320 of 324 passed together; the 4 failures were local Postgres refusing locks (out of shared memory, max_locks_per_transaction) under 13 parallel schema pushes, and those 4 files passed on their own (121 tests). The full lane is CI's.
  • After dropping the users grant: ✓ user-submissions-access (15), managers-access (14), block-user (8) and atlas-manager (17). The last covers the Registrations view, and its first case asserts an event assignee sees each registrant's address with no users grant. Then main merged again (feat(atlas): repeatable re-sync pipeline, with the data kept out of git #1079, seeds and unit specs only): ✓ the lean gate — 239 unit files / 3083 tests.
  • Retiring regionHint and adding page-editor: ✓ the lean gate — 239 unit files / 3084 tests, 36 s. atlas-submission-routing (14), user-submissions-review-lifecycle (36), user-submissions-access (14) and role-based-access (95), each run on its own.
  • Build: N/A — Railway builds the preview

Six assertions were watched failing against the defect before being kept: the three unchanged-value refusals, the ?locale=all scope guard, the regionHint paths, and the schema-drift guard. A seventh in the first review revision: the kept-region parameter's narrow type, watched refusing the whole filterOptions args object.

The regionHint-paths assertion is gone, because the paths are gone; what stands in its place asserts that every path in the clause resolves to a relationship column, watched failing with a JSON path put back. The locale assertion was inverted and watched failing against the hunk it now refuses.

This round added four, in merge-field-styles.spec.ts, all watched failing against a helper returning {}: a declared width reaches --field-width, a field with none flexes, the rest of a declared style survives beside the width, and a declared flex outranks the fallback.

Manual verification

  1. List a manager on a region. Open their manager record: the Roles select shows an Atlas Region Manager chip with no remove button, a note under it saying to edit the listing instead, and the Permissions table rows carry that role's access. Remove the listing and the chip goes.
  2. As that manager, open the region they are listed on and press Save without changing anything — it saves. Try to add a manager to a region outside their subtree: refused.
  3. Assign a manager to one event and nothing else. As them: the Atlas sidebar and dashboard appear, the event opens, Save works, the Manager field is read-only, and the locale dropdown offers English alone.
  4. GET /api/events?locale=all as either manager still resolves no roles.
  5. Submit a proposal whose address is in a state the atlas holds but a city it does not. The row's Region is empty and its Routing Region is that state — and the state's manager can read the row.
  6. Make a region manager a contact form's recipient and submit the form. The delivery mail reaches them with the sender as Reply-To. As them, open the message in the admin: Submitted By shows no address, by design. Registrants is absent from their sidebar.
  7. Assign a manager to an event that has a registration. As them, the event's Registrations tab lists the registrant's name and email.
  8. On a new-event proposal with a resolved Region, clear Region and press Accept: refused on the Region field, and no event is created.
  9. List a manager with no roles under a page's Page Editors. As them: We Meditate Web is their project, the locale dropdown offers English alone, the page saves, another page opens read-only and refuses a save, an image upload works, and the Page Editors field is read-only.

Notes for reviewer

  • Settled on the threads: neither Atlas role reads Registrants (00d6da1), and regionHint is retired here rather than in a follow-up, with no Accept fallback for a cleared Region.
  • A page editor now reads the whole We Meditate Web project, drafts included, not only the pages listing them — project membership is implicit read, as for web-translator. That covers unpublished pages and meditations; the restricted collections stay closed. They still update only their own pages; role-based-access pins both. Being listed on a trashed page may keep the role alive, as a trashed event already does for atlas-event-manager — not traced to the join SQL.
  • Neither Atlas role reads users, where atlas-manager did. ⚠ The cost: feat(api): let an admin block a submitter, and purge spam sign-ups #1060 made a submission's senderEmail a read of users under the reader's own access, so a manager's read of a contact message or a proposal carries no sender address. user-submissions-access pins that, and a ⚠ in roles.ts says why the grant is absent, so it is not restored to "fix" a blank sender. main's two contact-scope cases now identify their rows by form, and its Registrant-block case asserts a manager can read no Registrant at all. block-user (from main) lists its manager on a region instead of storing atlas-manager.
  • An event assignee gains user-submissions: read + update on the proposals on their own events. Accepting one writes an Events row with overrideAccess, so I checked the path: validateProposal's PRIVILEGED_FIELDS refuses manager, region, _status, deletedAt and images in a patch, and a brand-new-event proposal names no event, so an assignee's scope never reaches one.
  • DashboardView's kind: 'atlas-manager' is deliberately unchanged. It names the AtlasManager dashboard component — "everyone in Sahaj Atlas who is not an admin" — not a role, and dashboardChoiceFor keeps its admin-or-manager branch as the ticket says.
  • src/payload-types.ts moved, so the two consumer repos owe a resync. routingRegion is a new field on user-submissions, regionHint is gone, and RoleSlug gains page-editor; contractSync covers it after merge. No consumer code reads regionHint or routingRegion — checked all four checkouts — so the resync is types only.
  • A branch-level /security-review ran (the trigger paths match) and found nothing. It traced the client/inactive/scope escalation paths, the delegation lock against what Payload actually passes a field rule on single, bulk and capability paths, the relaxed unchanged-value comparison, the proposal-accept path above, and the raw-SQL reach of the regionHint clause. The routingRegion delta got its own pass: nothing, and it removes that raw-SQL reach — the clause no longer calls createJSONQuery at all, and the backfill is a static template with no interpolation. The critic round's delta touched no trigger path: a style merge and a doc. The main merge rounds touch src/plugins/access/config/roles.ts only to remove the users grant, which narrows access. The regionHint and page-editor round got its own pass: nothing exploitable. No access check ever read regionHint, Pages.managers stays admin-only (version restore included), clients never take the role, ?locale=all still resolves none, and no restricted collection opens.
  • 20260621_074306's own down cannot survive a real atlas-manager row — it rebuilds the enum to three members with the rows still present. Pre-existing, never run in production, and src/migrations/AGENTS.md says not to augment an old migration, so it is left alone and recorded here.
Detail

Why routingRegion is one column and not a level-partitioned set. country, state and anchorRegion are one ancestor line, and an owned subtree is closed downwards: whenever a broader entry is in it, every narrower one is too. So storing only the deepest match, and comparing that one, answers exactly what comparing all three would — which is what made option C (partitioning the owned ids by level) unnecessary rather than merely more expensive.

What the shortcut: cost, now that it is paid off. createJSONQuery expands an in into one OR'd jsonb_path_exists per value, inlined as raw SQL, so three hint paths cost three predicates per owned region id: a country manager owning ~1,000 regions sent ~3,000 unindexable predicates and the or degraded the read to a seq scan of user_submissions. Nobody measured it on real data, and the marker named the limit instead. The clause is now three relationship paths, each one IN against an indexed integer column. The marker is deleted rather than reworded — there is no remaining shortcut for it to name.

The three-spellings coupling is down to two, and the assertion changed shape with it. mergeProposal.ts and deliverProposal.ts still read the chain through submissionRoutingRegionId; the access clause no longer re-derives it, it compares a column. The integration case that derived the hint's key set from the booted JSON schema is therefore gone — it asserted a coupling that no longer exists. Two cases replace it: one that every path in the clause resolves to a relationship column (watched failing with a JSON path put back), and one that the chain's answer for a proposal with no region is a column the clause queries.

Why extractRoles gates on the collection as well as the scope. clients declares neither join, so no client document carries one — but virtualRoles reads a shape, not a collection, and a manager role reached by a published API key is the one mistake here that cannot be undone. A unit case asserts it, and it failed before the guard existed.

Why virtualRoles only asks whether the joins are non-empty. A join carries at most its own limit of rows (Payload's default is 10). resolveOwnedRegionIds answers "which regions" from a query; a truncated join would silently shrink a large country's subtree.

The fixture trap, verified against the real wiring. A createManager result is the create response, so its joins are empty — a region listed afterwards is invisible to it, and a spec would pass for the wrong reason. testData.authUser re-reads the manager the way Payload's JWT strategy does: findByID with no joins: false (payload/dist/auth/strategies/jwt.js:100, checked). withRoles and withLocalizedRoles both spread the user, so the joins survive the per-locale role hydration. tests/AGENTS.md records it.

One existing assertion changed meaning, not outcome. role-based-access's "exposes the role as project-scoped" passed no locale and relied on the flat-array branch a hand-built fixture takes. A derived role resolves only once the scope does, so each check now names 'en'. Production is unaffected: hydrateLocalizedRoles always produces the per-locale record, where a locale-less check already denied.

The ⚠ block on extractRoles was wrong in its first draft and is corrected here and in docs/rules/access.md: the scope test does not stop an all-locale grant, which is the intended behaviour. What it stops is answering a request that names no evaluable locale.

What was built beyond the access change. RolesField, a custom Managers.roles select, because Payload's SelectInput forwards no react-select props and so no built-in can mark one chip apart from another. No new collection, no new hook, no new dependency. PermissionsTable keeps the derived roles in its permission rows and no longer carries a footer row naming them — the select names them where an admin would go to change them. The virtual declaration carries only the join name — not the collection and field a config sweep would want — because no such sweep exists yet.

Why the field-style merge is a shared helper rather than a third copy. Payload merges admin.style and admin.width for every built-in field in a mergeFieldStyles its package does not export, and @payloadcms/ui is prebundled, so a deep import would load a second copy of its contexts. A custom field therefore mirrors it, and two already do. src/components/admin/helpers/mergeFieldStyles.ts is that mirror, once, with the four cases pinned in the unit lane and the rule stated in docs/rules/admin-ui.md — the failure is silent until someone sets a width, so prose and a copy per component were how RolesField shipped without it.

What the first review revision changed. Three critic findings, one commit each, plus the docs line each one made stale. docs/rules/access.md spelled the declaration virtual: true where the code reads virtual: { join }, so the documented recipe yielded a role offered in a select and never derived. storedRelationId was a one-caller wrapper beside the same findByID written inline, and is now folded into its call site with its overrideAccess rationale. And ownedRegionFilterOptions took a field name and read posted data under it while its JSDoc called that value stored — it takes the value now, typed as an id so the whole args object cannot be passed by mistake.

Dismissed review findings. grantSummary.ts's ROLE_LABELS map is a second spelling of role→label, and stays: its reason is the lenient fallback for a stored value outside the known set, and folding it into getRoleLabel would widen that helper's parameter to string and weaken two type-safe callers. The altitude pass proposed replacing keepCurrent with a row read keyed on id; FilterOptionsProps carries neither the host collection nor the field name, so that needs more configuration than the key name plus a query per picker call, and the row-level scope already refuses a real move. A ~0.1 ms allocation in extractRoles was left alone rather than guarded by restating virtualRoles' own test outside it. The critic's note that DashboardView's kind: 'atlas-manager' is a name left behind came with no thread, being outside the diff, and the bullet above stands: it names a component, not a role.

Closes #1068

🤖 Generated with Claude Code

https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661

Replace the hand-assigned `atlas-manager` role with two roles resolved at
check time: `atlas-region-manager` when a manager's `managedRegions` join is
non-empty, `atlas-event-manager` when `managedEvents` is. Being listed is the
role, so a removed listing withdraws the grant on the next request and there
is no stored value to keep in step.

The region role is today's grants minus `users: ['read']`, which has been dead
since registrations moved to `user-submissions` (#723). The event role is
`events: update/delete`, narrowed by the `manager == user` union
`regionSubtreeAccess` already had, plus the proposals on its own events.

`extractRoles` appends the derived roles only once the locale scope resolves,
so `?locale=all` keeps resolving nothing — appending earlier would hand a
listed manager their Atlas grants in all 19 locales at once.

`Regions.managers` and `Events.manager` take a field-level `update` lock:
whoever writes one hands out a role, so only an admin or a region manager
whose subtree holds the row may. An event assignee can no longer reassign or
disown the event their own grant comes from.

A manager's `user-submissions` scope now branches per role rather than
opening every proposal: a region manager reads the proposals landing in their
subtree, including the ones placed only by `regionHint` for a city the atlas
does not hold yet, which `deliverProposal` already mails them about.

The migration deletes the stored rows before the enum rebuild the generator
emitted — that rebuild's cast throws on a surviving row, which would abort the
boot migration. Its `down` rebuilds the enum rather than extending it, because
Postgres refuses to let one transaction use a value `ALTER TYPE … ADD VALUE`
added in it.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
`validateFilterOptions` re-runs on every save with no exemption for a value
that did not change, so `ownedRegionFilterOptions` returning only the owned
subtree refused two saves a manager is entitled to make: an event assignee
owns no region at all, and a region manager's own top region sits under a
parent above their subtree. Both could open the document and neither could
save it, which also blocked the re-verification a save performs.

`keepCurrent` names the field whose stored value stays selectable. Moving the
value is still refused — `scopeRegionSubtreeWrite` rejects an incoming region
outside the subtree at the row level, before any field runs.

Surfaced by #1068's second acceptance criterion, which asks for an event
assignee who may edit that event.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
`testData.authUser` re-reads a manager the way an authenticated request
carries them, with the `managedRegions` and `managedEvents` joins resolved. A
`createManager` result has neither, so a fixture built from it cannot hold a
derived role at all — every spec whose manager is listed afterwards now goes
through it.

New cases: the region role applies in every locale with nothing stored and
drops when the listing goes; the event role the same for an assignment; an
assignee may edit their own event and no sibling; a region manager may list a
manager inside their subtree and not outside; an assignee's write to `manager`
is stripped; a region manager reads the proposals landing in their subtree,
including one placed only by `regionHint`; an assignee reads the proposals on
their own events alone; and neither role reads `users`.

Two mutation checks, run and reverted: dropping the `regionHint` paths loses
the hint proposal, and dropping `extractRoles`' scope guard lets `?locale=all`
resolve a derived role.

The `users` join case now asserts the refusal rather than the join's scope,
since no manager role reaches that collection any more. Its comment says what
to restore if one ever does.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
What the two roles are read off, why nothing stores them, the scope guard that
keeps `?locale=all` resolving nothing, the join-limit rule, the field-level
lock on `Regions.managers` and `Events.manager`, which submissions each role
sees, and the `keepCurrent` clause. Plus the fixture trap: a `createManager`
result carries neither join.

`tests/PERF.md` and its three consumers take the new unit-spec count. The
timing figures are untouched — nothing was re-measured.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
Four review lenses over the branch diff. What was applied:

- `VirtualRoleUser` is `Partial<Pick<Manager, …>>` rather than a hand-written
  copy of the two join shapes, which also removes the cast at the one caller.
- Each derived role declares the join it is read off (`virtual: { join }`), so
  `virtualRoles` names none and adding one is a table edit. `isVirtualRole`
  becomes module-private — nothing outside the file read it.
- `subtreeDelegationAccess`'s factory becomes one `maySetManagerOn` predicate
  and two one-line rules. `Events.manager`'s `?? data.region` arm was dead: the
  rule is declared on `update`, where there is always a stored row.
- `PermissionsTable` hoists the pill-row style it had copied, and drops an
  `isClient` arm `virtualRoles` already answers.
- `createAuthenticatedRequest` in `tests/utils/testHelpers.ts` is deleted: zero
  callers, and it loaded a manager the way `authUser` now does minus the joins,
  so the next spec to find it would have got a user with no derived roles.

Two findings routed rather than fixed. The `regionHint` paths are a third
spelling of the proposal-routing chain, and the access plugin may not import a
collection's internals to share one — so an integration case derives the key
set from the booted `regionHint` schema and fails on a path this clause does
not query. And the same paths expand to one unindexable predicate per owned
region id each, which a `shortcut:` marker now bounds.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
Three defects found by the branch review, each reproduced before the fix.

**An event assignee could not save their own event.** Payload's admin posts
the whole document, `region` included, and the re-home guard refused any
posted region outside the owned subtree — which, for a manager who owns no
region, is every region. So the one save that re-verifies the event they are
named on answered `Forbidden`. The guard now compares the posted region
against the stored one and refuses only a real move; a bulk update, with no
one stored row, keeps the strict test.

**A region manager could not save the region they are listed on.** Same
shape: a subtree root's own parent sits above the subtree. The stored parent
is read only where the posted one is otherwise about to be refused, so a
capability check and an in-subtree save still make no query.

**The admin locale selector offered them English alone.** A derived role names
no locale and is granted in every configured one, but `filterAvailableLocales`
ranked stored roles only — so a manager whose only role is derived was pinned
to English, with the localized title of an event in their own region
unreachable. It now offers every locale, ranked stored ones first.

Also corrects the ⚠ block on `extractRoles`, and its copy in
`docs/rules/access.md`: the scope test does not stop an all-locale grant,
which is the intended behaviour. What it stops is answering a request that
names no evaluable locale.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
Removing an enum value is the one generated migration that cannot ship as
emitted: `up`'s cast throws on a surviving row, and `down`'s `ALTER TYPE …
ADD VALUE` adds a value the same transaction may not use. Both measured
against a throwaway database while writing #1068's migration, in the section
about the traps `migrate:create` leaves behind.

`tests/AGENTS.md` gains the fixture trap beside the other shared helpers: a
`createManager` result carries neither manager join, so an Atlas role derived
from one is invisible to it. `docs/rules/admin-ui.md` takes both joins where
it named only `managedEvents`, and stops naming a role that no longer exists.

Refs #1068

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXjjX5GSSTNsZgy661
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1074 November 2, 2026 23:31 Destroyed
@railway-app

railway-app Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

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

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

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

2 questions 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/accessConfigs.ts Resolved
@sydevs-bot

sydevs-bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 22:10Z address-review · attempt 2 · session · done
  • 22:10Z address-review · attempt 2 · session
  • 15:44Z address-review · attempt 1 · session · timed out
  • 15:44Z address-review · attempt 1 · session
  • 23:24Z resolve-conflicts · attempt 1 · session · done

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

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

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 Adversarial review

The diff is the ticket, no larger: one record of who manages what, replacing two that could disagree. virtual: { join } makes virtualRoles one generic filter instead of two branches, and getManagerProjects loses its managedEvents special case rather than gaining a second. The ladder found nothing re-implemented: Payload's access.update is the field lock, the memoized resolveManagedDocIds the subtree read, the JWT strategy's own joins the derived set.

One name is left behind. DashboardView's kind: 'atlas-manager' is the only one in src/ outside snapshots, and that string was the role, so a grep lands on a kind. 'atlas-non-admin' says what the branch tests. Outside this diff, so no thread.

Findings

  • should-fix — docs/rules/access.md:20 and :281 declare virtual: true; the code reads virtual: { join }, so the documented recipe yields a role offered in a select and never derived.
  • consider — regionSubtreeAccess.ts:101 storedRelationId has one caller, beside the same findByID inline at :191.
  • consider — regionSubtreeAccess.ts:87 the keepCurrent exemption reads posted data, which the JSDoc calls stored.

What was checked

Ticket #1068 criterion by criterion. Read whole from the branch: the eight changed plugins/access files, PermissionsTable.tsx, the three collections, the migration, four docs. managerSubmissionScope narrows update too, per the operation loop around its call. getRoleOptions' new throw reaches only Clients.ts:533 and Managers.ts:106, which name stored roles, so boot survives. Grepped five checkouts for atlas-manager: snapshots, DashboardView, two generated payload-types.ts; no hand-written consumer code. The two question threads were read, not restated. The preview holds no data, per the body.

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


Generated by Claude Code

Comment thread docs/rules/access.md Resolved
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 2, 2026
@sydevs-bot sydevs-bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 2, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 2, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 2, 2026
The recipe said `virtual: true` plus "a predicate in `virtualRoles`". Follow
it and the role fails silently: `virtualJoinOf` answers `undefined`, so
`getRoleOptions` offers it in a select and `virtualRoles` never returns it.
The join name is the whole declaration.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjUvJRcbWYwZrMx7ikv
`storedRelationId` had one caller, and the events branch fifteen lines down
issues its own `findByID` because it needs two fields — so the helper could
never gain a second caller in the shape it had. Its `overrideAccess`
rationale moves into the ⚠ comment already at the call site.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjUvJRcbWYwZrMx7ikv
`filterOptions` hands over posted form data, and the JSDoc called it stored —
the next reader would have trusted the exemption as a check. Taking the value
says where it comes from at the call site and drops the field-name union and
the record cast with it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjUvJRcbWYwZrMx7ikv
`keepCurrent` is the posted value, so the exemption narrows a picker and
checks nothing — and the row-level guard now refuses a real move rather than
every outside value, with the strict test kept for a bulk update.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjUvJRcbWYwZrMx7ikv
Typed `unknown`, passing the whole `filterOptions` args object compiles, and
`relationId` then reads the document's own id into the selectable set. The
narrow type refuses it — watched failing with that argument in place.

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

Copy link
Copy Markdown
Contributor Author

Addressed the critic's three findings, one commit each. The two question threads stay open — they wait on you.

  • virtual: true in the docs (thread) — adopted, c2b7ae9. Both lines read virtual: { join } now; the join name is the whole declaration.
  • One-caller storedRelationId (thread) — adopted, 98aac05. Folded into the regions-update branch, overrideAccess why kept.
  • keepCurrent's JSDoc called a posted value stored (thread) — adopted, 6f0548d. It takes the value, typed as an id. 6b08134 fixes the same claim in docs/rules/access.md, where the row-level sentence was stale too.

Lean gate ✓ (235 unit files / 3001 tests), plus role-based-access, regions, event-imports ✓ (135 tests). /security-review over the delta: nothing — it is what asked for the narrow parameter type.

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


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 3, 2026
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1074 November 5, 2026 04:39 Destroyed
Ardnived and others added 2 commits November 4, 2026 21:47
Reverts the restore. An Atlas manager reads their event's registrants on
the Registrations view (#1073), and a contact's sender address arrives in
its delivery mail; both read with `overrideAccess`, so neither needs the
Registrants collection.

The cost is deliberate and now pinned: a manager's read of a submission
carries no `senderEmail`, since that is `virtual: 'user.email'` (#1060).
Main's contact-scope cases identify rows by form instead, and the
Registrant-block case asserts the manager can read no Registrant at all.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1074 November 5, 2026 04:50 Destroyed
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 5, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 5, 2026
Ardnived and others added 2 commits November 5, 2026 11:20
`routingRegion` answers who reviews a proposal and `region` where an
accepted one is created, so `regionHint` was a second record of both.
Its `.state` and `.country` keys had no reader; `.anchorRegion` was only
the Accept fallback for a reviewer who cleared Region. That Accept is now
refused on the Region field instead, so intake's match cannot quietly undo
the reviewer's clear.

The new migration drops the column after the routing-region backfill reads it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A manager listed on a page now holds `page-editor`, read off the
`managedPages` join like the two Atlas roles. It places them in the
We Meditate Web project, with its implicit read, and grants images and
files create for the media a page edit needs. It carries no `pages` grant:
the listed pages already reach their editor through document-level
access, and a role grant would be every page. The admin locale selector
offers them English alone, since a page assignment names no language.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1074 November 5, 2026 18:42 Destroyed
@Ardnived Ardnived changed the title feat(access): derive Atlas roles from region and event ownership feat(access): derive manager roles from region, event and page listings Nov 5, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Nov 5, 2026
@Ardnived
Ardnived removed this pull request from the merge queue due to a manual request Nov 5, 2026
@Ardnived
Ardnived added this pull request to the merge queue Nov 5, 2026
Merged via the queue into main with commit 2feff13 Nov 5, 2026
26 of 27 checks passed
@Ardnived
Ardnived deleted the claude/feat-1068-derive-atlas-roles branch November 5, 2026 19:21
@sydevs-bot sydevs-bot moved this from Working to Done in SYDevelopers Technical Roadmap Nov 5, 2026
sydevs-bot added a commit to sydevs/WeMeditateWeb that referenced this pull request Nov 5, 2026
sydevs-bot pushed a commit that referenced this pull request Nov 5, 2026
All five conflicted hunks were measurement records, not behaviour. No code
file conflicted.

`tests/PERF.md`'s history table took both sides' appended rows and renumbered
them by date: #1055's 2026-11-01 run stays thirty-second, and main's three
#1074 rows shift to thirty-third through thirty-fifth. Taking either side
alone would have dropped a session's record, which the file says to never
replace.

The four count figures could take neither side. `perf-figures-pinned.spec.ts`
holds PERF.md's `Files / tests` row to the specs on disk and every consumer
doc to that row, so the merged tree's own figure is the only one that passes:
248 files and 3268 tests, measured here at 40.64 s. HEAD's 245 / 3238 and
main's 239 / 3079 each described their own branch.

A sixth copy, in `docs/rules/testing-reqs.md`'s dated-measurement sentence,
auto-merged to HEAD's 245 / 3238 without conflicting. The spec checks that
file too, so it is corrected here as well — the same class of silent fifth
copy the previous merge of `main` found in the local-vs-CI section.

Lean gate: lint, format, typecheck (src), typecheck (tests), unit lane
248 files / 3268 tests ✓ — 82 s. The two specs covering the conflicted files,
`perf-figures-pinned` and `conflict-markers`, both pass.

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

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1074 — f9c16b62 Deployed Nov 5, 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(access): derive Atlas roles from region and event ownership

3 participants