Логотип Architecture Crdts

Architecture Crdts

Спільнота
j4flmao
architecture-crdts

Use this skill when the user says 'CRDT', 'real-time collaboration', 'collaborative editing', 'Yjs', 'Automerge', 'local-first', 'offline sync with merge', 'conflict-free merge', 'operational transformation vs CRDT'. Designs replicated data that merges without coordination: choosing CRDT types, library (Yjs, Automerge, Loro), sync and persistence architecture, and handling tombstones, schema evolution, and authorization. Do NOT use for: server-authoritative consistency/consensus (system-design distributed-consensus), mobile offline caching without concurrent edits (mobile/universal/offline-first), or event sourcing (backend/universal/event-sourcing).

Огляд

Видавецьj4flmao
Репозиторійagent-skills
Назва навичкиarchitecture-crdts
Зірки
41
Форки
6
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: j4flmao. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Architecture Crdts у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/crdts
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/architecture/crdts .claude/skills/architecture-crdts
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Architecture Crdts в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Architecture Crdts, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Architecture Crdts не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Conflict-free Replicated Data Types (CRDTs)

Purpose

CRDTs let replicas accept writes independently (offline, peer-to-peer, multi-region) and still converge to the same state once they have seen the same updates, with no central lock or transform server. They trade some storage and semantic control for availability and simple sync. Use proven libraries; design the document model, sync transport, persistence, and access control around them.

Agent Protocol

Trigger

"CRDT", "collaborative editor", "multiplayer editing", "Yjs", "Automerge", "Loro", "local-first", "offline merge", "OT vs CRDT", "conflict resolution without server".

Input Context

  • Data shape (text, rich text, lists, maps, counters, trees/canvas).
  • Concurrency: number of simultaneous editors, offline duration.
  • Topology: client-server relay, peer-to-peer, multi-region servers.
  • Auth model and audit/history requirements.

Output Artifact

CRDT design: per-field type, library choice, sync/persistence architecture, compaction and auth plan.

Response Format

Document model: {field: CRDT type}
Library: {Yjs|Automerge|Loro}  Transport: {WebSocket relay|WebRTC|HTTP sync}
Persistence: {updates log + snapshots}  Compaction: {policy}
Auth: {room-level|server-validated updates}
Semantics caveats: {e.g. LWW on title, interleaving}

Completion Criteria

  • Each field's merge semantics stated (what happens on concurrent edits).
  • Server validates who may write which document.
  • Persistence keeps update log + periodic snapshots; growth bounded.
  • Convergence tested with randomized concurrent operations.

Two Families

FamilyReplicas exchangeRequirement on merge/delivery
State-based (CvRDT)Whole state (or deltas)Merge is commutative, associative, idempotent (a join-semilattice); any delivery order, duplicates OK
Operation-based (CmRDT)OperationsConcurrent ops commute; delivery exactly-once and causally ordered (usually provided by the library's sync protocol)

Delta-state CRDTs ship only the changed part of the state; Yjs and Automerge use compact update encodings with state vectors/heads so peers send only what the other side lacks.

Common Types

TypeMerge ruleCaveat
G-CounterPer-replica counts, merge = elementwise max, value = sumIncrement only
PN-CounterTwo G-Counters (inc, dec)Can go negative
LWW-RegisterHighest (timestamp, replica id) winsNeeds good clocks (hybrid logical clocks); silently drops one write
MV-RegisterKeep all concurrent valuesApp must resolve
OR-Set (add-wins)Adds tagged uniquely; remove deletes observed tagsMetadata grows
Sequence (RGA, YATA, Fugue)Elements get unique ids ordered relative to neighboursTombstones; concurrent inserts must not interleave badly
JSON/map CRDTNested maps/lists of the aboveConcurrent move/reparent is hard (tree CRDTs)
typescript
// G-Counter: the canonical state-based CRDT
type GCounter = Record<string, number>;

export const increment = (c: GCounter, replica: string, by = 1): GCounter => {
  if (by < 0) throw new RangeError(`G-Counter cannot decrement (replica=${replica}, by=${by})`);
  return { ...c, [replica]: (c[replica] ?? 0) + by };
};

export const merge = (a: GCounter, b: GCounter): GCounter => {
  const out: GCounter = { ...a };
  for (const [r, n] of Object.entries(b)) out[r] = Math.max(out[r] ?? 0, n);
  return out;
};

export const value = (c: GCounter): number => Object.values(c).reduce((s, n) => s + n, 0);

CRDT vs Operational Transformation

OTCRDT
CoordinationCentral server orders and transforms opsNone required
Offline / P2PPoorNative
MetadataSmallIds/tombstones per element (modern libs compress heavily)
Intent controlServer can enforceMerge rule is fixed by type
ExamplesGoogle Docs (historically), ShareDBYjs, Automerge, Loro

If you already have a single authoritative server and no offline requirement, server-ordered ops (OT or simple last-write with versioning) can be simpler.

Library Usage

Yjs (shared types + y-websocket relay):

typescript
import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import { IndexeddbPersistence } from "y-indexeddb";

const doc = new Y.Doc();
new IndexeddbPersistence("doc-42", doc);                       // offline cache
const provider = new WebsocketProvider("wss://sync.example.com", "doc-42", doc);

const text = doc.getText("body");
const meta = doc.getMap("meta");
doc.transact(() => {                                            // one update event
  text.insert(0, "Hello");
  meta.set("title", "Draft");                                   // map keys: last-writer-wins
});
provider.awareness.setLocalStateField("user", { name: "Ana" }); // presence, not persisted

// Server-side or tests: exchange binary updates
const update = Y.encodeStateAsUpdate(doc);
const replica = new Y.Doc();
Y.applyUpdate(replica, update);

Automerge (JSON-like documents, full history):

typescript
import * as A from "@automerge/automerge";

let a = A.from({ tasks: [] as { title: string; done: boolean }[], votes: new A.Counter(0) });
let b = A.clone(a);
a = A.change(a, d => { d.tasks.push({ title: "Write spec", done: false }); });
b = A.change(b, d => { d.votes.increment(1); });
const merged = A.merge(a, b);   // contains both changes

For networking and storage, Automerge Repo (@automerge/automerge-repo) provides sync adapters.

Architecture

  • The server is a relay plus persistence, but it is still the place for authorization: check the user may write the room before accepting updates; validate update size and rate.
  • Persist incremental updates; periodically merge them into a snapshot (Y.encodeStateAsUpdate) and truncate the log.
  • Project CRDT state into ordinary tables for search, reporting, and server-side business rules.

Pitfalls

  • Valid merge ≠ valid business state: two users each book the last seat; both merges are "correct". Invariants needing exclusivity (uniqueness, balances) need a server-side authority or reservation.
  • Tombstone growth: deleted text still has metadata; enable garbage collection (Yjs gc: true, default) unless you need full history, and snapshot.
  • Clock skew in LWW: use hybrid logical clocks, never raw wall clocks alone.
  • Schema evolution: field renames are new fields; write migrations that copy data inside a change, version the document schema.
  • Undo: must be per-user (Y.UndoManager with tracked origins), not global.
  • Large docs: split into sub-documents (one per page/board) to bound load time.

Checklist

  • Field-by-field CRDT type and concurrent-edit semantics documented.
  • Library chosen; no hand-rolled sequence CRDT.
  • Relay authorizes per document; rate and size limits.
  • Update log + snapshot compaction; GC policy.
  • Business invariants needing exclusivity handled server-side.
  • Property-based tests: random concurrent ops on N replicas converge.
  • Presence/awareness kept out of persisted state.

References

  • Shapiro et al., "Conflict-free Replicated Data Types" (SSS 2011).
  • Kleppmann et al., "Local-first software" (Onward! 2019).
  • Nicolaescu et al., YATA (GROUP 2016); Weidner & Kleppmann, "The Art of the Fugue" (2023).
  • Yjs docs (shared types, providers, awareness); Automerge docs.

Поширені запитання

Що робить навичка ШІ Architecture Crdts?

Use this skill when the user says 'CRDT', 'real-time collaboration', 'collaborative editing', 'Yjs', 'Automerge', 'local-first', 'offline sync with merge', 'conflict-free merge', 'operational transformation vs CRDT'. Designs replicated data that merges without coordination: choosing CRDT types, library (Yjs, Automerge, Loro), sync and persistence architecture, and handling tombstones, schema evolution, and authorization. Do NOT use for: server-authoritative consistency/consensus (system-design distributed-consensus), mobile offline caching without concurrent edits (mobile/universal/offline-...

Навіщо використовувати Architecture Crdts у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Architecture Crdts — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Architecture Crdts у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/crdts. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Architecture Crdts?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Architecture Crdts?

Зі скількома забажаєте. У TypingMind ви можете використовувати Architecture Crdts із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Architecture Crdts?

Так. На GitHub цю навичку публікує j4flmao за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇