Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/document-state-change-sets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-client': minor
'@tanstack/cms-store-postgres': minor
'@tanstack/cms-ui-react': patch
---

Change sets carry the document state strategy's state. A decision's `state` is stored on the document's one coalesced change set with the strategy's `id@version`, upgraded by the strategy's `migrate` when its version moves on; a change set no version can read is stranded and core refuses every decision on it except discarding it (new server export `listStrandedChangeSets`). Audit entries gain `changeSet`, `from` / `to` (the state before and after), `effects` and `reason`, and a decision that only changes the state is audited as the new `transitioned` decision. The review screen's audit trail labels it and the new `staged` decision. Storage migrations add the columns (SQLite/libsql v16, Postgres v8); `StorageOps` gains an optional `findDuePendingPublish` for the scheduler sweep.

Breaking changes (phase 4 bug fixes and rulings):

- Stage-only decisions are audited. An agent proposal, an author's review request or a publisher's draft now writes an audit row (`transitioned` with the built-ins, which store `pending_review` or `draft`; `staged` for a strategy that stores no state). Code that counts audit rows per decision should filter by `decision` or `action`.

- One event vocabulary: the in-process bus (`onCmsEvent`, plugin `onEvent`), webhooks and the `/api/cms/v1/events` stream use the durable names `document.created`, `document.updated`, `document.published`, `document.unpublished` and `document.deleted` (new `CmsContentEvent` type; `CmsEvent.event`, webhook payloads, `x-cms-event` and the client's `CmsLiveEvent` carry them). `document.published` fires only when a document goes live; a save of a live document is `document.updated` and no longer fires `publish`. The short names `publish`, `unpublish`, `delete`, `change` and `update` stay as deprecated aliases (`CmsEventAlias`) until phase 6: webhook `events` lists and the new `onCmsEvent(names, listener)` filter still match them. Default webhooks keep firing for publishes, unpublishes, deletes and updates of a live document. Code that compares `event.event` with a short name, and webhook receivers that read the event name, must switch to the `document.*` names.
- While a document's change set is open, a write from another source (an agent proposal, an author's review request, a publisher's draft) fails with `CONFLICT` and `details: { pendingId, source }` instead of taking it over. Same-source re-saves merge onto it, so an author's second save keeps their earlier staged edits.
- A direct commit that changes other fields rebases an open proposal onto the new revision (its `version` goes up). One that changes a field the proposal changed, or any commit under a staged delete, invalidates it: the change set is deleted, audited as `discarded` with `reason: 'stale'`, and `review.discarded` is emitted with the proposer as `author`. Approving it is then `NOT_FOUND` instead of `CONFLICT`.
- `scheduleDocument` with a future `publishAt` on a published document schedules its open change set and keeps the live version up, instead of unpublishing it until then; the scheduler sweep commits and publishes the change set as `scheduler`. With nothing pending it fails with `BAD_REQUEST`. Strategies get a `schedule` action, and the agent floor also covers scheduling a publish.
37 changes: 33 additions & 4 deletions docs/agents/review-queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ If validation fails, `stageWrite` throws a `CmsError` with code `VALIDATION_FAIL

### Coalescing and Refinement

An agent often makes several edits to the same document before anyone reviews them. `stageWrite` keeps **one pending change per document**: later writes replace the proposed `after` state but keep the original `before` snapshot, so the reviewer sees a single net diff.
An agent often makes several edits to the same document before anyone reviews them. `stageWrite` keeps **one pending change per document**: later writes replace the proposed `after` state but keep the original `before` snapshot, so the reviewer sees a single net diff. An author's re-save merges onto their open proposal the same way.

The pending change belongs to the door that opened it: an agent proposal (`agent`), an author's save (`review`) or a publisher's draft (`draft`). While it is open, a write through another door fails with `CONFLICT` and `details: { pendingId, source }` naming it. Approve, reject or discard it first.

Agents can read their own staged work. `read_document` and `update_document` fall back to the pending version when a document hasn't been committed yet, and `list_documents` includes pending creates. An agent can create a document, read it back, and refine it before anyone approves.

Expand All @@ -91,7 +93,12 @@ Anyone with `content.read` can view the queue (limited to collections they may r

The audit entry records both parties, for example `mcp (approved by Jane Doe)`. The underlying operations are `approveChange({ id, publish?, force? })` and `rejectChange({ id })`.

A pending change remembers the revision of the live document it was proposed against. If the live document changed after that (someone saved it, or it was created or deleted), approving fails with `CONFLICT` and `details: { baseRevision, actualRevision }` rather than silently overwriting the newer version. The review page explains the conflict and offers **Approve anyway**, which passes `force: true`.
A pending change remembers the revision of the live document it was proposed against. When someone commits a new live revision while it is open:

- If they changed different fields, the proposal moves onto the new revision: its own changes are re-applied over it, its `version` goes up, and approving it keeps both.
- If they changed a field the proposal also changed (or the proposal deletes the document), the proposal is invalidated. It leaves the queue with an audit entry `discarded`, reason `stale`, and a `review.discarded` event (payload `{ reason: 'stale' }`, the proposer as `author`) so the proposer can be told.

If the live revision still moved on underneath a proposal (for example, the database was written directly), approving fails with `CONFLICT` and `details: { baseRevision, actualRevision }` rather than silently overwriting the newer version. The review page explains the conflict and offers **Approve anyway**, which passes `force: true`.

## Choosing the Flow: Document State Strategies

Expand All @@ -110,7 +117,9 @@ defineCms({
})
```

Core refuses (with `FORBIDDEN`, audited as `refused`) a decision that drops an incoming change, emits a `document.*` event, changes a published document's content without `publish`, or lets an agent publish when the strategy doesn't grant `publish` to agents. With `review.autoApprove` set, the review strategy grants it, because an auto-approved agent write goes live. See [Document state strategy](../architecture/terminology#document-state-strategy).
Core refuses (with `FORBIDDEN`, audited as `refused`) a decision that drops an incoming change, emits a `document.*` event, changes a published document's content without `publish`, or lets an agent publish (or schedule a publish) when the strategy doesn't grant `publish` to agents. With `review.autoApprove` set, the review strategy grants it, because an auto-approved agent write goes live. See [Document state strategy](../architecture/terminology#document-state-strategy).

A decision can return a `state` as well as effects. Core stores it on the change set with the strategy's `id@version` and hands it back on the next decision, so a custom strategy can track steps such as a legal sign-off; a decision that only changes the state, or stages an edit with a new state, is audited as `transitioned`, with the state before (`from`) and after (`to`). A stage that stores no state is audited as `staged`; the built-ins store `pending_review` or `draft`, so their stages are `transitioned`. When a strategy's `version` goes up, its `migrate({ version, state })` upgrades change sets written by the older version. A change set it can't read (another strategy wrote it, there is no `migrate`, or `migrate` returns `{ stranded }`) is **stranded**: core refuses every decision on it except discarding it. `listStrandedChangeSets()` from `@tanstack/cms-core/server` lists them.

## Optimistic Concurrency

Expand Down Expand Up @@ -145,6 +154,8 @@ Every commit stores a full snapshot of the document as a numbered revision: dire

Documents carry `publishAt` and `unpublishAt` system fields. When a time passes, the scheduler publishes (or unpublishes) the document, records a revision, and logs an audit entry with actor `scheduler`. The sweep runs automatically as the store is used (at most once per second); on idle sites, call `runScheduledPublishing()` from `@tanstack/cms-core/server` in a cron job for exact timing. An agent's `schedule_document` is staged for review.

Scheduling a future publish of a **published** document schedules its open draft or proposal instead: the live version stays up, the pending change carries `publishAt`, and at that time the scheduler commits and publishes it (actor `scheduler`, the proposer as `author`). A published document with nothing pending has nothing to schedule, so `scheduleDocument` fails with `BAD_REQUEST`; save a draft first.

## Deleting Referenced Documents

Deleting a document that other documents reference through a `relation` field fails with `CONFLICT` and lists the references, unless the delete passes `force: true`. Relations inside `group`, `array`, and `blocks` fields count too; their `field` is the dotted path, such as `body.2.author`. The editor shows inbound references before you delete.
Expand All @@ -170,6 +181,12 @@ interface Pending {
source: 'agent' | 'draft' | 'review'
/** The document's `_revision` when the change was staged. */
baseRevision?: number
/** Bumped by every write to the change set. */
version?: number
/** When the scheduler publishes this change set (a published document's scheduled update). */
publishAt?: string
/** The strategy state, with the `id@version` that wrote it. */
workflow?: { strategy: string; state: unknown }
}

interface AuditEntry {
Expand All @@ -178,7 +195,19 @@ interface AuditEntry {
docId: string
type: WriteType
actor: string
decision: 'approved' | 'rejected'
action?: string // the strategy action: 'edit', 'approve', 'discard', …
decision:
| 'approved'
| 'rejected'
| 'discarded'
| 'refused'
| 'transitioned'
| 'staged'
changeSet?: string // the change set the decision acted on
from?: unknown // its strategy state before the decision
to?: unknown // and after it (null once closed)
effects?: Array<unknown> // the effects the decision ran
reason?: string // a refusal's reason, or 'stale'
at: string
}
```
Expand Down
7 changes: 6 additions & 1 deletion docs/api/cms-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,12 @@ function subscribeCmsCollectionEvents(
): () => void

interface CmsLiveEvent {
event: 'publish' | 'unpublish' | 'delete' | 'change'
event:
| 'document.created'
| 'document.updated'
| 'document.published'
| 'document.unpublished'
| 'document.deleted'
collection: string
id: string
at: string
Expand Down
39 changes: 30 additions & 9 deletions docs/api/cms-core-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,14 @@ await actOnDocument(systemContext('nightly legal sign-off'), {
})
```

### `listStrandedChangeSets()`

```ts
function listStrandedChangeSets(): Promise<Array<{ pending: Pending; reason: string }>>
```

Change sets whose stored strategy state their collection's strategy can't read: written by another strategy, or by an older version without a `migrate` that upgrades it. Core refuses every decision on them except discarding them.

### `listPending(options?)`, `getPending(id)`

```ts
Expand Down Expand Up @@ -594,7 +602,7 @@ Restoring commits the old content as a new revision (or stages it).
function listAudit(options?: { limit?: number; offset?: number }): Promise<Array<AuditEntry>> // default limit 50
```

Approve/reject decisions and direct deletes, newest first.
Every decision on a document, newest first: stages, commits, approvals, rejections, discards (with `reason: 'stale'` for a proposal a commit invalidated), refusals, `transitioned` state changes, and imports. A stage is `transitioned` when the strategy stores a state for the change set (the built-ins do) and `staged` otherwise. Document entries carry the `action`, the `changeSet` acted on, its strategy state before and after (`from` / `to`), and the `effects` that ran.

### Scheduling

Expand All @@ -615,27 +623,39 @@ interface ScheduledPublishResult {
}
```

`scheduleDocument` sets `publishAt` (a future time also sets `published: false`). `runScheduledPublishing` publishes every document whose `publishAt` has passed and unpublishes every live document whose `unpublishAt` has passed, recording revisions and emitting `publish` / `unpublish`. It also runs automatically, throttled to once per second, as the store is used; call it from a cron job for exact timing on idle sites.
`scheduleDocument` sets `publishAt` on an unpublished document (a future time also sets `published: false`). On a published document it schedules the open draft or proposal instead and returns that `Pending`: the live version stays up until then. A published document with nothing pending fails with `BAD_REQUEST`. `runScheduledPublishing` publishes every document whose `publishAt` has passed, publishes every change set whose `publishAt` has passed, and unpublishes every live document whose `unpublishAt` has passed, recording revisions and emitting `document.updated` with `document.published` / `document.unpublished`. It also runs automatically, throttled to once per second, as the store is used; call it from a cron job for exact timing on idle sites.

### `onCmsEvent(listener)`

```ts
function onCmsEvent(listener: (event: CmsEvent) => void): () => void // returns unsubscribe
function onCmsEvent(
events: CmsEventName | ReadonlyArray<CmsEventName>,
listener: (event: CmsEvent) => void,
): () => void // only the named events
function cmsEventDocument(event: CmsEvent): Doc | undefined // trusted server-only authorization snapshot

type CmsEventName = 'publish' | 'unpublish' | 'delete' | 'change'
type CmsContentEvent =
| 'document.created'
| 'document.updated'
| 'document.published'
| 'document.unpublished'
| 'document.deleted'
type CmsEventName = CmsContentEvent | CmsEventAlias // deprecated: 'publish' | 'unpublish' | 'delete' | 'change' | 'update'

interface CmsEvent {
event: CmsEventName
event: CmsContentEvent
collection: string
id: string
actor: string
at: string // ISO timestamp
doc?: Doc // the document after the change; omitted for 'delete'
doc?: Doc // the document after the change; omitted for 'document.deleted'
}
```

The in-process content event bus, emitted after commits in this process. The same events drive webhooks (`WebhookPayload` is a `CmsEvent`) and the `/api/cms/v1/events` stream. Use it for cache invalidation in long-running servers. Listener errors are swallowed so they never break a write.
The in-process content event bus, emitted after commits in this process, with the same names and order as the durable [events](../architecture/events-and-hooks): every commit emits `document.created` or `document.updated`, then `document.published` when the document went live or `document.unpublished` when it came down; a delete emits `document.deleted`. The same events drive webhooks (`WebhookPayload` is a `CmsEvent`) and the `/api/cms/v1/events` stream. Use it for cache invalidation in long-running servers. Listener errors are swallowed so they never break a write.

The short names are deprecated aliases until phase 6: subscribing by one still works (`publish` = `document.published`, `unpublish` = `document.unpublished`, `delete` = `document.deleted`, `change` = `document.created` or `document.updated`, `update` = `document.updated` of a document that stayed live), but the delivered event carries the `document.*` name.

Transport implementations can use `cmsEventDocument(event)` to authorize a
document event against its complete snapshot. For deletions that snapshot is
Expand All @@ -646,9 +666,10 @@ document data to a client.
```ts validate=type
import { onCmsEvent } from '@tanstack/cms-core/server'

const stop = onCmsEvent(({ event, collection, id }) => {
if (event === 'publish' || event === 'unpublish') console.log(`purge /${collection}/${id}`)
})
const stop = onCmsEvent(
['document.published', 'document.updated', 'document.unpublished', 'document.deleted'],
({ collection, id }) => console.log(`purge /${collection}/${id}`),
)
```

For **durable, retried** delivery to app-defined handlers (as opposed to this best-effort in-process bus), use the async event system below.
Expand Down
18 changes: 13 additions & 5 deletions docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const cms = defineCms({
webhooks: [
{
url: 'https://api.example.com/hooks/cms',
events: ['publish', 'unpublish', 'delete'],
events: ['document.published', 'document.updated', 'document.unpublished', 'document.deleted'],
collections: ['post'],
secret: () => process.env.CMS_WEBHOOK_SECRET,
},
Expand Down Expand Up @@ -379,18 +379,26 @@ interface RateLimitStore {
### `CmsWebhook` and `CmsWebhookEvent`

```ts
type CmsWebhookEvent = 'publish' | 'unpublish' | 'delete' | 'change'
type CmsContentEvent =
| 'document.created'
| 'document.updated'
| 'document.published'
| 'document.unpublished'
| 'document.deleted'
/** @deprecated aliases, removed in phase 6 */
type CmsEventAlias = 'publish' | 'unpublish' | 'delete' | 'change' | 'update'
type CmsWebhookEvent = CmsContentEvent | CmsEventAlias

interface CmsWebhook {
url: string | (() => string | undefined)
events?: Array<CmsWebhookEvent> // default ['publish', 'unpublish', 'delete']
events?: Array<CmsWebhookEvent> // default: what a public site shows changing (below)
collections?: Array<string> // default: all
secret?: string | (() => string | undefined) // HMAC-SHA256 signing secret
headers?: Record<string, string>
}
```

`publish` fires whenever a published version is committed (including edits to live content), `unpublish` when a live document is taken down, `delete` on deletion, and `change` on every commit. Deliveries are JSON `POST`s signed with `x-cms-signature`; they are durable (enqueued in the commit transaction on the transactional outbox and delivered by the dispatcher with retries + dead-lettering). See [Webhooks](./routes-and-endpoints#webhooks) for the payload and verification, and [`/server`](./cms-core-server#webhooks) for delivery semantics.
The names match the durable [events](../architecture/events-and-hooks): `document.created` or `document.updated` fires on every commit, `document.published` when a document goes live, `document.unpublished` when a live document is taken down, and `document.deleted` on deletion. Without `events`, a hook gets `document.published`, `document.unpublished`, `document.deleted`, and `document.updated` only while the document stays live. The short names (`publish`, `unpublish`, `delete`, `change` for created or updated, `update` for an update that stays live) are deprecated aliases: a list that uses them still matches, and deliveries carry the `document.*` name. Deliveries are JSON `POST`s signed with `x-cms-signature`; they are durable (enqueued in the commit transaction on the transactional outbox and delivered by the dispatcher with retries + dead-lettering). See [Webhooks](./routes-and-endpoints#webhooks) for the payload and verification, and [`/server`](./cms-core-server#webhooks) for delivery semantics.

### `CmsAdminConfig`

Expand Down Expand Up @@ -494,7 +502,7 @@ export const analytics = definePlugin({
}),
],
onEvent: (e) => {
if (e.event === 'publish') console.log(`published ${e.collection}/${e.id}`)
if (e.event === 'document.published') console.log(`published ${e.collection}/${e.id}`)
},
},
})
Expand Down
Loading
Loading