Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/default-flow-approved.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-ui-react': minor
---

The default document state strategy is now Draft → Pending Review → Approved → Published. A reviewer who holds `review.decide` but not `content.publish` approves a staged change into the new `approved` state (audited as `transitioned`, emitting `review.approved`) without touching the live document; a publisher's `publish` action then applies it (an approved deletion needs `content.delete`), or the scheduler publishes it at its `publishAt`. A reviewer who can publish still approves and publishes in one decision, so apps whose reviewers can publish behave as before. A new submission sends an approved change back to Pending Review. `approveChange` accepts reviewers without `content.publish` (the strategy decides, and core re-checks access for anything that writes live content), and the review page shows them a single **Approve** button and publishers a **Publish** button on approved changes.

Breaking changes:

- The default strategy's labels are `Pending Review` (was `Pending review`) and the new `Approved`; `ReviewState` gains `'approved'`.
- `approveChange` by a reviewer without `content.publish` used to fail with `FORBIDDEN`; it now moves the change to Approved.
- A scheduled or manual publish of an approved change set no longer emits a second `review.approved` (it was emitted at approval).
- `directStrategy().describe()` charts only its own states (Unpublished, Published, Draft); `reviewStrategy().describe()` adds Approved.
1 change: 1 addition & 0 deletions app/prm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Built for individuals, small teams, and families — ideal for running on a home

- **Self-contained instance data directory (`PRM_DATA_DIR`)** — stores configuration (`prm.json`), secrets (`secrets.env`), SQLite database (`cms.db`), uploaded photos (`uploads/`), and snapshots (`backups/`) in one directory outside the repo.
- **Multi-user DB authentication** — first-run `/setup` creates the `owner` account; invite family or teammates via one-time `/invite/$token` links from `/prm-settings`.
- **Owner direct, agent review** — the PRM's document state strategy, `ownerDirectAgentReview` in `src/document-state.ts`: people who may publish (owners, members) commit their own saves, and agent and import writes go through review.
- **Optional approval workflow (off by default)** — `approvalRequired: false` auto-approves agent and import writes while preserving full revision and audit history; flip it on in `/prm-settings` to stage changes into `/review`.
- **Groups & Events** — organize people into recurring circles (`TanStack`, `Creators`, `Founders`, `Oak St & School Parents`) or time-bounded events (`Timmy's Birthday Party`, `AI Coding Summit 2026`) with start/end times, location, per-event roles/talks, and a talked-with progress bar.
- **Rich person profiles** — multiple names (`aliases` / AKAs), `pronouns`, human-only personal contact fields (`phone`, `email`, `birthday`, `address`), per-field provenance (`personSource`), and deep-snoop enrichment.
Expand Down
9 changes: 6 additions & 3 deletions app/prm/src/cms.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
* - Stores all instance settings (`prm.json`), secrets (`secrets.env`), SQLite
* database (`cms.db`), and uploads (`uploads/`) inside a single data directory
* - DB-backed multi-user auth (`owner`, `member`, `viewer`) via `createDbAuth`
* - Optional review queue (`review.autoApprove` defaults to `!instance.approvalRequired`)
* - Owner direct, agent review (`ownerDirectAgentReview`): people who may publish
* commit their own saves; agent writes stage in the review queue, or are
* auto-approved when `instance.approvalRequired` is off
* - Two named conversational agents alongside `/agent`:
* - `enrich` (`actor: 'enrichment-agent'`, deep-snoop web tools, 30 iterations)
* - `ask` (`actor: 'crm-chat'`, read-only toolset, cited answers)
Expand All @@ -19,6 +21,7 @@ import { enrichAgentConfig, ENRICHMENT_SKILL_PROMPT } from './agents/enrich'
import { askAgentConfig } from './agents/ask'
import { crmEventHandlers } from './events'
import { definition } from './cms.definition'
import { ownerDirectAgentReview } from './document-state'

const resolveServerDataDir = createServerOnlyFn(async () => {
const { resolvePrmDataDir } = await import('./instance.server')
Expand All @@ -41,13 +44,13 @@ export const cms = defineCms(definition, {
ops: [importPeopleOp],
eventHandlers: crmEventHandlers,
seed,
review: {
documentState: ownerDirectAgentReview({
autoApprove: createServerOnlyFn(async () => {
await resolveServerDataDir()
const { getPrmInstanceSettings } = await import('./instance.server')
return !getPrmInstanceSettings().approvalRequired
}),
},
}),
auth: {
defaultRole: 'member',
getUser: createServerOnlyFn(async ({ request }) => {
Expand Down
43 changes: 43 additions & 0 deletions app/prm/src/document-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* The PRM's document state strategy: owner direct, agent review.
*
* The PRM is personal, so a signed-in person who may publish (owner, member,
* editor) commits their own saves at once; nobody approves their own notes.
* Agent writes (the `enrich` agent, MCP keys, `import_people`) go through the
* review flow: they stage in `/review` unless the instance's
* `approvalRequired` setting is off, in which case they are approved at once
* as `auto-approve`. Either way they stay attributed and audited.
*/
import { actorOf, directStrategy, reviewStrategy } from '@tanstack/cms-core'
import type {
AccessContext,
DocumentStateStrategy,
ReviewState,
ReviewStrategyOptions,
} from '@tanstack/cms-core'

const SAVES = new Set(['edit', 'submit', 'import'])

function ownsTheirSaves(ctx: AccessContext): boolean {
return (
actorOf(ctx).type === 'user' &&
ctx.permissions.some((p) => p === 'content.publish')
)
}

export function ownerDirectAgentReview(
options: Pick<ReviewStrategyOptions, 'autoApprove'> = {},
): DocumentStateStrategy<ReviewState> {
const review = reviewStrategy(options)
const direct = directStrategy()
return {
...review,
id: 'prm-owner-direct',
version: 1,
decide(ctx, doc, action) {
return SAVES.has(action.type) && ownsTheirSaves(ctx)
? direct.decide(ctx, doc, action)
: review.decide(ctx, doc, action)
},
}
}
59 changes: 57 additions & 2 deletions app/prm/tests/crm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ import {
normalizeSession,
PERMISSIONS,
} from '@tanstack/cms-core'
import type { Field } from '@tanstack/cms-core'
import type { AnyDocumentStateStrategy, Field } from '@tanstack/cms-core'
import {
accessContext,
actOnDocument,
approve,
closeStore,
cmsTools,
Expand Down Expand Up @@ -63,11 +65,16 @@ import {
import { isHumanCreatedNewPerson } from '../src/events'
import { BAKEOFF_SUBJECTS, runBakeoff } from '../scripts/bakeoff'
import { buildKodyMcpRegistration } from '../kody-package'
import { ownerDirectAgentReview } from '../src/document-state'

afterEach(closeStore)

function setupCrmTest(extra?: { textAdapter?: () => unknown }) {
function setupCrmTest(extra?: {
textAdapter?: () => unknown
documentState?: AnyDocumentStateStrategy
}) {
defineCms({
...(extra?.documentState ? { documentState: extra.documentState } : {}),
storage: createSqliteStorage({ path: ':memory:' }),
collections: crmCollections,
blockTypes: [],
Expand Down Expand Up @@ -108,6 +115,54 @@ function setupCrmTest(extra?: { textAdapter?: () => unknown }) {
}

describe('CRM acceptance criteria (§11)', () => {
it('owner direct, agent review: a person who may publish commits their own saves; agent saves stage unless approval is off', async () => {
for (const approvalRequired of [true, false]) {
setupCrmTest({
documentState: ownerDirectAgentReview({
autoApprove: () => !approvalRequired,
}),
})
const owner = normalizeSession({
isAuthenticated: true,
isAdmin: false,
role: 'editor',
user: { id: 'jack', name: 'Jack' },
})
const save = (id: string, ctx: Parameters<typeof actOnDocument>[0]) =>
actOnDocument(ctx, {
collection: 'person',
id,
action: {
type: 'submit',
patch: { name: id, headline: 'Notes', published: true },
input: { change: 'create', source: 'review' },
},
})

await save('by-owner', accessContext({ session: owner, mode: 'edit' }))
expect(await readDocument('person', 'by-owner')).toMatchObject({
name: 'by-owner',
})

await save(
'by-agent',
accessContext({ session: owner, agent: 'enrich', mode: 'edit' }),
)
if (approvalRequired) {
expect(await readDocument('person', 'by-agent')).toBeNull()
expect(
(await listPending()).map((p) => [p.docId, p.workflow?.state]),
).toEqual([['by-agent', 'pending_review']])
} else {
expect(await readDocument('person', 'by-agent')).toMatchObject({
name: 'by-agent',
})
expect(await listPending()).toEqual([])
}
await closeStore()
}
})

it('§11.8: personal contact fields (email, phone, birthday, address) are writable by humans and blocked for agent sessions', () => {
const contactFields = person.fields.filter((f) =>
['email', 'phone', 'birthday', 'address'].includes(f.name),
Expand Down
2 changes: 1 addition & 1 deletion docs/agents/custom-strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ export function defineLegalReview(
const live = doc.live?.published ? 'Published' : 'Unpublished'
if (!state) return live
const regions = regionLabel(state.value)
if (regions) return `Pending review (${regions})`
if (regions) return `Pending Review (${regions})`
switch (state.value) {
case 'changesRequested':
return 'Changes requested'
Expand Down
30 changes: 24 additions & 6 deletions docs/agents/review-queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a

- **Unpublished documents** are saved directly by anyone who may publish.
- **Published documents** get a **draft**: the live version stays as it is until someone publishes the changes.
- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them.
- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where a reviewer approves or rejects them.

A change moves through the default flow's states: **Draft** (a publisher's private working copy), **Pending Review** (a staged proposal), **Approved** (a reviewer approved it; it waits for a publisher) and **Published**. A reviewer who may also publish approves and publishes in one step, so **Approved** only appears when reviewing and publishing are separate roles.

Every commit records a **revision**, and every decision (a direct save, an approval, a rejection, a discarded draft, a scheduled publish, an import) lands in the **audit trail**.

Expand Down Expand Up @@ -84,7 +86,7 @@ Agents can read their own staged work. `read_document` and `update_document` fal

The `/review` page lists pending changes with a field-level diff, the proposer, and any instruction note the agent attached. Deletions are highlighted in red and list the fields that will be removed.

Anyone with `content.read` can view the queue (limited to collections they may read, with unreadable fields redacted). Deciding requires `review.decide`, plus the right to publish (or, for deletions, delete) in that collection:
Anyone with `content.read` can view the queue (limited to collections they may read, with unreadable fields redacted). Deciding requires `review.decide`. A reviewer who may also publish (or, for deletions, delete) in that collection applies the change as they approve it:

- **Approve & publish** commits the change and publishes it. For a proposal that already sets `published: true`, the document goes live as proposed.
- **Approve as draft** (offered for proposals that don't publish) commits the content with `published: false`.
Expand All @@ -93,7 +95,18 @@ Anyone with `content.read` can view the queue (limited to collections they may r

The audit entry records both parties, for example `mcp (approved by Jane Doe)`. The underlying operations are `approveChange({ id, publish?, force? })` and `rejectChange({ id })`.

Each pending change also shows its strategy's label for the document's state (for example **Pending review**, or a custom strategy's **Changes requested**), and its buttons are the actions the strategy offers you, so a custom strategy's actions (such as **Approve (legal)**) appear next to Approve and Reject. When the strategy offers `schedule`, a **Publish at** field sets or clears the change set's publish time, and a **Publishes …** badge shows it. These buttons call `actOnChange({ id, action, publishAt?, reason?, expectedVersion? })`, which runs the action through the strategy and refuses one it doesn't offer you.
A reviewer without `content.publish` sees **Approve** instead. It moves the change to **Approved** (audited as `transitioned`, with a `review.approved` event) and leaves the live document as it is. A publisher then sees **Publish**, which applies the approved change and publishes it (on a published document they can also schedule it with **Publish at**); a new submission sends it back to **Pending Review**. For example, a `reviewer` role that approves but can't publish:

```ts
defineCms({
roles: {
reviewer: ['content.read', 'review.decide'],
},
// ...
})
```

Each pending change also shows its strategy's label for the document's state (for example **Pending Review** or **Approved**, or a custom strategy's **Changes requested**), and its buttons are the actions the strategy offers you, so a custom strategy's actions (such as **Approve (legal)**) appear next to Approve and Reject. When the strategy offers `schedule`, a **Publish at** field sets or clears the change set's publish time, and a **Publishes …** badge shows it. These buttons call `actOnChange({ id, action, publishAt?, reason?, expectedVersion? })`, which runs the action through the strategy and refuses one it doesn't offer you.

A pending change remembers the revision of the live document it was proposed against. When someone commits a new live revision while it is open:

Expand All @@ -119,21 +132,26 @@ defineCms({
})
```

The built-in strategies' states and actions, generated from `reviewStrategy().describe()` with `stateGraphToMermaid`:
The default strategy's states and actions, generated from `reviewStrategy().describe()` with `stateGraphToMermaid`:

```mermaid
stateDiagram-v2
state "Unpublished" as unpublished
state "Published" as published
state "Draft" as draft
state "Pending review" as pending_review
state "Pending Review" as pending_review
state "Approved" as approved
unpublished --> pending_review: submit
published --> pending_review: submit
published --> draft: draft
draft --> published: edit
draft --> published: discard
pending_review --> published: approve
pending_review --> approved: approve
pending_review --> published: approve (publisher)
pending_review --> unpublished: reject
approved --> published: publish
approved --> pending_review: submit
approved --> unpublished: reject
unpublished --> published: publish
published --> unpublished: unpublish
```
Expand Down
2 changes: 1 addition & 1 deletion docs/api/routes-and-endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/
| `deleteDoc` | POST | `content.delete` | `{ collection, id, force? }` | `{ ok }` |
| `bulkDocuments` | POST | `content.write` | `{ collection, ids (1–100), action: 'publish' \| 'unpublish' \| 'delete' }` | `{ ok, results: [{ id, ok, error?: { code, message } }] }`. `delete` also needs `content.delete`; `publish` and `unpublish` need publish rights. One failed item doesn't stop the rest. |
| `reviewSnapshot` | GET | `content.read` | `{}` | `{ pending, audit }`. Each pending change carries `review: { label, actions, stranded? }` from its strategy, for the caller. Drafts are excluded unless stranded. |
| `approveChange` | POST | `review.decide` | `{ id, publish?, force? }` | The approved pending change. `CONFLICT` when the document changed since the proposal was staged, unless `force` is set. |
| `approveChange` | POST | `review.decide` | `{ id, publish?, force? }` | The approved pending change. A reviewer without `content.publish` moves it to **Approved** for a publisher to publish. `CONFLICT` when the document changed since the proposal was staged, unless `force` is set. |
| `rejectChange` | POST | `review.decide` | `{ id }` | The rejected pending change. |
| `actOnChange` | POST | `content.read` | `{ id, action, publishAt?: string \| null, reason?, expectedVersion? }` | `{ ok, effects, label }`. Runs only an action the change set's strategy offers the caller now (`FORBIDDEN` otherwise); actions that carry a document (`edit`, `submit`, `draft`, `import`) are `BAD_REQUEST`. `CONFLICT` when `expectedVersion` is stale. |
| `proposeEdit` | POST | `agent.use` | `{ collection, id, instruction, current }` | The AI-proposed document (not saved). |
Expand Down
Loading
Loading