Repository navigation
feat(api): resolve canonical webUrl per owning client region - #640
Merged
Merged
Conversation
Two URL shapes, no hash: `path` appends the region path to the mount, `query` carries it in an `atlas=` parameter joined with `?` or `&`. The prefix (`canonicalUrlBase`) is the primitive rather than the whole URL, because `publicUrlFields` composes `webUrl` as `base + webPath` — both shapes can express themselves that way precisely because the path is emitted raw and always last. `atlas-url-contract.json` pins the contract for SahajCloud, SahajAtlasWeb and WeMeditateWeb to assert against byte-identically. `UrlBase` is widened to receive the same read context as `buildPath`, so a base can vary per document. Source-compatible: the existing zero-arg thunks stay assignable, since a function ignoring its parameter satisfies one that receives it. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`webUrl` was `SAHAJATLAS_URL + webPath` for every event and region — one global base pointing at a host that is `noindex` on three layers, so every canonical URL this CMS emitted named a page we had told search engines to ignore. It is now per-region. A client that owns a region gets the canonical for that region, its sub-regions and its events on its own domain; anything unowned falls back up the region tree, and finally to the We Meditate surface. `SAHAJATLAS_URL` survives only in the two live-preview URLs. `regionWebPaths` becomes `regionTree`, exposing the ancestor chain alongside the path from the same single query — ownership resolves by walking that chain, and computing it twice would be two ways for one hierarchy to disagree. `getRegionWebPaths` stays as a thin projection, so a `webPath` read still costs exactly one query. Owners load lazily in a second memo rather than eagerly with the tree: the widget's geojson feed selects `webPath` and not `webUrl`, and it should keep paying for one query, not two. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Supplying `generateURL` to the nested-docs plugin populates the `breadcrumbs.url` sub-field that has existed in the schema all along and been null only because the config never passed one. That makes `where[breadcrumbs.url][equals]='/nl/amsterdam'` resolve a region in one query — no new endpoint, no new stored field, no migration. It derives from the same `buildRegionPath` as `webPath`, so the canonical and the lookup cannot disagree. Breadcrumbs populate on write, so existing rows need a resave: `backfill-region-breadcrumb-urls.ts` re-saves roots only and lets the plugin's own cascade visit each subtree once, rather than re-saving every region and repeating the work per ancestor. A blank slug makes a whole subtree's canonical URLs unbuildable, and the slug field's uniqueness `validate` replaces Payload's `required` default while opening with `if (!value) return true` — so an empty slug passes today. `requireNonEmptySlug` closes that, on the *transition* rather than the state: 16 regions are blank in the data now, and rejecting every write carrying a blank slug would block edits to their ancestors too, since the resave cascade passes each descendant's whole document back through `update`. `audit-region-slugs.ts` reports those rows and what each costs. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ists The invariant started as a collection `beforeValidate` hook, which is the wrong seam: Payload generates the slug from `name` in a *field* `beforeChange` hook, and the collection hooks all run before that (field beforeValidate → collection beforeValidate → collection beforeChange → field beforeChange). So it saw an empty slug on every auto-generating create and rejected writes that were fine — which is what broke region creation across four integration suites. Field `validate` runs after the generator, so it is the only place that sees the value that will actually be stored. `withNonEmptySlug` wraps the uniqueness validator the factory installs rather than replacing it, and grandfathers via `previousValue`. Also collapses the nested-docs registration into one shared REGION_NESTED_DOCS_CONFIG. The test harness builds its own Payload config, so `generateURL` configured only in payload.config.ts left the whole integration suite reading `breadcrumbs.url: null` — a plugin configured in one of the two behaves differently under test than in production. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- environment.md / .env.example: WEMEDITATE_ATLAS_BASE_PATH, and a note that SAHAJATLAS_URL is deliberately not a canonical base - api-clients.md: the two URL shapes, the two-query cost, the no-fragment and raw-path rules, and the breadcrumbs.url lookup's descendant-match caveat; corrects the "#633 is data only, nothing resolves" framing now that it does - scripts.md: the backfill + audit scripts - tests/COVERAGE.md: a regions row and the three new canonical subjects Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Per the /simplify pass: - Both resolvers hand-rolled a `WeakMap<PayloadRequest, Promise<T>>`. They now use `memoizeOnRequest`, which the project already has for exactly this — and which is strictly better here: it evicts a failed load so a later read in the same request can retry, where the WeakMap cached the rejection for the request's lifetime. - `getRegionOwners` is no longer exported; `getCanonicalUrlBase` is its only caller. - `audit-region-slugs.ts` tallied events with one `count` per blank region. One `events` query over the whole affected set, tallied in memory, instead. Adds an integration test for `backfillBreadcrumbUrls` — it proves the roots-only resave really does reach three levels down through the plugin's cascade, that the path lookup then resolves, and that a second pass is a no-op. The CLI wrapper around it stays unexercised locally (bootstrapping Payload hits drizzle's interactive push prompt against a dev DB on another branch's schema). Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review raised both, and both turned out to be worth proving rather than asserting. The grandfather clause exists so the nested-docs cascade can re-save a descendant that is already blank. Nothing tested that end-to-end — only the validator in isolation. `region-blank-slug-cascade` plants a blank slug through the DB adapter (the invariant is exactly what stops the normal path creating one) and saves its ancestor. Removing the clause makes it fail with the real production error: "Could not publish or save changes: One or more children are invalid." The backfill's roots-only strategy was flagged as skipping orphans — a region whose parent id points at a deleted row. It can't: `regions_parent_id_regions_id_fk` is ON DELETE **set null**, so deleting a parent promotes its children to roots. The defensive filter I first wrote was unreachable, so it is gone; the FK behaviour it assumed is pinned by a test instead, because the strategy is only correct for as long as that holds. Also folds the audit script's local crumbId into the shared relationId, and records why the backfill loop is sequential (each root cascades through its whole subtree — concurrent roots multiply into enough writes to exhaust the pool). Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…elds The resolver read `canonical.domain` / `.mount` / `.routing`. Those fields never shipped: #633 landed as PR #635 with a different shape, where an operator picks one of the embeds the widget reported (`canonical.embed`) and the CMS fills in host, mount and routing itself from what it observed loading that page (`canonical.verification.verified`). `ClientRow` is a hand-written interface rather than a slice of the generated types, so this type-checked cleanly while `canonical?.domain` was always undefined — every client fell through and every document resolved to the We Meditate fallback. Reading `verified` also enforces #633's trust boundary: a report only nominates a candidate, so an enabled-but-unverified client owns nothing rather than shaping a public URL from unattested data. The integration spec seeded the same removed fields; it now seeds a verified snapshot through a `createOwner` helper. Mutation-checked: restoring the old read fails 5 of its 21 assertions, each falling back to We Meditate instead of the owner's domain. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ilder There were two canonical-URL builders, and they disagreed on the shape that matters. The picker's copy emitted the Atlas path with its leading slash stripped and the rest percent-encoded — `?atlas=events%2F12345`. The widget guards that parameter with `safeLoaderPath`, which requires a leading `/` and rejects a bare `relative/path` outright (SahajAtlasWeb `loader/literals.ts`, and its hostile-input table pins `'relative/path'` as refused), so a URL of that shape restored nothing — the widget silently fell back to the embed's default route. Nothing shipped had emitted one yet: the resolver that turns these fields into a public `webUrl` is this ticket. But the picker renders that URL to an operator as the sample they approve before enabling ownership, so the preview named a shape production would never emit. `canonicalTargetForHost` is the shared conversion — pure and env-free, so the admin client component can use it without reaching server-only code. The picker's own spec now asserts its sample is byte-identical to the resolver's output, so the two cannot drift apart again. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The re-root case enabled `canonical` and set an embed, then expected the event's `webUrl` to move. That skipped the step the whole trust boundary rests on: `canonical.embed` only nominates one of the mounts the widget reported, and a report is reachable by anyone holding a published key from an allowed origin. Split into the two states it was conflating — enabled-but-unverified must leave the canonical exactly where it was, and only the job-written verified snapshot re-roots it. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…step `WEMEDITATE_ATLAS_BASE_PATH` was documented in `.claude/docs/environment.md` but missing from DEPLOYMENT.md's frontend-URL list, which is what an operator reads when provisioning an environment. Also records the two things that are only obvious from the ticket: the We Meditate fallback page does not exist yet, so unowned regions resolve to a 404 until it ships; and the breadcrumb-URL backfill has to be run once after deploy, because breadcrumbs populate on write. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three of the new suites had a byte-identical `createRegion` helper, differing only in the `mapboxId` prefix that keeps them from colliding on that unique index. Extracted to `testData.createRegionNode`, which takes the prefix. Kept separate from the existing `testData.createRegion`: that one makes a single throwaway city with a random id, where here the slug, level and ancestry are the fixture. Per /simplify pass. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`canonical.verification.verified.domain` is declared to be a bare host by `CANONICAL_DOMAIN_PATTERN`, and the JSON schema enforces it on `payload.update` — but the VerifyEmbeds job persists that column with a raw `pool.query`, so the schema never runs on the write that actually fills it. `splitMountKey` records `url.host`, which keeps a port, and `allowedDomains` compares port-stripped hostnames — so a mount of `https://example.org:8080/` passes the gate and stores `example.org:8080`. Inert until now: the value only rendered an admin sample. This ticket is what interpolates it into a public canonical URL, so the check has to hold here. Placed in `loadDirectOwners`, before the ancestor walk rather than after it. An unusable client is then skipped as an owner and the next ancestor up wins — put it at target-build time instead and one bad client mid-chain collapses its whole subtree to the We Meditate fallback, which an integration test caught. `canonicalTargetForHost` keeps the same guard for the admin picker, which now shows no sample rather than one the resolver would refuse. Deliberately *not* fixed by having `splitMountKey` drop the port, which was the reviewer's suggestion: the verifier loads the mount URL itself, so dropping it would verify `:8080` and publish `:443` — a page we never looked at. The integration test writes the column with the same raw UPDATE the job uses; going through `payload.update` is rejected by the schema and would prove nothing about the state the job can leave behind. Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Refs #634 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-640 environment in sahajcloud
|
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-640
August 19, 2026 20:02
Destroyed
Ardnived
added a commit
that referenced
this pull request
Aug 25, 2026
Rebasing #642 onto main reordered the chain but left its snapshots alone, so the newest one — the only one drizzle diffs against — still described a parallel history: no canonical columns from main's #635/#640, no registration columns from #626. Every `migrate:create` on this branch (and on main, which has the same file) emitted a bogus catch-up re-proposing DDL that was already applied, which would crash a deploy with "column already exists". Applying was never affected — snapshots aren't consulted then, and the `up` SQL across the chain is disjoint and correctly ordered. This only ever broke *creating* the next migration, which is why it surfaced the moment one was needed. Regenerated from the current config and swapped in. That is strictly more correct than what it replaced: `20260819_*` sorts before `20260820_*`, so the cumulative schema at this point in the rebased chain genuinely does include main's columns. The diff is exactly that — clients/_clients_v gain the canonical fields and lose `legacy_config`, registrations gain `event_feedback`, `event_feedback_at`, `follow_up_sent_at` — and nothing else. Safe to swap because Payload's adapter doesn't chain snapshots by id: `prevId` is all-zeros on every one of them. Verified the way the problem announced itself — `migrate:create` against an unchanged config now emits an **empty** migration body instead of a catch-up. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]>
Ardnived
added a commit
that referenced
this pull request
Aug 25, 2026
…and one shared activity log (#626) * feat(events): registrant confirm/deny voting with Wilson-scored community verdicts Registrants can now vouch for (or deny) an unverified event they attended, through the built-in Registrations update endpoint - no custom endpoint and no login: possession of the registration uuid (?registrationUuid=) is the credential, scoped in the access layer to exactly that one row, and the client patch is whitelisted to the eventFeedback field. - vote gate: feedback only while the event is published + unverified (denied and adopted events stop collecting votes; 409 feedback_closed) - sync hook recounts both tallies per vote (converges under races), writes the Wilson lower bound to the indexed confidenceScore (feed ranking) and the tallies into systemMeta.communityFeedback, and flips the event to denied + draft when >= 5 denials AND the Wilson upper bound < 0.5 - pure verdict math in lib/eventVerification (wilson-score-interval dep) - SendPostEventFollowUps job (daily): emails each registrant once after their registered occurrence passes (followUpSentAt ledger, 30-day window) with confirm/deny links to a tokenized SahajCloud page; the email's sections prop is the extension point for future follow-up content - /registrations/feedback page mirrors /events/verify: signed token, vote recorded only on explicit POST through the normal update path Co-Authored-By: Claude Fable 5 <[email protected]> * fix(feedback): answer once, then confirm — not the same question twice The emailed buttons say "Yes, it took place", and clicking one landed on an identical question you had to answer again. That reads as though the first click failed, and the second page couldn't even tell which button had been pressed — it showed the same two, so it was no protection against a misclick either. A `?vote=` arrival now submits that answer on mount and goes straight to a confirmation naming what was recorded, with a link to flip it. An answer already on file is no longer a dead end for the same reason: realising you misclicked is exactly why you'd reopen the link, and "Already recorded" took the choice away at that moment. **The vote still travels by POST.** That was the real point of the old two-step: mail scanners and prefetchers issue GETs, and a vote nobody cast corrupts the community verdict this feature exists to produce. Auto-submitting from JS keeps a real reader to one click while a scanner fetching the URL still records nothing — verified by GETting a live link and confirming `eventFeedback` stayed null. `<noscript>` keeps the two buttons for anyone without JS. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(feedback): send the reader into Atlas once their answer is recorded Both answers ended on our own confirmation card and stopped — a dead end for someone who just told us they were interested enough to attend a class. The vote now resolves a destination and redirects there, so the last step of a feedback email becomes a way back into the map. **A denial does not land on the event.** They have just said the class isn't there, so the listing is the one page that shouldn't greet them — and if theirs was the fifth denial, that vote has already unpublished it and `webUrl` reads null, because the field is publish-gated. Regions carry `requirePublished: false`, so the region page resolves either way and is the better re-engagement surface for someone who couldn't find a class. Confirmations go to the event, falling back to the region. The destination is resolved *after* the write, since it depends on what the write just did, and `redirect()` is called outside the try — it signals by throwing, and the catch would have reported a failed vote that in fact succeeded. No token rides along: it would sit in the address bar of an indexed page and leak through `Referer`. A reader who misclicked still has both buttons in the email, and the page handles an already-answered registration by offering to flip it. Nothing regresses if the Atlas half is late — an unresolvable destination keeps the reader on the current card, which is also the state until sydevs/SahajAtlasWeb#164 ships. The decision is pure and unit-tested (`feedbackDestination`); the read stays in the action. Mutation-checked: routing denials to the event fails two of the six cases. Refs #626, sydevs/SahajAtlasWeb#164 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(tokens): one HMAC helper for three link types; drop wilson dep There were **three** hand-rolled copies of the same signed-token construction — `utilities/signedToken` (86 lines), `eventVerification/ token` (112) and `registrations/unsubscribeToken` (78) — written months apart, each re-deriving base64url + timing-safe compare. Three places for a signature bug to hide, and only one of them had the `kind` discriminator that stops a token minted for one link being replayed against another. They now share `signedToken`, which grew `ttlMs: null` for the never-expiring case the unsubscribe link deliberately wants: that link authorizes one narrow idempotent action and may legitimately be clicked months into a course, so an expiry would break real links and prevent nothing. **The wire format changed**, so tokens minted before this don't parse. Handled differently per link, on the merits: - **Verify links** drop the old format outright. They last 10 days, and a manager whose link lapsed can verify from the event's admin banner. - **Unsubscribe links** keep a legacy read path — the one place backwards compatibility is worth its lines. They never expire, so every reminder email ever sent still holds one, and what they authorize is *stopping email*: a 404 there means someone who wants out reports the message as spam instead. Nothing signs that shape any more, and it's covered by two tests. Also drops `wilson-score-interval`: six lines of closed-form arithmetic shipping no types, which obliged us to hand-write an ambient module declaration — a contract that could silently disagree with the package it described. Inlined beside the domain wrapper that already had a unit test pinning its values, and `src/types/wilson-score-interval.d.ts` is deleted. The unsubscribe spec asserted the whole payload shape; it now asserts the absence of `exp`, which is the actual contract. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(jobs): keep a job's own code in the job, enforced by a test Six modules under `src/lib/` had exactly one consumer each — a job. That isn't shared code; it's one job's private helper sitting in the commons, importable by anything and read by the next person as though it were general-purpose. `verifyUrl`, `findOrCreateCity`, `sendSubmissionReview`, `sendRegistrationDigest`, `sendSessionReminder` and `unsubscribeUrl` now live with the job that owns them. The **view layer is untouched**: templates stay in `src/emails/` and a job's sender imports its template from there. What moved is the sending logic, which was never shared. Rule 4 of project-structure.md already said this; nothing checked, so it drifted. `tests/unit/lib-boundary.spec.ts` now fails the unit lane on any lib module whose only consumer is outside lib. **Writing that test corrected the analysis three times.** A `@/lib/…` grep says `recipients.ts` has one consumer; it has three, two reaching it through the notifications barrel — it stays in lib. `browserRendering.ts` is imported as `./browserRendering` by `verifyEmbed.ts` next door, which no path search sees — it stays too. And the email preview scripts import senders directly. Both would have been silently wrong moves; both were reverted after the test found them. Two exemptions are principled rather than convenient: a module consumed only from *inside* lib is a shared module decomposed into parts (a barrel and its members, or a seam like `turnstile/` kept separate so it tests without booting its caller), and one consumed only by `scripts/` is an operator routine deliberately kept testable outside its CLI wrapper — a pattern `.claude/rules/scripts.md` already records per backfill. `KNOWN_SINGLE_CONSUMER` records the seven that predate the check. A backlog, not an approval; it should only shrink. Also drops a dangling `buildVerifyEmailLink` re-export — the barrel was its only remaining reference. Mutation-checked: putting `findOrCreateCity` back in lib fails the guard. Test reads each source once (the first version re-read the tree per module and blew the lane's 5s budget); 1.4s for ~150 modules. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(registrations): name the system-req cast, tighten the vote gate `feedbackDestination` moves next to its only consumer. The token helpers it shared a file with are genuinely cross-boundary — the follow-up job signs, the page verifies — but the destination decision is the page's alone, which is what made that file feel like a grab-bag. `{ ...req, user: null } as typeof req` becomes `asSystemReq`, beside `asTrustedReq`. It was doing something subtle enough to need a comment every time: `overrideAccess` skips collection access but *not* `filterOptions`, which Payload validates against `req.user`, so a client-triggered system write touching the events `region` picker was 400ing on a filter the caller could never pass. The vote gate resolves the event once and applies one condition, instead of nesting the checks inside `if (eventId != null)`. **That last one is smaller than I first described it.** I claimed the gate silently accepted votes when the event couldn't be resolved; it didn't — a failed lookup was always refused, and only a wholly absent relationship skipped the gate, which `event: required` makes unreachable. The mutation check is what caught the overstatement: the new test passes against the old code too. Kept as a simplification, and the test kept for its own sake — that a trashed listing stops accepting the votes deciding whether it stays down was untested. `eventFeedbackAt` is **not** removed, though it is still write-only. Generating the migration produced a diff full of main's canonical columns and no drop at all: every `20260820_*` snapshot dates from before #642 was rebased onto main, so drizzle diffs from a schema out of a parallel history. That blocks *any* new migration on this branch, not just this one, and re-baselining the chain is its own careful change. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(tokens): sign email links with jose, and drop the legacy reader Answering "is there a library for this": **`jose`**, and it was already in the tree — Payload depends on it to sign its own auth JWTs. Adding it directly (pinned to Payload's 5.10.0, so the install keeps one copy) means the email links use the primitive the framework already trusts, and this repo now hand-rolls no crypto at all: `createHmac` and `timingSafeEqual` appear nowhere in `src/` or `tests/`. What the library buys beyond deleted code: - the algorithm is pinned on **verify**, so a token can't talk us into `none` or into an asymmetric alg — the classic JWT confusion attack, which our own verifier had no notion of; - `exp` is the library's job, against an injectable clock; - an authentic-but-aged token raises `JWTExpired` specifically, which is what lets the page say "this link expired" instead of 404; - `kind` becomes the JWT **audience**, checked by `jwtVerify` before any claim is read, so one link type can never be spent as another. The legacy unsubscribe reader is **gone** — no reminder emails have ever been sent, so nothing holds a token in the old format, and the compatibility path I argued for last round was protecting an empty set. `signToken`/`verifyToken` are now async (jose is promise-based), which rippled to twelve call sites; all were already in async contexts — server components, server actions, jobs, lifecycle ops. Tests: the forged-token cases were rebuilt as three-part JWTs, keeping the real header and signature and swapping only the claims, so they still fail on the *signature* rather than passing trivially as malformed. Added a cross-kind replay case. Mutation-checked — dropping the `audience` option fails both. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(migrations): re-baseline the newest snapshot after the #642 rebase Rebasing #642 onto main reordered the chain but left its snapshots alone, so the newest one — the only one drizzle diffs against — still described a parallel history: no canonical columns from main's #635/#640, no registration columns from #626. Every `migrate:create` on this branch (and on main, which has the same file) emitted a bogus catch-up re-proposing DDL that was already applied, which would crash a deploy with "column already exists". Applying was never affected — snapshots aren't consulted then, and the `up` SQL across the chain is disjoint and correctly ordered. This only ever broke *creating* the next migration, which is why it surfaced the moment one was needed. Regenerated from the current config and swapped in. That is strictly more correct than what it replaced: `20260819_*` sorts before `20260820_*`, so the cumulative schema at this point in the rebased chain genuinely does include main's columns. The diff is exactly that — clients/_clients_v gain the canonical fields and lose `legacy_config`, registrations gain `event_feedback`, `event_feedback_at`, `follow_up_sent_at` — and nothing else. Safe to swap because Payload's adapter doesn't chain snapshots by id: `prevId` is all-zeros on every one of them. Verified the way the problem announced itself — `migrate:create` against an unchanged config now emits an **empty** migration body instead of a catch-up. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(registrations): drop the write-only eventFeedbackAt column Stamped by the vote gate on every write and read by nothing — not a feed, not the admin, not a query; only its own test asserted it existed. Deferred last round because the snapshot drift made its migration impossible to generate. With the baseline corrected, it comes out as one reversible line. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor: simplify per /simplify pass - `lib-boundary` built its import graph per lib module, scanning every source ~150 times. 1.4s alone, 8.5s inside the parallel unit lane — which is the only place it runs, so it was failing the gate it exists to protect. Inverted to one pass over the files: 53ms. The sharper resolution also found a single-consumer module the buggier one missed (`sendRegistrationNotification`), baselined since it predates the check and this branch doesn't otherwise touch it. - `syncCommunityFeedback` awaited the event read after the two vote counts, though it depends on neither. All three now go together — one round trip instead of two, in an afterChange hook. - `signFeedbackToken` spread its claims into a fresh object; it now names the field, like the other two kind modules, so a field added to `FeedbackTokenClaims` can't silently become a JWT claim. Reuse and altitude passes found nothing. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * docs(rules): record the new email template and asSystemReq Two surfaces the branch made incomplete rather than stale: - `email.md` keeps a row per template and had none for `PostEventFollowUpEmail`, including the composable-`sections` shape that is the extension point for future follow-up kinds. - `api-clients.md` documents the `asTrustedReq` / `isTrustedReq` pair; `asSystemReq` now sits beside them, with the trap that motivates it — `overrideAccess` skips collection access but not `filterOptions`, which Payload still validates against `req.user`. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * feat(fields): one delivery-log field, and registrant-mail parity **`logField`** — "did that email actually go out, and to whom?" is a question managers ask, and answering it meant a database query. Two logs already existed and agreed on nothing: the Events verification log was rendered, the Registrations reminder ledger was invisible; one reset per cycle, one grew forever uncapped; each had its own coercion and membership helper. A third was about to be added for follow-ups. Now a factory in `src/fields/` with the shared config, a shared table (When / What / Sent to, newest first), and helpers — `asLog`, `hasLogEntry`, and `appendLogEntry`, which **caps** the log and drops the oldest. That cap is the robustness fix hiding in the abstraction: a reminder log on a weekly class gained an entry per occurrence, read and rewritten on every send, bounded by nothing. Entries tolerate extra properties and the renderer is overridable, so the verification log keeps its own columns — escalation level, recipient tier, linking region are what tell a manager *why* a reminder went where it did — while sharing the config and the cap. `Registrations.reminderLog` → `emailLog`: every message about a registration, reminders and follow-ups together, and **visible for the first time**. `followUpSentAt` stays: nothing can `where` on a JSON column cheaply, so the log is the record and the column is what the sweep selects on. Dedup now matches `event` *and* `key` — one log holds several kinds of message, and a bare key would collide. **Registrant-mail parity.** The follow-up email shared the layout components but broke four conventions its three siblings keep: no client branding (project brand instead), no localization (hardcoded English despite the registration carrying a `locale`), no `Reply-To`, no plain-text part. All four fixed, with seven new translation keys; the six-point checklist is now in `.claude/rules/email.md` so the next one can't half-land the same way. Also drops a dead branch: `extractRegistrationUuid` read `searchParams` as a fallback to `query`, which `createPayloadRequest` makes unreachable — it sets both from the same parse. The spec couldn't tell, because its hand-built request set only `query`; the fixture now sets both. Mutation-checked: removing the cap fails two of the nine log tests. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(fields): one log table, entries choose their own columns `NotificationLogTable` is gone — folded into `LogTable`, which now renders whatever columns an entry declares. Both logs go through it: the verification cycle keeps Activity / Who / Delivery, a registration shows Activity / Sent to, and neither is flattened into the other's shape. The wording moved with the columns. `format.ts` computed labels at render time from an entry's `kind`, `level` and `role`; `buildReminderEntry` and `buildVerificationEntry` now emit them, because the code that knows *why* a reminder went where it did is the code that writes the entry — the same reason screening composes its own notes. **Display lives under `cells`; everything else on an entry is data.** I had it the other way round first — every non-reserved key a column — and checked the output rather than assuming: the verification log rendered **fourteen** columns of raw enum values, because its entries carry `kind`, `stage`, `level`, `role`, `manager`, `channel` and more for `hasReminderForStage` to read back. Opt-in display keeps those readable as data and invisible as UI. Columns come from the **union** of entries, not the newest: a log whose latest entry is a cancellation would otherwise drop the recipient column and hide it for every email above. A cell is a string or `{ label?, text, sub? }` — `label` muted inline (`email: [email protected]`), `sub` muted beneath (a recipient's role and region). Those two options are exactly what the deleted `WhoCellView` and `DeliveryCellView` did. The field is now **`activityLog` / "Activity Log"** by default, since these record more than mail — a registration created or cancelled belongs here too. Both name and label stay overridable: Events keeps `notificationLog`, which resets per verification cycle rather than accumulating. Specs follow: the timeline fixture builds entries with the real builders instead of hand-shaping them, and the importer's seed assertion narrowed to the machine fields it is actually about. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(fields): declare log columns on the field, and show the rest on ⋯ Three changes to the activity log. **Events' `notificationLog` is `activityLog` too.** An event's history will grow past verification, so the generic name and label apply there as well; it keeps its own field only because it resets per cycle rather than accumulating. **Columns are declared by `logField` and delivered in `admin.custom`**, the way `SelectDescription` and `EventQualityPanel` get their config, instead of being derived from whatever the entries happened to carry. Order and headings are now fixed before the data is — a log that has only ever recorded one kind of event still shows the shape it grows into. Derivation stays as the fallback, so a new log is zero-config. **Every row ends in a ⋯ that opens the whole entry as JSON.** Columns carry what a manager usually needs; this is where the rest lives — a reminder's stage, level, recipient tier and exactly-once key. Payload's `Popup` renders into a portal, so a wide JSON block can't stretch the table it hangs off. **The migration is hand-edited, and that is the point.** Drizzle can't tell a rename from a new column, so it emitted a drop+add — which would have discarded every verification cycle on every event, since the Atlas import seeds an entry and each verification writes one. Rewritten as `ALTER TABLE … RENAME COLUMN` (both the table and its `_v` twin), which preserves the data and leaves the snapshot correct. Contrast the registration log's rename in the previous commit: that column was provably empty, so drop+add was safe there. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(admin): open log details on row hover, not a column that scrolled away The ⋯ column sat at the far right of the table's horizontal scroll area, so on a narrow window the details were present and unreachable. Gone: hovering anywhere on a row opens the entry, and the panel is pinned to both edges of the field rather than to the row, so it can't repeat the trick at any width. Verified at 620px. Payload's `Table` exposes nothing per row, so this went through two shapes. Wrapping each cell — the obvious way to keep the built-in — left the cell *padding* dead: hovering `td.cell-delivery` did nothing, because the handler was on a div inside it, and the pointer crossing the gap between two values dismissed the panel. One delegated `mouseOver` on the wrapper covers the whole row including its padding, needs no per-cell markup, and is less code. Payload writes our own array index into `data-id`, which is what makes the row identifiable without owning the `<tr>` — so the table still renders itself and no styling is reimplemented. `focus` bubbles the same way, so the one listener serves the keyboard too; the When cell carries the single tab stop per row, since hover alone can't reach the machine fields this panel exists to show. Also fixes the double scrollbar: the panel was a `<pre scroll>` nested in Payload's `Popup`, which scrolls as well, so a wheel gesture moved whichever the pointer happened to be over. Dropping `Popup` for a plain positioned panel leaves exactly one scroll container. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(admin): open a log entry in a Drawer on click, not on hover The hover panel reached the details at any width, but opened and closed as the pointer crossed the table — motion nobody asked for while reading a log. A click is deliberate, and it lets Payload own the rest. Now `Drawer` + `useDrawerSlug` + `useModal`, the pattern `.claude/rules/admin-ui.md` already documents: the overlay, title bar, close button, focus trap, dismissal and scrolling are all Payload's. That deleted the hand-rolled positioned panel, its offset measurement, and the second scroll container — the component is **62 lines lighter** than the hover version and imports one more built-in. What stayed custom is what has no built-in: the delegated `closest('tr[data-id]')` lookup, since `Table` exposes nothing per row, and a four-line stylesheet for `cursor: zoom-in`, which belongs on Payload's own `<tr>` and so can't be an inline style. Same `styles.css`-beside-the-component pattern as `EventSubmissions`. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(admin): make the log drawer slide, and the row hover visible on stripes **The drawer appeared in place because it was mounted already open.** `Drawer` seeds `animateIn` from `modalState[slug].isOpen` with `useState` — read once, at mount — and only adds `drawer--is-open` in a layout effect. Rendering it behind `selected !== null` meant it mounted in the same tick as `openModal`, so `animateIn` initialised to `true`, the class was present on the first paint, and there was no transition left to play. Mounting it unconditionally lets it mount closed and animate on open; it returns null while closed, so this costs nothing. **Hover matched the stripe.** Payload stripes odd rows with `--theme-elevation-50`, so hovering at that value left every other row looking untouched. `-100` was still indistinguishable under this project's theme (the elevation scale is overridden per project); `-150` reads clearly against both the striped and plain rows. Checked against a rendered table rather than the token names. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * docs: follow the log rename and the shared table through the rules Four references the branch made stale: - `architecture.md` still named `reminderLedger.ts` (deleted) and the `reminderLog` it read; the reminder job now dedupes on the shared `activityLog`, and the unsubscribe token is no longer a hand-rolled HMAC. - `admin-ui.md` pointed at `NotificationLogTable/` as the `Table` reference; it points at `LogTable/` now, and names the two things `Table` forced it to hand-roll — a delegated row listener, since nothing is exposed per row, and a stylesheet rule for `cursor`, which belongs on Payload's own `<tr>`. - `collections.md` described `notificationLog` as a name Events keeps; it doesn't any more. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> * refactor: simplify per /simplify pass Resolve a clicked log row by its position in `<tbody>` rather than by Payload's `data-id`. Correct either way today, but the attribute is Payload's to rename, and the failure mode was a click that silently found nothing. Row order is inherent to a table. Reuse and simplification passes found nothing. Four efficiency findings were rejected — see the PR description for the reasons. Refs #626 Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Ardnived
added a commit
that referenced
this pull request
Aug 25, 2026
* feat(api): serve SEO metadata for an atlas route Adds `GET /api/atlas/seo?route=/gb/london&locale=fr` — one route-keyed root endpoint that resolves a region or an event and answers with everything a host page needs to render it: title, meta description, canonical, hreflang, Open Graph, escaped JSON-LD, and the body content it renders as children of `<sahaj-atlas>`. Keyed by route rather than by id because a route is what a consumer holds. An id-keyed shape would make WeMeditateWeb and the WordPress plugin each resolve path -> id first, which is two round trips and the same logic written twice. The route is parsed with the same rule the widget applies to the same string, so a server-rendered page and the widget that upgrades over it cannot disagree about which document a URL names. Notable contract choices, all documented on the handler: - `canonical` is the document's own `webUrl`, read and never recomputed, so it is byte-identical to what #640 publishes everywhere else. - No HTML crosses the wire: a description arrives as plain-text paragraphs. The WordPress plugin echoes this into a template that never passes through `wp_kses`. - `jsonLdEscape()` escapes `<`, `>`, `&` and the two Unicode separators, so a CMS-authored string containing `</script>` or `<!--` cannot break out of the block it is embedded in. - A region has no description in the CMS, so it gets `description: null` rather than an untranslatable English sentence in somebody else's `<head>`. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(api): document /api/atlas/seo in the OpenAPI shim, with unit coverage The shim entry is where a consumer learns the parts of this contract it cannot infer — that the canonical is locale-free, that jsonLd is already escaped, that no HTML crosses the wire, that a region's list is capped while eventCount is not, and that an unresolvable route is a 404. Each of those is asserted in the guard spec, because a silent omission there is a consumer guessing wrong. The unit specs cover the two halves that need no database: route parsing (the widget's own rule, including view segments and legacy prefixes) and shaping (escaping, hreflang, JSON-LD nodes, the region/event variants). The escaping assertions were checked by flipping the escape off and confirming they go red. Moves the endpoint's private modules from src/lib/atlas/ into src/endpoints/atlasSeo/, which is where lib-boundary.spec.ts says single-owner code belongs — they had exactly one consumer each. `widgetLocales.ts` stays in lib, since the OpenAPI shim reads it too. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(api): key an atlas region route on its slug, not its breadcrumb trail The integration spec caught the region lookup resolving a city route to a venue two levels beneath it. `where['breadcrumbs.url'][equals]` looks like an exact path match but `breadcrumbs` is an array, and Payload's `equals` on an array sub-field matches when ANY element matches — so `/gb/london` matches every descendant of London as well as London itself, and which row comes back is whatever the database returned first. #640 shipped `generateURL` specifically to enable that lookup, and both the ticket and the programme record assert it works, so this is worth stating plainly: the stored `breadcrumbs.url` is a fine denormalization, it is just not a unique key. The region slug already is one — globally unique and indexed, and the importer disambiguates the handful of colliding names. So a route is now keyed by its terminal segment for both variants, which is also what the widget's own `resolvePath` does. That makes stale ancestry resolve rather than 404: a region moved in the tree, or a country re-slugged to its ISO code (#556), still lands on the right document, and the `route` and `canonical` in the answer name the URL the host should redirect to. 404-ing every inbound link into a restructured subtree is the opposite of what this endpoint is for. Adds tests/int/atlas-seo.int.spec.ts (29 cases) over a two-owner tree with a venue under a city: the canonical matching each document's own `webUrl`, each breadcrumb rung matching its own ancestor's, the descendant-inclusive listing, the 404 matrix, and an end-to-end check that a class titled `</script>...` leaves nothing for an HTML parser to act on. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(tests): register the atlas SEO endpoint in the coverage map Also records the breadcrumb-trail finding on the regions row, since that is where the next person will look before reaching for `breadcrumbs.url` as a lookup key. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(architecture): describe the atlas SEO endpoint and its contract Three things a reader would otherwise have to derive from source: that a route is keyed by its terminal segment, that `breadcrumbs.url` equality matches any trail element rather than one region, and that nothing in the atlas is localized (which is why the canonical is locale-free and why the endpoint composes no prose). Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(api): cover the og:image chain and decouple the mutating cases `images` is a relationship whose `url` is itself a virtual field, populated under the caller's own access — so an absent `og:image` would have been a silent failure rather than an error. One case now asserts the whole chain. The two cases that create their own class now put it in a sandbox city under France, so the UK listing counts don't depend on which cases have already run. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(api): simplify per /simplify pass Three findings applied from the cleanup agents: - Read an event at `depth: 0` and fetch its images only when it has some. The `depth: 1` read existed for `images`, but it also populated the event's `region` — a whole extra `regions` query, running that region's own webPath / webUrl afterRead hooks, for a document reduced to an id one line later. Most classes have no photos, so they now pay nothing at all for the image read. Pinned by a query-budget test: an event route costs exactly one `regions` and one `clients` read, and touches `images` only when there are any. - Extract `locationNode()` out of the triple-nested ternary in the JSON-LD event builder. - `images` now arrives on `EventSeoInput` rather than being read off the event, which keeps the shaper's "endpoint does the I/O" contract honest. Two findings rejected. `descendantRegionIds` and `getCanonicalUrlForRegion` were reported as lib-boundary violations that would fail CI; they are not — the check counts consumers per module, and both live in modules with several (`lib-boundary.spec.ts` passes). They are also at the right layer: the first sits beside `resolveOwnersByRegion`, the other pure function over the same `chainById`, and the second beside `getCanonicalUrlBase`, so canonical URLs stay composed in one place. And the per-ancestor re-await of the memoized tree in `regionBreadcrumbs` is a handful of microtasks on already-resolved promises; inlining it would create a second place that builds a canonical URL, which is the one thing this endpoint is careful not to do. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(api-clients): fold the atlas SEO endpoint into the client rules Two statements the endpoint made stale: contact-admin was the only root endpoint calling `assertClientOriginAllowed` itself, and the finished-events table listed every client-facing read. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(deploy): note that the Cache Rule's slug list misses root endpoints `GET /api/atlas/seo` emits the same cache headers as any client read, but the Cache Rule enumerates paths by collection slug and `atlas` is not one — so it stays DYNAMIC and every SSR page render reaches the origin. Nothing breaks (same fail-safe as an absent rule), but the caching never activates, and this endpoint is called once per host page render by two consumers. Records the one-line fix. The gap had not come up because the only prior root endpoint is a POST. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(api): keep the editor's image order, so og:image is the lead photo Reading a class's photos with `id in (…)` returns rows in database order, which is descending — so an event whose editor arranged its images ascending got them back reversed, and `og:image` unfurled the LAST photo instead of the first. The ordering was free while the event was read at `depth: 1` (Payload's own populate preserves a hasMany field's order); fetching the images separately, which is what makes a photo-less class cost nothing, is what dropped it. Re-applies the id order after the read, and drops ids with no surviving row rather than leaving a hole. The first version of the regression test asserted one fixed ordering and stayed green with the fix deleted — the database order happened to match it. It now asserts both directions, so whichever way the database sorts, one case must disagree with it. Verified by deleting the reordering and watching the ascending case go red. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(deploy): record the Cache Rule now covering /api/atlas/seo The rule was edited on the live zone (ruleset v8 -> v9), so the previous note — which said the endpoint stays DYNAMIC and told the reader how to enable it — was stale the moment it shipped. Keeps the reason the term had to go inside the existing rule rather than into a new one: only that rule carries the Authorization-present conjunct, and without it an unauthenticated request is served the cached authed body. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(api): move the SEO endpoint to src/endpoints/atlas/seo The folder path now mirrors the URL it serves: src/endpoints/atlas/seo/ -> GET /api/atlas/seo, handler in index.ts. A reader looking for what answers a route no longer has to know that `atlasSeo` is the camelCase of a two-segment path. Records the convention in the endpoints and project-structure rules, including why the supporting modules stay in the folder rather than moving to src/lib/ (single-owner code — lib-boundary.spec.ts fails a lib module with one consumer outside lib). `responseTypes.ts` stays at src/endpoints/ since both root endpoints share it. Pure move: no behaviour change, and the exported symbol is still `atlasSeo`. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(atlas): let an operator own the atlas language set The hreflang list was a hardcoded constant duplicating `supportedLanguages` in sydevs/SahajAtlasWeb — two lists that could disagree, neither of which an operator could change. It now lives on the Sahaj Atlas configuration global and the SEO endpoint reads it per request (memoized, so a route still costs one read), which makes enabling a language a content decision rather than a deploy in two repos. ⚠ The field is named `languages`, not `locales`, and that is load-bearing. A sub-table on a global is named `<global_table>_<field>`, and Payload already uses the `_locales` suffix for a localized document's value table — so a field called `locales` generates `sy_atlas_config_locales`, collides with that convention, and every read of the global then dies in Drizzle's relation builder with `Cannot read properties of undefined (reading 'referencedTable')`. Reproduced with select+hasMany, with an array, and with the array localized, on both the dev database and a fresh test schema; renaming the field is what fixes it. The comment on the field says so, because the next person to add a field here will not guess it. The constant survives as `ATLAS_DEFAULT_LOCALES`, serving as both the field's defaultValue and the fallback for an unconfigured column — one definition, so they cannot drift. That fallback is not cosmetic: production's global row already exists, a defaultValue does not backfill it, and without a matching fallback this deploy would collapse every atlas page's hreflang cluster from ten languages to one. It also means no data migration is needed. The OpenAPI enum stays the CMS locale superset, because the spec is built statically and the effective set is now runtime data — the description says so and points readers at `alternates`. Coverage splits along the same seam: the wiring (global changes -> hreflang changes, live) is an integration case, while the states the API cannot produce are unit-tested against the pure normalizer. An empty set is one of those: the field is `required` with `minRows: 1`, so Payload rejects it outright. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: record the operator-owned language set and the `locales` naming trap The globals rule described the Atlas config field-by-field and no longer matched it. It now covers `languages`, and carries the warning that cost real debugging time: a global's sub-table is `<global_table>_<field>`, Payload reserves the `_locales` suffix for a localized document's value table, and a field named `locales` therefore makes every read of that global 500 in Drizzle's relation builder. The fix is the field NAME, not its shape — worth stating plainly, because the failure looks nothing like a naming problem. Also notes the operator-owned hreflang set in the architecture doc, and the new coverage in the test map. Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(api): apply the simplify + review pass - Overlap the independent reads. An event route resolved images, ancestry and the language set one after another; a region route awaited the language set after its other reads had already returned. All now ride in one Promise.all. The risk that introduces — concurrent first-callers racing the per-request memo — is exactly what the query-budget test pins, and it still reports one `regions` and one `clients` read. - Breadcrumb `route` is `null`, not `''`, when a blank slug in the chain means no path can be built. It now goes null in the same cases `url` does, instead of an empty string that a host would render as a link to the current page. The published type said "Always present", which was false. - Simplify the recurrence interval to `Math.max(…, 1)` (same result for every input, including 0, negatives and undefined), hoist the schema's locale list, and drop an `isValidLocale` re-check that Zod's own refine already narrowed. That last one was checked rather than trusted: `.refine()` does not usually narrow, so a type probe was used to confirm `parsed.data.locale` really does infer as `LocaleCode | undefined` before the guard was removed. Rejected: the reported `weekdays` "double check" (the guard is on `firstDate`, not `recurrenceType`), an `og:image` "undefined" leak (guarded by `if (args.image)`), a region slug shadowing a reserved word (slugs are lowercase and the shadow is the documented guard), case-insensitive slug lookup (would diverge from the widget's own rule), `descendantRegionIds` being O(n·m) (~2400 checks on already-loaded maps, once per request), and the import-order reports (eslint enforces that rule and passes). Refs #645 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This was referenced Oct 30, 2026
Ardnived
added a commit
that referenced
this pull request
Nov 2, 2026
…1061) Backfills (owner confirmed both are done): delete scripts/backfill-region-breadcrumb-urls.ts (#640) and scripts/backfill-schedule-last-date.ts (#604), the src/lib routines only they used, their int specs, and the doc rows pointing at them. New writes fill breadcrumbs[].url and schedule.lastDate on their own, and region-canonical-url / events specs cover that live behaviour. seeds/tests harness: test-storyblok.sh and test-meditations.sh run importers that have had no CLI entry point since #156, so each "test" exited 0 having done nothing; check-db-stats.ts queried the music collections renamed in #180. Delete them with setup-test-db.ts and test-payload.config.ts (used only by them), rewrite the folder guide around the spec that stays, and drop the third buildConfig site from the systemEntities / access.md / postgresTestPool comments. Smaller: meditation-duration's "backfill migration logic" block re-implemented a migration deleted in #308 and called none of our code; seed-pagination's PaginationOptions block only read back an object literal; lemonfox-client's comment named transcribe.ts's old path. Co-authored-by: Claude Opus 5.5 <[email protected]>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
webUrlnow resolves per region — to the client that owns it, or the nearest owning ancestor — instead of one globalSAHAJATLAS_URLbase pointing at a host that isnoindexon three layers. Anything unowned falls back to the We Meditate surface.where[breadcrumbs.url][equals]='/nl/amsterdam') with no new endpoint, no new stored field and no migration.Four defects fixed on the way
#633 shipped a different shape than its ticket, and the resolver read the old one. PR #635 replaced
canonical.domain/.mount/.routingwithcanonical.embed+ a job-writtencanonical.verification.verified.ClientRowis a hand-written interface rather than a slice of the generated types, so reading the removed fields type-checked cleanly whilecanonical?.domainwas alwaysundefined— every client fell through and every document resolved to the fallback. Mutation-checked: restoring the old read fails 5 of the suite's 22 assertions.Every query-routed canonical URL would have been refused by the widget.
buildCanonicalUrlinlib/clients/verification.ts(shipped in #635, used by the admin picker) emitted the Atlas path with its leading slash stripped and the rest percent-encoded —?atlas=events%2F12345. The widget guards that parameter withsafeLoaderPath, which requires a leading/and whose hostile-input table pins'relative/path'as refused, so the route was discarded and the widget silently fell back to the embed default. There are no longer two builders: the picker now previews byte-identically what the resolver emits, asserted in its own spec.A verified host is not necessarily a bare host.
CANONICAL_DOMAIN_PATTERNis enforced by thecanonical.verificationJSON schema onpayload.update, but VerifyEmbeds persists that column with a rawpool.query, so the schema never runs on the write that fills it — andsplitMountKeyrecordsurl.host, which keeps a port thatallowedDomains(port-stripped) lets through. Inert until now, since the value only rendered an admin sample; this ticket is what interpolates it into a public URL. Re-validated inloadDirectOwners, before the ancestor walk, so an unusable client is skipped and the next ancestor wins rather than its subtree collapsing to the fallback — a placement bug the integration test caught.Enabling ownership without verification re-rooted the canonical.
canonical.embedonly nominates a mount, and reports are reachable by anyone holding a published key from an allowed origin. Only the job-writtenverifiedsnapshot may shape a public URL. Now split into two assertions instead of one.Changes
src/lib/atlas/canonicalUrl.ts— the two URL shapes, plusatlas-url-contract.json, the fixture SahajCloud / SahajAtlasWeb / WeMeditateWeb assert against byte-identically. It drives the unit table viait.each, not by hand.src/lib/atlas/regionTree.ts— wasregionWebPaths.ts; exposes the ancestor chain alongside the path from the same single query, since ownership resolves by walking that chain.getRegionWebPathssurvives as a thin projection, so awebPathread still costs one query.src/lib/atlas/regionOwners.ts— theclientsread + nearest-ancestor walk.src/fields/publicUrlFields.ts—webbase widened to take the read context. Source-compatible: existing zero-arg thunks stay assignable.src/payload.config.ts+tests/utils/testHelpers.ts— nested-docs config collapsed into one sharedREGION_NESTED_DOCS_CONFIG, so the harness can't diverge from production.scripts/—backfill-region-breadcrumb-urls.ts(write,--force-gated) andaudit-region-slugs.ts(read-only).Migration
None.
breadcrumbs.urlalready exists in the schema — it has been null only because the config never passed agenerateURL.pnpm generate:typesproduces no diff.But it needs a one-off backfill after deploy, since breadcrumbs populate on write:
It re-saves roots only and lets the plugin's own cascade visit each subtree once — re-saving all 646 regions individually would repeat the work once per ancestor.
Test Results
typecheck/typecheck:tests: ✓ cleangenerate:types: no diffTwo assertions were mutation-checked rather than trusted: restoring the old
canonical.domainread fails 5 assertions (each falling back to We Meditate instead of the owner's domain), and the query-count test now also asserts every document resolved a real URL — counting queries alone passes just as happily when the resolver returns null for all of them.Notes for reviewer
Behaviour changes that are the point of the ticket, not regressions:
SAHAJATLAS_URLbase and were updated. One,client-canonical.int.spec.ts, asserted feat(access): add embed metadata and canonical ownership to Clients #633's "nowebUrlchanges" claim — this is the follow-up that makes it change, so it now asserts the opposite.webPathis byte-identical throughout; ownership only decides what it is joined to.enableddefaults false and needs a verified embed), and We Meditate does not serve/map— it has no Atlas integration at all. So on merge, essentially everywebUrlbecomes a 404 on wemeditate.com rather than today's noindex-but-real Atlas URL, including the "View event" link in verify pages and reminder emails. This is the ticket's specified end state and was confirmed as the intended choice; the alternative considered was emittingnullwhen unowned. Flagging it because it is a live-behaviour change that lands before its destination page exists.Also worth extra scrutiny:
validate, not a collection hook: Payload generates the slug in a fieldbeforeChange, which runs after every collection hook, so a collection hook sees an empty slug on every auto-generating create. It also grandfathers a pre-existing blank, becauseresaveChildrenre-saves each descendant by passing its whole document back throughupdate.pnpm tsx scripts/audit-region-slugs.tsreports any that appear. Worth confirming against production.where[breadcrumbs.url][equals]matches descendants too (their trail contains the ancestor's URL). Addslugto thewherefor exactly one region. Pinned by a test either way.Review findings dismissed, with reasons:
webUrlis null when a caller selects onlywebUrlwithoutregion." — Not so:ensureWebPathDepsis a collectionbeforeOperationhook that re-addsregionand_statusto any include-modeselectnaming a path field, andevent-verification.int.spec.tsalready tests that exact scenario and asserts the resolved value.splitMountKeyuseurl.hostname." — That would verify:8080and publish:443, a page we never looked at. Refusing the value where it becomes a public URL is the correct fix.relationIdimplementations." — Real, but pre-existing onmainand cross-cutting into the access plugin. This branch already moved its own call sites onto the@/lib/utilitiesone.mountpattern to the verification JSON schema." — Defense-in-depth only:canonicalUrlBasealready refuses a fragment and a non-path mount, and the schema does not run on the job's raw write anyway.Known follow-ups (not in this PR):
atlas-url-contract.jsonneeds copying into SahajAtlasWeb and WeMeditateWeb for the cross-repo guarantee to be real; only the SahajCloud half is enforced here.if (!value) return trueinslugField's uniqueness validator disarms Payload'srequiredfor every collection using it, not just Regions. Fixed here only for Regions; the factory-wide fix deserves its own ticket and test sweep.Closes #634
🤖 Generated with Claude Code