Skip to content

feat: content branching - #17878

Open
paulpopus wants to merge 159 commits into
mainfrom
feat/content-branching
Open

paulpopus wants to merge 159 commits into
mainfrom
feat/content-branching

Conversation

@paulpopus

@paulpopus paulpopus commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Written with AI

Summary

This PR adds opt-in Content Branching to Payload. Editors can create named branches, change content in isolation, and merge selected changes into main.

Untouched documents inherit their current main state. The first branch change creates branch-owned data without changing the document on main.

Branching supports collections, globals, drafts, versions, localization, relationships, joins, uploads, Trash, Preview, and Live Preview.

Why

Editors often need to prepare related changes across documents and publish them together. Content Branching provides a separate workspace for review before those changes reach main.

What changes

  • Adds the root branching configuration. Eligible collections and globals can opt in or out separately.
  • Adds branch access controls, merge hooks, and custom merge validation.
  • Adds a branch switcher, branch management views, change review, diffs, merge, discard, scheduling, and merge history to the Admin Panel.
  • Makes database reads branch-aware, including counts, pagination, sorting, drafts, versions, relationships, joins, and distinct values.
  • Keeps branch-created upload files separate until merge and removes unused files during discard or cleanup.
  • Adds database support for MongoDB, Postgres, SQLite, D1 SQLite, and Vercel Postgres.

Authentication-enabled collections cannot use branching. Payload internal collections remain excluded unless they explicitly opt in.

API changes

Collection Local API operations now accept branch?: string | false. This includes create, update, delete, duplicate, count, find, findByID, findDistinct, version reads, and version restoration.

Global Local API operations also accept branch. This includes find, update, version counts, version reads, and version restoration.

A branch slug selects that branch. Local API operations inherit the branch from a supplied req unless an explicit branch argument overrides it. Without a branch argument or request branch context (including a branch query parameter), operations use main.

Pass branch: 'main' to explicitly target main. Passing branch: false bypasses branch filtering and identity projection for trusted cross-branch operations; it is not equivalent to selecting main.

Nested operations that pass the same req, including operations called from hooks, inherit its branch. Admin rendering resolves the user's stored branch preference separately; ordinary API operations do not load that preference.

REST operations accept a branch query parameter:

GET /api/pages?branch=fall-campaign
PATCH /api/pages/:id?branch=fall-campaign

GraphQL collection and global queries and mutations accept a branch argument.

The active branch is available as req.branch in access functions, hooks, Preview, and Live Preview callbacks.

Before

const page = await payload.findByID({
  collection: 'pages',
  id: pageID,
})

This reads the document from main.

After

const page = await payload.findByID({
  branch: 'fall-campaign',
  collection: 'pages',
  id: pageID,
})

await payload.update({
  branch: 'fall-campaign',
  collection: 'pages',
  id: pageID,
  data: {
    title: 'Fall campaign',
  },
})

These operations read and update the branch without changing main.

The new Local API supports merge and discard operations:

const preview = await payload.branches.merge({
  branch: 'fall-campaign',
  dryRun: true,
  overrideAccess: false,
  user,
})

await payload.branches.discard({
  branch: 'fall-campaign',
  changes: selectedChangeIDs,
  overrideAccess: false,
  user,
})

The equivalent REST endpoints are:

POST /api/payload-branches/:id/merge
POST /api/payload-branches/:id/discard

The merge endpoint supports selected changes, dry runs, optional branch closure, and streamed NDJSON progress.

Data modeling

Branching stores branch data beside the existing data. Ordinary content bookkeeping fields remain internal. Version responses expose _branch to identify the owning branch. Collection versions expose the logical document ID through parent; _branchParent remains internal.

Storage New fields Purpose
Branch-enabled collection _branch, _branchDocID _branch identifies the owning branch. _branchDocID links a branch copy to its logical document on main.
Collection version table _branch, _branchParent These fields separate version history by branch and retain the logical parent document ID.
Branch-enabled global _branch This identifies the branch that owns the global row.
Global version table _branch This keeps each branch version history separate.

Rows on main use _branch: 'main'. A copy of an existing document uses _branchDocID to retain the document ID visible through the API.

A document created on a branch does not need _branchDocID. Its own ID becomes the main document ID if the change is merged.

Payload also adds three internal collections:

  • payload-branches stores branch names, status, and lifecycle information.
  • payload-branch-changes records each pending create, update, or delete.
  • payload-branch-merges records merge history and the outcome of each change.

Unique fields and custom unique indexes include _branch. Separate branches can therefore use the same value while each branch remains internally unique.

Enabling branching requires a database migration. For Postgres and SQLite, generate the normal schema migration:

pnpm payload migrate:create enable-branching

For an existing MongoDB database, use the predefined migration:

pnpm payload migrate:create enable-branching --file @payloadcms/db-mongodb/branching

Run the migration before starting application code that expects the new fields and indexes.

Merge behavior

  • Callers can merge all pending changes or a selected set.
  • Branch data replaces the current main state. Payload does not merge individual fields.
  • Payload reports a warning when main changed after the branch copied a document.
  • Merge checks branch access, document access, field access, dependencies, and validation.
  • Real writes use the normal Local API, so hooks, versions, validation, and database constraints still apply.
  • Discard removes branch-owned data and does not change main.
  • Transactions are used when the database supports them. Recovery without transactions is best effort.

Breaking changes

None for projects that do not enable branching. The feature remains disabled by default.

Enabling branching changes the database schema and requires a migration. This is an explicit configuration change.

Current limitations

  • Merges can target only main.
  • There is no three-way or field-level conflict resolution.
  • Collections with custom ID fields are not supported.
  • Content Branching and @payloadcms/plugin-multi-tenant are not supported together.
  • A merge without database transaction support cannot guarantee atomic visibility.

Validation

The PR adds coverage across MongoDB, Postgres, and SQLite. Tests cover branch reads and writes, pagination, versions, globals, joins, access, merge, discard, cleanup, and recovery.

Preview

payload-pr-demo-content-branching-gestures-take-3.mp4

jmikrut and others added 30 commits August 10, 2026 11:34
Design proposal for named content branches: create a branch, CRUD and
publish documents on it in isolation, then merge selected changes back
to main.

Core mechanism is copy-on-write rows in the same table, discriminated by
a `_branch` column, so branch state is filtered by the database and
pagination, totalDocs, sorting and count stay correct.

Covers collections and globals with drafts/versions, access control via
existing Payload primitives, hook semantics on merge, and the enablement
and migration story. Recommends core rather than a plugin, since joins
are resolved inside the database adapters.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Verifies the three claims the branching design was inferred from, before
building anything on them.

Confirmed on SQLite:
- `not_in` on a hasMany field is unusable for shadow tracking, with two
  defects rather than the one predicted. A doc shadowed on ['a','b']
  leaks through `not_in: ['a']`, and a doc shadowed on nothing is
  excluded entirely because it produces no joined rows. The second would
  have hidden every untouched main document in a branch read.
- A compound (field, branch) unique index with a non-null sentinel keeps
  enforcing uniqueness within a branch while allowing the same value
  across branches.
- `latest` on collection versions is scoped per parent, so branch shadow
  rows can carry independent version chains with no version changes.

Postgres and Mongo require Docker and are not yet covered; running the
spike on all three is a prerequisite for closing phase 0.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
First implementation slice of content branching (CONTENT_BRANCHING_PLAN.md
phase 1). Covers the schema layer only; the read path, write path and merge
are not yet implemented.

- `branching` on the root config, plus per-entity `branching` on collections
  and globals for opting in or out.
- `sanitizeBranchingConfig` resolves the branchable set during
  `sanitizeConfig`. Ordering is load-bearing: after the default user
  collection is injected so auth detection sees it, and before the
  `sanitizeCollection` loop that consumes the result. Auth collections are
  detected by the `auth` flag rather than by slug, since the auth collection
  can be named anything and a project may have several.
- Built-in Payload collections and auth collections are off by default but
  can opt in. `payload-branches` and `payload-branch-changes` are hard
  excluded, since branching the registry that resolves branch state is
  circular.
- `injectBranchFields` adds `_branch`, `_branchDocID` and `_branchOp`, and
  rewrites `unique: true` fields into branch-scoped compound indexes so a
  branch copy does not collide with its main row. `_branch` defaults to the
  `'main'` sentinel rather than null, because Postgres treats nulls as
  distinct in unique indexes.
- `appendBranchFilter` builds the read predicate. Not yet wired into the
  adapters.

Verified on SQLite: 15 integration tests and 7 unit tests. The rest of the
matrix is scaffolded as todos.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Makes branching functional end to end for documents created on a branch.
Reads are now filtered by the database, so pagination and counts are
correct rather than patched after the fact.

- `payload-branches` and `payload-branch-changes` registered as core-owned
  collections when branching is enabled. The changeset registry references
  documents through a polymorphic relationship so it spans collections with
  different ID types without a coercion step that fails open.
- `resolveBranch` resolves the active branch once per request, in order:
  explicit Local API argument, `branch` query param, `X-Payload-Branch`
  header, `payload-branch` cookie, then main.
- `loadBranchManifest` loads a branch's changes in a single query per
  request and groups them by collection in memory, rather than querying per
  collection. Marked loaded before reading so the manifest read cannot
  recurse into itself.
- `resolveBranchQuery` is the single entry point both adapters call, so
  Mongo and Drizzle cannot drift apart on branch semantics. Wired into
  find, findOne and count in db-mongodb and drizzle.
- `branch` is a typed Local API option on find, findByID, create, update,
  delete and count. `branch: false` bypasses branching for merge and
  cross-branch reads.
- Creates on a branch are stamped via a beforeChange hook and recorded in
  the registry via afterChange. `_branchDocID` is left null for
  branch-created documents, since their canonical ID is their own.

Verified on SQLite: 18 integration tests including pagination integrity —
25 documents on main plus 5 on a branch reads as 25/3 pages on main and
30/3 pages on the branch, with no document appearing on two pages, and
count agreeing with find. Regression checked against versions,
collections-rest, database and access-control.

Updates and deletes on a branch are not implemented yet.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Editing a document on a branch now forks it into a branch-owned copy
instead of writing to production.

- `forkDocument` copies the main row wholesale on first branch edit,
  stamping `_branchDocID` and recording the change in the registry.
  Subsequent edits reuse the copy.
- `branchIDs` provides the canonical-identity translation. A shadow row's
  primary key is not the document's ID, so reads rewrite `id` constraints
  to match either a shadow row's `_branchDocID` or a main row's own `id`,
  and results project the canonical ID back over the row's key.
- `resolveBranchRowID` does the same for writes, which address rows by
  primary key directly and so cannot go through the where-tree rewrite.
  Canonical IDs stay the only identity the API exposes.
- Both are skipped under `branch: false`, since the fork and write-target
  lookups address rows by real primary key and would be corrupted by
  having canonical IDs projected over them.

Two bugs found by the tests:

- The shadowed-main-row exclusion compared `_branchDocID`, which is null
  on main rows, so it never excluded anything and a branch read returned
  both copies of an edited document. It must compare the main row's own
  `id`, since for a main row the canonical ID is its primary key. This
  also removes the design's stated dependency on relationship-field
  null-safe `not_in` for the exclusion.
- `findByID` passes a stub req to the adapter carrying only
  `transactionID`, so the branch predicate never applied and reads by ID
  silently resolved against main.

Verified on SQLite: 31 branching integration tests and 15 unit tests.
Regression checked against versions, collections-rest, database,
access-control and relationships.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Deleting on a branch no longer removes production content.

- Deleting a main document from a branch records the intent as a shadow
  row marked `_branchOp: delete`, which the read predicate hides on that
  branch and nowhere else. The main row is untouched and other branches
  still see the document.
- A document created on the branch is deleted outright, since no main row
  stands behind it and nothing is left to hide.
- An already-forked document is converted into a tombstone in place
  rather than gaining a second row for the same document.
- The absorbed delete still returns the document, so `afterDelete` hooks
  receive the payload they expect.

`resolveBranchDelete` resolves the target through the branch predicate
rather than by extracting an ID from the where clause, so it addresses the
branch's own copy when one exists and the main row otherwise.

Also corrects the plan: the shadowed-main-row exclusion compares a main
row's own `id`, not `_branchDocID`, which is null there. `_branchDocID`
remains a relationship field for ID typing, but its null-safe `not_in`
behavior is no longer load-bearing.

Verified on SQLite: 29 branching integration tests and 15 unit tests.
Regression checked against versions, collections-rest, database,
access-control, relationships and _community.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ran the branching suite and the regression set on all three adapters.
Everything passes unchanged, so no adapter-specific fixes were needed.

Closes phase 0. The two anti-join defects that rule out array-based shadow
tracking are now confirmed on Postgres as well as SQLite, and Mongo is
confirmed correct on both counts — meaning a Mongo-only test run would
have missed the hazard entirely. The compound unique index with the
`'main'` sentinel and per-parent `latest` scoping are confirmed on all
three.

One prediction did not hold: `_branchDocID` was expected to surface as an
ObjectID on Mongo and break canonical-ID projection. IDs are normalised
before the projection runs, so a single code path serves all adapters.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Drafts, versions and publishing now work per-branch, isolated from main.

- Version collections of branch-enabled collections gain `_branch` and
  `_branchParent`. A branch version's `parent` points at the shadow row,
  so `_branchParent` carries the canonical document the editor knows.
- `createVersion` attaches new versions to the branch's own copy and
  stamps the discriminator, so a draft saved on a branch no longer
  appends to main's version chain.
- `queryDrafts` applies the branch predicate and maps results back to
  canonical IDs.
- `getLatestCollectionVersion` and `replaceWithDraftIfAvailable` resolve
  the branch row before querying by `parent`; without this, draft reads on
  a branch silently returned main's content.

`latest` bookkeeping needed no branch scoping, confirming the design's
claim: a branch version's parent is the shadow row's own primary key, so
main's chain and the branch's chain are disjoint by construction and
cannot clear each other. Noted at the call site in db-mongodb.

Verified on MongoDB, Postgres and SQLite: 40 branching integration tests
each. Regression checked against versions (all three), plus
collections-rest, database, access-control, relationships, fields and
_community.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Globals now branch alongside collections, including drafts and publishing.

Globals are structurally simpler than collections: a global is a single
document, so there is no result set to paginate and the branch's row and
main's row can be fetched together and resolved in memory. They need only
`_branch` — no `_branchDocID`, since a global's identity is its slug and
is stable across branches, and no `_branchOp`, since globals cannot be
created or deleted and so have no tombstones.

- `_branch` injected into global tables and their version collections.
- `findGlobal` reads the branch's row and main's together, preferring the
  branch's, and falls through to main for a global the branch never
  touched.
- `updateGlobal` targets the branch's own row, seeding it from main's
  content the first time the global is edited, and registers the change.
- `findGlobalVersions` filters strictly by branch rather than reading
  through, so a version list cannot interleave two branches' histories.

Fixes the corruption case the design predicted. Unlike collection
versions, global versions have no `parent` to scope `latest` by — every
version of a global shares one stream — so the unscoped clearing in
`createGlobalVersion` would wipe main's latest flag when a draft was saved
on a branch, losing main's draft with no error. Now scoped by `_branch` in
both adapters.

One adapter divergence found by the tests: `Model.find` and the
`findOne` calls in mongo's `updateGlobal` do not return lean results the
way the surrounding code assumed, so transform received mongoose
Documents. Made explicit.

Verified on MongoDB, Postgres and SQLite: 46 branching integration tests
each, plus the globals suite and regression across versions,
collections-rest, database, access-control, relationships, fields and
_community.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Applies a branch's changes to main. Branch data wins outright — there is
no field-level reconciliation. What replaces conflict resolution is
selection: callers choose which changes to apply, and anything left behind
keeps the branch open.

- `payload.branches.merge({ branch, changes, dryRun })`, following the
  `payload.jobs` local API pattern.
- `dryRun` reports what would be applied and why, without writing.
- Selective merge applies only the chosen changes; the branch is marked
  merged once its changeset is empty.
- `main-moved` warnings report documents main changed after they were
  branched. Informational only — merging still overwrites, which is the
  chosen semantic.
- `beforeMerge` can throw to block. `afterMerge` fires after commit, so a
  failing deploy webhook cannot undo a merge.
- Writes run in a transaction, through the ordinary Local API, so every
  document hook, validation and version creation behaves as it would for a
  hand-made edit on main.

A branch-created document is merged by updating its existing row in place
rather than recreating it. The row already holds the ID inbound
relationships point at, and deleting it would cascade those relationship
rows away — recreating the row does not bring them back.

That made the hook `operation` label wrong: such a write is semantically a
create on main, but reported as an update. `updateDocument` hardcoded
`operation: 'update'` in eight places, so it now takes the label as a
parameter defaulting to `'update'` — existing paths are unchanged. One of
those eight turned out not to be a hook label at all: `ensureUsernameOrEmail`
uses it to pick a validation mode and takes a narrower type, caught by the
type checker and left alone.

Verified on MongoDB, Postgres and SQLite: 58 branching integration tests
each. Regression checked against versions, collections-rest, auth, hooks,
access-control, fields, relationships and database.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Join fields now resolve against the active branch. This is the reason
branching belongs in core: joins are assembled inside the adapters, below
any layer a plugin could reach, so a plugin implementation would have
returned main's related documents while on a branch.

Both adapters and both mongo join strategies are covered:

- `buildJoinAggregation` (mongo, the default path) applies the branch
  predicate to the `$lookup` pipeline.
- `resolveJoins` (mongo, used when join aggregations are disabled) applies
  it to the per-collection query.
- The drizzle join subquery applies it before `buildQuery`.

Join results also had to report canonical document IDs. A forked document
appears in a join as its shadow row, whose primary key nothing outside
branching knows about — population would then fail to resolve it. Mongo
projects it with a `$set` stage on the lookup pipeline, drizzle with a
`COALESCE` in the subquery select.

Join query builders are synchronous, so they cannot load the change
manifest themselves. `getBranchPredicateSync` reads the manifest the
top-level read already loaded and memoized on the request earlier in the
same query, and returns null when branching is inactive.

Verified on MongoDB, Postgres and SQLite: 62 branching integration tests
each. Regression checked against the joins suite on all three, plus
relationships, versions, collections-rest, fields and database.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Merge now checks the merging user's production permissions per document,
closing the gap left when merge landed without enforcement.

A branch is a proposal — nothing on it is real until merge — which is what
makes permissive branch writes safe. The preflight is therefore the
enforcement boundary for branching, not a second check layered on a role
check. Payload has access functions rather than roles, so who may merge is
derived entirely from the access already defined on the documents being
merged.

- Effective operation is resolved per change from the shadow row, so
  editing a published document on a branch is checked as a `publish`
  against main rather than a plain update. Publishing is not a distinct
  access type in Payload — it is `update` evaluated against published
  data, which is how the admin UI derives the publish button.
- Two tiers, so a large branch does not cost one access call per document:
  the collection's access function runs once per (collection, operation)
  group, and only a `Where` result falls through to a single query
  resolving that group per document.
- Denials are collected and reported per document rather than thrown, each
  naming the collection, document, operation and reason. Blocked changes
  are excluded from `mergeable` and left on the branch; the rest still
  merge.
- `overrideAccess` defaults to `true`, matching every other Local API
  operation. HTTP callers pass `false` with `user`.

Also fixes an import regression in the drizzle join builder: a lint
autofix merged an added type import into the existing value import and
marked the whole block `import type`, erasing five runtime imports. This
only failed on Postgres, because the nine tests that exercise those paths
are skipped on SQLite — a reminder that "green on three adapters" only
covers tests that actually run on each.

Verified on MongoDB, Postgres and SQLite: 68 branching integration tests
each, plus the joins suite on all three. Regression checked against
access-control, auth, versions, collections-rest, fields and database.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`POST /<branches>/:id/merge`, accepting `{ changes?, dryRun? }`.

Runs with `overrideAccess: false` and the authenticated user, so the
per-document preflight applies. This is where branching's access model is
actually enforced: the Local API, like every other Payload operation,
trusts server-side callers by default, so HTTP is the boundary.

Responds 403 with `blocked` populated when nothing could be applied and
something was refused, rather than an empty success — a programmatic
caller sees the same per-document reasons the admin UI would show.
Unknown branch is 404; unauthenticated is refused before any work.

Endpoints are registered through `wrapInternalEndpoints` so the POST body
is parsed onto `req.data`, matching every other built-in endpoint. Without
it `dryRun` silently read as false and a preview mutated main.

Verified on MongoDB, Postgres and SQLite: 73 branching integration tests
each. Regression checked against endpoints, auth, access-control,
collections-rest, joins, versions, database and fields.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Starts phase 6. The switcher is the first crumb in the breadcrumb trail: a
searchable popup listing `main` plus every open branch the user can read, with
a pinned "New branch…" action routing to the standard create view. Creating a
branch switches onto it, via the document event rather than the create view, so
any route that creates a branch is covered.

Branch selection is stored in the user's `branch` preference, so it follows them
across browsers and machines. Core stays argument-only — `resolveBranch` reads
the operation argument or `?branch=` and nothing else, so an unbranched request
costs no lookup. Turning the stored preference into that argument is the admin
UI's job, in `getRequestBranch` beside `getRequestLocale`, and every admin API
call now passes `branch` explicitly the way it passes `locale`.

`payload-branches` is no longer admin-hidden, since the create view 404s on a
hidden collection. Its slug is derived from the name and immutable after create
(it was `required` + `admin.readOnly`, so the form could never submit), and bulk
delete is off given the cascade on shadow rows.

The injected `_branch` / `_branchDocID` / `_branchOp` fields are now internally
writable only. They were `admin.hidden` but not read-only, and the admin form
round-trips every field it loads — so an edit made on a branch submitted the
`_branch` it was read with, stamping the shadow row back onto `main` and
duplicating the document in production. Field access is skipped under
`overrideAccess: true`, so merge can still flip `_branch`, and copy-on-write
writes through `payload.db` below field access entirely.

Also fixes three pre-existing type errors that blocked a build: a missing
`branch` on `FindGlobalVersionsArgs`, a missing `PayloadRequest` import in
mongodb's `resolveJoins`, and an aliased SQL expression assigned into drizzle's
column map.

`Combobox` gains the column selector's search treatment — icon, no-results
state, width lock — and the two now share one matcher, promoted to
`matchesSearchQuery`.

Known gaps are recorded in the plan: the rest of phase 6, scheduled publish
still targeting main, and `resolveBranch`-level branch validation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Adds the merge and discard workflows end to end, makes globals, localized
fields and nested fields work on a branch, closes the REST and GraphQL gaps,
and roughly halves the query cost of a branch write.

A coverage audit found eight defects that all produced wrong data rather than
an error, each hiding behind a sibling code path that still worked:

- `enforceMaxVersions` pruned by canonical parent with no `_branch` scoping, so
  saving on a branch deleted main's whole version chain
- `updateLatestVersion` rewrote main's latest version row with branch content
- `resolveBranch` ignored the `_branchBypass` sentinel and fell through to the
  query param, so merging over HTTP with `?branch=` silently did nothing
- bulk `update({ where, branch })` never forked, writing straight to main
- `findDistinct` had no branch predicate in either adapter
- the drafts predicate never rewrote `parent`, so filtering a drafts read by
  document ID returned nothing on a branch
- `_status` was read as a scalar, but localization makes it per-locale, so
  every publish on a branch looked like an untouched fork and merged nothing
- forks copied array and block rows verbatim, colliding on their primary keys
  under a relational adapter

An explicit `branch` on a Local API operation now wins over whatever the
request already resolved, on an isolated request, matching how `locale`
behaves; and the dataloader keys populated documents by branch.

Query cost is asserted rather than estimated: reads add one query per request
and none on main, writes add 5 on first touch and 3 after.

Docs are split into a PR-style overview, a status document and the original
design proposal.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Resolved one conflict in `updateByID`, taking main's base access control
(#17662) which passes the entity slug into every access check.

Three things the merge broke silently and needed fixing:

- the merge preflight called access functions without `slug`, now required
- `updateGlobal`'s branch-copy write passed a third argument to `Model.create`,
  which selects a different overload under Mongoose 9 (#17747)
- `payload` and `translations` dist were stale, so `ui` could not see main's
  new clipboard keys or the `slug` access argument

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

Mongoose 9 (#17747) deprecated the `new` option for `findOneAndUpdate` and
`findOneAndReplace`, and logs a warning when it is used. The Next dev server
forwards server logs to the browser console, and the e2e harness fails any test
that produces a console error — so every e2e test that saved a document failed,
34 of 37 in the branching suite.

Not branching-specific: `updateOne` is the generic document save. Any suite that
updates a document through the admin panel hits it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
DanRibbens and others added 10 commits October 23, 2026 16:34
Written with AI

## Description

The branching overview explains source-wins merges without explicitly
distinguishing a merge from publication. Clarify that merging the latest
draft state saves a draft on main and leaves an existing published
document's live content unchanged.

## Changes

Add a paragraph and before/after example in “Merge and discard”
comparing draft and published branch states. Scope the explanation to
collections and globals with drafts enabled. No runtime changes.

This documentation-only PR targets `feat/content-branching` and
addresses the draft/publication explanation in Q08 of the API review.

## Test Plan

Reviewed the wording against the existing effective merge operation
logic and checked the Markdown table. `git diff --check` passed. No
tests run for this prose-only change.
Written with AI

## Description

The branching overview does not explain the difference between a merged
branch that can accept new work and a terminal closed branch. Document
the four branch statuses and how `closeBranch` affects successful
merges.

## Changes

- Add a concise status table for open, merging, merged, and closed
branches.
- Explain that pending work keeps a branch open and that merge/closure
retains the branch record.
- Clarify that branch lifecycle operations use the `payload-branches`
collection while `payload.branches` exposes merge/discard only.

This documentation-only PR targets `feat/content-branching` and
addresses Q09 of the API review. No runtime changes.

## Test Plan

Compared the explanation with branch collection access/status handling,
writable-state checks, merge finalization, and reopening on new changes.
Reviewed Markdown table syntax; `git diff --check` passed. No tests run
for this prose-only change.
Written with AI

## Description

`branching.exclude` already excludes global slugs at runtime, but its
collection-only type rejects configured globals when generated types are
present. Accept `(CollectionSlug | GlobalSlug)[]` so projects can
exclude collections and globals in the same list while retaining
configured-slug validation.

## Changes

- Widen the exclusion type and document that explicit exclusions
override per-entity opt-in.
- Show collection and global exclusions in the branching overview and
clarify root enablement in the config JSDoc.
- Add generated-type assertions for mixed slugs and unknown-slug
rejection, plus a sanitizer regression for exclusion precedence on
collections and globals.

Runtime selection behavior is unchanged. This targets
`feat/content-branching` and resolves Q04 of the API review.

## Test Plan

- Sanitizer unit suite: 11 tests passed.
- Focused TSTyche test: 3 assertions passed with generated
collection/global types. The isolated checkout used a temporary tsconfig
mapping `payload` to its local source and Node type roots to the shared
installed dependencies.
- ESLint on changed production TypeScript files: no errors; 26 existing
warnings in the root config types file.
- `git diff --check`: passed.
- Available Prettier check on branching types and sanitizer tests:
passed. Repository oxfmt is not installed in the current environment.
Written with AI

Clarify in one sentence that Local API calls inherit the branch
associated with `req`, unless explicitly overridden, and otherwise fall
back to main.

Validation: documentation-only change; `git diff --check` passed. No
tests run.
Written with AI

## Description

Explain that scheduling a merge leaves branch content editable and
resolves pending changes at execution time rather than capturing a
snapshot.

## Changes

Document omitted selections, latest content for selected IDs, skipped
stale IDs, and the current empty-array inconsistency in the branching
overview. The accepted empty-array fix remains separate pending
implementation.

The scheduled-freeze workflow proposal is tracked locally and is outside
this PR. This documentation-only PR targets `feat/content-branching`; no
runtime changes.

## Test Plan

Compared the text with the schedule handler, task selection
normalization, and writable-state checks. `git diff --check` passed. No
tests run for prose-only changes.
Written with AI

## Description

Content branching moves navigation preferences from `nav` to `admin`,
leaving saved sidebar and group choices unread and removing the exported
`PREFERENCE_KEYS.NAV` constant. Keep `NAV: 'nav'` and store branch
selection alongside the existing navigation values, so existing
preference records remain in use without a migration.

## Changes

- Restore `PREFERENCE_KEYS.NAV` and update branch and navigation
readers/writers to use it.
- Retain the shared request-cached preference lookup and merged writes,
preserving the existing `open` and `groups` values.
- Update comments and add regression coverage for existing navigation
values, branch selection, and branching disabled.

This PR targets `feat/content-branching` and addresses Q03 of the API
review.

## Test Plan

- Focused unit tests: 3 passed (`pnpm exec vitest run --project unit
packages/payload/src/admin/getAdminPreferences.spec.ts`).
- ESLint on changed production files: no errors; one existing React
effect/ref warning in Nav context.
- `git diff --check`: passed.
- Repository oxfmt check could not run because oxfmt is absent from the
installed dependencies. Formatted the added test with the available
Prettier using the repository's existing quote, semicolon,
trailing-comma, and width conventions.
- Browser verification not run. Before merge, verify saved sidebar/group
state after reload and branch switching with branching enabled and
disabled.

## Accessibility assessment

The affected state is persisted sidebar visibility and navigation-group
expansion. Source review considered WCAG 2.2 A criteria 2.1.1
(Keyboard), 2.4.3 (Focus Order), and 4.1.2 (Name, Role, Value); this
change alters persistence keys without altering control markup, event
handlers, focus behavior, or ARIA state wiring. Unit evidence verifies
stored values only; it is not rendered accessibility evidence. Browser
keyboard and expanded-state verification remains outstanding; no
screen-reader or conformance claim is made.
Written with AI

## Description

Content branching introduces `maxShadowedIDs` as already deprecated even
though it only controls a fallback performance warning, not a read limit
or strategy switch. Remove it from public and sanitized configuration
and remove the warning. Preserve the fallback's existing document
visibility and identity filtering.

## Changes

- Remove the option, sanitizer default, test fixture setting, and
overview example.
- Verify fallback filtering above 2,000 overridden documents.
- Replace the native-read test's indirect warning assertion with direct
checks that reads/joins/drafts do not query the branch-change manifest.

No adapter API replacement is required to remove this config setting.
Manifest-backed helpers and write bookkeeping remain unchanged.

## Test Plan

- Focused unit suites: 21 tests passed (fallback query, predicate
construction, existing config sanitization coverage).
- Remaining branching type tests after review: 4 tests and 10 assertions
passed. Removed the unpublished config-property absence test as
requested. The isolated checkout used a temporary tsconfig pointing
`payload` to its local source and Node types to shared installed
dependencies.
- SQLite native-read/join/draft integration regression: 1 passed, 5
unselected tests skipped.
- MongoDB integration attempt could not start: no server listening at
localhost:27018.
- ESLint on changed production files: no errors; one existing console
warning in config sanitization.
- `git diff --check` and available Prettier checks on changed branching
source/unit files: passed. Repository oxfmt is not installed in the
current environment.
Written with AI

## Description

Follow-up to #17878, targeting `feat/content-branching`.

Collection version responses currently return both the logical `parent`
and the internal `_branchParent`. Remove the duplicate internal identity
from version-list and single-version responses while retaining `_branch`
provenance and logical parent IDs.

## Changes

- Strip top-level `_branchParent` at the collection operation response
boundary, after adapter identity projection and access checks.
- Preserve database adapter metadata and trusted `branch: false` bypass
reads for internal version workflows. `showHiddenFields: true` alone
does not expose `_branchParent`.
- Remove `_branchParent` from GraphQL version output types while
preserving internal storage and query fields.
- Add optional `_branch` to the shared `TypeWithVersion` response type.
Generated collection/global types do not define version wrappers and
need no regeneration.
- Document the version response contract and cover Local API, REST,
GraphQL, selection, parent population, main and branch-created
documents, restoration, storage, and global provenance.

## Test Plan

- Focused regression suite: 5 tests passed on each of MongoDB,
PostgreSQL, and SQLite.
- Existing branching GraphQL and merge version write guard suites: 18
tests passed on SQLite.
- Targeted oxlint, TypeScript-source formatting checks, and `git diff
--check` passed.

MongoDB and PostgreSQL were tested using isolated temporary local
databases. D1 SQLite and Vercel Postgres were not exercised separately;
their shared Drizzle path is covered by SQLite/PostgreSQL.

The legacy pre-commit hook invokes an unavailable `eslint` executable.
The commit uses `HUSKY=0` after the documented oxlint and source
formatting checks passed.
Written with AI

## Description

Fix three issues found while reviewing content branching in #17878. The
fixes remain in three separate commits for review.

## Changes

- Honor an explicit merge/discard user when the incoming request already
has a user. Scheduled merges now check the scheduling user's
permissions, including when an authenticated admin runs the queue.
- Fail scheduled merge jobs when access or validation preflight refuses
their changes, retaining the refusal details and clearing the progress
marker. Empty merges still complete successfully.
- Reconcile selected changes after refresh so discarding one change
cannot cause subsequent actions to target unchecked remaining changes.

## Test Plan

- 77 targeted unit tests passed.
- 20 SQLite integration tests passed, including six regressions for user
precedence, refused jobs, and empty merges.
- Five Chromium component tests passed.
- The real admin discard-selection regression passed, including keyboard
selection and disabled action states after refresh.
- Targeted ESLint, Prettier, and whitespace checks passed.
- New regressions fail against the original implementation.

Accessibility assessment covered keyboard operation (WCAG 2.1.1, Level
A) and checkbox/action states (WCAG 4.1.2, Level A). Screen-reader
speech was not verified.
@DanRibbens
DanRibbens force-pushed the feat/content-branching branch from d19dbd0 to 2c6d3d3 Compare October 23, 2026 20:55
DanRibbens and others added 4 commits October 26, 2026 09:37
Written with AI

## Description
The branch dropdown always used the shared Popup component's default
dark theme, even when the admin was in light mode. Make it inherit the
admin theme so its surface, text, search, icons, and actions use the
matching palette.

## Changes
- Pass `theme="auto"` to the branch selector's Combobox.

## Test Plan
- Passed `pnpm exec oxlint
packages/ui/src/elements/BranchSelector/index.tsx`.
- Passed `pnpm exec oxfmt --check
packages/ui/src/elements/BranchSelector/index.tsx`.
- Passed scoped `git diff --check`.
- Used Playwright against the running branching admin: verified the
actual dropdown renders a white surface with dark text in light mode and
a dark surface with white text in dark mode. Inspected screenshots of
both states. Switched the document's theme attribute to exercise both
CSS palettes.
- Verified search filters to Q4 Campaign, Escape dismisses the dropdown,
and focus returns to the branch trigger.

Accessibility assessment: reviewed WCAG 2.2 A/AA 1.4.1 (state cues),
1.4.3 (text contrast), 1.4.11 (icons and control contrast), and 2.4.7
(visible focus) for the theme change; checked 2.1.1 (keyboard) and 2.4.3
(focus order/restoration) with the browser interactions above. This is
scoped visual and interaction evidence, not a full contrast audit or
conformance claim. Human keyboard-focus visibility and all status/hover
variants still need review; no screen-reader-specific behavior changed
or speech verification performed.

### Before:

<img width="336" height="341" alt="image"
src="https://github.com/user-attachments/assets/0af50a5d-013c-49d1-ab68-6b087250430a"
/>

### After:

<img width="275" height="305" alt="image"
src="https://github.com/user-attachments/assets/61b73752-567a-4094-b653-ce0b47ae5888"
/>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants