[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6JQA6APEWWDWGC0ZP7C8EFB":3,"skill-same:01M6JQA6APEWWDWGC0ZP7C8EFB":83},{"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":23,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":47,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M6JQA6APEWWDWGC0ZP7C8EFB","saga_orchestration",null,"Patterns for managing distributed transactions and long-running business processes.","LongLeo287\u002FOmniClaw","LongLeo287","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F141803367?v=4","01M6JK75C62VCNZKR5BRZ386YV","LongLeo","01M6JK75GQ78TSP1ZPXNKK3MCH",9,"MIT","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fsaga_orchestration\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35],"orchestration","saga orchestration","saga","distributed","transactions","business","community","patterns","long","processes","for","unknown","2026-11-10 10:12:30",false,"---\nname: saga_orchestration\n\ndescription: \"Patterns for managing distributed transactions and long-running business processes.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Saga Orchestration\n\nPatterns for managing distributed transactions and long-running business processes.\n\n## Do not use this skill when\n\n- The task is unrelated to saga orchestration\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## Use this skill when\n\n- Coordinating multi-service transactions\n- Implementing compensating transactions\n- Managing long-running business workflows\n- Handling failures in distributed systems\n- Building order fulfillment processes\n- Implementing approval workflows\n\n## Core Concepts\n\n### 1. Saga Types\n\n```\nChoreography                    Orchestration\n┌─────┐  ┌─────┐  ┌─────┐     ┌─────────────┐\n│Svc A│─►│Svc B│─►│Svc C│     │ Orchestrator│\n└─────┘  └─────┘  └─────┘     └──────┬──────┘\n   │        │        │               │\n   ▼        ▼        ▼         ┌─────┼─────┐\n Event    Event    Event       ▼     ▼     ▼\n                            ┌────┐┌────┐┌────┐\n                            │Svc1││Svc2││Svc3│\n                            └────┘└────┘└────┘\n```\n\n### 2. Saga Execution States\n\n| State            | Description                    |\n| ---------------- | ------------------------------ |\n| **Started**      | Saga initiated                 |\n| **Pending**      | Waiting for step completion    |\n| **Compensating** | Rolling back due to failure    |\n| **Completed**    | All steps succeeded            |\n| **Failed**       | Saga failed after compensation |\n\n## Templates\n\n### Template 1: Saga Orchestrator Base\n\n```python\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import List, Dict, Any, Optional\nfrom datetime import datetime\nimport uuid\n\nclass SagaState(Enum):\n    STARTED = \"started\"\n    PENDING = \"pending\"\n    COMPENSATING = \"compensating\"\n    COMPLETED = \"completed\"\n    FAILED = \"failed\"\n\n\n@dataclass\nclass SagaStep:\n    name: str\n    action: str\n    compensation: str\n    status: str = \"pending\"\n    result: Optional[Dict] = None\n    error: Optional[str] = None\n    executed_at: Optional[datetime] = None\n    compensated_at: Optional[datetime] = None\n\n\n@dataclass\nclass Saga:\n    saga_id: str\n    saga_type: str\n    state: SagaState\n    data: Dict[str, Any]\n    steps: List[SagaStep]\n    current_step: int = 0\n    created_at: datetime = field(default_factory=datetime.utcnow)\n    updated_at: datetime = field(default_factory=datetime.utcnow)\n\n\nclass SagaOrchestrator(ABC):\n    \"\"\"Base class for saga orchestrators.\"\"\"\n\n    def __init__(self, saga_store, event_publisher):\n        self.saga_store = saga_store\n        self.event_publisher = event_publisher\n\n    @abstractmethod\n    def define_steps(self, data: Dict) -> List[SagaStep]:\n        \"\"\"Define the saga steps.\"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def saga_type(self) -> str:\n        \"\"\"Unique saga type identifier.\"\"\"\n        pass\n\n    async def start(self, data: Dict) -> Saga:\n        \"\"\"Start a new saga.\"\"\"\n        saga = Saga(\n            saga_id=str(uuid.uuid4()),\n            saga_type=self.saga_type,\n            state=SagaState.STARTED,\n            data=data,\n            steps=self.define_steps(data)\n        )\n        await self.saga_store.save(saga)\n        await self._execute_next_step(saga)\n        return saga\n\n    async def handle_step_completed(self, saga_id: str, step_name: str, result: Dict):\n        \"\"\"Handle successful step completion.\"\"\"\n        saga = await self.saga_store.get(saga_id)\n\n        # Update step\n        for step in saga.steps:\n            if step.name == step_name:\n                step.status = \"completed\"\n                step.result = result\n                step.executed_at = datetime.utcnow()\n                break\n\n        saga.current_step += 1\n        saga.updated_at = datetime.utcnow()\n\n        # Check if saga is complete\n        if saga.current_step >= len(saga.steps):\n            saga.state = SagaState.COMPLETED\n            await self.saga_store.save(saga)\n            await self._on_saga_completed(saga)\n        else:\n            saga.state = SagaState.PENDING\n            await self.saga_store.save(saga)\n            await self._execute_next_step(saga)\n\n    async def handle_step_failed(self, saga_id: str, step_name: str, error: str):\n        \"\"\"Handle step failure - start compensation.\"\"\"\n        saga = await self.saga_store.get(saga_id)\n\n        # Mark step as failed\n        for step in saga.steps:\n            if step.name == step_name:\n                step.status = \"failed\"\n                step.error = error\n                break\n\n        saga.state = SagaState.COMPENSATING\n        saga.updated_at = datetime.utcnow()\n        await self.saga_store.save(saga)\n\n        # Start compensation from current step backwards\n        await self._compensate(saga)\n\n    async def _execute_next_step(self, saga: Saga):\n        \"\"\"Execute the next step in the saga.\"\"\"\n        if saga.current_step >= len(saga.steps):\n            return\n\n        step = saga.steps[saga.current_step]\n        step.status = \"executing\"\n        await self.saga_store.save(saga)\n\n        # Publish command to execute step\n        await self.event_publisher.publish(\n            step.action,\n            {\n                \"saga_id\": saga.saga_id,\n                \"step_name\": step.name,\n                **saga.data\n            }\n        )\n\n    async def _compensate(self, saga: Saga):\n        \"\"\"Execute compensation for completed steps.\"\"\"\n        # Compensate in reverse order\n        for i in range(saga.current_step - 1, -1, -1):\n            step = saga.steps[i]\n            if step.status == \"completed\":\n                step.status = \"compensating\"\n                await self.saga_store.save(saga)\n\n                await self.event_publisher.publish(\n                    step.compensation,\n                    {\n                        \"saga_id\": saga.saga_id,\n                        \"step_name\": step.name,\n                        \"original_result\": step.result,\n                        **saga.data\n                    }\n                )\n\n    async def handle_compensation_completed(self, saga_id: str, step_name: str):\n        \"\"\"Handle compensation completion.\"\"\"\n        saga = await self.saga_store.get(saga_id)\n\n        for step in saga.steps:\n            if step.name == step_name:\n                step.status = \"compensated\"\n                step.compensated_at = datetime.utcnow()\n                break\n\n        # Check if all compensations complete\n        all_compensated = all(\n            s.status in (\"compensated\", \"pending\", \"failed\")\n            for s in saga.steps\n        )\n\n        if all_compensated:\n            saga.state = SagaState.FAILED\n            await self._on_saga_failed(saga)\n\n        await self.saga_store.save(saga)\n\n    async def _on_saga_completed(self, saga: Saga):\n        \"\"\"Called when saga completes successfully.\"\"\"\n        await self.event_publisher.publish(\n            f\"{self.saga_type}Completed\",\n            {\"saga_id\": saga.saga_id, **saga.data}\n        )\n\n    async def _on_saga_failed(self, saga: Saga):\n        \"\"\"Called when saga fails after compensation.\"\"\"\n        await self.event_publisher.publish(\n            f\"{self.saga_type}Failed\",\n            {\"saga_id\": saga.saga_id, \"error\": \"Saga failed\", **saga.data}\n        )\n```\n\n### Template 2: Order Fulfillment Saga\n\n```python\nclass OrderFulfillmentSaga(SagaOrchestrator):\n    \"\"\"Orchestrates order fulfillment across services.\"\"\"\n\n    @property\n    def saga_type(self) -> str:\n        return \"OrderFulfillment\"\n\n    def define_steps(self, data: Dict) -> List[SagaStep]:\n        return [\n            SagaStep(\n                name=\"reserve_inventory\",\n                action=\"InventoryService.ReserveItems\",\n                compensation=\"InventoryService.ReleaseReservation\"\n            ),\n            SagaStep(\n                name=\"process_payment\",\n                action=\"PaymentService.ProcessPayment\",\n                compensation=\"PaymentService.RefundPayment\"\n            ),\n            SagaStep(\n                name=\"create_shipment\",\n                action=\"ShippingService.CreateShipment\",\n                compensation=\"ShippingService.CancelShipment\"\n            ),\n            SagaStep(\n                name=\"send_confirmation\",\n                action=\"NotificationService.SendOrderConfirmation\",\n                compensation=\"NotificationService.SendCancellationNotice\"\n            )\n        ]\n\n\n# Usage\nasync def create_order(order_data: Dict):\n    saga = OrderFulfillmentSaga(saga_store, event_publisher)\n    return await saga.start({\n        \"order_id\": order_data[\"order_id\"],\n        \"customer_id\": order_data[\"customer_id\"],\n        \"items\": order_data[\"items\"],\n        \"payment_method\": order_data[\"payment_method\"],\n        \"shipping_address\": order_data[\"shipping_address\"]\n    })\n\n\n# Event handlers in each service\nclass InventoryService:\n    async def handle_reserve_items(self, command: Dict):\n        try:\n            # Reserve inventory\n            reservation = await self.reserve(\n                command[\"items\"],\n                command[\"order_id\"]\n            )\n            # Report success\n            await self.event_publisher.publish(\n                \"SagaStepCompleted\",\n                {\n                    \"saga_id\": command[\"saga_id\"],\n                    \"step_name\": \"reserve_inventory\",\n                    \"result\": {\"reservation_id\": reservation.id}\n                }\n            )\n        except InsufficientInventoryError as e:\n            await self.event_publisher.publish(\n                \"SagaStepFailed\",\n                {\n                    \"saga_id\": command[\"saga_id\"],\n                    \"step_name\": \"reserve_inventory\",\n                    \"error\": str(e)\n                }\n            )\n\n    async def handle_release_reservation(self, command: Dict):\n        # Compensating action\n        await self.release_reservation(\n            command[\"original_result\"][\"reservation_id\"]\n        )\n        await self.event_publisher.publish(\n            \"SagaCompensationCompleted\",\n            {\n                \"saga_id\": command[\"saga_id\"],\n                \"step_name\": \"reserve_inventory\"\n            }\n        )\n```\n\n### Template 3: Choreography-Based Saga\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, Any\nimport asyncio\n\n@dataclass\nclass SagaContext:\n    \"\"\"Passed through choreographed saga events.\"\"\"\n    saga_id: str\n    step: int\n    data: Dict[str, Any]\n    completed_steps: list\n\n\nclass OrderChoreographySaga:\n    \"\"\"Choreography-based saga using events.\"\"\"\n\n    def __init__(self, event_bus):\n        self.event_bus = event_bus\n        self._register_handlers()\n\n    def _register_handlers(self):\n        self.event_bus.subscribe(\"OrderCreated\", self._on_order_created)\n        self.event_bus.subscribe(\"InventoryReserved\", self._on_inventory_reserved)\n        self.event_bus.subscribe(\"PaymentProcessed\", self._on_payment_processed)\n        self.event_bus.subscribe(\"ShipmentCreated\", self._on_shipment_created)\n\n        # Compensation handlers\n        self.event_bus.subscribe(\"PaymentFailed\", self._on_payment_failed)\n        self.event_bus.subscribe(\"ShipmentFailed\", self._on_shipment_failed)\n\n    async def _on_order_created(self, event: Dict):\n        \"\"\"Step 1: Order created, reserve inventory.\"\"\"\n        await self.event_bus.publish(\"ReserveInventory\", {\n            \"saga_id\": event[\"order_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"items\": event[\"items\"]\n        })\n\n    async def _on_inventory_reserved(self, event: Dict):\n        \"\"\"Step 2: Inventory reserved, process payment.\"\"\"\n        await self.event_bus.publish(\"ProcessPayment\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"amount\": event[\"total_amount\"],\n            \"reservation_id\": event[\"reservation_id\"]\n        })\n\n    async def _on_payment_processed(self, event: Dict):\n        \"\"\"Step 3: Payment done, create shipment.\"\"\"\n        await self.event_bus.publish(\"CreateShipment\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"payment_id\": event[\"payment_id\"]\n        })\n\n    async def _on_shipment_created(self, event: Dict):\n        \"\"\"Step 4: Complete - send confirmation.\"\"\"\n        await self.event_bus.publish(\"OrderFulfilled\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"tracking_number\": event[\"tracking_number\"]\n        })\n\n    # Compensation handlers\n    async def _on_payment_failed(self, event: Dict):\n        \"\"\"Payment failed - release inventory.\"\"\"\n        await self.event_bus.publish(\"ReleaseInventory\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"reservation_id\": event[\"reservation_id\"]\n        })\n        await self.event_bus.publish(\"OrderFailed\", {\n            \"order_id\": event[\"order_id\"],\n            \"reason\": \"Payment failed\"\n        })\n\n    async def _on_shipment_failed(self, event: Dict):\n        \"\"\"Shipment failed - refund payment and release inventory.\"\"\"\n        await self.event_bus.publish(\"RefundPayment\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"payment_id\": event[\"payment_id\"]\n        })\n        await self.event_bus.publish(\"ReleaseInventory\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"reservation_id\": event[\"reservation_id\"]\n        })\n```\n\n### Template 4: Saga with Timeouts\n\n```python\nclass TimeoutSagaOrchestrator(SagaOrchestrator):\n    \"\"\"Saga orchestrator with step timeouts.\"\"\"\n\n    def __init__(self, saga_store, event_publisher, scheduler):\n        super().__init__(saga_store, event_publisher)\n        self.scheduler = scheduler\n\n    async def _execute_next_step(self, saga: Saga):\n        if saga.current_step >= len(saga.steps):\n            return\n\n        step = saga.steps[saga.current_step]\n        step.status = \"executing\"\n        step.timeout_at = datetime.utcnow() + timedelta(minutes=5)\n        await self.saga_store.save(saga)\n\n        # Schedule timeout check\n        await self.scheduler.schedule(\n            f\"saga_timeout_{saga.saga_id}_{step.name}\",\n            self._check_timeout,\n            {\"saga_id\": saga.saga_id, \"step_name\": step.name},\n            run_at=step.timeout_at\n        )\n\n        await self.event_publisher.publish(\n            step.action,\n            {\"saga_id\": saga.saga_id, \"step_name\": step.name, **saga.data}\n        )\n\n    async def _check_timeout(self, data: Dict):\n        \"\"\"Check if step has timed out.\"\"\"\n        saga = await self.saga_store.get(data[\"saga_id\"])\n        step = next(s for s in saga.steps if s.name == data[\"step_name\"])\n\n        if step.status == \"executing\":\n            # Step timed out - fail it\n            await self.handle_step_failed(\n                data[\"saga_id\"],\n                data[\"step_name\"],\n                \"Step timed out\"\n            )\n```\n\n## Durable Execution Alternative\n\nThe templates above build saga infrastructure from scratch — saga stores, event publishers, compensation tracking. **Durable execution frameworks** (like DBOS) eliminate much of this boilerplate: the workflow runtime automatically persists state to a database, retries failed steps, and resumes from the last checkpoint after crashes. Instead of building a `SagaOrchestrator` base class, you write a workflow function with steps — the framework handles persistence, crash recovery, and exactly-once execution semantics. Consider durable execution when you want saga-like reliability without managing the coordination infrastructure yourself.\n\n## Best Practices\n\n### Do's\n\n- **Make steps idempotent** - Safe to retry\n- **Design compensations carefully** - They must work\n- **Use correlation IDs** - For tracing across services\n- **Implement timeouts** - Don't wait forever\n- **Log everything** - For debugging failures\n\n### Don'ts\n\n- **Don't assume instant completion** - Sagas take time\n- **Don't skip compensation testing** - Most critical part\n- **Don't couple services** - Use async messaging\n- **Don't ignore partial failures** - Handle gracefully\n\n## Related Skills\n\nWorks well with: `event-sourcing-architect`, `workflow-automation`, `dbos-*`\n\n## Resources\n\n- [Saga Pattern](https:\u002F\u002Fmicroservices.io\u002Fpatterns\u002Fdata\u002Fsaga.html)\n- [Designing Data-Intensive Applications](https:\u002F\u002Fdataintensive.net\u002F)\n","# Saga Orchestration\n\nPatterns for managing distributed transactions and long-running business processes.\n\n## Do not use this skill when\n\n- The task is unrelated to saga orchestration\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## Use this skill when\n\n- Coordinating multi-service transactions\n- Implementing compensating transactions\n- Managing long-running business workflows\n- Handling failures in distributed systems\n- Building order fulfillment processes\n- Implementing approval workflows\n\n## Core Concepts\n\n### 1. Saga Types\n\n```\nChoreography                    Orchestration\n┌─────┐  ┌─────┐  ┌─────┐     ┌─────────────┐\n│Svc A│─►│Svc B│─►│Svc C│     │ Orchestrator│\n└─────┘  └─────┘  └─────┘     └──────┬──────┘\n   │        │        │               │\n   ▼        ▼        ▼         ┌─────┼─────┐\n Event    Event    Event       ▼     ▼     ▼\n                            ┌────┐┌────┐┌────┐\n                            │Svc1││Svc2││Svc3│\n                            └────┘└────┘└────┘\n```\n\n### 2. Saga Execution States\n\n| State            | Description                    |\n| ---------------- | ------------------------------ |\n| **Started**      | Saga initiated                 |\n| **Pending**      | Waiting for step completion    |\n| **Compensating** | Rolling back due to failure    |\n| **Completed**    | All steps succeeded            |\n| **Failed**       | Saga failed after compensation |\n\n## Templates\n\n### Template 1: Saga Orchestrator Base\n\n```python\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import List, Dict, Any, Optional\nfrom datetime import datetime\nimport uuid\n\nclass SagaState(Enum):\n    STARTED = \"started\"\n    PENDING = \"pending\"\n    COMPENSATING = \"compensating\"\n    COMPLETED = \"completed\"\n    FAILED = \"failed\"\n\n\n@dataclass\nclass SagaStep:\n    name: str\n    action: str\n    compensation: str\n    status: str = \"pending\"\n    result: Optional[Dict] = None\n    error: Optional[str] = None\n    executed_at: Optional[datetime] = None\n    compensated_at: Optional[datetime] = None\n\n\n@dataclass\nclass Saga:\n    saga_id: str\n    saga_type: str\n    state: SagaState\n    data: Dict[str, Any]\n    steps: List[SagaStep]\n    current_step: int = 0\n    created_at: datetime = field(default_factory=datetime.utcnow)\n    updated_at: datetime = field(default_factory=datetime.utcnow)\n\n\nclass SagaOrchestrator(ABC):\n    \"\"\"Base class for saga orchestrators.\"\"\"\n\n    def __init__(self, saga_store, event_publisher):\n        self.saga_store = saga_store\n        self.event_publisher = event_publisher\n\n    @abstractmethod\n    def define_steps(self, data: Dict) -> List[SagaStep]:\n        \"\"\"Define the saga steps.\"\"\"\n        pass\n\n    @property\n    @abstractmethod\n    def saga_type(self) -> str:\n        \"\"\"Unique saga type identifier.\"\"\"\n        pass\n\n    async def start(self, data: Dict) -> Saga:\n        \"\"\"Start a new saga.\"\"\"\n        saga = Saga(\n            saga_id=str(uuid.uuid4()),\n            saga_type=self.saga_type,\n            state=SagaState.STARTED,\n            data=data,\n            steps=self.define_steps(data)\n        )\n        await self.saga_store.save(saga)\n        await self._execute_next_step(saga)\n        return saga\n\n    async def handle_step_completed(self, saga_id: str, step_name: str, result: Dict):\n        \"\"\"Handle successful step completion.\"\"\"\n        saga = await self.saga_store.get(saga_id)\n\n        # Update step\n        for step in saga.steps:\n            if step.name == step_name:\n                step.status = \"completed\"\n                step.result = result\n                step.executed_at = datetime.utcnow()\n                break\n\n        saga.current_step += 1\n        saga.updated_at = datetime.utcnow()\n\n        # Check if saga is complete\n        if saga.current_step >= len(saga.steps):\n            saga.state = SagaState.COMPLETED\n            await self.saga_store.save(saga)\n            await self._on_saga_completed(saga)\n        else:\n            saga.state = SagaState.PENDING\n            await self.saga_store.save(saga)\n            await self._execute_next_step(saga)\n\n    async def handle_step_failed(self, saga_id: str, step_name: str, error: str):\n        \"\"\"Handle step failure - start compensation.\"\"\"\n        saga = await self.saga_store.get(saga_id)\n\n        # Mark step as failed\n        for step in saga.steps:\n            if step.name == step_name:\n                step.status = \"failed\"\n                step.error = error\n                break\n\n        saga.state = SagaState.COMPENSATING\n        saga.updated_at = datetime.utcnow()\n        await self.saga_store.save(saga)\n\n        # Start compensation from current step backwards\n        await self._compensate(saga)\n\n    async def _execute_next_step(self, saga: Saga):\n        \"\"\"Execute the next step in the saga.\"\"\"\n        if saga.current_step >= len(saga.steps):\n            return\n\n        step = saga.steps[saga.current_step]\n        step.status = \"executing\"\n        await self.saga_store.save(saga)\n\n        # Publish command to execute step\n        await self.event_publisher.publish(\n            step.action,\n            {\n                \"saga_id\": saga.saga_id,\n                \"step_name\": step.name,\n                **saga.data\n            }\n        )\n\n    async def _compensate(self, saga: Saga):\n        \"\"\"Execute compensation for completed steps.\"\"\"\n        # Compensate in reverse order\n        for i in range(saga.current_step - 1, -1, -1):\n            step = saga.steps[i]\n            if step.status == \"completed\":\n                step.status = \"compensating\"\n                await self.saga_store.save(saga)\n\n                await self.event_publisher.publish(\n                    step.compensation,\n                    {\n                        \"saga_id\": saga.saga_id,\n                        \"step_name\": step.name,\n                        \"original_result\": step.result,\n                        **saga.data\n                    }\n                )\n\n    async def handle_compensation_completed(self, saga_id: str, step_name: str):\n        \"\"\"Handle compensation completion.\"\"\"\n        saga = await self.saga_store.get(saga_id)\n\n        for step in saga.steps:\n            if step.name == step_name:\n                step.status = \"compensated\"\n                step.compensated_at = datetime.utcnow()\n                break\n\n        # Check if all compensations complete\n        all_compensated = all(\n            s.status in (\"compensated\", \"pending\", \"failed\")\n            for s in saga.steps\n        )\n\n        if all_compensated:\n            saga.state = SagaState.FAILED\n            await self._on_saga_failed(saga)\n\n        await self.saga_store.save(saga)\n\n    async def _on_saga_completed(self, saga: Saga):\n        \"\"\"Called when saga completes successfully.\"\"\"\n        await self.event_publisher.publish(\n            f\"{self.saga_type}Completed\",\n            {\"saga_id\": saga.saga_id, **saga.data}\n        )\n\n    async def _on_saga_failed(self, saga: Saga):\n        \"\"\"Called when saga fails after compensation.\"\"\"\n        await self.event_publisher.publish(\n            f\"{self.saga_type}Failed\",\n            {\"saga_id\": saga.saga_id, \"error\": \"Saga failed\", **saga.data}\n        )\n```\n\n### Template 2: Order Fulfillment Saga\n\n```python\nclass OrderFulfillmentSaga(SagaOrchestrator):\n    \"\"\"Orchestrates order fulfillment across services.\"\"\"\n\n    @property\n    def saga_type(self) -> str:\n        return \"OrderFulfillment\"\n\n    def define_steps(self, data: Dict) -> List[SagaStep]:\n        return [\n            SagaStep(\n                name=\"reserve_inventory\",\n                action=\"InventoryService.ReserveItems\",\n                compensation=\"InventoryService.ReleaseReservation\"\n            ),\n            SagaStep(\n                name=\"process_payment\",\n                action=\"PaymentService.ProcessPayment\",\n                compensation=\"PaymentService.RefundPayment\"\n            ),\n            SagaStep(\n                name=\"create_shipment\",\n                action=\"ShippingService.CreateShipment\",\n                compensation=\"ShippingService.CancelShipment\"\n            ),\n            SagaStep(\n                name=\"send_confirmation\",\n                action=\"NotificationService.SendOrderConfirmation\",\n                compensation=\"NotificationService.SendCancellationNotice\"\n            )\n        ]\n\n\n# Usage\nasync def create_order(order_data: Dict):\n    saga = OrderFulfillmentSaga(saga_store, event_publisher)\n    return await saga.start({\n        \"order_id\": order_data[\"order_id\"],\n        \"customer_id\": order_data[\"customer_id\"],\n        \"items\": order_data[\"items\"],\n        \"payment_method\": order_data[\"payment_method\"],\n        \"shipping_address\": order_data[\"shipping_address\"]\n    })\n\n\n# Event handlers in each service\nclass InventoryService:\n    async def handle_reserve_items(self, command: Dict):\n        try:\n            # Reserve inventory\n            reservation = await self.reserve(\n                command[\"items\"],\n                command[\"order_id\"]\n            )\n            # Report success\n            await self.event_publisher.publish(\n                \"SagaStepCompleted\",\n                {\n                    \"saga_id\": command[\"saga_id\"],\n                    \"step_name\": \"reserve_inventory\",\n                    \"result\": {\"reservation_id\": reservation.id}\n                }\n            )\n        except InsufficientInventoryError as e:\n            await self.event_publisher.publish(\n                \"SagaStepFailed\",\n                {\n                    \"saga_id\": command[\"saga_id\"],\n                    \"step_name\": \"reserve_inventory\",\n                    \"error\": str(e)\n                }\n            )\n\n    async def handle_release_reservation(self, command: Dict):\n        # Compensating action\n        await self.release_reservation(\n            command[\"original_result\"][\"reservation_id\"]\n        )\n        await self.event_publisher.publish(\n            \"SagaCompensationCompleted\",\n            {\n                \"saga_id\": command[\"saga_id\"],\n                \"step_name\": \"reserve_inventory\"\n            }\n        )\n```\n\n### Template 3: Choreography-Based Saga\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict, Any\nimport asyncio\n\n@dataclass\nclass SagaContext:\n    \"\"\"Passed through choreographed saga events.\"\"\"\n    saga_id: str\n    step: int\n    data: Dict[str, Any]\n    completed_steps: list\n\n\nclass OrderChoreographySaga:\n    \"\"\"Choreography-based saga using events.\"\"\"\n\n    def __init__(self, event_bus):\n        self.event_bus = event_bus\n        self._register_handlers()\n\n    def _register_handlers(self):\n        self.event_bus.subscribe(\"OrderCreated\", self._on_order_created)\n        self.event_bus.subscribe(\"InventoryReserved\", self._on_inventory_reserved)\n        self.event_bus.subscribe(\"PaymentProcessed\", self._on_payment_processed)\n        self.event_bus.subscribe(\"ShipmentCreated\", self._on_shipment_created)\n\n        # Compensation handlers\n        self.event_bus.subscribe(\"PaymentFailed\", self._on_payment_failed)\n        self.event_bus.subscribe(\"ShipmentFailed\", self._on_shipment_failed)\n\n    async def _on_order_created(self, event: Dict):\n        \"\"\"Step 1: Order created, reserve inventory.\"\"\"\n        await self.event_bus.publish(\"ReserveInventory\", {\n            \"saga_id\": event[\"order_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"items\": event[\"items\"]\n        })\n\n    async def _on_inventory_reserved(self, event: Dict):\n        \"\"\"Step 2: Inventory reserved, process payment.\"\"\"\n        await self.event_bus.publish(\"ProcessPayment\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"amount\": event[\"total_amount\"],\n            \"reservation_id\": event[\"reservation_id\"]\n        })\n\n    async def _on_payment_processed(self, event: Dict):\n        \"\"\"Step 3: Payment done, create shipment.\"\"\"\n        await self.event_bus.publish(\"CreateShipment\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"payment_id\": event[\"payment_id\"]\n        })\n\n    async def _on_shipment_created(self, event: Dict):\n        \"\"\"Step 4: Complete - send confirmation.\"\"\"\n        await self.event_bus.publish(\"OrderFulfilled\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"order_id\": event[\"order_id\"],\n            \"tracking_number\": event[\"tracking_number\"]\n        })\n\n    # Compensation handlers\n    async def _on_payment_failed(self, event: Dict):\n        \"\"\"Payment failed - release inventory.\"\"\"\n        await self.event_bus.publish(\"ReleaseInventory\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"reservation_id\": event[\"reservation_id\"]\n        })\n        await self.event_bus.publish(\"OrderFailed\", {\n            \"order_id\": event[\"order_id\"],\n            \"reason\": \"Payment failed\"\n        })\n\n    async def _on_shipment_failed(self, event: Dict):\n        \"\"\"Shipment failed - refund payment and release inventory.\"\"\"\n        await self.event_bus.publish(\"RefundPayment\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"payment_id\": event[\"payment_id\"]\n        })\n        await self.event_bus.publish(\"ReleaseInventory\", {\n            \"saga_id\": event[\"saga_id\"],\n            \"reservation_id\": event[\"reservation_id\"]\n        })\n```\n\n### Template 4: Saga with Timeouts\n\n```python\nclass TimeoutSagaOrchestrator(SagaOrchestrator):\n    \"\"\"Saga orchestrator with step timeouts.\"\"\"\n\n    def __init__(self, saga_store, event_publisher, scheduler):\n        super().__init__(saga_store, event_publisher)\n        self.scheduler = scheduler\n\n    async def _execute_next_step(self, saga: Saga):\n        if saga.current_step >= len(saga.steps):\n            return\n\n        step = saga.steps[saga.current_step]\n        step.status = \"executing\"\n        step.timeout_at = datetime.utcnow() + timedelta(minutes=5)\n        await self.saga_store.save(saga)\n\n        # Schedule timeout check\n        await self.scheduler.schedule(\n            f\"saga_timeout_{saga.saga_id}_{step.name}\",\n            self._check_timeout,\n            {\"saga_id\": saga.saga_id, \"step_name\": step.name},\n            run_at=step.timeout_at\n        )\n\n        await self.event_publisher.publish(\n            step.action,\n            {\"saga_id\": saga.saga_id, \"step_name\": step.name, **saga.data}\n        )\n\n    async def _check_timeout(self, data: Dict):\n        \"\"\"Check if step has timed out.\"\"\"\n        saga = await self.saga_store.get(data[\"saga_id\"])\n        step = next(s for s in saga.steps if s.name == data[\"step_name\"])\n\n        if step.status == \"executing\":\n            # Step timed out - fail it\n            await self.handle_step_failed(\n                data[\"saga_id\"],\n                data[\"step_name\"],\n                \"Step timed out\"\n            )\n```\n\n## Durable Execution Alternative\n\nThe templates above build saga infrastructure from scratch — saga stores, event publishers, compensation tracking. **Durable execution frameworks** (like DBOS) eliminate much of this boilerplate: the workflow runtime automatically persists state to a database, retries failed steps, and resumes from the last checkpoint after crashes. Instead of building a `SagaOrchestrator` base class, you write a workflow function with steps — the framework handles persistence, crash recovery, and exactly-once execution semantics. Consider durable execution when you want saga-like reliability without managing the coordination infrastructure yourself.\n\n## Best Practices\n\n### Do's\n\n- **Make steps idempotent** - Safe to retry\n- **Design compensations carefully** - They must work\n- **Use correlation IDs** - For tracing across services\n- **Implement timeouts** - Don't wait forever\n- **Log everything** - For debugging failures\n\n### Don'ts\n\n- **Don't assume instant completion** - Sagas take time\n- **Don't skip compensation testing** - Most critical part\n- **Don't couple services** - Use async messaging\n- **Don't ignore partial failures** - Handle gracefully\n\n## Related Skills\n\nWorks well with: `event-sourcing-architect`, `workflow-automation`, `dbos-*`\n\n## Resources\n\n- [Saga Pattern](https:\u002F\u002Fmicroservices.io\u002Fpatterns\u002Fdata\u002Fsaga.html)\n- [Designing Data-Intensive Applications](https:\u002F\u002Fdataintensive.net\u002F)\n",{"name":5,"risk":35,"source":30,"date_added":41,"description":7},"2026-02-27","main","c173cdffe08e788a99b91928a831b476b8434838","ecosystem\u002Fskills\u002Fsaga_orchestration",0,"https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw","https:\u002F\u002Fportfolio-longleo.vercel.app\u002Flabs\u002Fomniclaw.html","https:\u002F\u002Fgithub.com\u002FLongLeo287","https:\u002F\u002Fwww.facebook.com\u002FResourceRookie2023","2026-09-30 00:58:05",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add LongLeo287\u002FOmniClaw --skill saga_orchestration",{"tool":57,"command":58},"bunx","bunx skills add LongLeo287\u002FOmniClaw --skill saga_orchestration",{"tool":60,"command":61},"pnpm","pnpm dlx skills add LongLeo287\u002FOmniClaw --skill saga_orchestration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fsaga_orchestration\u002FSKILL.md",true,[65,71,75,79],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"_DIR_IDENTITY.md","REFERENCE","参考文档",158,"https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fsaga_orchestration\u002F_DIR_IDENTITY.md",{"path":72,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":73,"sourceHtmlUrl":74},"README.md",471,"https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fsaga_orchestration\u002FREADME.md",{"path":76,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":77,"sourceHtmlUrl":78},"resources\u002Fimplementation_playbook.md",859,"https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fsaga_orchestration\u002Fresources\u002Fimplementation_playbook.md",{"path":80,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":81,"sourceHtmlUrl":82},"schema.json",456,"https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fsaga_orchestration\u002Fschema.json",[84,123,144,171,187,214],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":102,"publishedAt":36},"01M6JR0KQP4MHT32TN40D9CBFX","UI-UX Pro Max","Advanced UI\u002FUX analysis and generation skills with data-driven patterns. Python scripts (core.py, search.py) for systematic UI pattern extraction, design system generation, and component search from curated data sources.","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fui_components\u002Fui_ux_pro_max\u002FSKILL.md",[90,93,94,99],{"categoryNo":91,"categoryName":92,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":95,"categoryName":96,"taxonomyType":97,"taxonomyTypeDesc":98},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",{"categoryNo":100,"categoryName":101,"taxonomyType":97,"taxonomyTypeDesc":98},"01JBSEEDCAT000000000000033","数据分析师",[103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122],"ux","ui","ui ux pro max","max","pro","ui ux","design","component","search","analysis","team","rd","ui-ux","active","systematic","scripts","pattern extraction","sources","advanced","data-driven",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":130,"publishedAt":36},"01M6JR0EF5AEQHP2FSTB57H05P","shadcn-ui","Expert guidance for integrating and building applications with shadcn\u002Fui components, including component discovery, installation, customization, and best practices.","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fui_components\u002Fshadcn_ui\u002FSKILL.md",[129],{"categoryNo":95,"categoryName":96,"taxonomyType":97,"taxonomyTypeDesc":98},[131,104,132,133,110,134,135,136,137,113,138,139,140,116,141,142,143,34],"shadcn","shadcn ui","components","core","best practices","applications","discovery","customization","guidance","expert","installation","ui components","with",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":153,"publishedAt":36},"01M6JR08F51BEN17RHFYX65WVE","zustand_store_ts","Create Zustand stores with TypeScript, subscribeWithSelector middleware, and proper state\u002Faction separation. Use when building React state management, creating global stores, or implementing reactive state patterns with Zustand.","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fzustand_store_ts\u002FSKILL.md",[150],{"categoryNo":151,"categoryName":152,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",[154,155,156,157,158,159,160,161,162,163,164,165,166,31,167,168,143,169,170],"zustand store ts","zustand","store","typescript","microsoft","react","create","state management","state","react state management","management","global","use","separation","middleware","action","implementing",{"skillNo":172,"name":155,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":36},"01M6JR00TDMVAFFCZXZ04AN7Q7","Zustand state management guide. Use when working with store code (src\u002Fstore\u002F**), implementing actions, managing state, or creating slices. Triggers on Zustand store development, state management questions, or action implementation.","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fzustand\u002FSKILL.md",[],[155,177,161,178,162,179,180,164,181,166,182,183,184,156,143,185,186,169,170],"development","code","actions","src","guide","implementation","zustand state","triggers","questions","zustand state management",{"skillNo":188,"name":189,"nameZh":6,"description":190,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":191,"categories":192,"keywords":197,"publishedAt":36},"01M6JQZSWV4KWJP112G6XHEP44","youtube_summarizer","Automatically fetch YouTube video transcripts, generate structured summaries, and send full transcripts to messaging platforms. Detects YouTube URLs and provides metadata, key insights, and downloadable transcripts.","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fyoutube_summarizer\u002FSKILL.md",[193,196],{"categoryNo":194,"categoryName":195,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213],"youtube","youtube summarizer","summarizer","generate","metadata","messaging","Video","fetch","telegram","transcription","summarization","structured","full","insights","transcripts","summaries",{"skillNo":215,"name":216,"nameZh":6,"description":217,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":218,"categories":219,"keywords":220,"publishedAt":36},"01M6JQZN3QJB6B77JGKJD62DQT","youtube_clipper","YouTube 视频智能剪辑工具。下载视频和字幕，AI 分析生成精细章节（几分钟级别）， 用户选择片段后自动剪辑、翻译字幕为中英双语、烧录字幕到视频，并生成总结文案。 使用场景：当用户需要剪辑 YouTube 视频、生成短视频片段、制作双语字幕版本时。 关键词：视频剪辑、YouTube、字幕翻译、双语字幕、视频下载、clip video","https:\u002F\u002Fgithub.com\u002FLongLeo287\u002FOmniClaw\u002Fblob\u002Fmain\u002Fecosystem\u002Fskills\u002Fyoutube_clipper\u002FSKILL.md",[],[198,221,222,204,223,224,225,226,227,228,229,230,231,232,233,234,235],"clipper","youtube clipper","Bash","下载","视频","生成","关键词","翻译","read","write","clip","总结","工具","文案","sonnet"]