Skip to content

Commit df9b7ed

Browse files
cursoragentjherr
andcommitted
feat(core,api,ui-react)!: default flow Draft → Pending Review → Approved → Published; PRM's owner-direct strategy; S3 restated (4d) (#37)
Chain step 14 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 <jherr@pobox.com>
1 parent 18d8f0f commit df9b7ed

20 files changed

Lines changed: 516 additions & 67 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@tanstack/cms-core': minor
3+
'@tanstack/cms-api': minor
4+
'@tanstack/cms-ui-react': minor
5+
---
6+
7+
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.
8+
9+
Breaking changes:
10+
11+
- The default strategy's labels are `Pending Review` (was `Pending review`) and the new `Approved`; `ReviewState` gains `'approved'`.
12+
- `approveChange` by a reviewer without `content.publish` used to fail with `FORBIDDEN`; it now moves the change to Approved.
13+
- A scheduled or manual publish of an approved change set no longer emits a second `review.approved` (it was emitted at approval).
14+
- `directStrategy().describe()` charts only its own states (Unpublished, Published, Draft); `reviewStrategy().describe()` adds Approved.

‎app/prm/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Built for individuals, small teams, and families — ideal for running on a home
88

99
- **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.
1010
- **Multi-user DB authentication** — first-run `/setup` creates the `owner` account; invite family or teammates via one-time `/invite/$token` links from `/prm-settings`.
11+
- **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.
1112
- **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`.
1213
- **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.
1314
- **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.

‎app/prm/src/cms.config.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
* - Stores all instance settings (`prm.json`), secrets (`secrets.env`), SQLite
66
* database (`cms.db`), and uploads (`uploads/`) inside a single data directory
77
* - DB-backed multi-user auth (`owner`, `member`, `viewer`) via `createDbAuth`
8-
* - Optional review queue (`review.autoApprove` defaults to `!instance.approvalRequired`)
8+
* - Owner direct, agent review (`ownerDirectAgentReview`): people who may publish
9+
* commit their own saves; agent writes stage in the review queue, or are
10+
* auto-approved when `instance.approvalRequired` is off
911
* - Two named conversational agents alongside `/agent`:
1012
* - `enrich` (`actor: 'enrichment-agent'`, deep-snoop web tools, 30 iterations)
1113
* - `ask` (`actor: 'crm-chat'`, read-only toolset, cited answers)
@@ -19,6 +21,7 @@ import { enrichAgentConfig, ENRICHMENT_SKILL_PROMPT } from './agents/enrich'
1921
import { askAgentConfig } from './agents/ask'
2022
import { crmEventHandlers } from './events'
2123
import { definition } from './cms.definition'
24+
import { ownerDirectAgentReview } from './document-state'
2225

2326
const resolveServerDataDir = createServerOnlyFn(async () => {
2427
const { resolvePrmDataDir } = await import('./instance.server')
@@ -41,13 +44,13 @@ export const cms = defineCms(definition, {
4144
ops: [importPeopleOp],
4245
eventHandlers: crmEventHandlers,
4346
seed,
44-
review: {
47+
documentState: ownerDirectAgentReview({
4548
autoApprove: createServerOnlyFn(async () => {
4649
await resolveServerDataDir()
4750
const { getPrmInstanceSettings } = await import('./instance.server')
4851
return !getPrmInstanceSettings().approvalRequired
4952
}),
50-
},
53+
}),
5154
auth: {
5255
defaultRole: 'member',
5356
getUser: createServerOnlyFn(async ({ request }) => {

‎app/prm/src/document-state.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* The PRM's document state strategy: owner direct, agent review.
3+
*
4+
* The PRM is personal, so a signed-in person who may publish (owner, member,
5+
* editor) commits their own saves at once; nobody approves their own notes.
6+
* Agent writes (the `enrich` agent, MCP keys, `import_people`) go through the
7+
* review flow: they stage in `/review` unless the instance's
8+
* `approvalRequired` setting is off, in which case they are approved at once
9+
* as `auto-approve`. Either way they stay attributed and audited.
10+
*/
11+
import { actorOf, directStrategy, reviewStrategy } from '@tanstack/cms-core'
12+
import type {
13+
AccessContext,
14+
DocumentStateStrategy,
15+
ReviewState,
16+
ReviewStrategyOptions,
17+
} from '@tanstack/cms-core'
18+
19+
const SAVES = new Set(['edit', 'submit', 'import'])
20+
21+
function ownsTheirSaves(ctx: AccessContext): boolean {
22+
return (
23+
actorOf(ctx).type === 'user' &&
24+
ctx.permissions.some((p) => p === 'content.publish')
25+
)
26+
}
27+
28+
export function ownerDirectAgentReview(
29+
options: Pick<ReviewStrategyOptions, 'autoApprove'> = {},
30+
): DocumentStateStrategy<ReviewState> {
31+
const review = reviewStrategy(options)
32+
const direct = directStrategy()
33+
return {
34+
...review,
35+
id: 'prm-owner-direct',
36+
version: 1,
37+
decide(ctx, doc, action) {
38+
return SAVES.has(action.type) && ownsTheirSaves(ctx)
39+
? direct.decide(ctx, doc, action)
40+
: review.decide(ctx, doc, action)
41+
},
42+
}
43+
}

‎app/prm/tests/crm.test.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@ import {
2828
normalizeSession,
2929
PERMISSIONS,
3030
} from '@tanstack/cms-core'
31-
import type { Field } from '@tanstack/cms-core'
31+
import type { AnyDocumentStateStrategy, Field } from '@tanstack/cms-core'
3232
import {
33+
accessContext,
34+
actOnDocument,
3335
approve,
3436
closeStore,
3537
cmsTools,
@@ -63,11 +65,16 @@ import {
6365
import { isHumanCreatedNewPerson } from '../src/events'
6466
import { BAKEOFF_SUBJECTS, runBakeoff } from '../scripts/bakeoff'
6567
import { buildKodyMcpRegistration } from '../kody-package'
68+
import { ownerDirectAgentReview } from '../src/document-state'
6669

6770
afterEach(closeStore)
6871

69-
function setupCrmTest(extra?: { textAdapter?: () => unknown }) {
72+
function setupCrmTest(extra?: {
73+
textAdapter?: () => unknown
74+
documentState?: AnyDocumentStateStrategy
75+
}) {
7076
defineCms({
77+
...(extra?.documentState ? { documentState: extra.documentState } : {}),
7178
storage: createSqliteStorage({ path: ':memory:' }),
7279
collections: crmCollections,
7380
blockTypes: [],
@@ -108,6 +115,54 @@ function setupCrmTest(extra?: { textAdapter?: () => unknown }) {
108115
}
109116

110117
describe('CRM acceptance criteria (§11)', () => {
118+
it('owner direct, agent review: a person who may publish commits their own saves; agent saves stage unless approval is off', async () => {
119+
for (const approvalRequired of [true, false]) {
120+
setupCrmTest({
121+
documentState: ownerDirectAgentReview({
122+
autoApprove: () => !approvalRequired,
123+
}),
124+
})
125+
const owner = normalizeSession({
126+
isAuthenticated: true,
127+
isAdmin: false,
128+
role: 'editor',
129+
user: { id: 'jack', name: 'Jack' },
130+
})
131+
const save = (id: string, ctx: Parameters<typeof actOnDocument>[0]) =>
132+
actOnDocument(ctx, {
133+
collection: 'person',
134+
id,
135+
action: {
136+
type: 'submit',
137+
patch: { name: id, headline: 'Notes', published: true },
138+
input: { change: 'create', source: 'review' },
139+
},
140+
})
141+
142+
await save('by-owner', accessContext({ session: owner, mode: 'edit' }))
143+
expect(await readDocument('person', 'by-owner')).toMatchObject({
144+
name: 'by-owner',
145+
})
146+
147+
await save(
148+
'by-agent',
149+
accessContext({ session: owner, agent: 'enrich', mode: 'edit' }),
150+
)
151+
if (approvalRequired) {
152+
expect(await readDocument('person', 'by-agent')).toBeNull()
153+
expect(
154+
(await listPending()).map((p) => [p.docId, p.workflow?.state]),
155+
).toEqual([['by-agent', 'pending_review']])
156+
} else {
157+
expect(await readDocument('person', 'by-agent')).toMatchObject({
158+
name: 'by-agent',
159+
})
160+
expect(await listPending()).toEqual([])
161+
}
162+
await closeStore()
163+
}
164+
})
165+
111166
it('§11.8: personal contact fields (email, phone, birthday, address) are writable by humans and blocked for agent sessions', () => {
112167
const contactFields = person.fields.filter((f) =>
113168
['email', 'phone', 'birthday', 'address'].includes(f.name),

‎docs/agents/custom-strategies.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ export function defineLegalReview(
420420
const live = doc.live?.published ? 'Published' : 'Unpublished'
421421
if (!state) return live
422422
const regions = regionLabel(state.value)
423-
if (regions) return `Pending review (${regions})`
423+
if (regions) return `Pending Review (${regions})`
424424
switch (state.value) {
425425
case 'changesRequested':
426426
return 'Changes requested'

‎docs/agents/review-queue.md‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ TanStack CMS has one workflow for every kind of change, whether a person or an a
2020

2121
- **Unpublished documents** are saved directly by anyone who may publish.
2222
- **Published documents** get a **draft**: the live version stays as it is until someone publishes the changes.
23-
- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where an editor approves or rejects them.
23+
- **Authors and agents** never commit. Their changes are **staged** in the review queue at `/review`, where a reviewer approves or rejects them.
24+
25+
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.
2426

2527
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**.
2628

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

8587
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.
8688

87-
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:
89+
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:
8890

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

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

96-
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.
98+
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:
99+
100+
```ts
101+
defineCms({
102+
roles: {
103+
reviewer: ['content.read', 'review.decide'],
104+
},
105+
// ...
106+
})
107+
```
108+
109+
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.
97110

98111
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:
99112

@@ -119,21 +132,26 @@ defineCms({
119132
})
120133
```
121134

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

124137
```mermaid
125138
stateDiagram-v2
126139
state "Unpublished" as unpublished
127140
state "Published" as published
128141
state "Draft" as draft
129-
state "Pending review" as pending_review
142+
state "Pending Review" as pending_review
143+
state "Approved" as approved
130144
unpublished --> pending_review: submit
131145
published --> pending_review: submit
132146
published --> draft: draft
133147
draft --> published: edit
134148
draft --> published: discard
135-
pending_review --> published: approve
149+
pending_review --> approved: approve
150+
pending_review --> published: approve (publisher)
136151
pending_review --> unpublished: reject
152+
approved --> published: publish
153+
approved --> pending_review: submit
154+
approved --> unpublished: reject
137155
unpublished --> published: publish
138156
published --> unpublished: unpublish
139157
```

‎docs/api/routes-and-endpoints.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/
250250
| `deleteDoc` | POST | `content.delete` | `{ collection, id, force? }` | `{ ok }` |
251251
| `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. |
252252
| `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. |
253-
| `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. |
253+
| `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. |
254254
| `rejectChange` | POST | `review.decide` | `{ id }` | The rejected pending change. |
255255
| `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. |
256256
| `proposeEdit` | POST | `agent.use` | `{ collection, id, instruction, current }` | The AI-proposed document (not saved). |

0 commit comments

Comments
 (0)