Skip to content

refactor(submissions): judge a proposal as a diff, not a form - #642

Merged
Ardnived merged 26 commits into
mainfrom
refactor/submission-proposal-review
Aug 24, 2026
Merged

Ardnived merged 26 commits into
mainfrom
refactor/submission-proposal-review

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #641. Stacked on feat/event-submissions (#625) — merge that first.

A submission is a proposal to judge, not a document to edit. #625 shipped it as ~25 fields mirroring Events plus a translator; the reviewer edited a form of proposed values with no way to see what would actually change. This collapses that to one Events-shaped patch, reviewed as a diff over a live preview of the resulting listing, and deletes the second review surface.

The review view

Field Renders as
title New Event: <the title the event would be created with> / Update Event: <target's title> — generated on create
screeningResult Status banner — 1–3 word state + what follows from it
submitterInfo Submitted By — identity, and the note as an attributed quotation
proposedChanges (virtual) Proposed Changes — the unified diff
previewEvent (virtual) admin.hidden — carries the merged event to the iframe, renders nothing
event shown only when set — an update proposal, or the event an accepted one created
manager / region shown only when it isn't — the two decisions a new event needs

One status vocabulary. STATUS_LABELS is what each status is called everywhere a reviewer meets it — list column, status select, banner heading — because a row reading "Pending Review" that opens onto a banner headed "Awaiting Review" makes a reader wonder whether they are two different things. The banner adds only the sentence saying what to do about it.

Live preview opens via livePreview.openByDefault (Payload 3.86), not a component. It is applied server-side when building the document view, so the panel is open on first paint, and it yields to the user's stored editViewType once they toggle it themselves — which a setIsLivePreviewing(true) mount effect could not do, and so re-opened the panel every time a reviewer closed it and came back. previewEvent then needed nothing but admin.hidden: Payload renders a HiddenField, so the value still sits in form state (what reduceFieldsToValues posts) with nothing on the page. Both mechanics are now in .claude/rules/admin-ui.md, which had recommended the effect.

Every component lives in components/admin/EventSubmissions/, one file each, each named for what it is.

The diff is unified, not columnar — with live preview open this field gets about a third of the window, and a current/proposed table wrapped every value onto three lines. Group and json fields collapse to one entry rendering every subfield YAML-style, word-diffed, so a venue-name correction shows the address it lands in rather than seven rows of moved keys. Long prose diffs by word. Keys within a block follow the Events config's own field order on both sides — a patch and a stored event enumerate them differently, so insertion order made the same group read one way on a new submission and another on an update, and the word diff called the reshuffle a change. Dates are formatted (18 Jul 2026, 16:00 UTC) before diffing, so the highlight lands on the month a reader sees rather than shredding an ISO string into digit runs. Groups and lists are both judged whole — microdiff reports a hasMany per index, so adding a language surfaced as Languages › #2, a row number a reviewer can't relate to anything. Within a group, a sub-field its own admin.condition rules out is dropped: the recurrence controls share one row and keep whatever was last typed into them, so a weekly event listed Monthly Mode, On Day, Week and Day — state with no effect on it. A condition is a hint for trimming noise and never a reason to show nothing, so a block emptied by its own conditions (the address group's mean “don't reveal these until a place is picked”) falls back to unfiltered. Selects render their option labels. Entries — and the keys inside a block — are ordered by where the collection declares each field: flattenedFields is depth-first in declaration order with tabs and rows flattened away, so that is the order a manager reads down the Events form, re-derived from the live config on every call rather than restated anywhere. Structure comes from microdiff (already a dependency, imported by nothing); word-level from diff (jsdiff) — see the dependency note below.

A manager can be assigned while accepting. Optional, new events only, and the whole of adoption: a created event with a manager is verified on the spot; without one it goes on the map marked unverified until somebody takes it on. newEventDefaults takes it, so the diff, the preview and the write agree about the stage — and the create drops skipVerifyHook, because that flag means "don't open a verification cycle" and skipping it would stamp verified with no nextCheckAt, leaving an event that never comes up for re-verification again.

The banner is written for the person reading it — a manager who runs meditation classes. No internal vocabulary ("adopt it into the verification cycle" → "the public sees this event marked unverified until it has a manager"), no delivery bookkeeping, and no line that restates the title: spam carried a heading, a fixed message and a note all saying the same thing, and now carries the reason alone. Screening stopped writing notes that ask nothing of anybody — a failed DNS lookup, which inbox got the review request — keeping them as an unrendered diagnostic instead of discarding them; and notes stop rendering once a submission is decided, since "check the Region below" was still showing on accepted ones, pointing at a field the page no longer shows.

Actions match the status: Accept / Reject while open, Reopen for spam or rejected, Delete once applied. No Save — correcting a region decides nothing on its own, so Accept persists the form when it's dirty.

One patch instead of a mirrored schema

proposed holds an Events data patch keyed by real field names, applied verbatim on Accept. mapToEvent.ts is deleted: with the widget sending the real scheduleFields shape there's no vocabulary to translate. mergeProposal merges the way Payload merges — groups recurse, arrays and nulls replace, rich text replaces whole — verified against the running API, because a diff that disagrees with what Accept writes is worse than no diff.

The submission's title reuses the same composition the Events title hook runs (lib/eventTitle/autoTitle.ts, lifted out of Events/hooks/eventTitle.ts so both share it), so the label a reviewer approves is the title they end up with.

Live preview needs no access change and no preview endpoint. Payload posts the document's form state into the iframe; previewEvent carries the merged event in that payload. The widget never reads event-submissions — it can't (create-only for API clients, and a new-event submission has no id to fetch).

One review surface. /submissions/review and its HMAC token helpers are deleted; the email links to the admin view. Review now requires being logged in — the trade for not maintaining two implementations of Accept/Reject.

Screening writes its own notes. The status bullets used to be assembled by the banner from stored enums — Email verdict: disposable email, No responsible manager found — which read like a debug dump and left the reviewer to infer the consequence. Screening is the only party that knows why it decided what it did, so it now composes complete sentences at the moment it decides ("No city could be matched to the submitted address, so this submission has no region yet. Set the Region field before accepting — a new event can't be created without one."). The enums are still stored for triage and querying; they are simply not what gets rendered. The shape moves to a leaf screening.ts — it had been declared in the job and re-declared, untyped, in the component, which is how the two drifted far enough that a malformed emailVerdict 500'd the edit view.

Defects found while building this

  • The spam scan had stopped working. The write guard named top-level fields, but the free text moved inside proposed / submitterInfo. An integration case that had pinned urls_not_allowed started passing spam through. Repointed — and the security pass then caught that naming address.venueName still left street, room and city unscanned, so the whole group is scanned now.
  • A nested read was rolling back the write. The virtual-field hooks loaded the target with the caller's req. They run in the afterRead of a create, so joining that transaction aborted the write: payload.create returned a document with an id and no row behind it. disableErrors doesn't help — the shared transaction is the problem. Written up in .claude/rules/collections.md.
  • Privilege escalation through proposed. The gate excluded admin.readOnly fields, but the registration cluster carries no readOnly — a manager edits it freely. An anonymous submitter could have set registrationNotificationEmail (every registrant's name, email and answers forwarded to an inbox of their choosing) or registrationMode: 'external' + externalRegistrationUrl (every registrant redirected off-site). Now privileged, along with images and the timestamps. The durable guard is a test pinning the exact proposable set against the real Events config — adding a field to Events fails it until someone decides whether the public may propose it.
  • inactive was invisible. Accepting a schedule-less submission creates a dormant listing that never appears on the map, and neither the diff nor the preview said so. The new-event defaults are now a function of the patch, composed by preview, diff and write alike.
  • Rich text was merged as a group — lexical is a plain object, so the recursive merge grafted the target's root attributes onto the proposal's tree. It replaces whole now.

Review notes

  • /simplify — 8 findings, 3 applied (shared status vocabulary via a leaf statuses.ts; inline margin → class). Rejected: importing status constants from EventSubmissions.ts (would pull serverEnv + every hook into the admin bundle — a leaf module was the right fix instead); "STATUS_LABELS and the banner copy are identical" (they differ deliberately — a stored value vs. what to do next); React key counter and a replaceAll memo (churn); hardcoded region-level tuples (pre-existing from feat(events): public event submissions, screening pipeline & write-guard plugin #625, out of scope).
  • /code-review — 1 high, 3 medium. Fixed: the inactive gap and the lexical merge. Rejected: the claim that a YAML key can split across diff segments and lose its bolding — both sides render keys from the same Events config, so a key can't differ between before and after; verified in the served HTML that an added line (On Days) is bolded.
  • /security-review — no critical/high. Fixed the address URL-scan gap and added the nested-key test. Not fixed, flagged: the live-preview postMessage carries the whole form state, including submitterInfo — so submitter name/email reach the Atlas iframe, which only needs previewEvent. It's a targeted postMessage to our own origin in a manager's browser, and the mitigation (dropping live preview) removes the feature; Event submission preview — render a user-submission proposal from postMessage SahajAtlasWeb#163 now carries the requirement as its own section: the preview route must render only data.previewEvent, verify the message origin, and never log (no Sentry breadcrumb) or persist the payload — with a scope checkbox against it.

Dependency

Adds diff (jsdiff) for diffWords. I tried fast-diff first — one file, no deps, the "does one thing" option — and rejected it on output: being character-level it rendered "main hall" → "annexe building" as m/a/i/n/n/exe, and it exports no semantic-cleanup pass. jsdiff is larger but runs server-side only, in the proposedChanges afterRead, so it never reaches the admin bundle. Flagging it explicitly since new dependencies need sign-off.

Verification

lint, typecheck, typecheck:tests, 1204 unit tests, 35 integration tests — all green.

Guards were mutation-checked rather than assumed: emptying PRIVILEGED_FIELDS fails the forgery test, and so does trimming it to manager/region. The diff-ordering tests were checked the same way — the first version of the "follows the collection" case passed with the sort removed (reversing the field list happened to coincide with blocks-then-scalars), so it now uses a permutation that interleaves a group and a list with the scalars.

Three migrations: 20260820_011749_submission_proposal_patch (drops the mirrored columns, adds the three jsonb), 20260820_151908_submission_title, and 20260820_202018_submission_manager. Separate from 20260812_032435_add_event_submissions, which is already applied to the #625 preview — regenerating it would crash the boot migration on "column already exists". No backfill: the collection has never left dev/preview.

Manual check that matters: open a pending update proposal — the diff should list only changed fields, live preview should already be open showing the event with the proposal applied, and the Network tab should show no request for /api/event-submissions/:id. The event data must arrive purely via the payload-live-preview postMessage.

⚠️ Live preview stays dark until sydevs/SahajAtlasWeb#163 lands. Everything else here stands alone.

🤖 Generated with Claude Code

@railway-app

railway-app Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Aug 24, 2026 at 6:05 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-642 August 20, 2026 19:14 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-642 August 20, 2026 20:03 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-642 August 20, 2026 20:29 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-642 August 20, 2026 20:52 Destroyed
Ardnived added a commit that referenced this pull request Aug 20, 2026
* docs(migrations): disambiguate "exit 0, no new files"

The outcome table read that signal as "no schema changes", full stop. In
PR #642 it meant the CLI had died silently instead — a `manager_id`
column genuinely needed a migration, and the table pointed straight at
the wrong conclusion. Shipping a schema change with no migration is a
prod crash-loop on boot, not a silent no-op, so the two readings are
worth separating.

They are indistinguishable from the shell, so the table now splits on
the newest `.json` snapshot: it is the schema the next migration diffs
against, so a column missing from it has been captured by nothing.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(tests): note that "no tests" means the spec doesn't parse

Vitest reports a syntax error in a spec file as an empty one, so a
broken test name reads as "no case matched" and sends you looking at the
lane config instead of the file you just edited.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-642 August 20, 2026 21:13 Destroyed
@Ardnived
Ardnived changed the base branch from feat/event-submissions to main August 24, 2026 17:59
Ardnived and others added 20 commits August 24, 2026 11:00
…atch

EventSubmissions carried ~25 fields mirroring Events, plus a
`mapSubmissionSchedule` translator converting the copy back into the real
shape. Two sources of truth with a lossy layer between them.

A submission now carries `proposed` — an Events data patch keyed by real
Events field names, which Accept applies verbatim. `mapToEvent.ts` is
deleted outright: with no simplified schedule vocabulary there is nothing
to translate and no Temporal reconstruction to get wrong.

`validateProposal` gates the patch at intake against the live Events
config: every key must be a real Events field, and none may be
system-managed (derived from `admin.readOnly`) or privileged. Without it
an anonymous POST could set `verificationStage: 'verified'` and a
`manager`, minting an adopted listing. Per-value validation stays where
it already was — Events' own validation at Accept, which runs with full
sibling context and surfaces to the reviewing manager.

Submitter strings and region targeting fold into `submitterInfo` /
`regionHint` JSON. The `submitter` relationship stays a real column: it
is what `upsertUserByEmail` writes, and a Users join can only target a
relationship (cf. `Users.submittedEvents`).

The screening email's `buildDetails` now reuses the diff's own formatter
and labeller, so email and review screen describe a submission the same
way and a new Events field reaches both without either being edited.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
The review view now shows what would change rather than a form of
proposed values. Three components, each mounted on the field holding the
data it renders (the pattern Events uses for notificationLog and
qualityReport) rather than on `ui` fields reaching across form state:

- ProposedChangesField on `proposedChanges` — a Payload `Table` of
  field / kind / current / proposed. The diff itself is microdiff, which
  was already a dependency and imported by nothing; it runs server-side
  because the browser has the proposal but not the event it would land
  on. Labels come from the Events config, so the wording cannot drift.
- SubmitterPanel on `submitterInfo` — who sent it, read-only.
- EventPreviewMount on `previewEvent` — opens live preview on mount and
  renders nothing. Keeping the arming and the data on one field means
  the panel can't be opened on a document with nothing to show.

Live preview needs no access change and no preview endpoint: Payload
posts the document's form state into the iframe, and `previewEvent`
carries the merged event in that payload.

The notice banner stops mapping `warning` onto Banner's `error` type —
`.banner--type-error` applies color-svg(--theme-error-600) to every svg
inside it, repainting WarningIcon's amber fill red and making a
"needs a look" notice look like a failure. `.banner--has-icon` also sets
only `display: flex`, so a 26px icon beside wrapping text stretched and
drifted off the first line; three declarations in styles.css fix it.
`emailVerdict` is now type-guarded — it 500'd the edit view when a
malformed value reached `.replaceAll`.

Accept no longer saves the form first; with nothing editable but
`region` there is nothing to persist before deciding.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Removes the ~25 columns and two child tables that mirrored Events, and
adds `proposed` / `submitter_info` / `region_hint` jsonb.

Pure drop + add: drizzle's rename-vs-create prompt was answered "create
column" for each, which is correct — none of the new JSON columns is a
renamed old one, and a rename would have carried a scalar into a jsonb
column. The `down` path restores every column, both child tables and
their FKs/indexes.

A separate migration rather than a regeneration of
20260812_032435_add_event_submissions: that one is already applied to
the #625 preview environment, and re-emitting it with a new timestamp
would crash the boot migration on "column already exists".

No data backfill: #625 is still open against main, so this collection
has never existed outside dev and preview.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
…t of the write

Two defects the schema collapse exposed.

The write guard's URL and email scans still named top-level fields, but
the free text a spammer would use now sits inside `proposed` /
`submitterInfo`. The scan silently found nothing — an integration case
that had pinned `urls_not_allowed` started passing the spam through. The
guard already walks paths, so the policy just needed repointing.

The `previewEvent` / `proposedChanges` hooks loaded the target event with
the caller's `req`. Those run in the `afterRead` of a create, so the
request is mid-transaction, and joining it for a read-only projection
aborted the write: `payload.create` returned a document with an id and
left no row behind it, and only submissions naming a target event took
the path. The projection needs the event's committed state, so it uses
its own connection; `req` remains the memo key.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Unit — mergeProposal (patch over target, group replaced wholesale not
merged, new-event defaults), the diff's value formatting and
Events-config labelling, and proposableEventFields.

Integration — the forgery gate (verificationStage / manager / region /
_status each rejected, posted as the literal wire body so the fixture
helper can't hoist a key out of the patch and quietly test nothing), the
diff and preview projections against a real target, and the findMany
guard that keeps a list read from firing an event lookup per row.

The privileged-field guard was mutation-checked: emptying
PRIVILEGED_FIELDS makes the forgery test fail.

Replaces the mapSubmissionSchedule / submissionEventPatch specs, whose
subjects are deleted. The remaining schedule fixture moves to the real
scheduleFields shape — with no translator, whatever the widget sends is
what Events validates on Accept, and the old vocabulary is now correctly
rejected.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Left behind when the mapSubmissionSchedule / submissionEventPatch specs
moved out.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Live preview pushes the document's form state into the iframe, so a
frontend does not have to fetch it back. Every preview route in this repo
re-fetches by collection+id, which reads like the only way — it isn't,
and it costs you preview on a restricted collection or a document with no
id, both of which describe an event submission.

A virtual field's afterRead also runs on the response of a create, while
that write's transaction is open. Forwarding `req` into a nested read
there aborts the write: `payload.create` returns a document with an id
and leaves no row behind it, and `disableErrors` does not help because
the shared transaction is the problem, not the read's result.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
ProposedChangesField and NotificationLogField each carried an identical
`column()` helper — same signature, same `field: {} as never` stub for
the property the Table type demands and never reads. Extracted to
`components/admin/tableColumn.ts` so the next table doesn't copy it a
third time.

Found by the /simplify reuse pass.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
…ed patches

A `proposed` patch is applied to Events with manager authority on Accept.
The gate excluded fields Events marks `admin.readOnly`, plus a short list
of manager-editable-but-privileged ones — and the registration fields
carry no `readOnly`, because a manager edits them freely. So an anonymous
submitter could propose:

- `registrationNotificationEmail` — every registrant's name, email and
  question answers forwarded to an inbox of their choosing, silently,
  from the moment a manager accepted;
- `registrationMode: 'external'` + `externalRegistrationUrl` — every
  would-be registrant redirected off-site;
- `images` — the listing dressed in another event's photographs;
- `createdAt` / `updatedAt` — a forged history.

The whole registration cluster is now privileged: registration is the
event's data-collection surface, and a submitter is only ever describing
an event, never configuring one. `join` fields are excluded by type — a
join has no column for a patch to write.

The security review found the notification-email hijack; the redirect via
`registrationMode` came out of checking the same class of field, and the
timestamps and the join came out of the new pin test.

That test is the durable part: it asserts the exact proposable set
against the real Events config, so adding a field to Events fails until
someone decides explicitly whether the public may propose it. The three
concrete exploits are pinned as their own cases.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Found reviewing the diff against real data.

`mergeProposal` replaced a group wholesale, so a proposal correcting only
`address.venueName` rendered as street, city, country, postcode and both
coordinates being *removed* — and the live preview showed the same
gutted event. Payload does not do that: verified against the running API,
`payload.update` with `{ address: { venueName } }` changes the venue name
and leaves its siblings intact. The diff was misrepresenting what Accept
writes, which is the one thing it must never do.

It now merges recursively through plain objects, while arrays and
explicit nulls replace — matching Payload on both counts. That alone
took a real update proposal from 27 rows to 10: the schedule group's
derived values (`icalRule`, `upcomingDates`, `lastDate`) are inherited
from the target now rather than read as deletions, so a one-line
schedule edit no longer lists its own consequences as seven more.

Also classify by what the reviewer sees rather than by microdiff's
key-level verdict: a column that held `null` and now holds a value is a
CHANGE to microdiff and plainly an addition to a human.

`proposed.venueName` in the write-guard policy was scanning a path that
never exists — the field nests inside the address group. Repointed, and
`proposed.title` added.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Three things that only showed up once the review view had real data in it
beside an open live-preview panel.

**The diff is unified.** Four columns of current/proposed wrapped every
value onto three lines in the ~third of the window this field gets with
preview open. Now it is label, then the current value struck through in
red above the proposed value in green, one column. An addition prints no
struck-out `empty` line and a removal prints no green one — only the side
that says something. No new dependency: `proposedChanges` already carries
label/before/after, so a text-diff library would only re-derive what the
server computed, and against raw JSON it would show quotes, commas and
field names instead of "Contact Phone Number".

**The submitter note reads as a quotation** — indented behind a rule,
italic, attributed. It is a stranger's own words, and a reviewer weighing
whether a submission is plausible needs to see that at a glance; as a
plain line with quote marks it read as the CMS talking. The email is a
mailto link, since replying is the obvious next move.

**The actions match the status.** "Save" was the only offer on a resolved
submission, which said nothing about what a manager could do next:

- open — Accept / Reject, with Save alongside for the one editable field
  (`region`), since fixing an unresolved region gates Accept;
- spam / rejected — **Reopen**, back to pending with the review stamp
  cleared. A screening false positive was otherwise unrecoverable from
  the admin;
- created / updated — **Delete**, the record having served its purpose.
  The event it created is untouched, and the confirm says so.

Reopen goes through `applyReview` rather than letting the form PATCH
`status`, so every transition stays in one place, and it refuses
`created`/`updated` (409 `not_reopenable`) — reopening one would invite a
second Accept and a duplicate listing with it.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
…itter card

**Long values diff by word.** A rewritten description was previously two
full paragraphs, leaving the reviewer to spot the edit themselves. Values
over 60 characters now render once with only the changed words
highlighted.

Adds `diff` (jsdiff) for its `diffWords`. I tried `fast-diff` first — one
file, no deps, exactly the "does one thing" library asked for — and
rejected it on its output: being character-level it turned "main hall" →
"annexe building" into `m`/`a`/`i`/`n`/`n`/`exe`, unreadable for prose,
and it exports no semantic-cleanup pass to group those back into words.
jsdiff is the larger package but runs **server-side only**, in the
`proposedChanges` afterRead, so it never reaches the admin bundle.

**The transition is named, not pilled.** The pill pushed the field name
onto its own line at this width and drew the eye first, when the name is
what a reviewer scans for. It is now a bold coloured suffix — "Contact
Phone Number — Changed" — and the red/green lines carry the rest.

**The submitter card is Payload's `Banner`** at its default neutral type,
so background, padding and radius come from the theme rather than from
hand-rolled CSS. `Card` was the obvious alternative and doesn't fit: it
takes a `title` string and no children, leaving nowhere for the note. The
note is a `<q>`, which supplies locale-correct quotation marks itself —
the point being that a reviewer can tell the submitter's words from ours.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
…l the fields

**Renames.** `SubmitterPanel` → `EventSubmitterPanel`,
`ProposedChangesField` → `EventSubmissionChanges`, `EventPreviewMount` →
`EventSubmissionPreview`. Every component on this page now says which
collection it belongs to; `src/components/admin/` is flat and shared, so
a bare `SubmitterPanel` read as if any collection could mount it.

**Field titles come from the collection.** `screeningResult` is labelled
"Status" (the banner is the submission's status, whatever the column is
called), plus "Submitted By" and "Proposed Changes".

Removing `label: false` was not enough on its own, and the reason is
worth recording: a custom `Field` component replaces Payload's **whole**
field render, label included, so dropping `FieldLabel` deleted the
headings rather than handing them back — only `event` and `region`, which
use default components, still drew one. `FieldLabel` *is* the built-in
title component, so it stays, now fed straight from `field.label` with no
fallback string: the collection is the only place the wording lives.
`previewEvent` keeps `label: false` — its component renders nothing, so a
heading would sit above empty space.

**The banner has its colour back.** Mapping `warning` onto Banner's
`error` type was what repainted the amber WarningIcon red, so the last
fix sent it to `default` — and left the entire pending state grey and
inert. Banner ships no warning variant, so this adds one from Payload's
own `--theme-warning-*` ramp (defined in its `colors.scss`, just unused
by Banner) and leaves the icon alone. No `info` variant: Payload defines
no info ramp, and screening/rejected are genuinely neutral.

**Smaller:** only a *changed* field is suffixed now — an addition shows
one green line and a removal one red line, so naming those was noise. The
submitter's note is prefixed "Message:" (upright, so the italics mark
only their words).

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
**A submission now has a title**, stamped on create: "New Event: <the
title the event would be created with>" or "Update Event: <the target's
title>". The list was a column of ids and the breadcrumb said "1", when
the two things a reviewer sorts by are which event and whether it is new.

For a new event the name is resolved through the **same composition the
Events title hook runs**, so the label a reviewer approves is the title
they end up with — a submission proposing a venue called Old Scout Hut is
named "New Event: Meditation at Old Scout Hut", exactly as Events would.
A submitter-supplied `proposed.title` wins, because Events only auto-fills
a blank one.

Getting that required lifting `resolveTitlePlace` / `resolveTitleTemplates`
out of `Events/hooks/eventTitle.ts` into `lib/eventTitle/autoTitle.ts`,
alongside the pure `compose.ts`. They were module-private, and a
cross-owner import into another collection's folder is what
`.claude/rules/project-structure.md` prohibits; the documented resolution
is to generalize into `src/lib/`. Events now composes from there too, so
the two cannot drift.

Where nothing names the place — an online submission with no address and
no anchor region, screening not yet having resolved one — the title
degrades to the bare prefix rather than guessing. "New Event" is honest,
and the diff under it carries the detail.

**The status notice leads with the state.** Each status gains a 1–3 word
title and a body trimmed of what the title, the buttons, or a field's own
description already said: the region hint and the Event link each explain
themselves where they sit, so the banner stopped repeating them. The
screening detail notes stay — a verdict and its warnings are unique data,
and they are what a spam call is triaged from.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
**A group now diffs as one block.** Seven separate "Address › …" rows told
a reviewer which keys moved but never what the address ends up reading as.
Any change inside a group or json field now collapses to a single entry
rendering *every* subfield YAML-style, word-diffed, so the edit is shown in
the context that makes it judgeable.

The YAML is hand-rolled rather than handed to a serialiser, deliberately:
keys are replaced with the Events field labels used elsewhere in the diff,
and leaves go through `formatValue`, so a populated relationship reads as
its title here exactly as it does on its own row. A serialiser would print
the raw shape.

Two things only real data revealed. Lexical rich text is a plain object
too, so the description was being block-rendered as `Root: / Type: root /
Children: [{…}]` — it stays on the scalar path, where `formatValue`
already turns it into the words a reader sees. And a rendered group
surfaced fields nobody proposes: `icalRule`, `upcomingDates`, `lastDate`
(all derived from the dates beside them) and the opaque Mapbox id behind
the address search box, now filtered.

**One folder.** Every component for this collection lives in
`components/admin/EventSubmissions/`, one file each, each named for what
it is rather than what it renders: `EventSubmissionNotice` →
`…Status`, `EventSubmitterPanel` → `…Submitter`, `EventSubmissionSaveButton`
→ `…Actions` (it draws Accept/Reject/Reopen/Delete, and hasn't been a save
button for several commits). Class prefixes follow, and the three
stylesheets merge into one.

**Rejected is red.** It was neutral, which read as informational; it is a
refusal, and should look like spam does at a glance.

**The submitter card is actually grey.** Banner's default background reads
from `--theme-elevation-*`, which `ProjectTheme` tints per project — under
Sahaj Atlas the "neutral" card came out blue. Mixing the text colour into
transparency gives a true grey that still inverts in dark mode.

**The title field moves into the System drawer** — it is derived and
read-only, and it already names the page via `useAsTitle`.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
**Group keys are bold**, so a rendered block scans as a table rather than
a paragraph. Done by walking the diff segments rather than the finished
string: a segment can begin mid-line, so only a key that genuinely starts
a line counts, and "10:30" inside a value must not become one. Group
entries carry a `block` flag for this rather than the renderer sniffing
for newlines, which would mistake any multi-line description for a group.

**Save is gone from the open state.** Saving a corrected region decides
nothing on its own, so it was asking for two steps where there is one
action; Accept now persists the form first when it is dirty. Nothing else
on the page is editable, so a dirty form can only mean the region moved.
The create view keeps a Save — a document that does not exist yet has
nothing to accept.

**The submitter card goes back to Banner's own background**, tinted with
the project theme like every other banner.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
"Needs Review" was amber, sitting beside red Spam, which made the
collection's normal inbox read as a fault. It is the state every
legitimate submission occupies until a manager decides — the point of the
collection, not an exception. Now neutral, and worded "Awaiting Review":
a queue rather than an alarm.

That leaves no status using `warning`, so the severity comes out of the
union along with its icon, its banner mapping and the custom
`--theme-warning-*` variant added for it. Payload ships no warning banner
style, which is why that variant existed; with nothing needing it, every
severity maps onto a variant Banner actually has and the override is gone.

The "— Changed" suffix in the diff keeps the warning ramp — that one is
genuinely drawing attention to a difference.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
`EventPreviewMount` is `EventSubmissionPreview` now, and `lib/eventTitle/`
is no longer purely pure: `compose.ts` still is, but `autoTitle.ts`
resolves a title against the templates global and the region name, and is
shared by the Events title hook and EventSubmissions.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Findings from the simplify / code-review / security passes.

**`inactive` was invisible to the reviewer.** `applyReview` derives it
from the patch — no schedule proposed means a dormant listing, which never
appears on the map until someone gives it one — but `mergeProposal` used a
flat constant, so neither the diff nor the live preview mentioned it. A
reviewer approved a complete-looking diff and got a hidden event. The
defaults are now a function of the patch, composed by the preview, the
diff and the write alike, so `applyReview` no longer restates
`verificationStage` / `manager` either. The new integration case proves
it: with no schedule the fixture had to grow a contact number, because
Events requires a contact route on a dormant listing — exactly what the
diff now surfaces up front.

**Rich text was being merged as a group.** Lexical is a plain object, so
the recursive merge walked into it and grafted the target's root
attributes onto the proposal's tree. It is a value, not a group — the same
reason `proposedChanges` keeps it off the block path — so it replaces
whole now.

**The URL scan covered one address subfield.** The policy named
`proposed.address.venueName`, leaving street, room, city and the rest
unscanned; a spammer could put a link in the street line. Naming the group
lets `stringLeaves` walk all of it, which is what the comment above the
policy already claimed.

**The status union was written out three times** — collection, review op,
two components — as string literals. Importing from `EventSubmissions.ts`
would have pulled `serverEnv`, every hook and the review endpoint into the
admin bundle, so a leaf `statuses.ts` that imports nothing carries it
instead. The components now derive their button conditions from the same
sets the review op enforces: a button offered for a status `applyReview`
would refuse is a promise the UI can't keep. `STATUS_LABELS` stays
distinct from the banner copy on purpose — the select names a stored value
("Pending Review"), the banner says what to do next ("Awaiting Review").

Also pins that an unknown key nested inside an allowed group never reaches
the event, and moves the notes list's inline margin into a class.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Three things a reviewer noticed reading the diff side by side:

- A YAML key was only bolded on a *changed* group. An added group carried
  no segments at all, so a wholly-new address rendered flat. Block entries
  now always carry segments, added or changed.
- A patch and a stored event enumerate their keys in different orders, so
  the same group read one way on a new submission and another on an
  update — and the word diff called the reshuffle a change. Keys now
  follow the Events config's own field order on both sides.
- Dates diffed as raw ISO strings, shredding `2026-07-18T16:00` into
  digit runs. They're formatted first (`18 Jul 2026, 16:00 UTC`), so the
  diff lands on the parts a human actually reads.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Ardnived and others added 6 commits August 24, 2026 11:00
The status bullets read like a debug dump — `Email verdict: disposable
email`, `No responsible manager found` — leaving the reviewer to infer
what followed from each. And the shape was declared in the job and
re-declared, untyped, in the component, which is how the two drifted far
enough that a malformed `emailVerdict` 500'd the edit view.

Both fixed by the same move: a leaf `screening.ts` holds the typed
`ScreeningResult` plus the note-writing functions, and the job composes
complete sentences at the moment it decides, because it is the only
party that knows *why*. `warnings` becomes `notes`; the enums stay
stored for triage but are no longer what gets rendered.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Three things a reviewer hit reading submission 14 side by side.

**A schedule listed nine keys, most of them inert.** The recurrence
controls all live in one row and keep whatever was last typed into them,
so a weekly event still carried `Monthly Mode`, `On Day`, `Week`, `Day`
and a stale `Occurrences` — state with no effect on the event, and no
clue as to how any of it related. The admin form already hides them, and
that rule is `admin.condition` on the field, so the diff now asks the
same question rather than hard-coding which keys pair with which. Select
values render as their option labels too (`Repeats: Weekly`, not
`WEEKLY`; `On Days: Thu`, not `TH`).

A condition is a hint for trimming noise, never a reason to show
nothing: the address group's conditions mean "don't reveal these until a
Mapbox place is picked", so honouring them literally filtered away every
line of a hand-typed address. A block emptied by its own conditions
falls back to the unfiltered one.

**A list diffed by row number.** microdiff reports a hasMany per index,
so adding a language surfaced as `Languages › #2`. Lists are now judged
whole, like groups: `German` → `German, English`.

**An added block was segmented** only so the renderer could bold its
keys off the segments, which made a pure addition look like a partial
edit. It's one plain `+` side again; the renderer bolds off `block`.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Entries came out blocks-first, each set in whatever order microdiff
walked them, so an update read Languages, Address, Schedule, then the
contact row — an order matching neither the form a manager knows nor
anything else.

They now sort by where the collection declares each field.
`flattenedFields` is depth-first in declaration order, with tabs, rows
and collapsibles flattened away, so that *is* the order a manager reads
down the Events form — and it's re-derived from the live config on every
call, so moving a field in Events.ts moves it in the diff with nothing
here to keep in step. A key the config doesn't declare sorts last rather
than being dropped; an unrecognised key is exactly what a reviewer
should see.

Same rule the group renderer already applied to its own keys, so both
now share one `declarationRank`.

Mutation-checked: all three ordering tests fail with the sort removed.
The first version of the "follows the collection" case passed without it
— reversing the field list happened to coincide with blocks-then-scalars
— so it now uses a permutation that interleaves a group and a list with
the scalars.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
…or one

Three changes to what a reviewer sees and can do.

**`event` is hidden when empty.** A read-only relationship with nothing
in it says only "no event" — which is already the message of the two
fields shown in its place. `event` and `manager`/`region` are now
complementary conditions, so the page always offers exactly one of the
two.

**A `manager` field, new events only.** Optional, and the whole of
adoption: a created event with a manager is verified on the spot,
without one it goes on the map marked unverified until somebody takes it
on. An update proposal's target already has its own manager, so the
field — and `region`, for the same reason — only show when there is no
event yet. `newEventDefaults` takes the manager, so the diff, the
preview and the write all agree about the stage. The create drops
`skipVerifyHook` when a manager is assigned: that flag means "don't open
a verification cycle", and skipping it would stamp `verified` with no
`nextCheckAt`, leaving an event that never comes up for re-verification
again. Pinned by an integration test that fails on exactly that.

**The banner is written for a manager, not for us.** It said "assign a
manager to adopt it into the verification cycle" — internal vocabulary
for what a reviewer needs stated plainly: the public sees this event
marked unverified until it has a manager. Spam said "Marked Spam / Kept
for abuse tracking. Nobody was notified." and then a note repeating the
classification; it now carries the reason alone. Screening no longer
writes notes that ask nothing of anybody — a failed DNS lookup and which
inbox the review request reached are ours to worry about, and are kept
as an unrendered `diagnostic` rather than discarded. Notes stop showing
once a submission is decided: "check the Region below" was still there
on an accepted one, pointing at a field the page no longer shows.

Two rendering defects surfaced by putting a relationship in the diff: a
populated one was block-rendered, so a proposed manager came out as
their whole row — id, roles, email, every notification preference — and
`data.manager` is a bare id inside a field `afterRead`, so it read
`Manager: 496`. References now format by name, resolved through the same
per-request memo as the target event.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
…yDefault

**The list and the banner now read from one place.** A row saying
"Pending Review" opened onto a banner headed "Awaiting Review", which
makes a reader stop and wonder whether they are two different things.
`STATUS_LABELS` is now what each status is *called* everywhere a
reviewer meets it — the list column, the `status` select, and the
banner's heading — and the banner adds only the sentence saying what to
do about it. (An earlier /simplify pass proposed merging these and I
rejected it, on the grounds that a stored value and an instruction are
different things. The instruction still is; the *name* never was.)

**`EventSubmissionPreview` is deleted.** Payload 3.86 has
`livePreview.openByDefault`, which does the same job better: it is
applied server-side when building the document view, so the panel is
open on first paint instead of after a mount effect, and it yields to
the user's stored `editViewType` preference once they toggle the panel
themselves — which the effect could not do, and so re-opened the panel
every time a reviewer closed it and came back.

That left the component doing nothing but render `null` to keep
`previewEvent` off the page, which `admin.hidden` does natively:
Payload renders a `HiddenField`, so the value still sits in form state —
what `reduceFieldsToValues` posts to the iframe — with nothing taking up
space. Verified in the served HTML: the hidden input's attribute reads
`[object Object]`, i.e. `useField` handed it the real object.

Both mechanics written up in `.claude/rules/admin-ui.md`, which
recommended the effect. `FrameEditor` keeps it — it arms the preview on
a tab, not on the document.

Mutation-checked: with the stored preference cleared, removing
`openByDefault` drops `collection-edit--is-live-previewing` from the
server-rendered markup.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
Cost a wrong implementation this branch: I assumed `data.manager` would
be the populated doc at admin depth and passed it straight through, and
the diff rendered `Manager: 496`. Population happens elsewhere in the
read, so a field hook sees the raw id whatever depth the caller asked
for.

Documented beside the sibling rule it depends on — the resolution has to
skip `req`, for the transaction reason directly above — with the
`memoizeOnRequest` shape both review hooks share, and the neighbouring
trap that a populated relationship is a plain object and will be
expanded as a group by anything that assumes otherwise.

Refs #641

Co-Authored-By: Claude Opus 5 <[email protected]>
@Ardnived
Ardnived force-pushed the refactor/submission-proposal-review branch from abfa9a5 to f5587d9 Compare August 24, 2026 18:02
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-642 August 24, 2026 18:02 Destroyed
@Ardnived
Ardnived merged commit b4d7741 into main Aug 24, 2026
2 checks passed
@Ardnived
Ardnived deleted the refactor/submission-proposal-review branch August 24, 2026 18:10
Ardnived added a commit that referenced this pull request Aug 25, 2026
`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]>
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]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-642 — f5587d96 Deployed Aug 24, 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.

Event submissions: judge a proposal, don't edit a copy

1 participant