Skip to content

refactor(fields): declare a jsonSchema on every JSON column, and delete the aliases they replace - #714

Merged
Ardnived merged 12 commits into
mainfrom
claude/refactor-json-schemas
Sep 7, 2026
Merged

Ardnived merged 12 commits into
mainfrom
claude/refactor-json-schemas

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • 14 stored JSON columns now declare a jsonSchema, so Payload validates writes with Ajv and generates their real type instead of { [k: string]: unknown } | unknown[] | string | number | boolean | null.
  • 6 more schemas cover the virtual columns, which review asked to fold in rather than defer. Nothing stores a virtual column, so its schema buys the generated type rather than a write gate — and can be closed against exactly what its own afterRead hook returns.
  • 12 hand-written type aliases go, replaced by the generated interface: LectureMetadata, TestDateRangeInput, SyncLectureMetadataInput, NotificationPreference, NotificationPreferencesValue, EventQualityReport, ReadinessReport, TagAssignment, AbuseScore, AbuseLevel, TagAssignmentField's row alias — plus a third copy of NotificationPreferences in the Atlas seed mapper, and the consumer casts that existed only because the generated index signature was unknown.
  • No behaviour change for any caller. Nothing here is on a public write path.

Changes

File Change
src/fields/fileMetadataField.ts New. One factory for the fileMetadata column the four upload collections each declared separately
src/lib/eventQuality/schema.ts New. EventQualityReport as JSON Schema, for Events.qualityReport
src/lib/utilities/subtitles.ts jsonSchema replaces typescriptSchema + a hand-rolled Zod validate. parseSubtitles / validateSubtitles deleted
src/lib/lectures/nirmalaVidya.ts lectureMetadataJsonSchema; the LectureMetadata alias deleted in favour of the generated interface
src/lib/meditations/frames.ts Schemas for Meditations.frames and subtleSystemNodeWeights; the latter declares type: ['object', 'null']
src/components/admin/NotificationPreferences/config.ts additionalProperties is a schema, not true, so the value is typed and the keys stay open. Both aliases deleted
src/lib/notifications/{recipients,registrationRecipient}.ts, src/jobs/RegistrationNotifications/SendRegistrationDigests.ts, src/collections/Events/lifecycle/verify.ts The four notificationPreferences casts deleted
seeds/atlas/helpers/managerMapper.ts The third copy of the shape deleted; seeds/atlas/import.ts imports the generated type directly
src/collections/{Managers,Meditations} The two custom validators now compose the built-in one
src/collections/{Frames,Images,Songs,Videos} Four inline fileMetadata definitions → the factory
Virtual columns AppCards.viewSchedule, Clients.usage.abuseScore, Events.qualityReport, the four Meditations join columns, schedule.upcomingDates, every readiness section
src/lib/{status,eventQuality}/types.ts, src/plugins/usage/abuse.ts, src/components/admin/{TagAssignmentField,AbuseScore/*,EventQualityPanel/*,ReadinessField/*} The four aliases the virtual schemas replace, now imported from @/payload-types at each call site
src/lib/clients/verification.ts Points at ClientCanonicalVerification, the interface the URN rename produced
src/collections/{Lectures,Lessons}, src/lib/richEditor/blocks/*, src/jobs/* Schema wired on
src/fields/{scheduleFields,legacyFields,logField,translationsField} Schema wired on, or a comment saying why the shape stays open
src/collections/AGENTS.md, src/types/AGENTS.md, tests/COVERAGE.md The rule, and the coverage rows

A virtual column takes a schema too — and it can be closed

The first round left the 8 virtual columns with a comment saying their type "lives at its source". That was wrong, and review caught it: "typed at its source" types the hook, never the interface. AppCard.viewSchedule generated the loose union regardless, so every consumer still cast.

Six schemas now cover them. Two are declared on factories rather than on one field — virtualJoinField puts one on all four Meditations join columns, and virtualReadinessField puts one on every readiness section — so six schemas reach more than six fields.

Closing these shapes looks like it contradicts this PR's own rule — "every property optional, unless nothing can hold the old shape". It does not. That rule exists because Payload validates a stored column on every save of its document, so a required key can strand a row written under an earlier shape. A virtual column has no stored row. Its only writer is its own afterRead hook, so the schema can state exactly what that hook returns, and the generated type is worth having.

Two things fell out of doing it:

  • A union needs oneOf, not one object with optional keys. EventQualityReport and ReadinessGroup are both discriminated unions. Merged into one object, both arms' keys go optional and narrowing on skipped or type stops working. oneOf keeps the discriminator, and generate:types renders it as a real TS union.
  • null still leaves the generated type where a hook returns it — no future occurrence, no locale. type: ['object','null'] does not combine with properties (the same finding as notificationPreferences, above), so consumers still null-check. Recorded in src/collections/AGENTS.md.

No alias survives the schema

The virtual-column round first landed its four new types as one-line aliases of the generated interfaces (export type ReadinessReport = GeneratedReadinessReport). Review asked, at all four sites, for the generated type to be imported at the call site instead. Adopted, and the aliases are deleted:

Alias Now
TagAssignment TagAssignments[number], written inline at both uses
AbuseScore ClientAbuseScore — calculateAbuseScore returns it, and the cell, field and display components import it
AbuseLevel Its union restated the generated level, so the display component keeps a local ClientAbuseScore['level'] shorthand and the export is gone
EventQualityReport The generated interface, at 6 consumers and 3 specs. Dropped from the @/lib/eventQuality barrel
ReadinessReport The generated interface, at 7 consumers and 2 specs. Dropped from the @/lib/status barrel

This branch had broken a rule the repo already carried. src/types/AGENTS.md says "A derived alias stays local, and is never re-exported" — a re-export chain outlives its derivation, so the next reader cannot see where the shape came from. src/collections/AGENTS.md's #659 rule then cited two of these four aliases as the pattern to follow, which is corrected here: delete the hand-written type and import the generated one at each call site.

ReadinessGroup beside ReadinessReport is the same shape one level down and is not changed: it predates this branch, and nine call sites build with it rather than read it. Raised as a question on the thread.

An open shape can still be typed

additionalProperties: true generates [k: string]: unknown. That is why the two notificationPreferences aliases outlived the first round: every consumer reads a dynamic key (prefs[notificationKey]?.method), which types as unknown without one. Giving additionalProperties a schema describes the value while leaving the keys open, so a retired notification type still strands no row — and the aliases, the seed copy and four casts all go.

The per-key properties had to go with them. An optional named property includes undefined, which is not assignable to an index signature that does not, so payload-types.ts itself failed pnpm typecheck with TS2411 on all four keys. They validated exactly what the catch-all does, differing only in a description, and requiring the four keys would have fixed the assignability by stranding every row missing one.

The branch head was red before an earlier round

pnpm typecheck failed on c0dbde9 with TS2305. Renaming the canonical-verification schema's $id to a URN renamed the interface Payload generates from it, and src/lib/clients/verification.ts still imported the old name. Fixed in its own commit (86df8c5), since it is unrelated to anything under review. The new name comes from the schema's title, so it is stable against a future $id change.

Preview

Test results

  • Lean gate, re-run on 1bb9610: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (126 files, 1629 tests)
  • Targeted integration specs: ✓ on the first round — lectures (26), sync-lecture-metadata (14), videos (6), meditationFrames, meditation-lectures, collections-smoke, pages, manager-verification, role-based-access, storage-utils — 264 across 12 files. Later rounds could not re-run them: the integration lane needs Postgres and this session has none. CI runs it against its own container.
  • Build: N/A — Railway builds the preview
  • Migration: none, in any round. jsonSchema is field metadata, and a virtual field has no column at all, so nothing reaches drizzle. The alias round changes no field config at all.
  • The alias round adds no assertion. What proves the generated interfaces are usable substitutes is pnpm typecheck passing with the aliases deleted — the four specs that named them were repointed, not weakened.

Every new assertion was confirmed failing first, at the site that causes it:

Defect reintroduced Goes red
jsonSchema dropped from Videos.subtitles 2 cases in json-field-schemas
Managers.notificationPreferences validate replaces instead of composes composes the built-in validator…
Meditations.frames validate replaces instead of composes composes the built-in validator on frames…
additionalProperties: false dropped from Lectures.metadata refuses a key the builder never writes
notificationPreferences.additionalProperties back to true types a retired key without closing it, composes the built-in validator…, and 7 pnpm typecheck errors at the consumer sites
subtleSystemNodeWeights back to type: 'object' pnpm typecheck:tests, on meditation-lectures.int.spec.ts
jsonSchema unwired from all six virtual columns all 6 virtual columns cases
tagAssignments.id widened back to ['integer','string'] types the Meditations virtual join columns — and pnpm typecheck, at useDocumentDrawer
EventQualityReport's oneOf collapsed to one open object keeps both arms of Events.qualityReport discriminated

The frames case needed two attempts. The first version passed with the composition removed, because the value it used ([{id: 1}]) normalizes to zero frames and the custom rule rejects it on its own. It now uses one good entry plus one bad, which only the schema half refuses.

Manual verification

Every column here is admin- or system-written, so the specs cover the write paths. What a browser adds is that the admin still renders and saves them:

  1. Videos → edit a video with subtitles → save. Then paste a cue missing endTimeMs and confirm the save is refused.
  2. Managers → Notifications → set a frequency with no method → the existing "Select a notification method for…" error still appears.
  3. Meditations → Frames → reorder and save; the frame list still renders after the reload. The four tag-assignment panels still list their tags.
  4. Upload an image and a video → fileMetadata shows originalFilename in the sidebar.
  5. Lectures → create one from a Vimeo URL → metadata populates as before.
  6. Events → open a listing → the quality panel and the schedule summary both still render (qualityReport and upcomingDates are the two virtual columns with a visible surface).
  7. Clients → open one with usage → the abuse-score pill still renders in both the list cell and the edit view.

Notes for reviewer

  • logField.ts and translationsField.ts stay untouched. feat(api)!: unify public intakes on the form-submissions pipeline #695 promotes activityLog to every submission type and decides what it declares. feat(translations): typed JSON groups, per-locale publish status, and an availableLocales field gated on published translations #705 derives a schema per leaf group in the other. A schema added here would be a second definition to reconcile at either merge. Both carry a comment saying so, and translationsField.ts's stale "Ajv breaks on Cloudflare Workers" note is corrected in place (Audit custom admin field components: JSON fields without a schema, and hand-rolled type indirection #659's fifth acceptance criterion).
  • Stored shapes stay open; virtual ones are closed. The two rules have the same justification read in opposite directions — see the section above. Only Lectures.metadata's top level is closed among the stored columns, because buildLectureMetadata is its only writer.
  • fileMetadataField no longer takes defaultEmpty — it sets defaultValue: {} for all four collections, per review. ⚠ That needs a migration this session cannot generate: the option maps to a Postgres column default ('{}'::jsonb) that only frames and videos carry today. Flagged rather than hand-written.
  • Managers.notificationPreferences keeps its custom validator, and I was wrong about why. admin.condition does gate server-side validation (beforeChange/promise.js:37), as review said. It still cannot carry this rule: condition gates a field, and frequency/method are two keys inside one json value, so there is no method field to mark required.
  • Payload emits FileMetadata, FileMetadata1, FileMetadata2, FileMetadata3 — one interface per usage of a shared $id, same shape each time. TagAssignments now does the same across its four call sites. Noise in the generated file, not something a factory can avoid.
  • Pre-existing bug found, filed not fixed: SyncLectureMetadata.ts:88 reads where ? `lectureIds[${lectureIds!.length}]` : 'all lectures', and where is always truthy — so the scheduled monthly run, which passes no input, throws a TypeError on its own log line. Two independent reviewers flagged it. It sits two lines from a changed line but predates this branch, so it is fix(jobs): SyncLectureMetadata throws on its own log line when the monthly run passes no input #715.
Adversarial review round — five threads, three adopted

should-fix, the surviving notificationPreferences aliases — acceptance criterion 2 was met for the three lecture/job aliases and not for these. Adopted, with a change to the suggested shape: the typed additionalProperties lands, the per-key properties go, for the TS2411 reason above.

should-fix, six copies of one five-line comment — adopted at all six sites. Each keeps one line: written by the hook below, and where the type lives. The rule's permanent address is src/collections/AGENTS.md.

consider, null missing from two generated types — half adopted, above.

consider, fileMetadataField's defaultEmpty — kept at the time, then removed in the review round when the reviewer asked for the behaviour standardized instead.

consider, deriving subtitlesJsonSchema from Zod — not taken. Checked against this repo's Zod 4.3.5: z.toJSONSchema reproduces this schema only for looseObject. subtitlesZodSchema is z.object, which emits additionalProperties: false — the exact closure 7b0cfa5 reopened by hand — and strips unknown keys on parse, so switching it changes what the Storyblok importer keeps. The two-way agreement spec stays. The Subtitles name collision the thread also raised is real, and left for a follow-up rather than renaming a generated type here.

What the earlier review passes changed

/code-review high and /security-review both ran over the branch. The security pass returned no findings, having read Payload's own json validator, beforeChange/promise.js, and config/sanitize.js to establish that a schema-backed default validator really does run, that fetchSchema never dials sahajcloud.dev when the schema is inline, and that no access or readOnly was dropped by the fileMetadata factory.

The code-review pass found five things, all confirmed against a real Postgres and all fixed in 7b0cfa5:

  1. subtitles narrowed the column. Zod's default object mode ignores an unknown cue key, so a row storing one has always been accepted. additionalProperties: false made such a row fail every later save of its video. Reopened.
  2. Lectures.metadata.subtitles keyed its map on LOCALES, so retiring a locale would strand every lecture still holding a track for it.
  3. notificationPreferences had the same shape, and worse: the field component spreads an unknown key back on save, so the admin could not have cleared it.
  4. Meditations.frames's comment had the hook order backwards — a field's beforeChange hooks run before its validate.
  5. Both job inputSchema comments claimed a runtime check. Payload feeds inputSchema only to generateJobsJSONSchemas.

Nothing was dismissed.

Closes #659

🤖 Written by the sydevs autonomous loop — see what this is

🤖 Generated with Claude Code

https://claude.ai/code/session_01EgER1gbKXnNKyM8qGLvwhV

…a shape

`type: 'json'` with no `jsonSchema` accepts anything a client sends and
generates a type that describes nothing. #659 audited all 36 of them; this
covers the collections #695 does not delete.

Fourteen columns gain a schema, so Payload validates writes with Ajv and
substitutes the shape into `payload-types.ts`:

- `subtitles` x3 (Videos, Lessons x2) — moved from `typescriptSchema` +
  a hand-rolled Zod validator to `jsonSchema`. The validator existed only
  because Ajv's `new Function()` is refused by the Cloudflare Workers
  isolate (#317), and this app has run on Node since. Payload's built-in
  validator skips the same four empty values the old `isEmpty` guard did,
  so nothing about an optional column changed.
- `fileMetadata` x4 (Frames, Images, Songs, Videos) — one shared
  `fileMetadataField()` factory replaces four copies.
- `Lectures.metadata`, `Meditations.frames`,
  `Meditations.subtleSystemNodeWeights`,
  `Managers.notificationPreferences`,
  `TableOfContentsBlock.headings`, and the two job inputs
  (`testDateRange`, `lectureIds`).

Three hand-written aliases go, replaced by the generated type:
`LectureMetadata`, `TestDateRangeInput`, `SyncLectureMetadataInput`.

Eight virtual columns keep no schema and gain a one-line comment instead.
Their value is produced by an `afterRead` hook and never written, so a
schema would validate nothing and restate a type that already exists at
its source — the drift this ticket set out to remove.

Supplying `validate` replaces the built-in validator, which is the thing
that runs the schema. The two columns keeping a custom rule now compose it
rather than shadowing it.

Every property stays optional and most shapes stay open, because Payload
validates a JSON column on every save of its document — including a save
that never touched the column. A `required` key would make a row written
under an earlier shape unsaveable.

`logField` and `translationsField` are deliberately untouched: #695 and
#705 respectively own what those declare, and a second definition here
would have to be reconciled at that merge.

Closes #659

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xrpuq5ibt5qsT8yK8pNMtu
… row

Findings from the branch review, all confirmed against a real Postgres:

- **`subtitles` narrowed the column.** The Zod validator it replaced used
  the default object mode, which ignores an unknown cue key — so a cue
  carrying one has always been accepted and stored. With
  `additionalProperties: false` such a row failed every later save of its
  video, including one touching only the title. The item is open again,
  and the commit message's "nothing about an optional column changed" now
  holds.
- **`Lectures.metadata.subtitles`** keyed its map on `LOCALES`, so
  retiring a locale would strand every lecture still holding a track for
  it — the exact failure the docstring above it says it avoids. The map
  takes any string key now; `apiLanguageToLocale` is what keeps the keys
  valid on write. The top level stays closed: one function writes it.
- **`notificationPreferences`** had the same shape. Retiring a
  notification type would have blocked every save of any manager still
  holding its key, and the field component spreads an unknown key back on
  save, so the admin could not clear it either.

Two comments were wrong rather than the code:

- **`Meditations.frames`** said validation runs before normalization. It
  is the other way round — a field's `beforeChange` hooks run before its
  `validate` — so the normalizer has already reduced every entry by the
  time the schema sees it. The schema types the column; it does not gate
  the save. The composed validator stays, because shadowing the built-in
  is wrong whether or not it currently rejects anything.
- **Both job `inputSchema` blocks** claimed the schema refuses a
  malformed input at enqueue. Payload feeds `inputSchema` only to
  `generateJobsJSONSchemas`, so nothing validates it at runtime.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xrpuq5ibt5qsT8yK8pNMtu
… LectureMetadata

- `src/types/AGENTS.md` said a `jsonSchema` column generates
  `HttpsSahajcloudDevSchemas…Json`. That is the fallback: with a `title`
  Payload names the interface after it.
- `LectureMetadata` was a derived alias re-exported from
  `nirmalaVidya.ts`, which `src/types/AGENTS.md` calls out as giving the
  shape a second home. Its three consumers import the generated interface
  from `@/payload-types` instead.
- `videos.int.spec.ts`'s guard comment named the validator this branch
  removed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xrpuq5ibt5qsT8yK8pNMtu
@sydevs-bot
sydevs-bot requested a review from Ardnived September 5, 2026 22:00
@railway-app

railway-app Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 7, 2026 at 7:10 pm UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

The diff is the right shape for the ticket. 14 schemas, 8 documented exemptions, 2 composed validators, both stale Workers notes corrected, logField.ts and translationsField.ts deliberately left to #695 and #705. Nothing is smuggled in beside the fix, and the one new abstraction — fileMetadataField — has four real callers and drops no access/readOnly.

Where it overshoots is prose, not code. The same five-line rationale is pasted at six virtual-column sites while the rule simultaneously gains a permanent 66-line home in collections/AGENTS.md. The ticket asked for one line each.

Where it undershoots is acceptance criterion 2. Three hand-written aliases went; at least three stayed — NotificationPreference/NotificationPreferencesValue, KeyframeDefinition, and a third copy in seeds/atlas/helpers/managerMapper.ts — with four consumers still casting to them. The generated interfaces as shaped aren't usable substitutes (all-optional plus [k: string]: unknown), which is fixable in the schema. That is the half of #659 the schemas exist to enable, so it is the finding I'd most want answered.

Two things sit just outside the diff:

  • SyncLectureMetadata.ts:88 — I'd fold #715 in here. I confirmed it independently: where is always an object literal, so `lectureIds[${lectureIds!.length}]` always evaluates, and the scheduled monthly run passes no input — a TypeError on the job's first log line, every run. This PR edits line 78, the declaration of that exact variable. A separate PR for Array.isArray(lectureIds) in a ternary you are already standing on costs more than it saves.
  • payload-types.ts is a cross-repo artifact. pnpm types:cms copies it verbatim into WeMeditateWeb, and SahajAtlasWeb vendors it too. I read both consumer sides: nothing breaks. But WeMeditateWeb's lib/lecture-shape.ts:28 hand-parses metadata "Stored untyped on the CMS (metadata is a generic json field), so it is parsed defensively" — which stops being true on its next sync — and it exports its own LectureMetadata interface that will then share a name with the generated one. Worth a line in the PR body, or a follow-up ticket on that repo.

Findings

should-fix Hand-written aliases the ticket required removing still stand, and the generated shapes can be fixed to allow it — NotificationPreferences/config.ts:135
should-fix Six near-identical five-line comments where the ticket asked for one line, now duplicating AGENTS.md — AppCards.ts:534
consider defaultEmpty preserves what looks like an accidental difference between the four call sites — fileMetadataField.ts:25
consider The Zod↔JSON-Schema mirror can be derived: Zod 4.3.5's z.toJSONSchema reproduces this schema exactly (verified) — subtitles.ts:32
consider The generated type drops null, so clearing a column now needs a cast — two were added to specs — frames.ts:83

What was checked

  • Ticket vs diff. #659 as rescoped 2026-09-05, its three comments, and each acceptance criterion against the branch. AC 1, 3, 4, 5 met; AC 2 partially (above); AC 6 verified by confirming no touched column is client-writable.
  • Payload's own behaviour, not the PR's claims about it. payload/dist/fields/validations.js — the json validator's empty-value skip and its new Ajv() per call, which is what makes one $id reused across four fileMetadata fields (and three subtitles fields) safe rather than a duplicate-schema throw. fields/hooks/beforeChange/promise.js — beforeChange hooks at line 58, validate at 86 (the frames note is right), and ...field spread into the validate options, which is what makes the composed jsonFieldValidation(value, options) actually see jsonSchema.
  • The closed shapes, against their writers. Lectures.metadata — grepped every writer; only buildLectureMetadata, via the create hook and the sync task. The seeds read metadata but never write it. Managers.notificationPreferences — all three writers (buildDefaultNotificationPreferences, the field component's updateRow, seeds/atlas/helpers/managerMapper.ts) emit strings for both inner keys, so no existing row is stranded by the inner additionalProperties: false.
  • Consumer sides. WeMeditateWeb lib/lecture-shape.ts, server/cms-client.ts, scripts/strip-payload-augmentation.mjs; SahajAtlasWeb src/types/payload/payload-types.ts (grepped for fileMetadata/subtitles/metadata usage — none). SahajAtlasWordpress consumes endpoint response types, untouched here.
  • Ran locally. z.toJSONSchema against this repo's Zod 4.3.5, to check the claim in the subtitles.ts comment before making it.
  • Read whole. fileMetadataField.ts, subtitles.ts, nirmalaVidya.ts, frames.ts, NotificationPreferences/config.ts + NotificationPreferencesField.tsx, lectureShape.ts, SyncLectureMetadata.ts, types/frames.ts, tests/unit/json-field-schemas.spec.ts, and the full payload-types.ts diff.
  • Not re-reviewed: style, naming, and test volume — the author-side pass owns those, and the five defects it already found and fixed in 7b0cfa5 are not re-litigated here.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread src/collections/AppCards/AppCards.ts Resolved
Comment thread src/fields/fileMetadataField.ts Resolved
Comment thread src/lib/utilities/subtitles.ts Resolved
Comment thread src/lib/meditations/frames.ts Resolved
web-flow and others added 2 commits September 5, 2026 23:17
…le asks for

The same five-line rationale was pasted at six virtual-column sites while the
rule itself gained a permanent home in `src/collections/AGENTS.md`. That is ~30
lines restating a rule that now has an address, and the closing clause named a
ticket that will read as archaeology once #659 closes.

Each site keeps what is local to it: that the value is written by the hook below,
and where its type already lives.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BjaSLP2jrYDcRtbqxnsVf8
…ree copies of its shape

#659's second acceptance criterion asked for no hand-written alias where the
schema now generates one. `NotificationPreference` /
`NotificationPreferencesValue` survived it, plus a third copy in the Atlas seed
mapper, because `additionalProperties: true` generates `[k: string]: unknown` —
so every consumer reading `prefs[key]?.method` needed an alias to cast to.

Giving `additionalProperties` a schema instead types the value while leaving the
keys open, so a retired notification type still strands no row. That deletes the
two aliases, the seed copy, and four consumer casts.

The per-key `properties` had to go with them: an optional named property
includes `undefined`, which is not assignable to an index signature that does
not, so `payload-types.ts` itself failed `tsc` with TS2411. They validated
exactly what the catch-all does, differing only in a description, and requiring
the four keys would have stranded every row missing one.

`meditationNodeWeightsFieldSchema` also declares `type: ['object', 'null']`,
which puts `null` back into the generated type and removes the `as never` a
spec needed to clear the column. It works only where a schema has no
`properties`; on `notificationPreferencesJsonSchema` `generate:types` emits
`X & (X | null)`, which is `X` again. Both facts are now in
`src/collections/AGENTS.md`.

Confirmed failing first: reverting `additionalProperties` to `true` gives 7
`pnpm typecheck` errors at the consumer sites and turns two
`json-field-schemas` cases red; reverting the node-weights type turns
`pnpm typecheck:tests` red on `meditation-lectures.int.spec.ts`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BjaSLP2jrYDcRtbqxnsVf8
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-714 September 5, 2026 23:17 Destroyed
@sydevs-bot sydevs-bot changed the title Audit custom admin field components: JSON fields without a schema, and hand-rolled type indirection refactor(fields): declare a jsonSchema on every JSON column, and delete the aliases they replace Sep 5, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Revised. Three of the five review threads applied and resolved. Two answered, left open for you.

Applied. notificationPreferences gives additionalProperties a schema instead of true, so the keys stay open and the value is typed. That deletes both aliases, a third copy in the Atlas seed mapper, and all four consumer casts — acceptance criterion 2 of #659, which the first round missed. The per-key properties went with them: an optional named property carries undefined, so payload-types.ts failed tsc with TS2411. subtleSystemNodeWeights declares type: ['object', 'null'], deleting a spec's as never. The six virtual-column comments are one line each.

Left open. defaultEmpty stays — unifying it changes what two collections write on create. subtitlesJsonSchema is not derived from Zod: z.toJSONSchema matches only for looseObject.

Gate green: lint, typecheck, typecheck:tests, test:unit (1611 tests). The integration lane needs a Postgres this session lacks — CI runs it.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread seeds/atlas/helpers/managerMapper.ts Resolved
Comment thread src/collections/AppCards/AppCards.ts Resolved
Comment thread src/collections/Clients/Clients.ts Resolved
Comment thread src/collections/Events/Events.ts Resolved
Comment thread src/collections/Frames/Frames.ts Resolved
Comment thread src/lib/meditations/frames.ts Resolved
Comment thread src/lib/meditations/frames.ts Resolved
Comment thread src/lib/status/virtualReadinessField.ts Resolved
@github-project-automation github-project-automation Bot moved this from In progress to Changes requested in SYDevelopers Technical Roadmap Sep 6, 2026
@Ardnived Ardnived removed the awaiting label Sep 6, 2026
claude and others added 2 commits September 6, 2026 18:06
…he fileMetadata default

Review round on #714.

- Every `$id`/`uri` moves from `https://sahajcloud.dev/schemas/<x>.json`, a
  domain nobody owns, to `urn:sahajcloud:schema:<x>`. Nothing fetches these:
  Payload registers the schema object inline and uses `uri` only as the Monaco
  model id. A URN says that, an https URL implies a document that does not
  exist.
- Two schemas carried no `title`, so Payload named their generated interfaces
  after the `$id` — `HttpsSahajcloudDevSchemasEventSystemMetaJson`. Adding
  `title` to `canonicalVerificationJsonSchema`, the embed-metadata schema and
  `systemMetaField` keeps `payload-types.ts` byte-identical through the URI
  change, and removes the last place a URL leaked into a type name.
- `fileMetadataField`'s `defaultEmpty` option is gone. All four upload
  collections now default the column to `{}`.
- `managerMapper.ts` no longer re-exports `NotificationPreferences`. Its one
  consumer imports it from `@/payload-types` directly.
- Both job input schemas move out of the `inputSchema` literal into named
  `*JsonSchema` consts, matching `lectureMetadataFieldSchema`.

Lean gate green: lint, typecheck, typecheck:tests, test:unit (126 files,
1623 tests). `pnpm generate:types` leaves `payload-types.ts` unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CkfqNbPusAZTtA3wwo45KV
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-714 September 6, 2026 18:14 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Pushed c0dbde9, with origin/main merged in — #711 and #712 landed while this sat, and tests/COVERAGE.md conflicted.

Applied. sahajcloud.dev is gone from every $id, uri and fileMatch — all urn:sahajcloud:schema:<name> now. Two schemas had no title, so Payload named their interfaces off the $id; adding one keeps payload-types.ts byte-identical through the change. defaultEmpty is gone, all four collections default to {}. No type re-export in managerMapper.ts. Both job schemas are named consts.

Declined, reasons on the threads. uri/fileMatch are mandatory in Payload's jsonSchema type. admin.condition gates admin visibility, not writes. The lecture schema stays beside its builder.

Three need you. Six virtual JSON fields really are untyped — fold their schemas in, or a follow-up? defaultValue: {} implies a column default images and songs lack, and this session has no Postgres to generate it. And src/fields/index.ts exports no type — which did you mean?

Lean gate green.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@Ardnived Ardnived removed the awaiting label Sep 7, 2026
#720 and #717 landed on main while this PR was open. #720 rewrote the
scope derivation in SyncLectureMetadata.ts, a few lines from this
branch's own edits to the same file.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017yU3grG7LTeRqSccKfdm91

# Conflicts:
#	src/jobs/SyncLectureMetadata/SyncLectureMetadata.ts
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-714 September 7, 2026 16:12 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged origin/main in — #720 and #717 landed. 8184993.

One conflict, in SyncLectureMetadata.ts: #720 rewrote the scope derivation a few lines from this branch's edit to the same block. Resolved by keeping both — this branch's typed input?.lectureIds, and #720's single scopedIds. The comment on line 52 already anticipates the Array.isArray test, so the two fit.

Gate green after the merge: lint, typecheck, typecheck:tests, 1629 unit tests, and tests/int/sync-lecture-metadata.int.spec.ts 9/9. Postgres was reachable this run.

Three threads still wait on you, each last-worded by me: subtitles.ts:32 (deriving the mirror from Zod — declined, reason on the thread), Managers.ts:249 (admin.condition), frames.ts:61. Labelled awaiting.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@Ardnived

Ardnived commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

@sydevs-bot I've addressed the outstanding issues. Go ahead and merge

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The gate needs an approving review, not a comment. #714 is still held.

You wrote "go ahead and merge". The gate reads reviews, not comments. Your last review here is CHANGES_REQUESTED, submitted 2026-09-06T17:51Z on 4460c5e. So merge-verdict.mjs returns HOLD — no approving review (CHANGES_REQUESTED).

Nothing else blocks it:

  • CI is green on 8184993 — Lint, Test & Smoke, state, and the Railway deploy.
  • All 36 review threads are resolved. You resolved the last three.
  • No conflict. mergeable_state: clean.

Press Approve and the next run merges it. Only your approval counts. Four repos here are public, so any account can submit a review, and the gate allowlists you alone.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Brings #727 (per-lecture userChoices in the /for-audience feed) onto this
branch after its squash-merge, so the next review round reads current code.

One conflict, in `src/lib/lectures/lectureShape.ts`: both sides rewrote the
`@/payload-types` import. This branch adds `LectureMetadata` (the generated
interface it exists to adopt); main adds `UserChoice` and the `FeedUserChoice`
alias. Both are kept — the two changes are additive and independent.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XmzSzbuPBtmPwBnsFuaoPk
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-714 September 7, 2026 19:08 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Merged origin/main in — #727 landed. 1ba036b. Still held on the same thing as 17:07: only your Approve clears it.

One conflict, in src/lib/lectures/lectureShape.ts. Both sides rewrote the @/payload-types import line: this branch adds LectureMetadata (the generated interface it exists to adopt), #727 adds UserChoice and its FeedUserChoice alias. Kept both — the changes are additive and independent, and nothing else in the file overlapped.

A plain rebase was not used. This branch carries two earlier merges from main, so flattening them replayed old resolutions and conflicted in three files that no longer disagree.

Gate green after the merge: lint, typecheck, typecheck:tests, 1641 unit tests, plus lectures-for-audience, meditation-lectures and sync-lecture-metadata integration specs, 89/89.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@Ardnived

Ardnived commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

@sydevs-bot I have already approved this PR multiple times

@Ardnived
Ardnived merged commit 5b288c0 into main Sep 7, 2026
2 of 3 checks passed
@github-project-automation github-project-automation Bot moved this from Changes requested to Done in SYDevelopers Technical Roadmap Sep 7, 2026
@Ardnived Ardnived removed the awaiting label Sep 7, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The red check here is not this PR — do not let it hold the approval.

Lint, Test & Smoke failed at 19:22 on the e2e lane. This PR's preview host returns 404 for every path, / included, so the specs cannot log in. Production answers 200, and #728's preview 404s identically on a completely unrelated diff. Details and the probe table are on #728.

Nothing about this branch changed the result: the merge commit 1ba036b is #727 plus one import-line resolution, and lint, typecheck and both test lanes passed locally.

Still the same ask as 17:07. All 36 threads resolved, no conflict, and only your Approve moves it. The e2e lane needs a re-run once Railway previews serve again.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

sydevs-bot added a commit that referenced this pull request Sep 8, 2026
… an availableLocales field gated on published translations (#731)

* refactor(translations): move the schema walker and plural family into src/lib/translations

Three owners now read the same schema-to-data-path mapping, so it stops
being one owner's private helper:

- `pluralCategories.ts` holds `PLURAL_CATEGORIES` (re-exported from
  `@/fields/translationsField`, so existing importers and its spec keep
  working) plus `pluralStorageKeys`, the expansion the field builder and
  the English merge both need.
- `schemaWalker.ts` takes `collectLeafLookups` and `extractPlainText` out
  of `WeMeditateAppStatus/sections/translations.ts`, and adds an
  `expandPlurals` option. The status report asks about one declared key;
  the English merge asks about the keys actually stored.
- `availableLocales.ts` and `clientEnglishFallback.ts` are new, and are
  consumed by the two commits that follow.

The failure this prevents: a second copy of the nesting rules drifting
from the field builder's. The status report already encoded them, and the
English merge needs exactly the same answer — a `<tab>_<sub>` column, a
JSON blob keyed by leaf key — for a different question.

`clientEnglishFallback` fills blank keys from English for API-client reads
only. Payload's locale fallback is per field, not per key, so a locale
with any translation at all returns a blob missing everything untranslated,
and each consumer repo would otherwise carry the same merge.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* feat(fields): declare a jsonSchema on every translations group, and make a strict maxLength block

Each leaf group's JSON column now carries a `jsonSchema`, so Payload
generates a named interface per group instead of the
`{ [k: string]: unknown } | … | null` union every consumer had to cast
away, and Ajv enforces the shape on write.

- `stringsJsonSchema` builds one schema per leaf group: plural keys
  expanded to their CLDR family, every property optional, per-key
  `description` kept (it becomes JSDoc), `additionalProperties` from the
  group. Title is `<Global><Parent><Leaf>Strings`, uri under
  `https://sahajcloud.dev/schemas/translations/`.
- The hand-rolled `validate` goes. Supplying one *replaces* Payload's
  built-in `json` validator; leaving it undefined installs that validator
  bound to the schema, which enforces exactly what the function did.
- `strict: true` beside a `maxLength` emits the limit into the schema, so
  the save is refused. `lengthStatus` gains `blocking`, and the row
  renders `ErrorIcon` plus "over the limit, this will not save".
- Sub-groups render as collapsibles, not inner tabs. Tabs inside tabs hide
  every sub-group but one, which is the wrong shape for a translator
  working down a page.

Three failures this prevents. A consumer casting a translations blob and
getting the cast wrong, silently. An over-length `strict` string saving
and breaking a layout, because the limit was advisory everywhere. And a
translator not finding a sub-group at all, because it sat behind a second
tab row.

Every property stays optional on purpose: Payload validates a stored
column on every save of its document, so a `required` key would strand
every locale not yet translated. `maxLength` is emitted only for a
`strict` key for the same reason — an advisory limit that suddenly blocked
would break keys already over it.

Only standard JSON Schema keywords may appear. Payload runs Ajv 8 in
strict mode, where an unknown keyword throws at validate time rather than
at boot, so `plural`, `screenshot` and `strict` must never leak in.

The collapsible change is presentational only: the data path and the
column name are `<tab>_<sub>` either way, so `wm-app-translations` reads
and saves as before and no migration is involved.

The two new `blocking` assertions were confirmed failing first, with
`blocking` forced to `false` at its own return site.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* feat(translations): per-locale publish status, and an availableLocales field gated on it

Two config globals now carry `availableLocales` — the set of languages the
project is offered in — and a locale can only be selected once that
project's translations are published in it.

- `experimental.localizeStatus` on the config root, plus
  `versions.drafts.localizeStatus` on `sy-atlas-translations` and
  `wm-web-translations`. `_status` becomes a localized column, so
  "published in French" is a fact the CMS can answer.
  `wm-app-translations` keeps `drafts: true` and one status for everything.
- `availableLocalesField({ translationsSlug, surface })` composes Payload's
  built-in `select` validator, then requires `en`, then reads the
  translations global once per request at `locale: 'all'` and rejects any
  selected locale whose status is not `published`.
- Both translations globals gain the `clientEnglishFallback` afterRead
  hook, so an API client reading a partially translated locale gets
  English for the blanks.
- `sy-atlas-config.languages` is replaced by the new field, and
  `src/lib/atlas/defaultLocales.ts` is deleted with it.

The failure this prevents: an operator offering a language whose
translations do not exist. `hreflang` then tells a crawler that language
has a page, the widget renders English, and nothing in the CMS could have
said no. `languages` was an unvalidated list of locale codes.

Two behaviour changes worth naming:

- **An unconfigured row now answers `['en']`, not the ten launch
  locales.** `ATLAS_DEFAULT_LOCALES` existed because a `defaultValue` does
  not backfill an existing row, and production's does exist. Keeping that
  fallback would promise a crawler nine languages before an operator said
  any of them were translated — the exact promise this field exists to
  stop. The atlas-seo spec asserts the new default rather than the old
  count.
- **`locale: 'all'` is load-bearing in the validator.** A single-locale
  read of an untranslated locale resolves `_status` through the English
  fallback and reports it published. The raw per-locale map cannot.

`skipAvailableLocalesCheck` on `req.context` relaxes only the publish
check, for local-API seeds and specs that create a config row before
anything is published. `en` stays required with it set.

`unpublishedLocales` also accepts a plain string `_status`, so the field
stays reusable on a global that has not opted into `localizeStatus`.

`tests/unit/atlas-locales.spec.ts` is replaced by
`tests/unit/available-locales.spec.ts` in the commit that adds it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* test(translations): cover the emitted jsonSchema, the publish gate and the English merge

Four new or rewritten suites, split by what each can actually prove:

- `tests/unit/available-locales.spec.ts` replaces `atlas-locales.spec.ts`.
  It covers `parseAvailableLocales`/`readAvailableLocales` and
  `unpublishedLocales` — including the new `['en']` default for an
  unconfigured column, which is the behaviour change #705 makes.
- `tests/unit/client-english-fallback.spec.ts` enumerates the four shapes
  of "blank", and the one case that must NOT be filled: a field the
  caller's `select` stripped.
- `translations-field.int.spec.ts` swaps its `validate` block for a
  `jsonSchema` block — the emitted schema's properties, its absent
  `required`, `additionalProperties`, `maxLength` only for `strict`, the
  interface title, and that no non-standard keyword leaks in. It also
  asserts collapsibles instead of an inner tabs row, and that `a11y`
  starts collapsed.
- `available-locales.int.spec.ts` is new: the English invariant, the
  publish gate refusing and then accepting, the message naming every
  unpublished locale, `skipAvailableLocalesCheck` relaxing only the
  publish check, the wm-web field gating on its own global, and the
  English merge reaching an API client but not a manager.
- `translations-globals.int.spec.ts` gains `localizeStatus` on/off per
  global, a per-locale publish, and three writes that prove the JSON
  column enforces its own schema.
- `testHelpers.ts` mirrors `experimental.localizeStatus`. Without it every
  suite would silently run the two web globals with one status for all
  locales, and every publish-gating assertion would pass for the wrong
  reason.

Every new assertion was confirmed failing first, at the site that causes
it:

| Defect reintroduced | Goes red |
| --- | --- |
| `blocking` forced to `false` in `lengthStatus` | 2 cases in `length-status` |
| the `['en']` fallback dropped from `readAvailableLocales` | `answers English alone for an unconfigured column` |
| the `Object.hasOwn` guard dropped from `mergeEnglish` | `never re-adds a field the document does not have` |
| `expandPlurals: false` in `schemaLookups` | 2 cases in `client-english-fallback` |
| an absent locale read as published in `unpublishedLocales` | `treats a locale absent from the map as unpublished` |
| `jsonSchema` unwired from the JSON field | 2 write-rejection cases in `translations-globals` |
| the `afterRead` hook removed from the atlas global | `fills a blank key from English for an API client` |
| `readPublishStatus` reading one locale instead of `'all'` | 3 publish-gate cases |

The last row is the one worth keeping. A single-locale read resolves
`_status` through the English fallback, so an untranslated locale reports
itself published and the gate opens for everything.

Two shapes the specs deliberately do not assert. Ajv is not a top-level
dependency here, so the schema's *enforcement* is proven by real writes in
the integration lane rather than by compiling the schema in a unit test.
And `wm-web-config` has four other required fields, so the positive case
there asserts that `availableLocales` stops objecting, not that the write
succeeds — filling in a home page and two page lists would test Payload's
`required`, not this field.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* chore(migrations): move translations _status into _locales, and swap languages for availableLocales

Generated by `payload.db.createMigration`, answering **create** at every
drizzle prompt. A "rename" would have carried
`sy_atlas_config_languages`' old `{ code }` rows into
`availableLocales`, whose stored shape is a bare locale code.

What it does:

- creates `sy_atlas_config_available_locales` and
  `wm_web_config_available_locales` (+ their enums), and drops
  `sy_atlas_config_languages` (+ its enum);
- moves `_status` / `version__status` for both web-project translations
  globals from the base tables into their `_locales` tables, with the
  matching indexes.

⚠ **Every locale lands as `draft`.** `ADD COLUMN "_status" … DEFAULT
'draft'` cannot know which locales were published before, and the old
column held one value for all of them. Operators publish each locale
after the seed, which the rollout requires anyway.

Payload's own `localizeStatus.up` data migration is deliberately not used:
it cannot coexist with the generated DDL, it takes its locale list from
`filterAvailableLocales({ req })` — `['en']` for a user-less migration
`req` — and it leaves `VARCHAR` columns without the index the snapshot
expects.

**Two lines here are not this ticket's.** `ALTER TABLE "songs" /
"images" ALTER COLUMN "file_metadata" SET DEFAULT '{}'::jsonb` is the
catch-up #714 flagged and could not generate ("that needs a migration this
session cannot generate"). Drizzle diffs against the snapshot, so the next
migration on this branch necessarily carries it, and hand-editing a
generated migration is not allowed. It is safe on its own terms: a column
default affects future inserts only, and `frames` and `videos` already
carry it.

Verified on a scratch database built from `origin/main`'s schema with rows
in `sy_atlas_config_languages`, not only on a clean one: `payload migrate`
applies, the old table is gone, `_status` is on the `_locales` tables and
off the base tables, and `payload migrate:down` puts all three back.
`migration-validator`: 4 pass, 0 fail, 3 warnings — the two DROP warnings
are the intended replacement and the intended `_status` move, and the D1
foreign-key warning predates the move to Postgres.

`src/payload-types.ts` is regenerated for all three preceding commits: a
named `…Strings` interface per translations group (114 of them, no
collisions), `availableLocales` on both config globals, `languages` gone.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* docs(translations): record the jsonSchema rule, the publish gate and the English merge

- `src/globals/AGENTS.md` — rewrites the config-globals section around
  `availableLocales` (both invariants, why `locale: 'all'` is load-bearing,
  what `skipAvailableLocalesCheck` relaxes, and why an unconfigured column
  answers `['en']`), and adds three sections to the translations part: the
  JSON column declaring its own shape (never give one a `validate`),
  sub-groups as collapsibles, and `strict` beside `maxLength`.
- `docs/architecture.md` — the atlas `alternates` set is now
  `availableLocales`, and is gated on published translations.
- `docs/rules/email.md` — says why `EMAIL_STRING_DEFAULTS` stays even
  though the CMS merges English now: the hook only fires for a `clients`
  read, and `resolveEmailStrings` is not one.
- `tests/COVERAGE.md` — rows for the emitted schema, the publish gate and
  the merge; the deleted `atlas-locales.spec.ts` is replaced by
  `available-locales.spec.ts`.

The failure this prevents is the next author giving one of these JSON
fields a `validate` again. That silently replaces the validator bound to
`jsonSchema`, and every shape check stops running with nothing to show for
it — which is exactly how the field arrived in this state.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* fix(translations): exempt English from the publish gate, and restore the array check

Three defects the review pass found, each verified by reintroducing it:

**1. The publish gate deadlocked English against itself.** Payload merges a
field's stored value into its sibling data and validates it on *every* save
of the global, not only when someone edits that field. The migration lands
every locale as `draft`. So on the deploy that ships this field, both config
globals would have been unsaveable — with an error telling the operator to
publish the one locale they cannot deselect. English is mandatory rather
than chosen, and every other locale falls back to it, so gating it buys
nothing. It is now exempt; every other locale is gated exactly as before.

**2. Dropping the hand-written `validate` newly accepted `[]`.** Payload's
built-in `json` validator short-circuits on an "empty" value, and an empty
array counts as empty, so the schema never saw it — an array could land in a
column whose generated type is an object. The field now **composes** the
built-in (the same pattern `Managers` and `Meditations` use) rather than
going without: one array check, then delegate. Replacing it outright is what
would switch the schema off, so the rule in `src/globals/AGENTS.md` is
restated as "compose, never replace".

**3. `mergeEnglish` wrote through into the caller's nested groups.**
`{ ...doc }` is one level deep, so a nested group's object was shared with
the input and the "does not mutate" claim held only at the top level — which
is why the existing spec passed either way. Groups are now cloned lazily on
first write.

Also here, all from the same cause as (1) — a newly `required` field refuses
a partial write that never mentions it:

- `seeds/wemeditate/import.ts` carries the stored value through, or seeds
  English, which is what `readAvailableLocales` already answers for an
  unconfigured row.
- `atlas-sitemap.int.spec.ts` and `region-canonical-url.int.spec.ts` supply
  the field on their `canonicalFallbackClient` writes.

| Defect reintroduced | Goes red |
| --- | --- |
| the `DEFAULT_LOCALE` exemption removed | 5 cases in `available-locales` |
| the array check dropped, delegating only | 2 cases in `translations-field` + `translations-globals` |
| the nested group shared instead of cloned | `does not mutate a nested group…` |

Verified green after: the full integration lane, 73 files / 1194 tests.
⚠ It needs `VITEST_INT_MAX_FORKS=2` on a 4-CPU box — the default of 6 gives
nondeterministic failures across unrelated suites.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013Yeh5CnyHkXr2HZguigryi

* perf(translations): narrow the availableLocales publish read to _status

The ticket specified `select: { _status: true }` on the gate's read and
named one fallback for dropping it. The fallback never fired, and the
`select` went anyway, so the gate pulled every translations JSON column in
every locale — 12 columns x 19 locale rows on `sy-atlas-translations` — to
answer a question about `_status` alone.

The width matters because the read is not only on save. `@payloadcms/ui`'s
`addFieldStatePromise` calls a field's `validate` with `event: 'onChange'`,
so the admin repeats this on every form-state rebuild of `sy-atlas-config`
and `wm-web-config`. Without the `select` that is a full localized read of
the largest global per interaction.

`select` composes with `locale: 'all'` — the publish-gate cases in
`available-locales.int.spec.ts` still distinguish a published locale from an
unpublished one, which they could not if `_status` came back empty.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ABp2XiB7GQSFE8jVPWR65J

* refactor(fields): drop the exports this PR added with no importer

Three dead surfaces, all introduced by this branch:

- `PLURAL_CATEGORIES` was re-exported from `translationsField` for
  back-compat, and its one importer was `translations-field.int.spec.ts` —
  a file this branch rewrites wholesale. The spec now imports the constant
  from its home, and the alias goes.
- `stringsJsonSchema` left the `@/fields` barrel. It has no importer outside
  `translationsField.ts` itself; the specs read the emitted schema off the
  built field instead, which tests the wiring rather than the helper.
  `availableLocalesField` stays in the barrel — the ticket asked for it.
- The re-export's docstring claimed three owners read the constant. Two do:
  the field builder and the schema walker. The email resolver derives the
  category from `Intl.PluralRules` and shares only the naming convention, so
  `pluralCategories.ts` now says that instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ABp2XiB7GQSFE8jVPWR65J

* test(translations): read both config globals over REST, as the ticket asked

#705 lists a REST read of `/api/globals/sy-atlas-config` and
`/api/globals/wm-web-config` via `createRestClient` among its acceptance
criteria. It did not ship, and was not on the manual-verification list
either, so nothing recorded that the criterion was open.

It is worth having rather than waiving. The `languages` -> `locales`
collision this field replaces was a read-time Drizzle failure: the config
compiled, the local API was never reached, and only a REST read surfaced it.
Both config globals gain a sub-table here, so the same class of failure is
in range.

The atlas case asserts the stored set comes back, not merely a 200 — an
assertion that only checked the status would pass against a global that
dropped the column. Confirmed by setting a different set and watching it go
red. The We Meditate case reads the global unconfigured, which is what
production looks like on this deploy.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ABp2XiB7GQSFE8jVPWR65J

* refactor(fields): simplify availableLocalesField, and drop the surface option

Answers both open review threads on #731.

`surface` existed only to interpolate a default `admin.description`. The
atlas call site already passed its own description, so the option was dead
there; the We Meditate one now passes its own too, naming that surface's
consumers the way the atlas one does. Generic help text was the weaker
half of the pair anyway — it could not say what the field drives.

Three other pieces of scaffolding go with it:

- `memoKey()` wrapped one template string, called once. Inlined, with the
  by-slug reason kept as a line where the key is built.
- the two error-message shapes collapse to one. "Publish the French
  translations before offering them." reads the same for one locale and
  for several, so the `missing.length === 1` branch bought nothing.
- `description` is now required rather than optional, which is what
  removing the default makes it.

No behaviour changes. The gate, the English exemption, the per-request
memo and the skip flag are untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014xMzPr9e342pbCm5toSJFH

---------

Co-authored-by: Claude <[email protected]>
sydevs-bot added a commit that referenced this pull request Sep 12, 2026
* feat(fields): derive a JSON column's schema metadata from its title

Payload's `jsonSchema` is `{ uri, fileMatch, schema }`, and every hand-written
site repeated one string three or four times — an exported `*_SCHEMA_URI`,
`fileMatch: [URI]`, `$id: URI`, plus a `title` restating it in PascalCase. No
URI is referenced for its own sake: Payload needs `uri` only non-empty, and
Monaco only needs it unique. So all four now derive from the title, which is
the only name that matters — it is what the generated interface is called.

Two overloads. Zod, so a column's shape can be declared inline at the field
that declares it; and raw `JSONSchema4` for what Zod cannot say.

Two hazards the helper exists to close, both measured against this repo's own
[email protected] rather than assumed:

- `z.toJSONSchema` emits `$schema`, and Ajv 8 resolves it as a meta-schema
  reference it does not carry — `no schema with key or ref
  "…draft-04/schema#"`. That throws on every save of a schema-bearing column,
  so it breaks writes rather than validation. Deleting it is what makes the
  output usable. `draft-07` does not throw but emits `const`/`propertyNames`,
  which drift from the rest of the tree.
- `z.int()` emits the safe-integer bounds as `minimum`/`maximum`. Harmless,
  but noise in the schema a reader opens in Monaco. `z.number().int()` emits
  them too, so an `override` hook is the only way to be rid of them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E2vsDPxnBrrxTkKYCGc2yh

* refactor(fields): build every jsonSchema through the helper

All 21 sites in one pass — the 15 from #714, the 5 that predate it, and
`systemMetaField`, whose caller-supplied `uri` becomes a title so it is the
general helper's special case rather than a parallel implementation.
`stringsJsonSchema` goes with them, which retires the last URI literal
(`https://sahajcloud.dev/schemas/translations`). Leaving any of them on the
old shape is the inconsistency this set out to fix.

No `*_SCHEMA_URI` is exported from `src/` any more, no `jsonSchema: {` literal
remains, and exactly one URI literal survives — the prefix inside the helper.
Sixteen sites now declare their shape in Zod, inline at the field. Five keep a
raw schema, each with a one-line reason: `maxProperties` and bare `enum`s
spliced from const arrays have no Zod equivalent.

Verified rather than assumed, by dumping every `jsonSchema` the config
declares on both `main` and this branch and diffing them. The only semantic
changes are four equivalent idiom shifts, none of which alters what Ajv
accepts: `oneOf` -> `anyOf` on branches that are closed and discriminated, so
at most one can ever match; `additionalProperties: true` -> `{}`;
`type: ['integer','string']` -> `anyOf`; `type: ['object','null']` ->
`anyOf`. The rest is URIs, which nothing dereferences.

`payload-types.ts` moves in exactly one way, and it is the ticket's
"expect a real diff" case: `Registration.questions`,
`UserMessage.screeningResult` and `UserMessage.context` had a `$id` but no
`title`, so their shapes were inlined. Given titles, they become named
interfaces with byte-identical bodies. Every other generated shape — the
sixteen Zod conversions included — is unchanged.

The four `HttpsSahajcloudDev…Json` renames the ticket predicted do not
appear: #714 had already migrated those five schemas to `urn:`.

Test URI assertions repoint at `jsonSchema.schema.title`, so nothing is
exported solely for a test. The new spec covers what the helper makes
impossible: a `$schema` reaching Ajv, and two shapes colliding on one derived
URI. Each new assertion was watched failing against its reintroduced defect.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E2vsDPxnBrrxTkKYCGc2yh

* docs: describe jsonFieldSchema as the one way to declare a JSON column's shape

Both guides described the hand-written triple the helper replaces, so a reader
following them would reintroduce it. `src/collections/AGENTS.md` now leads with
the helper, states which Zod idiom emits which JSON Schema keyword, and names
the two hazards (`$schema` reaching Ajv, two shapes colliding on one title)
with the spec that catches each. `src/types/AGENTS.md` gains the corollary: a
Zod type used this way types the column, so `z.infer` of it would be a second
definition — read the shape off `@/payload-types` as for any other column.

Two smaller corrections the refactor makes: the union bullet said `oneOf` where
`z.union` emits `anyOf`, which accepts identically on closed discriminated
branches; and the `HttpsSahajcloudDev…Json` fallback no longer exists, since
every schema now carries a title.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E2vsDPxnBrrxTkKYCGc2yh

* fix(fields): target draft-7, and keep zod out of the admin client bundle

Six findings from the review pass, three of them defects the refactor
introduced.

**The emission target was chosen from a type name, not from the runtime.**
`draft-04` was picked because `JSONSchema4` names it — but that type never
reaches a validator. Ajv 8 is what compiles the schema, it implements draft-07,
and it carries no draft-04 meta-schema. The two spell exclusive bounds
differently, and only one compiles:

    draft-04  z.number().positive() -> { minimum: 0, exclusiveMinimum: true }
              Ajv: schema is invalid: data/exclusiveMinimum must be number
    draft-7   z.number().positive() -> { exclusiveMinimum: 0 }          ok

So draft-04 handed the next author a column that fails every save the first
time they wrote `.positive()`, `.gt()` or `.lt()`, naming a keyword nobody
typed. Measured against this repo's [email protected]. The two forms draft-07 changes
for shapes already here are no-ops — `const` for a one-element `enum`, and
`propertyNames: {type:'string'}` on a record, since every JSON key is a string
— and `payload-types.ts` regenerates byte-identically either way.

**Two schemas were shipping zod to the browser.** Declaring a `jsonSchema`
pulls zod and a `toJSONSchema` call into whatever chunk the module lands in.
`verification.ts` and `NotificationPreferences/config.ts` are both value-imported
by `'use client'` admin components, and neither reached zod before — config.ts
had no runtime imports at all. Both schemas now sit at their fields, in
`Clients.ts` and `Managers.ts`, which is where this ticket's own rule says a
schema belongs. Each module carries a note saying why it must stay light.

**Three claims in the prose were false, and prose is what the next person
copies.** `$schema` does not break Ajv under draft-07 — that was true of
draft-04 only, so it is now stated as tidiness rather than necessity, and the
test that asserted it (passing only because it injected the draft-04 string)
is replaced by one pinning the target itself. `.nullable()` does not produce
`X & (X | null)`; that pathology belonged to `type: ['object','null']`, and
Zod's `anyOf` generates a clean `X | null`. And the escape hatch is not "what
Zod cannot express" — Zod reaches `maxProperties` via `.meta()`, and its enum
and nullable forms generate the same TypeScript. The honest criterion is that
the shape is assembled as data, which covers all five holdouts and does not
decay.

Also: `kebabCase` was `toKebabCase` from `payload/shared` rewritten — identical
output on all 23 titles in the tree, so the copy and its test are gone;
`stripSafeIntegerBounds` is not cosmetic as claimed, since Ajv enforces those
bounds and keeping them would narrow an integer column that accepts 1e21 today;
the unused barrel export and two unused Zod exports are dropped; the block
walker in the spec now reaches `TableOfContentsHeadings`, which hangs off a
Lexical editor rather than a field, and tolerates a Payload 3 `blockReferences`
slug; and a JSDoc block orphaned by a deleted constant is back on the factory
it documents.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01E2vsDPxnBrrxTkKYCGc2yh

* fix(tests): name what the $schema case pins

The case read "emits no $schema, so Ajv can compile the result". The helper's
own doc denies that causality, and the measurement agrees: with the delete
removed, both runSchema calls still pass and payload-types.ts regenerates
byte-identically. Only the toBeUndefined assertion reddens.

So the name claimed a necessity the delete does not have. Rename it to the
consistency property it does pin — a raw-overload schema carries no $schema,
so neither may a Zod one — and record the measurement beside both the case and
fromZod, so the next reader does not re-derive it.

The assertion itself is unchanged and still falsifying; the PR body's claim
that it was watched failing holds.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWnNG5pRL6QCiYMgUoSHXm

* fix(collections): move the notificationPreferences rationale to the guide

Twenty lines of narration sat above a ten-line schema, and part of it
described what the PR removed — the #659 alias, and a TS2411 combination
nobody will now write.

src/collections/AGENTS.md already carries the "open shape can still be typed"
rule and names this very field as its example, so the #659 half was a second
copy. The TS2411 trap was not there; it is now, as a bullet beside that rule,
where the next author writing a `z.record` column will read it.

What stays at the field is what is local to it: which keys the admin renders,
and why the frequency is a string rather than an enum.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MWnNG5pRL6QCiYMgUoSHXm

* refactor(fields): build the whole field, not just its schema

Review asked for a `jsonField` helper: rename `jsonFieldSchema.ts` to
`jsonField.ts`, take `schema: JSONSchema4 | z.ZodType` plus the rest of the
field, and export nothing else. Every one of the 21 sites now declares its
column with it, `systemMetaField`, `fileMetadataField` and `translationsField`
included.

Two consequences the rename alone does not give:

A field can no longer skip the helper. There is no bare `jsonSchema` to
obtain, so `type`, `uri`, `fileMatch`, `$id` and `title` cannot be written by
hand at a field — they were five lines a caller could get wrong before.

Six shapes that lived in a module only to be shared as one `jsonSchema` object
move to their fields as plain Zod: `MeditationFrames`, `MeditationNodeWeights`,
`Subtitles`, `LectureMetadata`, `ClientAbuseScore`, `ScheduleUpcomingDates`,
plus `EventQualityReport` and `ReadinessReport`, which stay named where they
are because a reader cannot take them in beside a field.

That last move would have renamed generated interfaces, which is why
`jsonField` interns: Payload names an interface off the schema OBJECT, not the
title, so handing three `subtitles` columns equal-but-separate objects emits
`Subtitles`, `Subtitles1`, `Subtitles2` — the same body under three names. One
object per distinct shape keeps a name a function of the shape. The new case
in the helper spec was watched failing with the interning removed:
`TagAssignments is declared as 4 separate objects`.

`payload-types.ts` moves in one direction only: `FileMetadata1/2/3` collapse
into `FileMetadata`, three duplicate interfaces nothing imported. No other
generated shape changes, and `db:migrations:create --skip-empty` wrote nothing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AzQHVAUMN3oxRKsmVmqJ66

* fix(fields): name the option schemaTitle, not title

Review: `title` reads as a field label beside `name`, `label` and `admin`,
which is what every other key in a `jsonField` call configures. This one
names a TypeScript interface — the one Payload generates into
`payload-types.ts` — and `JSONField` has no `title` of its own for it to be
confused with. `schemaTitle` says which of the two it is at the call site,
where the reader is.

All 24 call sites, `systemMetaField`'s own pass-through option, the
`Pick<JsonFieldOptions, …>` in `translationsField`, and both guides move
with it. The emitted JSON Schema's `title` keyword is unchanged, so no URI,
no generated interface name and no `payload-types.ts` line moves.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FNMyzjxxC4gWdVhpnqpf6p

* refactor(schedule): declare upcomingDates' shape at its field

Review asked whether `upcomingDatesSchema` had a reason to stay in
`@/lib/schedule/scheduleHooks`. It did not. It had exactly one consumer —
the field three lines of Zod now declare inline — and this PR's own rule is
that a column's shape is read where the column is declared.

It sat beside `computeUpcomingDates` because that hook is what writes it,
but the hook is named at the same field, so the pairing survives the move.
`scheduleHooks` drops its last `zod` import with it.

No generated type changes: `ScheduleUpcomingDates` is still one interned
object under one schemaTitle.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FNMyzjxxC4gWdVhpnqpf6p

* refactor(jobs): type lectureIds as a hasMany number field

Review: a list of lecture ids is a list of numbers, and Payload has a field
for that. `jsonField` was reaching for a JSON column to describe a shape the
field system already describes.

`{ type: 'number', hasMany: true }` generates `lectureIds?: number[] | null`
— what the handler already reads — and drops the `SyncLectureMetadataIds`
alias, an interface that existed only to name that array.

Nothing is lost by the move. `inputSchema` is fed only to
`generateJobsJSONSchemas`, so neither form was ever a runtime check, and the
handler's `Array.isArray` guard stands either way. The comment that called
the input "an unvalidated `json` field" now names the real reason instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FNMyzjxxC4gWdVhpnqpf6p

* refactor(jobs): model the cleanup span as two date fields

Review: `testDateRange` was a JSON column wrapping two ISO strings, which is
what `type: 'date'` already is. Two optional date fields say it in the field
system instead, and the `CleanupTestDateRange` interface — generated solely
to name that pair — goes with them.

They stop being test-only in name. The handler takes an explicit span from
anyone who supplies one, and only the integration spec does; calling it
`test*` described the one caller rather than the input. Both halves are
still required together, since one alone would pair a chosen bound with a
rotated one and silently run a third range.

The label moves with the name: `test-range` becomes `explicit-range`, so a
log line says what the run did rather than who asked for it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01FNMyzjxxC4gWdVhpnqpf6p

---------

Co-authored-by: Claude <[email protected]>
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…he fileMetadata default

Review round on #714.

- Every `$id`/`uri` moves from `https://sahajcloud.dev/schemas/<x>.json`, a
  domain nobody owns, to `urn:sahajcloud:schema:<x>`. Nothing fetches these:
  Payload registers the schema object inline and uses `uri` only as the Monaco
  model id. A URN says that, an https URL implies a document that does not
  exist.
- Two schemas carried no `title`, so Payload named their generated interfaces
  after the `$id` — `HttpsSahajcloudDevSchemasEventSystemMetaJson`. Adding
  `title` to `canonicalVerificationJsonSchema`, the embed-metadata schema and
  `systemMetaField` keeps `payload-types.ts` byte-identical through the URI
  change, and removes the last place a URL leaked into a type name.
- `fileMetadataField`'s `defaultEmpty` option is gone. All four upload
  collections now default the column to `{}`.
- `managerMapper.ts` no longer re-exports `NotificationPreferences`. Its one
  consumer imports it from `@/payload-types` directly.
- Both job input schemas move out of the `inputSchema` literal into named
  `*JsonSchema` consts, matching `lectureMetadataFieldSchema`.

Lean gate green: lint, typecheck, typecheck:tests, test:unit (126 files,
1623 tests). `pnpm generate:types` leaves `payload-types.ts` unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CkfqNbPusAZTtA3wwo45KV

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-714 — 1ba036b3 Deployed Sep 7, 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

Development

Successfully merging this pull request may close these issues.

Audit custom admin field components: JSON fields without a schema, and hand-rolled type indirection

4 participants