You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 8558d8e
Browse filesBrowse the repository at this point in the historyBrowse files
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>
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.
Copy file name to clipboardExpand all lines: docs/agents/review-queue.md
+21-2Lines changed: 21 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -22,7 +22,7 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a
22
22
-**Published documents** get a **draft**: the live version stays as it is until someone publishes the changes.
23
23
-**Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them.
24
24
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**.
26
26
27
27
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.
28
28
@@ -46,7 +46,7 @@ The rules come from the session's role, so custom roles and collection `access`
46
46
47
47
## Agent Writes Are Always Staged
48
48
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.
@@ -93,6 +93,25 @@ The audit entry records both parties, for example `mcp (approved by Jane Doe)`.
93
93
94
94
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`.
95
95
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.
// 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
+
96
115
## Optimistic Concurrency
97
116
98
117
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:
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.
Thewriteisthecollection'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`isthecommitteddocumentandnothingisleftinthequeue.
470
+
471
+
### `submitWrite(args)`
472
+
473
+
```ts
474
+
function submitWrite(args: StageWriteArgs): Promise<StrategyOutcome & { change: IncomingChange }>
475
+
```
476
+
477
+
`stageWrite`thatreturnsthestrategy'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.
function documentStateLabel(collection: string, id: string): Promise<string>
498
+
```
499
+
500
+
`actOnDocument`runsanyactionofthecollection's strategy (`approve`, `discard`, or a custom one such as `approve:legal`) as `ctx`, under core'srules; an`action.patch`isvalidatedthewaystagingdoesfirst. Arefuseddecisionisauditedandthrownas`FORBIDDEN`with`details: { action, rule, reason }`. `availableDocumentActions`iswhatthestrategyoffers`ctx`onthedocumentnow, and`documentStateLabel`namesitsstate.
501
+
502
+
```ts validate=type
503
+
import { actOnDocument, systemContext } from '@tanstack/cms-core/server'
Restoresanexport. Documentsarewrittenas-is: nohooks, validation, orreviewqueue. Eachwriteisthecollectionstrategy'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.
Copy file name to clipboardExpand all lines: docs/architecture/terminology.md
+6-4Lines changed: 6 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -50,13 +50,13 @@ The locator lives in the system namespace next to `id`, so a user field named `l
50
50
51
51
## Document state strategy
52
52
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.
54
54
55
55
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)`.
56
56
57
57
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.
58
58
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.
**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:
70
70
71
71
| Effect | Meaning |
72
72
| --- | --- |
@@ -82,7 +82,9 @@ Rules core enforces on every decision, whatever the strategy:
82
82
83
83
- A decision's effects and new state apply together in one transaction, or not at all.
84
84
- 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.
86
88
- Core emits `document.published` and `document.unpublished` from the `publish` and `unpublish` effects, so search, webhooks and connectors work with any strategy.
87
89
- Agents can't cause a publish unless the strategy grants it to agents.
0 commit comments