diff --git a/.changeset/default-flow-approved.md b/.changeset/default-flow-approved.md new file mode 100644 index 00000000..f5316c5d --- /dev/null +++ b/.changeset/default-flow-approved.md @@ -0,0 +1,14 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-ui-react': minor +--- + +The default document state strategy is now Draft → Pending Review → Approved → Published. A reviewer who holds `review.decide` but not `content.publish` approves a staged change into the new `approved` state (audited as `transitioned`, emitting `review.approved`) without touching the live document; a publisher's `publish` action then applies it (an approved deletion needs `content.delete`), or the scheduler publishes it at its `publishAt`. A reviewer who can publish still approves and publishes in one decision, so apps whose reviewers can publish behave as before. A new submission sends an approved change back to Pending Review. `approveChange` accepts reviewers without `content.publish` (the strategy decides, and core re-checks access for anything that writes live content), and the review page shows them a single **Approve** button and publishers a **Publish** button on approved changes. + +Breaking changes: + +- The default strategy's labels are `Pending Review` (was `Pending review`) and the new `Approved`; `ReviewState` gains `'approved'`. +- `approveChange` by a reviewer without `content.publish` used to fail with `FORBIDDEN`; it now moves the change to Approved. +- A scheduled or manual publish of an approved change set no longer emits a second `review.approved` (it was emitted at approval). +- `directStrategy().describe()` charts only its own states (Unpublished, Published, Draft); `reviewStrategy().describe()` adds Approved. diff --git a/app/prm/README.md b/app/prm/README.md index 324ae26c..73282816 100644 --- a/app/prm/README.md +++ b/app/prm/README.md @@ -8,6 +8,7 @@ Built for individuals, small teams, and families — ideal for running on a home - **Self-contained instance data directory (`PRM_DATA_DIR`)** — stores configuration (`prm.json`), secrets (`secrets.env`), SQLite database (`cms.db`), uploaded photos (`uploads/`), and snapshots (`backups/`) in one directory outside the repo. - **Multi-user DB authentication** — first-run `/setup` creates the `owner` account; invite family or teammates via one-time `/invite/$token` links from `/prm-settings`. +- **Owner direct, agent review** — the PRM's document state strategy, `ownerDirectAgentReview` in `src/document-state.ts`: people who may publish (owners, members) commit their own saves, and agent and import writes go through review. - **Optional approval workflow (off by default)** — `approvalRequired: false` auto-approves agent and import writes while preserving full revision and audit history; flip it on in `/prm-settings` to stage changes into `/review`. - **Groups & Events** — organize people into recurring circles (`TanStack`, `Creators`, `Founders`, `Oak St & School Parents`) or time-bounded events (`Timmy's Birthday Party`, `AI Coding Summit 2026`) with start/end times, location, per-event roles/talks, and a talked-with progress bar. - **Rich person profiles** — multiple names (`aliases` / AKAs), `pronouns`, human-only personal contact fields (`phone`, `email`, `birthday`, `address`), per-field provenance (`personSource`), and deep-snoop enrichment. diff --git a/app/prm/src/cms.config.ts b/app/prm/src/cms.config.ts index 3bb805c5..93e77003 100644 --- a/app/prm/src/cms.config.ts +++ b/app/prm/src/cms.config.ts @@ -5,7 +5,9 @@ * - Stores all instance settings (`prm.json`), secrets (`secrets.env`), SQLite * database (`cms.db`), and uploads (`uploads/`) inside a single data directory * - DB-backed multi-user auth (`owner`, `member`, `viewer`) via `createDbAuth` - * - Optional review queue (`review.autoApprove` defaults to `!instance.approvalRequired`) + * - Owner direct, agent review (`ownerDirectAgentReview`): people who may publish + * commit their own saves; agent writes stage in the review queue, or are + * auto-approved when `instance.approvalRequired` is off * - Two named conversational agents alongside `/agent`: * - `enrich` (`actor: 'enrichment-agent'`, deep-snoop web tools, 30 iterations) * - `ask` (`actor: 'crm-chat'`, read-only toolset, cited answers) @@ -19,6 +21,7 @@ import { enrichAgentConfig, ENRICHMENT_SKILL_PROMPT } from './agents/enrich' import { askAgentConfig } from './agents/ask' import { crmEventHandlers } from './events' import { definition } from './cms.definition' +import { ownerDirectAgentReview } from './document-state' const resolveServerDataDir = createServerOnlyFn(async () => { const { resolvePrmDataDir } = await import('./instance.server') @@ -41,13 +44,13 @@ export const cms = defineCms(definition, { ops: [importPeopleOp], eventHandlers: crmEventHandlers, seed, - review: { + documentState: ownerDirectAgentReview({ autoApprove: createServerOnlyFn(async () => { await resolveServerDataDir() const { getPrmInstanceSettings } = await import('./instance.server') return !getPrmInstanceSettings().approvalRequired }), - }, + }), auth: { defaultRole: 'member', getUser: createServerOnlyFn(async ({ request }) => { diff --git a/app/prm/src/document-state.ts b/app/prm/src/document-state.ts new file mode 100644 index 00000000..a24eb507 --- /dev/null +++ b/app/prm/src/document-state.ts @@ -0,0 +1,43 @@ +/** + * The PRM's document state strategy: owner direct, agent review. + * + * The PRM is personal, so a signed-in person who may publish (owner, member, + * editor) commits their own saves at once; nobody approves their own notes. + * Agent writes (the `enrich` agent, MCP keys, `import_people`) go through the + * review flow: they stage in `/review` unless the instance's + * `approvalRequired` setting is off, in which case they are approved at once + * as `auto-approve`. Either way they stay attributed and audited. + */ +import { actorOf, directStrategy, reviewStrategy } from '@tanstack/cms-core' +import type { + AccessContext, + DocumentStateStrategy, + ReviewState, + ReviewStrategyOptions, +} from '@tanstack/cms-core' + +const SAVES = new Set(['edit', 'submit', 'import']) + +function ownsTheirSaves(ctx: AccessContext): boolean { + return ( + actorOf(ctx).type === 'user' && + ctx.permissions.some((p) => p === 'content.publish') + ) +} + +export function ownerDirectAgentReview( + options: Pick = {}, +): DocumentStateStrategy { + const review = reviewStrategy(options) + const direct = directStrategy() + return { + ...review, + id: 'prm-owner-direct', + version: 1, + decide(ctx, doc, action) { + return SAVES.has(action.type) && ownsTheirSaves(ctx) + ? direct.decide(ctx, doc, action) + : review.decide(ctx, doc, action) + }, + } +} diff --git a/app/prm/tests/crm.test.ts b/app/prm/tests/crm.test.ts index a1c7d9da..b217663e 100644 --- a/app/prm/tests/crm.test.ts +++ b/app/prm/tests/crm.test.ts @@ -28,8 +28,10 @@ import { normalizeSession, PERMISSIONS, } from '@tanstack/cms-core' -import type { Field } from '@tanstack/cms-core' +import type { AnyDocumentStateStrategy, Field } from '@tanstack/cms-core' import { + accessContext, + actOnDocument, approve, closeStore, cmsTools, @@ -63,11 +65,16 @@ import { import { isHumanCreatedNewPerson } from '../src/events' import { BAKEOFF_SUBJECTS, runBakeoff } from '../scripts/bakeoff' import { buildKodyMcpRegistration } from '../kody-package' +import { ownerDirectAgentReview } from '../src/document-state' afterEach(closeStore) -function setupCrmTest(extra?: { textAdapter?: () => unknown }) { +function setupCrmTest(extra?: { + textAdapter?: () => unknown + documentState?: AnyDocumentStateStrategy +}) { defineCms({ + ...(extra?.documentState ? { documentState: extra.documentState } : {}), storage: createSqliteStorage({ path: ':memory:' }), collections: crmCollections, blockTypes: [], @@ -108,6 +115,54 @@ function setupCrmTest(extra?: { textAdapter?: () => unknown }) { } describe('CRM acceptance criteria (§11)', () => { + it('owner direct, agent review: a person who may publish commits their own saves; agent saves stage unless approval is off', async () => { + for (const approvalRequired of [true, false]) { + setupCrmTest({ + documentState: ownerDirectAgentReview({ + autoApprove: () => !approvalRequired, + }), + }) + const owner = normalizeSession({ + isAuthenticated: true, + isAdmin: false, + role: 'editor', + user: { id: 'jack', name: 'Jack' }, + }) + const save = (id: string, ctx: Parameters[0]) => + actOnDocument(ctx, { + collection: 'person', + id, + action: { + type: 'submit', + patch: { name: id, headline: 'Notes', published: true }, + input: { change: 'create', source: 'review' }, + }, + }) + + await save('by-owner', accessContext({ session: owner, mode: 'edit' })) + expect(await readDocument('person', 'by-owner')).toMatchObject({ + name: 'by-owner', + }) + + await save( + 'by-agent', + accessContext({ session: owner, agent: 'enrich', mode: 'edit' }), + ) + if (approvalRequired) { + expect(await readDocument('person', 'by-agent')).toBeNull() + expect( + (await listPending()).map((p) => [p.docId, p.workflow?.state]), + ).toEqual([['by-agent', 'pending_review']]) + } else { + expect(await readDocument('person', 'by-agent')).toMatchObject({ + name: 'by-agent', + }) + expect(await listPending()).toEqual([]) + } + await closeStore() + } + }) + it('§11.8: personal contact fields (email, phone, birthday, address) are writable by humans and blocked for agent sessions', () => { const contactFields = person.fields.filter((f) => ['email', 'phone', 'birthday', 'address'].includes(f.name), diff --git a/docs/agents/custom-strategies.md b/docs/agents/custom-strategies.md index c9801856..9ca8bdd7 100644 --- a/docs/agents/custom-strategies.md +++ b/docs/agents/custom-strategies.md @@ -420,7 +420,7 @@ export function defineLegalReview( const live = doc.live?.published ? 'Published' : 'Unpublished' if (!state) return live const regions = regionLabel(state.value) - if (regions) return `Pending review (${regions})` + if (regions) return `Pending Review (${regions})` switch (state.value) { case 'changesRequested': return 'Changes requested' diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index 811e1b3f..78d1d5cf 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -20,7 +20,9 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a - **Unpublished documents** are saved directly by anyone who may publish. - **Published documents** get a **draft**: the live version stays as it is until someone publishes the changes. -- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them. +- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where a reviewer approves or rejects them. + +A change moves through the default flow's states: **Draft** (a publisher's private working copy), **Pending Review** (a staged proposal), **Approved** (a reviewer approved it; it waits for a publisher) and **Published**. A reviewer who may also publish approves and publishes in one step, so **Approved** only appears when reviewing and publishing are separate roles. Every commit records a **revision**, and every decision (a direct save, an approval, a rejection, a discarded draft, a scheduled publish, an import) lands in the **audit trail**. @@ -84,7 +86,7 @@ Agents can read their own staged work. `read_document` and `update_document` fal The `/review` page lists pending changes with a field-level diff, the proposer, and any instruction note the agent attached. Deletions are highlighted in red and list the fields that will be removed. -Anyone with `content.read` can view the queue (limited to collections they may read, with unreadable fields redacted). Deciding requires `review.decide`, plus the right to publish (or, for deletions, delete) in that collection: +Anyone with `content.read` can view the queue (limited to collections they may read, with unreadable fields redacted). Deciding requires `review.decide`. A reviewer who may also publish (or, for deletions, delete) in that collection applies the change as they approve it: - **Approve & publish** commits the change and publishes it. For a proposal that already sets `published: true`, the document goes live as proposed. - **Approve as draft** (offered for proposals that don't publish) commits the content with `published: false`. @@ -93,7 +95,18 @@ 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 reviewer without `content.publish` sees **Approve** instead. It moves the change to **Approved** (audited as `transitioned`, with a `review.approved` event) and leaves the live document as it is. A publisher then sees **Publish**, which applies the approved change and publishes it (on a published document they can also schedule it with **Publish at**); a new submission sends it back to **Pending Review**. For example, a `reviewer` role that approves but can't publish: + +```ts +defineCms({ + roles: { + reviewer: ['content.read', 'review.decide'], + }, + // ... +}) +``` + +Each pending change also shows its strategy's label for the document's state (for example **Pending Review** or **Approved**, 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: @@ -119,21 +132,26 @@ defineCms({ }) ``` -The built-in strategies' states and actions, generated from `reviewStrategy().describe()` with `stateGraphToMermaid`: +The default strategy's 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 + state "Pending Review" as pending_review + state "Approved" as approved unpublished --> pending_review: submit published --> pending_review: submit published --> draft: draft draft --> published: edit draft --> published: discard - pending_review --> published: approve + pending_review --> approved: approve + pending_review --> published: approve (publisher) pending_review --> unpublished: reject + approved --> published: publish + approved --> pending_review: submit + approved --> unpublished: reject unpublished --> published: publish published --> unpublished: unpublish ``` diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index d3b08da2..b042f6da 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -250,7 +250,7 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/ | `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 }`. 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. | +| `approveChange` | POST | `review.decide` | `{ id, publish?, force? }` | The approved pending change. A reviewer without `content.publish` moves it to **Approved** for a publisher to publish. `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). | diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index 75d353c8..060f5a7f 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -50,13 +50,18 @@ The locator lives in the system namespace next to `id`, so a user field named `l ## Document state strategy -**Partly implemented.** The per-collection lifecycle of a document's edits: which actions exist (`edit`, `approve`, `publish`, …), who may take them, and what happens when they do. It's set per app in `defineCms` and can be overridden per collection. Every write passes through the collection's strategy; the strategy decides how much governance happens inside it. +**Implemented.** The per-collection lifecycle of a document's edits: which actions exist (`edit`, `approve`, `publish`, …), who may take them, and what happens when they do. It's set per app in `defineCms` and can be overridden per collection. Every write passes through the collection's strategy; the strategy decides how much governance happens inside it. A strategy is a small object. Given the [access context](#access-context), the document and an action, it returns a decision: a new state plus a list of [effects](#effect), or a rejection. It also answers "which actions can this actor take?" and "what is this state called?" for the admin UI. Its state is a serializable value that core stores and never interprets. It's versioned (`legal-review@1`), and a version that removes states must provide `migrate(state)`. -Planned built-ins: **review** (Draft → Pending Review → Approved → Published) and **direct** (an edit publishes immediately, for personal apps). Complex flows, such as legal and editorial approval running in parallel, can be written with XState. XState is a documented option, not the engine. +Two built-ins ship, neither written with XState: -**Today:** the interface, the effects and core's rules exist, with two built-ins that reproduce the one flow from before: `reviewStrategy()` (the default; writes either commit for publishers or stage into the review queue, approving a staged change commits it, and `review.autoApprove` loosens it) and `directStrategy()` (agent and author writes commit at once). Set one with `defineCms({ documentState })` or a collection's `documentState`. Every write door goes through it: saves, staging, approve, reject, drafts, the scheduler and `tanstack-cms import`. A decision's state is stored with the change set and upgraded with `migrate`; a change set no strategy version can read is stranded and can only be discarded (`listStrandedChangeSets()`). **Planned:** available actions and labels in the admin UI, and the new default-flow naming. +- **review**, `reviewStrategy()`, the default: Draft → Pending Review → Approved → Published. Publishers' saves commit (or become a private draft of a published document), and everyone else's stage as **Pending Review**. A reviewer who can't publish approves a change into **Approved**, and a publisher's `publish` applies it; a reviewer who can publish does both at once. `review.autoApprove` (or the `autoApprove` option) approves staged writes at once. +- **direct**, `directStrategy()`: agent and author writes commit at once, for personal apps. + +Set one with `defineCms({ documentState })`, and override it per collection with the collection's `documentState`. A strategy can branch on the context, too: the PRM's `ownerDirectAgentReview` commits a person's own saves and sends agent writes through review. Complex flows, such as legal and editorial approval running in parallel, can be written with XState ([Custom Document State Strategies](../agents/custom-strategies)). XState is a documented option, not the engine. + +Every write door goes through the strategy: saves, staging, approve, reject, drafts, the scheduler and `tanstack-cms import`. A decision's state is stored with the change set and upgraded with `migrate`; a change set no strategy version can read is stranded and can only be discarded (`listStrandedChangeSets()`). The review page shows each change set's state label and the actions its strategy offers the reviewer. ## Change set diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 251fec21..2f1b0843 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -57,7 +57,7 @@ interface CmsOperation { | `savePageBlocks` | POST | `content.write` | Save a page's blocks from the on-page editor | | `restoreDocRevision` | POST | `content.publish` | Restore a revision | | `deleteDoc` | POST | `content.delete` | Delete a document (`force` to ignore references) | -| `approveChange` | POST | `review.decide` | Approve a staged change (optionally as a draft) | +| `approveChange` | POST | `review.decide` | Approve a staged change (optionally as a draft); a reviewer who can't publish moves it to Approved | | `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 | diff --git a/examples/blog/e2e/cms.spec.ts b/examples/blog/e2e/cms.spec.ts index 08bc3254..e7a0bfb2 100644 --- a/examples/blog/e2e/cms.spec.ts +++ b/examples/blog/e2e/cms.spec.ts @@ -109,7 +109,7 @@ test('an author submits for review and an editor approves', async ({ .filter({ has: page.getByTestId('review-state') }) .filter({ hasText: 'Hello, reviewed world' }) await expect(proposal.getByTestId('review-state')).toHaveText( - 'Pending review', + 'Pending Review', ) await proposal.getByLabel('Publish at').fill('2999-01-01T09:00') await proposal.getByRole('button', { name: 'Schedule', exact: true }).click() diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 859c1751..7e43548b 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -1166,22 +1166,28 @@ const _ops = { const pending = await getPending(input.id) if (!pending) throw new CmsError(`Unknown pending change: ${input.id}`, 'NOT_FOUND') - assertCollectionAccess( - ctx.session, - pending.collection, - pending.type === 'delete' ? 'delete' : 'publish', - (await readDocument(pending.collection, pending.docId)) ?? - pending.before ?? - pending.after, - ) - if (pending.type !== 'delete') { - const live = await readDocument(pending.collection, pending.docId) + const live = await readDocument(pending.collection, pending.docId) + if (!hasPermission(ctx.session, 'content.publish')) { + // The strategy decides what a non-publishing reviewer's approval + // does; core re-checks access if it writes live content. + assertReadable(editing(ctx), pending.collection, { + id: pending.docId, + doc: live ?? pending.before ?? pending.after, + }) + } else { assertCollectionAccess( ctx.session, pending.collection, - live ? 'update' : 'create', - live ?? pending.after, + pending.type === 'delete' ? 'delete' : 'publish', + live ?? pending.before ?? pending.after, ) + if (pending.type !== 'delete') + assertCollectionAccess( + ctx.session, + pending.collection, + live ? 'update' : 'create', + live ?? pending.after, + ) } const decided = await approve(input.id, { session: ctx.session, diff --git a/packages/api/tests/act-on-change.test.ts b/packages/api/tests/act-on-change.test.ts index a26e5372..c507e62c 100644 --- a/packages/api/tests/act-on-change.test.ts +++ b/packages/api/tests/act-on-change.test.ts @@ -80,7 +80,7 @@ describe('the review queue and actOnChange', () => { setupCms() const pitch = await stagePitch() expect(pitch.review).toEqual({ - label: 'Pending review', + label: 'Pending Review', actions: expect.arrayContaining([ expect.objectContaining({ type: 'approve' }), expect.objectContaining({ type: 'reject' }), @@ -94,6 +94,51 @@ describe('the review queue and actOnChange', () => { ).not.toContain('approve') }) + it("a reviewer who can't publish approves into Approved, and a publisher publishes it", async () => { + setupCms({ roles: { reviewer: ['content.read', 'review.decide'] } }) + const pitch = await stagePitch() + const asReviewer = await call('reviewSnapshot', {}, 'reviewer') + expect( + asReviewer.result.pending[0].review.actions.map( + (a: { type: string }) => a.type, + ), + ).toEqual(['approve', 'reject']) + + expect( + await call( + 'approveChange', + { id: pitch.id, expectedVersion: pitch.version }, + 'reviewer', + ), + ).toMatchObject({ status: 200 }) + expect(await readDocument('post', 'pitch')).toBeNull() + const [approved] = (await call('reviewSnapshot', {}, 'editor')).result + .pending + expect(approved.review).toMatchObject({ + label: 'Approved', + actions: expect.arrayContaining([ + expect.objectContaining({ type: 'publish', label: 'Publish' }), + ]), + }) + + expect( + ( + await call( + 'actOnChange', + { id: pitch.id, action: 'publish' }, + 'reviewer', + ) + ).code, + ).toBe('FORBIDDEN') + expect( + await call('actOnChange', { id: pitch.id, action: 'publish' }, 'editor'), + ).toMatchObject({ status: 200, result: { label: 'Published' } }) + expect(await readDocument('post', 'pitch')).toMatchObject({ + title: 'Pitch', + published: true, + }) + }) + it("runs an action the strategy offers, and refuses one it doesn't", async () => { setupCms({ collections: [{ ...post, documentState: signoff() }] }) const pitch = await stagePitch() diff --git a/packages/core/src/document-state.ts b/packages/core/src/document-state.ts index 3310a2d3..b2240cd6 100644 --- a/packages/core/src/document-state.ts +++ b/packages/core/src/document-state.ts @@ -137,14 +137,16 @@ export type Decision = * - `submit`: propose `patch` for review (agents, authors). * - `draft`: save `patch` as a private draft of a published document. * - `approve` / `reject`: decide the open change set. `approve` takes - * `input.publish` to override the proposed published flag. + * `input.publish` to override the proposed published flag. Under the + * default strategy a reviewer who can't publish moves the change set to + * `approved`, and a publisher's `publish` then applies it. * - `discard`: drop the open change set. Core asks for it with * `input.reason: 'stale'` when a direct commit overlaps a proposal. * - `schedule`: set (`input.publishAt`) or clear (`null`) when the open change * set of a published document goes live. * - `publish` / `unpublish`: take the live revision up or down (the - * scheduler). A change set's scheduled publish arrives as `publish` with - * `input.changeSet` set to its id. + * scheduler), or apply an approved change set. A change set's scheduled + * publish arrives as `publish` with `input.changeSet` set to its id. * - `import`: restore `patch` from an export (actor `import`). */ export type BuiltInActionType = @@ -391,11 +393,14 @@ function scheduledActions( switch (action.type) { case 'publish': { const cs = doc.changeSet - if (cs && action.input?.changeSet === cs.id) { + const approved = changeSetState(doc) === 'approved' + if (cs && (approved || action.input?.changeSet === cs.id)) { return { effects: [ ...commitChange(doc.live, cs.type, cs.after, true), - ...(cs.source === 'draft' ? [] : [emit('review.approved')]), + ...(cs.source === 'draft' || approved + ? [] + : [emit('review.approved')]), ], } } @@ -450,8 +455,24 @@ const ACTIONS: Record = { import: { type: 'import', label: 'Import' }, } -/** Change-set states of the built-in strategies. */ -export type ReviewState = 'draft' | 'pending_review' +const PUBLISH_APPROVED: ActionDescriptor = { + type: 'publish', + label: 'Publish', + tone: 'primary', +} + +const DELETE_APPROVED: ActionDescriptor = { + type: 'publish', + label: 'Delete', + tone: 'danger', +} + +/** + * Change-set states of the built-in strategies: a publisher's private + * `draft`, a proposal `pending_review`, and a proposal a reviewer `approved` + * that waits for a publisher (live content is untouched until then). + */ +export type ReviewState = 'draft' | 'pending_review' | 'approved' function changeSetState(doc: DocView): ReviewState | undefined { const cs = doc.changeSet @@ -469,18 +490,36 @@ function builtInLabel( case 'draft': return 'Draft' case 'pending_review': - return 'Pending review' + return 'Pending Review' + case 'approved': + return 'Approved' case undefined: return liveLabel(doc.live) } } -const BUILT_IN_GRAPH: StateGraph = { +const DIRECT_GRAPH: StateGraph = { nodes: [ { id: 'unpublished', label: 'Unpublished' }, { id: 'published', label: 'Published' }, { id: 'draft', label: 'Draft' }, - { id: 'pending_review', label: 'Pending review' }, + ], + edges: [ + { from: 'published', to: 'draft', action: 'draft' }, + { from: 'draft', to: 'published', action: 'edit' }, + { from: 'draft', to: 'published', action: 'discard' }, + { from: 'unpublished', to: 'published', action: 'publish' }, + { from: 'published', to: 'unpublished', action: 'unpublish' }, + ], +} + +const REVIEW_GRAPH: StateGraph = { + nodes: [ + { id: 'unpublished', label: 'Unpublished' }, + { id: 'published', label: 'Published' }, + { id: 'draft', label: 'Draft' }, + { id: 'pending_review', label: 'Pending Review' }, + { id: 'approved', label: 'Approved' }, ], edges: [ { from: 'unpublished', to: 'pending_review', action: 'submit' }, @@ -488,8 +527,12 @@ const BUILT_IN_GRAPH: StateGraph = { { from: 'published', to: 'draft', action: 'draft' }, { from: 'draft', to: 'published', action: 'edit' }, { from: 'draft', to: 'published', action: 'discard' }, - { from: 'pending_review', to: 'published', action: 'approve' }, + { from: 'pending_review', to: 'approved', action: 'approve' }, + { from: 'pending_review', to: 'published', action: 'approve (publisher)' }, { from: 'pending_review', to: 'unpublished', action: 'reject' }, + { from: 'approved', to: 'published', action: 'publish' }, + { from: 'approved', to: 'pending_review', action: 'submit' }, + { from: 'approved', to: 'unpublished', action: 'reject' }, { from: 'unpublished', to: 'published', action: 'publish' }, { from: 'published', to: 'unpublished', action: 'unpublish' }, ], @@ -531,11 +574,14 @@ async function autoApproves( } /** - * The default strategy: publishers save directly, everyone else proposes - * changes that wait for a reviewer's approval, and publishers can keep a - * private draft of a published document. + * The default strategy: Draft → Pending Review → Approved → Published. + * Publishers save directly, everyone else proposes changes that wait for + * review, and publishers can keep a private draft of a published document. * - * `approve` commits and publishes (there is no separate "approved" state). + * A reviewer who can't publish (`review.decide` without `content.publish`) + * approves a proposal into `approved`; the live document is untouched until + * a publisher's `publish` (or a scheduled publish) applies it. A reviewer who + * can publish approves and publishes in one decision. */ export function reviewStrategy( options: ReviewStrategyOptions = {}, @@ -551,6 +597,13 @@ export function reviewStrategy( version: 1, ...(grants ? { grants } : {}), async decide(ctx, doc, action) { + if ( + action.type === 'publish' && + changeSetState(doc) === 'approved' && + doc.changeSet?.type === 'delete' && + !can(ctx, 'content.delete') + ) + return { reject: 'Applying an approved deletion needs content.delete.' } switch (action.type) { case 'edit': case 'import': @@ -589,6 +642,16 @@ export function reviewStrategy( case 'approve': { const cs = doc.changeSet if (!cs) return { reject: 'There is no change to approve.' } + const approved = changeSetState(doc) === 'approved' + if (!can(ctx, 'content.publish')) { + if (!can(ctx, 'review.decide')) + return { reject: 'Approving a change needs review.decide.' } + if (approved) + return { + reject: 'This change is approved and waits for a publisher.', + } + return { state: 'approved', effects: [emit('review.approved')] } + } return { effects: [ ...commitChange( @@ -597,7 +660,7 @@ export function reviewStrategy( cs.after, approvedPublished(action, cs.after), ), - emit('review.approved'), + ...(approved ? [] : [emit('review.approved')]), ], } } @@ -618,8 +681,15 @@ export function reviewStrategy( const out: Array = [] const state = changeSetState(doc) const agent = actorOf(ctx).type === 'agent' - if (state === 'pending_review' && can(ctx, 'review.decide') && !agent) + const decides = can(ctx, 'review.decide') && !agent + if (state === 'pending_review' && decides) out.push(ACTIONS.approve, ACTIONS.reject) + if (state === 'approved') { + const deletes = doc.changeSet?.type === 'delete' + if (can(ctx, deletes ? 'content.delete' : 'content.publish') && !agent) + out.push(deletes ? DELETE_APPROVED : PUBLISH_APPROVED) + if (decides) out.push(ACTIONS.reject) + } if (can(ctx, 'content.publish') && !agent) { out.push(ACTIONS.edit) if (doc.live?.published) out.push(ACTIONS.draft) @@ -631,7 +701,7 @@ export function reviewStrategy( return out }, label: builtInLabel, - describe: () => BUILT_IN_GRAPH, + describe: () => REVIEW_GRAPH, } } @@ -702,6 +772,6 @@ export function directStrategy( return out }, label: builtInLabel, - describe: () => BUILT_IN_GRAPH, + describe: () => DIRECT_GRAPH, } } diff --git a/packages/core/tests/document-state-strategy.sketch.test.ts b/packages/core/tests/document-state-strategy.sketch.test.ts index a14a1464..193d6187 100644 --- a/packages/core/tests/document-state-strategy.sketch.test.ts +++ b/packages/core/tests/document-state-strategy.sketch.test.ts @@ -112,7 +112,7 @@ describe('legal-review@1 XState sketch against the draft strategy interface', () review: { legal: 'pending', editorial: 'pending' }, }) expect(legalReview.label(state, view(state))).toBe( - 'Pending review (legal: pending, editorial: pending)', + 'Pending Review (legal: pending, editorial: pending)', ) }) diff --git a/packages/core/tests/document-state.test.ts b/packages/core/tests/document-state.test.ts index c307208f..a16852f6 100644 --- a/packages/core/tests/document-state.test.ts +++ b/packages/core/tests/document-state.test.ts @@ -251,7 +251,7 @@ describe('review strategy', () => { expect( (await availableDocumentActions(ctx, 'post', 'p1')).map((a) => a.type), ).toEqual(['approve', 'reject', 'edit', 'draft', 'schedule']) - expect(await documentStateLabel('post', 'p1')).toBe('Pending review') + expect(await documentStateLabel('post', 'p1')).toBe('Pending Review') expect( await availableDocumentActions(publicContext(), 'post', 'p1'), ).toEqual([]) @@ -282,6 +282,181 @@ describe('review strategy', () => { 'review.approved by eve', ]) }) + + it("a reviewer who can't publish approves into Approved; a publisher's publish applies it", async () => { + await setup({ + extra: { roles: { reviewer: ['content.read', 'review.decide'] } }, + }) + await commitDocument('post', 'p1', { title: 'Live', published: true }) + await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'update', + doc: { title: 'Proposal', published: true }, + actor: 'agent', + }) + await drain() + const reviewer = accessContext({ + session: normalizeSession({ + isAuthenticated: true, + isAdmin: false, + role: 'reviewer', + user: { id: 'rita' }, + }), + mode: 'edit', + }) + const publisher = accessContext({ session: editor, mode: 'edit' }) + const offered = async (ctx: typeof reviewer) => + (await availableDocumentActions(ctx, 'post', 'p1')).map((a) => a.type) + expect(await offered(reviewer)).toEqual(['approve', 'reject']) + + const approval = await actOnDocument(reviewer, { + collection: 'post', + id: 'p1', + action: { type: 'approve' }, + }) + expect(approval.committed).toBeNull() + expect(await documentStateLabel('post', 'p1')).toBe('Approved') + expect((await readDocument('post', 'p1'))?.title).toBe('Live') + expect((await listAudit())[0]).toMatchObject({ + action: 'approve', + decision: 'transitioned', + from: 'pending_review', + to: 'approved', + }) + expect((await drain()).map((e) => `${e.type} by ${e.actor}`)).toEqual([ + 'review.approved by rita', + ]) + expect(await offered(reviewer)).toEqual(['reject']) + await expect( + actOnDocument(reviewer, { + collection: 'post', + id: 'p1', + action: { type: 'approve' }, + }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }) + expect(await offered(publisher)).toEqual([ + 'publish', + 'reject', + 'edit', + 'draft', + 'schedule', + ]) + + const published = await actOnDocument(publisher, { + collection: 'post', + id: 'p1', + action: { type: 'publish' }, + }) + expect(published.committed).toMatchObject({ title: 'Proposal' }) + expect(await listPending()).toEqual([]) + expect(await documentStateLabel('post', 'p1')).toBe('Published') + expect((await listAudit())[0]).toMatchObject({ + action: 'publish', + from: 'approved', + }) + expect(await drain()).toEqual([]) + }) + + it('a new submission sends an approved change back to Pending Review', async () => { + await setup({ + extra: { roles: { reviewer: ['content.read', 'review.decide'] } }, + }) + const submit = (title: string) => + stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title, published: true }, + actor: 'agent', + }) + await submit('First') + await actOnDocument( + accessContext({ + session: normalizeSession({ + isAuthenticated: true, + isAdmin: false, + role: 'reviewer', + user: { id: 'rita' }, + }), + mode: 'edit', + }), + { collection: 'post', id: 'p1', action: { type: 'approve' } }, + ) + expect(await documentStateLabel('post', 'p1')).toBe('Approved') + await submit('Second') + expect(await documentStateLabel('post', 'p1')).toBe('Pending Review') + expect(await readDocument('post', 'p1')).toBeNull() + }) + + it('an approved deletion is applied only by someone who may delete', async () => { + await setup({ + extra: { + roles: { + reviewer: ['content.read', 'review.decide'], + publisher: ['content.read', 'content.write', 'content.publish'], + }, + }, + }) + await commitDocument('post', 'p1', { title: 'Live', published: true }) + await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'delete', + doc: {}, + actor: 'agent', + }) + const as = (role: string) => + accessContext({ + session: normalizeSession({ + isAuthenticated: true, + isAdmin: false, + role, + user: { id: role }, + }), + mode: 'edit', + }) + const act = (role: string, type: string) => + actOnDocument(as(role), { + collection: 'post', + id: 'p1', + action: { type }, + }) + await act('reviewer', 'approve') + expect( + (await availableDocumentActions(as('publisher'), 'post', 'p1')).find( + (a) => a.type === 'publish', + ), + ).toBeUndefined() + await expect(act('publisher', 'publish')).rejects.toMatchObject({ + code: 'FORBIDDEN', + }) + expect( + (await availableDocumentActions(as('editor'), 'post', 'p1')).find( + (a) => a.type === 'publish', + ), + ).toMatchObject({ label: 'Delete', tone: 'danger' }) + await act('editor', 'publish') + expect(await readDocument('post', 'p1')).toBeNull() + }) + + it('a publisher who approves publishes in the same decision', async () => { + await setup() + await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Proposal', published: true }, + actor: 'agent', + }) + await actOnDocument(accessContext({ session: editor, mode: 'edit' }), { + collection: 'post', + id: 'p1', + action: { type: 'approve' }, + }) + expect(await documentStateLabel('post', 'p1')).toBe('Published') + expect((await listAudit())[0]).toMatchObject({ decision: 'approved' }) + }) }) describe('core rules', () => { diff --git a/packages/core/tests/document-state/legal-review.xstate.ts b/packages/core/tests/document-state/legal-review.xstate.ts index 005c1f5c..07e3e85a 100644 --- a/packages/core/tests/document-state/legal-review.xstate.ts +++ b/packages/core/tests/document-state/legal-review.xstate.ts @@ -378,7 +378,7 @@ export function defineLegalReview( const live = doc.live?.published ? 'Published' : 'Unpublished' if (!state) return live const regions = regionLabel(state.value) - if (regions) return `Pending review (${regions})` + if (regions) return `Pending Review (${regions})` switch (state.value) { case 'changesRequested': return 'Changes requested' diff --git a/packages/ui-react/src/lib/i18n.ts b/packages/ui-react/src/lib/i18n.ts index 2e34bb19..f093df1e 100644 --- a/packages/ui-react/src/lib/i18n.ts +++ b/packages/ui-react/src/lib/i18n.ts @@ -350,6 +350,7 @@ export const defaultAdminMessages = { 'review.conflictHelp': 'Approving now would overwrite those newer changes. Reject the proposal, or approve it anyway.', 'review.approveAnyway': 'Approve anyway', + 'review.approve': 'Approve', 'review.approvePublish': 'Approve & publish', 'review.approveDelete': 'Approve & delete', 'review.approveDraft': 'Approve as draft', diff --git a/packages/ui-react/src/routes/review.tsx b/packages/ui-react/src/routes/review.tsx index bc44d4be..6f977904 100644 --- a/packages/ui-react/src/routes/review.tsx +++ b/packages/ui-react/src/routes/review.tsx @@ -76,6 +76,7 @@ function ReviewPage() { const { pending, audit } = Route.useLoaderData() const { ai } = useCmsAuth() const canDecide = useCan('review.decide') + const canPublish = useCan('content.publish') const router = useRouter() const [busy, setBusy] = useState(null) const [errors, setErrors] = useState< @@ -278,7 +279,16 @@ function ReviewPage() { )}
- {offered.has('approve') && ( + {offered.has('approve') && !canPublish && ( + + )} + {offered.has('approve') && canPublish && ( )} - {offered.has('approve') && isDraftProposal && ( - - )} + {offered.has('approve') && + canPublish && + isDraftProposal && ( + + )} {offered.has('reject') && (