Skip to content

Commit 8558d8e

Browse files
cursoragentjherr
andcommitted
feat(core): document state strategies with review and direct built-ins (4a) (#27)
Chain step 11 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: jherr <jherr@pobox.com>
1 parent 4f8e841 commit 8558d8e

38 files changed

Lines changed: 3102 additions & 905 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@tanstack/cms-core': minor
3+
'@tanstack/cms-api': minor
4+
'@tanstack/cms-ui-react': patch
5+
---
6+
7+
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)`.
8+
9+
Behaviour changes (bug fixes):
10+
11+
- 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`.
12+
- `discardDraft` is audited as `discarded` and no longer emits `review.rejected`.
13+
- With `review.autoApprove`, `saveDoc` reports the save as live (`staged: false`, no `pendingId`) instead of `staged: true`.
14+
- `importContent` (`tanstack-cms import`, seeding) is audited and emits `import.document` per document and `import.completed`.
15+
- 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.
16+
- A coalesced `stageWrite` without an `instruction` keeps the earlier one.
17+
- The review screen labels discarded and refused decisions.

‎docs/agents/review-queue.md‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a
2222
- **Published documents** get a **draft**: the live version stays as it is until someone publishes the changes.
2323
- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them.
2424

25-
Every commit records a **revision**, and every review decision lands in the **audit trail**.
25+
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**.
2626

2727
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.
2828

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

4747
## Agent Writes Are Always Staged
4848

49-
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.
49+
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.
5050

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

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

96+
## Choosing the Flow: Document State Strategies
97+
98+
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.
99+
100+
```ts
101+
import { defineCms, directStrategy, reviewStrategy } from '@tanstack/cms-core'
102+
103+
defineCms({
104+
// The default: equal to `review: { autoApprove }`.
105+
documentState: reviewStrategy({ autoApprove: false }),
106+
collections: [
107+
// A personal notes collection: agent and author writes commit at once.
108+
{ ...note, documentState: directStrategy() },
109+
],
110+
})
111+
```
112+
113+
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).
114+
96115
## Optimistic Concurrency
97116

98117
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:

‎docs/api/cli.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ Exports committed documents and media metadata as a portable JSON file (`format:
118118
tanstack-cms import <file> [--mode merge|skip-existing|replace] [--yes]
119119
```
120120

121-
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.
121+
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.
122122

123123
| Option | Description |
124124
| --- | --- |

‎docs/api/cms-core-server.md‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,50 @@ interface StageWriteArgs {
464464
}
465465
```
466466

467-
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.
467+
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.
468+
469+
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.
470+
471+
### `submitWrite(args)`
472+
473+
```ts
474+
function submitWrite(args: StageWriteArgs): Promise<StrategyOutcome & { change: IncomingChange }>
475+
```
476+
477+
`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.
478+
479+
### `documentStateStrategy(collection)`
480+
481+
Returns the document state strategy a collection uses: its own `documentState`, else `defineCms({ documentState })`, else `reviewStrategy({ autoApprove: review.autoApprove })`.
482+
483+
### `actOnDocument(ctx, args)`, `availableDocumentActions(ctx, collection, id)` and `documentStateLabel(collection, id)`
484+
485+
```ts
486+
function actOnDocument(
487+
ctx: AccessContext,
488+
args: { collection: string; id: string; action: Action },
489+
): Promise<StrategyOutcome>
490+
491+
function availableDocumentActions(
492+
ctx: AccessContext,
493+
collection: string,
494+
id: string,
495+
): Promise<ReadonlyArray<ActionDescriptor>>
496+
497+
function documentStateLabel(collection: string, id: string): Promise<string>
498+
```
499+
500+
`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.
501+
502+
```ts validate=type
503+
import { actOnDocument, systemContext } from '@tanstack/cms-core/server'
504+
505+
await actOnDocument(systemContext('nightly legal sign-off'), {
506+
collection: 'post',
507+
id: 'launch',
508+
action: { type: 'approve:legal' },
509+
})
510+
```
468511

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

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

493-
`approve` commits a staged change (document, revision, and audit entry); `reject` drops it and records the decision.
536+
`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`.
494537

495538
```ts validate=type
496539
import { approve, listPending } from '@tanstack/cms-core/server'
@@ -884,7 +927,7 @@ interface ImportResult {
884927
}
885928
```
886929

887-
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.
930+
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.
888931

889932
```ts validate=type
890933
import { readFile } from 'node:fs/promises'

‎docs/architecture/terminology.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,13 @@ The locator lives in the system namespace next to `id`, so a user field named `l
5050

5151
## Document state strategy
5252

53-
**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.
53+
**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.
5454

5555
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)`.
5656

5757
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.
5858

59-
**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.
59+
**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.
6060

6161
## Change set
6262

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

6767
## Effect
6868

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

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

8383
- A decision's effects and new state apply together in one transaction, or not at all.
8484
- A live document's visible content changes only through `publish`. A `commit` on a live doc without `publish` is rejected.
85-
- Audit isn't an effect. Core records the actor, action, from/to state and effects for every decision.
85+
- 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.)
86+
- A decision that receives an incoming change must stage or commit it.
87+
- Strategies can't emit `document.*` events; those are core's.
8688
- Core emits `document.published` and `document.unpublished` from the `publish` and `unpublish` effects, so search, webhooks and connectors work with any strategy.
8789
- Agents can't cause a publish unless the strategy grants it to agents.
8890

‎packages/api/src/ops.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ import {
8484
createDbUser,
8585
setDbUserDisabled,
8686
getPending,
87-
stageWrite,
87+
submitWrite,
8888
listComments,
8989
resolveComment,
9090
deleteComment,
@@ -421,7 +421,7 @@ async function saveAsHuman(
421421
session,
422422
)
423423
if (!canPublish(session, collection, existing ?? safe)) {
424-
const pending = await stageWrite({
424+
const outcome = await submitWrite({
425425
collection,
426426
docId: id,
427427
type: existing || !opts.create ? 'update' : 'create',
@@ -434,11 +434,22 @@ async function saveAsHuman(
434434
opts.expectedRevision ??
435435
(typeof existing?._revision === 'number' ? existing._revision : 0),
436436
})
437+
if (outcome.committed || !outcome.pending) {
438+
return {
439+
ok: true,
440+
staged: false,
441+
doc: redactFor(
442+
ctx.access,
443+
collection,
444+
(outcome.committed ?? outcome.change.doc) as Doc,
445+
),
446+
}
447+
}
437448
return {
438449
ok: true,
439450
staged: true,
440-
pendingId: pending.id,
441-
doc: redactFor(ctx.access, collection, pending.after as Doc),
451+
pendingId: outcome.pending.id,
452+
doc: redactFor(ctx.access, collection, outcome.pending.after as Doc),
442453
}
443454
}
444455
const isDraft =

‎packages/api/src/outputs.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ export const writeOutput = z.object({
7979
ok: z.literal(true),
8080
staged: z
8181
.boolean()
82-
.describe('True when the change went to the review queue instead of live.'),
82+
.describe(
83+
'True when the change went to the review queue; false when it is live (including an auto-approved save) or saved as a draft.',
84+
),
8385
draft: z
8486
.boolean()
8587
.optional()

‎packages/api/tests/characterization/save-paths.test.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@
1515
* Rows labelled `known bug, fixed in phase 4 (#N: …)`, with the test name
1616
* suffixed `[known bug, fixed in phase 4 (#N)]`, pin behaviour that was ruled
1717
* a bug on 2026-11-05 (cms-refactor-plan.md § Phase 4). They stay green until
18-
* phase 4 fixes the bug and updates the row in the same diff. N matches the
19-
* decision list (#1–#10) in workflow-suite.ts; this table covers #4 (one pending change
20-
* mixes sources), #5 (a direct commit leaves a stale proposal behind) and #6
21-
* (autoApprove saves report `staged: true`).
18+
* phase 4 fixes the bug and updates the row in the same diff; rows marked
19+
* `fixed in phase 4a (#N)` pin the fix. N matches the decision list (#1–#10)
20+
* in workflow-suite.ts; this table covers #4 (one pending change mixes
21+
* sources), #5 (a direct commit leaves a stale proposal behind) and #6
22+
* (autoApprove saves report `staged: true`, fixed in phase 4a).
2223
*/
2324
import { afterEach, describe, expect, it } from 'vitest'
2425
import {
@@ -356,24 +357,23 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => {
356357
expect(res.status).toBe(409)
357358
})
358359

359-
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 () => {
360+
it('review.autoApprove: the save is live at once, and the result reports it as live', async () => {
360361
await seed({ review: { autoApprove: true } })
361362
const out = await write(
362363
'saveDoc',
363364
{ collection: 'post', id: 'wip', doc: { title: 'Auto' } },
364365
'author',
365366
)
366-
// known bug, fixed in phase 4 (#6: autoApprove reports staged) — the
367-
// change is live, so the result should report it as live.
367+
// fixed in phase 4a (#6: autoApprove reports staged) — the change is
368+
// live, so the result reports it as live.
368369
expect(out).toMatchObject({
369-
staged: true,
370-
pendingId: expect.any(String),
370+
staged: false,
371371
doc: { title: 'Auto', _revision: 2 },
372372
})
373+
expect(out.pendingId).toBeUndefined()
373374
expect(await listPending()).toEqual([])
374375
expect((await readDocument('post', 'wip'))?.title).toBe('Auto')
375376
expect((await listAudit())[0]).toMatchObject({
376-
id: out.pendingId,
377377
actor: 'human (approved by auto-approve)',
378378
decision: 'approved',
379379
})

‎packages/api/tests/ops.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,7 @@ describe('activity log', () => {
458458
expect(review).toBeTruthy()
459459
expect(review.docId).toBe('draft')
460460
expect(review.type).toBe('update')
461-
expect(review.action).toBeUndefined()
461+
// Document entries name the document state strategy action.
462+
expect(review.action).toBe('reject')
462463
})
463464
})

0 commit comments

Comments
 (0)