Repository navigation
feat(events): bulk-import events into a region from CSV - #874
sydevs-bot wants to merge 67 commits into
Conversation
Phase 1 of the bulk event import (#828): the pure domain core every later phase reads, with no schema and no endpoint yet. One column spec (`csv/columns.ts`) drives both the parser and the downloadable template, so a renamed column cannot ship a template the parser then refuses — the failure a hand-written template produced in the Atlas seed's own tooling. A spec asserts the generated template round-trips through the real parser. The parser checks structure only. It deliberately does not map the schedule or the location: both need the row's timezone, which is unknown until the resolve step has geocoded it, so validating here on an assumed zone would put a row's whole recurrence hours out and surface as a wrong time rather than a refusal. Two decisions worth the review: - An unrecognised header is a whole-file refusal, not an ignored column. A misspelled `titel` would otherwise drop every title silently. - Blank lines are kept through the parse and skipped afterwards. `skipEmptyLines` drops them before the line counter sees them, so every row after one reported a number lower than the volunteer's spreadsheet shows. The spec that caught this failed first. The schedule mapper accumulates errors rather than short-circuiting, so one re-upload fixes every mistake, and refuses a monthly row that asks for both `monthWeek` and a bare `date` — "the 2nd Tuesday" and "day 14" are different recurrences, and guessing silently reschedules the class. Thresholds live in one `constants.ts` so a reviewer can weigh them as a set. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Y6K3wzJCEpBjd2P1fMbdFD
The MO-SU weekday table existed in three places and the HH:MM pattern in four. The weekday one is the dangerous copy: its ORDER is the `enum_events_schedule_weekdays` Postgres enum, and two callers read a code back out of it by position (`indexOf(code) + 1` is a Temporal `dayOfWeek`). Reorder one copy and schedules land on the wrong day, with no type error and no refused write. `src/lib/schedule/weekdays.ts` now owns the table plus `isWeekdayCode`, `isWeekNumber` and the two directions of the index mapping. The Atlas seed mapper reads it instead of its own copy, which is what makes it shared rather than a third declaration. `src/lib/schedule/time.ts` owns the HH:MM pattern and the local-wall-time to instant conversion. `scheduleFields`' endTime validator reads the pattern from there, because the bulk import (#828) writes through that field: two independent regexes meant a CSV row could be accepted by the import and then refused at write, which is the one failure the import's error accumulation exists to prevent. Behaviour-preserving. `tests/unit/atlas-schedule-mapper.spec.ts` covers the rewired seed mapper and is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Y6K3wzJCEpBjd2P1fMbdFD
Findings from the four-lens quality pass, each verified against the source before acting: - `ordinalWeekdayInMonth` scanned every day of the month to index one, and carried three branches no input could reach: every month holds four of every weekday, so neither null path could fire, which in turn forced an unreachable fallback in its caller. Replaced with the direct arithmetic and made total. Cross-checked against the scan over 2024-2036 — 5460 cases, no disagreement, and the scan never came up empty. - The three `build*` helpers took an `errors` array as an in-out parameter while each produced exactly one message. They return the message now, so no reader has to verify by hand that "returned nothing" means "pushed something". - The `untilDate`-before-`date` check returned its own single-error array, silently opting out of the module's stated error accumulation. It now accumulates with the rest, so a row with a backwards range and a bad weekday reports both. - `parse.ts` walked the records twice, once to count and once to build. One pass, with the line counter unchanged. - `checkHeader` re-derived the always-required set through a null-check that could not fire; it reads `requiredColumnsFor(undefined)` instead. - `EVENT_TYPES` restated a generated union. `satisfies readonly Event['eventType'][]` makes drift a compile error. Kept local rather than importing `EVENT_TYPE_OPTIONS` from the Events folder, which would be the cross-owner internal import `src/AGENTS.md` rule 4 prohibits. - Dropped the six thresholds no code reads yet. They described the resolve and proposal steps, so nothing could check them and nothing would go red if a value were wrong — and one claimed to mirror a seed constant that does not exist (`venueRouter.ts` has a bare literal). Each lands with the step that reads it. - Unexported the derived `WeekdayCode` alias, per `src/types/AGENTS.md`. - Recorded why there is no `daily` scheduleType: a daily class is all seven weekdays, and a fourth member would make a volunteer choose between two spellings of one thing. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Y6K3wzJCEpBjd2P1fMbdFD
From the correctness pass. Each was confirmed by running the real modules, and each new spec was watched failing with its guard neutered. - `untilDate` was only compared against an explicit `date`, so a weekly row leaving `date` blank could name an ending before its derived first date: `weekdays=MO, untilDate=2026-10-04` on 2026-10-01 imported an event with zero occurrences, already expired, with nothing on the row to say so. It compares against the resolved first date now. - An explicit `date` became `firstDate` with no check that it matched the recurrence stored beside it. `date=2026-10-06` (a Tuesday) with `weekdays=MO` published a first occurrence on a day the class never runs. Both the weekly and the monthly-ordinal arms now refuse the contradiction. - A wall time inside a spring-forward gap was shifted an hour silently, so `02:30`/`03:00` in Europe/Berlin on 2027-03-28 was accepted here and then refused by `scheduleFields`' own validator as "end before start" — exactly the accept-then-refuse divergence the shared helper exists to prevent. ⚠ `disambiguation: 'reject'` is NOT the check for this: it also refuses an AMBIGUOUS time, the hour a fall-back transition repeats, which genuinely exists. The first version of this fix did that and rejected a valid class one day a year; the ambiguous-time spec caught it. A gap is identified by the shift itself instead. - `scheduleType=weekly` with `monthWeek=2` dropped the `monthWeek` and published a weekly class where a 2nd-Tuesday monthly one was asked for. Columns a type does not read are reported rather than ignored; the monthly arm already refused the mirror-image mistake. - A row with more values than the header has columns was truncated by the positional read, so an unquoted comma in an address shifted every later value one column left and the volunteer was pointed at whichever column the shift happened to make invalid. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Y6K3wzJCEpBjd2P1fMbdFD
The schedule Key files list now names `weekdays.ts` and `time.ts`, each with the trap that put it there: the weekday array's order is the Postgres enum and is read back by position, and Temporal's `disambiguation: 'reject'` is not a gap check because it also refuses an ambiguous time. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Y6K3wzJCEpBjd2P1fMbdFD
|
🚅 Deployed to the SahajCloud-pr-874 environment in sahajcloud
1 service not affected by this PR
|
Where a batch lives between upload and commit: the target region, the
uploader, the status the endpoints drive, the batch default languages, and
`rows`, which holds `parseImportCsv`'s output verbatim.
The collection declares its own `access` block, which is the part worth
reading twice. `accessPlugin` composes `{ ...generated, ...collection.access }`,
so these four functions run INSTEAD of the role tables — and the `inactive`
→ deny step every other collection inherits from `bypassPermissions` does
not run at all. `access.ts` restates it for that reason, and the spec
reaches it with an inactive manager who is also the uploader, so removing
the check goes red.
`event-imports` is also named in `RESTRICTED_COLLECTIONS`. A collection in
no project reads as *shared*, so without the entry every published API key
— the Atlas widget's browser key included — would read every uploaded CSV
of contact names, phone numbers and addresses. The two layers are separate:
the access block refuses a client outright today, and the entry is what
survives if that block is ever narrowed. The spec asserts both, through
`hasPermission` for the entry, because the block alone would mask it.
That docblock predicted this: it said the list "fails open the day a fifth
is added". This is the fifth, and nothing but the comment asked for the
entry. Both it and `docs/rules/access.md` now say so rather than repeating
the prediction.
`rows` carries only the three keys the parser writes. The resolve and commit
steps widen it with their own — a geocode result, a duplicate match, the
event a row became — for the same reason `constants.ts` holds only phase
one's threshold: a key declared ahead of its writer generates a type a
consumer can read as available, and an Ajv rule nothing exercises.
⚠ The migration's `down` had one line removed by hand: drizzle emits a
`DROP CONSTRAINT` for a constraint the `DROP TABLE … CASCADE` above it has
already dropped, which aborts the batch rollback (#682).
`tests/unit/migration-down-cascade.spec.ts` is what refuses it, and
`src/migrations/AGENTS.md` sanctions exactly this edit — the migration
fails without it, and it is cleanup the cascade already handles.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BZSbxAJy8v1SzuquM1ggrV
A commit deletes its own batch, so what reaches this job is a discarded one and an abandoned one a manager trashed by hand. Seven days, on the existing `nightly` queue at 05:00 UTC — after the 02:00 expiry, the 03:00 notification sweeps and the 04:00 submissions purge, so no two retention jobs contend. ⚠ Payload empties no trash on any collection. `trash: true` buys the `deletedAt` column and the admin's trash view and nothing else, so without this job "discard" would mean the uploaded CSV merely leaves the list. `src/collections/AGENTS.md` now says that where the trash list is, since the gap belongs to the feature rather than to this job: Events are the deliberate exception, because a trashed listing is a manager's own record. ⚠ `trash: true` is passed on both the count and the delete, for two different reasons, and the spec pins each. The read needs it because Payload appends `deletedAt exists: false` to every query here, so the sweep would otherwise see none of the rows it exists to find. The delete needs it because a trashed row is not a legal target without it — `Not Found`, on an id the same query just returned. Every assertion in the spec was watched failing with its guard neutered, nine in all: the uploader `Where`, the inactive check, the restricted-list entry, the admin-only create, the retention window, both `trash` flags, `dryRun`, the closed row schema, and the locale base subtag. That last one is a real hazard rather than a formality. `pt-BR` and `en-AU` are admin locales and not ISO 639-1 languages, and `defaultLanguages` is what `Events.languages` takes for every row naming none of its own — so the default is the locale's base subtag, and a batch created at `pt-BR` gets `['pt']`. Known edge, not fixed here: both relationships are `NOT NULL` with drizzle's `ON DELETE set null`, so deleting a region with an open batch raises a foreign-key error rather than detaching it. Regions are admin-only to delete, and a refusal is the safer of the two answers. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BZSbxAJy8v1SzuquM1ggrV
Findings from the five-lens pass, each verified against the source before
acting.
**The access block now overrides two keys instead of four.** `create` and
`delete` were reimplementing what the generated config already decides: no
role names this slug, implicit read is off, and the document-manager
fallback covers read and update only — so both already answered "admins
only". Overriding a key also replaces the bypass behind it, so the shorter
the list the less there is to restate. `batchCreateAccess` is gone.
Dropping the `delete` override also takes a grant the ticket never asked
for. It says "read, update and trash", and trash is a write to `deletedAt`
— so the uploader kept hard delete by accident, and could empty the trash
the seven-day window exists to let them undo. It was also the one grant the
spec never exercised; now it is asserted.
**`index: true` on `uploader` was a no-op.** The drizzle adapter indexes
every single-relation column unconditionally
(`@payloadcms/drizzle/dist/schema/traverseFields.js`), and this branch's own
migration proves it: `targetRegion` sets no flag and still gets
`event_imports_target_region_idx`. The index is earned — every non-admin
read is a `Where` on that column — just not by the flag, and a comment
saying otherwise sends the next reader to the wrong file.
**The purge job did a `count` the real run never used.** `payload.delete`
returns the documents, so `docs.length` was already the answer; the count
now runs only for `dryRun`, which also removes the nesting that existed to
suppress a log for a case the outer condition had merged in. The delete
takes a `select` too: without one it hydrates every `rows` column it is
about to destroy — up to 500 rows of CSV per batch — and walks each through
the afterRead hooks, to produce one integer.
**`baseLanguage` is now one function in `@/lib/locales`.** The `pt-BR` → `pt`
derivation was written twice, and the second copy had a hole the first does
not: `req.locale` is request-supplied, `?locale=all` arrives as `'all'`, and
`'all'.split('-')[0]` is not a language any `getLanguageOptions()` field
accepts. The helper refuses anything that is not a configured locale, and a
spec walks all nineteen plus the non-locale cases.
**New guard: every collection in no project must be restricted.** The
docblock in `config/projects.ts` has said in prose that the list "fails open
the day a fifth is added" — and when `event-imports` became the fifth,
nothing but that comment asked for the entry. `tests/unit/restricted-collections.spec.ts`
is the gate it was describing. It sweeps the real collection list, so it
fails closed on the next one.
Docs: three statements this branch made stale. `docs/rules/access.md` said
every `access:` under `src/collections` is field-level — no longer true, and
it now carries the per-key rule and what overriding costs. `src/collections/AGENTS.md`
said collections never need a manual `access` config, and listed four of the
nine `trash: true` collections under a rule this branch made normative; five
of them are swept by nothing, which is a gap rather than a decision, and it
says so rather than reading as discharged.
Dismissed, with reasons:
- *Rename `uploader` → `manager` and delete the access block, letting the
document-manager fallback grant it.* Behaviourally close, and it would
delete the file. Rejected: it makes a field NAME load-bearing for access,
silently. This repo already made that call the other way — region-subtree
scoping is wired to an explicit slug allowlist rather than field
introspection, precisely so a stray `manager` field cannot widen access —
and an explicit block is more legible on a collection holding contact
details. The half of the finding that was right is applied above.
- *Role table plus a per-row `Where` in `createAccessConfig`.* Rejected:
manager roles are per-locale, so an `atlas-manager` holding the role in
English alone would be denied their own batch at `?locale=cs`. Batch
ownership is not locale-scoped.
- *Inline the access block into the collection file.* Rejected: a separate
module in the collection's own folder is this repo's colocation shape.
- *A shared `sweepRetention` helper, or a `TRASH_RETENTION` table for all
nine collections.* Rejected here: one consumer, and `src/AGENTS.md`
requires two. The gap is named in the trash list instead.
- *`addDays` from `@/lib/eventVerification/periods`.* Rejected: the
arithmetic is inline at seven sites and the helper is domain-namespaced.
- *comment-lint on "RFC 5545" / "RFC 4180".* Both stay.
`docs/rules/code-comments.md` names an RFC as an acceptable breadcrumb, so
this is a false positive of its section-number heuristic.
Not done, and worth a ticket somebody has to agree to: `isActiveManager`
exists as a predicate in three places now (`access.ts` here,
`systemEntities.ts`, `requireActiveManager.ts`) and is exported from none.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BZSbxAJy8v1SzuquM1ggrV
The bulk import creates an account for every `managerEmail` a CSV names (#828), so `atlas-manager` needs `managers: create`. That grant is only safe once two things are true, and neither was. `type` and `roles` were update-locked but not create-locked, so the grant as written would have let a region volunteer create an admin. Both now carry `create: adminOnlyFieldAccess`. A stripped `type` falls back to the field's `defaultValue`, which is `manager`; `roles` has no default, so it stays empty. `forceManagedTypeAndRoles` restates that for a write that skips access entirely. Field access is not evaluated under `overrideAccess: true`, which is how the commit step writes while acting as the uploader, so the hook is the only thing between a crafted CSV row and an admin account. A create with no user — a seed, a job — is left alone. The read half was already collection-wide (#821): a picker has to list other managers. It is now narrowed field by field to `name`, the one field a picker renders. `lockManagerFieldReads` applies `selfOrAdminFieldAccess` to everything the one-entry allowlist does not name, so a field added later is locked rather than leaked — `tests/unit/manager-field-locks.spec.ts` is what refuses the omission, and it sweeps the collection as `loginPlugin` leaves it, so the three fields that plugin injects are covered. `email` and `_verified` are declared bare at the top level to give the lock something to merge onto; `_verified` shipped `read: Boolean(user)` of its own, so every manager could read whether every other account had accepted its invitation. No schema change: `pnpm generate:types` leaves no diff. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XdA5L1eQBBwyrgp3wUdubm
`stripLockedFieldsOnSelfRead` fired whenever a caller read any row of its own auth collection, not just its own. That was harmless while `clients` locked two fields and `managers` locked none. Locking most of `managers` turns it into a live defect: an `afterRead` hook sees no `overrideAccess` flag, so an internal read of a *different* manager came back hollowed out. `syncVerificationOnSave` is the one that breaks. It reads the event manager's `notificationPreferences` with the acting manager's `req`, so an atlas-manager saving an event in their subtree lost that manager's cadence and `nextCheckAt` moved from 30 days to the 90-day default, with nothing to show it had. Narrowing to the caller's own row loses no coverage: every operation in the class this guard closes — `refresh`, `me`, `login`, `unlock`, `verifyEmail` — reads the authenticated row and nothing else. A sibling row read with `overrideAccess: false` is covered by field access itself. The int case asserts the 30-day window against the 90-day default, which is far enough apart that one window cannot satisfy both. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XdA5L1eQBBwyrgp3wUdubm
`_verified`, `magicLinkIssuedAt`, `pendingInvitation` and `invitationDueAt`
were all settable on create. The first marks an account accepted with no
address ever proven; a future stamp on the second makes the sign-in
throttle subtract to a negative delta, so that account is refused a link
until somebody edits the database — the field is hidden and unwritable.
All four are closed, the last three through one shared
`machineFieldAccess` block rather than three copies of the same triple.
Two framework claims this branch inherited are false against the
installed payload 3.90.2, and both drove a comment or a design. An
`afterRead` hook does receive `overrideAccess`, so
`stripLockedFieldsOnSelfRead` now stands down on a read that already
checked access. And `refreshOperation` runs its result through
`applyUserReadAccess({ overrideAccess: false })`, so #822's own path is
closed upstream and this guard is the net for whichever operation forgets
the flag next.
`forceManagedTypeAndRoles` is spelled against the admin rather than for
`managers`, so a grant to a second auth collection arrives rewritten
rather than exempt.
The field sweep enumerates with payload's own `flattenAllFields`. A sweep
that re-implements the traversal passes whenever the two agree, including
when both are wrong — and they disagree on a named tab, which is an entry
of its own to the framework and a container to the locker.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XdA5L1eQBBwyrgp3wUdubm
`docs/rules/access.md` said the `managers` restriction existed because every published key read every manager's name and email, and left the grant that replaced it unqualified. It now says what the grant returns, where the allowlist lives, and that `create` came with it. Two corrections in the same pass. The field-lock section claimed an `afterRead` hook sees no `overrideAccess` flag; it does, and `refresh` now passes it, so the guard is a net rather than the fix for #822. And the three reads that guard stands down on are stated, including the sibling row, which is what #828 changed. Plus the shape worth knowing before writing an assertion: a denied `array` field comes back as `[]`, not absent. The matching line in `src/collections/AGENTS.md` — narrowing what a grant returns is a field lock, not an `access` override — rode with the code it describes, one commit earlier. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XdA5L1eQBBwyrgp3wUdubm
The three answers the chunked resolve endpoint needs before it can write a row back, each decidable without a network call and so testable without one. The timezone comes from the coordinates, never from the country column: a country cannot answer it at all for the ones spanning several zones, and `scheduleFields` writes every recurrence against this single value, so a wrong zone moves a class by hours with no later read able to detect it. `tz-lookup` answers offline, and the result is narrowed against the list `payload.config.ts` installs rather than a copy of it — `firstDate_tz` is an enum baked from that list, so a zone missing from it is a row Postgres refuses at write, which is the failure this turns into a reported line number. The lookup is injectable for one reason, stated at the parameter: no coordinates can produce a zone the enum lacks today, so without the seam that narrowing is unreachable and would read as covered while deleted. The duplicate matcher compares a row against the events already in the target subtree and against the rows above it in the same file. Both of its rules need a shared weekday, which is what a bare address match gets wrong — a Tuesday class and a Thursday class in one hall are two classes. The address rule is checked first because it is the stronger claim, and because `nearby-address` tells a reviewer more than `city-and-time` about a pair satisfying both. A null city never matches, including another null: two rows that failed to resolve a city are not therefore in the same one. Two properties the comparison turns on, both read off the stored shape rather than re-derived per side. A weekly class's days come from `weekdays`, not from `firstDate` — the instant is merely one of them, so reading it would compare one class's single day against all of another's. And the start time is read in `firstDate_tz`: `firstDate` is an instant, so two 18:00 classes an hour of offset apart hold different ones. Every assertion was watched failing with its defect reintroduced at the site that would have caused it — sixteen in all, one at a time. Two came back green and both were real. The `!left.length` guard in `sharesWeekday` decided nothing, because `some` on an empty list is already false, so it is gone rather than tested. And the `asin` clamp is unreachable: `h` tops out one ulp above 1 for an antipodal pair, which `sqrt` rounds back to exactly 1, measured over 400k near-antipodal pairs. It stays as a guard, its comment now says what it really guards — a NaN distance compares false everywhere, so the import would quietly stop finding duplicates rather than fail — and the spec says plainly that it covers the formula's far edge and not the clamp. `distance.ts` sits in the import's own folder rather than `src/lib/geography/`: the import is its only owner, and a single-consumer module in the commons fails `tests/unit/lib-boundary.spec.ts`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Saf5gFWQT7AdPgsofsNmvT
Four lenses over the phase diff. The expensive finding was measured rather
than argued: `duplicateReason` derived both of its comparison inputs from a
`Temporal.ZonedDateTime` built inside the loop, and the loop is the cross
product of a 500-row batch against every event in the target subtree —
upwards of 600k pairs. At a measured 5µs per construction, and 13 to 25µs
per comparison for a schedule that names no weekday, that put 5 to 20
seconds of blocking CPU on the event loop, in an endpoint, for answers that
cannot change between comparisons.
So each class is now reduced once, by `prepareCandidate`, to a 7-bit
weekday mask and a start minute, and every comparison is integer
arithmetic: one `&` for the weekday overlap, one subtraction for the start
window. `findDuplicate` takes prepared entries and returns an index, which
is also what removes the `<T>` plus `keyOf` callback — that signature
invited the costly mapper into the innermost loop, so the API shape was
what made the cost unfixable from the call site.
Three helpers were written here that the repo already owns, and in each
case the copy was the looser of the two:
`wallStartTime` was `getLocalTimeHHMM` (`src/lib/schedule/scheduleHooks.ts`)
rewritten — same conversion, same null-on-throw contract, five existing
callers and eight assertions including DST and a half-hour offset. It now
delegates. The wrapper stays because the pairing is the point: that helper
takes an instant and a zone as two arguments, and handing it a schedule's
instant with anybody else's zone is the error its own ⚠ warns about.
`minutesOfDay` was a third spelling of the `HH:MM` grammar, after
`HHMM_PATTERN` in `src/lib/schedule/time.ts` and a private regex in
`registrationDetails.ts` — and the three disagreed about what a malformed
value yields. It moves to `time.ts`, the module documented as owning that
rule, tested with the pattern already there, and `registrationDetails`
drops its copy. Its own line 90 already composed exactly this pair, which
is the evidence it belonged there.
The timezone membership test was a second copy of the seed's
`TIMEZONE_VALUES` + `supportedTimezone`, and the two already disagreed
about trimming with nobody having chosen that. `isSupportedTimezone` now
sits in `@/lib/timezones` beside the list it tests — the same split
`weekdays.ts` uses for weekday codes — and both callers keep their own
policy: the seed substitutes `UTC` and warns, the import reports the row.
The injected `lookup` seam is gone with it. It was a production parameter
paying for a dead branch's coverage, and it let a future caller break the
module's own offline promise; `vi.mock('tz-lookup')` reaches the same
branch, which is what seven other unit specs already do for a module-level
dependency. The narrow-or-refuse tail was also written twice, so collapsing
it dissolved the `unsupported` helper that existed only for the repetition.
Two findings declined. Promoting the seed's overnight-wrap variant of
`minutesOfDay` alongside the others would unify three functions of which
only two agree — `scheduleMatch.ts` deliberately wraps past midnight, which
is the opposite of what the duplicate window must do. And a bounding-box
pre-reject in `metersBetween` saves nothing: the trig measured 0.006µs, is
gated behind the weekday mask, and is 2600× cheaper than the call that used
to sit beside it.
All seventeen assertions were re-watched failing after the restructure,
since the mechanisms they pin changed shape — the mask's Monday bit, the
no-schedule class's empty mask, and `findDuplicate`'s first-match order
among them.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Saf5gFWQT7AdPgsofsNmvT
…d dep
`src/lib/schedule/time.ts`'s entry in the schedule Key files list named two
of its three exports. `minutesOfDay` arrived there because it had been
written privately twice with the copies disagreeing, which is the part worth
keeping — the list is where a reader looks to find out whether a shared
schedule helper already exists.
`src/types/AGENTS.md` had no answer for a dependency that ships no types,
and `tz-lookup.d.ts` is the repo's first hand-written `.d.ts`. The trap is
adjacent to the `declare global` rule already there and inverts it: a file
whose body is `declare module` is already ambient, so the `export {}` that
section requires would make the declaration local and invisible instead.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Saf5gFWQT7AdPgsofsNmvT
`AddressSearchField` held the only copy of the rule that turns a Mapbox `context.region` entry into an ISO 3166-2 code, and the bulk import needs the same answer to decide whether a row landed inside a state target. The rule is three fallbacks deep because Mapbox spells the answer three ways and only sometimes the first — a second copy would have had to rediscover which of the three each result shape needs, and a copy that stops at `region_code` leaves the subdivision empty for whole countries rather than for odd rows. `isCountryCode` and `countryCodeForName` join it for the same reason the predicate belongs beside its table: `src/lib/geography` shipped the country list without a membership test, so each owner was about to layer its own on top. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015GWP8vnodVxMqAM7rJu4wU
`POST /api/event-imports/:id/resolve` geocodes the next 25 rows, places each against the batch's target region, flags the ones that repeat a class, and writes the answers back. The review UI calls it until the response says `done`. Chunked because the work is per row and talks to Mapbox: 500 forward geocodes with a retry each is not a request anybody can hold open. The chunk is whichever rows have no answer yet, so a dropped response costs one chunk and a re-call resumes — there is no cursor for a client to get wrong. **Containment is the part the region tree cannot answer directly.** Every row has to be confined to the target, and `Regions` carries a name, a slug and a `mapboxId` but no ISO code, while a geocoded row comes back with `country.country_code` and `region.region_code`. So `resolveTargetScope` reduces the chain above the target to those two codes, reading a country's slug first (the Atlas seed assigns a country its code as its slug, #556) and its English name second. A chain that yields neither **fails the whole batch with the region named** rather than importing unchecked: the alternative is admitting every row in the world into somebody's country. For the same reason a state node that resolves to no subdivision is an error, and a result whose own subdivision Mapbox did not name fails closed — "Mapbox did not say which" is not evidence a row is inside the target. The country is checked twice on purpose. Once from the row's own column before any call, so a file holding another country's classes does not spend one geocode per row to learn what it already said; and once against the result, because Mapbox honours `country` as a filter rather than a guarantee and this is the last place a foreign result can be stopped before a region is created for it. The resolved row stores the point, the zone, the city, the ids phase 5 matches on, the languages, and the schedule's comparison key — but not the schedule. The commit re-derives that from `anchorDate` and `timezone`, which is why both are stored: `mapCsvSchedule` is pure, so the same two inputs give the same recurrence, and a second declaration of its shape in the JSON schema would be a hand-written copy of `firstDate_tz`, `weekdays` and `weekNumber` — the drift that imported events the CMS then rejected at write (#671). The key is stored because re-derivation is the one thing that cannot give it back cheaply: the duplicate check spans chunks, so a row resolved an hour ago has to stay comparable without re-running the mapper over the batch. `geocodeLocation` joins the region importer's geocoder rather than becoming a second client: the retry, the 429 backoff and the token read are already there, and only the answer differs. ⚠ A context layer's id arrives under `id` in `@mapbox/search-js-core`'s own types and under `mapbox_id` in the API reference, so both are read; nothing in this phase is load-bearing on it, and the duplicate check compares normalised city names, which is the only spelling a stored event can offer. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015GWP8vnodVxMqAM7rJu4wU
The security sweep over this phase found one high finding and three worth closing now. Each is a case where the containment this phase introduces was advisory rather than enforced. **`status` and `rows` were writable by the uploader over REST.** They carry no field access, and `rows` is `readOnly` only in the admin, which is a UI affordance. The uploader holds `update` on the whole document, so a `PATCH /api/event-imports/:id` could hand-write a `resolved` block at any coordinates and set `status: 'resolved'` — and the resolve endpoint treats a row that already has an answer as finished, so the country and subdivision checks would never run on it. Both now carry the `adminOnlyFieldAccess` update lock `targetRegion` and `uploader` already had; the endpoints keep writing them because they elevate. What the uploader keeps is the discard. **`MAX_IMPORT_ROWS` was enforced only by the parser.** It claims to bound the geocoder spend, and the column is what spends it, so the cap is now on the schema as well — the parse step is not the only writer once an endpoint elevates past field access. **A batch id of `1e30` is an integer.** `Number.isInteger` admitted it, and it reached Postgres as an out-of-range `integer`, so an intended 400 came back a 500. **A miss and an outage were one answer.** `geocodeLocation` returned null for a miss, an exhausted retry and a missing token alike, so a few minutes of Mapbox trouble would have written "could not find this location" onto 25 real addresses and skipped them for good. It now answers `found | missed | unavailable`; the chunk stops on `unavailable`, keeps the rows it already resolved, and answers 503, so the next call resumes. `fetchForwardFeature` distinguishes the two internally and `geocodeRegion` collapses them exactly as before, because its caller is a seed run a maintainer re-runs anyway. Two findings are recorded rather than closed, each where the code says so: a city-level target is confined no more tightly than its state, because a city has no ISO code and matching its name would refuse München to an admin whose locale spells it Munich — the city match belongs to the proposal step. And the gate is document ownership rather than role, which the upload endpoint has to settle. The specs pin what the fixes are about rather than the fixes: the stripped write, the outage that leaves rows pending, and the inactive manager and API client that `ownedRegionFilterOptions` would wave through if the two guards were ever reordered. ⚠ It also pins a gap it found on the way. `access.ts` says the discard rides on `update`, and it does not: `updateByID` detects `deletedAt` in a patch and runs `access.delete` as well, which here is admins-only — so no volunteer can discard a batch, and the seven-day retention window has no reachable way in. Closing it means overriding `delete` for a trash attempt, which belongs with the review UI that offers the button. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015GWP8vnodVxMqAM7rJu4wU
…r misses The adversarial pass over this phase measured something the design got wrong, and the measurement is the finding: **19 of the Atlas tree's 101 `region` nodes match no ISO 3166-2 subdivision.** `country-region-data` lists GB's 217 councils and no England, Scotland, Wales or Northern Ireland, so all eight UK regions are among them, with parts of France and Italy. Failing the batch closed on an unresolvable state therefore made the entire UK — the fleet's largest English-speaking country — unimportable, and told the volunteer to rename the region to a subdivision name that does not exist. So the subdivision narrowing degrades to the country and reports what it lost, while the country refusal stays hard. Nothing structural rested on it: the proposal step creates every node **under** the target, so a row cannot leave the subtree either way. What the narrowing buys is catching a row for the wrong end of a country early, which is worth having where it works and reporting where it does not. **A POST with no body answered 400.** `parseBody` reads `req.json()`, which rejects on an empty body, and Payload populates `req.data` for no custom endpoint — so the review UI's own call would have been refused. The endpoint takes no body, so it no longer reads one. The spec could not have caught it: its hand-built `req` had no `json` at all, a shape the REST pipeline never produces. It now throws the way a real empty POST does, so re-adding a body read fails 19 cases instead of none. **Two different online classes in one city were merged.** An online row is geocoded by its town, so every online row in that city shares the place centroid — and `nearby-address` is checked before the time rule, which is what made an 18:00 and a 20:00 class one class. An online row now carries no point, so it falls through to city-and-time, the right question for a class with no hall. A stored online event carries no address either, so the two sides stay symmetric. **Last year's class swallowed this year's row.** `excludeFinishedEvents` only fires for an API client, so a manager's read of the duplicate pool saw every expired series. The read now ANDs `notFinishedWhere`. **A file whose every row failed the parse never reached `resolved`.** Nothing is pending from the first call, so the early return was the only path and it wrote no status — leaving a batch the UI calls done and the commit step refuses. Two smaller ones: `region_code` arrives from Mapbox unnormalised, so the subdivision comparison now uppercases both sides as the country one already did; and the local `relationId` is gone in favour of `src/lib/utilities/relationId`, which returns null for a non-numeric id rather than letting `NaN` into a query. Three specs were pinning less than their names claimed. The subtree refusal matched both 403 messages, and the outsider managed no region at all — so it passed without the subtree check ever running. The admin case asserted only a 200, not that the chunk drained. And no spec used a `region`-level target, which is the whole class of failure above; one now imports a London row under South East. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015GWP8vnodVxMqAM7rJu4wU
…im exemption `event-imports` had no row in `tests/COVERAGE.md` at all — not the collection, not the nightly purge, not the endpoint — so the map said nothing was tested while three spec files covered it. All three rows are added, including the gap the access suite now pins: a `deletedAt` patch runs `access.delete`, so the discard `access.ts` documents is admin-only today. `docs/rules/endpoints.md` gains the rule a reviewer would otherwise read as an oversight: a manager-only endpoint stays out of the OpenAPI shim on purpose, because registering one publishes an admin-panel action in the client spec. Three are absent for that reason now, and each says so in its own handler. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015GWP8vnodVxMqAM7rJu4wU
…proposed for Phase 5a of the bulk import: which rows belong together, decided without the region tree and without a network call. A country or state target groups rows into cities, a city target into the halls two or more classes share. What a group turns out to BE — an existing region, or a new node under a proposed state layer — is the next phase's question, against the tree. **A place is keyed by its Mapbox id, and only then by its city name.** The merge below reasons about places, and two same-named towns at opposite ends of a country are two places, so keying on the name alone would file both under one node. The name is the fallback because `placeId` is nullable: Mapbox carries the `place` layer in a result's context, and an online row placed by its town alone does not always get one back. The metro merge is also what repairs that — one town split between an id-keyed group and a name-keyed one is two clusters at the same centroid, so the smaller folds into the larger and a missing place id costs a merge rather than a duplicate city. **Two properties of the metro merge are load-bearing, and each was watched failing.** Every member row must be inside the radius, not just the centroid: a ring of outlying villages averages to a point near the city they ring, so a centroid test merges them while no class in the group is anywhere near town. And the pass runs **largest first**, which is what makes the chain guard hold — running smallest first offers a village to its nearest town before that town has merged into the city, so the guard sees an unabsorbed target and the village's classes ride into a city 30 km from them. A node is named after the commonest spelling its rows carried, not the first: Mapbox answers one town with a district on one row and the city on the next, and row order must not decide what a region is called. A venue is identified by its address, not by proximity. Two rows 20 m apart are a duplicate where they share a weekday and two different halls where they do not, so a radius here would merge the hall next door. Two spellings of one hall that share neither an id nor an address text therefore propose two nodes, which is a node a human can see rather than a misplaced class — the review's "map to an existing region" is where that is corrected. **One guard was removed because a spec proved it unreachable.** The ranking read each place's size from a map frozen before the pass, against a merge changing the next decision. Under descending iteration it cannot: a cluster only ever absorbs from clusters processed after it, so its own count is pristine at its turn, and growth only raises a size that was already larger. Live counts pass all 20 cases, so the map and its justification are gone rather than kept with a comment claiming a failure that cannot occur. Seven defects were reintroduced one at a time and watched failing at the site that would have caused each: the centroid-only radius test, a merge on equal counts, keying on the city name, taking the first spelling, the dropped venue threshold, the missing rank tie-break, and smallest-first iteration. The first of those exposed a vacuous case of its own — the ring and the city had the same row count, so no merge was ever eligible and the assertion passed for a reason unrelated to the radius. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LcQ5wUGvM2YgADvHvCEgr5
|
Superseded by #907, which rebuilds this feature on Payload's own primitives instead of a parallel stack. This PR stays open for reference until #907 lands; close it then. What carries over, unchanged: the pure core — What does not, and why:
Three migration snapshots become one. |
|
Nothing to adopt — #907 supersedes this, and nothing in your comment asks for code. Parked: left open, nothing pushed, no gate re-run. I left the body alone — your comment is the record, and re-sending one this size to add a line risks losing it. I verified the carry-over list in the checkout. Every module and spec #907 names as lifted is on Two corrections for #907, both cheap to get wrong on a branch off
🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Pull request was closed
…summary email Phase 2 of #907. The browser no longer drives any of this work: a batch's stage moves through one `beforeChange` hook, and the geocoding and the writes are Payload jobs on their own `imports` queue. `transitionStatus` is the gate `status` never had. The field carries only `admin.readOnly`, and the uploader holds document-level `update` through the `manager` field — so before this a `PATCH` could name any status and rewrite `rows` within the Ajv schema. Inert while nothing read them; the moment a job dispatches on `status` and trusts `rows[].resolved`, it is a way to file a class under any region and claim another import's exactly-once key. The hook owns the transition table and the reviewer's own delta: in `proposedRegions` only a rename or a mapping, in `rows` only a duplicate's skip-or-import. `ResolveEventImport` is #874's resolve and propose endpoints with the chunking, the lease and the time budget gone. Geocoding runs four at a time (`p-map`); the duplicate match runs after it, sequentially, so a file's answers no longer depend on which request returned first — the chunked version keyed them on chunk boundaries. `CommitEventImport` is #874's commit and finish without the chunking or the overwrite branch. One worker per job row replaces the lease (`enableConcurrencyControl`), `importKey` is checked before every create so a retry adopts rather than repeats, and the deferred Cloudflare purge is paid back once per tag at the end. `SweepEventImports` deletes a discarded batch and anything untouched for 30 days, whatever its status: what sets the window is the CSV's contact details, and a finished batch keeps them no more legitimately than a failed one. One email replaces #874's two, to the uploader with the admins copied and no attachment — the batch now survives the commit until the sweep, so the skipped rows are a download on its own page. `cc` had to be added to the Resend adapter's hand-written field mapping, where an unmapped field is dropped in silence. `runScreeningQueueAfterCommit` is generalised to `@/lib/jobs/runQueueAfterCommit` and becomes a one-line wrapper. A second migration rather than a reshaped first: both task-slug enums need the three new values, and phase 1's migration has already applied on the PR preview, where regenerating it crash-loops the boot (#633). Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0129s1BT4vyN8fW34rzijJ3a
…not sum The template has no Mailpit preview script — the ticket drops #874's — so a render spec is the only thing that sees it at all. Four cases: the uploader and both links, the twenty-line cap and the count beyond it, the section appearing for errors alone, and nothing at all when nothing was skipped. The third is the one worth keeping. A row can carry both a duplicate match and an error, so a summed "rows skipped" over-counts the lines; restoring the sum turns that case red. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0129s1BT4vyN8fW34rzijJ3a
Phase 4 of #907. The batch's own edit form becomes the review screen: four Payload Field components, one per field they edit, and an Import tab on Regions that is the only way a volunteer reaches a batch at all. `RowsTable` and `RegionTree` write form state, so the edits they offer are exactly the deltas `hooks/reviewerEdits.ts` accepts — a duplicate's skip-or-import, and a node's rename or mapping. `RegionTree` composes `applyTreeEdits`, the same function the write side composes, rather than patching the one node: a rename reassigns slugs across siblings and a mapping can prune an empty state, so a patch would store a tree the commit walks past. `RegionTreeField` is a server component because the mappable regions are a tree read, narrowed to the levels the proposal holds. #874 asked the same question from an endpoint the browser called on every edit. `ImportProgress` is what makes the flow work without a reload: the resolve job writes from a worker, so an open form holds the document as it was at the create. It polls two columns and refreshes the form once the status settles. The template is a checked-in file rather than an endpoint, with a drift case that prints what to paste — so a renamed column cannot ship a template the parser refuses, which is the whole reason `columns.ts` is one constant. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LFS2VJixNGs1VPYPeSA9MM
* feat(lib): decide how a session reaches a gated PR preview `workflow/lib/preview-auth.mjs` turns a repo's own `previewUrl` block and a PR number into the host, the sign-in request to send, the Access headers to attach by env-var name, and one verdict both `finalize-pr` and `review-pr` read: whether this repo seeds previews at all. It decides and never fetches, like `railway.mjs` beside it — a routine cannot reach an API from a script, so the session sends the request and this file holds no credential. Each token variable is reported only as set or unset, and the headers are shell references, so a plan can be logged. The two token env-var names go in `loop-config.json` as `previewAccess`, beside `railway.tokenEnvVar`: a name typed into a skill is a tuning change nobody can review on its own. `ceilings` is untouched. The route and the account are the producing repo's, carried in its `.auth` block, so nothing here knows either and nothing here goes stale when they change. The test fixture deliberately uses a `.invalid` host for the same reason: a copy of another repo's config value is a second definition, in a fixture as much as in a skill. The failure this prevents: `review-pr` reads no repo config today, so without one answer in one place each skill would re-derive "does this repo seed previews" on every dispatch — 25 to 40 times a day — and the two are then free to disagree. Refs #241 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * feat(finalize-pr): give previewUrl.auth a meaning Step 7's *Every link opens on data* now asks the helper first, and signs in with what it answers where a repo declares `previewUrl.auth`. The configuration table gains the key beside `.pattern` and `.seed`. The example Preview block stops naming a real host. The pair it used names SahajCloud's Railway address, which sydevs/SahajCloud#1081 shuts — so the example would have told the next reader to write a link that 403s, and a host spelled in this skill is a copy of a config value either way. The failure this prevents: a run that holds a preview-only Access token still had nowhere to read the route, the account or the header names from, so it would have written `Data: not seeded yet` beside a preview it could have filled. ⚠ No step assumes `previewUrl.seed` is set. SahajCloud's copy carries only `.pattern` today, and the same hand-edit that adds `.auth` adds `.seed`; the `Cannot seed` case still covers an unset one. Refs #241 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * fix(review-pr): a red seed check outranks a line in the body Two places let a change admit it has no data and pass anyway. Where a repo's own CI goes red on a preview that exists and could not be filled, the red check is the gate and a sentence cannot stand in for it. ⚠ **Conditional, never a removal.** That text is correct for the other four repos, which have no seeding check and no gate — there the line is still the only honest thing to write. Each edit decides from the helper's verdict, so neither skill names a number, a label or a repo. `rule-delta.mjs` reports no dropped rule. The failure this prevents is the one the written rule has already accepted twice: sydevs/SahajCloud#1073 shipped its Registrations page with `Data: not seeded` and a console snippet to paste, and sydevs/SahajCloud#874 linked three pages nobody saw anything on — filling that one by hand afterwards found three defects in a minute. The story goes behind one new `docs/why.md` anchor, beside the rule it extends. Each edit still reads as an instruction with the citation removed. Refs #241 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * docs(routine-setup): write down both preview Access tokens They live in two different places, so the doc needs a row in each: the `github-ci` pair as an org-level GitHub secret, read by SahajCloud CI's seed and smoke steps, and the `claude-loop` pair as a Claude cloud-environment variable, read only by `workflow/lib/preview-auth.mjs`. The ⚠ on "There is no secret store" now says what a preview-only Access token reaches — every preview of the gated repo, as a service identity whose every use Cloudflare logs — and what it does not: anything on the live site, whose address it cannot change. The failure this prevents is a person setting up the loop with one Service Auth policy on "any service token", which reads like the simpler choice and makes switching one token off a deletion of both. Two named policies are what let the loop's be switched off while CI keeps running, and the other way round. Nothing here names a stopgap variable: sydevs/SahajCloud#1081 retires it, and this doc never carried a row for it. Refs #241 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * chore(plugin): 5.3.0 → 5.4.0 Every skill change in this PR reaches a cloud routine on its next run, and an installed plugin on no run at all until this string moves: `installed_plugins.json` records a `gitCommitSha` and never revisits it, and the cache directory is named after `version`. A skill change without a bump is the one failure this repo has already paid eight days of stale skills for. `.claude-plugin/marketplace.json` still parses and still points at `./workflow`. Refs #241 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * fix(why): the 874 anonymisation was a hand seed, and no code does it That passage read as though the seed itself replaced coordinator identities with `preview.invalid` addresses. It did not: `grep -rn 'preview\.invalid'` over sydevs/SahajCloud returns zero hits, and nothing writes that address. The anonymisation was done by hand, once, on one preview. Left as it was, the passage stated the opposite of the parent goal's whole premise — that the content system has nothing safe to fill a preview with, since its only data scripts import real people's names and addresses. A reader who trusted it would have concluded the problem was already solved. What makes made-up preview data true in code is the committed fixture sydevs/SahajCloud#1081 adds, and that is structural rather than tested: the real-data files left that checkout in sydevs/SahajCloud#1079, so no CI run holds a real name to leak. It remains no promise about a preview somebody filled by hand. Replaced in place, not appended. Refs #241 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * fix(lib): refuse a plan that would leave the preview host or carry half a token Four defects found reviewing the helper, each the kind a prose rule cannot hold and a script can. A sign-in route came from config and was concatenated onto the host with no check, so `@evil.example/x` or a bare `.evil.example/x` moved the origin while `finalize-pr` attached the Access service token to the request. The route is joined, then the composed origin is compared against the host's; anything else plans no sign-in. For the same reason `{pr}` now takes digits only — the slot sits inside the hostname — and a pattern must be `https:`, since `http:` would put the pair on the wire in cleartext and `file:` would read the disk. `headers` was built from the variable NAMES, so an environment holding no token still handed the session two headers that expand to empty. Cloudflare logs a blank client id as a failed service-token attempt, and the run reads two headers as a working credential. Both halves must now be set. SahajCloud's `accessTokenHeaders` already answered this question the same way; two answers were one too many. The pair also rides only with a gated request now: a repo declaring no `.auth` has no Access in front of it, and a preview host a repo has since moved is a name anyone may claim. `seedsPreviews` was true for any truthy `auth`, `{}` included. That verdict tells `review-pr` to raise a `should-fix` on every empty preview in a repo where no run can sign in or seed — a finding no author can comply with. It now reads a usable plan. `accountsPage` is gone. The seed route accepts only an admin manager, so a run that picked another account from that page could not then seed, and the field widened what the credential was used for while adding nothing. The suite caught none of this: 7 of 7 mutations survived it, the "opens no connection" assertion grepped for `fetch(` alone and passed a module importing `node:https`, and neither field-name override was exercised. It now asserts the import list against an allowlist, and 11 mutations were watched failing against it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * fix(skills): make the new preview rules executable, and drop three false claims Review found the skill half stated things that are not true and asked for things a run cannot do. False, and a false sentence in a skill is in the next run's context: the example's hosts did not "become unreachable the day #1081 shut Railway's address" — that ticket is open, and the raw host redirects rather than going dark. The reason the hosts are gone is timeless, so it is stated that way. `finalize-pr` promised that a repo's seed check "will red this PR", but SahajCloud's step reds only where a preview was discovered; with none, CI warns. `why.md` claimed in the present tense a fixture that an unmerged PR commits, and named the ticket rather than the PR. Not executable: `review-pr` was told to call the helper but never where its input lives — `previewUrl` is not in `loop-config.json`, which is the only config that skill opens — nor that the path needs the `CLAUDE_PLUGIN_ROOT` convention, which is why 52 sessions once lost a call each. It also never got the Access headers, so on a gated repo every preview link answers with the login screen and reads as empty: the critic would have filed its own missing credential as a finding. And the new absolute collided with the carve-out two lines above it, leaving a mid-build 404 ambiguous. `finalize-pr` asked for a JSON subobject hand-spliced into a single-quoted shell string while the file was right there, and named no check on the token before sending. Both are `jq` and one clause. Hard rules still carried the unconditional form of the rule this PR makes conditional, which is the section a run under pressure re-reads, and step 7b restated the bullet instead of pointing at it. Two rules added rather than corrected. The token must never be printed — `fix-ci` already says so for the analogous case, and the values reach the shell even though the script never holds them. And data a preview already held must never be quoted into a public body: somebody may have filled it by hand from a real source. `rule-delta` reports that second one as a removal because it absorbed the shorter "never seed real people's contact details", which it contains. The docs now carry the Access application steps, because a service token is account-scoped and the promise that it "opens nothing on the live site" is kept by a policy nobody was told to create — with a verification `curl` against the live hostname expecting 403. The `CF_ACCESS_*` row moves to a repo secret: `--visibility all` would hand one repo's previews to every workflow in five. And both docs now say the feature is inert until a repo declares `previewUrl.auth`, naming its keys, which nothing told the person who must write that block. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ * fix(review-pr): key the unreachable preview on a signIn, not empty headers `headers: []` has two causes and the text read only one. `authPlan` empties it whenever `signIn` is null, so every repo with no `previewUrl.auth` — all four product repos today — matched the sentence, and so did a repo carrying `seed` alone. The branch's own test at `workflow/lib/preview-auth.test.mjs:141` is that case: `seedsPreviews: true`, `signIn: null`, `headers: []`. Read as written, the rule recorded such a preview unreachable and raised nothing, cancelling the `should-fix` the next sentence demands. The condition is now a `signIn` present with either `access` half unset, which is the only shape that means this environment cannot pass a gate, and empty `headers` with no `signIn` is named as no gate rather than a missing token. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW1KpxUngcdTDx7hQ1 * fix(finalize-pr): pin the unreachable preview to a signIn and name the field Same misreading as review-pr:98, and unscoped here. `authPlan` returns `headers: []` whenever `signIn` is null, so all four repos carrying no `previewUrl.auth` matched this sentence on every preview. Read as written, step 7 stopped checking data and wrote "unreachable" instead — the exact failure the step exists to prevent. The sentence now requires a `signIn`, and names the condition as `access.clientId.set` / `.clientSecret.set` rather than leaving the run to infer it from an empty list. Empty `headers` with no `signIn` is stated to mean no gate, so the data check proceeds as before. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW1KpxUngcdTDx7hQ1 * fix(preview): send the Access pair only to the plan's own host The security review found a credential leak this PR introduced, and it is the kind a prose rule cannot hold. `review-pr` was told to "send each link with the plan's `access.headers`", where each link is a `## Preview` link read out of the body under review. That body is not ours. `dispatcher/decide.mjs` fires `review-pr` with `onDemand` on a PR no member authored as soon as a `respondTo` login types the review verb, and the skill is told to judge a ticketless PR against its own body. So anyone able to open a PR could name their own host in a Preview section and collect the Cloudflare Access service token from their logs — a token that opens every PR preview of the gated repo. The branch had already hardened the script against leaving the host: `routeOn` joins the sign-in route and compares the composed origin. The prose then left by a different door, because the module validated the one URL it built while the skill attached the same headers to URLs it never saw. `onHost` closes it where a rule can be evaluated, and `--on-host <link>` answers `ON_HOST` or `OFF_HOST` for one link. Both skills now send the pair to an `ON_HOST` link only, and an `OFF_HOST` link in a body is a `should-fix` of its own: a body pointing where the repo publishes no preview is one a reviewer cannot check. `review-pr` also gains the `Never print the token` rule its `finalize-pr` counterpart already carried, since it publishes a public What-was-checked section. `railway.mjs` allowlists an outside poster's host for the same reason. Four mutations of the check were watched failing the suite: the `https:` guard dropped, `endsWith` for origin equality, hostname for origin, and always allowing. A fifth, dropping the null-host guard, is behaviour-preserving — the try/catch already answers false. `budget.test.mjs` asserts every verdict word a skill names is one a script can print, so each script now exports its own list and the test reads their union. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW1KpxUngcdTDx7hQ1 --------- Co-authored-by: Claude <[email protected]> Co-authored-by: sydevs-bot <[email protected]>
Summary
ff104a5..e45cb80, by @Ardnived) from an adversarial review that broke the import against a real Postgres database: concurrent commits duplicating classes, a failed write-back duplicating them on retry, a re-uploaded file importing every row again, and a 2 MB upload costing ~15 s of CPU. They add a per-batch lease, a uniqueEvents.importKeywith its migration, upload-time field checks, geocoder and timezone fixes, opt-in coordinator invitations, and a resume/finish/discard flow. The commit comment on the PR carries the full account and the four decisions behind it.f2f29638(@Ardnived), after running the sample CSVs against the hardened importer. German addresses were still landing in the wrong town, so an address lookup moves from Search Box to Geocoding v6 with structured fields and acts on v6's match grade; and a volunteer's own#note row is skipped instead of importing as a broken class. Its comment carries the account.lookupUrlsendspermanent=trueon every import lookup (src/lib/mapbox/geocoder.ts), because the import stores each class's point and address id. A token without that entitlement stops every lookup with "Geocoding is not configured on this server".updatewritingdeletedAt, and Payload runs thedeletecheck for that patch too — so the uploader was refused their own discard. Granting it then let them backdate the timestamp past the purge cutoff, which the review pass caught; the server stamps it now.GET /:id/reviewafter every edit rather than patching what it holds, because a rename re-slugs across the tree and a mapping can prune a state that just emptied.Phases
event-importscollection, its migration and generated types, plus thePurgeEventImportsnightly taskatlas-managergainsmanagers: create,type/rolesgetcreatelocks, read narrows to namesproposedRegionstreeproposedRegionscolumn, its migration, and the propose endpointviews.editregistration, its condition, and the regenerated import map#note rows kept out (f2f29638)Changes
Phase 7c-iii-b:
src/components/admin/RegionImport/ImportReview.tsx— the surface: the tree, the line table, the commit loop, the discardsrc/components/admin/RegionImport/reviewModel.ts— its pure core, includingcommitVerdict, the loop's own termination boundsrc/components/admin/RegionImport/importUrls.ts— the three new steps, the batch document URL the discard patches, and the one request helper both components now sharesrc/collections/EventImports/access.ts—batchDiscardAccess: the uploader may trash their own batch, nobody but an admin may erase onesrc/collections/EventImports/discard.ts— the discard's timestamp is the server's, so the retention window cannot be backdated awaysrc/collections/AGENTS.md,docs/rules/access.md— the overridden-key list, and what a soft delete costs in access termsThe hardening pass touches 109 files;
git diff --stat 221b752..e45cb80is the list, and its own commit comment groups it by concern.The follow-up
f2f29638touches 8, four of them specs:src/lib/mapbox/geocoder.ts—GEOCODE_URL(Geocoding v6) beside the existing Search BoxFORWARD_URL, the structuredlookupUrlwithpermanent=true, and thematch_codegrade read ontoGeocodedLocationsrc/collections/EventImports/resolve/resolveRow.ts— the query becomes fields rather than one line, and alowgrade (or amediumwhose town did not match) refuses the rowsrc/collections/EventImports/csv/parse.ts—isCommentRow: a#row whoseeventTypeandscheduleTypename nothing a class could be is a note, and skippedsrc/collections/EventImports/endpoints/resolve.ts— passes the structured query through⚠ Search Box is still what
geocodeRegionandresolveRegionLocationuse, andseeds/atlas/import.tsis their only caller. See Notes for reviewer.Preview
Seeded 2026-10-06. 646 regions and 648 classes from
seeds/atlas. The 495 coordinator accounts were seeded with their identities anonymised (atlas-manager-<legacyId>@preview.invalid). The tree, the existing-region matches, and the duplicate check all have real data to work against. Sign in at/admin/loginasPREVIEW_ADMIN_EMAIL.⚠ Re-measured after the hardening, and it was still wrong —
f2f29638is the fix. The note here used to record 9 of 13 offline lines landing in the wrong town beforeff104a5..e45cb80, and to ask whether87ff29emoved them. It did not: @Ardnived's re-run put Köln's Hansaring in Kiel, Hannover in Berne and Offenbach in Bad Vilbel, because one joined query line let Search Box match the same street name in another town.f2f29638sends street, postcode, town and state as separate Geocoding v6 fields, and reports every German and Californian test address landing in its own town. Nobody has re-run this against a deployed preview since — and the preview's token needs the permanent-geocoding entitlement named in Summary before it can answer at all.⚠ The two CSVs below are this PR's own copy.
f2f29638's comment reports the sample files and their README updated inevent-import-test-csvs/, which is outside the repo — so whether these two still match them is unverified.Germany CSV (save as
germany.csv)California CSV (save as
california.csv)Test results
Phase 7c-iii-b (
911a86aand earlier):pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(2788 passed, 201 files) — 80stests/unit/event-import-review-model.spec.ts(38),tests/unit/event-import-review-surface.spec.ts(19, jsdom)event-imports,event-import-review,-tree,-commit,-upload,-propose,-resolve,-tab(139) — all eight, because the access change and the new hook are read by every one of themThe hardening pass (
ff104a5..e45cb80), as its own commit comment reports: lint and both typechecks clean, 3,030 unit tests over 207 files, and the full integration lane run once locally — 1,672 tests over 100 files, because the shared test helper changed. Its new specs aretests/int/event-import-hardening.int.spec.ts, which reproduces each break proven against the database, plus unit specs for the field checks, the skipped-lines CSV round trip, request retries, codeless subdivisions and subdivision aliases.The follow-up
f2f29638, as its comment reports: lint and both typechecks clean, 3,038 unit tests, and the resolve, upload and event-imports integration specs. Its own diff adds cases totests/unit/mapbox-geocoder.spec.ts,-resolve-row,-parseandtests/int/event-import-resolve.int.spec.ts.This routine re-ran no gate for either — it pushed no code, and CI is what checks those figures.
⚠ Migration: one, not none. Phase 7c-iii-b's line here said "Migration: none. No collection field changed", and the hardening made that false. It adds
src/migrations/20261006_190923_event_import_hardening.{ts,json}, wired intosrc/migrations/index.ts—events.import_key(unique), five batch columns, and thefinishedstatus, with adown()that reverses all of it.Events.importKeyis insrc/payload-types.ts, and the admin import map needed no regeneration, because the pass registered no new component path. Each of those four was confirmed in the checkout rather than read off the commit comment.f2f29638adds none — its diffstat touches no collection field and no migration.Manual verification
event-import-test-csvs/has one; the copy in Preview is unverified against it.commit/finish.ts), so a repeated call replays the report instead of answering 404. Phase 7c-iii-b's line here said the batch "is deleted by that call, so the skipped lines it lists are the only account of them that exists" — no longer true. Switching the admin locale on that screen must still not clear it, and the skipped lines also arrive by email as a CSV now.deletedAtset to now (as an admin,?trash=true) — not to whatever a client clock said. A batch part-way through its commit must offer Resume and refuse Discard.f2f29638, and unverified against a preview: that every German address lands in its own town; that an address Mapbox does not hold (99999 Nowhere Lane, Xyzzyville) is refused with the closest address named, rather than placed; and that a#note row is skipped while a real#1 Beginners Classstill imports.Notes for reviewer
Everything in this section is phase 7c-iii-b's, except the first item below. The hardening pass has its own account, on its commit comment, including the four decisions behind it, and
f2f29638has its own.New, and the one question
f2f29638leaves open:permanent=truewent on the import's lookup and not on the other one.geocodeRegionandresolveRegionLocationstill call Search Box throughFORWARD_URLwith nopermanent, and their only caller —seeds/atlas/import.ts— writes what they answer ontoRegionsaslocation. By the rulelookupUrl's own ⚠ states, a stored geocode has to have been asked for as permanent, so the seed path reads as the same exposure the import just closed. It predates this PR and is not the import's code, so nothing here changes it. Whether it is in scope, and whether the seed's storage is permanent-eligible at all, is a call for you.Read this one first: the Discard button needed an access change, and that change needed a second one. Trashing is an
updatewritingdeletedAt, andupdateByID(and the bulkupdate) runsaccess.deleteas well for exactly that patch, passingdataso the check can tell a trash from an erasure;deleteByIDand the bulkdeletepass none, which is what keeps the hard delete with the admins and the purge job. Phase 2's spec had pinned the uploader's refusal with a note saying to close it in the change that offers the button — so this deletes that case and asserts the discard instead.Then the thing I got wrong, which the review pass caught: granting the trash was not enough to make it safe.
deletedAtis Payload's own auto-added column — no validator, no field access — so aPATCHcarrying a date a week old was a valid discard thatPurgeEventImportsfound already past its cutoff, and the CSV was hard-deleted on the next nightly run. That handed a volunteer the erasure the grant deliberately withholds, one day later and by another route, while the "refuses the uploader a hard delete" case stayed green.stampDiscardTimemakes the timestamp the server's. It also takes the client's clock out of the retention window, which the button had put there.The judgement call I most want checked:
/security-review's trigger pattern does not match this diff, and I ran it anyway — which is the only reason the above was found.securityReview.triggerPatterncoverssrc/plugins/access/but not a collection's ownaccess.ts, so a change that widens adeletegrant would have shipped without the branch-level sweep. I did not edit the pattern:.claude/workflow.jsonis a protected path, which an unattended session cannot write. It wants theaccess.tscase added, attended. Still open, and the hardening widened the stakes — it touches access and field locks across six commits.Second: a node whose state the prune dropped was in the tree and on no screen.
prunedOfEmptyStateskeeps a state only while some child would be created, and a city matchedelsewherekeeps its parent's key — so the renderer, walking down from the root, never reached it. That is exactly the region whose refusal the reviewer needs to see, and it is reachable from the UI in one click (map the lastcreatecity under a state and itselsewheresibling vanished). The root adopts an orphan now.Third: a locale switch after the commit destroyed the only report of it.
load's identity changes with the admin locale and the mount effect had no phase gate, so it re-read a batch the finish had already deleted and replaced the committed and skipped lines with a 404.Fourth: the loop bound did not bind. A 200 whose body carries no
pendingleaves every comparisonundefined >= undefined— false on every chunk — so a bound written as a comparison alone never ends. Fixed here and re-asserted on the resolve loop, which had the same shape since 7c-i.Fifth: four comments claimed more than the code did. The response shapes are cast, not parsed;
linesis the proposal's own count after the unresolvable rows are gone; the bound's rationale needed the clause that makes it true; andSelectInputdoes not need a form path —ImportRunnerpasses one outside any form 140 lines away. All four now say what is true, and thedistline ranges are gone, since a range is wrong at the next Payload bump and nothing fails when it goes.What I declined, with reasons. Exporting
isCreatedNodefrompropose/tree.tsto replaceisEditableNode: that would put a runtime edge from a browser entry into the proposal engine, whichtests/unit/client-bundle-safety.spec.tswalks and which #633 already paid for once — a one-line predicate is not worth it. AuseRunGuard()hook over the two components'mounted/runningrefs: the duplicated part is ten lines of idiomatic React, and the two ⚠ comments say different things (two batches vs two chunks). And leaving the mapping control native rather thanSelectInput, for the reason the comment now gives.Still deliberately out. No per-line filter on the table, so a 500-line batch renders 500 rows. The uploader can still restore their own trashed batch by PATCHing
deletedAt: null— that predates this phase, and an uploader undoing their own discard is what the window is for, so I left it.⚠ Known holes carried forward — the hardening closed most of them. This list read: "7c-iii-a's
GET /api/managers?where[email][equals]=…existence oracle (pre-dates this PR, #821), the CJK slug fallback from 7c-ii, 7a's unswept abandoned batch, and 6b/6c's five." Three are now closed, confirmed in the checkout:reviewEmails(review/rows.ts) asks only about rows that resolved, so a batch of unparseable rows learns nothing.propose/slugs.tstransliterates throughanyAsciibefore slugifying, and hashes only what nothing transliterates.ABANDONED_BATCH_DAYS = 30sweeps a batch nobody committed or discarded.6b/6c's five are the remainder.
CLAUDE.mdsays to ask before filing an issue, which a routine cannot, so they are still unticketed.Detail
Review passes. No
pr-review-toolkitplugin is available to a routine (ListPluginsreturns empty), so this ran/code-review high,/simplify's lenses and/security-reviewas three subagents over4e4a28d..856310c. All three reported and all three found real defects; the third commit is their triage.comment-lintflags the same two comments as the previous phase, both from earlier phases and both RFC citations, which the code-comments rule names as an acceptable breadcrumb.⚠ The first push happened before those reports landed. The session's stop hook flagged two unpushed commits on an ephemeral container, where losing them costs more than a second CI run, and the gate was green at that point. So this PR has two CI runs for one phase, and
911a86ais what the reviews turned into.Independently verified, because the grant is the risky part. Every caller of
access.deletein Payload:updateByIDand the bulkupdatepassdataand only whenisTrashAttempt;deleteByIDand the bulkdeletepass none, sobatchDiscardAccessrefuses both for a non-admin. TheWherefrombatchUploaderAccessis ANDed into the row filter, so another manager's batch is simply not found — the refusal reads as 404, with no existence oracle. I read those four operations myself rather than taking the report's word for it.The mutation watch: 25 mutations across the three commits, each applied at the site that would have caused the defect, each run against the specs that should catch it, each restored and then diffed back byte-for-byte. The first 14 went red first time. Of the 9 for the review fixes, two did not — the resolve loop's re-asserted bound and the resume label after a failed chunk were both unasserted, so each got a case before being counted. That is the second time in this phase the watch caught a vacuous spec rather than a bug.
Three spec faults found by watching them fail rather than pass. Assigning
.valueand dispatchingchangetests nothing: React tracks each input's last value on the node, so the event it hears looks like a no-op and is swallowed — the first version of the edit assertions passed while the component had been sent nothing. Taking the first<select>in the tree aimed a city's id at the state node's control, which correctly selects nothing and sends nothing. And the discard case left a trashed batch behind that the purge-sweep cases below it then counted.Collapsed, per the simplify pass. One request helper (
sendImportRequest) instead of two byte-identical ones; one spelling of the region tally — the runner's banner keeps the rows, the review owns the regions, and they were being rendered stacked;MappableRegionexported from the module that shapes it; and both response shapes trimmed to the fields the surface reads, since an unread field cannot fail.commitVerdictstays separate fromresolveVerdict: onechunkVerdictwas proposed and is defensible, but they read different shapes and I would rather not refactor 7c-i's bound in the same commit that fixes it.Payload built-ins, per
docs/rules/admin-ui.md. The line table is Payload's ownTablethrough the existingtableColumnhelper. The rename box isTextInput. The tree is nested<ul>s, because nothing in@payloadcms/uiis a tree and the nesting indents with no CSS (socustom.scssis untouched); the mapping control stays a native<select>, because one control per node in a nested list is not a form field and a spec asserting what a reviewer picked would have to reproduce react-select'sOption-shapedonChange.One fixture assumption, stated and checked. Every fixture in both new specs is typed against the server's own exported shapes, so
pnpm typecheck:testsis what holds them to the endpoints that answer them. The real configuration read for this wasEventImports.ts'sproposedRegionsschema, where a node's closed shape is declared.Docs went with their behaviour commits rather than a trailing
docs:commit, because each describes one of them. They ship in the same push either way.Closes #828
🤖 Generated with Claude Code
https://claude.ai/code/session_01J4T9RWUEXkAvskWWaaySYh