Studio implementation handoff
Where to implement drafts as overlays, saves without GitHub, immutable delivery and fast rollback in Studio, with contracts and acceptance scenarios.
This is the engineering handoff for the hosted site editor, written so implementation does not depend on the original discussion. It extends Studio's existing Fast Preview rather than introducing a second editing backend. The contracts below are its implementation defaults.
Read Content protocol, Keeping drafts current and Production delivery and rollback for the shared semantics. This page maps those decisions onto Studio, supplies operation sequences, and names the checks that demonstrate completion.
Decisions to preserve
- Business users work with drafts. A draft is the blocks an editor changed, kept in Deco's storage; there are no draft branches, and creating branches or rebasing is never an editor task.
- Successful autosave means a durable draft write. A save writes the whole blocks the editor changed into the draft and never calls GitHub, so a GitHub outage can't fail a save, and cannot prevent serving an already prepared release.
- The editor's forms show the production branch, read through the GitHub API when the editor opens and in its background check (never in a save), with the draft on top. The preview renders the same draft over the latest release. A draft never records a base of its own. At Publish, any block the draft changed wins in full; there is no property merge.
- Each saved block carries a precondition checked against the draft alone: "not in the draft yet" for a block the draft doesn't hold, else the draft's version the form loaded (a deletion the draft holds has a version too). A mismatch writes nothing and opens the editor's existing reconcile view from the draft's copy the refusal carries: values only one side changed merge on their own, the rest are asked value by value (per whole block for A/B tests and campaigns), and a block one side deleted gets one plain question. Never a dead-end message. An editor never conflicts with their own saves: the version after each save comes from that save's answer.
- Studio validates no content: not on save, not in the browser, not at Publish. The only content check is
deco checkin the site's CI. - Production and versioned preview delivery read only prepared object-store assets. Neither a cache miss nor recovery contacts GitHub, Studio's editing API or its database.
- A draft asset is an immutable overlay of changed blocks and tombstones, with no base revision. Preview uses its server's existing production content, captured once per client; publish still builds a complete snapshot.
- A release asset is immutable. A channel manifest selects the current release. Rollback increases the channel generation while selecting an older revision; it does not decrease the generation or require a build.
- Editing, publication and preparation are TypeScript control-plane work. The data plane is object storage/CDN with a minimal authorization layer when needed, independently deployable from Studio.
- The portable protocol has seven methods: since
deco-content1.1 (@decocms/blocks8.2.0),changes.list,changes.getandchanges.discardcompare a source with its base, which for a draft is the production branch. Since 1.2 (@decocms/blocks8.8.0) the hosted storage is an overlay: it implementswriteSnapshot()(the draft's own blocks, no GitHub), soblocks.applychecksifMatchagainst the draft alone, andchanges.listis the draft's own blocks. Draft lifecycle, publication, rollback and preview grants are separate Studio routes.
Existing Studio integration points
These are relative paths in the public Studio repository, not paths to add to Blocks. Recheck their current interfaces before implementation; the responsibilities below are the stable part of the map.
| Existing module | Reuse | Change or extend |
|---|---|---|
apps/api/src/api/routes/decofile.ts | Organization/project authorization and the /rpc route | For a request that only holds blocks.apply, gate on the cached v8 marker and never read the production branch. Add the publish review route |
apps/api/src/hosted/draft-content-storage.ts | The protocol storage for a hosted draft; the layered read (production branch from GitHub, draft on top) for blocks.list, schema.get and changes.* | Add writeSnapshot(): the draft's own files, no GitHub. In commit(), no schema, no production-branch reads, no dropping blocks equal to production: a put sets the whole block, a delete records a tombstone. changes() lists the draft's own names. No readSecretsPublicKey |
apps/api/src/hosted/draft-store.ts | Conditional (If-Match) draft writes and slugs | Unchanged: re-read and re-apply on a failed condition, so saves of different blocks are both kept |
apps/api/src/hosted/release-objects.ts | Release object reads and writes | The latest release's commit, for the publish review |
apps/api/src/hosted/publish.ts | Committing the draft's whole blocks on the production branch's head | When the branch moves meanwhile, rebuild on the new head (bounded) instead of failing. Report the blocks a developer also changed; never block on them |
apps/web/src/components/sections-editor/form-conflict-dialog.tsx | The reconcile view: theirs and yours, per field | Open it for every conflict of a save, a delete or a move, A/B tests and campaigns included (whole-block choice there) |
apps/api/src/api/routes/github-webhook.ts | Existing signed GitHub event intake | Durably enqueue push processing, deduplicate deliveries, trigger release preparation |
apps/web/src/components/sections-editor/content-sync.ts | Save queue | End "saving" when the hosted write is confirmed; update the list of changes from the save's answer and refresh the preview outside the queue |
Mount organization routes through Studio's existing org-scoped middleware and emit updates through its existing SSE delivery. Reuse durable workflow infrastructure for jobs and database-backed coordination. An in-process mutex or workflow-local map is not cross-replica serialization; the draft's conditional write is what serializes saves. Keep GitHub rate-limit handling and bounded fetch utilities for publishing.
The protocol now lives under @decocms/blocks/protocol, with shared keys, server, filesystem storage and conformance subpaths. The hosted storage adapter belongs in Studio; the SDK must not import the editing protocol at runtime.
Persisted state
Store these records through Studio's existing storage adapters and migrations. IDs are opaque; repository, organization and app-root scope are checked on every access. A repository can host several sites.
| Record | Minimum persisted fields |
|---|---|
| Draft | id, organization/project/site IDs, app root, draft object key, lifecycle state, last editor activity, latest preview overlay version. No base commit: the editor lays it over the production branch, the preview over the latest release |
| Repository observation | repo/ref scope, latest reconciled head, observed time; webhook delivery IDs recorded separately for deduplication |
| Release | site ID, source repo/app root/commit, content revision, format, asset key, byte size and integrity digest, preparation state and timestamps |
| Channel | site/environment, monotonic generation, revision, automatic or held mode, desired manifest, last confirmed manifest generation |
| Promotion operation | request key and digest, expected generation, source intent, target revision, durable result and storage-write recovery state |
| Audit event | actor, operation, before/after identifiers, blocks kept over a developer's change, timestamp; no tokens |
Draft lifecycle is open → published or open → discarded. Release preparation is queued → preparing → ready or failed. A channel promotes only ready assets.
Commit SHA, per-block content hash, draft etag, content revision and channel generation are different identifiers. Never use a commit SHA as publication order, or an asset revision as authorization.
Hosted operation contracts
These routes are the Studio surface under /api/:org/sites/:siteId. Keep project/root authorization explicit. Use the existing protocol errors for protocol calls; lifecycle routes return ordinary HTTP errors and typed bodies.
| Operation | Request | Result |
|---|---|---|
POST /drafts | request key, optional display name | Stable draft ID; reuse the default open draft where appropriate |
GET /drafts/:id | editor session | Lifecycle state, the latest release its preview is laid over, preview readiness |
POST /drafts/:id/rpc | The seven-method JSON-RPC protocol | Endpoint bound to the draft; describe reports overlay: true |
GET /drafts/:id/publish/review | editor session | The draft's blocks a developer also changed on the production branch since the latest release |
POST /drafts/:id/publish | request key, expected draft etag, expected channel generation | Durable operation ID; states distinguish awaiting checks, Git committed, preparing and promoted; reports the blocks the draft kept over a developer's change |
POST /drafts/:id/discard | request key, expected draft etag | Terminal draft state; coordinated with in-flight saves |
POST /drafts/:id/preview | exact saved draft etag or prepared overlay version | Preparing status, or signed pointer to the exact prepared overlay with expiry |
POST /channels/:channel/rollback | request key, expected generation, retained target revision, reason | New generation and held channel state; no GitHub work in this operation |
POST /channels/:channel/resume | request key, expected generation | Explicitly resume automatic mode and reconcile latest desired production; never resume merely because an event arrived |
GET /operations/:id | editor session | Durable status/result or bounded error with retry timing |
A stale expected draft or generation is a conflict, not a silent overwrite. The managed editor sends ifMatch on every save: null for a block the draft doesn't hold, else the draft's version from changes.list or from its own last save's answer. A block the draft deletes is held: changes.list lists it as a delete with the tombstone version ("tombstone", TOMBSTONE_VERSION), and restoring it sends that version. The draft records a tombstone for every name it deletes, even one main doesn't have, since the save never reads main; the protocol allows that (Overlays). Until Studio depends on a @decocms/blocks release that exports TOMBSTONE_VERSION, its write storage still guards the tombstone at "tombstone", but the delete's answer and changes.list report null for it, so the editor sends "tombstone" for a block it knows the draft deletes.
A block someone else saved meanwhile is a Conflict, and the editor opens the reconcile view with their version and the editor's own, keeping what the editor typed. A block one side deleted gets one question instead: on an edit, "Keep my version" (saved over the deletion with ifMatch: "tombstone") or "Leave it deleted"; on a delete, "Delete anyway" or "Keep their version". Choosing theirs writes nothing more and shows one toast, "Kept their version" or "Left it deleted", in place of the save's success toast.
Event notifications invalidate editor reads; they do not replace durable status or the portable polling fallback. Never log signed preview pointers. The lifecycle response and SSE event report summaries, not the entire content map.
Save sequence
A save reads and writes only the draft object in Deco's storage.
save(draft, params):
authorize (the site's v8 marker is cached; no GitHub call)
read the draft object and its etag
version of a block = content hash of the draft's block; a block the draft deletes is "tombstone"; any other is null
check every ifMatch against those versions; a mismatch is a Conflict
normalize set/delete (set wins); enforce names, shapes and sizes
put each set block in whole; record each delete as a tombstone
write the draft with If-Match: <etag>
on a failed condition: reread and recheck every guard, then reapply, with bounded retries
return the new versions ("tombstone" for each delete, which the draft records whether or not main has the name); enqueue overlay materializationThe save never reads the production branch, the latest release, the schema or GitHub. Its revision combines the last production-branch commit the editor read and the draft's etag, so it moves when either moves. There is no per-draft base pointer, no private snapshot of unreleased commits and no background base move.
Batch/coalescer logic retains each caller's identity and guards. Coalescing cannot cause one failed apply to partially write, or report another caller's unrelated mutation as its own result.
Reads are where GitHub comes in, at open and in the background check only: blocks.list and schema.get read the production branch and lay the draft on top. changes.list is the draft's own blocks; changes.get reads their "before" from the production branch. After a save, the editor updates its list of changes from the save's answer, with the "before" it loaded, instead of reading again.
Publication and materialization sequence
Publication is the only operation that writes to GitHub. It freezes the draft the editor confirmed, reads the production branch's head, and commits the draft's whole blocks and deletions on top of it, content files only. A tombstone of a name main doesn't have changes nothing, and the default commit message names only the deletions main had. If the branch moves before the commit lands, it reads the new head and builds the commit again, a bounded number of times; it never fails because a developer pushed. If another editor saves meanwhile, that later work stays in the draft as unpublished; don't claim it was included in the confirmed publication. Follow branch protection and required checks, using a PR when needed.
Before the editor confirms, the review lists each draft block whose production-branch version differs from the latest release's, the blocks a developer also changed: "Your developer also changed Footer. Publishing keeps your version." It never blocks; the whole draft block wins (see Publish: the whole draft block wins).
Schema compatibility and route diagnostics belong in deco check in CI. Studio adds no content validation: not on save, not in the browser and not at publish. Input syntax, operation limits, authorization and snapshot integrity are still enforced. Successful preparation does not certify compatibility with every deployed build; code-first rollout and selecting a compatible rollback target remain operational requirements.
prepare(site, commit):
pin commit; reuse cached Git trees/blobs where available
stream normalized entries into a canonical snapshot with byte limits
compute revision; upload immutable asset and verify integrity
record ready release and enqueue promotion intent
never update a channel from the ingestion worker itselfWebhook receipt acknowledges only after durable enqueue. Deduplicate by provider delivery ID, and deduplicate preparation by site/app root/commit/format. A slow reconciliation sweep finds missed commits. Use the latest reconciled production head, not webhook arrival order; when several commits arrive, preparing only the newest is acceptable. Studio-initiated commits can enqueue directly, with webhook deduplication handling the later duplicate.
Define canonical content hashing once in Blocks and import it in the CLI and materializer: recursively sorted object keys in JavaScript code-unit order, preserved array order, compact UTF-8 JSON with no trailing newline, and SHA-256 over the canonical blocks map. Emit keys in that order in the serializer rather than relying on object insertion order, particularly for numeric-looking keys; use JSON string escaping and number encoding, including the normalization of negative zero to zero. The format is versioned, and the snapshot envelope's revision is excluded from its own hash. Incremental materialization must produce the same bytes as the reference serializer; ship shared golden fixtures before allowing promotion. Reject values JSON cannot represent. Protocol request digests use a separate domain prefix and canonical request body.
Release preparation, channel operations and rollback run in an independently deployed release-control service with its own durable state and credentials. The logical API namespace above may be routed to several services; rollback must not depend on the editing API being available. The delivery gateway remains read-only.
Use configured R2 storage and CDN as the initial deployment target; keep the asset contract portable. The control plane writes assets. The delivery gateway has only read access and locally verifies scoped credentials using deployed verification keys. It does not query Studio's database per request. Token rotation/revocation must have a documented bounded propagation policy; if revocation state is consulted, serve that state from the isolated storage plane too. Private caching always happens behind authorization and is scoped to site and format/revision.
Draft overlay preparation
The draft object already is an overlay: whole replacement entries for the blocks the editor saved, and tombstones for deletions. It records no base of its own; nothing is sent as a baseRevision or imposed on the servers that render drafts, which lay it over the latest release. Normalize filename aliases using the shared key rule. A block saved back to its released content stays in the overlay: the draft is what the editor saved.
Use the write bodies from autosave and their content hashes to update the overlay. Never crawl repository contents or rebuild a whole draft decofile merely to serve preview.
Upload new changed-block assets first. Then upload the complete immutable overlay manifest, whose set references block hashes and whose delete enumerates cumulative deletions. Reuse unchanged blob assets across saves. The grant authorizes this manifest and its referenced blobs. Enforce ordinary persistence guards before asset creation. The schema and blocks.list editor contract still describe the effective editable content; the overlay is a delivery optimization, not a replacement for that protocol shape.
At request time, capture the server's existing normal production snapshot, then fetch the overlay and only missing changed blobs. Build a read-through immutable view for lookup and enumeration. No production revision is downloaded or refreshed just to satisfy a draft. Bound caches of blobs, overlays and composed views; composed-view keys include the local production revision and overlay version. References and deletion handling use that same view for every resolve in the client. For non-HTTP consumers the client lifetime has the same capture rule.
Keep publication separate: it commits the draft on top of repository production and prepares a full release. A preview is not a promise that its inherited blocks match the later publication, especially during rollback holds when delivered content differs from Git.
Promotion, rollback and recovery
Use a durable per-channel lane with expected generations and stored desired manifests. It owns the only credential allowed to write channel objects. Preparation workers cannot promote directly. Every deliberate publish/resume/rollback gets a new ordered intent; superseded preparation may finish and retain its asset but cannot promote.
For an immutable ready target, store the next generation and desired manifest durably, then write the channel object and confirm it. The data plane considers the object authoritative. A lost storage-write response is reconciled by rereading the stored manifest. A retry of the same operation returns the same generation, rather than allocating another.
Only one writer may perform channel writes at a time. A database lease alone cannot fence an expired worker's outstanding object-store upload. For the initial R2 deployment, use a small promotion Worker with the R2 binding: put with onlyIf: { etagMatches: observedEtag } fences updates against the stored manifest; a failed condition returns null. Bootstrap with a conditional create, not an unconditional upload. R2 conditional operations document these primitives. Test them against the live provider as well as local emulation. A different provider adapter must supply equivalent conditional writes; do not ship a check-then-unconditional-put sequence. Stop promotion on an unresolved write instead of allowing two writers to race.
Rollback uses this same lane with a retained ready target and sets mode to held. Recovery, webhook replay and periodic reconciliation must respect the hold. Explicit resume creates a new intent against the latest production observation. Record the delivery/Git mismatch and offer a separate Git revert; GitHub downtime does not block rollback.
The SDK retains the greatest observed channel generation, discards stale asynchronous fetch completions, and accepts an older revision selected by a newer generation. In-flight page clients keep their original snapshot. Emit the cache-invalidation callback on generation changes even when content hashes repeat. Never substitute newer draft changes for an immutable overlay version. Apply it to the production captured by this client, after the release check a draft read makes first (it waits for that check, so the base is the latest release); do not fetch or await a base matching the overlay.
Initial defaults
Keep these values in versioned configuration; the protocol's own limits are fixed by @decocms/blocks and not advertised. They are starting defaults for implementation and load testing, not a guarantee that raw JSON byte size equals heap usage. Changing a public limit requires updating this table and its acceptance tests.
| Setting | Initial default |
|---|---|
| Production branch reads | At editor open and in the background check only, never in a save; the listing is cached per head commit |
| Preparation worker memory / accumulated read budget | 512 MiB container; 32 MiB input bytes per attempt, then checkpoint and yield; monitor actual heap and RSS |
| Protocol writes | 500 names, 1 MiB per entry, 8 MiB per request, 10 calls per batch |
| Schema / block-list / aggregate batch response | 16 MiB / 16 MiB / 32 MiB uncompressed; error instead of truncation |
| Prepared production snapshot | 8 MiB canonical block-map bytes; oversized historical sites need an explicit profiled tier before onboarding |
| Publish head-race retries | 3 attempts, jittered backoff; rate-limit responses wait for provider retry timing |
| Draft conditional-write retries | 3 attempts, jittered backoff; then Unavailable with retry timing |
| Editor activity heartbeat / active window | 30 seconds / 2 minutes |
| Hosted editor conditional fallback poll | 30 seconds and on focus; local protocol remains 2 seconds |
| Repository reconciliation | Every 5 minutes for connected sites; bounded concurrency and provider-budget-aware backoff |
| Channel manifest cache | At most 5 seconds; generation-based ETag, no negative caching |
| Immutable revision cache | 1 year with immutable keys; authorize private access before using shared byte caches |
| SDK release poll | 60 seconds by default (5 seconds minimum, set with interval) with up to 1 second jitter, subject to the existing idle/Worker scheduling |
| Rollback retention | 30 days minimum; always retain live channel targets and explicit pins |
| Draft overlays / changed-blob cache | 8 MiB cumulative changed-block bytes per overlay; bounded cache, at most 3 composed views per site by default; unchanged production objects shared |
| Preview grants / discarded-draft cleanup | 1 hour grants; assets retained beyond every unexpired grant before cleanup |
Track readiness lag, promotion lag, conditional-write retries per save, whole-block draft-win counts at publish, job RSS, publish head retries and held channels. Test the 8 MiB runtime limit with fallback, old/new revisions and concurrent pinned readers on the target hosts before rollout. A parser or serializer can still have high allocation overhead below the byte limit; lower concurrency or limits based on measurements.
The active-server propagation target at these defaults is preparation time plus up to roughly 75 seconds for manifest caching and polling/jitter, followed by any HTML cache delay. Scheduling and outages can extend it. Idle Workers have no elapsed-time guarantee until a request schedules refresh; their first response can serve the bundled fallback. Rollback follows the same rule.
Acceptance scenarios
| Scenario | Required evidence |
|---|---|
| Editor opens a new project and saves | No branch is created; the save is one conditional write to the draft object, with zero GitHub calls and no schema read |
| One editor saves the same block many times | Never a conflict: each save's guard is the version the previous save answered with |
| A developer's push changes the footer while the draft changes the title | The forms show both on the next background check, the preview once the push is released: the footer from production, the title from the draft |
| Both change the same block, including different properties or deletion | The draft's whole block wins at Publish; the publish review names the block, and nothing blocks |
| Production moves while Publish runs | Publish rebuilds on the new head and lands; the review's list still names the blocks kept |
| Two editors save the same block | The second save, guarded with the version its form loaded, is a Conflict; nothing is overwritten, and the reconcile view opens |
| Two editors save different blocks on different replicas at once | The conditional write fails for one; it rereads the draft, rechecks its guards and reapplies, so both blocks are kept |
| An A/B test or a campaign changed meanwhile | The reconcile view opens with a whole-version choice |
| Save response lost, worker restarted | The client rereads changes.list: a save that landed shows its version; nothing is applied twice |
| Block saved back to its production content | It stays in changes.list until it's published or discarded |
| A draft saved before this design | Opens and saves as is; no migration |
| GitHub unavailable | Saving and previews continue for an open editor; opening the editor and the background check wait for GitHub; publishing pauses; prepared production assets and rollback continue serving |
| Webhook duplicated, missed or delivered out of order | Idempotent preparation and reconciliation; older events cannot regress production |
| Asset upload fails or is incomplete | Previous manifest stays live; missing reads never fetch GitHub |
| Old job completes after rollback | Channel remains at the rollback generation in held mode |
| Manifest write succeeds but response is lost | Retry reconciles the same generation; an expired writer cannot overwrite a newer one |
| SDK revision B fetch finishes after rollback to A | The higher-generation A remains selected; in-flight pages may finish on their pinned B |
| Old preview link used after another save | Exact old overlay or draft error, never newer draft changes; inherited content follows local production |
| Local release changes while a draft renders | In-flight client keeps its pair; next client uses the new local release without downloading another full draft |
| Draft deletes a block that exists in production | Tombstone hides it from lookup and listing; absent override without a tombstone inherits production |
| Draft deletes a name main doesn't have | The save records a tombstone without reading main; Publish commits nothing for it and its default message doesn't name it |
| An editor edits a block someone else deleted meanwhile | One question: "Keep my version" saves over the deletion with its tombstone version; "Leave it deleted" writes nothing |
| An editor creates a block under a name the draft deletes | Created over the deletion with its tombstone version; nothing is asked (the create edited nothing that was deleted) |
| An editor moves or deletes a block someone else changed meanwhile | One question: "Delete anyway" writes the whole move or delete over their version; "Keep their version" cancels all of it, so a move never lands as a copy |
| Two servers have different local release revisions | Same overlay intentionally produces different inherited content; composed caches cannot cross those base identities |
| Repeated saves change one previously edited block | Fetch the small manifest and only changed-blob hashes missing from cache, not the full production or draft map |
| Private asset requested without a valid grant | No shared-cache bypass; tenant scope checked before bytes are served |
| Publish confirmed, then another save arrives | Confirmed content publishes; later save remains unpublished |
| GC runs during rollback or preview use | Channel targets, pins, referenced uploads and unexpired grants survive |
| Max-sized snapshot and simultaneous readers | Measured peak memory stays within the runtime budget; preparation cannot OOM the API |
Run portable protocol conformance against the filesystem and GitHub adapters. Add focused integration tests for provider head races, durable recovery and object-store fencing, and E2E tests extending Fast Preview's existing Git-sync and decofile suites. Include SDK generation/cache tests; a happy-path editor demo alone does not establish these guarantees.
Rollout order
- Ship the shared protocol subpaths and golden hashing fixtures.
- Make the hosted draft storage an overlay (
writeSnapshot()): saves write whole blocks into the draft with conditional writes only, guarded against the draft, and stop calling GitHub. Version every block by its content hash. The forms keep reading the production branch at open and in the background check. Existing drafts keep working with no migration. - Show "Saved" when the write is confirmed, update the list of changes from the save's answer, refresh the preview in the background, and route every save conflict to the reconcile view.
- Add the publish review (the blocks a developer also changed) and commit the whole draft blocks on top of the production branch's head, rebuilding when the head moves.
- Add complete production snapshot and draft-overlay materialization and a shadow delivery channel. Compare outputs with current control-plane reads without changing production traffic.
- Enable the isolated data plane for selected sites after cold-read, outage and memory tests. Keep the bundled last-good fallback; no data-plane GitHub fallback is allowed during rollout.
- Enable channel promotion, rollback/hold/resume and retention after race/recovery tests pass. Make save, preview-ready, Git-committed and promoted status visible in the editor.
Track these phases in the Studio and Deco API roadmap. Implementation is complete when the acceptance scenarios pass, a save makes no GitHub call, the deployed data plane cannot access GitHub, and operators can restore a retained release while GitHub and Studio's editing API are unavailable.