diff --git a/.changeset/phase-6-removal.md b/.changeset/phase-6-removal.md new file mode 100644 index 00000000..a1b3046b --- /dev/null +++ b/.changeset/phase-6-removal.md @@ -0,0 +1,37 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-client': minor +'@tanstack/cms-ui-react': minor +'@tanstack/search-cms': patch +--- + +This alpha finishes the core API refactor: one read vocabulary (`get`, `list`, and `searchAs` for full-text search), one write vocabulary (`save`, `act`), access contexts on every read, and the `document.*` event names. The verbs and aliases the earlier steps deprecated are removed. See step 31 of the [upgrading guide](https://github.com/TanStack/cms/blob/main/docs/deployment/upgrading.md#31-the-deprecated-verbs-are-removed), which lists every removed name, its replacement and its codemod. From a TanStack/cms checkout, run them in this order and review each warning: + +```sh +pnpm codemod access-context /path/to/your/app +pnpm codemod read-verbs /path/to/your/app +pnpm codemod write-verbs /path/to/your/app +pnpm codemod event-names /path/to/your/app +``` + +**Kept for one more alpha, removed in the next alpha:** `queryDocumentsAs` and `queryDocuments` (use `searchAs` or `listAs`), `readDocumentAs` and `readDocument` (use `getAs`, with `staged: false` for a read that feeds a write), their `cmsAs(cms, ctx)` methods, the `getPublicDocument` operation and Start function (use `get`), and the `read_document` agent tool (use `get_document`). + +**Breaking, removed:** + +- `@tanstack/cms-core/server`: the read functions without a context (`readSingleton`, `populateRelations`, `listDocuments`, `queryDocumentSummaries`, `groupDocuments`, `findReferences`, `listTranslations`, `listRevisions`, `readDocumentWithPending`, `readDocumentBySlug`, `findDocumentBySlug`; use the `…As(ctx, …)` form), `readDocumentBySlugAs` (use `getAs` by `id`, then by `locator`), and `findDocumentBySlugAs` (use `getAs` per collection), with the matching `cmsAs(cms, ctx)` methods. `searchAs(ctx, options)` is new: full-text and multi-collection search, `queryDocumentsAs` under its canonical name. +- Operations and `@tanstack/cms-api/start` functions: `listPublishedDocuments` (use `list`), `saveDoc` (use `save`), `createDoc` (use `save` with `create: true`) and `actOnChange` (use `act`, with the document's id instead of the pending change's). +- Agent tools: `create_document` (use `save_document` with `create: true`) and `update_document` (use `save_document`). +- `@tanstack/cms-client`: `collection(name).published`, `.save` and `.create` (use `client.list` and `client.save`). +- Events: the short names `publish`, `unpublish`, `delete`, `change` and `update`, and the `CmsEventAlias` type. A webhook `events` list that uses a short name now throws at `defineCms`, and an `onCmsEvent` filter throws when it subscribes, naming the replacement. + +**Behaviour changes to check, because nothing fails when they bite:** + +- **Relations are populated by default.** `get`, `list`, `client.get/list`, the `get`/`list` operations and `get_document` return `relations` beside each document unless called with `populate: false`. Code that only needs ids pays for the extra reads. +- **Content roles are no longer guessed from field names.** Collections that don't declare `summaryField`, `bylineField`, `dateField` and the rest lose SEO descriptions, social images, JSON-LD dates and authors, and post-card summaries, with no error. `pnpm codemod explicit-roles` declares what the old fallbacks picked. +- **A `publicPrefix` gives a collection a default `path`** derived from each document's locator, so the sitemap, "View" links and page navigation move to `{publicPrefix}/{locator}`, and a published URL change adds a redirect when the CMS has a redirects collection. +- The `save` operation records the operation's actor in revisions and the review queue (for example `api` over HTTP), where `saveDoc` recorded `human`. A staged create no longer records the "Created document" instruction. +- `save` with `create: true` (and `save_document` with `create: true`) refuses an existing id with `CONFLICT`. `create_document` replaced the document. +- `list` with a `locale` filters by document locale; `listPublishedDocuments` resolved localized fields instead. +- The canned `/p/$id` and `/post/$id` routes and `cmsDocumentQueryOptions` read only their own collection, by id and then by locator. They used to resolve the key across collections. +- The agent chat's Approve button reads the staged change from `save_document`'s `state.changeSet`. diff --git a/.claude/skills/voting/SKILL.md b/.claude/skills/voting/SKILL.md index 74617b16..db0ec185 100644 --- a/.claude/skills/voting/SKILL.md +++ b/.claude/skills/voting/SKILL.md @@ -20,13 +20,13 @@ they sort and filter through the indexed read path), and the write path is a server function composed from the same store primitives the admin uses. All store functions from `@tanstack/cms-core/server` are **async** — -`await` every `getAs`, `listAs`, `readDocumentAs`, `commitDocument`, and -`deleteDocument`. Every read takes an access context: `publicContext()` for +`await` every `getAs`, `listAs`, `commitDocument`, and `deleteDocument`. Every read takes an access context: `publicContext()` for what a visitor may see (published posts), and a named `systemContext(reason)` for the server-owned vote records. Reads that feed a -write (the existing vote, the post whose tally you commit) use -`readDocumentAs`, which returns the stored row; `getAs` in a system (edit) -context returns the working copy, with any staged changes overlaid. +write (the existing vote, the post whose tally you commit) pass +`staged: false` to `getAs`, which returns the stored row; without it, `getAs` +in a system (edit) context returns the working copy, with any staged changes +overlaid. ## 0. Prerequisites @@ -81,7 +81,7 @@ And on `post`, add: ``` Vote documents are never `published`, so they don't appear in the public -read paths (`get`, `list`, and the older `listPublishedDocuments`); `access.read` +read paths (`get` and `list`); `access.read` then keeps them out of non-admin API and MCP reads. **Deterministic vote ids.** Enforce one-vote-per-user with the id itself: @@ -132,7 +132,6 @@ import { getAs, listAs, publicContext, - readDocumentAs, requireAuthenticated, systemContext, } from '@tanstack/cms-core/server' @@ -140,6 +139,14 @@ import { // Votes and the cached tallies are maintained by the server, not the voter. const VOTES = systemContext('voting: votes and tallies are server-owned') +// The stored row, for a read that feeds a write. +async function stored(collection: string, id: string) { + return ( + (await getAs(VOTES, { collection, id, staged: false, populate: false })) + ?.doc ?? null + ) +} + export async function castVoteForVoter( postId: string, value: 1 | -1, @@ -157,7 +164,7 @@ export async function castVoteForVoter( } const id = voteId(postId, voterId) - const existing = await readDocumentAs(VOTES, 'vote', id) + const existing = await stored('vote', id) if (existing && Number(existing.value) === value) { await deleteDocument('vote', id, { actor: voterId }) // retract } else { @@ -189,7 +196,7 @@ export async function castVoteForVoter( } while (cursor) // Re-read the stored post: a public read may leave out fields the commit // would then drop. - const post = await readDocumentAs(VOTES, 'post', postId) + const post = await stored('post', postId) await commitDocument( 'post', postId, @@ -258,9 +265,7 @@ export async function getVoteState(postId: string, voterId?: string) { populate: false, }) )?.doc - const mine = voterId - ? await readDocumentAs(VOTES, 'vote', voteId(postId, voterId)) - : null + const mine = voterId ? await stored('vote', voteId(postId, voterId)) : null return { upvotes: Number(post?.upvotes ?? 0), downvotes: Number(post?.downvotes ?? 0), diff --git a/README.md b/README.md index 4701dc32..a38c7139 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ const products = createCollection( createCmsCollectionOptions(cms, queryClient, 'product'), ) -// In a component: a live query, and an optimistic write that runs saveDoc +// In a component: a live query, and an optimistic write that runs save const { data } = useLiveQuery({ query: (q) => q.from({ p: products }).where(({ p }) => gt(p.stock, 0)), }) diff --git a/app/base/e2e/base.spec.ts b/app/base/e2e/base.spec.ts index a5e8d8d1..f9864b52 100644 --- a/app/base/e2e/base.spec.ts +++ b/app/base/e2e/base.spec.ts @@ -58,10 +58,9 @@ test('first-run owner setup, sign-out, and API protection', async ({ await expect(page).toHaveURL(/\/login/) await page.goto('/setup') await expect(page).toHaveURL(/\/login/) - const denied = await page.request.post( - '/api/cms/v1/ops/listPublishedDocuments', - { data: { collection: 'products' } }, - ) + const denied = await page.request.post('/api/cms/v1/ops/list', { + data: { collection: 'products', populate: false }, + }) expect(denied.status()).toBe(401) const deniedList = await page.request.get('/api/cms/v1/ops/list', { params: { input: JSON.stringify({ collection: 'products' }) }, @@ -630,10 +629,11 @@ test('saved report snapshots stay fixed while live pages refresh; revisions requ kind: 'report', }) expect(initial.result.nodes[0].props.value).toBe(1) - await op(page, 'createDoc', { + await op(page, 'save', { collection: 'recipes', id: 'soup', doc: { title: 'Soup', instructions: '## Simmer\nCook slowly.' }, + create: true, }) const after = await op(page, 'readInterface', { id: 'recipe-count', @@ -747,10 +747,11 @@ test('collection events refresh affected interface components without waiting fo const body = request.postData() if (body?.includes('"componentIds"')) refreshes.push(body) }) - await op(page, 'createDoc', { + await op(page, 'save', { collection: 'recipes', id: 'pasta', doc: { title: 'Pasta', instructions: '## Boil\nCook pasta.' }, + create: true, }) await expect( page.getByRole('cell', { name: 'Pasta', exact: true }), @@ -827,10 +828,11 @@ test('admins enable a reviewed snapshot schedule, pause/resume it, and run the a report.getByText('Scheduled recipe count', { exact: true }), ).toBeVisible() await expect(report.locator('.cms-interface-metric')).toHaveText('2') - await op(page, 'createDoc', { + await op(page, 'save', { collection: 'recipes', id: 'toast', doc: { title: 'Toast' }, + create: true, }) await expect(report.locator('.cms-interface-metric')).toHaveText('2') await page diff --git a/app/base/scripts/smoke-docker.mjs b/app/base/scripts/smoke-docker.mjs index f7810d39..ee150bbe 100644 --- a/app/base/scripts/smoke-docker.mjs +++ b/app/base/scripts/smoke-docker.mjs @@ -155,13 +155,8 @@ try { await start(volumes[0]) await healthy() assert.equal( - ( - await request( - '/api/cms/v1/ops/listPublishedDocuments', - { collection: 'products' }, - '', - ) - ).status, + (await request('/api/cms/v1/ops/list', { collection: 'products' }, '')) + .status, 401, ) const setup = await request('/api/base-auth/setup', { @@ -213,10 +208,11 @@ try { } assert((await op('baseValidateSchemaDraft', schemaRef)).canPublish) await op('basePublishSchemaDraft', schemaRef) - await op('createDoc', { + await op('save', { collection: 'customers', id: 'ada', doc: { title: 'Ada', published: true }, + create: true, }) assert.equal( (await op('getDocument', { collection: 'customers', id: 'ada' })).doc @@ -286,7 +282,7 @@ try { name: 'recipes', draftVersion: recipeDraft.draft.version, }) - await op('createDoc', { + await op('save', { collection: 'recipes', id: 'cake', doc: { @@ -298,6 +294,7 @@ try { { name: 'Eggs', quantity: 2, unit: 'each' }, ], }, + create: true, }) const recipeNext = structuredClone(recipeDraft.draft.definition) recipeNext.fields @@ -376,7 +373,7 @@ try { assert.equal( ( await request( - '/api/cms/v1/ops/listPublishedDocuments', + '/api/cms/v1/ops/list', { collection: 'reports' }, viewerCookie, ) @@ -504,10 +501,11 @@ try { } } await readUntil((text) => text.includes('event: connected')) - await op('createDoc', { + await op('save', { collection: 'recipes', id: 'temporary-live-recipe', doc: { title: 'Temporary live recipe' }, + create: true, }) await readUntil((text) => text.includes('"id":"temporary-live-recipe"')) await op('deleteDoc', { collection: 'recipes', id: 'temporary-live-recipe' }) diff --git a/app/base/src/chat.server.ts b/app/base/src/chat.server.ts index 43fd43d9..2d740aac 100644 --- a/app/base/src/chat.server.ts +++ b/app/base/src/chat.server.ts @@ -41,5 +41,5 @@ ${mayConfigure ? `You may propose collection schemas. Current schema versions: $ Use baseListSchemas before creating or editing a schema; pass its exact version and draftVersion as expectedVersion and expectedDraftVersion to baseProposeCollection. New collections use zero for both. Re-read before retrying conflicts. Preserve existing fields and only add fields. Internal protected collections cannot be changed. Schema definition: {name:lowercase_underscore_name,label,titleField:"title",fields:[{name,label,type,required?,defaultValue?,options?,collection?,many?,fields?}]}. Supported types: ${fieldTypes.join(', ')}. Objects use type "group" with fields; arrays of objects use type "array" with fields. Ingredients are usually an array of objects with name, quantity, unit. Food images use a URL field and instructions use markdown. Only title needs required:true initially; avoid unsupported properties and executable validation. Select options are strings. Relation targets must already be approved collections. A published boolean is added automatically. baseProposeCollection saves and validates a draft. It does NOT publish. Tell the customer to use the chat's Approve collection button (or Collections) and STOP before creating data in that collection. Approval is a human UI action, never a tool or a chat instruction. On the next turn, consult current collections before adding data. -For records, use create_document or update_document. These produce proposals; the customer approves records in chat or Review. Never claim records are saved before approval. A query sees committed records; use read_document when explicitly asked about a pending proposal. If the user asks for sample data you may invent clearly identified examples; query answers must use tool results. For counts use search_documents.total. Fetch more pages when aggregating and state any limit. Preserve nested objects and arrays. Do not invent image URLs. Use concise Markdown, including tables when useful.` +For records, use save_document (with create: true for a new record). It produces proposals; the customer approves records in chat or Review. Never claim records are saved before approval. A query sees committed records; use get_document when explicitly asked about a pending proposal. If the user asks for sample data you may invent clearly identified examples; query answers must use tool results. For counts use search_documents.total. Fetch more pages when aggregating and state any limit. Preserve nested objects and arrays. Do not invent image URLs. Use concise Markdown, including tables when useful.` } diff --git a/app/base/src/operations.server.ts b/app/base/src/operations.server.ts index 6d4de339..6f56f6c3 100644 --- a/app/base/src/operations.server.ts +++ b/app/base/src/operations.server.ts @@ -22,9 +22,9 @@ import { listInterfaces, accessContext, systemContext, - readDocumentAs, listAs, withMode, + getAs, } from '@tanstack/cms-core/server' import { evacuateWordPress } from '@tanstack/cms-migrate-wp' import { listSkills } from '@tanstack/cms-skills' @@ -49,7 +49,15 @@ function guardSources(ctx: CmsOpContext) { } } async function committed(name: string, id: string, ctx: CmsOpContext) { - const doc = await readDocumentAs(CHECKED, name, id) + const doc = + ( + await getAs(CHECKED, { + collection: name, + id, + staged: false, + populate: false, + }) + )?.doc ?? null if (!doc) throw new CmsError('Document not found.', 'NOT_FOUND') assertCollectionAccess(ctx.session, name, 'read', doc) return redactDoc(name, doc, ctx.session) @@ -213,7 +221,15 @@ export async function submitReport( ctx: CmsOpContext, ) { const id = `coffee-trends-${data.endDate}` - const before = await readDocumentAs(CHECKED, 'reports', id) + const before = + ( + await getAs(CHECKED, { + collection: 'reports', + id, + staged: false, + populate: false, + }) + )?.doc ?? null assertCollectionAccess( ctx.session, 'reports', @@ -316,11 +332,15 @@ export async function evacuateWordPressToBase( let documentsImported = 0 for (const docItem of evacResult.documents) { if (!getCmsConfig().collections[docItem.collection]) continue - const existing = await readDocumentAs( - CHECKED, - docItem.collection, - docItem.id, - ) + const existing = + ( + await getAs(CHECKED, { + collection: docItem.collection, + id: docItem.id, + staged: false, + populate: false, + }) + )?.doc ?? null await commitDocument(docItem.collection, docItem.id, docItem.doc, { session: ctx.session, actor, @@ -337,7 +357,15 @@ export async function evacuateWordPressToBase( const rule = evacResult.redirects[i] if (!rule) continue const redirId = `wp-redirect-${rule.wpId}-${i + 1}` - const existing = await readDocumentAs(CHECKED, 'redirects', redirId) + const existing = + ( + await getAs(CHECKED, { + collection: 'redirects', + id: redirId, + staged: false, + populate: false, + }) + )?.doc ?? null await commitDocument( 'redirects', redirId, @@ -364,11 +392,15 @@ export async function evacuateWordPressToBase( let stagedReviewCount = 0 for (const seoProposal of evacResult.seoAuditProposals) { if (!getCmsConfig().collections[seoProposal.collection]) continue - const current = await readDocumentAs( - CHECKED, - seoProposal.collection, - seoProposal.docId, - ) + const current = + ( + await getAs(CHECKED, { + collection: seoProposal.collection, + id: seoProposal.docId, + staged: false, + populate: false, + }) + )?.doc ?? null if (!current) continue await stageWrite({ collection: seoProposal.collection, @@ -390,11 +422,15 @@ export async function evacuateWordPressToBase( for (const skillProp of evacResult.skillProposals) { for (const iface of skillProp.interfaceProposals) { if (!getCmsConfig().collections.interfaces) continue - const existingIface = await readDocumentAs( - CHECKED, - 'interfaces', - iface.id, - ) + const existingIface = + ( + await getAs(CHECKED, { + collection: 'interfaces', + id: iface.id, + staged: false, + populate: false, + }) + )?.doc ?? null await stageWrite({ collection: 'interfaces', docId: iface.id, @@ -440,7 +476,15 @@ export async function evacuateWordPressToBase( // 7. Update shop settings with migrated site title if available if (evacResult.site.title) { - const beforeShop = await readDocumentAs(CHECKED, 'shop', 'settings') + const beforeShop = + ( + await getAs(CHECKED, { + collection: 'shop', + id: 'settings', + staged: false, + populate: false, + }) + )?.doc ?? null if (beforeShop) { await commitDocument( 'shop', diff --git a/app/base/tests/base.test.ts b/app/base/tests/base.test.ts index c9a72958..b8dd8604 100644 --- a/app/base/tests/base.test.ts +++ b/app/base/tests/base.test.ts @@ -19,8 +19,8 @@ import { setDbUserDisabled, setUserRole, systemContext, - queryDocumentsAs, - readDocumentAs, + listAs, + getAs, } from '@tanstack/cms-core/server' import type { CmsOpContext, Field } from '@tanstack/cms-core' import { invokeAnyOp } from '@tanstack/cms-api' @@ -335,8 +335,12 @@ describe('coffee shop and reports', () => { }) expect(report.result.revenueCents).toBe(777000) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'reports' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'reports', + populate: false, + }) + ).total, ).toBe(0) await completeOnboarding( { name: 'New shop', pairingsEnabled: false }, @@ -344,7 +348,16 @@ describe('coffee shop and reports', () => { ) await closeStore() expect( - (await readDocumentAs(systemContext('test'), 'shop', 'settings'))?.name, + ( + ( + await getAs(systemContext('test'), { + collection: 'shop', + id: 'settings', + staged: false, + populate: false, + }) + )?.doc ?? null + )?.name, ).toBe('New shop') }) it('accepts preferences idempotently, leaving schemas unchanged', async () => { @@ -357,12 +370,24 @@ describe('coffee shop and reports', () => { await completeOnboarding({ name: 'My shop', pairingsEnabled: true }, ctx) await completeOnboarding({ name: 'My shop', pairingsEnabled: true }, ctx) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'shop' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'shop', + populate: false, + }) + ).total, ).toBe(1) expect( - (await readDocumentAs(systemContext('test'), 'shop', 'settings')) - ?.onboardingComplete, + ( + ( + await getAs(systemContext('test'), { + collection: 'shop', + id: 'settings', + staged: false, + populate: false, + }) + )?.doc ?? null + )?.onboardingComplete, ).toBe(true) await expect( completeOnboarding( @@ -375,11 +400,25 @@ describe('coffee shop and reports', () => { const ctx = context() const first = await submitReport({ endDate: DEMO_END_DATE }, ctx) expect( - await readDocumentAs(systemContext('test'), 'reports', first.reportId), + ( + await getAs(systemContext('test'), { + collection: 'reports', + id: first.reportId, + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() await reject(first.pendingId, { rejecter: 'Owner' }) expect( - await readDocumentAs(systemContext('test'), 'reports', first.reportId), + ( + await getAs(systemContext('test'), { + collection: 'reports', + id: first.reportId, + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() const second = await submitReport({ endDate: DEMO_END_DATE }, ctx) await approve(second.pendingId, { approver: 'Owner', publish: true }) @@ -391,8 +430,16 @@ describe('coffee shop and reports', () => { const third = await submitReport({ endDate: DEMO_END_DATE }, ctx) await approve(third.pendingId, { approver: 'Owner', publish: true }) expect( - (await readDocumentAs(systemContext('test'), 'reports', third.reportId)) - ?._revision, + ( + ( + await getAs(systemContext('test'), { + collection: 'reports', + id: third.reportId, + staged: false, + populate: false, + }) + )?.doc ?? null + )?._revision, ).toBe(2) }) it('denies scoped report reads and operations without credentials', async () => { @@ -403,8 +450,8 @@ describe('coffee shop and reports', () => { ).rejects.toThrow() expect( await invokeAnyOp( - 'listPublishedDocuments', - { collection: 'reports' }, + 'list', + { collection: 'reports', populate: false }, { access: accessContext({ session: scoped.session, mode: 'edit' }), }, @@ -412,13 +459,6 @@ describe('coffee shop and reports', () => { ).toMatchObject({ items: [] }) await expect(invokeAnyOp('baseTrends', {})).rejects.toThrow() // Public CMS data endpoints must not expose the seeded shop. - expect( - ( - await guardApiRequest( - new Request('http://localhost/api/cms/v1/ops/listPublishedDocuments'), - ) - )?.status, - ).toBe(401) expect( ( await guardApiRequest( @@ -432,24 +472,6 @@ describe('coffee shop and reports', () => { await approve(staged.pendingId, { publish: true }) const scoped = context('viewer') scoped.session.scope = { collections: ['reports'] } - await expect( - invokeAnyOp( - 'listPublishedDocuments', - { collection: 'reports' }, - { - access: accessContext({ session: scoped.session, mode: 'edit' }), - }, - ), - ).rejects.toThrow() - await expect( - invokeAnyOp( - 'getPublicDocument', - { slugOrId: staged.reportId }, - { - access: accessContext({ session: scoped.session, mode: 'edit' }), - }, - ), - ).rejects.toThrow() await expect( invokeAnyOp( 'list', @@ -507,7 +529,14 @@ describe('coffee shop and reports', () => { )) as { reportId: string; staged: boolean } expect(pending.staged).toBe(true) expect( - await readDocumentAs(systemContext('test'), 'reports', pending.reportId), + ( + await getAs(systemContext('test'), { + collection: 'reports', + id: pending.reportId, + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() }) it('audits human CRUD and access changes without including credentials', async () => { @@ -515,7 +544,7 @@ describe('coffee shop and reports', () => { access: accessContext({ session: context().session, mode: 'edit' }), } await invokeAnyOp( - 'createDoc', + 'save', { collection: 'suppliers', id: 'audit-test', @@ -524,6 +553,7 @@ describe('coffee shop and reports', () => { email: 'audit@example.com', published: true, }, + create: true, }, admin, ) diff --git a/app/base/tests/chat.test.ts b/app/base/tests/chat.test.ts index c342a9bf..af753384 100644 --- a/app/base/tests/chat.test.ts +++ b/app/base/tests/chat.test.ts @@ -8,7 +8,7 @@ import { closeStore, listPending, systemContext, - readDocumentAs, + getAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { definition as cmsDefinition } from '../src/cms.definition' @@ -162,8 +162,8 @@ describe('customer chat tools', () => { } vi.mocked(chat).mockImplementation(async (options) => { expect(options.systemPrompts?.join('\n')).toContain('ingredients:array') - await options.tools!.find((tool) => tool.name === 'create_document')! - .execute!({ collection: 'recipes', id: 'cake', doc }) + await options.tools!.find((tool) => tool.name === 'save_document')! + .execute!({ collection: 'recipes', id: 'cake', doc, create: true }) return { text: 'Review this recipe.', chunks: [] } }) const staged = (await call('agentChat', { @@ -172,21 +172,27 @@ describe('customer chat tools', () => { })) as { toolResults: Array<{ result: { - pendingId: string - pendingVersion: number - resultingDocument: typeof doc + doc: typeof doc + state: { changeSet: { id: string; version: number } } } }> } - expect(staged.toolResults[0].result.resultingDocument.ingredients).toEqual( + expect(staged.toolResults[0].result.doc.ingredients).toEqual( doc.ingredients, ) expect( - await readDocumentAs(systemContext('test'), 'recipes', 'cake'), + ( + await getAs(systemContext('test'), { + collection: 'recipes', + id: 'cake', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() await call('approveChange', { - id: staged.toolResults[0].result.pendingId, - expectedVersion: staged.toolResults[0].result.pendingVersion, + id: staged.toolResults[0].result.state.changeSet.id, + expectedVersion: staged.toolResults[0].result.state.changeSet.version, }) vi.mocked(chat).mockImplementation(async (options) => { await options.tools!.find((tool) => tool.name === 'search_documents')! diff --git a/app/base/tests/schema-registry.test.ts b/app/base/tests/schema-registry.test.ts index be975897..9f29ac16 100644 --- a/app/base/tests/schema-registry.test.ts +++ b/app/base/tests/schema-registry.test.ts @@ -13,7 +13,7 @@ import { stageWrite, approve, systemContext, - readDocumentAs, + getAs, } from '@tanstack/cms-core/server' import { invokeAnyOp, ops } from '@tanstack/cms-api' import { definition as cmsDefinition } from '../src/cms.definition' @@ -167,10 +167,11 @@ describe('persisted runtime collection schemas', () => { expect(meta).toBeTruthy() }) expect(getCmsConfig().collections.customers).toBeUndefined() - await call('createDoc', { + await call('save', { collection: 'customers', id: 'ada', doc: { title: 'Ada' }, + create: true, }) const result = (await call('getDocument', { collection: 'customers', @@ -374,8 +375,14 @@ describe('persisted runtime collection schemas', () => { await approve(pending.id) await restoreRevision('customers', 'ada', 1) expect( - (await readDocumentAs(systemContext('test'), 'customers', 'ada'))! - .loyalty, + (( + await getAs(systemContext('test'), { + collection: 'customers', + id: 'ada', + staged: false, + populate: false, + }) + )?.doc ?? null)!.loyalty, ).toBe(10) }) const audit = await storage.listAudit() @@ -385,10 +392,11 @@ describe('persisted runtime collection schemas', () => { }) it('rejects transactions captured before a schema publish without overwriting migrated records', async () => { await publish() - await call('createDoc', { + await call('save', { collection: 'customers', id: 'ada', doc: { title: 'Ada' }, + create: true, }) const entry = (await readRegistry()).entries.find( (e) => e.name === 'customers', @@ -459,10 +467,11 @@ describe('persisted runtime collection schemas', () => { }) it('rolls back metadata and records if a migration write fails', async () => { await publish() - await call('createDoc', { + await call('save', { collection: 'customers', id: 'ada', doc: { title: 'Ada' }, + create: true, }) const storage = await getStorage() const current = (await readRegistry()).entries.find( @@ -672,15 +681,27 @@ describe('CMS nested schemas exposed by Base', () => { await closeStore() await withSchemaRegistry(false, async () => { expect( - (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! - .ingredients, + (( + await getAs(systemContext('test'), { + collection: 'recipes', + id: 'cake', + staged: false, + populate: false, + }) + )?.doc ?? null)!.ingredients, ).toEqual([ { name: 'Flour', quantity: 250, unit: 'g' }, { name: 'Eggs', quantity: 2, unit: 'each' }, ]) expect( - (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! - .preparation, + (( + await getAs(systemContext('test'), { + collection: 'recipes', + id: 'cake', + staged: false, + populate: false, + }) + )?.doc ?? null)!.preparation, ).toEqual({ minutes: 45, }) @@ -761,12 +782,24 @@ describe('CMS nested schemas exposed by Base', () => { await approve(pending.id) await restoreRevision('recipes', 'cake', 1) expect( - (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! - .ingredients, + (( + await getAs(systemContext('test'), { + collection: 'recipes', + id: 'cake', + staged: false, + populate: false, + }) + )?.doc ?? null)!.ingredients, ).toEqual(after.doc.ingredients) expect( - (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! - .preparation, + (( + await getAs(systemContext('test'), { + collection: 'recipes', + id: 'cake', + staged: false, + populate: false, + }) + )?.doc ?? null)!.preparation, ).toEqual(after.doc.preparation) }) }) diff --git a/app/base/tests/worker.test.ts b/app/base/tests/worker.test.ts index 56452b39..3dc9c372 100644 --- a/app/base/tests/worker.test.ts +++ b/app/base/tests/worker.test.ts @@ -20,7 +20,7 @@ import { setDbUserDisabled, setUserRole, systemContext, - readDocumentAs, + getAs, } from '@tanstack/cms-core/server' import { definition as cmsDefinition } from '../src/cms.definition' import { collectionRuntimes } from '../src/collection-runtime' @@ -127,11 +127,14 @@ describe('Base background interface worker', () => { .poll( async () => ( - await readDocumentAs( - systemContext('test'), - 'interfaces', - 'scheduled', - ) + ( + await getAs(systemContext('test'), { + collection: 'interfaces', + id: 'scheduled', + staged: false, + populate: false, + }) + )?.doc ?? null )?._revision, { timeout: 5000, interval: 100 }, ) diff --git a/app/base/tests/wp-evacuation.test.ts b/app/base/tests/wp-evacuation.test.ts index 7c4a5d68..804e1097 100644 --- a/app/base/tests/wp-evacuation.test.ts +++ b/app/base/tests/wp-evacuation.test.ts @@ -7,7 +7,7 @@ import { closeStore, listPending, systemContext, - queryDocumentsAs, + listAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsSearch } from '@tanstack/search-cms' @@ -237,9 +237,10 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { // 4. Verify documents are queryable and de-souped const caseStudies = await withSchemaRegistry(true, () => - queryDocumentsAs(systemContext('test'), { + listAs(systemContext('test'), { collection: 'case_study', limit: 50, + populate: false, }), ) expect(caseStudies.total).toBe(20) @@ -285,9 +286,10 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { // 6. Verify 1:1 SEO 301 Redirects are persisted in the `redirects` collection expect(result.redirectsCreated).toBe(100) const redirects = await withSchemaRegistry(true, () => - queryDocumentsAs(systemContext('test'), { + listAs(systemContext('test'), { collection: 'redirects', limit: 100, + populate: false, }), ) expect(redirects.total).toBe(100) @@ -357,33 +359,37 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { // Verify coffee_bean, store_location, 10 brewing posts, and menu_item are queryable in app/base const beans = await withSchemaRegistry(true, () => - queryDocumentsAs(systemContext('test'), { + listAs(systemContext('test'), { collection: 'coffee_bean', limit: 10, + populate: false, }), ) expect(beans.total).toBe(2) const locations = await withSchemaRegistry(true, () => - queryDocumentsAs(systemContext('test'), { + listAs(systemContext('test'), { collection: 'store_location', limit: 10, + populate: false, }), ) expect(locations.total).toBe(2) const posts = await withSchemaRegistry(true, () => - queryDocumentsAs(systemContext('test'), { + listAs(systemContext('test'), { collection: 'posts', limit: 20, + populate: false, }), ) expect(posts.total).toBe(10) const menuItems = await withSchemaRegistry(true, () => - queryDocumentsAs(systemContext('test'), { + listAs(systemContext('test'), { collection: 'menu_item', limit: 10, + populate: false, }), ) expect(menuItems.total).toBe(5) diff --git a/app/prm/kody-package/index.ts b/app/prm/kody-package/index.ts index f4a486a1..d9c02431 100644 --- a/app/prm/kody-package/index.ts +++ b/app/prm/kody-package/index.ts @@ -27,17 +27,16 @@ export interface KodyMcpCrmClient { collection: string limit?: number }) => Promise - read_document: (input: { collection: string; id: string }) => Promise - create_document: (input: { + get_document: (input: { collection: string id: string - doc: Record - instruction?: string + populate?: boolean }) => Promise - update_document: (input: { + save_document: (input: { collection: string id: string doc: Record + create?: boolean instruction?: string }) => Promise } diff --git a/app/prm/scripts/mine-summit-speakers.ts b/app/prm/scripts/mine-summit-speakers.ts index df75b4f4..0ba724e7 100644 --- a/app/prm/scripts/mine-summit-speakers.ts +++ b/app/prm/scripts/mine-summit-speakers.ts @@ -35,7 +35,7 @@ import { closeStore, commitDocument, systemContext, - readDocumentAs, + getAs, } from '@tanstack/cms-core/server' import { createExaSearchProvider } from '../src/enrich/search-provider' import { @@ -547,11 +547,16 @@ async function main() { } privateSeed.documents.organisation![orgId] = orgDoc if ( - !(await readDocumentAs( - systemContext('prm script: local maintenance'), - 'organisation', - orgId, - )) + !( + ( + await getAs(systemContext('prm script: local maintenance'), { + collection: 'organisation', + id: orgId, + staged: false, + populate: false, + }) + )?.doc ?? null + ) ) { await commitDocument('organisation', orgId, orgDoc, { actor: 'enrichment-agent', diff --git a/app/prm/scripts/snoop-sunil.ts b/app/prm/scripts/snoop-sunil.ts index e2f59eb0..1c73081f 100644 --- a/app/prm/scripts/snoop-sunil.ts +++ b/app/prm/scripts/snoop-sunil.ts @@ -6,7 +6,7 @@ import { listPending, seedContent, systemContext, - readDocumentAs, + getAs, } from '@tanstack/cms-core/server' import { runAgent } from '@tanstack/cms-api' @@ -78,11 +78,15 @@ async function main() { } } - const liveDoc = await readDocumentAs( - systemContext('prm script: local maintenance'), - 'person', - 'sunil-pai', - ) + const liveDoc = + ( + await getAs(systemContext('prm script: local maintenance'), { + collection: 'person', + id: 'sunil-pai', + staged: false, + populate: false, + }) + )?.doc ?? null console.log( `\nLive person.enrichmentStatus before /review approval: "${String(liveDoc?.enrichmentStatus)}"`, ) diff --git a/app/prm/src/agents/ask.ts b/app/prm/src/agents/ask.ts index 83831354..dc1644b0 100644 --- a/app/prm/src/agents/ask.ts +++ b/app/prm/src/agents/ask.ts @@ -3,7 +3,7 @@ * * Distinct from `/agent`: * - `toolset: 'read'` — only `list_collections`, `list_documents`, - * `read_document`, `search_documents`, `list_revisions`, `list_translations`, + * `get_document`, `search_documents`, `list_revisions`, `list_translations`, * `list_comments`. Zero write operations exist in its toolset. * - `actor: 'crm-chat'` * - No web access — answers strictly from PRM documents and says so. @@ -15,7 +15,7 @@ import { z } from 'zod' import type { CmsAgentConfig } from '@tanstack/cms-core' export const ASK_CRM_PROMPT = `You are the Ask-the-PRM assistant for this Personal Relationship Manager (PRM). -You answer questions strictly from the data stored in the PRM using your read-only tools (\`search_documents\`, \`list_documents\`, \`read_document\`, \`list_revisions\`). +You answer questions strictly from the data stored in the PRM using your read-only tools (\`search_documents\`, \`list_documents\`, \`get_document\`, \`list_revisions\`). You have NO write tools and NO web access. Non-negotiable rules (§6.1): diff --git a/app/prm/src/agents/enrich.ts b/app/prm/src/agents/enrich.ts index e32c7d4d..90d2be46 100644 --- a/app/prm/src/agents/enrich.ts +++ b/app/prm/src/agents/enrich.ts @@ -24,14 +24,14 @@ Rules (§2, §4, §5, §8): - Set enrichmentStatus to "needs-disambiguation" on the person document. - Propose NO other field changes and NEVER merge two existing person docs. - Stage only a markdown note in \`notes\` listing each candidate, what they do, and a source URL for each. -2. PROVENANCE PER FIELD (§4): For every field you set or change on \`person\` (including \`notes\`), you MUST also call \`create_document\` on \`personSource\` with: +2. PROVENANCE PER FIELD (§4): For every field you set or change on \`person\` (including \`notes\`), you MUST also call \`save_document\` with \`create: true\` on \`personSource\` with: - \`person\`: the person's id - \`field\`: the exact field name ("headline", "org", "role", "location", "website", "github", "linkedin", "bluesky", "xHandle", "interests", "notes") - \`sourceUrl\`: the allowed public URL where you found the fact - \`fetchedAt\`: today's YYYY-MM-DD date - \`confidence\`: "high" (stated verbatim on the source), "medium" (stated once / changeable), or "low" (your inference — \`interests\` MUST ALWAYS be "low") - \`published\`: true -3. RESPECT HUMAN EDITS (§5.5): Before updating an existing person, call \`read_document\` and \`list_revisions\` for that person. Never overwrite a human-entered field (actor "human" or "admin") with a lower-confidence sourced value; if there is a conflict, keep the human value and note the conflict under \`## Open questions\` in \`notes\`. +3. RESPECT HUMAN EDITS (§5.5): Before updating an existing person, call \`get_document\` and \`list_revisions\` for that person. Never overwrite a human-entered field (actor "human" or "admin") with a lower-confidence sourced value; if there is a conflict, keep the human value and note the conflict under \`## Open questions\` in \`notes\`. 4. DIFF-ONLY RE-ENRICHMENT (§5.4): Check existing \`personSource\` documents for the person first. If the person's facts have not changed since \`enrichedAt\`, stage NO writes at all and reply that the card is already up to date. 5. DEEP SNOOP NOTES STRUCTURE (§5.6): When running a deep snoop (the default for a manual add or Enrich button), write \`person.notes\` using this exact Markdown structure: ## Summary diff --git a/app/prm/src/ops/import-people.ts b/app/prm/src/ops/import-people.ts index 8c618d4f..715d0310 100644 --- a/app/prm/src/ops/import-people.ts +++ b/app/prm/src/ops/import-people.ts @@ -144,7 +144,7 @@ export const importPeopleOp = defineOp({ .describe('Target event document id for imported talks.'), }), run: async (input) => { - const { stageWrite, systemContext, readDocumentAs } = + const { stageWrite, systemContext, getAs } = await import('@tanstack/cms-core/server') // Whether each record exists decides between staging a create and an update. const existing = systemContext('import_people: create or update') @@ -163,11 +163,15 @@ export const importPeopleOp = defineOp({ if (row.orgName) { orgId = slugify(row.orgName) if (orgId) { - const existingOrg = await readDocumentAs( - existing, - 'organisation', - orgId, - ) + const existingOrg = + ( + await getAs(existing, { + collection: 'organisation', + id: orgId, + staged: false, + populate: false, + }) + )?.doc ?? null if (!existingOrg && !stagedOrgs.includes(orgId)) { await stageWrite({ collection: 'organisation', @@ -186,7 +190,15 @@ export const importPeopleOp = defineOp({ } } - const existingPerson = await readDocumentAs(existing, 'person', personId) + const existingPerson = + ( + await getAs(existing, { + collection: 'person', + id: personId, + staged: false, + populate: false, + }) + )?.doc ?? null const existingGroups = Array.isArray(existingPerson?.groups) ? (existingPerson.groups as Array) : [] @@ -220,7 +232,15 @@ export const importPeopleOp = defineOp({ if (row.talkTitle) { const talkId = `talk-${personId}` - const existingTalk = await readDocumentAs(existing, 'talk', talkId) + const existingTalk = + ( + await getAs(existing, { + collection: 'talk', + id: talkId, + staged: false, + populate: false, + }) + )?.doc ?? null await stageWrite({ collection: 'talk', docId: talkId, @@ -236,7 +256,15 @@ export const importPeopleOp = defineOp({ instruction: `Import talk for ${row.name}`, }) const roleId = `role-${input.eventId}-${personId}` - const existingRole = await readDocumentAs(existing, 'eventRole', roleId) + const existingRole = + ( + await getAs(existing, { + collection: 'eventRole', + id: roleId, + staged: false, + populate: false, + }) + )?.doc ?? null const priority = row.tier === 'tier-1' ? 'high' @@ -266,11 +294,15 @@ export const importPeopleOp = defineOp({ if (row.sourceUrl) { const sourceId = `src-${personId}-headline` - const existingSource = await readDocumentAs( - existing, - 'personSource', - sourceId, - ) + const existingSource = + ( + await getAs(existing, { + collection: 'personSource', + id: sourceId, + staged: false, + populate: false, + }) + )?.doc ?? null await stageWrite({ collection: 'personSource', docId: sourceId, diff --git a/app/prm/src/routes/ask.tsx b/app/prm/src/routes/ask.tsx index 7b2bba79..653a9bcd 100644 --- a/app/prm/src/routes/ask.tsx +++ b/app/prm/src/routes/ask.tsx @@ -3,7 +3,7 @@ * * Distinct from `/agent`: * - Calls `agentChat({ agent: 'ask', includeToolResults: true })` - * - Has a strictly read-only toolset (`list_documents`, `read_document`, + * - Has a strictly read-only toolset (`list_documents`, `get_document`, * `search_documents`, `list_revisions`) and NO web access * - Renders cited person cards (leading with photo + what-they-do) * - When a person or fact is not in the CRM, surfaces two explicit action diff --git a/app/prm/tests/crm.test.ts b/app/prm/tests/crm.test.ts index d7b92034..0309bdf4 100644 --- a/app/prm/tests/crm.test.ts +++ b/app/prm/tests/crm.test.ts @@ -40,7 +40,7 @@ import { runOp, seedContent, systemContext, - readDocumentAs, + getAs, } from '@tanstack/cms-core/server' import { createSqliteStorage } from '@tanstack/cms-core/storage' import { createCmsApiHandler, invokeAnyOp } from '@tanstack/cms-api' @@ -141,7 +141,14 @@ describe('CRM acceptance criteria (§11)', () => { await save('by-owner', accessContext({ session: owner, mode: 'edit' })) expect( - await readDocumentAs(systemContext('test'), 'person', 'by-owner'), + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'by-owner', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toMatchObject({ name: 'by-owner', }) @@ -152,14 +159,28 @@ describe('CRM acceptance criteria (§11)', () => { ) if (approvalRequired) { expect( - await readDocumentAs(systemContext('test'), 'person', 'by-agent'), + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'by-agent', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() expect( (await listPending()).map((p) => [p.docId, p.workflow?.state]), ).toEqual([['by-agent', 'pending_review']]) } else { expect( - await readDocumentAs(systemContext('test'), 'person', 'by-agent'), + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'by-agent', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toMatchObject({ name: 'by-agent', }) @@ -243,14 +264,13 @@ describe('CRM acceptance criteria (§11)', () => { ...extraAskTools.map((t) => t.name), ] expect(allAskToolNames).toContain('list_documents') - expect(allAskToolNames).toContain('read_document') + expect(allAskToolNames).toContain('get_document') expect(allAskToolNames).toContain('search_documents') expect(allAskToolNames).toContain('list_revisions') expect(allAskToolNames).toContain('offer_next_step') for (const forbiddenWriteOp of [ - 'create_document', - 'update_document', + 'save_document', 'delete_document', 'restore_document', 'unpublish_document', @@ -284,7 +304,7 @@ describe('CRM acceptance criteria (§11)', () => { }) // Enrichment agent proposes a new person card + personSource rows await runOp( - 'create_document', + 'save_document', { collection: 'person', id: 'new-speaker', @@ -301,13 +321,14 @@ describe('CRM acceptance criteria (§11)', () => { published: true, }, instruction: 'Deep-snoop enrichment for Priya Nair', + create: true, }, 'enrichment-agent', agent, ) await runOp( - 'create_document', + 'save_document', { collection: 'personSource', id: 'src-priya-headline', @@ -319,13 +340,14 @@ describe('CRM acceptance criteria (§11)', () => { confidence: 'high', published: true, }, + create: true, }, 'enrichment-agent', agent, ) await runOp( - 'create_document', + 'save_document', { collection: 'personSource', id: 'src-priya-interests', @@ -338,6 +360,7 @@ describe('CRM acceptance criteria (§11)', () => { note: 'Inferred from WASM sandbox talk abstract', published: true, }, + create: true, }, 'enrichment-agent', agent, @@ -345,14 +368,24 @@ describe('CRM acceptance criteria (§11)', () => { // Nothing appears in live `documents` before `/review` approval (§11.3) expect( - await readDocumentAs(systemContext('test'), 'person', 'new-speaker'), + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'new-speaker', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() expect( - await readDocumentAs( - systemContext('test'), - 'personSource', - 'src-priya-headline', - ), + ( + await getAs(systemContext('test'), { + collection: 'personSource', + id: 'src-priya-headline', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() const pending = await listPending() @@ -370,11 +403,15 @@ describe('CRM acceptance criteria (§11)', () => { await approve(personPending!.id, { approver: 'Jack' }) await approve(interestSourcePending!.id, { approver: 'Jack' }) - const committed = await readDocumentAs( - systemContext('test'), - 'person', - 'new-speaker', - ) + const committed = + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'new-speaker', + staged: false, + populate: false, + }) + )?.doc ?? null expect(committed?.headline).toContain('Staff Compiler Engineer') expect(committed?.enrichmentStatus).toBe('enriched') @@ -395,11 +432,15 @@ describe('CRM acceptance criteria (§11)', () => { await seedContent() // §11.2: Alex Chen is in `needs-disambiguation` with candidate notes - const alex = await readDocumentAs( - systemContext('test'), - 'person', - 'alex-chen', - ) + const alex = + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'alex-chen', + staged: false, + populate: false, + }) + )?.doc ?? null expect(alex?.enrichmentStatus).toBe('needs-disambiguation') expect(String(alex?.notes)).toContain('Disambiguation required') @@ -468,7 +509,14 @@ describe('CRM acceptance criteria (§11)', () => { expect(result.importedCount).toBe(1) expect(result.stagedPeople).toEqual(['elena-rostova']) expect( - await readDocumentAs(systemContext('test'), 'person', 'elena-rostova'), + ( + await getAs(systemContext('test'), { + collection: 'person', + id: 'elena-rostova', + staged: false, + populate: false, + }) + )?.doc ?? null, ).toBeNull() const pending = await listPending() @@ -591,8 +639,7 @@ describe('CRM acceptance criteria (§11)', () => { const readText = await readList.text() expect(readText).toContain('list_documents') expect(readText).toContain('search_documents') - expect(readText).not.toContain('create_document') - expect(readText).not.toContain('update_document') + expect(readText).not.toContain('save_document') // 3. Write key with x-cms-agent header -> stages under mcp: const writeCall = await handler( @@ -609,7 +656,7 @@ describe('CRM acceptance criteria (§11)', () => { id: 2, method: 'tools/call', params: { - name: 'create_document', + name: 'save_document', arguments: { collection: 'interaction', id: 'int-mcp-test', @@ -626,7 +673,7 @@ describe('CRM acceptance criteria (§11)', () => { }), ) expect(writeCall.status).toBe(200) - expect(await writeCall.text()).toContain('Staged') + expect(await writeCall.text()).toContain('"source":"agent"') const pending = await listPending() const mcpPending = pending.find((p) => p.docId === 'int-mcp-test') diff --git a/docs/agents/content-agent.md b/docs/agents/content-agent.md index e58e19dc..9024abda 100644 --- a/docs/agents/content-agent.md +++ b/docs/agents/content-agent.md @@ -88,7 +88,7 @@ const reply = await chat({ ### Tools and Permissions -The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `save_document`, `create_document` and `update_document` (deprecated), `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`. +The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `save_document`, `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`. The tools run with the signed-in user's session, so the agent sees only the collections and fields that user may read, and preserves fields they may not write. Every write is **staged** in the [review queue](./review-queue) with `actor: 'content-agent'`, even when an admin is chatting. When the agent stages something, the page shows a **Review changes** link to `/review`. diff --git a/docs/agents/on-page-editor.md b/docs/agents/on-page-editor.md index 98c87314..e7fb696d 100644 --- a/docs/agents/on-page-editor.md +++ b/docs/agents/on-page-editor.md @@ -87,7 +87,7 @@ All of these return proposals and never save. They require `agent.use` (`editPag - The proposed title, fields, or blocks render live in the page layout, with an "AI proposed" marker on each changed element. - The bottom bar switches to proposal mode with **Approve & publish** and **Discard**. -- Approving saves through `saveDoc` (or `savePageBlocks`), so the [normal workflow](./review-queue) applies: an author's change is staged in the review queue, and a publisher's change is committed and goes live immediately, even on a published document (the admin editor, by contrast, keeps a draft until **Publish changes**). Every commit records a revision you can restore from the editor. +- Approving saves through `save` (or `savePageBlocks`), so the [normal workflow](./review-queue) applies: an author's change is staged in the review queue, and a publisher's change is committed and goes live immediately, even on a published document (the admin editor, by contrast, keeps a draft until **Publish changes**). Every commit records a revision you can restore from the editor. Agents working off the page (the content agent, MCP, WebMCP) never get this direct path: their writes are always staged in `/review`. diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index 2dfae90c..8327a973 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -28,16 +28,16 @@ Every commit records a **revision**, and every decision (a direct save, an appro 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. -Editing reads expose `pendingVersion`. Pass it as `expectedPendingVersion` to `saveDoc` (use `0` when there is no pending copy) to detect another editor changing a draft/proposal. The built-in editor reads both versions from `getDocEditorMeta`'s `state` and sends them with `save` as `expectedRevision` and `expectedPendingVersion`. +Editing reads expose `pendingVersion`. Pass it as `expectedPendingVersion` to `save` (use `0` when there is no pending copy) to detect another editor changing a draft/proposal. The built-in editor reads both versions from `getDocEditorMeta`'s `state` and sends them with `save` as `expectedRevision` and `expectedPendingVersion`. ## Who Commits, Who Drafts, Who Is Reviewed -When someone saves in the editor (the `saveDoc` operation), the outcome depends on whether they may publish in that collection (the `content.publish` permission plus the collection's `access.publish` rule): +When someone saves in the editor (the `save` operation), the outcome depends on whether they may publish in that collection (the `content.publish` permission plus the collection's `access.publish` rule): | Saver | Document is unpublished or new | Document is published | | --- | --- | --- | | Can publish (`editor`, `admin`) | Committed immediately | Saved as a **draft**; live version unchanged | -| Can publish, with **Publish changes** (`saveDoc({ publish: true })`) | Committed | Committed; the draft is folded in and goes live | +| Can publish, with **Publish changes** (`save({ publish: true })`) | Committed | Committed; the draft is folded in and goes live | | Cannot publish (`author`) | **Staged** for review | **Staged** for review | | Any agent (content agent, MCP, WebMCP) | **Staged** for review | **Staged** for review | @@ -49,7 +49,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, 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. +Agents work through the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas). The write tools (`save_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) @@ -81,7 +81,7 @@ An agent often makes several edits to the same document before anyone reviews th The pending change belongs to the door that opened it: an agent proposal (`agent`), an author's save (`review`) or a publisher's draft (`draft`). While it is open, a write through another door fails with `CONFLICT` and `details: { pendingId, source }` naming it. Approve, reject or discard it first. -Agents can read their own staged work. `get_document` (in the agent's `edit` mode), `save_document` and `update_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue. +Agents can read their own staged work. `get_document` (in the agent's `edit` mode) and `save_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue. ## Reviewing Changes @@ -107,7 +107,7 @@ defineCms({ }) ``` -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. +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 `act({ collection, id, action, publishAt?, reason?, expectedVersion? })` with the document's id, 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: @@ -174,11 +174,12 @@ const cms = createCmsClient({ baseUrl: 'https://cms.example.com' }) export async function rename(id: string, title: string, loadedRevision: number) { try { - return await cms.collection('post').save( + return await cms.save({ + collection: 'post', id, - { title }, - { expectedRevision: loadedRevision }, - ) + doc: { title }, + expectedRevision: loadedRevision, + }) } catch (e) { if (e instanceof CmsApiError && e.code === 'CONFLICT') { return { conflict: true as const } diff --git a/docs/api/cms-api.md b/docs/api/cms-api.md index 62932a00..dfbe3b27 100644 --- a/docs/api/cms-api.md +++ b/docs/api/cms-api.md @@ -109,7 +109,7 @@ function requestAccessContext(request?: Request, options?: { mode?: ReadMode; de const READ_MODE_HEADER = 'x-cms-read-mode' ``` -Builds the access context for one request: `accessContext({ session: await resolveSession(request), mode })` from [`@tanstack/cms-core/server`](./cms-core-server#access-contexts). `mode` is `options.mode`, else the `x-cms-read-mode` header, else `options.defaultMode` (`edit`). Every HTTP handler builds its context this way. Use it in hosts other than TanStack Start, and pass the result as `ctx.access` or to `cmsAs`. An `edit` request context is the widest the caller may read. The public read operations (`get`, `list`, and the older `getPublicDocument` and `listPublishedDocuments`) serve drafts only to callers who may read them, and a `live` header narrows them to published documents. +Builds the access context for one request: `accessContext({ session: await resolveSession(request), mode })` from [`@tanstack/cms-core/server`](./cms-core-server#access-contexts). `mode` is `options.mode`, else the `x-cms-read-mode` header, else `options.defaultMode` (`edit`). Every HTTP handler builds its context this way. Use it in hosts other than TanStack Start, and pass the result as `ctx.access` or to `cmsAs`. An `edit` request context is the widest the caller may read. The public read operations (`get`, `list`, and the deprecated `getPublicDocument`) serve drafts only to callers who may read them, and a `live` header narrows them to published documents. `agentActorName(surface, session?)` names the agent actor for a surface (`mcp`, `webmcp`, `content-agent`). It appends the session's `x-cms-agent` name, as in `mcp:claude`. @@ -173,20 +173,18 @@ function Blog() { | `getDocument` | GET | `content.read` | | `get` | GET | public | | `list` | GET | public | -| `getPublicDocument` | GET | public | -| `listPublishedDocuments` | GET | public | +| `getPublicDocument` | GET | public (deprecated, removed in the next alpha: `get`) | | `resolveRedirect` | GET | public | | `getDocEditorMeta` | GET | `content.read` | | `restoreDocRevision` | POST | `content.publish` | -| `saveDoc` | POST | `content.write` | -| `createDoc` | POST | `content.write` | +| `save` | POST | `content.write` | +| `act` | POST | `content.read` | | `discardDraft` | POST | `content.write` | | `deleteDoc` | POST | `content.delete` | | `bulkDocuments` | POST | `content.write` | | `reviewSnapshot` | GET | `content.read` | | `approveChange` | POST | `review.decide` | | `rejectChange` | POST | `review.decide` | -| `actOnChange` | POST | `content.read` | | `proposeEdit` | POST | `agent.use` | | `agentChat` | POST | `agent.use` | | `editPageBlocks` | POST | `agent.use` | diff --git a/docs/api/cms-client.md b/docs/api/cms-client.md index 44aa9af9..e8071e52 100644 --- a/docs/api/cms-client.md +++ b/docs/api/cms-client.md @@ -121,7 +121,7 @@ import { createCmsClient } from '@tanstack/cms-client' const cms = createCmsClient({ baseUrl: 'https://cms.example.com' }) -const found = await cms.op('getPublicDocument', { slugOrId: 'about', preferred: ['page'] }) +const found = await cms.op('get', { collection: 'page', locator: 'about' }) const redirect = await cms.op('resolveRedirect', { path: '/old-about' }) const custom = await cms.call<{ count: number }>('myCustomOp', { tag: 'news' }) console.log(found?.collection, redirect?.to, custom.count) @@ -129,23 +129,20 @@ console.log(found?.collection, redirect?.to, custom.count) ### `collection(name)` -Typed helpers for one collection, wrapping the older document operations. Its `list` and `get` are the admin editor's reads, and `save` and `create` the deprecated `saveDoc` and `createDoc`; for content, use the client's `get`, `list` and `save`: +Typed helpers for the admin editor's document operations on one collection. For content, use the client's `get`, `list` and `save`: | Method | Operation | Access | Returns | | --- | --- | --- | --- | -| `published(options?)` | `listPublishedDocuments` | public | `{ items: [{ id, doc }], total, nextCursor? }`. Options: `where`, `sort`, `limit`, `offset`, `cursor`. | | `list(options?)` | `listDocumentSummaries` | `content.read` | `{ items: DocSummary[], total }`. Options: `search`, `status`, `locale`, `ids`, `sort`, `limit`, `offset`, `columns`. | | `get(id)` | `getDocument` | `content.read` | The latest version, including any staged change or draft, or `null`. | -| `save(id, doc, options?)` | `saveDoc` | `content.write` | `{ ok, staged, draft?, pendingId?, doc }`. Options: `expectedRevision`, `publish`. | -| `create(id, doc?)` | `createDoc` | `content.write` | As `save`. Fails with `CONFLICT` when the id exists. | | `delete(id, options?)` | `deleteDoc` | `content.delete` | `{ ok }`. Option: `force`. | | `discardDraft(id)` | `discardDraft` | `content.write` + publish rights | `{ ok }` | `collection(name).get()` is an editing read and needs `content.read`. Anonymous readers use the client's `get` and `list`. -Saving follows the [workflow rules](./cms-core-server#workflow-drafts-review-queue-revisions-scheduling): changes to a published document are a draft until saved with `publish: true`, and callers without publish rights have their changes staged for review (`staged: true`). +Saving follows the [workflow rules](./cms-core-server#workflow-drafts-review-queue-revisions-scheduling): changes to a published document are a draft until saved with `publish: true`, and callers without publish rights have their changes staged for review (`state.changeSet.source` is `'review'`). -`save()` and `saveDoc` merge partial document fields into the current document (or its existing human draft); omitted fields keep their values. Supply an explicit empty value to clear a field. Access predicates use the stored document, and hidden/unwritable fields remain protected. Pass the revision you last loaded as `expectedRevision` to detect stale edits. +`save()` merges partial document fields into the current document (or its existing human draft); omitted fields keep their values. Supply an explicit empty value to clear a field. Access predicates use the stored document, and hidden/unwritable fields remain protected. Pass the revision you last loaded as `expectedRevision` to detect stale edits. ```ts validate=type import { CmsApiError, createCmsClient } from '@tanstack/cms-client' @@ -154,11 +151,16 @@ const cms = createCmsClient({ baseUrl: 'https://cms.example.com', getAuthHeader: () => `Bearer ${process.env.CMS_API_KEY}`, }) -const posts = cms.collection('post') try { - const result = await posts.save('hello-world', { title: 'Hello, world' }, { publish: true, expectedRevision: 3 }) - console.log(result.staged ? 'Sent for review' : 'Published') + const result = await cms.save({ + collection: 'post', + id: 'hello-world', + doc: { title: 'Hello, world' }, + publish: true, + expectedRevision: 3, + }) + console.log(result.state.changeSet?.source === 'review' ? 'Sent for review' : 'Published') } catch (e) { if (e instanceof CmsApiError && e.code === 'CONFLICT') console.log('Someone else saved first') else throw e @@ -197,7 +199,7 @@ Every non-2xx response throws a `CmsApiError` built from the [error envelope](./ - **API keys**: admins create keys on the admin Settings page (or with the `createApiKey` operation). Return `Bearer tscms_…` from `getAuthHeader`. Keep keys on the server; don't ship them in browser bundles. - **Same-origin browser apps** with a cookie session need no header: the browser sends the cookie with same-origin requests. Pass a custom `fetch` to change credentials behavior, for example `fetch: (input, init) => fetch(input, { ...init, credentials: 'include' })` for a cross-origin API whose origin is listed in `security.allowedOrigins`. -- **Anonymous** callers can run the public operations (`published()`, `getPublicDocument`, `resolveRedirect`, `getAuthSession`). +- **Anonymous** callers can run the public operations (`get`, `list`, `resolveRedirect`, `getAuthSession`). `getAuthHeader` runs before every request, so it can return a rotating token. @@ -221,7 +223,7 @@ declare module '@tanstack/cms-core' { } ``` -Then `cms.collection('post')` only accepts registered collection names, and `published()`, `get()`, and `save()` use the post's document type. Without a registration, any collection name is accepted and documents are untyped. A client in a separate project can import the config's type from a shared package, or use `RegisteredDoc<'post'>` from `@tanstack/cms-core` once the registration is visible. +Then `get`, `list`, `save` and `cms.collection('post')` only accept registered collection names, and use the post's document type. Without a registration, any collection name is accepted and documents are untyped. A client in a separate project can import the config's type from a shared package, or use `RegisteredDoc<'post'>` from `@tanstack/cms-core` once the registration is visible. Non-JavaScript clients can generate bindings from the OpenAPI document at `GET /api/cms/v1/openapi.json`. @@ -305,9 +307,9 @@ Opens a browser `EventSource` against `/api/cms/v1/events?collection=