事件溯源 logo

事件溯源

Organization
microwind
事件溯源

将状态变更存储为不可变的事件序列,通过重播事件重建状态,提供完整的审计追踪。

Overview

Publishermicrowind
Repositoryai-skills
Skill name事件溯源
Stars
93
Forks
25
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by microwind on GitHub. Read the source before you install it.

Installation

Install the 事件溯源 AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/microwind/ai-skills/tree/main/domain-driven-design/event-sourcing
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/microwind/ai-skills.git /tmp/ai-skills
mkdir -p .claude/skills
cp -r /tmp/ai-skills/domain-driven-design/event-sourcing .claude/skills/microwind-68
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable 事件溯源 in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads 事件溯源 on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so 事件溯源 is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

事件溯源 (Event Sourcing)

概述

事件溯源是一种持久化模式:不存储当前状态,而是存储导致状态变化的所有事件。当前状态通过重播事件序列来重建。

传统方式:只存最终状态
Account { balance: 850 }

事件溯源:存储所有变化
Event 1: AccountOpened { amount: 1000 }
Event 2: MoneyWithdrawn { amount: 200 }
Event 3: MoneyDeposited { amount: 50 }
→ 重播后: balance = 1000 - 200 + 50 = 850

代码示例

java
// 事件定义
public sealed interface AccountEvent {
    record AccountOpened(String accountId, BigDecimal initialBalance, Instant at) implements AccountEvent {}
    record MoneyDeposited(String accountId, BigDecimal amount, Instant at) implements AccountEvent {}
    record MoneyWithdrawn(String accountId, BigDecimal amount, Instant at) implements AccountEvent {}
}

// 聚合通过事件重建状态
public class Account {
    private String id;
    private BigDecimal balance;
    private List<AccountEvent> uncommittedEvents = new ArrayList<>();

    // 从事件历史重建
    public static Account fromHistory(List<AccountEvent> history) {
        Account account = new Account();
        history.forEach(account::apply);
        return account;
    }

    // 业务操作产生事件
    public void deposit(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new DomainException("金额必须为正");
        }
        raiseEvent(new MoneyDeposited(id, amount, Instant.now()));
    }

    public void withdraw(BigDecimal amount) {
        if (amount.compareTo(balance) > 0) {
            throw new DomainException("余额不足");
        }
        raiseEvent(new MoneyWithdrawn(id, amount, Instant.now()));
    }

    // 应用事件改变状态
    private void apply(AccountEvent event) {
        switch (event) {
            case AccountOpened e -> {
                this.id = e.accountId();
                this.balance = e.initialBalance();
            }
            case MoneyDeposited e -> this.balance = balance.add(e.amount());
            case MoneyWithdrawn e -> this.balance = balance.subtract(e.amount());
        }
    }

    private void raiseEvent(AccountEvent event) {
        apply(event);
        uncommittedEvents.add(event);
    }
}

// 事件存储
public class EventStore {
    public void save(String aggregateId, List<AccountEvent> events, long expectedVersion) {
        // 追加事件到事件流(乐观锁检查版本号)
        for (AccountEvent event : events) {
            db.append("events", Map.of(
                "aggregate_id", aggregateId,
                "version", ++expectedVersion,
                "event_type", event.getClass().getSimpleName(),
                "data", serialize(event),
                "timestamp", Instant.now()
            ));
        }
    }

    public List<AccountEvent> load(String aggregateId) {
        return db.query("events")
            .where("aggregate_id", aggregateId)
            .orderBy("version")
            .map(this::deserialize);
    }
}
python
# Python 事件溯源
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal

@dataclass(frozen=True)
class AccountOpened:
    account_id: str
    initial_balance: Decimal
    at: datetime

@dataclass(frozen=True)
class MoneyDeposited:
    account_id: str
    amount: Decimal
    at: datetime

class Account:
    def __init__(self):
        self.id = None
        self.balance = Decimal(0)
        self._uncommitted = []

    @classmethod
    def from_history(cls, events: list) -> "Account":
        account = cls()
        for event in events:
            account._apply(event)
        return account

    def deposit(self, amount: Decimal):
        if amount <= 0:
            raise DomainError("金额必须为正")
        self._raise(MoneyDeposited(self.id, amount, datetime.now()))

    def _apply(self, event):
        match event:
            case AccountOpened():
                self.id = event.account_id
                self.balance = event.initial_balance
            case MoneyDeposited():
                self.balance += event.amount

    def _raise(self, event):
        self._apply(event)
        self._uncommitted.append(event)

快照优化

事件很多时重播很慢,用快照加速:

Events: [E1, E2, E3, ..., E999, E1000]
                      ↑
Snapshot at E500: { balance: 5000 }

重建时:从 Snapshot 开始 + 重播 E501-E1000
而非:重播全部 1000 个事件

优缺点

✅ 优点

  1. 完整审计 — 所有变更历史可追溯
  2. 时间旅行 — 可重建任意时间点的状态
  3. 事件驱动 — 天然支持事件驱动架构
  4. 无数据丢失 — 只追加不修改不删除
  5. 调试友好 — 可重播事件复现问题

❌ 缺点

  1. 查询困难 — 需要配合 CQRS 构建读模型
  2. 事件演化 — 事件格式变更需要版本管理
  3. 学习曲线 — 思维方式与传统 CRUD 不同
  4. 存储增长 — 事件不断累积需要快照和归档

与其他DDD概念的关系

概念关系
领域事件事件溯源的基础是领域事件
CQRS事件溯源几乎总是配合 CQRS 使用
读模型优化从事件投影构建读模型
聚合根聚合通过事件重建状态

总结

核心:存储事件序列而非当前状态,通过重播事件重建状态。

适用:需要完整审计、时间旅行、事件驱动的场景。通常配合 CQRS 使用。

Frequently asked questions

What does the 事件溯源 AI skill do?

将状态变更存储为不可变的事件序列,通过重播事件重建状态,提供完整的审计追踪。

Why use 事件溯源 on TypingMind?

Because you install it once and use it with any model. 事件溯源 is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install 事件溯源 in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/microwind/ai-skills/tree/main/domain-driven-design/event-sourcing. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use 事件溯源?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with 事件溯源?

As many as you like. As long as a model supports skills, you can use 事件溯源 with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the 事件溯源 AI skill free?

It is published on GitHub by microwind. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇