Assists with Yjs patterns, shared types, and conflict resolution for building collaborative applications.

Install

mkdir -p .claude/skills/yjs && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/2298" && unzip -o skill.zip -d .claude/skills/yjs && rm skill.zip

Installs to .claude/skills/yjs

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Yjs CRDT patterns, shared types (Y.Map, Y.Array, Y.Text), transactions, y-protocols sync and awareness, y-indexeddb persistence, conflict resolution, and document storage. Use when mentioning Yjs, Y.Doc, CRDTs, collaborative editing, real-time sync, awareness, IndexeddbPersistence, or Yjs providers.
300 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • Configures shared data models using Y.Map and Y.Array
  • Implements fractional indexing for reordering logic
  • Encapsulates persistence strategies via indexedDB
  • Enforces state-vector sync for data consistency

How it works

It applies CRDT principles to structure collaborative state and manages transaction propagation to ensure document consistency across distributed clients.

Inputs & outputs

You give it
Data structure requirement and sync constraints
You get back
Yjs shared type configuration and logic

When to use yjs

  • Setting up shared data structures
  • Handling conflict resolution
  • Implementing real-time synchronization
  • Optimizing Yjs document storage

About this skill

Yjs 14 CRDT Patterns

Reference Repositories

  • Yjs: CRDT framework for shared editing and offline-first data
  • Yjs Protocols: algorithmic grounding for sync and awareness

Upstream Grounding

When conflict semantics, transaction origins, shared-type behavior, update encoding, storage growth, or shared-type APIs affect correctness, use source-backed grounding before relying on memory. If DeepWiki MCP is available, ask a narrow question against yjs/yjs; for sync and awareness algorithms, ask against yjs/y-protocols. If DeepWiki is unavailable or the repo is not indexed, use upstream source or official docs directly. Treat DeepWiki as orientation, then verify decisive details against the locally pinned @y/y types and source before changing code.

Epicenter targets @y/y 14 only. Do not add yjs 13, y-indexeddb, a compatibility reader, a package alias, a dual wire, or a fallback. Existing Yjs 13 code is replacement material, not a compatibility surface.

Skip DeepWiki for stable basics and repo-local patterns already documented below.

Related Skills: See workspace-api for the workspace abstraction built on Yjs.

Transactions, Origins, And Undo

  • Yjs updates are commutative and idempotent. Custom sync and persistence layers should use state vectors instead of inventing ordering guarantees.
  • Use Y.encodeStateVector(doc) to describe local clocks, then Y.encodeStateAsUpdateV2(doc, remoteStateVector) to send only missing updates.
  • Persist and transmit bytes from the updateV2 event. Replay them with Y.applyUpdateV2(doc, update, origin).
  • Wrap multi-write user actions in doc.transact(() => { ... }, origin). This reduces observer churn and gives persistence, providers, and undo logic a useful origin.
  • Treat transaction origins as the boundary for filtering provider echoes, app-authored operations, and undo tracking.
  • Scope Y.UndoManager to concrete shared types. Set trackedOrigins, tune captureTimeout, and call stopCapturing() between logically separate commands.
  • Use relative positions for collaborative cursor and selection anchors. Raw numeric indexes drift under remote edits.
  • Y.snapshot() is a historical marker that depends on retained delete history. Y.encodeStateAsUpdateV2(doc) is the self-contained checkpoint format.
  • Prefer separate top-level docs over Yjs subdocuments unless Epicenter owns the whole provider lifecycle for the subdoc path.

Row Document Connection

  • Yjs is network-agnostic. It supplies CRDT state, state vectors, updates, and awareness behavior, not Epicenter's connection topology, authorization, row lifecycle, or durability contract.
  • Each currently open row document uses one authenticated WebSocket at /api/workspaces/:workspaceId/tables/:table/rows/:rowId/document. Do not create an arbitrary room id or a mutable multiplex subscription set.
  • Authenticate the bearer into a principal. The account authority derives deterministically from that principal alone (ADR-0092: the principal is the partition and the actor); the route workspace id is a name inside the requester's own partition. There is no catalog, grant, or authority key.
  • The structured (workspaceId, table, rowId) route address selects one lifecycle-bound document inside the account authority. The address is a name, not a secret or capability. Check row liveness atomically with committed-state load on admission and again on every persisted update.
  • Select the exact epicenter-document-v3 WebSocket subprotocol. Binary messages carry only sync-request(stateVector), sync-response(updateV2), and update(updateV2). Both peers request missing state. Do not add an envelope fact already owned by the route, subprotocol, WebSocket boundary, close code, state vector, or update bytes.
  • There is no terminal document close verdict. The authority enforces the shared compound bound (DOCUMENT_BOUND: canonical encoded bytes and decoded struct count) exactly on the post-candidate state; the client measures the same bound, suppresses every upstream update-bearing frame while over it (including its deferred handshake reply), keeps applying downstream, and resumes automatically when a measure comes back under. Close 1009 is a retryable defensive backstop, never a product state. A row that is not live refuses or closes retryably with no reserved code; the client's scalar plane owns pending-versus-deleted knowledge and revokes the document when a deletion marker installs. Do not encode lifecycle verdicts as Yjs binary frames.
  • On Cloudflare, serialize the socket's complete fixed address within the 16,384 byte hibernation attachment limit and fan out by enumerating the actor's sockets and comparing complete attachment addresses. No tag index until measured socket counts earn one. The server retains no live Y.Doc; hydrate disposable committed state per admission and acceptance.
  • Reconnect with the same structured route and repeat state-vector exchange. Do not add durable subscription recovery or multiplexing until measured open-document socket pressure earns that machinery.
  • Use state-vector exchange followed by incremental updateV2 messages instead of exchanging complete documents by default.
  • Presence is deliberately absent from document v3 until a concrete consumer earns awareness state, disconnect cleanup, and a later protocol major. If added later, awareness is ephemeral and must never be persisted into Y.Doc or the SQLite update log as canonical data.
  • Browser upgrades authenticate through exactly one bearer.<token> subprotocol entry. Non-browser clients may instead use an Authorization header. Do not use cookie-only upgrades, query-string credentials, or post-accept authentication frames.
  • Authentication, deterministic authority resolution, and row liveness are three distinct facts with one surface. Row liveness is a lifecycle invariant, not a second per-row authorization system.

Owner-Side SQLite Persistence

Row documents persist beside scalar facts in the same Data-owned SQLite database. document_updates stores the Yjs 14 update chain at the exact (namespace, table_name, row_id) address. document_publication stores the durable outbound obligation for locally authored document work. The browser Worker owns its OPFS SQLite database, the Bun runtime owns its native database, and the desktop WebView borrows the Bun owner over the Data desktop protocol. Do not add a separate IndexedDB provider or a second document store.

  • createDocumentRuntime owns live Y.Doc handles, durable append and compaction, explicit pull, capture, publication settlement, and revocation.
  • Attach the updateV2 listener before hydration. Replay stored updates with a private hydration origin so loading cannot append the same bytes again.
  • A locally authored append stores copied update bytes and advances document_publication.revision in the same SQLite transaction. Authority-accepted bytes use acceptedDocumentOrigin and create no outbound obligation.
  • Check row liveness inside the append transaction. A late write after scalar deletion must fail rather than resurrect document content.
  • Scalar row deletion removes the update chain and publication obligation in the same replica transaction, then revokes any live handle.
  • Compact a bounded chain by replaying it into a fresh gc: true document and replacing the covered updates with one complete V2 state update. Compaction does not remove modeling costs inside the encoded document.
  • Pull and publication are separate operations. Pulling accepted state never marks it as local work; publishing captures current complete state with the revision it covers and settles only that revision.
  • Treat replay corruption or transaction failure as storage failure. Revoke the live handle rather than allowing memory to diverge from durable SQLite state.

Core Concepts

Shared Types

Yjs provides six shared types. You'll mostly use three:

  • Y.Map - Key-value pairs (like JavaScript Map)
  • Y.Array - Ordered lists (like JavaScript Array)
  • Y.Text - Rich text with formatting

The other three (Y.XmlElement, Y.XmlFragment, Y.XmlText) are for rich text editor integrations.

Client ID

Every Y.Doc gets a random clientID on creation. Raw Yjs conflict ordering can use this id, so concurrent writes to the same raw map key are not "latest timestamp wins" unless the data structure adds its own timestamp policy.

const doc = new Y.Doc();
console.log(doc.clientID); // Random number like 1090160253

From dmonad (Yjs creator):

"The 'winner' is decided by ydoc.clientID of the document (which is a generated number). The higher clientID wins."

Source: GitHub issue #520

The actual comparison in source (updates.js#L357):

return dec2.curr.id.client - dec1.curr.id.client; // Higher clientID wins

This is deterministic (all clients converge to the same state) but not intuitive: a later edit can lose. Design document roots around that fact. Epicenter's scalar tables and KV do not use Yjs or YKeyValueLww; runtime-native SQLite and the scalar row protocol own their convergence semantics.

Shared Types Cannot Move

Once you add a shared type to a document, it can never be moved. "Moving" an item in an array is actually delete + insert. Yjs doesn't know these operations are related.

Critical Patterns

1. Single-Writer Keys (Counters, Votes, Presence)

Problem: Multiple writers updating the same key causes lost writes.

// BAD: Both clients read 5, both write 6, one click lost
function increment(ymap) {
	const count = ymap.get('count') || 0;
	ymap.set('count', count + 1);
}

Solution: Partition by clientID. Each writer owns their key.

// GOOD: Each client writes to their own 

---

*Content truncated.*

When not to use it

  • When high-latency operations do not require real-time conflict resolution
  • When local-only, single-user state management is sufficient

Prerequisites

yjs

Limitations

  • High memory consumption with large, unoptimized document state
  • Requires explicit handling of provider-specific lifecycle

How it compares

It provides structural guidance for distributed state, avoiding the common pitfalls of manual merge-conflict resolution.

Compared to similar skills

yjs side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
yjs (this skill)22moNo flagsAdvanced
shopify-development126moReviewIntermediate
nuxt196moNo flagsIntermediate
tanstack-query72moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

Search skills

Search the agent skills registry