From 8558d8e93293cddebb898fb307c8b695ca0e4dab Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 6 Nov 2026 14:18:34 +0000 Subject: [PATCH] feat(core): document state strategies with review and direct built-ins (4a) (#27) Chain step 11 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: jherr --- .changeset/document-state-strategy.md | 17 + docs/agents/review-queue.md | 23 +- docs/api/cli.md | 2 +- docs/api/cms-core-server.md | 49 +- docs/architecture/terminology.md | 10 +- packages/api/src/ops.ts | 19 +- packages/api/src/outputs.ts | 4 +- .../tests/characterization/save-paths.test.ts | 20 +- packages/api/tests/ops.test.ts | 3 +- packages/core/src/config.ts | 7 + packages/core/src/document-state.ts | 605 +++++++++ packages/core/src/events.ts | 5 + packages/core/src/index.ts | 44 + packages/core/src/schema.ts | 6 + packages/core/src/server.ts | 8 + packages/core/src/server/access-context.ts | 27 + packages/core/src/server/dispatcher.ts | 1 + packages/core/src/server/outbox.ts | 8 + packages/core/src/server/store.ts | 12 + .../core/src/server/store/document-state.ts | 1077 +++++++++++++++++ packages/core/src/server/store/review.ts | 611 ++++------ packages/core/src/server/store/scheduling.ts | 132 +- packages/core/src/server/store/write.ts | 119 +- packages/core/src/server/transfer.ts | 131 +- packages/core/src/storage.ts | 1 + packages/core/src/storage/sql-storage.ts | 3 +- packages/core/src/storage/types.ts | 25 +- .../tests/characterization/workflow-suite.ts | 179 ++- ...document-state-strategy.acceptance.test.ts | 15 +- .../document-state-strategy.sketch.test.ts | 7 +- packages/core/tests/document-state.test.ts | 509 ++++++++ .../core/tests/draft/acceptance-harness.ts | 23 +- .../tests/draft/document-state-strategy.ts | 246 +--- .../core/tests/draft/legal-review.xstate.ts | 11 +- packages/core/tests/transfer.test.ts | 15 +- .../store-postgres/tests/invariants.test.ts | 13 +- packages/ui-react/src/lib/i18n.ts | 2 + packages/ui-react/src/routes/review.tsx | 18 +- 38 files changed, 3102 insertions(+), 905 deletions(-) create mode 100644 .changeset/document-state-strategy.md create mode 100644 packages/core/src/document-state.ts create mode 100644 packages/core/src/server/store/document-state.ts create mode 100644 packages/core/tests/document-state.test.ts diff --git a/.changeset/document-state-strategy.md b/.changeset/document-state-strategy.md new file mode 100644 index 00000000..d8336a55 --- /dev/null +++ b/.changeset/document-state-strategy.md @@ -0,0 +1,17 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-ui-react': patch +--- + +Add document state strategies. Every write now goes through its collection's strategy, which decides what an action does by returning effects (`stage`, `commit`, `publish(revision?)`, `unpublish`, `schedule`, `discard`, `emit`); core applies them in one transaction and writes the audit entry. Set one with `defineCms({ documentState })` or a collection's `documentState`. The built-ins are `reviewStrategy()` (the default, equal to today's flow including `review.autoApprove`) and `directStrategy()` (agent and author writes commit at once). `defineDocumentStateStrategy` types a custom one. Core refuses, with `FORBIDDEN` and an audited `refused` entry, a decision that drops an incoming change, emits a `document.*` event, changes a published document without `publish`, or lets an agent publish when the strategy doesn't grant it. New server exports: `submitWrite`, `documentStateStrategy`, and `actOnDocument(ctx, { collection, id, action })` (the generic door: run any strategy action as an access context), `availableDocumentActions(ctx, collection, id)` and `documentStateLabel(collection, id)`. + +Behaviour changes (bug fixes): + +- Direct commits (`commitDocument`, saves by publishers, deletes, scheduled publishes) now write an audit entry. Document audit entries carry the strategy `action` (`edit`, `approve`, `reject`, `discard`, `publish`, `import`, …), and `decision` can now also be `discarded` or `refused`. +- `discardDraft` is audited as `discarded` and no longer emits `review.rejected`. +- With `review.autoApprove`, `saveDoc` reports the save as live (`staged: false`, no `pendingId`) instead of `staged: true`. +- `importContent` (`tanstack-cms import`, seeding) is audited and emits `import.document` per document and `import.completed`. +- Events after `approve` (and auto-approval) name the approver as the actor (`reviewer`, `auto-approve`), with the proposer as the new `author` field on the event envelope. +- A coalesced `stageWrite` without an `instruction` keeps the earlier one. +- The review screen labels discarded and refused decisions. diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index ccb10dbb..3aaab0e7 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -22,7 +22,7 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a - **Published documents** get a **draft**: the live version stays as it is until someone publishes the changes. - **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them. -Every commit records a **revision**, and every review decision lands in the **audit trail**. +Every commit records a **revision**, and every decision (a direct save, an approval, a rejection, a discarded draft, a scheduled publish, an import) lands in the **audit trail**. Pending proposals have a monotonically increasing `version`. Send the version shown to the reviewer as `expectedVersion` when calling `approveChange` or `rejectChange`; the built-in review screen does this automatically. A rejected, replaced or already decided proposal conflicts even with `force: true`. `force` overrides a stale live revision, while `forceDelete` separately opts into deleting referenced content and records a forced deletion in revision history. @@ -46,7 +46,7 @@ The rules come from the session's role, so custom roles and collection `access` ## Agent Writes Are Always Staged -Agents work through the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas). The write tools (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`) all call `stageWrite()`. No agent tool commits, publishes, or deletes, whatever the role of the user or API key behind it. Proposing a deletion still needs delete rights (`content.delete` and the collection's `delete` rule), and proposing an unpublish needs publish rights, so an author's agent cannot fill the queue with deletions. +Agents work through the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas). The write tools (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`) all call `stageWrite()`. No agent tool commits, publishes, or deletes, whatever the role of the user or API key behind it, unless the collection's [strategy](#choosing-the-flow-document-state-strategies) commits staged writes (`review.autoApprove`, `directStrategy()`). Proposing a deletion still needs delete rights (`content.delete` and the collection's `delete` rule), and proposing an unpublish needs publish rights, so an author's agent cannot fill the queue with deletions. ```text Agent tool call (create / update / delete / unpublish / restore / schedule) @@ -93,6 +93,25 @@ The audit entry records both parties, for example `mcp (approved by Jane Doe)`. 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`. +## Choosing the Flow: Document State Strategies + +The flow above is the built-in **review** strategy, the default. Every write goes through its collection's document state strategy, which decides what an action (`edit`, `submit`, `approve`, …) does by returning effects such as `stage()`, `commit()` and `publish()`. Core applies them in one transaction and writes the audit entry. + +```ts +import { defineCms, directStrategy, reviewStrategy } from '@tanstack/cms-core' + +defineCms({ + // The default: equal to `review: { autoApprove }`. + documentState: reviewStrategy({ autoApprove: false }), + collections: [ + // A personal notes collection: agent and author writes commit at once. + { ...note, documentState: directStrategy() }, + ], +}) +``` + +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). + ## Optimistic Concurrency Saves can carry the `_revision` the editor loaded as `expectedRevision`. If the stored document has moved on (someone else saved in the meantime), the save fails with `CONFLICT` and `details: { expectedRevision, actualRevision }` instead of overwriting their work. The admin editor sends it automatically and asks you to reload. HTTP clients pass it the same way: diff --git a/docs/api/cli.md b/docs/api/cli.md index 141cdd03..001cd2cd 100644 --- a/docs/api/cli.md +++ b/docs/api/cli.md @@ -118,7 +118,7 @@ Exports committed documents and media metadata as a portable JSON file (`format: tanstack-cms import [--mode merge|skip-existing|replace] [--yes] ``` -Imports an export file. Documents are written as-is: no hooks, validation, reference checks, or review queue, so relations in the file may point at documents that don't exist. `unique` fields are still enforced by the SQL stores' indexes, and a violation aborts the whole import. +Imports an export file. Documents are written as-is: no hooks, validation, reference checks, or review queue, so relations in the file may point at documents that don't exist. `unique` fields are still enforced by the SQL stores' indexes, and a violation aborts the whole import. Each document is an `import` action of its collection's document state strategy, as actor `import`: it is audited and emits `import.document`, and the import emits `import.completed` (not `document.*`, so a restore doesn't refire publication side effects). A strategy that refuses one document aborts the whole import. | Option | Description | | --- | --- | diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index f46b1509..eec8e419 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -464,7 +464,50 @@ interface StageWriteArgs { } ``` -Validates and stages a change in the review queue without touching the committed document. A second staged write for the same document merges into the existing entry. +Validates and stages a change in the review queue without touching the committed document. A second staged write for the same document merges into the existing entry, keeping the earlier `instruction` when the new write has none. + +The write is the collection's [document state strategy](../agents/review-queue#choosing-the-flow-document-state-strategies) `submit` action (`draft` for `source: 'draft'`). When the strategy commits it at once (`review.autoApprove`, or `directStrategy()`), the returned entry's `after` is the committed document and nothing is left in the queue. + +### `submitWrite(args)` + +```ts +function submitWrite(args: StageWriteArgs): Promise +``` + +`stageWrite` that returns the strategy's outcome instead of a queue entry: `pending` (the change set it staged, or `null`), `committed` (the live document when the strategy committed the write), `effects`, and the `strategy` key (`review@1`). Use it to tell a staged write from one that went live. + +### `documentStateStrategy(collection)` + +Returns the document state strategy a collection uses: its own `documentState`, else `defineCms({ documentState })`, else `reviewStrategy({ autoApprove: review.autoApprove })`. + +### `actOnDocument(ctx, args)`, `availableDocumentActions(ctx, collection, id)` and `documentStateLabel(collection, id)` + +```ts +function actOnDocument( + ctx: AccessContext, + args: { collection: string; id: string; action: Action }, +): Promise + +function availableDocumentActions( + ctx: AccessContext, + collection: string, + id: string, +): Promise> + +function documentStateLabel(collection: string, id: string): Promise +``` + +`actOnDocument` runs any action of the collection's strategy (`approve`, `discard`, or a custom one such as `approve:legal`) as `ctx`, under core's rules; an `action.patch` is validated the way staging does first. A refused decision is audited and thrown as `FORBIDDEN` with `details: { action, rule, reason }`. `availableDocumentActions` is what the strategy offers `ctx` on the document now, and `documentStateLabel` names its state. + +```ts validate=type +import { actOnDocument, systemContext } from '@tanstack/cms-core/server' + +await actOnDocument(systemContext('nightly legal sign-off'), { + collection: 'post', + id: 'launch', + action: { type: 'approve:legal' }, +}) +``` ### `listPending(options?)`, `getPending(id)` @@ -490,7 +533,7 @@ interface ApproveOptions { function reject(pendingId: string, options?: { rejecter?: string; expectedVersion?: number }): Promise ``` -`approve` commits a staged change (document, revision, and audit entry); `reject` drops it and records the decision. +`approve` commits a staged change (document, revision, and audit entry); `reject` drops it and records the decision. Events after `approve` name the approver as the actor and carry the proposer as `author`. ```ts validate=type import { approve, listPending } from '@tanstack/cms-core/server' @@ -884,7 +927,7 @@ interface ImportResult { } ``` -Restores an export. Documents are written as-is: no hooks, validation, or review queue. `merge` creates or overwrites each document, `skip-existing` only creates missing ones, and `replace` also deletes documents of the imported collections that are not in the file. +Restores an export. Documents are written as-is: no hooks, validation, or review queue. Each write is the collection strategy's `import` action (actor `import`, or `options.actor`), audited, with `import.document` per document and `import.completed` at the end. `merge` creates or overwrites each document, `skip-existing` only creates missing ones, and `replace` also deletes documents of the imported collections that are not in the file. ```ts validate=type import { readFile } from 'node:fs/promises' diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index bb53d341..26ab4680 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -50,13 +50,13 @@ The locator lives in the system namespace next to `id`, so a user field named `l ## Document state strategy -**Planned.** The per-collection lifecycle of a document's edits: which actions exist (`edit`, `approve`, `publish`, …), who may take them, and what happens when they do. It's set per app in `defineCms` and can be overridden per collection. Every write passes through the collection's strategy; the strategy decides how much governance happens inside it. +**Partly implemented.** The per-collection lifecycle of a document's edits: which actions exist (`edit`, `approve`, `publish`, …), who may take them, and what happens when they do. It's set per app in `defineCms` and can be overridden per collection. Every write passes through the collection's strategy; the strategy decides how much governance happens inside it. A strategy is a small object. Given the [access context](#access-context), the document and an action, it returns a decision: a new state plus a list of [effects](#effect), or a rejection. It also answers "which actions can this actor take?" and "what is this state called?" for the admin UI. Its state is a serializable value that core stores and never interprets. It's versioned (`legal-review@1`), and a version that removes states must provide `migrate(state)`. Planned built-ins: **review** (Draft → Pending Review → Approved → Published) and **direct** (an edit publishes immediately, for personal apps). Complex flows, such as legal and editorial approval running in parallel, can be written with XState. XState is a documented option, not the engine. -**Today:** one implicit flow. Writes either commit (publishers) or stage into the review queue, and approving a staged change commits it. `review.autoApprove` loosens it. +**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. ## Change set @@ -66,7 +66,7 @@ Planned built-ins: **review** (Draft → Pending Review → Approved → Publish ## Effect -**Planned.** The only way a strategy changes anything. A strategy returns effects and core applies them: +**Implemented.** The only way a strategy changes anything. A strategy returns effects and core applies them: | Effect | Meaning | | --- | --- | @@ -82,7 +82,9 @@ 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. +- 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.) +- 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. - Agents can't cause a publish unless the strategy grants it to agents. diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index c79a5112..80f6243a 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -84,7 +84,7 @@ import { createDbUser, setDbUserDisabled, getPending, - stageWrite, + submitWrite, listComments, resolveComment, deleteComment, @@ -421,7 +421,7 @@ async function saveAsHuman( session, ) if (!canPublish(session, collection, existing ?? safe)) { - const pending = await stageWrite({ + const outcome = await submitWrite({ collection, docId: id, type: existing || !opts.create ? 'update' : 'create', @@ -434,11 +434,22 @@ async function saveAsHuman( opts.expectedRevision ?? (typeof existing?._revision === 'number' ? existing._revision : 0), }) + if (outcome.committed || !outcome.pending) { + return { + ok: true, + staged: false, + doc: redactFor( + ctx.access, + collection, + (outcome.committed ?? outcome.change.doc) as Doc, + ), + } + } return { ok: true, staged: true, - pendingId: pending.id, - doc: redactFor(ctx.access, collection, pending.after as Doc), + pendingId: outcome.pending.id, + doc: redactFor(ctx.access, collection, outcome.pending.after as Doc), } } const isDraft = diff --git a/packages/api/src/outputs.ts b/packages/api/src/outputs.ts index be6c1aae..1118b2b8 100644 --- a/packages/api/src/outputs.ts +++ b/packages/api/src/outputs.ts @@ -79,7 +79,9 @@ export const writeOutput = z.object({ ok: z.literal(true), staged: z .boolean() - .describe('True when the change went to the review queue instead of live.'), + .describe( + 'True when the change went to the review queue; false when it is live (including an auto-approved save) or saved as a draft.', + ), draft: z .boolean() .optional() diff --git a/packages/api/tests/characterization/save-paths.test.ts b/packages/api/tests/characterization/save-paths.test.ts index 052470c9..78c94ba9 100644 --- a/packages/api/tests/characterization/save-paths.test.ts +++ b/packages/api/tests/characterization/save-paths.test.ts @@ -15,10 +15,11 @@ * Rows labelled `known bug, fixed in phase 4 (#N: …)`, with the test name * 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. 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 - * (autoApprove saves report `staged: true`). + * 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 + * (autoApprove saves report `staged: true`, fixed in phase 4a). */ import { afterEach, describe, expect, it } from 'vitest' import { @@ -356,24 +357,23 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { expect(res.status).toBe(409) }) - it('review.autoApprove: the save is live at once, yet the result still says staged with a pendingId [known bug, fixed in phase 4 (#6)]', async () => { + it('review.autoApprove: the save is live at once, and the result reports it as live', async () => { await seed({ review: { autoApprove: true } }) const out = await write( 'saveDoc', { collection: 'post', id: 'wip', doc: { title: 'Auto' } }, 'author', ) - // known bug, fixed in phase 4 (#6: autoApprove reports staged) — the - // change is live, so the result should report it as live. + // fixed in phase 4a (#6: autoApprove reports staged) — the change is + // live, so the result reports it as live. expect(out).toMatchObject({ - staged: true, - pendingId: expect.any(String), + staged: false, doc: { title: 'Auto', _revision: 2 }, }) + expect(out.pendingId).toBeUndefined() expect(await listPending()).toEqual([]) expect((await readDocument('post', 'wip'))?.title).toBe('Auto') expect((await listAudit())[0]).toMatchObject({ - id: out.pendingId, actor: 'human (approved by auto-approve)', decision: 'approved', }) diff --git a/packages/api/tests/ops.test.ts b/packages/api/tests/ops.test.ts index 412ef539..59d60ff5 100644 --- a/packages/api/tests/ops.test.ts +++ b/packages/api/tests/ops.test.ts @@ -458,6 +458,7 @@ describe('activity log', () => { expect(review).toBeTruthy() expect(review.docId).toBe('draft') expect(review.type).toBe('update') - expect(review.action).toBeUndefined() + // Document entries name the document state strategy action. + expect(review.action).toBe('reject') }) }) diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 93e9a50b..d15aeddf 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -52,6 +52,7 @@ import type { OpOutputOf, } from './ops' import type { CmsEventsConfig, EventHandlerDefinition } from './events' +import type { AnyDocumentStateStrategy } from './document-state' /** The seed store an app ships so a fresh install isn't empty. */ export interface SeedStore { @@ -298,6 +299,12 @@ export interface CmsConfig { mcp?: CmsMcpConfig /** Optional review-queue behaviour (e.g. `autoApprove`). */ review?: CmsReviewConfig + /** + * The document state strategy every collection follows unless it sets its + * own: how saves, submissions, approvals and imports reach the live + * document. Defaults to `reviewStrategy({ autoApprove: review.autoApprove })`. + */ + documentState?: AnyDocumentStateStrategy /** * Persistence backend. Defaults to `createSqliteStorage()` at `/cms.db`. * See `@tanstack/cms-core/storage` and `@tanstack/cms-store-libsql`. diff --git a/packages/core/src/document-state.ts b/packages/core/src/document-state.ts new file mode 100644 index 00000000..cb2137ad --- /dev/null +++ b/packages/core/src/document-state.ts @@ -0,0 +1,605 @@ +/** + * Document state strategies: the workflow a document's change set follows on + * its way live, expressed as decisions over effects. + * + * Core owns the live record (the `published` flag, the schedule, revisions); + * a strategy only decides what an action does, by returning effects + * (`stage`, `commit`, `publish`, `unpublish`, `schedule`, `discard`, `emit`). + * Core's executor runs them in one transaction, enforces its rules on every + * decision, and writes the audit trail. + * + * ```ts + * defineCms({ + * documentState: reviewStrategy(), + * collections: [{ ...note, documentState: directStrategy() }], + * }) + * ``` + * + * Client-safe: types, effect constructors and the built-in strategies. The + * executor lives server-side. + */ +import type { CmsReviewConfig } from './config' +import type { Doc } from './schema' +import type { AccessActor, AccessContext } from './lib/access-context' +import type { PendingSource, WriteType } from './storage/types' + +// --------------------------------------------------------------------------- +// Actors +// --------------------------------------------------------------------------- + +/** + * Who acts, as far as a strategy (and the agent publish floor) is concerned: + * the access context's actor kind. + */ +export type ActorType = AccessActor['kind'] + +export interface StrategyActor { + type: ActorType + /** A stable id for messages and guards, e.g. a user id or `mcp:enrich`. */ + id: string + /** The CMS role(s) the actor holds. */ + roles: ReadonlyArray +} + +/** The actor `ctx` acts as. */ +export function actorOf(ctx: AccessContext): StrategyActor { + const { actor } = ctx + switch (actor.kind) { + case 'public': + return { type: 'public', id: 'public', roles: [] } + case 'user': + return { + type: 'user', + id: actor.id ?? 'user', + roles: actor.role ? [actor.role] : [], + } + case 'agent': + return { + type: 'agent', + id: actor.agent, + roles: actor.role ? [actor.role] : [], + } + case 'system': + return { type: 'system', id: `system:${actor.reason}`, roles: [] } + case 'scheduler': + return { type: 'scheduler', id: 'scheduler', roles: [] } + case 'import': + return { type: 'import', id: actor.reason, roles: [] } + case 'preview': + return { type: 'preview', id: `preview:${actor.tokenId}`, roles: [] } + } +} + +// --------------------------------------------------------------------------- +// Effects: the only way a strategy changes anything +// --------------------------------------------------------------------------- + +export type Effect = + /** Keep the incoming change in the document's (one, coalesced) change set. */ + | { readonly type: 'stage' } + /** Apply the change set (or the incoming change) as a new revision. */ + | { readonly type: 'commit' } + /** + * Make a revision live. Default: the one this decision commits, else the + * current one. An older `revision` is restored as a new live revision. + */ + | { readonly type: 'publish'; readonly revision?: number } + | { readonly type: 'unpublish' } + /** Set (a string) or clear (`null`) the publish / unpublish times. */ + | { + readonly type: 'schedule' + readonly publishAt?: string | null + readonly unpublishAt?: string | null + } + /** Drop the change set. */ + | { readonly type: 'discard' } + /** + * A strategy-named event through the durable outbox. `document.*` events + * are core's and can't be emitted. + */ + | { + readonly type: 'emit' + readonly event: string + readonly payload?: unknown + } + +export type EffectType = Effect['type'] + +export const stage = (): Effect => ({ type: 'stage' }) +export const commit = (): Effect => ({ type: 'commit' }) +export const publish = (revision?: number): Effect => + revision === undefined ? { type: 'publish' } : { type: 'publish', revision } +export const unpublish = (): Effect => ({ type: 'unpublish' }) +export const schedule = (at: { + publishAt?: string | null + unpublishAt?: string | null +}): Effect => ({ type: 'schedule', ...at }) +export const discard = (): Effect => ({ type: 'discard' }) +export const emit = (event: string, payload?: unknown): Effect => + payload === undefined + ? { type: 'emit', event } + : { type: 'emit', event, payload } + +/** What a strategy answers: a new state and effects, or a refusal. */ +export type Decision = + | { state?: S; effects?: ReadonlyArray } + | { reject: string } + +// --------------------------------------------------------------------------- +// What a strategy sees and receives +// --------------------------------------------------------------------------- + +/** + * The verbs the built-in strategies understand. A custom strategy may define + * its own (`approve:legal`). + * + * - `edit`: save `patch` to the working copy now (the publisher's save). + * - `submit`: propose `patch` for review (agents, authors). + * - `draft`: save `patch` as a private draft of a published document. + * - `approve` / `reject`: decide the open change set. `approve` takes + * `input.publish` to override the proposed published flag. + * - `discard`: drop the open draft. + * - `publish` / `unpublish`: take the live revision up or down (the scheduler). + * - `import`: restore `patch` from an export (actor `import`). + */ +export type BuiltInActionType = + | 'edit' + | 'submit' + | 'draft' + | 'approve' + | 'reject' + | 'discard' + | 'publish' + | 'unpublish' + | 'import' + +export interface Action { + /** + * A built-in verb (`BuiltInActionType`), or a strategy-defined one such as + * `approve:legal`. + */ + type: string + /** + * The incoming document for actions that carry a change (`edit`, `submit`, + * `draft`, `import`), already validated and through the collection's + * hooks. + */ + patch?: Record + /** + * Verb arguments. Core sets `change` (`create` / `update` / `delete`) on + * actions that carry one, and `source` on `submit` / `draft`. + */ + input?: Record + /** + * The attribution label core writes to revisions and the audit trail + * (`human`, `agent`, `mcp:`, `scheduler`, `import`). + */ + by?: string +} + +export interface ActionDescriptor { + type: string + label: string + tone?: 'default' | 'primary' | 'danger' +} + +/** The core-owned live record. */ +export interface LiveView { + doc: Doc + revision: number + published: boolean + publishAt: string | null + unpublishAt: string | null +} + +/** The document's open change set (at most one, coalesced). */ +export interface ChangeSetView { + id: string + version: number + type: WriteType + /** Which door opened it: an agent proposal, an author's review request, or a draft. */ + source: PendingSource + /** Attribution of the latest write to it. */ + actor: string + after: Doc + baseRevision: number | null + instruction?: string + /** + * 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`. + */ + workflow: { strategy: string; state: S } | null +} + +export interface DocView { + collection: string + id: string + /** `null` for a document that was never committed. */ + live: LiveView | null + changeSet: ChangeSetView | null +} + +/** A state graph, for the generated Mermaid chart. */ +export interface StateGraph { + nodes: ReadonlyArray<{ + id: string + label: string + parent?: string + parallel?: boolean + final?: boolean + }> + edges: ReadonlyArray<{ from: string; to: string; action: string }> +} + +export type Migration = { state: S } | { stranded: string } + +/** + * A document state strategy. `S` is the serializable state of one change + * set; core stores it next to `id@version` and never interprets it. + */ +export interface DocumentStateStrategy { + id: string + version: number + /** + * Actor types allowed to cause `publish` / `unpublish` effects beyond + * core's floor. Core refuses a publish caused by an `agent` actor unless + * `agent` is listed here. + */ + grants?: { publish?: ReadonlyArray } + decide: ( + ctx: AccessContext, + doc: DocView, + action: Action, + ) => Decision | Promise> + availableActions: ( + ctx: AccessContext, + doc: DocView, + ) => ReadonlyArray + label: (state: S | undefined, doc: DocView) => string + describe?: () => StateGraph + /** + * Upgrades state written by an older version. Without it, change sets from + * an older version are reported as stranded. + */ + migrate?: (from: { version: number; state: unknown }) => Migration +} + +/** + * A strategy of any state type, as configured on `defineCms` or a + * collection. + */ +// oxlint-disable-next-line typescript/no-explicit-any -- S is invariant (decide reads and returns it), so a config slot must accept every S +export type AnyDocumentStateStrategy = DocumentStateStrategy + +/** `id@version`, as stored with change-set state. */ +export function strategyKey( + strategy: Pick, +): string { + return `${strategy.id}@${strategy.version}` +} + +/** Type-safe identity helper for a custom strategy. */ +export function defineDocumentStateStrategy( + strategy: DocumentStateStrategy, +): DocumentStateStrategy { + return strategy +} + +// --------------------------------------------------------------------------- +// Built-in strategies +// --------------------------------------------------------------------------- + +function changeOf(action: Action): WriteType { + const change = action.input?.change + return change === 'create' || change === 'delete' ? change : 'update' +} + +/** Publish when the outcome is published; take a live document down otherwise. */ +function visibility(live: LiveView | null, published: boolean): Array { + if (published) return [publish()] + return live?.published ? [unpublish()] : [] +} + +function proposedPublished(doc: Record | undefined): boolean { + return doc?.published === true +} + +/** Commit an incoming change (or the open change set) with matching visibility. */ +function commitChange( + live: LiveView | null, + change: WriteType, + doc: Record | undefined, + published?: boolean, +): Array { + if (change === 'delete') return [commit()] + return [commit(), ...visibility(live, published ?? proposedPublished(doc))] +} + +function approvedPublished(action: Action, after: Doc): boolean { + const override = action.input?.publish + 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 liveLabel(live: LiveView | null): string { + if (!live) return 'New' + return live.published ? 'Published' : 'Unpublished' +} + +function can(ctx: AccessContext, permission: string): boolean { + return ctx.permissions.some((p) => p === permission) +} + +const ACTIONS: Record = { + edit: { type: 'edit', label: 'Save', tone: 'primary' }, + submit: { type: 'submit', label: 'Submit for review', tone: 'primary' }, + draft: { type: 'draft', label: 'Save draft' }, + approve: { type: 'approve', label: 'Approve', tone: 'primary' }, + reject: { type: 'reject', label: 'Reject', tone: 'danger' }, + discard: { type: 'discard', label: 'Discard draft', tone: 'danger' }, + publish: { type: 'publish', label: 'Publish' }, + unpublish: { type: 'unpublish', label: 'Unpublish' }, + import: { type: 'import', label: 'Import' }, +} + +/** Change-set states of the built-in strategies. */ +export type ReviewState = 'draft' | 'pending_review' + +function changeSetState(doc: DocView): ReviewState | undefined { + const cs = doc.changeSet + if (!cs) return undefined + return ( + cs.workflow?.state ?? (cs.source === 'draft' ? 'draft' : 'pending_review') + ) +} + +function builtInLabel( + state: ReviewState | undefined, + doc: DocView, +): string { + switch (state ?? changeSetState(doc)) { + case 'draft': + return 'Draft' + case 'pending_review': + return 'Pending review' + case undefined: + return liveLabel(doc.live) + } +} + +const BUILT_IN_GRAPH: StateGraph = { + nodes: [ + { id: 'unpublished', label: 'Unpublished' }, + { id: 'published', label: 'Published' }, + { id: 'draft', label: 'Draft' }, + { id: 'pending_review', label: 'Pending review' }, + ], + edges: [ + { from: 'unpublished', to: 'pending_review', action: 'submit' }, + { from: 'published', to: 'pending_review', action: 'submit' }, + { from: 'published', to: 'draft', action: 'draft' }, + { from: 'draft', to: 'published', action: 'edit' }, + { from: 'draft', to: 'published', action: 'discard' }, + { from: 'pending_review', to: 'published', action: 'approve' }, + { from: 'pending_review', to: 'unpublished', action: 'reject' }, + { from: 'unpublished', to: 'published', action: 'publish' }, + { from: 'published', to: 'unpublished', action: 'unpublish' }, + ], +} + +export interface ReviewStrategyOptions { + /** + * Approve submitted changes at once, as actor `auto-approve` (same shape + * as `defineCms({ review: { autoApprove } })`, which the default strategy + * reads). Setting it grants agents the publish its approvals cause. + */ + autoApprove?: CmsReviewConfig['autoApprove'] + /** Actor types allowed to publish beyond core's floor. */ + grants?: DocumentStateStrategy['grants'] +} + +async function autoApproves( + rule: CmsReviewConfig['autoApprove'], + ctx: AccessContext, + doc: DocView, + action: Action, +): Promise { + if (typeof rule === 'boolean') return rule + if (typeof rule !== 'function') return false + const source = action.input?.source + try { + return Boolean( + await rule({ + collection: doc.collection, + docId: doc.id, + type: changeOf(action), + actor: action.by ?? actorOf(ctx).id, + source: source === 'review' || source === 'draft' ? source : 'agent', + }), + ) + } catch { + return false + } +} + +/** + * The default strategy: publishers save directly, everyone else proposes + * changes that wait for a reviewer's approval, and publishers can keep a + * private draft of a published document. + * + * `approve` commits and publishes (there is no separate "approved" state). + */ +export function reviewStrategy( + options: ReviewStrategyOptions = {}, +): DocumentStateStrategy { + const { autoApprove } = options + const grants = + options.grants ?? + (autoApprove !== undefined && autoApprove !== false + ? { publish: ['agent'] as const } + : undefined) + return { + id: 'review', + version: 1, + ...(grants ? { grants } : {}), + async decide(ctx, doc, action) { + switch (action.type) { + case 'edit': + case 'import': + return { + effects: commitChange(doc.live, changeOf(action), action.patch), + } + case 'draft': + return { state: 'draft', effects: [stage()] } + case 'submit': { + const change = changeOf(action) + if (await autoApproves(autoApprove, ctx, doc, action)) { + return { + effects: [ + stage(), + ...commitChange(doc.live, change, action.patch), + emit('review.approved'), + ], + } + } + const instruction = action.input?.instruction + return { + state: 'pending_review', + effects: doc.changeSet + ? [stage()] + : [ + stage(), + emit('review.submitted', { + source: action.input?.source ?? 'agent', + ...(typeof instruction === 'string' && instruction + ? { instruction } + : {}), + }), + ], + } + } + case 'approve': { + const cs = doc.changeSet + if (!cs) return { reject: 'There is no change to approve.' } + return { + effects: [ + ...commitChange( + doc.live, + cs.type, + cs.after, + approvedPublished(action, cs.after), + ), + emit('review.approved'), + ], + } + } + case 'reject': + 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()] } + default: + return ( + scheduledActions(action) ?? { + reject: `The review strategy has no "${action.type}" action.`, + } + ) + } + }, + availableActions(ctx, doc) { + const out: Array = [] + const state = changeSetState(doc) + const agent = actorOf(ctx).type === 'agent' + if (state === 'pending_review' && can(ctx, 'review.decide') && !agent) + out.push(ACTIONS.approve, ACTIONS.reject) + if (can(ctx, 'content.publish') && !agent) { + out.push(ACTIONS.edit) + if (doc.live?.published) out.push(ACTIONS.draft) + if (state === 'draft') out.push(ACTIONS.discard) + } else if (can(ctx, 'content.write') || agent) { + out.push(ACTIONS.submit) + } + return out + }, + label: builtInLabel, + describe: () => BUILT_IN_GRAPH, + } +} + +export interface DirectStrategyOptions { + /** Actor types allowed to publish beyond core's floor (agents need it). */ + grants?: DocumentStateStrategy['grants'] +} + +/** + * No review: every save, submission and import commits at once, published + * or not as the document says. Drafts still work, and an open change set can + * still be approved, rejected or discarded. + * + * Agents can't publish under `direct` unless `grants.publish` lists `agent`. + */ +export function directStrategy( + options: DirectStrategyOptions = {}, +): DocumentStateStrategy { + return { + id: 'direct', + version: 1, + ...(options.grants ? { grants: options.grants } : {}), + decide(_ctx, doc, action) { + switch (action.type) { + case 'edit': + case 'submit': + case 'import': + return { + effects: commitChange(doc.live, changeOf(action), action.patch), + } + case 'draft': + return { state: 'draft', effects: [stage()] } + case 'approve': { + const cs = doc.changeSet + if (!cs) return { reject: 'There is no change to approve.' } + return { + effects: commitChange( + doc.live, + cs.type, + cs.after, + approvedPublished(action, cs.after), + ), + } + } + case 'reject': + case 'discard': + if (!doc.changeSet) + return { reject: `There is no change to ${action.type}.` } + return { effects: [discard()] } + default: + return ( + scheduledActions(action) ?? { + reject: `The direct strategy has no "${action.type}" action.`, + } + ) + } + }, + availableActions(ctx, doc) { + const out: Array = [] + if (!can(ctx, 'content.write')) return out + out.push(ACTIONS.edit) + if (doc.live?.published) out.push(ACTIONS.draft) + const state = changeSetState(doc) + if (state === 'draft') out.push(ACTIONS.discard) + if (state === 'pending_review' && can(ctx, 'review.decide')) + out.push(ACTIONS.approve, ACTIONS.reject) + return out + }, + label: builtInLabel, + describe: () => BUILT_IN_GRAPH, + } +} diff --git a/packages/core/src/events.ts b/packages/core/src/events.ts index f87bad12..bf97bbcc 100644 --- a/packages/core/src/events.ts +++ b/packages/core/src/events.ts @@ -65,6 +65,11 @@ export interface CmsEventEnvelope { documentId?: string /** Who caused the event (`human`, `agent`, `scheduler`, `system`, …). */ actor: string + /** + * Who wrote the change, when it differs from `actor`: an approved + * proposal's proposer, while `actor` is the approver. + */ + author?: string /** ISO timestamp recorded in the firing transaction. */ occurredAt: string payload: TPayload diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7d74f6dc..3e67af3b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -246,6 +246,50 @@ export type { ScopedCmsClient, } from './events' +// Document state strategies: the workflow a change set follows on its way +// live (`defineCms({ documentState })`, overridable per collection). The types, +// effect constructors and built-in strategies are client-safe; the executor +// lives server-side. +export { + actorOf, + commit, + defineDocumentStateStrategy, + directStrategy, + discard, + emit, + publish, + reviewStrategy, + schedule, + stage, + strategyKey, + unpublish, +} from './document-state' +export type { + Action, + ActionDescriptor, + ActorType, + AnyDocumentStateStrategy, + BuiltInActionType, + ChangeSetView, + Decision, + DirectStrategyOptions, + DocView, + DocumentStateStrategy, + Effect, + EffectType, + LiveView, + Migration, + ReviewState, + ReviewStrategyOptions, + StateGraph, + StrategyActor, +} from './document-state' +export type { + AccessActor, + AccessContext, + ReadMode, +} from './server/access-context' + // Framework-agnostic authorization contract. React bindings (context, hooks, // full mock auth switcher with HeaderControl) live in `@tanstack/cms-ui-react`; // Svelte bindings live in `@tanstack/cms-ui-dom`. diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index d6a07163..0389c2b5 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -20,6 +20,7 @@ import { contentLocales, getCmsConfig } from './config' import type { CollectionAccess, FieldAccess } from './lib/access' import type { AccessContext } from './lib/access-context' import type { StorageAdapter } from './storage/types' +import type { AnyDocumentStateStrategy } from './document-state' import { isBuiltInFieldType } from './lib/authoring' export { @@ -491,6 +492,11 @@ export interface Collection { hooks?: CollectionHooks /** Narrow read / write / publish / delete for this collection by role. */ access?: CollectionAccess + /** + * This collection's document state strategy, overriding + * `defineCms({ documentState })`. + */ + documentState?: AnyDocumentStateStrategy /** * Public URL path of a document (e.g. `(doc, id) => \`/post/${id}\``), or * null when it has no page. Used by the sitemap; collections without it diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 7c5b5477..5cccfea9 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -38,6 +38,7 @@ export { reindexDocuments, groupDocuments, stageWrite, + submitWrite, listPending, getPending, approve, @@ -60,6 +61,10 @@ export { restoreRevision, runScheduledPublishing, scheduleDocument, + actOnDocument, + availableDocumentActions, + documentStateLabel, + documentStateStrategy, } from './server/store' // Optional storage-capability narrowing (auth users / api keys / user roles). export { requireStorageCapability } from './storage/capabilities' @@ -97,6 +102,9 @@ export type { CommitOptions, DeleteOptions, ScheduledPublishResult, + IncomingChange, + RefusalRule, + StrategyOutcome, } from './server/store' export { interfaceCollectionName, diff --git a/packages/core/src/server/access-context.ts b/packages/core/src/server/access-context.ts index cebac884..8c62e60f 100644 --- a/packages/core/src/server/access-context.ts +++ b/packages/core/src/server/access-context.ts @@ -164,6 +164,33 @@ export function systemContext( }) } +/** + * An agent writing through the MCP tools or the agent operations. With a + * signed-in session it is `accessContext({ session, agent, mode: 'edit' })`; + * without one it holds no permissions and its reads bypass the rules, as a + * sessionless legacy read does. + * + * @internal + */ +export function agentContext(args: { + agent: string + session?: CmsSession +}): AccessContext { + if (args.session?.isAuthenticated) { + return accessContext({ + session: args.session, + agent: args.agent, + mode: 'edit', + }) + } + return frozen({ + actor: { kind: 'agent', agent: args.agent, id: null, role: null }, + permissions: [], + mode: 'edit', + publicRead: false, + }) +} + /** * The holder of a verified preview token: the token's one document, drafts * and staged changes included, returned as stored. diff --git a/packages/core/src/server/dispatcher.ts b/packages/core/src/server/dispatcher.ts index 5a674569..b77050a7 100644 --- a/packages/core/src/server/dispatcher.ts +++ b/packages/core/src/server/dispatcher.ts @@ -159,6 +159,7 @@ function toEnvelope(rec: EventRecord): CmsEventEnvelope { payload: data.payload, ...(data.previous !== undefined ? { previous: data.previous } : {}), ...(data.changedFields ? { changedFields: data.changedFields } : {}), + ...(data.author ? { author: data.author } : {}), ...(rec.causationId ? { causationId: rec.causationId } : {}), causationDepth: rec.causationDepth, } diff --git a/packages/core/src/server/outbox.ts b/packages/core/src/server/outbox.ts index c2a13c5f..142ba110 100644 --- a/packages/core/src/server/outbox.ts +++ b/packages/core/src/server/outbox.ts @@ -79,6 +79,7 @@ export interface EventData { payload: JsonValue previous?: JsonValue changedFields?: Array + author?: string /** Internal delivery ledger; never part of the handler's event envelope. */ deliveries?: Record< string, @@ -95,6 +96,8 @@ export interface EnqueueInput { collection?: string documentId?: string actor: string + /** Who wrote the change, when someone else (`actor`) decided it. */ + author?: string occurredAt: string payload: JsonValue previous?: JsonValue @@ -117,6 +120,7 @@ export async function enqueueEvent( payload: input.payload, ...(input.previous !== undefined ? { previous: input.previous } : {}), ...(input.changedFields ? { changedFields: input.changedFields } : {}), + ...(input.author ? { author: input.author } : {}), } const record: EventRecord = { id, @@ -244,6 +248,7 @@ export async function enqueueDocumentChange( collection: string id: string actor: string + author?: string before: Doc | null after: Doc occurredAt: string @@ -253,6 +258,7 @@ export async function enqueueDocumentChange( collection: args.collection, documentId: args.id, actor: args.actor, + ...(args.author ? { author: args.author } : {}), occurredAt: args.occurredAt, } if (args.before) { @@ -297,6 +303,7 @@ export async function enqueueDocumentDelete( collection: string id: string actor: string + author?: string last: Doc | null occurredAt: string }, @@ -305,6 +312,7 @@ export async function enqueueDocumentDelete( collection: args.collection, documentId: args.id, actor: args.actor, + ...(args.author ? { author: args.author } : {}), occurredAt: args.occurredAt, type: 'document.deleted', payload: { id: args.id }, diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 600be6e5..98b77478 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -79,6 +79,7 @@ export type { } from './store/query' export { stageWrite, + submitWrite, listPending, getPending, approve, @@ -88,6 +89,17 @@ export { listAudit, } from './store/review' export type { StageWriteArgs, ApproveOptions } from './store/review' +export { + actOnDocument, + availableDocumentActions, + documentStateLabel, + documentStateStrategy, +} from './store/document-state' +export type { + IncomingChange, + RefusalRule, + StrategyOutcome, +} from './store/document-state' export { addComment, listComments, diff --git a/packages/core/src/server/store/document-state.ts b/packages/core/src/server/store/document-state.ts new file mode 100644 index 00000000..501bc23b --- /dev/null +++ b/packages/core/src/server/store/document-state.ts @@ -0,0 +1,1077 @@ +/** + * The document state strategy executor: every write door asks the + * collection's strategy for a decision, checks it against core's rules, and + * runs its effects here. + * + * Rules core enforces on every decision: + * 1. Atomic: the effects run in order, in one transaction. + * 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. + * 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. + * 6. A decision on an incoming change must stage or commit it. + * 7. Strategies can't emit `document.*` events. + * + * Server-only. + */ +import { randomUUID } from 'node:crypto' +import { getCmsConfig } from '../../config' +import { CmsError } from '../../errors' +import { assetCollectionName, emptyDoc } from '../../schema' +import { actorOf, reviewStrategy, strategyKey } from '../../document-state' +import { protectWrite } from '../access' +import { assertCollectionAccess } from '../auth' +import { + stampContentVersion, + upgradeIncomingDoc, + upgradeStoredDoc, +} from '../content-migrations' +import { emitCmsEvent } from '../events' +import { deleteAssetBlob } from '../media-store' +import { queueNotification } from '../notifications' +import { enqueueDocumentChange, enqueueEvent } from '../outbox' +import { getStorage, notifyStorageCommit } from '../storage' +import { + applyPostRead, + assertExpectedRevision, + assertSingletonSlot, + checkFieldRules, + emitCommit, + recordAudit, + recordRevision, + requireWritableCollection, + runAfterChange, + runAfterDelete, + runPreValidate, + runPostValidate, + runPreDelete, + validate, + writeDocument, +} from './internal' +import { commitDeletion } from './write' +import { systemContext } from '../access-context' +import type { ResolvedCmsConfig } from '../../config' +import type { + Action, + ActionDescriptor, + AnyDocumentStateStrategy, + ChangeSetView, + DocView, + Effect, + EffectType, +} from '../../document-state' +import type { CmsSession } from '../../lib/auth' +import type { Collection, Doc, JsonValue } from '../../schema' +import type { + AuditRecord, + IndexedDocumentRecord, + PendingSource, + StorageOps, + WriteType, +} from '../../storage/types' +import type { AccessContext } from '../../lib/access-context' +import type { Pending } from './internal' + +// --------------------------------------------------------------------------- +// Resolving the strategy +// --------------------------------------------------------------------------- + +const defaults = new WeakMap() + +/** + * The strategy `collectionName` follows: its own `documentState`, else the + * app's, else `reviewStrategy` with the app's `review.autoApprove`. + */ +export function documentStateStrategy( + collectionName: string, +): AnyDocumentStateStrategy { + const config = getCmsConfig() + const own = config.collections[collectionName]?.documentState + if (own) return own + if (config.documentState) return config.documentState + let fallback = defaults.get(config) + if (!fallback) { + fallback = reviewStrategy({ autoApprove: config.review?.autoApprove }) + defaults.set(config, fallback) + } + return fallback +} + +// --------------------------------------------------------------------------- +// The document view +// --------------------------------------------------------------------------- + +interface LoadedView { + view: DocView + liveRow: IndexedDocumentRecord | null + pending: Pending | null +} + +function changeSetView(pending: Pending): ChangeSetView { + return { + id: pending.id, + version: pending.version ?? 1, + type: pending.type, + source: pending.source, + actor: pending.actor, + after: pending.after, + baseRevision: pending.baseRevision ?? null, + ...(pending.instruction ? { instruction: pending.instruction } : {}), + workflow: null, + } +} + +async function loadView( + storage: StorageOps, + collection: string, + docId: string, + pendingOverride?: Pending | null, +): Promise { + const liveRow = await storage.getDocument(collection, docId) + const pending = + pendingOverride === undefined + ? await storage.getPendingFor(collection, docId) + : pendingOverride + const revision = liveRow?.doc._revision + return { + liveRow, + pending, + view: { + collection, + id: docId, + live: liveRow + ? { + doc: liveRow.doc, + revision: typeof revision === 'number' ? revision : 0, + published: liveRow.published, + publishAt: liveRow.publishAt, + unpublishAt: liveRow.unpublishAt, + } + : null, + changeSet: pending ? changeSetView(pending) : null, + }, + } +} + +/** The actions `ctx` can take on a document right now, from its strategy. */ +export async function availableDocumentActions( + ctx: AccessContext, + collection: string, + docId: string, +): Promise> { + const storage = await getStorage() + const { view } = await loadView(storage, collection, docId) + return documentStateStrategy(collection).availableActions(ctx, view) +} + +/** The strategy's label for a document's current state. */ +export async function documentStateLabel( + collection: string, + docId: string, +): Promise { + const storage = await getStorage() + const { view } = await loadView(storage, collection, docId) + return documentStateStrategy(collection).label(undefined, view) +} + +// --------------------------------------------------------------------------- +// Deciding +// --------------------------------------------------------------------------- + +/** Which of core's rules refused a decision (`strategy` = the strategy said no). */ +export type RefusalRule = + | 'strategy' + | 'effects' + | 'live-content' + | 'agent-floor' + | 'drops-change' + | 'core-event' + +const EFFECT_TYPES = new Set([ + 'stage', + 'commit', + 'publish', + 'unpublish', + 'schedule', + 'discard', + 'emit', +]) + +interface Refusal { + rule: RefusalRule + reason: string +} + +function checkDecision( + strategy: AnyDocumentStateStrategy, + ctx: AccessContext, + loaded: LoadedView, + action: Action, + effects: ReadonlyArray, + change: WriteType | null, +): Refusal | null { + for (const effect of effects) { + if (!EFFECT_TYPES.has(effect.type)) { + return { + rule: 'effects', + reason: `Unknown effect "${String(effect.type)}".`, + } + } + if (effect.type === 'emit' && effect.event.startsWith('document.')) { + return { + rule: 'core-event', + reason: `Strategies can't emit "${effect.event}": document.* events are core's.`, + } + } + } + const has = (type: EffectType) => effects.some((e) => e.type === type) + if (change !== null && !has('stage') && !has('commit')) { + return { + rule: 'drops-change', + reason: `A "${action.type}" decision must stage or commit the incoming change.`, + } + } + const actor = actorOf(ctx) + if ( + actor.type === 'agent' && + (has('publish') || has('unpublish')) && + !strategy.grants?.publish?.includes('agent') + ) { + return { + rule: 'agent-floor', + reason: `Agents can't publish or unpublish under the "${strategy.id}" strategy.`, + } + } + let staged = false + let discarded = false + for (const effect of effects) { + switch (effect.type) { + case 'stage': + if (change === null) { + return { + rule: 'effects', + reason: `"${action.type}" carries no change to stage.`, + } + } + staged = true + break + case 'commit': + if (discarded || (!staged && change === null && !loaded.pending)) { + return { rule: 'effects', reason: 'There is no change to commit.' } + } + break + case 'discard': + if (!loaded.pending && !staged) { + return { + rule: 'effects', + reason: 'There is no change set to discard.', + } + } + discarded = true + break + case 'publish': + case 'unpublish': + case 'schedule': + case 'emit': + break + } + } + const committed = committedChange(loaded, effects, change) + if ( + loaded.view.live?.published && + has('commit') && + committed !== 'delete' && + !has('publish') && + !has('unpublish') + ) { + return { + rule: 'live-content', + reason: + 'A published document changes only through publish: commit without publish (or unpublish) is refused.', + } + } + return null +} + +/** The type of change the decision's `commit` applies, if any. */ +function committedChange( + loaded: LoadedView, + effects: ReadonlyArray, + change: WriteType | null, +): WriteType | null { + if (!effects.some((e) => e.type === 'commit')) return null + return change ?? loaded.pending?.type ?? null +} + +export interface RefusedDecision { + collection: string + docId: string + by: string + action: Action + change: WriteType | null + rule: RefusalRule + reason: string +} + +/** Audit a refused decision (nothing else changes) and throw it as `FORBIDDEN`. */ +export async function refuseDecision(refused: RefusedDecision): Promise { + const storage = await getStorage() + await storage.transaction(async (tx) => { + await recordAudit(tx, { + collection: refused.collection, + docId: refused.docId, + ...(refused.change ? { type: refused.change } : {}), + actor: refused.by, + action: refused.action.type, + decision: 'refused', + at: new Date().toISOString(), + }) + }) + throw new CmsError(refused.reason, 'FORBIDDEN', { + action: refused.action.type, + rule: refused.rule, + reason: refused.reason, + }) +} + +export interface DecideArgs { + ctx: AccessContext + /** Attribution for revisions, audit and events (today's actor strings). */ + by: string + collection: string + docId: string + action: Action + incoming?: IncomingChange + /** Act on this change set rather than the document's current one. */ + pending?: Pending + /** Staging: the source to record and the instruction to keep. */ + source?: PendingSource + instruction?: string +} + +export type DecidedWrite = + | { + ok: true + strategy: AnyDocumentStateStrategy + loaded: LoadedView + action: Action + state: unknown + effects: ReadonlyArray + } + | { ok: false; refused: RefusedDecision } + +/** + * Ask the collection's strategy what `args.action` does and check the + * decision against core's rules. Reads only, through `storage`. + */ +export async function decideStrategyWrite( + storage: StorageOps, + args: DecideArgs, +): Promise { + const strategy = documentStateStrategy(args.collection) + const loaded = await loadView( + storage, + args.collection, + args.docId, + args.pending, + ) + const change = args.incoming?.type ?? null + const action: Action = { + ...args.action, + by: args.by, + input: { + ...args.action.input, + ...(change ? { change } : {}), + ...(args.source ? { source: args.source } : {}), + ...(args.instruction ? { instruction: args.instruction } : {}), + }, + ...(args.incoming && args.action.patch === undefined + ? { patch: args.incoming.doc } + : {}), + } + const refused = (rule: RefusalRule, reason: string): DecidedWrite => ({ + ok: false, + refused: { + collection: args.collection, + docId: args.docId, + by: args.by, + action, + change: change ?? loaded.pending?.type ?? null, + rule, + reason, + }, + }) + const decision = await strategy.decide(args.ctx, loaded.view, action) + if ('reject' in decision) return refused('strategy', decision.reject) + const effects = decision.effects ?? [] + const refusal = checkDecision( + strategy, + args.ctx, + loaded, + action, + effects, + change, + ) + if (refusal) return refused(refusal.rule, refusal.reason) + return { ok: true, strategy, loaded, action, state: decision.state, effects } +} + +// --------------------------------------------------------------------------- +// Executing +// --------------------------------------------------------------------------- + +/** The change an action carries, prepared by the door that received it. */ +export interface IncomingChange { + type: WriteType + /** Validated; for `delete`, the document being deleted. */ + doc: Doc + /** + * The hooks the door already ran: `stage` ran `preValidate` (as staging + * does), `commit` ran both stages (as a direct save does), `raw` ran none + * (an import restores documents as they are). + */ + prepared: 'stage' | 'commit' | 'raw' + /** The live document as the door read it (hooks applied), for `before`. */ + before?: Doc | null + /** The live `_revision` the door saw (absent for a new document). */ + baseRevision?: number +} + +export interface StrategyWrite extends DecideArgs { + /** The clock for this write (the scheduler's sweep time). */ + at?: string + /** Committing: the revision summary. */ + summary?: string + /** Committing a deletion: delete despite references. */ + forceDelete?: boolean + /** Committing: check this session's update and publish rights in the transaction. */ + session?: CmsSession + /** Committing a change set: who wrote it, for the revision (default `by`). */ + author?: string + /** The audit row's actor (default `by`). */ + auditActor?: string + /** The outbox and bus events' actor (default `by`). */ + eventActor?: string + /** + * When the decision commits the change it stages (an auto-approval), who + * approved it: the audit reads ` (approved by )` and the + * events name `approvedBy`, with `by` as the author. + */ + approvedBy?: string + /** + * Runs first in the transaction. Throw to abort; return `false` to skip + * the decision silently (a scheduled publish that no longer applies). + * `readLive` reads the live row once; the precondition decides whether + * that read comes before or after its own (row-lock order on Postgres). + */ + precondition?: ( + tx: StorageOps, + readLive: () => Promise, + ) => Promise + /** + * The live `_revision` (0 for none) the door expects, checked in the + * transaction after the session's access (a forced approval). + */ + expectedRevision?: number +} + +export interface StrategyOutcome { + /** `id@version` of the strategy that decided. */ + strategy: string + state: unknown + effects: ReadonlyArray + /** The change set this decision staged, decided or discarded. */ + pending: Pending | null + /** The committed document, when the decision committed one. */ + committed: Doc | null + /** True when the decision committed a deletion. */ + deleted: boolean + /** True when the precondition skipped the decision. */ + skipped: boolean +} + +/** + * `doc` with the visibility and schedule the effects give it: `published` + * follows `publish` / `unpublish` (else stays as live), and `schedule` sets + * or clears the times. + */ +export function sealVisibility( + doc: Doc, + effects: ReadonlyArray, + live: IndexedDocumentRecord | null, +): Doc { + const has = (type: EffectType) => effects.some((e) => e.type === type) + const published = has('publish') + ? true + : has('unpublish') + ? false + : Boolean(live?.published) + let next: Doc = + Boolean(doc.published) === published ? doc : { ...doc, published } + for (const effect of effects) { + if (effect.type !== 'schedule') continue + for (const key of ['publishAt', 'unpublishAt'] as const) { + const value = effect[key] + if (value === undefined) continue + if (value === null || value === '') { + const { [key]: _cleared, ...rest } = next + next = rest + } else { + next = { ...next, [key]: value } + } + } + } + return next +} + +type CommitSource = + | { from: 'incoming'; doc: Doc; prepared: IncomingChange['prepared'] } + | { from: 'changeSet'; doc: Doc } + | { from: 'live'; doc: Doc; summary: string } + +async function prepareCommit( + collection: Collection, + write: StrategyWrite, + source: CommitSource, + effects: ReadonlyArray, + live: IndexedDocumentRecord | null, + storage: StorageOps, +): Promise { + const actor = write.author ?? write.by + const operation = live ? 'update' : 'create' + const id = write.docId + if (source.from === 'incoming' && source.prepared !== 'stage') { + return sealVisibility(source.doc, effects, live) + } + if (source.from === 'live') { + let next = sealVisibility(source.doc, effects, live) + next = validate( + collection, + await runPreValidate(collection, next, id, operation, actor), + ) + await checkFieldRules(storage, collection, id, next) + next = await runPostValidate(collection, next, id, operation, actor) + next = sealVisibility(next, effects, live) + next = { ...next, ...validate(collection, next) } + await checkFieldRules(storage, collection, id, next) + return next + } + let doc: Doc = sealVisibility( + await upgradeStoredDoc(write.collection, id, source.doc), + effects, + live, + ) + if (write.session) + doc = protectWrite(write.collection, doc, live?.doc, write.session) + doc = await runPostValidate(collection, doc, id, operation, actor) + doc = sealVisibility(doc, effects, live) + doc = { ...doc, ...validate(collection, doc) } + await checkFieldRules(storage, collection, id, doc) + return doc +} + +function auditDecision( + action: Action, + effects: ReadonlyArray, +): 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')) + return 'approved' + if (has('discard')) return 'discarded' + return null +} + +/** + * 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 + * decision is audited and thrown as `FORBIDDEN`. + */ +export async function executeStrategyWrite( + write: StrategyWrite, +): Promise { + const collection = requireWritableCollection(write.collection) + const storage = await getStorage() + const decided = await decideStrategyWrite(storage, write) + if (!decided.ok) return refuseDecision(decided.refused) + const { strategy, loaded, action, effects } = decided + const change = write.incoming?.type ?? null + + const has = (type: EffectType) => effects.some((e) => e.type === type) + const stagesFirst = + has('stage') && + effects.findIndex((e) => e.type === 'stage') < + effects.findIndex((e) => e.type === 'commit') + const commitType = committedChange(loaded, effects, change) + const writesLive = + has('commit') || has('publish') || has('unpublish') || has('schedule') + const { liveRow } = loaded + const operation: 'create' | 'update' = liveRow ? 'update' : 'create' + const author = write.author ?? write.by + const autoApproved = stagesFirst && write.approvedBy !== undefined + const eventActor = autoApproved + ? (write.approvedBy ?? write.by) + : (write.eventActor ?? write.by) + const auditActor = autoApproved + ? `${write.by} (approved by ${write.approvedBy ?? ''})` + : (write.auditActor ?? write.by) + const proposer = write.author ?? (autoApproved ? write.by : undefined) + const eventAuthor = proposer !== eventActor ? proposer : undefined + const actsOnChangeSet = + (has('commit') && (!write.incoming || stagesFirst)) || has('discard') + const now = write.at ?? new Date().toISOString() + + // Prepare what the transaction writes: hooks and validation run outside it. + let content: Doc | null = null + let summary = write.summary + if (writesLive && commitType !== 'delete') { + let source: CommitSource + if (has('commit')) { + if (write.incoming && !stagesFirst) { + source = { + from: 'incoming', + doc: write.incoming.doc, + prepared: write.incoming.prepared, + } + } else { + const after = stagesFirst ? write.incoming?.doc : loaded.pending?.after + if (!after) + throw new CmsError('There is no change to commit.', 'CONFLICT') + source = { from: 'changeSet', doc: after } + } + } else { + const publishEffect = effects.find((e) => e.type === 'publish') + const revision = + publishEffect?.type === 'publish' ? publishEffect.revision : undefined + const liveRevision = loaded.view.live?.revision ?? 0 + if (revision !== undefined && revision !== liveRevision) { + const restored = ( + await storage.listRevisions(write.collection, write.docId) + ).find((r) => r.revision === revision) + if (!restored || restored.doc._deleted) + throw new CmsError( + `No revision ${revision} of ${write.collection}/${write.docId}.`, + 'NOT_FOUND', + ) + source = { + from: 'live', + doc: restored.doc, + summary: `Published revision ${revision}`, + } + } else { + if (!liveRow) + throw new CmsError( + `No ${write.collection} document with id "${write.docId}".`, + 'NOT_FOUND', + ) + source = { + from: 'live', + doc: liveRow.doc, + summary: has('publish') + ? 'Published document' + : has('unpublish') + ? 'Unpublished document' + : 'Scheduled document', + } + } + summary ??= source.summary + } + content = await prepareCommit( + collection, + write, + source, + effects, + liveRow, + storage, + ) + } + if (commitType === 'delete') + await runPreDelete(collection, write.docId, author) + + let staged: Pending | null = null + let committed: Doc | null = null + let deleted: Doc | null | undefined + let notifySubmitted = false + const outcome = await storage.transaction(async (tx) => { + let liveRead: Promise | undefined + const readLive = () => + (liveRead ??= tx.getDocument(write.collection, write.docId)) + if ((await write.precondition?.(tx, readLive)) === false) return false + const live = await readLive() + if (write.session && writesLive && commitType !== 'delete') { + assertCollectionAccess( + write.session, + write.collection, + live ? 'update' : 'create', + live?.doc ?? content, + ) + assertCollectionAccess( + write.session, + write.collection, + 'publish', + live?.doc ?? content, + ) + } + if (write.expectedRevision !== undefined) + assertExpectedRevision(live?.doc ?? null, write.expectedRevision) + let changeSet: Pending | null = loaded.pending + for (const effect of effects) { + switch (effect.type) { + case 'stage': { + const incoming = write.incoming + if (!incoming) break + const latest = await tx.getPendingFor(write.collection, write.docId) + staged = { + id: latest?.id ?? randomUUID(), + version: (latest?.version ?? 0) + 1, + collection: write.collection, + docId: write.docId, + type: incoming.type, + before: latest + ? (latest.before ?? incoming.before ?? null) + : (incoming.before ?? null), + after: incoming.doc, + actor: write.by, + instruction: write.instruction ?? latest?.instruction, + createdAt: now, + source: write.source ?? stageSource(write), + baseRevision: + latest?.baseRevision ?? + (typeof live?.doc._revision === 'number' + ? live.doc._revision + : undefined), + } + await tx.putPending(staged) + changeSet = staged + break + } + case 'commit': + if (commitType === 'delete') { + deleted = await commitDeletion( + tx, + write.collection, + write.docId, + { + actor: author, + summary: + write.summary ?? + changeSet?.instruction ?? + `Approved delete from ${author}`, + force: write.forceDelete, + ...(changeSet ? { auditId: changeSet.id } : {}), + auditActor, + auditAction: action.type, + eventActor, + ...(eventAuthor ? { eventAuthor } : {}), + session: write.session, + }, + now, + ) + break + } + committed = await writeLive(tx, live, content, { + fromChangeSet: !write.incoming || stagesFirst, + consumed: changeSet, + }) + break + case 'publish': + case 'unpublish': + case 'schedule': + if (!has('commit') && !committed) + committed = await writeLive(tx, live, content, { + fromChangeSet: false, + consumed: null, + }) + break + case 'discard': { + const target = changeSet ?? loaded.pending + 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, + collection: write.collection, + documentId: write.docId, + actor: eventActor, + occurredAt: now, + ...(eventAuthor ? { author: eventAuthor } : {}), + payload: target + ? { pendingId: target.id, type: target.type, ...extra } + : extra, + }) + if (effect.event === 'review.submitted') notifySubmitted = true + break + } + } + } + const decisionValue = auditDecision(action, effects) + if (decisionValue && commitType !== 'delete') { + const target = actsOnChangeSet ? (changeSet ?? loaded.pending) : null + await recordAudit(tx, { + ...(target ? { id: target.id } : {}), + collection: write.collection, + docId: write.docId, + type: commitType ?? target?.type ?? 'update', + actor: auditActor, + action: action.type, + decision: decisionValue, + at: now, + }) + } + return true + }) + + function eventBefore(live: IndexedDocumentRecord | null): Doc | null { + const incoming = write.incoming + if (incoming?.prepared === 'commit' && incoming.before !== undefined) + return incoming.before + return live?.doc ?? null + } + + async function writeLive( + tx: StorageOps, + live: IndexedDocumentRecord | null, + doc: Doc | null, + opts: { fromChangeSet: boolean; consumed: Pending | null }, + ): Promise { + if (!doc) throw new CmsError('There is no change to commit.', 'CONFLICT') + await assertSingletonSlot(tx, collection, write.docId) + await checkFieldRules(tx, collection, write.docId, doc, { + validators: false, + }) + const revision = (await tx.maxRevision(write.collection, write.docId)) + 1 + const final: Doc = { ...doc, _revision: revision, _updatedAt: now } + await writeDocument(tx, write.collection, write.docId, final, now) + if (opts.fromChangeSet && opts.consumed) { + await tx.deletePending(opts.consumed.id) + } else if (has('commit')) { + const draft = await tx.getPendingFor(write.collection, write.docId) + if (draft?.source === 'draft') await tx.deletePending(draft.id) + } + await recordRevision(tx, { + collection: write.collection, + docId: write.docId, + revision, + doc: final, + actor: author, + summary: + summary ?? + (opts.fromChangeSet && opts.consumed + ? (opts.consumed.instruction ?? + `Approved ${opts.consumed.type} from ${opts.consumed.actor}`) + : live + ? 'Edited document' + : 'Created document'), + at: now, + }) + await enqueueDocumentChange(tx, { + collection: write.collection, + id: write.docId, + actor: eventActor, + ...(eventAuthor ? { author: eventAuthor } : {}), + before: eventBefore(live), + after: final, + occurredAt: now, + }) + return final + } + + const key = strategyKey(strategy) + if (!outcome) { + return { + strategy: key, + state: decided.state, + effects, + pending: null, + committed: null, + deleted: false, + skipped: true, + } + } + notifyStorageCommit() + const decidedPending: Pending | null = + staged ?? (actsOnChangeSet ? loaded.pending : null) + if (committed) { + const doc: Doc = committed + await runAfterChange(collection, { + doc, + id: write.docId, + operation, + actor: author, + }) + emitCommit( + write.collection, + write.docId, + eventActor, + eventBefore(liveRow), + doc, + ) + } + if (deleted !== undefined) { + await runAfterDelete(collection, { id: write.docId, actor: author }) + emitCmsEvent('delete', { + collection: write.collection, + id: write.docId, + actor: eventActor, + ...(deleted ? { doc: deleted } : {}), + }) + } + if (notifySubmitted && staged) notifyReviewSubmitted(staged, write.incoming) + if (has('discard') && decidedPending) await cleanupDiscarded(decidedPending) + return { + strategy: key, + state: decided.state, + effects, + pending: decidedPending, + committed, + deleted: deleted !== undefined, + skipped: false, + } +} + +function stageSource(write: StrategyWrite): PendingSource { + if (write.action.type === 'draft') return 'draft' + return actorOf(write.ctx).type === 'agent' ? 'agent' : 'review' +} + +function notifyReviewSubmitted( + pending: Pending, + incoming: IncomingChange | undefined, +): void { + const before = incoming?.before + const assignee = + typeof pending.after._assignee === 'string' + ? pending.after._assignee + : typeof before?._assignee === 'string' + ? before._assignee + : undefined + queueNotification({ + type: 'review.submitted', + collection: pending.collection, + documentId: pending.docId, + actor: pending.actor, + ...(assignee ? { recipient: assignee } : {}), + title: `${pending.collection}/${pending.docId} entered review (${pending.type})`, + at: pending.createdAt, + }) +} + +/** + * A discarded staged asset *create* leaves an uploaded blob with no + * document; delete the orphaned bytes. Discarding an asset *update* keeps + * the committed asset and its blob. + */ +async function cleanupDiscarded(pending: Pending): Promise { + if ( + pending.type === 'create' && + pending.collection === assetCollectionName() && + typeof pending.after?.blobKey === 'string' + ) { + await deleteAssetBlob(pending.after.blobKey) + } +} + +// --------------------------------------------------------------------------- +// Preparing incoming changes +// --------------------------------------------------------------------------- + +/** + * Validate a change the way staging does: `preValidate`, the schema and the + * field rules. `type` is recomputed from whether a live document exists. + */ +const STAGE_BEFORE_READ = systemContext('staging: the committed document') + +export async function prepareStagedChange( + collection: Collection, + docId: string, + doc: Record, + options: { delete?: boolean; actor: string; existing?: Pending | null }, +): Promise { + const storage = await getStorage() + const beforeRow = await storage.getDocument(collection.name, docId) + const before = beforeRow + ? await applyPostRead( + collection.name, + docId, + beforeRow.doc, + STAGE_BEFORE_READ, + ) + : null + const baseRevision = + typeof beforeRow?.doc._revision === 'number' + ? beforeRow.doc._revision + : undefined + if (options.delete) { + const existing = + options.existing === undefined + ? await storage.getPendingFor(collection.name, docId) + : options.existing + if (!before && !existing) { + throw new CmsError( + `No ${collection.name} document with id "${docId}".`, + 'NOT_FOUND', + ) + } + return { + type: 'delete', + doc: before ?? existing?.after ?? {}, + prepared: 'stage', + before, + baseRevision, + } + } + if (!before) await assertSingletonSlot(storage, collection, docId) + const type: WriteType = before ? 'update' : 'create' + const incoming = await upgradeIncomingDoc(collection.name, docId, doc as Doc) + let after = validate( + collection, + await runPreValidate( + collection, + { ...emptyDoc(collection), ...incoming }, + docId, + type, + options.actor, + ), + ) + await checkFieldRules(storage, collection, docId, after) + after = stampContentVersion(collection.name, after) + return { type, doc: after, prepared: 'stage', before, baseRevision } +} + +/** + * The generic door: run `action` on a document as `ctx`. A `patch` is + * validated the way staging does first. Core's rules apply; a refused + * decision is audited and thrown as `FORBIDDEN`. + */ +export async function actOnDocument( + ctx: AccessContext, + args: { collection: string; id: string; action: Action }, +): Promise { + const collection = requireWritableCollection(args.collection) + const by = actorOf(ctx).id + const incoming = args.action.patch + ? await prepareStagedChange(collection, args.id, args.action.patch, { + actor: by, + }) + : undefined + return executeStrategyWrite({ + ctx, + by, + collection: args.collection, + docId: args.id, + action: incoming ? { ...args.action, patch: incoming.doc } : args.action, + incoming, + ...(ctx.session ? { session: ctx.session } : {}), + }) +} diff --git a/packages/core/src/server/store/review.ts b/packages/core/src/server/store/review.ts index 41e9c9b1..0dfc01a6 100644 --- a/packages/core/src/server/store/review.ts +++ b/packages/core/src/server/store/review.ts @@ -1,48 +1,26 @@ /** * The review gate: staging writes, drafts, approving and rejecting - * pending changes, and the audit log. + * pending changes, and the audit log. Each door is an action the + * collection's document state strategy decides. * * Server-only. */ import { randomUUID } from 'node:crypto' -import { emitCmsEvent } from '../events' -import { queueNotification } from '../notifications' -import { enqueueDocumentChange, enqueueEvent } from '../outbox' -import { deleteAssetBlob } from '../media-store' import { CmsError } from '../../errors' -import { getCmsConfig } from '../../config' -import { assetCollectionName, emptyDoc } from '../../schema' +import { getStorage } from '../storage' +import { agentContext, accessContext, systemContext } from '../access-context' import { - stampContentVersion, - upgradeIncomingDoc, - upgradeStoredDoc, -} from '../content-migrations' -import { getStorage, notifyStorageCommit } from '../storage' -import { - applyPostRead, assertExpectedRevision, assertSingletonSlot, checkFieldRules, - emitCommit, - recordAudit, - recordRevision, requireWritableCollection, - runAfterChange, - runAfterDelete, - runPreValidate, - runPostValidate, - runPreDelete, - validate, - writeDocument, } from './internal' import { readDocument } from './read' -import { commitDeletion } from './write' -import { assertCollectionAccess } from '../auth' -import { protectWrite } from '../access' -import { systemContext } from '../access-context' +import { executeStrategyWrite, prepareStagedChange } from './document-state' import type { CmsSession } from '../../lib/auth' -import type { Doc } from '../../schema' import type { PendingSource, StorageOps, WriteType } from '../../storage/types' +import type { AccessContext } from '../../lib/access-context' +import type { IncomingChange, StrategyOutcome } from './document-state' import type { AuditEntry, Pending } from './internal' export interface StageWriteArgs { @@ -55,167 +33,103 @@ export interface StageWriteArgs { source?: PendingSource expectedRevision?: number expectedPendingVersion?: number + /** + * Who is writing. Defaults to an agent context for `source: 'agent'` + * (the default) and a system context for author saves and drafts. + */ + ctx?: AccessContext +} + +function stageContext(args: StageWriteArgs, source: PendingSource) { + if (args.ctx) return args.ctx + return source === 'agent' + ? agentContext({ agent: args.actor }) + : systemContext(`${source} write by ${args.actor}`) } /** - * Validate and stage a write in the review queue. Nothing touches committed - * documents until someone approves. A second staged write for the same - * document coalesces into the existing pending entry. + * Stage a write as the strategy's `submit` (or `draft`) action and return + * the decision's outcome: the change set it staged, and the committed + * document when the strategy committed it at once (auto-approval, `direct`). */ -const STAGE_BEFORE_READ = systemContext('stageWrite: the committed document') - -export async function stageWrite(args: StageWriteArgs): Promise { +export async function submitWrite( + args: StageWriteArgs, +): Promise { const collection = requireWritableCollection(args.collection) - const storage = await getStorage() - const beforeRow = await storage.getDocument(args.collection, args.docId) - const before = beforeRow - ? await applyPostRead( - args.collection, - args.docId, - beforeRow.doc, - STAGE_BEFORE_READ, + const source = args.source ?? 'agent' + const incoming = await prepareStagedChange(collection, args.docId, args.doc, { + delete: args.type === 'delete', + actor: args.actor, + }) + const outcome = await executeStrategyWrite({ + ctx: stageContext(args, source), + by: args.actor, + collection: args.collection, + docId: args.docId, + action: { type: source === 'draft' ? 'draft' : 'submit' }, + incoming, + source, + ...(args.instruction ? { instruction: args.instruction } : {}), + approvedBy: 'auto-approve', + async precondition(tx, readLive) { + const live = await readLive() + assertExpectedRevision( + live?.doc ?? null, + args.expectedRevision ?? incoming.baseRevision ?? 0, ) - : null - const existing = await storage.getPendingFor(args.collection, args.docId) - - let type: WriteType - let after: Doc - if (args.type === 'delete') { - if (!before && !existing) { - throw new CmsError( - `No ${args.collection} document with id "${args.docId}".`, - 'NOT_FOUND', + if (!live) await assertSingletonSlot(tx, collection, args.docId) + if (incoming.type !== 'delete') + await checkFieldRules(tx, collection, args.docId, incoming.doc, { + validators: false, + }) + const latest = await tx.getPendingFor(args.collection, args.docId) + if ( + args.expectedPendingVersion !== undefined && + args.expectedPendingVersion !== (latest?.version ?? 0) ) - } - type = 'delete' - after = before ?? existing?.after ?? {} - } else { - if (!before) await assertSingletonSlot(storage, collection, args.docId) - type = before ? 'update' : 'create' - const incoming = await upgradeIncomingDoc( - args.collection, - args.docId, - args.doc as Doc, - ) - after = validate( - collection, - await runPreValidate( - collection, - { ...emptyDoc(collection), ...incoming }, - args.docId, - type, - args.actor, - ), - ) - await checkFieldRules(storage, collection, args.docId, after) - after = stampContentVersion(args.collection, after) - } - - const baseRevision = - typeof beforeRow?.doc._revision === 'number' - ? beforeRow.doc._revision - : undefined - const source = args.source ?? 'agent' - // A draft is the author's own private save; it has not "entered review". - const entersReview = source !== 'draft' - let shouldAutoApprove = false - if (entersReview) { - try { - const rule = getCmsConfig().review?.autoApprove - if (typeof rule === 'boolean') { - shouldAutoApprove = rule - } else if (typeof rule === 'function') { - shouldAutoApprove = Boolean( - await rule({ - collection: args.collection, - docId: args.docId, - type, - actor: args.actor, - source, - }), + throw new CmsError( + 'The pending document changed. Reload it before saving.', + 'CONFLICT', ) - } - } catch { - shouldAutoApprove = false - } - } - const pending = await storage.transaction(async (tx) => { - const current = await tx.getDocument(args.collection, args.docId) - assertExpectedRevision( - current?.doc ?? null, - args.expectedRevision ?? baseRevision ?? 0, - ) - if (!current) await assertSingletonSlot(tx, collection, args.docId) - if (args.type !== 'delete') - await checkFieldRules(tx, collection, args.docId, after, { - validators: false, - }) - const latest = await tx.getPendingFor(args.collection, args.docId) - if ( - args.expectedPendingVersion !== undefined && - args.expectedPendingVersion !== (latest?.version ?? 0) - ) - throw new CmsError( - 'The pending document changed. Reload it before saving.', - 'CONFLICT', - ) - const record: Pending = { - id: latest?.id ?? randomUUID(), - version: (latest?.version ?? 0) + 1, - collection: args.collection, - docId: args.docId, - type, - before: latest ? (latest.before ?? before) : before, - after, - actor: args.actor, - instruction: args.instruction, - createdAt: new Date().toISOString(), - source, - baseRevision: latest?.baseRevision ?? baseRevision, - } - await tx.putPending(record) - // Record the "entered review" event in the same transaction as the stage, - // so a durable handler and the notifier see every submission exactly once. - if (entersReview && !shouldAutoApprove && !latest) { - await enqueueEvent(tx, { - type: 'review.submitted', - collection: record.collection, - documentId: record.docId, - actor: record.actor, - occurredAt: record.createdAt, - payload: { - pendingId: record.id, - type: record.type, - source: record.source, - ...(record.instruction ? { instruction: record.instruction } : {}), - }, - }) - } - return record + }, }) - if (shouldAutoApprove) { - return approve(pending.id, { approver: 'auto-approve', force: true }) - } - // Fire the notification off the write path (coalesced re-stages of an - // existing proposal do not re-notify — only the first submission does). - if (entersReview && pending.version === 1) { - const assignee = - typeof pending.after._assignee === 'string' - ? pending.after._assignee - : typeof before?._assignee === 'string' - ? before._assignee - : undefined - queueNotification({ - type: 'review.submitted', - collection: pending.collection, - documentId: pending.docId, - actor: pending.actor, - ...(assignee ? { recipient: assignee } : {}), - title: `${pending.collection}/${pending.docId} entered review (${pending.type})`, - at: pending.createdAt, + return { ...outcome, change: incoming } +} + +/** + * Validate and stage a write in the review queue. Nothing touches committed + * documents until someone approves. A second staged write for the same + * document coalesces into the existing pending entry. + */ +export async function stageWrite(args: StageWriteArgs): Promise { + const outcome = await submitWrite(args) + const pending = outcome.pending + if (pending) + return outcome.committed + ? { ...pending, after: outcome.committed } + : pending + if (!outcome.committed && !outcome.deleted) + throw new CmsError('The write was not staged.', 'CONFLICT', { + effects: outcome.effects, }) + // The strategy committed without staging (`direct`): describe the change + // the way a staged-and-approved one reads. + return { + id: randomUUID(), + version: 1, + collection: args.collection, + docId: args.docId, + type: outcome.change.type, + before: outcome.change.before ?? null, + after: outcome.committed ?? outcome.change.doc, + actor: args.actor, + ...(args.instruction ? { instruction: args.instruction } : {}), + createdAt: new Date().toISOString(), + source: args.source ?? 'agent', + ...(outcome.change.baseRevision === undefined + ? {} + : { baseRevision: outcome.change.baseRevision }), } - return pending } export async function listPending(options?: { @@ -243,6 +157,8 @@ export interface ApproveOptions { forceDelete?: boolean expectedVersion?: number session?: CmsSession + /** Who is approving. Defaults to the session's context, else a system one. */ + ctx?: AccessContext } async function assertPendingCurrent( @@ -271,10 +187,9 @@ async function assertPendingCurrent( } } -/** Commit a staged change: writes the document, a revision, and an audit entry. */ -export async function approve( +async function requirePending( pendingId: string, - options?: ApproveOptions, + expectedVersion: number | undefined, ): Promise { const storage = await getStorage() const pending = await storage.getPending(pendingId) @@ -282,184 +197,76 @@ export async function approve( throw new CmsError(`Unknown pending change: ${pendingId}`, 'NOT_FOUND') } if ( - options?.expectedVersion !== undefined && - options.expectedVersion !== (pending.version ?? 0) + expectedVersion !== undefined && + expectedVersion !== (pending.version ?? 0) ) throw new CmsError( 'This proposal changed. Reload the review queue.', 'CONFLICT', ) - await assertPendingCurrent(storage, pending, options?.force) - const collection = requireWritableCollection(pending.collection) - const now = new Date().toISOString() - const auditActor = options?.approver - ? `${pending.actor} (approved by ${options.approver})` - : pending.actor + return pending +} - if (pending.type === 'delete') { - await runPreDelete(collection, pending.docId, pending.actor) - const deleted = await storage.transaction(async (tx) => { - await assertPendingCurrent(tx, pending, options?.force) - const removed = await commitDeletion( - tx, - pending.collection, - pending.docId, - { - actor: pending.actor, - summary: - pending.instruction ?? `Approved delete from ${pending.actor}`, - force: options?.forceDelete, - auditId: pending.id, - auditActor, - session: options?.session, - }, - now, - ) - await enqueueEvent(tx, { - type: 'review.approved', - collection: pending.collection, - documentId: pending.docId, - actor: auditActor, - occurredAt: now, - payload: { pendingId: pending.id, type: pending.type }, - }) - return removed - }) - notifyStorageCommit() - await runAfterDelete(collection, { - id: pending.docId, - actor: pending.actor, - }) - emitCmsEvent('delete', { - collection: pending.collection, - id: pending.docId, - actor: pending.actor, - ...(deleted ? { doc: deleted } : {}), - }) - return pending - } +function deciderContext( + ctx: AccessContext | undefined, + session: CmsSession | undefined, + reason: string, +): AccessContext { + if (ctx) return ctx + return session + ? accessContext({ session, mode: 'edit' }) + : systemContext(reason) +} +/** + * Commit a staged change as the strategy's `approve` action: writes the + * document, a revision, and an audit entry. Events name the approver as the + * actor and the proposer as the author. + */ +export async function approve( + pendingId: string, + options?: ApproveOptions, +): Promise { + const pending = await requirePending(pendingId, options?.expectedVersion) + const storage = await getStorage() + await assertPendingCurrent(storage, pending, options?.force) + const approver = options?.approver const existingRow = await storage.getDocument( pending.collection, pending.docId, ) - const operation: 'create' | 'update' = existingRow ? 'update' : 'create' - let doc: Doc = { - ...(await upgradeStoredDoc( - pending.collection, - pending.docId, - pending.after, - )), - ...(typeof options?.publish === 'boolean' - ? { published: options.publish } + const outcome = await executeStrategyWrite({ + ctx: deciderContext(options?.ctx, options?.session, 'approve'), + by: approver ?? pending.actor, + collection: pending.collection, + docId: pending.docId, + action: { + type: 'approve', + ...(typeof options?.publish === 'boolean' + ? { input: { publish: options.publish } } + : {}), + }, + pending, + author: pending.actor, + auditActor: approver + ? `${pending.actor} (approved by ${approver})` + : pending.actor, + eventActor: approver ?? pending.actor, + ...(options?.session ? { session: options.session } : {}), + ...(options?.forceDelete ? { forceDelete: true } : {}), + ...(options?.force && pending.type !== 'delete' + ? { + expectedRevision: + typeof existingRow?.doc._revision === 'number' + ? existingRow.doc._revision + : 0, + } : {}), - } - if (options?.session) - doc = protectWrite( - pending.collection, - doc, - existingRow?.doc, - options.session, - ) - doc = await runPostValidate( - collection, - doc, - pending.docId, - operation, - pending.actor, - ) - doc = { ...doc, ...validate(collection, doc) } - if (collection) { - await checkFieldRules(storage, collection, pending.docId, doc) - } - - const committed = await storage.transaction(async (tx) => { - await assertPendingCurrent(tx, pending, options?.force) - if (options?.session) { - const live = await tx.getDocument(pending.collection, pending.docId) - assertCollectionAccess( - options.session, - pending.collection, - live ? 'update' : 'create', - live?.doc ?? doc, - ) - assertCollectionAccess( - options.session, - pending.collection, - 'publish', - live?.doc ?? doc, - ) - } - if (options?.force) { - const live = await tx.getDocument(pending.collection, pending.docId) - assertExpectedRevision( - live?.doc ?? null, - typeof existingRow?.doc._revision === 'number' - ? existingRow.doc._revision - : 0, - ) - } - await assertSingletonSlot(tx, collection, pending.docId) - await checkFieldRules(tx, collection, pending.docId, doc, { - validators: false, - }) - const revision = - (await tx.maxRevision(pending.collection, pending.docId)) + 1 - const final: Doc = { ...doc, _revision: revision, _updatedAt: now } - await writeDocument(tx, pending.collection, pending.docId, final, now) - await tx.deletePending(pendingId) - await recordRevision(tx, { - collection: pending.collection, - docId: pending.docId, - revision, - doc: final, - actor: pending.actor, - summary: - pending.instruction ?? `Approved ${pending.type} from ${pending.actor}`, - at: now, - }) - await recordAudit(tx, { - id: pending.id, - collection: pending.collection, - docId: pending.docId, - type: pending.type, - actor: auditActor, - decision: 'approved', - at: now, - }) - await enqueueDocumentChange(tx, { - collection: pending.collection, - id: pending.docId, - actor: pending.actor, - before: existingRow?.doc ?? null, - after: final, - occurredAt: now, - }) - await enqueueEvent(tx, { - type: 'review.approved', - collection: pending.collection, - documentId: pending.docId, - actor: auditActor, - occurredAt: now, - payload: { pendingId: pending.id, type: pending.type }, - }) - return final - }) - notifyStorageCommit() - await runAfterChange(collection, { - doc: committed, - id: pending.docId, - operation, - actor: pending.actor, + async precondition(tx) { + await assertPendingCurrent(tx, pending, options?.force) + }, }) - emitCommit( - pending.collection, - pending.docId, - pending.actor, - existingRow?.doc ?? null, - committed, - ) - return { ...pending, after: committed } + return outcome.committed ? { ...pending, after: outcome.committed } : pending } /** @@ -476,6 +283,7 @@ export async function saveDraft( expectedRevision?: number expectedPendingVersion?: number summary?: string + ctx?: AccessContext }, ): Promise { const live = await readDocument(collectionName, id) @@ -490,81 +298,74 @@ export async function saveDraft( instruction: options?.summary, expectedRevision: options?.expectedRevision, expectedPendingVersion: options?.expectedPendingVersion, + ...(options?.ctx ? { ctx: options.ctx } : {}), }) } -/** Throw away a document's draft. Returns false when there is none. */ +function assertVersion(pending: Pending) { + return async (tx: StorageOps): Promise => { + const current = await tx.getPending(pending.id) + if (!current || (current.version ?? 0) !== (pending.version ?? 0)) { + throw new CmsError( + 'This proposal was decided or changed. Reload the review queue.', + 'CONFLICT', + ) + } + } +} + +/** + * Throw away a document's draft as the strategy's `discard` action (audited + * as `discarded`; no review event). Returns false when there is none. + */ export async function discardDraft( collectionName: string, id: string, - options?: { actor?: string }, + options?: { actor?: string; ctx?: AccessContext }, ): Promise { const storage = await getStorage() const pending = await storage.getPendingFor(collectionName, id) if (!pending || pending.source !== 'draft') return false - await reject(pending.id, { rejecter: options?.actor }) + const by = options?.actor ?? pending.actor + await executeStrategyWrite({ + ctx: options?.ctx ?? systemContext('discard draft'), + by, + collection: collectionName, + docId: id, + action: { type: 'discard' }, + pending, + auditActor: options?.actor + ? `${pending.actor} (discarded by ${options.actor})` + : pending.actor, + precondition: assertVersion(pending), + }) return true } +/** Reject a staged change as the strategy's `reject` action. */ export async function reject( pendingId: string, - options?: { rejecter?: string; expectedVersion?: number }, + options?: { + rejecter?: string + expectedVersion?: number + ctx?: AccessContext + }, ): Promise { - const storage = await getStorage() - const pending = await storage.getPending(pendingId) - if (!pending) { - throw new CmsError(`Unknown pending change: ${pendingId}`, 'NOT_FOUND') - } - const now = new Date().toISOString() - if ( - options?.expectedVersion !== undefined && - options.expectedVersion !== (pending.version ?? 0) - ) - throw new CmsError( - 'This proposal changed. Reload the review queue.', - 'CONFLICT', - ) - await storage.transaction(async (tx) => { - const current = await tx.getPending(pendingId) - if (!current || (current.version ?? 0) !== (pending.version ?? 0)) { - throw new CmsError( - 'This proposal was decided or changed. Reload the review queue.', - 'CONFLICT', - ) - } - await tx.deletePending(pendingId) - const rejectActor = options?.rejecter - ? `${pending.actor} (rejected by ${options.rejecter})` - : pending.actor - await recordAudit(tx, { - id: pending.id, - collection: pending.collection, - docId: pending.docId, - type: pending.type, - actor: rejectActor, - decision: 'rejected', - at: now, - }) - await enqueueEvent(tx, { - type: 'review.rejected', - collection: pending.collection, - documentId: pending.docId, - actor: rejectActor, - occurredAt: now, - payload: { pendingId: pending.id, type: pending.type }, - }) + const pending = await requirePending(pendingId, options?.expectedVersion) + const rejectActor = options?.rejecter + ? `${pending.actor} (rejected by ${options.rejecter})` + : pending.actor + await executeStrategyWrite({ + ctx: options?.ctx ?? systemContext('reject'), + by: options?.rejecter ?? pending.actor, + collection: pending.collection, + docId: pending.docId, + action: { type: 'reject' }, + pending, + auditActor: rejectActor, + eventActor: rejectActor, + precondition: assertVersion(pending), }) - // Rejecting a staged asset *create* means the uploaded blob has no home: its - // document will never exist. Delete the orphaned bytes. (A reject of an asset - // *update* keeps the committed asset — and its blob — intact.) A full - // orphan-sweep for crashed uploads is phase 3 (see server/assets.ts). - if ( - pending.type === 'create' && - pending.collection === assetCollectionName() && - typeof pending.after?.blobKey === 'string' - ) { - await deleteAssetBlob(pending.after.blobKey) - } return pending } diff --git a/packages/core/src/server/store/scheduling.ts b/packages/core/src/server/store/scheduling.ts index 132ebaad..ae917b20 100644 --- a/packages/core/src/server/store/scheduling.ts +++ b/packages/core/src/server/store/scheduling.ts @@ -3,27 +3,11 @@ * * Server-only. */ -import { emitCmsEvent } from '../events' -import { enqueueDocumentChange } from '../outbox' import { CmsError } from '../../errors' import { cmsLogger } from '../../config' -import { upgradeStoredDoc } from '../content-migrations' -import { - getStorage, - notifyStorageCommit, - registerScheduledSweep, -} from '../storage' -import { - checkFieldRules, - collections, - recordAudit, - recordRevision, - runAfterChange, - runPreValidate, - runPostValidate, - validate, - writeDocument, -} from './internal' +import { systemContext } from '../access-context' +import { getStorage, registerScheduledSweep } from '../storage' +import { executeStrategyWrite } from './document-state' import { readDocument } from './read' import { stageWrite } from './review' import { commitDocument } from './write' @@ -31,100 +15,38 @@ import type { Doc } from '../../schema' import type { IndexedDocumentRecord, StorageAdapter } from '../../storage/types' import type { Pending } from './internal' -function sealScheduledDoc(doc: Doc, mode: 'publish' | 'unpublish'): Doc { - if (mode === 'publish') return { ...doc, published: true } - const { unpublishAt: _done, ...rest } = doc - return { ...rest, published: false } -} +const SCHEDULER = systemContext('scheduled publishing', { actor: 'scheduler' }) +/** + * Fire the strategy's `publish` / `unpublish` action as the scheduler. Skips + * (returns false) when the document changed since the sweep found it due. + */ async function applyScheduledDocument( - storage: StorageAdapter, row: IndexedDocumentRecord, nowIso: string, mode: 'publish' | 'unpublish', summary: string, ): Promise { - const col = collections()[row.collection] - const current = await upgradeStoredDoc(row.collection, row.id, row.doc) - let next = sealScheduledDoc(current, mode) - if (col) { - next = validate( - col, - await runPreValidate(col, next, row.id, 'update', 'scheduler'), - ) - await checkFieldRules(storage, col, row.id, next) - } - next = await runPostValidate(col, next, row.id, 'update', 'scheduler') - next = sealScheduledDoc(next, mode) - if (col) next = { ...next, ...validate(col, next) } - if (col) await checkFieldRules(storage, col, row.id, next) - const committed = await storage.transaction(async (tx) => { - const live = await tx.getDocument(row.collection, row.id) - if ( - !live || - live.doc._revision !== row.doc._revision || - (mode === 'publish' - ? live.published || live.publishAt !== row.publishAt - : !live.published || live.unpublishAt !== row.unpublishAt) - ) - return null - if (col) await checkFieldRules(tx, col, row.id, next, { validators: false }) - const revision = (await tx.maxRevision(row.collection, row.id)) + 1 - const doc: Doc = { - ...sealScheduledDoc(next, mode), - _revision: revision, - _updatedAt: nowIso, - } - await writeDocument(tx, row.collection, row.id, doc, nowIso) - await recordRevision(tx, { - collection: row.collection, - docId: row.id, - revision, - doc, - actor: 'scheduler', - summary, - at: nowIso, - }) - await recordAudit(tx, { - collection: row.collection, - docId: row.id, - type: 'update', - actor: 'scheduler', - decision: 'approved', - at: nowIso, - }) - await enqueueDocumentChange(tx, { - collection: row.collection, - id: row.id, - actor: 'scheduler', - before: current, - after: doc, - occurredAt: nowIso, - }) - return doc - }) - if (!committed) return false - notifyStorageCommit() - await runAfterChange(col, { - doc: committed, - id: row.id, - operation: 'update', - actor: 'scheduler', - }) - const event = mode === 'publish' ? 'publish' : 'unpublish' - emitCmsEvent('change', { - collection: row.collection, - id: row.id, - actor: 'scheduler', - doc: committed, - }) - emitCmsEvent(event, { + const outcome = await executeStrategyWrite({ + ctx: SCHEDULER, + by: 'scheduler', collection: row.collection, - id: row.id, - actor: 'scheduler', - doc: committed, + docId: row.id, + action: { type: mode }, + summary, + at: nowIso, + async precondition(_tx, readLive) { + const live = await readLive() + const due = + live !== null && + live.doc._revision === row.doc._revision && + (mode === 'publish' + ? !live.published && live.publishAt === row.publishAt + : live.published && live.unpublishAt === row.unpublishAt) + return due + }, }) - return true + return !outcome.skipped } export interface ScheduledPublishResult { @@ -145,7 +67,6 @@ async function publishDue( if (!publishAt || row.doc.published || publishAt > nowIso) continue try { const changed = await applyScheduledDocument( - storage, row, nowIso, 'publish', @@ -170,7 +91,6 @@ async function publishDue( if (!unpublishAt || unpublishAt > nowIso) continue try { await applyScheduledDocument( - storage, row, nowIso, 'unpublish', diff --git a/packages/core/src/server/store/write.ts b/packages/core/src/server/store/write.ts index db370da4..9f5ca1eb 100644 --- a/packages/core/src/server/store/write.ts +++ b/packages/core/src/server/store/write.ts @@ -4,7 +4,7 @@ * Server-only. */ import { emitCmsEvent } from '../events' -import { enqueueDocumentChange, enqueueDocumentDelete } from '../outbox' +import { enqueueDocumentDelete } from '../outbox' import { deleteAssetBlob } from '../media-store' import { CmsError } from '../../errors' import { assetCollectionName, emptyDoc } from '../../schema' @@ -14,11 +14,9 @@ import { assertExpectedRevision, assertSingletonSlot, checkFieldRules, - emitCommit, recordAudit, recordRevision, requireWritableCollection, - runAfterChange, runAfterDelete, runPreValidate, runPostValidate, @@ -29,6 +27,9 @@ import { import { findReferences, readDocument, readDocumentWithPending } from './read' import { stageWrite } from './review' import { assertCollectionAccess } from '../auth' +import { accessContext, systemContext } from '../access-context' +import { executeStrategyWrite } from './document-state' +import type { AccessContext } from '../access-context' import type { CmsSession } from '../../lib/auth' import type { Doc } from '../../schema' import type { Pending } from './internal' @@ -44,10 +45,12 @@ export interface CommitOptions { expectedRevision?: number expectedPendingVersion?: number session?: CmsSession + /** Who is committing. Defaults to the session's context, else a system one. */ + ctx?: AccessContext } /** - * Commit directly, bypassing the review queue (human editor, revision + * Commit directly as the strategy's `edit` action (human editor, revision * restore). A draft of this document (pending, source `draft`) is folded in: * committing it is how a draft gets published. */ @@ -98,71 +101,39 @@ export async function commitDocument( next = { ...next, ...validate(collection, next) } await checkFieldRules(storage, collection, id, next) - const now = new Date().toISOString() - const committed = await storage.transaction(async (tx) => { - if (options?.session) { - const current = await tx.getDocument(collectionName, id) - assertCollectionAccess( - options.session, - collectionName, - current ? 'update' : 'create', - current?.doc ?? next, - ) - assertCollectionAccess( - options.session, - collectionName, - 'publish', - current?.doc ?? next, - ) - } - await assertSingletonSlot(tx, collection, id) - if (options?.expectedRevision !== undefined) { - const current = await tx.getDocument(collectionName, id) - assertExpectedRevision(current?.doc ?? null, options.expectedRevision) - } - await checkFieldRules(tx, collection, id, next, { validators: false }) - const revision = (await tx.maxRevision(collectionName, id)) + 1 - const draft = await tx.getPendingFor(collectionName, id) - if ( - options?.expectedPendingVersion !== undefined && - options.expectedPendingVersion !== (draft?.version ?? 0) - ) - throw new CmsError( - 'The pending document changed. Reload it before saving.', - 'CONFLICT', - ) - const final: Doc = { ...next, _revision: revision, _updatedAt: now } - await writeDocument(tx, collectionName, id, final, now) - if (draft?.source === 'draft') await tx.deletePending(draft.id) - await recordRevision(tx, { - collection: collectionName, - docId: id, - revision, - doc: final, - actor, - summary: - options?.summary ?? (existing ? 'Edited document' : 'Created document'), - at: now, - }) - await enqueueDocumentChange(tx, { - collection: collectionName, - id, - actor, + const outcome = await executeStrategyWrite({ + ctx: + options?.ctx ?? + (options?.session + ? accessContext({ session: options.session, mode: 'edit' }) + : systemContext('commitDocument')), + by: actor, + collection: collectionName, + docId: id, + action: { type: 'edit' }, + incoming: { + type: operation, + doc: next, + prepared: 'commit', before: existing, - after: final, - occurredAt: now, - }) - return final - }) - notifyStorageCommit() - await runAfterChange(collection, { - doc: committed, - id, - operation, - actor, + }, + ...(options?.summary ? { summary: options.summary } : {}), + ...(options?.session ? { session: options.session } : {}), + async precondition(tx, readLive) { + const current = await readLive() + if (options?.expectedRevision !== undefined) + assertExpectedRevision(current?.doc ?? null, options.expectedRevision) + if (options?.expectedPendingVersion !== undefined) { + const draft = await tx.getPendingFor(collectionName, id) + if (options.expectedPendingVersion !== (draft?.version ?? 0)) + throw new CmsError( + 'The pending document changed. Reload it before saving.', + 'CONFLICT', + ) + } + }, }) - emitCommit(collectionName, id, actor, existing, committed) - return committed + return outcome.committed ?? outcome.pending?.after ?? next } export interface DeleteOptions { @@ -296,6 +267,12 @@ export async function commitDeletion( purge?: boolean auditId?: string auditActor?: string + /** The strategy action audited with the deletion. */ + auditAction?: string + /** The `document.deleted` event's actor (default `actor`). */ + eventActor?: string + /** Who proposed the deletion, when `eventActor` decided it. */ + eventAuthor?: string session?: CmsSession }, now: string, @@ -361,13 +338,15 @@ export async function commitDeletion( docId: id, type: 'delete', actor: options.auditActor ?? actor, + ...(options.auditAction ? { action: options.auditAction } : {}), decision: 'approved', at: now, }) await enqueueDocumentDelete(tx, { collection: collectionName, id, - actor, + actor: options.eventActor ?? actor, + ...(options.eventAuthor ? { author: options.eventAuthor } : {}), last: stored, occurredAt: now, }) @@ -416,13 +395,15 @@ export async function commitDeletion( docId: id, type: 'delete', actor: options.auditActor ?? actor, + ...(options.auditAction ? { action: options.auditAction } : {}), decision: 'approved', at: now, }) await enqueueDocumentDelete(tx, { collection: collectionName, id, - actor, + actor: options.eventActor ?? actor, + ...(options.eventAuthor ? { author: options.eventAuthor } : {}), last: existingRow?.doc ?? pendingRow?.after ?? null, occurredAt: now, }) diff --git a/packages/core/src/server/transfer.ts b/packages/core/src/server/transfer.ts index bc625c36..d8483785 100644 --- a/packages/core/src/server/transfer.ts +++ b/packages/core/src/server/transfer.ts @@ -14,7 +14,16 @@ import { requireStorageCapability } from '../storage/capabilities' import { denormalize } from './indexing' import { resolveMediaAdapter } from './media' import { getStorage, resolveStorageAdapter, uniqueFieldSpecs } from './storage' +import { enqueueEvent } from './outbox' +import { systemContext } from './access-context' +import { + decideStrategyWrite, + refuseDecision, + sealVisibility, +} from './store/document-state' +import { recordAudit } from './store/internal' import { stageWrite } from './store/review' +import type { RefusedDecision } from './store/document-state' import type { Doc } from '../schema' import type { ApiKeyRecord, @@ -184,7 +193,7 @@ export interface ImportOptions { * collections that are not in the file. */ mode?: ImportMode - /** Recorded as the revision actor. Default `import`. */ + /** Recorded as the revision, audit and event actor. Default `import`. */ actor?: string /** * When true, stage every imported document into the Governance review queue @@ -288,8 +297,13 @@ async function writeDocument( } /** - * Restore an export. Documents are written as-is (no hooks, validation, or - * review queue): this is a restore path, not an editing path. + * Restore an export. Each document is an `import` action decided by its + * collection's document state strategy (actor `import`, or `options.actor`); + * the strategy decides visibility, and documents are otherwise written as-is + * (no hooks or validation): this is a restore path, not an editing path. + * Every write is audited and emits `import.document`, and the import emits + * `import.completed`; it does not emit `document.*`, so a restore doesn't + * refire publication side effects. */ export async function importContent( data: CmsExport, @@ -354,6 +368,7 @@ export async function importContent( doc: entry.doc, actor, instruction: 'Imported', + ctx: systemContext(actor, { actor: 'import' }), }) if (existingDoc) result.updated++ else result.created++ @@ -361,6 +376,8 @@ export async function importContent( return result } + const ctx = systemContext(actor, { actor: 'import' }) + let refused: RefusedDecision | null = null // Every read happens before the first write, so adapters that commit // queued writes on a read (D1) still apply the import as one batch. await storage.transaction(async (tx) => { @@ -432,6 +449,91 @@ export async function importContent( } } + // Decide every write before the first one; a refusal writes nothing. + const sealed = new Map() + const decided = new Set() + for (const entry of writable) { + const k = key(entry.collection, entry.id) + if (decided.has(k)) continue + decided.add(k) + if (existing.has(k) && mode === 'skip-existing') continue + const decision = await decideStrategyWrite(tx, { + ctx, + by: actor, + collection: entry.collection, + docId: entry.id, + action: { type: 'import' }, + incoming: { + type: existing.has(k) ? 'update' : 'create', + doc: entry.doc, + prepared: 'raw', + }, + }) + if (!decision.ok) { + refused = decision.refused + return + } + if (!decision.effects.some((e) => e.type === 'commit')) { + refused = { + collection: entry.collection, + docId: entry.id, + by: actor, + action: decision.action, + 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.`, + } + return + } + sealed.set( + k, + sealVisibility(entry.doc, decision.effects, decision.loaded.liveRow), + ) + } + for (const { collection, id } of stale) { + const decision = await decideStrategyWrite(tx, { + ctx, + by: actor, + collection, + docId: id, + action: { type: 'import' }, + incoming: { type: 'delete', doc: {}, prepared: 'raw' }, + }) + if (!decision.ok) { + refused = decision.refused + return + } + } + + const imported = async ( + collection: string, + id: string, + type: 'create' | 'update' | 'delete', + revision?: number, + ) => { + await recordAudit(tx, { + collection, + docId: id, + type, + actor, + action: 'import', + decision: 'approved', + at: now, + }) + await enqueueEvent(tx, { + type: 'import.document', + collection, + documentId: id, + actor, + occurredAt: now, + payload: { + collection, + id, + type, + ...(revision === undefined ? {} : { revision }), + }, + }) + } for (const entry of writable) { const k = key(entry.collection, entry.id) if (existing.has(k) && mode === 'skip-existing') { @@ -440,7 +542,7 @@ export async function importContent( } const written = await writeDocument( tx, - entry, + { ...entry, doc: sealed.get(k) ?? entry.doc }, revisionsByDoc.get(k) ?? [], maxRevision.get(k) ?? 0, actor, @@ -448,6 +550,12 @@ export async function importContent( ) maxRevision.set(k, written.revision) result.revisions += written.inserted + await imported( + entry.collection, + entry.id, + existing.has(k) ? 'update' : 'create', + written.revision, + ) if (existing.has(k)) result.updated++ else { result.created++ @@ -457,6 +565,7 @@ export async function importContent( for (const { collection, id } of stale) { await tx.deletePendingFor(collection, id) await tx.deleteDocument(collection, id) + await imported(collection, id, 'delete') result.deleted++ } for (const m of newMedia.values()) { @@ -479,7 +588,21 @@ export async function importContent( for (const apiKey of data.workflow.apiKeys) await keys.putApiKey(apiKey) } } + await enqueueEvent(tx, { + type: 'import.completed', + actor, + occurredAt: now, + payload: { + created: result.created, + updated: result.updated, + skipped: result.skipped, + deleted: result.deleted, + revisions: result.revisions, + media: result.media, + }, + }) }) + if (refused) await refuseDecision(refused) return result } diff --git a/packages/core/src/storage.ts b/packages/core/src/storage.ts index 21a7403c..6e186a55 100644 --- a/packages/core/src/storage.ts +++ b/packages/core/src/storage.ts @@ -48,6 +48,7 @@ export type { ApiKeyRecord, AuthUserRecord, UserRoleMappingRecord, + AuditDecision, AuditRecord, CommentOps, CommentRecord, diff --git a/packages/core/src/storage/sql-storage.ts b/packages/core/src/storage/sql-storage.ts index 94d2237b..dc08e2fa 100644 --- a/packages/core/src/storage/sql-storage.ts +++ b/packages/core/src/storage/sql-storage.ts @@ -18,6 +18,7 @@ import type { SqlDriver, SqlExecutor, SqlValue } from './sql-driver' import type { ApiKeyRecord, AuthUserRecord, + AuditDecision, AuditRecord, CommentRecord, DeadLetterRecord, @@ -898,7 +899,7 @@ function opsFor(db: SqlExecutor): StorageOps { doc_id: string | null type: WriteType | null actor: string - decision: 'approved' | 'rejected' | null + decision: AuditDecision | null action: string | null target: string | null at: string diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts index 90e11c01..88cd295b 100644 --- a/packages/core/src/storage/types.ts +++ b/packages/core/src/storage/types.ts @@ -96,19 +96,24 @@ export interface PendingRecord { * non-document admin actions (API-key create/revoke, settings changes, …): * such entries set `action` and `target` and omit the doc-centric fields. * - * Back-compat: an entry with no `action` is a review decision (its `decision` - * field is set); an entry with an `action` is a generic admin action. Never + * 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 + * `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 interface AuditRecord { id: string actor: string at: string /** - * The action category for non-review entries, e.g. `apikey.create`, - * `apikey.revoke`, `settings.update`. Absent on legacy review-decision - * entries (identified by `decision`). + * The action: a document state strategy action on document entries + * (`edit`, `approve`, …), a category on admin entries (`apikey.create`, + * `apikey.revoke`, `settings.update`). Absent on older document entries. */ action?: string /** @@ -116,11 +121,17 @@ export interface AuditRecord { * prefix, a user id, a setting key). Never a secret. */ target?: string - // Document-centric fields — present on review-decision entries. + // Document-centric fields — present on document entries. collection?: string docId?: string type?: WriteType - decision?: 'approved' | 'rejected' + /** + * `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. + */ + decision?: AuditDecision } export interface RevisionRecord { diff --git a/packages/core/tests/characterization/workflow-suite.ts b/packages/core/tests/characterization/workflow-suite.ts index 89148a6e..207a4d4d 100644 --- a/packages/core/tests/characterization/workflow-suite.ts +++ b/packages/core/tests/characterization/workflow-suite.ts @@ -15,8 +15,9 @@ * Rows labelled `known bug, fixed in phase 4 (#N: …)`, with the test name * 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. N is the - * decision number: + * 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): * #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 @@ -78,6 +79,8 @@ const DURABLE_EVENTS = [ 'document.published', 'document.unpublished', 'document.deleted', + 'import.document', + 'import.completed', ] as const /** Far enough ahead that the store's own throttled sweep never finds it due. */ @@ -132,7 +135,9 @@ export function runWorkflowCharacterization( id: `characterize-${type}`, on: type, run: ({ event }) => { - durable.push(`${event.type} by ${event.actor}`) + durable.push( + `${event.type} by ${event.actor}${event.author ? ` (author ${event.author})` : ''}`, + ) }, }), ), @@ -168,6 +173,15 @@ export function runWorkflowCharacterization( return (await listAudit()).filter((a) => a.docId === docId) } + /** The audit row of seedLive's direct commit (#1). */ + const seedAudit = () => + expect.objectContaining({ + type: 'create', + actor: 'human', + action: 'edit', + decision: 'approved', + }) + async function publicTitle(): Promise { const found = await readDocumentBySlug('post', 'p1', { publishedOnly: true, @@ -262,7 +276,7 @@ export function runWorkflowCharacterization( expect(fresh.type).toBe('create') }) - it('coalesces: a second stage reuses the pending id, bumps version, keeps the first before/baseRevision, takes the latest after/actor; review.submitted fires once [known bug, fixed in phase 4 (#10)]', async () => { + it('coalesces: a second stage reuses the pending id, bumps version, keeps the first before/baseRevision and instruction, takes the latest after/actor; review.submitted fires once', async () => { setup() await seedLive() const first = await stageWrite({ @@ -287,9 +301,9 @@ export function runWorkflowCharacterization( expect(second.baseRevision).toBe(1) expect(second.after.title).toBe('Two') expect(second.actor).toBe('agent-b') - // known bug, fixed in phase 4 (#10: coalesce keeps instruction) — a - // coalesced stage without an instruction drops the earlier one. - expect(second.instruction).toBeUndefined() + // fixed in phase 4a (#10: coalesce keeps instruction) — a coalesced + // stage without an instruction keeps the earlier one. + expect(second.instruction).toBe('first') const all = await listPending() expect(all).toHaveLength(1) expect(all[0]).toMatchObject({ id: first.id, version: 2 }) @@ -363,7 +377,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 [known bug, fixed in phase 4 (#1, #2, #9)]', async () => { + 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 () => { setup() await seedLive() const pending = await stageWrite({ @@ -395,8 +409,8 @@ export function runWorkflowCharacterization( actor: 'agent', summary: 'Retitle', }) - // known bug, fixed in phase 4 (#1: direct commit audit) — the - // seedLive commit wrote no audit row, so only the decision is here. + // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is + // audited too. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: pending.id, @@ -404,20 +418,24 @@ export function runWorkflowCharacterization( docId: 'p1', type: 'update', actor: 'agent (approved by reviewer)', + action: 'approve', decision: 'approved', }), + seedAudit(), ]) - // known bug, fixed in phase 4 (#9: approver as event actor) — the - // document.* events carry the proposer; review.approved the - // combined audit actor. + // fixed in phase 4a (#9: approver as event actor) — events carry the + // approver; the proposer is recorded as the author. expect(await drainDurable()).toEqual([ - 'document.updated by agent', - 'review.approved by agent (approved by reviewer)', + '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 agent', 'publish by agent']) + expect(takeBus()).toEqual([ + 'change by reviewer', + 'publish by reviewer', + ]) }) it('approve create of a published proposal: document.created + document.published; default summary names the proposer', async () => { @@ -511,7 +529,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, bus delete [known bug, fixed in phase 4 (#1, #9)]', async () => { + it('approve delete: soft delete (revision +1, deletedAt), audit approved type delete, document.deleted + review.approved by the approver, bus delete', async () => { setup() await seedLive() const pending = await stageWrite({ @@ -528,8 +546,8 @@ export function runWorkflowCharacterization( expect( await readDocument('post', 'p1', { includeDeleted: true }), ).toMatchObject({ _revision: 2, deletedAt: expect.any(String) }) - // known bug, fixed in phase 4 (#1: direct commit audit) — the - // seedLive commit wrote no audit row, so only the decision is here. + // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is + // audited too. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: pending.id, @@ -537,19 +555,20 @@ export function runWorkflowCharacterization( decision: 'approved', actor: 'agent (approved by reviewer)', }), + seedAudit(), ]) - // known bug, fixed in phase 4 (#9: approver as event actor) — the - // document.* event carries the proposer, not the approver. + // fixed in phase 4a (#9: approver as event actor) — the events + // carry the approver. expect(await drainDurable()).toEqual([ - 'document.deleted by agent', - 'review.approved by agent (approved by reviewer)', + 'document.deleted by reviewer (author agent)', + 'review.approved by reviewer (author agent)', ]) - expect(takeBus()).toEqual(['delete by agent']) + expect(takeBus()).toEqual(['delete by reviewer']) }) }) describe('reject', () => { - it('reject: pending row deleted, live untouched, no revision, audit rejected, review.rejected; nothing on the bus [known bug, fixed in phase 4 (#1)]', async () => { + it('reject: pending row deleted, live untouched, no revision, audit rejected, review.rejected; nothing on the bus', async () => { setup() await seedLive() const pending = await stageWrite({ @@ -568,15 +587,17 @@ export function runWorkflowCharacterization( _revision: 1, }) expect(await listRevisions('post', 'p1')).toHaveLength(1) - // known bug, fixed in phase 4 (#1: direct commit audit) — the - // seedLive commit wrote no audit row, so only the decision is here. + // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is + // audited too. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: pending.id, type: 'update', + action: 'reject', decision: 'rejected', actor: 'agent (rejected by reviewer)', }), + seedAudit(), ]) expect(await drainDurable()).toEqual([ 'review.rejected by agent (rejected by reviewer)', @@ -589,7 +610,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 [known bug, fixed in phase 4 (#1)]', async () => { + it('saveDraft of a live doc: pending source draft, live unchanged, no review.submitted, no audit for the draft', async () => { setup() await seedLive() const draft = await saveDraft( @@ -605,14 +626,14 @@ export function runWorkflowCharacterization( baseRevision: 1, }) expect(await publicTitle()).toBe('Hello') - // known bug, fixed in phase 4 (#1: direct commit audit) — empty - // only because the seedLive commit wrote no audit row. - expect(await auditFor('p1')).toEqual([]) + // 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()]) expect(await drainDurable()).toEqual([]) expect(takeBus()).toEqual([]) }) - it('commitDocument publishes a draft: folds it in (pending deleted), revision +1, no audit row [known bug, fixed in phase 4 (#1, #2)]', async () => { + it('commitDocument publishes a draft: folds it in (pending deleted), revision +1, audit approved [known bug, fixed in phase 4 (#2)]', async () => { setup() await seedLive() await saveDraft('post', 'p1', { @@ -628,16 +649,24 @@ export function runWorkflowCharacterization( expect(committed._revision).toBe(2) expect(await listPending()).toEqual([]) expect(await publicTitle()).toBe('Draft edit') - // known bug, fixed in phase 4 (#1: direct commit audit) — direct - // commits (human publish) write a revision but no audit row. - expect(await auditFor('p1')).toEqual([]) + // fixed in phase 4a (#1: direct commit audit) — direct commits are + // audited. + expect(await auditFor('p1')).toEqual([ + expect.objectContaining({ + type: 'update', + actor: 'human', + action: 'edit', + decision: 'approved', + }), + 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']) }) - it('discardDraft: deletes the draft through reject — audit rejected and review.rejected, though it never entered review [known bug, fixed in phase 4 (#1, #3)]', async () => { + it('discardDraft: deletes the draft — audit discarded, no review.rejected', async () => { setup() await seedLive() const draft = await saveDraft('post', 'p1', { @@ -653,20 +682,20 @@ export function runWorkflowCharacterization( title: 'Hello', _revision: 1, }) - // known bug, fixed in phase 4 (#3: discard is not reject) — the - // discard is logged and emitted as a rejection. - // known bug, fixed in phase 4 (#1: direct commit audit) — the - // seedLive commit wrote no audit row, so only the discard is here. + // fixed in phase 4a (#3: discard is not reject) — the discard is + // logged as a discard and emits nothing. + // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is + // audited too. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ id: draft.id, - decision: 'rejected', - actor: 'human (rejected by editor)', + action: 'discard', + decision: 'discarded', + actor: 'human (discarded by editor)', }), + seedAudit(), ]) - expect(await drainDurable()).toEqual([ - 'review.rejected by human (rejected by editor)', - ]) + expect(await drainDurable()).toEqual([]) expect(await discardDraft('post', 'p1')).toBe(false) }) @@ -851,7 +880,7 @@ export function runWorkflowCharacterization( expect(await listRevisions('post', 'p1')).toHaveLength(1) }) - it('deleteDocument (direct): soft delete, revision +1, audit approved type delete under the human actor [known bug, fixed in phase 4 (#1)]', async () => { + it('deleteDocument (direct): soft delete, revision +1, audit approved type delete under the human actor', async () => { setup() await seedLive() await deleteDocument('post', 'p1') @@ -860,14 +889,15 @@ export function runWorkflowCharacterization( revision: 2, summary: 'Deleted document', }) - // known bug, fixed in phase 4 (#1: direct commit audit) — the - // seedLive commit wrote no audit row, so only the delete is here. + // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is + // audited too. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ type: 'delete', decision: 'approved', actor: 'human', }), + seedAudit(), ]) expect(await drainDurable()).toEqual(['document.deleted by human']) expect(takeBus()).toEqual(['delete by human']) @@ -875,7 +905,7 @@ export function runWorkflowCharacterization( }) describe('scheduling (actor scheduler)', () => { - it('scheduleDocument (future) commits publishAt with published false; the sweep publishes as scheduler with a revision, an audit row and events [known bug, fixed in phase 4 (#1)]', async () => { + it('scheduleDocument (future) commits publishAt with published false; the sweep publishes as scheduler with a revision, an audit row and events', async () => { setup() await commitDocument('post', 'p1', { title: 'Soon', slug: 'p1' }) await drainDurable() @@ -906,14 +936,26 @@ export function runWorkflowCharacterization( actor: 'scheduler', summary: `Auto-published on schedule (${LATER})`, }) - // known bug, fixed in phase 4 (#1: direct commit audit) — the create - // and scheduleDocument commits wrote no audit rows, so only the - // scheduler's is here. + // fixed in phase 4a (#1: direct commit audit) — the create and + // scheduleDocument commits are audited too. expect(await auditFor('p1')).toEqual([ expect.objectContaining({ type: 'update', decision: 'approved', actor: 'scheduler', + action: 'publish', + }), + expect.objectContaining({ + type: 'update', + decision: 'approved', + actor: 'human', + action: 'edit', + }), + expect.objectContaining({ + type: 'create', + decision: 'approved', + actor: 'human', + action: 'edit', }), ]) expect(await drainDurable()).toEqual([ @@ -994,7 +1036,7 @@ export function runWorkflowCharacterization( }) describe('review.autoApprove', () => { - it('autoApprove true: the stage commits immediately as auto-approve; review.approved without review.submitted [known bug, fixed in phase 4 (#9)]', async () => { + it('autoApprove true: the stage commits immediately as auto-approve; review.approved without review.submitted; events name auto-approve', async () => { setup({ review: { autoApprove: true } }) const result = await stageWrite({ collection: 'post', @@ -1013,12 +1055,12 @@ export function runWorkflowCharacterization( actor: 'agent (approved by auto-approve)', }), ]) - // known bug, fixed in phase 4 (#9: approver as event actor) — the - // document.* events carry the proposer, not auto-approve. + // fixed in phase 4a (#9: approver as event actor) — the events carry + // auto-approve, with the proposer as the author. expect(await drainDurable()).toEqual([ - 'document.created by agent', - 'document.published by agent', - 'review.approved by agent (approved by auto-approve)', + 'document.created by auto-approve (author agent)', + 'document.published by auto-approve (author agent)', + 'review.approved by auto-approve (author agent)', ]) }) @@ -1097,7 +1139,7 @@ export function runWorkflowCharacterization( ], }) - it('default: bypasses governance — writes live as-is with an Imported revision; no pending, no audit, no outbox or bus events [known bug, fixed in phase 4 (#8)]', async () => { + it('default: bypasses review — writes live as-is with an Imported revision; no pending; audited as import; import.* events, no document.* or bus events', async () => { setup() const result = await importContent(exportOf('Imported')) expect(result).toMatchObject({ created: 1, updated: 0 }) @@ -1110,11 +1152,20 @@ export function runWorkflowCharacterization( summary: 'Imported', }), ]) - // known bug, fixed in phase 4 (#8: import events) — no audit row, - // and the catalog declares import.document/import.completed but - // nothing emits them. - expect(await auditFor('p1')).toEqual([]) - expect(await drainDurable()).toEqual([]) + // fixed in phase 4a (#8: import events) — the import is audited and + // emits import.document per document and import.completed. + expect(await auditFor('p1')).toEqual([ + expect.objectContaining({ + type: 'create', + actor: 'import', + action: 'import', + decision: 'approved', + }), + ]) + expect(await drainDurable()).toEqual([ + 'import.completed by import', + 'import.document by import', + ]) expect(takeBus()).toEqual([]) }) diff --git a/packages/core/tests/document-state-strategy.acceptance.test.ts b/packages/core/tests/document-state-strategy.acceptance.test.ts index 1d60ec5d..f949376e 100644 --- a/packages/core/tests/document-state-strategy.acceptance.test.ts +++ b/packages/core/tests/document-state-strategy.acceptance.test.ts @@ -3,10 +3,11 @@ * editorial approval in parallel on one change set (cms-refactor-plan.md, * item 7, "The parallel-approval acceptance test", steps 1–11). * - * Skipped until phase 4c. Phase 4 implements `createAcceptanceHarness` - * against the real engine, promotes the draft types from `./draft` into - * `src`, and removes the `.skip`. If a step can't pass without reaching into - * core internals, the interface is wrong, not the spec. + * Skipped until phase 4c. Phase 4a promoted the draft types into `src` + * (`./draft/document-state-strategy` re-exports them); 4b and 4c add what + * `./draft/acceptance-harness` lists, implement `createAcceptanceHarness` + * against the real engine, and remove the `.skip`. If a step can't pass + * without reaching into core internals, the interface is wrong, not the spec. * * The decided model this encodes: * - Core owns live (`published`, schedule, revisions). The strategy owns the @@ -144,7 +145,7 @@ describe.skip.each(['libsql', 'postgres'] as const)( // A verb the strategy didn't offer is refused, and nothing changes. expect(await act(author, 'approve:legal')).toMatchObject({ ok: false }) - expect((await cms.changeSet(p1))?.workflow.state.value).toEqual( + expect((await cms.changeSet(p1))?.workflow?.state.value).toEqual( bothPending, ) }) @@ -320,7 +321,7 @@ describe.skip.each(['libsql', 'postgres'] as const)( await cms.runScheduler('2026-11-30T09:00:00.000Z') expect(await liveTitle()).toBe('Hello') - expect((await cms.changeSet(p1))?.workflow.state.value).toBe('scheduled') + expect((await cms.changeSet(p1))?.workflow?.state.value).toBe('scheduled') await cms.runScheduler(PUBLISH_AT) expect(await liveTitle()).toBe('Hello, world') @@ -367,7 +368,7 @@ describe.skip.each(['libsql', 'postgres'] as const)( }) await edit('Hello, world') await act(lawyer, 'reject:legal') - expect((await cms.changeSet(p1))?.workflow.state.value).toBe( + expect((await cms.changeSet(p1))?.workflow?.state.value).toBe( 'changesRequested', ) }) diff --git a/packages/core/tests/document-state-strategy.sketch.test.ts b/packages/core/tests/document-state-strategy.sketch.test.ts index 6d9bbb42..13f048da 100644 --- a/packages/core/tests/document-state-strategy.sketch.test.ts +++ b/packages/core/tests/document-state-strategy.sketch.test.ts @@ -1,7 +1,7 @@ /** * Runs the `legal-review@1` XState sketch on its own, with no core: proves the - * strategy half of the acceptance spec is expressible through the draft - * interface today. Core carrying state between calls is simulated by passing + * strategy half of the acceptance spec is expressible through the strategy + * interface (`src/document-state.ts`). Core carrying state between calls is simulated by passing * the returned state back in. */ import { createActor } from 'xstate' @@ -46,6 +46,9 @@ function view(state?: LegalReviewState): DocView { changeSet: state ? { id: 'chg_9', + version: 1, + type: 'update', + source: 'review', actor: 'user:ada', after: { title: 'Hello, world' }, baseRevision: 3, diff --git a/packages/core/tests/document-state.test.ts b/packages/core/tests/document-state.test.ts new file mode 100644 index 00000000..c58b5085 --- /dev/null +++ b/packages/core/tests/document-state.test.ts @@ -0,0 +1,509 @@ +/** + * The document state strategy executor: core's rules on every decision, the + * built-in `review` and `direct` strategies, and per-collection overrides. + */ +import { afterEach, describe, expect, it } from 'vitest' +import { + actorOf, + commit, + defineCms, + defineDocumentStateStrategy, + defineEventHandler, + directStrategy, + emit, + normalizeSession, + publish, + reviewStrategy, + stage, + strategyKey, +} from '../src/index' +import { createSqliteStorage } from '../src/storage' +import { + actOnDocument, + availableDocumentActions, + closeStore, + commitDocument, + documentStateLabel, + documentStateStrategy, + getStorage, + importContent, + listAudit, + listPending, + listRevisions, + readDocument, + runEventDispatch, + saveDraft, + stageWrite, + submitWrite, +} from '../src/server' +import { + accessContext, + agentContext, + publicContext, + systemContext, +} from '../src/server/access-context' +import type { + AnyDocumentStateStrategy, + CmsConfig, + DocumentStateStrategy, + Effect, +} from '../src/index' + +const post: CmsConfig['collections'][number] = { + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'published', label: 'Published', type: 'boolean' }, + ], +} + +const outbox: Array<{ type: string; actor: string; payload: unknown }> = [] + +async function setup( + options: { + documentState?: AnyDocumentStateStrategy + postState?: AnyDocumentStateStrategy + extra?: Partial + } = {}, +) { + outbox.length = 0 + defineCms({ + collections: [ + { + ...post, + ...(options.postState ? { documentState: options.postState } : {}), + }, + { ...post, name: 'note', label: 'Notes' }, + ], + blockTypes: [], + storage: createSqliteStorage({ path: ':memory:' }), + events: { dispatch: 'manual' }, + eventHandlers: [ + 'custom.flagged', + 'review.submitted', + 'review.approved', + 'document.published', + ].map((on) => + defineEventHandler({ + id: `test-${on}`, + on, + run: ({ event }) => { + outbox.push({ + type: event.type, + actor: event.actor, + payload: event.payload, + }) + }, + }), + ), + ...(options.documentState ? { documentState: options.documentState } : {}), + ...options.extra, + }) + await getStorage() +} + +async function drain() { + await runEventDispatch({ now: '2999-01-01T00:00:00.000Z' }) + return outbox.splice(0) +} + +/** A strategy whose every decision is `effects`. */ +function fixed( + effects: ReadonlyArray, + extra: Partial = {}, +): DocumentStateStrategy { + return defineDocumentStateStrategy({ + id: 'fixed', + version: 1, + decide: () => ({ effects }), + availableActions: () => [], + label: () => 'Fixed', + ...extra, + }) +} + +const editor = normalizeSession({ + isAuthenticated: true, + isAdmin: false, + role: 'editor', + user: { id: 'eve' }, +}) + +afterEach(closeStore) + +describe('resolving the strategy', () => { + it('defaults to review, configured from review.autoApprove', async () => { + await setup() + expect(strategyKey(documentStateStrategy('post'))).toBe('review@1') + expect(documentStateStrategy('post').grants).toBeUndefined() + await closeStore() + await setup({ extra: { review: { autoApprove: true } } }) + expect(documentStateStrategy('post').grants).toEqual({ + publish: ['agent'], + }) + }) + + it('takes the app strategy, and a collection overrides it', async () => { + const app = directStrategy() + const custom = fixed([commit()]) + await setup({ documentState: app, postState: custom }) + expect(documentStateStrategy('post')).toBe(custom) + expect(documentStateStrategy('note')).toBe(app) + }) +}) + +describe('direct strategy', () => { + it('commits an agent write at once, audited as submit', async () => { + await setup({ postState: directStrategy() }) + const result = await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Now' }, + actor: 'agent', + }) + expect(result.after).toMatchObject({ title: 'Now', _revision: 1 }) + expect(await listPending()).toEqual([]) + expect(await readDocument('post', 'p1')).toMatchObject({ title: 'Now' }) + expect((await listAudit())[0]).toMatchObject({ + docId: 'p1', + actor: 'agent', + action: 'submit', + decision: 'approved', + }) + expect(await drain()).toEqual([]) + }) + + it('still keeps drafts of published documents private', async () => { + await setup({ postState: directStrategy() }) + await commitDocument('post', 'p1', { title: 'Live', published: true }) + await saveDraft('post', 'p1', { title: 'Draft', published: true }) + expect((await readDocument('post', 'p1'))?.title).toBe('Live') + expect(await listPending()).toEqual([ + expect.objectContaining({ source: 'draft' }), + ]) + }) + + it('submitWrite reports the commit', async () => { + await setup({ postState: directStrategy() }) + const outcome = await submitWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Now' }, + actor: 'agent', + }) + expect(outcome.pending).toBeNull() + expect(outcome.committed).toMatchObject({ title: 'Now' }) + expect(outcome.strategy).toBe('direct@1') + }) +}) + +describe('review strategy', () => { + it('stages an agent write and emits review.submitted with the change set', async () => { + await setup() + const pending = await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Proposal' }, + actor: 'agent', + instruction: 'Draft it', + }) + expect(await readDocument('post', 'p1')).toBeNull() + expect(await drain()).toEqual([ + { + type: 'review.submitted', + actor: 'agent', + payload: { + pendingId: pending.id, + type: 'create', + source: 'agent', + instruction: 'Draft it', + }, + }, + ]) + }) + + it('offers actions from the session permissions and labels the state', async () => { + await setup() + await commitDocument('post', 'p1', { title: 'Live', published: true }) + const ctx = accessContext({ session: editor, mode: 'edit' }) + expect( + (await availableDocumentActions(ctx, 'post', 'p1')).map((a) => a.type), + ).toEqual(['edit', 'draft']) + expect(await documentStateLabel('post', 'p1')).toBe('Published') + await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'update', + doc: { title: 'Proposal', published: true }, + actor: 'agent', + }) + expect( + (await availableDocumentActions(ctx, 'post', 'p1')).map((a) => a.type), + ).toEqual(['approve', 'reject', 'edit', 'draft']) + expect(await documentStateLabel('post', 'p1')).toBe('Pending review') + expect( + await availableDocumentActions(publicContext(), 'post', 'p1'), + ).toEqual([]) + }) + + it('approves through the generic door as the approving context', async () => { + await setup() + await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Proposal', published: true }, + actor: 'agent', + }) + await drain() + const outcome = await actOnDocument( + accessContext({ session: editor, mode: 'edit' }), + { collection: 'post', id: 'p1', action: { type: 'approve' } }, + ) + expect(outcome.committed).toMatchObject({ title: 'Proposal' }) + expect((await listAudit())[0]).toMatchObject({ + action: 'approve', + decision: 'approved', + actor: 'eve', + }) + expect((await drain()).map((e) => `${e.type} by ${e.actor}`)).toEqual([ + 'document.published by eve', + 'review.approved by eve', + ]) + }) +}) + +describe('core rules', () => { + it('refuses a strategy rejection, audits it with the action, and writes nothing', async () => { + await setup({ + postState: fixed([], { decide: () => ({ reject: 'Not today.' }) }), + }) + await expect( + commitDocument('post', 'p1', { title: 'Nope' }), + ).rejects.toMatchObject({ + code: 'FORBIDDEN', + message: 'Not today.', + details: { action: 'edit', rule: 'strategy' }, + }) + expect(await readDocument('post', 'p1')).toBeNull() + expect(await listAudit()).toEqual([ + expect.objectContaining({ + docId: 'p1', + type: 'create', + action: 'edit', + actor: 'human', + decision: 'refused', + }), + ]) + }) + + it('rule 6: refuses a decision that drops the incoming change', async () => { + await setup({ postState: fixed([]) }) + await expect( + commitDocument('post', 'p1', { title: 'Lost' }), + ).rejects.toMatchObject({ details: { rule: 'drops-change' } }) + await expect( + stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Lost' }, + actor: 'agent', + }), + ).rejects.toMatchObject({ details: { rule: 'drops-change' } }) + expect(await listPending()).toEqual([]) + }) + + it('rule 7: refuses emitting a document.* event', async () => { + await setup({ postState: fixed([commit(), emit('document.published')]) }) + await expect( + commitDocument('post', 'p1', { title: 'Forged' }), + ).rejects.toMatchObject({ details: { rule: 'core-event' } }) + expect(await readDocument('post', 'p1')).toBeNull() + expect(await drain()).toEqual([]) + }) + + it('rule 2: a published document changes only through publish', async () => { + let effects: ReadonlyArray = [commit(), publish()] + await setup({ postState: fixed([], { decide: () => ({ effects }) }) }) + await commitDocument('post', 'p1', { title: 'Live', published: true }) + effects = [commit()] + await expect( + commitDocument('post', 'p1', { title: 'Sneaky', published: true }), + ).rejects.toMatchObject({ details: { rule: 'live-content' } }) + expect((await readDocument('post', 'p1'))?.title).toBe('Live') + }) + + it('the agent floor: an agent causes publish only when the strategy grants it', async () => { + const effects = [commit(), publish()] + await setup({ postState: fixed(effects) }) + const write = () => + stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Agent' }, + actor: 'agent', + }) + await expect(write()).rejects.toMatchObject({ + details: { rule: 'agent-floor' }, + }) + expect((await listAudit())[0]).toMatchObject({ decision: 'refused' }) + await closeStore() + await setup({ + postState: fixed(effects, { grants: { publish: ['agent'] } }), + }) + await write() + expect(await readDocument('post', 'p1')).toMatchObject({ + title: 'Agent', + published: true, + }) + }) + + it('stamps emitted events with the change set', async () => { + await setup({ + postState: fixed([stage(), emit('custom.flagged', { reason: 'x' })]), + }) + const pending = await stageWrite({ + collection: 'post', + docId: 'p1', + type: 'create', + doc: { title: 'Flag' }, + actor: 'agent', + }) + expect(await drain()).toEqual([ + { + type: 'custom.flagged', + actor: 'agent', + payload: { reason: 'x', pendingId: pending.id, type: 'create' }, + }, + ]) + }) + + it('publish(revision) restores an older revision as a new live revision', async () => { + await setup({ + postState: defineDocumentStateStrategy({ + id: 'restorer', + version: 1, + decide: (_ctx, _doc, action) => + action.type === 'restore' + ? { effects: [publish(Number(action.input?.revision))] } + : { effects: [commit(), publish()] }, + availableActions: () => [], + label: () => '', + }), + }) + await commitDocument('post', 'p1', { title: 'One', published: true }) + await commitDocument('post', 'p1', { title: 'Two', published: true }) + const outcome = await actOnDocument(systemContext('test'), { + collection: 'post', + id: 'p1', + action: { type: 'restore', input: { revision: 1 } }, + }) + expect(outcome.committed).toMatchObject({ title: 'One', _revision: 3 }) + expect(await readDocument('post', 'p1')).toMatchObject({ + title: 'One', + published: true, + _revision: 3, + }) + expect((await listRevisions('post', 'p1')).map((r) => r.revision)).toEqual([ + 3, 2, 1, + ]) + }) + + it('a refusal in the middle of an import writes none of it', async () => { + await setup({ + postState: fixed([], { + decide: (_ctx, doc) => + doc.id === 'bad' + ? { reject: 'Not this one.' } + : { effects: [commit()] }, + }), + }) + await expect( + importContent({ + format: 'tanstack-cms-export', + version: 1, + exportedAt: '', + documents: [ + { collection: 'post', id: 'good', doc: { title: 'Good' } }, + { collection: 'post', id: 'bad', doc: { title: 'Bad' } }, + ], + }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }) + expect(await readDocument('post', 'good')).toBeNull() + expect(await listAudit()).toEqual([ + expect.objectContaining({ + docId: 'bad', + action: 'import', + decision: 'refused', + }), + ]) + }) +}) + +describe('actorOf', () => { + it('maps each access context to an actor type', () => { + expect(actorOf(publicContext())).toEqual({ + type: 'public', + id: 'public', + roles: [], + }) + expect(actorOf(accessContext({ session: editor }))).toEqual({ + type: 'user', + id: 'eve', + roles: ['editor'], + }) + expect(actorOf(agentContext({ agent: 'mcp:enrich' }))).toMatchObject({ + type: 'agent', + id: 'mcp:enrich', + }) + expect( + actorOf(agentContext({ agent: 'mcp:enrich', session: editor })), + ).toEqual({ type: 'agent', id: 'mcp:enrich', roles: ['editor'] }) + expect(actorOf(systemContext('seed')).type).toBe('system') + expect( + actorOf(systemContext('scheduled publishing', { actor: 'scheduler' })), + ).toMatchObject({ type: 'scheduler' }) + expect(actorOf(systemContext('seed', { actor: 'import' }))).toMatchObject({ + type: 'import', + id: 'seed', + }) + }) +}) + +describe('built-in strategies, without core', () => { + it('review routes a submit through the queue unless auto-approved', async () => { + const view = { + collection: 'post', + id: 'p1', + live: null, + changeSet: null, + } + const ctx = agentContext({ agent: 'agent' }) + const submit = { + type: 'submit', + patch: { title: 'x' }, + input: { change: 'create', source: 'agent' }, + } + expect(await reviewStrategy().decide(ctx, view, submit)).toEqual({ + state: 'pending_review', + effects: [stage(), emit('review.submitted', { source: 'agent' })], + }) + const auto = await reviewStrategy({ autoApprove: true }).decide( + ctx, + view, + submit, + ) + expect('effects' in auto && auto.effects?.map((e) => e.type)).toEqual([ + 'stage', + 'commit', + 'emit', + ]) + }) +}) diff --git a/packages/core/tests/draft/acceptance-harness.ts b/packages/core/tests/draft/acceptance-harness.ts index 710e6b83..a0e59056 100644 --- a/packages/core/tests/draft/acceptance-harness.ts +++ b/packages/core/tests/draft/acceptance-harness.ts @@ -1,11 +1,24 @@ /** * DRAFT core-side surface the document state strategy acceptance spec drives. * - * Nothing here exists yet. Phase 4 implements `createAcceptanceHarness` on - * top of the real engine (effect executor, `cms.as(ctx)` handle, scheduler, - * storage conformance harness) and un-skips the spec. Keep this file thin: - * it should map one-to-one onto public engine calls, so the spec never - * reaches into core internals. + * The strategy types are real since phase 4a (re-exported through + * `./document-state-strategy`), and so are the effect executor and the + * scheduler firing `publish` as the `scheduler` actor. `createAcceptanceHarness` + * still rejects, because the spec needs what lands later: + * + * - 4b: strategy state persisted with the change set (`workflow_strategy` / + * `workflow_state` on `pending`, so `ChangeSetView.workflow` is not + * `null`); transition fields on `audit` (`from`, `to`, `effects`, a + * refusal's `reason`) behind `AuditRow`; change-set scheduling (a + * `schedule` effect on a live doc's change set, and the sweep that fires + * `publish` for it); stranded change-set detection for `stranded()`. + * - 4c: the spec shipped as an exported, runner-injected suite (like + * `runStorageConformance`) so `store-libsql` and `store-postgres` run it, + * this harness implemented on the public engine calls, and the `.skip` + * removed. + * + * Keep this file thin: it should map one-to-one onto public engine calls, so + * the spec never reaches into core internals. */ import type { AccessContext, diff --git a/packages/core/tests/draft/document-state-strategy.ts b/packages/core/tests/draft/document-state-strategy.ts index 3796b27d..1d952e40 100644 --- a/packages/core/tests/draft/document-state-strategy.ts +++ b/packages/core/tests/draft/document-state-strategy.ts @@ -1,51 +1,59 @@ /** - * DRAFT document state strategy API (phase 0 of the core API refactor). + * The document state strategy API the acceptance spec and the XState sketch + * are written against. * - * Test-local on purpose: nothing here is exported from `src`. Phase 4a - * promotes these types (and the effect constructors) into - * `@tanstack/cms-core` once core has an effect executor. Until then they are - * the contract the parallel-approval acceptance spec is written against. - * - * The decided model: core owns the live record (`documents.published`, the - * schedule columns, revisions). A strategy owns only the workflow of the one - * coalesced pending change set per document, and asks core to act through - * effects. + * Phase 0 drafted it here; phase 4a promoted the types and effect constructors + * into `@tanstack/cms-core` (`src/document-state.ts`), and `ctx` is the phase + * 2a `AccessContext`. This module now re-exports the real API and keeps the + * draft's context helpers, built from real contexts. It stays test-local + * because the context builders are internal until phase 2b. */ - -// --------------------------------------------------------------------------- -// Access context (phase 2). The actor shape waits for the task 8 review. -// --------------------------------------------------------------------------- - -export type ActorType = - | 'anonymous' - | 'user' - | 'agent' - | 'system' - | 'scheduler' - | 'import' - -export interface Actor { - type: ActorType - /** Attribution id written to audit rows, e.g. `user:lee`, `agent:enrich`. */ - id: string - roles: ReadonlyArray -} +import { agentContext as engineAgentContext } from '../../src/server/access-context' +import { accessContext, systemContext } from '../../src/server/access-context' +import type { AccessContext, ReadMode } from '../../src/server/access-context' +import type { CmsSession } from '../../src/lib/auth' + +export { + actorOf, + commit, + discard, + emit, + publish, + schedule, + stage, + strategyKey, + unpublish, +} from '../../src/document-state' +export type { + Action, + ActionDescriptor, + ChangeSetView, + DocView, + DocumentStateStrategy, + Effect, + StateGraph, + StrategyActor as Actor, +} from '../../src/document-state' +export type { AccessContext, ReadMode } +export { publicContext } from '../../src/server/access-context' +export { systemContext } + +/** The scheduler, as core builds it for scheduled publishes. */ +export const schedulerContext = (): AccessContext => + systemContext('scheduled publishing', { actor: 'scheduler' }) /** - * `live` reads what readers see (`published` is true). `preview` and `edit` - * read the change set overlay. + * A signed-in user. A session holds one role today, so only `roles[0]` is + * used; the role is taken as declared (no `defineCms` role registry check), + * so strategy-defined roles such as `legal` work. */ -export type ReadMode = 'live' | 'preview' | 'edit' - -export interface AccessContext { - actor: Actor - mode: ReadMode -} - -export function publicContext(): AccessContext { +function session(id: string, roles: ReadonlyArray): CmsSession { return { - actor: { type: 'anonymous', id: 'anonymous', roles: [] }, - mode: 'live', + isAuthenticated: true, + isAdmin: false, + role: roles[0] ?? null, + permissions: [], + user: { id }, } } @@ -54,163 +62,13 @@ export function userContext( roles: ReadonlyArray, mode: ReadMode = 'edit', ): AccessContext { - return { actor: { type: 'user', id, roles }, mode } + return accessContext({ session: session(id, roles), mode }) } export function agentContext( name: string, roles: ReadonlyArray = ['author'], ): AccessContext { - return { actor: { type: 'agent', id: `agent:${name}`, roles }, mode: 'edit' } -} - -/** `reason` is required so privileged contexts stay greppable in review. */ -export function systemContext(reason: string): AccessContext { - return { - actor: { type: 'system', id: `system:${reason}`, roles: [] }, - mode: 'edit', - } -} - -/** The context core's scheduler acts under when a scheduled time comes due. */ -export function schedulerContext(): AccessContext { - return { - actor: { type: 'scheduler', id: 'scheduler', roles: [] }, - mode: 'edit', - } -} - -// --------------------------------------------------------------------------- -// Effects: the only way a strategy changes anything. -// --------------------------------------------------------------------------- - -export type Effect = - /** Keep the incoming change in the doc's (coalesced) change set. */ - | { type: 'stage' } - /** Apply the change set as a new revision. Consumes the change set. */ - | { type: 'commit' } - /** Make a revision live. Default: the one just committed. */ - | { type: 'publish'; revision?: number } - | { type: 'unpublish' } - | { type: 'schedule'; publishAt?: string; unpublishAt?: string } - /** Drop the change set. */ - | { type: 'discard' } - /** Strategy-named event through the outbox. */ - | { type: 'emit'; event: string; payload?: unknown } - -export const stage = (): Effect => ({ type: 'stage' }) -export const commit = (): Effect => ({ type: 'commit' }) -export const publish = (revision?: number): Effect => - revision === undefined ? { type: 'publish' } : { type: 'publish', revision } -export const unpublish = (): Effect => ({ type: 'unpublish' }) -export const schedule = (at: { - publishAt?: string - unpublishAt?: string -}): Effect => ({ type: 'schedule', ...at }) -export const discard = (): Effect => ({ type: 'discard' }) -export const emit = (event: string, payload?: unknown): Effect => - payload === undefined - ? { type: 'emit', event } - : { type: 'emit', event, payload } - -export type Decision = - | { state?: S; effects?: ReadonlyArray } - | { reject: string } - -// --------------------------------------------------------------------------- -// What the strategy sees and receives. -// --------------------------------------------------------------------------- - -export interface Action { - /** `edit`, or a strategy-defined verb such as `approve:legal`. */ - type: string - /** The incoming field changes, for `edit`. */ - patch?: Record - /** Verb arguments, e.g. a requested `publishAt`. */ - input?: Record -} - -export interface ActionDescriptor { - type: string - label: string - tone?: 'default' | 'primary' | 'danger' -} - -/** Core-owned live record. `null` for a document that was never committed. */ -export interface LiveView { - doc: Record - revision: number - published: boolean - publishAt: string | null - unpublishAt: string | null -} - -export interface ChangeSetView { - id: string - actor: string - after: Record - baseRevision: number | null - workflow: { - /** `id@version` of the strategy that wrote `state`. */ - strategy: string - state: S - } -} - -export interface DocView { - collection: string - id: string - live: LiveView | null - changeSet: ChangeSetView | null -} - -/** A graph for the generated Mermaid chart. */ -export interface StateGraph { - nodes: ReadonlyArray<{ - id: string - label: string - parent?: string - parallel?: boolean - final?: boolean - }> - edges: ReadonlyArray<{ from: string; to: string; action: string }> -} - -export type Migration = { state: S } | { stranded: string } - -/** - * `S` is the strategy's serializable state for one change set. Core stores it - * verbatim next to `strategy@version` and never interprets it. - */ -export interface DocumentStateStrategy { - id: string - version: number - /** - * Actor types allowed to cause `publish`/`unpublish` effects beyond core's - * floor. Core rejects a publish caused by an `agent` actor unless `agent` - * is listed here. - */ - grants?: { publish?: ReadonlyArray } - decide: ( - ctx: AccessContext, - doc: DocView, - action: Action, - ) => Decision | Promise> - availableActions: ( - ctx: AccessContext, - doc: DocView, - ) => ReadonlyArray - label: (state: S | undefined, doc: DocView) => string - describe?: () => StateGraph - /** - * Called by core at boot for change sets written by an older version. - * Without it, every older in-flight change set is reported as stranded. - */ - migrate?: (from: { version: number; state: unknown }) => Migration -} - -export function strategyKey( - strategy: Pick, 'id' | 'version'>, -): string { - return `${strategy.id}@${strategy.version}` + const agent = `agent:${name}` + return engineAgentContext({ agent, session: session(agent, roles) }) } diff --git a/packages/core/tests/draft/legal-review.xstate.ts b/packages/core/tests/draft/legal-review.xstate.ts index e843e376..2009a7d5 100644 --- a/packages/core/tests/draft/legal-review.xstate.ts +++ b/packages/core/tests/draft/legal-review.xstate.ts @@ -1,6 +1,6 @@ /** * XState sketch of `legal-review@1`: legal and editorial approval run in - * parallel on one change set, written against the draft + * parallel on one change set, written against the * `DocumentStateStrategy` interface. XState is the documented power path, * not the engine: core never imports it, it only stores what `decide` * returns. @@ -14,6 +14,7 @@ */ import { assign, initialTransition, setup, transition } from 'xstate' import { + actorOf, commit, discard, emit, @@ -238,7 +239,7 @@ const CANDIDATE_ACTIONS: ReadonlyArray = [ ] function toEvent(ctx: AccessContext, action: Action): LegalReviewEvent | null { - const { actor } = ctx + const actor = actorOf(ctx) switch (action.type) { case 'edit': { const at = action.input?.publishAt @@ -361,18 +362,18 @@ export function defineLegalReview( machine, // No `grants`: agents may edit (and so stage), never publish. decide(ctx, doc, action) { - const snapshot = restore(doc.changeSet?.workflow.state) + const snapshot = restore(doc.changeSet?.workflow?.state) const event = toEvent(ctx, action) if (!event || !snapshot.can(event)) { return { - reject: `${action.type} is not available to ${ctx.actor.id} in ${JSON.stringify(snapshot.value)}`, + reject: `${action.type} is not available to ${actorOf(ctx).id} in ${JSON.stringify(snapshot.value)}`, } } const [next, actions] = transition(machine, snapshot, event) return { state: persist(next), effects: toEffects(actions) } }, availableActions(ctx, doc) { - const snapshot = restore(doc.changeSet?.workflow.state) + const snapshot = restore(doc.changeSet?.workflow?.state) return CANDIDATE_ACTIONS.filter((candidate) => { const event = toEvent(ctx, { type: candidate.type }) return event !== null && snapshot.can(event) diff --git a/packages/core/tests/transfer.test.ts b/packages/core/tests/transfer.test.ts index 37e5cef1..f34aeca1 100644 --- a/packages/core/tests/transfer.test.ts +++ b/packages/core/tests/transfer.test.ts @@ -190,9 +190,18 @@ describe('seed, migrate, backup', () => { expect( (await listPending()).map((pending) => pending.source).sort(), ).toEqual(['agent', 'draft']) - // One review-decision entry (the rejection) plus one admin-action entry - // (the API-key creation) — both survive a backup/restore round-trip. - expect(await listAudit()).toHaveLength(2) + // The direct commit, 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 -', + 'edit approved', + 'import approved', + 'reject rejected', + ]) expect(await listApiKeys()).toHaveLength(1) expect( ( diff --git a/packages/store-postgres/tests/invariants.test.ts b/packages/store-postgres/tests/invariants.test.ts index e7d92700..d0d99fb0 100644 --- a/packages/store-postgres/tests/invariants.test.ts +++ b/packages/store-postgres/tests/invariants.test.ts @@ -369,7 +369,18 @@ describe.skipIf(!url)( expect((await readDocument('post', 'fr'))?.translationOf).toBe('en') expect(await listRevisions('post', 'en')).toHaveLength(1) expect(await second.listPending()).toHaveLength(1) - expect(await second.listAudit()).toHaveLength(1) + // The restored decisions, plus the restore's own import audit. + expect( + (await second.listAudit()) + .map((entry) => `${entry.action} ${entry.decision}`) + .sort(), + ).toEqual([ + 'edit approved', + 'edit approved', + 'import approved', + 'import approved', + 'reject rejected', + ]) expect(await second.listApiKeys?.()).toHaveLength(1) expect( (await exportContent({ revisions: true, workflow: true })).documents, diff --git a/packages/ui-react/src/lib/i18n.ts b/packages/ui-react/src/lib/i18n.ts index db4f2002..f81d83c4 100644 --- a/packages/ui-react/src/lib/i18n.ts +++ b/packages/ui-react/src/lib/i18n.ts @@ -357,6 +357,8 @@ export const defaultAdminMessages = { 'review.audit': 'Audit trail', 'review.decision.approved': 'approved', 'review.decision.rejected': 'rejected', + 'review.decision.discarded': 'discarded', + 'review.decision.refused': 'refused', '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 eb07fa22..385658e5 100644 --- a/packages/ui-react/src/routes/review.tsx +++ b/packages/ui-react/src/routes/review.tsx @@ -10,7 +10,7 @@ import { AdminShell, CommentsPanel } from '../primitives' import { routeSession, useCan, useCmsAuth } from '../lib/auth' import { adminRich, adminT } from '../lib/i18n' import type { AdminMessageId } from '../lib/i18n' -import type { Pending } from '@tanstack/cms-core/server' +import type { AuditRecord, Pending } from '@tanstack/cms-core/server' import '../app-renderers' export const Route = createFileRoute('/review')({ @@ -38,6 +38,16 @@ const TYPE_LABELS = { delete: 'review.type.delete', } as const satisfies Record +const DECISION_LABELS = { + approved: 'review.decision.approved', + rejected: 'review.decision.rejected', + discarded: 'review.decision.discarded', + refused: 'review.decision.refused', +} as const satisfies Record< + NonNullable, + AdminMessageId +> + function ReviewPage() { const { pending, audit } = Route.useLoaderData() const { ai } = useCmsAuth() @@ -258,11 +268,7 @@ function ReviewPage() { : 'font-medium text-neutral-500' } > - {adminT( - a.decision === 'approved' - ? 'review.decision.approved' - : 'review.decision.rejected', - )} + {adminT(DECISION_LABELS[a.decision ?? 'rejected'])}