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
17 changes: 17 additions & 0 deletions .changeset/document-state-strategy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-ui-react': patch
---

Add document state strategies. Every write now goes through its collection's strategy, which decides what an action does by returning effects (`stage`, `commit`, `publish(revision?)`, `unpublish`, `schedule`, `discard`, `emit`); core applies them in one transaction and writes the audit entry. Set one with `defineCms({ documentState })` or a collection's `documentState`. The built-ins are `reviewStrategy()` (the default, equal to today's flow including `review.autoApprove`) and `directStrategy()` (agent and author writes commit at once). `defineDocumentStateStrategy` types a custom one. Core refuses, with `FORBIDDEN` and an audited `refused` entry, a decision that drops an incoming change, emits a `document.*` event, changes a published document without `publish`, or lets an agent publish when the strategy doesn't grant it. New server exports: `submitWrite`, `documentStateStrategy`, and `actOnDocument(ctx, { collection, id, action })` (the generic door: run any strategy action as an access context), `availableDocumentActions(ctx, collection, id)` and `documentStateLabel(collection, id)`.

Behaviour changes (bug fixes):

- Direct commits (`commitDocument`, saves by publishers, deletes, scheduled publishes) now write an audit entry. Document audit entries carry the strategy `action` (`edit`, `approve`, `reject`, `discard`, `publish`, `import`, …), and `decision` can now also be `discarded` or `refused`.
- `discardDraft` is audited as `discarded` and no longer emits `review.rejected`.
- With `review.autoApprove`, `saveDoc` reports the save as live (`staged: false`, no `pendingId`) instead of `staged: true`.
- `importContent` (`tanstack-cms import`, seeding) is audited and emits `import.document` per document and `import.completed`.
- Events after `approve` (and auto-approval) name the approver as the actor (`reviewer`, `auto-approve`), with the proposer as the new `author` field on the event envelope.
- A coalesced `stageWrite` without an `instruction` keeps the earlier one.
- The review screen labels discarded and refused decisions.
23 changes: 21 additions & 2 deletions docs/agents/review-queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a
- **Published documents** get a **draft**: the live version stays as it is until someone publishes the changes.
- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them.

Every commit records a **revision**, and every review decision lands in the **audit trail**.
Every commit records a **revision**, and every decision (a direct save, an approval, a rejection, a discarded draft, a scheduled publish, an import) lands in the **audit trail**.

Pending proposals have a monotonically increasing `version`. Send the version shown to the reviewer as `expectedVersion` when calling `approveChange` or `rejectChange`; the built-in review screen does this automatically. A rejected, replaced or already decided proposal conflicts even with `force: true`. `force` overrides a stale live revision, while `forceDelete` separately opts into deleting referenced content and records a forced deletion in revision history.

Expand All @@ -46,7 +46,7 @@ The rules come from the session's role, so custom roles and collection `access`

## Agent Writes Are Always Staged

Agents work through the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas). The write tools (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`) all call `stageWrite()`. No agent tool commits, publishes, or deletes, whatever the role of the user or API key behind it. Proposing a deletion still needs delete rights (`content.delete` and the collection's `delete` rule), and proposing an unpublish needs publish rights, so an author's agent cannot fill the queue with deletions.
Agents work through the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas). The write tools (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`) all call `stageWrite()`. No agent tool commits, publishes, or deletes, whatever the role of the user or API key behind it, unless the collection's [strategy](#choosing-the-flow-document-state-strategies) commits staged writes (`review.autoApprove`, `directStrategy()`). Proposing a deletion still needs delete rights (`content.delete` and the collection's `delete` rule), and proposing an unpublish needs publish rights, so an author's agent cannot fill the queue with deletions.

```text
Agent tool call (create / update / delete / unpublish / restore / schedule)
Expand Down Expand Up @@ -93,6 +93,25 @@ The audit entry records both parties, for example `mcp (approved by Jane Doe)`.

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`.

## Choosing the Flow: Document State Strategies

The flow above is the built-in **review** strategy, the default. Every write goes through its collection's document state strategy, which decides what an action (`edit`, `submit`, `approve`, …) does by returning effects such as `stage()`, `commit()` and `publish()`. Core applies them in one transaction and writes the audit entry.

```ts
import { defineCms, directStrategy, reviewStrategy } from '@tanstack/cms-core'

defineCms({
// The default: equal to `review: { autoApprove }`.
documentState: reviewStrategy({ autoApprove: false }),
collections: [
// A personal notes collection: agent and author writes commit at once.
{ ...note, documentState: directStrategy() },
],
})
```

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).

## Optimistic Concurrency

Saves can carry the `_revision` the editor loaded as `expectedRevision`. If the stored document has moved on (someone else saved in the meantime), the save fails with `CONFLICT` and `details: { expectedRevision, actualRevision }` instead of overwriting their work. The admin editor sends it automatically and asks you to reload. HTTP clients pass it the same way:
Expand Down
2 changes: 1 addition & 1 deletion docs/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ Exports committed documents and media metadata as a portable JSON file (`format:
tanstack-cms import <file> [--mode merge|skip-existing|replace] [--yes]
```

Imports an export file. Documents are written as-is: no hooks, validation, reference checks, or review queue, so relations in the file may point at documents that don't exist. `unique` fields are still enforced by the SQL stores' indexes, and a violation aborts the whole import.
Imports an export file. Documents are written as-is: no hooks, validation, reference checks, or review queue, so relations in the file may point at documents that don't exist. `unique` fields are still enforced by the SQL stores' indexes, and a violation aborts the whole import. Each document is an `import` action of its collection's document state strategy, as actor `import`: it is audited and emits `import.document`, and the import emits `import.completed` (not `document.*`, so a restore doesn't refire publication side effects). A strategy that refuses one document aborts the whole import.

| Option | Description |
| --- | --- |
Expand Down
49 changes: 46 additions & 3 deletions docs/api/cms-core-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,50 @@ interface StageWriteArgs {
}
```

Validates and stages a change in the review queue without touching the committed document. A second staged write for the same document merges into the existing entry.
Validates and stages a change in the review queue without touching the committed document. A second staged write for the same document merges into the existing entry, keeping the earlier `instruction` when the new write has none.

The write is the collection's [document state strategy](../agents/review-queue#choosing-the-flow-document-state-strategies) `submit` action (`draft` for `source: 'draft'`). When the strategy commits it at once (`review.autoApprove`, or `directStrategy()`), the returned entry's `after` is the committed document and nothing is left in the queue.

### `submitWrite(args)`

```ts
function submitWrite(args: StageWriteArgs): Promise<StrategyOutcome & { change: IncomingChange }>
```

`stageWrite` that returns the strategy's outcome instead of a queue entry: `pending` (the change set it staged, or `null`), `committed` (the live document when the strategy committed the write), `effects`, and the `strategy` key (`review@1`). Use it to tell a staged write from one that went live.

### `documentStateStrategy(collection)`

Returns the document state strategy a collection uses: its own `documentState`, else `defineCms({ documentState })`, else `reviewStrategy({ autoApprove: review.autoApprove })`.

### `actOnDocument(ctx, args)`, `availableDocumentActions(ctx, collection, id)` and `documentStateLabel(collection, id)`

```ts
function actOnDocument(
ctx: AccessContext,
args: { collection: string; id: string; action: Action },
): Promise<StrategyOutcome>

function availableDocumentActions(
ctx: AccessContext,
collection: string,
id: string,
): Promise<ReadonlyArray<ActionDescriptor>>

function documentStateLabel(collection: string, id: string): Promise<string>
```

`actOnDocument` runs any action of the collection's strategy (`approve`, `discard`, or a custom one such as `approve:legal`) as `ctx`, under core's rules; an `action.patch` is validated the way staging does first. A refused decision is audited and thrown as `FORBIDDEN` with `details: { action, rule, reason }`. `availableDocumentActions` is what the strategy offers `ctx` on the document now, and `documentStateLabel` names its state.

```ts validate=type
import { actOnDocument, systemContext } from '@tanstack/cms-core/server'

await actOnDocument(systemContext('nightly legal sign-off'), {
collection: 'post',
id: 'launch',
action: { type: 'approve:legal' },
})
```

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

Expand All @@ -490,7 +533,7 @@ interface ApproveOptions {
function reject(pendingId: string, options?: { rejecter?: string; expectedVersion?: number }): Promise<Pending>
```

`approve` commits a staged change (document, revision, and audit entry); `reject` drops it and records the decision.
`approve` commits a staged change (document, revision, and audit entry); `reject` drops it and records the decision. Events after `approve` name the approver as the actor and carry the proposer as `author`.

```ts validate=type
import { approve, listPending } from '@tanstack/cms-core/server'
Expand Down Expand Up @@ -884,7 +927,7 @@ interface ImportResult {
}
```

Restores an export. Documents are written as-is: no hooks, validation, or review queue. `merge` creates or overwrites each document, `skip-existing` only creates missing ones, and `replace` also deletes documents of the imported collections that are not in the file.
Restores an export. Documents are written as-is: no hooks, validation, or review queue. Each write is the collection strategy's `import` action (actor `import`, or `options.actor`), audited, with `import.document` per document and `import.completed` at the end. `merge` creates or overwrites each document, `skip-existing` only creates missing ones, and `replace` also deletes documents of the imported collections that are not in the file.

```ts validate=type
import { readFile } from 'node:fs/promises'
Expand Down
10 changes: 6 additions & 4 deletions docs/architecture/terminology.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ The locator lives in the system namespace next to `id`, so a user field named `l

## Document state strategy

**Planned.** The per-collection lifecycle of a document's edits: which actions exist (`edit`, `approve`, `publish`, …), who may take them, and what happens when they do. It's set per app in `defineCms` and can be overridden per collection. Every write passes through the collection's strategy; the strategy decides how much governance happens inside it.
**Partly implemented.** The per-collection lifecycle of a document's edits: which actions exist (`edit`, `approve`, `publish`, …), who may take them, and what happens when they do. It's set per app in `defineCms` and can be overridden per collection. Every write passes through the collection's strategy; the strategy decides how much governance happens inside it.

A strategy is a small object. Given the [access context](#access-context), the document and an action, it returns a decision: a new state plus a list of [effects](#effect), or a rejection. It also answers "which actions can this actor take?" and "what is this state called?" for the admin UI. Its state is a serializable value that core stores and never interprets. It's versioned (`legal-review@1`), and a version that removes states must provide `migrate(state)`.

Planned built-ins: **review** (Draft → Pending Review → Approved → Published) and **direct** (an edit publishes immediately, for personal apps). Complex flows, such as legal and editorial approval running in parallel, can be written with XState. XState is a documented option, not the engine.

**Today:** one implicit flow. Writes either commit (publishers) or stage into the review queue, and approving a staged change commits it. `review.autoApprove` loosens it.
**Today:** the interface, the effects and core's rules exist, with two built-ins that reproduce the one flow from before: `reviewStrategy()` (the default; writes either commit for publishers or stage into the review queue, approving a staged change commits it, and `review.autoApprove` loosens it) and `directStrategy()` (agent and author writes commit at once). Set one with `defineCms({ documentState })` or a collection's `documentState`. Every write door goes through it: saves, staging, approve, reject, drafts, the scheduler and `tanstack-cms import`. **Planned:** the strategy's state stored with the change set, available actions and labels in the admin UI, and the new default-flow naming.

## Change set

Expand All @@ -66,7 +66,7 @@ Planned built-ins: **review** (Draft → Pending Review → Approved → Publish

## Effect

**Planned.** The only way a strategy changes anything. A strategy returns effects and core applies them:
**Implemented.** The only way a strategy changes anything. A strategy returns effects and core applies them:

| Effect | Meaning |
| --- | --- |
Expand All @@ -82,7 +82,9 @@ Rules core enforces on every decision, whatever the strategy:

- A decision's effects and new state apply together in one transaction, or not at all.
- A live document's visible content changes only through `publish`. A `commit` on a live doc without `publish` is rejected.
- Audit isn't an effect. Core records the actor, action, from/to state and effects for every decision.
- Audit isn't an effect. Core records the actor, action, from/to state and effects for every decision, including refused ones. (Today: the actor, the action and the outcome; from/to state and effects are planned.)
- A decision that receives an incoming change must stage or commit it.
- Strategies can't emit `document.*` events; those are core's.
- Core emits `document.published` and `document.unpublished` from the `publish` and `unpublish` effects, so search, webhooks and connectors work with any strategy.
- Agents can't cause a publish unless the strategy grants it to agents.

Expand Down
19 changes: 15 additions & 4 deletions packages/api/src/ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ import {
createDbUser,
setDbUserDisabled,
getPending,
stageWrite,
submitWrite,
listComments,
resolveComment,
deleteComment,
Expand Down Expand Up @@ -421,7 +421,7 @@ async function saveAsHuman(
session,
)
if (!canPublish(session, collection, existing ?? safe)) {
const pending = await stageWrite({
const outcome = await submitWrite({
collection,
docId: id,
type: existing || !opts.create ? 'update' : 'create',
Expand All @@ -434,11 +434,22 @@ async function saveAsHuman(
opts.expectedRevision ??
(typeof existing?._revision === 'number' ? existing._revision : 0),
})
if (outcome.committed || !outcome.pending) {
return {
ok: true,
staged: false,
doc: redactFor(
ctx.access,
collection,
(outcome.committed ?? outcome.change.doc) as Doc,
),
}
}
return {
ok: true,
staged: true,
pendingId: pending.id,
doc: redactFor(ctx.access, collection, pending.after as Doc),
pendingId: outcome.pending.id,
doc: redactFor(ctx.access, collection, outcome.pending.after as Doc),
}
}
const isDraft =
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/outputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ export const writeOutput = z.object({
ok: z.literal(true),
staged: z
.boolean()
.describe('True when the change went to the review queue instead of live.'),
.describe(
'True when the change went to the review queue; false when it is live (including an auto-approved save) or saved as a draft.',
),
draft: z
.boolean()
.optional()
Expand Down
20 changes: 10 additions & 10 deletions packages/api/tests/characterization/save-paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@
* Rows labelled `known bug, fixed in phase 4 (#N: …)`, with the test name
* suffixed `[known bug, fixed in phase 4 (#N)]`, pin behaviour that was ruled
* a bug on 2026-11-05 (cms-refactor-plan.md § Phase 4). They stay green until
* phase 4 fixes the bug and updates the row in the same diff. N matches the
* decision list (#1–#10) in workflow-suite.ts; this table covers #4 (one pending change
* mixes sources), #5 (a direct commit leaves a stale proposal behind) and #6
* (autoApprove saves report `staged: true`).
* phase 4 fixes the bug and updates the row in the same diff; rows marked
* `fixed in phase 4a (#N)` pin the fix. N matches the decision list (#1–#10)
* in workflow-suite.ts; this table covers #4 (one pending change mixes
* sources), #5 (a direct commit leaves a stale proposal behind) and #6
* (autoApprove saves report `staged: true`, fixed in phase 4a).
*/
import { afterEach, describe, expect, it } from 'vitest'
import {
Expand Down Expand Up @@ -356,24 +357,23 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => {
expect(res.status).toBe(409)
})

it('review.autoApprove: the save is live at once, yet the result still says staged with a pendingId [known bug, fixed in phase 4 (#6)]', async () => {
it('review.autoApprove: the save is live at once, and the result reports it as live', async () => {
await seed({ review: { autoApprove: true } })
const out = await write(
'saveDoc',
{ collection: 'post', id: 'wip', doc: { title: 'Auto' } },
'author',
)
// known bug, fixed in phase 4 (#6: autoApprove reports staged) — the
// change is live, so the result should report it as live.
// fixed in phase 4a (#6: autoApprove reports staged) — the change is
// live, so the result reports it as live.
expect(out).toMatchObject({
staged: true,
pendingId: expect.any(String),
staged: false,
doc: { title: 'Auto', _revision: 2 },
})
expect(out.pendingId).toBeUndefined()
expect(await listPending()).toEqual([])
expect((await readDocument('post', 'wip'))?.title).toBe('Auto')
expect((await listAudit())[0]).toMatchObject({
id: out.pendingId,
actor: 'human (approved by auto-approve)',
decision: 'approved',
})
Expand Down
3 changes: 2 additions & 1 deletion packages/api/tests/ops.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ describe('activity log', () => {
expect(review).toBeTruthy()
expect(review.docId).toBe('draft')
expect(review.type).toBe('update')
expect(review.action).toBeUndefined()
// Document entries name the document state strategy action.
expect(review.action).toBe('reject')
})
})
Loading
Loading