diff --git a/.changeset/document-state-change-sets.md b/.changeset/document-state-change-sets.md new file mode 100644 index 00000000..39cce00a --- /dev/null +++ b/.changeset/document-state-change-sets.md @@ -0,0 +1,18 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-client': minor +'@tanstack/cms-store-postgres': minor +'@tanstack/cms-ui-react': patch +--- + +Change sets carry the document state strategy's state. A decision's `state` is stored on the document's one coalesced change set with the strategy's `id@version`, upgraded by the strategy's `migrate` when its version moves on; a change set no version can read is stranded and core refuses every decision on it except discarding it (new server export `listStrandedChangeSets`). Audit entries gain `changeSet`, `from` / `to` (the state before and after), `effects` and `reason`, and a decision that only changes the state is audited as the new `transitioned` decision. The review screen's audit trail labels it and the new `staged` decision. Storage migrations add the columns (SQLite/libsql v16, Postgres v8); `StorageOps` gains an optional `findDuePendingPublish` for the scheduler sweep. + +Breaking changes (phase 4 bug fixes and rulings): + +- Stage-only decisions are audited. An agent proposal, an author's review request or a publisher's draft now writes an audit row (`transitioned` with the built-ins, which store `pending_review` or `draft`; `staged` for a strategy that stores no state). Code that counts audit rows per decision should filter by `decision` or `action`. + +- One event vocabulary: the in-process bus (`onCmsEvent`, plugin `onEvent`), webhooks and the `/api/cms/v1/events` stream use the durable names `document.created`, `document.updated`, `document.published`, `document.unpublished` and `document.deleted` (new `CmsContentEvent` type; `CmsEvent.event`, webhook payloads, `x-cms-event` and the client's `CmsLiveEvent` carry them). `document.published` fires only when a document goes live; a save of a live document is `document.updated` and no longer fires `publish`. The short names `publish`, `unpublish`, `delete`, `change` and `update` stay as deprecated aliases (`CmsEventAlias`) until phase 6: webhook `events` lists and the new `onCmsEvent(names, listener)` filter still match them. Default webhooks keep firing for publishes, unpublishes, deletes and updates of a live document. Code that compares `event.event` with a short name, and webhook receivers that read the event name, must switch to the `document.*` names. +- While a document's change set is open, a write from another source (an agent proposal, an author's review request, a publisher's draft) fails with `CONFLICT` and `details: { pendingId, source }` instead of taking it over. Same-source re-saves merge onto it, so an author's second save keeps their earlier staged edits. +- A direct commit that changes other fields rebases an open proposal onto the new revision (its `version` goes up). One that changes a field the proposal changed, or any commit under a staged delete, invalidates it: the change set is deleted, audited as `discarded` with `reason: 'stale'`, and `review.discarded` is emitted with the proposer as `author`. Approving it is then `NOT_FOUND` instead of `CONFLICT`. +- `scheduleDocument` with a future `publishAt` on a published document schedules its open change set and keeps the live version up, instead of unpublishing it until then; the scheduler sweep commits and publishes the change set as `scheduler`. With nothing pending it fails with `BAD_REQUEST`. Strategies get a `schedule` action, and the agent floor also covers scheduling a publish. diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index 3aaab0e7..a0854723 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -74,7 +74,9 @@ If validation fails, `stageWrite` throws a `CmsError` with code `VALIDATION_FAIL ### Coalescing and Refinement -An agent often makes several edits to the same document before anyone reviews them. `stageWrite` keeps **one pending change per document**: later writes replace the proposed `after` state but keep the original `before` snapshot, so the reviewer sees a single net diff. +An agent often makes several edits to the same document before anyone reviews them. `stageWrite` keeps **one pending change per document**: later writes replace the proposed `after` state but keep the original `before` snapshot, so the reviewer sees a single net diff. An author's re-save merges onto their open proposal the same way. + +The pending change belongs to the door that opened it: an agent proposal (`agent`), an author's save (`review`) or a publisher's draft (`draft`). While it is open, a write through another door fails with `CONFLICT` and `details: { pendingId, source }` naming it. Approve, reject or discard it first. Agents can read their own staged work. `read_document` and `update_document` fall back to the pending version when a document hasn't been committed yet, and `list_documents` includes pending creates. An agent can create a document, read it back, and refine it before anyone approves. @@ -91,7 +93,12 @@ 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 })`. -A pending change remembers the revision of the live document it was proposed against. If the live document changed after that (someone saved it, or it was created or deleted), approving fails with `CONFLICT` and `details: { baseRevision, actualRevision }` rather than silently overwriting the newer version. The review page explains the conflict and offers **Approve anyway**, which passes `force: true`. +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. +- If they changed a field the proposal also changed (or the proposal deletes the document), the proposal is invalidated. It leaves the queue with an audit entry `discarded`, reason `stale`, and a `review.discarded` event (payload `{ reason: 'stale' }`, the proposer as `author`) so the proposer can be told. + +If the live revision still moved on underneath a proposal (for example, the database was written directly), approving fails with `CONFLICT` and `details: { baseRevision, actualRevision }` rather than silently overwriting the newer version. The review page explains the conflict and offers **Approve anyway**, which passes `force: true`. ## Choosing the Flow: Document State Strategies @@ -110,7 +117,9 @@ defineCms({ }) ``` -Core refuses (with `FORBIDDEN`, audited as `refused`) a decision that drops an incoming change, emits a `document.*` event, changes a published document's content without `publish`, or lets an agent publish when the strategy doesn't grant `publish` to agents. With `review.autoApprove` set, the review strategy grants it, because an auto-approved agent write goes live. See [Document state strategy](../architecture/terminology#document-state-strategy). +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. ## Optimistic Concurrency @@ -145,6 +154,8 @@ Every commit stores a full snapshot of the document as a numbered revision: dire Documents carry `publishAt` and `unpublishAt` system fields. When a time passes, the scheduler publishes (or unpublishes) the document, records a revision, and logs an audit entry with actor `scheduler`. The sweep runs automatically as the store is used (at most once per second); on idle sites, call `runScheduledPublishing()` from `@tanstack/cms-core/server` in a cron job for exact timing. An agent's `schedule_document` is staged for review. +Scheduling a future publish of a **published** document schedules its open draft or proposal instead: the live version stays up, the pending change carries `publishAt`, and at that time the scheduler commits and publishes it (actor `scheduler`, the proposer as `author`). A published document with nothing pending has nothing to schedule, so `scheduleDocument` fails with `BAD_REQUEST`; save a draft first. + ## Deleting Referenced Documents Deleting a document that other documents reference through a `relation` field fails with `CONFLICT` and lists the references, unless the delete passes `force: true`. Relations inside `group`, `array`, and `blocks` fields count too; their `field` is the dotted path, such as `body.2.author`. The editor shows inbound references before you delete. @@ -170,6 +181,12 @@ interface Pending { source: 'agent' | 'draft' | 'review' /** The document's `_revision` when the change was staged. */ baseRevision?: number + /** Bumped by every write to the change set. */ + version?: number + /** When the scheduler publishes this change set (a published document's scheduled update). */ + publishAt?: string + /** The strategy state, with the `id@version` that wrote it. */ + workflow?: { strategy: string; state: unknown } } interface AuditEntry { @@ -178,7 +195,19 @@ interface AuditEntry { docId: string type: WriteType actor: string - decision: 'approved' | 'rejected' + action?: string // the strategy action: 'edit', 'approve', 'discard', … + decision: + | 'approved' + | 'rejected' + | 'discarded' + | 'refused' + | 'transitioned' + | '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) + effects?: Array // the effects the decision ran + reason?: string // a refusal's reason, or 'stale' at: string } ``` diff --git a/docs/api/cms-client.md b/docs/api/cms-client.md index 6942eacb..31866c97 100644 --- a/docs/api/cms-client.md +++ b/docs/api/cms-client.md @@ -242,7 +242,12 @@ function subscribeCmsCollectionEvents( ): () => void interface CmsLiveEvent { - event: 'publish' | 'unpublish' | 'delete' | 'change' + event: + | 'document.created' + | 'document.updated' + | 'document.published' + | 'document.unpublished' + | 'document.deleted' collection: string id: string at: string diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index eec8e419..929c37e9 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -509,6 +509,14 @@ await actOnDocument(systemContext('nightly legal sign-off'), { }) ``` +### `listStrandedChangeSets()` + +```ts +function listStrandedChangeSets(): Promise> +``` + +Change sets whose stored strategy state their collection's strategy can't read: written by another strategy, or by an older version without a `migrate` that upgrades it. Core refuses every decision on them except discarding them. + ### `listPending(options?)`, `getPending(id)` ```ts @@ -594,7 +602,7 @@ Restoring commits the old content as a new revision (or stages it). function listAudit(options?: { limit?: number; offset?: number }): Promise> // default limit 50 ``` -Approve/reject decisions and direct deletes, newest first. +Every decision on a document, newest first: stages, commits, approvals, rejections, discards (with `reason: 'stale'` for a proposal a commit invalidated), refusals, `transitioned` state changes, and imports. A stage is `transitioned` when the strategy stores a state for the change set (the built-ins do) and `staged` otherwise. Document entries carry the `action`, the `changeSet` acted on, its strategy state before and after (`from` / `to`), and the `effects` that ran. ### Scheduling @@ -615,27 +623,39 @@ interface ScheduledPublishResult { } ``` -`scheduleDocument` sets `publishAt` (a future time also sets `published: false`). `runScheduledPublishing` publishes every document whose `publishAt` has passed and unpublishes every live document whose `unpublishAt` has passed, recording revisions and emitting `publish` / `unpublish`. It also runs automatically, throttled to once per second, as the store is used; call it from a cron job for exact timing on idle sites. +`scheduleDocument` sets `publishAt` on an unpublished document (a future time also sets `published: false`). On a published document it schedules the open draft or proposal instead and returns that `Pending`: the live version stays up until then. A published document with nothing pending fails with `BAD_REQUEST`. `runScheduledPublishing` publishes every document whose `publishAt` has passed, publishes every change set whose `publishAt` has passed, and unpublishes every live document whose `unpublishAt` has passed, recording revisions and emitting `document.updated` with `document.published` / `document.unpublished`. It also runs automatically, throttled to once per second, as the store is used; call it from a cron job for exact timing on idle sites. ### `onCmsEvent(listener)` ```ts function onCmsEvent(listener: (event: CmsEvent) => void): () => void // returns unsubscribe +function onCmsEvent( + events: CmsEventName | ReadonlyArray, + listener: (event: CmsEvent) => void, +): () => void // only the named events function cmsEventDocument(event: CmsEvent): Doc | undefined // trusted server-only authorization snapshot -type CmsEventName = 'publish' | 'unpublish' | 'delete' | 'change' +type CmsContentEvent = + | 'document.created' + | 'document.updated' + | 'document.published' + | 'document.unpublished' + | 'document.deleted' +type CmsEventName = CmsContentEvent | CmsEventAlias // deprecated: 'publish' | 'unpublish' | 'delete' | 'change' | 'update' interface CmsEvent { - event: CmsEventName + event: CmsContentEvent collection: string id: string actor: string at: string // ISO timestamp - doc?: Doc // the document after the change; omitted for 'delete' + doc?: Doc // the document after the change; omitted for 'document.deleted' } ``` -The in-process content event bus, emitted after commits in this process. The same events drive webhooks (`WebhookPayload` is a `CmsEvent`) and the `/api/cms/v1/events` stream. Use it for cache invalidation in long-running servers. Listener errors are swallowed so they never break a write. +The in-process content event bus, emitted after commits in this process, with the same names and order as the durable [events](../architecture/events-and-hooks): every commit emits `document.created` or `document.updated`, then `document.published` when the document went live or `document.unpublished` when it came down; a delete emits `document.deleted`. The same events drive webhooks (`WebhookPayload` is a `CmsEvent`) and the `/api/cms/v1/events` stream. Use it for cache invalidation in long-running servers. Listener errors are swallowed so they never break a write. + +The short names are deprecated aliases until phase 6: subscribing by one still works (`publish` = `document.published`, `unpublish` = `document.unpublished`, `delete` = `document.deleted`, `change` = `document.created` or `document.updated`, `update` = `document.updated` of a document that stayed live), but the delivered event carries the `document.*` name. Transport implementations can use `cmsEventDocument(event)` to authorize a document event against its complete snapshot. For deletions that snapshot is @@ -646,9 +666,10 @@ document data to a client. ```ts validate=type import { onCmsEvent } from '@tanstack/cms-core/server' -const stop = onCmsEvent(({ event, collection, id }) => { - if (event === 'publish' || event === 'unpublish') console.log(`purge /${collection}/${id}`) -}) +const stop = onCmsEvent( + ['document.published', 'document.updated', 'document.unpublished', 'document.deleted'], + ({ collection, id }) => console.log(`purge /${collection}/${id}`), +) ``` For **durable, retried** delivery to app-defined handlers (as opposed to this best-effort in-process bus), use the async event system below. diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 3f13b213..0195a6f0 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -77,7 +77,7 @@ export const cms = defineCms({ webhooks: [ { url: 'https://api.example.com/hooks/cms', - events: ['publish', 'unpublish', 'delete'], + events: ['document.published', 'document.updated', 'document.unpublished', 'document.deleted'], collections: ['post'], secret: () => process.env.CMS_WEBHOOK_SECRET, }, @@ -379,18 +379,26 @@ interface RateLimitStore { ### `CmsWebhook` and `CmsWebhookEvent` ```ts -type CmsWebhookEvent = 'publish' | 'unpublish' | 'delete' | 'change' +type CmsContentEvent = + | 'document.created' + | 'document.updated' + | 'document.published' + | 'document.unpublished' + | 'document.deleted' +/** @deprecated aliases, removed in phase 6 */ +type CmsEventAlias = 'publish' | 'unpublish' | 'delete' | 'change' | 'update' +type CmsWebhookEvent = CmsContentEvent | CmsEventAlias interface CmsWebhook { url: string | (() => string | undefined) - events?: Array // default ['publish', 'unpublish', 'delete'] + events?: Array // default: what a public site shows changing (below) collections?: Array // default: all secret?: string | (() => string | undefined) // HMAC-SHA256 signing secret headers?: Record } ``` -`publish` fires whenever a published version is committed (including edits to live content), `unpublish` when a live document is taken down, `delete` on deletion, and `change` on every commit. Deliveries are JSON `POST`s signed with `x-cms-signature`; they are durable (enqueued in the commit transaction on the transactional outbox and delivered by the dispatcher with retries + dead-lettering). See [Webhooks](./routes-and-endpoints#webhooks) for the payload and verification, and [`/server`](./cms-core-server#webhooks) for delivery semantics. +The names match the durable [events](../architecture/events-and-hooks): `document.created` or `document.updated` fires on every commit, `document.published` when a document goes live, `document.unpublished` when a live document is taken down, and `document.deleted` on deletion. Without `events`, a hook gets `document.published`, `document.unpublished`, `document.deleted`, and `document.updated` only while the document stays live. The short names (`publish`, `unpublish`, `delete`, `change` for created or updated, `update` for an update that stays live) are deprecated aliases: a list that uses them still matches, and deliveries carry the `document.*` name. Deliveries are JSON `POST`s signed with `x-cms-signature`; they are durable (enqueued in the commit transaction on the transactional outbox and delivered by the dispatcher with retries + dead-lettering). See [Webhooks](./routes-and-endpoints#webhooks) for the payload and verification, and [`/server`](./cms-core-server#webhooks) for delivery semantics. ### `CmsAdminConfig` @@ -494,7 +502,7 @@ export const analytics = definePlugin({ }), ], onEvent: (e) => { - if (e.event === 'publish') console.log(`published ${e.collection}/${e.id}`) + if (e.event === 'document.published') console.log(`published ${e.collection}/${e.id}`) }, }, }) diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index df7c0005..18784f11 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -140,7 +140,7 @@ Change them with `defineCms({ security: { rateLimits } })`; plug in a shared cou ### Event stream -`GET /api/cms/v1/events[?collection=post]` is a Server-Sent Events stream of `publish`, `unpublish`, `delete`, and `change` events (`{ event, collection, id, at }`), used by `createCmsCollectionOptions({ live: true })`. +`GET /api/cms/v1/events[?collection=post]` is a Server-Sent Events stream of `document.created`, `document.updated`, `document.published`, `document.unpublished`, and `document.deleted` events (`{ event, collection, id, at }`), used by `createCmsCollectionOptions({ live: true })`. - **Access**: it requires `content.read`, so anonymous callers get `401`. A `collection` the session can't read gets `403`, and an unknown one `404`. - **Filtering**: events from collections the session can't read, and documents a `read` rule hides, are dropped. An update also invalidates a previously readable record that becomes hidden, using the same metadata-only frame. @@ -339,7 +339,7 @@ All URLs use `seo.siteUrl`, or the request origin when it isn't set. ## Webhooks -`defineCms({ webhooks })` POSTs a JSON payload to each hook after commits (`publish`, `unpublish`, `delete`, `change`), filtered by the hook's `events` and `collections`. +`defineCms({ webhooks })` POSTs a JSON payload to each hook after commits (`document.created`, `document.updated`, `document.published`, `document.unpublished`, `document.deleted`), filtered by the hook's `events` and `collections`. The short names (`publish`, `change`, …) still match as deprecated aliases. ```json { @@ -352,13 +352,13 @@ All URLs use `seo.siteUrl`, or the request origin when it isn't set. } ``` -`doc` is omitted for `delete`. +`doc` is omitted for `document.deleted`. | Header | Value | | --- | --- | | `content-type` | `application/json` | | `user-agent` | `tanstack-cms-webhook` | -| `x-cms-event` | The event name. | +| `x-cms-event` | The event name (`document.published`, …). | | `x-cms-delivery` | A UUID, the same across retries of one delivery. | | `x-cms-timestamp` | Unix time in seconds. | | `x-cms-signature` | `sha256=`: HMAC-SHA256 of `.` with the hook's `secret` (only when a secret is set). | diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index 26ab4680..75d353c8 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -56,13 +56,13 @@ A strategy is a small object. Given the [access context](#access-context), the d Planned built-ins: **review** (Draft → Pending Review → Approved → Published) and **direct** (an edit publishes immediately, for personal apps). Complex flows, such as legal and editorial approval running in parallel, can be written with XState. XState is a documented option, not the engine. -**Today:** the interface, the effects and core's rules exist, with two built-ins that reproduce the one flow from before: `reviewStrategy()` (the default; writes either commit for publishers or stage into the review queue, approving a staged change commits it, and `review.autoApprove` loosens it) and `directStrategy()` (agent and author writes commit at once). Set one with `defineCms({ documentState })` or a collection's `documentState`. Every write door goes through it: saves, staging, approve, reject, drafts, the scheduler and `tanstack-cms import`. **Planned:** the strategy's state stored with the change set, available actions and labels in the admin UI, and the new default-flow naming. +**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. ## Change set **Implemented, extended later.** The pending edits to one document that aren't live yet. There is exactly one change set per document: new edits coalesce into it. While a published doc has a change set, readers keep seeing the live version. -**Today:** the `pending` row (`UNIQUE (collection, doc_id)`), with a source of `agent`, `draft` or `review`. **Planned:** the change set also carries the strategy's state and `strategy@version`. Parallel approvals are one compound state on that one change set, not several pending rows. +**Today:** the `pending` row (`UNIQUE (collection, doc_id)`), with a source of `agent`, `draft` or `review`, the strategy's state with its `strategy@version`, and an optional scheduled `publishAt`. Same-source edits coalesce into it; a write from another source is refused with `CONFLICT` while it's open. A commit that changes other fields rebases it onto the new revision, and one that changes the same field invalidates it (audited as a discard with reason `stale`). Parallel approvals are one compound state on that one change set, not several pending rows. ## Effect @@ -74,7 +74,7 @@ Planned built-ins: **review** (Draft → Pending Review → Approved → Publish | `commit()` | Apply the change set as a new revision | | `publish(revision?)` | Make a revision live (default: the one just committed) | | `unpublish()` | Take the document down | -| `schedule({ publishAt, unpublishAt })` | Do it later; the scheduler acts as actor `scheduler` | +| `schedule({ publishAt, unpublishAt })` | Do it later; the scheduler acts as actor `scheduler`. On a live document with a change set, `publishAt` schedules the change set and the live version stays up | | `discard()` | Drop the change set | | `emit(event, payload?)` | Send a strategy-named event through the outbox | @@ -82,10 +82,10 @@ Rules core enforces on every decision, whatever the strategy: - A decision's effects and new state apply together in one transaction, or not at all. - A live document's visible content changes only through `publish`. A `commit` on a live doc without `publish` is rejected. -- Audit isn't an effect. Core records the actor, action, from/to state and effects for every decision, including refused ones. (Today: the actor, the action and the outcome; from/to state and effects are planned.) +- Audit isn't an effect. Core records the actor, action, from/to state and effects for every decision, including refused ones (with the reason). A stage is audited too: as `transitioned` when it stores strategy state, otherwise as `staged`. - A decision that receives an incoming change must stage or commit it. - Strategies can't emit `document.*` events; those are core's. -- Core emits `document.published` and `document.unpublished` from the `publish` and `unpublish` effects, so search, webhooks and connectors work with any strategy. +- Core emits `document.published` and `document.unpublished` from the `publish` and `unpublish` effects, so search, webhooks and connectors work with any strategy. The bus, webhooks and the event stream use the same `document.*` names: `document.published` only when a document goes live, and `document.updated` on every update commit, including a live document's content changing. - Agents can't cause a publish unless the strategy grants it to agents. ## Live vs working copy diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index c73fa044..55f445d8 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -355,6 +355,30 @@ export const renderers = defineRenderers({ The admin routes use the module named in `createRoutes(definition, { renderers })`. A bespoke admin passes the same object to `FieldInput`, `CollectionSection`, and `columnFields(collection, session, renderers)`. A custom field type is offered as a list column only when a cell is bound for it, as before. See [Custom inputs and cells](../schema/collections-and-fields#custom-inputs-and-cells). +### 24. Content events, pending changes and scheduling + +- **One event vocabulary.** The bus (`onCmsEvent`, plugin `onEvent`), webhooks and the event stream use the durable event names: `document.created` or `document.updated` on every commit, `document.published` only when a document goes from unpublished to published, `document.unpublished`, and `document.deleted`. Payloads, `x-cms-event` and the stream's `event` carry the new name. A save of a live document is `document.updated`; it no longer fires `publish`. + - The short names (`publish`, `unpublish`, `delete`, `change`, `update`) are deprecated aliases until phase 6. A webhook `events` list or an `onCmsEvent(names, listener)` filter that uses them still matches (`change` = created or updated, `update` = an update of a document that stays live). + - Default webhooks (no `events`) still fire for what a public site shows changing: publishes, unpublishes, deletes, and updates of a live document. + - Code that compares `event.event` with a short name, and webhook receivers that read `payload.event` or `x-cms-event`, must switch to the new names: + + ```ts + // before + onCmsEvent(({ event, collection, id }) => { + if (event === 'publish' || event === 'unpublish') purge(collection, id) + }) + // after + onCmsEvent( + ['document.published', 'document.updated', 'document.unpublished', 'document.deleted'], + ({ collection, id }) => purge(collection, id), + ) + ``` + +- **One source per pending change.** While an agent proposal, an author's save or a publisher's draft is open, a write through another of those doors fails with `CONFLICT` (`details: { pendingId, source }`) instead of taking it over. Resolve the open change first. +- **Commits update open proposals.** A commit that changes other fields moves an open proposal onto the new revision; one that changes the same field invalidates it (audited `discarded` with reason `stale`, and a `review.discarded` event). Approving such a proposal no longer returns `CONFLICT`. +- **Scheduling a published document** schedules its open draft or proposal and keeps the live version up, instead of unpublishing it until `publishAt`. With nothing pending it fails with `BAD_REQUEST`. +- **Storage.** Migrations add change-set workflow and schedule columns and audit transition columns (SQLite/libsql v16, Postgres v8); run `tanstack-cms migrate`. Custom `StorageAdapter`s should persist the new `PendingRecord` (`workflow`, `publishAt`) and `AuditRecord` (`changeSet`, `from`, `to`, `effects`, `reason`) fields and may implement `findDuePendingPublish`. + ## Versioning policy From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The diff --git a/packages/api/src/http.ts b/packages/api/src/http.ts index 0e845a3c..80d2eb5c 100644 --- a/packages/api/src/http.ts +++ b/packages/api/src/http.ts @@ -573,7 +573,7 @@ async function canSeeEvent( const previous = cmsEventPreviousDocument(payload) return ( readable(doc) || - (payload.event === 'change' && !!previous && readable(previous)) + (payload.event === 'document.updated' && !!previous && readable(previous)) ) } catch { return false @@ -582,7 +582,8 @@ async function canSeeEvent( /** * `GET /api/cms/v1/events` — Server-Sent Events stream of CMS content - * lifecycle changes (`publish`, `unpublish`, `delete`, `change`). + * lifecycle changes (`document.created`, `document.updated`, + * `document.published`, `document.unpublished`, `document.deleted`). * Supports `?collection=` filtering. Requires `content.read`; events * are limited to collections (and documents) the session may read, and open * streams are capped (`security.eventStreams`). diff --git a/packages/api/src/openapi.ts b/packages/api/src/openapi.ts index 2207ac73..a8d79804 100644 --- a/packages/api/src/openapi.ts +++ b/packages/api/src/openapi.ts @@ -354,7 +354,13 @@ function endpointPaths(): Record { properties: { event: { type: 'string', - enum: ['publish', 'unpublish', 'delete', 'change'], + enum: [ + 'document.created', + 'document.updated', + 'document.published', + 'document.unpublished', + 'document.deleted', + ], }, collection: { type: 'string' }, id: { type: 'string' }, diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 80f6243a..ce6f361d 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -412,8 +412,13 @@ async function saveAsHuman( existing ? 'update' : 'create', existing ?? doc, ) - const draft = existing ? await readDocumentWithPending(collection, id) : null - const base = draft?.pendingSource === 'draft' ? draft.doc : existing + const open = existing ? await readDocumentWithPending(collection, id) : null + // A re-save merges onto this door's own open change set; another door's is + // refused by the strategy executor until it's resolved. + const ownSource = canPublish(session, collection, existing ?? (doc as Doc)) + ? 'draft' + : 'review' + const base = open?.pendingSource === ownSource ? open.doc : existing const safe = protectWrite( collection, { ...base, ...doc } as Doc, diff --git a/packages/api/tests/characterization/save-paths.test.ts b/packages/api/tests/characterization/save-paths.test.ts index 78c94ba9..362a4e06 100644 --- a/packages/api/tests/characterization/save-paths.test.ts +++ b/packages/api/tests/characterization/save-paths.test.ts @@ -16,9 +16,10 @@ * suffixed `[known bug, fixed in phase 4 (#N)]`, pin behaviour that was ruled * a bug on 2026-11-05 (cms-refactor-plan.md § Phase 4). They stay green until * phase 4 fixes the bug and updates the row in the same diff; rows marked - * `fixed in phase 4a (#N)` pin the fix. N matches the decision list (#1–#10) - * in workflow-suite.ts; this table covers #4 (one pending change mixes - * sources), #5 (a direct commit leaves a stale proposal behind) and #6 + * `fixed in phase 4a (#N)` or `fixed in phase 4b (#N)` pin the fix. N + * matches the decision list (#1–#10) in workflow-suite.ts; this table covers + * #4 (one pending change mixes sources, fixed in phase 4b), #5 (a direct + * commit leaves a stale proposal behind, fixed in phase 4b) and #6 * (autoApprove saves report `staged: true`, fixed in phase 4a). */ import { afterEach, describe, expect, it } from 'vitest' @@ -49,8 +50,16 @@ async function call(name: string, input: unknown, role: string) { }), ) // 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 } + const body = (await res.json()) as { + result?: any + error?: { code: string; details?: unknown } + } + return { + status: res.status, + result: body.result, + code: body.error?.code, + details: body.error?.details, + } } /** A write op's result, checked against the published `writeOutput` schema. */ @@ -313,7 +322,7 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { expect((await readDocument('post', 'wip'))?.title).toBe('WIP') }) - it('a second author save coalesces into the same pendingId, rebuilt from the live doc [known bug, fixed in phase 4 (#4)]', async () => { + it('a second author save coalesces into the same pendingId, merged onto the open proposal', async () => { await seed() const first = await write( 'saveDoc', @@ -330,11 +339,13 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { 'author', ) expect(second.pendingId).toBe(first.pendingId) - // known bug, fixed in phase 4 (#4: pending mixes sources) — only drafts - // are used as the merge base, so a re-save drops the earlier staged edits. - expect(second.doc.cover).toBe((await readDocument('post', 'wip'))?.cover) - expect(second.doc.cover).not.toBe('/a.png') - expect((await listPending())[0]?.version).toBe(2) + // fixed in phase 4b (#4: pending mixes sources) — a same-source re-save + // merges onto the open proposal, keeping its earlier edits. + expect(second.doc).toMatchObject({ title: 'Two', cover: '/a.png' }) + expect((await listPending())[0]).toMatchObject({ + version: 2, + after: { title: 'Two', cover: '/a.png' }, + }) }) it('a stale expectedPendingVersion is a 409', async () => { @@ -381,7 +392,7 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { }) describe('mixed actors on one document', () => { - it('an editor save on a published doc absorbs a pending author proposal into the editor draft [known bug, fixed in phase 4 (#4)]', async () => { + it('an editor save on a published doc with an open author proposal is a 409 naming it; the proposal stays in review', async () => { await seed() const proposal = await write( 'saveDoc', @@ -392,24 +403,33 @@ describe('mixed actors on one document', () => { }, 'author', ) - const draft = await write( + const res = await call( 'saveDoc', { collection: 'post', id: 'live', doc: { title: 'Editor edit' } }, 'editor', ) - // known bug, fixed in phase 4 (#4: pending mixes sources) — the author's - // proposal leaves the review queue and its other edits are dropped. - expect(draft).toMatchObject({ draft: true, pendingId: proposal.pendingId }) - expect(draft.doc.cover).toBe((await readDocument('post', 'live'))?.cover) - expect(draft.doc.cover).not.toBe('/author.png') + // fixed in phase 4b (#4: pending mixes sources) — another source's open + // change set refuses the save until it's resolved. + expect(res).toMatchObject({ + status: 409, + code: 'CONFLICT', + details: { pendingId: proposal.pendingId, source: 'review' }, + }) expect(await listPending()).toEqual([ - expect.objectContaining({ source: 'draft', version: 2 }), + expect.objectContaining({ + id: proposal.pendingId, + source: 'review', + version: 1, + after: expect.objectContaining({ cover: '/author.png' }), + }), ]) const review = await call('reviewSnapshot', {}, 'editor') - expect(review.result.pending).toEqual([]) + expect(review.result.pending.map((p: { id: string }) => p.id)).toEqual([ + proposal.pendingId, + ]) }) - it('an editor commit on an unpublished doc leaves the author proposal pending, and approving it is then a 409 [known bug, fixed in phase 4 (#5)]', async () => { + it('an editor commit on an unpublished doc that changes the proposed field invalidates the author proposal; approving it is then a 404', async () => { await seed() const proposal = await write( 'saveDoc', @@ -421,17 +441,18 @@ describe('mixed actors on one document', () => { { collection: 'post', id: 'wip', doc: { title: 'Editor edit' } }, 'editor', ) - // known bug, fixed in phase 4 (#5: stale proposal after direct commit) — - // the editor's commit leaves the author's proposal stale. - expect(await listPending()).toEqual([ - expect.objectContaining({ id: proposal.pendingId, source: 'review' }), - ]) + // fixed in phase 4b (#5: stale proposal after direct commit) — both + // changed the title, so the commit invalidates the proposal. + expect(await listPending()).toEqual([]) + expect( + (await listAudit()).find((a) => a.decision === 'discarded'), + ).toMatchObject({ id: proposal.pendingId, reason: 'stale' }) const res = await call( 'approveChange', { id: proposal.pendingId }, 'editor', ) - expect(res.status).toBe(409) + expect(res.status).toBe(404) }) }) diff --git a/packages/api/tests/events.test.ts b/packages/api/tests/events.test.ts index 47e801e5..f7abb3d7 100644 --- a/packages/api/tests/events.test.ts +++ b/packages/api/tests/events.test.ts @@ -132,7 +132,7 @@ describe('GET /api/cms/v1/events', () => { await deleteDocument('post', 'mine') const text = await readUntil(stream, (body) => body.includes('"mine"')) expect(text).not.toContain('"hidden"') - expect(text).toContain('"event":"delete"') + expect(text).toContain('"event":"document.deleted"') }) it('requires content.read', async () => { setupCms({ collections }) diff --git a/packages/api/tests/health.test.ts b/packages/api/tests/health.test.ts index 21712f06..d777ae72 100644 --- a/packages/api/tests/health.test.ts +++ b/packages/api/tests/health.test.ts @@ -180,15 +180,17 @@ describe('logger', () => { logger: log, // Webhooks ride the durable outbox; drain it explicitly to deliver. events: { dispatch: 'manual' }, - webhooks: [{ url: 'https://hooks.test/cms', events: ['change'] }], + webhooks: [ + { url: 'https://hooks.test/cms', events: ['document.created'] }, + ], }) await commitDocument('post', 'a', { title: 'A' }) await runEventDispatch() expect(log.warn).toHaveBeenCalledWith( expect.stringMatching( - /webhook change → https:\/\/hooks.test\/cms failed/, + /webhook document.created → https:\/\/hooks.test\/cms failed/, ), - { event: 'change', collection: 'post', id: 'a' }, + { event: 'document.created', collection: 'post', id: 'a' }, ) }) }) diff --git a/packages/api/tests/helpers.ts b/packages/api/tests/helpers.ts index 2a4691dd..147fcfb5 100644 --- a/packages/api/tests/helpers.ts +++ b/packages/api/tests/helpers.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { defineCms } from '@tanstack/cms-core' -import { closeStore } from '@tanstack/cms-core/server' +import { closeStore, getStorage } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' const dirs: Array = [] @@ -60,3 +60,41 @@ export const PNG = new Uint8Array([ 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x08, 0x06, 0x00, 0x00, 0x00, ]) + +/** + * Write a new live revision straight to storage, so an open proposal is left + * stale. Commits through the engine rebase or invalidate it instead. + */ +export async function moveLiveUnder( + collection: string, + id: string, + patch: Record, +): Promise { + const storage = await getStorage() + await storage.transaction(async (tx) => { + const live = await tx.getDocument(collection, id) + if (!live) throw new Error(`${collection}/${id} is not live`) + const { doc, updatedAt, ...index } = live + await tx.putDocument( + { + collection, + id, + doc: { + ...doc, + ...patch, + _revision: (doc._revision as number) + 1, + } as typeof doc, + updatedAt, + }, + { + published: index.published, + locale: index.locale, + slug: index.slug, + title: index.title, + publishAt: index.publishAt, + unpublishAt: index.unpublishAt, + deletedAt: index.deletedAt, + }, + ) + }) +} diff --git a/packages/api/tests/readiness.test.ts b/packages/api/tests/readiness.test.ts index d0e40ba5..d1addce3 100644 --- a/packages/api/tests/readiness.test.ts +++ b/packages/api/tests/readiness.test.ts @@ -12,7 +12,7 @@ import { } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { invokeAnyOp } from '../src/ops' -import { cleanup, req, setupCms, PNG } from './helpers' +import { cleanup, moveLiveUnder, req, setupCms, PNG } from './helpers' afterEach(cleanup) @@ -479,10 +479,9 @@ describe('1.0 request invariants', () => { { collection: 'post', id: 'one', doc: { title: 'Author proposal' } }, { request: req('/', { role: 'author' }) }, )) as { pendingId: string } - await commitDocument('post', 'one', { + await moveLiveUnder('post', 'one', { title: 'Admin edit', secret: 'second', - published: true, }) await invokeAnyOp( 'approveChange', diff --git a/packages/api/tests/workflow.test.ts b/packages/api/tests/workflow.test.ts index f47cb64a..46521ab2 100644 --- a/packages/api/tests/workflow.test.ts +++ b/packages/api/tests/workflow.test.ts @@ -7,7 +7,7 @@ import { stageWrite, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' -import { cleanup, req, setupCms } from './helpers' +import { cleanup, moveLiveUnder, req, setupCms } from './helpers' afterEach(cleanup) @@ -157,7 +157,7 @@ describe('approving stale proposals', () => { doc: { title: 'Agent', published: false }, actor: 'mcp', }) - await commitDocument('post', 'wip', { title: 'Human', published: false }) + await moveLiveUnder('post', 'wip', { title: 'Human' }) const stale = await call('approveChange', { id: pending.id }) expect(stale.status).toBe(409) @@ -171,7 +171,7 @@ describe('approving stale proposals', () => { }) describe('scheduled unpublish', () => { - it('runScheduledPublishing unpublishes past unpublishAt and emits unpublish', async () => { + it('runScheduledPublishing unpublishes past unpublishAt and emits document.unpublished', async () => { await seed() await commitDocument('post', 'expiring', { title: 'Expiring', @@ -185,7 +185,7 @@ describe('scheduled unpublish', () => { }) const events: Array = [] const off = onCmsEvent((e) => { - if (e.event === 'unpublish') events.push(e.id) + if (e.event === 'document.unpublished') events.push(e.id) }) await runScheduledPublishing() off() diff --git a/packages/client/src/db.ts b/packages/client/src/db.ts index 3200902c..4158203e 100644 --- a/packages/client/src/db.ts +++ b/packages/client/src/db.ts @@ -62,7 +62,12 @@ export interface CmsCollectionDbOptions { } export interface CmsLiveEvent { - event: 'publish' | 'unpublish' | 'delete' | 'change' + event: + | 'document.created' + | 'document.updated' + | 'document.published' + | 'document.unpublished' + | 'document.deleted' collection: string id: string at: string diff --git a/packages/client/tests/db.test.ts b/packages/client/tests/db.test.ts index 97ab1aa8..c8b1a24c 100644 --- a/packages/client/tests/db.test.ts +++ b/packages/client/tests/db.test.ts @@ -273,6 +273,7 @@ describe('createCmsCollectionOptions', () => { expect(received.length).toBeGreaterThanOrEqual(1) expect(received[0]).toMatchObject({ + event: 'document.created', collection: 'post', id: 'live-1', }) diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index d15aeddf..6a69a27f 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -568,11 +568,40 @@ export interface CmsSeoConfig { redirectsCollection?: string } -export type CmsWebhookEvent = 'publish' | 'unpublish' | 'delete' | 'change' +/** + * A committed content change, named like the durable `document.*` events. + * `document.created` / `document.updated`: every create or update commit, + * live or not. `document.published`: a document went live. + * `document.unpublished`: it came down. `document.deleted`: it was deleted. + */ +export type CmsContentEvent = + | 'document.created' + | 'document.updated' + | 'document.published' + | 'document.unpublished' + | 'document.deleted' + +/** + * @deprecated The short event names, still accepted where events are + * subscribed to by name (webhook `events`, `onCmsEvent(names, listener)`) and + * removed in phase 6. `publish` = `document.published`, `unpublish` = + * `document.unpublished`, `delete` = `document.deleted`, `change` = + * `document.created` or `document.updated`, `update` = `document.updated` of + * a document that stayed live. Delivered events carry the `document.*` name. + */ +export type CmsEventAlias = + | 'publish' + | 'unpublish' + | 'delete' + | 'change' + | 'update' + +/** An event name a webhook `events` list or an `onCmsEvent` filter accepts. */ +export type CmsWebhookEvent = CmsContentEvent | CmsEventAlias /** A content change, as delivered to `onCmsEvent` listeners, plugins, and webhooks. */ export interface CmsEvent { - event: CmsWebhookEvent + event: CmsContentEvent collection: string id: string actor: string @@ -588,7 +617,11 @@ type ServerValue = string | (() => string | undefined) export interface CmsWebhook { /** Endpoint to POST to. */ url: ServerValue - /** Events to send. Default `['publish', 'unpublish', 'delete']`. */ + /** + * Events to send. Default: what a public site shows changing — + * `document.published`, `document.unpublished`, `document.deleted`, and + * `document.updated` while the document stays live. + */ events?: Array /** Only these collections. Default all. */ collections?: Array diff --git a/packages/core/src/document-state.ts b/packages/core/src/document-state.ts index cb2137ad..a9f5fb16 100644 --- a/packages/core/src/document-state.ts +++ b/packages/core/src/document-state.ts @@ -138,8 +138,13 @@ export type Decision = * - `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. - * - `discard`: drop the open draft. - * - `publish` / `unpublish`: take the live revision up or down (the scheduler). + * - `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. * - `import`: restore `patch` from an export (actor `import`). */ export type BuiltInActionType = @@ -149,6 +154,7 @@ export type BuiltInActionType = | 'approve' | 'reject' | 'discard' + | 'schedule' | 'publish' | 'unpublish' | 'import' @@ -204,12 +210,20 @@ export interface ChangeSetView { after: Doc baseRevision: number | null instruction?: string + /** When the scheduler publishes this change set (a live document's scheduled update). */ + publishAt: string | null /** * The strategy state stored with the change set, with the `id@version` of - * the strategy that wrote it. `null` while change sets carry no stored - * state; the built-in strategies derive theirs from `source`. + * the strategy that wrote it (already upgraded by `migrate`). `null` when + * no decision stored a state. */ workflow: { strategy: string; state: S } | null + /** + * Set when the change set was written by another strategy, or by an older + * version this one can't `migrate`: core then refuses every decision on it + * except discarding it. + */ + stranded?: string } export interface DocView { @@ -321,11 +335,48 @@ function approvedPublished(action: Action, after: Doc): boolean { return typeof override === 'boolean' ? override : proposedPublished(after) } -function scheduledActions(action: Action): Decision | null { - if (action.type === 'publish') return { effects: [publish()] } - if (action.type === 'unpublish') - return { effects: [unpublish(), schedule({ unpublishAt: null })] } - return null +function scheduledActions( + doc: DocView, + action: Action, +): Decision | null { + switch (action.type) { + case 'publish': { + const cs = doc.changeSet + if (cs && action.input?.changeSet === cs.id) { + return { + effects: [ + ...commitChange(doc.live, cs.type, cs.after, true), + ...(cs.source === 'draft' ? [] : [emit('review.approved')]), + ], + } + } + return { effects: [publish()] } + } + case 'unpublish': + return { effects: [unpublish(), schedule({ unpublishAt: null })] } + case 'schedule': { + if (!doc.changeSet) return { reject: 'There is no change to schedule.' } + const at = action.input?.publishAt + return { + effects: [schedule({ publishAt: typeof at === 'string' ? at : null })], + } + } + default: + return null + } +} + +/** Discard the open change set; a stale proposal tells its proposer. */ +function discardChangeSet( + doc: DocView, + action: Action, +): Decision { + const cs = doc.changeSet + if (!cs) return { reject: `There is no change to ${action.type}.` } + const reason = action.input?.reason + if (typeof reason === 'string' && cs.source !== 'draft') + return { effects: [discard(), emit('review.discarded', { reason })] } + return { effects: [discard()] } } function liveLabel(live: LiveView | null): string { @@ -344,6 +395,7 @@ const ACTIONS: Record = { approve: { type: 'approve', label: 'Approve', tone: 'primary' }, reject: { type: 'reject', label: 'Reject', tone: 'danger' }, discard: { type: 'discard', label: 'Discard draft', tone: 'danger' }, + schedule: { type: 'schedule', label: 'Schedule' }, publish: { type: 'publish', label: 'Publish' }, unpublish: { type: 'unpublish', label: 'Unpublish' }, import: { type: 'import', label: 'Import' }, @@ -504,11 +556,10 @@ export function reviewStrategy( if (!doc.changeSet) return { reject: 'There is no change to reject.' } return { effects: [discard(), emit('review.rejected')] } case 'discard': - if (!doc.changeSet) return { reject: 'There is no draft to discard.' } - return { effects: [discard()] } + return discardChangeSet(doc, action) default: return ( - scheduledActions(action) ?? { + scheduledActions(doc, action) ?? { reject: `The review strategy has no "${action.type}" action.`, } ) @@ -524,6 +575,7 @@ export function reviewStrategy( out.push(ACTIONS.edit) if (doc.live?.published) out.push(ACTIONS.draft) if (state === 'draft') out.push(ACTIONS.discard) + if (state && doc.live?.published) out.push(ACTIONS.schedule) } else if (can(ctx, 'content.write') || agent) { out.push(ACTIONS.submit) } @@ -582,7 +634,7 @@ export function directStrategy( return { effects: [discard()] } default: return ( - scheduledActions(action) ?? { + scheduledActions(doc, action) ?? { reject: `The direct strategy has no "${action.type}" action.`, } ) @@ -597,6 +649,7 @@ export function directStrategy( if (state === 'draft') out.push(ACTIONS.discard) if (state === 'pending_review' && can(ctx, 'review.decide')) out.push(ACTIONS.approve, ACTIONS.reject) + if (state && doc.live?.published) out.push(ACTIONS.schedule) return out }, label: builtInLabel, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3e67af3b..4f4b978a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -47,6 +47,8 @@ export type { CmsSeoConfig, CmsWebhook, CmsWebhookEvent, + CmsContentEvent, + CmsEventAlias, CmsEvent, CmsPlugin, CmsPluginDefinition, diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 5cccfea9..50cf5c79 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -65,6 +65,7 @@ export { availableDocumentActions, documentStateLabel, documentStateStrategy, + listStrandedChangeSets, } from './server/store' // Optional storage-capability narrowing (auth users / api keys / user roles). export { requireStorageCapability } from './storage/capabilities' @@ -104,6 +105,7 @@ export type { ScheduledPublishResult, IncomingChange, RefusalRule, + StrandedChangeSet, StrategyOutcome, } from './server/store' export { diff --git a/packages/core/src/server/events.ts b/packages/core/src/server/events.ts index a00e6f88..be4023f9 100644 --- a/packages/core/src/server/events.ts +++ b/packages/core/src/server/events.ts @@ -14,6 +14,7 @@ import { applyPlugins, getCmsConfig, runWithCmsConfig } from '../config' import type { CmsConfig, + CmsContentEvent, CmsEvent, CmsPlugin, CmsWebhookEvent, @@ -22,6 +23,7 @@ import type { import type { Doc } from '../schema' export type { CmsEvent } from '../config' +/** A name `onCmsEvent` filters on: a `document.*` event or a deprecated alias. */ export type CmsEventName = CmsWebhookEvent export type CmsEventListener = (event: CmsEvent) => void @@ -49,6 +51,7 @@ export function cmsEventScope( } const eventDocuments = new WeakMap() const previousDocuments = new WeakMap() +const stayedLiveEvents = new WeakSet() /** An update may invalidate a document the reader could see before it changed. */ export function cmsEventPreviousDocument(event: CmsEvent): Doc | undefined { return previousDocuments.get(event) @@ -60,11 +63,24 @@ export function cmsEventDocument(event: CmsEvent): Doc | undefined { } /** - * Subscribe to content events (`change`, `publish`, `unpublish`, `delete`) - * emitted after commits in this process. Returns the unsubscribe function. - * A listener that throws is ignored; it never breaks the write. + * Subscribe to content events (`document.created`, `document.updated`, + * `document.published`, `document.unpublished`, `document.deleted`) emitted + * after commits in this process, optionally only the named ones (deprecated + * short aliases such as `publish` still match). Returns the unsubscribe + * function. A listener that throws is ignored; it never breaks the write. */ -export function onCmsEvent(listener: CmsEventListener): () => void { +export function onCmsEvent(listener: CmsEventListener): () => void +export function onCmsEvent( + events: CmsEventName | ReadonlyArray, + listener: CmsEventListener, +): () => void +export function onCmsEvent( + ...args: + | [CmsEventListener] + | [CmsEventName | ReadonlyArray, CmsEventListener] +): () => void { + const [names, listener] = + args.length === 1 ? [undefined, args[0]] : [toArray(args[0]), args[1]] const config = getCmsConfig() const scope = cmsEventScope(config) let registered = listeners.get(scope) @@ -73,8 +89,16 @@ export function onCmsEvent(listener: CmsEventListener): () => void { listeners.set(scope, registered) } const scoped = registered - const bound: CmsEventListener = (event) => + const bound: CmsEventListener = (event) => { + if ( + names && + !names.some((name) => + cmsEventMatches(name, event.event, stayedLiveEvents.has(event)), + ) + ) + return runWithCmsConfig(config, () => listener(event)) + } scoped.add(bound) return () => { scoped.delete(bound) @@ -89,21 +113,82 @@ function plugins(): ReadonlyArray { } } +function toArray(value: T | ReadonlyArray): ReadonlyArray { + return Array.isArray(value) ? value : [value as T] +} + +/** + * The events a create or update commit produces, in order: + * `document.created` or `document.updated`, then `document.published` when + * the document went live or `document.unpublished` when it came down. The + * same names and order as the durable outbox. + */ +export function commitEvents( + before: Doc | null, + after: Doc, +): Array { + const events: Array = [ + before ? 'document.updated' : 'document.created', + ] + const wasPublished = Boolean(before?.published) + const isPublished = Boolean(after.published) + if (isPublished && !wasPublished) events.push('document.published') + if (wasPublished && !isPublished) events.push('document.unpublished') + return events +} + +/** The document was live before and after the commit. */ +export function stayedLive(before: Doc | null, after: Doc): boolean { + return Boolean(before?.published) && Boolean(after.published) +} + +/** + * Whether a subscription to `name` (a `document.*` event or a deprecated + * alias) receives `event`. `live`: the document was live before and after + * (the alias `update` means a live-content save). + */ +export function cmsEventMatches( + name: CmsEventName, + event: CmsContentEvent, + live: boolean, +): boolean { + switch (name) { + case 'publish': + return event === 'document.published' + case 'unpublish': + return event === 'document.unpublished' + case 'delete': + return event === 'document.deleted' + case 'change': + return event === 'document.created' || event === 'document.updated' + case 'update': + return event === 'document.updated' && live + case 'document.created': + case 'document.updated': + case 'document.published': + case 'document.unpublished': + case 'document.deleted': + return name === event + } +} + /** Emit a content event to every in-process listener and plugin `onEvent` hook. */ export function emitCmsEvent( - event: CmsEventName, + event: CmsContentEvent, payload: { collection: string id: string actor: string doc?: Doc previous?: Doc | null + stayedLive?: boolean }, ): void { - const { previous, ...current } = payload + const { previous, stayedLive: live, ...current } = payload const full: CmsEvent = { event, at: new Date().toISOString(), ...current } if (previous) previousDocuments.set(full, structuredClone(previous)) - if (event === 'delete') { + if (live) stayedLiveEvents.add(full) + if (event === 'document.deleted') { if (payload.doc) eventDocuments.set(full, structuredClone(payload.doc)) delete full.doc } diff --git a/packages/core/src/server/outbox.ts b/packages/core/src/server/outbox.ts index 142ba110..0471b143 100644 --- a/packages/core/src/server/outbox.ts +++ b/packages/core/src/server/outbox.ts @@ -15,6 +15,7 @@ import { AsyncLocalStorage } from 'node:async_hooks' import { randomUUID } from 'node:crypto' import { getCmsConfig } from '../config' +import { commitEvents, stayedLive } from './events' import { matchingWebhooks } from './webhooks' import type { CmsEvent } from '../config' import type { CmsEventTypeInput } from '../events' @@ -157,6 +158,7 @@ export async function enqueueEvent( export async function enqueueWebhooks( tx: StorageOps, event: CmsEvent, + live = false, ): Promise { if (!tx.insertEvent) return // Handler write-backs (depth > 0) never fan out to webhooks: this is the @@ -166,7 +168,7 @@ export async function enqueueWebhooks( const config = getCmsConfig() const hooks = config.webhooks ?? [] if (!hooks.length) return - const matching = matchingWebhooks(event) + const matching = matchingWebhooks(event, live) if (!matching.length) return for (const hook of matching) { const hookIndex = hooks.indexOf(hook) @@ -193,8 +195,9 @@ export async function enqueueWebhooks( /** * Build the `CmsEvent` wire payloads a create/update commit emits - * (`change`, then `publish`/`unpublish` on a publish-state transition), exactly - * as the in-process bus (`emitCommit`) did. The webhook contract is defined by + * (`document.created` / `document.updated`, then `document.published` / + * `document.unpublished` on a publish-state transition), exactly as the + * in-process bus (`emitCommit`) does. The webhook contract is defined by * these payloads, so enqueue and in-process delivery stay byte-identical. */ function commitWebhookEvents(args: { @@ -212,15 +215,10 @@ function commitWebhookEvents(args: { at: args.occurredAt, doc: args.after, } - const events: Array = [{ event: 'change', ...base }] - const wasPublished = Boolean(args.before?.published) - const isPublished = Boolean(args.after.published) - if (isPublished) { - events.push({ event: 'publish', ...base }) - } else if (wasPublished) { - events.push({ event: 'unpublish', ...base }) - } - return events + return commitEvents(args.before, args.after).map((event) => ({ + event, + ...base, + })) } const INTERNAL_FIELDS = new Set(['_revision', '_updatedAt', '_contentVersion']) @@ -291,8 +289,9 @@ export async function enqueueDocumentChange( payload: args.after, }) } + const live = stayedLive(args.before, args.after) for (const event of commitWebhookEvents(args)) { - await enqueueWebhooks(tx, event) + await enqueueWebhooks(tx, event, live) } } @@ -318,9 +317,10 @@ export async function enqueueDocumentDelete( payload: { id: args.id }, ...(args.last ? { previous: args.last } : {}), }) - // The webhook `delete` payload carries no `doc` (matching the in-process bus). + // The webhook `document.deleted` payload carries no `doc` (matching the + // in-process bus). await enqueueWebhooks(tx, { - event: 'delete', + event: 'document.deleted', collection: args.collection, id: args.id, actor: args.actor, diff --git a/packages/core/src/server/storage.ts b/packages/core/src/server/storage.ts index e374302a..8be77b7a 100644 --- a/packages/core/src/server/storage.ts +++ b/packages/core/src/server/storage.ts @@ -54,6 +54,18 @@ export function registerScheduledSweep( scheduledSweep = fn } +/** Change sets due for their scheduled publish, for adapters without the query. */ +export async function duePendingPublishes( + storage: Pick, + nowIso: string, +): Promise> { + if (storage.findDuePendingPublish) + return storage.findDuePendingPublish(nowIso) + return (await storage.listPending()) + .filter((p) => p.publishAt !== undefined && p.publishAt <= nowIso) + .sort((a, b) => ((a.publishAt ?? '') < (b.publishAt ?? '') ? -1 : 1)) +} + let dispatchKick: (() => void) | null = null let dispatchStop: (() => Promise) | null = null const dispatchLoading = new Map>() @@ -241,6 +253,13 @@ function createCompositeStorage(cfg: ResolvedCmsConfig): StorageAdapter { } return out }, + async findDuePendingPublish(nowIso) { + const out: Array = [] + for (const a of writableAdapters()) { + out.push(...(await duePendingPublishes(a, nowIso))) + } + return out + }, putDocument: (record, index) => forCollection(record.collection).putDocument(record, index), deleteDocument: (collection, id) => diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 98b77478..3db8ad97 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -94,10 +94,12 @@ export { availableDocumentActions, documentStateLabel, documentStateStrategy, + listStrandedChangeSets, } from './store/document-state' export type { IncomingChange, RefusalRule, + StrandedChangeSet, StrategyOutcome, } from './store/document-state' export { diff --git a/packages/core/src/server/store/document-state.ts b/packages/core/src/server/store/document-state.ts index 501bc23b..feac6230 100644 --- a/packages/core/src/server/store/document-state.ts +++ b/packages/core/src/server/store/document-state.ts @@ -8,7 +8,7 @@ * 2. A published document's content changes only together with `publish` * (or comes down with `unpublish`). * 3. Audit is not an effect: core writes the audit row (actor, action, - * outcome), refusals included. + * outcome, from / to state, effects), refusals included. * 4. Collection hooks run when a change is staged or committed; core emits * `document.*` events from the commit and the publish / unpublish effects. * 5. Agents can't cause `publish` / `unpublish` unless the strategy grants it. @@ -32,7 +32,7 @@ import { import { emitCmsEvent } from '../events' import { deleteAssetBlob } from '../media-store' import { queueNotification } from '../notifications' -import { enqueueDocumentChange, enqueueEvent } from '../outbox' +import { changedFields, enqueueDocumentChange, enqueueEvent } from '../outbox' import { getStorage, notifyStorageCommit } from '../storage' import { applyPostRead, @@ -108,9 +108,63 @@ interface LoadedView { view: DocView liveRow: IndexedDocumentRecord | null pending: Pending | null + /** The change set's state was upgraded by `migrate`; store it with the decision. */ + migrated: boolean } -function changeSetView(pending: Pending): ChangeSetView { +interface ResolvedWorkflow { + workflow: { strategy: string; state: unknown } | null + stranded?: string + migrated: boolean +} + +function parseStrategyKey(key: string): { id: string; version: number } { + const at = key.lastIndexOf('@') + return at < 0 + ? { id: key, version: 0 } + : { id: key.slice(0, at), version: Number(key.slice(at + 1)) || 0 } +} + +/** + * The change set's stored state as `strategy` sees it: as stored when the + * same version wrote it, upgraded by `migrate` when an older version did, + * else stranded. + */ +function resolveWorkflow( + strategy: AnyDocumentStateStrategy, + pending: Pending, +): ResolvedWorkflow { + const stored = pending.workflow + if (!stored) return { workflow: null, migrated: false } + const key = strategyKey(strategy) + if (stored.strategy === key) return { workflow: stored, migrated: false } + const from = parseStrategyKey(stored.strategy) + const stranded = (reason: string): ResolvedWorkflow => ({ + workflow: stored, + stranded: `Change set ${pending.id} was written by ${stored.strategy}; ${reason}`, + migrated: false, + }) + if (from.id !== strategy.id || from.version > strategy.version) + return stranded(`the collection now uses ${key}.`) + if (!strategy.migrate) return stranded(`${key} has no migrate().`) + try { + const result = strategy.migrate({ + version: from.version, + state: stored.state, + }) + if ('stranded' in result) return stranded(result.stranded) + return { workflow: { strategy: key, state: result.state }, migrated: true } + } catch (err) { + return stranded( + `${key}'s migrate() threw: ${err instanceof Error ? err.message : String(err)}`, + ) + } +} + +function changeSetView( + pending: Pending, + resolved: ResolvedWorkflow, +): ChangeSetView { return { id: pending.id, version: pending.version ?? 1, @@ -120,12 +174,15 @@ function changeSetView(pending: Pending): ChangeSetView { after: pending.after, baseRevision: pending.baseRevision ?? null, ...(pending.instruction ? { instruction: pending.instruction } : {}), - workflow: null, + publishAt: pending.publishAt ?? null, + workflow: resolved.workflow, + ...(resolved.stranded ? { stranded: resolved.stranded } : {}), } } async function loadView( storage: StorageOps, + strategy: AnyDocumentStateStrategy, collection: string, docId: string, pendingOverride?: Pending | null, @@ -136,9 +193,11 @@ async function loadView( ? await storage.getPendingFor(collection, docId) : pendingOverride const revision = liveRow?.doc._revision + const resolved = pending ? resolveWorkflow(strategy, pending) : null return { liveRow, pending, + migrated: resolved?.migrated ?? false, view: { collection, id: docId, @@ -151,7 +210,7 @@ async function loadView( unpublishAt: liveRow.unpublishAt, } : null, - changeSet: pending ? changeSetView(pending) : null, + changeSet: pending && resolved ? changeSetView(pending, resolved) : null, }, } } @@ -163,8 +222,9 @@ export async function availableDocumentActions( docId: string, ): Promise> { const storage = await getStorage() - const { view } = await loadView(storage, collection, docId) - return documentStateStrategy(collection).availableActions(ctx, view) + const strategy = documentStateStrategy(collection) + const { view } = await loadView(storage, strategy, collection, docId) + return strategy.availableActions(ctx, view) } /** The strategy's label for a document's current state. */ @@ -173,8 +233,36 @@ export async function documentStateLabel( docId: string, ): Promise { const storage = await getStorage() - const { view } = await loadView(storage, collection, docId) - return documentStateStrategy(collection).label(undefined, view) + const strategy = documentStateStrategy(collection) + const { view } = await loadView(storage, strategy, collection, docId) + return strategy.label(view.changeSet?.workflow?.state, view) +} + +export interface StrandedChangeSet { + pending: Pending + reason: string +} + +/** + * Change sets whose stored state their collection's strategy can't read: + * written by another strategy, or by an older version without a `migrate` + * that upgrades it. Decisions on them are refused until they're discarded. + */ +export async function listStrandedChangeSets(): Promise< + Array +> { + const storage = await getStorage() + const out: Array = [] + for (const pending of await storage.listPending()) { + if (!pending.workflow || !getCmsConfig().collections[pending.collection]) + continue + const { stranded } = resolveWorkflow( + documentStateStrategy(pending.collection), + pending, + ) + if (stranded) out.push({ pending, reason: stranded }) + } + return out } // --------------------------------------------------------------------------- @@ -189,6 +277,29 @@ export type RefusalRule = | 'agent-floor' | 'drops-change' | 'core-event' + | 'stranded' + +/** + * Whether the decision's `schedule` lands on the change set: a published + * document with an open (or just staged) change set keeps its live version + * up, and the scheduler publishes the change set when it's due. Anything + * else schedules the document itself. + */ +function schedulesChangeSet( + loaded: LoadedView, + effects: ReadonlyArray, + change: WriteType | null, +): boolean { + const has = (type: EffectType) => effects.some((e) => e.type === type) + return ( + has('schedule') && + !has('commit') && + !has('publish') && + !has('unpublish') && + Boolean(loaded.view.live?.published) && + (loaded.pending !== null || (has('stage') && change !== null)) + ) +} const EFFECT_TYPES = new Set([ 'stage', @@ -212,6 +323,7 @@ function checkDecision( action: Action, effects: ReadonlyArray, change: WriteType | null, + storesState: boolean, ): Refusal | null { for (const effect of effects) { if (!EFFECT_TYPES.has(effect.type)) { @@ -228,6 +340,17 @@ 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', @@ -235,9 +358,12 @@ function checkDecision( } } const actor = actorOf(ctx) + const schedulesPublish = effects.some( + (e) => e.type === 'schedule' && typeof e.publishAt === 'string', + ) if ( actor.type === 'agent' && - (has('publish') || has('unpublish')) && + (has('publish') || has('unpublish') || schedulesPublish) && !strategy.grants?.publish?.includes('agent') ) { return { @@ -272,9 +398,20 @@ function checkDecision( } discarded = true break + case 'schedule': + if ( + effect.unpublishAt !== undefined && + schedulesChangeSet(loaded, effects, change) + ) { + return { + rule: 'effects', + reason: + 'A change set can only be scheduled to publish: unpublishAt belongs to the document.', + } + } + break case 'publish': case 'unpublish': - case 'schedule': case 'emit': break } @@ -296,6 +433,11 @@ function checkDecision( return null } +/** The open change set's strategy state, as audited (`null`: none). */ +function stateOf(loaded: LoadedView): JsonValue { + return (loaded.view.changeSet?.workflow?.state ?? null) as JsonValue +} + /** The type of change the decision's `commit` applies, if any. */ function committedChange( loaded: LoadedView, @@ -314,6 +456,10 @@ export interface RefusedDecision { change: WriteType | null rule: RefusalRule reason: string + /** The open change set the action targeted, if any. */ + changeSet?: string + /** Its strategy state (`null`: none). */ + from: JsonValue } /** Audit a refused decision (nothing else changes) and throw it as `FORBIDDEN`. */ @@ -327,6 +473,9 @@ export async function refuseDecision(refused: RefusedDecision): Promise { actor: refused.by, action: refused.action.type, decision: 'refused', + ...(refused.changeSet ? { changeSet: refused.changeSet } : {}), + from: refused.from, + reason: refused.reason, at: new Date().toISOString(), }) }) @@ -374,6 +523,7 @@ export async function decideStrategyWrite( const strategy = documentStateStrategy(args.collection) const loaded = await loadView( storage, + strategy, args.collection, args.docId, args.pending, @@ -402,6 +552,8 @@ export async function decideStrategyWrite( change: change ?? loaded.pending?.type ?? null, rule, reason, + ...(loaded.pending ? { changeSet: loaded.pending.id } : {}), + from: stateOf(loaded), }, }) const decision = await strategy.decide(args.ctx, loaded.view, action) @@ -414,6 +566,7 @@ 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 } @@ -573,18 +726,158 @@ async function prepareCommit( return doc } +/** The audited outcome of a decision; `null` only for a pure `emit`. */ function auditDecision( action: Action, effects: ReadonlyArray, + schedulesOnChangeSet: boolean, + storesState: boolean, ): AuditRecord['decision'] | null { if (action.type === 'reject') return 'rejected' const has = (type: EffectType) => effects.some((e) => e.type === type) - if (has('commit') || has('publish') || has('unpublish') || has('schedule')) + if ( + has('commit') || + has('publish') || + has('unpublish') || + (has('schedule') && !schedulesOnChangeSet) + ) return 'approved' if (has('discard')) return 'discarded' + if (has('stage')) return storesState ? 'transitioned' : 'staged' + if (storesState || has('schedule')) return 'transitioned' return null } +/** + * Whether a change set overlaps a commit of `content`: both changed the same + * field, relative to the live versions they were based on, to different + * values. A staged delete overlaps any change. + */ +function overlaps( + pending: Pending, + changed: ReadonlySet, + content: Doc, +): boolean { + if (pending.type === 'delete') return changed.size > 0 + return changedFields(pending.before ?? {}, pending.after).some( + (field) => + changed.has(field) && + JSON.stringify(pending.after[field]) !== JSON.stringify(content[field]), + ) +} + +/** + * `open` moved onto the new live version `live`: its own fields re-applied + * over it, based on that revision. + */ +function rebaseChangeSet( + open: Pending, + live: Doc, + touched: ReadonlyArray, +): Pending { + const { _revision: revision, _updatedAt: _stamp, ...base } = live + const after: Doc = { ...base } + for (const field of touched) { + if (field in open.after) after[field] = open.after[field] as JsonValue + else delete after[field] + } + return { + ...open, + version: (open.version ?? 0) + 1, + type: open.type === 'delete' ? 'delete' : 'update', + before: live, + after, + ...(typeof revision === 'number' ? { baseRevision: revision } : {}), + } +} + +/** What a new live revision does to the document's open change set (#5). */ +interface StalePlan { + pending: Pending + /** Rebase: the change set's fields, re-applied over the new live version. */ + touched: ReadonlyArray + /** Invalidate instead: the strategy's `discard` (reason `stale`) effects. */ + invalidate: ReadonlyArray | null + from: JsonValue +} + +/** + * Ask the strategy how to discard a proposal a direct commit made stale. + * Anything but discard (and emits) falls back to a plain discard: core + * won't leave a stale change set behind. + */ +async function staleDiscard( + storage: StorageOps, + write: StrategyWrite, + pending: Pending, +): Promise> { + const decided = await decideStrategyWrite(storage, { + ctx: write.ctx, + by: write.by, + collection: write.collection, + docId: write.docId, + action: { type: 'discard', input: { reason: 'stale' } }, + pending, + }) + if ( + decided.ok && + decided.effects.some((e) => e.type === 'discard') && + decided.effects.every((e) => e.type === 'discard' || e.type === 'emit') + ) + return decided.effects + return [{ type: 'discard' }] +} + +/** + * A stage that would mix sources: the open change set came through another + * door (an agent's proposal, an author's review request, a draft), so it is + * refused until that change set is approved, rejected or discarded. + */ +function assertSameSource(open: Pending | null, source: PendingSource): void { + if (!open || open.source === source) return + throw new CmsError( + `${open.collection}/${open.docId} has an open ${open.source} change set (${open.id}). Approve, reject or discard it first.`, + 'CONFLICT', + { pendingId: open.id, source: open.source }, + ) +} + +interface EmitTarget { + collection: string + docId: string + actor: string + author?: string + at: string +} + +async function enqueueEmit( + tx: StorageOps, + effect: Extract, + changeSet: Pending | null, + target: EmitTarget, +): Promise { + const extra = + effect.payload && typeof effect.payload === 'object' + ? (effect.payload as Record) + : effect.payload === undefined + ? {} + : { value: effect.payload as JsonValue } + await enqueueEvent(tx, { + type: effect.event, + collection: target.collection, + documentId: target.docId, + actor: target.actor, + occurredAt: target.at, + ...(target.author ? { author: target.author } : {}), + payload: changeSet + ? { pendingId: changeSet.id, type: changeSet.type, ...extra } + : extra, + }) +} + +const asJson = (effects: ReadonlyArray): Array => + effects.map((e) => ({ ...e }) as JsonValue) + /** * Ask the collection's strategy what `write.action` does, check the decision * against core's rules, and run its effects in one transaction. A refused @@ -606,8 +899,26 @@ export async function executeStrategyWrite( effects.findIndex((e) => e.type === 'stage') < effects.findIndex((e) => e.type === 'commit') const commitType = committedChange(loaded, effects, change) + const onChangeSet = schedulesChangeSet(loaded, effects, change) const writesLive = - has('commit') || has('publish') || has('unpublish') || has('schedule') + has('commit') || + has('publish') || + has('unpublish') || + (has('schedule') && !onChangeSet) + const stagedSource = + has('stage') && write.incoming ? (write.source ?? stageSource(write)) : null + if (stagedSource) assertSameSource(loaded.pending, stagedSource) + const key = strategyKey(strategy) + const storesState = decided.state !== undefined + const workflow: Pending['workflow'] = storesState + ? { strategy: key, state: decided.state as JsonValue } + : ((loaded.view.changeSet?.workflow as Pending['workflow'] | null) ?? + undefined) + const scheduled = onChangeSet + ? effects.find((e) => e.type === 'schedule') + : undefined + const changeSetPublishAt = + scheduled?.type === 'schedule' ? scheduled.publishAt : undefined const { liveRow } = loaded const operation: 'create' | 'update' = liveRow ? 'update' : 'create' const author = write.author ?? write.by @@ -620,8 +931,16 @@ export async function executeStrategyWrite( : (write.auditActor ?? write.by) const proposer = write.author ?? (autoApproved ? write.by : undefined) const eventAuthor = proposer !== eventActor ? proposer : undefined - const actsOnChangeSet = + /** The decision commits or discards the open (or just staged) change set. */ + const closesChangeSet = (has('commit') && (!write.incoming || stagesFirst)) || has('discard') + /** It keeps the open change set and changes its state or publish time. */ + const updatesChangeSet = + !closesChangeSet && + !has('stage') && + loaded.pending !== null && + (storesState || loaded.migrated || onChangeSet) + const actsOnChangeSet = closesChangeSet || updatesChangeSet const now = write.at ?? new Date().toISOString() // Prepare what the transaction writes: hooks and validation run outside it. @@ -691,9 +1010,33 @@ export async function executeStrategyWrite( if (commitType === 'delete') await runPreDelete(collection, write.docId, author) + // A new live revision that leaves the open change set in place moves it + // onto that revision, or invalidates it when they changed the same field. + let stale: StalePlan | null = null + const foldsDraft = has('commit') && loaded.pending?.source === 'draft' + if ( + content && + loaded.pending && + !closesChangeSet && + !has('stage') && + !foldsDraft + ) { + const changed = new Set(changedFields(liveRow?.doc ?? {}, content)) + stale = { + pending: loaded.pending, + touched: changedFields(loaded.pending.before ?? {}, loaded.pending.after), + invalidate: overlaps(loaded.pending, changed, content) + ? await staleDiscard(storage, write, loaded.pending) + : null, + from: stateOf(loaded), + } + } + let staged: Pending | null = null + let updated: Pending | null = null let committed: Doc | null = null let deleted: Doc | null | undefined + let invalidated: Pending | null = null let notifySubmitted = false const outcome = await storage.transaction(async (tx) => { let liveRead: Promise | undefined @@ -724,6 +1067,12 @@ export async function executeStrategyWrite( const incoming = write.incoming if (!incoming) break const latest = await tx.getPendingFor(write.collection, write.docId) + const source = stagedSource ?? stageSource(write) + assertSameSource(latest, source) + const publishAt = + changeSetPublishAt === undefined + ? latest?.publishAt + : changeSetPublishAt || undefined staged = { id: latest?.id ?? randomUUID(), version: (latest?.version ?? 0) + 1, @@ -737,12 +1086,14 @@ export async function executeStrategyWrite( actor: write.by, instruction: write.instruction ?? latest?.instruction, createdAt: now, - source: write.source ?? stageSource(write), + source, baseRevision: latest?.baseRevision ?? (typeof live?.doc._revision === 'number' ? live.doc._revision : undefined), + ...(workflow ? { workflow } : {}), + ...(publishAt ? { publishAt } : {}), } await tx.putPending(staged) changeSet = staged @@ -764,6 +1115,12 @@ export async function executeStrategyWrite( ...(changeSet ? { auditId: changeSet.id } : {}), auditActor, auditAction: action.type, + auditTransition: { + ...(changeSet ? { changeSet: changeSet.id } : {}), + from: stateOf(loaded), + to: null, + effects: asJson(effects), + }, eventActor, ...(eventAuthor ? { eventAuthor } : {}), session: write.session, @@ -780,6 +1137,7 @@ export async function executeStrategyWrite( case 'publish': case 'unpublish': case 'schedule': + if (onChangeSet) break if (!has('commit') && !committed) committed = await writeLive(tx, live, content, { fromChangeSet: false, @@ -791,41 +1149,106 @@ export async function executeStrategyWrite( if (target) await tx.deletePending(target.id) break } - case 'emit': { - const target = changeSet ?? loaded.pending - const extra = - effect.payload && typeof effect.payload === 'object' - ? (effect.payload as Record) - : effect.payload === undefined - ? {} - : { value: effect.payload as JsonValue } - await enqueueEvent(tx, { - type: effect.event, + case 'emit': + await enqueueEmit(tx, effect, changeSet ?? loaded.pending, { collection: write.collection, - documentId: write.docId, + docId: write.docId, actor: eventActor, - occurredAt: now, ...(eventAuthor ? { author: eventAuthor } : {}), - payload: target - ? { pendingId: target.id, type: target.type, ...extra } - : extra, + at: now, }) if (effect.event === 'review.submitted') notifySubmitted = true break + } + } + if (updatesChangeSet && loaded.pending) { + const current = await tx.getPending(loaded.pending.id) + if (!current || (current.version ?? 0) !== (loaded.pending.version ?? 0)) + throw new CmsError( + 'This change set was decided or changed. Reload it and try again.', + 'CONFLICT', + ) + const { workflow: _old, publishAt: _at, ...rest } = current + const publishAt = + changeSetPublishAt === undefined + ? current.publishAt + : changeSetPublishAt || undefined + updated = { + ...rest, + version: (current.version ?? 0) + 1, + ...(workflow ? { workflow } : {}), + ...(publishAt ? { publishAt } : {}), + } + await tx.putPending(updated) + changeSet = updated + } + if (stale) { + const open = await tx.getPendingFor(write.collection, write.docId) + if ( + open?.id !== stale.pending.id || + (open.version ?? 0) !== (stale.pending.version ?? 0) + ) + throw new CmsError( + "The document's change set changed while this was saved. Try again.", + 'CONFLICT', + { pendingId: stale.pending.id }, + ) + if (!stale.invalidate) { + if (committed) { + await tx.putPending(rebaseChangeSet(open, committed, stale.touched)) } + } else { + await tx.deletePending(open.id) + for (const effect of stale.invalidate) { + if (effect.type !== 'emit') continue + await enqueueEmit(tx, effect, open, { + collection: write.collection, + docId: write.docId, + actor: eventActor, + author: open.actor, + at: now, + }) + } + await recordAudit(tx, { + id: open.id, + collection: write.collection, + docId: write.docId, + type: open.type, + actor: auditActor, + action: 'discard', + decision: 'discarded', + changeSet: open.id, + from: stale.from, + to: null, + effects: asJson(stale.invalidate), + reason: 'stale', + at: now, + }) + invalidated = open } } - const decisionValue = auditDecision(action, effects) + const decisionValue = auditDecision( + action, + effects, + onChangeSet, + storesState, + ) if (decisionValue && commitType !== 'delete') { - const target = actsOnChangeSet ? (changeSet ?? loaded.pending) : null + const target = + actsOnChangeSet || has('stage') ? (changeSet ?? loaded.pending) : null + const survives = target !== null && !closesChangeSet await recordAudit(tx, { - ...(target ? { id: target.id } : {}), + ...(target && closesChangeSet ? { id: target.id } : {}), collection: write.collection, docId: write.docId, type: commitType ?? target?.type ?? 'update', actor: auditActor, action: action.type, decision: decisionValue, + ...(target ? { changeSet: target.id } : {}), + from: stateOf(loaded), + to: (survives ? (workflow?.state ?? null) : null) as JsonValue, + effects: asJson(effects), at: now, }) } @@ -887,7 +1310,6 @@ export async function executeStrategyWrite( return final } - const key = strategyKey(strategy) if (!outcome) { return { strategy: key, @@ -901,7 +1323,8 @@ export async function executeStrategyWrite( } notifyStorageCommit() const decidedPending: Pending | null = - staged ?? (actsOnChangeSet ? loaded.pending : null) + staged ?? updated ?? (actsOnChangeSet ? loaded.pending : null) + if (invalidated) await cleanupDiscarded(invalidated) if (committed) { const doc: Doc = committed await runAfterChange(collection, { @@ -920,7 +1343,7 @@ export async function executeStrategyWrite( } if (deleted !== undefined) { await runAfterDelete(collection, { id: write.docId, actor: author }) - emitCmsEvent('delete', { + emitCmsEvent('document.deleted', { collection: write.collection, id: write.docId, actor: eventActor, diff --git a/packages/core/src/server/store/internal.ts b/packages/core/src/server/store/internal.ts index c9507ace..1e053482 100644 --- a/packages/core/src/server/store/internal.ts +++ b/packages/core/src/server/store/internal.ts @@ -18,7 +18,7 @@ import { import { isLocalizedValue, primaryLocaleValue } from '../../i18n' import { stampContentVersion, upgradeStoredDoc } from '../content-migrations' import { denormalize } from '../indexing' -import { emitCmsEvent } from '../events' +import { commitEvents, emitCmsEvent, stayedLive } from '../events' import { collectRelations } from './relations' import type { Collection, @@ -497,19 +497,16 @@ export function emitCommit( before: Doc | null, after: Doc, ): void { - emitCmsEvent('change', { - collection, - id, - actor, - doc: after, - previous: before, - }) - const wasPublished = Boolean(before?.published) - const isPublished = Boolean(after.published) - if (isPublished) { - emitCmsEvent('publish', { collection, id, actor, doc: after }) - } else if (wasPublished) { - emitCmsEvent('unpublish', { collection, id, actor, doc: after }) + const live = stayedLive(before, after) + for (const event of commitEvents(before, after)) { + emitCmsEvent(event, { + collection, + id, + actor, + doc: after, + previous: before, + stayedLive: live, + }) } } diff --git a/packages/core/src/server/store/scheduling.ts b/packages/core/src/server/store/scheduling.ts index ae917b20..12eae696 100644 --- a/packages/core/src/server/store/scheduling.ts +++ b/packages/core/src/server/store/scheduling.ts @@ -6,13 +6,18 @@ import { CmsError } from '../../errors' import { cmsLogger } from '../../config' import { systemContext } from '../access-context' -import { getStorage, registerScheduledSweep } from '../storage' +import { + duePendingPublishes, + getStorage, + registerScheduledSweep, +} from '../storage' import { executeStrategyWrite } from './document-state' import { readDocument } from './read' import { stageWrite } from './review' import { commitDocument } from './write' import type { Doc } from '../../schema' import type { IndexedDocumentRecord, StorageAdapter } from '../../storage/types' +import type { AccessContext } from '../../lib/access-context' import type { Pending } from './internal' const SCHEDULER = systemContext('scheduled publishing', { actor: 'scheduler' }) @@ -49,6 +54,37 @@ async function applyScheduledDocument( return !outcome.skipped } +/** + * Fire the strategy's `publish` action as the scheduler on a change set whose + * publish time came (`input.changeSet` names it). Skips (returns false) when + * the change set changed or was decided since the sweep found it due. + */ +async function applyScheduledChangeSet( + pending: Pending, + nowIso: string, +): Promise { + const outcome = await executeStrategyWrite({ + ctx: SCHEDULER, + by: 'scheduler', + collection: pending.collection, + docId: pending.docId, + action: { type: 'publish', input: { changeSet: pending.id } }, + pending, + author: pending.actor, + summary: `Auto-published on schedule (${pending.publishAt ?? nowIso})`, + at: nowIso, + async precondition(tx) { + const current = await tx.getPending(pending.id) + return ( + current !== null && + (current.version ?? 0) === (pending.version ?? 0) && + current.publishAt === pending.publishAt + ) + }, + }) + return !outcome.skipped +} + export interface ScheduledPublishResult { collection: string id: string @@ -61,6 +97,21 @@ async function publishDue( ): Promise> { const due = await storage.findDueScheduled(nowIso) const out: Array = [] + for (const pending of await duePendingPublishes(storage, nowIso)) { + try { + if (await applyScheduledChangeSet(pending, nowIso)) + out.push({ + collection: pending.collection, + id: pending.docId, + publishedAt: nowIso, + }) + } catch (err) { + cmsLogger().error( + `[tanstack-cms] scheduled publish failed for change set ${pending.id} (${pending.collection}/${pending.docId}):`, + err, + ) + } + } for (const row of due) { const publishAt = typeof row.doc.publishAt === 'string' ? row.doc.publishAt : '' @@ -109,10 +160,10 @@ async function publishDue( registerScheduledSweep(publishDue) /** - * Publish every scheduled draft whose `publishAt <= nowIso`, and unpublish - * every live document whose `unpublishAt <= nowIso`. Also runs - * automatically (throttled to once per second) as the store is used; call it - * from a cron job for exact timing on idle sites. + * Publish every change set and unpublished document whose `publishAt <= + * nowIso`, and unpublish every live document whose `unpublishAt <= nowIso`. + * Also runs automatically (throttled to once per second) as the store is + * used; call it from a cron job for exact timing on idle sites. */ export async function runScheduledPublishing( nowIso?: string, @@ -120,12 +171,19 @@ export async function runScheduledPublishing( return publishDue(await getStorage(), nowIso) } -/** Set (or clear with `null`/`""`) a document's `publishAt` schedule. */ +/** + * Set (or clear with `null`/`""`) when a document goes live. + * + * An unpublished document is scheduled itself: it stays down until + * `publishAt`. A published document stays up: its open change set (a draft + * or proposal) is scheduled instead, and the scheduler publishes it then. A + * published document with no change set has nothing to schedule. + */ export async function scheduleDocument( collectionName: string, docId: string, publishAt: string | null, - options?: { actor?: string; stage?: boolean }, + options?: { actor?: string; stage?: boolean; ctx?: AccessContext }, ): Promise { const existing = await readDocument(collectionName, docId) if (!existing) { @@ -139,6 +197,34 @@ export async function scheduleDocument( throw new CmsError(`Invalid publishAt datetime: "${clean}"`, 'BAD_REQUEST') } const isFuture = clean !== '' && clean > new Date().toISOString() + if (existing.published && !options?.stage) { + const storage = await getStorage() + const open = await storage.getPendingFor(collectionName, docId) + if (open) { + const outcome = await executeStrategyWrite({ + ctx: options?.ctx ?? systemContext('scheduleDocument'), + by: options?.actor ?? 'human', + collection: collectionName, + docId, + action: { type: 'schedule', input: { publishAt: clean || null } }, + pending: open, + async precondition(tx) { + const current = await tx.getPending(open.id) + if (!current || (current.version ?? 0) !== (open.version ?? 0)) + throw new CmsError( + 'The pending document changed. Reload it before scheduling.', + 'CONFLICT', + ) + }, + }) + return outcome.pending ?? open + } + if (isFuture) + throw new CmsError( + `${collectionName}/${docId} is already published, with no pending change to schedule. Save a draft first, then schedule it.`, + 'BAD_REQUEST', + ) + } const next: Record = { ...existing, publishAt: clean || undefined, diff --git a/packages/core/src/server/store/write.ts b/packages/core/src/server/store/write.ts index 9f5ca1eb..c0ff7eb9 100644 --- a/packages/core/src/server/store/write.ts +++ b/packages/core/src/server/store/write.ts @@ -33,7 +33,7 @@ import type { AccessContext } from '../access-context' import type { CmsSession } from '../../lib/auth' import type { Doc } from '../../schema' import type { Pending } from './internal' -import type { StorageOps } from '../../storage/types' +import type { AuditRecord, StorageOps } from '../../storage/types' export interface CommitOptions { actor?: string @@ -201,7 +201,7 @@ export async function deleteDocument( }) notifyStorageCommit() await runAfterDelete(collection, { id, actor }) - emitCmsEvent('delete', { + emitCmsEvent('document.deleted', { collection: collectionName, id, actor, @@ -269,6 +269,8 @@ export async function commitDeletion( auditActor?: string /** The strategy action audited with the deletion. */ auditAction?: string + /** The decision's change set, from / to state and effects, for the audit row. */ + auditTransition?: Pick /** The `document.deleted` event's actor (default `actor`). */ eventActor?: string /** Who proposed the deletion, when `eventActor` decided it. */ @@ -340,6 +342,7 @@ export async function commitDeletion( actor: options.auditActor ?? actor, ...(options.auditAction ? { action: options.auditAction } : {}), decision: 'approved', + ...options.auditTransition, at: now, }) await enqueueDocumentDelete(tx, { @@ -397,6 +400,7 @@ export async function commitDeletion( actor: options.auditActor ?? actor, ...(options.auditAction ? { action: options.auditAction } : {}), decision: 'approved', + ...options.auditTransition, at: now, }) await enqueueDocumentDelete(tx, { diff --git a/packages/core/src/server/transfer.ts b/packages/core/src/server/transfer.ts index d8483785..bc6013cf 100644 --- a/packages/core/src/server/transfer.ts +++ b/packages/core/src/server/transfer.ts @@ -482,6 +482,7 @@ export async function importContent( change: existing.has(k) ? 'update' : 'create', rule: 'strategy', reason: `The "${decision.strategy.id}" strategy did not commit an imported document; import with { stage: true } to stage it.`, + from: null, } return } diff --git a/packages/core/src/server/webhooks.ts b/packages/core/src/server/webhooks.ts index 8be418db..94d2450f 100644 --- a/packages/core/src/server/webhooks.ts +++ b/packages/core/src/server/webhooks.ts @@ -12,7 +12,8 @@ * manual replays. */ import { getCmsConfig } from '../config' -import type { CmsEvent, CmsWebhook, CmsWebhookEvent } from '../config' +import { cmsEventMatches } from './events' +import type { CmsEvent, CmsWebhook } from '../config' /** The JSON body of a delivery: the content event that triggered it. */ export type WebhookPayload = CmsEvent @@ -34,11 +35,6 @@ export interface WebhookAttempt { error?: string } -const DEFAULT_EVENTS: ReadonlyArray = [ - 'publish', - 'unpublish', - 'delete', -] const RETRY_DELAYS_MS = [500, 2000] const TIMEOUT_MS = 10_000 @@ -146,9 +142,22 @@ export async function deliverWebhook( return last } -/** Whether `hook` subscribes to this event + collection (per-hook scoping). */ -export function webhookMatches(hook: CmsWebhook, event: CmsEvent): boolean { - if (!(hook.events ?? DEFAULT_EVENTS).includes(event.event)) return false +/** + * Whether `hook` subscribes to this event + collection (per-hook scoping). + * `stayedLive`: the document was live before and after the commit. Without + * an `events` list a hook gets what a public site shows changing: + * publishes, unpublishes, deletes, and updates of a live document. + */ +export function webhookMatches( + hook: CmsWebhook, + event: CmsEvent, + stayedLive = false, +): boolean { + const subscribed = hook.events + ? hook.events.some((name) => cmsEventMatches(name, event.event, stayedLive)) + : event.event !== 'document.created' && + (event.event !== 'document.updated' || stayedLive) + if (!subscribed) return false if (hook.collections && !hook.collections.includes(event.collection)) { return false } @@ -156,7 +165,10 @@ export function webhookMatches(hook: CmsWebhook, event: CmsEvent): boolean { } /** The configured webhooks subscribed to `event` (empty when none / no config). */ -export function matchingWebhooks(event: CmsEvent): Array { +export function matchingWebhooks( + event: CmsEvent, + stayedLive = false, +): Array { let hooks: Array | undefined try { hooks = getCmsConfig().webhooks @@ -164,7 +176,7 @@ export function matchingWebhooks(event: CmsEvent): Array { return [] } if (!hooks?.length) return [] - return hooks.filter((hook) => webhookMatches(hook, event)) + return hooks.filter((hook) => webhookMatches(hook, event, stayedLive)) } /** diff --git a/packages/core/src/storage/conformance.ts b/packages/core/src/storage/conformance.ts index 76109457..684bb20e 100644 --- a/packages/core/src/storage/conformance.ts +++ b/packages/core/src/storage/conformance.ts @@ -585,6 +585,135 @@ export function runStorageConformance( ]) })) + it('round-trips change-set workflow state and schedule, and finds due change sets', () => + withStorage(async (s) => { + await seedPosts(s) + const base = { + collection: 'post', + type: 'update' as const, + before: { title: 'Hello world' }, + after: { title: 'Hello again' }, + actor: 'editor', + createdAt: now, + source: 'review' as const, + } + const state = { legal: 'approved', editorial: 'pending' } + await s.putPending({ + ...base, + id: 'w1', + docId: 'a', + version: 2, + workflow: { strategy: 'legal-review@1', state }, + publishAt: '2026-02-01T00:00:00.000Z', + }) + await s.putPending({ + ...base, + id: 'w2', + docId: 'b', + workflow: { strategy: 'review@1', state: 'pending_review' }, + publishAt: '2026-03-01T00:00:00.000Z', + }) + await s.putPending({ ...base, id: 'w3', docId: 'c' }) + expect(await s.getPending('w1')).toMatchObject({ + version: 2, + workflow: { strategy: 'legal-review@1', state }, + publishAt: '2026-02-01T00:00:00.000Z', + }) + expect((await s.getPendingFor('post', 'b'))?.workflow).toEqual({ + strategy: 'review@1', + state: 'pending_review', + }) + const plain = await s.getPending('w3') + expect(plain?.workflow).toBeUndefined() + expect(plain?.publishAt).toBeUndefined() + + if (s.findDuePendingPublish) { + expect( + await s.findDuePendingPublish('2026-01-31T00:00:00.000Z'), + ).toEqual([]) + expect( + (await s.findDuePendingPublish('2026-03-02T00:00:00.000Z')).map( + (p) => p.id, + ), + ).toEqual(['w1', 'w2']) + } + // Clearing the schedule and state on a re-put. + const w1 = await s.getPending('w1') + if (!w1) throw new Error('pending w1 missing') + const { publishAt: _cleared, workflow: _gone, ...rest } = w1 + await s.putPending({ ...rest, version: 3 }) + expect(await s.getPending('w1')).toMatchObject({ version: 3 }) + expect((await s.getPending('w1'))?.publishAt).toBeUndefined() + expect((await s.getPending('w1'))?.workflow).toBeUndefined() + if (s.findDuePendingPublish) { + expect( + (await s.findDuePendingPublish('2026-03-02T00:00:00.000Z')).map( + (p) => p.id, + ), + ).toEqual(['w2']) + } + })) + + it('round-trips audit transition fields', () => + withStorage(async (s) => { + await s.insertAudit({ + id: 't1', + collection: 'post', + docId: 'a', + type: 'update', + actor: 'user:lee', + action: 'approve:legal', + decision: 'transitioned', + changeSet: 'chg_9', + from: { legal: 'pending', editorial: 'pending' }, + to: { legal: 'approved', editorial: 'pending' }, + effects: [], + at: '2026-01-01T00:00:00.000Z', + }) + await s.insertAudit({ + id: 't2', + collection: 'post', + docId: 'a', + actor: 'agent', + action: 'publish', + decision: 'refused', + from: null, + reason: "Agents can't publish.", + at: '2026-01-02T00:00:00.000Z', + }) + await s.insertAudit({ + id: 't3', + collection: 'post', + docId: 'a', + actor: 'human', + action: 'discard', + decision: 'discarded', + changeSet: 'chg_9', + effects: [{ type: 'discard' }, { type: 'emit', event: 'x' }], + reason: 'stale', + at: '2026-01-03T00:00:00.000Z', + }) + const [discarded, refused, transitioned] = await s.listAudit() + expect(transitioned).toMatchObject({ + changeSet: 'chg_9', + from: { legal: 'pending', editorial: 'pending' }, + to: { legal: 'approved', editorial: 'pending' }, + effects: [], + }) + expect(transitioned?.reason).toBeUndefined() + expect(refused).toMatchObject({ + decision: 'refused', + from: null, + reason: "Agents can't publish.", + }) + expect(refused?.to).toBeUndefined() + expect(refused?.effects).toBeUndefined() + expect(discarded).toMatchObject({ + reason: 'stale', + effects: [{ type: 'discard' }, { type: 'emit', event: 'x' }], + }) + })) + it('stores threaded editorial comments with open counts', () => withStorage(async (s) => { // Comment ops are an optional capability; skip adapters without them. diff --git a/packages/core/src/storage/migrations.ts b/packages/core/src/storage/migrations.ts index 38366230..aff2f98c 100644 --- a/packages/core/src/storage/migrations.ts +++ b/packages/core/src/storage/migrations.ts @@ -534,6 +534,31 @@ export const SQL_MIGRATIONS: Array = [ `) }, }, + { + version: 16, + name: 'document state: workflow state and schedule on change sets, transitions on audit', + up: async (db) => { + if ((await columnNames(db, 'pending')).size) { + await addColumns(db, 'pending', [ + ['workflow_strategy', 'TEXT'], + ['workflow_state', 'TEXT'], + ['publish_at', 'TEXT'], + ]) + await db.exec( + `CREATE INDEX IF NOT EXISTS idx_pending_publish_at ON pending(publish_at) WHERE publish_at IS NOT NULL`, + ) + } + if ((await columnNames(db, 'audit')).size) { + await addColumns(db, 'audit', [ + ['change_set', 'TEXT'], + ['from_state', 'TEXT'], + ['to_state', 'TEXT'], + ['effects', 'TEXT'], + ['reason', 'TEXT'], + ]) + } + }, + }, ] export const LATEST_SCHEMA_VERSION = diff --git a/packages/core/src/storage/sql-storage.ts b/packages/core/src/storage/sql-storage.ts index dc08e2fa..c84648c7 100644 --- a/packages/core/src/storage/sql-storage.ts +++ b/packages/core/src/storage/sql-storage.ts @@ -79,8 +79,31 @@ interface PendingRow { source: PendingSource | null base_revision: number | null proposal_version: number + workflow_strategy: string | null + workflow_state: string | null + publish_at: string | null +} + +interface AuditRow { + id: string + collection: string | null + doc_id: string | null + type: WriteType | null + actor: string + decision: AuditDecision | null + action: string | null + target: string | null + at: string + change_set: string | null + from_state: string | null + to_state: string | null + effects: string | null + reason: string | null } +const jsonOrNull = (value: JsonValue | undefined): string | null => + value === undefined ? null : JSON.stringify(value) + interface MediaRow { id: string key: string @@ -147,9 +170,37 @@ function toPending(r: PendingRow): PendingRecord { ...(typeof r.base_revision === 'number' ? { baseRevision: Number(r.base_revision) } : {}), + ...(r.workflow_strategy + ? { + workflow: { + strategy: r.workflow_strategy, + state: (r.workflow_state === null + ? null + : JSON.parse(r.workflow_state)) as JsonValue, + }, + } + : {}), + ...(r.publish_at ? { publishAt: r.publish_at } : {}), } } +function toAudit(r: AuditRow): AuditRecord { + const record: AuditRecord = { id: r.id, actor: r.actor, at: r.at } + if (r.action != null) record.action = r.action + if (r.target != null) record.target = r.target + if (r.collection != null) record.collection = r.collection + if (r.doc_id != null) record.docId = r.doc_id + if (r.type != null) record.type = r.type + if (r.decision != null) record.decision = r.decision + if (r.change_set != null) record.changeSet = r.change_set + if (r.from_state != null) record.from = JSON.parse(r.from_state) as JsonValue + if (r.to_state != null) record.to = JSON.parse(r.to_state) as JsonValue + if (r.effects != null) + record.effects = JSON.parse(r.effects) as Array + if (r.reason != null) record.reason = r.reason + return record +} + function parseTags(raw: string | null): Array | undefined { if (!raw) return undefined try { @@ -804,14 +855,17 @@ function opsFor(db: SqlExecutor): StorageOps { async putPending(p: PendingRecord) { await db.run( `INSERT INTO pending - (id, collection, doc_id, type, before_doc, after_doc, actor, instruction, created_at, source, base_revision, proposal_version) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + (id, collection, doc_id, type, before_doc, after_doc, actor, instruction, created_at, source, base_revision, proposal_version, workflow_strategy, workflow_state, publish_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET type = excluded.type, before_doc = excluded.before_doc, after_doc = excluded.after_doc, actor = excluded.actor, instruction = excluded.instruction, created_at = excluded.created_at, source = excluded.source, base_revision = excluded.base_revision, - proposal_version = excluded.proposal_version`, + proposal_version = excluded.proposal_version, + workflow_strategy = excluded.workflow_strategy, + workflow_state = excluded.workflow_state, + publish_at = excluded.publish_at`, [ p.id, p.collection, @@ -825,10 +879,22 @@ function opsFor(db: SqlExecutor): StorageOps { p.source, p.baseRevision ?? null, p.version ?? 0, + p.workflow?.strategy ?? null, + p.workflow ? jsonOrNull(p.workflow.state) : null, + p.publishAt ?? null, ], ) }, + async findDuePendingPublish(nowIso) { + const rows = await db.all( + `SELECT * FROM pending WHERE publish_at IS NOT NULL AND publish_at <= ? + ORDER BY publish_at, rowid`, + [nowIso], + ) + return rows.map(toPending) + }, + async deletePending(id) { await db.run(`DELETE FROM pending WHERE id = ?`, [id]) }, @@ -893,36 +959,17 @@ function opsFor(db: SqlExecutor): StorageOps { async listAudit(page) { const params: Array = [] - const rows = await db.all<{ - id: string - collection: string | null - doc_id: string | null - type: WriteType | null - actor: string - decision: AuditDecision | null - action: string | null - target: string | null - at: string - }>( + const rows = await db.all( `SELECT * FROM audit ORDER BY at DESC, rowid DESC${pageClause(page, params)}`, params, ) - return rows.map((r): AuditRecord => { - const record: AuditRecord = { id: r.id, actor: r.actor, at: r.at } - if (r.action != null) record.action = r.action - if (r.target != null) record.target = r.target - if (r.collection != null) record.collection = r.collection - if (r.doc_id != null) record.docId = r.doc_id - if (r.type != null) record.type = r.type - if (r.decision != null) record.decision = r.decision - return record - }) + return rows.map(toAudit) }, async insertAudit(a: AuditRecord) { await db.run( - `INSERT OR REPLACE INTO audit (id, collection, doc_id, type, actor, decision, action, target, at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT OR REPLACE INTO audit (id, collection, doc_id, type, actor, decision, action, target, at, change_set, from_state, to_state, effects, reason) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ a.id, a.collection ?? null, @@ -933,6 +980,11 @@ function opsFor(db: SqlExecutor): StorageOps { a.action ?? null, a.target ?? null, a.at, + a.changeSet ?? null, + jsonOrNull(a.from), + jsonOrNull(a.to), + a.effects ? JSON.stringify(a.effects) : null, + a.reason ?? null, ], ) }, diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts index 88cd295b..9d8d7aa1 100644 --- a/packages/core/src/storage/types.ts +++ b/packages/core/src/storage/types.ts @@ -86,6 +86,16 @@ export interface PendingRecord { source: PendingSource /** `_revision` of the committed document when the change was staged. */ baseRevision?: number + /** + * The document state strategy's state for this change set, with the + * `id@version` of the strategy that wrote it. + */ + workflow?: { strategy: string; state: JsonValue } + /** + * When the scheduler publishes this change set: a scheduled update of a + * live document, which stays up until then. + */ + publishAt?: string } /** @@ -97,14 +107,21 @@ export interface PendingRecord { * such entries set `action` and `target` and omit the doc-centric fields. * * Document entries are written by the document state strategy executor for - * every decision that commits, discards or is refused: `action` names the - * strategy action (`edit`, `approve`, `reject`, `discard`, `publish`, - * `import`, …) and `decision` its outcome. Older document entries carry only + * every decision that stages, commits, discards, changes the change set's + * state or is refused: `action` names the strategy action (`edit`, `approve`, + * `reject`, `discard`, `publish`, `import`, …), `decision` its outcome, and + * `from` / `to` / `effects` the transition. Older document entries carry only * `decision`. An entry without `collection`/`docId` is an admin action. Never * store secrets here — log identifiers/prefixes only (e.g. an API-key prefix, * never its hash). */ -export type AuditDecision = 'approved' | 'rejected' | 'discarded' | 'refused' +export type AuditDecision = + | 'approved' + | 'rejected' + | 'discarded' + | 'refused' + | 'transitioned' + | 'staged' export interface AuditRecord { id: string @@ -129,9 +146,22 @@ export interface AuditRecord { * `approved`: the change was committed (or the live document published, * unpublished or rescheduled). `rejected`: a reviewer rejected it. * `discarded`: the change set was dropped. `refused`: core or the strategy - * refused the action, and nothing changed. + * refused the action, and nothing changed. `transitioned`: the change set + * stayed open in a new state (or with a new publish time), including a + * stage that stores strategy state. `staged`: the change was staged into + * the change set without strategy state. */ decision?: AuditDecision + /** The change set the decision acted on. */ + 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). */ + to?: JsonValue + /** The effects the decision ran, in order (none when refused). */ + effects?: Array + /** Why: a refusal's reason, or `stale` for an invalidated proposal. */ + reason?: string } export interface RevisionRecord { @@ -572,6 +602,11 @@ export interface StorageOps locale?: string, ) => Promise> putPending: (record: PendingRecord) => Promise + /** + * Change sets whose `publishAt` has passed, oldest first. Optional: the + * scheduler falls back to scanning `listPending`. + */ + findDuePendingPublish?: (nowIso: string) => Promise> deletePending: (id: string) => Promise deletePendingFor: (collection: string, docId: string) => Promise diff --git a/packages/core/tests/characterization/workflow-suite.ts b/packages/core/tests/characterization/workflow-suite.ts index 207a4d4d..7fbcf42c 100644 --- a/packages/core/tests/characterization/workflow-suite.ts +++ b/packages/core/tests/characterization/workflow-suite.ts @@ -16,8 +16,9 @@ * suffixed `[known bug, fixed in phase 4 (#N)]`, pin behaviour that was ruled * a bug on 2026-11-05 (cms-refactor-plan.md § Phase 4). They stay green until * phase 4 fixes the bug and updates the row in the same diff; rows marked - * `fixed in phase 4a (#N)` pin the fix. N is the decision number (phase 4a - * fixed #1, #3, #6, #8, #9 and #10): + * `fixed in phase 4a (#N)` or `fixed in phase 4b (#N)` pin the fix. N is the + * decision number (phase 4a fixed #1, #3, #6, #8, #9 and #10; phase 4b fixed + * #2, #4, #5 and #7): * #1 direct commits write no audit row * #2 bus/webhook `publish` fires on every save of a published doc * #3 discarding a draft is logged and emitted as a rejection @@ -29,6 +30,13 @@ * #9 events after approve carry the proposer, not the approver * #10 a coalesced stage without an instruction drops the earlier one * + * Rows labelled `decided in phase 4 (2026-11-06): one event vocabulary` + * changed with the coordinator's ruling that the in-process bus, webhooks and + * the SSE stream use the durable `document.*` names (the short names stay as + * deprecated subscription aliases). Rows labelled `decided in phase 4 + * (2026-11-06): stage decisions are audited` changed with the coordinator's ruling that 4a's mandatory-audit + * rule covers stage-only decisions: they used to pin "no audit" for a stage. + * * Shared by the storage adapters: core runs it on the built-in SQLite * storage, `@tanstack/cms-store-libsql` on libsql and * `@tanstack/cms-store-postgres` on Postgres. @@ -74,6 +82,7 @@ const DURABLE_EVENTS = [ 'review.submitted', 'review.approved', 'review.rejected', + 'review.discarded', 'document.created', 'document.updated', 'document.published', @@ -182,6 +191,27 @@ export function runWorkflowCharacterization( decision: 'approved', }) + /** + * The audit row of a stage-only decision. The review built-in stores + * `pending_review` for a submission and `draft` for a draft, so it is + * `transitioned` from no change set. + */ + const stageAudit = ( + actor: string, + action: 'submit' | 'draft', + fields: Record = {}, + ) => + expect.objectContaining({ + type: 'update', + actor, + action, + decision: 'transitioned', + from: null, + to: action === 'submit' ? 'pending_review' : 'draft', + effects: expect.arrayContaining([{ type: 'stage' }]), + ...fields, + }) + async function publicTitle(): Promise { const found = await readDocumentBySlug('post', 'p1', { publishedOnly: true, @@ -190,7 +220,7 @@ export function runWorkflowCharacterization( } describe('stageWrite', () => { - it('stage create: one pending entry (version 1, source agent); nothing live, no revision, no audit; emits review.submitted only', async () => { + it('stage create: one pending entry (version 1, source agent); nothing live, no revision, audit staged; emits review.submitted only', async () => { setup() const pending = await stageWrite({ collection: 'post', @@ -216,7 +246,13 @@ export function runWorkflowCharacterization( expect(await readDocument('post', 'p1')).toBeNull() expect(await publicTitle()).toBeUndefined() expect(await listRevisions('post', 'p1')).toEqual([]) - expect(await auditFor('p1')).toEqual([]) + // decided in phase 4 (2026-11-06): stage decisions are audited. + expect(await auditFor('p1')).toEqual([ + stageAudit('agent', 'submit', { + type: 'create', + changeSet: pending.id, + }), + ]) expect(await drainDurable()).toEqual(['review.submitted by agent']) expect(takeBus()).toEqual([]) }) @@ -377,7 +413,7 @@ export function runWorkflowCharacterization( }) describe('approve (commits; there is no "approved" state)', () => { - it('approve update: live doc replaced, revision +1, pending row deleted, audit approved under the pending id; events name the approver [known bug, fixed in phase 4 (#2)]', async () => { + it('approve update: live doc replaced, revision +1, pending row deleted, audit approved under the pending id; events name the approver; the bus says document.updated, not a publish', async () => { setup() await seedLive() const pending = await stageWrite({ @@ -411,6 +447,7 @@ export function runWorkflowCharacterization( }) // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is // audited too. + // decided in phase 4 (2026-11-06): stage decisions are audited. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: pending.id, @@ -421,6 +458,7 @@ export function runWorkflowCharacterization( action: 'approve', decision: 'approved', }), + stageAudit('agent', 'submit', { changeSet: pending.id }), seedAudit(), ]) // fixed in phase 4a (#9: approver as event actor) — events carry the @@ -429,13 +467,12 @@ export function runWorkflowCharacterization( 'document.updated by reviewer (author agent)', 'review.approved by reviewer (author agent)', ]) - // known bug, fixed in phase 4 (#2: publish event on every save) — - // the bus fires `publish` on every commit of a published doc, not - // only on the unpublished → published transition the outbox uses. - expect(takeBus()).toEqual([ - 'change by reviewer', - 'publish by reviewer', - ]) + // fixed in phase 4b (#2: publish event on every save) — the doc was + // already live, so the bus fires no publish event; that is kept for + // the unpublished → published transition. + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.updated by reviewer']) }) it('approve create of a published proposal: document.created + document.published; default summary names the proposer', async () => { @@ -466,7 +503,12 @@ export function runWorkflowCharacterization( 'document.published by agent', 'review.approved by agent', ]) - expect(takeBus()).toEqual(['change by agent', 'publish by agent']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual([ + 'document.created by agent', + 'document.published by agent', + ]) }) it('approve({ publish }) overrides the proposed published flag', async () => { @@ -483,7 +525,7 @@ export function runWorkflowCharacterization( expect(await publicTitle()).toBe('New') }) - it('stale approve: CONFLICT while the live revision moved past baseRevision; force overwrites [known bug, fixed in phase 4 (#5)]', async () => { + it('stale approve: a direct commit of the same field invalidates the proposal (audited discard, reason stale); approve is NOT_FOUND', async () => { setup() await seedLive() const pending = await stageWrite({ @@ -498,17 +540,30 @@ export function runWorkflowCharacterization( slug: 'p1', published: true, }) - // known bug, fixed in phase 4 (#5: stale proposal after direct - // commit) — the direct commit above leaves the proposal stale. + // fixed in phase 4b (#5: stale proposal after direct commit) — both + // changed the title, so the commit invalidates the proposal and the + // proposer is told why. await expect(approve(pending.id)).rejects.toMatchObject({ - code: 'CONFLICT', - details: { baseRevision: 1, actualRevision: 2 }, + code: 'NOT_FOUND', }) - await approve(pending.id, { force: true }) + expect(await listPending()).toEqual([]) expect(await readDocument('post', 'p1')).toMatchObject({ - title: 'Agent', - _revision: 3, + title: 'Human', + _revision: 2, + }) + expect( + (await auditFor('p1')).find((a) => a.decision === 'discarded'), + ).toMatchObject({ + id: pending.id, + changeSet: pending.id, + action: 'discard', + reason: 'stale', }) + expect(await drainDurable()).toEqual([ + 'document.updated by human', + 'review.discarded by human (author agent)', + 'review.submitted by agent', + ]) }) it('approve guards: unknown id is NOT_FOUND; a stale expectedVersion is CONFLICT', async () => { @@ -529,7 +584,7 @@ export function runWorkflowCharacterization( expect(await getPending(pending.id)).not.toBeNull() }) - it('approve delete: soft delete (revision +1, deletedAt), audit approved type delete, document.deleted + review.approved by the approver, bus delete', async () => { + it('approve delete: soft delete (revision +1, deletedAt), audit approved type delete, document.deleted + review.approved by the approver, bus document.deleted', async () => { setup() await seedLive() const pending = await stageWrite({ @@ -548,6 +603,7 @@ export function runWorkflowCharacterization( ).toMatchObject({ _revision: 2, deletedAt: expect.any(String) }) // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is // audited too. + // decided in phase 4 (2026-11-06): stage decisions are audited. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: pending.id, @@ -555,6 +611,10 @@ export function runWorkflowCharacterization( decision: 'approved', actor: 'agent (approved by reviewer)', }), + stageAudit('agent', 'submit', { + type: 'delete', + changeSet: pending.id, + }), seedAudit(), ]) // fixed in phase 4a (#9: approver as event actor) — the events @@ -563,7 +623,9 @@ export function runWorkflowCharacterization( 'document.deleted by reviewer (author agent)', 'review.approved by reviewer (author agent)', ]) - expect(takeBus()).toEqual(['delete by reviewer']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.deleted by reviewer']) }) }) @@ -589,6 +651,7 @@ export function runWorkflowCharacterization( expect(await listRevisions('post', 'p1')).toHaveLength(1) // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is // audited too. + // decided in phase 4 (2026-11-06): stage decisions are audited. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: pending.id, @@ -597,6 +660,7 @@ export function runWorkflowCharacterization( decision: 'rejected', actor: 'agent (rejected by reviewer)', }), + stageAudit('agent', 'submit', { changeSet: pending.id }), seedAudit(), ]) expect(await drainDurable()).toEqual([ @@ -610,7 +674,7 @@ export function runWorkflowCharacterization( }) describe('drafts (pending source "draft")', () => { - it('saveDraft of a live doc: pending source draft, live unchanged, no review.submitted, no audit for the draft', async () => { + it('saveDraft of a live doc: pending source draft, live unchanged, no review.submitted, audit staged', async () => { setup() await seedLive() const draft = await saveDraft( @@ -626,17 +690,21 @@ export function runWorkflowCharacterization( baseRevision: 1, }) expect(await publicTitle()).toBe('Hello') - // fixed in phase 4a (#1: direct commit audit) — only seedLive's - // commit is audited; staging a draft is not a decision. - expect(await auditFor('p1')).toEqual([seedAudit()]) + // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is + // audited too. + // decided in phase 4 (2026-11-06): stage decisions are audited. + expect(await auditFor('p1')).toEqual([ + stageAudit('human', 'draft', { changeSet: draft.id }), + seedAudit(), + ]) expect(await drainDurable()).toEqual([]) expect(takeBus()).toEqual([]) }) - it('commitDocument publishes a draft: folds it in (pending deleted), revision +1, audit approved [known bug, fixed in phase 4 (#2)]', async () => { + it('commitDocument publishes a draft: folds it in (pending deleted), revision +1, audit approved; the bus says document.updated', async () => { setup() await seedLive() - await saveDraft('post', 'p1', { + const draft = await saveDraft('post', 'p1', { title: 'Draft edit', slug: 'p1', published: true, @@ -651,6 +719,7 @@ export function runWorkflowCharacterization( expect(await publicTitle()).toBe('Draft edit') // fixed in phase 4a (#1: direct commit audit) — direct commits are // audited. + // decided in phase 4 (2026-11-06): stage decisions are audited. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ type: 'update', @@ -658,12 +727,15 @@ export function runWorkflowCharacterization( action: 'edit', decision: 'approved', }), + stageAudit('human', 'draft', { changeSet: draft.id }), seedAudit(), ]) expect(await drainDurable()).toEqual(['document.updated by human']) - // known bug, fixed in phase 4 (#2: publish event on every save) — - // the doc was already live, yet the bus fires `publish` again. - expect(takeBus()).toEqual(['change by human', 'publish by human']) + // fixed in phase 4b (#2: publish event on every save) — the doc was + // already live, so the bus fires an update, not a publish. + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.updated by human']) }) it('discardDraft: deletes the draft — audit discarded, no review.rejected', async () => { @@ -686,6 +758,7 @@ export function runWorkflowCharacterization( // logged as a discard and emits nothing. // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is // audited too. + // decided in phase 4 (2026-11-06): stage decisions are audited. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: draft.id, @@ -693,6 +766,7 @@ export function runWorkflowCharacterization( decision: 'discarded', actor: 'human (discarded by editor)', }), + stageAudit('human', 'draft', { changeSet: draft.id }), seedAudit(), ]) expect(await drainDurable()).toEqual([]) @@ -713,7 +787,7 @@ export function runWorkflowCharacterization( expect(await listPending()).toHaveLength(1) }) - it('one pending entry per doc across sources: a draft save absorbs an agent proposal (source becomes draft) [known bug, fixed in phase 4 (#4)]', async () => { + it('one pending entry per doc across sources: a draft save over an open agent proposal is a CONFLICT naming it; the proposal stays in review', async () => { setup() await seedLive() const proposal = await stageWrite({ @@ -723,25 +797,29 @@ export function runWorkflowCharacterization( doc: { title: 'Agent', slug: 'p1', published: true }, actor: 'agent', }) - const draft = await saveDraft('post', 'p1', { - title: 'Human draft', - slug: 'p1', - published: true, - }) - // known bug, fixed in phase 4 (#4: pending mixes sources) — the - // agent's proposal silently becomes the human's draft and leaves - // review. - expect(draft).toMatchObject({ - id: proposal.id, - version: 2, - source: 'draft', - actor: 'human', - after: { title: 'Human draft' }, + // fixed in phase 4b (#4: pending mixes sources) — another source's + // open change set refuses the write until it's resolved. + await expect( + saveDraft('post', 'p1', { + title: 'Human draft', + slug: 'p1', + published: true, + }), + ).rejects.toMatchObject({ + code: 'CONFLICT', + details: { pendingId: proposal.id, source: 'agent' }, }) - expect(await listPending()).toHaveLength(1) + expect(await listPending()).toEqual([ + expect.objectContaining({ + id: proposal.id, + version: 1, + source: 'agent', + after: expect.objectContaining({ title: 'Agent' }), + }), + ]) }) - it('one pending entry per doc across sources: an agent stage over a draft turns it into a proposal without review.submitted [known bug, fixed in phase 4 (#4)]', async () => { + it('one pending entry per doc across sources: an agent stage over an open draft is a CONFLICT naming it; the draft is kept', async () => { setup() await seedLive() const draft = await saveDraft('post', 'p1', { @@ -749,25 +827,29 @@ export function runWorkflowCharacterization( slug: 'p1', published: true, }) - const proposal = await stageWrite({ - collection: 'post', - docId: 'p1', - type: 'update', - doc: { title: 'Agent', slug: 'p1', published: true }, - actor: 'agent', + // fixed in phase 4b (#4: pending mixes sources) — another source's + // open change set refuses the write until it's resolved. + await expect( + stageWrite({ + collection: 'post', + docId: 'p1', + type: 'update', + doc: { title: 'Agent', slug: 'p1', published: true }, + actor: 'agent', + }), + ).rejects.toMatchObject({ + code: 'CONFLICT', + details: { pendingId: draft.id, source: 'draft' }, }) - expect(proposal).toMatchObject({ - id: draft.id, - version: 2, - source: 'agent', + expect(await getPending(draft.id)).toMatchObject({ + version: 1, + source: 'draft', + after: { title: 'Human draft' }, }) - // known bug, fixed in phase 4 (#4: pending mixes sources) — the - // entry enters review but review.submitted only fires for a new - // entry. expect(await drainDurable()).toEqual([]) }) - it('commitDocument leaves a non-draft proposal in place, which then goes stale [known bug, fixed in phase 4 (#5)]', async () => { + it('commitDocument of other fields rebases a non-draft proposal onto the new revision; approving it keeps both changes', async () => { setup() await seedLive() const proposal = await stageWrite({ @@ -778,18 +860,24 @@ export function runWorkflowCharacterization( actor: 'agent', }) await commitDocument('post', 'p1', { - title: 'Human', - slug: 'p1', + title: 'Hello', + slug: 'p1-moved', published: true, }) - // known bug, fixed in phase 4 (#5: stale proposal after direct - // commit) — the proposal survives the commit and can't be approved. + // fixed in phase 4b (#5: stale proposal after direct commit) — the + // commit changed a field the proposal didn't, so the proposal moves + // onto the new revision instead of going stale. expect(await getPending(proposal.id)).toMatchObject({ source: 'agent', - baseRevision: 1, + version: 2, + baseRevision: 2, + after: { title: 'Agent', slug: 'p1-moved' }, }) - await expect(approve(proposal.id)).rejects.toMatchObject({ - code: 'CONFLICT', + await approve(proposal.id) + expect(await readDocument('post', 'p1')).toMatchObject({ + title: 'Agent', + slug: 'p1-moved', + _revision: 3, }) }) }) @@ -810,18 +898,22 @@ export function runWorkflowCharacterization( expect((await readDocument('post', 'p2'))?._revision).toBe(1) }) - it('create unpublished: document.created only, bus change only; edit: document.updated, bus change', async () => { + it('create unpublished: document.created only, on the outbox and the bus; edit: document.updated', async () => { setup() await commitDocument('post', 'p1', { title: 'v1', slug: 'p1' }) expect(await drainDurable()).toEqual(['document.created by human']) - expect(takeBus()).toEqual(['change by human']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.created by human']) await commitDocument('post', 'p1', { title: 'v2', slug: 'p1' }) expect(await drainDurable()).toEqual(['document.updated by human']) - expect(takeBus()).toEqual(['change by human']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.updated by human']) expect(await publicTitle()).toBeUndefined() }) - it('publish transition: document.updated + document.published; editing while published: document.updated only on the outbox, publish again on the bus [known bug, fixed in phase 4 (#2)]', async () => { + it('publish transition: document.updated + document.published; editing while published: document.updated only', async () => { setup() await commitDocument('post', 'p1', { title: 'v1', slug: 'p1' }) await drainDurable() @@ -835,19 +927,26 @@ export function runWorkflowCharacterization( 'document.published by human', 'document.updated by human', ]) - expect(takeBus()).toEqual(['change by human', 'publish by human']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual([ + 'document.updated by human', + 'document.published by human', + ]) await commitDocument('post', 'p1', { title: 'v2', slug: 'p1', published: true, }) expect(await drainDurable()).toEqual(['document.updated by human']) - // known bug, fixed in phase 4 (#2: publish event on every save) — - // an edit of a live doc fires `publish` again on the bus. - expect(takeBus()).toEqual(['change by human', 'publish by human']) + // fixed in phase 4b (#2: publish event on every save) — an edit of a + // live doc fires an update, not a publish. + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.updated by human']) }) - it('unpublishDocument: commits published false with publishAt cleared; document.unpublished, bus unpublish', async () => { + it('unpublishDocument: commits published false with publishAt cleared; document.updated + document.unpublished on the outbox and the bus', async () => { setup() await seedLive() const doc = await unpublishDocument('post', 'p1') @@ -860,7 +959,12 @@ export function runWorkflowCharacterization( 'document.unpublished by human', 'document.updated by human', ]) - expect(takeBus()).toEqual(['change by human', 'unpublish by human']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual([ + 'document.updated by human', + 'document.unpublished by human', + ]) }) it('expectedRevision mismatch is a CONFLICT and writes nothing', async () => { @@ -900,7 +1004,9 @@ export function runWorkflowCharacterization( seedAudit(), ]) expect(await drainDurable()).toEqual(['document.deleted by human']) - expect(takeBus()).toEqual(['delete by human']) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.deleted by human']) }) }) @@ -962,9 +1068,11 @@ export function runWorkflowCharacterization( 'document.published by scheduler', 'document.updated by scheduler', ]) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. expect(takeBus()).toEqual([ - 'change by scheduler', - 'publish by scheduler', + 'document.updated by scheduler', + 'document.published by scheduler', ]) expect(await runScheduledPublishing(AFTER_LATER)).toEqual([]) }) @@ -996,27 +1104,61 @@ export function runWorkflowCharacterization( 'document.unpublished by scheduler', 'document.updated by scheduler', ]) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. expect(takeBus()).toEqual([ - 'change by scheduler', - 'unpublish by scheduler', + 'document.updated by scheduler', + 'document.unpublished by scheduler', ]) }) - it('scheduling a future publish on a live doc takes it offline now [known bug, fixed in phase 4 (#7)]', async () => { + it('scheduling a future publish on a live doc schedules its change set: live stays up until the sweep publishes it as scheduler', async () => { setup() await seedLive() - await scheduleDocument('post', 'p1', LATER) - // known bug, fixed in phase 4 (#7: schedule unpublishes live doc) — - // the live version should stay up until publishAt. - expect(await readDocument('post', 'p1')).toMatchObject({ - published: false, + // fixed in phase 4b (#7: schedule unpublishes live doc) — a live doc + // with nothing pending has nothing to schedule. + await expect( + scheduleDocument('post', 'p1', LATER), + ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + const draft = await saveDraft('post', 'p1', { + title: 'Next', + slug: 'p1', + published: true, + }) + const scheduled = await scheduleDocument('post', 'p1', LATER) + // fixed in phase 4b (#7) — the schedule lands on the change set and + // the live version stays up until publishAt. + expect(scheduled).toMatchObject({ + id: draft.id, + version: 2, publishAt: LATER, }) - expect(await publicTitle()).toBeUndefined() + expect(await readDocument('post', 'p1')).toMatchObject({ + title: 'Hello', + published: true, + _revision: 1, + }) + expect(await publicTitle()).toBe('Hello') + expect(await drainDurable()).toEqual([]) + takeBus() + + expect(await runScheduledPublishing(AFTER_LATER)).toEqual([ + expect.objectContaining({ collection: 'post', id: 'p1' }), + ]) + expect(await listPending()).toEqual([]) + expect(await readDocument('post', 'p1')).toMatchObject({ + title: 'Next', + published: true, + _revision: 2, + }) + expect(await publicTitle()).toBe('Next') expect(await drainDurable()).toEqual([ - 'document.unpublished by human', - 'document.updated by human', + 'document.updated by scheduler (author human)', ]) + // decided in phase 4 (2026-11-06): one event vocabulary — the bus + // uses the durable document.* names. + expect(takeBus()).toEqual(['document.updated by scheduler']) + expect(await runScheduledPublishing(AFTER_LATER)).toEqual([]) }) it('scheduleDocument({ stage: true }) stages the schedule change as the agent', async () => { diff --git a/packages/core/tests/document-state-strategy.sketch.test.ts b/packages/core/tests/document-state-strategy.sketch.test.ts index 13f048da..56305a85 100644 --- a/packages/core/tests/document-state-strategy.sketch.test.ts +++ b/packages/core/tests/document-state-strategy.sketch.test.ts @@ -52,6 +52,7 @@ function view(state?: LegalReviewState): DocView { actor: 'user:ada', after: { title: 'Hello, world' }, baseRevision: 3, + publishAt: null, workflow: { strategy: strategyKey(legalReview), state }, } : null, diff --git a/packages/core/tests/document-state.test.ts b/packages/core/tests/document-state.test.ts index c58b5085..c307208f 100644 --- a/packages/core/tests/document-state.test.ts +++ b/packages/core/tests/document-state.test.ts @@ -2,6 +2,9 @@ * The document state strategy executor: core's rules on every decision, the * built-in `review` and `direct` strategies, and per-collection overrides. */ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { actorOf, @@ -10,6 +13,7 @@ import { defineDocumentStateStrategy, defineEventHandler, directStrategy, + discard, emit, normalizeSession, publish, @@ -25,11 +29,13 @@ import { commitDocument, documentStateLabel, documentStateStrategy, + getPending, getStorage, importContent, listAudit, listPending, listRevisions, + listStrandedChangeSets, readDocument, runEventDispatch, saveDraft, @@ -244,7 +250,7 @@ describe('review strategy', () => { }) expect( (await availableDocumentActions(ctx, 'post', 'p1')).map((a) => a.type), - ).toEqual(['approve', 'reject', 'edit', 'draft']) + ).toEqual(['approve', 'reject', 'edit', 'draft', 'schedule']) expect(await documentStateLabel('post', 'p1')).toBe('Pending review') expect( await availableDocumentActions(publicContext(), 'post', 'p1'), @@ -385,6 +391,30 @@ describe('core rules', () => { ]) }) + it('audits a stage without strategy state as staged', async () => { + await setup({ postState: fixed([stage()]) }) + const pending = await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Staged' }, + actor: 'agent', + }) + expect(await listAudit()).toEqual([ + expect.objectContaining({ + docId: 'p1', + type: 'create', + action: 'submit', + actor: 'agent', + decision: 'staged', + changeSet: pending.id, + from: null, + to: null, + effects: [{ type: 'stage' }], + }), + ]) + }) + it('publish(revision) restores an older revision as a new live revision', async () => { await setup({ postState: defineDocumentStateStrategy({ @@ -447,6 +477,190 @@ describe('core rules', () => { }) }) +describe('change-set state', () => { + interface Legal { + legal: boolean + migrated?: boolean + } + + /** Stages agent changes; `approve:legal` clears them; `approve` needs that. */ + function steps( + version: number, + extra: Partial> = {}, + ): DocumentStateStrategy { + return defineDocumentStateStrategy({ + id: 'steps', + version, + decide: (_ctx, doc, action) => { + const state = doc.changeSet?.workflow?.state + if (action.type === 'approve:legal') + return { effects: [], state: { ...state, legal: true } } + if (action.type === 'approve') + return state?.legal + ? { effects: [commit(), publish()] } + : { reject: 'Legal has not cleared this.' } + if (action.type === 'discard') return { effects: [discard()] } + if (action.type === 'edit') return { effects: [commit(), publish()] } + return { effects: [stage()], state: { legal: false } } + }, + availableActions: () => [], + label: (state) => (state?.legal ? 'Cleared' : 'Needs legal'), + ...extra, + }) + } + + const dirs: Array = [] + afterEach(() => { + for (const dir of dirs.splice(0)) + rmSync(dir, { recursive: true, force: true }) + }) + function fileStorage() { + const dir = mkdtempSync(join(tmpdir(), 'cms-state-')) + dirs.push(dir) + const path = join(dir, 'cms.db') + return () => createSqliteStorage({ path }) + } + + async function stageProposal(): Promise { + await commitDocument('post', 'p1', { title: 'Live', published: true }) + const pending = await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'update', + doc: { title: 'Proposal', published: true }, + actor: 'agent', + }) + return pending.id + } + + it('stores the decided state on the change set and audits a state-only decision as transitioned', async () => { + await setup({ postState: steps(1) }) + const id = await stageProposal() + expect(await getPending(id)).toMatchObject({ + version: 1, + workflow: { strategy: 'steps@1', state: { legal: false } }, + }) + expect(await documentStateLabel('post', 'p1')).toBe('Needs legal') + + await expect( + actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'approve' }, + }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }) + + await actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'approve:legal' }, + }) + expect(await getPending(id)).toMatchObject({ + version: 2, + workflow: { strategy: 'steps@1', state: { legal: true } }, + }) + expect(await documentStateLabel('post', 'p1')).toBe('Cleared') + expect((await listAudit())[0]).toMatchObject({ + changeSet: id, + action: 'approve:legal', + decision: 'transitioned', + from: { legal: false }, + to: { legal: true }, + effects: [], + }) + + await actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'approve' }, + }) + expect(await readDocument('post', 'p1')).toMatchObject({ + title: 'Proposal', + _revision: 2, + }) + expect( + (await listAudit()).find((a) => a.decision === 'approved'), + ).toMatchObject({ + id, + changeSet: id, + from: { legal: true }, + to: null, + effects: [{ type: 'commit' }, { type: 'publish' }], + }) + }) + + it('upgrades state from an older version with migrate', async () => { + const storage = fileStorage() + await setup({ postState: steps(1), extra: { storage: storage() } }) + const id = await stageProposal() + await actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'approve:legal' }, + }) + await closeStore() + + await setup({ + postState: steps(2, { + migrate: ({ version, state }) => + version === 1 + ? { state: { ...(state as Legal), migrated: true } } + : { stranded: `unknown version ${version}` }, + }), + extra: { storage: storage() }, + }) + expect(await listStrandedChangeSets()).toEqual([]) + await actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'approve' }, + }) + expect((await readDocument('post', 'p1'))?.title).toBe('Proposal') + expect( + (await listAudit()).find((a) => a.decision === 'approved'), + ).toMatchObject({ id, from: { legal: true, migrated: true } }) + }) + + it('strands a change set it cannot read, refuses decisions on it, and still discards it', async () => { + const storage = fileStorage() + await setup({ postState: steps(1), extra: { storage: storage() } }) + const id = await stageProposal() + await closeStore() + + await setup({ postState: steps(2), extra: { storage: storage() } }) + expect(await listStrandedChangeSets()).toEqual([ + { + pending: expect.objectContaining({ id }), + reason: expect.stringContaining('steps@1'), + }, + ]) + await expect( + actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'approve:legal' }, + }), + ).rejects.toMatchObject({ + code: 'FORBIDDEN', + details: expect.objectContaining({ rule: 'stranded' }), + }) + expect((await listAudit())[0]).toMatchObject({ + changeSet: id, + decision: 'refused', + reason: expect.stringContaining('steps@1'), + }) + + await actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'discard' }, + }) + expect(await listPending()).toEqual([]) + expect(await listStrandedChangeSets()).toEqual([]) + expect((await readDocument('post', 'p1'))?.title).toBe('Live') + }) +}) + describe('actorOf', () => { it('maps each access context to an actor type', () => { expect(actorOf(publicContext())).toEqual({ diff --git a/packages/core/tests/plugins.test.ts b/packages/core/tests/plugins.test.ts index 879a2fbf..d45017b7 100644 --- a/packages/core/tests/plugins.test.ts +++ b/packages/core/tests/plugins.test.ts @@ -16,7 +16,13 @@ import { pluginAdminNav, runWithCmsConfig, } from '../src/index' -import { closeStore, commitDocument, readDocument } from '../src/server' +import { + closeStore, + commitDocument, + onCmsEvent, + readDocument, +} from '../src/server' +import type { CmsEventName } from '../src/server' import type { BlockType, CmsEvent, Collection } from '../src/index' const dirs: Array = [] @@ -172,11 +178,42 @@ describe('defineCms({ plugins })', () => { await commitDocument('pageview', 'p1', { path: '/', published: true }) expect(await readDocument('pageview', 'p1')).toMatchObject({ path: '/' }) expect(events.map((e) => [e.event, e.collection, e.id])).toEqual([ - ['change', 'pageview', 'p1'], - ['publish', 'pageview', 'p1'], + ['document.created', 'pageview', 'p1'], + ['document.published', 'pageview', 'p1'], ]) }) + it('onCmsEvent filters by document.* name or deprecated alias', async () => { + defineCms({ dataDir: dataDir(), collections: [post], blockTypes: [] }) + const seen: Record> = {} + const listen = ( + key: string, + names: CmsEventName | ReadonlyArray, + ) => + onCmsEvent(names, (event) => { + ;(seen[key] ??= []).push(event.event) + }) + const stops = [ + listen('published', 'document.published'), + listen('publish', 'publish'), + listen('update', ['update']), + listen('change', ['change', 'delete']), + ] + try { + await commitDocument('post', 'p', { title: 'A', published: true }) + await commitDocument('post', 'p', { title: 'B', published: true }) + await commitDocument('post', 'p', { title: 'B', published: false }) + } finally { + for (const stop of stops) stop() + } + expect(seen).toEqual({ + published: ['document.published'], + publish: ['document.published'], + update: ['document.updated'], + change: ['document.created', 'document.updated', 'document.updated'], + }) + }) + it('applies plugins for scoped configs, with a stable identity', () => { const raw = { collections: [], blockTypes: [], plugins: [analytics] } const seen = runWithCmsConfig(raw, () => getCmsConfig()) diff --git a/packages/core/tests/readiness.test.ts b/packages/core/tests/readiness.test.ts index 0099c592..2eecb4ec 100644 --- a/packages/core/tests/readiness.test.ts +++ b/packages/core/tests/readiness.test.ts @@ -160,7 +160,10 @@ describe('1.0 workflow invariants', () => { release.resolve() await failed expect(await readDocument('post', 'one')).toBeNull() - expect(await listAudit()).toHaveLength(1) + expect((await listAudit()).map((entry) => entry.action)).toEqual([ + 'reject', + 'submit', + ]) }) it('does not commit an old proposal after it was replaced during approval', async () => { @@ -253,7 +256,7 @@ describe('1.0 workflow invariants', () => { expect((await readDocument('post', 'one'))?.title).toBe('Live') }) - it('lets agents edit the latest draft while keeping their changes in review', async () => { + it('lets agents read the latest draft but not edit over it while it is open', async () => { await setup({ collections: [ { @@ -270,7 +273,7 @@ describe('1.0 workflow invariants', () => { body: 'Live body', published: true, }) - await saveDraft('post', 'one', { + const draft = await saveDraft('post', 'one', { title: 'Human draft', body: 'Draft body', published: true, @@ -278,17 +281,23 @@ describe('1.0 workflow invariants', () => { expect( await runOp('read_document', { collection: 'post', id: 'one' }, 'agent'), ).toMatchObject({ title: 'Human draft' }) - await runOp( - 'update_document', - { collection: 'post', id: 'one', doc: { body: 'Agent body' } }, - 'agent', - ) - const pending = (await listPending())[0]! - expect(pending.source).toBe('agent') - expect(pending.after).toMatchObject({ - title: 'Human draft', - body: 'Agent body', + await expect( + runOp( + 'update_document', + { collection: 'post', id: 'one', doc: { body: 'Agent body' } }, + 'agent', + ), + ).rejects.toMatchObject({ + code: 'CONFLICT', + details: { pendingId: draft.id, source: 'draft' }, }) + expect(await listPending()).toEqual([ + expect.objectContaining({ + id: draft.id, + source: 'draft', + after: expect.objectContaining({ body: 'Draft body' }), + }), + ]) expect((await readDocument('post', 'one'))?.body).toBe('Live body') }) @@ -331,9 +340,16 @@ describe('1.0 workflow invariants', () => { code: 'FORBIDDEN', }) await entered.promise - await commitDocument('post', 'one', { - title: 'Changed owner', - owner: 'bob', + // A direct commit would rebase or invalidate the proposal; change the + // owner underneath it so only the ownership recheck can refuse. + const storage = await getStorage() + await storage.transaction(async (tx) => { + const live = (await tx.getDocument('post', 'one'))! + const { collection, id, doc, updatedAt, ...index } = live + await tx.putDocument( + { collection, id, doc: { ...doc, owner: 'bob' }, updatedAt }, + index, + ) }) release.resolve() await failed @@ -470,7 +486,7 @@ describe('1.0 workflow invariants', () => { ]) expect(results.flat()).toHaveLength(1) expect((await readDocument('post', 'one'))?._revision).toBe(2) - expect(events).toEqual(['change', 'publish']) + expect(events).toEqual(['document.updated', 'document.published']) } finally { stop() } diff --git a/packages/core/tests/seo.test.ts b/packages/core/tests/seo.test.ts index 22647ee7..6c77c918 100644 --- a/packages/core/tests/seo.test.ts +++ b/packages/core/tests/seo.test.ts @@ -283,13 +283,18 @@ describe('webhooks', () => { const events = calls.map( (c) => (c.init.headers as Record)['x-cms-event'], ) - // Updating live content is a new publish (caches must revalidate). - expect(events).toEqual(['publish', 'publish', 'delete']) + // Updating live content is an update; publish is the transition. The + // unpublished redirect's create isn't in the default events. + expect(events).toEqual([ + 'document.published', + 'document.updated', + 'document.deleted', + ]) const first = calls[0]! const headers = first.init.headers as Record const body = first.init.body as string expect(JSON.parse(body)).toMatchObject({ - event: 'publish', + event: 'document.published', collection: 'post', id: 'a', doc: { title: 'A' }, @@ -327,14 +332,14 @@ describe('webhooks', () => { await deliver() expect(calls).toHaveLength(1) expect(warn).toHaveBeenCalledWith(expect.stringContaining('HTTP 400'), { - event: 'publish', + event: 'document.published', collection: 'post', id: 'a', }) warn.mockRestore() }) - it('opts into change events', async () => { + it('opts into every commit with the deprecated change alias', async () => { const calls = captureFetch() setup({ events: { dispatch: 'manual' }, diff --git a/packages/core/tests/storage-conformance.test.ts b/packages/core/tests/storage-conformance.test.ts index 93051ddb..4798dd82 100644 --- a/packages/core/tests/storage-conformance.test.ts +++ b/packages/core/tests/storage-conformance.test.ts @@ -435,7 +435,14 @@ describe('createMarkdownStorage & read-only collections', () => { expect(await listPending()).toEqual([]) expect((await readDocument('auditCol', 'c1'))?.title).toBe('Custom Doc') const audits = await listAudit() - expect(audits.map((a) => a.collection).sort()).toEqual(['auditCol', 'post']) + expect( + audits.map((a) => `${a.collection} ${a.action} ${a.decision}`).sort(), + ).toEqual([ + 'auditCol approve approved', + 'auditCol submit transitioned', + 'post reject rejected', + 'post submit transitioned', + ]) const backupDir = join(dir, 'backup-out') const backup = await backupCms(backupDir) diff --git a/packages/core/tests/store.test.ts b/packages/core/tests/store.test.ts index 35a02f9e..8841a796 100644 --- a/packages/core/tests/store.test.ts +++ b/packages/core/tests/store.test.ts @@ -16,6 +16,7 @@ import { commitDocument, dbFile, deleteDocument, + getPending, listAudit, listDocuments, listPending, @@ -197,7 +198,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect((await listAudit())[0]?.decision).toBe('rejected') }) - it('refuses to approve a proposal whose document changed since staging', async () => { + it('a direct commit that changes a field a proposal changed invalidates the proposal', async () => { const dir = makeTempDir() setupTestCms(dir, { post: { hello: { title: 'v1', published: true } } }) @@ -214,18 +215,56 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { published: true, }) + expect(await listPending()).toEqual([]) await expect(approve(staged.id)).rejects.toMatchObject({ - code: 'CONFLICT', - details: { baseRevision: 1, actualRevision: 2 }, + code: 'NOT_FOUND', }) expect((await readDocument('post', 'hello'))?.title).toBe('Human edit') - expect(await listPending()).toHaveLength(1) + expect( + (await listAudit()).find((a) => a.decision === 'discarded'), + ).toMatchObject({ + id: staged.id, + changeSet: staged.id, + action: 'discard', + decision: 'discarded', + reason: 'stale', + }) + }) + + it('a direct commit that changes other fields rebases a proposal onto the new revision', async () => { + const dir = makeTempDir() + setupTestCms(dir, { + post: { hello: { title: 'v1', tags: [], published: true } }, + }) + + const staged = await stageWrite({ + collection: 'post', + docId: 'hello', + type: 'update', + doc: { title: 'Agent edit', tags: [], published: true }, + actor: 'mcp', + }) + await commitDocument('post', 'hello', { + title: 'v1', + tags: ['news'], + published: true, + }) - await approve(staged.id, { force: true }) - expect((await readDocument('post', 'hello'))?.title).toBe('Agent edit') + const rebased = await getPending(staged.id) + expect(rebased).toMatchObject({ + version: 2, + baseRevision: 2, + after: { title: 'Agent edit', tags: ['news'] }, + }) + await approve(staged.id) + expect(await readDocument('post', 'hello')).toMatchObject({ + title: 'Agent edit', + tags: ['news'], + _revision: 3, + }) }) - it('refuses a stale delete or a create whose id was taken meanwhile', async () => { + it('a direct commit invalidates a staged delete, and a create whose id was taken meanwhile', async () => { const dir = makeTempDir() setupTestCms(dir, { post: { hello: { title: 'v1', published: true } } }) @@ -237,9 +276,8 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { actor: 'mcp', }) await commitDocument('post', 'hello', { title: 'v2', published: true }) - await expect(approve(del.id)).rejects.toMatchObject({ code: 'CONFLICT' }) + await expect(approve(del.id)).rejects.toMatchObject({ code: 'NOT_FOUND' }) expect(await readDocument('post', 'hello')).not.toBeNull() - await reject(del.id) const create = await stageWrite({ collection: 'post', @@ -249,7 +287,10 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { actor: 'mcp', }) await commitDocument('post', 'fresh', { title: 'Human', published: false }) - await expect(approve(create.id)).rejects.toMatchObject({ code: 'CONFLICT' }) + await expect(approve(create.id)).rejects.toMatchObject({ + code: 'NOT_FOUND', + }) + expect((await readDocument('post', 'fresh'))?.title).toBe('Human') }) it('supports scheduled publishing and auto-publishes when publishAt is reached', async () => { @@ -1044,10 +1085,10 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect((await readDocument('post', 'unsched-1'))?.published).toBe(false) expect(emitted.every((e) => e.hasDoc)).toBe(true) expect(emitted.map((e) => `${e.event}:${e.id}`)).toEqual([ - 'change:sched-1', - 'publish:sched-1', - 'change:unsched-1', - 'unpublish:unsched-1', + 'document.updated:sched-1', + 'document.published:sched-1', + 'document.updated:unsched-1', + 'document.unpublished:unsched-1', ]) expect( (await readDocument('post', 'unsched-1'))?.unpublishAt, diff --git a/packages/core/tests/transfer.test.ts b/packages/core/tests/transfer.test.ts index f34aeca1..bae3683d 100644 --- a/packages/core/tests/transfer.test.ts +++ b/packages/core/tests/transfer.test.ts @@ -190,17 +190,20 @@ describe('seed, migrate, backup', () => { expect( (await listPending()).map((pending) => pending.source).sort(), ).toEqual(['agent', 'draft']) - // The direct commit, the rejection and the API-key creation survive a - // backup/restore round-trip; the restore audits its own import. + // The direct commit, the stages, the rejection and the API-key creation + // survive a backup/restore round-trip; the restore audits its own import. expect( (await listAudit()) .map((entry) => `${entry.action ?? '-'} ${entry.decision ?? '-'}`) .sort(), ).toEqual([ 'apikey.create -', + 'draft transitioned', 'edit approved', 'import approved', 'reject rejected', + 'submit transitioned', + 'submit transitioned', ]) expect(await listApiKeys()).toHaveLength(1) expect( diff --git a/packages/core/tests/webhooks-outbox.test.ts b/packages/core/tests/webhooks-outbox.test.ts index f75bd3f2..cf0fad06 100644 --- a/packages/core/tests/webhooks-outbox.test.ts +++ b/packages/core/tests/webhooks-outbox.test.ts @@ -133,14 +133,18 @@ describe('webhooks via the durable outbox', () => { await deliver() const events = calls.map((c) => c.headers['x-cms-event']) - expect(events).toEqual(['publish', 'unpublish', 'delete']) + expect(events).toEqual([ + 'document.published', + 'document.unpublished', + 'document.deleted', + ]) // Wire contract: HMAC-SHA256 over `.`, x-cms-* headers. const publish = calls[0]! expect(publish.headers['x-cms-delivery']).toBeTruthy() expect(publish.headers['x-cms-timestamp']).toBeTruthy() expect(JSON.parse(publish.body)).toMatchObject({ - event: 'publish', + event: 'document.published', collection: 'post', id: 'p', doc: { title: 'Hello' }, @@ -177,7 +181,7 @@ describe('webhooks via the durable outbox', () => { await deliver() await deliver() expect( - calls.filter((c) => c.headers['x-cms-event'] === 'publish'), + calls.filter((c) => c.headers['x-cms-event'] === 'document.published'), ).toHaveLength(1) }) @@ -188,8 +192,8 @@ describe('webhooks via the durable outbox', () => { webhooks: [ // All events, only `post`. { url: 'https://a.test', collections: ['post'] }, - // Only `change`, all collections. - { url: 'https://b.test', events: ['change'] }, + // Only `document.created`, all collections. + { url: 'https://b.test', events: ['document.created'] }, // Only `note`. { url: 'https://c.test', collections: ['note'] }, ], @@ -199,14 +203,62 @@ describe('webhooks via the durable outbox', () => { const byUrl = (u: string) => calls.filter((c) => c.url === u).map((c) => c.headers['x-cms-event']) - // Hook A: default events (publish/unpublish/delete) on post → publish only. - expect(byUrl('https://a.test')).toEqual(['publish']) - // Hook B: change on any collection → change. - expect(byUrl('https://b.test')).toEqual(['change']) + // Hook A: default events on post → the publish only, not the create. + expect(byUrl('https://a.test')).toEqual(['document.published']) + // Hook B: creates on any collection. + expect(byUrl('https://b.test')).toEqual(['document.created']) // Hook C: scoped to `note`, saw nothing. expect(byUrl('https://c.test')).toEqual([]) }) + it('matches the deprecated short names as aliases and delivers document.* names', async () => { + const calls = captureFetch() + setup({ + dataDir: makeTempDir(), + webhooks: [ + { url: 'https://publish.test', events: ['publish'] }, + { url: 'https://update.test', events: ['update'] }, + { url: 'https://change.test', events: ['change'] }, + { url: 'https://unpublish.test', events: ['unpublish', 'delete'] }, + { url: 'https://default.test' }, + ], + }) + // Created unpublished, edited unpublished, published, edited live, + // unpublished, deleted. + await commitDocument('post', 'p', { title: 'A', published: false }) + await commitDocument('post', 'p', { title: 'B', published: false }) + await commitDocument('post', 'p', { title: 'B', published: true }) + await commitDocument('post', 'p', { title: 'C', published: true }) + await unpublishDocument('post', 'p', { actor: 'human' }) + await deleteDocument('post', 'p') + await deliver() + + const byUrl = (u: string) => + calls.filter((c) => c.url === u).map((c) => c.headers['x-cms-event']) + expect(byUrl('https://publish.test')).toEqual(['document.published']) + // `update` is an update of a document that stayed live. + expect(byUrl('https://update.test')).toEqual(['document.updated']) + // `change` is every create or update commit. + expect(byUrl('https://change.test')).toEqual([ + 'document.created', + 'document.updated', + 'document.updated', + 'document.updated', + 'document.updated', + ]) + expect(byUrl('https://unpublish.test')).toEqual([ + 'document.unpublished', + 'document.deleted', + ]) + // The default: what a public site shows changing. + expect(byUrl('https://default.test')).toEqual([ + 'document.published', + 'document.updated', + 'document.unpublished', + 'document.deleted', + ]) + }) + it('retries then dead-letters a persistently failing webhook', async () => { const calls = captureFetch(500) // always a retryable 5xx vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -253,7 +305,12 @@ describe('webhooks via the durable outbox', () => { const calls = captureFetch() setup({ dataDir: makeTempDir(), - webhooks: [{ url: 'https://hooks.test', events: ['change'] }], + webhooks: [ + { + url: 'https://hooks.test', + events: ['document.created', 'document.updated'], + }, + ], eventHandlers: [ // On any post create, the handler writes a note. That cascaded write // is depth 1 and must NOT enqueue a webhook. diff --git a/packages/store-postgres/README.md b/packages/store-postgres/README.md index abec185e..c933dd37 100644 --- a/packages/store-postgres/README.md +++ b/packages/store-postgres/README.md @@ -83,7 +83,7 @@ await storage.transact(async (tx) => { ) await tx.insertOutboxEvent({ id: crypto.randomUUID(), - event: 'publish', + event: 'document.published', collection: 'post', docId: 'hello', payload: { id: 'hello' }, diff --git a/packages/store-postgres/src/index.ts b/packages/store-postgres/src/index.ts index df307882..dcefe353 100644 --- a/packages/store-postgres/src/index.ts +++ b/packages/store-postgres/src/index.ts @@ -549,9 +549,10 @@ export function createPostgresStorage( explicit, ) await q( - `INSERT INTO ${t('pending')}(id, collection, doc_id, document_id, record, created_at) - VALUES ($1, $2, $3, CASE WHEN EXISTS(SELECT 1 FROM ${t('documents')} WHERE collection = $2 AND id = $3) OR $5 <> 'create' THEN $3 ELSE NULL END, $4::jsonb, $6) - ON CONFLICT(id) DO UPDATE SET collection = excluded.collection, doc_id = excluded.doc_id, document_id = excluded.document_id, record = excluded.record, created_at = excluded.created_at`, + `INSERT INTO ${t('pending')}(id, collection, doc_id, document_id, record, created_at, workflow_strategy, workflow_state, publish_at) + VALUES ($1, $2, $3, CASE WHEN EXISTS(SELECT 1 FROM ${t('documents')} WHERE collection = $2 AND id = $3) OR $5 <> 'create' THEN $3 ELSE NULL END, $4::jsonb, $6, $7, $8::jsonb, $9) + ON CONFLICT(id) DO UPDATE SET collection = excluded.collection, doc_id = excluded.doc_id, document_id = excluded.document_id, record = excluded.record, created_at = excluded.created_at, + workflow_strategy = excluded.workflow_strategy, workflow_state = excluded.workflow_state, publish_at = excluded.publish_at`, [ record.id, record.collection, @@ -559,9 +560,17 @@ export function createPostgresStorage( JSON.stringify(record), record.type, record.createdAt, + record.workflow?.strategy ?? null, + record.workflow ? JSON.stringify(record.workflow.state) : null, + record.publishAt ?? null, ], ) }, + findDuePendingPublish: (nowIso) => + records( + `SELECT record FROM ${t('pending')} WHERE publish_at <= $1 ORDER BY publish_at, sequence`, + [nowIso], + ), async deletePending(id) { const pending = await one('pending', id) if (pending) { @@ -624,14 +633,15 @@ export function createPostgresStorage( }, async insertAudit(record) { await q( - `INSERT INTO ${t('audit')}(id, collection, doc_id, record, at) VALUES ($1, $2, $3, $4::jsonb, $5) - ON CONFLICT(id) DO UPDATE SET collection = excluded.collection, doc_id = excluded.doc_id, record = excluded.record, at = excluded.at`, + `INSERT INTO ${t('audit')}(id, collection, doc_id, record, at, change_set) VALUES ($1, $2, $3, $4::jsonb, $5, $6) + ON CONFLICT(id) DO UPDATE SET collection = excluded.collection, doc_id = excluded.doc_id, record = excluded.record, at = excluded.at, change_set = excluded.change_set`, [ record.id, record.collection ?? null, record.docId ?? null, JSON.stringify(record), record.at, + record.changeSet ?? null, ], ) }, diff --git a/packages/store-postgres/src/migrations.ts b/packages/store-postgres/src/migrations.ts index 91dc7501..ebca6236 100644 --- a/packages/store-postgres/src/migrations.ts +++ b/packages/store-postgres/src/migrations.ts @@ -348,6 +348,44 @@ export const POSTGRES_MIGRATIONS: ReadonlyArray = [ `) }, }, + { + version: 8, + name: 'document state: workflow state and schedule on change sets, transitions on audit', + async up({ client, table: t }) { + // The full records stay in `record`; these columns are the lookups + // (stranded change sets, the change-set publish sweep, an audit trail + // per change set). publish_at is written on each put, like documents. + await client.query(` + ALTER TABLE ${t('pending')} + ADD COLUMN workflow_strategy TEXT, + ADD COLUMN workflow_state JSONB, + ADD COLUMN publish_at TIMESTAMPTZ; + UPDATE ${t('pending')} SET + workflow_strategy = record->'workflow'->>'strategy', + workflow_state = record->'workflow'->'state', + publish_at = (record->>'publishAt')::timestamptz + WHERE record ? 'workflow' OR record ? 'publishAt'; + CREATE INDEX ${t('idx_pending_publish_at')} + ON ${t('pending')}(publish_at) WHERE publish_at IS NOT NULL; + ALTER TABLE ${t('audit')} ADD COLUMN change_set TEXT; + UPDATE ${t('audit')} SET change_set = record->>'changeSet' + WHERE record ? 'changeSet'; + CREATE INDEX ${t('idx_audit_change_set')} + ON ${t('audit')}(change_set) WHERE change_set IS NOT NULL; + `) + }, + async down({ client, table: t }) { + await client.query(` + DROP INDEX ${t('idx_audit_change_set')}; + ALTER TABLE ${t('audit')} DROP COLUMN change_set; + DROP INDEX ${t('idx_pending_publish_at')}; + ALTER TABLE ${t('pending')} + DROP COLUMN publish_at, + DROP COLUMN workflow_state, + DROP COLUMN workflow_strategy; + `) + }, + }, ] export const LATEST_POSTGRES_SCHEMA_VERSION = diff --git a/packages/store-postgres/tests/events.test.ts b/packages/store-postgres/tests/events.test.ts index 30dcb012..8635fd9e 100644 --- a/packages/store-postgres/tests/events.test.ts +++ b/packages/store-postgres/tests/events.test.ts @@ -296,7 +296,7 @@ describe.skipIf(!url)('async events over Postgres', () => { expect(r.delivered).toBe(1) expect(calls).toHaveLength(1) const call = calls[0]! - expect(call.headers['x-cms-event']).toBe('publish') + expect(call.headers['x-cms-event']).toBe('document.published') expect(call.headers['x-cms-signature']).toBe( await signWebhook( 'pg-secret', diff --git a/packages/store-postgres/tests/invariants.test.ts b/packages/store-postgres/tests/invariants.test.ts index d0d99fb0..4124e4a9 100644 --- a/packages/store-postgres/tests/invariants.test.ts +++ b/packages/store-postgres/tests/invariants.test.ts @@ -218,10 +218,13 @@ describe.skipIf(!url)( }), ) const approving = runWithCmsConfig(b, () => approve(proposal.id)) + const refused = expect(approving).rejects.toMatchObject({ + code: 'CONFLICT', + }) await reading.promise resume.resolve() await blocker - await expect(approving).rejects.toMatchObject({ code: 'CONFLICT' }) + await refused expect((await first.getPending(proposal.id))?.after.title).toBe( 'Replacement', ) @@ -380,6 +383,8 @@ describe.skipIf(!url)( 'import approved', 'import approved', 'reject rejected', + 'submit transitioned', + 'submit transitioned', ]) expect(await second.listApiKeys?.()).toHaveLength(1) expect( diff --git a/packages/ui-react/src/lib/i18n.ts b/packages/ui-react/src/lib/i18n.ts index f81d83c4..4fbe7fba 100644 --- a/packages/ui-react/src/lib/i18n.ts +++ b/packages/ui-react/src/lib/i18n.ts @@ -359,6 +359,8 @@ export const defaultAdminMessages = { 'review.decision.rejected': 'rejected', 'review.decision.discarded': 'discarded', 'review.decision.refused': 'refused', + 'review.decision.transitioned': 'advanced', + 'review.decision.staged': 'submitted', 'review.blockCount': '{count} block(s)', 'review.imageRemoved': '(image removed)', 'review.imageUpdated': '(image updated)', diff --git a/packages/ui-react/src/routes/review.tsx b/packages/ui-react/src/routes/review.tsx index 385658e5..31f656bf 100644 --- a/packages/ui-react/src/routes/review.tsx +++ b/packages/ui-react/src/routes/review.tsx @@ -43,6 +43,8 @@ const DECISION_LABELS = { rejected: 'review.decision.rejected', discarded: 'review.decision.discarded', refused: 'review.decision.refused', + transitioned: 'review.decision.transitioned', + staged: 'review.decision.staged', } as const satisfies Record< NonNullable, AdminMessageId diff --git a/scripts/dialect-inventory.baseline.json b/scripts/dialect-inventory.baseline.json index 218a7975..c8b65a9d 100644 --- a/scripts/dialect-inventory.baseline.json +++ b/scripts/dialect-inventory.baseline.json @@ -81,6 +81,10 @@ "nonTest": 0, "test": 2 }, + "shortEventNames": { + "nonTest": 6, + "test": 5 + }, "seoCascadeFields": { "nonTest": 0, "test": 0 diff --git a/scripts/dialect-inventory.ts b/scripts/dialect-inventory.ts index 09692635..b0119247 100644 --- a/scripts/dialect-inventory.ts +++ b/scripts/dialect-inventory.ts @@ -146,6 +146,14 @@ export const MARKERS: ReadonlyArray = [ label: '`RelationSearchContext` / `PaletteSearchContext`', pattern: /\b(?:RelationSearchContext|PaletteSearchContext)\b/g, }, + { + id: 'shortEventNames', + label: + 'short content-event aliases (`publish`, `change`, …) for `document.*`', + // The alias type, and subscriptions or comparisons by a short name. + pattern: + /\bCmsEventAlias\b|(?:\bevents:\s*\[\s*|\.event\s*===?\s*|\bonCmsEvent\(\s*\[?\s*)['"](?:publish|unpublish|delete|change|update)['"]/g, + }, { id: 'seoCascadeFields', label: 'field names in `lib/seo.ts` cascade lists',