diff --git a/.changeset/document-state-acceptance.md b/.changeset/document-state-acceptance.md new file mode 100644 index 00000000..29603aa5 --- /dev/null +++ b/.changeset/document-state-acceptance.md @@ -0,0 +1,10 @@ +--- +'@tanstack/cms-core': minor +--- + +The document state strategy acceptance suite ships as `@tanstack/cms-core/document-state/acceptance`: `runDocumentStateAcceptance(name, { database, strategies }, runner)` runs the parallel-approval spec (eleven steps plus core's rules) with an injected test runner and strategies, and the built-in SQLite, libsql and Postgres storages all run it. The XState parallel-approval example in the new "Custom Document State Strategies" docs page passes it. New exports: `stateGraphToMermaid(graph)` (a Mermaid chart of a strategy's `describe()`; the review-queue docs embed the default strategy's) and, from `@tanstack/cms-core/server`, `readChangeSet(collection, id)` (the open change set as its strategy reads it). + +Breaking changes: + +- Core no longer asks the strategy about a stranded change set. Every action on it except `discard` is refused (`rule: 'stranded'`), and core runs the `discard` itself for a reviewer (`review.decide`, not an agent); a strategy's emits on that discard no longer run. `availableDocumentActions` offers reviewers only **Discard change set** on it, and `documentStateLabel` reads `Stranded`. +- An audit entry's `to` records the state a closing decision returned (for example the final approval's `published`); it was always `null` once the change set closed. diff --git a/.changeset/review-queue-strategy-actions.md b/.changeset/review-queue-strategy-actions.md new file mode 100644 index 00000000..a1692d64 --- /dev/null +++ b/.changeset/review-queue-strategy-actions.md @@ -0,0 +1,8 @@ +--- +'@tanstack/cms-api': minor +'@tanstack/cms-ui-react': minor +--- + +The review queue follows each collection's document state strategy. `reviewSnapshot` items carry `review: { label, actions, stranded? }` (type `ChangeSetReview`: the strategy's state label and the actions it offers the caller), and the new `actOnChange({ id, action, publishAt?, reason?, expectedVersion? })` operation (also a `createServerFn` in `@tanstack/cms-api/start`) runs any offered action that doesn't carry a document, such as a custom sign-off, `schedule` or `discard`. The `/review` page shows the label, renders buttons from the offered actions (Approve and Reject only when the strategy offers them), lets reviewers set or clear a change set's publish time, and lists stranded change sets with a **Discard change set** button. + +Behavior change: `reviewSnapshot` now also lists stranded drafts (a stranded change set has to be discarded from the queue), and the Approve and Reject buttons follow the strategy's offered actions instead of the caller's `review.decide` permission alone. diff --git a/docs/agents/ai-images.md b/docs/agents/ai-images.md index ae92477c..5107ca68 100644 --- a/docs/agents/ai-images.md +++ b/docs/agents/ai-images.md @@ -1,7 +1,7 @@ --- title: Media & AI Images id: ai-images -order: 4 +order: 5 description: "Upload, browse, and render images in TanStack CMS, and generate or edit them with an app-supplied @tanstack/ai image adapter." keywords: - tanstack cms diff --git a/docs/agents/custom-strategies.md b/docs/agents/custom-strategies.md new file mode 100644 index 00000000..c9801856 --- /dev/null +++ b/docs/agents/custom-strategies.md @@ -0,0 +1,588 @@ +--- +title: Custom Document State Strategies +id: custom-strategies +order: 4 +description: "Write your own document state strategy for TanStack CMS: a legal and editorial sign-off that runs in parallel, built with XState, charted with Mermaid, and proven with the acceptance suite every storage adapter runs." +keywords: + - tanstack cms + - document state strategy + - workflow + - parallel approval + - xstate + - actOnDocument + - availableDocumentActions + - runDocumentStateAcceptance +--- + +The built-in [review strategy](./review-queue#choosing-the-flow-document-state-strategies) covers the common flow: publishers save, everyone else proposes, a reviewer approves. When a collection needs its own flow, write a **document state strategy**. This page builds one where a legal and an editorial reviewer sign off **in parallel**, in either order, before a change goes live. + +## The Contract + +A strategy is a plain object. Core asks it what an action does and runs the answer; it never interprets the strategy's state. + +- `decide(ctx, doc, action)` returns a new `state` and the `effects` to run (`stage()`, `commit()`, `publish()`, `unpublish()`, `schedule({ publishAt })`, `discard()`, `emit(event, payload)`), or `{ reject: reason }`. +- `availableActions(ctx, doc)` lists what `ctx` may do now. The admin shows these as buttons. +- `label(state, doc)` is the status the admin shows. +- `describe()` returns the state graph for the chart below. +- `migrate({ version, state })` upgrades change sets an older `version` wrote. + +Core stores `state` on the document's one open change set with the strategy's `id@version`, writes the audit entry for every decision, emits the `document.*` events, and refuses a decision that breaks its rules (see [Review Queue](./review-queue#choosing-the-flow-document-state-strategies)): a published document's content changes only with `publish`, an incoming change must be staged or committed, `document.*` events are core's, and agents publish only where `grants.publish` lists `agent`. + +## Parallel Approval with XState + +`legal-review` works like this: + +- An **author's** `edit` stages the change set with both approvals pending. A new edit resets them. +- A user with the `legal` role sees **Approve (legal)** and **Reject (legal)**; an `editor` sees the editorial pair. The author sees neither. +- The last approval commits and publishes, or, if the author asked for a `publishAt`, schedules the change set; the scheduler then fires `publish` as actor `scheduler`. +- A rejection sends the change set back to the author (`changesRequested`) and emits `legal-review.rejected`. + +XState is optional: core never imports it. The machine runs through XState's pure `transition()`, so `decide` keeps no actor alive between requests, and the stored state is the snapshot's plain JSON. + +```ts validate=type +/** + * `legal-review`: legal and editorial approval run in parallel on one change + * set, as an XState machine behind the `DocumentStateStrategy` interface. + * Core never imports XState; it stores what `decide` returns. + * + * The persisted state is the snapshot's `value` and `context` (plain JSON). + * The machine runs through XState's pure `transition()`, so `decide` has no + * running actor to keep alive between requests. + */ +import { assign, initialTransition, setup, transition } from 'xstate' +import { + actorOf, + commit, + discard, + emit, + publish, + schedule, + stage, +} from '@tanstack/cms-core' +import type { AnyStateNode, StateValue } from 'xstate' +import type { + AccessContext, + Action, + ActionDescriptor, + DocView, + DocumentStateStrategy, + Effect, + StateGraph, + StrategyActor, +} from '@tanstack/cms-core' + +export interface LegalReviewContext { + /** A publish time the author asked for; approvals gate it. */ + publishAt: string | null +} + +export interface LegalReviewState { + value: StateValue + context: LegalReviewContext +} + +type Region = 'legal' | 'editorial' + +type LegalReviewEvent = + | { type: 'edit'; actor: StrategyActor; publishAt: string | null } + | { type: 'discard'; actor: StrategyActor } + | { type: 'publish'; actor: StrategyActor } + | { type: `approve:${Region}`; actor: StrategyActor } + | { type: `reject:${Region}`; actor: StrategyActor; reason: string } + +const REVIEWER_ROLE: Record = { + legal: 'legal', + editorial: 'editor', +} + +function hasRole(actor: StrategyActor, role: string): boolean { + return actor.roles.includes(role) +} + +interface MachineOptions { + /** + * v1 sends a rejected change set back to the author ("changes requested"). + * v2 drops that state: a rejection discards the change set. + */ + onReject: 'changesRequested' | 'discard' +} + +function createLegalReviewMachine({ onReject }: MachineOptions) { + const rejected = + onReject === 'changesRequested' + ? '#legal-review.changesRequested' + : '#legal-review.discarded' + + return setup({ + types: { + context: {} as LegalReviewContext, + events: {} as LegalReviewEvent, + }, + guards: { + isAuthor: ({ event }) => hasRole(event.actor, 'author'), + isLegal: ({ event }) => hasRole(event.actor, REVIEWER_ROLE.legal), + isEditor: ({ event }) => hasRole(event.actor, REVIEWER_ROLE.editorial), + isScheduler: ({ event }) => event.actor.type === 'scheduler', + hasPublishAt: ({ context }) => context.publishAt !== null, + }, + actions: { + rememberPublishAt: assign({ + publishAt: ({ event }) => + event.type === 'edit' ? event.publishAt : null, + }), + // Effect markers: `transition()` returns them and `decide` maps them + // to effects. Nothing runs inside the machine. + stage: () => {}, + commit: () => {}, + publish: () => {}, + discard: () => {}, + schedule: (_, _params: { publishAt: string }) => {}, + emit: (_, _params: { event: string; region: Region }) => {}, + }, + }).createMachine({ + id: 'legal-review', + initial: 'idle', + context: { publishAt: null }, + states: { + idle: { + on: { + edit: { + guard: 'isAuthor', + target: 'review', + actions: ['stage', 'rememberPublishAt'], + }, + }, + }, + review: { + type: 'parallel', + on: { + // Strategy choice for acceptance step 4: any edit resets both + // approvals. + edit: { + guard: 'isAuthor', + target: 'review', + reenter: true, + actions: ['stage', 'rememberPublishAt'], + }, + discard: { guard: 'isAuthor', target: 'discarded' }, + }, + states: { + legal: { + initial: 'pending', + states: { + pending: { + on: { + 'approve:legal': { guard: 'isLegal', target: 'approved' }, + 'reject:legal': { + guard: 'isLegal', + target: rejected, + actions: { + type: 'emit', + params: { + event: 'legal-review.rejected', + region: 'legal', + }, + }, + }, + }, + }, + approved: { type: 'final' }, + }, + }, + editorial: { + initial: 'pending', + states: { + pending: { + on: { + 'approve:editorial': { + guard: 'isEditor', + target: 'approved', + }, + 'reject:editorial': { + guard: 'isEditor', + target: rejected, + actions: { + type: 'emit', + params: { + event: 'legal-review.rejected', + region: 'editorial', + }, + }, + }, + }, + }, + approved: { type: 'final' }, + }, + }, + }, + // Both regions final: publish now, or at the time the author asked for. + onDone: [ + { + guard: 'hasPublishAt', + target: 'scheduled', + actions: { + type: 'schedule', + params: ({ context }) => ({ publishAt: context.publishAt ?? '' }), + }, + }, + { target: 'published', actions: ['commit', 'publish'] }, + ], + }, + ...(onReject === 'changesRequested' + ? { + changesRequested: { + on: { + edit: { + guard: 'isAuthor', + target: 'review', + actions: ['stage', 'rememberPublishAt'], + }, + discard: { guard: 'isAuthor', target: 'discarded' }, + }, + }, + } + : {}), + scheduled: { + on: { + edit: { + guard: 'isAuthor', + target: 'review', + actions: ['stage', 'rememberPublishAt'], + }, + discard: { guard: 'isAuthor', target: 'discarded' }, + publish: { + guard: 'isScheduler', + target: 'published', + actions: ['commit', 'publish'], + }, + }, + }, + published: { type: 'final' }, + discarded: { type: 'final', entry: 'discard' }, + }, + }) +} + +type LegalReviewMachine = ReturnType + +const CANDIDATE_ACTIONS: ReadonlyArray = [ + { type: 'edit', label: 'Save changes', tone: 'primary' }, + { type: 'approve:legal', label: 'Approve (legal)', tone: 'primary' }, + { type: 'reject:legal', label: 'Reject (legal)', tone: 'danger' }, + { type: 'approve:editorial', label: 'Approve (editorial)', tone: 'primary' }, + { type: 'reject:editorial', label: 'Reject (editorial)', tone: 'danger' }, + { type: 'discard', label: 'Discard changes', tone: 'danger' }, + { type: 'publish', label: 'Publish' }, +] + +function toEvent(ctx: AccessContext, action: Action): LegalReviewEvent | null { + const actor = actorOf(ctx) + switch (action.type) { + case 'edit': { + const at = action.input?.publishAt + return { + type: 'edit', + actor, + publishAt: typeof at === 'string' ? at : null, + } + } + case 'discard': + case 'publish': + case 'approve:legal': + case 'approve:editorial': + return { type: action.type, actor } + case 'reject:legal': + case 'reject:editorial': { + const reason = action.input?.reason + return { + type: action.type, + actor, + reason: typeof reason === 'string' ? reason : '', + } + } + default: + return null + } +} + +function toEffects( + actions: ReadonlyArray<{ type: string; params: unknown }>, +): Array { + const effects: Array = [] + for (const action of actions) { + const params = (action.params ?? {}) as Record + switch (action.type) { + case 'stage': + effects.push(stage()) + break + case 'commit': + effects.push(commit()) + break + case 'publish': + effects.push(publish()) + break + case 'discard': + effects.push(discard()) + break + case 'schedule': + effects.push(schedule({ publishAt: String(params.publishAt) })) + break + case 'emit': + effects.push(emit(String(params.event), { region: params.region })) + break + // XState built-ins (assign) are already folded into the snapshot. + } + } + return effects +} + +function regionLabel(value: StateValue): string | null { + if (typeof value === 'string') return null + const review = value.review + if (!review || typeof review === 'string') return null + return `legal: ${String(review.legal)}, editorial: ${String(review.editorial)}` +} + +function graphOf(root: AnyStateNode): StateGraph { + const nodes: Array = [] + const edges: Array = [] + const visit = (node: AnyStateNode, parent?: string) => { + if (node !== root) { + nodes.push({ + id: node.id, + label: node.key, + ...(parent && parent !== root.id ? { parent } : {}), + ...(node.type === 'parallel' ? { parallel: true } : {}), + ...(node.type === 'final' ? { final: true } : {}), + }) + } + for (const [eventType, transitions] of node.transitions) { + for (const t of transitions) { + for (const target of t.target ?? []) { + const action = eventType.startsWith('xstate.done.state.') + ? 'done' + : eventType + edges.push({ from: node.id, to: target.id, action }) + } + } + } + for (const child of Object.values(node.states)) visit(child, node.id) + } + visit(root) + return { nodes, edges } +} + +export interface LegalReviewStrategyOptions { + version: number + onReject: MachineOptions['onReject'] + migrate?: DocumentStateStrategy['migrate'] +} + +export function defineLegalReview( + options: LegalReviewStrategyOptions, +): DocumentStateStrategy & { machine: LegalReviewMachine } { + const machine = createLegalReviewMachine({ onReject: options.onReject }) + + const restore = (state: LegalReviewState | undefined) => + state + ? machine.resolveState({ value: state.value, context: state.context }) + : initialTransition(machine)[0] + + const persist = (snapshot: ReturnType): LegalReviewState => ({ + value: snapshot.value, + context: { ...snapshot.context }, + }) + + return { + id: 'legal-review', + version: options.version, + machine, + // No `grants`: agents may edit (and so stage), never publish. + decide(ctx, doc, action) { + const snapshot = restore(doc.changeSet?.workflow?.state) + const event = toEvent(ctx, action) + if (!event || !snapshot.can(event)) { + return { + reject: `${action.type} is not available to ${actorOf(ctx).id} in ${JSON.stringify(snapshot.value)}`, + } + } + const [next, actions] = transition(machine, snapshot, event) + return { state: persist(next), effects: toEffects(actions) } + }, + availableActions(ctx, doc) { + const snapshot = restore(doc.changeSet?.workflow?.state) + return CANDIDATE_ACTIONS.filter((candidate) => { + const event = toEvent(ctx, { type: candidate.type }) + return event !== null && snapshot.can(event) + }) + }, + label(state, doc: DocView) { + const live = doc.live?.published ? 'Published' : 'Unpublished' + if (!state) return live + const regions = regionLabel(state.value) + if (regions) return `Pending review (${regions})` + switch (state.value) { + case 'changesRequested': + return 'Changes requested' + case 'scheduled': + return `Scheduled for ${state.context.publishAt ?? '?'}` + default: + return live + } + }, + describe: () => graphOf(machine.root), + ...(options.migrate ? { migrate: options.migrate } : {}), + } +} + +export const legalReview = defineLegalReview({ + version: 1, + onReject: 'changesRequested', +}) + +/** `@2` removes `changesRequested`; in-flight v1 change sets there resume review. */ +export const legalReviewV2 = defineLegalReview({ + version: 2, + onReject: 'discard', + migrate: ({ state }) => { + const prior = state as LegalReviewState + if (prior.value === 'changesRequested') { + return { + state: { + value: { review: { legal: 'pending', editorial: 'pending' } }, + context: prior.context, + }, + } + } + return { state: prior } + }, +}) + +/** `@2` with no `migrate`: core must report v1 change sets as stranded. */ +export const legalReviewV2WithoutMigrate = defineLegalReview({ + version: 2, + onReject: 'discard', +}) +``` + +Install `xstate` in your app, then set the strategy on the collection. The approver's session also needs the rights core checks before a decision writes live content (`content.write` and `content.publish`), so declare the `legal` role: + +```ts +defineCms({ + roles: { + legal: ['content.read', 'content.write', 'content.publish', 'review.decide'], + }, + collections: [{ ...post, documentState: legalReview }], +}) +``` + +## The Chart + +`stateGraphToMermaid(strategy.describe())` turns a strategy's graph into a Mermaid state diagram. For `legal-review`: + +```mermaid +stateDiagram-v2 + state "idle" as legal_review_idle + state "review" as legal_review_review + state legal_review_review { + state "legal" as legal_review_review_legal + state legal_review_review_legal { + state "pending" as legal_review_review_legal_pending + state "approved" as legal_review_review_legal_approved + legal_review_review_legal_approved --> [*] + legal_review_review_legal_pending --> legal_review_review_legal_approved: approve:legal + } + -- + state "editorial" as legal_review_review_editorial + state legal_review_review_editorial { + state "pending" as legal_review_review_editorial_pending + state "approved" as legal_review_review_editorial_approved + legal_review_review_editorial_approved --> [*] + legal_review_review_editorial_pending --> legal_review_review_editorial_approved: approve:editorial + } + } + state "changesRequested" as legal_review_changesRequested + state "scheduled" as legal_review_scheduled + state "published" as legal_review_published + legal_review_published --> [*] + state "discarded" as legal_review_discarded + legal_review_discarded --> [*] + legal_review_idle --> legal_review_review: edit + legal_review_review --> legal_review_review: edit + legal_review_review --> legal_review_discarded: discard + legal_review_review --> legal_review_scheduled: done + legal_review_review --> legal_review_published: done + legal_review_review_legal_pending --> legal_review_changesRequested: reject:legal + legal_review_review_editorial_pending --> legal_review_changesRequested: reject:editorial + legal_review_changesRequested --> legal_review_review: edit + legal_review_changesRequested --> legal_review_discarded: discard + legal_review_scheduled --> legal_review_review: edit + legal_review_scheduled --> legal_review_discarded: discard + legal_review_scheduled --> legal_review_published: publish +``` + +## Acting on Documents + +The admin and the HTTP API drive strategies through the same server calls you can use directly from `@tanstack/cms-core/server`: + +```ts validate=type +import { + actOnDocument, + availableDocumentActions, + documentStateLabel, + readChangeSet, +} from '@tanstack/cms-core/server' +import type { AccessContext } from '@tanstack/cms-core' + +export async function approveLegal(ctx: AccessContext, id: string) { + const offered = await availableDocumentActions(ctx, 'post', id) + if (!offered.some((a) => a.type === 'approve:legal')) return null + await actOnDocument(ctx, { + collection: 'post', + id, + action: { type: 'approve:legal' }, + }) + return { + label: await documentStateLabel('post', id), + changeSet: await readChangeSet('post', id), + } +} +``` + +A refused decision throws `CmsError` `FORBIDDEN` with `details.rule` naming the rule, and lands in the audit trail as `refused`. The admin review page (`/review`) labels each change set with `label()`, shows the buttons `availableActions()` offers, and runs them with `actOnDocument`. + +## Version Bumps and Stranded Change Sets + +Bump `version` when you change the machine in a way old state can't follow, and give the new version a `migrate` that maps the old state forward. In the example, `legalReviewV2` drops `changesRequested`, and its `migrate` sends those change sets back to review with both approvals pending. `legalReviewV2WithoutMigrate` has no `migrate`, so the same change sets are stranded under it. + +A change set the strategy can't read (another strategy wrote it, there is no `migrate`, or `migrate` returns `{ stranded: reason }`) is **stranded**. Core doesn't ask the strategy about it: it refuses every action except `discard` by a reviewer (`review.decide`), which core runs itself. `listStrandedChangeSets()` lists them, and the review page shows them with a **Discard** button. + +## Proving It: the Acceptance Suite + +`@tanstack/cms-core/document-state/acceptance` exports the suite this example passes: the eleven parallel-approval steps (staging, per-actor actions, either-order approval, resets, publishing, atomic refusals, audit, scheduling, restarts, version bumps) and core's rules. The test runner and the strategies are injected, so it runs under any framework, and every storage adapter runs it: + +```ts +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { runDocumentStateAcceptance } from '@tanstack/cms-core/document-state/acceptance' +import { createLibsqlStorage } from '@tanstack/cms-store-libsql' +import { legalReview, legalReviewV2, legalReviewV2WithoutMigrate } from './legal-review' + +runDocumentStateAcceptance( + 'libsql', + { + // A fresh database per test; the opener runs again on every restart. + database: () => { + const url = `file:${tempFile()}` + return () => createLibsqlStorage({ url }) + }, + strategies: { legalReview, legalReviewV2, legalReviewV2WithoutMigrate }, + }, + { describe, it, expect, beforeEach, afterEach }, +) +``` + +## Next Steps + +- [Review Queue & Drafts](./review-queue) - The built-in strategy and its chart +- [Events & Hooks](../architecture/events-and-hooks) - Reacting to `document.*` and your strategy's own events +- [Authentication & Access Control](../architecture/authentication) - Roles and permissions diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index a0854723..811e1b3f 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -93,6 +93,8 @@ 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 })`. +Each pending change also shows its strategy's label for the document's state (for example **Pending review**, or a custom strategy's **Changes requested**), and its buttons are the actions the strategy offers you, so a custom strategy's actions (such as **Approve (legal)**) appear next to Approve and Reject. When the strategy offers `schedule`, a **Publish at** field sets or clears the change set's publish time, and a **Publishes …** badge shows it. These buttons call `actOnChange({ id, action, publishAt?, reason?, expectedVersion? })`, which runs the action through the strategy and refuses one it doesn't offer you. + 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. @@ -117,9 +119,30 @@ defineCms({ }) ``` +The built-in strategies' states and actions, generated from `reviewStrategy().describe()` with `stateGraphToMermaid`: + +```mermaid +stateDiagram-v2 + state "Unpublished" as unpublished + state "Published" as published + state "Draft" as draft + state "Pending review" as pending_review + unpublished --> pending_review: submit + published --> pending_review: submit + published --> draft: draft + draft --> published: edit + draft --> published: discard + pending_review --> published: approve + pending_review --> unpublished: reject + unpublished --> published: publish + published --> unpublished: unpublish +``` + 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. +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, and the review page offers reviewers a **Discard** button for each. + +To write your own flow, such as a legal and an editorial sign-off in parallel, see [Custom Document State Strategies](./custom-strategies). ## Optimistic Concurrency @@ -205,7 +228,7 @@ interface AuditEntry { | '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) + to?: unknown // and after it (a closing decision's returned state, else null once closed) effects?: Array // the effects the decision ran reason?: string // a refusal's reason, or 'stale' at: string @@ -252,6 +275,7 @@ export async function decide(pendingId: string, ok: boolean, reviewer: string) { ## Next Steps +- [Custom Document State Strategies](./custom-strategies) - Your own approval flow, built with XState - [Conversational Content Agent](./content-agent) - The in-app agent that stages changes - [HTTP MCP Server](../mcp/http-mcp-server) - External agents that stage changes - [Authentication & Access Control](../architecture/authentication) - Who may approve, publish, and delete diff --git a/docs/api/cms-api.md b/docs/api/cms-api.md index b8642785..e8cf79d9 100644 --- a/docs/api/cms-api.md +++ b/docs/api/cms-api.md @@ -184,6 +184,7 @@ function Blog() { | `reviewSnapshot` | GET | `content.read` | | `approveChange` | POST | `review.decide` | | `rejectChange` | POST | `review.decide` | +| `actOnChange` | POST | `content.read` | | `proposeEdit` | POST | `agent.use` | | `agentChat` | POST | `agent.use` | | `editPageBlocks` | POST | `agent.use` | diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index 18784f11..d3b08da2 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -249,9 +249,10 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/ | `discardDraft` | POST | `content.write` | `{ collection, id }` | `{ ok }`. Also needs publish rights. | | `deleteDoc` | POST | `content.delete` | `{ collection, id, force? }` | `{ ok }` | | `bulkDocuments` | POST | `content.write` | `{ collection, ids (1–100), action: 'publish' \| 'unpublish' \| 'delete' }` | `{ ok, results: [{ id, ok, error?: { code, message } }] }`. `delete` also needs `content.delete`; `publish` and `unpublish` need publish rights. One failed item doesn't stop the rest. | -| `reviewSnapshot` | GET | `content.read` | `{}` | `{ pending, audit }` (drafts excluded) | +| `reviewSnapshot` | GET | `content.read` | `{}` | `{ pending, audit }`. Each pending change carries `review: { label, actions, stranded? }` from its strategy, for the caller. Drafts are excluded unless stranded. | | `approveChange` | POST | `review.decide` | `{ id, publish?, force? }` | The approved pending change. `CONFLICT` when the document changed since the proposal was staged, unless `force` is set. | | `rejectChange` | POST | `review.decide` | `{ id }` | The rejected pending change. | +| `actOnChange` | POST | `content.read` | `{ id, action, publishAt?: string \| null, reason?, expectedVersion? }` | `{ ok, effects, label }`. Runs only an action the change set's strategy offers the caller now (`FORBIDDEN` otherwise); actions that carry a document (`edit`, `submit`, `draft`, `import`) are `BAD_REQUEST`. `CONFLICT` when `expectedVersion` is stale. | | `proposeEdit` | POST | `agent.use` | `{ collection, id, instruction, current }` | The AI-proposed document (not saved). | | `agentChat` | POST | `agent.use` | `{ messages: [{ role: 'user' \| 'assistant', content }], includeToolResults? }` | `{ reply, toolResults? }`. Actual tool receipts are opt-in; record writes are staged. | | `editPageBlocks` | POST | `agent.use` | `{ id, collection?, blocksField?, instruction }` | `{ blocks }` (not saved) | diff --git a/docs/config.json b/docs/config.json index 9e4c9183..8c93582d 100644 --- a/docs/config.json +++ b/docs/config.json @@ -193,6 +193,12 @@ "addedAt": "2026-10-04", "updatedAt": "2026-10-08" }, + { + "label": "Custom Document State Strategies", + "to": "agents/custom-strategies", + "addedAt": "2026-11-06", + "updatedAt": "2026-11-06" + }, { "label": "Media & AI Images", "to": "agents/ai-images", diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 5eabcf23..251fec21 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -49,7 +49,7 @@ interface CmsOperation { | `listDocumentSummaries` | GET | `content.read` | Admin list with search, status filter, sort, and pagination | | `getDocument` | GET | `content.read` | One document for editing, with any pending version overlaid | | `getDocEditorMeta` | GET | `content.read` | Revisions, translations, and inbound references | -| `reviewSnapshot` | GET | `content.read` | Pending changes and audit trail | +| `reviewSnapshot` | GET | `content.read` | Pending changes (with their strategy label and the caller's actions) and audit trail | | `saveDoc` | POST | `content.write` | Save a document (commit, draft, or stage for review) | | `createDoc` | POST | `content.write` | Create a document | | `discardDraft` | POST | `content.write` | Drop the draft of a published document (publishers only) | @@ -59,6 +59,7 @@ interface CmsOperation { | `deleteDoc` | POST | `content.delete` | Delete a document (`force` to ignore references) | | `approveChange` | POST | `review.decide` | Approve a staged change (optionally as a draft) | | `rejectChange` | POST | `review.decide` | Reject a staged change | +| `actOnChange` | POST | `content.read` | Run an action the change set's strategy offers the caller (a custom approval, a discard, a schedule) | | `agentChat` | POST | `agent.use` | Conversational content agent | | `proposeEdit` | POST | `agent.use` | AI proposal for a document's fields (does not save) | | `editPageBlocks` | POST | `agent.use` | AI proposal for a page's blocks (does not save) | diff --git a/examples/blog/e2e/cms.spec.ts b/examples/blog/e2e/cms.spec.ts index 09e5a872..08bc3254 100644 --- a/examples/blog/e2e/cms.spec.ts +++ b/examples/blog/e2e/cms.spec.ts @@ -104,7 +104,19 @@ test('an author submits for review and an editor approves', async ({ await signInAs(context, 'editor') await open(page, '/review') await expect(page.getByText('Hello, reviewed world').first()).toBeVisible() - await page.getByRole('button', { name: 'Approve & publish' }).first().click() + const proposal = page + .locator('li') + .filter({ has: page.getByTestId('review-state') }) + .filter({ hasText: 'Hello, reviewed world' }) + await expect(proposal.getByTestId('review-state')).toHaveText( + 'Pending review', + ) + await proposal.getByLabel('Publish at').fill('2999-01-01T09:00') + await proposal.getByRole('button', { name: 'Schedule', exact: true }).click() + await expect(proposal.getByText(/^Publishes /)).toBeVisible() + await proposal.getByRole('button', { name: 'Clear schedule' }).click() + await expect(proposal.getByText(/^Publishes /)).toHaveCount(0) + await proposal.getByRole('button', { name: 'Approve & publish' }).click() await expect( page.getByRole('button', { name: 'Approve & publish' }), ).toHaveCount(0) diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index c6ec80ae..592a9453 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -23,6 +23,7 @@ export { export { aiCapabilities, resolveImageAdapter, resolveTextAdapter } from './ai' export type { CmsAiCapabilityFlags } from './ai' export type { + ChangeSetReview, CmsContext, CmsOpContext, CmsOperation, diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index ce6f361d..859c1751 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -37,8 +37,12 @@ import { whereInput, } from '@tanstack/cms-core' import { + actOnDocument, agentOps, approve, + availableDocumentActions, + documentStateLabel, + readChangeSet, assertTrustedOrigin, runOp, cmsTools, @@ -111,6 +115,7 @@ import { writeOutput, } from './outputs' import type { + ActionDescriptor, Block, CmsOpContext, CmsToolResult, @@ -119,7 +124,11 @@ import type { Doc, OpAccess, } from '@tanstack/cms-core' -import type { AccessContext, ReadMode } from '@tanstack/cms-core/server' +import type { + AccessContext, + Pending, + ReadMode, +} from '@tanstack/cms-core/server' export type { CmsOpContext, OpAccess } @@ -254,6 +263,44 @@ const rejectChangeInput = z.object({ id: z.string(), expectedVersion: z.number().int().min(0).optional(), }) +const actOnChangeInput = z.object({ + id: z.string(), + /** An action the change set's strategy offers the caller (`approve:legal`, `discard`, `schedule`, …). */ + action: z.string().min(1), + /** `schedule`: when the change set goes live; `null` clears it. */ + publishAt: z.string().nullable().optional(), + reason: z.string().max(2000).optional(), + expectedVersion: z.number().int().min(0).optional(), +}) + +/** Actions that carry a document: they go through `saveDoc`, not `actOnChange`. */ +const CHANGE_CARRYING_ACTIONS = new Set(['edit', 'submit', 'draft', 'import']) + +/** What the review queue shows about a change set: from its strategy, for the caller. */ +export interface ChangeSetReview { + /** The strategy's label for the change set's state. */ + label: string + /** The actions the strategy offers the caller now. */ + actions: Array + /** Set when the strategy can't read the change set: only a discard is possible. */ + stranded?: string +} + +async function changeSetReview( + access: AccessContext, + pending: Pending, +): Promise { + const [changeSet, label, actions] = await Promise.all([ + readChangeSet(pending.collection, pending.docId), + documentStateLabel(pending.collection, pending.docId), + availableDocumentActions(access, pending.collection, pending.docId), + ]) + return { + label, + actions: actions.map((a) => ({ ...a })), + ...(changeSet?.stranded ? { stranded: changeSet.stranded } : {}), + } +} const deleteDocInput = docRef.extend({ force: z.boolean().optional() }) const purgeDocInput = docRef.extend({ force: z.boolean().optional() }) const listCommentsInput = docRef @@ -1049,22 +1096,31 @@ const _ops = { run: async (_input: z.infer, ctx: CmsOpContext) => { const access = editing(ctx) const [pending, audit] = await Promise.all([listPending(), listAudit()]) + const readable = pending.filter( + (p) => + canReadCollection(access, p.collection) && + canReadDocument(access, p.collection, { + id: p.docId, + published: false, + doc: p.before ?? p.after, + }), + ) + const reviewed = await Promise.all( + readable.map(async (p) => ({ + p, + review: await changeSetReview(access, p), + })), + ) return { - pending: pending - .filter( - (p) => - p.source !== 'draft' && - canReadCollection(access, p.collection) && - canReadDocument(access, p.collection, { - id: p.docId, - published: false, - doc: p.before ?? p.after, - }), - ) - .map((p) => ({ + // Drafts stay private to their publisher unless stranded: then a + // reviewer has to discard them. + pending: reviewed + .filter(({ p, review }) => p.source !== 'draft' || review.stranded) + .map(({ p, review }) => ({ ...p, before: redactFor(access, p.collection, p.before), after: redactFor(access, p.collection, p.after), + review, })), audit: ( await Promise.all( @@ -1175,6 +1231,77 @@ const _ops = { }, }, + actOnChange: { + method: 'POST', + access: 'content.read', + description: + "Run an action the change set's document state strategy offers the caller (a custom approval, a discard, a schedule).", + input: actOnChangeInput, + run: async (input: z.infer, ctx: CmsOpContext) => { + const pending = await getPending(input.id) + if (!pending) + throw new CmsError(`Unknown pending change: ${input.id}`, 'NOT_FOUND') + if ( + input.expectedVersion !== undefined && + (pending.version ?? 0) !== input.expectedVersion + ) + throw new CmsError( + 'This change set changed since you loaded it. Reload and try again.', + 'CONFLICT', + { pendingId: pending.id }, + ) + const access = editing(ctx) + assertReadable(access, pending.collection, { + id: pending.docId, + doc: + (await readDocument(pending.collection, pending.docId)) ?? + pending.before ?? + pending.after, + }) + if (CHANGE_CARRYING_ACTIONS.has(input.action)) + throw new CmsError( + `"${input.action}" carries a document: save it with saveDoc.`, + 'BAD_REQUEST', + ) + const offered = await availableDocumentActions( + access, + pending.collection, + pending.docId, + ) + if (!offered.some((a) => a.type === input.action)) + throw new CmsError( + `"${input.action}" is not available to you on this change set.`, + 'FORBIDDEN', + ) + if ( + typeof input.publishAt === 'string' && + Number.isNaN(Date.parse(input.publishAt)) + ) + throw new CmsError( + `Invalid publishAt datetime: "${input.publishAt}"`, + 'BAD_REQUEST', + ) + const outcome = await actOnDocument(access, { + collection: pending.collection, + id: pending.docId, + action: { + type: input.action, + input: { + ...(input.publishAt !== undefined + ? { publishAt: input.publishAt } + : {}), + ...(input.reason ? { reason: input.reason } : {}), + }, + }, + }) + return { + ok: true, + effects: outcome.effects.map((e) => e.type), + label: await documentStateLabel(pending.collection, pending.docId), + } + }, + }, + agentChat: { method: 'POST', access: 'agent.use', diff --git a/packages/api/src/start.ts b/packages/api/src/start.ts index 797d0318..f392a93e 100644 --- a/packages/api/src/start.ts +++ b/packages/api/src/start.ts @@ -194,6 +194,10 @@ export const rejectChange = createServerFn({ method: 'POST' }) .validator(ops.rejectChange.input) .handler(async ({ data }) => invokeOp('rejectChange', data, await req())) +export const actOnChange = createServerFn({ method: 'POST' }) + .validator(ops.actOnChange.input) + .handler(async ({ data }) => invokeOp('actOnChange', data, await req())) + export const agentChat = createServerFn({ method: 'POST' }) .validator(ops.agentChat.input) .handler(async ({ data }) => invokeOp('agentChat', data, await req())) diff --git a/packages/api/tests/act-on-change.test.ts b/packages/api/tests/act-on-change.test.ts new file mode 100644 index 00000000..a26e5372 --- /dev/null +++ b/packages/api/tests/act-on-change.test.ts @@ -0,0 +1,171 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { commit, defineCms, discard, publish, stage } from '@tanstack/cms-core' +import { closeStore, readDocument } from '@tanstack/cms-core/server' +import { createCmsApiHandler } from '../src/http' +import { cleanup, cookieAuth, req, setupCms } from './helpers' +import type { DocumentStateStrategy } from '@tanstack/cms-core' + +afterEach(cleanup) + +const handler = createCmsApiHandler() + +async function call(name: string, input: unknown, role?: string) { + const res = await handler( + req(`/api/cms/v1/ops/${name}`, { + method: 'POST', + role, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(input), + }), + ) + // oxlint-disable-next-line typescript/no-explicit-any -- assertions probe op-specific result shapes + const body = (await res.json()) as { result?: any; error?: { code: string } } + return { status: res.status, result: body.result, code: body.error?.code } +} + +/** Staged changes wait for a reviewer's `sign`, which commits and publishes them. */ +function signoff(version = 1): DocumentStateStrategy<{ step: string }> { + return { + id: 'signoff', + version, + decide: (_ctx, doc, action) => { + switch (action.type) { + case 'edit': + case 'submit': + return { state: { step: 'waiting' }, effects: [stage()] } + case 'sign': + return doc.changeSet + ? { state: { step: 'signed' }, effects: [commit(), publish()] } + : { reject: 'Nothing to sign.' } + case 'discard': + return { effects: [discard()] } + default: + return { reject: `signoff has no "${action.type}".` } + } + }, + availableActions: (ctx, doc) => + doc.changeSet && ctx.permissions.includes('review.decide') + ? [ + { type: 'sign', label: 'Sign off', tone: 'primary' }, + { type: 'discard', label: 'Discard', tone: 'danger' }, + ] + : [], + label: (state) => (state ? `Sign-off: ${state.step}` : 'Live'), + } +} + +const post = { + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' as const }], +} + +async function stagePitch() { + await call( + 'createDoc', + { collection: 'post', id: 'pitch', doc: { title: 'Pitch' } }, + 'author', + ) + const snapshot = await call('reviewSnapshot', {}, 'editor') + return snapshot.result.pending[0] as { + id: string + version: number + review: { label: string; actions: Array<{ type: string }> } + } +} + +describe('the review queue and actOnChange', () => { + it("shows each change set's strategy label and the caller's actions", async () => { + setupCms() + const pitch = await stagePitch() + expect(pitch.review).toEqual({ + label: 'Pending review', + actions: expect.arrayContaining([ + expect.objectContaining({ type: 'approve' }), + expect.objectContaining({ type: 'reject' }), + ]), + }) + const asAuthor = await call('reviewSnapshot', {}, 'author') + expect( + asAuthor.result.pending[0].review.actions.map( + (a: { type: string }) => a.type, + ), + ).not.toContain('approve') + }) + + it("runs an action the strategy offers, and refuses one it doesn't", async () => { + setupCms({ collections: [{ ...post, documentState: signoff() }] }) + const pitch = await stagePitch() + expect(pitch.review).toMatchObject({ + label: 'Sign-off: waiting', + actions: [{ type: 'sign' }, { type: 'discard' }], + }) + + expect( + (await call('actOnChange', { id: pitch.id, action: 'sign' }, 'author')) + .code, + ).toBe('FORBIDDEN') + expect( + (await call('actOnChange', { id: pitch.id, action: 'edit' }, 'editor')) + .code, + ).toBe('BAD_REQUEST') + expect( + ( + await call( + 'actOnChange', + { id: pitch.id, action: 'sign', expectedVersion: pitch.version + 1 }, + 'editor', + ) + ).code, + ).toBe('CONFLICT') + expect(await readDocument('post', 'pitch')).toBeNull() + + const signed = await call( + 'actOnChange', + { id: pitch.id, action: 'sign', expectedVersion: pitch.version }, + 'editor', + ) + expect(signed).toMatchObject({ + status: 200, + result: { ok: true, effects: ['commit', 'publish'], label: 'Live' }, + }) + expect(await readDocument('post', 'pitch')).toMatchObject({ + title: 'Pitch', + published: true, + }) + }) + + it('lists a stranded change set with only a discard, which a reviewer can run', async () => { + const dataDir = setupCms({ + collections: [{ ...post, documentState: signoff(1) }], + }) + const pitch = await stagePitch() + await closeStore() + defineCms({ + dataDir, + collections: [{ ...post, documentState: signoff(2) }], + blockTypes: [], + auth: cookieAuth, + }) + + const [stranded] = (await call('reviewSnapshot', {}, 'editor')).result + .pending + expect(stranded.review).toEqual({ + label: 'Stranded', + actions: [expect.objectContaining({ type: 'discard' })], + stranded: expect.stringContaining('signoff@1'), + }) + expect( + (await call('actOnChange', { id: pitch.id, action: 'sign' }, 'editor')) + .code, + ).toBe('FORBIDDEN') + expect( + (await call('actOnChange', { id: pitch.id, action: 'discard' }, 'editor')) + .status, + ).toBe(200) + expect((await call('reviewSnapshot', {}, 'editor')).result.pending).toEqual( + [], + ) + }) +}) diff --git a/packages/core/package.json b/packages/core/package.json index 73147548..965811a2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -26,6 +26,7 @@ "./flags": "./src/flags.ts", "./storage": "./src/storage.ts", "./storage/conformance": "./src/storage/conformance.ts", + "./document-state/acceptance": "./src/document-state/acceptance.ts", "./media": "./src/media.ts", "./media/conformance": "./src/media/conformance.ts", "./package.json": "./package.json" @@ -64,6 +65,10 @@ "types": "./dist/storage/conformance.d.ts", "import": "./dist/storage/conformance.js" }, + "./document-state/acceptance": { + "types": "./dist/document-state/acceptance.d.ts", + "import": "./dist/document-state/acceptance.js" + }, "./media": { "types": "./dist/media.d.ts", "import": "./dist/media.js" diff --git a/packages/core/src/document-state.ts b/packages/core/src/document-state.ts index a9f5fb16..3310a2d3 100644 --- a/packages/core/src/document-state.ts +++ b/packages/core/src/document-state.ts @@ -246,6 +246,55 @@ export interface StateGraph { edges: ReadonlyArray<{ from: string; to: string; action: string }> } +/** + * A Mermaid `stateDiagram-v2` chart of a strategy's `describe()` graph. + * Nested nodes become composite states, a parallel node's regions are split + * with `--`, final nodes lead to `[*]`, and each edge is drawn in the + * innermost state that holds both ends. + */ +export function stateGraphToMermaid(graph: StateGraph): string { + const key = (id: string) => id.replace(/[^A-Za-z0-9_]/g, '_') + const label = (text: string) => text.replace(/"/g, "'") + const parentOf = new Map( + graph.nodes.map((n) => [n.id, n.parent]), + ) + const ancestors = (id: string): Array => { + const out: Array = [] + for (let at = parentOf.get(id); at !== undefined; at = parentOf.get(at)) + out.push(at) + return [...out, undefined] + } + const scopeOf = (from: string, to: string): string | undefined => { + const toScopes = new Set(ancestors(to)) + if (from === to) return parentOf.get(from) + return ancestors(from).find((scope) => toScopes.has(scope)) + } + const lines = ['stateDiagram-v2'] + const render = (parent: string | undefined, depth: number) => { + const pad = ' '.repeat(depth) + const children = graph.nodes.filter((n) => n.parent === parent) + const parallel = graph.nodes.find((n) => n.id === parent)?.parallel + children.forEach((node, i) => { + if (parallel && i > 0) lines.push(`${pad}--`) + lines.push(`${pad}state "${label(node.label)}" as ${key(node.id)}`) + if (graph.nodes.some((n) => n.parent === node.id)) { + lines.push(`${pad}state ${key(node.id)} {`) + render(node.id, depth + 1) + lines.push(`${pad}}`) + } + if (node.final) lines.push(`${pad}${key(node.id)} --> [*]`) + }) + for (const edge of graph.edges) { + if (scopeOf(edge.from, edge.to) !== parent) continue + lines.push( + `${pad}${key(edge.from)} --> ${key(edge.to)}: ${label(edge.action)}`, + ) + } + } + render(undefined, 1) + return lines.join('\n') +} + export type Migration = { state: S } | { stranded: string } /** diff --git a/packages/core/src/document-state/acceptance.ts b/packages/core/src/document-state/acceptance.ts new file mode 100644 index 00000000..fbb46267 --- /dev/null +++ b/packages/core/src/document-state/acceptance.ts @@ -0,0 +1,871 @@ +/** + * The document state strategy acceptance suite: legal and editorial approval + * in parallel on one change set (steps 1–11), plus core's rules. Every + * storage adapter runs it, so a strategy behaves the same on every backend: + * + * ```ts + * import { afterEach, beforeEach, describe, expect, it } from 'vitest' + * import { runDocumentStateAcceptance } from '@tanstack/cms-core/document-state/acceptance' + * + * runDocumentStateAcceptance( + * 'libsql', + * { + * database: () => { + * const url = `file:${tempFile()}` + * return () => createLibsqlStorage({ url }) + * }, + * strategies: { legalReview, legalReviewV2, legalReviewV2WithoutMigrate }, + * }, + * { describe, it, expect, beforeEach, afterEach }, + * ) + * ``` + * + * The test runner and the strategies are injected, so this module depends on + * neither a test framework nor XState. The reference strategies are the + * XState example in the docs ("Custom Document State Strategies"). The suite + * drives only the public engine calls. + */ +import { defineCms, defineEventHandler, isCmsError } from '../index' +import { + accessContext, + actOnDocument, + availableDocumentActions, + closeStore, + getStorage, + listAudit, + listStrandedChangeSets, + publicContext, + readChangeSet, + readDocumentAs, + runEventDispatch, + runScheduledPublishing, + systemContext, +} from '../server' +import { + commit, + emit, + publish, + schedule, + stage, + strategyKey, +} from '../document-state' +import type { + AccessContext, + Action, + ActionDescriptor, + AnyDocumentStateStrategy, + ChangeSetView, + DocumentStateStrategy, + Effect, +} from '../index' +import type { CmsSession } from '../lib/auth' +import type { Permission } from '../lib/access' +import type { StorageAdapter } from '../storage/types' + +/* oxlint-disable typescript/no-explicit-any -- minimal structural typing for an injected test runner */ +export interface AcceptanceRunner { + describe: (name: string, fn: () => void) => void + it: (name: string, fn: () => Promise) => void + beforeEach: (fn: () => Promise) => void + afterEach: (fn: () => Promise) => void + expect: ((value: unknown) => any) & { + objectContaining: (value: object) => any + } +} +/* oxlint-enable typescript/no-explicit-any */ + +/** + * The parallel-approval strategy under test, in its three versions: + * + * - `legalReview` (`legal-review@1`): an author's `edit` stages the change + * set with `{ review: { legal: 'pending', editorial: 'pending' } }`; + * `approve:legal` (role `legal`) and `approve:editorial` (role `editor`) + * land in either order; the last one commits and publishes, or schedules + * the author's `input.publishAt`, which the scheduler's `publish` fires; a + * reject moves to `changesRequested` and emits `legal-review.rejected`; a + * new edit resets both approvals. + * - `legalReviewV2` (`@2`): drops `changesRequested`; its `migrate` moves + * such change sets back to both approvals pending. + * - `legalReviewV2WithoutMigrate`: `@2` with no `migrate`. + */ +export interface ParallelApprovalStrategies { + legalReview: AnyDocumentStateStrategy + legalReviewV2: AnyDocumentStateStrategy + legalReviewV2WithoutMigrate: AnyDocumentStateStrategy +} + +export interface DocumentStateAcceptanceOptions { + /** + * A new, empty database for one test. Returns an opener: core calls it on + * boot and again on every restart, and each adapter it returns must see + * the same data. + */ + database: () => () => StorageAdapter + strategies: ParallelApprovalStrategies +} + +interface DocRef { + collection: string + id: string +} + +interface LiveRead { + doc: Record + revision: number + published: boolean +} + +type ActResult = + | { ok: true; state: unknown; effects: ReadonlyArray } + | { ok: false; reason: string } + +interface AuditRow { + changeSet: string | null + actor: string + action: string + from: unknown + to: unknown + effects: ReadonlyArray +} + +interface OutboxEvent { + type: string + collection: string + id: string + actor: string + payload?: unknown +} + +interface StrandedChangeSet { + collection: string + id: string + changeSet: string + strategy: string + reason: string +} + +interface BoundHandle { + /** Honors the context's mode: a `live` context reads the published record. */ + get: (ref: DocRef) => Promise + act: (ref: DocRef & { action: Action }) => Promise + availableActions: (ref: DocRef) => Promise> +} + +interface AcceptanceHarness { + as: (ctx: AccessContext) => BoundHandle + /** Seeds a committed document straight into storage, outside any strategy. */ + seed: ( + ref: DocRef & { + doc: Record + revision: number + published: boolean + }, + ) => Promise + changeSet: (ref: DocRef) => Promise | null> + /** The document's audit rows, oldest first. */ + audit: (ref: DocRef) => Promise> + /** Everything enqueued in the outbox since this harness booted. */ + events: () => Promise> + /** Runs one scheduler sweep as if the clock read `nowIso`. */ + runScheduler: (nowIso: string) => Promise + /** Closes this engine and boots a new one over the same database. */ + restart: (options?: { + strategy?: AnyDocumentStateStrategy + }) => Promise + strandedChangeSets: () => Promise> + /** Idempotent; `restart` closes the harness it was called on. */ + close: () => Promise +} + +const COLLECTION = 'post' + +/** The events the suite reads back from the outbox. */ +const OUTBOX_EVENTS = [ + 'document.created', + 'document.updated', + 'document.published', + 'document.unpublished', + 'document.deleted', + 'legal-review.rejected', +] as const + +/** Past every time the suite schedules, so a drain delivers everything. */ +const DRAIN_AT = '3000-01-01T00:00:00.000Z' + +/** + * Who may act is the strategy's call in this suite: every signed-in actor + * holds the permissions core checks before a decision writes live content, + * and the strategy's guards read the role. + */ +const PERMISSIONS: ReadonlyArray = [ + 'content.read', + 'content.write', + 'content.publish', + 'review.decide', +] + +function session(id: string, role: string): CmsSession { + return { + isAuthenticated: true, + isAdmin: false, + role, + permissions: [...PERMISSIONS], + user: { id }, + } +} + +const userContext = (id: string, role: string): AccessContext => + accessContext({ session: session(id, role), mode: 'edit' }) + +const agentContext = (name: string, role = 'author'): AccessContext => { + const agent = `agent:${name}` + return accessContext({ session: session(agent, role), agent, mode: 'edit' }) +} + +const schedulerContext = (): AccessContext => + systemContext('scheduled publishing', { actor: 'scheduler' }) + +async function bootHarness( + open: () => StorageAdapter, + strategy: AnyDocumentStateStrategy, +): Promise { + const delivered: Array = [] + defineCms({ + storage: open(), + collections: [ + { + name: COLLECTION, + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], + documentState: strategy, + }, + ], + blockTypes: [], + events: { dispatch: 'manual' }, + eventHandlers: OUTBOX_EVENTS.map((type) => + defineEventHandler({ + id: `acceptance-${type}`, + on: type, + run: ({ event }) => { + delivered.push({ + type: event.type, + collection: event.collection ?? '', + id: event.documentId ?? '', + actor: event.actor, + ...(event.payload === undefined ? {} : { payload: event.payload }), + }) + }, + }), + ), + }) + await getStorage() + let closed = false + + const drain = async () => { + await runEventDispatch({ now: DRAIN_AT }) + } + + const harness: AcceptanceHarness = { + as: (ctx) => ({ + async get(ref) { + const doc = await readDocumentAs(ctx, ref.collection, ref.id) + if (!doc) return null + return { + doc, + revision: typeof doc._revision === 'number' ? doc._revision : 0, + published: Boolean(doc.published), + } + }, + async act(ref) { + try { + const outcome = await actOnDocument(ctx, ref) + return { ok: true, state: outcome.state, effects: outcome.effects } + } catch (err) { + if (isCmsError(err)) return { ok: false, reason: err.message } + throw err + } + }, + availableActions: (ref) => + availableDocumentActions(ctx, ref.collection, ref.id), + }), + async seed({ collection, id, doc, revision, published }) { + const storage = await getStorage() + const at = new Date().toISOString() + const stored = { ...doc, published, _revision: revision, _updatedAt: at } + await storage.transaction(async (tx) => { + await tx.putDocument( + { collection, id, doc: stored, updatedAt: at }, + { + title: String(doc.title ?? id), + published, + slug: null, + locale: 'en', + publishAt: null, + unpublishAt: null, + deletedAt: null, + }, + ) + await tx.insertRevision({ + id: `${collection}:${id}:${revision}`, + collection, + docId: id, + revision, + doc: stored, + actor: 'seed', + createdAt: at, + }) + }) + }, + changeSet: (ref) => readChangeSet(ref.collection, ref.id), + async audit(ref) { + const entries = await listAudit({ limit: 1000 }) + return entries + .filter((e) => e.collection === ref.collection && e.docId === ref.id) + .reverse() + .map((e) => ({ + changeSet: e.changeSet ?? null, + actor: e.actor, + action: e.action ?? '', + from: e.from ?? null, + to: e.to ?? null, + effects: e.effects ?? [], + })) + }, + async events() { + await drain() + return [...delivered] + }, + async runScheduler(nowIso) { + await runScheduledPublishing(nowIso) + }, + async restart(options) { + await harness.close() + return bootHarness(open, options?.strategy ?? strategy) + }, + async strandedChangeSets() { + return (await listStrandedChangeSets()).map(({ pending, reason }) => ({ + collection: pending.collection, + id: pending.docId, + changeSet: pending.id, + strategy: pending.workflow?.strategy ?? '', + reason, + })) + }, + async close() { + if (closed) return + closed = true + await drain() + await closeStore() + }, + } + return harness +} + +const p1: DocRef = { collection: COLLECTION, id: 'p1' } +const p2: DocRef = { collection: COLLECTION, id: 'p2' } + +const bothPending = { review: { legal: 'pending', editorial: 'pending' } } +const legalApproved = { review: { legal: 'approved', editorial: 'pending' } } +const editorialApproved = { + review: { legal: 'pending', editorial: 'approved' }, +} + +/** Far ahead, so the store's own throttled sweep (real clock) never fires it. */ +const PUBLISH_AT = '2999-12-01T09:00:00.000Z' +const BEFORE_PUBLISH_AT = '2999-11-30T09:00:00.000Z' + +/** + * Register the acceptance suite as one `describe` block named after + * `name`. Pass `describe.skip` (e.g. Postgres without a URL) to skip it. + */ +export function runDocumentStateAcceptance( + name: string, + options: DocumentStateAcceptanceOptions, + runner: AcceptanceRunner, +): void { + const { describe, it, expect, beforeEach, afterEach } = runner + const { legalReview, legalReviewV2, legalReviewV2WithoutMigrate } = + options.strategies + + const author = userContext('user:ada', 'author') + const lawyer = userContext('user:lee', 'legal') + const editor = userContext('user:eve', 'editor') + const reader = publicContext() + + describe(`document state strategy acceptance: parallel approval (${name})`, () => { + let cms: AcceptanceHarness + + beforeEach(async () => { + cms = await bootHarness(options.database(), legalReview) + await cms.seed({ + ...p1, + doc: { title: 'Hello' }, + revision: 3, + published: true, + }) + }) + + afterEach(async () => { + await cms.close() + }) + + const liveTitle = async (ref: DocRef = p1) => + (await cms.as(reader).get(ref))?.doc.title + + const edit = (title: string, input?: Record) => + cms.as(author).act({ + ...p1, + action: { type: 'edit', patch: { title }, ...(input ? { input } : {}) }, + }) + + const act = (ctx: AccessContext, type: string) => + cms.as(ctx).act({ ...p1, action: { type } }) + + const actionTypes = async (ctx: AccessContext) => + (await cms.as(ctx).availableActions(p1)).map((a) => a.type) + + const documentEvents = async () => + (await cms.events()).filter((e) => e.type.startsWith('document.')) + + const stateOf = async () => + ( + (await cms.changeSet(p1))?.workflow?.state as + | { value: unknown } + | undefined + )?.value + + it('1. an author edit stages a change set with both approvals pending; live is untouched', async () => { + const result = await edit('Hello, world') + + expect(result).toMatchObject({ ok: true, effects: [stage()] }) + expect(result.ok && (result.state as { value: unknown }).value).toEqual( + bothPending, + ) + + expect(await cms.changeSet(p1)).toMatchObject({ + actor: 'user:ada', + after: { title: 'Hello, world' }, + baseRevision: 3, + workflow: { + strategy: strategyKey(legalReview), + state: { value: bothPending }, + }, + }) + expect(await liveTitle()).toBe('Hello') + expect(await cms.as(reader).get(p1)).toMatchObject({ + revision: 3, + published: true, + }) + }) + + it("2. availableActions are per actor: each reviewer sees only their region's pair, the author sees neither", async () => { + await edit('Hello, world') + + expect(await actionTypes(lawyer)).toEqual([ + 'approve:legal', + 'reject:legal', + ]) + expect(await actionTypes(editor)).toEqual([ + 'approve:editorial', + 'reject:editorial', + ]) + const authorActions = await actionTypes(author) + for (const type of [ + 'approve:legal', + 'reject:legal', + 'approve:editorial', + 'reject:editorial', + ]) + expect(authorActions).not.toContain(type) + // A system context is privileged for core, not a reviewer for the strategy. + expect(await actionTypes(systemContext('acceptance-spec'))).toEqual([]) + + // A verb the strategy didn't offer is refused, and nothing changes. + expect(await act(author, 'approve:legal')).toMatchObject({ ok: false }) + expect(await stateOf()).toEqual(bothPending) + }) + + describe('3. approvals land in either order', () => { + it('legal first, then editorial', async () => { + await edit('Hello, world') + expect(await act(lawyer, 'approve:legal')).toMatchObject({ + ok: true, + state: { value: legalApproved }, + effects: [], + }) + expect(await act(editor, 'approve:editorial')).toMatchObject({ + ok: true, + effects: [commit(), publish()], + }) + }) + + it('editorial first, then legal', async () => { + await edit('Hello, world') + expect(await act(editor, 'approve:editorial')).toMatchObject({ + ok: true, + state: { value: editorialApproved }, + effects: [], + }) + expect(await act(lawyer, 'approve:legal')).toMatchObject({ + ok: true, + effects: [commit(), publish()], + }) + }) + + it('either reviewer may reject; legal-review@1 sends the change set back to the author', async () => { + await edit('Hello, world') + await act(editor, 'approve:editorial') + + expect(await act(lawyer, 'reject:legal')).toMatchObject({ + ok: true, + state: { value: 'changesRequested' }, + effects: [emit('legal-review.rejected', { region: 'legal' })], + }) + expect(await cms.changeSet(p1)).toMatchObject({ + after: { title: 'Hello, world' }, + workflow: { state: { value: 'changesRequested' } }, + }) + expect(await actionTypes(editor)).toEqual([]) + expect(await actionTypes(author)).toEqual(['edit', 'discard']) + expect(await liveTitle()).toBe('Hello') + expect( + (await cms.events()).filter( + (e) => e.type === 'legal-review.rejected', + ), + ).toEqual([expect.objectContaining({ id: 'p1', actor: 'user:lee' })]) + }) + }) + + it('4. a new edit during partial approval reaches decide as `edit`; legal-review@1 resets both approvals', async () => { + await edit('Hello, world') + await act(lawyer, 'approve:legal') + + const result = await edit('Hello, world!') + + expect(result).toMatchObject({ + ok: true, + state: { value: bothPending }, + effects: [stage()], + }) + expect(await cms.changeSet(p1)).toMatchObject({ + after: { title: 'Hello, world!' }, + workflow: { state: { value: bothPending } }, + }) + expect(await actionTypes(lawyer)).toEqual([ + 'approve:legal', + 'reject:legal', + ]) + }) + + it('5. the final approval commits and publishes; only then does live change, and `published` stays true', async () => { + await edit('Hello, world') + expect(await cms.as(reader).get(p1)).toMatchObject({ published: true }) + + await act(lawyer, 'approve:legal') + expect(await liveTitle()).toBe('Hello') + expect(await cms.as(reader).get(p1)).toMatchObject({ published: true }) + + const final = await act(editor, 'approve:editorial') + + expect(final).toMatchObject({ ok: true, effects: [commit(), publish()] }) + expect(await cms.as(reader).get(p1)).toEqual({ + doc: expect.objectContaining({ title: 'Hello, world' }), + revision: 4, + published: true, + }) + // `commit` consumes the coalesced change set. + expect(await cms.changeSet(p1)).toBeNull() + }) + + it('6. core rejects a decision that commits on a live doc without publishing, atomically', async () => { + const commitOnly: DocumentStateStrategy<'edited'> = { + id: 'commit-only', + version: 1, + decide: () => ({ state: 'edited', effects: [commit()] }), + availableActions: () => [], + label: () => 'Edited', + } + const broken = await cms.restart({ strategy: commitOnly }) + + const result = await broken.as(author).act({ + ...p1, + action: { type: 'edit', patch: { title: 'Sneaky' } }, + }) + + expect(result).toMatchObject({ ok: false }) + expect(await broken.as(reader).get(p1)).toMatchObject({ + doc: { title: 'Hello' }, + revision: 3, + published: true, + }) + expect(await broken.changeSet(p1)).toBeNull() + expect( + (await broken.events()).filter((e) => e.type.startsWith('document.')), + ).toEqual([]) + await broken.close() + }) + + it('7. every decision writes an audit row (actor, action, from/to, effects); core emits the content event once', async () => { + await edit('Hello, world') + await act(lawyer, 'approve:legal') + await act(editor, 'approve:editorial') + + expect(await cms.audit(p1)).toEqual([ + expect.objectContaining({ + actor: 'user:ada', + action: 'edit', + from: null, + to: expect.objectContaining({ value: bothPending }), + effects: [stage()], + }), + expect.objectContaining({ + actor: 'user:lee', + action: 'approve:legal', + from: expect.objectContaining({ value: bothPending }), + to: expect.objectContaining({ value: legalApproved }), + effects: [], + }), + expect.objectContaining({ + actor: 'user:eve', + action: 'approve:editorial', + from: expect.objectContaining({ value: legalApproved }), + to: expect.objectContaining({ value: 'published' }), + effects: [commit(), publish()], + }), + ]) + // Audit is core's job: no strategy effect asked for it. The document + // stayed live, so core emits `document.updated`; `document.published` + // means it went live. + expect(await documentEvents()).toEqual([ + expect.objectContaining({ + type: 'document.updated', + collection: COLLECTION, + id: 'p1', + actor: 'user:eve', + }), + ]) + }) + + it("8. scheduling: approvals schedule the author's publishAt; the scheduler fires `publish` as actor `scheduler`", async () => { + await edit('Hello, world', { publishAt: PUBLISH_AT }) + await act(lawyer, 'approve:legal') + + expect(await act(editor, 'approve:editorial')).toMatchObject({ + ok: true, + state: { value: 'scheduled' }, + effects: [schedule({ publishAt: PUBLISH_AT })], + }) + expect(await liveTitle()).toBe('Hello') + expect(await cms.changeSet(p1)).toMatchObject({ publishAt: PUBLISH_AT }) + // Only the scheduler can fire the scheduled publish. + expect(await actionTypes(author)).not.toContain('publish') + expect(await actionTypes(schedulerContext())).toEqual(['publish']) + + await cms.runScheduler(BEFORE_PUBLISH_AT) + expect(await liveTitle()).toBe('Hello') + expect(await stateOf()).toBe('scheduled') + + await cms.runScheduler(PUBLISH_AT) + expect(await liveTitle()).toBe('Hello, world') + expect(await cms.changeSet(p1)).toBeNull() + + const audit = await cms.audit(p1) + expect(audit.at(-1)).toMatchObject({ + actor: 'scheduler', + action: 'publish', + effects: [commit(), publish()], + }) + expect(await documentEvents()).toEqual([ + expect.objectContaining({ + type: 'document.updated', + id: 'p1', + actor: 'scheduler', + }), + ]) + }) + + it('9. strategy state survives a serialize/restart round trip', async () => { + await edit('Hello, world') + await act(lawyer, 'approve:legal') + const before = await cms.changeSet(p1) + + cms = await cms.restart() + + expect(await cms.changeSet(p1)).toEqual(before) + expect(await actionTypes(lawyer)).toEqual([]) + expect(await actionTypes(editor)).toEqual([ + 'approve:editorial', + 'reject:editorial', + ]) + expect(await act(editor, 'approve:editorial')).toMatchObject({ + ok: true, + effects: [commit(), publish()], + }) + expect(await liveTitle()).toBe('Hello, world') + }) + + describe('11. bumping the strategy version', () => { + beforeEach(async () => { + await cms.seed({ + ...p2, + doc: { title: 'Untouched' }, + revision: 1, + published: true, + }) + await edit('Hello, world') + await act(lawyer, 'reject:legal') + expect(await stateOf()).toBe('changesRequested') + }) + + it('@2 without `migrate` reports the in-flight @1 change set as stranded; published docs are unaffected', async () => { + cms = await cms.restart({ strategy: legalReviewV2WithoutMigrate }) + + expect(await cms.strandedChangeSets()).toEqual([ + expect.objectContaining({ + collection: COLLECTION, + id: 'p1', + strategy: strategyKey(legalReview), + }), + ]) + expect(await liveTitle(p1)).toBe('Hello') + expect(await liveTitle(p2)).toBe('Untouched') + // Core does not guess: acting on a stranded change set is refused. + expect( + await cms + .as(author) + .act({ ...p1, action: { type: 'edit', patch: { title: 'x' } } }), + ).toMatchObject({ ok: false }) + }) + + it('@2 with `migrate` moves the removed state forward at boot', async () => { + cms = await cms.restart({ strategy: legalReviewV2 }) + + expect(await cms.strandedChangeSets()).toEqual([]) + expect(await cms.changeSet(p1)).toMatchObject({ + after: { title: 'Hello, world' }, + workflow: { + strategy: strategyKey(legalReviewV2), + state: { value: bothPending }, + }, + }) + expect(await liveTitle(p2)).toBe('Untouched') + }) + }) + + describe('core rules beyond the eleven steps', () => { + const directForEveryone = ( + grants?: DocumentStateStrategy['grants'], + ): DocumentStateStrategy => ({ + id: 'direct-test', + version: 1, + ...(grants ? { grants } : {}), + decide: () => ({ effects: [commit(), publish()] }), + availableActions: () => [{ type: 'edit', label: 'Save' }], + label: () => 'Published', + }) + const agent = agentContext('enrich') + const agentEdit = { + ...p1, + action: { type: 'edit', patch: { title: 'By agent' } }, + } + const unchanged = async (harness: AcceptanceHarness) => { + expect(await harness.as(reader).get(p1)).toMatchObject({ + doc: { title: 'Hello' }, + revision: 3, + }) + expect(await harness.changeSet(p1)).toBeNull() + expect( + (await harness.events()).filter((e) => + e.type.startsWith('document.'), + ), + ).toEqual([]) + } + + it('agents may stage under legal-review@1 but never publish through it', async () => { + expect(await cms.as(agent).act(agentEdit)).toMatchObject({ + ok: true, + effects: [stage()], + }) + expect(await cms.changeSet(p1)).toMatchObject({ actor: 'agent:enrich' }) + }) + + it('core rejects a publish caused by an agent unless the strategy grants it', async () => { + const floor = await cms.restart({ strategy: directForEveryone() }) + expect(await floor.as(agent).act(agentEdit)).toMatchObject({ + ok: false, + }) + expect(await floor.as(reader).get(p1)).toMatchObject({ + doc: { title: 'Hello' }, + }) + + cms = await floor.restart({ + strategy: directForEveryone({ publish: ['agent'] }), + }) + expect(await cms.as(agent).act(agentEdit)).toMatchObject({ + ok: true, + }) + expect(await cms.as(reader).get(p1)).toMatchObject({ + doc: { title: 'By agent' }, + }) + }) + + it('core rejects `emit` of reserved `document.*` events, so a strategy cannot forge document.published', async () => { + const forger: DocumentStateStrategy = { + id: 'forger', + version: 1, + decide: () => ({ + effects: [stage(), emit('document.published')], + }), + availableActions: () => [], + label: () => 'Forged', + } + cms = await cms.restart({ strategy: forger }) + + expect( + await cms.as(author).act({ + ...p1, + action: { type: 'edit', patch: { title: 'Forged' } }, + }), + ).toMatchObject({ ok: false }) + await unchanged(cms) + }) + + it('core rejects an `edit` decision that neither stages nor commits, so an incoming patch is never dropped silently', async () => { + const dropper: DocumentStateStrategy<'seen'> = { + id: 'dropper', + version: 1, + decide: () => ({ state: 'seen', effects: [] }), + availableActions: () => [], + label: () => 'Seen', + } + cms = await cms.restart({ strategy: dropper }) + + expect( + await cms.as(author).act({ + ...p1, + action: { type: 'edit', patch: { title: 'Dropped' } }, + }), + ).toMatchObject({ ok: false }) + await unchanged(cms) + }) + + it('a refused decision is audited with its reason, and nothing else changes', async () => { + await edit('Hello, world') + await act(author, 'approve:legal') + + expect((await cms.audit(p1)).at(-1)).toMatchObject({ + actor: 'user:ada', + action: 'approve:legal', + from: { value: bothPending }, + to: null, + effects: [], + }) + expect(await stateOf()).toEqual(bothPending) + }) + }) + }) +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4f4b978a..04c4cca9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -263,6 +263,7 @@ export { reviewStrategy, schedule, stage, + stateGraphToMermaid, strategyKey, unpublish, } from './document-state' diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 50cf5c79..53c0432b 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -66,6 +66,7 @@ export { documentStateLabel, documentStateStrategy, listStrandedChangeSets, + readChangeSet, } from './server/store' // Optional storage-capability narrowing (auth users / api keys / user roles). export { requireStorageCapability } from './storage/capabilities' diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 3db8ad97..1bb51150 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -95,6 +95,7 @@ export { documentStateLabel, documentStateStrategy, listStrandedChangeSets, + readChangeSet, } from './store/document-state' export type { IncomingChange, diff --git a/packages/core/src/server/store/document-state.ts b/packages/core/src/server/store/document-state.ts index feac6230..2b85c6b3 100644 --- a/packages/core/src/server/store/document-state.ts +++ b/packages/core/src/server/store/document-state.ts @@ -21,7 +21,12 @@ import { randomUUID } from 'node:crypto' import { getCmsConfig } from '../../config' import { CmsError } from '../../errors' import { assetCollectionName, emptyDoc } from '../../schema' -import { actorOf, reviewStrategy, strategyKey } from '../../document-state' +import { + actorOf, + discard, + reviewStrategy, + strategyKey, +} from '../../document-state' import { protectWrite } from '../access' import { assertCollectionAccess } from '../auth' import { @@ -215,7 +220,24 @@ async function loadView( } } -/** The actions `ctx` can take on a document right now, from its strategy. */ +const DISCARD_STRANDED: ActionDescriptor = { + type: 'discard', + label: 'Discard change set', + tone: 'danger', +} + +/** Reviewers (and trusted callers) may discard a stranded change set. */ +function canDiscardStranded(ctx: AccessContext): boolean { + return ( + actorOf(ctx).type !== 'agent' && + ctx.permissions.some((p) => p === 'review.decide') + ) +} + +/** + * The actions `ctx` can take on a document right now, from its strategy. On + * a stranded change set the strategy isn't asked: reviewers may discard it. + */ export async function availableDocumentActions( ctx: AccessContext, collection: string, @@ -224,6 +246,8 @@ export async function availableDocumentActions( const storage = await getStorage() const strategy = documentStateStrategy(collection) const { view } = await loadView(storage, strategy, collection, docId) + if (view.changeSet?.stranded) + return canDiscardStranded(ctx) ? [DISCARD_STRANDED] : [] return strategy.availableActions(ctx, view) } @@ -235,9 +259,24 @@ export async function documentStateLabel( const storage = await getStorage() const strategy = documentStateStrategy(collection) const { view } = await loadView(storage, strategy, collection, docId) + if (view.changeSet?.stranded) return 'Stranded' return strategy.label(view.changeSet?.workflow?.state, view) } +/** + * The document's open change set as its strategy reads it (state upgraded by + * `migrate`, `stranded` set when it can't be read), or `null`. + */ +export async function readChangeSet( + collection: string, + docId: string, +): Promise | null> { + const storage = await getStorage() + const strategy = documentStateStrategy(collection) + const { view } = await loadView(storage, strategy, collection, docId) + return view.changeSet +} + export interface StrandedChangeSet { pending: Pending reason: string @@ -323,7 +362,6 @@ function checkDecision( action: Action, effects: ReadonlyArray, change: WriteType | null, - storesState: boolean, ): Refusal | null { for (const effect of effects) { if (!EFFECT_TYPES.has(effect.type)) { @@ -340,17 +378,6 @@ function checkDecision( } } const has = (type: EffectType) => effects.some((e) => e.type === type) - const stranded = loaded.view.changeSet?.stranded - if ( - stranded && - (storesState || - effects.some((e) => e.type !== 'discard' && e.type !== 'emit')) - ) { - return { - rule: 'stranded', - reason: `${stranded} Discard it before deciding anything else.`, - } - } if (change !== null && !has('stage') && !has('commit')) { return { rule: 'drops-change', @@ -556,6 +583,24 @@ export async function decideStrategyWrite( from: stateOf(loaded), }, }) + // The strategy can't read a stranded change set's state, so it isn't + // asked: core discards it for a reviewer and refuses anything else. + const stranded = loaded.view.changeSet?.stranded + if (stranded) { + if (action.type !== 'discard' || !canDiscardStranded(args.ctx)) + return refused( + 'stranded', + `${stranded} A reviewer must discard it before anything else is decided.`, + ) + return { + ok: true, + strategy, + loaded, + action, + state: undefined, + effects: [discard()], + } + } const decision = await strategy.decide(args.ctx, loaded.view, action) if ('reject' in decision) return refused('strategy', decision.reject) const effects = decision.effects ?? [] @@ -566,7 +611,6 @@ export async function decideStrategyWrite( action, effects, change, - decision.state !== undefined, ) if (refusal) return refused(refusal.rule, refusal.reason) return { ok: true, strategy, loaded, action, state: decision.state, effects } @@ -1118,7 +1162,7 @@ export async function executeStrategyWrite( auditTransition: { ...(changeSet ? { changeSet: changeSet.id } : {}), from: stateOf(loaded), - to: null, + to: storesState ? (workflow?.state ?? null) : null, effects: asJson(effects), }, eventActor, @@ -1247,7 +1291,9 @@ export async function executeStrategyWrite( decision: decisionValue, ...(target ? { changeSet: target.id } : {}), from: stateOf(loaded), - to: (survives ? (workflow?.state ?? null) : null) as JsonValue, + to: (survives || storesState + ? (workflow?.state ?? null) + : null) as JsonValue, effects: asJson(effects), at: now, }) diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts index 9d8d7aa1..9538d925 100644 --- a/packages/core/src/storage/types.ts +++ b/packages/core/src/storage/types.ts @@ -156,7 +156,10 @@ export interface AuditRecord { changeSet?: string /** The change set's strategy state before the decision (`null`: none). */ from?: JsonValue - /** The change set's strategy state after it (`null`: closed or none). */ + /** + * The change set's strategy state after it: the state a closing decision + * returned (`published`), else `null` once closed or when there is none. + */ to?: JsonValue /** The effects the decision ran, in order (none when refused). */ effects?: Array diff --git a/packages/core/tests/document-state-docs.test.ts b/packages/core/tests/document-state-docs.test.ts new file mode 100644 index 00000000..fd14483f --- /dev/null +++ b/packages/core/tests/document-state-docs.test.ts @@ -0,0 +1,35 @@ +/** + * The docs show generated and copied code: the default strategy's chart, and + * the XState parallel-approval example the acceptance suite runs. These fail + * when the source moves on without the docs. + */ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { reviewStrategy, stateGraphToMermaid } from '../src/index' +import { legalReview } from './document-state/legal-review.xstate' + +const read = (path: string) => + readFileSync(new URL(path, import.meta.url), 'utf8') + +const mermaid = (chart: string) => '```mermaid\n' + chart + '\n```' + +describe('document state docs', () => { + it("review-queue.md charts the default strategy's graph", () => { + const chart = stateGraphToMermaid( + reviewStrategy().describe?.() ?? { nodes: [], edges: [] }, + ) + expect(read('../../../docs/agents/review-queue.md')).toContain( + mermaid(chart), + ) + }) + + it('custom-strategies.md shows the example the acceptance suite runs, and its chart', () => { + const page = read('../../../docs/agents/custom-strategies.md') + const source = read('./document-state/legal-review.xstate.ts') + expect(page).toContain('```ts validate=type\n' + source + '```') + const chart = stateGraphToMermaid( + legalReview.describe?.() ?? { nodes: [], edges: [] }, + ) + expect(page).toContain(mermaid(chart)) + }) +}) diff --git a/packages/core/tests/document-state-strategy.acceptance.test.ts b/packages/core/tests/document-state-strategy.acceptance.test.ts index f949376e..cad2a669 100644 --- a/packages/core/tests/document-state-strategy.acceptance.test.ts +++ b/packages/core/tests/document-state-strategy.acceptance.test.ts @@ -1,465 +1,29 @@ -/** - * Acceptance spec for the document state strategy interface: legal and - * editorial approval in parallel on one change set (cms-refactor-plan.md, - * item 7, "The parallel-approval acceptance test", steps 1–11). - * - * Skipped until phase 4c. Phase 4a promoted the draft types into `src` - * (`./draft/document-state-strategy` re-exports them); 4b and 4c add what - * `./draft/acceptance-harness` lists, implement `createAcceptanceHarness` - * against the real engine, and remove the `.skip`. If a step can't pass - * without reaching into core internals, the interface is wrong, not the spec. - * - * The decided model this encodes: - * - Core owns live (`published`, schedule, revisions). The strategy owns the - * workflow state of the one coalesced pending change set per document. - * - The strategy acts only through effects: `stage`, `commit`, - * `publish(revision?)`, `unpublish`, `schedule`, `discard`, `emit`. - * - Core enforces: decisions are atomic; a live doc's content changes only - * through `publish`; audit is written by core, never an effect; core emits - * `document.published|unpublished` from the effects; agents can't cause a - * publish unless the strategy grants it. - */ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createAcceptanceHarness } from './draft/acceptance-harness' -import { - agentContext, - commit, - emit, - publicContext, - publish, - schedule, - schedulerContext, - stage, - strategyKey, - systemContext, - userContext, -} from './draft/document-state-strategy' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest' +import { runDocumentStateAcceptance } from '../src/document-state/acceptance' +import { createSqliteStorage } from '../src/storage' import { legalReview, legalReviewV2, legalReviewV2WithoutMigrate, -} from './draft/legal-review.xstate' -import type { AcceptanceHarness, DocRef } from './draft/acceptance-harness' -import type { - AccessContext, - DocumentStateStrategy, -} from './draft/document-state-strategy' -import type { LegalReviewState } from './draft/legal-review.xstate' - -const p1: DocRef = { collection: 'post', id: 'p1' } -const p2: DocRef = { collection: 'post', id: 'p2' } - -const author = userContext('user:ada', ['author']) -const lawyer = userContext('user:lee', ['legal']) -const editor = userContext('user:eve', ['editor']) -const reader = publicContext() - -const bothPending = { review: { legal: 'pending', editorial: 'pending' } } -const legalApproved = { review: { legal: 'approved', editorial: 'pending' } } -const editorialApproved = { - review: { legal: 'pending', editorial: 'approved' }, -} - -const PUBLISH_AT = '2026-12-01T09:00:00.000Z' - -// Step 10: the whole scenario runs once per storage dialect. -describe.skip.each(['libsql', 'postgres'] as const)( - 'document state strategy acceptance: parallel approval (%s)', - (storage) => { - let cms: AcceptanceHarness - - beforeEach(async () => { - cms = await createAcceptanceHarness({ - storage, - collection: 'post', - strategy: legalReview, - }) - await cms.seed({ - ...p1, - doc: { title: 'Hello' }, - revision: 3, - published: true, - }) - }) - - afterEach(async () => { - await cms.close() - }) - - const liveTitle = async (ref: DocRef = p1) => - (await cms.as(reader).get(ref))?.doc.title - - const edit = (title: string, input?: Record) => - cms.as(author).act({ - ...p1, - action: { type: 'edit', patch: { title }, ...(input ? { input } : {}) }, - }) - - const act = (ctx: AccessContext, type: string) => - cms.as(ctx).act({ ...p1, action: { type } }) - - const actionTypes = async (ctx: AccessContext) => - (await cms.as(ctx).availableActions(p1)).map((a) => a.type) - - it('1. an author edit stages a change set with both approvals pending; live is untouched', async () => { - const result = await edit('Hello, world') - - expect(result).toMatchObject({ ok: true, effects: [stage()] }) - expect(result.ok && result.state?.value).toEqual(bothPending) - - const changeSet = await cms.changeSet(p1) - expect(changeSet).toMatchObject({ - actor: 'user:ada', - after: { title: 'Hello, world' }, - baseRevision: 3, - workflow: { - strategy: 'legal-review@1', - state: { value: bothPending }, - }, - }) - expect(await liveTitle()).toBe('Hello') - expect(await cms.as(reader).get(p1)).toMatchObject({ - revision: 3, - published: true, - }) - }) - - it("2. availableActions are per actor: each reviewer sees only their region's pair, the author sees neither", async () => { - await edit('Hello, world') - - expect(await actionTypes(lawyer)).toEqual([ - 'approve:legal', - 'reject:legal', - ]) - expect(await actionTypes(editor)).toEqual([ - 'approve:editorial', - 'reject:editorial', - ]) - const authorActions = await actionTypes(author) - expect(authorActions).not.toContain('approve:legal') - expect(authorActions).not.toContain('reject:legal') - expect(authorActions).not.toContain('approve:editorial') - expect(authorActions).not.toContain('reject:editorial') - // A system context is privileged for core, not a reviewer for the strategy. - expect(await actionTypes(systemContext('acceptance-spec'))).toEqual([]) - - // A verb the strategy didn't offer is refused, and nothing changes. - expect(await act(author, 'approve:legal')).toMatchObject({ ok: false }) - expect((await cms.changeSet(p1))?.workflow?.state.value).toEqual( - bothPending, - ) - }) - - describe('3. approvals land in either order', () => { - it('legal first, then editorial', async () => { - await edit('Hello, world') - expect(await act(lawyer, 'approve:legal')).toMatchObject({ - ok: true, - state: { value: legalApproved }, - effects: [], - }) - expect(await act(editor, 'approve:editorial')).toMatchObject({ - ok: true, - effects: [commit(), publish()], - }) - }) - - it('editorial first, then legal', async () => { - await edit('Hello, world') - expect(await act(editor, 'approve:editorial')).toMatchObject({ - ok: true, - state: { value: editorialApproved }, - effects: [], - }) - expect(await act(lawyer, 'approve:legal')).toMatchObject({ - ok: true, - effects: [commit(), publish()], - }) - }) - - it('either reviewer may reject; legal-review@1 sends the change set back to the author', async () => { - await edit('Hello, world') - await act(editor, 'approve:editorial') - - expect(await act(lawyer, 'reject:legal')).toMatchObject({ - ok: true, - state: { value: 'changesRequested' }, - effects: [emit('legal-review.rejected', { region: 'legal' })], - }) - expect(await cms.changeSet(p1)).toMatchObject({ - after: { title: 'Hello, world' }, - workflow: { state: { value: 'changesRequested' } }, - }) - expect(await actionTypes(editor)).toEqual([]) - expect(await actionTypes(author)).toEqual(['edit', 'discard']) - expect(await liveTitle()).toBe('Hello') - }) - }) - - it('4. a new edit during partial approval reaches decide as `edit`; legal-review@1 resets both approvals', async () => { - await edit('Hello, world') - await act(lawyer, 'approve:legal') - - const result = await edit('Hello, world!') - - expect(result).toMatchObject({ - ok: true, - state: { value: bothPending }, - effects: [stage()], - }) - expect(await cms.changeSet(p1)).toMatchObject({ - after: { title: 'Hello, world!' }, - workflow: { state: { value: bothPending } }, - }) - expect(await actionTypes(lawyer)).toEqual([ - 'approve:legal', - 'reject:legal', - ]) - }) - - it('5. the final approval commits and publishes; only then does live change, and `published` stays true', async () => { - await edit('Hello, world') - expect(await cms.as(reader).get(p1)).toMatchObject({ published: true }) - - await act(lawyer, 'approve:legal') - expect(await liveTitle()).toBe('Hello') - expect(await cms.as(reader).get(p1)).toMatchObject({ published: true }) - - const final = await act(editor, 'approve:editorial') - - expect(final).toMatchObject({ ok: true, effects: [commit(), publish()] }) - expect(await cms.as(reader).get(p1)).toEqual({ - doc: expect.objectContaining({ title: 'Hello, world' }), - revision: 4, - published: true, - }) - // `commit` consumes the coalesced change set. - expect(await cms.changeSet(p1)).toBeNull() - }) - - it('6. core rejects a decision that commits on a live doc without publishing, atomically', async () => { - const commitOnly: DocumentStateStrategy<'edited'> = { - id: 'commit-only', - version: 1, - decide: () => ({ state: 'edited', effects: [commit()] }), - availableActions: () => [], - label: () => 'Edited', - } - const broken = await cms.restart({ strategy: commitOnly }) - - const result = await broken.as(author).act({ - ...p1, - action: { type: 'edit', patch: { title: 'Sneaky' } }, - }) - - expect(result).toMatchObject({ ok: false }) - expect(await broken.as(reader).get(p1)).toMatchObject({ - doc: { title: 'Hello' }, - revision: 3, - published: true, - }) - expect(await broken.changeSet(p1)).toBeNull() - expect( - (await broken.events()).filter((e) => e.type.startsWith('document.')), - ).toEqual([]) - await broken.close() - }) - - it('7. every decision writes an audit row (actor, action, from/to, effects); core emits document.published once', async () => { - await edit('Hello, world') - await act(lawyer, 'approve:legal') - await act(editor, 'approve:editorial') - - expect(await cms.audit(p1)).toEqual([ - expect.objectContaining({ - actor: 'user:ada', - action: 'edit', - from: null, - to: expect.objectContaining({ value: bothPending }), - effects: [stage()], - }), - expect.objectContaining({ - actor: 'user:lee', - action: 'approve:legal', - from: expect.objectContaining({ value: bothPending }), - to: expect.objectContaining({ value: legalApproved }), - effects: [], - }), - expect.objectContaining({ - actor: 'user:eve', - action: 'approve:editorial', - from: expect.objectContaining({ value: legalApproved }), - to: expect.objectContaining({ value: 'published' }), - effects: [commit(), publish()], - }), - ]) - // Audit is core's job: no strategy effect asked for it. - expect( - (await cms.events()).filter((e) => e.type === 'document.published'), - ).toEqual([ - expect.objectContaining({ - collection: 'post', - id: 'p1', - actor: 'user:eve', - }), - ]) - }) - - it("8. scheduling: approvals schedule the author's publishAt; the scheduler fires `publish` as actor `scheduler`", async () => { - await edit('Hello, world', { publishAt: PUBLISH_AT }) - await act(lawyer, 'approve:legal') - - expect(await act(editor, 'approve:editorial')).toMatchObject({ - ok: true, - state: { value: 'scheduled' }, - effects: [schedule({ publishAt: PUBLISH_AT })], - }) - expect(await liveTitle()).toBe('Hello') - // Only the scheduler can fire the scheduled publish. - expect(await actionTypes(author)).not.toContain('publish') - expect(await actionTypes(schedulerContext())).toEqual(['publish']) - - await cms.runScheduler('2026-11-30T09:00:00.000Z') - expect(await liveTitle()).toBe('Hello') - expect((await cms.changeSet(p1))?.workflow?.state.value).toBe('scheduled') - - await cms.runScheduler(PUBLISH_AT) - expect(await liveTitle()).toBe('Hello, world') - expect(await cms.changeSet(p1)).toBeNull() - - const audit = await cms.audit(p1) - expect(audit.at(-1)).toMatchObject({ - actor: 'scheduler', - action: 'publish', - effects: [commit(), publish()], - }) - expect( - (await cms.events()).filter((e) => e.type === 'document.published'), - ).toEqual([expect.objectContaining({ id: 'p1', actor: 'scheduler' })]) - }) - - it('9. strategy state survives a serialize/restart round trip', async () => { - await edit('Hello, world') - await act(lawyer, 'approve:legal') - const before = await cms.changeSet(p1) - - cms = await cms.restart() - - expect(await cms.changeSet(p1)).toEqual(before) - expect(await actionTypes(lawyer)).toEqual([]) - expect(await actionTypes(editor)).toEqual([ - 'approve:editorial', - 'reject:editorial', - ]) - expect(await act(editor, 'approve:editorial')).toMatchObject({ - ok: true, - effects: [commit(), publish()], - }) - expect(await liveTitle()).toBe('Hello, world') - }) - - describe('11. bumping the strategy version', () => { - beforeEach(async () => { - await cms.seed({ - ...p2, - doc: { title: 'Untouched' }, - revision: 1, - published: true, - }) - await edit('Hello, world') - await act(lawyer, 'reject:legal') - expect((await cms.changeSet(p1))?.workflow?.state.value).toBe( - 'changesRequested', - ) - }) - - it('@2 without `migrate` reports the in-flight @1 change set as stranded; published docs are unaffected', async () => { - cms = await cms.restart({ strategy: legalReviewV2WithoutMigrate }) - - expect(await cms.strandedChangeSets()).toEqual([ - expect.objectContaining({ - collection: 'post', - id: 'p1', - strategy: 'legal-review@1', - }), - ]) - expect(await liveTitle(p1)).toBe('Hello') - expect(await liveTitle(p2)).toBe('Untouched') - // Core does not guess: acting on a stranded change set is refused. - expect( - await cms - .as(author) - .act({ ...p1, action: { type: 'edit', patch: { title: 'x' } } }), - ).toMatchObject({ ok: false }) - }) - - it('@2 with `migrate` moves the removed state forward at boot', async () => { - cms = await cms.restart({ strategy: legalReviewV2 }) - - expect(await cms.strandedChangeSets()).toEqual([]) - expect(await cms.changeSet(p1)).toMatchObject({ - after: { title: 'Hello, world' }, - workflow: { - strategy: strategyKey(legalReviewV2), - state: { value: bothPending }, - }, - }) - expect(await liveTitle(p2)).toBe('Untouched') - }) - }) - - describe('core rules beyond the eleven steps', () => { - const directForEveryone = ( - grants?: DocumentStateStrategy['grants'], - ): DocumentStateStrategy => ({ - id: 'direct-test', - version: 1, - ...(grants ? { grants } : {}), - decide: () => ({ effects: [commit(), publish()] }), - availableActions: () => [{ type: 'edit', label: 'Save' }], - label: () => 'Published', - }) - const agent = agentContext('enrich') - const agentEdit = { - ...p1, - action: { type: 'edit', patch: { title: 'By agent' } }, - } - - it('agents may stage under legal-review@1 but never publish through it', async () => { - expect(await cms.as(agent).act(agentEdit)).toMatchObject({ - ok: true, - effects: [stage()], - }) - expect(await cms.changeSet(p1)).toMatchObject({ actor: 'agent:enrich' }) - }) - - it('core rejects a publish caused by an agent unless the strategy grants it', async () => { - const floor = await cms.restart({ strategy: directForEveryone() }) - expect(await floor.as(agent).act(agentEdit)).toMatchObject({ - ok: false, - }) - expect(await floor.as(reader).get(p1)).toMatchObject({ - doc: { title: 'Hello' }, - }) - - const granted = await floor.restart({ - strategy: directForEveryone({ publish: ['agent'] }), - }) - expect(await granted.as(agent).act(agentEdit)).toMatchObject({ - ok: true, - }) - expect(await granted.as(reader).get(p1)).toMatchObject({ - doc: { title: 'By agent' }, - }) - await granted.close() - }) - - it.todo( - '(proposed, not in the plan) core rejects `emit` of reserved `document.*` events, so a strategy cannot forge document.published', - ) - it.todo( - '(proposed, not in the plan) core rejects an `edit` decision that neither stages, commits nor rejects, so an incoming patch is never dropped silently', - ) - }) +} from './document-state/legal-review.xstate' + +const dirs: Array = [] +afterAll(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }) +}) + +runDocumentStateAcceptance( + 'sqlite (built-in)', + { + database: () => { + const dir = mkdtempSync(join(tmpdir(), 'cms-acceptance-')) + dirs.push(dir) + return () => createSqliteStorage({ path: join(dir, 'cms.db') }) + }, + strategies: { legalReview, legalReviewV2, legalReviewV2WithoutMigrate }, }, + { describe, it, expect, beforeEach, afterEach }, ) diff --git a/packages/core/tests/document-state-strategy.sketch.test.ts b/packages/core/tests/document-state-strategy.sketch.test.ts index 56305a85..a14a1464 100644 --- a/packages/core/tests/document-state-strategy.sketch.test.ts +++ b/packages/core/tests/document-state-strategy.sketch.test.ts @@ -7,30 +7,30 @@ import { createActor } from 'xstate' import { describe, expect, it } from 'vitest' import { - agentContext, commit, discard, emit, publish, schedule, - schedulerContext, stage, strategyKey, unpublish, +} from '../src/index' +import { + agentContext, + schedulerContext, userContext, -} from './draft/document-state-strategy' -import { legalReview, legalReviewV2 } from './draft/legal-review.xstate' -import type { - AccessContext, - Action, - DocView, - Effect, -} from './draft/document-state-strategy' -import type { LegalReviewState } from './draft/legal-review.xstate' +} from './document-state/contexts' +import { + legalReview, + legalReviewV2, +} from './document-state/legal-review.xstate' +import type { AccessContext, Action, DocView, Effect } from '../src/index' +import type { LegalReviewState } from './document-state/legal-review.xstate' -const author = userContext('user:ada', ['author']) -const lawyer = userContext('user:lee', ['legal']) -const editor = userContext('user:eve', ['editor']) +const author = userContext('user:ada', 'author') +const lawyer = userContext('user:lee', 'legal') +const editor = userContext('user:eve', 'editor') function view(state?: LegalReviewState): DocView { return { diff --git a/packages/core/tests/document-state/contexts.ts b/packages/core/tests/document-state/contexts.ts new file mode 100644 index 00000000..f77c2af5 --- /dev/null +++ b/packages/core/tests/document-state/contexts.ts @@ -0,0 +1,30 @@ +/** + * Access contexts for running a strategy without an engine (the sketch test). + * Roles are taken as declared, with no `defineCms` role registry, so + * strategy-defined roles such as `legal` work. + */ +import { accessContext, systemContext } from '../../src/server' +import type { AccessContext } from '../../src/server' +import type { CmsSession } from '../../src/lib/auth' + +export const schedulerContext = (): AccessContext => + systemContext('scheduled publishing', { actor: 'scheduler' }) + +function session(id: string, role: string): CmsSession { + return { + isAuthenticated: true, + isAdmin: false, + role, + permissions: [], + user: { id }, + } +} + +export function userContext(id: string, role: string): AccessContext { + return accessContext({ session: session(id, role), mode: 'edit' }) +} + +export function agentContext(name: string, role = 'author'): AccessContext { + const agent = `agent:${name}` + return accessContext({ session: session(agent, role), agent, mode: 'edit' }) +} diff --git a/packages/core/tests/draft/legal-review.xstate.ts b/packages/core/tests/document-state/legal-review.xstate.ts similarity index 94% rename from packages/core/tests/draft/legal-review.xstate.ts rename to packages/core/tests/document-state/legal-review.xstate.ts index 2009a7d5..005c1f5c 100644 --- a/packages/core/tests/draft/legal-review.xstate.ts +++ b/packages/core/tests/document-state/legal-review.xstate.ts @@ -1,16 +1,11 @@ /** - * XState sketch of `legal-review@1`: legal and editorial approval run in - * parallel on one change set, written against the - * `DocumentStateStrategy` interface. XState is the documented power path, - * not the engine: core never imports it, it only stores what `decide` - * returns. + * `legal-review`: legal and editorial approval run in parallel on one change + * set, as an XState machine behind the `DocumentStateStrategy` interface. + * Core never imports XState; it stores what `decide` returns. * * The persisted state is the snapshot's `value` and `context` (plain JSON). * The machine runs through XState's pure `transition()`, so `decide` has no * running actor to keep alive between requests. - * - * Phase 4c turns this into the docs example that passes - * `document-state-strategy.acceptance.test.ts`. */ import { assign, initialTransition, setup, transition } from 'xstate' import { @@ -21,18 +16,18 @@ import { publish, schedule, stage, -} from './document-state-strategy' +} from '@tanstack/cms-core' import type { AnyStateNode, StateValue } from 'xstate' import type { AccessContext, Action, ActionDescriptor, - Actor, DocView, DocumentStateStrategy, Effect, StateGraph, -} from './document-state-strategy' + StrategyActor, +} from '@tanstack/cms-core' export interface LegalReviewContext { /** A publish time the author asked for; approvals gate it. */ @@ -47,18 +42,18 @@ export interface LegalReviewState { type Region = 'legal' | 'editorial' type LegalReviewEvent = - | { type: 'edit'; actor: Actor; publishAt: string | null } - | { type: 'discard'; actor: Actor } - | { type: 'publish'; actor: Actor } - | { type: `approve:${Region}`; actor: Actor } - | { type: `reject:${Region}`; actor: Actor; reason: string } + | { type: 'edit'; actor: StrategyActor; publishAt: string | null } + | { type: 'discard'; actor: StrategyActor } + | { type: 'publish'; actor: StrategyActor } + | { type: `approve:${Region}`; actor: StrategyActor } + | { type: `reject:${Region}`; actor: StrategyActor; reason: string } const REVIEWER_ROLE: Record = { legal: 'legal', editorial: 'editor', } -function hasRole(actor: Actor, role: string): boolean { +function hasRole(actor: StrategyActor, role: string): boolean { return actor.roles.includes(role) } diff --git a/packages/core/tests/draft/acceptance-harness.ts b/packages/core/tests/draft/acceptance-harness.ts deleted file mode 100644 index a0e59056..00000000 --- a/packages/core/tests/draft/acceptance-harness.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * DRAFT core-side surface the document state strategy acceptance spec drives. - * - * The strategy types are real since phase 4a (re-exported through - * `./document-state-strategy`), and so are the effect executor and the - * scheduler firing `publish` as the `scheduler` actor. `createAcceptanceHarness` - * still rejects, because the spec needs what lands later: - * - * - 4b: strategy state persisted with the change set (`workflow_strategy` / - * `workflow_state` on `pending`, so `ChangeSetView.workflow` is not - * `null`); transition fields on `audit` (`from`, `to`, `effects`, a - * refusal's `reason`) behind `AuditRow`; change-set scheduling (a - * `schedule` effect on a live doc's change set, and the sweep that fires - * `publish` for it); stranded change-set detection for `stranded()`. - * - 4c: the spec shipped as an exported, runner-injected suite (like - * `runStorageConformance`) so `store-libsql` and `store-postgres` run it, - * this harness implemented on the public engine calls, and the `.skip` - * removed. - * - * Keep this file thin: it should map one-to-one onto public engine calls, so - * the spec never reaches into core internals. - */ -import type { - AccessContext, - Action, - ActionDescriptor, - ChangeSetView, - DocumentStateStrategy, - Effect, -} from './document-state-strategy' - -export type StorageDialect = 'libsql' | 'postgres' - -export interface LiveRead { - doc: Record - revision: number - published: boolean -} - -export type ActResult = - | { ok: true; state: S | undefined; effects: ReadonlyArray } - | { ok: false; reason: string } - -export interface AuditRow { - changeSet: string | null - actor: string - action: string - from: unknown - to: unknown - effects: ReadonlyArray -} - -export interface OutboxEvent { - type: string - collection: string - id: string - actor: string - payload?: unknown -} - -export interface StrandedChangeSet { - collection: string - id: string - changeSet: string - /** `id@version` the change set was written with. */ - strategy: string - reason: string -} - -export interface DocRef { - collection: string - id: string -} - -/** What `cms.as(ctx)` will offer for this spec. */ -export interface BoundHandle { - /** Honors the context mode: `live` reads the core-owned live record. */ - get: (ref: DocRef) => Promise - act: (ref: DocRef & { action: Action }) => Promise> - availableActions: (ref: DocRef) => Promise> -} - -export interface AcceptanceHarness { - as: (ctx: AccessContext) => BoundHandle - /** Seeds a committed document directly, outside any strategy. */ - seed: ( - ref: DocRef & { - doc: Record - revision: number - published: boolean - }, - ) => Promise - changeSet: (ref: DocRef) => Promise | null> - audit: (ref: DocRef) => Promise> - /** Everything enqueued in the outbox since the harness started. */ - events: () => Promise> - /** Runs one scheduler sweep as if the clock read `nowIso`. */ - runScheduler: (nowIso: string) => Promise - /** Closes the engine and boots a new one over the same storage. */ - restart: (options?: { - strategy?: DocumentStateStrategy - }) => Promise> - /** The boot report of change sets the current strategy can't interpret. */ - strandedChangeSets: () => Promise> - /** Idempotent; `restart` closes the harness it was called on. */ - close: () => Promise -} - -export interface AcceptanceHarnessOptions { - storage: StorageDialect - collection: string - strategy: DocumentStateStrategy -} - -export function createAcceptanceHarness( - options: AcceptanceHarnessOptions, -): Promise> { - return Promise.reject( - new Error( - `createAcceptanceHarness(${options.storage}, ${options.strategy.id}@${options.strategy.version}) lands in phase 4 of the core API refactor`, - ), - ) -} diff --git a/packages/core/tests/draft/document-state-strategy.ts b/packages/core/tests/draft/document-state-strategy.ts deleted file mode 100644 index 1d952e40..00000000 --- a/packages/core/tests/draft/document-state-strategy.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * The document state strategy API the acceptance spec and the XState sketch - * are written against. - * - * Phase 0 drafted it here; phase 4a promoted the types and effect constructors - * into `@tanstack/cms-core` (`src/document-state.ts`), and `ctx` is the phase - * 2a `AccessContext`. This module now re-exports the real API and keeps the - * draft's context helpers, built from real contexts. It stays test-local - * because the context builders are internal until phase 2b. - */ -import { agentContext as engineAgentContext } from '../../src/server/access-context' -import { accessContext, systemContext } from '../../src/server/access-context' -import type { AccessContext, ReadMode } from '../../src/server/access-context' -import type { CmsSession } from '../../src/lib/auth' - -export { - actorOf, - commit, - discard, - emit, - publish, - schedule, - stage, - strategyKey, - unpublish, -} from '../../src/document-state' -export type { - Action, - ActionDescriptor, - ChangeSetView, - DocView, - DocumentStateStrategy, - Effect, - StateGraph, - StrategyActor as Actor, -} from '../../src/document-state' -export type { AccessContext, ReadMode } -export { publicContext } from '../../src/server/access-context' -export { systemContext } - -/** The scheduler, as core builds it for scheduled publishes. */ -export const schedulerContext = (): AccessContext => - systemContext('scheduled publishing', { actor: 'scheduler' }) - -/** - * A signed-in user. A session holds one role today, so only `roles[0]` is - * used; the role is taken as declared (no `defineCms` role registry check), - * so strategy-defined roles such as `legal` work. - */ -function session(id: string, roles: ReadonlyArray): CmsSession { - return { - isAuthenticated: true, - isAdmin: false, - role: roles[0] ?? null, - permissions: [], - user: { id }, - } -} - -export function userContext( - id: string, - roles: ReadonlyArray, - mode: ReadMode = 'edit', -): AccessContext { - return accessContext({ session: session(id, roles), mode }) -} - -export function agentContext( - name: string, - roles: ReadonlyArray = ['author'], -): AccessContext { - const agent = `agent:${name}` - return engineAgentContext({ agent, session: session(agent, roles) }) -} diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.ts index 84d72217..340d1d4a 100644 --- a/packages/core/tsdown.config.ts +++ b/packages/core/tsdown.config.ts @@ -8,6 +8,7 @@ export default defineConfig({ 'src/flags.ts', 'src/storage.ts', 'src/storage/conformance.ts', + 'src/document-state/acceptance.ts', 'src/media.ts', 'src/media/conformance.ts', ], diff --git a/packages/store-libsql/tests/document-state-acceptance.test.ts b/packages/store-libsql/tests/document-state-acceptance.test.ts new file mode 100644 index 00000000..cda67ff4 --- /dev/null +++ b/packages/store-libsql/tests/document-state-acceptance.test.ts @@ -0,0 +1,30 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest' +import { runDocumentStateAcceptance } from '@tanstack/cms-core/document-state/acceptance' +import { + legalReview, + legalReviewV2, + legalReviewV2WithoutMigrate, +} from '../../core/tests/document-state/legal-review.xstate' +import { createLibsqlStorage } from '../src' + +const dirs: Array = [] +afterAll(() => { + for (const d of dirs) rmSync(d, { recursive: true, force: true }) +}) + +runDocumentStateAcceptance( + 'libsql (local file)', + { + database: () => { + const dir = mkdtempSync(join(tmpdir(), 'cms-libsql-acceptance-')) + dirs.push(dir) + const url = `file:${join(dir, 'cms.db')}` + return () => createLibsqlStorage({ url }) + }, + strategies: { legalReview, legalReviewV2, legalReviewV2WithoutMigrate }, + }, + { describe, it, expect, beforeEach, afterEach }, +) diff --git a/packages/store-postgres/tests/document-state-acceptance.test.ts b/packages/store-postgres/tests/document-state-acceptance.test.ts new file mode 100644 index 00000000..6d60ebe3 --- /dev/null +++ b/packages/store-postgres/tests/document-state-acceptance.test.ts @@ -0,0 +1,27 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { runDocumentStateAcceptance } from '@tanstack/cms-core/document-state/acceptance' +import { + legalReview, + legalReviewV2, + legalReviewV2WithoutMigrate, +} from '../../core/tests/document-state/legal-review.xstate' +import { createPostgresStorage } from '../src' +import { newPrefix, pool, url } from './helpers' + +runDocumentStateAcceptance( + 'postgres', + { + database: () => { + const prefix = newPrefix() + return () => createPostgresStorage({ pool: pool!, prefix }) + }, + strategies: { legalReview, legalReviewV2, legalReviewV2WithoutMigrate }, + }, + { + describe: url ? describe : describe.skip, + it, + expect, + beforeEach, + afterEach, + }, +) diff --git a/packages/ui-react/src/lib/i18n.ts b/packages/ui-react/src/lib/i18n.ts index 4fbe7fba..2e34bb19 100644 --- a/packages/ui-react/src/lib/i18n.ts +++ b/packages/ui-react/src/lib/i18n.ts @@ -354,6 +354,12 @@ export const defaultAdminMessages = { 'review.approveDelete': 'Approve & delete', 'review.approveDraft': 'Approve as draft', 'review.reject': 'Reject', + 'review.stranded': + "This collection's workflow can't read this change set. Discard it to unblock the document.", + 'review.scheduledFor': 'Publishes {at}', + 'review.scheduleAt': 'Publish at', + 'review.schedule': 'Schedule', + 'review.clearSchedule': 'Clear schedule', 'review.audit': 'Audit trail', 'review.decision.approved': 'approved', 'review.decision.rejected': 'rejected', diff --git a/packages/ui-react/src/routes/review.tsx b/packages/ui-react/src/routes/review.tsx index 31f656bf..bc44d4be 100644 --- a/packages/ui-react/src/routes/review.tsx +++ b/packages/ui-react/src/routes/review.tsx @@ -2,6 +2,7 @@ import { createFileRoute, useRouter } from '@tanstack/react-router' import { useState } from 'react' import { collections, hasPermission } from '@tanstack/cms-core' import { + actOnChange, approveChange, rejectChange, reviewSnapshot, @@ -10,6 +11,7 @@ import { AdminShell, CommentsPanel } from '../primitives' import { routeSession, useCan, useCmsAuth } from '../lib/auth' import { adminRich, adminT } from '../lib/i18n' import type { AdminMessageId } from '../lib/i18n' +import type { ActionDescriptor } from '@tanstack/cms-core' import type { AuditRecord, Pending } from '@tanstack/cms-core/server' import '../app-renderers' @@ -50,6 +52,26 @@ const DECISION_LABELS = { AdminMessageId > +/** + * Strategy actions the review page runs with dedicated controls (`approve`, + * `reject`, `schedule`) or not at all (the ones that carry a document). + */ +const NOT_GENERIC = new Set([ + 'approve', + 'reject', + 'schedule', + 'edit', + 'submit', + 'draft', + 'import', +]) + +const TONE_CLASSES: Record, string> = { + primary: 'bg-green-600 text-white hover:bg-green-700', + danger: 'bg-white text-red-700 ring-1 ring-red-300 hover:bg-red-50', + default: 'bg-white text-neutral-700 ring-1 ring-neutral-300', +} + function ReviewPage() { const { pending, audit } = Route.useLoaderData() const { ai } = useCmsAuth() @@ -60,11 +82,13 @@ function ReviewPage() { Record >({}) - async function act( + const versionOf = (id: string) => + pending.find((proposal) => proposal.id === id)?.version ?? 0 + + async function run( id: string, - decision: 'approve' | 'reject', + call: () => Promise, publish?: boolean, - force?: boolean, ) { setBusy(id) setErrors((prev) => { @@ -73,11 +97,7 @@ function ReviewPage() { return next }) try { - const expectedVersion = - pending.find((proposal) => proposal.id === id)?.version ?? 0 - if (decision === 'approve') { - await approveChange({ data: { id, publish, force, expectedVersion } }) - } else await rejectChange({ data: { id, expectedVersion } }) + await call() await router.invalidate() } catch (e) { const message = e instanceof Error ? e.message : String(e) @@ -90,6 +110,36 @@ function ReviewPage() { } } + function act( + id: string, + decision: 'approve' | 'reject', + publish?: boolean, + force?: boolean, + ) { + const expectedVersion = versionOf(id) + return run( + id, + () => + decision === 'approve' + ? approveChange({ data: { id, publish, force, expectedVersion } }) + : rejectChange({ data: { id, expectedVersion } }), + publish, + ) + } + + function runAction(id: string, action: string, publishAt?: string | null) { + return run(id, () => + actOnChange({ + data: { + id, + action, + expectedVersion: versionOf(id), + ...(publishAt !== undefined ? { publishAt } : {}), + }, + }), + ) + } + return (
@@ -112,6 +162,10 @@ function ReviewPage() { !isDelete && !p.after.published && !p.after.publishAt const collectionLabel = collections()[p.collection]?.label ?? p.collection + const offered = new Set(p.review.actions.map((a) => a.type)) + const generic = p.review.actions.filter( + (a) => !NOT_GENERIC.has(a.type), + ) return (
  • {' '} {collectionLabel} /{' '} - {p.docId} + {p.docId}{' '} + + {p.review.label} + + {p.publishAt && ( + + {adminT('review.scheduledFor', { + at: new Date(p.publishAt).toLocaleString(), + })} + + )}
  • {typeof p.after._assignee === 'string' && @@ -145,6 +216,15 @@ function ReviewPage() { {actorLabel(p.actor)}
    + {p.review.stranded && ( +
    +

    {adminT('review.stranded')}

    +

    {p.review.stranded}

    +
    + )} {isDelete && (
    {adminRich('review.deleteWarning', { @@ -197,8 +277,8 @@ function ReviewPage() { )}
    )} - {canDecide && ( -
    +
    + {offered.has('approve') && ( - {isDraftProposal && ( - - )} + )} + {offered.has('approve') && isDraftProposal && ( + + )} + {offered.has('reject') && ( -
    - )} + )} + {generic.map((action) => ( + + ))} + {offered.has('schedule') && ( + + void runAction(p.id, 'schedule', at) + } + /> + )} +
    ) })} @@ -302,6 +405,48 @@ function ReviewPage() { ) } +/** Set or clear when a change set goes live (the strategy's `schedule` action). */ +function ScheduleControl({ + publishAt, + disabled, + onSchedule, +}: { + publishAt: string | null + disabled: boolean + onSchedule: (at: string | null) => void +}) { + const [value, setValue] = useState('') + return ( + + + + {publishAt && ( + + )} + + ) +} + function PendingDiff({ pending }: { pending: Pending }) { const collection = collections()[pending.collection] const fields = [ diff --git a/tsconfig.docs.json b/tsconfig.docs.json index aba1b66b..53bb943e 100644 --- a/tsconfig.docs.json +++ b/tsconfig.docs.json @@ -42,7 +42,8 @@ ], "@tanstack/ai-mcp/server": [ "./packages/api/node_modules/@tanstack/ai-mcp/dist/esm/server/index.d.ts" - ] + ], + "xstate": ["./packages/core/node_modules/xstate/dist/xstate.cjs.d.mts"] } } }