# Sanity integration

Source: https://pinprompt.veren-technology.com/docs/reference/sanity

Turns content feedback into a **Sanity draft**. A QA tester pins the shipping banner on staging ("still says €30, it's €40"), and the banner's text in a draft of `siteSettings` now reads "Free shipping on orders over €40". An editor opens the draft in Studio, checks it and publishes it. **pinprompt never publishes**: every write goes to `drafts.<id>`, and the client refuses anything else.

Like GitHub, it subscribes to the event log. Turning it off changes nothing else, and agents keep working over MCP with or without it.

## Set it up

You need the **owner** or **developer** role on the project.

1. **Make a token** at https://www.sanity.io/manage → your project → **API → Tokens → Add API token**.
   - Permissions: **Editor** (read and write documents). pinprompt only writes drafts, but Sanity has no "drafts only" role.
   - One token per pinprompt project. When you delete it, deliveries fail with `401` until you paste a new one (Edit → Replace token, then Retry).
2. In pinprompt open **Project → Settings → Integrations → Connect Sanity**. Enter the project id and dataset (pre-filled from the project's CMS settings), paste the token, and add your **Studio URL** (`https://halden.sanity.studio`) so "Open in Studio" links go straight to the document. The token is encrypted with `PINPROMPT_SECRET_KEY` and never shown again.
3. Optional: **page mappings** for pages whose elements don't say which document they come from (below).
4. Optional, recommended: add the note field to the schemas you want feedback on, so Studio shows the notes nicely instead of as an unknown field:

   ```ts
   defineField({
     name: "pinpromptFeedback",
     title: "Feedback from pinprompt",
     type: "array",
     readOnly: true,
     of: [{ type: "object", name: "pinpromptFeedback", fields: [
       { name: "key", type: "string" }, { name: "title", type: "string" }, { name: "field", type: "string" },
       { name: "requested", type: "text" }, { name: "observed", type: "text" }, { name: "applied", type: "boolean" },
       { name: "note", type: "string" }, { name: "url", type: "url" }, { name: "sentAt", type: "datetime" },
     ] }],
   })
   ```

5. Click **Test connection**. It reads the dataset, then asks Sanity to *dry-run* a draft write (`dryRun=true`): the answer proves the token can write drafts, and nothing is created.

## Which document

For each item pinprompt looks, in this order, at:

1. **The pin.** The compiler records `target.cms_ref` when the pinned element carries `data-cms="sanity:siteSettings#shippingBanner.text"` or `data-sanity="siteSettings#shippingBanner.text"`.
2. **The captured DOM.** A `data-sanity` attribute in the element's snippet, in either form: `docId#field.path`, or Sanity visual editing's `id=…;type=…;path=…` (as written by `createDataAttribute`). When several elements carry one, the element marked `data-sanity-edit-target` wins.
3. **Page mappings** from settings, first match wins:
   - `/` → document id `siteSettings`, field `shippingBanner.text`
   - `/faq` → document id `faqPage`
   - `/products/:slug` → type `product` by `:slug`: a parameterised GROQ query `*[_type == $type && slug.current == $slug][0]` finds the product (`slugField` defaults to `slug.current`)
   - `*` matches the rest of a path: `/journal/*`

Ids and field paths that come from a page are untrusted: ids must look like Sanity ids (no `drafts.` / `versions.` prefix), field paths must be plain (`hero.title`, `body[_key=="a1"].children[_key=="s1"].text`), and system fields (`_id`, `_type`, `_rev`, …) are never written. **Only these document types** in settings restricts it further.

## What it writes

The draft is the existing draft if there is one (an editor's unpublished work is kept), otherwise a copy of the published document (`createIfNotExists drafts.<id>`). Then, in one transaction:

| The request | What happens |
|---|---|
| Expected quotes one text (`"Free shipping on orders over €40"`) and the field reads almost the same (most words shared, similar length) | The field is set to the quoted text. Without a field, the one field in the document that reads almost the same; two or more → a note |
| A pair: `"€30" → "€40"`, `Change "Order now" to "Add to bag"`, the title's `€30 → €40`, or a quote in Observed vs one in Expected | The old text is replaced when it occurs **exactly once** (in the field, or across the document's text fields, portable text spans included) |
| The document already says it | Nothing changes in the text |
| Anything else (appears twice, not found, no quoted text, not a text field) | The text is left alone and the draft gets a **note** for an editor |

With **Notes** on (default), the draft also gets an entry in `pinpromptFeedback[]`, keyed by the item (`_key: "fb-1189"`): the title, what was observed and requested, whether it was applied, why not, and a link back to the item. Re-sending replaces that entry, it never adds a second one. With Notes off, an ambiguous request writes nothing at all.

The first patch carries the draft's `ifRevisionID`: if an editor changed the draft in between, Sanity answers `409` and the delivery is retried against the new revision.

Text in quotes is the reporter's text. It only ever lands in a **draft**, which an editor reviews before publishing.

## When

| In pinprompt | In Sanity |
|---|---|
| A content item becomes **Agent ready** (or is created agent ready) and **Automatic** is on | The draft is written. Only clear CMS text goes automatically: the router sent it to the CMS (`routing.destination = cms`), or it is a `content` item, or the pinned element names a document, and it has no source file (a copy item in `CheckoutHint.tsx` is code, not CMS) |
| A person clicks **Send to Sanity** on the item page (owners, developers, PMs: `item.triage`) | The draft is written for any open item, whatever its kind. Sending again updates the same draft |
| The spec is revised (an answer, a merge) while a draft is linked | The draft is updated |
| **Done**, **Won't fix**, **Merged** | Recorded on the item link. Nothing is discarded in Sanity (Won't fix says so on the item, so someone can discard the draft in Studio) |

A **bulk change** is handled per item, but each item is synced once per change from its state after it: merging several items into one with a linked draft refreshes the draft once. Undoing a bulk change never discards a draft.

The integration never moves an item. A content item that the integration put in a draft stays where it is until a person checks the draft and signs off.

On the item: a line in the thread ("Sanity draft updated: shippingBanner.text on siteSettings now reads …" or "Sent to Sanity as a note on the siteSettings draft (“€30” appears 2 times …)"), the **Sanity** row in Properties with the document and an **Open in Studio** link, and an `item.external_linked` event. A send that can't find a document says how to fix it on the item ("Pin an element that has a data-sanity attribute, or add a page mapping").

Each event is delivered at most once per integration (`integration_deliveries`). `5xx`, `429`, `409` and network errors retry with backoff (30s, 1m, 2m, 4m, 8m; 6 attempts). `400`, `401`, `403` and `404` stop at once. Both show on the card with **Retry**. The API host is `https://<projectId>.api.sanity.io` (an override must be a public `https` host in production) and redirects are never followed with the token.

## For developers

- Code: `packages/core/src/integrations/sanity/` (`config.ts` settings and id/path grammar, `resolve.ts` which document, `change.ts` which text change, `client.ts` the HTTP API with the drafts-only guard, `outbound.ts` the event handler, `service.ts` the item page's `sanityForItem` and `sendItemToSanity`).
- Event `item.cms_draft_requested` (`{ key, integrationId, cms: "sanity" }`) is the "Send to Sanity" request.
- Link: `external_links` kind `sanity_draft`, external id `sanity:<project>/<dataset>/<documentId>@<itemId>`, states `applied`, `noted`, `needs_editor`, then `done`, `wont_fix`, `merged`.
- Tests run against a local mock of the Sanity API (`packages/core/test/sanity-mock.ts`), never the real one.

## Not yet

- Internationalised fields (`{ en, de }` objects, document-level i18n) are noted, not patched.
- Portable text is patched only through a unique old → new replacement inside one span; marks spanning several spans become a note.
- Sanity's own Comments and Content Releases aren't used: notes live in an array field, and drafts are plain drafts.
- No backfill on connect: items already agent ready before Sanity was connected need **Send to Sanity**.

## Linking a document by hand, Open in Studio, and the Studio plugin

- **Link** (next to *Send to Sanity* on an item): search the dataset by title or paste an id, pick the document and optionally the field. The pick wins over the pin, the page attribute and the mappings, so *Send to Sanity* writes there. Unlink to fall back.
- **Open in Studio**: the Sanity row on the item links to the document (and field) in Studio once the Studio URL is set, before anything is sent.
- **Studio plugin** (`integrations/sanity-studio`, `sanity-plugin-pinprompt`): Settings → Integrations → Sanity → Studio plugin → *Set up* makes a Studio key (shown once) and shows the config. Each document gets a badge ("2 in pinprompt") and a *pinprompt feedback* action listing the items linked or sent to it. Read-only, from `GET /api/v1/sanity/studio?document=<id>` with `Authorization: Bearer <key>`.
