Skip to content

feat(access): add embed metadata and canonical ownership to Clients - #635

Merged
Ardnived merged 17 commits into
mainfrom
feat/client-canonical
Aug 19, 2026
Merged

Ardnived merged 17 commits into
mainfrom
feat/client-canonical

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • An operator declares canonical ownership by picking one of the embeds their own site reported — domain, mount and routing all follow from that single choice, instead of three hand-typed fields.
  • The CMS then verifies that choice by loading the page itself through Cloudflare Browser Rendering and confirming the widget really booted. Only a verified embed ever yields a canonical URL.
  • Data only. canonical.enabled defaults false, nothing resolves differently, and no webUrl anywhere changes — asserted by a test, not just claimed. The per-region resolver that consumes these fields is the follow-up ticket.

Why the shape changed mid-PR

The ticket specified three text fields (canonical.domain / .mount / .routing). That was sized for the ~31 services we configure ourselves; the client base is growing sharply and most of those users are not technical, so three fields are three chances to name a URL that points nowhere with nothing to say so.

Making the server the attesting party also closes a hole the original design would have opened: if routing were derived from what a client reports, anyone holding a published key could reshape a live canonical URL. Now reports only nominate a candidate — the CMS decides.

Changes

  • src/lib/clients/embedMetadata.ts — mount-key parsing and the pure keyed merge. A reported path may carry a WordPress ?p=<digits> permalink and nothing else: discarding the query collapses a default-permalink site onto one mount, leaving the page an operator must name unnameable, for exactly this feature's audience.
  • src/lib/clients/verification.ts — the verified snapshot, the three-strikes ladder, and buildCanonicalUrl (which joins with & when the mount already carries a query).
  • src/lib/embedVerification/ — Cloudflare Browser Rendering client, readiness-marker parser, and the routine that turns a render into a result.
  • src/jobs/VerifyEmbeds/ — nightly, watermarked on the indexed canonical.nextVerifyAt, bounded to services that actually own canonical URLs.
  • src/components/admin/CanonicalEmbedPicker/ — the picker plus a description that renders the finished sample URL before you save.
  • src/collections/Clients/endpoints/report.ts — the widget's write path; verifyEmbed.ts — the same verification on demand.

Three defects this fixed along the way

Every report would have 400'd. The shipped widget (sydevs/SahajAtlasWeb#159) sends origin and pathname as separate fields with mode: 'inline'; this took a single url and expected script.

Every successful report would have hung. The usage plugin increments usage_daily_requests on the caller's own row, on its own connection, for the very request being served — while payload.update held that row inside the request transaction. Both sides sat on Lock: transactionid and the request never returned. Replaced with a single autocommit jsonb || merge.

The deploy failed on a browser bundle. The picker is a client component and reached pg through the @/plugins/usage barrel. CI never builds this app — Railway does — so it type-checked, passed every test, and failed the deploy with Can't resolve 'dns'. tests/unit/client-bundle-safety.spec.ts walks the real import graph so it cannot regress silently.

Migration

  • 20260819_002657_add_client_canonical — canonical columns + embed_metadata on clients and _clients_v, the nextVerifyAt index, and the verifyEmbeds job enum.
  • 20260819_002715_drop_client_legacy_config — drops legacy_config from both.
  • Reversible; the full 43-migration chain was applied to a clean database and verified.

Deviations from the ticket

Worth reading before checking the acceptance criteria, several of which describe fields that no longer exist:

  • canonical.domain / .mount / .routing are gone, replaced by canonical.embed + a job-written canonical.verification. The routing vocabulary is still exactly query | path.
  • The backfill script is deleted. Canonical ownership now requires a verified reported embed, which legacy Atlas config can never produce, so seeding a domain from it would be misleading rather than helpful.
  • A reported path may carry ?p=<digits> — a narrow, deliberate exception to the no-query rule.

Test results

  • Unit: 1234 passing (100 files) · Integration: 26 in client-canonical.int.spec.ts · Lint / typecheck / typecheck:tests green.
  • The Cloudflare integration is exercised against the live API by pnpm tsx scripts/verify-embed-live.ts --self-test, which drives all four outcomes in ~20s. Its error classification keys on codes captured from real responses (6002, 5006, 10000), pinned in the unit tests.

Notes for reviewer

  • The smoke lane has never run on this PR. It was skipped by an 18-minute Playwright browser install that blew the job timeout (now removed — the specs are request-only and launch nothing), and then by the preview environment being deleted to clear a poisoned migration state. CI now emits a warning whenever smoke skips, so this is visible rather than silent.
  • inconclusive vs failed is load-bearing. A provider error, exhausted quota or bot challenge means we could not look, and changes nothing — auto-disabling a working canonical would change live public URLs for no reason.
  • The marker proves a broken embed, not a forged one. It carries no nonce and any host running our script can write it; the trust boundary stays allowedDomains. What it adds against a stolen key is real: they cannot make the customer's domain serve a marker they control.
  • Nothing activates until the widget ships to customer sites and a human enables ownership.

Closes #633

🤖 Generated with Claude Code

Ardnived and others added 9 commits August 14, 2026 09:59
The Sahaj Atlas white-label program needs two things on a client: a place
for the embed to report what it observed about the page it is installed
on, and an explicit, uniqueness-enforced statement of which region a
client owns the canonical URLs for.

Data only — `canonical.enabled` defaults false, nothing resolves
differently, and no `webUrl` changes.

- `embedMetadata` (json, admin-readonly) keyed by origin + pathname, so a
  site with several embeds accumulates a record per mount. A JSON column
  because nothing queries it: the ownership resolver loads every client
  with `pagination: false` (~31 rows) and filters in memory. Wired to a
  JSON Schema, so Payload both generates the type and rejects a malformed
  write.
- `canonical` group — `enabled` (default false), `domain` (bare host,
  deliberately not derived from the multi-valued `allowedDomains`),
  `mount` (may carry a query string; WP default permalinks are `/?p=123`)
  and `routing` (`query` | `path`, never `hash`).
- `validateCanonicalOwnership` requires a region + domain when enabled,
  and rejects a second enabled client on a region, naming the incumbent —
  `region` alone cannot identify an owner (3 published clients map to
  Czechia, 2 to Finland, 2 to Australia).
- `POST /api/clients/report` writes it. `clients` is excluded from the
  usage plugin, so origin enforcement is called by hand; the reported
  mount's host is checked against `allowedDomains` too.
- `legacyConfig` removed rather than promoted: a second, contradictory
  source of routing_type/embed_type beside the new fields is how they
  drift, and the legacy values are unverified (`sahajayoga.at` is recorded
  as `script` and in fact serves an iframe).

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Mandatory per .claude/rules/endpoints.md. The request schema sources its
`mode` / `routing` enums and its `url` bound from the collection's own
constants, so they can't drift from the Zod schema in the handler.

It stays `x-internal` in the filtered spec — `clients` is in
ALWAYS_HIDDEN_COLLECTIONS and in no project — which is the right outcome
for the first-party widget's telemetry channel. Pinned by a test so a
future filterSpec change can't publish it by accident.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…nfig

A starting point, never a decision — `canonical.enabled` is left false on
every row, because the legacy values are unverified.

Reads `legacyData.config`, the verbatim import record kept by
`legacyMigrationFields()`, rather than the `legacyConfig` column this
ticket drops. Same values (the importer copied one from the other), and
reading the surviving one means the script works whether it runs before
or after the deploy that applies the migration — migrations auto-apply
in-process on Railway boot, so a script needing the dropped column could
never be run in time.

Dry run by default, `--force` to write, re-runnable: it only ever fills a
field that is currently empty, so a hand-set value outranks the legacy
one and a second pass finds nothing to do.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Split into two migrations on purpose. Generated as one, drizzle sees
`legacy_config` dropped alongside `canonical_enabled` added in the same
table and raises its rename-vs-create prompt — which hangs on non-TTY
stdin and, answered wrong, would rewrite the column instead of dropping
it. Additive-then-destructive gives each migration an unambiguous diff,
so both generate non-interactively and read clearly in review.

Both cover `clients` and `_clients_v` (drafts are on), and both are
reversible.

The dropped `legacy_config` is not a data loss: the importer copied it
from `legacyData.config`, which is untouched, and that is what
`scripts/backfill-client-canonical.ts` reads.

One thing the generated SQL settled: `canonical_routing` ships
`DEFAULT 'query'`, and Postgres backfills that onto every existing row —
so "the field is empty" can't gate the routing seed, and the backfill
would have skipped the single legacy client on `path`. It now seeds
routing whenever the legacy value differs, which is safe because it
already refuses to touch a client that opted in. `domain` keeps the
fill-only-when-empty rule, since that one is typed by hand.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Pure-function coverage for the two things the endpoint delegates every
decision to: mount-key validation (query/fragment/scheme/credentials
refusals, and that two spellings of one page collapse to one key) and the
keyed merge (two pages produce two keys, the freshness window suppresses
a repeat write, a malformed sibling is repaired, the cap evicts
least-recently-seen but never the mount just reported).

Plus a compile-time pin that the hand-written record type and the field's
JSON Schema agree. Verified by mutation: adding a field to
EmbedMountRecord that the schema doesn't declare fails
`pnpm typecheck:tests`.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
One Payload bootstrap, three surfaces.

The ownership hook: each rejection asserts the message a human actually
reads (Payload keeps the generic summary on `.message` and the per-field
text on `.data.errors[]`, which is what the admin renders under the
field), including that the incumbent is named. Also covers the case the
hook nearly missed — moving an already-enabled client onto an owned
region, which is why it watches `region` and not just `canonical`.

The endpoint: refuses a draft caller, an Origin outside allowedDomains, a
reported host outside it, and a url carrying a query string or fragment;
two pages of one site round-trip through the DB as two keys; a repeated
identical report is proven not to write by the row's own `updatedAt`
rather than by the response body.

The backfill: seeds from `legacyData.config`, never opts a client in,
leaves a draft a draft (a disabled Atlas service must stay unable to
authenticate), doesn't overwrite a hand-set domain, and is idempotent.

And the ticket's data-only claim, asserted directly: an event's `webUrl`
and `webPath` are unchanged by enabling canonical ownership on a client
that owns its region.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
api-clients.md gets the field contract and the three things about
`POST /api/clients/report` that aren't obvious from the handler: `clients`
is excluded from the usage plugin so both origin enforcement and usage
tracking are the handler's own problem; the reported url's host is
checked against `allowedDomains` on top of the request's Origin; and
"rate limiting" here is Cloudflare's edge limit plus a no-op-on-unchanged
write, since the app-level hook is a no-op on Railway.

Also records the two decisions a reader will otherwise re-litigate: why
canonical.domain isn't derived from allowedDomains, and why canonical
identity stays a human's call while viability is automatic.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Per /simplify's altitude + reuse passes.

Altitude: `canonical.ts`, `embedMetadata.ts` and `backfillCanonical.ts`
sat in the collection folder while being imported by the OpenAPI plugin
and an operator script — the exact cross-owner internal import rule 4 of
project-structure.md prohibits. Before this branch, nothing in the repo
imported from `src/collections/` into `src/plugins/` or `scripts/`; these
three were the first. They're pure vocabulary and pure functions with no
Payload dependency, so `src/lib/clients/` is their home, alongside
`src/lib/schedule/` which exists for the same reason. No barrel — the
consumers cherry-pick, as with `schedule/`.

Reuse: `normalizeCanonicalDomain` was a second URL normalizer beside
`normalizeHost` in the origin-enforcement helpers. It now delegates. The
one behaviour it must not inherit — `normalizeHost` preserves a `*.`
wildcard label, which a canonical domain must never be — is rejected for
free by CANONICAL_DOMAIN_PATTERN, whose character class has no `*`.

Not taken: the pass also flagged `parseAllowedDomains` running twice per
report (once inside `assertClientOriginAllowed`, once for the reported
mount's host). Deduplicating it means inlining that helper's logic — the
preview-secret bypass, the missing-origin allowance, the WARN log — which
trades a duplicated security rule for one `split` on a two-line textarea.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two findings from the code-review pass.

`lastSeen` is the eviction sort key, and `sanitizeEmbedMetadata` only
checked it was a string. A corrupt stamp therefore survived into
`evictOldest`, whose comparator would return NaN — which does not sort
that record last, it corrupts the ordering of the whole array and evicts
arbitrary mounts. Rejecting it at the sanitize layer removes the cause
rather than patching the comparator, and matches what that layer already
promises for every other field: drop the bad record, repair on next write.

`canonical.mount` accepted any text, so an operator could paste
`https://host:8080/path` into it. The host is stated once, in
`canonical.domain`, so the resolver would have joined the two into a URL
resolving nowhere. It now requires a leading `/` — which still accepts
`/?p=123`, the WordPress default permalink this field exists for.

Also documents, at the hook, that the one-owner-per-region rule is
check-then-write: two simultaneous admin saves could both pass. Left
undefended on purpose (human-paced writes, visible rather than silent
result); the airtight fix is a partial unique index Payload can't declare,
and the note says where to add it if the resolver needs the invariant.

Not taken: a claim that the backfill skips the routing seed when
`canonical.routing` is unset. It's inverted — `'query' !== undefined` is
true, so that is exactly the case that seeds.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app

railway-app Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ◻️ Removed (View Logs) Web Aug 19, 2026 at 4:34 pm

Ardnived and others added 4 commits August 18, 2026 16:30
# Conflicts:
#	src/migrations/index.ts
#	src/payload-types.ts
Two defects that would each have broken this endpoint in production.

**Every report would have 400'd.** The widget shipped in sydevs/SahajAtlasWeb#159
sends `origin` and `pathname` as separate fields and spells the inline mode
`inline`; this took a single `url` and expected `script`. The split is not
cosmetic — it is what lets the path be checked on its own.

**Every successful report would have hung.** The usage plugin increments
`usage_daily_requests` on the caller's own `clients` row, on its own connection,
for the very request being served, while `payload.update` held that row inside
the request transaction. Both sides sit on `Lock: transactionid` and the request
never returns. Replaced with a single autocommit `jsonb ||` merge through the
same pg-pool seam the usage counters use, which also closes the
read-modify-write window.

Also: a reported path may now carry a WordPress `?p=<digits>` permalink and
nothing else. Discarding the query collapses a default-permalink site onto one
mount — every post reports as `https://site.com/` — leaving the page an operator
must name as canonical unnameable, for exactly the audience this feature targets.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replaces `canonical.domain` / `.mount` / `.routing` with one choice — which of
the embeds this service actually reported owns its canonical URLs — and has the
CMS confirm that choice by loading the page itself.

Three hand-typed fields were sized for ~31 services we configured. The client
base is growing sharply and most of those users are not technical; three fields
are three chances to name a URL that points nowhere, with nothing to say so.

- `canonical.embed` — the nomination, chosen from a picker
  (`CanonicalEmbedPicker`) whose description renders the finished sample URL,
  including the `&` join a WordPress `?p=` mount needs.
- `canonical.verification` — job-written only, from what was observed on the
  live page. Reports nominate; the server decides. Deriving routing from reports
  would let a forged report reshape a live canonical URL.
- `canonical.nextVerifyAt` — an indexed column, so the job keeps the cheap
  single-predicate query `ExpireEvents` uses.
- `lib/embedVerification/` + `jobs/VerifyEmbeds` — Cloudflare Browser Rendering,
  the readiness-marker parser, and the nightly ladder. Three consecutive
  *definitive* failures disable ownership and notify; `inconclusive` (provider
  error, quota, bot challenge) never counts, because auto-disabling a working
  canonical changes live public URLs for no reason.
- `POST /api/clients/:id/verify-embed` — the same routine on demand, so setup is
  not gated on the cron. It never disables: three strikes is a judgement about a
  pattern over days.

Tabs regrouped Config / SEO / Access, with the reported embeds collapsed beside
the setting they inform. `required` on `embed` plus the `enabled` condition is
exactly "required when canonical ownership is on" — the same shape as
`primaryContact`, and an integration test pins that a disabled service still
saves with no embed through a plain API write.

The legacy backfill is deleted: canonical now requires a *verified reported*
embed, which legacy Atlas config can never produce. Both canonical migrations
were regenerated to emit the final shape rather than add-then-drop, since
neither has been applied anywhere.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- api-clients: rewrites the canonical section for the picker model, adds how a
  nomination becomes a canonical URL, and states plainly what the readiness
  marker proves (a broken embed) and what it does not (a forged one) — the
  obvious reading of "server-attested" is too strong. Also records why the report
  write is raw SQL and why the body is two fields.
- openapi: request schema follows the widget's `origin` + `pathname` split, with
  the guard asserting it so the two cannot drift apart again.
- migrations: never generate with `E2E_TEST=true` — it disables the usage plugin,
  so the snapshot loses `resetUsage`/`trackUsage` and a later migration tries to
  re-add a label that has existed since the initial schema, aborting the boot
  migration. It is tempting precisely because it is the workaround for the
  ethereal outage that kills the CLI. Also: `generate:types` silence means "no
  change", not "done".
- storage: `CLOUDFLARE_API_KEY` now also carries Browser Rendering, and losing
  that permission degrades to a silent `not-configured`.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-635 August 19, 2026 02:00 Destroyed
The Railway deploy failed with `Module not found: Can't resolve 'dns'`. The
canonical picker is a client component; it imports `@/lib/clients/canonical`,
which imported the `@/plugins/usage` barrel, which re-exports the pg-pool seam —
so `pg` was pulled into the browser bundle.

Nothing local caught it. It type-checks, lints, and passes every test, because
**GitHub Actions does not build this app** — Railway does. Reproduced both ways
before and after the fix: `pnpm build` fails with six module-resolution errors on
the barrel import and succeeds on the deep one.

`tests/unit/client-bundle-safety.spec.ts` walks the real import graph from each
admin client entry point so this cannot regress silently again. It carries its
own control — the report endpoint legitimately uses the pg seam and must be
flagged — so the walk can't pass vacuously.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-635 August 19, 2026 15:35 Destroyed
…ts codes

The verifier had never touched Cloudflare — every test stubbed the render — so
the request shape, the auth header, and the error patterns were assumptions.
Driven against the live API they turned out right in shape and wrong in method.

`classifyRenderError` now keys on Cloudflare's numeric codes, captured live:
`6002` selector timeout, `5006` network/DNS, `10000` auth. Prose matching stays
as the fallback for codes we have not met, but it cannot be the primary rule —
a dead customer domain returns `Network connection closed.`, which says nothing
on its own and only classified correctly because the pattern happened to include
"connection". The real payloads are pinned in the unit tests.

`5006` counts as a real failure even though Cloudflare's own detail says it "can
also happen" for other reasons. Detecting dead domains is the main thing this job
exists for, and three-consecutive-failures is what makes that safe: a blip does
not repeat on three separate nights.

`verifyEmbed` now refuses any non-http(s) mount before rendering. `canonical.embed`
is normally a picker option, but it is a plain text field an admin can type into,
and that is the point where a string becomes an outbound page load — `data:`,
`file:` and `javascript:` have no business reaching a browser.

`scripts/verify-embed-live.ts --self-test` drives all four outcomes against the
live API in ~20s, so the integration can be re-proven after any change, and a
disabled canonical can be diagnosed by running its URL through the same path the
job takes.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-635 August 19, 2026 15:42 Destroyed
The job was cancelled at 25 minutes with no explanation. It was the
`timeout-minutes` cap: `playwright install --with-deps chromium` ran for 18m22s,
and a GitHub job timeout reports as *cancelled* rather than failed, so nothing
said why.

The install was never needed. Every smoke spec uses only the `request` fixture
(`APIRequestContext`), which is plain Node HTTP — nothing launches Chromium,
despite the `chromium` project name in the config. Verified by running the whole
suite with `PLAYWRIGHT_BROWSERS_PATH` pointed at an empty directory: all six
specs issued real requests and failed on an application error, not a missing
browser.

Two related things this surfaced:

- **A skipped smoke lane looked identical to a passing one.** When no preview is
  discovered both steps skip and the job stays green, so "Lint, Test & Smoke:
  pass" could mean smoke never ran — which is what happened on the previous
  commit, where discovery polled for 12 minutes and then gave up. CI now emits a
  `::warning` saying so.
- **The budget was structurally impossible.** Discovery alone allows 12 min for
  the deploy plus 5 for health; with ~6 min of tests that is 23 of the 25-minute
  cap before smoke starts. Raised to 30 for headroom.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-635 August 19, 2026 16:22 Destroyed
I regenerated the canonical migrations to emit their final shape, saying neither
had been applied anywhere. That was wrong: Railway builds a preview environment
on every PR push and runs `prodMigrations` on boot, so both had already run —
four times. The preview kept the old migration's columns with no row naming the
new one, so it re-ran and died on `column "canonical_enabled" ... already
exists`, crash-looping the app and 502-ing every route.

The clean-database migrate test passed precisely because it was clean; the
failing state needs a database that ran the old migration.

Writes up the rule, both remedies (reset the environment, or stack a migration
instead of regenerating), why `ADD COLUMN IF NOT EXISTS` is the wrong escape
hatch, and how to read PR-preview logs at all — a Railway *project* token only
sees production, so the CLI's user session is the only way in.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Ardnived
Ardnived merged commit a7ba5bc into main Aug 19, 2026
1 check passed
@Ardnived
Ardnived deleted the feat/client-canonical branch August 19, 2026 17:31
Ardnived added a commit that referenced this pull request Aug 19, 2026
* feat(atlas): add the canonical URL builder and a context-aware URL base

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]>

* feat(atlas): resolve canonical webUrl per owning client region

`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]>

* feat(regions): make breadcrumb paths queryable, require a non-empty slug

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]>

* fix(regions): enforce the slug invariant where the generated value exists

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]>

* docs(atlas): document per-region canonical URLs and the new env var

- 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]>

* refactor(atlas): share the request memo, and cover the backfill routine

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]>

* test(regions): pin the two assumptions the slug invariant rests on

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]>

* fix(atlas): resolve ownership from the verified embed, not removed fields

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]>

* fix(clients): build the picker's sample URL from the one canonical builder

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]>

* test(clients): pin that opting in without verification owns nothing

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]>

* docs(deployment): list the Atlas canonical env vars and the backfill 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]>

* refactor(tests): share the region-tree fixture builder

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]>

* fix(atlas): require a bare host before publishing a canonical URL

`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]>

* docs(rules): record why the verified host is re-checked at read time

Refs #634

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(access): add embed metadata and canonical ownership to Clients

1 participant