Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

yjsYJS 命令行

Agent Skill

yjs 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

2,571

周安装

103

GitHub Stars

4,535

下载量

832
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:yjs(YJS 命令行)
来源仓库:https://github.com/epicenterhq/epicenter
仓库路径:skills/yjs
安装命令:
npx skills add https://github.com/epicenterhq/epicenter --skill yjs
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/epicenterhq/epicenter --skill yjs

简介

yjs 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合围绕仓库状态和协作事项进行整理。

  • 适用于需要跟踪代码变更、管理 Issue 或审查 Pull Request 的场景。
  • 可结合项目现有流程,自动提取关键信息并生成报告。
  • 安装命令:npx skills add https://github.com/epicenterhq/epicenter --skill yjs。
  • 建议确认权限范围,避免触发不必要的命令执行或文件读写。

SKILL.md

Yjs CRDT Patterns

Reference Repositories

  • Yjs — CRDT framework for shared editing and offline-first data
Related Skills: See workspace-api for the workspace abstraction built on Yjs.

When to Apply This Skill

Use this pattern when you need to:

  • Design collaborative data models with Y.Map, Y.Array, or Y.Text.
  • Handle conflict-prone updates with single-writer keys or nested maps.
  • Implement drag-and-drop reordering with fractional indexing.
  • Optimize Yjs storage for high-churn key-value workloads.
  • Review boundaries to prevent raw Yjs type leaks into consumer code.

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. This ID is used for conflict resolution—when two clients write to the same key simultaneously, the higher clientID wins, not the later timestamp.

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." — 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 same state) but not intuitive (later edits can lose).

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 key
function increment(ymap) {
	const key = ymap.doc.clientID;
	const count = ymap.get(key) || 0;
	ymap.set(key, count + 1);
}

function getCount(ymap) {
	let sum = 0;
	for (const value of ymap.values()) {
		sum += value;
	}
	return sum;
}

2. Fractional Indexing (Reordering)

Problem: Drag-and-drop reordering with delete+insert causes duplicates and lost updates.

// BAD: "Move" = delete + insert = broken
function move(yarray, from, to) {
	const [item] = yarray.delete(from, 1);
	yarray.insert(to, [item]);
}

Solution: Add an index property. Sort by index. Reordering = updating a property.

// GOOD: Reorder by changing index property
function move(yarray, from, to) {
	const sorted = [...yarray].sort((a, b) => a.get('index') - b.get('index'));
	const item = sorted[from];

	const earlier = from > to;
	const before = sorted[earlier ? to - 1 : to];
	const after = sorted[earlier ? to : to + 1];

	const start = before?.get('index') ?? 0;
	const end = after?.get('index') ?? 1;

	// Add randomness to prevent collisions
	const index = (end - start) * (Math.random() + Number.MIN_VALUE) + start;
	item.set('index', index);
}

3. Nested Structures for Conflict Avoidance

Problem: Storing entire objects under one key means any property change conflicts with any other.

// BAD: Alice changes nullable, Bob changes default, one loses
schema.set('title', {
	type: 'text',
	nullable: true,
	default: 'Untitled',
});

Solution: Use nested Y.Maps so each property is a separate key.

// GOOD: Each property is independent
const titleSchema = schema.get('title'); // Y.Map
titleSchema.set('type', 'text');
titleSchema.set('nullable', true);
titleSchema.set('default', 'Untitled');
// Alice and Bob edit different keys = no conflict

Storage Optimization

Y.Map vs Y.Array for Key-Value Data

Y.Map tombstones retain the key forever. Every ymap.set(key, value) creates a new internal item and tombstones the previous one.

For high-churn key-value data (frequently updated rows), consider YKeyValue from yjs/y-utility:

// YKeyValue stores {key, val} pairs in Y.Array
// Deletions are structural, not per-key tombstones
import { YKeyValue } from 'y-utility/y-keyvalue';

const kv = new YKeyValue(yarray);
kv.set('myKey', { data: 'value' });

When to use Y.Map: Bounded keys, rarely changing values (settings, config). When to use YKeyValue: Many keys, frequent updates, storage-sensitive.

Epoch-Based Compaction

If your architecture uses versioned snapshots, you get free compaction:

// Compact a Y.Doc by re-encoding current state
const snapshot = Y.encodeStateAsUpdate(doc);
const freshDoc = new Y.Doc({ guid: doc.guid });
Y.applyUpdate(freshDoc, snapshot);
// freshDoc has same content, no history overhead

Common Mistakes

1. Assuming "Last Write Wins" Means Timestamps

It doesn't. Higher clientID wins, not later timestamp. Design around this or add explicit timestamps with y-lwwmap.

2. Using Y.Array Position for User-Controlled Order

Array position is for append-only data (logs, chat). User-reorderable lists need fractional indexing.

3. Forgetting Document Integration

Y types must be added to a document before use:

// BAD: Orphan Y.Map
const orphan = new Y.Map();
orphan.set('key', 'value'); // Works but doesn't sync

// GOOD: Attached to document
const attached = doc.getMap('myMap');
attached.set('key', 'value'); // Syncs to peers

4. Storing Non-Serializable Values

Y types store JSON-serializable data. No functions, no class instances, no circular references.

5. Expecting Moves to Preserve Identity

// This creates a NEW item, not a moved item
yarray.delete(0);
yarray.push([sameItem]); // Different Y.Map instance internally

Any concurrent edits to the "moved" item are lost because you deleted the original.

6. Working with Raw Y.js Types Outside Their Owning Module

Y.js shared types (Y.Map, Y.Text, Y.XmlFragment, Y.Array) are implementation details that should stay behind typed APIs. When consumer code reaches through an abstraction to manipulate raw shared types, it creates coupling that's hard to change later.

The pattern: If a module returns Y.js shared types for editor binding (e.g., handle.asText() returns Y.Text), that's intentional—the consumer needs the live CRDT reference. But if consumer code is *constructing*, *casting*, or *mutating* Y.js types that the owning module should encapsulate, that's a leak.

// BAD: consumer reaches through handle to do raw Y.Text mutation
const entry = handle.currentEntry;
if (entry?.type === 'text') {
    handle.batch(() => entry.content.insert(entry.content.length, text));
}

// GOOD: timeline owns the append operation
handle.append(text);
// BAD: consumer constructs Y.Maps to call an internal CSV helper
import { parseSheetFromCsv } from '@epicenter/workspace';
const columns = new Y.Map<Y.Map<string>>();
const rows = new Y.Map<Y.Map<string>>();
parseSheetFromCsv(csv, columns, rows);

// GOOD: use the handle's write method, which encapsulates CSV parsing
handle.write(csv);  // mode-aware, handles sheet internally

How to Spot Abstraction Leaks

These are code smell indicators that Y.js internals are leaking:

  • Type assertions: as Y.Map, as Y.Text, as Y.XmlFragment outside the owning module means someone is working with untyped data and forcing it into shape. The typed API is incomplete.
  • Mode branching: if (entry.type === 'text')... else if (entry.type === 'sheet') in consumer code means the consumer knows about internal content modes that the abstraction should handle.
  • Raw mutations in batch callbacks: handle.batch(() => ytext.insert(...)) means the consumer is doing CRDT operations that should be a method on the handle.
  • Internal helper re-exports: Functions that take Y.Map<Y.Map<string>> parameters on a public API force consumers to have raw Y.js references to call them.
  • ydoc.getArray()/ydoc.getMap() outside infrastructure: Consumer code accessing the raw Y.Doc to read/write data bypasses the table/kv/timeline APIs.

The Boundary Rule

Three layers, each with clear Y.js exposure:

┌──────────────────────────────────────────────────────┐
│  Consumer Code (apps, features)                      │
│  • Uses handle.read(), handle.write(), tables.*.set()│
│  • MAY bind to Y.Text/Y.XmlFragment from as*()      │
│  • NEVER constructs Y.js types                       │
│  • NEVER casts to Y.js types                         │
│  • NEVER calls .insert()/.delete() on raw types      │
├──────────────────────────────────────────────────────┤
│  Format Bridges (markdown, sheet converters)          │
│  • Accepts Y.js types as parameters (they're bridges)│
│  • Converts between Y.js ↔ string/JSON               │
│  • Lives close to the owning module                   │
├──────────────────────────────────────────────────────┤
│  Timeline / Table / KV Internals                      │
│  • Constructs and manages Y.js shared types           │
│  • Owns the Y.Doc layout (array keys, map structure)  │
│  • Exposes typed APIs that hide the CRDT details      │
└──────────────────────────────────────────────────────┘

When reviewing code, ask: "Could this consumer do its job with only the typed API?" If yes and it's using raw Y.js types instead, that's a leak worth fixing.

See the article docs/articles/yjs-abstraction-leaks-cost-more-than-the-abstraction.md for the full pattern with real examples.

Debugging Tips

Inspect Document State

console.log(doc.toJSON()); // Full document as plain JSON

Check Client IDs

// See who would win a conflict
console.log('My ID:', doc.clientID);

Watch for Tombstone Bloat

If documents grow unexpectedly, check for:

  • Frequent Y.Map key overwrites
  • "Move" operations on arrays
  • Missing epoch compaction

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.7%
按下载量换算322

Claude

31.91%
按下载量换算265

Cursor

17.06%
按下载量换算142

Gemini CLI

10.27%
按下载量换算85

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills