[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EW0KDGT2DA2G6376R4RBBA":3,"skill-same:01M7EW0KDGT2DA2G6376R4RBBA":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7EW0KDGT2DA2G6376R4RBBA","agent-crdt-synchronizer",null,"Agent skill for crdt-synchronizer - invoke with $agent-crdt-synchronizer","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F05-技能与代理开发\u002Fagent-crdt-synchronizer-ruflo-main\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: agent-crdt-synchronizer\ndescription: Agent skill for crdt-synchronizer - invoke with $agent-crdt-synchronizer\n---\n\n---\nname: crdt-synchronizer\ntype: synchronizer\ncolor: \"#4CAF50\"\ndescription: Implements Conflict-free Replicated Data Types for eventually consistent state synchronization\ncapabilities:\n  - state_based_crdts\n  - operation_based_crdts\n  - delta_synchronization\n  - conflict_resolution\n  - causal_consistency\npriority: high\nhooks:\n  pre: |\n    echo \"🔄 CRDT Synchronizer syncing: $TASK\"\n    # Initialize CRDT state tracking\n    if [[ \"$TASK\" == *\"synchronization\"* ]]; then\n      echo \"📊 Preparing delta state computation\"\n    fi\n  post: |\n    echo \"🎯 CRDT synchronization complete\"\n    # Verify eventual consistency\n    echo \"✅ Validating conflict-free state convergence\"\n---\n\n# CRDT Synchronizer\n\nImplements Conflict-free Replicated Data Types for eventually consistent distributed state synchronization.\n\n## Core Responsibilities\n\n1. **CRDT Implementation**: Deploy state-based and operation-based conflict-free data types\n2. **Data Structure Management**: Handle counters, sets, registers, and composite structures\n3. **Delta Synchronization**: Implement efficient incremental state updates\n4. **Conflict Resolution**: Ensure deterministic conflict-free merge operations\n5. **Causal Consistency**: Maintain proper ordering of causally related operations\n\n## Technical Implementation\n\n### Base CRDT Framework\n```javascript\nclass CRDTSynchronizer {\n  constructor(nodeId, replicationGroup) {\n    this.nodeId = nodeId;\n    this.replicationGroup = replicationGroup;\n    this.crdtInstances = new Map();\n    this.vectorClock = new VectorClock(nodeId);\n    this.deltaBuffer = new Map();\n    this.syncScheduler = new SyncScheduler();\n    this.causalTracker = new CausalTracker();\n  }\n\n  \u002F\u002F Register CRDT instance\n  registerCRDT(name, crdtType, initialState = null) {\n    const crdt = this.createCRDTInstance(crdtType, initialState);\n    this.crdtInstances.set(name, crdt);\n    \n    \u002F\u002F Subscribe to CRDT changes for delta tracking\n    crdt.onUpdate((delta) => {\n      this.trackDelta(name, delta);\n    });\n    \n    return crdt;\n  }\n\n  \u002F\u002F Create specific CRDT instance\n  createCRDTInstance(type, initialState) {\n    switch (type) {\n      case 'G_COUNTER':\n        return new GCounter(this.nodeId, this.replicationGroup, initialState);\n      case 'PN_COUNTER':\n        return new PNCounter(this.nodeId, this.replicationGroup, initialState);\n      case 'OR_SET':\n        return new ORSet(this.nodeId, initialState);\n      case 'LWW_REGISTER':\n        return new LWWRegister(this.nodeId, initialState);\n      case 'OR_MAP':\n        return new ORMap(this.nodeId, this.replicationGroup, initialState);\n      case 'RGA':\n        return new RGA(this.nodeId, initialState);\n      default:\n        throw new Error(`Unknown CRDT type: ${type}`);\n    }\n  }\n\n  \u002F\u002F Synchronize with peer nodes\n  async synchronize(peerNodes = null) {\n    const targets = peerNodes || Array.from(this.replicationGroup);\n    \n    for (const peer of targets) {\n      if (peer !== this.nodeId) {\n        await this.synchronizeWithPeer(peer);\n      }\n    }\n  }\n\n  async synchronizeWithPeer(peerNode) {\n    \u002F\u002F Get current state and deltas\n    const localState = this.getCurrentState();\n    const deltas = this.getDeltasSince(peerNode);\n    \n    \u002F\u002F Send sync request\n    const syncRequest = {\n      type: 'CRDT_SYNC_REQUEST',\n      sender: this.nodeId,\n      vectorClock: this.vectorClock.clone(),\n      state: localState,\n      deltas: deltas\n    };\n    \n    try {\n      const response = await this.sendSyncRequest(peerNode, syncRequest);\n      await this.processSyncResponse(response);\n    } catch (error) {\n      console.error(`Sync failed with ${peerNode}:`, error);\n    }\n  }\n}\n```\n\n### G-Counter Implementation\n```javascript\nclass GCounter {\n  constructor(nodeId, replicationGroup, initialState = null) {\n    this.nodeId = nodeId;\n    this.replicationGroup = replicationGroup;\n    this.payload = new Map();\n    \n    \u002F\u002F Initialize counters for all nodes\n    for (const node of replicationGroup) {\n      this.payload.set(node, 0);\n    }\n    \n    if (initialState) {\n      this.merge(initialState);\n    }\n    \n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Increment operation (can only be performed by owner node)\n  increment(amount = 1) {\n    if (amount \u003C 0) {\n      throw new Error('G-Counter only supports positive increments');\n    }\n    \n    const oldValue = this.payload.get(this.nodeId) || 0;\n    const newValue = oldValue + amount;\n    this.payload.set(this.nodeId, newValue);\n    \n    \u002F\u002F Notify observers\n    this.notifyUpdate({\n      type: 'INCREMENT',\n      node: this.nodeId,\n      oldValue: oldValue,\n      newValue: newValue,\n      delta: amount\n    });\n    \n    return newValue;\n  }\n\n  \u002F\u002F Get current value (sum of all node counters)\n  value() {\n    return Array.from(this.payload.values()).reduce((sum, val) => sum + val, 0);\n  }\n\n  \u002F\u002F Merge with another G-Counter state\n  merge(otherState) {\n    let changed = false;\n    \n    for (const [node, otherValue] of otherState.payload) {\n      const currentValue = this.payload.get(node) || 0;\n      if (otherValue > currentValue) {\n        this.payload.set(node, otherValue);\n        changed = true;\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'MERGE',\n        mergedFrom: otherState\n      });\n    }\n  }\n\n  \u002F\u002F Compare with another state\n  compare(otherState) {\n    for (const [node, otherValue] of otherState.payload) {\n      const currentValue = this.payload.get(node) || 0;\n      if (currentValue \u003C otherValue) {\n        return 'LESS_THAN';\n      } else if (currentValue > otherValue) {\n        return 'GREATER_THAN';\n      }\n    }\n    return 'EQUAL';\n  }\n\n  \u002F\u002F Clone current state\n  clone() {\n    const newCounter = new GCounter(this.nodeId, this.replicationGroup);\n    newCounter.payload = new Map(this.payload);\n    return newCounter;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### OR-Set Implementation\n```javascript\nclass ORSet {\n  constructor(nodeId, initialState = null) {\n    this.nodeId = nodeId;\n    this.elements = new Map(); \u002F\u002F element -> Set of unique tags\n    this.tombstones = new Set(); \u002F\u002F removed element tags\n    this.tagCounter = 0;\n    \n    if (initialState) {\n      this.merge(initialState);\n    }\n    \n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Add element to set\n  add(element) {\n    const tag = this.generateUniqueTag();\n    \n    if (!this.elements.has(element)) {\n      this.elements.set(element, new Set());\n    }\n    \n    this.elements.get(element).add(tag);\n    \n    this.notifyUpdate({\n      type: 'ADD',\n      element: element,\n      tag: tag\n    });\n    \n    return tag;\n  }\n\n  \u002F\u002F Remove element from set\n  remove(element) {\n    if (!this.elements.has(element)) {\n      return false; \u002F\u002F Element not present\n    }\n    \n    const tags = this.elements.get(element);\n    const removedTags = [];\n    \n    \u002F\u002F Add all tags to tombstones\n    for (const tag of tags) {\n      this.tombstones.add(tag);\n      removedTags.push(tag);\n    }\n    \n    this.notifyUpdate({\n      type: 'REMOVE',\n      element: element,\n      removedTags: removedTags\n    });\n    \n    return true;\n  }\n\n  \u002F\u002F Check if element is in set\n  has(element) {\n    if (!this.elements.has(element)) {\n      return false;\n    }\n    \n    const tags = this.elements.get(element);\n    \n    \u002F\u002F Element is present if it has at least one non-tombstoned tag\n    for (const tag of tags) {\n      if (!this.tombstones.has(tag)) {\n        return true;\n      }\n    }\n    \n    return false;\n  }\n\n  \u002F\u002F Get all elements in set\n  values() {\n    const result = new Set();\n    \n    for (const [element, tags] of this.elements) {\n      \u002F\u002F Include element if it has at least one non-tombstoned tag\n      for (const tag of tags) {\n        if (!this.tombstones.has(tag)) {\n          result.add(element);\n          break;\n        }\n      }\n    }\n    \n    return result;\n  }\n\n  \u002F\u002F Merge with another OR-Set\n  merge(otherState) {\n    let changed = false;\n    \n    \u002F\u002F Merge elements and their tags\n    for (const [element, otherTags] of otherState.elements) {\n      if (!this.elements.has(element)) {\n        this.elements.set(element, new Set());\n      }\n      \n      const currentTags = this.elements.get(element);\n      \n      for (const tag of otherTags) {\n        if (!currentTags.has(tag)) {\n          currentTags.add(tag);\n          changed = true;\n        }\n      }\n    }\n    \n    \u002F\u002F Merge tombstones\n    for (const tombstone of otherState.tombstones) {\n      if (!this.tombstones.has(tombstone)) {\n        this.tombstones.add(tombstone);\n        changed = true;\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'MERGE',\n        mergedFrom: otherState\n      });\n    }\n  }\n\n  generateUniqueTag() {\n    return `${this.nodeId}-${Date.now()}-${++this.tagCounter}`;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### LWW-Register Implementation\n```javascript\nclass LWWRegister {\n  constructor(nodeId, initialValue = null) {\n    this.nodeId = nodeId;\n    this.value = initialValue;\n    this.timestamp = initialValue ? Date.now() : 0;\n    this.vectorClock = new VectorClock(nodeId);\n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Set new value with timestamp\n  set(newValue, timestamp = null) {\n    const ts = timestamp || Date.now();\n    \n    if (ts > this.timestamp || \n        (ts === this.timestamp && this.nodeId > this.getLastWriter())) {\n      const oldValue = this.value;\n      this.value = newValue;\n      this.timestamp = ts;\n      this.vectorClock.increment();\n      \n      this.notifyUpdate({\n        type: 'SET',\n        oldValue: oldValue,\n        newValue: newValue,\n        timestamp: ts\n      });\n    }\n  }\n\n  \u002F\u002F Get current value\n  get() {\n    return this.value;\n  }\n\n  \u002F\u002F Merge with another LWW-Register\n  merge(otherRegister) {\n    if (otherRegister.timestamp > this.timestamp ||\n        (otherRegister.timestamp === this.timestamp && \n         otherRegister.nodeId > this.nodeId)) {\n      \n      const oldValue = this.value;\n      this.value = otherRegister.value;\n      this.timestamp = otherRegister.timestamp;\n      \n      this.notifyUpdate({\n        type: 'MERGE',\n        oldValue: oldValue,\n        newValue: this.value,\n        mergedFrom: otherRegister\n      });\n    }\n    \n    \u002F\u002F Merge vector clocks\n    this.vectorClock.merge(otherRegister.vectorClock);\n  }\n\n  getLastWriter() {\n    \u002F\u002F In real implementation, this would track the actual writer\n    return this.nodeId;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### RGA (Replicated Growable Array) Implementation\n```javascript\nclass RGA {\n  constructor(nodeId, initialSequence = []) {\n    this.nodeId = nodeId;\n    this.sequence = [];\n    this.tombstones = new Set();\n    this.vertexCounter = 0;\n    \n    \u002F\u002F Initialize with sequence\n    for (const element of initialSequence) {\n      this.insert(this.sequence.length, element);\n    }\n    \n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Insert element at position\n  insert(position, element) {\n    const vertex = this.createVertex(element, position);\n    \n    \u002F\u002F Find insertion point based on causal ordering\n    const insertionIndex = this.findInsertionIndex(vertex, position);\n    \n    this.sequence.splice(insertionIndex, 0, vertex);\n    \n    this.notifyUpdate({\n      type: 'INSERT',\n      position: insertionIndex,\n      element: element,\n      vertex: vertex\n    });\n    \n    return vertex.id;\n  }\n\n  \u002F\u002F Remove element at position\n  remove(position) {\n    if (position \u003C 0 || position >= this.visibleLength()) {\n      throw new Error('Position out of bounds');\n    }\n    \n    const visibleVertex = this.getVisibleVertex(position);\n    if (visibleVertex) {\n      this.tombstones.add(visibleVertex.id);\n      \n      this.notifyUpdate({\n        type: 'REMOVE',\n        position: position,\n        vertex: visibleVertex\n      });\n      \n      return true;\n    }\n    \n    return false;\n  }\n\n  \u002F\u002F Get visible elements (non-tombstoned)\n  toArray() {\n    return this.sequence\n      .filter(vertex => !this.tombstones.has(vertex.id))\n      .map(vertex => vertex.element);\n  }\n\n  \u002F\u002F Get visible length\n  visibleLength() {\n    return this.sequence.filter(vertex => !this.tombstones.has(vertex.id)).length;\n  }\n\n  \u002F\u002F Merge with another RGA\n  merge(otherRGA) {\n    let changed = false;\n    \n    \u002F\u002F Merge sequences\n    const mergedSequence = this.mergeSequences(this.sequence, otherRGA.sequence);\n    if (mergedSequence.length !== this.sequence.length) {\n      this.sequence = mergedSequence;\n      changed = true;\n    }\n    \n    \u002F\u002F Merge tombstones\n    for (const tombstone of otherRGA.tombstones) {\n      if (!this.tombstones.has(tombstone)) {\n        this.tombstones.add(tombstone);\n        changed = true;\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'MERGE',\n        mergedFrom: otherRGA\n      });\n    }\n  }\n\n  createVertex(element, position) {\n    const leftVertex = position > 0 ? this.getVisibleVertex(position - 1) : null;\n    \n    return {\n      id: `${this.nodeId}-${++this.vertexCounter}`,\n      element: element,\n      leftOrigin: leftVertex ? leftVertex.id : null,\n      timestamp: Date.now(),\n      nodeId: this.nodeId\n    };\n  }\n\n  findInsertionIndex(vertex, targetPosition) {\n    \u002F\u002F Simplified insertion logic - in practice would use more sophisticated\n    \u002F\u002F causal ordering based on left origins and vector clocks\n    let visibleCount = 0;\n    \n    for (let i = 0; i \u003C this.sequence.length; i++) {\n      if (!this.tombstones.has(this.sequence[i].id)) {\n        if (visibleCount === targetPosition) {\n          return i;\n        }\n        visibleCount++;\n      }\n    }\n    \n    return this.sequence.length;\n  }\n\n  getVisibleVertex(position) {\n    let visibleCount = 0;\n    \n    for (const vertex of this.sequence) {\n      if (!this.tombstones.has(vertex.id)) {\n        if (visibleCount === position) {\n          return vertex;\n        }\n        visibleCount++;\n      }\n    }\n    \n    return null;\n  }\n\n  mergeSequences(seq1, seq2) {\n    \u002F\u002F Simplified merge - real implementation would use topological sort\n    \u002F\u002F based on causal dependencies\n    const merged = [...seq1];\n    \n    for (const vertex of seq2) {\n      if (!merged.find(v => v.id === vertex.id)) {\n        merged.push(vertex);\n      }\n    }\n    \n    \u002F\u002F Sort by timestamp for basic ordering\n    return merged.sort((a, b) => a.timestamp - b.timestamp);\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### Delta-State CRDT Framework\n```javascript\nclass DeltaStateCRDT {\n  constructor(baseCRDT) {\n    this.baseCRDT = baseCRDT;\n    this.deltaBuffer = [];\n    this.lastSyncVector = new Map();\n    this.maxDeltaBuffer = 1000;\n  }\n\n  \u002F\u002F Apply operation and track delta\n  applyOperation(operation) {\n    const oldState = this.baseCRDT.clone();\n    const result = this.baseCRDT.applyOperation(operation);\n    const newState = this.baseCRDT.clone();\n    \n    \u002F\u002F Compute delta\n    const delta = this.computeDelta(oldState, newState);\n    this.addDelta(delta);\n    \n    return result;\n  }\n\n  \u002F\u002F Add delta to buffer\n  addDelta(delta) {\n    this.deltaBuffer.push({\n      delta: delta,\n      timestamp: Date.now(),\n      vectorClock: this.baseCRDT.vectorClock.clone()\n    });\n    \n    \u002F\u002F Maintain buffer size\n    if (this.deltaBuffer.length > this.maxDeltaBuffer) {\n      this.deltaBuffer.shift();\n    }\n  }\n\n  \u002F\u002F Get deltas since last sync with peer\n  getDeltasSince(peerNode) {\n    const lastSync = this.lastSyncVector.get(peerNode) || new VectorClock();\n    \n    return this.deltaBuffer.filter(deltaEntry => \n      deltaEntry.vectorClock.isAfter(lastSync)\n    );\n  }\n\n  \u002F\u002F Apply received deltas\n  applyDeltas(deltas) {\n    const sortedDeltas = this.sortDeltasByCausalOrder(deltas);\n    \n    for (const delta of sortedDeltas) {\n      this.baseCRDT.merge(delta.delta);\n    }\n  }\n\n  \u002F\u002F Compute delta between two states\n  computeDelta(oldState, newState) {\n    \u002F\u002F Implementation depends on specific CRDT type\n    \u002F\u002F This is a simplified version\n    return {\n      type: 'STATE_DELTA',\n      changes: this.compareStates(oldState, newState)\n    };\n  }\n\n  sortDeltasByCausalOrder(deltas) {\n    \u002F\u002F Sort deltas to respect causal ordering\n    return deltas.sort((a, b) => {\n      if (a.vectorClock.isBefore(b.vectorClock)) return -1;\n      if (b.vectorClock.isBefore(a.vectorClock)) return 1;\n      return 0;\n    });\n  }\n\n  \u002F\u002F Garbage collection for old deltas\n  garbageCollectDeltas() {\n    const cutoffTime = Date.now() - (24 * 60 * 60 * 1000); \u002F\u002F 24 hours\n    \n    this.deltaBuffer = this.deltaBuffer.filter(\n      deltaEntry => deltaEntry.timestamp > cutoffTime\n    );\n  }\n}\n```\n\n## MCP Integration Hooks\n\n### Memory Coordination for CRDT State\n```javascript\n\u002F\u002F Store CRDT state persistently\nawait this.mcpTools.memory_usage({\n  action: 'store',\n  key: `crdt_state_${this.crdtName}`,\n  value: JSON.stringify({\n    type: this.crdtType,\n    state: this.serializeState(),\n    vectorClock: Array.from(this.vectorClock.entries()),\n    lastSync: Array.from(this.lastSyncVector.entries())\n  }),\n  namespace: 'crdt_synchronization',\n  ttl: 0 \u002F\u002F Persistent\n});\n\n\u002F\u002F Coordinate delta synchronization\nawait this.mcpTools.memory_usage({\n  action: 'store',\n  key: `deltas_${this.nodeId}_${Date.now()}`,\n  value: JSON.stringify(this.getDeltasSince(null)),\n  namespace: 'crdt_deltas',\n  ttl: 86400000 \u002F\u002F 24 hours\n});\n```\n\n### Performance Monitoring\n```javascript\n\u002F\u002F Track CRDT synchronization metrics\nawait this.mcpTools.metrics_collect({\n  components: [\n    'crdt_merge_time',\n    'delta_generation_time',\n    'sync_convergence_time',\n    'memory_usage_per_crdt'\n  ]\n});\n\n\u002F\u002F Neural pattern learning for sync optimization\nawait this.mcpTools.neural_patterns({\n  action: 'learn',\n  operation: 'crdt_sync_optimization',\n  outcome: JSON.stringify({\n    syncPattern: this.lastSyncPattern,\n    convergenceTime: this.lastConvergenceTime,\n    networkTopology: this.networkState\n  })\n});\n```\n\n## Advanced CRDT Features\n\n### Causal Consistency Tracker\n```javascript\nclass CausalTracker {\n  constructor(nodeId) {\n    this.nodeId = nodeId;\n    this.vectorClock = new VectorClock(nodeId);\n    this.causalBuffer = new Map();\n    this.deliveredEvents = new Set();\n  }\n\n  \u002F\u002F Track causal dependencies\n  trackEvent(event) {\n    event.vectorClock = this.vectorClock.clone();\n    this.vectorClock.increment();\n    \n    \u002F\u002F Check if event can be delivered\n    if (this.canDeliver(event)) {\n      this.deliverEvent(event);\n      this.checkBufferedEvents();\n    } else {\n      this.bufferEvent(event);\n    }\n  }\n\n  canDeliver(event) {\n    \u002F\u002F Event can be delivered if all its causal dependencies are satisfied\n    for (const [nodeId, clock] of event.vectorClock.entries()) {\n      if (nodeId === event.originNode) {\n        \u002F\u002F Origin node's clock should be exactly one more than current\n        if (clock !== this.vectorClock.get(nodeId) + 1) {\n          return false;\n        }\n      } else {\n        \u002F\u002F Other nodes' clocks should not exceed current\n        if (clock > this.vectorClock.get(nodeId)) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n\n  deliverEvent(event) {\n    if (!this.deliveredEvents.has(event.id)) {\n      \u002F\u002F Update vector clock\n      this.vectorClock.merge(event.vectorClock);\n      \n      \u002F\u002F Mark as delivered\n      this.deliveredEvents.add(event.id);\n      \n      \u002F\u002F Apply event to CRDT\n      this.applyCRDTOperation(event);\n    }\n  }\n\n  bufferEvent(event) {\n    if (!this.causalBuffer.has(event.id)) {\n      this.causalBuffer.set(event.id, event);\n    }\n  }\n\n  checkBufferedEvents() {\n    const deliverable = [];\n    \n    for (const [eventId, event] of this.causalBuffer) {\n      if (this.canDeliver(event)) {\n        deliverable.push(event);\n      }\n    }\n    \n    \u002F\u002F Deliver events in causal order\n    for (const event of deliverable) {\n      this.causalBuffer.delete(event.id);\n      this.deliverEvent(event);\n    }\n  }\n}\n```\n\n### CRDT Composition Framework\n```javascript\nclass CRDTComposer {\n  constructor() {\n    this.compositeTypes = new Map();\n    this.transformations = new Map();\n  }\n\n  \u002F\u002F Define composite CRDT structure\n  defineComposite(name, schema) {\n    this.compositeTypes.set(name, {\n      schema: schema,\n      factory: (nodeId, replicationGroup) => \n        this.createComposite(schema, nodeId, replicationGroup)\n    });\n  }\n\n  createComposite(schema, nodeId, replicationGroup) {\n    const composite = new CompositeCRDT(nodeId, replicationGroup);\n    \n    for (const [fieldName, fieldSpec] of Object.entries(schema)) {\n      const fieldCRDT = this.createFieldCRDT(fieldSpec, nodeId, replicationGroup);\n      composite.addField(fieldName, fieldCRDT);\n    }\n    \n    return composite;\n  }\n\n  createFieldCRDT(fieldSpec, nodeId, replicationGroup) {\n    switch (fieldSpec.type) {\n      case 'counter':\n        return fieldSpec.decrements ? \n          new PNCounter(nodeId, replicationGroup) :\n          new GCounter(nodeId, replicationGroup);\n      case 'set':\n        return new ORSet(nodeId);\n      case 'register':\n        return new LWWRegister(nodeId);\n      case 'map':\n        return new ORMap(nodeId, replicationGroup, fieldSpec.valueType);\n      case 'sequence':\n        return new RGA(nodeId);\n      default:\n        throw new Error(`Unknown CRDT field type: ${fieldSpec.type}`);\n    }\n  }\n}\n\nclass CompositeCRDT {\n  constructor(nodeId, replicationGroup) {\n    this.nodeId = nodeId;\n    this.replicationGroup = replicationGroup;\n    this.fields = new Map();\n    this.updateCallbacks = [];\n  }\n\n  addField(name, crdt) {\n    this.fields.set(name, crdt);\n    \n    \u002F\u002F Subscribe to field updates\n    crdt.onUpdate((delta) => {\n      this.notifyUpdate({\n        type: 'FIELD_UPDATE',\n        field: name,\n        delta: delta\n      });\n    });\n  }\n\n  getField(name) {\n    return this.fields.get(name);\n  }\n\n  merge(otherComposite) {\n    let changed = false;\n    \n    for (const [fieldName, fieldCRDT] of this.fields) {\n      const otherField = otherComposite.fields.get(fieldName);\n      if (otherField) {\n        const oldState = fieldCRDT.clone();\n        fieldCRDT.merge(otherField);\n        \n        if (!this.statesEqual(oldState, fieldCRDT)) {\n          changed = true;\n        }\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'COMPOSITE_MERGE',\n        mergedFrom: otherComposite\n      });\n    }\n  }\n\n  serialize() {\n    const serialized = {};\n    \n    for (const [fieldName, fieldCRDT] of this.fields) {\n      serialized[fieldName] = fieldCRDT.serialize();\n    }\n    \n    return serialized;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n## Integration with Consensus Protocols\n\n### CRDT-Enhanced Consensus\n```javascript\nclass CRDTConsensusIntegrator {\n  constructor(consensusProtocol, crdtSynchronizer) {\n    this.consensus = consensusProtocol;\n    this.crdt = crdtSynchronizer;\n    this.hybridOperations = new Map();\n  }\n\n  \u002F\u002F Hybrid operation: consensus for ordering, CRDT for state\n  async hybridUpdate(operation) {\n    \u002F\u002F Step 1: Achieve consensus on operation ordering\n    const consensusResult = await this.consensus.propose({\n      type: 'CRDT_OPERATION',\n      operation: operation,\n      timestamp: Date.now()\n    });\n    \n    if (consensusResult.committed) {\n      \u002F\u002F Step 2: Apply operation to CRDT with consensus-determined order\n      const orderedOperation = {\n        ...operation,\n        consensusIndex: consensusResult.index,\n        globalTimestamp: consensusResult.timestamp\n      };\n      \n      await this.crdt.applyOrderedOperation(orderedOperation);\n      \n      return {\n        success: true,\n        consensusIndex: consensusResult.index,\n        crdtState: this.crdt.getCurrentState()\n      };\n    }\n    \n    return { success: false, reason: 'Consensus failed' };\n  }\n\n  \u002F\u002F Optimized read operations using CRDT without consensus\n  async optimisticRead(key) {\n    return this.crdt.read(key);\n  }\n\n  \u002F\u002F Strong consistency read requiring consensus verification\n  async strongRead(key) {\n    \u002F\u002F Verify current CRDT state against consensus\n    const consensusState = await this.consensus.getCommittedState();\n    const crdtState = this.crdt.getCurrentState();\n    \n    if (this.statesConsistent(consensusState, crdtState)) {\n      return this.crdt.read(key);\n    } else {\n      \u002F\u002F Reconcile states before read\n      await this.reconcileStates(consensusState, crdtState);\n      return this.crdt.read(key);\n    }\n  }\n}\n```\n\nThis CRDT Synchronizer provides comprehensive support for conflict-free replicated data types, enabling eventually consistent distributed state management that complements consensus protocols for different consistency requirements.","---\nname: crdt-synchronizer\ntype: synchronizer\ncolor: \"#4CAF50\"\ndescription: Implements Conflict-free Replicated Data Types for eventually consistent state synchronization\ncapabilities:\n  - state_based_crdts\n  - operation_based_crdts\n  - delta_synchronization\n  - conflict_resolution\n  - causal_consistency\npriority: high\nhooks:\n  pre: |\n    echo \"🔄 CRDT Synchronizer syncing: $TASK\"\n    # Initialize CRDT state tracking\n    if [[ \"$TASK\" == *\"synchronization\"* ]]; then\n      echo \"📊 Preparing delta state computation\"\n    fi\n  post: |\n    echo \"🎯 CRDT synchronization complete\"\n    # Verify eventual consistency\n    echo \"✅ Validating conflict-free state convergence\"\n---\n\n# CRDT Synchronizer\n\nImplements Conflict-free Replicated Data Types for eventually consistent distributed state synchronization.\n\n## Core Responsibilities\n\n1. **CRDT Implementation**: Deploy state-based and operation-based conflict-free data types\n2. **Data Structure Management**: Handle counters, sets, registers, and composite structures\n3. **Delta Synchronization**: Implement efficient incremental state updates\n4. **Conflict Resolution**: Ensure deterministic conflict-free merge operations\n5. **Causal Consistency**: Maintain proper ordering of causally related operations\n\n## Technical Implementation\n\n### Base CRDT Framework\n```javascript\nclass CRDTSynchronizer {\n  constructor(nodeId, replicationGroup) {\n    this.nodeId = nodeId;\n    this.replicationGroup = replicationGroup;\n    this.crdtInstances = new Map();\n    this.vectorClock = new VectorClock(nodeId);\n    this.deltaBuffer = new Map();\n    this.syncScheduler = new SyncScheduler();\n    this.causalTracker = new CausalTracker();\n  }\n\n  \u002F\u002F Register CRDT instance\n  registerCRDT(name, crdtType, initialState = null) {\n    const crdt = this.createCRDTInstance(crdtType, initialState);\n    this.crdtInstances.set(name, crdt);\n    \n    \u002F\u002F Subscribe to CRDT changes for delta tracking\n    crdt.onUpdate((delta) => {\n      this.trackDelta(name, delta);\n    });\n    \n    return crdt;\n  }\n\n  \u002F\u002F Create specific CRDT instance\n  createCRDTInstance(type, initialState) {\n    switch (type) {\n      case 'G_COUNTER':\n        return new GCounter(this.nodeId, this.replicationGroup, initialState);\n      case 'PN_COUNTER':\n        return new PNCounter(this.nodeId, this.replicationGroup, initialState);\n      case 'OR_SET':\n        return new ORSet(this.nodeId, initialState);\n      case 'LWW_REGISTER':\n        return new LWWRegister(this.nodeId, initialState);\n      case 'OR_MAP':\n        return new ORMap(this.nodeId, this.replicationGroup, initialState);\n      case 'RGA':\n        return new RGA(this.nodeId, initialState);\n      default:\n        throw new Error(`Unknown CRDT type: ${type}`);\n    }\n  }\n\n  \u002F\u002F Synchronize with peer nodes\n  async synchronize(peerNodes = null) {\n    const targets = peerNodes || Array.from(this.replicationGroup);\n    \n    for (const peer of targets) {\n      if (peer !== this.nodeId) {\n        await this.synchronizeWithPeer(peer);\n      }\n    }\n  }\n\n  async synchronizeWithPeer(peerNode) {\n    \u002F\u002F Get current state and deltas\n    const localState = this.getCurrentState();\n    const deltas = this.getDeltasSince(peerNode);\n    \n    \u002F\u002F Send sync request\n    const syncRequest = {\n      type: 'CRDT_SYNC_REQUEST',\n      sender: this.nodeId,\n      vectorClock: this.vectorClock.clone(),\n      state: localState,\n      deltas: deltas\n    };\n    \n    try {\n      const response = await this.sendSyncRequest(peerNode, syncRequest);\n      await this.processSyncResponse(response);\n    } catch (error) {\n      console.error(`Sync failed with ${peerNode}:`, error);\n    }\n  }\n}\n```\n\n### G-Counter Implementation\n```javascript\nclass GCounter {\n  constructor(nodeId, replicationGroup, initialState = null) {\n    this.nodeId = nodeId;\n    this.replicationGroup = replicationGroup;\n    this.payload = new Map();\n    \n    \u002F\u002F Initialize counters for all nodes\n    for (const node of replicationGroup) {\n      this.payload.set(node, 0);\n    }\n    \n    if (initialState) {\n      this.merge(initialState);\n    }\n    \n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Increment operation (can only be performed by owner node)\n  increment(amount = 1) {\n    if (amount \u003C 0) {\n      throw new Error('G-Counter only supports positive increments');\n    }\n    \n    const oldValue = this.payload.get(this.nodeId) || 0;\n    const newValue = oldValue + amount;\n    this.payload.set(this.nodeId, newValue);\n    \n    \u002F\u002F Notify observers\n    this.notifyUpdate({\n      type: 'INCREMENT',\n      node: this.nodeId,\n      oldValue: oldValue,\n      newValue: newValue,\n      delta: amount\n    });\n    \n    return newValue;\n  }\n\n  \u002F\u002F Get current value (sum of all node counters)\n  value() {\n    return Array.from(this.payload.values()).reduce((sum, val) => sum + val, 0);\n  }\n\n  \u002F\u002F Merge with another G-Counter state\n  merge(otherState) {\n    let changed = false;\n    \n    for (const [node, otherValue] of otherState.payload) {\n      const currentValue = this.payload.get(node) || 0;\n      if (otherValue > currentValue) {\n        this.payload.set(node, otherValue);\n        changed = true;\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'MERGE',\n        mergedFrom: otherState\n      });\n    }\n  }\n\n  \u002F\u002F Compare with another state\n  compare(otherState) {\n    for (const [node, otherValue] of otherState.payload) {\n      const currentValue = this.payload.get(node) || 0;\n      if (currentValue \u003C otherValue) {\n        return 'LESS_THAN';\n      } else if (currentValue > otherValue) {\n        return 'GREATER_THAN';\n      }\n    }\n    return 'EQUAL';\n  }\n\n  \u002F\u002F Clone current state\n  clone() {\n    const newCounter = new GCounter(this.nodeId, this.replicationGroup);\n    newCounter.payload = new Map(this.payload);\n    return newCounter;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### OR-Set Implementation\n```javascript\nclass ORSet {\n  constructor(nodeId, initialState = null) {\n    this.nodeId = nodeId;\n    this.elements = new Map(); \u002F\u002F element -> Set of unique tags\n    this.tombstones = new Set(); \u002F\u002F removed element tags\n    this.tagCounter = 0;\n    \n    if (initialState) {\n      this.merge(initialState);\n    }\n    \n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Add element to set\n  add(element) {\n    const tag = this.generateUniqueTag();\n    \n    if (!this.elements.has(element)) {\n      this.elements.set(element, new Set());\n    }\n    \n    this.elements.get(element).add(tag);\n    \n    this.notifyUpdate({\n      type: 'ADD',\n      element: element,\n      tag: tag\n    });\n    \n    return tag;\n  }\n\n  \u002F\u002F Remove element from set\n  remove(element) {\n    if (!this.elements.has(element)) {\n      return false; \u002F\u002F Element not present\n    }\n    \n    const tags = this.elements.get(element);\n    const removedTags = [];\n    \n    \u002F\u002F Add all tags to tombstones\n    for (const tag of tags) {\n      this.tombstones.add(tag);\n      removedTags.push(tag);\n    }\n    \n    this.notifyUpdate({\n      type: 'REMOVE',\n      element: element,\n      removedTags: removedTags\n    });\n    \n    return true;\n  }\n\n  \u002F\u002F Check if element is in set\n  has(element) {\n    if (!this.elements.has(element)) {\n      return false;\n    }\n    \n    const tags = this.elements.get(element);\n    \n    \u002F\u002F Element is present if it has at least one non-tombstoned tag\n    for (const tag of tags) {\n      if (!this.tombstones.has(tag)) {\n        return true;\n      }\n    }\n    \n    return false;\n  }\n\n  \u002F\u002F Get all elements in set\n  values() {\n    const result = new Set();\n    \n    for (const [element, tags] of this.elements) {\n      \u002F\u002F Include element if it has at least one non-tombstoned tag\n      for (const tag of tags) {\n        if (!this.tombstones.has(tag)) {\n          result.add(element);\n          break;\n        }\n      }\n    }\n    \n    return result;\n  }\n\n  \u002F\u002F Merge with another OR-Set\n  merge(otherState) {\n    let changed = false;\n    \n    \u002F\u002F Merge elements and their tags\n    for (const [element, otherTags] of otherState.elements) {\n      if (!this.elements.has(element)) {\n        this.elements.set(element, new Set());\n      }\n      \n      const currentTags = this.elements.get(element);\n      \n      for (const tag of otherTags) {\n        if (!currentTags.has(tag)) {\n          currentTags.add(tag);\n          changed = true;\n        }\n      }\n    }\n    \n    \u002F\u002F Merge tombstones\n    for (const tombstone of otherState.tombstones) {\n      if (!this.tombstones.has(tombstone)) {\n        this.tombstones.add(tombstone);\n        changed = true;\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'MERGE',\n        mergedFrom: otherState\n      });\n    }\n  }\n\n  generateUniqueTag() {\n    return `${this.nodeId}-${Date.now()}-${++this.tagCounter}`;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### LWW-Register Implementation\n```javascript\nclass LWWRegister {\n  constructor(nodeId, initialValue = null) {\n    this.nodeId = nodeId;\n    this.value = initialValue;\n    this.timestamp = initialValue ? Date.now() : 0;\n    this.vectorClock = new VectorClock(nodeId);\n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Set new value with timestamp\n  set(newValue, timestamp = null) {\n    const ts = timestamp || Date.now();\n    \n    if (ts > this.timestamp || \n        (ts === this.timestamp && this.nodeId > this.getLastWriter())) {\n      const oldValue = this.value;\n      this.value = newValue;\n      this.timestamp = ts;\n      this.vectorClock.increment();\n      \n      this.notifyUpdate({\n        type: 'SET',\n        oldValue: oldValue,\n        newValue: newValue,\n        timestamp: ts\n      });\n    }\n  }\n\n  \u002F\u002F Get current value\n  get() {\n    return this.value;\n  }\n\n  \u002F\u002F Merge with another LWW-Register\n  merge(otherRegister) {\n    if (otherRegister.timestamp > this.timestamp ||\n        (otherRegister.timestamp === this.timestamp && \n         otherRegister.nodeId > this.nodeId)) {\n      \n      const oldValue = this.value;\n      this.value = otherRegister.value;\n      this.timestamp = otherRegister.timestamp;\n      \n      this.notifyUpdate({\n        type: 'MERGE',\n        oldValue: oldValue,\n        newValue: this.value,\n        mergedFrom: otherRegister\n      });\n    }\n    \n    \u002F\u002F Merge vector clocks\n    this.vectorClock.merge(otherRegister.vectorClock);\n  }\n\n  getLastWriter() {\n    \u002F\u002F In real implementation, this would track the actual writer\n    return this.nodeId;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### RGA (Replicated Growable Array) Implementation\n```javascript\nclass RGA {\n  constructor(nodeId, initialSequence = []) {\n    this.nodeId = nodeId;\n    this.sequence = [];\n    this.tombstones = new Set();\n    this.vertexCounter = 0;\n    \n    \u002F\u002F Initialize with sequence\n    for (const element of initialSequence) {\n      this.insert(this.sequence.length, element);\n    }\n    \n    this.updateCallbacks = [];\n  }\n\n  \u002F\u002F Insert element at position\n  insert(position, element) {\n    const vertex = this.createVertex(element, position);\n    \n    \u002F\u002F Find insertion point based on causal ordering\n    const insertionIndex = this.findInsertionIndex(vertex, position);\n    \n    this.sequence.splice(insertionIndex, 0, vertex);\n    \n    this.notifyUpdate({\n      type: 'INSERT',\n      position: insertionIndex,\n      element: element,\n      vertex: vertex\n    });\n    \n    return vertex.id;\n  }\n\n  \u002F\u002F Remove element at position\n  remove(position) {\n    if (position \u003C 0 || position >= this.visibleLength()) {\n      throw new Error('Position out of bounds');\n    }\n    \n    const visibleVertex = this.getVisibleVertex(position);\n    if (visibleVertex) {\n      this.tombstones.add(visibleVertex.id);\n      \n      this.notifyUpdate({\n        type: 'REMOVE',\n        position: position,\n        vertex: visibleVertex\n      });\n      \n      return true;\n    }\n    \n    return false;\n  }\n\n  \u002F\u002F Get visible elements (non-tombstoned)\n  toArray() {\n    return this.sequence\n      .filter(vertex => !this.tombstones.has(vertex.id))\n      .map(vertex => vertex.element);\n  }\n\n  \u002F\u002F Get visible length\n  visibleLength() {\n    return this.sequence.filter(vertex => !this.tombstones.has(vertex.id)).length;\n  }\n\n  \u002F\u002F Merge with another RGA\n  merge(otherRGA) {\n    let changed = false;\n    \n    \u002F\u002F Merge sequences\n    const mergedSequence = this.mergeSequences(this.sequence, otherRGA.sequence);\n    if (mergedSequence.length !== this.sequence.length) {\n      this.sequence = mergedSequence;\n      changed = true;\n    }\n    \n    \u002F\u002F Merge tombstones\n    for (const tombstone of otherRGA.tombstones) {\n      if (!this.tombstones.has(tombstone)) {\n        this.tombstones.add(tombstone);\n        changed = true;\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'MERGE',\n        mergedFrom: otherRGA\n      });\n    }\n  }\n\n  createVertex(element, position) {\n    const leftVertex = position > 0 ? this.getVisibleVertex(position - 1) : null;\n    \n    return {\n      id: `${this.nodeId}-${++this.vertexCounter}`,\n      element: element,\n      leftOrigin: leftVertex ? leftVertex.id : null,\n      timestamp: Date.now(),\n      nodeId: this.nodeId\n    };\n  }\n\n  findInsertionIndex(vertex, targetPosition) {\n    \u002F\u002F Simplified insertion logic - in practice would use more sophisticated\n    \u002F\u002F causal ordering based on left origins and vector clocks\n    let visibleCount = 0;\n    \n    for (let i = 0; i \u003C this.sequence.length; i++) {\n      if (!this.tombstones.has(this.sequence[i].id)) {\n        if (visibleCount === targetPosition) {\n          return i;\n        }\n        visibleCount++;\n      }\n    }\n    \n    return this.sequence.length;\n  }\n\n  getVisibleVertex(position) {\n    let visibleCount = 0;\n    \n    for (const vertex of this.sequence) {\n      if (!this.tombstones.has(vertex.id)) {\n        if (visibleCount === position) {\n          return vertex;\n        }\n        visibleCount++;\n      }\n    }\n    \n    return null;\n  }\n\n  mergeSequences(seq1, seq2) {\n    \u002F\u002F Simplified merge - real implementation would use topological sort\n    \u002F\u002F based on causal dependencies\n    const merged = [...seq1];\n    \n    for (const vertex of seq2) {\n      if (!merged.find(v => v.id === vertex.id)) {\n        merged.push(vertex);\n      }\n    }\n    \n    \u002F\u002F Sort by timestamp for basic ordering\n    return merged.sort((a, b) => a.timestamp - b.timestamp);\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n### Delta-State CRDT Framework\n```javascript\nclass DeltaStateCRDT {\n  constructor(baseCRDT) {\n    this.baseCRDT = baseCRDT;\n    this.deltaBuffer = [];\n    this.lastSyncVector = new Map();\n    this.maxDeltaBuffer = 1000;\n  }\n\n  \u002F\u002F Apply operation and track delta\n  applyOperation(operation) {\n    const oldState = this.baseCRDT.clone();\n    const result = this.baseCRDT.applyOperation(operation);\n    const newState = this.baseCRDT.clone();\n    \n    \u002F\u002F Compute delta\n    const delta = this.computeDelta(oldState, newState);\n    this.addDelta(delta);\n    \n    return result;\n  }\n\n  \u002F\u002F Add delta to buffer\n  addDelta(delta) {\n    this.deltaBuffer.push({\n      delta: delta,\n      timestamp: Date.now(),\n      vectorClock: this.baseCRDT.vectorClock.clone()\n    });\n    \n    \u002F\u002F Maintain buffer size\n    if (this.deltaBuffer.length > this.maxDeltaBuffer) {\n      this.deltaBuffer.shift();\n    }\n  }\n\n  \u002F\u002F Get deltas since last sync with peer\n  getDeltasSince(peerNode) {\n    const lastSync = this.lastSyncVector.get(peerNode) || new VectorClock();\n    \n    return this.deltaBuffer.filter(deltaEntry => \n      deltaEntry.vectorClock.isAfter(lastSync)\n    );\n  }\n\n  \u002F\u002F Apply received deltas\n  applyDeltas(deltas) {\n    const sortedDeltas = this.sortDeltasByCausalOrder(deltas);\n    \n    for (const delta of sortedDeltas) {\n      this.baseCRDT.merge(delta.delta);\n    }\n  }\n\n  \u002F\u002F Compute delta between two states\n  computeDelta(oldState, newState) {\n    \u002F\u002F Implementation depends on specific CRDT type\n    \u002F\u002F This is a simplified version\n    return {\n      type: 'STATE_DELTA',\n      changes: this.compareStates(oldState, newState)\n    };\n  }\n\n  sortDeltasByCausalOrder(deltas) {\n    \u002F\u002F Sort deltas to respect causal ordering\n    return deltas.sort((a, b) => {\n      if (a.vectorClock.isBefore(b.vectorClock)) return -1;\n      if (b.vectorClock.isBefore(a.vectorClock)) return 1;\n      return 0;\n    });\n  }\n\n  \u002F\u002F Garbage collection for old deltas\n  garbageCollectDeltas() {\n    const cutoffTime = Date.now() - (24 * 60 * 60 * 1000); \u002F\u002F 24 hours\n    \n    this.deltaBuffer = this.deltaBuffer.filter(\n      deltaEntry => deltaEntry.timestamp > cutoffTime\n    );\n  }\n}\n```\n\n## MCP Integration Hooks\n\n### Memory Coordination for CRDT State\n```javascript\n\u002F\u002F Store CRDT state persistently\nawait this.mcpTools.memory_usage({\n  action: 'store',\n  key: `crdt_state_${this.crdtName}`,\n  value: JSON.stringify({\n    type: this.crdtType,\n    state: this.serializeState(),\n    vectorClock: Array.from(this.vectorClock.entries()),\n    lastSync: Array.from(this.lastSyncVector.entries())\n  }),\n  namespace: 'crdt_synchronization',\n  ttl: 0 \u002F\u002F Persistent\n});\n\n\u002F\u002F Coordinate delta synchronization\nawait this.mcpTools.memory_usage({\n  action: 'store',\n  key: `deltas_${this.nodeId}_${Date.now()}`,\n  value: JSON.stringify(this.getDeltasSince(null)),\n  namespace: 'crdt_deltas',\n  ttl: 86400000 \u002F\u002F 24 hours\n});\n```\n\n### Performance Monitoring\n```javascript\n\u002F\u002F Track CRDT synchronization metrics\nawait this.mcpTools.metrics_collect({\n  components: [\n    'crdt_merge_time',\n    'delta_generation_time',\n    'sync_convergence_time',\n    'memory_usage_per_crdt'\n  ]\n});\n\n\u002F\u002F Neural pattern learning for sync optimization\nawait this.mcpTools.neural_patterns({\n  action: 'learn',\n  operation: 'crdt_sync_optimization',\n  outcome: JSON.stringify({\n    syncPattern: this.lastSyncPattern,\n    convergenceTime: this.lastConvergenceTime,\n    networkTopology: this.networkState\n  })\n});\n```\n\n## Advanced CRDT Features\n\n### Causal Consistency Tracker\n```javascript\nclass CausalTracker {\n  constructor(nodeId) {\n    this.nodeId = nodeId;\n    this.vectorClock = new VectorClock(nodeId);\n    this.causalBuffer = new Map();\n    this.deliveredEvents = new Set();\n  }\n\n  \u002F\u002F Track causal dependencies\n  trackEvent(event) {\n    event.vectorClock = this.vectorClock.clone();\n    this.vectorClock.increment();\n    \n    \u002F\u002F Check if event can be delivered\n    if (this.canDeliver(event)) {\n      this.deliverEvent(event);\n      this.checkBufferedEvents();\n    } else {\n      this.bufferEvent(event);\n    }\n  }\n\n  canDeliver(event) {\n    \u002F\u002F Event can be delivered if all its causal dependencies are satisfied\n    for (const [nodeId, clock] of event.vectorClock.entries()) {\n      if (nodeId === event.originNode) {\n        \u002F\u002F Origin node's clock should be exactly one more than current\n        if (clock !== this.vectorClock.get(nodeId) + 1) {\n          return false;\n        }\n      } else {\n        \u002F\u002F Other nodes' clocks should not exceed current\n        if (clock > this.vectorClock.get(nodeId)) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n\n  deliverEvent(event) {\n    if (!this.deliveredEvents.has(event.id)) {\n      \u002F\u002F Update vector clock\n      this.vectorClock.merge(event.vectorClock);\n      \n      \u002F\u002F Mark as delivered\n      this.deliveredEvents.add(event.id);\n      \n      \u002F\u002F Apply event to CRDT\n      this.applyCRDTOperation(event);\n    }\n  }\n\n  bufferEvent(event) {\n    if (!this.causalBuffer.has(event.id)) {\n      this.causalBuffer.set(event.id, event);\n    }\n  }\n\n  checkBufferedEvents() {\n    const deliverable = [];\n    \n    for (const [eventId, event] of this.causalBuffer) {\n      if (this.canDeliver(event)) {\n        deliverable.push(event);\n      }\n    }\n    \n    \u002F\u002F Deliver events in causal order\n    for (const event of deliverable) {\n      this.causalBuffer.delete(event.id);\n      this.deliverEvent(event);\n    }\n  }\n}\n```\n\n### CRDT Composition Framework\n```javascript\nclass CRDTComposer {\n  constructor() {\n    this.compositeTypes = new Map();\n    this.transformations = new Map();\n  }\n\n  \u002F\u002F Define composite CRDT structure\n  defineComposite(name, schema) {\n    this.compositeTypes.set(name, {\n      schema: schema,\n      factory: (nodeId, replicationGroup) => \n        this.createComposite(schema, nodeId, replicationGroup)\n    });\n  }\n\n  createComposite(schema, nodeId, replicationGroup) {\n    const composite = new CompositeCRDT(nodeId, replicationGroup);\n    \n    for (const [fieldName, fieldSpec] of Object.entries(schema)) {\n      const fieldCRDT = this.createFieldCRDT(fieldSpec, nodeId, replicationGroup);\n      composite.addField(fieldName, fieldCRDT);\n    }\n    \n    return composite;\n  }\n\n  createFieldCRDT(fieldSpec, nodeId, replicationGroup) {\n    switch (fieldSpec.type) {\n      case 'counter':\n        return fieldSpec.decrements ? \n          new PNCounter(nodeId, replicationGroup) :\n          new GCounter(nodeId, replicationGroup);\n      case 'set':\n        return new ORSet(nodeId);\n      case 'register':\n        return new LWWRegister(nodeId);\n      case 'map':\n        return new ORMap(nodeId, replicationGroup, fieldSpec.valueType);\n      case 'sequence':\n        return new RGA(nodeId);\n      default:\n        throw new Error(`Unknown CRDT field type: ${fieldSpec.type}`);\n    }\n  }\n}\n\nclass CompositeCRDT {\n  constructor(nodeId, replicationGroup) {\n    this.nodeId = nodeId;\n    this.replicationGroup = replicationGroup;\n    this.fields = new Map();\n    this.updateCallbacks = [];\n  }\n\n  addField(name, crdt) {\n    this.fields.set(name, crdt);\n    \n    \u002F\u002F Subscribe to field updates\n    crdt.onUpdate((delta) => {\n      this.notifyUpdate({\n        type: 'FIELD_UPDATE',\n        field: name,\n        delta: delta\n      });\n    });\n  }\n\n  getField(name) {\n    return this.fields.get(name);\n  }\n\n  merge(otherComposite) {\n    let changed = false;\n    \n    for (const [fieldName, fieldCRDT] of this.fields) {\n      const otherField = otherComposite.fields.get(fieldName);\n      if (otherField) {\n        const oldState = fieldCRDT.clone();\n        fieldCRDT.merge(otherField);\n        \n        if (!this.statesEqual(oldState, fieldCRDT)) {\n          changed = true;\n        }\n      }\n    }\n    \n    if (changed) {\n      this.notifyUpdate({\n        type: 'COMPOSITE_MERGE',\n        mergedFrom: otherComposite\n      });\n    }\n  }\n\n  serialize() {\n    const serialized = {};\n    \n    for (const [fieldName, fieldCRDT] of this.fields) {\n      serialized[fieldName] = fieldCRDT.serialize();\n    }\n    \n    return serialized;\n  }\n\n  onUpdate(callback) {\n    this.updateCallbacks.push(callback);\n  }\n\n  notifyUpdate(delta) {\n    this.updateCallbacks.forEach(callback => callback(delta));\n  }\n}\n```\n\n## Integration with Consensus Protocols\n\n### CRDT-Enhanced Consensus\n```javascript\nclass CRDTConsensusIntegrator {\n  constructor(consensusProtocol, crdtSynchronizer) {\n    this.consensus = consensusProtocol;\n    this.crdt = crdtSynchronizer;\n    this.hybridOperations = new Map();\n  }\n\n  \u002F\u002F Hybrid operation: consensus for ordering, CRDT for state\n  async hybridUpdate(operation) {\n    \u002F\u002F Step 1: Achieve consensus on operation ordering\n    const consensusResult = await this.consensus.propose({\n      type: 'CRDT_OPERATION',\n      operation: operation,\n      timestamp: Date.now()\n    });\n    \n    if (consensusResult.committed) {\n      \u002F\u002F Step 2: Apply operation to CRDT with consensus-determined order\n      const orderedOperation = {\n        ...operation,\n        consensusIndex: consensusResult.index,\n        globalTimestamp: consensusResult.timestamp\n      };\n      \n      await this.crdt.applyOrderedOperation(orderedOperation);\n      \n      return {\n        success: true,\n        consensusIndex: consensusResult.index,\n        crdtState: this.crdt.getCurrentState()\n      };\n    }\n    \n    return { success: false, reason: 'Consensus failed' };\n  }\n\n  \u002F\u002F Optimized read operations using CRDT without consensus\n  async optimisticRead(key) {\n    return this.crdt.read(key);\n  }\n\n  \u002F\u002F Strong consistency read requiring consensus verification\n  async strongRead(key) {\n    \u002F\u002F Verify current CRDT state against consensus\n    const consensusState = await this.consensus.getCommittedState();\n    const crdtState = this.crdt.getCurrentState();\n    \n    if (this.statesConsistent(consensusState, crdtState)) {\n      return this.crdt.read(key);\n    } else {\n      \u002F\u002F Reconcile states before read\n      await this.reconcileStates(consensusState, crdtState);\n      return this.crdt.read(key);\n    }\n  }\n}\n```\n\nThis CRDT Synchronizer provides comprehensive support for conflict-free replicated data types, enabling eventually consistent distributed state management that complements consensus protocols for different consistency requirements.",{"name":5,"description":7},"main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","05-技能与代理开发\u002Fagent-crdt-synchronizer-ruflo-main",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill agent-crdt-synchronizer",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill agent-crdt-synchronizer",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill agent-crdt-synchronizer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F05-技能与代理开发\u002Fagent-crdt-synchronizer-ruflo-main\u002FSKILL.md",true,[],[47,55,60,67,74,81],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":54},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":56,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":54},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":54},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":54},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":54},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":54},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]