Repository navigation
feat(scripts): work locally on a safe copy of production data - #879
sydevs-bot wants to merge 10 commits into
Conversation
…o pause jobs on the copy Replace the local dev database with a read-only pg_dump of production. Dry run by default, --force to replace. Refuses a non-local target, restores beside the old database and swaps only on success, empties the copied job queue, and deletes the dump on exit. JOBS_AUTORUN_ENABLED gates jobs.autoRun through shouldAutoRun, so a local server on a prod copy does not run the scheduled queues against real people. On by default, parsed like EVENT_VERIFICATION_ENABLED. Co-Authored-By: Claude Opus 5.5 <[email protected]>
shouldAutoRun gated the cron ticks only. runScreeningQueueAfterCommit called payload.jobs.run directly, guarded by nothing but NODE_ENV, so a `pending` submission created on a copy of production still screened and delivered within two seconds — real Mailchimp, Brevo or Klaviyo calls with the plain-text key copied from prod, plus registrant and manager mail. Both sites now read one predicate, jobsMayAutoRun, so the flag cannot stop one and miss the other. The NODE_ENV=test suppression stays where it is: it is about racing a spec's assertions, not about jobs policy. With the flag off there is no safety net either, which is the intended behaviour and not a regression — the rows wait for the flag to come back on. Refs #876 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
… off The script copied production without ever checking the one flag that keeps the copy's jobs away from real people's mailing lists. Its default is on, so the safe configuration was the one nobody was holding. --force now exits non-zero before production is read, naming the flag and where to set it. The dry run reports the resolved value, so checking first is worth something. Resolution shares the existing DATABASE_URL parse, so the value reported and the value enforced cannot differ. The two-token test duplicates the transform in src/lib/env/server.ts because the script cannot import TypeScript, and reading that module would validate every unrelated variable as a side effect. The comment names the original. Refs #876 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
…machine pnpm db:refresh-from-prod makes both claims false locally, and each was the only statement of the reason something was safe. docs/rules/email.md said Mailpit holds only fixtures and preview traffic. A local SMTP_URL pointing at the shared Railway Mailpit now puts real people's mail behind a login several people hold, for 7 days. The claim about previews and production stays, since both are still true; the third sender is named, and so is the configuration that is the only guard. docs/rules/storage.md's preview paragraph is cited elsewhere as the reason a delete is safe. For a local prod copy it is not the reason: isStorageIsolationActive() is !isProductionDeployment(), true off Railway, so the delete guard is what holds. Said next to the original rather than inside it, so the preview claim keeps its one home. The README section now carries the three things that reach production from a developer's machine with nothing in code to stop them — SMTP_URL, purgeCloudflareCache's two variables, and railway run — plus the backlog that waits for the flag to come back on. Refs #876 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
Review pass over the branch. No behaviour change except where noted. The two pause flags had the same zod transform written out twice, with a comment asserting the sameness instead of the code. They share a `pauseFlag` schema now, so the bash mirror in the refresh script has one definition to mirror rather than two that could drift. The script derived the `_incoming` suffix in node and again in bash, which was the only real drift risk in the five-field handoff. Node emits the name. dropdb's inline `2>/dev/null || true` hid every failure, not just the missing database `--if-exists` already handles, and moved the complaint to createdb where it reads worse. Behaviour change: a dropdb failure now stops the script and says why. Notices are quietened via client_min_messages rather than redirected, so an error keeps its message. The trap's copy is untouched — a trap must not mask the real exit code. Verified against a stand-in production database: the swap copies content, empties the job queue, leaves no staging database, refuses --force with the flag on, and reports a held-open staging database instead of swallowing it. Comment and spec trims: the predicate's docblock said in thirteen lines what the name plus #876 carries, and the kick spec's table re-tested flag vocabulary that server-env.spec.ts owns. Refs #876 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
The flag was documented as though it were the whole guard. It is not, and a developer following a job docblock on a copy of production would find out the hard way. The README's prod-copy section now lists the paths it cannot reach: a run the operator asks for (pnpm payload jobs:run, /api/payload-jobs/run — four job docblocks suggest that exact command), and saving a clients document, which validates its mailing-list key against the real provider. SMTP_URL's bullet keeps the rule and hands the detail to docs/rules/email.md, which owns it. Two surfaces the flag belonged on and was missing from: DEPLOYMENT.md's environment table, beside EVENT_VERIFICATION_ENABLED, and the Scheduled Jobs section of docs/architecture.md, where the runs-not-scheduling distinction is what explains the backlog. The storage.md paragraph is cut back to the one sentence the neighbouring rule does not already carry — that rule says to cite it rather than restate it. Refs #876 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JcXxB4nhQxZgMABUAGDmD4
|
🚅 Deployed to the SahajCloud-pr-879 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
Scope matches the ticket — four items remained, four done.
The parked decision is still the one that matters. This guard is a process env var, so it protects the process while the copy stays faithful. The body counts three request paths it cannot reach (magicLinks.ts:152, invitations.ts:288, validateMailingList.ts:79). The scrub the ticket asked about is one statement beside the existing TRUNCATE, and travels with the database rather than a shell. Yours to settle.
The gate is complete for runs this process starts. payload.jobs.run has one call site, and shouldAutoRun covers every autoRun entry, the cron loginPlugin appends included.
Findings
consider—src/lib/jobs/autoRun.ts:11: does the module need to exist?consider—src/lib/env/server.ts:34: the schema's docblock now documentspauseFlag.
What was checked
Read: screeningQueue.ts, autoRun.ts, server.ts, the script. Grepped every jobs.run / autoRun site on the branch. No contract surface in the diff.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
| * mailing list on a copy of production (#876). A run the operator asked for — | ||
| * `GET /api/payload-jobs/run`, admin-only — is unaffected. | ||
| */ | ||
| export const jobsMayAutoRun = (): boolean => serverEnv.JOBS_AUTORUN_ENABLED |
There was a problem hiding this comment.
Does this module need to exist? It is one read of one serverEnv field, and that field is already the single predicate the ticket asked for — shouldAutoRun: () => serverEnv.JOBS_AUTORUN_ENABLED in the config and the same read in the kick is the same gate, one file fewer.
The name is the other half. src/CLAUDE.md reserves src/jobs/ for one folder per job, so src/lib/jobs/ reads as shared code for those jobs — and this is runner policy, not a job's.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Keeping both, with reasons.
The module. server.ts:97 tells readers to take the flag through jobsMayAutoRun(), never directly, so the cron and the kick cannot be gated separately. Two raw reads reopen the split #876 was filed for.
The name. src/lib/<domain>/ mirroring an owner folder is this repo's pattern: src/lib/clients/ beside src/collections/Clients/, src/lib/submissions/ beside UserSubmissions.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The shared `pauseFlag` schema landed between `ServerEnvSchema`'s docblock and its declaration, so the block documenting the schema attached to the flag transform instead, and the schema was left with none. Declaring `pauseFlag` above the block restores both. Comment placement only. Refs #876 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FVSr4kigMtwDmRn1yh4YWR
|
One adopted, one rebutted. Pushed
Nothing asked. Lean gate green: lint, both typechecks, 172 unit files / 2285 tests. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
The red check is the Railway preview build, and it is not this PR's. Nothing pushed.
The diff changes no build input — no dependency, no Six previews rebuilt at once when
I cannot read the Railway build log — no Railway CLI and no token in a routine environment — and I cannot re-run a Railway build. Redeploy this preview from Railway; its log is the only evidence left if it fails again. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
Still the Railway preview, and CI has now confirmed it. Nothing pushed. Three facts my last comment could not yet state:
Redeploy this preview from Railway. Its log stays the only evidence left, and a routine has neither the CLI nor a token. Filed sydevs/claude-workflow#164: a deploy commit status bypasses 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
…fresh-from-prod Two conflicts, both where #878 rewrote what this branch extends. `src/payload.config.ts`: #878 moved the `autoRun` array into `src/jobs/queues.ts` as `JOB_AUTO_RUN`, adding the `monthly` entry. This branch had added `shouldAutoRun: jobsMayAutoRun` beside the inline array. Kept both — the flag predicate stays, and the list comes from `queues.ts`, whose entries already include the `screening` safety net this branch's version carried. `docs/architecture.md`: both sides wrote into the Scheduled Jobs preamble. Kept this branch's `JOBS_AUTORUN_ENABLED` paragraph and #878's dead-schedule warning, plus #878's rewritten `CleanupOrphanedMedia` and new `SyncLectureMetadata` bullets. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AaQi3J1bGMtnwrWiNgpXZD
|
Merged
Gate green on the merge: lint, both typechecks, 177 unit files / 2313 tests — 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
Not required, so not blocking: 🤖 sydevs dispatcher |
|
The preview build died inside Turbopack, not in this diff. Nothing pushed. Both of this branch's failures crash at the same step, right after
Evidence it is not the change:
Redeploy this preview from Railway. A routine may neither re-run a Railway build nor clear its cache. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Pull request was closed
Summary
JOBS_AUTORUN_ENABLED, so apendingsubmission on a prod copy still delivered to a real mailing list within two seconds. Both triggers now read one predicate.pnpm db:refresh-from-prod --forcerefuses to copy production until the flag resolves to off, before production is read. The dry run reports the resolved value.Test results
.claude/skills/pr-prep/check.sh— lint, typecheck, typecheck:tests, 172 unit files / 2285 testsscreen-submissions.int.spec.ts+user-submissions-create.int.spec.ts(49), andlib-boundary/client-bundle-safety/public-env-substitutionfor the newsrc/lib/jobs/modulePreview
The preview sets no flag, so it runs with autoRun on — it shows the unchanged path, not the gated one.
pendingrow here still screens and delivers as onmainManual verification
Needs a machine with
railway loginand Postgres client tools — the routine has neither.JOBS_AUTORUN_ENABLED=truein the shell,pnpm db:refresh-from-prod --forceexits non-zero naming the flag, andpsql "$DATABASE_URL" -c 'select 1'still connects to the unchanged database.pnpm db:refresh-from-prodprints the production host, the target database andJOBS_AUTORUN_ENABLED resolves to on, then exits 0.JOBS_AUTORUN_ENABLED=false, create auser-submissionsrow withstatus: pendingin the admin, wait 5 s, thenselect count(*) from payload_jobs_log where created_at > now() - interval '1 minute'returns 0.Notes for reviewer
The ticket's open question is now answerable with numbers. It chose the flag over scrubbing secrets from the copy, and kept that choice here. The review enumerated what the flag cannot reach, which is the evidence that was missing:
magicLinks.ts:152/:166mails a real manager a sign-in link,invitations.ts:288mails on a manager save, andvalidateMailingList.ts:79GETs the real provider with the production key — all request paths, none of them a job. Scrubbing is one statement at a seam the script already has (UPDATE clients SET mailing_list_api_key = NULLbeside the existingTRUNCATE), and it would travel with the database rather than with a process env. I did not do it: the ticket decided against it explicitly and marked it for you.Adopted from the adversarial review, in 48cb0b6:
ServerEnvSchema's docblock had drifted onto the sharedpauseFlagdeclaration, leaving the schema undocumented.Dismissed findings, with reasons:
server.tsand the bash script via a dependency-free.mjsboth import. A shim in the env graph costs more than the duplication, and the script's comment names the original.server-env.spec.tsto a flatit.eachnow that onepauseFlagschema is under test. Kept thedescribe.each: it pins each field's semantics, so giving one flag its own transform later cannot pass silently.tests/utils/. Two predate this branch; consolidating means editing two specs this ticket does not touch.serverEnvread at both sites, and renamesrc/lib/jobs/so it does not read as a job's. Kept both:server.ts:97instructs readers to take the flag only throughjobsMayAutoRun(), so two raw reads reopen the split feat(scripts): work locally on a safe copy of production data #876 was filed for, andsrc/lib/<domain>/mirroring an owner folder is the established shape (src/lib/clients/,src/lib/submissions/).Detail
Why the kick was the gap.
shouldAutoRunis checked per cron tick, butrunScreeningQueueAfterCommitcalledpayload.jobs.run({ queue: 'screening' })directly with only aNODE_ENV === 'test'guard. It fires fromenqueueSubmissionScreeningon anypendingcreate — the default status — and again fromScreenSubmissionsto deliver. TheNODE_ENV=testsuppression stayed where it is: it is about racing a spec's assertions, not jobs policy.The spec was proven non-vacuous in both directions. With the gate removed, the three "off" rows failed; with the predicate forced to
false, the two "on" rows failed. The table is deliberately two rows now — the flag's vocabulary (0,FALSE, padding) is the schema's and is pinned inserver-env.spec.ts.NODE_ENVisdevelopmentin the fixture, or the other guard would mask the flag entirely and both rows would pass for the wrong reason.Script verification.
railwayis absent in the routine environment, so a stub stood in for it and a throwaway database stood in for production, seeded withpayload_jobs,payload_jobs_logand a content table. Confirmed: content copied, both job tables truncated, no leftover_incomingdatabase,--forcerefused with the flag on and with it unset, the gate passed with it off, and the target untouched in every refusal. A staging database held open by another session now reportsis being accessed by other usersand stops, where before2>/dev/null || trueswallowed it andcreatedbfailed with a worse message.Flag resolution duplicates the schema's two-token test in bash, because the script cannot import TypeScript and reading
server.tswould validate every unrelated variable as a side effect. It comes out of the existingDATABASE_URLparse, so the value reported and the value enforced cannot differ.No migration. The change adds no field and no collection.
Fixture pre-mortem.
tests/unit/screening-queue-kick.spec.ts'sbaseEnvassumesServerEnvSchema's required set isPAYLOAD_SECRET,DATABASE_URL,WEMEDITATE_WEB_URL,SAHAJATLAS_URL. Verified againstsrc/lib/env/server.tsand againsttests/unit/server-env.spec.ts's ownrequiredEnv, which matches.Security review ran (the diff touches
src/payload.config.ts, which matchessecurityReview.triggerPattern) and returned no finding above the confidence threshold. It traced theALTER DATABASEidentifier interpolation, the production URI onpg_dump's argv, the dump file'sumask 077+mktemp -d+ EXIT trap, and the local-targetcaseguard, and dropped each with a stated reason.Review lenses:
/simplify(reuse, simplification, efficiency, altitude) plus/security-review.pr-review-toolkitis not installed in a routine.comment-lintclean over 6 changed files.Worth a follow-up, not done here: the repo guards storage at the delete boundary and derives the condition from the deployment (
isStorageIsolationActive()), rather than asking anyone to set anything. Email has no equivalent, and a flag on job autorun cannot reach the three request paths above even in principle. The general change is a third reason in the existing transport branch atpayload.config.ts:258-264, covering all 14sendEmailcallers at one point. Out of scope here, andSMTP_URLunset already disables those sends loudly.Closes #876
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_01FVSr4kigMtwDmRn1yh4YWR