Repository navigation
feat(api)!: async user-messages intake with deep spam screening - #653
Conversation
The intake is becoming a `user-messages` collection screened by a job, so the email path is named for what it carries rather than for the endpoint that used to own it: - `sendContactAdmin` -> `sendUserMessage` - `ContactAdminEmail` -> `UserMessageEmail` (plus `buildContactDetails` -> `buildUserMessageDetails` and the two exported types) - `ContactAdminContext` -> `UserMessageContext`, relocated out of `endpoints/responseTypes.ts` into the collection that will store it Also corrects the template footer, which promised "nothing about this message is stored; this email is the only record". That was true under #602 and is about to be false — a copy is kept for screening and triage, then purged. What the sender is told about their own data is not bookkeeping trivia, so it changes with the behaviour. `CONTACT_EMAIL` is untouched: it is the public support address, not part of this intake. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replaces the synchronous send inside `POST /api/contact-admin` with a persisted collection plus a screening job, applying the shape `ScreenEventSubmissions` established to a second public intake. Intake moves onto the collection seam — API clients create through the built-in `POST /api/user-messages` — which is what earns it the usage plugin's origin enforcement and the write-guard's anti-spam policy instead of hand-rolling both. Screening runs what the request path could not afford: an MX lookup (fail-open), a disposable-list re-check, how many messages this sender sent in the last 24h, and whether this exact body arrived before. Clean messages are emailed and marked `delivered`; the rest are kept as `spam` for triage. The failure story survives async delivery. A send failure marks the row `failed` *before* rethrowing — the job runner gives each task an isolated transactionID, so that write commits and the row is visible immediately, while the throw still earns a retry that re-attempts the send. Access is deliberately tighter than event-submissions: `user-messages` is in RESTRICTED_COLLECTIONS and granted by NO manager role, so reading one takes the admin bypass. `sahaj-atlas-client` holds create only. Two things are duplicated on purpose, both noted in the code: this job owns its copy of `hasMxRecords` (the two intakes stay independent, and the verdict *wording* was never shareable), and `screening.ts` writes its own notes rather than reusing the event-submission ones. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Persisting messages was accepted on the understanding that they do not accumulate, so the retention policy ships with the intake rather than being deferred. Delivered messages are deleted after 7 days — short enough to nearly keep #602's "nothing is stored" promise, long enough that the two 24-hour screening windows still have history to count against. That lower bound is the load-bearing part: shorten it past the window and the repeat-sender and duplicate-body checks would silently pass everything. Spam is kept 90 days, because a sender's history is what makes a pattern visible, and `failed` is never swept — it is the one state where deleting the row destroys the only record that a message went undelivered. Runs at 04:00 UTC on the existing `nightly` queue, after the 02:00/03:00 sweeps. Note that `monthly` has no autoRun entry, so a task scheduled there would never fire. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…take
BREAKING CHANGE: `POST /api/contact-admin` is gone. Clients create through
`POST /api/user-messages` instead. Three things move on the wire:
- the Turnstile token goes in the `x-turnstile-token` HEADER, not the body
(the write-guard reads it there — it is transport metadata, not document
data);
- the response is Payload's `{ doc, message }` at 201, not `{ ok: true }`;
- the machine code moves from `errors[].code` to `errors[].data.code`,
which is where Payload's `formatErrors` puts an APIError's `data`.
Safe to cut over in one step: the Atlas widget is still pre-release and no
third-party host embeds it yet. SahajAtlasWeb needs the matching change.
Deletes with it: the `ContactAdmin*` types in `endpoints/responseTypes.ts`,
the hand-authored OpenAPI path + schemas, and `antiSpamErrorResponse` —
whose only production consumer was that handler. `parseBody`, `checkNoUrls`
and `verifyTurnstileOrFail` all have other consumers and stay.
`atlas/seo` is now the ONLY root endpoint, so every doc that used
contact-admin as the canonical example is re-pointed. `.claude/rules/
endpoints.md` keeps the story rather than erasing it: "stored nowhere and
owned by nothing" was true only because the endpoint chose not to store
anything, and that is the trap — ask whether a resource is genuinely
ownerless or merely unpersisted before reaching for the root.
`responseTypes.ts` stays put despite now serving one endpoint; client repos
sync it by a stable raw GitHub URL.
Refs #632
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Its consumers are now the write-guard plugin and the two screening jobs — not a single endpoint, since `contactAdmin` became a collection. Leaving it under `endpoints/` would have made the folder name a lie for the next reader. `requireActiveClient` / `parseBody` / `parseQuery` stay: those are still genuinely endpoint helpers. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Generated by `db:migrations:create`, unedited. Validated: - `up` is purely additive — 0 DROP statements. The two the validator flags are both in `down`, reversing the new table, which is correct. - The task-slug enums gain their values via `ADD VALUE ... BEFORE`, not the drop-and-recreate that a value *rename* would have produced. - `client_id` / `user_id` are `ON DELETE set null`: deleting a client or a registrant must not destroy the message they relayed or sent. - Indexes land on `sender_email` and `body_hash` — the two columns the screening job's history counts look up by. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three integration lanes plus a unit lane. Three of the assertions were checked by breaking the thing they guard, because each could otherwise pass vacuously: - the field-access tests forge `screeningResult` and `deliveredAt`, not `status` — status is defended twice (field access AND the prepare hook overwrites it), so it cannot isolate the guard. Removing `systemFieldAccess` makes both fail; with it, both stick as stripped. - the intake spec runs `overrideAccess: false` with a real published client. The override the sibling event-submissions spec uses skips field access entirely, so a spec using it could not tell a stripped field from an accepted one. - the retention/window invariant (delivered retention must outlive the screening window, or the history checks count against deleted rows and silently pass everything) fails when the constant is lowered. Two findings recorded rather than papered over: - The screening spec's fixtures originally shared one message body and seven cases failed on the duplicate-body check. That was the check working; `seed()` now varies the body unless a case names one. - `ALLOW_POST_FOR` turns out to be necessary but NOT sufficient: tier 2 hides any path whose collection is in no project, so both public intakes' POSTs are `x-internal`. The test asserts the real behaviour for both, and `.claude/rules/openapi.md` now says what would actually change it. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The status banner is registered as a field `components.Field`, which the admin import map has to resolve at runtime. Generated, not hand-edited. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three cleanups, no behaviour change: - `screen()` returned its verdict from five places, three of which hand-carried the diagnostic via a repeated spread and two of which correctly omitted it — a shape a reader has to verify rather than read. One `settle()` exit now carries it wherever it has been set. - `screen()` took `messageId` alongside the `message` it came from. - `context`'s validator was inline while `message`'s was extracted; both are named functions now. Reuse angle found nothing to reuse: no shared hash or name-from-email helper exists, and `hasMxRecords`'s duplication is the recorded decision. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`isScreeningResult` asserted `value is UserMessageScreeningResult` while checking only that `verdict` was a string — an assertion wider than its check, which the compiler then propagates. The review that raised this described the wrong failure (notes filled with `undefined` via `messageVerdictNote`); that cannot happen, because the note is only ever composed from a freshly computed verdict, never from the restored one. The real consequence is worse and is now pinned by a test: a `failed` row whose stored verdict is unrecognisable was TRUSTED, so screening was skipped and a disposable-address message got delivered. Loosening the guard makes that test fail with `expected 'delivered' to be 'spam'`. `MESSAGE_VERDICTS` is now a runtime list with the type derived from it — the same shape as `USER_MESSAGE_STATUSES` — because a value read back out of a JSON column needs something to check against. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Found by the security pass, as a parity gap rather than a vulnerability. The endpoint this collection replaces bounded `email` at 254 via Zod, and its OpenAPI schema published that. Payload's `email` field has **no** `maxLength` option — the option is absent from `EmailField`, present only on text-shaped fields — so moving the intake onto a collection dropped the bound silently, leaving an unbounded string on a public write path. Restored as a validator composing Payload's own `email` check, the same shape `message` already uses. Tested in both directions so it cannot pass by rejecting everything. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Docs-sync sweep of the branch diff turned up three stale spots and one that was misleading before this branch: - DEPLOYMENT.md quoted a log line operators grep for, `contactAdmin: Turnstile verification could not be completed`, which no longer exists — the guard logs under `antiSpamGuard:` now. Both it and .env.example also described the secret as belonging to one endpoint; it covers the whole public write surface, via a header. - `.claude/rules/access.md` said a collection in no project is reachable only by explicit-permission users. That is the opposite of what step 5 of its own permission flow says: no project means SHARED, i.e. implicitly readable by every role. `RESTRICTED_COLLECTIONS` exists precisely because of that, and the section never mentioned it — which is a trap for anyone adding a collection that holds personal data. Rewritten with the two knobs and how they compose. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-653 environment in sahajcloud
|
PR #651 adds `/api/atlas/sitemap` as another root endpoint, so wording that asserted "exactly one" / "the only root endpoint" would have been false the moment either PR merged, whichever went first — and would have collided textually in the same paragraphs. The durable point was never the count: it is that "unpersisted" is not "ownerless", which is what #632 demonstrated by deleting an endpoint whose only claim to being ownerless was that it chose not to store anything. That survives any number of siblings. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…address" Removed at the user's request. The bound was raised by the security pass as a parity gap rather than a vulnerability — an over-long address is a storage concern, not an exploitable one — and Payload's `email` field still rejects anything that isn't a well-formed address. This reverts d8f5a2b, including its test. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
#651 landed `/api/atlas/sitemap` as a third root endpoint while this branch was deleting `contactAdmin`, so both touched the same paragraphs of four docs plus `payload.config.ts` and `responseTypes.ts`. Resolved by taking both sides everywhere: the root-endpoint list keeps `atlas/seo` and `atlas/sitemap` and drops `contact-admin`, and the note about *why* it was dropped ("unpersisted is not ownerless") is kept, now phrased against a third rather than a second endpoint. `responseTypes.ts` is shared by both survivors again, which is its original justification. Verified after resolution: lint, both typechecks, 1497 unit, and 92 integration across this branch's specs plus #651's new sitemap suite. Refs #632 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Cost ~30 minutes of this session. `main` moved under this branch (#651), the PR went CONFLICTING, and GitHub silently stopped scheduling runs — a `pull_request` workflow runs against the merge commit, and a conflicted PR has none. Nothing surfaces that: `gh pr checks` showed only Railway (which kept deploying, since it builds the branch head, not the merge), `gh run list --branch` was empty, and no job appeared failed. It reads exactly like a stuck scheduler, so the instinct is to wait, or to close/reopen the PR — neither of which touches the cause. Documents the one-command diagnostic (`gh pr view <n> --json mergeable,mergeStateStatus`) in AGENTS.md, and puts it as a precondition in the finalize pipeline's CI-watch step, which is where the workflow actually meets it. Two traps recorded with it: a green run can be STALE (it predates `main` moving, so a conflicted PR looks tested — check the run's `head_sha`), and docs conflict far more readily than code, because sibling feature PRs edit the same paragraph of the same rules file even when they share no functions. Hence the advice to write shared rule docs as a criterion rather than a count. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ardnived
left a comment
There was a problem hiding this comment.
@sydevs-bot Please review the comments in this review and respond accordingly. Fix issues and pushback as needed. There are a lot of review comments here that center around the effective use of typescript, removing unnecessary indirection, and improving hygiene for custom admin components. You should also analyze all other admin components along these lines and propose another ticket to resolve those inconsistencies and inefficiencies.
| } | ||
| return true | ||
| } | ||
|
|
There was a problem hiding this comment.
Can we just use minLength as well as maxLength instead of adding a custom validator?
There was a problem hiding this comment.
Yes — minLength exists on textarea and I should have used it. It's in the field's config table alongside maxLength, both "used by the default validation function".
One thing it loses, for you to weigh: the built-in measures value.length, the custom validator measures value.trim().length. So minLength: 10 accepts ten spaces, which the current code rejects. On a public intake that's exactly the junk worth refusing — but the write-guard's URL/email checks and the async screening both sit behind this, so it isn't the only line.
My recommendation: take minLength: MESSAGE_MIN and drop the validator. It deletes a composed-validator hazard (see the context thread — a custom validate replaces the built-in and it's easy to lose maxLength that way), and the whitespace case is worth less than the simplification. If you want the trim kept, it stays a composed validator and minLength goes in for the message only.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Go ahead with your recommendation, but also get rid of MESSAGE_MIN and just write the minimum inline
There was a problem hiding this comment.
Done deal — minLength: 10 inline, validateMessage and MESSAGE_MIN both deleted. Checked the ripple: nothing outside this file referenced MESSAGE_MIN, and no test pins the custom "Tell us a little more…" copy, so Payload's default message takes over with nothing to update.
Two things that fall out, neither needing a decision from you:
- The
TextareaFieldValidationtype import andtextarea as validateTextareafrompayload/sharedboth lose their last use and go too. maxLength: MESSAGE_MAXkeeps working — it was only ever at risk because a customvalidatereplaced the default that enforces it. Deleting the validator removes that hazard rather than creating one.
MESSAGE_MAX is now the same shape as MESSAGE_MIN was — a file-local constant with exactly one use, at line 143. Your reasoning applies to it identically; I've left it alone because you named only the one. Say if you want maxLength: 5000 inline too and it goes in the same edit.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Yes, put MESSAGE_MAX inline as well
There was a problem hiding this comment.
Does this need a separate file? I think PayloadCMS might already provide us with a type if we set jsonSchema for the context field. Investigate that
There was a problem hiding this comment.
Investigated — you're right, and the file can go. Setting jsonSchema on context generates UserMessage['context'] in payload-types.ts, so this is a second hand-maintained source of truth for a column Payload will describe itself.
Three consumers import it — jobs/ScreenUserMessages, emails/UserMessageEmail, lib/notifications/sendUserMessage — so the move is: put the five keys in the schema, delete types.ts, repoint those three at the generated type.
The one thing worth preserving is the per-key JSDoc — "Route the sender was on", "Absolute URL of the host page" — which is what makes the type readable at those three call sites. JSON Schema description should carry through as JSDoc in the generated file, since Payload generates via json-schema-to-typescript. I could not verify that here (no node_modules), so it's the thing to check by eye after pnpm generate:types: if the descriptions don't survive, this trades documentation for deduplication and is worth reconsidering.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Go ahead and implement this
| const BANNER_TYPE: Record<Severity, 'default' | 'error' | 'success'> = { | ||
| info: 'default', | ||
| error: 'error', | ||
| success: 'success', | ||
| } |
There was a problem hiding this comment.
Instead of having our own Severity type and them mapping it to the Banner's type, couldn't we just use Banner['type'] in COPY?
There was a problem hiding this comment.
Yes — Severity and BANNER_TYPE both go. Key COPY and ICONS on Banner's own type and the mapping table disappears:
const COPY: Record<MessageStatus, { type: BannerProps['type']; message?: string }> = {
screening: { type: 'default', message: '…' },
delivered: { type: 'success', message: '…' },
spam: { type: 'error' },
failed: { type: 'error', message: '…' },
}The only thing lost is the word info reading better than default for the screening state, which isn't worth a type and a lookup table.
One knock-on: the user-message-status--${severity} class name currently interpolates the severity. Nothing in styles.css uses those modifier classes — only the base .user-message-status — so that interpolation can go at the same time rather than quietly becoming --default.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Go ahead and implement this
| /** | ||
| * The stored value is JSON, so it can be anything a bad write left behind — | ||
| * render only real strings rather than trusting the column's declared type. A | ||
| * malformed row degrades to no notes instead of throwing the edit view. | ||
| */ | ||
| function notesOf(result: UserMessageScreeningResult | null | undefined): string[] { | ||
| const notes = result?.notes | ||
| return Array.isArray(notes) | ||
| ? notes.filter((note): note is string => typeof note === 'string') | ||
| : [] | ||
| } |
There was a problem hiding this comment.
Is this really necessary if we enforce a jsonSchema on the field?
There was a problem hiding this comment.
Largely, yes — drop it to result?.notes ?? [].
With additionalProperties: false and notes: { type: 'array', items: { type: 'string' } } enforced on write, the only writer is ScreenUserMessages and it can no longer store a malformed value. This is a new collection with no existing rows, so there's no legacy data the schema didn't gate — which is the case that would normally justify keeping a runtime filter.
The honest caveat, so it's a decision rather than an oversight: a schema binds Payload writes, not the database. A migration or hand-run SQL could still put anything in the column, and this renders in the edit view, where a throw takes the whole document page down rather than one banner.
I'd still drop it. That residual risk applies to every field in the admin and we don't defend any of the others this way, so singling out this one is inconsistent rather than careful. ?? [] keeps the null case, which is real — a message that hasn't been screened yet.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Go ahead and implement this
|
|
||
| return ( | ||
| <div className="field-type json read-only"> | ||
| <FieldLabel label={label} path={name} /> |
There was a problem hiding this comment.
Instead of redeclaring the <FieldLabel> within this custom component, we should only override the Input component instead of the entire Field component
There was a problem hiding this comment.
Same answer as the collection-config thread: Input isn't one of the slots (Field, Cell, Filter, Label, Error, Diff, Description, beforeInput, afterInput), and Field is the only one that replaces the control.
On this file specifically: the <div className="field-type json read-only"> + FieldLabel here isn't incidental scaffolding — it's what makes the field align with every other field on the page, take the read-only treatment, and give the banner an accessible label. Removing it wouldn't yield a narrower component, it would yield an unlabelled banner floating outside the field grid.
Not adopting. If Payload adds a narrower slot, this and the 19 other components doing the same thing move together — #659 records it.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
|
You're right about the JSON fields, and I can't push the fix to this branch. Per-thread answers below; this is the summary and the one blocker. Adopted (8): the whole Pushed back (4), with evidence: the two "override The blocker: this branch is Follow-up ticket you asked for: #659. Its useful content turned out to be which of your four themes generalise — two do, two don't, and the numbers are in there. The finding that settles most of the review — and a gotcha that would silently undo it
Two comments in the tree say the opposite, and they are stale. ⚠ The gotcha: supplying One thing I could not verify from here and would check while implementing: that 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
⚠ This PR is conflicted, so no CI can run on it — and the green check above is stale. Found on a subscription wake, separate from the review replies. The irony is worth a second: the conflicting file is the commit that documents this exact trap. The fix, and why I'm not doing it: resolution is to accept ⚠ Don't let the 13 lines go with the file. They're real guidance and the plugin's copy ( Evidence — including the one claim in your PR body I checked and can confirm
Two commits landed on Your "CI: green on 58d6609" claim is accurate — I checked rather than assuming, since it looked like a candidate for the stale-run trap. It is nonetheless stale in the sense that matters: it predates both commits above, and no new Actions run can be scheduled while the merge commit is uncomputable. The only signal on the PR now is the Railway status from 2026-08-28T01:08Z, which stays green because Railway builds the branch head rather than the merge — exactly the asymmetry
🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Resolves one delete/modify conflict on .claude/skills/finalize-pr/SKILL.md: main deleted it in #656 when the workflow skills moved to the sydevs/claude-workflow plugin, while this branch had edited it. Taking main's deletion. The edit itself was worth keeping and is not lost — it documents that a conflicted PR schedules zero workflow runs, silently, so `gh run list` reads as a stuck scheduler rather than a blocked merge. That has been ported to the plugin's copy of finalize-pr, which is now the only copy. Co-Authored-By: Claude Opus 5 <[email protected]>
The smoke lane's `ensureAdmin` bootstraps a preview by logging in and, on failure, calling Payload's `first-register`. Payload returns Forbidden from `first-register` as soon as the auth collection holds any document, so once a preview has been seeded the only 403 it can produce means "an admin already exists that PREVIEW_ADMIN_PASSWORD does not open" — the opposite of what the raw error reads like. That is the state this PR's preview is in. Its Postgres has been up since 2026-08-26T22:47Z and the first smoke run seeded [email protected] with the password that was still hardcoded in this file; #656 then moved the credential to the PREVIEW_ADMIN_PASSWORD secret (created 2026-08-27T17:35Z), and a preview's volume outlives its deploys, so the seeded admin kept the old value. Login fails on the new secret, first-register is Forbidden, and all five auth-dependent smoke specs die on a Payload stack that says only "You are not allowed to perform this action". #656's own CI could not catch this: the preview-URL discovery step found no preview on #656, #657 or #658, so the smoke lane skipped there and this branch is the only place the change has ever run. Report the real cause and the remedy, drop the getter's stale pointer at the Railway service variables (nothing server-side reads that name), and record in AGENTS.md that the secret is stable per preview rather than rotatable on its own. This does not turn the lane green — the preview database still has to be reset so it can be seeded again — but it stops the failure from reading as a registration bug. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
All six of those are already implemented — they're sitting in #660, waiting on you. I opened it on 29 Aug against this branch, because I can only push to Verified just now against
⚠ One of them is not what you approved, and it's the first oneYou said "go ahead with your recommendation" on the A typed So the per-unknown-key size bound is gone. What remains is That reverses the exposure I raised on the thread and you accepted on that basis, so it's yours to re-decide rather than mine to quietly settle. Three ways to get a bound back, if you want one:
My preference is to leave it open as shipped and take the unbounded-unknown-key risk, since Nothing is blocked on me here. #660 is green on its own gate (lint, typecheck, typecheck:tests, 1497 unit) and 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
…nd types (#660) Applies the review on #653. The JSON fields now carry a `jsonSchema`, which Payload compiles to a write-time validator AND generates the field's type from — so `types.ts`'s `UserMessageContext` and `screening.ts`'s `UserMessageScreeningResult` are gone rather than kept in agreement by eye. - `context`: open schema (unknown keys still pass, per the intake contract); `validateContext` and its serialized-length cap deleted. - `screeningResult`: closed schema, `verdict` enum derived from MESSAGE_VERDICTS so the runtime list and stored contract cannot drift. - `message`: built-in `minLength`/`maxLength` replace the composed validator; both bounds inline. - `messageVerdictNote` becomes the `MESSAGE_VERDICT_NOTES` record. - `UserMessageStatus`: `Severity`/`BANNER_TYPE` collapse into `Banner`'s own type; the defensive `notesOf` filter goes, the schema having closed the hole. - `normalizedBodyHash` folds into its one consumer, `prepareUserMessage`. Per-key documentation survives as JSON Schema `description`, which Payload renders into the generated type's JSDoc. Claude-Session: https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC Co-authored-by: Claude <[email protected]>
) Rewrites every in-scope prose file (67 of 69 flagged by the audit) into strict Simplified Technical English and retires D1/Cloudflare Workers-era debris three months after the Postgres/Railway migration. Tracked *.md (excluding CLAUDE.md symlinks and the vendored .agents/skills/payload/ skill, left untouched pending ownership confirmation) drops from 770,090 to 600,797 chars (22%). The five hot-path files auto-imported every session (AGENTS.md, docs/architecture.md, docs/environment.md, docs/code-style.md, .claude/workflow.json) drop from 84,492 to 36,397 chars (57%). Deleted (dead, zero referrers, grepped clean): seed-issues-report.md, src/migrations/README.md (its one fact folded into src/migrations/AGENTS.md). Merged: DEPLOYMENT.md + RAILWAY_RUNBOOK.md split by lifecycle (how it runs today vs. provision-from-scratch/disaster-recovery), resolving their D1-decommission contradiction — PR #468 (merged 2026-06-08) confirms the Worker is gone, so the stale "Remaining (gated)" TODOs are removed, not reworded. Legacy debris fixed (D1/SQLite/Cloudflare-Workers-as-current retired): migration-reviewer.md's whole persona rewritten for Postgres/Drizzle, seeds/wemeditate/AGENTS.md's Dual-Database table corrected to Postgres, src/globals/AGENTS.md's json_array() rationale corrected to Postgres's real FUNC_MAX_ARGS=100 limit, docs/mcp-setup.md's cloudflare-docs row drops Workers/D1. grep for D1|SQLite|Cloudflare Workers across .claude/agents/, seeds/wemeditate/, src/globals/, docs/mcp-setup.md is clean. README.md's stale `cd sy-devs-cms` corrected to `cd SahajCloud`. Mandatory AGENTS.md fixes applied: dropped the nonexistent `pnpm test:e2e`, replaced the broken dev-server.sh path with the `/workflow:dev-server` skill, fixed the seeds/atlas/MIGRATION_PLAN.md:103 anchor (now resolves to `AGENTS.md#website-selection-rules-584`), collapsed duplicate PR-workflow/test-tier prose into single pointers to testing-reqs.md and the finalize-pr skill. Traps preserved (compressed, never deleted): the conflicted-PR "zero CI" diagnostic with its docs/why.md anchor and #632/#653 numbers; the Cache Rule authorization-header predicate and root-endpoint fix; DB_QUERY_LOGGING and TURNSTILE_SECRET_KEY footguns; storage.md's preview/prod asset-isolation risk; the payload-cli silent-exit/hang ladder; the migration snapshot out-of-order duplicate-re-emission trap; access.md's per-locale-roles gotcha (#665); endpoints.md's root-endpoint hook gap; email.md's two- token-URL-shapes bug; seeds/atlas/AGENTS.md's silent-rollback-on-trashed- relation trap; the never-name-a-global-field-locales rule. The 2026-08-27 dated Admin Access exception is kept (still current). Comment sweep: rewrote comments to STE in every file the audit flagged as touched (route.ts's mandatory dead-comment deletions, r2NativeAdapter.ts, Icon.tsx, scalarPlugin.ts, env/server.ts, localizedRolesAuth.ts, plus the full tests/seeds/scripts/.claude/root-config/.github sweep — 227 files total). Verified comment-only: every changed line in every .ts/.tsx/.mjs/ .cjs/.sh/.py file has an identical code portion before its comment marker; zero functional changes. Deleted a dead `sharp` import and several doc- duplicating/obvious comments (e.g. vitest.setup.ts's two narrate-the- obvious lines). Verification run as finisher: pnpm lint, typecheck, typecheck:tests, and the full unit lane (1564 tests) all pass, plus targeted integration specs for every touched collection/access path (events, regions, role-based- access — 79 tests, live Postgres). ste-lint.py run on all 40 changed .md files: hard violations cut from 169 to 118, concentrated in five already- dense reference docs (admin-ui/api-clients/email/endpoints/openapi/ storage.md) where the prior compression pass already prioritized fidelity over the linter's raw sentence-length cap; remaining flags are verified domain terms (Railway's "Health Check", Zod's "Validate", literal HTTP methods GET/DELETE, SQL "cascade delete", TS "type erasure") or residue in those five files. rule-delta.mjs vs main on AGENTS.md/docs/rules/*.md/ migration-reviewer.md: 3 directives flagged REMOVED, all three verified as de-bolded (not deleted) — "GET /api/events/geojson always excluded, no opt-out" (api-clients.md) and the two CPU parallel-test-run rules (testing-reqs.md) all still present as plain bullets/cells, content identical. 1 flagged ADDED is the same pass-by-reference comment rule gaining full-sentence bold (previously invisible to the tool since only "Do not" was bold). Sequencing: PRs #692 (UNKNOWN), #686 (BLOCKED, not CONFLICTING), #691 (CLEAN) show no current CONFLICTING/DIRTY state, so this PR is not blocked today, though #692/#691 touch overlapping files and should land or be watched. securityReview trigger paths (access/, storage/, api routes, webhook scripts) all confirmed comment-only. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…nd types Applies the review on #653. The JSON fields now carry a `jsonSchema`, which Payload compiles to a write-time validator AND generates the field's type from — so `types.ts`'s `UserMessageContext` and `screening.ts`'s `UserMessageScreeningResult` are gone rather than kept in agreement by eye. - `context`: open schema (unknown keys still pass, per the intake contract); `validateContext` and its serialized-length cap deleted. - `screeningResult`: closed schema, `verdict` enum derived from MESSAGE_VERDICTS so the runtime list and stored contract cannot drift. - `message`: built-in `minLength`/`maxLength` replace the composed validator; both bounds inline. - `messageVerdictNote` becomes the `MESSAGE_VERDICT_NOTES` record. - `UserMessageStatus`: `Severity`/`BANNER_TYPE` collapse into `Banner`'s own type; the defensive `notesOf` filter goes, the schema having closed the hole. - `normalizedBodyHash` folds into its one consumer, `prepareUserMessage`. Per-key documentation survives as JSON Schema `description`, which Payload renders into the generated type's JSDoc. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC
…nd types (#660) Applies the review on #653. The JSON fields now carry a `jsonSchema`, which Payload compiles to a write-time validator AND generates the field's type from — so `types.ts`'s `UserMessageContext` and `screening.ts`'s `UserMessageScreeningResult` are gone rather than kept in agreement by eye. - `context`: open schema (unknown keys still pass, per the intake contract); `validateContext` and its serialized-length cap deleted. - `screeningResult`: closed schema, `verdict` enum derived from MESSAGE_VERDICTS so the runtime list and stored contract cannot drift. - `message`: built-in `minLength`/`maxLength` replace the composed validator; both bounds inline. - `messageVerdictNote` becomes the `MESSAGE_VERDICT_NOTES` record. - `UserMessageStatus`: `Severity`/`BANNER_TYPE` collapse into `Banner`'s own type; the defensive `notesOf` filter goes, the schema having closed the hole. - `normalizedBodyHash` folds into its one consumer, `prepareUserMessage`. Per-key documentation survives as JSON Schema `description`, which Payload renders into the generated type's JSDoc. Claude-Session: https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC Co-authored-by: Claude <[email protected]>
Summary
POST /api/contact-adminbecomes theuser-messagescollection: accept fast, screen deeply in a job.failednever.Breaking change
POST /api/contact-adminis deleted. Clients create throughPOST /api/user-messages. Three things move on the wire, so SahajAtlasWeb needs the matching change alongside this merge:x-turnstile-tokenheader200 { ok: true }201 { doc, message }errors[].codeerrors[].data.codeAlso:
emailbecomessenderEmail. Safe to cut over in one step — the Atlas widget is pre-release and no third-party host embeds it yet.Tracked client-side by sydevs/SahajAtlasWeb#171, which must land alongside this. Note the trap recorded there:
asRefusalis shared with the registration mutation, andPOST /api/events/{id}/registerstill emitserrors[].codeat the top level — so the client has to accept both positions, not switch.Changes
src/collections/UserMessages/— the collection, its status/verdict vocabulary, and the create hooks.src/jobs/ScreenUserMessages/— MX + disposable re-check, the two history counts, delivery.src/jobs/PurgeUserMessages/— the nightly retention sweep (04:00 UTC,nightlyqueue).src/plugins/access/config/—RESTRICTED_COLLECTIONS+ a create-only grant forsahaj-atlas-client.src/plugins/writeGuard/policies.ts— the anti-spam policy that replaces the endpoint's hand-rolled gate.Migration
src/migrations/20260826_214829_add_user_messages.tsuser_messagestable + status enum; adds two task-slug enum values viaADD VALUE, not a drop-and-recreate.upcontains zero destructive statements.downdrops the new table and column, which is the correct reversal.Decisions worth reviewing
event-submissions.user-messagesis granted by no manager role — reading one takes the admin bypass. That is deliberate: these are unscreened messages from strangers about anything at all.spamscanneris BUSL-1.1; the small alternatives are abandonware;bayes/naturalneed a corpus we don't have;obscenitydetects profanity, which would flag an angry-but-genuine bug report. Duplicate-body hashing replaces it — exact, no tuning.hasMxRecordsis duplicated on purpose (~38 lines) so the two intakes stay independent; the verdict wording was never shareable. Cost stated in the file: an MX bug needs fixing twice.senderEmail. Payload'semailfield has nomaxLengthoption, so the 254-char cap the old endpoint enforced is not carried over. Raised by the security pass and removed at the maintainer's request — an over-long but well-formed address is a storage concern, not an exploitable one.Two things found while shipping
ALLOW_POST_FORis necessary but not sufficient. Tier 2 offilterSpechides any path whose collection is in no project, so both public intakes' POSTs arex-internal—event-submissionshas been in that state since feat(events): public event submissions, screening pipeline & write-guard plugin #625. Asserted for both, and.claude/rules/openapi.mdnow says what would actually change it..claude/rules/access.mdwas misleading. It said a collection in no project is reachable only by explicit-permission users; step 5 of its own permission flow says the opposite (no project ⇒ shared).RESTRICTED_COLLECTIONSexists because of that and went unmentioned. Rewritten.Behaviour change to note
The 500 for an unavailable captcha now carries
code: "captcha_unavailable". The deleted endpoint deliberately suppressed it ("a public caller must not learn whether the secret is unset or Cloudflare is down"). The shared write-guard has always exposed it forevent-submissions, so this aligns the two rather than adding a special case — flagging it because #602 called that suppression a pinned contract.Test Results
origin/mainsrc/+ tests): ✓DROPs are indown, verified58d6609d(bothLint, Test & Smokeand the Railway preview)origin/mainis merged in — #651 landed/api/atlas/sitemapmid-flight and conflicted with this branch across four rule docs pluspayload.config.ts. Worth knowing: a conflicted PR runs no CI at all, silently, because there is no merge commit to run against. That's now documented inAGENTS.mdwith the one-command diagnostic.Three assertions were checked by breaking the thing they guard, since each could otherwise pass vacuously: removing
systemFieldAccessmakes the forged-field tests fail; lowering the retention constant fails the window invariant; loosening the verdict guard delivers a message that should be spam.Manual verification
POST /api/user-messageswith a client key +x-turnstile-token→ 201, row appears under User Messages as Checking with the right Client.screeningqueue → flips to Delivered, email captured by Ethereal.mailinator.comsender → Marked Spam; post the same body twice → duplicate verdict.Closes #632
🤖 Generated with Claude Code