Skip to content

feat(events): keep finished events published but off the public feeds - #604

Merged
Ardnived merged 12 commits into
mainfrom
feat/finished-events-off-feeds
Aug 3, 2026
Merged

Ardnived merged 12 commits into
mainfrom
feat/finished-events-off-feeds

Conversation

@Ardnived

@Ardnived Ardnived commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A finished event now stays published, so its Atlas page keeps resolving for a seeker following an old link — it drops out of the public feeds instead of being unpublished.
  • "Finished" becomes DB-queryable: a stored, indexed schedule.lastDate column (end of the final occurrence's local day) replaces the virtual upcomingDates check, retiring the 6-month MAX_MONTHS_AHEAD false positive.
  • POST /api/events/{id}/register now refuses an event that has ended (409) — the published-only access filter no longer catches it.

Changes

  • src/fields/scheduleFields.ts, src/lib/schedule/scheduleHooks.ts — stored lastDate sub-field + the pure lastOccurrenceEnd it projects, and the computeLastDate beforeChange hook.
  • src/lib/schedule/scheduleStatus.ts (new) — shouldFinish, moved out of the ExpireEvents stage machine now that the feeds and registration share it.
  • src/collections/Events/lifecycle/finished.ts (new) — notFinishedWhere, the SQL counterpart.
  • src/collections/Events/endpoints/geojson.ts — unconditional filter (no opt-out).
  • src/collections/Events/hooks/excludeFinishedEvents.ts (new) — client find/count default, with an explicit-where opt-out.
  • src/jobs/ExpireEvents/ExpireEvents.ts — finishEvent no longer touches _status; finished joins PUBLISHED_STAGES.
  • src/lib/schedule/backfillLastDate.ts + scripts/backfill-schedule-last-date.ts (new) — recompute the column on existing rows.
  • src/plugins/usage/hooks.ts — isTrustedReq, the companion predicate to asTrustedReq.

Migration

  • New migration: src/migrations/20260730_170909_schedule_last_date.ts
  • Impact: adds a nullable schedule_last_date timestamp + btree index to events, app_cards and both version tables (scheduleFields is shared with AppCards). No data transformed.
  • Reversible: yes — down drops the indexes and columns.
  • No deploy-order hazard. shouldFinish computes from the schedule sub-fields rather than reading the column, so the nightly sweep is correct from the moment this ships whether or not the backfill has run. A NULL column reads as "never ends", so an un-backfilled event stays visible (today's behaviour) rather than disappearing. Any write to a row back-fills it via computeLastDate.

Test Results

  • Lint: ✓ no errors · Typecheck: ✓ clean
  • Unit: 892 passed (82 files)
  • CI (full Tier-3 suite): ✓ green — 892 unit + 874 integration, 53 int specs
  • Railway preview deploy: ✓ built and deployed
  • One CI-only failure, fixed: event-verification.int.spec.ts asserted _status: 'draft' after a finish — the contract this PR inverts. My local targeted set covered events / events-geojson / event-registration / expire-events / backfill but not that spec, which also drives the ExpireEvents job.

Notes for reviewer

Two mutation checks — the central claims aren't vacuous, verified by flipping the code:

  • Restoring _status: 'draft' in finishEvent fails the new expire-events test (expected 'draft' to be 'published').
  • Removing skipVerifyHook from the backfill fails its test on a moved nextCheckAt — without it, backfilling would silently restart every event's escalation cycle.

Three Payload behaviours this had to accommodate (each verified against Payload, each a silent failure otherwise):

  1. find and findByID both reach a beforeOperation hook as operation: 'read'. Guarding on 'find' matched nothing — the list filter silently did nothing until the guard became 'read' + 'id' in args (the trick filterMeditationsByLocale uses).
  2. Only the dotted schedule.lastDate path is queryable; the nested-group form is rejected upstream with "path cannot be queried". So the opt-out check needs no nested branch — a test pins that rejection.
  3. The registration endpoint forwards the client req via asTrustedReq, so the new list filter was hiding the event from the endpoint's own lookup and collapsing the 409 back into a 404. Hence isTrustedReq: result-shaping hooks honour the trusted flag, security gates deliberately don't (see validateClientOriginHook).

Deviations from the ticket, all deliberate:

  • §8 overlaps feat(events): registration gating + fullness for atlas redesign #599 / PR feat(events): registration gating + fullness for atlas redesign #601. That PR already lands shouldFinish at src/lib/schedule/scheduleStatus.ts and an event_ended (409) gate. I used the same path and export so whichever merges second is a small conflict, and feat(events): registration gating + fullness for atlas redesign #601's gate inherits the lastDate definition for free. My guard uses the same 409 + message shape so it collapses into evaluateRegistrationGate cleanly.
  • Two ticket claims didn't hold, so nothing changed for them: the finished copy in VerificationStageField/timeline.ts already said "no longer publicly listed", and .claude/docs/architecture.md had no ExpireEvents section to correct (I added the missing one). The genuinely stale copy was the admin notice telling managers to "republish" a finished event, plus a comment in lifecycle/verify.ts.
  • /api/events isn't annotated in OpenAPI. Custom paths merge into the generated spec by shallow spread, so adding a /api/events entry would replace the generated operation. The list-read default + opt-out is documented on the geojson operation's description instead (and in .claude/rules/api-clients.md). Annotating the generated path would need a new deep-merge/description seam in the openapi plugin — left out of scope.
  • isPublishedStage / PUBLISHED_STAGES have no consumers anywhere in src/ or tests/. The ticket asked for the copy fix, so I made it, but they're dead exports worth deleting separately.
  • The backfill was not verified by a live run. A dry run against the shared local dev DB blocks on drizzle's rename-vs-create prompt, because push: true wants to add the column that this migration adds properly. Covered instead by tests/int/schedule-last-date-backfill.int.spec.ts against a schema built from the current config.

Reviews: /simplify (4 fixes applied), /code-review at high effort over all 7 identified risk areas (clean), /security-review on the endpoint + trust-mechanism changes (clean — confirmed req.context is never populated from user input, so a client cannot forge a trusted req). One review note — "the backfill deletes historical exclusion records" — was measured and rejected: cleanupExpiredExclusions strips a >1-day-past exclusion on every write including the create, so such a row never had one to lose. Measuring it did surface a genuine wrinkle, now pinned by a test (see the last commit).

Drive-by, not fixed: .claude/rules/scripts.md lists two scripts that no longer exist (repair-r2-meditation-filenames.ts, create-sample-page.ts). Left alone as unrelated to this ticket.

Manual verification

The automated lanes cover the feeds, the sweep and registration. Worth an eyeball:

  1. Open a finished event in the admin — the notice should read "…no longer listed publicly — its page still opens for anyone following an old link", and the stage tracker should show Finished while _status stays Published.

  2. Atlas manager sidebar counts should be unchanged (they bucket on verificationStage, not _status).

  3. Against a seeded finished event (note curl -g — the select[...] brackets are glob metacharacters):

    curl -g "http://localhost:3000/api/events/geojson?select[title]=true&select[schedule][lastDate]=true"   # absent
    curl -g "http://localhost:3000/api/events/<finished-id>?select[title]=true&select[webUrl]=true"          # still resolves

Closes #603

🤖 Generated with Claude Code

Ardnived and others added 10 commits July 30, 2026 10:07
Adds a stored, indexed, hidden `lastDate` sub-field to `scheduleFields()`,
recomputed on every write by a `computeLastDate` beforeChange field hook.
Value is the end of the final occurrence's *local* day (so an event running
today stays live until its own midnight), or `null` when the recurrence never
ends. The pure `lastOccurrenceEnd()` helper is the single definition; the
column is just its DB-queryable projection.

Termination is read off the built rule's own options rather than re-derived
from the sub-fields, so it can't drift from buildRRuleTemporal's conditions.
The hook computes from `{ ...previousSiblingDoc, ...siblingData }`: a field
beforeChange hook only receives the incoming patch and Payload materialises
`{}` for an omitted group, so reading siblingData alone would NULL lastDate
on every unrelated write.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nullable timestamp + btree index on events, app_cards and both version
tables (scheduleFields is shared with AppCards). Nullable by design: the
column degrades gracefully — a NULL reads as "never ends", so the feeds
keep showing an un-backfilled event rather than hiding it — and any write
to a row back-fills it via computeLastDate.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replaces the `upcomingDates` finished-check with one shared definition:

- `shouldFinish` moves from the ExpireEvents stage machine into
  `@/lib/schedule/scheduleStatus` — it's now shared with the public feeds
  and (once #599 lands) the registration gate, so it can't live inside one
  job. It keys off the schedule's last occurrence instead of the virtual
  `upcomingDates`, retiring the MAX_MONTHS_AHEAD false positive that made a
  monthly-every-12-months event read as finished while still running.
- `notFinishedWhere(now)` is its SQL counterpart, over the stored column.
  A unit matrix pins the two to the same answers — they're separate
  implementations because a `where` can't call a function.
- `finishEvent` no longer sets `_status: 'draft'`: a finished event stays
  published so its Atlas page keeps resolving for a late seeker following an
  old link. `finished` therefore joins PUBLISHED_STAGES.

`shouldFinish` computes from the sub-fields rather than reading the stored
column, so the nightly sweep is correct from the moment this ships, with no
dependency on the backfill having run.

`EventScheduleInput` moves to src/types/schedule.ts now that it has a second
consumer, and becomes the parameter type of buildRRuleTemporal /
lastOccurrenceEnd so reading a schedule off a document needs no cast.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nothing unpublishes a finished event any more, so these two filters are the
only thing keeping it off the map and out of listings:

- `GET /api/events/geojson` ANDs `notFinishedWhere(now)` onto the caller's
  `where` unconditionally. Because it's part of the read rather than a
  post-read drop, `totalDocs` and pagination reflect the filtered set, and a
  caller's own `where` cannot bring finished events back into the map feed.
- `excludeFinishedEvents` (beforeOperation) does the same for an API client's
  `find` / `count`, but with an opt-out: a `where` naming `schedule.lastDate`
  is honoured, so a client asking for past events gets them. `findByID` is
  untouched, so old Atlas links keep resolving.

Two things Payload's behaviour dictated here, both verified against it:

- `find` and `findByID` both reach a beforeOperation hook as `operation:
  'read'`, so the list/single split is made on `findByID`'s `id` arg — the
  same trick `filterMeditationsByLocale` uses. Guarding on `'find'` silently
  matched nothing.
- Only the dotted `schedule.lastDate` path is queryable; the nested-group
  shape is rejected upstream with "path cannot be queried". So the opt-out
  check needs no nested-form branch, and a test pins that rejection.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Covers the behaviour change directly: finishing sets `finished` + clears
`nextCheckAt` and leaves `_status: 'published'` (with webPath/webUrl still
non-null), an open-ended recurrence never finishes, and the unverified ladder
still unpublishes at `urgent → expired` and trashes after the grace period.

Verified non-vacuous: restoring `_status: 'draft'` in finishEvent fails the
first case with "expected 'draft' to be 'published'".

Also adds the missing `captureMessage` export to this spec's Sentry mock.
`resolveRecipients` reports an absent region manager through it, so every
region-escalating stage threw before reaching its assertions — no existing
test drove one to completion, so the ladder never actually advanced here.
It now does (advanced: 1, remindersSent: 1, failed: 0).

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`POST /api/events/{id}/register` relied on the published-only access filter to
404 an unregistrable event. A finished event is now published, so that filter
no longer catches one whose schedule has run out — registration would have
succeeded for an event that is over. Rejects with 409 + "This event has ended"
instead: the event exists and is readable, its state just conflicts.

Doing this needed one supporting change. The endpoint's own event lookup
forwards the client `req` via `asTrustedReq`, so `excludeFinishedEvents` was
filtering the event out of it — collapsing the new 409 back into a 404. The
hook now exempts trusted reqs via a new `isTrustedReq` companion to
`asTrustedReq`: an endpoint doing its own lookup needs the true state to answer
precisely. This follows the split `validateClientOriginHook` documents —
result-shaping hooks honour the trusted flag, security gates don't.

Scope note: #599 owns the broader gating rules (capacity, external mode, a
course already under way) and lands the same refusal as `event_ended`; this
closes only the hole reopened here.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Rows written before the column shipped hold NULL, which reads as "never ends" —
so a finished event would stay on the public feeds until something recomputed
it. `scripts/backfill-schedule-last-date.ts` walks `events` + `app-cards` and
fixes them; reports by default, writes with `--force`.

The routine lives in `src/lib/schedule/backfillLastDate.ts` rather than in the
script: it spans two collections, so it belongs to neither one's folder, and
keeping it out of the CLI makes it testable without the script's dotenv +
config-bootstrap side effects.

Two safety properties are pinned by tests rather than asserted:

- `skipVerifyHook` on the write. Without it the Events `verifyOnSave` hook
  treats each backfilled row as a fresh verification and silently restarts
  every escalation cycle — removing the flag fails the test on a moved
  `nextCheckAt`.
- Re-runnable. `lastOccurrenceEnd` has no clock, so a second pass reports 0
  changed.

Not verified by a live run: a dry run against the shared local dev DB blocks on
drizzle's rename-vs-create prompt, because `push: true` wants to add the column
that migration 20260730_170909 adds properly. The int tests cover the behaviour
against a schema built from the current config.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The behaviour change is only discoverable if it's written down — an existing
client whose `GET /api/events` result set shrinks needs to find out why from
/api/docs, not from the source.

- OpenAPI: the geojson description now states the exclusion, the definition of
  finished, the local-midnight rule, that `where` cannot override it there, and
  where the opt-out *does* work; register gains its 409. Guarded by
  tests/unit/openapi-custom-endpoints.spec.ts.
- `.claude/rules/endpoints.md`: a passthrough may narrow the caller's `where`
  — filter inside the read (so totalDocs/pagination stay consistent), and state
  the opt-out convention (feeds unconditional, list reads yield to an explicit
  `where`). Plus the two Payload behaviours that bite: `find`/`findByID` both
  arrive as `operation: 'read'`, and trusted forwarded reads must be exempt.
- `.claude/rules/api-clients.md`: per-read contract table + `isTrustedReq`.
- `.claude/rules/collections.md`: `lastDate` alongside the virtuals, the
  read-termination-off-`options()` and partial-update traps, refreshed key files
  (also fixes a stale `scheduleField.ts` → `scheduleFields.ts` filename).
- `.claude/docs/architecture.md`: adds the missing `ExpireEvents` section.
- `tests/COVERAGE.md`: events row, a new ExpireEvents scheduled-job row, and the
  shouldFinish/notFinishedWhere agreement subject.
- `.claude/rules/scripts.md`: the backfill script.

Two claims in the ticket turned out not to hold, so nothing was changed for
them: the `finished` copy in VerificationStageField/timeline.ts already said
"no longer publicly listed", and architecture.md had no ExpireEvents section to
correct. The genuinely stale copy was the admin notice telling managers to
"republish" a finished event, and a comment in lifecycle/verify.ts.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- `lastOccurrenceEnd` calls `rule.options()` once instead of twice.
- Drops the dead `EventScheduleInput` re-exports from scheduleHooks and
  icsBuilder — every consumer imports it from `@/types/schedule`. (The
  `ScheduleSubFields` re-export stays; SendSessionReminders and AppCards use it.)
- Inlines the single-use `LAST_DATE_PATH` constant.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Found by measuring while triaging a review note, not by reading. The claim under
test was "the backfill deletes historical exclusion records"; it doesn't —
`cleanupExpiredExclusions` strips a >1-day-past exclusion on *every* write,
including the original create, so such a row never had one to lose.

What is real is subtler: `computeLastDate` runs against the incoming patch, so a
create can store a `lastDate` that reflects an exclusion the same write is
removing. The stored value is then not reproducible from the stored sub-fields
(tail excluded at create → the earlier date; a recompute → the later one), and
the first backfill pass rewrites it. Behaviourally inert — a stripped exclusion
is by definition past, so both candidates are behind `now` and the event is
finished either way — but it explains why a first pass can move a `lastDate`
that looked fine, which would otherwise read as a bug.

Refs #603

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

railway-app Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Aug 1, 2026 at 4:15 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-604 July 30, 2026 20:44 Destroyed
`event-verification.int.spec.ts` asserted `_status: 'draft'` after the sweep
marks an event finished — the exact contract #603 inverts. Now asserts
`published` plus non-null webPath/webUrl, which is the point of the change:
the event's Atlas page has to keep resolving for a late arrival.

Caught by CI, not locally: my targeted integration set covered events,
events-geojson, event-registration, expire-events and the backfill, but not
event-verification, which also drives the ExpireEvents job.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-604 July 30, 2026 21:09 Destroyed
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-604 August 1, 2026 16:13 Destroyed
@Ardnived
Ardnived merged commit 4da0578 into main Aug 3, 2026
2 checks passed
@Ardnived
Ardnived deleted the feat/finished-events-off-feeds branch August 3, 2026 21:44
Ardnived added a commit that referenced this pull request Aug 3, 2026
Reconciles #599 (registration gating + fullness) with main's #603/#604
finished-event overhaul, which landed the same shared surface differently:

- shouldFinish: took main's lastDate-based implementation
  (src/lib/schedule/scheduleStatus.ts) over my upcomingDates-based one; the
  gate's event_ended check + gating.ts now use it (typed via EventScheduleInput),
  and pass `now` through so the gate is evaluated at a single instant.
- Finished-event contract: main keeps finished events *published* (off the
  feeds via excludeFinishedEvents / notFinishedWhere), the opposite of my
  original "finished ⇒ draft ⇒ 404" note. Flipped the Item-3 docs (Events.ts
  JSDoc, architecture.md) to match, and removed main's minimal stopgap
  ended-check in registerForEvent — my full gate (with a machine-readable
  code) supersedes it, as main's own comment anticipated.
- Events hooks: combined main's excludeFinishedEvents (beforeOperation) with
  my syncEventFullness (beforeChange).
- OpenAPI + tests: kept my 4-code register 409 doc/test and main's geojson
  finished-exclusion doc/test; refreshed the gating unit fixtures for the
  lastDate model.
- Migration: dropped my 0722 registrations_full migration and regenerated it
  on top of main's schedule_last_date (0730) so the snapshot chain stays
  cumulative → 20260803_221051_registrations_full_flag.

Refs #599

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived added a commit that referenced this pull request Nov 2, 2026
…1061)

Backfills (owner confirmed both are done): delete
scripts/backfill-region-breadcrumb-urls.ts (#640) and
scripts/backfill-schedule-last-date.ts (#604), the src/lib routines only
they used, their int specs, and the doc rows pointing at them. New writes
fill breadcrumbs[].url and schedule.lastDate on their own, and
region-canonical-url / events specs cover that live behaviour.

seeds/tests harness: test-storyblok.sh and test-meditations.sh run
importers that have had no CLI entry point since #156, so each "test"
exited 0 having done nothing; check-db-stats.ts queried the music
collections renamed in #180. Delete them with setup-test-db.ts and
test-payload.config.ts (used only by them), rewrite the folder guide
around the spec that stays, and drop the third buildConfig site from
the systemEntities / access.md / postgresTestPool comments.

Smaller: meditation-duration's "backfill migration logic" block
re-implemented a migration deleted in #308 and called none of our code;
seed-pagination's PaginationOptions block only read back an object
literal; lemonfox-client's comment named transcribe.ts's old path.

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(events): keep finished events published but off the public feeds

1 participant