Skip to content

feat(events): registrant confirm/deny voting, post-event follow-ups, and one shared activity log - #626

Merged
Ardnived merged 19 commits into
mainfrom
feat/event-feedback
Aug 25, 2026
Merged

Ardnived merged 19 commits into
mainfrom
feat/event-feedback

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Registrants — the only people who can actually know — vote on whether an unverified event took place. Votes never auto-verify anything; they rank listings and, past a threshold, unpublish fakes.

Part 3 of the crowdsourced-listings plan. Was stacked on #625; both #625 and #642 have since merged, so this is rebased onto main and stands alone.

  • Voting is registration-gated: one vote per registration, through the built-in Registrations update endpoint. No login — possession of the registration uuid is the credential. The access layer scopes the client's update grant to exactly that row, and a beforeValidate whitelist reverts every field except eventFeedback.
  • Verdict: the sync hook recounts both tallies (idempotent under races), writes the Wilson lower bound to the indexed confidenceScore, and flips the event to denied + draft when denials ≥ 5 and the Wilson upper bound < 0.5.
  • Solicitation: SendPostEventFollowUps (daily, 30-day window) emails each registrant once after their occurrence passes. One click in that email records the answer and lands them back in Atlas.

The feedback flow

The emailed buttons say "Yes, it took place", and used to land on an identical question you had to answer again — which reads as though the first click failed, and the second page couldn't tell which button you'd pressed, so it guarded against nothing. 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.

The vote still travels by POST, never by opening the link. Mail scanners and prefetchers issue GETs, and a vote nobody cast corrupts the verdict this feature exists to produce. Auto-submitting from JS keeps a real reader to one click while a scanner fetching the URL records nothing — verified by GETting a live link and confirming eventFeedback stayed null. <noscript> keeps the two buttons.

Once recorded the reader is redirected into Atlas: confirmed → the event page, denied → the event's region page. A denial deliberately doesn't land on the event — they just said it isn't there, and if theirs was the fifth denial that vote has already unpublished it, so webUrl is null (publish-gated; regions aren't). No token rides along, so it can't leak via Referer. Atlas renders the banner from ?feedback= — sydevs/SahajAtlasWeb#164; until that ships the redirect lands on a normal page.

Tokens: three hand-rolled HMACs → one jose JWT

utilities/signedToken (86 lines), eventVerification/token (112) and registrations/unsubscribeToken (78) were three copies of the same construction, written months apart, each re-deriving base64url and a timing-safe compare. Only one had a kind discriminator.

They now share one helper backed by jose — already in the tree as Payload's own dependency (it signs the auth JWTs), pinned to its 5.10.0 so the install keeps one copy. The repo now hand-rolls no crypto: createHmac and timingSafeEqual appear nowhere in src/ or tests/.

Beyond deleted code: the algorithm is pinned on verify, so a token can't talk us into none or an asymmetric alg — an attack our own verifier had no notion of; exp is the library's job against an injectable clock; JWTExpired is distinct, which is what lets a page say "this link expired" rather than 404; and kind is the JWT audience, checked before any claim is read, so one link type can't be spent as another.

Signing/verifying became async, rippling to twelve call sites — all already in async contexts. No legacy format is retained: no reminder emails have ever been sent, and verify links last 10 days with an in-admin alternative.

One activity log, one table

Two logs existed and agreed on nothing: the Events verification log had a bespoke renderer, the Registrations reminder ledger was invisible json with no component at all; 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.

src/fields/logField.ts is now the one field — activityLog / "Activity Log" by default, both overridable — and LogTable the one renderer. What it records is broader than mail: a registration created or cancelled belongs there too.

  • Columns are declared on the field and delivered in admin.custom, like SelectDescription and EventQualityPanel. Order and headings are fixed before the data is; omit them and the table derives from the entries, so a new log is zero-config.
  • Display lives under cells; everything else is machine data. I built it the other way first — every non-reserved key a column — and checked the output: the verification log rendered fourteen columns of raw enum values, because its entries carry stage, level, role, manager and more for hasReminderForStage to read back.
  • The wording moved to the entry builders. format.ts computed "Escalation" and "Region manager · Bay Area" at render time from raw enums; buildReminderEntry emits them now — the code that knows why a reminder went where it did is the code that writes the entry.
  • Clicking a row opens the whole entry as JSON in Payload's Drawer. That went through two worse shapes: a trailing ⋯ column that sat off the right edge of the table's scroll area on a narrow window, and a hover panel that opened and closed as the pointer crossed the table.
  • appendLogEntry caps the log. The reminder ledger gained an entry per occurrence — 52 a year on a weekly class, read and rewritten on every send — and nothing bounded it.

Registrations.followUpSentAt stays as a real dated column beside the log: nothing can where on JSON cheaply, so the sweep still needs something to select on. The log says what happened; the column is what the query filters.

Where a job's code lives

Six modules under src/lib/ had exactly one consumer each — a job. That isn't shared code; it's one job's private helper in the commons, importable by anything. They now live with their job; the view layer is untouched (templates stay in src/emails/).

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, with two principled exemptions and a KNOWN_SINGLE_CONSUMER backlog.

Writing that test corrected the analysis three times — recipients.ts has three consumers, two via a barrel; browserRendering.ts is imported as ./browserRendering next door; the email preview scripts import senders directly. Two files had already been moved before the test caught them, and were reverted.

Registrant-mail parity

PostEventFollowUpEmail shared the layout components but broke three conventions its siblings keep: no plain-text part, no localization, and the project brand instead of the client service's. All three were gaps in the job, not the template. email.md now carries the checklist so the next registrant email doesn't rediscover them.

Migration

Five, of which two are renames and one is a repair:

  • 20260812_034732_add_registration_event_feedback — the vote columns.
  • 20260825_005719_drop_event_feedback_at — drops a write-only column (stamped on every write, read by nothing but its own assertion).
  • 20260825_041552_activity_log — registrations.reminder_log → activity_log, as drop+add. Safe because that column was provably empty: no reminder emails have ever been sent.
  • 20260825_150733_events_activity_log — events.notification_log → activity_log, hand-edited to ALTER TABLE … RENAME COLUMN. Drizzle can't tell a rename from a new column and emitted drop+add, which would have discarded every verification cycle on every event — the Atlas import seeds an entry and each verification writes one. Same-shaped diff as the one above, opposite correct answer. Both the table and its _v twin are renamed; reversible.
  • 20260820_202018_submission_manager.json — snapshot re-baseline, no DDL. Rebasing refactor(submissions): judge a proposal as a diff, not a form #642 onto main reordered the chain but left its snapshots alone, so the newest one — the only one drizzle diffs against — described a parallel history, and every migrate:create emitted a bogus catch-up that would crash a deploy with "column already exists". Applying was never affected; only creating the next migration. Verified the way the problem announced itself: migrate:create against an unchanged config now emits an empty body.

main carried that broken snapshot too, so this PR fixes it there — which holds as long as nothing else creates a migration before it merges.

Tests

1389 unit · 97 targeted integration. Guards were mutation-checked rather than assumed:

  • Dropping the audience option fails two token tests — the cross-kind replay guard is real.
  • Routing denials to the event fails two destination tests.
  • Putting findOrCreateCity back in src/lib fails the boundary guard.
  • Removing the log cap fails two appendLogEntry tests.

Three corrections worth recording, each caught by checking rather than reasoning:

  • I claimed the vote gate silently accepted votes when the event couldn't be resolved. It didn't — a failed lookup was always refused; only a wholly absent relationship skipped it, which event: required makes unreachable. Kept as a simplification, not a fix.
  • The forged-token tests needed rebuilding, not just await: they constructed two-part forgeries, which under jose fail as malformed rather than as bad signature — passing while testing nothing.
  • lib-boundary scanned every source once per lib module: 1.4s alone, 8.5s inside the parallel unit lane, so the guard was failing the gate it exists to protect. Inverted to one pass: 53ms.

Review findings dismissed

Four efficiency findings, each rejected against the source:

  • Memoise the sort / column derivation / Table props in LogTable (×3) — the log is capped at 50 rows, and Payload's Table is not React.memo'd (checked), so memoising data/columns cannot prevent the re-render the finding aimed at. renderedCells are fresh elements every render regardless.
  • Promise.all the token and strings in SendPostEventFollowUps — resolveEmailStrings is request-memoised, so the claimed 50–100ms is only the first registration; and the two sit either side of the sections.length === 0 early return, so parallelising would resolve strings for every skipped registration. A regression on the common path.

Security review — no critical or high. Two low observations, both dismissed as already-handled: the event title reaching an activity-log entry unescaped (stored as JSON and rendered through JSON.stringify into a <pre>, so there's no injection path — and the email subject already runs stripNewlines), and the vote coercion treating any non-confirmed value as denied (redundant with the select field's own enum validation, kept as a graceful fallback for a malformed POST).

Code review — no correctness findings. It independently re-verified the hand-edited RENAME migration against its snapshot, all twelve jose call sites for placement of await, the exactly-once guards after the entry shape changed, and the row-position lookup.

One altitude finding accepted: row resolution read Payload's data-id. Correct today, but the attribute is Payload's to rename and the failure mode was a click that silently found nothing — it now uses the row's position in <tbody>.

🤖 Generated with Claude Code

@railway-app

railway-app Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Aug 25, 2026 at 5:28 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 12, 2026 04:00 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 12, 2026 04:02 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 13, 2026 02:17 Destroyed
@Ardnived
Ardnived force-pushed the feat/event-feedback branch from 96e80dc to 88d7f06 Compare August 13, 2026 02:19
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 13, 2026 02:19 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 13, 2026 18:24 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 13, 2026 20:37 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 13, 2026 20:39 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 13, 2026 21:05 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 19, 2026 17:35 Destroyed
@Ardnived
Ardnived changed the base branch from feat/event-submissions to main August 24, 2026 17:59
…nity 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]>
@Ardnived
Ardnived force-pushed the feat/event-feedback branch from 5868bb5 to 0969cef Compare August 24, 2026 18:13
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 24, 2026 18:13 Destroyed
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]>
Ardnived and others added 8 commits August 24, 2026 13:00
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]>
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]>
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]>
`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]>
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]>
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]>
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]>
- `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]>
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]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 25, 2026 01:30 Destroyed
@Ardnived Ardnived changed the title feat(events): registrant confirm/deny voting + post-event follow-up emails feat(events): registrant confirm/deny voting, post-event follow-ups, and one signed-token helper Aug 25, 2026
Ardnived and others added 8 commits August 24, 2026 20:17
**`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]>
`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]>
… 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]>
… 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]>
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]>
…tripes

**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]>
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]>
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]>
@Ardnived Ardnived changed the title feat(events): registrant confirm/deny voting, post-event follow-ups, and one signed-token helper feat(events): registrant confirm/deny voting, post-event follow-ups, and one shared activity log Aug 25, 2026
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-626 August 25, 2026 17:28 Destroyed
@Ardnived
Ardnived merged commit 720fd74 into main Aug 25, 2026
2 checks passed
@Ardnived
Ardnived deleted the feat/event-feedback branch August 25, 2026 18:12
Ardnived added a commit that referenced this pull request Sep 15, 2026
…754)

* feat(api)!: unify public intakes on a `user-submissions` collection (phase 1)

Phase 1 of #695, per #723: the form-builder plugin's submissions collection
is renamed `user-submissions` and given the typed columns every public write
needs, beside the three collections it will eventually replace. Nothing is
deleted here — `registrations`, `user-messages` and `event-submissions` keep
working until Phase 3.

- `formSubmissionOverrides.slug` + a `fields` override adds `type`, `uuid`,
  `status`, `senderEmail`, `user`, `client`, `subject`, `screeningResult`,
  `activityLog`, `event`, `startingAt`, `unsubscribedAt`, `eventFeedback`,
  `followUpSentAt` and `proposed`. `submissionData` keeps only the flat
  free-form remainder, since it is client-writable as one blob and nothing
  queryable, unique, relational or system-gated can be protected inside it.
- `prepareUserSubmission` (beforeValidate) enforces per-type allowed keys and
  lengths on that blob, issues the `uuid`, composes `subject`, upserts the
  sender into `users`, and stamps provenance from the authenticated key.
- The plugin's unconditional `form` requirement becomes per-type: required for
  `contact` and `subscribe`, refused for the two that name an `event`. The
  plugin's own existence check is composed with, not replaced.
- Forms gain `actionType` with conditional `recipient` / `client`, save-time
  validation of the authored field list, and lose `emails` — a structural
  disable of the plugin's pre-screening `sendEmail`, not a suppression.
- Every `type: 'json'` column declares a `jsonSchema`, `logField`'s included.
  Its entries stay open (`additionalProperties: true`) because machine data is
  each writer's own; `LogDisplayCells` declares the matching index signature.
- `user-submissions` joins RESTRICTED_COLLECTIONS and leaves the wemeditate-web
  project. Clients get create-only; a manager's read is narrowed per row to
  contact rows addressed to them plus proposals.
- The `registrations: ['update']` client grant, its uuid-scoped access branch
  and `restrictClientRegistrationUpdate` are removed. The vote's only writer is
  the CMS-hosted feedback page, which writes with `overrideAccess` — that grant
  was an open write path nothing used.
- `Users` shows one `submissions` join in place of `registrations` and
  `submittedEvents`.

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

* test(api): cover the unified intake's create path, access matrix and form actions

Four spec files, plus the two the change re-points.

Each caught a defect while being written, which is the reason for the shape
they take:

- `user-submissions-access.int.spec.ts` reads rows back through
  `overrideAccess: false` rather than asserting grants, and found that the
  form-builder plugin's own `access` block outranks the whole RBAC layer
  (`accessPlugin` composes `{ ...rbac, ...collection.access }`). Its
  `read: !!user` would have granted every API client read of every stranger's
  message, with `RESTRICTED_COLLECTIONS` looking like it applied. The plugin's
  `access` is now cleared for this collection.
- `user-submissions-create.int.spec.ts` found the Turnstile stub succeeding for
  any argument, so the "no token" case passed for the wrong reason; found the
  offending key missing from a `ValidationError`'s message, which is the one
  thing the acceptance criterion asks for; and found the plugin's `sendEmail`
  throwing once per form-less submission.
- `forms-action-type.int.spec.ts` pins the save-time rules and that `emails` is
  absent from the sanitized config.
- `submission-data.spec.ts` holds the per-type key matrix in the unit lane, and
  the URL-scan exemption that keeps a crash report from reading as spam.

The access, form-action and submission-data specs were each re-run with the
rule they cover disabled, and each went red.

`event-feedback.int.spec.ts` is re-pointed at the real writer: the feedback
page's server action, which votes with `overrideAccess`. Its client-vote block
becomes the assertion that no client write path exists.

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

* fix(api): gate the proposed patch, and loosen the activity-log schema

Two corrections found reviewing the branch against `src/collections/AGENTS.md`.

`proposed` reaches `user-submissions` from a public POST and is a patch of real
Events fields, so Phase 3's accept path would apply it to an Event with a
manager's authority behind it — a submitter setting `verificationStage` mints a
verified listing, and `registrationNotificationEmail` forwards registrants'
answers to an inbox of their choosing. `validateProposal` is `event-submissions`'
own gate and derives its allowlist from the live Events config, so it is reused
rather than re-derived. It moves to a shared home in Phase 3, when that
collection is deleted.

`activityLog`'s schema now declares no `required` keys. Payload runs a JSON
validator on every save of the document, including one that never touches the
column — and this column predates the `logField` factory: it was Registrations'
`reminderLog`, whose entries were reminders with no `cells`. A `required` list
would have made any row holding one permanently unsaveable, which no test here
could see because no test holds a pre-#626 row. Type checks on the properties
that are present still apply.

The verification spec's hand-built log fixture is rebuilt with the real entry
builders either way: the entries it spelled out omitted `type` and `cells`,
which nothing that writes the column omits, so the crash it simulates was a
state the app cannot reach.

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

* docs(api): describe the unified intake's client contract and access rules

The new refusal codes, the URL-scan exemption, and the create-only grant are
things an integrator observes, so they belong beside the Turnstile contract
rather than only in the code that raises them. Also corrects a cross-reference
in EventSubmissions to the Users join that replaced `submittedEvents`.

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

* fix(api): close the defects an adversarial review found in the intake

Nine findings from a security pass and a code-quality pass over the branch.
Five would have shipped a defect; each now has a test that fails without the
fix.

- **An unrecognised `type` crashed the public POST with a 500.** This hook runs
  before Payload validates the select's options, so the cast reached
  `TYPE_SUBMISSION_KEYS[type]` and spread `undefined`. Checked now, with the
  same 400 the neighbouring refusals use.
- **`type` was never reconciled with the form's `actionType`**, and
  `enforceSubscribeReach` keys on `type` — so a restricted client could post
  against another client's subscribe form while calling the row a `contact`,
  and the reach check never ran. The form is the authority; a disagreement is
  refused rather than silently corrected.
- **`activityLog` was client-writable.** `logField`'s docblock promised it was
  never writable through the API and stated that nowhere the server reads, which
  did not matter while the column sat on collections no client could write. The
  admin renders it as system-written history. Denied to clients — deliberately
  not a flat `update: () => false`, because the admin verify action writes that
  log with `overrideAccess: false` so the manager's own permissions gate it, and
  a blanket deny silently dropped the record of who verified a listing.
- **`validateFormAction` merged with `??`.** Payload normalises a cleared
  relationship to `null` and hands the hook data already merged with the stored
  document, so clearing a subscribe form's client read as the old client and
  passed the one rule the hook exists for. It now reads the merged value, and
  judges a save only when it changes the field list, the action or the client —
  which is also what stops a legacy form, back-filled to `contact` and lacking a
  message field, becoming unsaveable on an unrelated edit.
- **`subject` echoed the title of any event id a client named**, drafts and
  trashed rows included, routing around the published-only narrowing a client's
  own reads get.

Three test cases could not fail for their own rule: a form fixture that also
broke a second rule, a `?? []` join assertion that could not tell "filtered to
nothing" from "never populated", and an "admins read everything" case reading
with `overrideAccess: true`. All three assert the property they name now.

Also: the entry cap short-circuits instead of emitting one message per row;
`activityLog` gained `maxItems`; a `.catch(() => null)` that turned a transient
database error into a 400 blaming the integrator is gone; the dead
`urlScanFields: ['subject']` entry is removed with a note saying why field
access had already emptied it; and the docs' claim that both new refusals are
400 is corrected — `subscribe_target_forbidden` is 403.

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

* build(deps): patch drizzle-kit so migrate:create survives a table rename

`pnpm payload migrate:create` died with "Cannot read properties of
undefined (reading 'columns')" on this branch, before writing any file.

drizzle-kit's `applyPgSnapshotsDiff` rewrites the old snapshot as it
resolves each rename, but hands `preparePgAlterColumns` the raw `json1`
instead of the rename-patched copy. So a renamed table that also has
altered columns — `form_submissions` -> `user_submissions`, which is every
collection rename — is looked up in the pre-rename snapshot under its new
name, comes back undefined, and the diff throws.

The patch passes the rename-patched `tables` while keeping the original
`enums`: the same function reads `json1.enums` by *old* enum name, so
substituting the fully patched snapshot would break enum-rename detection.

Still unfixed upstream through 0.31.10, and @payloadcms/db-postgres pins
drizzle-kit to exactly 0.31.7, so patch rather than bump. `payload` and
`@payloadcms/db-postgres` drop their carets for the same reason — a float
onto a release carrying a different drizzle-kit would leave the patch
matching nothing.

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

* feat(db): add the user-submissions migration

The schema change landed in 537da0c with no migration, so every Railway
preview boot ran this branch's code against an unmigrated database and
`GET /api/forms` 500'd on the missing `forms.action_type`.

Renames rather than rebuilds, so existing submissions survive:
`form_submissions` -> `user_submissions`, its `submission_data` child
table, and `payload_locked_documents_rels.form_submissions_id`. Then the
intake columns (`type`, `status`, `sender_email`, `uuid`, the event and
client relations, the jsonb `proposed`/`screening_result`/`activity_log`),
`forms.action_type`/`recipient_id`/`client_id`, and the drop of
`forms_emails` + `forms_emails_locales`, which `action_type` and
`recipient_id` replace. `user_submissions.form_id` loses NOT NULL — a
submission need no longer come from a form.

`down` reverses all of it, including recreating both dropped tables.
Validator: 4 pass, 0 fail; the four warnings are the expected DROP TABLE /
DROP COLUMN / RENAME notices. No DDL here repeats anything in the applied
chain.

Generating it needed the drizzle-kit patch in the previous commit.

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

* docs(migrations): record the drizzle-kit rename patch

The patch and its exact-version pins landed in b001669 undocumented, so the
next person to hit "Cannot read properties of undefined (reading 'columns')"
would re-derive the whole diagnosis. States what the patch fixes, why the
versions lost their carets, and that the rename prompt still needs an
attended run.

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

* Create migration

* fix(db): empty the duplicate resync migration

20260914_175014 was generated against the pre-merge snapshot, so its 142
statements were all re-emissions of DDL this chain already applies. Checked
one by one against every other migration: zero were new. They come from
20260705_160029, 20260705_161112, 20260909_161243, 20260909_161353,
20260909_161848, 20260909_162104, 20260911_235823, 20260912_031449 and
20260913_212558 — every one of them ahead of it in index.ts.

Replaying that aborts the boot migration on its first statement, CREATE TYPE
enum_wm_app_config_available_locales already exists, and the drops further
down would take the translation columns with them. This is #566, the
out-of-order snapshot trap the PR body warned was still open.

The .json half is the fix, not the problem: it was generated on the merged
tree, so it carries both user_submissions and main's 20260909-20260913
schema. Keeping it as the highest-timestamp snapshot with no DDL beneath it
heals the chain. Verified: db:migrations:create --skip-empty now writes no
files, so the snapshot and the config agree exactly.

Nothing rolls back here. The migration failed on statement one, so it
committed no schema and left no payload_migrations row.

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

* docs(migrations): record how to heal a stale snapshot

The trap section said the chain heals once a fresh snapshot lands, but not
what to do with the unusable .ts that arrives beside it. Names the shape —
keep the snapshot, empty the DDL, keep the timestamp — and the probe that
proves it worked.

Also states what cost this a second round: push: !isProduction means no test
lane ever replays the chain, so CI is silent about a migration that cannot
apply. Only a Railway boot runs prodMigrations.

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

* fix(users): keep the registration and proposal joins until Phase 3

The `submissions` join was added in place of `registrations` and
`submittedEvents`, but nothing writes `user-submissions` yet — Phase 1 adds
the schema only. `registerForEvent` still creates `registrations`, and
`event-submissions` still takes proposals. So the new join showed nothing
while the two it replaced were the admin's only window onto a registrant's
live history.

#723 is explicit that the old collections' behaviour does not change this
phase. All three joins now sit side by side; the two legacy ones go in Phase
3, with the collections they read. The comment says why they are still there,
so the next reader does not re-derive it.

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

* fix(deps): pin the whole Payload family, not two of it

`payload` and `@payloadcms/db-postgres` dropped their carets so the
drizzle-kit patch key keeps matching. The other eight family members kept
`^3.86.0`, and Payload does not support a mixed-version family — so one
`pnpm update` could put `@payloadcms/[email protected]` beside a pinned
`[email protected]`, a break with no patch involved.

Every `@payloadcms/*` now pins `3.86.0`, `typescript-plugin` included. No
version moves: only the nine `specifier:` lines change in the lockfile, and
`pnpm install --frozen-lockfile` accepts it unchanged.

`src/migrations/AGENTS.md` says why the pins are there and how to bump them,
beside the patch story that made the first two exact.

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

* fix(forms): one home for the sendEmail removal story

The mechanism was told three times and one telling was wrong.
`Forms/fields.ts` and the first `formBuilder/index.ts` docblock both said
stripping `emails` disables the plugin's `sendEmail` hook, via its
"nothing-to-send" branch. It does not get that far: it loads `data.form` and
spreads `data.submissionData` first, both optional here, so it throws.
Removing the hook is what disables it.

The detailed docblock also sat on `formBuilder` while describing what
`formsPlugin` does. It moves onto `formsPlugin`, which is where the `access`
clear and the hook removal happen, and is now the one statement of both.
`formBuilder` documents the plugin options alone. `Forms/fields.ts` keeps
why `emails` is stripped — it owns that list — and points here for the hook.
`collections/AGENTS.md` points here too rather than restating it.

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

* fix(submissions): say what subject is actually composed from

The docblock said "not client-writable: it is derived". The column is indeed
denied to clients, but `composeSubject` joins a contact form's title with the
sender's own `subject` pair — so unreviewed submitter text does reach the
admin list title, which is the thing the old wording promised it would not.

Wording, not a hole: the pair is URL-scanned, bounded by `checkSubmissionData`
and truncated to 300. The docblock now says both halves, and says to treat the
value as untrusted at any new render site.

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

* fix(submissions): fold the proposal schema into its field

`proposal.ts` was 38 lines for one constant with one consumer, 29 of them
comment. The rationale reads better beside the field it governs, and there is
nothing left to share: the Phase 2 job and admin component that would have
made it a leaf module do not exist yet.

`screening.ts` stays. It has two importers — `UserMessages` reads
`screeningResultJsonSchema` too — so folding it here would make one collection
import another's field list.

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

* fix(forms): inline the one-use block helper

`blockTypes` was a four-line wrapper over `new Set(...)` with one caller, and
its name said what it did rather than why — so a reader met an abstraction
before the rule it serves. The set is now built where it is read, with a line
saying what it is for.

The hook's own purpose is unchanged and stated in its docblock: a subscribe
form with no email field, or a contact form with no message body, collects
nothing usable and fails on every submission thereafter, one visitor at a
time, with the author never present to see it. Refusing the save is the one
moment the person who can fix it is there.

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

* fix(submissions): drop the subscribe reach check

Any client role may now subscribe a person to any client's list, as asked in
review. `enforceSubscribeReach`, its `subscribe_target_forbidden` refusal, the
`UNRESTRICTED_SUBSCRIBE_ROLES` exemption and its integration case are gone,
along with the row in `docs/rules/api-clients.md`.

The `type`/`actionType` reconciliation in `prepareUserSubmission` stays. It was
introduced partly to keep this check reachable, but it stands on its own: every
per-type rule downstream keys on `type`, so a row calling itself a `contact`
against a subscribe form is judged by the wrong rules throughout. Its comment
no longer cites the removed hook.

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

* fix(submissions): declare the JSON columns in zod

`screeningResult` and `proposed` still hand-built a `JSONSchema4` literal and a
`{ uri, fileMatch, schema }` wrapper. #756 made `jsonField` the one way to
declare a JSON column, with the shape in Zod inline at the field, so both are
now declared that way and the three repeated URI strings are gone.

`screening.ts` keeps `SUBMISSION_VERDICTS` and drops the schema. That module is
a leaf an admin component may import, and a Zod shape there would pull `zod`
and a `toJSONSchema` call into the browser chunk to describe a column only the
server validates — the rule in `src/collections/AGENTS.md`. `z.enum` reads the
verdict list directly, so nothing is spliced.

`pnpm generate:types` regenerates `src/payload-types.ts` byte-identically, which
is the evidence that `SubmissionScreeningResult` and `SubmissionProposal` are
the same shapes as before.

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

* fix(fields): declare the activity log in zod

`logField` built its own `{ uri, fileMatch, schema }` wrapper from a
hand-written `JSONSchema4`, which is exactly what `jsonField` exists to stop
(#756) — and it exported `ACTIVITY_LOG_SCHEMA_URI`, the kind of `*_SCHEMA_URI`
constant that refactor deleted everywhere else. Nothing imported any of the
three, so they go rather than being re-exported.

The shape is unchanged: every property stays optional and the entry object
stays open, because Payload runs this validator on every save of the document
and the column predates the factory — a `required` key strands a row holding
an older entry. `z.looseObject` emits `additionalProperties: {}` for that, and
`.max(500)` keeps the cap a single bypassing write would otherwise ignore.

`jsonField` interns one object per distinct shape, so Events, Registrations and
`user-submissions` still share one generated `ActivityLog` interface rather
than getting `ActivityLog1`. `pnpm generate:types` regenerates
`src/payload-types.ts` byte-identically, which is what proves it.

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

* fix(submissions): derive the submission unions from payload types

`SubmissionType` and `SubmissionStatus` were `(typeof ARRAY)[number]`, which is
a restatement one hop away from the generated column — the pattern
`src/types/AGENTS.md` refuses, because such a type drifts wider than the CMS and
then compiles values the database rejects.

Both now read off `UserSubmission['type']` and `UserSubmission['status']`. The
const arrays stay: they are the runtime values `fields.ts` builds the two
selects from, so the column is generated from them and deriving the types back
closes the loop. An option added without a `TYPE_LABELS` or
`TYPE_SUBMISSION_KEYS` entry is now a compile error instead of an `undefined`
spread at runtime.

The module stays a leaf — `@/payload-types` is types only, so nothing reaches a
browser chunk that did not before.

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

* fix(submissions): fold the verdict list in beside its column

`screening.ts` held one const with one consumer and an alias with none, so
it goes the way `proposal.ts` went in b4c2d8f. `SUBMISSION_VERDICTS` now sits
beside `screeningResultField` in `fields.ts`, which builds the schema's enum
from it, and the module's one substantive paragraph — why the machine verdict
lives in this column and never in `status` — moves onto that field.

`SubmissionVerdict` is deleted rather than re-derived. Nothing imported it, and
the list already generates `SubmissionScreeningResult['verdict']`; an exported
alias would be the second definition `src/types/AGENTS.md` says to delete, not
to point somewhere else. A Phase 2 consumer reads the generated type directly.

`pnpm generate:types` leaves `payload-types.ts` byte-identical, which is the
evidence no shape moved.

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

* fix(submissions): read the type unions straight from payload-types

`UserSubmissions/types.ts` is gone. Its two exported aliases were the
re-export chain `src/types/AGENTS.md` prohibits: `SubmissionType` and
`SubmissionStatus` already spelled `UserSubmission['type']` and
`['status']`, and exporting them gave each shape a second home for every
consumer to reach through.

Each consumer now names the generated union at its own call site —
`submissionData.ts` twice, `fields.ts` once, `prepareUserSubmission.ts`
three times — so no file imports a type from another module that is only
forwarding one. With `submissionData.ts` off the module entirely, the
pure-module objection that kept `types.ts` alive last round is gone: it
takes `@/payload-types`, which is types only, and pulls no `zod` or
`logField` into the unit lane.

The runtime halves move to `fields.ts`, beside the selects they build —
the same fold `proposal.ts` and `screening.ts` got. `SUBMISSION_STATUSES`
and `STATUS_LABELS` stop being exported: only `statusField` reads them.

No shape moves. `pnpm generate:types` leaves `src/payload-types.ts`
byte-identical.

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

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Devindra <[email protected]>
Co-authored-by: sydevs-bot <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-626 — 8c49221e Deployed Aug 25, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant