Skip to content

chore(infra): migrate to Railway + Postgres (host-agnostic code) - #468

Merged
Ardnived merged 46 commits into
mainfrom
chore/railway-postgres-migration
Jun 8, 2026
Merged

Ardnived merged 46 commits into
mainfrom
chore/railway-postgres-migration

Conversation

@Ardnived

@Ardnived Ardnived commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Summary

The code-only / host-agnostic portion of the Cloudflare Workers + D1 → Railway (Node) + Postgres migration (#466). This branch makes the codebase run on a long-lived Node server with Postgres and R2-over-S3; it keeps Cloudflare for Images, Stream, and (post-cutover) edge caching/WAF.

Scope note: This is the implementable code slice. The infrastructure steps in #466 — Railway provisioning, secrets, the 1:1 prod-data ETL, DNS/edge cutover, and per-PR preview environments — are deferred to you and marked with TODO(railway) anchors in code/docs. This PR is therefore not mergeable until that infra exists (the baseline migration + a reachable Postgres are prerequisites). It does not close #466.

Built per the agreed plan: branch off main, land the host-agnostic code, defer infra. (The unrelated pnpm audit work stays on its own chore/ci-pnpm-audit branch — not included here.)

What's in this PR (14 commits)

  • Deps — drop @opennextjs/cloudflare, wrangler, @payloadcms/db-{d1-sqlite,sqlite}, @sentry/cloudflare, better-sqlite3 + the OpenNext patch; add @payloadcms/db-postgres, @sentry/nextjs, sharp (pg/aws-sdk were already present).
  • DB — payload.config.ts now uses postgresAdapter({ pool: { connectionString: DATABASE_URL }, push: !isProduction }); all Cloudflare-context plumbing removed. Dev/test/E2E use push; prod runs pnpm db:migrate.
  • Migrations — the 36 SQLite/D1 migrations + the D1 generated schema are reset; src/migrations/README.md documents generating the Postgres baseline.
  • Storage — R2 moves off the native Worker binding to the S3 API (@aws-sdk/client-s3) in r2NativeAdapter.ts/storagePlugin.ts; Buffer byte-copy workarounds dropped. Images + Stream + the Stream webhook are unchanged.
  • Usage — hooks.ts/tasks.ts collapse the D1/SQLite forks to one atomic Postgres UPDATE via the pg pool; the rate-limit binding is removed (edge handles it).
  • Sentry — @sentry/cloudflare → @sentry/nextjs with instrumentation.ts + sentry.server.config.ts + withSentryConfig.
  • Runtime — delete src/worker.ts, open-next.config.ts, wrangler.toml, worker-configuration.d.ts, src/types/cloudflare.d.ts, the patch; clean next.config.mjs (re-enable image optimization, keep output:'standalone'); drop the in-Worker Cache API in the openapi route.
  • Railway — Dockerfile + railway.toml (build pnpm build, start pnpm start, preDeploy pnpm db:migrate, healthcheck /api/health).
  • Tests — integration + E2E run on Postgres (isolated schema per suite); the storage-utils tests are rewritten to mock the S3 client.
  • CI — ci.yml gets a postgres:16 service; smoke specs gated behind RAILWAY_PREVIEW_URL; D1 preview-reclone.yml + wait-for-200.sh deleted.
  • Docs — DEPLOYMENT.md, env/architecture docs, and the migrations/storage/api-clients/tests rules rewritten for the new stack; the D1 PRAGMA gotcha removed.

Testing

Lean local gate (this branch can't run Postgres-backed checks locally):

  • ✅ pnpm lint
  • ✅ pnpm test:unit — 381/381
  • ✅ pnpm exec payload generate:types — config builds against the Postgres adapter; no type drift
  • ✅ tests/int/storage-utils.int.spec.ts — 57/57 (mock-only; validates the R2→S3 rewrite + storagePlugin S3 wiring)
  • ⏳ pnpm test:int (full) + pnpm build — require a reachable Postgres / Railway env; CI runs the int suite against its Postgres service.

Deferred to you — TODO(railway)

  1. Provision the Railway service + Railway Postgres + automated backups; set all secrets/env (DATABASE_URL, PAYLOAD_SECRET, R2 S3 creds, NEXT_PUBLIC_SENTRY_DSN, app URLs, Cloudflare Images/Stream creds).
  2. Generate the Postgres baseline migration against the live DB (pnpm db:migrations:create) and commit it.
  3. Run the 1:1 prod-data ETL (D1 → Postgres) + the verification gate (row-count parity, referential integrity, admin spot-checks).
  4. Wire per-PR Railway preview envs (restore latest prod backup + sanitize — port the PII logic in scripts/sanitize-preview-dump.ts) and set RAILWAY_PREVIEW_URL so CI smoke runs.
  5. DNS/edge cutover: put Cloudflare's proxy in front of Railway, configure Cache Rules/WAF/Rate-Limiting Rules, flip cloud.sydevelopers.com. Keep CF/D1 deployable as the rollback path; decommission after soak.

Acceptance criteria (#466)

Code-addressable items are implemented here (Postgres adapter; R2 via S3; Images/Stream retained; Sentry via nextjs; single-path usage reset; CF-only files removed; CI on Postgres; docs). Infra-gated items (boots on Railway, 1:1 data verified, edge caching/WAF, preview env, rollback) are the deferred steps above and should be checked off as the infra lands.

Minor follow-ups (not done here, to keep scope contained)

  • .claude/rules/{types,routes}.md still reference the (removed) cloudflare.d.ts global-types example and the createWorkerSafeLogger Workers cold-start rationale — valid patterns, stale CF examples.
  • RATE_LIMIT_* constants retained as documentation of the intended edge limits (no code consumer yet).

🤖 Generated with Claude Code

Ardnived and others added 14 commits June 6, 2026 08:51
Remove the Workers/D1 runtime dependencies (@opennextjs/cloudflare,
wrangler, @payloadcms/db-d1-sqlite, @payloadcms/db-sqlite, better-sqlite3,
@sentry/cloudflare) and the OpenNext patch. Add @payloadcms/db-postgres
and @sentry/nextjs; pg/@aws-sdk were already present. Repoint the
generate:types (no wrangler types) and deploy scripts at Postgres/Railway.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remove the 36 D1 migrations + their .json snapshots and the
payload-generated-schema.ts drizzle snapshot — all SQLite/D1-specific
(imported @payloadcms/db-d1-sqlite). The Postgres baseline is generated
later against a live Railway Postgres via `pnpm db:migrations:create`
(interactive); only data migrates 1:1. A README documents the step.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add the required Postgres DATABASE_URL and the R2 S3-API credentials
(R2_BUCKET, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY); the R2 S3 endpoint is
derived from CLOUDFLARE_ACCOUNT_ID. Images/Stream + the R2 delivery URL stay
(those services remain on Cloudflare). Remove the wrangler-only CLOUDFLARE_ENV.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Rewrite r2NativeAdapter to use @aws-sdk/client-s3 (Put/Get/DeleteObject)
against the R2 S3 endpoint derived from CLOUDFLARE_ACCOUNT_ID; storagePlugin
now builds the S3 client and validates S3 credentials instead of the R2Bucket
binding. Drop the manual Buffer→Uint8Array byte-copy in the R2/Images/Stream
adapters (a Workers polyfill workaround; native Node Buffer works). Remove the
now-unused requireBinding helper. Images + Stream stay on Cloudflare.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the sqliteD1Adapter / sqliteAdapter branch with a single
postgresAdapter({ pool: { connectionString: DATABASE_URL }, push: !isProduction }).
Remove all Cloudflare context plumbing: the @opennextjs/cloudflare + wrangler
imports, the getCloudflareContext resolution block, getCloudflareContextFromWrangler,
the E2E SQLite-file path, and the now-unused isCLI flag. storagePlugin() no longer
receives cloudflare.env (it reads config from env vars).

Refs #466

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

Usage tracking and the daily reset now run one atomic Postgres UPDATE via the
pg pool (req.payload.db.pool), removing the NODE_ENV prod/dev fork, the D1 and
better-sqlite3 code paths, and getCloudflareContext. SQLite MAX(...) becomes
Postgres GREATEST(...); placeholders become $1..$3. Rate limiting moves to the
Cloudflare edge: rateLimitHook is now a documented no-op (binding removed),
buildRateLimitKey is retained for tests / a future Redis limiter. Sentry import
swapped to @sentry/nextjs.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Swap server-side captures (sentryPlugin, meditations/frames) to @sentry/nextjs
and add the standard Next instrumentation: sentry.server.config.ts (Node init)
+ instrumentation.ts (register + onRequestError). Convert the client init in
instrumentation-client.ts to @sentry/nextjs (client capture sites stay on
@sentry/react, which shares the global hub). No edge runtime to instrument
(no middleware). next.config withSentryConfig wiring lands with the next.config
cleanup.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Delete the Worker entrypoints and config: src/worker.ts, open-next.config.ts,
wrangler.toml, worker-configuration.d.ts, and the OpenNext patch. Clean
next.config.mjs (drop experimental.cpus:1 and the D1/SQLite serverExternalPackages;
re-enable Next image optimization — add sharp — keep output:'standalone' for
Docker; wrap with withSentryConfig). Drop the in-Worker Cache API in the
openapi.json route in favour of edge caching via Cache-Control. Tidy tsconfig.

(cloudflare.d.ts is removed with the storage-test rewrite in the test commit.)

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Multi-stage Dockerfile (node:22-slim, pnpm) that builds the Next + Payload app
and starts it with `pnpm start`; keeps node_modules in the runtime image so the
Payload CLI is available for migrations. railway.toml uses the Dockerfile builder,
runs `pnpm db:migrate` as the preDeployCommand, and health-checks /api/health.
Build-time env placeholders satisfy serverEnv validation during `next build`
(real values injected by Railway at runtime). .dockerignore trims the context.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Switch the integration + E2E test configs from in-memory/file SQLite to the
Postgres adapter. Each integration suite gets an isolated Postgres schema
(created via push, dropped on cleanup) for the same per-file isolation the
in-memory SQLite gave; E2E uses a dedicated "e2e" schema. vitest injects a test
DATABASE_URL. Rewrite the storage-utils R2 tests to mock the S3 client
(send/PutObjectCommand) instead of the R2Bucket binding, and delete the now-unused
cloudflare.d.ts global types. storage-utils.int.spec.ts (57 mock-only tests) passes.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a postgres:16 service container to the CI job and point DATABASE_URL at it
so integration tests run on Postgres. Remove the Cloudflare Workers-Builds wait
step and scripts/wait-for-200.sh; gate the Playwright smoke specs behind a
RAILWAY_PREVIEW_URL variable (skipped until per-PR Railway previews are wired,
keeping CI green). Delete the obsolete D1 preview-reclone workflow.

scripts/sanitize-preview-dump.ts (+ its unit test) is retained — its PII-stripping
logic is reusable for the future Railway/pg_restore preview path.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Update AGENTS.md, DEPLOYMENT.md, the environment/architecture docs, and the
migrations/storage/api-clients/tests rules for the new stack: Railway Node host
(Dockerfile + railway.toml), Postgres adapter (dev push / prod migrate, baseline
reset), R2 via the S3 API (Images/Stream unchanged), @sentry/nextjs, edge rate
limiting + caching, and Postgres-backed tests (isolated schema per suite). Remove
the D1 PRAGMA foreign-keys gotcha and wrangler/D1 operational references; mark
deferred infra (provisioning, ETL, DNS cutover, per-PR previews) as TODO(railway).

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
DATABASE_URL is now a required server env var, so the serverEnv validation
fixture in server-env.spec.ts must include it.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `(req.payload.db as unknown as { pool?: Pool }).pool` cast was duplicated in
hooks.ts and tasks.ts. Centralize it in src/plugins/usage/db.ts so the narrow
cast lives in one place.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
❌ Deployment failed
View logs
sahajcloud 2069a52 Jun 06 2026, 01:22 PM

Ardnived and others added 8 commits June 6, 2026 12:51
The usage-tracking increment and the daily-reset run raw pool queries
(`UPDATE clients ...`), which resolve against the connection's default
search_path (public). That's fine in production (default public schema) but
fails under a non-public schema — e.g. the per-suite isolated schema the
integration tests use ("relation clients does not exist"). Add a
getDbSchema(req) helper and qualify the table (`UPDATE "<schema>".clients`);
it returns 'public' when no schema is configured, so prod behavior is unchanged.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Three fixes so the full int suite passes against Postgres (643/643 locally):
- meditation-duration: import `sql` from @payloadcms/db-postgres (not the removed
  db-sqlite; drizzle-orm isn't a declared dep so it won't resolve under pnpm) and
  use drizzle `execute` with a schema-qualified table.
- Disable `synchronous_commit` on test connections — Postgres' per-commit fsync
  made write-heavy suites time out; this removes the wait (durability is moot in
  tests). Cut suite wall-clock ~657s → ~324s.
- Bump int testTimeout/hookTimeout for Postgres' real per-op latency vs the old
  instant in-memory SQLite.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Generated with `pnpm db:migrations:create` and applied with `pnpm db:migrate`
against the live Railway Postgres 18 instance — 117 tables created cleanly
(collections, _rels, _v version, _locales, junctions). This is the fresh
Postgres baseline the reset migrations dir was waiting for; production/CI apply
it via the preDeploy `pnpm db:migrate`, dev uses push.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Railway provisioned PostgreSQL 18.4 (the latest stable major). Bump the CI
service container postgres:16 -> postgres:18 so tests run on the same major as
prod, and correct the DEPLOYMENT.md stack notes (Postgres 18, Node 22).

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
End-to-end operator runbook for the CF Workers+D1 -> Railway+Postgres cutover:
provisioning, env/secrets inventory, baseline migration + first deploy, the 1:1
data ETL + verification gate, Cloudflare reverse-proxy + DNS cutover, CI/preview
envs, monitoring/decommission, and rollback.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add optional R2_S3_ENDPOINT; the S3 client uses it when set, else falls back to
the account-derived `https://<accountId>.r2.cloudflarestorage.com`. Needed for
jurisdiction buckets (e.g. EU → `https://<accountId>.eu.r2.cloudflarestorage.com`):
the old native R2 binding resolved the bucket by name regardless of jurisdiction,
but the S3 API needs the exact endpoint or the bucket isn't found.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The setup-stream-webhook.ts success message still printed the old
`wrangler secret put` + `pnpm run deploy:prod` flow. Point it at
`railway variables --set` / a Railway redeploy instead.

Refs #466

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

The Stream webhook secret is intentionally left unset until everything else is
deployed and Railway is live. It's account-scoped and shared with the still-running
Worker, so rotating it early would break the live Worker; set it (rotate via
scripts/setup-stream-webhook.ts --force) at cutover. App boots fine without it.

Refs #466

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

Railway's corepack pulls the latest pnpm (11.5.2), but engines.pnpm capped at
^9||^10 (ERR_PNPM_UNSUPPORTED_ENGINE) and pnpm 11 no longer reads the package.json
"pnpm" field. Fix:
- Pin packageManager to [email protected] (single source of truth for Railway/CI/local
  via corepack); widen engines.pnpm to include ^11.
- Move settings to pnpm-workspace.yaml: allowBuilds approves esbuild/unrs-resolver/
  sharp (prebuilt binaries) and skips @sentry/cli/better-sqlite3/aws-crt
  (build-time-only / transitive / unused — avoids a native compile in the slim
  image); minimumReleaseAge: 0 opts out of pnpm 11's default publish-age cooldown
  so frozen-lockfile builds stay deterministic.
- Dockerfile copies pnpm-workspace.yaml + sets COREPACK_ENABLE_DOWNLOAD_PROMPT=0;
  CI reads the pinned packageManager instead of a hardcoded version.

The existing lockfile (v9.0) is unchanged and frozen-installs cleanly on pnpm 11.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`next build`'s type-check failed on seeds/tests/test-payload.config.ts, which
still imported the removed @payloadcms/db-sqlite — point it at the Postgres
adapter (dedicated seed_test schema). Also export onRouterTransitionStart from
instrumentation-client.ts (resolves @sentry/nextjs' ACTION REQUIRED warning) and
fix the stale @sentry/cloudflare reference in the sentry plugin's index comment.

`pnpm build` now completes locally (compile + tsc + static generation).

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The deps stage ran `pnpm install` (which fires the root `postinstall` =
`node scripts/postinstall.cjs`) but only copied the manifest/lockfile/workspace,
so the install crashed: "Cannot find module '/app/scripts/postinstall.cjs'".
Copy that one self-contained file into the deps stage (it no-ops under CI=true).

Also move the build-time placeholder env from a stage-level ENV onto the
`pnpm build` RUN so it never persists into the image and stops tripping Docker's
SecretsUsedInArgOrEnv lint (these are throwaway, not real secrets).

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived and others added 3 commits June 7, 2026 15:52
…le .env

- Remove the unused aws-crt dependency (declared, never imported) + its
  allowBuilds approval; refresh the lockfile.
- Delete Cloudflare/D1-era scripts superseded by the Railway preview flow:
  scripts/seed-preview-admin.mjs (wrangler d1 execute) and
  scripts/sanitize-preview-dump.ts (D1 SQL dump) + its unit test.
- Fix the stale local .env: DATABASE_URI=file:./local.db -> DATABASE_URL (Postgres),
  drop CLOUDFLARE_ENV (wrangler env selection, no longer applicable).

Refs #466

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

- DEPLOYMENT.md: replace the "TODO(railway) — Deferred Infrastructure" +
  "Preview Environment (TODO)" sections with an accurate "Migration status"
  (provisioning, ETL, cutover [proxied], per-PR previews all done) + the
  remaining gated items + a list of dead Cloudflare-artifact refs to remove later.
- seeds/atlas/MIGRATION_PLAN.md: platform note -> DNS cutover complete.
- .claude/rules/routes.md: drop the Workers cold-start framing (keep the
  prefer-createWorkerSafeLogger guidance; Node has no cold start).
- .claude/rules/types.md: replace the Cloudflare Workers global-types example
  (R2Bucket/D1Database) with a generic one.

Refs #466

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

The seed scripts run only on Node now (local dev + the Railway seed API), so the
Cloudflare Workers / D1 code paths were dead. Remove:
- runtime detection (seeds/lib/runtime.ts isCloudflareWorker/isLocalDevelopment)
  and the safeBufferCopy no-op (kept the real ArrayBuffer->Buffer converters)
- dual-mode data loading: data.json is committed, so always read from the
  filesystem; dropped the workerUrl remote-fetch fallback
- Workers filesystem guards (fileUtils, mediaDownloader, validationReport,
  BaseImporter) — the fs paths now run unconditionally
- D1 rate-limit batch-size + retry-pattern branches (pagination, delays);
  batch sizes collapsed to the Node values

Update remaining Cloudflare/D1/Workers comments + seeds/AGENTS.md +
seeds/lib/AGENTS.md to Node/Postgres. Node behavior + seed API contract
unchanged. lint + tsc clean.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 7, 2026 08:20 Inactive
next.config.mjs headers() is evaluated at BUILD time, and the Docker build
runs with no WEMEDITATE_WEB_URL, so the frame-src *fallback* is what actually
ships. It was https://wemeditate.com, which no longer matches the runtime
live-preview URL (WEMEDITATE_WEB_URL now points at the workers.dev preview
host) — so the browser CSP-blocked the meditation live-preview iframe
("wemeditate-web.contact-c66.workers.dev is blocked").

Point the fallback at the production preview host so the build-time frame-src
matches the runtime livePreview.url.

Refs #466

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 7, 2026 10:11 Inactive
next.config headers() (and thus the CSP frame-src) is evaluated at BUILD time.
The Dockerfile hardcoded WEMEDITATE_WEB_URL=https://wemeditate.com as a build
placeholder, which overrode the real value, so the shipped CSP always allowed
wemeditate.com regardless of the runtime live-preview host — CSP-blocking the
preview iframe when WEMEDITATE_WEB_URL points elsewhere.

Railway exposes all service variables at build time, so drop the placeholders
and let the build read the real values; correct the stale top-of-file comment.
Reverts the f4be2e1 next.config fallback hack (literals are now local/CI only).

Refs #466
…them

The prior commit removed the build-time env entirely, but Railway exposes
service variables to a Dockerfile build as build ARGs (not auto-env), so
`pnpm build` saw none and serverEnv validation failed — PAYLOAD_SECRET,
DATABASE_URL, WEMEDITATE_WEB_URL, SAHAJCLOUD_PREVIEW_SECRET, SAHAJATLAS_URL
were all undefined and the build failed (prod stayed on f4be2e1).

Declare those vars as ARG and pass them inline to `pnpm build` so Railway's
real values reach serverEnv and next.config's build-time CSP frame-src (which
fixes the live-preview CSP block). Scoped to the RUN; nothing persists into
the runtime image.

Refs #466
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 8, 2026 04:48 Inactive
…ckerfile)

Move off the multi-stage Dockerfile to Railway's native Railpack builder, which
exposes all service variables to the build as real env — removing the per-var
build-ARG plumbing and the build-time/runtime env mismatch that broke the CSP.

- payload.config: apply pending migrations in-process on boot via `prodMigrations`
  (long-running container) instead of the `pnpm db:migrate` preDeployCommand,
  which required the full Payload CLI in the runtime image.
- railway.toml: builder = RAILPACK; drop preDeployCommand.
- delete Dockerfile; rename .dockerignore -> .railwayignore (Railpack honors it,
  keeps the build context lean + keeps the committed .env out of the image so
  Railway's injected env is the single source of truth).
- drop the obsolete deploy:prod script.

Verified pre-flight: payload_migrations already records the baseline (batch 1),
so prodMigrations is a no-op on boot; NODE_ENV=production is set on Railway, so
Drizzle push stays disabled in prod.

Refs #466
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 8, 2026 05:44 Inactive
…ebug.log

- postinstall.cjs: skip the Playwright browser download on Railway by detecting
  RAILWAY_ENVIRONMENT / RAILWAY_SERVICE_ID (Railway exposes these at build),
  instead of relying on the incidental CI flag Railway happens to set. Drop the
  dead CLOUDFLARE_PAGES check.
- Remove debug.log from the repo (accidentally committed in d29e0f2) + gitignore
  *.log.

Refs #466
- Remove cross-env: every package.json script now uses native `NODE_OPTIONS=...`.
  The repo is Unix-only (devsafe already uses `rm -rf`; dev is macOS; CI + Railway
  are Linux), and cross-env only matters for Windows cmd/PowerShell shells.
- Remove the outdated `reset` script + its now-dead backing (reset-storage.ts,
  seeds/lib/cloudflare-api.ts, seeds/lib/r2-client.ts), plus squash-migrations.sh
  and reset-migrations.sh — all D1/wrangler-era (drop tables via `wrangler d1`,
  `.wrangler` state, old CLOUDFLARE_R2_* env names), broken since the Postgres
  migration. Recoverable from git if a Postgres/S3 reset is rebuilt later.
- seeds/AGENTS.md: remove the Reset Scripts section + fix stale file-tree comments
  (runtime.ts / dataLoader.ts are no longer dual-mode).
- tests/unit/seed-pagination.spec.ts: drop the getEnvironment + ScriptMetadata
  .environment assertions (those were removed in the seed dual-mode cleanup, and
  the unit lane wasn't re-run at the time).

Refs #466
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 8, 2026 06:50 Inactive
- Remove NODE_OPTIONS=--no-deprecation from all scripts (keep only
  --max-old-space-size=8000 on build). Verified it suppressed no real output:
  lint/test/typecheck/seed/next emit zero deprecation lines on Node 22 — the
  punycode DEP0040 it guarded never fires in our commands. Use a targeted
  --disable-warning=DEP0040 if one ever surfaces.
- Add `typecheck` script (tsc --noEmit).
- De-credit seed:dev: ADMIN_EMAIL/ADMIN_PASSWORD now live in .env.local
  (gitignored, loaded by seeds/env.ts), and the seed:dev script is removed —
  `pnpm seed` reads them from .env.local, so the committed local password is
  gone. seed:prod keeps only the SAHAJCLOUD_URL override.

Refs #466
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 8, 2026 07:03 Inactive
Align the docs with the current stack after the deployment rethink:
- Build via Railpack (no Dockerfile); Railway injects env at build.
- Migrations run in-process on boot via Payload prodMigrations — no
  preDeployCommand / `pnpm db:migrate` in the deploy flow.
- Scripts: `typecheck` added; cross-env / --no-deprecation / deploy:prod /
  reset / seed:dev removed; seed creds live in .env.local.
- CI: no "Cloudflare Build" job.

Updated DEPLOYMENT.md, AGENTS.md, RAILWAY_RUNBOOK.md (reorganized into an ops
runbook), .claude/rules/migrations.md, src/migrations/README.md,
.claude/docs/{environment,architecture}.md, .claude/commands/reset-db.md,
seeds/AGENTS.md, and the fix-bug / implement-issue / migration-validator /
review-pr / security-reviewer / draft-ticket skill docs (stale Workers/D1/
Dockerfile/wrangler refs -> Railway/Postgres; skill behavior unchanged).

Refs #466
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 8, 2026 07:24 Inactive
@railway-app
railway-app Bot temporarily deployed to sahajcloud / production June 8, 2026 07:48 Inactive
@Ardnived
Ardnived merged commit 68517b1 into main Jun 8, 2026
1 of 2 checks passed
Ardnived added a commit that referenced this pull request Aug 3, 2026
…re import (#605)

* feat(atlas): groom legacy event listings before import

The 511 Atlas events were typed by ~200 volunteer managers over four years
with no validation, so the free-text fields carried information the listing
already renders structurally, copy-paste junk, spelling mistakes, and dates
now 2-4 years stale. 219 of 511 events needed at least one edit.

Grooming (events.json, managers' wording kept verbatim):

- Removed what `address` / `room` / `schedule` / `contactInfo` /
  `onlineUrl` / `registrationUrl` / `website` already render. Where prose
  and schedule disagreed the schedule won — its weekday always matches
  startDate's day-of-week, the prose did not (#128, #149, #235, #389, #443).
- Dropped stale dates (25 events named a year, 48 a specific date) and 18
  expired notices ("On Christmas break", "Sommerpause", "CLOSED during
  August 2024").
- Fixed capitalization (the Italian `SAHAJA YOGA -` prefix, the Australian
  `HORNSBY Thursdays 6.30pm` pattern, German title-case, missing accents)
  and ~25 confirmed spelling errors across 8 languages.
- Stripped 480 U+2800 braille blanks used as VK padding, 31 zero-width
  spaces, tabs, CRLF, `</br>`, and styled Mathematical-Alphanumeric letters.
- Rewrote titles that were a bare place name, a venue name, an address, or
  a day and time.

A weekday stays in a title where it is the only thing separating sibling
events at one venue, and in a description where `schedule` cannot express
the real cadence — both noted in AGENTS.md.

Supporting changes:

- Add `Events.contactEmail`. Atlas has no such column: 16 addresses came
  out of descriptions and 12 from the `contactInfo.email_address` the
  importer never read. Deliberately outside the contactPhone -> contactName
  required gate, since some events publish an email and no phone.
- Promote 10 `contactInfo.meetup`/`facebook` values to `website`, own
  domain beating the aggregator per the #584 rule.
- Derive a missing `schedule.weekday` from `startDate` in `parseSchedule`.
  49 rows use a YAML dialect with no `on` key; weekly ones were already
  covered by scheduleMapper's fallback, but `monthly_1st` was not — 2
  events recurred on "day 3 of the month" instead of "first Sunday".
- Emit optional event fields as `null`, not `undefined`. Payload omits
  `undefined` from an update, so the 36 descriptions this pass cleared
  survived the first `--update` reseed unchanged.
- Skip the leftover test records #494/#575, warning with the document id
  when an earlier import already created them (#575 landed published).
- Move recurrence parsing to `helpers/recurrence.ts` so it is unit-testable
  (extract.ts runs `main()` at module load).

tests/unit/atlas-events-data.spec.ts guards the grooming invariants so a
re-extraction — which drops every curated value — fails the unit lane
instead of quietly shipping. 13 of its 15 cases fail against the
pre-grooming file.

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

* feat(events): time-of-day auto-titles, and prefer them over generic names

A blank event title is better than a hand-written generic one: the auto-fill
localizes, and improving one string improves every event, where 60 copies of
"Free Meditation Classes in <Place>" cannot be. This makes the auto-fill worth
preferring, then retires the generic names in favour of it.

Auto-title:

- Add `event.title` to the Atlas translations global — `morning` / `afternoon` /
  `evening` / `default`. Each is a complete sentence with a `%{place}`
  placeholder, not a shared prefix plus a time-of-day word: a locale that puts
  the time of day after the place, or inflects it with the preposition, cannot
  be served by concatenation.
- Pick the slot from the event's *local* start hour via `schedule.firstDate_tz`.
  19:00 in Auckland is 07:00 UTC, so reading the UTC hour would label it a
  morning class. `default` covers a 22:00-04:59 start and the 19 events with no
  schedule at all.
- Slots fall back to English individually — Payload's locale fallback is
  per-field, not per-key, so a partly translated locale would otherwise yield
  `undefined` for the slots a translator skipped.

The hook previously read `event.titlePrefix`, which was never declared in
`translationsSchema.json`: the lookup always missed and every title used the
hardcoded English. `event` holds nested groups and the builder cannot mix leaf
keys with groups at one level, which is likely why it was never added — hence a
`title` group rather than a bare key.

Titles (69 blanked, 11 kept or restored):

- Blanked the standardised "Free Meditation Classes in <Place>" names an earlier
  pass introduced, three indistinguishable "Online Meditation" listings, five
  casing/"Weekly" variants, eight that collided at one venue, and five carrying
  an English generic on a DE/FR event.
- Restored 10 titles that name the **venue** — the auto-fill only has the
  street, so `Regina Public Library, Glen Elm branch` carries what
  `1601 Dewdney Ave E` cannot. Kept #293/#294/#371, whose streets are `Zentrum`,
  `Innenstadt` and `B26`; fixed #294 `Tyrol` -> `Tirol`.
- The importer now sends `title: ''` for a blank `customName`. The hook keeps
  `originalDoc.title` for a nullish value, so clearing a title in events.json
  would otherwise never reach an already-imported row.

Because the auto-fill takes the first comma-segment of `street`, three venue
records were producing "Meditation at 9" / "at solihull" / "at old bar"; fixed
in venues.json, which improves the rendered address too.

The four Swiss `Introduction & Meditation Course` events are not a translation
gap — they are the `course` half of duplicate pairs (same venue, weekday,
language, and time in 5 of 7). Translating them would mint a duplicate title per
venue, so they are blanked and the pairs documented for a manager to reconcile.

Verified: lint, typecheck, 897 unit tests, and 60 integration tests across the
events/atlas/translations specs. The full integration lane is flaky on this
machine — the clean tree at 4f7ca64 fails 12 files / 13 tests the same way
(timeouts in media- and meditation-heavy suites), so this branch sits inside the
existing noise band rather than adding to it.

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

* feat(atlas): merge 12 confirmed duplicate events

Atlas let one real class be entered twice. 12 pairs were confirmed by sharing a
venue *and* an identical frequency/interval/weekday/weekNumber/startTime, then
differing only in title, description, lifecycle status or language. Atlas's own
`status` decided the survivor: 0 = verified/live, 6 = finished, so a 6/0 pair
means Atlas had already retired one side.

15 rows removed from events.json (511 -> 496):

- #195 -> #603   same Zoom room + slot, same manager and region; title blanked
- #752 -> #753   one bilingual Ixelles session listed twice, EN and FR
- #360 -> #684, #392 -> #698                     Helsinki, retired half dropped
- #458/#461/#464/#468/#469 -> #560/#565/#562/#570/#571
                 one Swiss manager's `course` rows, retired and re-entered as
                 `dropin` at the same venue/weekday/time/language
- #82 + #496, #497 + #534, #355 + #535           both sides already retired

A merge is not a delete: values the removed row held and the survivor lacked
were carried over first — #684 gained #360's meetup `website` and contact, #698
gained #392's contact.

- Add a curated `languageCodes` override. Atlas stored one code per row but
  Payload's `languages` is hasMany, so the merged bilingual #753 carries
  ['EN','FR']; `mapEventLanguages` prefers it over `languageCode`.
- Generalise the skip guard into `EXCLUDED_EVENT_LEGACY_IDS`, a reason-per-id
  map covering the 2 test records and all 15 removals, so a re-extraction (which
  rebuilds the file from `select * from events`) cannot undo the merge. It warns
  with the document id when an excluded row already exists from an earlier
  import — all 15 do.
- `expectedCounts.events` 509 -> 494. Removing rows also drops 3 venues from
  multi-use to single-use (132, 317, 562), so the import now creates 3 fewer
  region centers; regions still clear their expected minimum.

Deliberately not merged: #115/#116 (same Zoom link but different `areaId` — one
room advertised to two regions on purpose), five pairs owned by two *different*
managers, and #400/#404 + #435/#437, which only look co-located because a venue
record's coordinates disagree with its own stated address.

Verified with captured exit codes: lint, typecheck, 899 unit tests, and 33
integration tests across the atlas/events/translations specs.

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

* refactor(atlas): blank 78 titles that only say "meditation"

A custom title has to earn its place: the auto-fill localizes and improves
centrally, so a generic name is strictly worse than none. 78 titles said nothing
the auto-title doesn't — often the identical string repeated verbatim across a
dozen cities, so they never distinguished anything either.

Blanked, among others:

  10x  Taller de meditación          (5 Spanish cities)
   7x  Viikoittainen meditaatio      (4 Finnish cities)
   6x  Corso di Meditazione          (6 Italian cities)
   5x  Meditatie Cursus              (5 Belgian towns)
   5x  Sahaja Yoga Präsentation und Meditationsübung
   3x  Méditation                    (#753/#754/#755)

plus one-offs — `Aula aberta`, `Meditation Course`, `Learn to meditate`,
`Meditate for inner peace`, `Медитация`, `Meditação Presencial` ("in person"
is `eventType`), `Weekly meditation`, `Daily online meditation`.

Kept, because they name something the auto-fill cannot:

- a venue      — Regina Public Library, University of Guelph, Button Factory
- an audience  — Kids' Meditations, Aula de Aprofundamento, Meditation für
                 Fortgeschrittene
- a language   — Viikoittainen meditaatio suomeksi, Meditationskurs auf Deutsch,
                 Sahaja Yoga in English
- a format     — Music and Meditation, Live Online WhatsApp Video Meditation,
                 Taller de musicoterapia
- a named event — Corso Leopold, Puja a Shri Ganesha, Vaasan Taiteiden Yö

Blanking can collide: two events at one venue in the same time-of-day slot
auto-fill to the same title. #463 and #569 were therefore left named, each
sharing a street with an already-blank sibling. The 7 remaining collisions are
all pre-existing pairs already on the unmerged-duplicates list — #263-#266 were
four identical `Taller de meditación` titles before this change, so they are no
less distinguishable than they were.

Two guards added to tests/unit/atlas-events-data.spec.ts: a regex rejecting bare
"meditation/class/course" titles in 9 languages, and a check that every blank
title can still produce one (online, or a venue with a street). The first was
mutation-checked by re-introducing `Méditation` on #753 — it fails.

221 custom titles remain, 273 events auto-fill.

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

* fix(atlas): group events that meet at one address into a shared venue

A venue used by more than one event becomes a Regions node those events point
at; a single-use venue's address is inlined and the record dropped. That already
worked — but grouping keys on `venueId`, and Atlas holds the same place under
several venue rows, so two events at one address each looked single-use and
neither grouped.

Ten pairs added to VENUE_MERGES, each verified by hand. **36 -> 44 shared
venues**, 346 inlined.

Coordinates alone are not evidence in either direction: two Civitavecchia venues
sit 177 m apart but are different places, while Athens 386/432 are 230 m apart
yet share a name, street, city and postcode. Two candidates were rejected on
inspection — Móstoles 155/158 (404 km apart, different names; one row's `street`
is simply wrong) and Воронеж/Тольятти 483/511 (700 km apart). Both had surfaced
from a normaliser that stripped non-Latin text to an empty string, so every
Cyrillic and Greek address matched every other one.

The kept side is whichever holds better data, not the lower id — 191 -> 215
because 215 is named `Wensum Sports Centre`, which event #315's own description
names; 50 -> 514 because 50's postcode `1017ZP` is Amsterdam's on a Den Haag
venue. VENUE_FIELD_OVERRIDES repairs a field where the *deleted* row was better
(514 keeps its correct postcode but takes 50's real name, `Atelier`), in code so
a re-extraction reproduces it.

Two bugs this fixes:

- Venues 11 and 104 sit 1 m apart and were *both* shared, so the import created
  two nodes for one Amsterdam building.
- Merges apply in a single pass, so a chain strands events on a deleted row. The
  pre-existing `342 -> 104` had to become `342 -> 11` once 104 merged into 11.
  `venueMergeChains()` + a unit test now reject any chain.

Also: warn on orphaned nodes. The import only upserts, so a venue dropping below
the >1-event bar leaves a stale region behind with its public URL. It reports the
document id rather than deleting — a manager may have hung content off it.

Three postcode conflicts are left as they stand, flagged in AGENTS.md, because
the data cannot settle them: Eindhoven 5641EC/5641PC, Tampere 33541/33540,
Derby DE73 5SA/5UA.

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

* feat(events): keep the venue name, and let the auto-title use it

`venueToEventAddress` discarded a venue's own name when folding a single-use
venue into an event's address, leaving nothing but a street — so a blank title
auto-filled to "Meditation at 9 St Peter's Park Rd" rather than naming the
meeting house a seeker is looking for.

- Add `address.venueName` (text, max 100) behind a `hasVenueName` option on the
  shared addressFields factory; only Events opts in. Distinct from `room`, which
  says where *inside* the building to go.
- `addressPlaceName` prefers it over the street, so `composeEventTitle` now takes
  the address rather than the street alone.
- The importer sets it for 232 offline events.

166 names are deliberately dropped, because they add nothing over the address:

- **the street rewritten** — Atlas names many venues after their own address with
  the house number on the other end ("22 Manenburgstraat" for "Manenburgstraat
  22"). Compared as a sorted token bag, so word order and punctuation don't
  matter.
- **the city** — venue 483 is named "Воронеж", in Воронеж. Using that as the
  place would be worse than the street, not better.

Trailing separators are stripped: "Browns Bay Community Centre," and
"Waimarie: Hamilton East Community House," both carried one, and would otherwise
have ended a title with a comma.

Resulting titles: "#4 Evening Meditation at Main Sahaja Centre in New Zealand",
"#11 Afternoon Meditation at Upper Riccarton Community and School Library".

The generated migration also picks up `event_title` on the translations locales
tables — that group was added in 023fc39 without one. Dev runs `push: true` so
it went unnoticed; production would have been missing the column.

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

* refactor(regions): rename the `center` level to `venue`

Most of these are public libraries and community halls that host more than one
class, not Sahaja Yoga centres — "SY Center" claimed more than the data supports.
The level is what it actually is: a venue shared by several events.

Renamed the stored enum value, not just the label, so the API says the same thing
the admin does: `level: 'center'` -> `'venue'`, "SY Center" -> "Venue", the
Centers tab -> Venues, `childrenCenters` -> `childrenVenues`, and the importer's
`center:<venueId>` map keys -> `venue:<venueId>`.

*** BREAKING FOR AtlasReact *** — the widget reads `level` off the region API and
must be updated in step. Nothing else consumes the value: it appears only in
Regions.ts, Events.ts's City/Venue filter, geocoder.ts's radius default, the
importer, and generated types.

`src/lib/atlasSidebar/sidebarModel.ts` declares its own `RegionLevel` union
(deliberately, to keep the client tree free of the server collection), so
typecheck could NOT catch it — the stale `center` key surfaced only when the unit
lane ran. Worth remembering the next time a level value changes.

*** THE MIGRATION NEEDS A HAND-EDIT BEFORE MERGE ***

`20260730_172342_rename_region_level_center_to_venue.ts` is committed exactly as
generated, and as generated it will FAIL on deploy: it casts the column to text,
drops and recreates the type, then casts back with
`USING "level"::"enum_regions_level"` — which throws on every existing row
holding 'center' (44 of them), aborting the in-process boot migration.

The hook blocks me from editing files under src/migrations. Replace both bodies
with an in-place rename, which carries the rows and needs no backfill:

  up:    ALTER TYPE "public"."enum_regions_level" RENAME VALUE 'center' TO 'venue';
  down:  ALTER TYPE "public"."enum_regions_level" RENAME VALUE 'venue' TO 'center';

Verified with captured exit codes: lint, typecheck, 919 unit tests, 29
integration tests across atlas-collections / regions / events / atlas-sidebar.

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

* refactor: re-export RegionLevel instead of redeclaring it

`sidebarModel.ts` declared its own copy of the `RegionLevel` union, so the
`center` -> `venue` rename typechecked cleanly while leaving two stale `center`
keys behind — the failure surfaced only when the unit lane ran. A type-only
re-export from the canonical union makes tsc catch it.

Type-only, so it's erased at compile time: none of geocoder.ts's server-side
Mapbox code reaches the client bundle this module feeds ('use client' components
under src/components/admin/AtlasNav/).

Mutation-checked — renaming the canonical value now produces
`sidebarModel.ts(147,3): Type '"venue"' is not assignable to type
'RegionLevel | null'` where it previously compiled silently.

`REGION_LEVEL_LABEL` stays duplicated on purpose, now with the reason recorded:
`REGION_LEVEL_OPTIONS` is a runtime value inside a server collection config, so
importing it would drag that config, its hooks and `serverEnv` into the client
bundle.

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

* fix(seeds): correct the expected Atlas region count to 518

`expectedCounts.atlas.regions` was 482 with a comment claiming "482 source geo
nodes (29 + 100 + 353)". Both halves were wrong: regions.json holds 474 rows
(29 country + 99 region + 346 area, post-dedupe), and the importer adds one
shared-venue node per venue used by more than one surviving event — 44 of them.
The real figure is 518.

This mattered because verification is `actual >= expected`, so an understated
constant is not a conservative choice — it degrades into no check at all. At 482
the import could have silently lost 36 regions and still reported a pass.

Adds a unit test deriving the number from the data (regions.json row count +
shared-venue count computed off events.json, excluding the two test records the
importer skips) and asserting EXPECTED_COUNTS matches. Mutation-checked: with
the constant back at 482 the case fails with "expected 482 to be 518".

Also corrects the `eventTitle` no-place comment, which claimed an empty title
would fall through to `useAsTitle`/the document id. It doesn't — `title` is
`required`, and field `beforeChange` hooks run *before* validation
(payload/dist/fields/hooks/beforeChange/promise.js:16-19), so the field is
refused rather than saved blank. The behaviour was already correct and already
covered by "leaves no event unable to produce a title at all"; only the comment
was misleading.

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

* docs(atlas): sync the region-level rename and the groomed/region counts

The branch renamed the Regions `center` level to `venue` and moved several
counts; the docs still described the old shape.

- MIGRATION_PLAN.md: three "Regions `center`" references → `venue` node.
- atlas/AGENTS.md: the grooming pass covers 446 of the 511 extracted events, not
  219 (the figure predates the second and third passes); contactEmail is on 27
  events; the venue-topology note points at the test that now guards the count.
- seeds/AGENTS.md: atlas events 511 → 494, regions 482 → 518 in the collection
  metadata table, and the same 446 correction.
- Records why an understated `expectedCounts` value is not a safe default.

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

* fix(migrations): rename the region level enum value in place

The generated migration cast `regions.level` to text, dropped the enum type,
recreated it without 'center', then cast back with
`USING "level"::"enum_regions_level"` — which throws
`22P02 invalid input value for enum enum_regions_level: "center"` on every
existing 'center' row. Prod has 44, and Railway PR previews boot against cloned
prod data, so as generated this aborted the in-process boot migration.

`ALTER TYPE ... RENAME VALUE` renames the label in place, so no row is rewritten.
Verified in a scratch schema seeded with center rows: the generated form fails
with 22P02, RENAME VALUE succeeds, the column default survives as
'country'::enum_regions_level, and `down` reverses cleanly.

Augmentation case 1 in .claude/rules/migrations.md — the migration fails without
the edit. The .json snapshot already records the post-rename values, so the
chain stays intact for the next migrate:create.

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

* fix(tests): finish the center → venue rename in the access specs

`role-based-access.int.spec.ts` still created regions with `level: 'center'` in
four places, so the whole "recursive inheritance via breadcrumbs" block failed CI
with "Details > Type: This field has an invalid selection" (plus a cascading slug
collision as the fixture chain unwound).

The reason it reached CI: `tsconfig.json` excludes `tests`, so `pnpm typecheck`
never reads the int specs — the type-only RegionLevel re-export added earlier
guards `src/` but cannot guard here. Compounding it, both `createRegion` helpers
took `Record<string, unknown>`, so `level` was unconstrained even in-editor.

Narrows both helpers to a `RegionFixture` type keyed on the canonical
`RegionLevel`, and renames the leftover center/Center identifiers and test names
in both region specs to match the level they now create.

Including `tests` in the tsconfig program would be the real fix — it surfaces 189
pre-existing errors across ~20 spec files, so it needs its own ticket rather than
riding along here.

Verified: role-based-access + regions + atlas-collections int specs pass (79
tests), and the lean gate is green.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Ardnived added a commit that referenced this pull request Sep 5, 2026
)

Rewrites every in-scope prose file (67 of 69 flagged by the audit) into
strict Simplified Technical English and retires D1/Cloudflare Workers-era
debris three months after the Postgres/Railway migration. Tracked *.md
(excluding CLAUDE.md symlinks and the vendored .agents/skills/payload/
skill, left untouched pending ownership confirmation) drops from 770,090
to 600,797 chars (22%). The five hot-path files auto-imported every
session (AGENTS.md, docs/architecture.md, docs/environment.md,
docs/code-style.md, .claude/workflow.json) drop from 84,492 to 36,397
chars (57%).

Deleted (dead, zero referrers, grepped clean): seed-issues-report.md,
src/migrations/README.md (its one fact folded into src/migrations/AGENTS.md).

Merged: DEPLOYMENT.md + RAILWAY_RUNBOOK.md split by lifecycle (how it runs
today vs. provision-from-scratch/disaster-recovery), resolving their
D1-decommission contradiction — PR #468 (merged 2026-06-08) confirms the
Worker is gone, so the stale "Remaining (gated)" TODOs are removed, not
reworded.

Legacy debris fixed (D1/SQLite/Cloudflare-Workers-as-current retired):
migration-reviewer.md's whole persona rewritten for Postgres/Drizzle,
seeds/wemeditate/AGENTS.md's Dual-Database table corrected to Postgres,
src/globals/AGENTS.md's json_array() rationale corrected to Postgres's
real FUNC_MAX_ARGS=100 limit, docs/mcp-setup.md's cloudflare-docs row
drops Workers/D1. grep for D1|SQLite|Cloudflare Workers across
.claude/agents/, seeds/wemeditate/, src/globals/, docs/mcp-setup.md is
clean. README.md's stale `cd sy-devs-cms` corrected to `cd SahajCloud`.

Mandatory AGENTS.md fixes applied: dropped the nonexistent `pnpm
test:e2e`, replaced the broken dev-server.sh path with the
`/workflow:dev-server` skill, fixed the seeds/atlas/MIGRATION_PLAN.md:103
anchor (now resolves to `AGENTS.md#website-selection-rules-584`),
collapsed duplicate PR-workflow/test-tier prose into single pointers to
testing-reqs.md and the finalize-pr skill.

Traps preserved (compressed, never deleted): the conflicted-PR "zero CI"
diagnostic with its docs/why.md anchor and #632/#653 numbers; the Cache
Rule authorization-header predicate and root-endpoint fix; DB_QUERY_LOGGING
and TURNSTILE_SECRET_KEY footguns; storage.md's preview/prod asset-isolation
risk; the payload-cli silent-exit/hang ladder; the migration snapshot
out-of-order duplicate-re-emission trap; access.md's per-locale-roles
gotcha (#665); endpoints.md's root-endpoint hook gap; email.md's two-
token-URL-shapes bug; seeds/atlas/AGENTS.md's silent-rollback-on-trashed-
relation trap; the never-name-a-global-field-locales rule. The 2026-08-27
dated Admin Access exception is kept (still current).

Comment sweep: rewrote comments to STE in every file the audit flagged
as touched (route.ts's mandatory dead-comment deletions, r2NativeAdapter.ts,
Icon.tsx, scalarPlugin.ts, env/server.ts, localizedRolesAuth.ts, plus the
full tests/seeds/scripts/.claude/root-config/.github sweep — 227 files
total). Verified comment-only: every changed line in every .ts/.tsx/.mjs/
.cjs/.sh/.py file has an identical code portion before its comment marker;
zero functional changes. Deleted a dead `sharp` import and several doc-
duplicating/obvious comments (e.g. vitest.setup.ts's two narrate-the-
obvious lines).

Verification run as finisher: pnpm lint, typecheck, typecheck:tests, and
the full unit lane (1564 tests) all pass, plus targeted integration specs
for every touched collection/access path (events, regions, role-based-
access — 79 tests, live Postgres). ste-lint.py run on all 40 changed .md
files: hard violations cut from 169 to 118, concentrated in five already-
dense reference docs (admin-ui/api-clients/email/endpoints/openapi/
storage.md) where the prior compression pass already prioritized fidelity
over the linter's raw sentence-length cap; remaining flags are verified
domain terms (Railway's "Health Check", Zod's "Validate", literal HTTP
methods GET/DELETE, SQL "cascade delete", TS "type erasure") or residue
in those five files. rule-delta.mjs vs main on AGENTS.md/docs/rules/*.md/
migration-reviewer.md: 3 directives flagged REMOVED, all three verified
as de-bolded (not deleted) — "GET /api/events/geojson always excluded,
no opt-out" (api-clients.md) and the two CPU parallel-test-run rules
(testing-reqs.md) all still present as plain bullets/cells, content
identical. 1 flagged ADDED is the same pass-by-reference comment rule
gaining full-sentence bold (previously invisible to the tool since only
"Do not" was bold). Sequencing: PRs #692 (UNKNOWN), #686 (BLOCKED, not
CONFLICTING), #691 (CLEAN) show no current CONFLICTING/DIRTY state, so
this PR is not blocked today, though #692/#691 touch overlapping files
and should land or be watched. securityReview trigger paths (access/,
storage/, api routes, webhook scripts) all confirmed comment-only.

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

This branch was previously deployed

1 inactive deployment
sahajcloud / production — 65677434 Deployed Jun 8, 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.

chore(infra): migrate host to Railway + DB to Postgres

1 participant