agentleFS
revealui-studiorevealui-studio/revskills/skills/yjs-collaboration/SKILL.md

yjs-collaboration

Skill2 starsChanged 40 days agoMITView on GitHub

Yjs CRDT collaboration patterns for real-time and offline-first editing. Use when building collaborative documents, shared scratchpads, or multi-user editing. Covers Y.Doc, Y.Map, Y.Array, Y.Text, state encoding, structured patches, server-side document manipulation, and conflict-free merge semantics.

We split this skill into the rules it gives an agent

6 rules. About 0 are common, 0 are distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Always call doc.destroy() after server-side operations to free memory

    line 230
  2. Very specific:

    Use Buffer.from(state) when storing in Postgres bytea columns

    line 231
  3. Very specific:

    Use new Uint8Array(buffer) when reading from Postgres bytea columns

    line 232
  4. Very specific:

    Prefer Y.Text over plain strings for content that may be collaboratively edited

    line 233
  5. Very specific:

    Use Y.Array for ordered lists (append-heavy patterns)

    line 234
  6. Very specific:

    Use Y.Map as the root container for structured documents

    line 235

≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Yjs CRDT Collaboration

Core Concepts

Yjs is a CRDT framework. Multiple peers can edit concurrently and merge without conflicts. Every operation is commutative and idempotent.

import * as Y from 'yjs';

const doc = new Y.Doc();
const root = doc.getMap('root');

Type System

TypeUse CaseAPI
Y.MapKey-value storeset(key, val), get(key), delete(key)
Y.ArrayOrdered listpush([item]), insert(idx, [item]), delete(idx, len)
Y.TextRich/plain textinsert(idx, str), delete(idx, len), toString()

Nested types: Y.Map values can be other shared types.

const root = doc.getMap('root');

// String values
root.set('title', 'My Document');

// Nested Y.Text
const findings = new Y.Text();
findings.insert(0, 'Initial finding...');
root.set('findings', findings);

// Nested Y.Array
const items = new Y.Array();
items.push(['Item 1', 'Item 2']);
root.set('items', items);

State Encoding & Persistence

// Encode full state as a binary update
const state = Y.encodeStateAsUpdate(doc);       // Uint8Array
const vector = Y.encodeStateVector(doc);          // Uint8Array

// Persist to database (Postgres bytea column)
await db.update(documents)
  .set({
    state: Buffer.from(state),
    stateVector: Buffer.from(vector),
  })
  .where(eq(documents.id, docId));

// Restore from database
const doc = new Y.Doc();
Y.applyUpdate(doc, new Uint8Array(storedState));

Server-Side Document Manipulation

For CLI agents or batch processes that cannot use WebSocket:

import * as Y from 'yjs';

function applyStructuredPatch(
  existingState: Uint8Array | null,
  patchType: string,
  path: string,
  content: string,
): { state: Uint8Array; stateVector: Uint8Array } {
  const doc = new Y.Doc();

  if (existingState) {
    Y.applyUpdate(doc, existingState);
  }

  const root = doc.getMap('root');

  switch (patchType) {
    case 'set_key':
      root.set(path, content);
      break;

    case 'append_section': {
      let section = root.get(path);
      if (!(section instanceof Y.Text)) {
        section = new Y.Text();
        root.set(path, section);
      }
      section.insert(section.length, content);
      break;
    }

    case 'append_item': {
      let arr = root.get(path);
      if (!(arr instanceof Y.Array)) {
        arr = new Y.Array();
        root.set(path, arr);
      }
      arr.push([content]);
      break;
    }

    case 'replace_section': {
      const text = new Y.Text();
      text.insert(0, content);
      root.set(path, text);
      break;
    }
  }

  const result = {
    state: Y.encodeStateAsUpdate(doc),
    stateVector: Y.encodeStateVector(doc),
  };

  doc.destroy();
  return result;
}

Reading Document Content

function readDocument(state: Uint8Array): Record<string, unknown> {
  const doc = new Y.Doc();
  Y.applyUpdate(doc, state);
  const root = doc.getMap('root');
  const result: Record<string, unknown> = {};

  for (const [key, value] of root.entries()) {
    if (value instanceof Y.Text) {
      result[key] = value.toString();
    } else if (value instanceof Y.Array) {
      result[key] = value.toArray();
    } else {
      result[key] = value;
    }
  }

  doc.destroy();
  return result;
}

Merging Two Documents

// Two docs edited independently
const doc1 = new Y.Doc();
const doc2 = new Y.Doc();

// ... edits happen on each ...

// Merge: apply each doc's state to the other
const state1 = Y.encodeStateAsUpdate(doc1);
const state2 = Y.encodeStateAsUpdate(doc2);

Y.applyUpdate(doc1, state2); // doc1 now has both edits
Y.applyUpdate(doc2, state1); // doc2 now has both edits
// Both docs are identical after merge

Database Schema

CREATE TABLE yjs_documents (
  id TEXT PRIMARY KEY,
  state BYTEA NOT NULL,
  state_vector BYTEA,
  connected_clients INTEGER NOT NULL DEFAULT 0,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

WebSocket Provider (Real-Time)

For browser agents that need live character-by-character collaboration:

import { WebsocketProvider } from 'y-websocket';

const doc = new Y.Doc();
const provider = new WebsocketProvider(
  'wss://collab.example.com',
  'document-id',
  doc,
);

provider.on('status', ({ status }) => {
  console.log('Connection:', status); // 'connecting' | 'connected' | 'disconnected'
});

Awareness (Presence)

const awareness = provider.awareness;

// Set local state (cursor position, user info)
awareness.setLocalState({
  user: { name: 'Agent A', color: '#ff0000' },
  cursor: { index: 42, length: 0 },
});

// Listen for remote state changes
awareness.on('change', () => {
  const states = awareness.getStates();
  // Map<clientId, { user, cursor }>
});

Best Practices

  • Always call doc.destroy() after server-side operations to free memory
  • Use Buffer.from(state) when storing in Postgres bytea columns
  • Use new Uint8Array(buffer) when reading from Postgres bytea columns
  • Prefer Y.Text over plain strings for content that may be collaboratively edited
  • Use Y.Array for ordered lists (append-heavy patterns)
  • Use Y.Map as the root container for structured documents
  • Server-side patches and WebSocket edits merge cleanly via CRDT semantics

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

Reviews can't be read right now.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.