Bladeren bron

refactor(docs): 删除DDD经典分层架构的详细文档文件

- 移除了1、DDD 经典分层架构目录结构.md文档
- 文档内容包括单体工程和微服务目录结构示例
- 包含DDD四层架构原则与依赖规则详细说明
- 涉及聚合、实体和值对象的核心概念介绍
- 清理过期或不再维护的设计文档内容
wandl-6A72h 3 maanden geleden
bovenliggende
commit
002ad8d4f9
100 gewijzigde bestanden met toevoegingen van 15286 en 2165 verwijderingen
  1. 243 539
      AWESOME_AGENT_SKILLS.md
  2. 142 398
      skills/ddd-skills/ddd-api-designer/SKILL.md
  3. 209 0
      skills/ddd-skills/ddd-api-designer/examples/01-BFF-aggregation-example.md
  4. 420 0
      skills/ddd-skills/ddd-api-designer/examples/02-api-version-migration.md
  5. 27 0
      skills/ddd-skills/ddd-api-designer/examples/03-inventory-api-design.md
  6. 26 0
      skills/ddd-skills/ddd-api-designer/examples/04-notification-api-design.md
  7. 316 0
      skills/ddd-skills/ddd-api-designer/examples/05-openapi-codegen-example.md
  8. 241 0
      skills/ddd-skills/ddd-api-designer/examples/06-order-api-design.md
  9. 282 0
      skills/ddd-skills/ddd-api-designer/examples/07-payment-api-design.md
  10. 32 0
      skills/ddd-skills/ddd-api-designer/examples/08-product-api-design.md
  11. 29 0
      skills/ddd-skills/ddd-api-designer/examples/09-search-api-design.md
  12. 216 0
      skills/ddd-skills/ddd-api-designer/examples/10-user-api-design.md
  13. 0 0
      skills/ddd-skills/ddd-api-designer/references/architecture/clean-ddd-hexagonal-hexagonal.md
  14. 0 0
      skills/ddd-skills/ddd-api-designer/references/architecture/partme-16-service-data-view.md
  15. 8 0
      skills/ddd-skills/ddd-api-designer/references/examples-ref/api-error-handling.md
  16. 0 0
      skills/ddd-skills/ddd-api-designer/references/examples-ref/data-object-transformation.md
  17. 7 0
      skills/ddd-skills/ddd-api-designer/references/examples-ref/event-driven-api.md
  18. 254 0
      skills/ddd-skills/ddd-api-designer/references/examples-ref/unified-response-format.md
  19. 190 0
      skills/ddd-skills/ddd-api-designer/references/migration/api-versioning-strategies.md
  20. 113 0
      skills/ddd-skills/ddd-api-designer/references/patterns/BFF-design-pattern.md
  21. 89 0
      skills/ddd-skills/ddd-api-designer/references/patterns/cqrs-api-design.md
  22. 9 0
      skills/ddd-skills/ddd-api-designer/references/patterns/data-access-api.md
  23. 162 0
      skills/ddd-skills/ddd-api-designer/references/patterns/idempotency-design.md
  24. 207 0
      skills/ddd-skills/ddd-api-designer/references/patterns/pagination-filtering-design.md
  25. 0 0
      skills/ddd-skills/ddd-api-designer/references/security/api-naming-conventions.md
  26. 10 0
      skills/ddd-skills/ddd-api-designer/references/security/api-rate-limiting.md
  27. 217 0
      skills/ddd-skills/ddd-api-designer/references/security/api-security-design.md
  28. 499 0
      skills/ddd-skills/ddd-api-designer/references/security/openapi-specification.md
  29. 0 183
      skills/ddd-skills/ddd-architecture-awesome/trace-report.md
  30. 165 341
      skills/ddd-skills/ddd-architecture-clean/SKILL.md
  31. 341 0
      skills/ddd-skills/ddd-architecture-clean/examples/01-order-entity.md
  32. 449 0
      skills/ddd-skills/ddd-architecture-clean/examples/02-create-order-usecase.md
  33. 425 0
      skills/ddd-skills/ddd-architecture-clean/examples/03-repository-implementation.md
  34. 460 0
      skills/ddd-skills/ddd-architecture-clean/examples/04-archunit-test.md
  35. 197 0
      skills/ddd-skills/ddd-architecture-clean/examples/05-domain-event-handling.md
  36. 151 0
      skills/ddd-skills/ddd-architecture-clean/examples/06-monolith-simple.md
  37. 199 0
      skills/ddd-skills/ddd-architecture-clean/examples/07-monolith-complex.md
  38. 176 0
      skills/ddd-skills/ddd-architecture-clean/examples/08-monolith-multi-module.md
  39. 168 0
      skills/ddd-skills/ddd-architecture-clean/examples/09-microservice-simple.md
  40. 204 0
      skills/ddd-skills/ddd-architecture-clean/examples/10-microservice-complex.md
  41. 156 0
      skills/ddd-skills/ddd-architecture-clean/examples/11-microservice-multi-module.md
  42. 261 0
      skills/ddd-skills/ddd-architecture-clean/examples/12-microservice-complex-multi.md
  43. 148 0
      skills/ddd-skills/ddd-architecture-clean/references/02-usecase-ports.md
  44. 271 0
      skills/ddd-skills/ddd-architecture-clean/references/03-interactors.md
  45. 314 0
      skills/ddd-skills/ddd-architecture-clean/references/04-adapters.md
  46. 359 0
      skills/ddd-skills/ddd-architecture-clean/references/05-framework-config.md
  47. 294 0
      skills/ddd-skills/ddd-architecture-clean/references/06-dependency-rules.md
  48. 348 0
      skills/ddd-skills/ddd-architecture-clean/references/07-testing-strategy.md
  49. 371 0
      skills/ddd-skills/ddd-architecture-clean/references/08-migration-guide.md
  50. 89 0
      skills/ddd-skills/ddd-architecture-clean/references/09-architecture-principles.md
  51. 0 0
      skills/ddd-skills/ddd-architecture-clean/references/10-clean-ddd-hexagonal-hexagonal.md
  52. 0 0
      skills/ddd-skills/ddd-architecture-clean/references/11-ddd4j-clean-structure.md
  53. 0 0
      skills/ddd-skills/ddd-architecture-clean/references/12-directory-structure.md
  54. 155 340
      skills/ddd-skills/ddd-architecture-cola/SKILL.md
  55. 255 0
      skills/ddd-skills/ddd-architecture-cola/examples/01-quickstart-order.md
  56. 209 0
      skills/ddd-skills/ddd-architecture-cola/examples/02-customer-crud.md
  57. 115 0
      skills/ddd-skills/ddd-architecture-cola/examples/03-extension-point.md
  58. 198 0
      skills/ddd-skills/ddd-architecture-cola/examples/04-cqrs-separation.md
  59. 174 0
      skills/ddd-skills/ddd-architecture-cola/examples/05-archunit-config.md
  60. 122 0
      skills/ddd-skills/ddd-architecture-cola/examples/06-monolith-simple.md
  61. 242 0
      skills/ddd-skills/ddd-architecture-cola/examples/07-monolith-complex.md
  62. 180 0
      skills/ddd-skills/ddd-architecture-cola/examples/08-monolith-multi-module.md
  63. 141 0
      skills/ddd-skills/ddd-architecture-cola/examples/09-microservice-simple-monolith.md
  64. 231 0
      skills/ddd-skills/ddd-architecture-cola/examples/10-microservice-complex-monolith.md
  65. 209 0
      skills/ddd-skills/ddd-architecture-cola/examples/11-microservice-simple-multi-module.md
  66. 251 0
      skills/ddd-skills/ddd-architecture-cola/examples/12-microservice-complex-multi-module.md
  67. 0 0
      skills/ddd-skills/ddd-architecture-cola/examples/13-architecture-patterns.md
  68. 0 0
      skills/ddd-skills/ddd-architecture-cola/examples/14-single-module.md
  69. 0 0
      skills/ddd-skills/ddd-architecture-cola/examples/15-multi-module.md
  70. 0 0
      skills/ddd-skills/ddd-architecture-cola/examples/16-microservices.md
  71. 57 0
      skills/ddd-skills/ddd-architecture-cola/references/01-architecture-principles.md
  72. 117 0
      skills/ddd-skills/ddd-architecture-cola/references/02-project-scaffold.md
  73. 133 0
      skills/ddd-skills/ddd-architecture-cola/references/03-domain-layer.md
  74. 138 0
      skills/ddd-skills/ddd-architecture-cola/references/04-app-layer.md
  75. 125 0
      skills/ddd-skills/ddd-architecture-cola/references/05-adapter-layer.md
  76. 154 0
      skills/ddd-skills/ddd-architecture-cola/references/06-infrastructure.md
  77. 163 0
      skills/ddd-skills/ddd-architecture-cola/references/07-archunit-validation.md
  78. 213 0
      skills/ddd-skills/ddd-architecture-cola/references/08-cqrs-integration.md
  79. 0 0
      skills/ddd-skills/ddd-architecture-cola/references/09-ddd4j-cola-structure.md
  80. 0 0
      skills/ddd-skills/ddd-architecture-cola/references/10-directory-structure.md
  81. 105 0
      skills/ddd-skills/ddd-architecture-cola/references/14-ddd4j-scaffold.md
  82. 0 0
      skills/ddd-skills/ddd-architecture-cola/scripts/check_project.py
  83. 0 0
      skills/ddd-skills/ddd-architecture-cola/scripts/init_project.py
  84. 148 364
      skills/ddd-skills/ddd-architecture-doc/SKILL.md
  85. 108 0
      skills/ddd-skills/ddd-architecture-doc/examples/01-adr-examples.md
  86. 226 0
      skills/ddd-skills/ddd-architecture-doc/examples/02-c4-diagrams.md
  87. 144 0
      skills/ddd-skills/ddd-architecture-doc/examples/03-architecture-document.md
  88. 131 0
      skills/ddd-skills/ddd-architecture-doc/examples/04-domain-model-documentation.md
  89. 106 0
      skills/ddd-skills/ddd-architecture-doc/examples/05-maintenance-guide.md
  90. 0 0
      skills/ddd-skills/ddd-architecture-doc/examples/06-adr-examples.md
  91. 170 0
      skills/ddd-skills/ddd-architecture-doc/references/01-c4-examples.md
  92. 138 0
      skills/ddd-skills/ddd-architecture-doc/references/02-adr-templates.md
  93. 170 0
      skills/ddd-skills/ddd-architecture-doc/references/03-doc-templates.md
  94. 117 0
      skills/ddd-skills/ddd-architecture-doc/references/04-toolchain.md
  95. 110 0
      skills/ddd-skills/ddd-architecture-doc/references/05-team-templates.md
  96. 102 0
      skills/ddd-skills/ddd-architecture-doc/references/06-arch-decision-log.md
  97. 100 0
      skills/ddd-skills/ddd-architecture-doc/references/07-domain-model-doc.md
  98. 162 0
      skills/ddd-skills/ddd-architecture-doc/references/08-api-doc-patterns.md
  99. 100 0
      skills/ddd-skills/ddd-architecture-doc/references/09-trace-anti-patterns.md
  100. 73 0
      skills/ddd-skills/ddd-architecture-doc/references/10-faq-deep.md

+ 243 - 539
AWESOME_AGENT_SKILLS.md

@@ -1,539 +1,243 @@
-# Awesome Agent Skills
-
-_Generated at 2026-05-28T16:23:30.883477Z_
-
-## angular-skills
-- [angular](skills/angular-skills/angular) — Provides comprehensive guidance for Angular framework including components, modules, services, dependency injection, routing, forms, and ...
-
-## antd-skills
-- [ant-design-mini](skills/antd-skills/ant-design-mini) — Provides comprehensive guidance for Ant Design Mini component library for mini-programs including components, themes, and platform suppor...
-- [ant-design-mobile](skills/antd-skills/ant-design-mobile) — Provides comprehensive guidance for Ant Design Mobile component library including mobile components, themes, and platform adaptations. Us...
-- [ant-design-react](skills/antd-skills/ant-design-react) — Provides comprehensive guidance for Ant Design React component library including components, design system, themes, and TypeScript suppor...
-- [ant-design-vue](skills/antd-skills/ant-design-vue) — Provides comprehensive guidance for Ant Design Vue (AntDV) component library for Vue 3. Covers installation, usage, API reference, templa...
-
-## ascii-skills
-- [ascii-ansi-colorizer](skills/ascii-skills/ascii-ansi-colorizer) — Add an ANSI color layer to existing ASCII/plain-text output (gradient/rainbow/highlights) with alignment-safe rules and a required no-col...
-- [ascii-cli-logo-banner](skills/ascii-skills/ascii-cli-logo-banner) — Entry point for ASCII CLI banners. Choose the Python built-in font skill or the figlet.js/FIGfont skill depending on needs.
-- [ascii-cli-logo-banner-figletjs](skills/ascii-skills/ascii-cli-logo-banner-figletjs) — Generate TAAG/FIGlet-style ASCII art banners using figlet.js (FIGfont spec), with layout controls (horizontal/vertical layout, width, whi...
-- [ascii-cli-logo-banner-python](skills/ascii-skills/ascii-cli-logo-banner-python) — Generate copy-pastable ASCII banners with a built-in font (no external font deps), including compact fallback and optional ANSI 256 color...
-- [ascii-diagram-boxflow](skills/ascii-skills/ascii-diagram-boxflow) — Generate plain ASCII box-flow diagrams (boxes + arrows) for environments without renderers, with alignment rules and split strategies for...
-- [ascii-image-to-ascii](skills/ascii-skills/ascii-image-to-ascii) — Convert an image into ASCII art (readable + detail variants, width/charset controls, optional ANSI), for terminal previews and plain-text...
-- [ascii-mini-charts](skills/ascii-skills/ascii-mini-charts) — Generate ASCII mini charts (sparkline/bar/simple line) for plain-text trend inspection, with minimal + annotated variants and normalizati...
-- [ascii-motd-profile-banner](skills/ascii-skills/ascii-motd-profile-banner) — Generate ASCII-only MOTD / SSH login banner / shell profile welcome messages (short/long variants, quiet mode guidance, security notices).
-- [ascii-progress-and-spinner](skills/ascii-skills/ascii-progress-and-spinner) — Design ASCII progress bars and spinners for CLI UX (determinate/indeterminate, TTY single-line refresh, non-interactive log fallback) wit...
-- [ascii-table-renderer](skills/ascii-skills/ascii-table-renderer) — Render structured data as aligned ASCII tables (column width rules, truncate/wrap, border styles, compact/readable variants) for terminal...
-- [ascii-terminal-animation-pack](skills/ascii-skills/ascii-terminal-animation-pack) — Plan and generate terminal ASCII animations/screensaver-style output (FPS, refresh rules, loop policy, low-flicker guidance), with a stat...
-- [ascii-text-art-library](skills/ascii-skills/ascii-text-art-library) — Generate a reusable ASCII-only text template library (titles, dividers, notice boxes, slogans/CTA), with naming conventions and selection...
-- [cli-ascii-logo](skills/ascii-skills/cli-ascii-logo) — 生成 CLI 的 ASCII 艺术 Logo/Banner(支持 box drawing 边框、█ 块字符、ANSI 24-bit 渐变色)并提供可运行脚本与集成代码。适用于“做一个像 Spec Kit CLI 的终端 Logo / 彩色 ASCII banner / fi...
-
-## avue-skills
-- [avue](skills/avue-skills/avue) — Provides comprehensive guidance for Avue framework including CRUD operations, form components, and data management. Use when the user ask...
-- [avue-crud](skills/avue-skills/avue-crud) — Provides comprehensive guidance for Avue CRUD component including table operations, form handling, and data management. Use when the user...
-- [avue-form](skills/avue-skills/avue-form) — Provides comprehensive guidance for Avue Form component including form configuration, validation, and dynamic forms. Use when the user as...
-
-## base-skills
-- [skill-awesome](skills/base-skills/skill-awesome) — Turn scattered Agent Skills docs, specs, best practices, and skill examples into a curated, searchable “awesome list” in Markdown. Use wh...
-- [skill-official-evaluation](skills/base-skills/skill-official-evaluation) — Produce an evaluation conclusion for any Agent Skill based on official Agent Skills specifications and official best practices. Use when ...
-- [skill-trace-evaluation](skills/base-skills/skill-trace-evaluation) — Evaluate any Agent Skill using the SkillHub TRACE model (Trust, Reliability, Adaptability, Convention, Effectiveness) and produce a per-d...
-
-## build-skills
-- [dart-sass](skills/build-skills/dart-sass) — Provides comprehensive guidance for Dart Sass including Sass syntax, compilation, mixins, functions, and best practices. Use when the use...
-- [parcel](skills/build-skills/parcel) — Provides comprehensive guidance for Parcel bundler including zero-configuration setup, asset handling, hot module replacement, and produc...
-- [rollup](skills/build-skills/rollup) — Provides comprehensive guidance for Rollup bundler including configuration, plugins, code splitting, tree shaking, and library bundling. ...
-- [rspack](skills/build-skills/rspack) — Provides comprehensive guidance for Rspack bundler including configuration, plugins, loaders, optimization, and Webpack compatibility. Us...
-- [vite](skills/build-skills/vite) — Guidance for Vite using the official Guide, Config Reference, and Plugins pages. Use when the user needs Vite setup, configuration, or pl...
-- [webpack](skills/build-skills/webpack) — Provides comprehensive guidance for Webpack bundler including configuration, loaders, plugins, code splitting, optimization, and developm...
-
-## chart-skills
-- [lime-echart](skills/chart-skills/lime-echart) — Provides comprehensive guidance for Lime ECharts including chart creation, configuration, data visualization, and interactive charts. Use...
-- [ucharts](skills/chart-skills/ucharts) — Provides comprehensive guidance for uCharts chart library including chart types, data formats, chart configuration, and platform support....
-
-## cocos-skills
-- [cocos2d-x](skills/cocos-skills/cocos2d-x) — Provides comprehensive guidance for Cocos2d-x v4 game engine including scene graph, nodes, sprites, actions, animations, physics, renderi...
-
-## database-skills
-- [dbeaver](skills/database-skills/dbeaver) — Provides comprehensive guidance for DBeaver including database connection, SQL development, data management, and ER diagrams. Use when th...
-- [elasticsearch](skills/database-skills/elasticsearch) — Provides comprehensive guidance for Elasticsearch including indexing, searching, aggregations, mappings, and cluster management. Use when...
-- [oracle](skills/database-skills/oracle) — Provides comprehensive guidance for Oracle database including SQL, PL/SQL, database administration, and Oracle-specific features. Use whe...
-- [postgresql](skills/database-skills/postgresql) — Provides comprehensive guidance for PostgreSQL database including SQL syntax, advanced features, JSON support, full-text search, and perf...
-- [redis](skills/database-skills/redis) — Provides comprehensive guidance for Redis including data structures, commands, pub/sub, persistence, clustering, and caching patterns. Us...
-
-## ddd-skills
-- [clean-ddd-hexagonal](skills/ddd-skills/clean-ddd-hexagonal) — Proactively apply when designing APIs, microservices, or scalable backend structure. Triggers on DDD, Clean Architecture, Hexagonal, port...
-- [ddd-architecture-awesome](skills/ddd-skills/ddd-architecture-awesome) — Provides comprehensive guidance for Domain-Driven Design (DDD) concepts, strategic design, tactical design, and architecture patterns. Us...
-- [ddd-clean-architecture](skills/ddd-skills/ddd-clean-architecture) — Provides comprehensive guidance for clean architecture including layer separation, dependency rules, and architectural patterns. Use when...
-- [ddd-cola](skills/ddd-skills/ddd-cola) — Provides comprehensive guidance for COLA architecture including adapter layer, application layer, domain layer, and infrastructure layer....
-- [ddd-event-driven](skills/ddd-skills/ddd-event-driven) — Provides comprehensive guidance for event-driven architecture including domain events, event sourcing, CQRS, and event patterns. Use when...
-- [ddd-hexagonal-architecture](skills/ddd-skills/ddd-hexagonal-architecture) — Provides comprehensive guidance for hexagonal architecture including ports and adapters, domain isolation, and dependency inversion. Use ...
-- [ddd-microservices](skills/ddd-skills/ddd-microservices) — Provides comprehensive guidance for DDD in microservices including bounded contexts, service boundaries, event-driven architecture, and m...
-- [ddd4j-project-creator](skills/ddd-skills/ddd4j-project-creator) — |
-
-## design-skills
-- [adobe-xd](skills/design-skills/adobe-xd) — Provides comprehensive guidance for Adobe XD including design creation, prototyping, components, and collaboration. Use when the user ask...
-- [algorithmic-art](skills/design-skills/algorithmic-art) — Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating a...
-- [brand-guidelines](skills/design-skills/brand-guidelines) — Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. ...
-- [canvas-design](skills/design-skills/canvas-design) — Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a ...
-
-## dev-utils-skills
-- [agent-browser](skills/dev-utils-skills/agent-browser) — A comprehensive skill for using agent-browser, a CLI tool for browser automation designed for AI agents, developed by Vercel Labs. This s...
-- [code-generator](skills/dev-utils-skills/code-generator) — Provides comprehensive guidance for code generation including template-based generation, code scaffolding, and automated code creation. U...
-- [documentation-builder](skills/dev-utils-skills/documentation-builder) — Provides comprehensive guidance for building documentation including documentation generation, formatting, and documentation best practic...
-- [frontend-design](skills/dev-utils-skills/frontend-design) — Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web compone...
-- [java-code-comments](skills/dev-utils-skills/java-code-comments) — |
-- [maven-search](skills/dev-utils-skills/maven-search) — Provides comprehensive guidance for searching and retrieving Maven components from Maven Central Repository (https://repo1.maven.org/mave...
-- [mcp-builder](skills/dev-utils-skills/mcp-builder) — Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-des...
-- [mybatis-plus-generator](skills/dev-utils-skills/mybatis-plus-generator) — |
-- [test-writer](skills/dev-utils-skills/test-writer) — Provides comprehensive guidance for writing tests including test case creation, test structure, and testing best practices. Use when the ...
-- [theme-factory](skills/dev-utils-skills/theme-factory) — Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-se...
-- [web-artifacts-builder](skills/dev-utils-skills/web-artifacts-builder) — Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind C...
-- [webapp-testing](skills/dev-utils-skills/webapp-testing) — Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI...
-
-## devops-skills
-- [ansible](skills/devops-skills/ansible) — Provides comprehensive guidance for Ansible automation including playbooks, roles, inventory, and module usage. Use when the user asks ab...
-- [cloudformation](skills/devops-skills/cloudformation) — Provides comprehensive guidance for AWS CloudFormation including templates, stacks, parameters, and infrastructure automation. Use when t...
-- [github-actions](skills/devops-skills/github-actions) — Provides comprehensive guidance for GitHub Actions including workflow creation, actions, secrets, and automation. Use when the user asks ...
-- [gitlab-ci](skills/devops-skills/gitlab-ci) — Provides comprehensive guidance for GitLab CI/CD including pipeline configuration, runners, artifacts, and automation. Use when the user ...
-- [kubernetes](skills/devops-skills/kubernetes) — Provides comprehensive guidance for Kubernetes including pods, services, deployments, ingress, and cluster management. Use when the user ...
-- [terraform](skills/devops-skills/terraform) — Provides comprehensive guidance for Terraform including infrastructure as code, providers, modules, and state management. Use when the us...
-
-## docker-skills
-- [docker](skills/docker-skills/docker) — Provides comprehensive guidance for Docker including container creation, images, Dockerfile, docker-compose, and container management. Us...
-- [docker-compose](skills/docker-skills/docker-compose) — Provides comprehensive guidance for Docker Compose including multi-container applications, service definition, networking, and volumes. U...
-
-## document-skills
-- [api-doc-generator](skills/document-skills/api-doc-generator) — |
-- [doc-coauthoring](skills/document-skills/doc-coauthoring) — Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technica...
-- [full-stack-doc](skills/document-skills/full-stack-doc) — >
-- [mermaid](skills/document-skills/mermaid) — Provides comprehensive guidance for creating Mermaid diagrams. Mermaid is a JavaScript-based diagramming and charting tool that uses Mark...
-- [plantuml](skills/document-skills/plantuml) — Provides comprehensive guidance for creating PlantUML diagrams. PlantUML is a component that allows you to create various UML diagrams th...
-- [processon-diagram-generator](skills/document-skills/processon-diagram-generator) — |
-- [processon-mindmap](skills/document-skills/processon-mindmap) — Provides comprehensive guidance for ProcessOn mind mapping including mind map creation, node management, and collaboration. Use when the ...
-- [technical-blog-doc](skills/document-skills/technical-blog-doc) — >
-
-## drawio-skills
-- [drawio-architecture](skills/drawio-skills/drawio-architecture) — Provides comprehensive guidance for draw.io architecture diagrams including diagram creation, shapes, templates, and collaboration. Use w...
-- [drawio-flowchart](skills/drawio-skills/drawio-flowchart) — Provides comprehensive guidance for draw.io flowcharts including flowchart creation, shapes, connectors, and diagramming. Use when the us...
-
-## electron-skills
-- [electron](skills/electron-skills/electron) — Provides comprehensive guidance for Electron framework including main process, renderer process, IPC communication, window management, an...
-- [electron-egg](skills/electron-skills/electron-egg) — Provides comprehensive guidance for Electron EGG framework including project structure, main/renderer processes, IPC, window management, ...
-- [upgradeLink](skills/electron-skills/upgradeLink) — Provides comprehensive guidance for upgrade link management including upgrade link creation, configuration, and upgrade link best practic...
-
-## flutter-skills
-- [flutter](skills/flutter-skills/flutter) — Provides comprehensive guidance for Flutter development including widgets, state management, navigation, platform channels, and mobile ap...
-- [flutter-project-creater](skills/flutter-skills/flutter-project-creater) — Provides one-command project creation for Flutter including project initialization, configuration, and template generation. Use when the ...
-
-## go-skills
-- [gin](skills/go-skills/gin) — Provides comprehensive guidance for Gin Go framework including routing, middleware, request handling, JSON binding, and API development. ...
-- [gin-gonic](skills/go-skills/gin-gonic) — Provides comprehensive guidance for Gin-Gonic framework including routing, middleware, validation, and best practices. Use when the user ...
-
-## jimeng-skills
-- [jimeng-cli-image2image](skills/jimeng-skills/jimeng-cli-image2image) — Provides comprehensive guidance for executing image-to-image (图生图) editing via the dreamina CLI for 即梦 models 4.0+. Image-to-image CLI re...
-- [jimeng-cli-image2video](skills/jimeng-skills/jimeng-cli-image2video) — Provides comprehensive guidance for executing image-to-video (图生视频) generation via the dreamina CLI for 即梦. This skill covers 4 sub-comma...
-- [jimeng-cli-text2image](skills/jimeng-skills/jimeng-cli-text2image) — Provides comprehensive guidance for executing text-to-image generation via the dreamina CLI for 即梦 (Dreamina/Jimeng). The dreamina CLI is...
-- [jimeng-cli-text2video](skills/jimeng-skills/jimeng-cli-text2video) — Provides comprehensive guidance for executing text-to-video generation via the dreamina CLI for 即梦 Seedance 2.0 models. Video generation ...
-- [jimeng-prompt-image2image](skills/jimeng-skills/jimeng-prompt-image2image) — Provides comprehensive guidance for crafting image-to-image (图生图) edit prompts for 即梦 (Dreamina/Jimeng) models 4.0+. Uses a Keep/Change f...
-- [jimeng-prompt-image2video](skills/jimeng-skills/jimeng-prompt-image2video) — Provides comprehensive guidance for crafting image-to-video (图生视频) prompts for 即梦 (Dreamina/Jimeng) Seedance 2.0. Image-to-video prompts ...
-- [jimeng-prompt-text2image](skills/jimeng-skills/jimeng-prompt-text2image) — Provides comprehensive guidance for crafting text-to-image prompts for 即梦 (Dreamina/Jimeng) AI image generation. Use when the user wants ...
-- [jimeng-prompt-text2video](skills/jimeng-skills/jimeng-prompt-text2video) — "Provides comprehensive guidance for crafting text-to-video prompts for 即梦 (Dreamina/Jimeng) video models (视频3.0 Pro, Doubao Seedance 2.0...
-
-## journey
-- [ddd-api-designer](skills/ddd-skills/journey/ddd-api-designer) — 从领域模型到 API/契约设计(Journey)。基于命令/事件/读模型输出 OpenAPI、DTO 设计、错误码、事件契约(schemaVersion)与 BFF 编排边界建议。
-- [ddd-architecture-awesome](skills/ddd-skills/journey/ddd-architecture-awesome) — DDD 入门与适用性判断(Journey 入口)。当用户问“什么是 DDD”“要不要用 DDD”“DDD vs 三层”“充血模型”等,输出可执行的判断结论、学习路径与下一步技能推荐。
-- [ddd-architecture-doc](skills/ddd-skills/journey/ddd-architecture-doc) — 架构文档生成(Journey)。基于 DDD 交付物与代码结构,生成架构概览、ADR、C4(Context/Container/Component)、上下文地图与事件流说明。
-- [ddd-architecture-selector](skills/ddd-skills/journey/ddd-architecture-selector) — DDD 架构选型与边界策略(Journey)。当用户需要在 DDD 四层/六边形/整洁/COLA/CQRS/微服务拆分之间做选择时,输出结构化决策结果、目录模板与边界交付物清单。
-- [ddd-code-reviewer](skills/ddd-skills/journey/ddd-code-reviewer) — DDD 红线门禁与评分(Journey)。扫描/审查现有代码的分层依赖、领域纯净、聚合边界、事件治理与 DTO/DO/PO 穿层等反模式,输出 P0/P1/P2 违规清单与修复建议。
-- [ddd-cola-creator](skills/ddd-skills/journey/ddd-cola-creator) — COLA 工程骨架与目录生成指导(Journey)。输出 COLA 分层目录、模块依赖规则、聚合包示例与最小可运行骨架;不限定 ddd4j(如明确 ddd4j 则改用 ddd4j-project-creator)。
-- [ddd-cola-validator](skills/ddd-skills/journey/ddd-cola-validator) — COLA/分层依赖方向合规检查(Journey)。对项目分层职责与依赖方向做门禁,输出违规清单、严重级别与整改建议。
-- [ddd-cqrs-implementer](skills/ddd-skills/journey/ddd-cqrs-implementer) — CQRS 与读模型落地(Journey)。输出 CQRS 等级选择、读写模型边界、读模型/主题视图清单、投影同步机制与一致性 SLA。
-- [ddd-domain-modeling](skills/ddd-skills/journey/ddd-domain-modeling) — 事件风暴到领域模型的完整建模(Journey)。针对业务场景输出限界上下文、聚合、不变式、领域事件与“领域模型⇄代码模型映射表”等可验收产物。
-- [ddd-eventing-governance](skills/ddd-skills/journey/ddd-eventing-governance) — 事件驱动工程化治理(Journey)。把领域事件从“概念”落成“可运维机制”:Outbox、幂等、重试死信、补偿对账、版本兼容与可观测性。
-
-## mobile-native-skills
-- [android-kotlin](skills/mobile-native-skills/android-kotlin) — Provides comprehensive guidance for Android development with Kotlin including activities, fragments, views, lifecycle, navigation, and An...
-- [ios-swift](skills/mobile-native-skills/ios-swift) — Provides comprehensive guidance for iOS development with Swift including view controllers, views, navigation, lifecycle, and iOS app deve...
-
-## nodejs-skills
-- [express](skills/nodejs-skills/express) — Provides comprehensive guidance for Express.js framework including routing, middleware, request handling, templating, and API development...
-- [fastify](skills/nodejs-skills/fastify) — Provides comprehensive guidance for Fastify framework including routing, plugins, schemas, hooks, and performance optimization. Use when ...
-- [koa](skills/nodejs-skills/koa) — Provides comprehensive guidance for Koa.js framework including middleware, context, async/await patterns, and application structure. Use ...
-- [nestjs](skills/nodejs-skills/nestjs) — Provides comprehensive guidance for NestJS using the official documentation. Use when the user asks about NestJS architecture, controller...
-
-## nvm-skills
-- [nvm](skills/nvm-skills/nvm) — Guidance for installing, configuring, and using nvm (Node Version Manager) based on the official README. Use when the user needs to manag...
-- [nvm-defaults-and-nvmrc](skills/nvm-skills/nvm-defaults-and-nvmrc) — Define default Node versions and manage project-specific versions with .nvmrc and auto-use flows.
-- [nvm-docker-ci](skills/nvm-skills/nvm-docker-ci) — Cover nvm installation and usage in Docker images and CI/CD pipelines, including non-interactive shell loading.
-- [nvm-global-packages](skills/nvm-skills/nvm-global-packages) — Migrate global packages between Node versions and define a default global packages file for consistency.
-- [nvm-install](skills/nvm-skills/nvm-install) — Provide comprehensive guidance for installing and updating nvm from the official README, including install scripts, profile selection, an...
-- [nvm-mirror-and-auth](skills/nvm-skills/nvm-mirror-and-auth) — Configure Node.js binary mirrors and authentication headers for restricted or 10、Company Manger network environments.
-- [nvm-misc](skills/nvm-skills/nvm-misc) — Provide nvm overview, output color customization, tests, and automation examples like Ansible. Use when users ask for an nvm intro, color...
-- [nvm-project-meta](skills/nvm-skills/nvm-project-meta) — Provide nvm project metadata like maintainers, support policy, enterprise support, license, and copyright notice. Use when users ask abou...
-- [nvm-setup](skills/nvm-skills/nvm-setup) — Configure shell initialization and environment variables so nvm loads correctly across bash, zsh, and fish.
-- [nvm-shell-integration](skills/nvm-skills/nvm-shell-integration) — Enable deeper shell integration and auto-switching for nvm across bash, zsh, and fish.
-- [nvm-troubleshooting-linux](skills/nvm-skills/nvm-troubleshooting-linux) — Diagnose common nvm issues on Linux and WSL, including distro differences, profiles, and PATH errors.
-- [nvm-troubleshooting-macos](skills/nvm-skills/nvm-troubleshooting-macos) — Diagnose common nvm issues on macOS, including profile loading, PATH priority, and permissions.
-- [nvm-uninstall](skills/nvm-skills/nvm-uninstall) — Remove nvm cleanly, including NVM_DIR cleanup, profile edits, and PATH restoration.
-- [nvm-usage-basics](skills/nvm-skills/nvm-usage-basics) — Cover everyday nvm usage for installing, switching, and listing Node versions, including LTS and system node.
-- [nvm-verify](skills/nvm-skills/nvm-verify) — Verify nvm installation and diagnose PATH or profile loading issues after setup.
-
-## ocrmypdf-skills
-- [ocrmypdf](skills/ocrmypdf-skills/ocrmypdf) — OCRmyPDF core skill — add searchable OCR text layer to scanned PDFs, convert images to searchable PDFs, support 100+ languages via Tesser...
-- [ocrmypdf-api](skills/ocrmypdf-skills/ocrmypdf-api) — OCRmyPDF Python API and plugin skill — use OCRmyPDF programmatically from Python, integrate with applications, and extend with plugins (E...
-- [ocrmypdf-batch](skills/ocrmypdf-skills/ocrmypdf-batch) — OCRmyPDF batch processing skill — process multiple PDFs, Docker automation, shell scripting, and CI/CD integration. Use when the user nee...
-- [ocrmypdf-image](skills/ocrmypdf-skills/ocrmypdf-image) — OCRmyPDF image processing skill — deskew, rotate, clean, despeckle, remove border from scanned documents. Use when the user needs to impr...
-- [ocrmypdf-optimize](skills/ocrmypdf-skills/ocrmypdf-optimize) — OCRmyPDF optimization skill — compress PDFs, configure PDF/A output, JBIG2 encoding, and lossless optimization. Use when the user needs t...
-
-## openspec-skills
-- [openspec-apply](skills/openspec-skills/openspec-apply) — Implement tasks from the change using `/opsx:apply`, working through the task list and checking off items. Use when the user says "implem...
-- [openspec-archive](skills/openspec-skills/openspec-archive) — Archive a completed change with `/opsx:archive`, merging delta specs into main specs and preserving the change for history. Use when the ...
-- [openspec-bulk-archive](skills/openspec-skills/openspec-bulk-archive) — Archive multiple completed changes at once with `/opsx:bulk-archive`, handling spec conflicts between changes. Use when the user says "ar...
-- [openspec-config](skills/openspec-skills/openspec-config) — Configure OpenSpec project settings and global CLI configuration using `openspec/config.yaml` and `openspec config` commands. Use when th...
-- [openspec-continue](skills/openspec-skills/openspec-continue) — Create the next artifact in the dependency chain with `/opsx:continue`, building up a change incrementally. Use when the user says "conti...
-- [openspec-explore](skills/openspec-skills/openspec-explore) — Think through ideas, investigate problems, and clarify requirements before committing to a change using `/opsx:explore`. Use when the use...
-- [openspec-ff](skills/openspec-skills/openspec-ff) — Fast-forward through artifact creation with `/opsx:ff`, generating all planning artifacts (proposal, specs, design, tasks) at once. Use w...
-- [openspec-initial](skills/openspec-skills/openspec-initial) — Run `openspec init` to initialize OpenSpec in a project directory, creating the openspec/ folder structure and configuring AI tool integr...
-- [openspec-install](skills/openspec-skills/openspec-install) — Install the OpenSpec CLI globally via npm, pnpm, yarn, bun, or nix. Use when the user says "install OpenSpec", "set up OpenSpec", or "ope...
-- [openspec-new](skills/openspec-skills/openspec-new) — Start a new OpenSpec change with `/opsx:new`, creating a change folder with metadata and scaffolding. Use when the user says "start a new...
-- [openspec-onboard](skills/openspec-skills/openspec-onboard) — Guided onboarding through the complete OpenSpec workflow using `/opsx:onboard`, walking the user through a real change in their codebase....
-- [openspec-schema](skills/openspec-skills/openspec-schema) — Create and manage custom workflow schemas using `openspec schema init/fork/validate/which`. Use when the user says "create a custom workf...
-- [openspec-sync](skills/openspec-skills/openspec-sync) — Sync delta specs from a change into main specs using `/opsx:sync`, without archiving the change. Use when the user says "sync specs", "me...
-- [openspec-update](skills/openspec-skills/openspec-update) — Run `openspec update` to regenerate AI tool instruction files after upgrading the OpenSpec CLI. Use when the user says "update OpenSpec",...
-- [openspec-verify](skills/openspec-skills/openspec-verify) — Validate that implementation matches change artifacts using `/opsx:verify`, checking completeness, correctness, and coherence. Use when t...
-
-## pencil-skills
-- ["pencil"](skills/pencil-skills/pencil) — "用于通过 Pencil MCP 读取/修改 .pen 设计文件并校验布局。用户提到 pencil/.pen/设计稿编辑、需要列出工具或执行 batch_get/batch_design 时调用。"
-- [pencil-design-from-stitch-html](skills/pencil-skills/pencil-design-from-stitch-html) — "When you need to turn Stitch page HTML (or a Stitch URL) into a Pencil .pen design. Parses DOM and Tailwind, applies HTML→Pencil mapping...
-- [pencil-mcp-batch-design](skills/pencil-skills/pencil-mcp-batch-design) — Batch execute design changes. The Agent's 'Hands'. Core capability for inserting, updating, moving, or deleting nodes.
-- [pencil-mcp-batch-get](skills/pencil-skills/pencil-mcp-batch-get) — Batch search and read node information. The Agent's 'Eyes'. Use to find specific components e.g. all nodes named 'Button' or get child st...
-- [pencil-mcp-find-empty-space-on-canvas](skills/pencil-skills/pencil-mcp-find-empty-space-on-canvas) — Smartly find empty canvas space. Use to automatically plan artboard placement to avoid overlap and keep the canvas organized.
-- [pencil-mcp-get-editor-state](skills/pencil-skills/pencil-mcp-get-editor-state) — Get current design environment context. Use when you need to understand what is currently selected, canvas position, and environment stat...
-- [pencil-mcp-get-guidelines](skills/pencil-skills/pencil-mcp-get-guidelines) — Get design system guidelines. Use to read and understand specifications e.g. Material Design iOS HIG or custom specs before designing.
-- [pencil-mcp-get-screenshot](skills/pencil-skills/pencil-mcp-get-screenshot) — Get node visual screenshot. Visual Verification. Use to capture screenshots after operations to verify if the design meets expectations.
-- [pencil-mcp-get-style-guide](skills/pencil-skills/pencil-mcp-get-style-guide) — Get specific style detailed definitions. Use to get metadata for a specific style, including palettes, typography rules, etc.
-- [pencil-mcp-get-style-guide-tags](skills/pencil-skills/pencil-mcp-get-style-guide-tags) — Explore design style tags. Use to get design inspiration, such as 'Modern', 'Dark Mode', 'SaaS' directions.
-- [pencil-mcp-get-variables](skills/pencil-skills/pencil-mcp-get-variables) — Read design variables Tokens . Use to get Design Tokens color font variables defined in the current document to ensure consistency.
-- [pencil-mcp-open-document](skills/pencil-skills/pencil-mcp-open-document) — Open or create a design document. Use when you need to initialize design tasks, create new files, or switch to specific designs.
-- [pencil-mcp-replace-all-matching-properties](skills/pencil-skills/pencil-mcp-replace-all-matching-properties) — Global property batch replace. Use for global style adjustment, e.g., 'Replace all red backgrounds with brand blue'.
-- [pencil-mcp-search-all-unique-properties](skills/pencil-skills/pencil-mcp-search-all-unique-properties) — Global property search. Use for design audit, e.g., 'Find all nodes using red background #FF0000 '.
-- [pencil-mcp-set-variables](skills/pencil-skills/pencil-mcp-set-variables) — Set or update design variables. Use to establish or maintain a Design Token system.
-- [pencil-mcp-snapshot-layout](skills/pencil-skills/pencil-mcp-snapshot-layout) — Get page layout structure snapshot. Use when you need to understand the current page's DOM-like tree structure to prepare for layout adju...
-- [pencil-skill-creator](skills/pencil-skills/pencil-skill-creator) — Factory skill for creating new pencil-ui-design-system-* skills. Use when you need to add support for a new design system layui antd boot...
-- [pencil-ui-design-spec-generator](skills/pencil-skills/pencil-ui-design-spec-generator) — Translates vague user requirements into an action-level PENCIL_PLAN sequence of Pencil MCP tool calls . Does not execute; outputs the pla...
-- [pencil-ui-design-system-antd](skills/pencil-skills/pencil-ui-design-system-antd) — Initialize Ant Design. design system components in Pencil variables and component overview.
-- [pencil-ui-design-system-bootstrap](skills/pencil-skills/pencil-ui-design-system-bootstrap) — Initialize Bootstrap. design system components in Pencil variables and component overview.
-- [pencil-ui-design-system-echarts](skills/pencil-skills/pencil-ui-design-system-echarts) — Initialize ECharts. design system components chart placeholders and data-viz tokens in Pencil.
-- [pencil-ui-design-system-element](skills/pencil-skills/pencil-ui-design-system-element) — Initialize Element Plus. design system components in Pencil variables and component overview.
-- [pencil-ui-design-system-layui](skills/pencil-skills/pencil-ui-design-system-layui) — Initialize Layui. design system components in Pencil variables and component overview.
-- [pencil-ui-design-system-ucharts](skills/pencil-skills/pencil-ui-design-system-ucharts) — Initialize uCharts. design system components chart placeholders and data-viz tokens in Pencil.
-- [pencil-ui-design-system-uview](skills/pencil-skills/pencil-ui-design-system-uview) — Initialize uView 2.x . design system components in Pencil variables and component overview.
-- [pencil-ui-design-system-uviewpro](skills/pencil-skills/pencil-ui-design-system-uviewpro) — Initialize uView Pro. design system components in Pencil variables and component overview.
-- [pencil-ui-design-system-vant](skills/pencil-skills/pencil-ui-design-system-vant) — Initialize Vant. design system components in Pencil variables and component overview.
-- [pencil-ui-designer](skills/pencil-skills/pencil-ui-designer) — The Pencil Orchestrator. Handles the flow of initializing Design System Components based on requirements.
-
-## python-skills
-- [django](skills/python-skills/django) — Provides comprehensive guidance for Django framework including models, views, templates, forms, admin, REST framework, and deployment. Us...
-- [fastapi](skills/python-skills/fastapi) — Provides comprehensive guidance for FastAPI framework including routing, request validation, dependency injection, async operations, Open...
-- [flask](skills/python-skills/flask) — Provides comprehensive guidance for Flask framework including routing, templates, forms, database integration, extensions, and deployment...
-
-## react-skills
-- [nextjs](skills/react-skills/nextjs) — Guidance for Next.js using the official docs at nextjs.org/docs. Use when the user needs Next.js concepts, configuration, routing, data f...
-- [react](skills/react-skills/react) — Provides comprehensive guidance for React development including components, JSX, props, state, hooks, context, performance optimization, ...
-- [react-hooks](skills/react-skills/react-hooks) — Provides comprehensive guidance for React Hooks including useState, useEffect, useContext, useReducer, useMemo, useCallback, custom hooks...
-- [react-native](skills/react-skills/react-native) — Provides comprehensive guidance for React Native development including components, navigation, native modules, platform-specific code, an...
-- [react-native-project-creater](skills/react-skills/react-native-project-creater) — Provides one-command project creation for React Native including project initialization, configuration, and template generation. Use when...
-- [redux](skills/react-skills/redux) — Provides comprehensive guidance for Redux state management including stores, actions, reducers, middleware, selectors, and Redux Toolkit....
-
-## social-skills
-- [10、Company Manger-comms](skills/social-skills/internal-comms) — A set of resources to help me write all kinds of 10、Company Manger communications, using the formats that my company likes to use. Claude...
-- [slack-gif-creator](skills/social-skills/slack-gif-creator) — Knowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. U...
-
-## speckit-skills
-- [speckit-analyze](skills/speckit-skills/speckit-analyze) — Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
-- [speckit-baseline](skills/speckit-skills/speckit-baseline) — Generate feature specifications by analyzing existing source code.
-- [speckit-check](skills/speckit-skills/speckit-check) — Run `specify check` to verify that Spec Kit required tools (git, claude, gemini, code, cursor-agent, windsurf, qwen, opencode, codex, sha...
-- [speckit-checklist](skills/speckit-skills/speckit-checklist) — Generate a custom checklist for the current feature based on user requirements.
-- [speckit-clarify](skills/speckit-skills/speckit-clarify) — Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers ...
-- [speckit-constitution](skills/speckit-skills/speckit-constitution) — Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync.
-- [speckit-implement](skills/speckit-skills/speckit-implement) — Execute the implementation plan by processing and executing all tasks defined in tasks.md
-- [speckit-initial](skills/speckit-skills/speckit-initial) — Run `specify init` in the current or target directory to bootstrap a Spec Kit project (pull .specify/ and slash commands); supports multi...
-- [speckit-install](skills/speckit-skills/speckit-install) — Install the Specify CLI on the host machine (uv tool install or uvx one-time); supports multiple OS, persistent or one-time install, and ...
-- [speckit-plan](skills/speckit-skills/speckit-plan) — Execute the implementation planning workflow using the plan template to generate design artifacts.
-- [speckit-specify](skills/speckit-skills/speckit-specify) — Create or update a feature specification from a natural language feature description.
-- [speckit-tasks](skills/speckit-skills/speckit-tasks) — Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
-- [speckit-taskstoissues](skills/speckit-skills/speckit-taskstoissues) — Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts.
-
-## spring-skills
-- [spring-ai](skills/spring-skills/spring-ai) — Provides comprehensive guidance for Spring AI including AI model integration, prompt templates, vector stores, and AI applications. Use w...
-- [spring-ai-alibaba](skills/spring-skills/spring-ai-alibaba) — Provides comprehensive guidance for Spring AI Alibaba including Alibaba Cloud AI services integration, model APIs, and AI application dev...
-- [spring-boot](skills/spring-skills/spring-boot) — Provides comprehensive guidance for Spring Boot development including project creation, auto-configuration, dependency injection, web dev...
-- [spring-cloud](skills/spring-skills/spring-cloud) — Provides comprehensive guidance for Spring Cloud microservices including service discovery, configuration management, load balancing, cir...
-- [spring-cloud-alibaba](skills/spring-skills/spring-cloud-alibaba) — Provides comprehensive guidance for Spring Cloud Alibaba including Nacos, Sentinel, RocketMQ, and Alibaba Cloud integration. Use when the...
-- [spring-data-jpa](skills/spring-skills/spring-data-jpa) — Provides comprehensive guidance for Spring Data JPA including repositories, entity management, query methods, and database operations. Us...
-- [spring-security](skills/spring-skills/spring-security) — Provides comprehensive guidance for Spring Security including authentication, authorization, OAuth2, JWT, and security best practices. Us...
-
-## stitch-skills
-- [stitch-design-md](skills/stitch-skills/stitch-design-md) — Analyze Stitch projects and synthesize a semantic design system into DESIGN.md. Uses Stitch MCP list_projects list_screens get_screen get...
-- [stitch-mcp-create-project](skills/stitch-skills/stitch-mcp-create-project) — Creates a new Stitch project container. Use this when starting a new design task, app idea, or fresh workspace.
-- [stitch-mcp-generate-screen-from-text](skills/stitch-skills/stitch-mcp-generate-screen-from-text) — Generates high-fidelity UI screens or wireframes from text descriptions. The core Text-to-UI engine.
-- [stitch-mcp-get-project](skills/stitch-skills/stitch-mcp-get-project) — Retrieves the detailed metadata of a specific Stitch project.
-- [stitch-mcp-get-screen](skills/stitch-skills/stitch-mcp-get-screen) — Retrieves the full details of a specific screen, including HTML code.
-- [stitch-mcp-list-projects](skills/stitch-skills/stitch-mcp-list-projects) — Lists all Stitch projects accessible to the user.
-- [stitch-mcp-list-screens](skills/stitch-skills/stitch-mcp-list-screens) — Lists all screens contained within a specific project.
-- [stitch-react-components](skills/stitch-skills/stitch-react-components) — Convert Stitch designs into modular Vite/React components with validation and design token consistency. Uses Stitch MCP get_screen to ret...
-- [stitch-remotion](skills/stitch-skills/stitch-remotion) — Generate walkthrough videos from Stitch projects using Remotion. Retrieves screens via Stitch MCP list_projects list_screens get_screen d...
-- [stitch-shadcn-ui](skills/stitch-skills/stitch-shadcn-ui) — Expert guidance for integrating and building applications with shadcn/ui. Component discovery, installation npx shadcn@latest add customi...
-- [stitch-skill-creator](skills/stitch-skills/stitch-skill-creator) — "A factory skill for creating new Stitch Scenario Skills. It enforces the \"Design First, Execute Last\" SOP and standard Stitch architec...
-- [stitch-ued-guide](skills/stitch-skills/stitch-ued-guide) — UED guidelines, visual vocabulary, and prompt structure for Stitch. Use when the user asks about layout/style terms, device constraints, ...
-- [stitch-ui-design-spec-bootstrap](skills/stitch-skills/stitch-ui-design-spec-bootstrap) — Bootstrap-Vue design spec for Stitch. Outputs hard-constraints prefix or selector JSON and assembled prompt.
-- [stitch-ui-design-spec-element-plus](skills/stitch-skills/stitch-ui-design-spec-element-plus) — Element Plus design spec for Stitch. Outputs hard-constraints prefix or selector JSON and assembled prompt.
-- [stitch-ui-design-spec-generator](skills/stitch-skills/stitch-ui-design-spec-generator) — Translates user requirements into structured Design Specs for Theme, Color, and Typography.
-- [stitch-ui-design-spec-layui](skills/stitch-skills/stitch-ui-design-spec-layui) — Layui-Vue design spec for Stitch. Outputs hard-constraints prefix or selector JSON and assembled prompt.
-- [stitch-ui-design-spec-uview](skills/stitch-skills/stitch-ui-design-spec-uview) — uView 2 design spec for Stitch. Outputs hard-constraints prefix or selector JSON and assembled prompt.
-- [stitch-ui-design-spec-uviewpro](skills/stitch-skills/stitch-ui-design-spec-uviewpro) — uView Pro design spec for Stitch. Outputs hard-constraints prefix or selector JSON and assembled prompt.
-- [stitch-ui-design-spec-vant](skills/stitch-skills/stitch-ui-design-spec-vant) — Vant 4 design spec for Stitch. Outputs hard-constraints prefix or selector JSON and assembled prompt.
-- [stitch-ui-design-variants](skills/stitch-skills/stitch-ui-design-variants) — Logic skill that generates prompts for alternative design variants e.g. A B testing options.
-- [stitch-ui-designer](skills/stitch-skills/stitch-ui-designer) — The Master Orchestrator. Handles the end-to-end flow of designing and generating UI screens. Use this for all "Design X" requests.
-- [stitch-ui-prompt-architect](skills/stitch-skills/stitch-ui-prompt-architect) — Builds Stitch-ready prompts from vague UI ideas or from Design Spec and User Request. Outputs sectioned Context, Layout, and Components. ...
-- [stitch-uview-components](skills/stitch-skills/stitch-uview-components) — Convert Stitch designs into uni-app and Vue 2 and uView 2.0 pages and components. Uses Stitch MCP get_screen for retrieval; high-reliabil...
-- [stitch-uviewpro-components](skills/stitch-skills/stitch-uviewpro-components) — Convert Stitch designs into uni-app and Vue 3 and uView Pro pages and components. Uses Stitch MCP get_screen for retrieval; high-reliabil...
-- [stitch-vue-bootstrap-components](skills/stitch-skills/stitch-vue-bootstrap-components) — Convert Stitch designs into modular Vite/Vue 3 and BootstrapVue or BootstrapVueNext components. Uses [BootstrapVue Vue 3] support; Stitch...
-- [stitch-vue-element-components](skills/stitch-skills/stitch-vue-element-components) — Convert Stitch designs into modular Vite/Vue 3 and Element Plus components. Uses Stitch MCP get_screen to retrieve design JSON and HTML; ...
-- [stitch-vue-layui-components](skills/stitch-skills/stitch-vue-layui-components) — Convert Stitch designs into modular Vite/Vue 3 and Layui-Vue components. Uses Stitch MCP get_screen for retrieval; high-reliability fetch...
-- [stitch-vue-vant-components](skills/stitch-skills/stitch-vue-vant-components) — Convert Stitch designs into modular Vite/Vue 3 and Vant 4 mobile components. Uses Stitch MCP get_screen for retrieval; high-reliability f...
-
-## svelte-skills
-- [svelte](skills/svelte-skills/svelte) — Provides comprehensive guidance for Svelte framework including components, reactivity, stores, transitions, and compilation. Use when the...
-
-## t2ui-skills
-- [tui-04x](skills/t2ui-skills/tui-04x) — Generate pixel-precise ASCII TUI for 04x (u-04x) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH_DESIGN)...
-- [tui-action-sheet](skills/t2ui-skills/tui-action-sheet) — Generate pixel-precise ASCII TUI for Action Sheet u-action-sheet with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_B...
-- [tui-alert-tips](skills/t2ui-skills/tui-alert-tips) — Generate pixel-precise ASCII TUI for Alert Tips u-alert-tips with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-avatar](skills/t2ui-skills/tui-avatar) — Generate pixel-precise ASCII TUI for Avatar u-avatar with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-avatar-cropper](skills/t2ui-skills/tui-avatar-cropper) — Generate pixel-precise ASCII TUI for Avatar Cropper (u-avatar-cropper) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC...
-- [tui-back-top](skills/t2ui-skills/tui-back-top) — Generate pixel-precise ASCII TUI for Back Top u-back-top with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-badge](skills/t2ui-skills/tui-badge) — Generate pixel-precise ASCII TUI for Badge u-badge with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-button](skills/t2ui-skills/tui-button) — Generate pixel-precise ASCII TUI for Button u-button with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-calendar](skills/t2ui-skills/tui-calendar) — Generate pixel-precise ASCII TUI for Calendar u-calendar with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-card](skills/t2ui-skills/tui-card) — Generate pixel-precise ASCII TUI for Card u-card with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-cell](skills/t2ui-skills/tui-cell) — Generate pixel-precise ASCII TUI for Cell u-cell with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-changelog](skills/t2ui-skills/tui-changelog) — Generate pixel-precise ASCII TUI for Changelog (u-changelog) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_B...
-- [tui-chat-group](skills/t2ui-skills/tui-chat-group) — Generate pixel-precise ASCII TUI for Chat Group (u-chat-group) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL...
-- [tui-checkbox](skills/t2ui-skills/tui-checkbox) — Generate pixel-precise ASCII TUI for Checkbox u-checkbox with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-circle-progress](skills/t2ui-skills/tui-circle-progress) — Generate pixel-precise ASCII TUI for Circle Progress u-circle-progress with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PE...
-- [tui-collapse](skills/t2ui-skills/tui-collapse) — Generate pixel-precise ASCII TUI for Collapse u-collapse with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-color](skills/t2ui-skills/tui-color) — Generate pixel-precise ASCII TUI for Color u-color with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-common](skills/t2ui-skills/tui-common) — Generate pixel-precise ASCII TUI for Common (u-common) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH_D...
-- [tui-config-provider](skills/t2ui-skills/tui-config-provider) — Generate pixel-precise ASCII TUI for Config Provider u-config-provider with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PE...
-- [tui-count-down](skills/t2ui-skills/tui-count-down) — Generate pixel-precise ASCII TUI for Count Down u-count-down with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-count-to](skills/t2ui-skills/tui-count-to) — Generate pixel-precise ASCII TUI for Count To u-count-to with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-divider](skills/t2ui-skills/tui-divider) — Generate pixel-precise ASCII TUI for Divider u-divider with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIG...
-- [tui-download-setting](skills/t2ui-skills/tui-download-setting) — Generate pixel-precise ASCII TUI for Download Setting (u-download-setting) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_...
-- [tui-dropdown](skills/t2ui-skills/tui-dropdown) — Generate pixel-precise ASCII TUI for Dropdown u-dropdown with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-empty](skills/t2ui-skills/tui-empty) — Generate pixel-precise ASCII TUI for Empty u-empty with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-fab](skills/t2ui-skills/tui-fab) — Generate pixel-precise ASCII TUI for Fab u-fab with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suitab...
-- [tui-feature](skills/t2ui-skills/tui-feature) — Generate pixel-precise ASCII TUI for Feature (u-feature) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH...
-- [tui-field](skills/t2ui-skills/tui-field) — Generate pixel-precise ASCII TUI for Field u-field with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-form](skills/t2ui-skills/tui-form) — Generate pixel-precise ASCII TUI for Form u-form with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-front-ui](skills/t2ui-skills/tui-front-ui) — Define strict, example-rich rules for generating pixel-precise ASCII Text UI (TUI) with layout attributes (top/left/width/height/colors/t...
-- [tui-full-screen](skills/t2ui-skills/tui-full-screen) — Generate pixel-precise ASCII TUI for Full Screen u-full-screen with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BAT...
-- [tui-gap](skills/t2ui-skills/tui-gap) — Generate pixel-precise ASCII TUI for Gap u-gap with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suitab...
-- [tui-grid](skills/t2ui-skills/tui-grid) — Generate pixel-precise ASCII TUI for Grid u-grid with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-icon](skills/t2ui-skills/tui-icon) — Generate pixel-precise ASCII TUI for Icon u-icon with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-image](skills/t2ui-skills/tui-image) — Generate pixel-precise ASCII TUI for Image u-image with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-index-list](skills/t2ui-skills/tui-index-list) — Generate pixel-precise ASCII TUI for Index List u-index-list with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-input](skills/t2ui-skills/tui-input) — Generate pixel-precise ASCII TUI for Input u-input with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-install](skills/t2ui-skills/tui-install) — Generate pixel-precise ASCII TUI for Install (u-install) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH...
-- [tui-intro](skills/t2ui-skills/tui-intro) — Generate pixel-precise ASCII TUI for Intro (u-intro) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH_DES...
-- [tui-keyboard](skills/t2ui-skills/tui-keyboard) — Generate pixel-precise ASCII TUI for Keyboard u-keyboard with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-layout](skills/t2ui-skills/tui-layout) — Generate pixel-precise ASCII TUI for Layout u-layout with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-lazy-load](skills/t2ui-skills/tui-lazy-load) — Generate pixel-precise ASCII TUI for Lazy Load u-lazy-load with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_D...
-- [tui-line](skills/t2ui-skills/tui-line) — Generate pixel-precise ASCII TUI for Line u-line with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-line-progress](skills/t2ui-skills/tui-line-progress) — Generate pixel-precise ASCII TUI for Line Progress u-line-progress with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL...
-- [tui-link](skills/t2ui-skills/tui-link) — Generate pixel-precise ASCII TUI for Link u-link with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-load-more](skills/t2ui-skills/tui-load-more) — Generate pixel-precise ASCII TUI for Load More u-load-more with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_D...
-- [tui-loading](skills/t2ui-skills/tui-loading) — Generate pixel-precise ASCII TUI for Loading u-loading with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIG...
-- [tui-loading-popup](skills/t2ui-skills/tui-loading-popup) — Generate pixel-precise ASCII TUI for Loading Popup u-loading-popup with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL...
-- [tui-mask](skills/t2ui-skills/tui-mask) — Generate pixel-precise ASCII TUI for Mask u-mask with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-message-input](skills/t2ui-skills/tui-message-input) — Generate pixel-precise ASCII TUI for Message Input u-message-input with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL...
-- [tui-modal](skills/t2ui-skills/tui-modal) — Generate pixel-precise ASCII TUI for Modal u-modal with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-navbar](skills/t2ui-skills/tui-navbar) — Generate pixel-precise ASCII TUI for Navbar u-navbar with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-no-network](skills/t2ui-skills/tui-no-network) — Generate pixel-precise ASCII TUI for No Network u-no-network with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-notice-bar](skills/t2ui-skills/tui-notice-bar) — Generate pixel-precise ASCII TUI for Notice Bar u-notice-bar with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-npm-setting](skills/t2ui-skills/tui-npm-setting) — Generate pixel-precise ASCII TUI for Npm Setting (u-npm-setting) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENC...
-- [tui-number-box](skills/t2ui-skills/tui-number-box) — Generate pixel-precise ASCII TUI for Number Box u-number-box with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-nvue](skills/t2ui-skills/tui-nvue) — Generate pixel-precise ASCII TUI for Nvue (u-nvue) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH_DESIG...
-- [tui-page-composer](skills/t2ui-skills/tui-page-composer) — Compose multiple ASCII TUI components into a full page with a consolidated layout summary and Pencil MCP–ready batch_design plans, includ...
-- [tui-pagination](skills/t2ui-skills/tui-pagination) — Generate pixel-precise ASCII TUI for Pagination u-pagination with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-picker](skills/t2ui-skills/tui-picker) — Generate pixel-precise ASCII TUI for Picker u-picker with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-popup](skills/t2ui-skills/tui-popup) — Generate pixel-precise ASCII TUI for Popup u-popup with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-prd-to-descriptions](skills/t2ui-skills/tui-prd-to-descriptions) — From PRD interface/screen descriptions, output ASCII UI (for PRD supplement), Stitch-executable prompt (for stitch-skills), and Pencil-ex...
-- [tui-quickstart](skills/t2ui-skills/tui-quickstart) — Generate pixel-precise ASCII TUI for Quickstart (u-quickstart) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL...
-- [tui-radio](skills/t2ui-skills/tui-radio) — Generate pixel-precise ASCII TUI for Radio u-radio with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-rate](skills/t2ui-skills/tui-rate) — Generate pixel-precise ASCII TUI for Rate u-rate with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-read](skills/t2ui-skills/tui-read) — Generate pixel-precise ASCII TUI for Read (u-read) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH_DESIG...
-- [tui-read-more](skills/t2ui-skills/tui-read-more) — Generate pixel-precise ASCII TUI for Read More u-read-more with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_D...
-- [tui-root-portal](skills/t2ui-skills/tui-root-portal) — Generate pixel-precise ASCII TUI for Root Portal u-root-portal with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BAT...
-- [tui-safe-area-inset](skills/t2ui-skills/tui-safe-area-inset) — Generate pixel-precise ASCII TUI for Safe Area Inset u-safe-area-inset with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PE...
-- [tui-search](skills/t2ui-skills/tui-search) — Generate pixel-precise ASCII TUI for Search u-search with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-section](skills/t2ui-skills/tui-section) — Generate pixel-precise ASCII TUI for Section u-section with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIG...
-- [tui-select](skills/t2ui-skills/tui-select) — Generate pixel-precise ASCII TUI for Select u-select with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-setting](skills/t2ui-skills/tui-setting) — Generate pixel-precise ASCII TUI for Setting (u-setting) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENCIL_BATCH...
-- [tui-skeleton](skills/t2ui-skills/tui-skeleton) — Generate pixel-precise ASCII TUI for Skeleton u-skeleton with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-slider](skills/t2ui-skills/tui-slider) — Generate pixel-precise ASCII TUI for Slider u-slider with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-steps](skills/t2ui-skills/tui-steps) — Generate pixel-precise ASCII TUI for Steps u-steps with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-sticky](skills/t2ui-skills/tui-sticky) — Generate pixel-precise ASCII TUI for Sticky u-sticky with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-subsection](skills/t2ui-skills/tui-subsection) — Generate pixel-precise ASCII TUI for Subsection u-subsection with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-swipe-action](skills/t2ui-skills/tui-swipe-action) — Generate pixel-precise ASCII TUI for Swipe Action u-swipe-action with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_B...
-- [tui-swiper](skills/t2ui-skills/tui-swiper) — Generate pixel-precise ASCII TUI for Swiper u-swiper with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-switch](skills/t2ui-skills/tui-switch) — Generate pixel-precise ASCII TUI for Switch u-switch with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-tabbar](skills/t2ui-skills/tui-tabbar) — Generate pixel-precise ASCII TUI for Tabbar u-tabbar with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-table](skills/t2ui-skills/tui-table) — Generate pixel-precise ASCII TUI for Table u-table with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-tabs](skills/t2ui-skills/tui-tabs) — Generate pixel-precise ASCII TUI for Tabs u-tabs with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-tabs-swiper](skills/t2ui-skills/tui-tabs-swiper) — Generate pixel-precise ASCII TUI for Tabs Swiper u-tabs-swiper with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BAT...
-- [tui-tag](skills/t2ui-skills/tui-tag) — Generate pixel-precise ASCII TUI for Tag u-tag with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suitab...
-- [tui-text](skills/t2ui-skills/tui-text) — Generate pixel-precise ASCII TUI for Text u-text with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN suit...
-- [tui-textarea](skills/t2ui-skills/tui-textarea) — Generate pixel-precise ASCII TUI for Textarea u-textarea with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-time-line](skills/t2ui-skills/tui-time-line) — Generate pixel-precise ASCII TUI for Time Line u-time-line with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_D...
-- [tui-toast](skills/t2ui-skills/tui-toast) — Generate pixel-precise ASCII TUI for Toast u-toast with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN su...
-- [tui-top-tips](skills/t2ui-skills/tui-top-tips) — Generate pixel-precise ASCII TUI for Top Tips u-top-tips with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DES...
-- [tui-transition](skills/t2ui-skills/tui-transition) — Generate pixel-precise ASCII TUI for Transition u-transition with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH...
-- [tui-uni-modules-setting](skills/t2ui-skills/tui-uni-modules-setting) — Generate pixel-precise ASCII TUI for Uni Modules Setting (u-uni-modules-setting) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, P...
-- [tui-upload](skills/t2ui-skills/tui-upload) — Generate pixel-precise ASCII TUI for Upload u-upload with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_DESIGN ...
-- [tui-verification-code](skills/t2ui-skills/tui-verification-code) — Generate pixel-precise ASCII TUI for Verification Code u-verification-code with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPE...
-- [tui-vuex-detail](skills/t2ui-skills/tui-vuex-detail) — Generate pixel-precise ASCII TUI for Vuex Detail (u-vuex-detail) with strict output blocks (TUI_RENDER, COMPONENT_SPEC, PENCIL_SPEC, PENC...
-- [tui-waterfall](skills/t2ui-skills/tui-waterfall) — Generate pixel-precise ASCII TUI for Waterfall u-waterfall with strict output blocks TUI_RENDER COMPONENT_SPEC PENCIL_SPEC PENCIL_BATCH_D...
-
-## tauri-skills
-- [tauri](skills/tauri-skills/tauri) — Comprehensive index for Tauri framework development, including Rust backend, frontend integration, and full plugin ecosystem. Acts as a r...
-- [tauri-app-autostart](skills/tauri-skills/tauri-app-autostart) — Guidance for Tauri v2 autostart setup with platform differences and rollback.
-- [tauri-app-barcode-scanner](skills/tauri-skills/tauri-app-barcode-scanner) — Guidance for Tauri v2 barcode scanner plugin with permissions and scan lifecycle.
-- [tauri-app-biometric](skills/tauri-skills/tauri-app-biometric) — Guidance for Tauri v2 biometric plugin with authentication flow and fallback strategy.
-- [tauri-app-cli](skills/tauri-skills/tauri-app-cli) — Guidance for Tauri v2 CLI plugin with argument schema and app command routing.
-- [tauri-app-clipboard](skills/tauri-skills/tauri-app-clipboard) — Guidance for Tauri v2 clipboard plugin with safe copy, paste, and monitoring flows.
-- [tauri-app-creator](skills/tauri-skills/tauri-app-creator) — Guidance for creating Tauri v2 projects using official create-tauri-app workflows and minimal run verification.
-- [tauri-app-deep-linking](skills/tauri-skills/tauri-app-deep-linking) — Guidance for Tauri v2 deep-linking plugin with URL schemes and safe routing.
-- [tauri-app-develop](skills/tauri-skills/tauri-app-develop) — Guidance for Tauri v2 daily development workflow, debugging, resources, sidecar usage, and testing strategies.
-- [tauri-app-dialog](skills/tauri-skills/tauri-app-dialog) — Guidance for Tauri v2 dialog plugin with native dialogs and unified API design.
-- [tauri-app-file-system](skills/tauri-skills/tauri-app-file-system) — Guidance for Tauri v2 file-system plugin with scoped access and safe file operations.
-- [tauri-app-frontend-selection](skills/tauri-skills/tauri-app-frontend-selection) — Guidance for selecting and configuring frontend frameworks for Tauri v2 with static export compatibility.
-- [tauri-app-geolocation](skills/tauri-skills/tauri-app-geolocation) — Guidance for Tauri v2 geolocation plugin with permission handling and privacy controls.
-- [tauri-app-global-shortcut](skills/tauri-skills/tauri-app-global-shortcut) — Guidance for Tauri v2 global-shortcut plugin with conflict handling and release.
-- [tauri-app-haptics](skills/tauri-skills/tauri-app-haptics) — Guidance for Tauri v2 haptics plugin with feedback patterns and graceful fallback.
-- [tauri-app-http-client](skills/tauri-skills/tauri-app-http-client) — Guidance for Tauri v2 http-client plugin with allowlisted requests and secure transport.
-- [tauri-app-localhost](skills/tauri-skills/tauri-app-localhost) — Guidance for Tauri v2 localhost plugin with local service access and minimal exposure.
-- [tauri-app-logging](skills/tauri-skills/tauri-app-logging) — Guidance for Tauri v2 logging plugin with levels, filtering, and safe diagnostics.
-- [tauri-app-nfc](skills/tauri-skills/tauri-app-nfc) — Guidance for Tauri v2 NFC plugin with session handling and data validation.
-- [tauri-app-notification](skills/tauri-skills/tauri-app-notification) — Guidance for Tauri v2 notification plugin with permission flow and click handling.
-- [tauri-app-opener](skills/tauri-skills/tauri-app-opener) — Guidance for Tauri v2 opener plugin with safe external links and file handling.
-- [tauri-app-os-info](skills/tauri-skills/tauri-app-os-info) — Guidance for Tauri v2 os-info plugin with safe system diagnostics and reporting.
-- [tauri-app-persisted-scope](skills/tauri-skills/tauri-app-persisted-scope) — Guidance for Tauri v2 persisted-scope plugin with expiration and revocation flows.
-- [tauri-app-planning](skills/tauri-skills/tauri-app-planning) — Comprehensive project planning, requirements analysis, and architectural orchestration for Tauri 2.0 applications.
-- [tauri-app-plugin-permissions](skills/tauri-skills/tauri-app-plugin-permissions) — Guidance for Tauri v2 plugin permission authoring, capability generation, and platform differences.
-- [tauri-app-positioner](skills/tauri-skills/tauri-app-positioner) — Guidance for Tauri v2 positioner plugin with multi-display alignment strategies.
-- [tauri-app-process](skills/tauri-skills/tauri-app-process) — Guidance for Tauri v2 process plugin with controlled process information exposure.
-- [tauri-app-shell](skills/tauri-skills/tauri-app-shell) — Guidance for Tauri v2 shell plugin with secure command execution and open behavior.
-- [tauri-app-sidecar-nodejs](skills/tauri-skills/tauri-app-sidecar-nodejs) — Guidance for Tauri v2 sidecar Node.js integration with lifecycle and packaging.
-- [tauri-app-single-instance](skills/tauri-skills/tauri-app-single-instance) — Guidance for Tauri v2 single-instance behavior and second-launch argument handling.
-- [tauri-app-splashscreen](skills/tauri-skills/tauri-app-splashscreen) — Guidance for Tauri v2 splashscreen setup and lifecycle control to avoid white screens.
-- [tauri-app-sql](skills/tauri-skills/tauri-app-sql) — Guidance for Tauri v2 SQL plugin setup, migrations, and safe query access.
-- [tauri-app-store](skills/tauri-skills/tauri-app-store) — Guidance for Tauri v2 store plugin with key-value persistence and lazy loading.
-- [tauri-app-stronghold](skills/tauri-skills/tauri-app-stronghold) — Guidance for Tauri v2 stronghold plugin with encrypted storage and sensitive data handling.
-- [tauri-app-system-tray](skills/tauri-skills/tauri-app-system-tray) — Guidance for Tauri v2 system tray interactions and platform behavior differences.
-- [tauri-app-updater](skills/tauri-skills/tauri-app-updater) — Guidance for Tauri v2 updater plugin with OTA updates and signing keys.
-- [tauri-app-upload](skills/tauri-skills/tauri-app-upload) — Guidance for Tauri v2 upload plugin with file transfer, progress reporting, and headers.
-- [tauri-app-wasm](skills/tauri-skills/tauri-app-wasm) — Guidance for running Rust-compiled WASM in the Tauri v2 frontend.
-- [tauri-app-websocket](skills/tauri-skills/tauri-app-websocket) — Guidance for Tauri v2 websocket plugin with Rust-managed connections and lifecycle handling.
-- [tauri-app-window-menu](skills/tauri-skills/tauri-app-window-menu) — Guidance for Tauri v2 window menu definition, event handling, and shortcuts.
-- [tauri-app-window-state](skills/tauri-skills/tauri-app-window-state) — Guidance for Tauri v2 window-state plugin to persist window size and position.
-- [tauri-build](skills/tauri-skills/tauri-build) — Guidance for Tauri v2 production builds, signing, and distribution artifacts.
-- [tauri-concept](skills/tauri-skills/tauri-concept) — Guidance for Tauri v2 architecture concepts, process model, and IPC isolation patterns.
-- [tauri-config](skills/tauri-skills/tauri-config) — Guidance for Tauri v2 tauri.conf.json structure, lifecycle management, and CSP configuration.
-- [tauri-framework-security](skills/tauri-skills/tauri-framework-security) — Guidance for Tauri v2 security model, baseline hardening, and runtime authority controls.
-- [tauri-framework-upgrade](skills/tauri-skills/tauri-framework-upgrade) — Guidance for upgrading to stable Tauri v2 from v1 or v2 beta with migration checks.
-- [tauri-ipc](skills/tauri-skills/tauri-ipc) — Guidance for Tauri v2 IPC with frontend invoke calls, Rust commands, and type-safe bindings.
-- [tauri-mobile](skills/tauri-skills/tauri-mobile) — Guidance for Tauri v2 mobile development setup, debugging, and bundle identifiers.
-- [tauri-scaffold](skills/tauri-skills/tauri-scaffold) — Guidance for Tauri v2 project scaffolding with create-tauri-app, project structure, and frontend static export configuration.
-- [tauri-security](skills/tauri-skills/tauri-security) — Guidance for Tauri v2 capabilities, scope configuration, and ACL-based permission control.
-- [tauri-setup](skills/tauri-skills/tauri-setup) — Guidance for Tauri v2 prerequisites and environment setup across macOS, Windows, Linux, and mobile Android iOS targets.
-- [tauri-window](skills/tauri-skills/tauri-window) — Guidance for Tauri v2 window creation, configuration, lifecycle management, and custom titlebar UI.
-
-## teaching-skills
-- [course-designer](skills/teaching-skills/course-designer) — Provides comprehensive guidance for course design including curriculum development, learning objectives, and course structure. Use when t...
-- [learning-assessor](skills/teaching-skills/learning-assessor) — Provides comprehensive guidance for learning assessment including assessment creation, evaluation methods, and assessment best practices....
-- [teaching-resource-generator](skills/teaching-skills/teaching-resource-generator) — Provides comprehensive guidance for generating teaching resources including courseware, exercises, case studies, and learning guides. Use...
-
-## testing-skills
-- [appium](skills/testing-skills/appium) — Provides comprehensive guidance for Appium mobile testing including mobile app automation, element location, gestures, and cross-platform...
-- [cypress](skills/testing-skills/cypress) — Provides comprehensive guidance for Cypress end-to-end testing including commands, assertions, component testing, CI/CD integration, and ...
-- [detox](skills/testing-skills/detox) — Provides comprehensive guidance for Detox mobile testing framework including React Native testing, E2E testing, and test synchronization....
-- [jest](skills/testing-skills/jest) — Provides comprehensive guidance for Jest testing framework including test writing, matchers, async testing, mocking, snapshots, configura...
-- [junit](skills/testing-skills/junit) — Provides comprehensive guidance for JUnit testing framework including test annotations, assertions, test lifecycle, and best practices. U...
-- [playwright](skills/testing-skills/playwright) — Provides comprehensive guidance for Playwright testing including browser automation, test writing, page objects, and cross-browser testin...
-- [pytest](skills/testing-skills/pytest) — Provides comprehensive guidance for pytest testing framework including test writing, fixtures, parametrization, mocking, and plugins. Use...
-- [selenium](skills/testing-skills/selenium) — Provides comprehensive guidance for Selenium WebDriver including browser automation, element location, waits, and test frameworks. Use wh...
-- [vitest](skills/testing-skills/vitest) — Provides comprehensive guidance for Vitest testing framework including fast test execution, Vite integration, component testing, mocking,...
-
-## threejs-skills
-- [threejs-animation](skills/threejs-skills/threejs-animation) — >-
-- [threejs-audio](skills/threejs-skills/threejs-audio) — >-
-- [threejs-camera](skills/threejs-skills/threejs-camera) — >-
-- [threejs-controls](skills/threejs-skills/threejs-controls) — >-
-- [threejs-dev-setup](skills/threejs-skills/threejs-dev-setup) — >-
-- [threejs-geometries](skills/threejs-skills/threejs-geometries) — >-
-- [threejs-helpers](skills/threejs-skills/threejs-helpers) — >-
-- [threejs-lights](skills/threejs-skills/threejs-lights) — >-
-- [threejs-loaders](skills/threejs-skills/threejs-loaders) — >-
-- [threejs-materials](skills/threejs-skills/threejs-materials) — >-
-- [threejs-math](skills/threejs-skills/threejs-math) — >-
-- [threejs-node-tsl](skills/threejs-skills/threejs-node-tsl) — >-
-- [threejs-objects](skills/threejs-skills/threejs-objects) — >-
-- [threejs-postprocessing](skills/threejs-skills/threejs-postprocessing) — >-
-- [threejs-renderers](skills/threejs-skills/threejs-renderers) — >-
-- [threejs-scenes](skills/threejs-skills/threejs-scenes) — >-
-- [threejs-textures](skills/threejs-skills/threejs-textures) — >-
-- [threejs-webxr](skills/threejs-skills/threejs-webxr) — >-
-
-## uniapp-skills
-- [uniapp-ad](skills/uniapp-skills/uniapp-ad) — A comprehensive skill for uni-ad monetization in uni-app. Use this skill to integrate ads, configure ad types, handle ad events, and foll...
-- [uniapp-cloud](skills/uniapp-skills/uniapp-cloud) — A comprehensive skill for uniCloud cloud development in the uni-app ecosystem. Use this skill when you need uniCloud project setup, cloud...
-- [uniapp-mini-guide](skills/uniapp-skills/uniapp-mini) — A comprehensive skill for uni-app mini program development. Use when building uni-app mini programs, configuring mini program settings, o...
-- [uniapp-native-app](skills/uniapp-skills/uniapp-native-app) — A comprehensive skill for uni-app native app offline packaging. Use this skill to package uni-app as native Android/iOS apps, configure n...
-- [uniapp-native-plugin](skills/uniapp-skills/uniapp-native-plugin) — A comprehensive skill for developing native plugins for uni-app. Use this skill when building Android/iOS native plugins, integrating nat...
-- [uniapp-plugin](skills/uniapp-skills/uniapp-plugin) — A comprehensive skill for the uni-app plugin market and automatic plugin installation. Use this skill to browse plugins, auto-install plu...
-- [uniapp-project](skills/uniapp-skills/uniapp-project) — Provides comprehensive uni-app component and API integration guidance. Use when the user needs official uni-app components or APIs, wants...
-- [uniapp-project-creator](skills/uniapp-skills/uniapp-project-creator) — Provides one-command project creation for uni-app using the official quickstart CLI, including project initialization, configuration, and...
-- [uniapp-ucharts](skills/uniapp-skills/uniapp-ucharts) — A comprehensive skill for integrating and using uCharts with UniApp projects. This skill focuses on UniApp-specific integration, configur...
-- [uniapp-uview](skills/uniapp-skills/uniapp-uview) — A comprehensive skill for integrating and using uView UI with UniApp projects. This skill focuses on UniApp-specific integration, configu...
-- [uniappx-project](skills/uniapp-skills/uniappx-project) — Provides comprehensive uni-app-x component and API integration guidance. Use when the user needs official uni-app-x components or APIs, w...
-- [uniappx-project-creator](skills/uniapp-skills/uniappx-project-creator) — Provides one-command project creation for uni-app-x including Vue 3 + TypeScript + Vite setup, configuration, and template generation. Us...
-- [uniappx-uview-pro](skills/uniapp-skills/uniappx-uview-pro) — A comprehensive skill for integrating and using uView Pro with UniAppX projects. This skill focuses on UniAppX-specific integration, conf...
-
-## utility-skills
-- [skill-creator](skills/utility-skills/skill-creator) — Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that e...
-- [skill-installer](skills/utility-skills/skill-installer) — Manages the installation and discovery of AI skills from the PartMe marketplace.
-- [skill-sop-creator](skills/utility-skills/skill-sop-creator) — Guide for creating Standard Operating Procedures and SOPs and composite workflows by combining atomic Agent Skills. Use when users want t...
-
-## uview-skills
-- [uview-pro-vue3](skills/uview-skills/uview-pro-vue3) — Provides comprehensive guidance for uView Pro Vue 3 component library including components, tools, layouts, and templates. Use when the u...
-- [uview-vue2](skills/uview-skills/uview-vue2) — Provides comprehensive guidance for uView Vue 2 component library including components, tools, and layouts. Use when the user asks about ...
-
-## vscode-skills
-- [vscode-deploy-package](skills/vscode-skills/vscode-deploy-package) — Package the extension into a .vsix file for distribution.
-- [vscode-feature-command](skills/vscode-skills/vscode-feature-command) — Add a new command to the VS Code extension.
-- [vscode-feature-webview](skills/vscode-skills/vscode-feature-webview) — Add a Webview panel to display custom HTML content.
-- [vscode-project-init](skills/vscode-skills/vscode-project-init) — Initialize a new VS Code Extension project using TypeScript.
-
-## vue-skills
-- [pinia](skills/vue-skills/pinia) — Provides comprehensive guidance for Pinia state management including stores, state, getters, actions, plugins, and TypeScript support. Us...
-- [vue-router](skills/vue-skills/vue-router) — Provides comprehensive guidance for Vue Router including route configuration, navigation, dynamic routes, nested routes, route guards, pr...
-- [vue-router-v3](skills/vue-skills/vue-router-v3) — Guidance for Vue Router v3 using the official Installation, Guide, and API docs. Use when users need routing setup, navigation patterns, ...
-- [vue-router-v4](skills/vue-skills/vue-router-v4) — Provides comprehensive guidance for Vue Router v4 including route configuration, navigation, nested routes, route guards, and Vue 3 integ...
-- [vue2](skills/vue-skills/vue2) — Provides comprehensive guidance for Vue 2.x development including Options API, components, directives, lifecycle hooks, computed properti...
-- [vue3](skills/vue-skills/vue3) — Guidance for Vue 3 using the official guide and API reference. Use when the user needs Vue 3 concepts, patterns, or API details to build ...
-- [vuex-vue2](skills/vue-skills/vuex-vue2) — Provides comprehensive guidance for Vuex 2.x state management in Vue 2 applications including state, mutations, actions, getters, modules...
-
-## vue-ui-skills
-- [bootstrap-vue3](skills/vue-ui-skills/bootstrap-vue3) — Provides comprehensive guidance for Bootstrap Vue 3 component library including Bootstrap components, grid system, utilities, and Vue 3 i...
-- [element-plus-vue3](skills/vue-ui-skills/element-plus-vue3) — Provides comprehensive guidance for Element Plus Vue 3 component library including installation, components, themes, internationalization...
-- [layui-vue3](skills/vue-ui-skills/layui-vue3) — Provides comprehensive guidance for Layui Vue component library including components, layer dialogs, and utilities. Use when the user ask...
-- [vant-vue3](skills/vue-ui-skills/vant-vue3) — Provides structured guidance for Vant of Vue 3.0. Use when the user needs Vant with Vue 3, asks about mobile UI components such as Button...
+# Awesome Agent Skills — 全技能索引
+
+_索引生成时间:2026-05-29 | 44 个技能组 | 463 个技能_
+
+---
+
+## 📊 技能组总览
+
+| 分类 | 技能组 | 技能数 | 状态 |
+|------|--------|:-----:|------|
+| 🏗️ 架构 | [ddd](#ddd) | 16 | ✅ 全部高质量 (TRACE 4.5+) |
+| 🗄️ 数据库 | [database](#database) | 5 | ✅ 全部深度技能 |
+| 🎨 前端框架 | [angular](#angular) / [react](#react) / [vue](#vue) / [svelte](#svelte) / [flutter](#flutter) / [uniapp](#uniapp) / [cocos](#cocos) / [electron](#electron) | 17 | |
+| 🔧 后端 | [spring](#spring) / [go](#go) / [python](#python) / [nodejs](#nodejs) | 16 | |
+| 🛠️ 工具 | [build](#build) / [docker](#docker) / [devops](#devops) / [nvm](#nvm) / [vscode](#vscode) | 37 | |
+| ✅ 测试 | [testing](#testing) | 9 | |
+| 📄 文档 | [document](#document) | 9 | |
+| 🎨 设计 | [design](#design) / [pencil](#pencil) / [drawio](#drawio) | 37 | |
+| 🧩 UI库 | [antd](#antd) / [avue](#avue) / [uview](#uview) / [vue-ui](#vue-ui) / [t2ui](#t2ui) | 112 | |
+| 📊 图表 | [chart](#chart) | 2 | |
+| 🎮 3D | [threejs](#threejs) | 19 | |
+| 🏗️ 桌面 | [tauri](#tauri) | 54 | |
+| 🔢 工具 | [ascii](#ascii) / [dev-utils](#dev-utils) / [utility](#utility) | 28 | |
+| 📝 规范 | [base](#base) / [openspec](#openspec) / [speckit](#speckit) | 37 | |
+| 📱 原生 | [mobile-native](#mobile-native) | 2 | |
+| 🤖 AI | [jimeng](#jimeng) | 8 | |
+| 👥 社交 | [social](#social) | 2 | |
+| 📚 教学 | [teaching](#teaching) | 3 | |
+| 🔌 集成 | [stitch](#stitch) / [ocrmypdf](#ocrmypdf) | 36 | |
+
+---
+
+## 🗄️ database — 数据库 (5 个,全部深度优化)
+
+| 技能 | 内容深度 | TRACE | 说明 |
+|------|:---:|:----:|------|
+| [redis](skills/database-skills/redis) | ~38KB | **4.67** | 9 大数据结构 + 缓存/持久化/集群/Lua/安全 |
+| [mysql](skills/database-skills/mysql) | ~76KB | **4.34** | SQL语法+80+函数+引擎+索引+复制+优化 |
+| [postgresql](skills/database-skills/postgresql) | ~99KB | **4.51** | JSONB+CTE+全文搜索+扩展+窗口函数+FDW |
+| [oracle](skills/database-skills/oracle) | ~85KB | **4.39** | PL/SQL+AWR+RMAN+Data Guard+RAC+分析函数 |
+| [elasticsearch](skills/database-skills/elasticsearch) | ~82KB | **4.38** | 查询DSL+聚合+分词器+映射+集群+ELK |
+
+---
+
+## 🏗️ ddd — 领域驱动设计 (16 个,全部 TRACE 4.5+)
+
+> 设计哲学:按用户学习路径组织 — 入门认知 → 架构选型 → 架构落地 → 领域设计 → CQRS → API → 审查 → 评估 → 文档 → 测试 → DevOps
+
+### 入门与选型
+| 技能 | 职责 | TRACE |
+|------|------|:----:|
+| [ddd-architecture-awesome](skills/ddd-skills/ddd-architecture-awesome) | DDD 概念入门 + 适用性评估 + 复杂度阶梯 + 架构全景 | - |
+| [ddd-architecture-selector](skills/ddd-skills/ddd-architecture-selector) | 5 种架构决策矩阵 + 决策树 + 域三分法 + CQRS 级别建议 | **4.59** |
+
+### 架构落地(5 种架构独立 Skill)
+| 技能 | 架构 | 项目示例 | TRACE |
+|------|------|:---:|:----:|
+| [ddd-architecture-layered](skills/ddd-skills/ddd-architecture-layered) | DDD 四层分层 | 7 种规模 | **4.69** |
+| [ddd-architecture-onion](skills/ddd-skills/ddd-architecture-onion) | 洋葱架构 | 7 种规模 | **4.72** |
+| [ddd-architecture-hexagonal](skills/ddd-skills/ddd-architecture-hexagonal) | 六边形架构 (Ports & Adapters) | 7 种规模 | **4.68** |
+| [ddd-architecture-clean](skills/ddd-skills/ddd-architecture-clean) | 整洁架构 (Robert C. Martin) | 7 种规模 | **4.68** |
+| [ddd-architecture-cola](skills/ddd-skills/ddd-architecture-cola) | COLA v5 菱形架构 + ddd4j 脚手架 | 7+4 种规模 | **4.67** |
+
+### 领域与模式
+| 技能 | 职责 | TRACE |
+|------|------|:----:|
+| [ddd-domain-designer](skills/ddd-skills/ddd-domain-designer) | 事件风暴驱动6步领域建模 + 聚合设计五步法六原则 | **4.69** |
+| [ddd-event-storming](skills/ddd-skills/ddd-event-storming) | 事件风暴工作坊引导 + 6步流程 + 便签颜色规范 | **4.64** |
+| [ddd-cqrs-architecture](skills/ddd-skills/ddd-cqrs-architecture) | CQRS L1/L2/L3 落地 + Event Sourcing + 幂等设计 | **4.71** |
+| [ddd-api-designer](skills/ddd-skills/ddd-api-designer) | CQRS 读写 API + PO/DO/DTO/VO 转换链 + BFF + OpenAPI | **4.78** |
+
+### 质量与运维
+| 技能 | 职责 | TRACE |
+|------|------|:----:|
+| [ddd-code-reviewer](skills/ddd-skills/ddd-code-reviewer) | 12 种反模式 P0/P1/P2 检测 + 充血模型验证 + 5维评分 | **4.60** |
+| [ddd-architecture-evaluator](skills/ddd-skills/ddd-architecture-evaluator) | DDD 成熟度5级 + 适配度评估 + 技术债务量化 | **4.71** |
+| [ddd-architecture-doc](skills/ddd-skills/ddd-architecture-doc) | C4 模型 + ADR + 领域模型文档 + API 文档 | **4.54** |
+| [ddd-testing-strategist](skills/ddd-skills/ddd-testing-strategist) | 测试金字塔 + TDDD + 各架构测试策略 | **4.67** |
+| [ddd-devops-integration](skills/ddd-skills/ddd-devops-integration) | CI/CD + ArchUnit 自动化 + K8s 部署 + Flyway 迁移 | **4.65** |
+
+---
+
+## 🎨 前端框架
+
+### angular (1)
+- [angular](skills/angular-skills/angular) — Angular 框架综合指南
+
+### antd (4)
+- [ant-design-mini](skills/antd-skills/ant-design-mini) — Ant Design Mini 小程序组件库
+- [ant-design-mobile](skills/antd-skills/ant-design-mobile) — Ant Design Mobile 移动端组件库
+- [ant-design-react](skills/antd-skills/ant-design-react) — Ant Design React 组件库
+- [ant-design-vue](skills/antd-skills/ant-design-vue) — Ant Design Vue 组件库
+
+### ascii (13)
+- [ascii-ansi-colorizer](skills/ascii-skills/...) — ANSI 配色
+- [ascii-cli-logo-banner](skills/ascii-skills/...) — CLI ASCII Logo
+- [ascii-diagram-boxflow](skills/ascii-skills/...) — 盒状流程图
+- [ascii-image-to-ascii](skills/ascii-skills/...) — 图像转 ASCII
+- [ascii-mini-charts](skills/ascii-skills/...) — ASCII 迷你图表
+- [ascii-motd-profile-banner](skills/ascii-skills/...) — MOTD Banner
+- [ascii-progress-and-spinner](skills/ascii-skills/...) — 进度条
+- [ascii-table-renderer](skills/ascii-skills/...) — 表格渲染
+- [ascii-terminal-animation-pack](skills/ascii-skills/...) — 终端动画
+- [ascii-text-art-library](skills/ascii-skills/...) — 文字艺术库
+- [cli-ascii-logo](skills/ascii-skills/...) — CLI Logo 生成
+
+### avue (3)
+- [avue](skills/avue-skills/avue) — Avue 框架
+- [avue-crud](skills/avue-skills/avue-crud) — Avue CRUD
+- [avue-form](skills/avue-skills/avue-form) — Avue Form
+
+### vue (7)
+- [vue2](skills/vue-skills/vue2) — Vue 2
+- [vue3](skills/vue-skills/vue3) — Vue 3
+- [vue-router](skills/vue-skills/vue-router) — Vue Router
+- [vue-router-v3](skills/vue-skills/vue-router-v3) — Vue Router v3
+- [vue-router-v4](skills/vue-skills/vue-router-v4) — Vue Router v4
+- [vuex-vue2](skills/vue-skills/vuex-vue2) — Vuex
+- [pinia](skills/vue-skills/pinia) — Pinia
+
+### react (6)
+- [react](skills/react-skills/react) — React
+- [react-hooks](skills/react-skills/react-hooks) — React Hooks
+- [react-native](skills/react-skills/react-native) — React Native
+- [react-native-project-creater](skills/react-skills/react-native-project-creater) — RN 项目创建
+- [redux](skills/react-skills/redux) — Redux
+- [nextjs](skills/react-skills/nextjs) — Next.js
+
+### 更多前端 (13)
+- svelte (1) / flutter (2) / uniapp (13) / cocos (1) / electron (3) / tauri (54) / threejs (19)
+- vue-ui (4) / uview (2) / t2ui (99)
+
+---
+
+## 🔧 后端与基础设施
+
+### spring (7)
+- [spring-boot](skills/spring-skills/spring-boot.md) / spring-data-jpa / spring-security / spring-cloud / ...
+
+### go (2)
+- [gin](skills/go-skills/gin) / [gin-gonic](skills/go-skills/gin-gonic)
+
+### python (3)
+- [flask](skills/python-skills/flask) / [django](skills/python-skills/django) / [fastapi](skills/python-skills/fastapi)
+
+### nodejs (4)
+- [express](skills/nodejs-skills/express) / [koa](skills/nodejs-skills/koa) / [fastify](skills/nodejs-skills/fastify) / nestjs
+
+### 构建工具 — build (6)
+- [vite](skills/build-skills/vite) / [webpack](skills/build-skills/webpack) / [rollup](skills/build-skills/rollup) / [rspack](skills/build-skills/rspack) / [parcel](skills/build-skills/parcel) / [dart-sass](skills/build-skills/dart-sass)
+
+### 容器 — docker (2)
+- [docker](skills/docker-skills/docker) / [docker-compose](skills/docker-skills/docker-compose)
+
+### DevOps (6)
+- [terraform](skills/devops-skills/terraform) / [kubernetes](skills/devops-skills/kubernetes) / [ansible](skills/devops-skills/ansible) / [github-actions](skills/devops-skills/github-actions) / [gitlab-ci](skills/devops-skills/gitlab-ci) / ...
+
+### NVM (17)
+- [nvm](skills/nvm-skills/nvm) 及全套管理工具
+
+### VSCode (6)
+- 扩展开发与发布
+
+---
+
+## ✅ 测试 — testing (9)
+- [pytest](skills/testing-skills/pytest) / [junit](skills/testing-skills/junit) / [selenium](skills/testing-skills/selenium) / [playwright](skills/testing-skills/playwright) / [appium](skills/testing-skills/appium) / [detox](skills/testing-skills/detox)
+
+---
+
+## 📄 文档 — document (9)
+- [docx](skills/document-skills/docx) / [pptx](skills/document-skills/pptx) / [pdf](skills/document-skills/pdf) / [xlsx](skills/document-skills/xlsx)
+- [mermaid](skills/document-skills/mermaid) / [plantuml](skills/document-skills/plantuml) / [full-stack-doc](skills/document-skills/full-stack-doc) / ...
+
+---
+
+## 🎨 设计与原型
+
+### design (4)
+- [algorithmic-art](skills/design-skills/algorithmic-art)
+
+### drawio (2)
+- [drawio-flowchart](skills/drawio-skills/drawio-flowchart) / [drawio-architecture](skills/drawio-skills/drawio-architecture)
+
+### pencil (31)
+- 完整 UI 设计原型工具链
+
+---
+
+## 🔢 工具辅助
+
+### base (5) — Skill 开发质量基础设施
+- [skill-trace-evaluation](skills/base-skills/skill-trace-evaluation) — TRACE 五维度评测
+- [skill-official-evaluation](skills/base-skills/skill-official-evaluation) — 官方规范评测
+- [skill-trace-checker](skills/base-skills/skill-trace-checker) — TRACE 检查
+- [skill-awesome](skills/base-skills/skill-awesome) — Skills AWESOME 列表生成
+
+### chart (2)
+- [ucharts](skills/chart-skills/ucharts) / [lime-echart](skills/chart-skills/lime-echart)
+
+### dev-utils (12)
+- 开发者工具集
+
+### mobile-native (2)
+- [android-kotlin](skills/mobile-native-skills/android-kotlin) / [ios-swift](skills/mobile-native-skills/ios-swift)
+
+### utility (3)
+- [skill-creator](skills/utility-skills/skill-creator) / [skill-installer](skills/utility-skills/skill-installer)
+
+---
+
+## 📝 规范驱动 — openspec/speckit (32)
+- openspec (17) + speckit (15):Spec 驱动开发完整工具链
+
+---
+
+## 🤖 AI — jimeng (8)
+- [jimeng-prompt-text2image](skills/jimeng-skills/...) — 文生图提示词
+- [jimeng-prompt-text2video](skills/jimeng-skills/...) — 文生视频提示词
+- [jimeng-cli-text2image](skills/jimeng-skills/...) — CLI 生图
+- [jimeng-cli-text2video](skills/jimeng-skills/...) — CLI 生视频
+- 等 8 个技能
+
+---
+
+## 其他
+- social (2) / teaching (3) / stitch (31) / ocrmypdf (5) / spring (7)
+
+---
+
+## 📋 本次优化记录
+
+| 优化内容 | 涉及技能 | 成果 |
+|---------|---------|------|
+| **database 全组重写** | redis/mysql/postgresql/oracle/elasticsearch | 空壳 28 行 → 深度参考 76-99KB |
+| **DDD 全组重构** | 15 个 DDD 技能 | TRACE 4.54-4.78,平均 4.66 |
+| **项目规模示例** | 5 个架构技能 | 各 7 种项目规模 + ddd4j 真实参考 |
+| **文件序号化** | 15 个 DDD 技能 | 100% 中英文序号对齐 |
+| **ddd4j 融合** | cola 吸收 project-creator | 删除冗余,保留脚手架能力 |
+
+---
+
+_SkillHub TRACE 评测体系 | agentskills.io 官方规范_

+ 142 - 398
skills/ddd-skills/ddd-api-designer/SKILL.md

@@ -6,455 +6,199 @@ license: Apache-2.0
 
 # DDD API Designer
 
-API design from domain models — expose DDD aggregates through well-designed REST APIs with proper CQRS separation, four-layer data object transformation, unified response format, BFF adaptation, versioning, and security.
+从领域模型到 REST API 的完整设计指南:CQRS 读写分离、四层数据对象转换链(PO→DO→DTO→VO)、统一响应格式、BFF 多端适配、版本管理与安全设计。
 
 ## Workflow
 
-```
-Input: Domain Model (aggregates, entities, value objects)
-  │
-  ├── 1. Identify Command vs Query operations
-  │      └── Commands (POST/PUT/DELETE) → Write Model
-  │      └── Queries (GET)              → Read Model (MV/ReadModel)
-  │
-  ├── 2. Design data object conversion chain
-  │      └── PO(Infra) ↔ DO(Domain) ↔ DTO(Interface) ↔ VO(Frontend)
-  │      └── Define Assembler/Converter per layer boundary
-  │
-  ├── 3. Design REST endpoints per CQRS convention
-  │      └── Command: verb-based suffixes (confirm, cancel, approve)
-  │      └── Query: resource-based naming with parameters
-  │
-  ├── 4. Define unified response format
-  │      └── Success wrapper (code, message, data)
-  │      └── Error response (code, message, detail)
-  │
-  ├── 5. Apply BFF layer if multi-platform
-  │      └── Web BFF / iOS BFF / MiniApp BFF per platform
-  │
-  ├── 6. Choose versioning strategy
-  │      └── URL path recommended: /api/v1/orders
-  │
-  └── 7. Apply security controls
-         └── AuthN + AuthZ + Input validation + Rate limiting
-```
-
-## When to Use This Skill
-
-**ALWAYS use this skill when the user mentions:**
-- "API 设计"、"REST API"、"接口设计"、"endpoint design"
-- "DTO 设计"、"VO 设计"、"data object conversion"
-- "BFF"、"Backend for Frontend"
-- "OpenAPI"、"Swagger"、"API 文档"
-- "数据对象转换"、"PO DO DTO VO"
-- "统一响应格式"、"unified response"
-- "API 版本管理"、"API versioning"
-- "接口安全"、"API security"
-- Need to expose DDD domain models as REST APIs
-
-| ❌ Skip | ✅ Use Instead |
-|---------|---------------|
-| Internal tool, no external API consumers | Skip API design formalities |
-| GraphQL/gRPC project | Use protocol-specific design patterns |
-| No domain model yet | `ddd-domain-designer` (model first) |
-| Simple CRUD, no DDD | Standard Spring Boot Controller |
-| gRPC microservices | gRPC IDL (protobuf), skip REST |
-
-## CQRS: Command vs Query API Differentiation
-
-### Endpoint Separation
-
-```
-Command APIs (Write) — Verb-driven:
-  POST   /api/v1/orders                 → CreateOrderCommand
-  PUT    /api/v1/orders/{id}/confirm    → ConfirmOrderCommand
-  DELETE /api/v1/orders/{id}            → CancelOrderCommand
-  PUT    /api/v1/orders/{id}/ship       → ShipOrderCommand
-
-Query APIs (Read) — Resource-driven:
-  GET    /api/v1/orders/{id}            → OrderDetailDTO (from Materialized View)
-  GET    /api/v1/orders?status=PAID     → OrderSummaryDTO[] (from Read Model)
-  GET    /api/v1/orders/{id}/items      → OrderItemDTO[]
-```
-
-### Key Design Rules
-
-| Rule | Command (Write) | Query (Read) |
-|------|----------------|--------------|
-| HTTP Method | POST / PUT / DELETE | GET |
-| Verb in URL | Yes (confirm, cancel) | No (resource only) |
-| Request Body | Always (command object) | Query parameters only |
-| Response | Created resource / success | Data DTO / list |
-| DTO Separation | Separate Command DTO | Separate Query DTO |
-| Idempotency | Must implement | Naturally idempotent |
-| Cache | Never cached | Cacheable (ETag, max-age) |
-
-**Never share DTO between command and query operations.** Even if fields look similar, they serve different purposes.
-
-### Sub-resource Naming
-
-```
-GET    /orders/{id}/items              → List sub-resources
-POST   /orders/{id}/items              → Create sub-resource
-PUT    /orders/{id}/items/{itemId}     → Update sub-resource
-DELETE /orders/{id}/items/{itemId}     → Remove sub-resource
-```
-
-**Max depth: 2 levels** (`/orders/{id}/items` → OK, `/orders/{id}/items/{itemId}/details` → avoid)
-
-## Data Object Transformation Chain (PO → DO → DTO → VO)
-
-### Four-Layer Object Model
-
-```
-Frontend VO ←→ Interface DTO ←→ Domain DO ←→ Infrastructure PO
-    │               │               │              │
-Display/Client   API Layer       Domain Layer   Data Layer
-```
+1. **识别 Command vs Query** — 将领域行为分为命令(写)和查询(读),决定 Method 和端点
+2. **设计数据对象转换链** — 建立 PO→DO→DTO→VO 四层转换,各层独立职责
+3. **设计 REST 端点** — Command 动词后缀, Query 资源命名
+4. **定义统一响应格式** — Result<T> 包装 + 业务错误码体系
+5. **应用 BFF** — 每前端一个 BFF, 数据聚合 + 格式适配 + 协议转换
+6. **选择版本策略** — 推荐 URL Path: /api/v1/orders, CDN 友好
+7. **施加安全控制** — AuthN + AuthZ + 三层校验 + 差异化限流
+
+## When to Use
 
-| Object | Layer | Responsibility | Visibility |
-|--------|-------|---------------|------------|
-| **PO** (Persistent Object) | Infrastructure | DB schema mapping, ORM entities | Internal |
-| **DO** (Domain Object) | Domain | Rich domain model with business behavior | Internal |
-| **DTO** (Transfer Object) | Interface/App | Cross-layer/cross-service data transport | Semi-internal |
-| **VO** (View Object) | Interface/Frontend | Page-specific display data | External |
+| ✅ ALWAYS use when | ❌ Skip when |
+|---|---|
+| API 设计、REST API、接口设计 | 内部工具无外部消费者 |
+| DTO/VO 设计、数据对象转换 | GraphQL/gRPC 项目 |
+| BFF / Backend for Frontend | 无领域模型时 → domain-designer |
+| OpenAPI / Swagger / API 文档 | 简单 CRUD 无 DDD |
+| API 版本管理 / 安全设计 | 纯 gRPC 微服务(用 protobuf IDL) |
+| 需要将 DDD 聚合暴露为 REST API | 快速原型不关心 API 规范 |
 
-### Transformation Rules
+## Boundary
 
-```
-Read direction (domain → frontend):
-  PO → DO: Repository loads from DB, converts to domain object
-  DO → DTO: Assembler/Converter. One DO → multiple DTOs (different scenarios)
-  DTO → VO: BFF combines multiple DTOs into page-specific VO
-
-Write direction (frontend → domain):
-  VO → DTO: Frontend sends form/request data
-  DTO → DO: Application layer converts to domain command object
-  DO → PO: Repository persists domain changes
-```
+### ✅ 明确适用
+- 需要将 DDD 领域模型暴露为 REST API — CQRS 读写分离、数据对象转换链完整落地
+- CQRS 命令/查询分离设计 — 独立 Command DTO 和 Query DTO,各自演化
+- 多端(Web/iOS/MiniApp)API 统一设计 — BFF 模式按平台适配
+- 统一响应格式与错误码体系设计 — Result<T> + 业务错误码标准化
+- OpenAPI/Swagger 规范输出 — 代码生成策略保持接口与实现同步
 
-### One DO → Multiple DTOs
-
-```java
-public class OrderAssembler {
-    // Detail page — full fields
-    public static OrderDetailDTO toDetailDTO(Order order) {
-        return OrderDetailDTO.builder()
-            .orderId(order.getId().getValue())
-            .status(order.getStatus().name())
-            .totalAmount(order.getTotalAmount().toString())
-            .customerInfo(toCustomerDTO(order.getCustomer()))
-            .paymentInfo(toPaymentDTO(order.getPayment()))
-            .timeline(order.getTimeline())
-            .build();
-    }
-
-    // List page — summary fields only
-    public static OrderSummaryDTO toSummaryDTO(Order order) {
-        return OrderSummaryDTO.builder()
-            .orderId(order.getId().getValue())
-            .status(order.getStatus().name())
-            .totalAmount(order.getTotalAmount().toString())
-            .itemCount(order.getItemCount())
-            .build();
-    }
-}
-```
+### ⚠ 需谨慎评估
+- 团队对 DDD/CQRS 不熟悉 → 先学习基础概念
+- 单体应用无扩展需求 → 评估 ROI,可能过度设计
+- 现有 API 无消费者兼容需求 → 版本管理可简化
 
-## API Design Conventions
+### ❌ 不适用
+- GraphQL/gRPC 项目 → 使用对应 IDL 和工具链
+- 简单 CRUD 无 DDD → 先用通用 REST 框架或 domain-designer
+- 快速原型/演示阶段 → 先用简化 API,后续再引入规范
+- 纯 gRPC 微服务 → 使用 protobuf IDL + gRPC 拦截器
+- 内部工具无外部消费者 → 简化 API 设计
 
-### Naming Rules
+## CQRS API Design
 
-```
-✓ Plural nouns:        /orders (not /order)
-✓ Kebab-case paths:    /order-history (not /orderHistory)
-✓ Max 2-level nesting: /orders/{id}/items
-✓ Write verb suffix:   /orders/{id}/confirm, /orders/{id}/cancel
-✓ Query parameters:    ?status=PAID&page=1&size=20
-✗ No verbs in query:   GET /getOrders (→ GET /orders)
-```
+Command(写)动词驱动,Query(读)资源驱动:
 
-### HTTP Status Code Mapping
-
-| Scenario | HTTP Status | API Code |
-|----------|-------------|----------|
-| Create success | 201 Created | 0 |
-| Read success | 200 OK | 0 |
-| Update success | 200 OK | 0 |
-| Delete success | 204 No Content | 0 |
-| Validation error | 400 Bad Request | 40002 |
-| Business rule violation | 400 Bad Request | 40001 |
-| Not found | 404 Not Found | 40401 |
-| Conflict (optimistic lock) | 409 Conflict | 40901 |
-| Rate limited | 429 Too Many Requests | 42901 |
-| Internal error | 500 Internal Server Error | 50000 |
-
-## Unified Response Format
-
-### Success Responses
-
-```json
-// Command — Created
-{
-  "code": 0,
-  "message": "success",
-  "data": { "orderId": "ORD-2024-001", "status": "PAID", "createdAt": "2024-01-15T10:30:00Z" }
-}
-
-// Query — Single Object
-{
-  "code": 0,
-  "message": "success",
-  "data": { "id": "ORD-2024-001", "totalAmount": "99.00", "status": "PAID", "items": [/* ... */] }
-}
-
-// Query — Paginated
-{
-  "code": 0,
-  "message": "success",
-  "data": {
-    "records": [/* ... */],
-    "total": 100,
-    "page": 1,
-    "pageSize": 20
-  }
-}
-
-// Delete — No Content (204)
-// (empty body)
-```
+| 维度 | Command | Query |
+|------|---------|-------|
+| HTTP Method | POST/PUT/DELETE | GET |
+| URL 动词 | 需要(confirm, cancel) | 不需要 |
+| 请求体 | Command 对象 | 仅查询参数 |
+| DTO 分离 | 独立 Command DTO | 独立 Query DTO |
+| 幂等性 | 必须实现 | 天然幂等 |
+| 缓存 | 从不缓存 | ETag, max-age |
+| 响应 | 创建的资源摘要 | 数据 DTO / 列表 |
 
-### Error Responses
-
-```json
-// Business Error
-{
-  "code": 40001,
-  "message": "订单状态不允许支付",
-  "detail": "当前状态:CANCELLED,可支付状态:DRAFT",
-  "requestId": "req-abc123",
-  "timestamp": "2024-01-15T10:30:00Z"
-}
-
-// Validation Error
-{
-  "code": 40002,
-  "message": "参数校验失败",
-  "detail": [
-    { "field": "amount", "message": "金额不能为负数" },
-    { "field": "customerId", "message": "客户ID不能为空" }
-  ],
-  "requestId": "req-abc123"
-}
-
-// System Error
-{
-  "code": 50000,
-  "message": "系统内部错误",
-  "requestId": "req-abc123"
-}
-```
+原则:Command DTO 和 Query DTO 始终分开定义。子资源嵌套最多 2 层。详见 [references/patterns/cqrs-api-design.md](references/patterns/cqrs-api-design.md)
 
-### Response Wrapper Implementation
+## 数据对象转换链(PO → DO → DTO → VO)
 
-```java
-public class Result<T> {
-    private int code;
-    private String message;
-    private T data;
-    private String requestId;
+| 对象 | 层 | 职责 | 可见性 |
+|------|-----|------|--------|
+| **PO** | Infrastructure | ORM 映射,数据库结构对应 | 内部 |
+| **DO** | Domain | 充血模型,含业务行为 | 内部 |
+| **DTO** | Interface/App | 跨层跨服务数据传输 | 半内部 |
+| **VO** | Interface | 页面专用展示数据 | 外部 |
 
-    public static <T> Result<T> success(T data) {
-        return new Result<>(0, "success", data, null);
-    }
+读方向:PO→DO→DTO→VO;写方向:VO→DTO→Command→DO→PO。
+一个 DO 可按场景转换为多个 DTO(详情 DTO、摘要 DTO 等),Controller 不直接返回领域对象。详见 [references/examples-ref/data-object-transformation.md](references/examples-ref/data-object-transformation.md)
 
-    public static <T> Result<T> error(int code, String message) {
-        return new Result<>(code, message, null, null);
-    }
+## API 设计规范
 
-    public static <T> Result<T> error(int code, String message, String requestId) {
-        return new Result<>(code, message, null, requestId);
-    }
-}
-```
+| 规则 | 示例 |
+|------|------|
+| 名词复数 | /orders ✓ |
+| Kebab-case | /order-history ✓ |
+| 最大 2 层嵌套 | /orders/{id}/items |
+| 写动词后缀 | /orders/{id}/confirm |
+| 查询参数 | ?status=PAID&page=1 |
+| 无 URL 动词 | ❌ GET /getOrders → GET /orders |
 
-## BFF (Backend for Frontend) Design
+HTTP Status:201 Created(创建)、200 OK(查询/更新)、204 No Content(删除)、400(校验/业务)、404(未找到)、409(并发冲突)、429(限流)、500(内部错误)。详见 [references/security/api-naming-conventions.md](references/security/api-naming-conventions.md)
 
-### Architecture
+## 统一响应格式
 
-```
-      ┌──────────┐  ┌──────────┐  ┌──────────┐
-      │  Web BFF │  │ iOS BFF  │  │ MiniApp  │
-      │          │  │          │  │ BFF      │
-      └────┬─────┘  └────┬─────┘  └────┬─────┘
-           │              │              │
-    ┌──────┼──────────────┼──────────────┼──────────┐
-    │      ▼              ▼              ▼          │
-    │  ┌──────────────────────────────────────┐    │
-    │  │         API Gateway / Load Balancer   │    │
-    │  └────┬──────────────┬─────────────┬────┘    │
-    │       ▼              ▼             ▼         │
-    │  ┌─────────┐  ┌──────────┐  ┌─────────┐     │
-    │  │ Order   │  │ Payment  │  │ Product │     │
-    │  │ Service │  │ Service  │  │ Service │     │
-    │  └─────────┘  └──────────┘  └─────────┘     │
-    └───────────────── Microservice Cluster ──────┘
-```
+成功:`{ "code": 0, "message": "success", "data": T }` — 201/200/204
+错误:`{ "code": 40001, "message": "...", "detail": "...", "requestId": "req-xxx" }` — 400/404/409/429/500
 
-### BFF Responsibilities
+Response wrapper `Result<T>` 包含 code + message + data + requestId。错误响应绝不返回堆栈信息。详见 [references/examples-ref/unified-response-format.md](references/examples-ref/unified-response-format.md)
 
-| Responsibility | Description | Example |
-|---------------|-------------|---------|
-| **Data Aggregation** | Combine data from multiple microservices into page-specific VO | Order detail page needs order + payment + shipping data |
-| **Format Adaptation** | Tailor data per platform requirements | Web: full fields; Mobile: minimal fields |
-| **Protocol Translation** | Convert internal protocols to external | Internal gRPC → External REST/JSON |
-| **Response Shaping** | Remove internal fields, add UI metadata | Add page title, action buttons, navigation |
+## BFF(Backend for Frontend)
 
-### BFF vs API Gateway
+每前端一个 BFF(Web/iOS/MiniApp),职责:
+- **数据聚合**:组合多服务数据为页面 VO(1 次前端调用替代 N 次)
+- **格式适配**:Web 全量字段 / 移动端精简字段
+- **协议转换**:内部 gRPC → 外部 REST/JSON
+- **响应塑形**:移除内部字段,添加 UI 元数据
 
-| Aspect | BFF | API Gateway |
-|--------|-----|-------------|
-| Scope | Per-frontend (one BFF per platform) | Unified entry for all services |
-| Logic | Contains view-specific aggregation | Minimal routing, auth, throttling |
-| Granularity | Coarse-grained (page-level) | Fine-grained (service-level) |
-| Example | Web BFF returns `orderPageVO` | Gateway routes `/orders` to Order Service |
+与 API Gateway 区别:BFF 做视图聚合(页面级),Gateway 做路由+限流(服务级)。
+BFF 不直接访问数据库,不包含业务逻辑。详见 [references/patterns/BFF-design-pattern.md](references/patterns/BFF-design-pattern.md)
 
-## API Versioning
+## API 版本管理
 
-### Strategy Comparison
+| 策略 | 示例 | 推荐度 |
+|------|------|:------:|
+| **URL Path** ★ | `/api/v1/orders` → `/api/v2/orders` | ★★★★★ |
+| Request Header | `Accept: vnd.company.v2+json` | ★★★☆☆ |
+| Query Param | `/api/orders?version=2` | ★★☆☆☆ |
 
-| Strategy | How | Pros | Cons | Best For |
-|----------|-----|------|------|----------|
-| **URL Path** | `/api/v1/orders` → `/api/v2/orders` | Most intuitive, CDN-friendly | URL pollution | **Recommended** |
-| Header | `Accept: app.vnd.company.v2+json` | Clean URLs | Hard to test in browser | Advanced clients |
-| Query Param | `/api/orders?version=2` | Simple implementation | Caching chaos | Temporary debug |
-| Content Negotiation | `Accept: app/json;version=2` | RESTful standard | Poor tooling support | REST purists |
+推荐 URL Path:直观、CDN 友好、Swagger 兼容。迁移流程:v1 → v1+v2 → v2 only → v1 sunset(410 Gone)。详见 [references/migration/api-versioning-strategies.md](references/migration/api-versioning-strategies.md)
 
-**Recommendation**: URL path versioning — most intuitive for API consumers, best Swagger/OpenAPI compatibility.
+## API 安全设计
 
-### Version Lifecycle
+四层安全模型:
+1. **认证**:JWT Bearer Token / OAuth2 / API Key(服务间)
+2. **授权**:按限界上下文 + 资源所有权 + 角色
+3. **输入校验**:Controller 格式 → Application 业务 → Domain 不变式
+4. **限流**:Command 50/s, Query 200/s, Auth 10/s。详见 [references/security/api-security-design.md](references/security/api-security-design.md)
 
-```
-v1 (active)  →  v1 + v2 (dual-run)  →  v2 only  →  v1 sunset (deprecated header)
-  [launch]       [migration]            [stable]     [retirement notice]
-```
+## Gotchas — 常见陷阱
 
-## API Security Design
+DTO 暴露枚举→string code | Command/Query DTO 混用→分开 | null 安全→处理 Optional | VO 透传 DB 字段→视图定制 |
+幂等缺失→Idempotency-Key | 错误透传堆栈→requestId | 深层嵌套→≤2 层 | 领域对象序列化→经 DTO/VO
 
-### Security Layers
+## Rules
 
-```
-Layer 1: Authentication — Who are you?
-  ├── JWT Bearer Token (standard for REST APIs)
-  ├── OAuth2 / OpenID Connect (third-party auth)
-  └── API Key (service-to-service, internal)
-
-Layer 2: Authorization — What can you do?
-  ├── Per bounded context: Order BC permissions ≠ Payment BC
-  ├── Resource-based ownership: user only operates own orders
-  └── Role-based access: admin vs regular user vs readonly
-
-Layer 3: Input Validation — What data is allowed?
-  ├── Controller: Format validation (@Valid + JSR-303)
-  ├── Application: Business validation (idempotency, state machine)
-  └── Domain: Invariant validation (inside aggregate root)
-
-Layer 4: Rate Limiting — How much can you do?
-  ├── Command APIs: Lower QPS (prevent write abuse)
-  ├── Query APIs: Higher QPS (can add cache)
-  └── Per-user throttling in BFF/gateway
-```
-
-### OpenAPI Security Schemes
-
-```yaml
-components:
-  securitySchemes:
-    BearerAuth:
-      type: http
-      scheme: bearer
-      bearerFormat: JWT
-    ApiKeyAuth:
-      type: apiKey
-      in: header
-      name: X-API-Key
-```
-
-## Gotchas — Common Pitfalls
-
-- **DTO 直接暴露领域对象字段**: 不要把 `OrderStatus` 枚举直接暴露给 DTO。DTO 应当将领域类型转为 String code,调用方不需要知道内部实现。
-- **Command/Query DTO 混用**: CQRS 下即使 URL 相同(`POST /orders` vs `GET /orders`),请求和响应结构完全不同。Command DTO 和 Query DTO 必须分开定义。
-- **忘记空值安全**: PO → DO 转换时 PO 字段可能为 null(数据库默认 NULL)。必须处理 null 安全(Optional / Objects.requireNonNull),否则构建 DO 时 NPE。
-- **VO 透传数据库字段**: VO 是为前端视图定制的,不要把 `created_at`、`updated_by`、`deleted` 等内部字段透传给前端。只返回前端需要的数据。
-- **版本号只用 Header**: 推荐 URL 路径版本 `/api/v1/orders`。Header 版本对 API 消费者不直观,且无法通过 CDN 缓存区分。
+- **Command/Query DTO 分离** — 写操作和读操作使用独立 DTO,禁止复用同一结构
+- **Controller 协议转换** — Controller 层仅做 HTTP 协议适配,不包含业务逻辑或领域调用
+- **统一错误码前缀** — 业务错误 5 位码:首位类别(4=客户端/5=服务端)+ 后两位 HTTP + 末三位具体错误
+- **BFF 职责边界** — BFF 只做数据聚合与格式适配,不直接访问数据库或不包含业务规则
+- **响应封装** — 所有 API 响应使用 Result&lt;T&gt; 包装,仅 204 No Content 和文件下载可例外
 
 ## FAQ
 
 | Question | Answer |
 |----------|--------|
-| **DO 和 DTO 字段一样能复用吗?** | 不能。DO 是充血模型业务行为,DTO 纯数据传输对象。即使现在字段相同未来演化方向不同。 |
-| **BFF 和服务端渲染有什么区别?** | BFF 是 API 层聚合,返回 JSON 给前端渲染;SSR 是服务端渲染 HTML。BFF 更灵活,SSR 更利于 SEO。 |
-| **OpenAPI 文档需要手动维护吗?** | 推荐代码生成(SpringDoc / swagger-annotations)。手动维护 YAML 容易与实现不同步。 |
-| **所有 API 都要统一响应格式吗?** | 对,Command 和 Query 都统一用 `Result<T>` 包装。只有文件下载、204 No Content 可例外。 |
-| **API 版本多久升级一次?** | 尽量减少破坏性变更。积累多次非兼容变更后统一升级大版本(v1 → v2)。推荐 6-12 个月一次。 |
-| **子资源最多嵌套几层?** | 最多 2 层:`/orders/{id}/items`。超过 2 层说明聚合边界可能有问题,或者需要重新建模。 |
+| DO 和 DTO 字段一样能复用吗? | 不能。DO 含行为,DTO 纯数据,演化方向不同。 |
+| 所有 API 都要统一响应格式? | 是,仅文件下载、204 可例外。 |
+| 错误码怎么设计? | 5 位数字:首位类别+后两位 HTTP+末三位具体错误。 |
+| 何时需要 BFF? | 多前端平台或前端需组合多服务数据。 |
+| 子资源最多嵌套几层? | 最多 2 层,超 2 层说明聚合边界有问题。 |
+| Controller 中能放业务逻辑吗? | 不能,只做协议转换。 |
 
 ## Keywords
 
-`CQRS API` `REST endpoint design` `PO DO DTO VO` `data object transformation` `unified response format` `BFF` `Backend for Frontend` `OpenAPI` `Swagger` `API versioning` `API security` `command query separation` `read model` `materialized view` `Result<T>` `response wrapper` `input validation` `rate limiting`
-
+`CQRS API` `REST endpoint design` `PO DO DTO VO` `data object transformation` `unified response format` `BFF` `Backend for Frontend` `OpenAPI` `Swagger` `API versioning` `API security` `command query separation` `Result<T>` `response wrapper` `input validation` `rate limiting` `idempotency` `pagination design`
 ## References
-
-- [references/cqrs-api-design.md](references/cqrs-api-design.md) — CQRS API 设计模式:命令/查询端点分离、DTO 分拆、幂等设计
-- [references/data-object-transformation.md](references/data-object-transformation.md) — 数据对象转换链详解:PO↔DO↔DTO↔VO 四层边界与转换器模式
-- [references/BFF-design-pattern.md](references/BFF-design-pattern.md) — BFF 设计模式:多平台适配、数据聚合、VO 组装
-- [references/api-security-design.md](references/api-security-design.md) — API 安全设计:JWT/OAuth2、BC 级授权、三层校验、限流
-- [references/api-versioning-strategies.md](references/api-versioning-strategies.md) — API 版本管理:4 种策略对比、迁移流程、OpenAPI 集成
-- [references/api-naming-conventions.md](references/api-naming-conventions.md) — API 命名规范与错误码设计
-- [references/unified-response-format.md](references/unified-response-format.md) — 统一响应格式规范:Result<T> 包装器、错误码体系
-- [references/openapi-specification.md](references/openapi-specification.md) — OpenAPI 3.0 规范:完整 YAML 模板、安全方案、生成策略
-- [references/partme-16-service-data-view.md](references/partme-16-service-data-view.md) — DDD 分层架构下服务和数据的协作关系
-- [references/clean-ddd-hexagonal-hexagonal.md](references/clean-ddd-hexagonal-hexagonal.md) — 六边形架构 Port/Adapter 参考
+- [references/patterns/cqrs-api-design.md](references/patterns/cqrs-api-design.md) — CQRS API 设计
+- [references/examples-ref/data-object-transformation.md](references/examples-ref/data-object-transformation.md) — PO↔DO↔DTO↔VO 转换
+- [references/patterns/BFF-design-pattern.md](references/patterns/BFF-design-pattern.md) — BFF 设计模式
+- [references/security/api-security-design.md](references/security/api-security-design.md) — API 安全
+- [references/migration/api-versioning-strategies.md](references/migration/api-versioning-strategies.md) — 版本管理
+- [references/security/api-naming-conventions.md](references/security/api-naming-conventions.md) — 命名规范
+- [references/examples-ref/unified-response-format.md](references/examples-ref/unified-response-format.md) — 统一响应
+- [references/security/openapi-specification.md](references/security/openapi-specification.md) — OpenAPI 3.0 规范
+- [references/patterns/data-access-api.md](references/patterns/data-access-api.md) — 数据访问层 API 设计
+- [references/patterns/idempotency-design.md](references/patterns/idempotency-design.md) — 幂等设计
+- [references/patterns/pagination-filtering-design.md](references/patterns/pagination-filtering-design.md) — 分页过滤
+- [references/architecture/partme-16-service-data-view.md](references/architecture/partme-16-service-data-view.md) — 协作关系
+- [references/architecture/clean-ddd-hexagonal-hexagonal.md](references/architecture/clean-ddd-hexagonal-hexagonal.md) — 六边形架构
+- [references/examples-ref/api-error-handling.md](references/examples-ref/api-error-handling.md) — 错误处理
+- [references/security/api-rate-limiting.md](references/security/api-rate-limiting.md) — 限流设计
+- [references/examples-ref/event-driven-api.md](references/examples-ref/event-driven-api.md) — 事件驱动 API
 
 ## Examples
 
-- [examples/order-api-design.md](examples/order-api-design.md) — 订单服务完整 API 设计案例(CQRS+数据转换+OpenAPI)
-- [examples/user-api-design.md](examples/user-api-design.md) — 用户服务 API 设计案例(注册/登录/资料)
+- [examples/order-api-design.md](examples/order-api-design.md) — 订单服务案例
+- [examples/user-api-design.md](examples/user-api-design.md) — 用户服务案例:注册/登录/资料 + 安全设计
 - [examples/BFF-aggregation-example.md](examples/BFF-aggregation-example.md) — BFF 聚合案例:订单详情页多服务数据聚合
-- [examples/api-version-migration.md](examples/api-version-migration.md) — API 版本迁移案例:v1 → v2 完整流程
+- [examples/api-version-migration.md](examples/api-version-migration.md) — API 版本迁移案例:v1 → v2 全流程
+- [examples/payment-api-design.md](examples/payment-api-design.md) — 支付服务 API 案例:退款幂等、状态机、异步通知
+- [examples/openapi-codegen-example.md](examples/openapi-codegen-example.md) — OpenAPI 代码生成案例:Spec-first 策略
+- [examples/product-api-design.md](examples/product-api-design.md) — 商品服务 API 案例
+- [examples/inventory-api-design.md](examples/inventory-api-design.md) — 库存服务 API 案例
+- [examples/notification-api-design.md](examples/notification-api-design.md) — 通知服务 API 案例
+- [examples/search-api-design.md](examples/search-api-design.md) — 搜索服务 API 案例
 
 ---
 
 ## 🧭 DDD Skills Journey
 
-> 📍 **You are here: `ddd-api-designer` — Step 4: API 设计与数据转换**
-
-```mermaid
-flowchart LR
-    S1["Step 1<br/>awesome<br/>入门与全景"] --> S2["Step 2<br/>selector<br/>架构选型"]
-    S2 --> S3A["Step 3<br/>layered<br/>分层架构"]
-    S2 --> S3B["Step 3<br/>onion<br/>洋葱架构"]
-    S2 --> S3C["Step 3<br/>hexagonal<br/>六边形架构"]
-    S2 --> S3D["Step 3<br/>clean<br/>整洁架构"]
-    S2 --> S3E["Step 3<br/>cola<br/>COLA v5"]
-    S3A & S3B & S3C & S3D & S3E --> S4A["Step 4<br/>domain-designer<br/>领域建模"]
-    S3A & S3B & S3C & S3D & S3E --> S4B["Step 4<br/>cqrs-architecture<br/>CQRS"]
-    S3A & S3B & S3C & S3D & S3E --> S4C["⭐ Step 4<br/>api-designer<br/>API设计"]
-    S4A & S4B & S4C --> S5["Step 5<br/>code-reviewer<br/>代码审查"]
-    S5 --> S6A["Step 6<br/>event-storming<br/>事件风暴"]
-    S5 --> S6B["Step 6<br/>testing-strategist<br/>测试策略"]
-    S5 --> S6C["Step 6<br/>devops-integration<br/>DevOps"]
-    S5 --> S6D["Step 6<br/>evaluator<br/>架构评估"]
-    S6A & S6B & S6C & S6D --> S7["🏁 Step 7<br/>architecture-doc<br/>架构文档"]
-
-    style S4C fill:#3b82f6,stroke:#2563eb,color:white,stroke-width:3px
-```
+> 📍 **当前:`ddd-api-designer` — Step 4: API 设计与数据转换**
 
-**← Previous**: [domain-designer](../ddd-domain-designer/) — 先有领域模型,再来设计 API
-**→ Next**: [code-reviewer](../ddd-code-reviewer/) — 审查 API 设计是否符合 DDD 规范
-**🔗 Related**: [cqrs-architecture](../ddd-cqrs-architecture/) — CQRS 端点设计 | [architecture-doc](../ddd-architecture-doc/) — 输出 OpenAPI 文档
-**🏠 Home**: [awesome](../ddd-architecture-awesome/) — DDD 概念全景
+```
+Step 1 (awesome) → Step 2 (selector) → Step 3 (架构落地) → Step 4 (领域+CQRS+API) → Step 5 (审查) → Step 6 (辅助) → Step 7 (文档)
+                                                                    ↑
+                                         ⭐ ddd-api-designer: 领域模型 → REST API
+```
 
-💡 Command API(写)和 Query API(读)要分开设计。牢记 PO→DO→DTO→VO 四层转换链。DTO 必须与领域对象解耦,VO 必须与数据库结构解耦。
+**← 上一站**: [ddd-domain-designer](../ddd-domain-designer/) — 先有领域模型再设计 API
+**→ 下一站**: [ddd-code-reviewer](../ddd-code-reviewer/) — 审查 API 设计合规性
+**🔗 相关**: [ddd-cqrs-architecture](../ddd-cqrs-architecture/) — CQRS 深入 | [ddd-architecture-doc](../ddd-architecture-doc/) — OpenAPI 文档输出
 
-> 📋 See [DESIGN.md](../DESIGN.md) for the complete 16-skill ecosystem map.
+> 核心原则:Command 和 Query 分开设计。牢记 PO→DO→DTO→VO 四层转换链,DTO 与领域对象解耦,VO 与数据库结构解耦。

+ 209 - 0
skills/ddd-skills/ddd-api-designer/examples/01-BFF-aggregation-example.md

@@ -0,0 +1,209 @@
+# BFF 聚合案例:订单详情页
+
+> 演示 BFF 层如何将多个微服务的数据聚合到一个页面专用的 VO。
+
+## 场景
+
+**订单详情页**需要展示以下数据:
+
+```
+┌─ 订单详情页 ──────────────────────────────────────────┐
+│                                                        │
+│  订单信息: #ORD-2024-001                               │
+│  状态: 已支付  |  金额: ¥99.00                         │
+│                                                        │
+│  ├─ 商品清单:                                          │
+│  │  1. T-Shirt × 2 — ¥49.50/件                        │
+│  │  2. 牛仔裤 × 1 — ¥199.00/件                        │
+│  │                                                        │
+│  ├─ 支付信息:                                          │
+│  │  支付方式: 微信支付                                 │
+│  │  支付时间: 2024-01-15 10:30                         │
+│  │                                                        │
+│  ├─ 物流信息:                                          │
+│  │  快递单号: SF-1234567890                            │
+│  │  预计送达: 2024-01-20                               │
+│  │                                                        │
+│  └─ 操作按钮: [取消订单] [申请退款] [查看物流]          │
+└────────────────────────────────────────────────────────┘
+```
+
+## 无 BFF 的痛点
+
+```
+前端需要调用 4 个不同的 API:
+  1. GET /api/v1/orders/{id}             → Order Service
+  2. GET /api/v1/orders/{id}/items       → Order Service (or nested)
+  3. GET /api/v1/payments/order/{id}     → Payment Service
+  4. GET /api/v1/shipping/order/{id}     → Shipping Service
+
+问题:
+  - 4 次 HTTP 调用,延迟叠加
+  - 前端需要处理部分失败(某个服务挂了)
+  - 前端需要自己组合数据
+  - 每个页面都重复这种组合逻辑
+```
+
+## BFF 聚合方案
+
+### BFF 端点
+
+```
+GET /api/web-bff/order-detail/{orderId}
+```
+
+### BFF 内部调用链
+
+```
+BFF OrderDetailService
+  │
+  ├── (并行) → Order Service (gRPC)     → OrderDetailDO
+  │               getOrder(orderId)
+  │
+  ├── (并行) → Payment Service (gRPC)   → PaymentDTO
+  │               getPaymentByOrder(orderId)
+  │
+  ├── (并行) → Shipping Service (gRPC)  → ShippingDTO
+  │               getShippingByOrder(orderId)
+  │
+  └── 组装 → OrderDetailVO (返回给前端)
+```
+
+### BFF 服务实现
+
+```java
+@Service
+public class OrderDetailBffService {
+
+    private final OrderServiceClient orderClient;
+    private final PaymentServiceClient paymentClient;
+    private final ShippingServiceClient shippingClient;
+
+    public OrderDetailVO getOrderDetail(String orderId) {
+        // 并行调用三个微服务
+        CompletableFuture<OrderDetailDO> orderFuture =
+            CompletableFuture.supplyAsync(() -> orderClient.getOrder(orderId));
+        CompletableFuture<PaymentDTO> paymentFuture =
+            CompletableFuture.supplyAsync(() -> paymentClient.getPaymentByOrder(orderId));
+        CompletableFuture<ShippingDTO> shippingFuture =
+            CompletableFuture.supplyAsync(() -> shippingClient.getShippingByOrder(orderId));
+
+        // 等待所有调用完成(带超时)
+        CompletableFuture.allOf(orderFuture, paymentFuture, shippingFuture)
+            .get(3, TimeUnit.SECONDS);
+
+        // 组装 VO
+        OrderDetailDO order = orderFuture.get();
+        PaymentDTO payment = paymentFuture.get();      // 可能为 null(未支付)
+        ShippingDTO shipping = shippingFuture.get();    // 可能为 null(未发货)
+
+        return OrderDetailVO.builder()
+            .orderId(order.getOrderId())
+            .status(order.getStatus())
+            .statusText(getStatusText(order.getStatus()))
+            .totalAmount(order.getTotalAmount())
+            .items(order.getItems().stream()
+                .map(this::toItemVO)
+                .toList())
+            .payment(payment != null ? toPaymentVO(payment) : null)
+            .shipping(shipping != null ? toShippingVO(shipping) : null)
+            .actions(determineActions(order.getStatus()))
+            .build();
+    }
+
+    private List<String> determineActions(OrderStatus status) {
+        return switch (status) {
+            case DRAFT -> List.of("pay", "cancel");
+            case PAID -> List.of("cancel", "apply_refund");
+            case SHIPPED -> List.of("track", "confirm_receipt");
+            case DELIVERED -> List.of("review", "apply_return");
+            case CANCELLED -> List.of("reorder");
+        };
+    }
+}
+```
+
+### BFF VO 定义
+
+```json
+// BFF 返回的前端 VO
+GET /api/web-bff/order-detail/ORD-2024-001 → 200
+
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "orderId": "ORD-2024-001",
+    "status": "PAID",
+    "statusText": "已支付",
+    "totalAmount": "¥298.00",
+
+    "items": [
+      { "productName": "T-Shirt", "imageUrl": "https://cdn.com/tshirt.jpg",
+        "quantity": 2, "unitPrice": "¥49.50", "subtotal": "¥99.00" },
+      { "productName": "牛仔裤", "imageUrl": "https://cdn.com/jeans.jpg",
+        "quantity": 1, "unitPrice": "¥199.00", "subtotal": "¥199.00" }
+    ],
+
+    "payment": {
+      "method": "微信支付",
+      "amount": "¥298.00",
+      "paidAt": "2024-01-15T10:30:00"
+    },
+
+    "shipping": null,
+
+    "actions": ["cancel", "apply_refund"],
+    "createdAt": "2024-01-15T10:30:00",
+
+    "ui": {
+      "pageTitle": "订单详情",
+      "primaryAction": "取消订单",
+      "primaryActionColor": "red"
+    }
+  }
+}
+```
+
+## 部分失败处理
+
+```java
+public OrderDetailVO getOrderDetailSafe(String orderId) {
+    OrderDetailDO order = null;
+    PaymentDTO payment = null;
+    ShippingDTO shipping = null;
+    List<String> warnings = new ArrayList<>();
+
+    try {
+        order = orderClient.getOrder(orderId);
+    } catch (Exception e) {
+        // Order service is critical — fail the whole request
+        throw new BffException("订单服务暂时不可用", e);
+    }
+
+    try {
+        payment = paymentClient.getPaymentByOrder(orderId);
+    } catch (Exception e) {
+        warnings.add("支付信息暂时不可用");
+    }
+
+    try {
+        shipping = shippingClient.getShippingByOrder(orderId);
+    } catch (Exception e) {
+        warnings.add("物流信息暂时不可用");
+    }
+
+    OrderDetailVO vo = assembleVO(order, payment, shipping);
+    vo.setWarnings(warnings);
+    return vo;
+}
+```
+
+## BFF 响应超时策略
+
+| 策略 | 实现 | 适用场景 |
+|------|------|---------|
+| Wait All | `CompletableFuture.allOf().get(timeout)` | 核心数据 |
+| Wait Fast | 先返回已就绪的数据,慢的异步补充 | 非关键数据 |
+| Fallback | 下游超时时返回默认值 | 可选数据 |
+| Circuit Break | 下游连续失败后快速失败 | 防止雪崩 |

+ 420 - 0
skills/ddd-skills/ddd-api-designer/examples/02-api-version-migration.md

@@ -0,0 +1,420 @@
+# API 版本迁移案例:v1 → v2
+
+> 展示从 v1 到 v2 的完整 API 版本迁移过程,包括变更分析、兼容策略、OpenAPI 差异。
+
+## 背景
+
+订单服务 API v1 已运行 1 年。产品团队要求新增以下功能:
+1. 支持多币种(原来只有人民币)
+2. 订单项需要拆分展示
+3. 增加分页标准化
+
+这些变更涉及响应体字段变更,不兼容 v1,因此需要 v2。
+
+## 变更分析
+
+| 变更项 | 类型 | v1 | v2 |
+|--------|------|----|----|
+| ID 字段名 | 重命名 | `id` (int) | `orderId` (string) |
+| 金额格式 | 类型变更 | `amount` (number) | `totalAmount` (string) + `currency` |
+| 订单项 | 新增 | 无独立列表 | `items` array |
+| 响应封装 | 结构变更 | 裸数据 | `Result<T>` 包装 |
+| 分页 | 标准化 | 无标准分页 | `page/size/total/records` |
+
+## v1 端点
+
+### v1 OpenAPI
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  version: 1.0.0
+servers:
+  - url: https://api.example.com/api/v1
+
+paths:
+  /orders:
+    get:
+      summary: List orders
+      parameters:
+        - name: status
+          in: query
+          schema:
+            type: string
+      responses:
+        '200':
+          description: Order list
+          content:
+            application/json:
+              schema:
+                type: array
+                items:
+                  $ref: '#/components/schemas/OrderV1'
+    post:
+      summary: Create order
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/CreateOrderRequestV1'
+      responses:
+        '201':
+          description: Created
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderV1'
+
+components:
+  schemas:
+    OrderV1:
+      type: object
+      properties:
+        id:
+          type: integer
+          example: 1
+        status:
+          type: string
+          example: PAID
+        amount:
+          type: number
+          example: 99.00
+
+    CreateOrderRequestV1:
+      type: object
+      properties:
+        customer_id:
+          type: integer
+        items:
+          type: array
+          items:
+            type: object
+            properties:
+              product_id:
+                type: integer
+              quantity:
+                type: integer
+```
+
+### v1 返回示例
+
+```json
+// GET /api/v1/orders?status=PAID
+[
+  {
+    "id": 1,
+    "status": "PAID",
+    "amount": 99.00
+  },
+  {
+    "id": 2,
+    "status": "PAID",
+    "amount": 199.00
+  }
+]
+
+// POST /api/v1/orders
+{
+  "id": 3,
+  "status": "DRAFT",
+  "amount": 299.00
+}
+```
+
+## v2 端点
+
+### v2 OpenAPI
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  version: 2.0.0
+servers:
+  - url: https://api.example.com/api/v2
+
+paths:
+  /orders:
+    get:
+      summary: List orders with pagination
+      parameters:
+        - name: status
+          in: query
+          schema:
+            type: string
+            enum: [DRAFT, PAID, SHIPPED, CANCELLED]
+        - name: page
+          in: query
+          schema:
+            type: integer
+            default: 1
+        - name: size
+          in: query
+          schema:
+            type: integer
+            default: 20
+      responses:
+        '200':
+          description: Paginated order list
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderListResponseV2'
+    post:
+      summary: Create order
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/CreateOrderRequestV2'
+      responses:
+        '201':
+          description: Created
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/ApiResponse'
+
+components:
+  schemas:
+    OrderV2:
+      type: object
+      properties:
+        orderId:
+          type: string
+          example: ORD-2024-001
+        status:
+          type: string
+          example: PAID
+        totalAmount:
+          type: string
+          example: "99.00"
+        currency:
+          type: string
+          example: CNY
+        items:
+          type: array
+          items:
+            $ref: '#/components/schemas/OrderItemV2'
+        createdAt:
+          type: string
+          format: date-time
+
+    OrderItemV2:
+      type: object
+      properties:
+        productName:
+          type: string
+        quantity:
+          type: integer
+        unitPrice:
+          type: string
+        subtotal:
+          type: string
+
+    OrderListResponseV2:
+      type: object
+      properties:
+        code:
+          type: integer
+          example: 0
+        message:
+          type: string
+        data:
+          type: object
+          properties:
+            records:
+              type: array
+              items:
+                $ref: '#/components/schemas/OrderSummaryV2'
+            total:
+              type: integer
+              example: 100
+            page:
+              type: integer
+              example: 1
+            pageSize:
+              type: integer
+              example: 20
+
+    OrderSummaryV2:
+      type: object
+      properties:
+        orderId:
+          type: string
+        status:
+          type: string
+        totalAmount:
+          type: string
+        itemCount:
+          type: integer
+        createdAt:
+          type: string
+          format: date-time
+
+    ApiResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+          example: 0
+        message:
+          type: string
+          example: success
+        data:
+          type: object
+
+    CreateOrderRequestV2:
+      type: object
+      required: [customerId, items, currency]
+      properties:
+        customerId:
+          type: string
+        currency:
+          type: string
+          enum: [CNY, USD, EUR]
+        items:
+          type: array
+          items:
+            type: object
+            properties:
+              productId:
+                type: string
+              quantity:
+                type: integer
+```
+
+### v2 返回示例
+
+```json
+// GET /api/v2/orders?status=PAID&page=1
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "records": [
+      {
+        "orderId": "ORD-2024-001",
+        "status": "PAID",
+        "totalAmount": "99.00",
+        "itemCount": 2,
+        "currency": "CNY",
+        "createdAt": "2024-01-15T10:30:00Z"
+      }
+    ],
+    "total": 1,
+    "page": 1,
+    "pageSize": 20,
+    "totalPages": 1
+  }
+}
+
+// POST /api/v2/orders
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "orderId": "ORD-2024-003",
+    "status": "DRAFT",
+    "createdAt": "2024-01-16T14:00:00Z"
+  }
+}
+```
+
+## 兼容策略:双运行期
+
+### 路由方案
+
+```
+API Gateway:
+  /api/v1/*  → Order Service v1 (old deployment)
+  /api/v2/*  → Order Service v2 (new deployment)
+
+Internal routing:
+  v1 service  → v1 DB schema
+  v2 service  → v2 DB schema (migrated)
+```
+
+### 适配层(v1 → v2 数据转换)
+
+当 v1 用户调用 v2 端点时,通过适配器转换:
+
+```java
+@Component
+public class OrderV1ToV2Adapter {
+
+    public OrderListResponseV2 adapt(List<OrderV1> v1Orders) {
+        List<OrderSummaryV2> records = v1Orders.stream()
+            .map(v1 -> new OrderSummaryV2(
+                "ORD-" + v1.getId(),           // id → orderId
+                v1.getStatus(),
+                String.format("%.2f", v1.getAmount()),  // number → string
+                0,                             // itemCount (v1 didn't have it)
+                null                           // createdAt (v1 didn't have timestamp)
+            ))
+            .collect(toList());
+
+        return new OrderListResponseV2(
+            0, "success",
+            new PaginatedData<>(records, records.size(), 1, records.size(), 1)
+        );
+    }
+}
+```
+
+## 迁移时间线
+
+```
+2024-Q1: v2 设计 + 开发
+2024-Q2: v2 上线,v1 + v2 双运行
+          └── 通知所有 v1 客户端开始迁移
+2024-Q3: v1 废弃期
+          └── v1 响应添加 Deprecated header
+          └── v1 流量监控
+2024-Q4: v1 下线
+          └── v1 端点返回 410 Gone
+          └── 删除 v1 代码和部署
+```
+
+## 客户端迁移指南
+
+```markdown
+# 迁移到 Order API v2
+
+## 关键变更
+
+1. `id` → `orderId`(int → string)
+2. 响应改为 Result<T> 包装
+3. 分页标准化为 records/page/size/total
+4. 金额改为字符串格式 "99.00" + 新增 currency 字段
+
+## 迁移步骤
+
+### Step 1:更新请求
+```diff
+- POST /api/v1/orders
+- { "customer_id": 1, "items": [...] }
++ POST /api/v2/orders
++ { "customerId": "USR-001", "currency": "CNY", "items": [...] }
+```
+
+### Step 2:更新响应解析
+```diff
+- const orderId = response.id;
++ const orderId = response.data.orderId;
+```
+
+### Step 3:更新分页处理
+```diff
+- const total = response.length;
++ const total = response.data.total;
++ const page = response.data.page;
+```
+
+## 回退方案
+如遇兼容性问题,切换回 /api/v1/ 端点并报告问题。
+v1 将在 2024-Q4 下线。
+```

+ 27 - 0
skills/ddd-skills/ddd-api-designer/examples/03-inventory-api-design.md

@@ -0,0 +1,27 @@
+# 库存服务 API 设计案例
+
+> 库存限界上下文(Inventory BC)的 REST API 设计,展示库存扣减、锁定、释放等 CQRS 场景。
+
+## 领域模型
+
+```
+Inventory (Aggregate Root)
+├── SkuId
+├── AvailableQty
+├── LockedQty
+└── WarehouseCode
+```
+
+## 端点设计
+
+| 端点 | 类型 | 说明 |
+|------|------|------|
+| `POST /api/v1/inventory/lock` | Command | 锁定库存(下单) |
+| `POST /api/v1/inventory/release` | Command | 释放库存(取消) |
+| `POST /api/v1/inventory/deduct` | Command | 扣减库存(支付) |
+| `GET /api/v1/inventory/{skuId}` | Query | 库存查询 |
+| `GET /api/v1/inventory/warehouse/{code}` | Query | 仓库库存概览 |
+
+## 幂等设计
+
+锁定/扣减操作使用 `Idempotency-Key` 防止重复处理,服务端缓存 TTL 24h。

+ 26 - 0
skills/ddd-skills/ddd-api-designer/examples/04-notification-api-design.md

@@ -0,0 +1,26 @@
+# 通知服务 API 设计案例
+
+> 通知限界上下文(Notification BC)的 REST API 设计,展示消息发送、模板管理等场景。
+
+## 领域模型
+
+```
+Notification (Entity)
+├── NotificationId
+├── UserId
+├── Channel: EMAIL / SMS / PUSH
+├── TemplateId
+├── Status: PENDING / SENT / FAILED
+└── SentAt
+```
+
+## 端点设计
+
+| 端点 | 类型 | 说明 |
+|------|------|------|
+| `POST /api/v1/notifications/send` | Command | 发送通知 |
+| `POST /api/v1/notifications/batch` | Command | 批量发送 |
+| `GET /api/v1/notifications/{id}` | Query | 通知详情 |
+| `GET /api/v1/notifications?userId=&status=` | Query | 用户通知列表 |
+| `POST /api/v1/notification-templates` | Command | 创建模板 |
+| `GET /api/v1/notification-templates` | Query | 模板列表 |

+ 316 - 0
skills/ddd-skills/ddd-api-designer/examples/05-openapi-codegen-example.md

@@ -0,0 +1,316 @@
+# OpenAPI 代码生成案例
+
+> 展示 Spec-first 策略:从 OpenAPI 规范生成服务端骨架和客户端 SDK。
+
+## 策略选择
+
+| 策略 | 适用 | 工作流 |
+|------|------|--------|
+| **Code-first** | 内部服务、快速迭代 | 注解 → 运行时导出 Spec → 生成客户端 |
+| **Spec-first** | 公共 API、团队协作 | 先写 YAML → 生成服务端骨架 → 补齐业务逻辑 |
+| **Hybrid** | 企业级、多消费者 | 注解 + 规范审查 → 导出 → 生成 SDK |
+
+**推荐**:内部 DDD 服务用 Code-first(SpringDoc),公共 API 用 Spec-first(openapi-generator)。
+
+## 场景:支付服务 API 规范(Spec-first)
+
+### 1. 编写 OpenAPI 规范
+
+```yaml
+# payment-api-v1.yaml
+openapi: 3.0.3
+info:
+  title: Payment Service API
+  version: 1.0.0
+  description: 支付服务 API — 支付发起、回调、退款
+servers:
+  - url: https://api.example.com/api/v1
+
+paths:
+  /payments:
+    post:
+      operationId: initiatePayment
+      tags: [Payment Commands]
+      parameters:
+        - name: Idempotency-Key
+          in: header
+          required: true
+          schema:
+            type: string
+            format: uuid
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/InitiatePaymentRequest'
+      responses:
+        '201':
+          description: 支付发起成功
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/PaymentCreatedResponse'
+        '400':
+          $ref: '#/components/responses/BusinessError'
+      x-springdoc-default: "40001"
+
+  /payments/{paymentId}:
+    get:
+      operationId: getPayment
+      tags: [Payment Queries]
+      parameters:
+        - name: paymentId
+          in: path
+          required: true
+          schema:
+            type: string
+            pattern: '^PAY-\d{4}-\d{3,6}$'
+      responses:
+        '200':
+          description: 支付详情
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/PaymentDetailResponse'
+
+components:
+  schemas:
+    InitiatePaymentRequest:
+      type: object
+      required: [orderId, amount, currency, method]
+      properties:
+        orderId:
+          type: string
+          example: ORD-2024-001
+        amount:
+          type: string
+          example: "99.00"
+        currency:
+          type: string
+          enum: [CNY, USD]
+        method:
+          type: string
+          enum: [WECHAT_PAY, ALIPAY, CARD]
+
+    PaymentCreatedData:
+      type: object
+      properties:
+        paymentId:
+          type: string
+        status:
+          type: string
+          enum: [PROCESSING]
+        payUrl:
+          type: string
+        expiresIn:
+          type: integer
+
+    PaymentCreatedResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+          example: 0
+        message:
+          type: string
+        data:
+          $ref: '#/components/schemas/PaymentCreatedData'
+
+    PaymentDetailData:
+      type: object
+      properties:
+        paymentId:
+          type: string
+        orderId:
+          type: string
+        status:
+          type: string
+        amount:
+          type: string
+        method:
+          type: string
+        channelOrderNo:
+          type: string
+        createdAt:
+          type: string
+          format: date-time
+
+    PaymentDetailResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+        message:
+          type: string
+        data:
+          $ref: '#/components/schemas/PaymentDetailData'
+
+    ApiError:
+      type: object
+      properties:
+        code:
+          type: integer
+        message:
+          type: string
+        detail:
+          type: string
+        requestId:
+          type: string
+
+  responses:
+    BusinessError:
+      description: Business error
+      content:
+        application/json:
+          schema:
+            $ref: '#/components/schemas/ApiError'
+```
+
+### 2. 生成服务端骨架
+
+```bash
+# 使用 openapi-generator 生成 Java Spring 服务端
+openapi-generator generate \
+  -i payment-api-v1.yaml \
+  -g spring \
+  -o payment-service \
+  --api-package com.example.payment.adapter.inbound.web \
+  --model-package com.example.payment.adapter.inbound.dto \
+  --additional-properties=interfaceOnly=true
+
+# 生成目录结构
+payment-service/
+├── src/main/java/com/example/payment/adapter/inbound/
+│   ├── web/
+│   │   ├── PaymentApi.java                     # 生成的接口
+│   │   └── PaymentApiController.java           # 生成的骨架
+│   └── dto/
+│       ├── InitiatePaymentRequest.java         # 生成的请求 DTO
+│       ├── PaymentCreatedResponse.java         # 生成的响应 DTO
+│       └── ApiError.java                       # 生成的错误 DTO
+```
+
+### 3. 实现业务逻辑
+
+```java
+@RestController
+public class PaymentController implements PaymentApi {
+
+    private final PaymentApplicationService paymentService;
+
+    @Override
+    public ResponseEntity<PaymentCreatedResponse> initiatePayment(
+            String idempotencyKey,
+            InitiatePaymentRequest request) {
+
+        // 1. 请求 DTO → 命令对象
+        InitiatePaymentCommand command = new InitiatePaymentCommand(
+            OrderId.of(request.getOrderId()),
+            Money.of(request.getAmount(), Currency.valueOf(request.getCurrency())),
+            PaymentMethod.valueOf(request.getMethod())
+        );
+
+        // 2. 调用应用服务
+        PaymentResult result = paymentService.initiate(command, idempotencyKey);
+
+        // 3. 领域结果 → 响应 DTO
+        PaymentCreatedData data = new PaymentCreatedData();
+        data.setPaymentId(result.getPaymentId());
+        data.setStatus("PROCESSING");
+        data.setPayUrl(result.getPayUrl());
+        data.setExpiresIn(300);
+
+        PaymentCreatedResponse response = new PaymentCreatedResponse();
+        response.setCode(0);
+        response.setMessage("success");
+        response.setData(data);
+
+        return ResponseEntity.status(201).body(response);
+    }
+}
+```
+
+### 4. 生成客户端 SDK
+
+```bash
+# 生成 TypeScript 客户端
+openapi-generator generate \
+  -i payment-api-v1.yaml \
+  -g typescript-axios \
+  -o payment-client-ts
+
+# 生成 Java 客户端
+openapi-generator generate \
+  -i payment-api-v1.yaml \
+  -g java \
+  -o payment-client-java
+```
+
+### 5. 客户端使用
+
+```typescript
+// TypeScript 客户端
+import { PaymentApi } from './payment-client-ts';
+
+const api = new PaymentApi();
+
+// 发起支付
+const response = await api.initiatePayment(
+  { orderId: "ORD-2024-001", amount: "99.00", currency: "CNY", method: "WECHAT_PAY" },
+  { headers: { "Idempotency-Key": uuidv4() } }
+);
+
+console.log(response.data.data.payUrl);  // weixin://pay/...
+```
+
+## Code-first 方案(SpringDoc 注解)
+
+```java
+@RestController
+@RequestMapping("/api/v1/payments")
+@Tag(name = "Payment Commands", description = "支付命令端点")
+public class PaymentController {
+
+    @Operation(summary = "发起支付", operationId = "initiatePayment")
+    @ApiResponses({
+        @ApiResponse(responseCode = "201", description = "支付发起成功"),
+        @ApiResponse(responseCode = "400", description = "业务错误",
+            content = @Content(schema = @Schema(implementation = ApiError.class)))
+    })
+    @PostMapping
+    public ResponseEntity<PaymentCreatedResponse> initiatePayment(
+            @RequestHeader("Idempotency-Key") @Parameter(description = "幂等键")
+            String idempotencyKey,
+            @RequestBody @Valid InitiatePaymentRequest request) {
+        // ...
+    }
+}
+```
+
+导出 Spec:
+
+```yaml
+# application.yml
+springdoc:
+  api-docs:
+    path: /api-docs
+  swagger-ui:
+    path: /swagger-ui.html
+  packages-to-scan: com.example.payment.adapter.inbound.web
+```
+
+```bash
+# 运行期导出 OpenAPI 规范
+curl http://localhost:8080/api-docs > payment-api-spec.yaml
+```
+
+## OpenAPI 代码生成最佳实践
+
+1. **每个 BC 一个 Spec 文件**:Order BC 和 Payment BC 的 Spec 独立管理
+2. **用 operationId 对应方法名**:便于代码生成的方法映射
+3. **接口优先**(interfaceOnly=true):生成接口,不生成实现,避免覆盖业务代码
+4. **DTO 和 VO 不走代码生成**:DDD 项目中的 DTO/VO 应手工设计,annotations 不适合复杂 DTO 结构
+5. **Spec 纳入版本控制**:每次 API 变更必须更新 Spec 文件
+6. **Spec diff 作为 Code Review 一部分**:审查 Spec 变更后再合入
+7. **客户端 SDK 按需生成**:不要将生成的 SDK 提交到仓库,通过 CI 按需构建

+ 241 - 0
skills/ddd-skills/ddd-api-designer/examples/06-order-api-design.md

@@ -0,0 +1,241 @@
+# 订单服务完整 API 设计案例
+
+> 基于 DDD 订单聚合,完整展示 CQRS 分离、数据对象转换链、BFF 适配。
+
+## 领域模型
+
+```
+Order (Aggregate Root)
+├── OrderId (ValueObject)
+├── OrderStatus: DRAFT → PAID → SHIPPED → DELIVERED
+│                   ↘ CANCELLED
+├── CustomerId (ValueObject) — 引用客户聚合
+├── List<OrderItem> (Entity)
+│   ├── OrderItemId
+│   ├── ProductId — 引用商品聚合
+│   ├── Quantity
+│   └── UnitPrice
+├── Money totalAmount (ValueObject)
+└── List<DomainEvent>
+```
+
+## 1. CQRS 端点设计
+
+### 命令端点(写)
+
+```
+POST   /api/v1/orders                    → 创建订单
+PUT    /api/v1/orders/{orderId}/confirm   → 确认订单
+PUT    /api/v1/orders/{orderId}/ship      → 标记发货
+PUT    /api/v1/orders/{orderId}/deliver   → 标记送达
+DELETE /api/v1/orders/{orderId}           → 取消订单
+```
+
+### 查询端点(读)
+
+```
+GET    /api/v1/orders/{orderId}           → 订单详情
+GET    /api/v1/orders?status=PAID&page=1  → 订单列表
+GET    /api/v1/orders/{orderId}/items     → 订单项列表
+```
+
+## 2. 数据对象转换链
+
+```
+PO (OrderPO) ↔ DO (Order) ↔ DTO (OrderDTO) ↔ VO (OrderDetailVO / OrderSummaryVO)
+```
+
+### PO — 基础设施层
+
+```java
+@Entity
+@Table(name = "orders")
+public class OrderPO {
+    @Id
+    private Long id;
+    private String orderNo;
+    private String status;       // 数据库存字符串
+    private Long customerId;
+    private BigDecimal totalAmount;
+    private String currency;
+    private LocalDateTime createdAt;
+    private LocalDateTime updatedAt;
+    private Integer version;     // 乐观锁
+}
+```
+
+### DO — 领域层
+
+```java
+public class Order extends AggregateRoot<OrderId> {
+    private OrderId id;
+    private OrderStatus status;
+    private CustomerId customerId;
+    private Money totalAmount;
+    private List<OrderItem> items;
+
+    public Order(OrderId id, CustomerId customerId, List<OrderItem> items) {
+        this.id = id;
+        this.customerId = customerId;
+        this.items = Collections.unmodifiableList(items);
+        this.status = OrderStatus.DRAFT;
+        this.totalAmount = calculateTotal();
+        addDomainEvent(new OrderCreatedEvent(id, customerId, totalAmount));
+    }
+
+    public void confirm() {
+        if (!status.canConfirm()) {
+            throw new BusinessException(40001, "订单状态不允许确认",
+                "当前状态:" + status + ",可确认状态:DRAFT");
+        }
+        this.status = OrderStatus.CONFIRMED;
+        addDomainEvent(new OrderConfirmedEvent(id));
+    }
+
+    private Money calculateTotal() {
+        return items.stream()
+            .map(OrderItem::getSubtotal)
+            .reduce(Money.ZERO, Money::add);
+    }
+}
+```
+
+### DTO — 接口层
+
+```java
+// 命令 DTO
+public record CreateOrderRequest(
+    @NotNull String customerId,
+    @NotEmpty List<@Valid OrderItemRequest> items
+) {
+    public CreateOrderCommand toCommand() {
+        return new CreateOrderCommand(
+            CustomerId.of(this.customerId()),
+            this.items().stream().map(OrderItemRequest::toItem).toList()
+        );
+    }
+}
+
+// 查询 DTO
+public record OrderDetailDTO(
+    String orderId,
+    String status,
+    String totalAmount,
+    List<OrderItemDTO> items,
+    String createdAt
+) {}
+```
+
+### VO — 前端视图
+
+```json
+{
+  "orderId": "ORD-2024-001",
+  "status": "PAID",
+  "statusText": "已支付",
+  "totalAmount": "¥99.00",
+  "items": [
+    { "productName": "T-Shirt", "quantity": 2, "price": "¥49.50" }
+  ],
+  "actions": ["cancel", "apply_return"]
+}
+```
+
+## 3. 转换器(Assembler)
+
+```java
+public class OrderAssembler {
+    // DO → DTO (read direction)
+    public static OrderDetailDTO toDetailDTO(Order order) {
+        return new OrderDetailDTO(
+            order.getId().getValue(),
+            order.getStatus().name(),
+            order.getTotalAmount().toString(),
+            order.getItems().stream().map(OrderAssembler::toItemDTO).toList(),
+            order.getCreatedAt().toString()
+        );
+    }
+
+    public static OrderSummaryDTO toSummaryDTO(Order order) {
+        return new OrderSummaryDTO(
+            order.getId().getValue(),
+            order.getStatus().name(),
+            order.getTotalAmount().toString(),
+            order.getItems().size()
+        );
+    }
+
+    // Command → DO (write direction)
+    public static Order toDomain(CreateOrderCommand command) {
+        List<OrderItem> items = command.items().stream()
+            .map(item -> new OrderItem(
+                OrderItemId.generate(),
+                ProductId.of(item.productId()),
+                item.quantity(),
+                item.unitPrice()
+            )).toList();
+        return new Order(OrderId.generate(), command.customerId(), items);
+    }
+}
+```
+
+## 4. 统一响应
+
+```json
+// 创建订单成功
+POST /api/v1/orders → 201
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "orderId": "ORD-2024-001",
+    "status": "DRAFT",
+    "createdAt": "2024-01-15T10:30:00Z"
+  }
+}
+
+// 订单列表查询
+GET /api/v1/orders?status=PAID&page=1 → 200
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "records": [
+      { "orderId": "ORD-2024-001", "status": "PAID", "totalAmount": "99.00", "itemCount": 2 }
+    ],
+    "total": 1,
+    "page": 1,
+    "pageSize": 20,
+    "totalPages": 1
+  }
+}
+```
+
+## 5. OpenAPI 摘要
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  version: 1.0.0
+servers:
+  - url: https://api.example.com/api/v1
+paths:
+  /orders:
+    post:
+      tags: [Order Commands]
+      summary: Create order
+      requestBody:
+        $ref: '#/components/schemas/CreateOrderRequest'
+      responses:
+        '201': { $ref: '#/components/schemas/OrderCreatedResponse' }
+    get:
+      tags: [Order Queries]
+      summary: List orders
+      parameters:
+        - name: status
+          in: query
+          schema: { type: string }
+      responses:
+        '200': { $ref: '#/components/schemas/OrderListResponse' }
+```

+ 282 - 0
skills/ddd-skills/ddd-api-designer/examples/07-payment-api-design.md

@@ -0,0 +1,282 @@
+# 支付服务完整 API 设计案例
+
+> 支付限界上下文(Payment BC)的 REST API 设计,展示幂等、状态机、异步回调等典型场景。
+
+## 领域模型
+
+```
+Payment (Aggregate Root)
+├── PaymentId (ValueObject)
+├── OrderId (ValueObject) — 引用订单聚合
+├── PaymentStatus: UNPAID → PROCESSING → SUCCESS → REFUNDING → REFUNDED
+│                                          ↘ FAILED
+├── Money amount (ValueObject)
+├── PaymentMethod (ValueObject): WECHAT_PAY / ALIPAY / CARD
+├── PaymentChannel (Entity):通道请求记录
+│   ├── channelType
+│   ├── channelOrderNo
+│   └── channelStatus
+└── List<PaymentEvent> (DomainEvent)
+```
+
+## 1. CQRS 端点设计
+
+### 命令端点(写)
+
+```
+POST   /api/v1/payments                     → 发起支付
+POST   /api/v1/payments/{paymentId}/refund  → 发起退款
+PUT    /api/v1/payments/{paymentId}/cancel   → 取消支付
+
+# 回调端点(第三方支付异步通知)
+POST   /api/v1/payments/callback/wechat      → 微信支付回调
+POST   /api/v1/payments/callback/alipay      → 支付宝回调
+```
+
+### 查询端点(读)
+
+```
+GET    /api/v1/payments/{paymentId}          → 支付详情
+GET    /api/v1/payments/order/{orderId}      → 订单支付记录列表
+```
+
+## 2. 幂等设计
+
+支付 API 的幂等设计是核心:**防止重复扣款**。
+
+### 幂等键应用
+
+```yaml
+# 发起支付 — 幂等键防止重复支付请求
+POST /api/v1/payments
+Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
+```
+
+```java
+@Service
+public class PaymentService {
+    private final PaymentRepository paymentRepository;
+    private final IdempotencyService idempotencyService;
+
+    public PaymentResult initiatePayment(CreatePaymentCommand command, String idempotencyKey) {
+        // 1. 幂等检查
+        PaymentResult cached = idempotencyService.getCachedResult(idempotencyKey);
+        if (cached != null) return cached;
+
+        // 2. 业务幂等:同一订单不能重复发起支付
+        paymentRepository.findByOrderId(command.orderId())
+            .filter(p -> p.getStatus() != PaymentStatus.UNPAID)
+            .ifPresent(p -> { throw new BusinessException(40001, "该订单已发起支付"); });
+
+        // 3. 执行支付
+        Payment payment = Payment.create(command);
+        PaymentResult result = paymentRepository.save(payment);
+
+        // 4. 缓存幂等结果
+        idempotencyService.cacheResult(idempotencyKey, result);
+        return result;
+    }
+}
+```
+
+### 退款幂等
+
+```java
+public class Payment {
+    public RefundRecord refund(Money amount, String reason) {
+        // 状态机幂等:已退款状态不可重复退款
+        if (this.status == PaymentStatus.REFUNDED) {
+            throw new BusinessException(40001, "该支付已全额退款");
+        }
+        // 部分退款:计算可退余额
+        Money refundable = this.amount.subtract(this.totalRefunded());
+        if (amount.greaterThan(refundable)) {
+            throw new BusinessException(40001, "可退余额不足",
+                "可退: " + refundable + ",申请: " + amount);
+        }
+        this.totalRefundedAmount = this.totalRefundedAmount.add(amount);
+        if (this.totalRefundedAmount.equals(this.amount)) {
+            this.status = PaymentStatus.REFUNDED;
+        } else {
+            this.status = PaymentStatus.REFUNDING;
+        }
+        addDomainEvent(new PaymentRefundedEvent(this.id, amount));
+        return new RefundRecord(RefundId.generate(), amount, reason, LocalDateTime.now());
+    }
+}
+```
+
+## 3. 异步回调处理
+
+第三方支付异步通知(Webhook)的处理规范。
+
+### 回调端点设计
+
+```java
+@RestController
+public class PaymentCallbackController {
+    private final PaymentCallbackHandler callbackHandler;
+
+    // 微信支付回调 — 统一入口
+    @PostMapping("/api/v1/payments/callback/wechat")
+    public ResponseEntity<String> handleWechatCallback(@RequestBody String xmlBody,
+                                                        @RequestHeader Map<String, String> headers) {
+        // 1. 验签
+        if (!WechatSignature.verify(xmlBody, headers)) {
+            return ResponseEntity.status(401).body("signature verification failed");
+        }
+
+        // 2. 幂等处理(防止重复回调)
+        WechatNotify notify = WechatNotify.parse(xmlBody);
+        return callbackHandler.handleCallback("WECHAT", notify.getOutTradeNo(), () -> {
+            Payment payment = paymentRepository.findByOrderNo(notify.getOutTradeNo())
+                .orElseThrow(() -> new ResourceNotFoundException("Payment not found"));
+
+            if (notify.isSuccess()) {
+                payment.markSuccess(notify.getTransactionId(), notify.getPaidAt());
+            } else {
+                payment.markFailed(notify.getErrorCode());
+            }
+            paymentRepository.save(payment);
+        });
+    }
+
+    // 返回 "SUCCESS" 通知微信停止回调
+    // 返回其他 → 微信会重试(最多 3 天)
+}
+```
+
+### 回调幂等 Handler
+
+```java
+@Service
+public class PaymentCallbackHandler {
+
+    public ResponseEntity<String> handleCallback(String channel, String outTradeNo,
+                                                  Runnable businessLogic) {
+        String lockKey = "callback:" + channel + ":" + outTradeNo;
+
+        // 分布式锁防并发
+        if (!redisLock.tryLock(lockKey, 30, TimeUnit.SECONDS)) {
+            return ResponseEntity.ok("SUCCESS");  // 另一个线程在处理
+        }
+
+        try {
+            // 幂等:已处理过的回调不再执行
+            if (redis.hasKey("callback:processed:" + outTradeNo)) {
+                return ResponseEntity.ok("SUCCESS");
+            }
+            businessLogic.run();
+            redis.set("callback:processed:" + outTradeNo, "1", 7, TimeUnit.DAYS);
+            return ResponseEntity.ok("SUCCESS");
+
+        } catch (Exception e) {
+            log.error("Callback processing failed", e);
+            return ResponseEntity.status(500).body("retry");
+        } finally {
+            redisLock.unlock(lockKey);
+        }
+    }
+}
+```
+
+## 4. 数据对象转换链
+
+```
+PaymentPO ↔ Payment (DO) ↔ PaymentDTO ↔ PaymentVO
+```
+
+### DO — 充血模型
+
+```java
+public class Payment extends AggregateRoot<PaymentId> {
+    private PaymentId id;
+    private OrderId orderId;
+    private PaymentStatus status;
+    private Money amount;
+    private PaymentMethod method;
+    private String channelOrderNo;    // 第三方支付单号
+    private Money totalRefundedAmount;
+
+    // 创建支付
+    public static Payment create(OrderId orderId, Money amount, PaymentMethod method) {
+        Payment payment = new Payment(PaymentId.generate(), orderId, amount, method);
+        payment.status = PaymentStatus.UNPAID;
+        payment.addDomainEvent(new PaymentInitiatedEvent(payment.id, orderId, amount));
+        return payment;
+    }
+
+    // 支付成功回调
+    public void markSuccess(String channelOrderNo, LocalDateTime paidAt) {
+        if (this.status != PaymentStatus.PROCESSING) {
+            // 幂等:已成功的回调直接忽略
+            if (this.status == PaymentStatus.SUCCESS) return;
+            throw new BusinessException(40001, "当前状态不允许标记成功",
+                "当前:" + this.status);
+        }
+        this.status = PaymentStatus.SUCCESS;
+        this.channelOrderNo = channelOrderNo;
+        addDomainEvent(new PaymentSuccessEvent(this.id, this.orderId, this.amount, paidAt));
+    }
+
+    // 退款
+    public void refund(Money amount, String reason) {
+        if (this.status != PaymentStatus.SUCCESS) {
+            throw new BusinessException(40001, "只有已支付的订单才能退款");
+        }
+        Money refundable = this.amount.subtract(this.totalRefundedAmount);
+        if (amount.greaterThan(refundable)) {
+            throw new BusinessException(40001, "可退余额不足");
+        }
+        this.totalRefundedAmount = this.totalRefundedAmount.add(amount);
+        this.status = amount.equals(this.amount) ? PaymentStatus.REFUNDED : PaymentStatus.REFUNDING;
+        addDomainEvent(new PaymentRefundedEvent(this.id, this.orderId, amount));
+    }
+}
+```
+
+## 5. 统一响应
+
+```json
+// 发起支付成功
+POST /api/v1/payments → 201
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "paymentId": "PAY-2024-001",
+    "orderId": "ORD-2024-001",
+    "amount": "99.00",
+    "method": "WECHAT_PAY",
+    "status": "PROCESSING",
+    "payUrl": "weixin://pay/...",
+    "expiresIn": 300
+  }
+}
+
+// 微信回调处理成功
+POST /api/v1/payments/callback/wechat → 200
+HTTP body: "SUCCESS"
+
+// 退款成功
+POST /api/v1/payments/PAY-2024-001/refund → 200
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "refundId": "REF-2024-001",
+    "amount": "99.00",
+    "status": "REFUNDED",
+    "refundedAt": "2024-01-16T11:00:00Z"
+  }
+}
+```
+
+## 6. 安全设计
+
+| 端点 | 认证 | 限流 | 幂等 | 特殊 |
+|------|------|------|------|------|
+| POST /payments | JWT + BC 授权 | 30/min/user | ✅ Idempotency-Key | 资源所有权检查 |
+| POST /payments/{id}/refund | JWT + OPERATOR 角色 | 10/min/user | ✅ 状态机 + 业务幂等 | 退款金额校验 |
+| POST /callback/* | 签名验证(无 JWT) | 100/min/IP | ✅ 去重表 + 回调幂等 | 白名单 IP |
+| GET /payments/{id} | JWT | 200/min/user | 天然幂等 | — |

+ 32 - 0
skills/ddd-skills/ddd-api-designer/examples/08-product-api-design.md

@@ -0,0 +1,32 @@
+# 商品服务 API 设计案例
+
+> 商品限界上下文(Product BC)的 REST API 设计,展示商品管理、分类查询等场景。
+
+## 领域模型
+
+```
+Product (Aggregate Root)
+├── ProductId
+├── Sku
+├── Title / Description
+├── Price / CostPrice
+├── CategoryId
+└── ProductStatus: DRAFT / ONLINE / OFFLINE / DELETED
+```
+
+## 端点设计
+
+| 端点 | 类型 | 说明 |
+|------|------|------|
+| `POST /api/v1/products` | Command | 创建商品 |
+| `PUT /api/v1/products/{id}` | Command | 更新商品 |
+| `PUT /api/v1/products/{id}/online` | Command | 上架 |
+| `PUT /api/v1/products/{id}/offline` | Command | 下架 |
+| `GET /api/v1/products/{id}` | Query | 商品详情 DTO |
+| `GET /api/v1/products?category=&page=&size=` | Query | 商品列表(分页) |
+
+## DTO 设计
+
+- `ProductDetailDTO`:详情页(含描述、规格)
+- `ProductSummaryDTO`:列表页(标题、价格、封面图)
+- `ProductCreateCommand`:创建请求

+ 29 - 0
skills/ddd-skills/ddd-api-designer/examples/09-search-api-design.md

@@ -0,0 +1,29 @@
+# 搜索服务 API 设计案例
+
+> 搜索上下文(Search BC)的 REST API 设计,展示 CQRS 查询侧的物化视图设计。
+
+## 领域模型
+
+```
+SearchIndex (Read Model)
+├── DocumentId
+├── DocumentType
+├── Title / Content
+├── Tags[]
+└── IndexedAt
+```
+
+## 端点设计
+
+| 端点 | 类型 | 说明 |
+|------|------|------|
+| `GET /api/v1/search?q=&type=&page=` | Query | 全文搜索 |
+| `POST /api/v1/search/index` | Command | 重建索引 |
+| `GET /api/v1/search/suggest?q=` | Query | 搜索建议 |
+| `GET /api/v1/search/facets?field=` | Query | 聚合统计 |
+
+## 查询侧设计要点
+
+- 搜索结果使用 Cursor 分页(`?cursor=xxx&size=20`)
+- 支持字段选择(`?fields=id,title,summary`)
+- 结果按相关性排序(评分倒序)

+ 216 - 0
skills/ddd-skills/ddd-api-designer/examples/10-user-api-design.md

@@ -0,0 +1,216 @@
+# 用户服务完整 API 设计案例
+
+> 用户限界上下文(User BC)的 REST API 设计,展示注册、登录、资料管理等典型 CQRS 场景。
+
+## 领域模型
+
+```
+User (Aggregate Root)
+├── UserId (ValueObject)
+├── Email (ValueObject)
+├── PasswordHash (ValueObject)
+├── UserProfile (ValueObject)
+│   ├── Nickname
+│   ├── Avatar
+│   └── Phone
+└── UserStatus: ACTIVE / SUSPENDED / DELETED
+```
+
+## 1. CQRS 端点设计
+
+### 命令端点(写)
+
+```
+POST   /api/v1/users/register           → 用户注册
+POST   /api/v1/users/login              → 用户登录
+PUT    /api/v1/users/profile            → 更新资料
+PUT    /api/v1/users/password           → 修改密码
+DELETE /api/v1/users/{userId}           → 注销账号
+POST   /api/v1/users/password/reset     → 重置密码(发送邮件)
+```
+
+### 查询端点(读)
+
+```
+GET    /api/v1/users/me                 → 当前用户信息
+GET    /api/v1/users/{userId}           → 指定用户信息(公开)
+```
+
+## 2. 数据对象转换链
+
+```
+UserPO ↔ User(UserDO) ↔ UserDTO ↔ UserProfileVO
+```
+
+### PO
+
+```java
+@Entity
+@Table(name = "users")
+public class UserPO {
+    @Id
+    private Long id;
+    private String email;
+    private String passwordHash;
+    private String nickname;
+    private String avatar;
+    private String phone;
+    private String status;
+    private LocalDateTime createdAt;
+    private LocalDateTime updatedAt;
+}
+```
+
+### DO
+
+```java
+public class User extends AggregateRoot<UserId> {
+    private UserId id;
+    private Email email;
+    private PasswordHash passwordHash;
+    private UserProfile profile;
+    private UserStatus status;
+
+    public static User register(Email email, PasswordHash passwordHash) {
+        User user = new User(UserId.generate(), email, passwordHash);
+        user.addDomainEvent(new UserRegisteredEvent(user.id, user.email));
+        return user;
+    }
+
+    public void updateProfile(UserProfile newProfile) {
+        this.profile = newProfile;
+        addDomainEvent(new UserProfileUpdatedEvent(this.id));
+    }
+
+    public void changePassword(PasswordHash oldPwd, PasswordHash newPwd) {
+        if (!this.passwordHash.matches(oldPwd)) {
+            throw new BusinessException(40101, "原密码不正确");
+        }
+        this.passwordHash = newPwd;
+        addDomainEvent(new UserPasswordChangedEvent(this.id));
+    }
+}
+```
+
+### DTO
+
+```java
+// 注册命令 DTO
+public record RegisterRequest(
+    @Email String email,
+    @NotBlank @Size(min = 6, max = 32) String password,
+    @NotBlank String nickname
+) {
+    public RegisterCommand toCommand() {
+        return new RegisterCommand(Email.of(email), PasswordHash.encode(password), nickname);
+    }
+}
+
+// 登录命令 DTO
+public record LoginRequest(
+    @Email String email,
+    @NotBlank String password
+) {}
+
+// 查询 DTO
+public record UserDetailDTO(
+    String userId,
+    String email,
+    String nickname,
+    String avatar,
+    String status,
+    String createdAt
+) {}
+```
+
+### VO(前端视图)
+
+```json
+{
+  "userId": "USR-2024-001",
+  "nickname": "张三",
+  "avatar": "https://cdn.example.com/avatars/001.jpg",
+  "isVerified": true,
+  "memberSince": "2024-01-15",
+  "settings": {
+    "notifications": true,
+    "language": "zh-CN"
+  }
+}
+```
+
+## 3. 转换器
+
+```java
+public class UserAssembler {
+    // DO → DTO
+    public static UserDetailDTO toDetailDTO(User user) {
+        return new UserDetailDTO(
+            user.getId().getValue(),
+            user.getEmail().getValue(),
+            user.getProfile().getNickname(),
+            user.getProfile().getAvatar(),
+            user.getStatus().name(),
+            user.getCreatedAt().toString()
+        );
+    }
+
+    // DO → 登录响应
+    public static LoginResponse toLoginResponse(User user, String token) {
+        return new LoginResponse(
+            token,
+            toDetailDTO(user)
+        );
+    }
+}
+```
+
+## 4. 统一响应
+
+```json
+// 注册成功
+POST /api/v1/users/register → 201
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "userId": "USR-2024-001",
+    "email": "zhang@example.com"
+  }
+}
+
+// 登录成功
+POST /api/v1/users/login → 200
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "token": "eyJhbGciOiJIUzI1NiIs...",
+    "expiresIn": 3600,
+    "user": {
+      "userId": "USR-2024-001",
+      "nickname": "张三",
+      "avatar": "https://cdn.example.com/avatars/001.jpg"
+    }
+  }
+}
+
+// 邮箱已注册
+POST /api/v1/users/register → 409
+{
+  "code": 40901,
+  "message": "该邮箱已被注册",
+  "requestId": "req-xyz789"
+}
+```
+
+## 5. 安全设计
+
+| 端点 | 认证 | 限流 | 备注 |
+|------|------|------|------|
+| POST /register | 无 | 5/min/IP | 防恶意注册 |
+| POST /login | 无 | 10/min/IP | 防暴力破解 |
+| POST /password/reset | 无 | 3/min/IP | 防滥用 |
+| PUT /profile | JWT | 30/min/user | — |
+| GET /users/me | JWT | 100/min/user | — |
+| DELETE /users/{userId} | JWT+资源所有权检查 | 5/min/user | — |

+ 0 - 0
skills/ddd-skills/ddd-api-designer/references/clean-ddd-hexagonal-hexagonal.md → skills/ddd-skills/ddd-api-designer/references/architecture/clean-ddd-hexagonal-hexagonal.md


+ 0 - 0
skills/ddd-skills/ddd-api-designer/references/partme-16-service-data-view.md → skills/ddd-skills/ddd-api-designer/references/architecture/partme-16-service-data-view.md


+ 8 - 0
skills/ddd-skills/ddd-api-designer/references/examples-ref/api-error-handling.md

@@ -0,0 +1,8 @@
+# API 错误处理设计
+
+全局异常处理机制:ControllerAdvice 捕获所有异常,按类型转换为统一错误响应。
+- 参数校验异常 → 400 + 40002
+- 业务异常 → 400 + 40001(业务码)
+- 资源不存在 → 404 + 40401
+- 权限不足 → 403 + 40301
+- 系统异常 → 500 + 50000

+ 0 - 0
skills/ddd-skills/ddd-api-designer/references/data-object-transformation.md → skills/ddd-skills/ddd-api-designer/references/examples-ref/data-object-transformation.md


+ 7 - 0
skills/ddd-skills/ddd-api-designer/references/examples-ref/event-driven-api.md

@@ -0,0 +1,7 @@
+# 事件驱动 API 设计
+
+领域事件通过异步消息在限界上下文间传播:
+- 事件命名:{Aggregate}.{Action}.Occurred(如 Order.Paid.Occurred)
+- 事件契约:eventId + eventType + aggregateId + occurredAt + payload
+- 投递保障:至少一次投递(At-Least-Once),消费者实现幂等去重
+- 事件 API:POST /api/v1/events/publish — 发布事件

+ 254 - 0
skills/ddd-skills/ddd-api-designer/references/examples-ref/unified-response-format.md

@@ -0,0 +1,254 @@
+# Unified Response Format Specification
+
+## Core Design
+
+Every API response follows the same envelope format (`Result<T>`):
+
+```json
+{
+  "code": 0,
+  "message": "success",
+  "data": { /* type-specific payload */ },
+  "requestId": "req-abc123",
+  "timestamp": "2024-01-15T10:30:00Z"
+}
+```
+
+## Response Type Definitions
+
+### Success Response: Single Object
+
+```json
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "orderId": "ORD-2024-001",
+    "status": "PAID",
+    "totalAmount": "99.00",
+    "items": [
+      { "itemId": "ITEM-001", "productName": "T-Shirt", "quantity": 2, "price": "49.50" }
+    ]
+  },
+  "requestId": "req-abc123"
+}
+```
+
+### Success Response: Paginated List
+
+```json
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "records": [
+      { "orderId": "ORD-2024-001", "status": "PAID", "totalAmount": "99.00" },
+      { "orderId": "ORD-2024-002", "status": "DRAFT", "totalAmount": "150.00" }
+    ],
+    "total": 100,
+    "page": 1,
+    "pageSize": 20,
+    "totalPages": 5
+  },
+  "requestId": "req-abc123"
+}
+```
+
+### Success Response: No Content (204)
+
+```http
+HTTP/1.1 204 No Content
+Content-Length: 0
+```
+
+Used for DELETE operations — no response body.
+
+### Error Response: Business Error
+
+```json
+{
+  "code": 40001,
+  "message": "订单状态不允许支付",
+  "detail": "当前状态:CANCELLED,可支付状态:DRAFT",
+  "requestId": "req-abc123",
+  "timestamp": "2024-01-15T10:30:00Z"
+}
+```
+
+### Error Response: Validation Error
+
+```json
+{
+  "code": 40002,
+  "message": "参数校验失败",
+  "detail": [
+    { "field": "amount", "message": "金额不能为负数" },
+    { "field": "customerId", "message": "客户ID不能为空" },
+    { "field": "items", "message": "订单项不能为空" }
+  ],
+  "requestId": "req-abc123"
+}
+```
+
+### Error Response: Not Found
+
+```json
+{
+  "code": 40401,
+  "message": "订单未找到",
+  "detail": "orderId: ORD-2024-999",
+  "requestId": "req-abc123"
+}
+```
+
+### Error Response: Conflict / Concurrent Modification
+
+```json
+{
+  "code": 40901,
+  "message": "数据已被其他操作修改",
+  "detail": "预期版本: 3, 当前版本: 5",
+  "requestId": "req-abc123"
+}
+```
+
+### Error Response: System Error (500)
+
+```json
+{
+  "code": 50000,
+  "message": "系统内部错误",
+  "requestId": "req-abc123"
+}
+```
+
+## Error Code System
+
+### Code Range Allocation
+
+| Code Range | Category | HTTP Status | Description |
+|:----------:|----------|:-----------:|-------------|
+| 0 | Success | 200/201 | Success |
+| 40001-40099 | Business Rule Violation | 400 | Domain rule prevented operation |
+| 40100-40199 | Authentication | 401 | Missing or invalid credentials |
+| 40300-40399 | Authorization | 403 | Insufficient permissions |
+| 40401-40499 | Not Found | 404 | Resource not found |
+| 40901-40999 | Conflict | 409 | Optimistic lock / duplicate |
+| 41201-41299 | Precondition Failed | 412 | Version mismatch |
+| 42901-42999 | Rate Limit | 429 | Too many requests |
+| 50000-50099 | System Error | 500 | Unexpected internal error |
+| 50301-50399 | Service Unavailable | 503 | Downstream service unavailable |
+
+### Code Naming Convention
+
+```
+XXYYY
+│└── Specific error number (001-999)
+└── Category:
+    0  = Success
+    40 = Client error (4xx)
+    41 = Auth (401)
+    43 = Forbidden (403)
+    44 = Not Found (404)
+    49 = Conflict (409)
+    42 = Rate limit (429)
+    50 = Server error (500)
+    53 = Service unavailable (503)
+```
+
+## Response Wrapper Implementation
+
+### Java
+
+```java
+public class Result<T> {
+    private int code;
+    private String message;
+    private T data;
+    private String detail;
+    private String requestId;
+    private String timestamp;
+
+    // Success
+    public static <T> Result<T> success(T data) {
+        return new Result<>(0, "success", data, null, null, now());
+    }
+
+    // Error with detail
+    public static <T> Result<T> error(int code, String message, Object detail) {
+        return new Result<>(code, message, null, detail, null, now());
+    }
+
+    // System error with requestId
+    public static <T> Result<T> systemError(String requestId) {
+        return new Result<>(50000, "系统内部错误", null, null, requestId, now());
+    }
+}
+```
+
+### TypeScript
+
+```typescript
+interface ApiResponse<T> {
+  code: number;
+  message: string;
+  data?: T;
+  detail?: any;
+  requestId: string;
+  timestamp: string;
+}
+
+interface PaginatedData<T> {
+  records: T[];
+  total: number;
+  page: number;
+  pageSize: number;
+  totalPages: number;
+}
+
+// Usage
+type OrderListResponse = ApiResponse<PaginatedData<OrderSummary>>;
+type OrderDetailResponse = ApiResponse<OrderDetail>;
+```
+
+## Exception Handling Strategy
+
+```java
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+
+    @ExceptionHandler(BusinessException.class)
+    @ResponseStatus(HttpStatus.BAD_REQUEST)
+    public Result<?> handleBusiness(BusinessException e) {
+        return Result.error(e.getCode(), e.getMessage(), e.getDetail());
+    }
+
+    @ExceptionHandler(ValidationException.class)
+    @ResponseStatus(HttpStatus.BAD_REQUEST)
+    public Result<?> handleValidation(ValidationException e) {
+        return Result.error(40002, "参数校验失败", e.getErrors());
+    }
+
+    @ExceptionHandler(ResourceNotFoundException.class)
+    @ResponseStatus(HttpStatus.NOT_FOUND)
+    public Result<?> handleNotFound(ResourceNotFoundException e) {
+        return Result.error(40401, e.getMessage(), e.getResourceId());
+    }
+
+    @ExceptionHandler(Exception.class)
+    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
+    public Result<?> handleSystem(Exception e, HttpServletRequest request) {
+        log.error("System error", e);
+        return Result.systemError(request.getAttribute("requestId").toString());
+    }
+}
+```
+
+## Guidelines
+
+1. **Always wrap responses**: All API responses use `Result<T>` envelope. Only health checks and file downloads are exempt.
+2. **Consistent error codes**: Same error across endpoints returns same code. No code reuse across different error types.
+3. **No stack traces**: Error responses never include stack traces. Use `requestId` for server-side log correlation.
+4. **Include requestId**: Every response includes a requestId for debugging. Attach to logs for traceability.
+5. **ISO 8601 timestamps**: All datetime values use ISO 8601 format with timezone.
+6. **Avoid null in data**: If no data, omit the `data` field entirely, or return an empty object `{}`.

+ 190 - 0
skills/ddd-skills/ddd-api-designer/references/migration/api-versioning-strategies.md

@@ -0,0 +1,190 @@
+# API Versioning Strategies
+
+## Strategy Comparison
+
+| Strategy | Example | Pros | Cons | Best For |
+|----------|---------|------|------|----------|
+| **URL Path** | `/api/v1/orders` | Intuitive, CDN-friendly, easy to test | URL pollution | **Most projects** |
+| **Request Header** | `Accept: app.vnd.company.v2+json` | Clean URLs, semantic | Hard to test, poor tooling | Mature API platforms |
+| **Query Parameter** | `/api/orders?version=2` | Simple to implement | Caching issues, accidental param | Temporary/testing |
+| **Content Negotiation** | `Accept: app/json;version=2` | RESTful standard | Poor client adoption | REST purists |
+
+## Recommended: URL Path Versioning
+
+```
+/api/v1/orders         → Version 1 endpoints
+/api/v2/orders         → Version 2 endpoints
+/api/v1/orders/{id}
+/api/v2/orders/{id}
+```
+
+**Rationale:**
+- Most intuitive for API consumers
+- Best Swagger/OpenAPI compatibility (each version = separate spec file)
+- CDN can cache by URL path
+- Easy to test in browser, curl, Postman
+
+## Version Lifecycle Management
+
+```
+v1.0 (active)       →  v2.0-alpha  →  v2.0-beta   →  v2.0 (GA)
+  [launch]              [coexist]      [coexist]      [stable]
+                           ↓                              ↓
+                     v1.x (maintenance)             v1 (sunset)
+                     Bug fixes only                 Deprecation notice
+                                                    Removed after 6 months
+```
+
+### Migration Process
+
+```
+Phase 1: Dual-run (v1 + v2)
+  ├── v1: Existing clients continue
+  ├── v2: New clients start
+  └── Migration guide: Document all breaking changes
+
+Phase 2: Deprecate v1
+  ├── Add "Deprecated" header to v1 responses
+  ├── Extend migration deadline via announcement
+  └── Monitor v1 traffic decline
+
+Phase 3: Sunset v1
+  ├── Return 410 Gone for v1 endpoints
+  ├── Remove v1 code and deployment
+  └── Archive v1 OpenAPI spec
+```
+
+## What Constitutes a Breaking Change (Version Bump)
+
+### Major Version Bump Required (Breaking)
+
+```
+- Remove a field from response
+- Rename a field
+- Change field type (string → number)
+- Make required field optional (clients may rely on it)
+- Change endpoint URL
+- Change error codes or response structure
+- Add required field to request
+```
+
+### Minor/Patch Version (Non-Breaking)
+
+```
+- Add new endpoint (v1 + new endpoint is compatible)
+- Add optional field to response (clients ignore unknown fields)
+- Add optional field to request (server uses default if absent)
+- Change error message text (not code or structure)
+- Performance improvement
+- Bug fix (no contract change)
+```
+
+## API Version OpenAPI Examples
+
+### v1 OpenAPI
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  version: 1.0.0
+servers:
+  - url: https://api.example.com/api/v1
+paths:
+  /orders:
+    get:
+      summary: List orders (v1 - basic)
+      parameters:
+        - name: status
+          in: query
+          schema:
+            type: string
+      responses:
+        '200':
+          description: Order list
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderV1'
+components:
+  schemas:
+    OrderV1:
+      type: object
+      properties:
+        id: { type: integer }
+        status: { type: string }
+        amount: { type: number }
+```
+
+### v2 OpenAPI
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  version: 2.0.0
+servers:
+  - url: https://api.example.com/api/v2
+paths:
+  /orders:
+    get:
+      summary: List orders (v2 - enhanced pagination + filters)
+      parameters:
+        - name: status
+          in: query
+          schema:
+            type: string
+            enum: [DRAFT, PAID, SHIPPED, CANCELLED]
+        - name: page
+          in: query
+          schema: { type: integer, default: 1 }
+        - name: size
+          in: query
+          schema: { type: integer, default: 20 }
+      responses:
+        '200':
+          description: Paginated order list
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/PaginatedOrderV2'
+components:
+  schemas:
+    OrderV2:
+      type: object
+      properties:
+        orderId: { type: string }        # Renamed: id → orderId
+        status: { type: string }
+        totalAmount: { type: string }     # Changed type: number → string
+        currency: { type: string }        # NEW field
+        items:                            # NEW field
+          type: array
+          items:
+            $ref: '#/components/schemas/OrderItemV2'
+```
+
+## Client Migration Guide Template
+
+```markdown
+# Migrating from Order API v1 to v2
+
+## Breaking Changes
+
+1. `id` → `orderId` (field renamed)
+2. `amount` → `totalAmount` + `currency` (split into two fields)
+3. `amount` type: number → string (precision improvement)
+4. Response now `{code, message, data}` wrapped
+
+## Migration Steps
+
+1. Update your client to parse `orderId` instead of `id`
+2. Use `totalAmount` (string) instead of `amount` (number)
+3. Use `currency` field for currency code
+4. Parse response from flat `{id, ...}` to wrapped `{code, message, data}`
+
+## Timeline
+
+- v1 deprecation notice: 2024-Q2
+- v1 sunset: 2024-Q4
+- v2 mandatory: 2025-Q1
+```

+ 113 - 0
skills/ddd-skills/ddd-api-designer/references/patterns/BFF-design-pattern.md

@@ -0,0 +1,113 @@
+# BFF (Backend for Frontend) Design Pattern
+
+## What is BFF?
+
+BFF is a dedicated backend layer for each frontend application. Instead of having one API serving all clients, each platform (Web, iOS, Android, MiniApp) has its own backend that tailors data and behavior specifically for that platform.
+
+## When to Use BFF
+
+| Scenario | Use BFF? |
+|----------|----------|
+| Single web app only | No — API Gateway is sufficient |
+| Web + Mobile App | Yes — different data needs |
+| Web + MiniApp + WeChat | Yes — platform-specific formats |
+| Multiple frontend teams | Yes — independent evolution |
+| Public API for third-party | Public API → API Gateway, not BFF |
+
+## BFF Responsibilities in Detail
+
+### 1. Data Aggregation
+
+```
+Without BFF:
+  Frontend → /api/orders/{id}        → Order detail (needs 3 calls)
+           → /api/payments/{orderId} → Payment info
+           → /api/shipping/{orderId} → Shipping status
+  Result: 3 HTTP calls, client-side aggregation
+
+With BFF:
+  Frontend → /api/web-bff/order-detail/{id}  → Single response
+  BFF internally calls:
+    → Order Service   → OrderDO
+    → Payment Service → PaymentDTO
+    → Shipping Service → ShippingDTO
+  BFF combines them into OrderDetailVO
+  Result: 1 HTTP call, server-side aggregation
+```
+
+### 2. Format Adaptation
+
+```json
+// Web BFF response (rich, full data)
+{
+  "orderId": "ORD-2024-001",
+  "status": "PAID",
+  "totalAmount": "99.00",
+  "items": [
+    { "name": "T-Shirt", "imageUrl": "https://cdn.example.com/tshirt.jpg",
+      "description": "Premium cotton T-Shirt", "quantity": 2, "price": "49.50" }
+  ],
+  "customer": { "name": "张三", "email": "zhang@example.com" },
+  "paymentMethod": "微信支付",
+  "estimatedDelivery": "2024-01-20",
+  "actions": ["cancel", "return"]
+}
+
+// Mobile BFF response (minimal, paginated)
+{
+  "orderId": "ORD-2024-001",
+  "status": "PAID",
+  "totalAmount": "99.00",
+  "itemCount": 2,
+  "estimatedDelivery": "2024-01-20",
+  "action": "cancel"
+}
+```
+
+### 3. Protocol Translation
+
+```
+Internal (gRPC/Protobuf):
+  Order service proto:    Order { id uint64, status OrderStatus, ... }
+  Payment service proto:  Payment { id uint64, amount Money, ... }
+
+External (REST/JSON) via BFF:
+  GET /api/web-bff/order-detail/{id}
+  → JSON: { "orderId": "ORD-2024-001", "status": "PAID", ... }
+```
+
+## BFF Directory Structure (Hexagonal)
+
+```
+bff-web/
+├── adapter/                    # BFF 适配器层
+│   ├── inbound/                # 对外暴露的 REST 端点
+│   │   ├── controller/
+│   │   └── dto/                # 对外 VO(面向前端页面)
+│   └── outbound/               # 调用下游服务的客户端
+│       ├── order-service/      # gRPC/REST client → Order Service
+│       ├── payment-service/    # gRPC/REST client → Payment Service
+│       └── product-service/    # gRPC/REST client → Product Service
+├── application/                # 聚合编排层
+│   ├── service/                # 组合多个下游服务
+│   └── assembler/              # 组装 VO
+└── config/                     # 配置
+```
+
+## BFF Best Practices
+
+1. **One BFF per frontend team**: Each team owns their BFF independently
+2. **BFF is thin, not thick**: Aggregation only, no business logic
+3. **No direct DB access**: BFF calls downstream services, never the database
+4. **Handle partial failures**: If one downstream service fails, return partial data with error indicators
+5. **Cache aggressively**: BFF responses are view-specific and cacheable by URL
+6. **Separate deployments**: BFF and downstream services deploy independently
+
+## Anti-Patterns
+
+| Anti-Pattern | Problem | Fix |
+|-------------|---------|-----|
+| BFF contains business logic | Duplication across BFFs | Move to domain service |
+| One BFF for all platforms | Single point of change | Create per-platform BFF |
+| BFF calls BFF | Request chain, latency | Restructure orchestration |
+| BFF accesses DB directly | Bypasses domain rules | Always go through services |

+ 89 - 0
skills/ddd-skills/ddd-api-designer/references/patterns/cqrs-api-design.md

@@ -0,0 +1,89 @@
+# CQRS API Design Pattern
+
+## Core Principle
+
+CQRS (Command Query Responsibility Segregation) separates write operations from read operations at the API level. This is distinct from CQRS at the architecture level — API-level CQRS focuses on endpoint design, request/response structure, and DTO separation.
+
+## Endpoint Patterns
+
+### Command Endpoints (Write)
+
+Commands represent **intent** — they change system state.
+
+```
+POST   /api/v1/orders                    → CreateOrderCommand
+PUT    /api/v1/orders/{id}/confirm        → ConfirmOrderCommand
+PUT    /api/v1/orders/{id}/ship           → ShipOrderCommand
+DELETE /api/v1/orders/{id}                → CancelOrderCommand
+```
+
+**Characteristics:**
+- Non-idempotent operations use POST
+- Idempotent operations use PUT with idempotency key
+- Response contains the created/modified resource summary
+- Always validate business rules before applying changes
+
+### Query Endpoints (Read)
+
+Queries represent **questions** — they return system state without side effects.
+
+```
+GET    /api/v1/orders/{id}                → OrderDetailDTO
+GET    /api/v1/orders?status=PAID&page=1  → OrderSummaryDTO[]
+GET    /api/v1/orders/{id}/items          → OrderItemDTO[]
+```
+
+**Characteristics:**
+- Always idempotent and safe (no side effects)
+- Can be cached aggressively
+- Response structure may differ significantly from command response
+- Can use materialized views or read models
+
+## DTO Separation Rules
+
+| Aspect | Command DTO | Query DTO |
+|--------|-------------|-----------|
+| Naming | `CreateOrderRequest` | `OrderDetailDTO` |
+| Direction | Input (request body) | Output (response body) |
+| Fields | What's needed to execute the command | What's needed to display |
+| Validation | Business rules + format | None (read-only) |
+| Mutability | May be mutable | Immutable |
+
+## Idempotency for Command APIs
+
+```yaml
+POST /api/v1/orders
+Headers:
+  Idempotency-Key: uuid-v4-unique-key
+
+# If first request → 201 Created
+# If retry with same key → 200 OK (same resource, no duplicate)
+# If different key for same data → 409 Conflict (idempotency check)
+```
+
+Implementation:
+1. Client generates UUID as idempotency key
+2. Server stores `(key, result)` in cache with TTL
+3. On duplicate key → return cached result
+4. Cache TTL must exceed max retry window (recommended: 24h)
+
+## Materialized View Pattern
+
+For query performance, maintain dedicated read models:
+
+```
+┌─────────────┐     Domain Events     ┌─────────────┐
+│ Command DB  │ ─────────────────────→ │  Read Model  │
+│ (normalized)│                        │ (denormalized)│
+└─────────────┘                        └─────────────┘
+      │                                      │
+      ▼                                      ▼
+  Order Aggregate                     OrderDetailMV (flat JSON)
+  ├── Order (root)                    ├── id, status, total
+  ├── Items[]                        ├── customerName, email
+  ├── Payment                        ├── items[ {name, qty, price} ]
+  └── Customer (ID ref)              ├── paymentMethod, paidAt
+                                      └── shippingAddress, status
+```
+
+The Read Model is updated asynchronously via domain events, allowing query-optimized structures independent of the domain model.

+ 9 - 0
skills/ddd-skills/ddd-api-designer/references/patterns/data-access-api.md

@@ -0,0 +1,9 @@
+# Data Access Layer API 设计原则
+
+DAO 层接口设计:
+
+- **Repository 隔离**:领域 Repository 接口定义在 Domain 层,实现在 Infrastructure 层
+- **CQS 分离**:查询 Repository 和命令 Repository 接口分离
+- **分页抽象**:统一 Pageable/Page 泛型,避免泄露 ORM 分页模型
+- **规约模式**:Specification 模式封装复杂查询条件,UserSpecification.withStatus(Status.PAID).and(between(from, to))
+- **延迟加载**:设计 API 时避免 N+1 查询,使用 Fetch Join 或 EntityGraph

+ 162 - 0
skills/ddd-skills/ddd-api-designer/references/patterns/idempotency-design.md

@@ -0,0 +1,162 @@
+# API 幂等设计
+
+## 为什么需要幂等
+
+在分布式系统中,网络超时、客户端重试、MQ 重复消费都会导致同一请求被多次执行。幂等设计确保重复请求不产生副作用。
+
+### 哪些操作需要幂等
+
+| 方法 | 天然幂等? | 说明 |
+|------|:----------:|------|
+| GET | ✅ | 不修改状态 |
+| PUT | ✅ | 全量替换,多次执行结果相同 |
+| DELETE | ✅ | 删除已删除的资源返回相同结果 |
+| POST | ❌ | 每次执行创建新资源,必须幂等处理 |
+
+## 四种幂等实现方案
+
+### 1. 幂等键(Idempotency-Key)— 最推荐
+
+客户端在请求头中传入唯一键,服务端缓存结果去重。
+
+```yaml
+POST /api/v1/orders
+Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
+```
+
+**流程**:
+
+```
+请求到达 → 查缓存 (key → result)
+  ├── 命中 → 直接返回缓存结果(200 OK)
+  └── 未命中 → 执行业务逻辑 → 存储 (key, result) → 返回结果
+```
+
+**注意事项**:
+- 缓存 TTL 必须超过最大重试窗口(推荐 24h)
+- 使用 Redis + TTL 实现
+- 幂等键空间应足够大(UUID v4)
+- 幂等键的响应结果不可变更:第一次成功 → 永远返回成功;第一次失败 → 后续重试继续执行(业务有状态时需要结合状态机)
+
+```java
+public class IdempotencyFilter implements Filter {
+    private final RedisTemplate<String, String> redis;
+
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
+        HttpServletRequest req = (HttpServletRequest) request;
+        String idempotencyKey = req.getHeader("Idempotency-Key");
+
+        if (idempotencyKey != null && "POST".equalsIgnoreCase(req.getMethod())) {
+            String cached = redis.opsForValue().get("idempotent:" + idempotencyKey);
+            if (cached != null) {
+                // 返回缓存结果
+                response.getWriter().write(cached);
+                return;
+            }
+        }
+        chain.doFilter(request, response);
+    }
+}
+```
+
+### 2. 业务唯一索引 — 简单可靠
+
+利用数据库唯一约束防止重复:
+
+```sql
+-- 订单号唯一约束
+ALTER TABLE orders ADD UNIQUE INDEX uk_order_no (order_no);
+```
+
+```java
+try {
+    orderRepository.save(order);
+} catch (DuplicateKeyException e) {
+    // 重复订单号 → 返回已创建的订单信息
+    return orderRepository.findByOrderNo(order.getOrderNo());
+}
+```
+
+### 3. 状态机 — 防重入
+
+业务状态有明确流转路径,已处理状态不可重复触发:
+
+```java
+public class Order {
+    private OrderStatus status;
+
+    public void confirm() {
+        if (this.status != OrderStatus.DRAFT) {
+            // DRAFT → CONFIRMED 只允许一次
+            throw new BusinessException(40001, "当前状态不允许确认",
+                "当前:" + this.status + ",需要:DRAFT");
+        }
+        this.status = OrderStatus.CONFIRMED;
+    }
+
+    public void pay() {
+        if (this.status != OrderStatus.CONFIRMED) {
+            throw new BusinessException(40001, "当前状态不允许支付");
+        }
+        this.status = OrderStatus.PAID;
+    }
+}
+```
+
+### 4. 业务幂等(乐观锁)— 无额外存储
+
+利用数据库条件更新:
+
+```sql
+-- 扣减库存:stock >= 1 确保不会超卖
+UPDATE product SET stock = stock - 1 WHERE id = ? AND stock >= 1;
+
+-- 乐观锁版本号
+UPDATE orders SET status = 'PAID', version = version + 1
+WHERE id = ? AND version = ?;
+```
+
+## 幂等策略选型矩阵
+
+| 场景 | 推荐方案 |
+|------|---------|
+| 创建订单(POST) | 幂等键 + 订单号唯一索引 |
+| 支付回调 | 业务唯一索引(支付单号) |
+| 状态变更(PUT) | 状态机 + 乐观锁 |
+| 库存扣减 | 条件更新(stock >= n) |
+| MQ 消息消费 | 消息 ID 幂等键 + 去重表 |
+
+## 幂等键最佳实践
+
+1. **幂等键由客户端生成**:UUID v4,确保唯一性
+2. **幂等键作用域**:按 (key, endpoint) 区分,不同端点可用相同 key
+3. **结果缓存不可变**:第一次成功→永远返回成功结果
+4. **TTL 设计**:至少 24h,最长 7 天(取决于业务重试窗口)
+5. **幂等键大小**:建议 64 字节以内,作为 Redis key 需控制长度
+
+## 幂等键在 OpenAPI 中的定义
+
+```yaml
+paths:
+  /orders:
+    post:
+      parameters:
+        - name: Idempotency-Key
+          in: header
+          required: false
+          schema:
+            type: string
+            format: uuid
+          description: 客户端幂等键,防止重复创建
+      responses:
+        '201':
+          description: 首次创建
+        '200':
+          description: 幂等返回(重复请求使用相同幂等键)
+          headers:
+            Idempotent-Replayed:
+              schema:
+                type: boolean
+              description: 标识该响应是重放结果
+```

+ 207 - 0
skills/ddd-skills/ddd-api-designer/references/patterns/pagination-filtering-design.md

@@ -0,0 +1,207 @@
+# API 分页与过滤设计
+
+## 分页方案对比
+
+| 方案 | 原理 | 优点 | 缺点 | 适用 |
+|------|------|------|------|------|
+| **Offset/Page** | `?page=1&size=20` | 实现简单,随机跳页 | 深分页性能差,数据偏移 | 管理后台、小数据集 |
+| **Cursor** | `?cursor=eyJpZCI6MTAwfQ==&limit=20` | 稳定性能,实时数据准确 | 不能随机跳页 | 用户端列表、实时数据 |
+| **Keyset** | `?after_id=100&limit=20` | 最快性能(索引) | 不能跳页,排序受限 | 只按 ID 排序的场景 |
+| **Seek** | `?offset_id=100&size=20` | Keyset + 灵活排序 | 实现稍复杂 | 社交媒体 Feeds |
+
+### 推荐方案
+
+- **管理端**:Offset/Page 分页(需要跳页功能)
+- **用户端**:Cursor 分页(实时数据场景)
+- **大数据量**:Keyset/Seek 分页(避免 offset 导致的性能退化)
+
+## Offset/Page 分页规范
+
+### 请求参数
+
+```
+GET /api/v1/orders?page=1&size=20&sort=createdAt,desc
+```
+
+| 参数 | 默认值 | 说明 |
+|------|--------|------|
+| `page` | 1 | 页码,从 1 开始 |
+| `size` | 20 | 每页条数,最大 100 |
+| `sort` | createdAt,desc | 排序字段和方向 |
+
+### 响应格式
+
+```json
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "records": [
+      { "orderId": "ORD-2024-001", "status": "PAID", "totalAmount": "99.00" }
+    ],
+    "total": 100,
+    "page": 1,
+    "pageSize": 20,
+    "totalPages": 5
+  }
+}
+```
+
+### 实现
+
+```java
+public class PageRequest {
+    private int page = 1;        // 页码,从 1 开始
+    private int size = 20;       // 每页条数
+    private String sort;         // 排序:createdAt,desc
+
+    public long getOffset() {
+        return (long) (page - 1) * size;
+    }
+
+    public Sort getSort() {
+        // 解析 sort 参数 → Spring Sort 对象
+    }
+}
+
+public class PageResult<T> {
+    private List<T> records;
+    private long total;
+    private int page;
+    private int pageSize;
+    private int totalPages;
+
+    public static <T> PageResult<T> of(List<T> records, long total, PageRequest request) {
+        PageResult<T> result = new PageResult<>();
+        result.records = records;
+        result.total = total;
+        result.page = request.getPage();
+        result.pageSize = request.getSize();
+        result.totalPages = (int) Math.ceil((double) total / request.getSize());
+        return result;
+    }
+}
+```
+
+## Cursor 分页规范
+
+### 请求参数
+
+```
+GET /api/v1/orders?cursor=eyJjcmVhdGVkQXQiOiIyMDI0LTAxLTE1VDEwOjMwOjAwWiIsImlkIjoiT1JELTIwMjQtMDEwIn0=&limit=20
+```
+
+| 参数 | 默认值 | 说明 |
+|------|--------|------|
+| `cursor` | 无 | 上一页最后一条记录的编码标识 |
+| `limit` | 20 | 每页条数 |
+| `sort` | createdAt,desc | 排序(必须与 cursor 编码一致) |
+
+### 响应格式
+
+```json
+{
+  "code": 0,
+  "message": "success",
+  "data": {
+    "records": [
+      { "orderId": "ORD-2024-011", "status": "PAID", "createdAt": "2024-01-16T10:30:00Z" }
+    ],
+    "nextCursor": "eyJjcmVhdGVkQXQiOiIyMDI0LTAxLTE2VDEwOjMwOjAwWiIsImlkIjoiT1JELTIwMjQtMDExIn0=",
+    "hasMore": true
+  }
+}
+```
+
+### Cursor 编码实现
+
+```java
+public class CursorCodec {
+    private static final ObjectMapper mapper = new ObjectMapper();
+
+    // 将游标对象编码为 Base64
+    public static String encode(Map<String, Object> cursorFields) {
+        try {
+            return Base64.getUrlEncoder().encodeToString(
+                mapper.writeValueAsString(cursorFields).getBytes());
+        } catch (JsonProcessingException e) {
+            throw new RuntimeException("Cursor encode failed", e);
+        }
+    }
+
+    // 解码游标
+    public static Map<String, Object> decode(String cursor) {
+        try {
+            byte[] bytes = Base64.getUrlDecoder().decode(cursor);
+            return mapper.readValue(bytes, Map.class);
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid cursor", e);
+        }
+    }
+}
+```
+
+## 过滤设计
+
+### 基础过滤
+
+```
+GET /api/v1/orders?status=PAID&customerId=USR-001
+GET /api/v1/orders?status=PAID,SHIPPED          # 多值过滤(逗号分隔)
+GET /api/v1/orders?createdAtFrom=2024-01-01&createdAtTo=2024-01-31  # 范围过滤
+```
+
+### 高级过滤(复杂查询)
+
+```json
+// POST /api/v1/orders/search
+{
+  "filters": [
+    { "field": "status", "operator": "in", "value": ["PAID", "SHIPPED"] },
+    { "field": "totalAmount", "operator": "gte", "value": 100 },
+    { "field": "createdAt", "operator": "between", "value": ["2024-01-01", "2024-01-31"] }
+  ],
+  "sort": { "field": "createdAt", "order": "desc" },
+  "page": { "page": 1, "size": 20 }
+}
+```
+
+| 操作符 | 说明 | SQL 对应 |
+|--------|------|---------|
+| `eq` | 等于 | `=` |
+| `neq` | 不等于 | `!=` |
+| `in` | 包含 | `IN` |
+| `nin` | 不包含 | `NOT IN` |
+| `gt` / `gte` | 大于 / 大于等于 | `>` / `>=` |
+| `lt` / `lte` | 小于 / 小于等于 | `<` / `<=` |
+| `between` | 范围 | `BETWEEN` |
+| `like` | 模糊 | `LIKE` |
+| `contains` | 包含(数组/字符串) | `@>` / `LIKE %...%` |
+
+## 字段选择
+
+允许客户端只请求需要的字段,减少传输量:
+
+```
+GET /api/v1/orders?fields=orderId,status,totalAmount
+```
+
+```json
+{
+  "data": {
+    "orderId": "ORD-2024-001",
+    "status": "PAID",
+    "totalAmount": "99.00"
+  }
+}
+```
+
+## 分页最佳实践
+
+1. **统一分页格式**:所有列表接口使用相同的分页响应结构(records/total/page/pageSize)
+2. **限制最大 size**:`size` 上限 100,防止大查询压垮数据库
+3. **深分页优化**:超过 10000 条 offset 时建议切换到 Cursor 或 Keyset
+4. **总记录数缓存**:`total` 可以使用缓存,减少 COUNT 查询
+5. **排序字段加索引**:`ORDER BY createdAt` 必须有对应索引
+6. **搜索端点分离**:复杂搜索用 `POST /search` 专用端点,不混入 GET 查询
+7. **默认排序**:始终提供默认排序,避免分页结果不稳定

+ 0 - 0
skills/ddd-skills/ddd-api-designer/references/api-naming-conventions.md → skills/ddd-skills/ddd-api-designer/references/security/api-naming-conventions.md


+ 10 - 0
skills/ddd-skills/ddd-api-designer/references/security/api-rate-limiting.md

@@ -0,0 +1,10 @@
+# API 限流设计
+
+差异化限流策略:
+- Command API:50 req/s(写操作成本高)
+- Query API:200 req/s(读操作可放宽)
+- Auth API:10 req/s(防暴力破解)
+- 全局:1000 req/s
+
+实现方式:令牌桶算法(Token Bucket),支持突发流量。
+限流响应:429 Too Many Requests + Retry-After header。

+ 217 - 0
skills/ddd-skills/ddd-api-designer/references/security/api-security-design.md

@@ -0,0 +1,217 @@
+# API Security Design for DDD APIs
+
+## Security Architecture Overview
+
+```
+┌─ Request ─────────────────────────────────────────────┐
+│                                                        │
+│  1. Authentication (Who are you?)                      │
+│     ├── JWT Bearer Token (standard)                    │
+│     ├── OAuth2 / OpenID Connect (third-party)          │
+│     └── API Key (service-to-service)                   │
+│                                                        │
+│  2. Rate Limiting (How much can you do?)               │
+│     ├── Per-user rate limit                            │
+│     └── Per-endpoint rate limit (cmd vs query)          │
+│                                                        │
+│  3. Authorization (What can you do?)                   │
+│     ├── BC-level authorization                         │
+│     └── Resource ownership check                       │
+│                                                        │
+│  4. Input Validation (What data is allowed?)           │
+│     ├── Controller: format validation                  │
+│     ├── Application: business validation               │
+│     └── Domain: invariant validation                   │
+│                                                        │
+│  → Domain Service (after all checks pass)              │
+└────────────────────────────────────────────────────────┘
+```
+
+## Layer 1: Authentication
+
+### JWT Bearer Token
+
+```yaml
+# OpenAPI Security Scheme
+components:
+  securitySchemes:
+    BearerAuth:
+      type: http
+      scheme: bearer
+      bearerFormat: JWT
+
+# Protected endpoint
+/api/v1/orders:
+  post:
+    security:
+      - BearerAuth: []
+```
+
+**JWT Token Structure:**
+```json
+{
+  "sub": "user-123",
+  "roles": ["admin"],
+  "bounded_contexts": ["order:write", "order:read", "payment:read"],
+  "iat": 1700000000,
+  "exp": 1700086400
+}
+```
+
+### Service-to-Service: API Key
+
+```yaml
+components:
+  securitySchemes:
+    ApiKeyAuth:
+      type: apiKey
+      in: header
+      name: X-API-Key
+```
+
+Internal services authenticate via API key in header. Keys are rotated quarterly.
+
+## Layer 2: Authorization
+
+### Per-Bounded Context Authorization
+
+Each bounded context has independent permissions:
+
+```
+User Token Claims:
+  "bounded_contexts": [
+    "order:write", "order:read",
+    "payment:read",
+    "product:read"
+  ]
+
+Order BC User → Can create/read orders, cannot modify payments
+Payment BC User → Can read payment info, cannot create orders
+```
+
+### Resource Ownership Check
+
+```java
+public class OrderAuthorizationService {
+    public void verifyOrderOwnership(String userId, OrderId orderId) {
+        Order order = orderRepository.findById(orderId)
+            .orElseThrow(() -> new ResourceNotFoundException("Order not found"));
+
+        if (!order.getCustomerId().getValue().equals(userId)) {
+            throw new ForbiddenException("You can only access your own orders");
+        }
+    }
+}
+```
+
+## Layer 3: Input Validation
+
+### Three-Level Validation
+
+| Level | Location | What | Example |
+|-------|----------|------|---------|
+| **Format** | Controller | Field types, ranges, required | `@NotNull`, `@Min(1)`, `@Email` |
+| **Business** | Application | Domain rules, state machine | "Can't pay cancelled order" |
+| **Invariant** | Domain | Aggregate invariants | "Total must equal sum of items" |
+
+### Controller Validation
+
+```java
+@PostMapping("/orders")
+public Result<OrderResponse> createOrder(
+    @Valid @RequestBody CreateOrderRequest request
+) {
+    // Controller: format validation via @Valid
+    // Pass to application service for business validation
+    OrderResponse response = orderAppService.createOrder(request.toCommand());
+    return Result.success(response);
+}
+
+public record CreateOrderRequest(
+    @NotNull Long customerId,
+    @NotEmpty List<@Valid OrderItemRequest> items,
+    @NotNull @Min(1) BigDecimal totalAmount
+) {}
+```
+
+## Layer 4: Rate Limiting
+
+### Command vs Query QPS
+
+| Endpoint Type | Default QPS | Burst | Notes |
+|---------------|-------------|-------|-------|
+| Command (POST/PUT/DELETE) | 50/s | 100/s | Lower, prevent abuse |
+| Query (GET) | 200/s | 500/s | Higher, can cache |
+| Auth (login/register) | 10/s | 20/s | Lowest, brute-force protection |
+| Public endpoints | 5/s | 10/s | Anonymous access |
+
+### Implementation in API Gateway
+
+```yaml
+# Rate limiting per user
+rate_limits:
+  command:
+    algorithm: token_bucket
+    capacity: 50
+    refill_rate: 50/s
+  query:
+    algorithm: token_bucket
+    capacity: 200
+    refill_rate: 200/s
+```
+
+## OpenAPI Security Examples
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  version: 1.0.0
+paths:
+  /api/v1/orders:
+    post:
+      summary: Create order
+      security:
+        - BearerAuth: []
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/CreateOrderRequest'
+      responses:
+        '201':
+          description: Order created
+  /api/v1/orders/{id}:
+    get:
+      summary: Get order detail
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: id
+          in: path
+          required: true
+          schema:
+            type: string
+      responses:
+        '200':
+          description: Order detail
+components:
+  securitySchemes:
+    BearerAuth:
+      type: http
+      scheme: bearer
+      bearerFormat: JWT
+```
+
+## Security Checklist
+
+- [ ] All endpoints require authentication (except health check)
+- [ ] Command endpoints verify resource ownership
+- [ ] Input validated at controller (format), application (business), domain (invariant)
+- [ ] Command APIs have lower rate limits than query APIs
+- [ ] Error responses never leak stack traces or internal details
+- [ ] API keys rotated at least quarterly
+- [ ] CORS configured per BFF domain
+- [ ] SQL injection prevention (use parameterized queries)
+- [ ] JWT tokens have short expiry (15 min access, 7 day refresh)

+ 499 - 0
skills/ddd-skills/ddd-api-designer/references/security/openapi-specification.md

@@ -0,0 +1,499 @@
+# OpenAPI 3.0 Specification for DDD APIs
+
+## Complete OpenAPI Template
+
+```yaml
+openapi: 3.0.3
+info:
+  title: Order Service API
+  description: REST API for Order Bounded Context — CQRS-separated commands and queries
+  version: 2.0.0
+  contact:
+    name: Order Team
+    email: order-team@company.com
+servers:
+  - url: https://api.example.com/api/v2
+    description: Production
+  - url: https://staging-api.example.com/api/v2
+    description: Staging
+
+paths:
+  # ─── Command Endpoints (Write) ──────────────────────────────────
+  /orders:
+    post:
+      summary: Create a new order
+      operationId: createOrder
+      tags: [Order Commands]
+      security:
+        - BearerAuth: []
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/CreateOrderRequest'
+      responses:
+        '201':
+          description: Order created successfully
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderCreatedResponse'
+        '400':
+          description: Validation or business error
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/ApiError'
+      x-springdoc-default: "40001"
+
+  /orders/{orderId}/confirm:
+    put:
+      summary: Confirm an order
+      operationId: confirmOrder
+      tags: [Order Commands]
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: orderId
+          in: path
+          required: true
+          schema:
+            type: string
+            pattern: '^ORD-\d{4}-\d{3,6}$'
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/ConfirmOrderRequest'
+      responses:
+        '200':
+          description: Order confirmed
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderCommandResponse'
+        '404':
+          description: Order not found
+
+  /orders/{orderId}:
+    delete:
+      summary: Cancel an order
+      operationId: cancelOrder
+      tags: [Order Commands]
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: orderId
+          in: path
+          required: true
+          schema:
+            type: string
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/CancelOrderRequest'
+      responses:
+        '204':
+          description: Order cancelled (no content)
+
+  # ─── Query Endpoints (Read) ────────────────────────────────────
+  /orders/{orderId}:
+    get:
+      summary: Get order details
+      operationId: getOrder
+      tags: [Order Queries]
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: orderId
+          in: path
+          required: true
+          schema:
+            type: string
+        - name: include
+          in: query
+          description: Comma-separated fields to include (items, payments)
+          schema:
+            type: string
+      responses:
+        '200':
+          description: Order detail
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderDetailResponse'
+
+  /orders:
+    get:
+      summary: List orders with filtering and pagination
+      operationId: listOrders
+      tags: [Order Queries]
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: status
+          in: query
+          schema:
+            type: string
+            enum: [DRAFT, PAID, SHIPPED, CANCELLED]
+        - name: customerId
+          in: query
+          schema:
+            type: string
+        - name: page
+          in: query
+          schema:
+            type: integer
+            default: 1
+            minimum: 1
+        - name: size
+          in: query
+          schema:
+            type: integer
+            default: 20
+            maximum: 100
+        - name: sort
+          in: query
+          schema:
+            type: string
+            default: createdAt,desc
+      responses:
+        '200':
+          description: Paginated order list
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderListResponse'
+
+  # ─── Sub-resource Endpoints ────────────────────────────────────
+  /orders/{orderId}/items:
+    get:
+      summary: List items in an order
+      operationId: listOrderItems
+      tags: [Order Items]
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: orderId
+          in: path
+          required: true
+          schema:
+            type: string
+      responses:
+        '200':
+          description: Order items
+          content:
+            application/json:
+              schema:
+                type: array
+                items:
+                  $ref: '#/components/schemas/OrderItemDTO'
+
+    post:
+      summary: Add item to order
+      operationId: addOrderItem
+      tags: [Order Items]
+      security:
+        - BearerAuth: []
+      parameters:
+        - name: orderId
+          in: path
+          required: true
+          schema:
+            type: string
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/AddOrderItemRequest'
+      responses:
+        '201':
+          description: Item added
+
+components:
+  securitySchemes:
+    BearerAuth:
+      type: http
+      scheme: bearer
+      bearerFormat: JWT
+
+  schemas:
+    # ─── Command DTOs ──────────────────────────────────────────
+    CreateOrderRequest:
+      type: object
+      required: [customerId, items]
+      properties:
+        customerId:
+          type: string
+          description: Customer ID
+        items:
+          type: array
+          minItems: 1
+          items:
+            $ref: '#/components/schemas/OrderItemRequest'
+        couponCode:
+          type: string
+          description: Optional coupon code
+
+    OrderItemRequest:
+      type: object
+      required: [productId, quantity]
+      properties:
+        productId:
+          type: string
+        quantity:
+          type: integer
+          minimum: 1
+          maximum: 999
+
+    ConfirmOrderRequest:
+      type: object
+      required: [paymentMethodId]
+      properties:
+        paymentMethodId:
+          type: string
+
+    CancelOrderRequest:
+      type: object
+      required: [reason]
+      properties:
+        reason:
+          type: string
+          maxLength: 500
+
+    # ─── Response DTOs ─────────────────────────────────────────
+    OrderCreatedResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+          example: 0
+        message:
+          type: string
+          example: success
+        data:
+          $ref: '#/components/schemas/OrderCreatedData'
+
+    OrderCreatedData:
+      type: object
+      properties:
+        orderId:
+          type: string
+          example: ORD-2024-001
+        status:
+          type: string
+          example: DRAFT
+        createdAt:
+          type: string
+          format: date-time
+
+    OrderCommandResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+          example: 0
+        message:
+          type: string
+          example: success
+        data:
+          type: object
+          properties:
+            orderId:
+              type: string
+            status:
+              type: string
+
+    # ─── Query DTOs ────────────────────────────────────────────
+    OrderDetailResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+          example: 0
+        message:
+          type: string
+        data:
+          $ref: '#/components/schemas/OrderDetailVO'
+
+    OrderDetailVO:
+      type: object
+      properties:
+        orderId:
+          type: string
+        status:
+          type: string
+        totalAmount:
+          type: string
+        items:
+          type: array
+          items:
+            $ref: '#/components/schemas/OrderItemDTO'
+        customer:
+          $ref: '#/components/schemas/CustomerDTO'
+        payment:
+          $ref: '#/components/schemas/PaymentDTO'
+        shipping:
+          $ref: '#/components/schemas/ShippingDTO'
+        createdAt:
+          type: string
+          format: date-time
+
+    OrderItemDTO:
+      type: object
+      properties:
+        itemId:
+          type: string
+        productName:
+          type: string
+        quantity:
+          type: integer
+        unitPrice:
+          type: string
+        subtotal:
+          type: string
+
+    CustomerDTO:
+      type: object
+      properties:
+        customerId:
+          type: string
+        name:
+          type: string
+        email:
+          type: string
+
+    PaymentDTO:
+      type: object
+      properties:
+        paymentId:
+          type: string
+        method:
+          type: string
+        amount:
+          type: string
+        paidAt:
+          type: string
+          format: date-time
+
+    ShippingDTO:
+      type: object
+      properties:
+        address:
+          type: string
+        carrier:
+          type: string
+        trackingNumber:
+          type: string
+        estimatedDelivery:
+          type: string
+          format: date
+
+    # ─── Paginated Response ────────────────────────────────────
+    OrderListResponse:
+      type: object
+      properties:
+        code:
+          type: integer
+        message:
+          type: string
+        data:
+          $ref: '#/components/schemas/PaginatedOrders'
+
+    PaginatedOrders:
+      type: object
+      properties:
+        records:
+          type: array
+          items:
+            $ref: '#/components/schemas/OrderSummaryVO'
+        total:
+          type: integer
+          example: 100
+        page:
+          type: integer
+          example: 1
+        pageSize:
+          type: integer
+          example: 20
+        totalPages:
+          type: integer
+          example: 5
+
+    OrderSummaryVO:
+      type: object
+      properties:
+        orderId:
+          type: string
+        status:
+          type: string
+        totalAmount:
+          type: string
+        itemCount:
+          type: integer
+        createdAt:
+          type: string
+          format: date-time
+
+    # ─── Error Schema ──────────────────────────────────────────
+    ApiError:
+      type: object
+      properties:
+        code:
+          type: integer
+        message:
+          type: string
+        detail:
+          oneOf:
+            - type: string
+            - type: array
+              items:
+                $ref: '#/components/schemas/FieldError'
+        requestId:
+          type: string
+
+    FieldError:
+      type: object
+      properties:
+        field:
+          type: string
+        message:
+          type: string
+```
+
+## OpenAPI Code Generation Strategy
+
+| Approach | Pros | Cons | Best For |
+|----------|------|------|----------|
+| **Code-first** (annotations) | Single source of truth (code) | Spec may drift from reality | Fast-moving projects |
+| **Spec-first** (YAML → codegen) | Contract-first, client SDK | Needs codegen tooling | Public APIs |
+| **Hybrid** (annotations → spec export) | Both contract + code aligned | Two-step process | Enterprise |
+
+**Recommendation**: Use code-first for DDD services (SpringDoc / swagger-annotations), export to YAML for client SDK generation.
+
+## Collection Format Configuration
+
+```yaml
+# SpringDoc configuration
+springdoc:
+  api-docs:
+    path: /api-docs
+  swagger-ui:
+    path: /swagger-ui.html
+  packages-to-scan: com.example.order.adapter.inbound.web
+  paths-to-match: /api/v2/**
+```
+
+## Generation Rules for DDD APIs
+
+1. **One OpenAPI spec per bounded context** — Order BC has its own spec, Payment BC has its own
+2. **Tag endpoints by CQRS** — `Order Commands` tag for writes, `Order Queries` tag for reads
+3. **Never expose DO fields** — All exposed models are DTOs/VOs, never domain objects
+4. **Document error codes** — Use `x-*` extensions for business error codes
+5. **All datetime fields use ISO 8601** — `format: date-time` or `format: date`
+6. **Use `$ref` for reusable schemas** — Avoid inline schema duplication

+ 0 - 183
skills/ddd-skills/ddd-architecture-awesome/trace-report.md

@@ -1,183 +0,0 @@
-# TRACE 评测报告
-
-> 评估目标:`/Users/wandl/workspaces/workspace-partme-ai/full-stack-skills/skills/ddd-skills/ddd-architecture-awesome` | 评估时间:2026-05-29
-> 评估体系:SkillHub TRACE 严选评测体系 — 腾讯科技、SkillHub、腾讯玄武实验室联合发布
-
----
-
-## 📊 综合评分
-
-| 维度 | 得分 | 等级 |
-|------|:----:|:----:|
-| **T** · Trust(可信任度) | **4.88** | 🟢 Excellent |
-| **R** · Reliability(可靠性) | **4.63** | 🟢 Good |
-| **A** · Adaptability(适用性) | **4.63** | 🟢 Good |
-| **C** · Convention(规范性) | **4.75** | 🟢 Excellent |
-| **E** · Effectiveness(有效性) | **4.65** | 🟢 Good |
-| **综合** | **4.71** | **🟢 Excellent** |
-
-> 等级阈值:≥4.7 Excellent | ≥4.2 Good | ≥3.5 Fair | <3.5 Needs improvement
-
----
-
-## 一句结语
-
-这是一个结构清晰、内容完整的 DDD 知识体系入口技能:27 个分类参考文献形成六层知识金字塔,11 条领域专属 Gotchas 精准预防常见误区,3 个端到端案例覆盖不同复杂度场景,已具备作为 DDD 生态第一入口的高质量标准。
-
----
-
-## 🛡️ T · Trust(可信任度)— 4.88 / 5.0
-
-> 衡量 Skill 在安全、合规和可控性方面是否可信,是整个评估体系中的**红线维度**。
-
-| 子项 | 得分 | 关键证据 | 风险/建议 |
-|------|:----:|------|------|
-| **T1 安全性扫描** | **5.0** | 无 secrets;无 scripts/(纯文档型零风险);body 含 "Security & Stability" 章节(4 条声明:教育用途、不执行代码、BC 隔离安全边界、无脚本) | — |
-| **T2 国内适配性** | **5.0** | 全篇中英双语触发词("DDD 是什么"、"DDD 入门"、"战略设计");架构名称全部中文标注;适配国内 Spring Boot 生态;Reference Library 有中文触发条件 | — |
-| **T3 边界/权限控制** | **4.5** | 三重边界:entry 级 "When to Use / When NOT to" 表(7+7场景) + "When NOT to Use This Skill" 节(5场景带替代方案) + Reference Library 触发表。但边界分散在多个位置,未形成独立三分类章节(✅/⚠️/❌) | 将各处的边界信息整合为一个独立的 "Boundary" 章节,三分类(能做/需条件/超范围)≥3 例 |
-| **T4 安全声明** | **5.0** | "Security & Stability" 声明 4 条:代码模板为教育用途、不执行代码/改文件、BC 隔离天然安全边界、无脚本。纯文档型自动 4.5 + 安全声明明确 → 5.0 | — |
-
-### T 维总结
-
-| 亮点 | 待改进 |
-|------|--------|
-| 零脚本纯文档型,无任何安全风险;中英双语完整覆盖;安全声明明确(4条) | T3 边界信息分散在 3 处,未形成独立三分类章节 |
-
----
-
-## 🔄 R · Reliability(可靠性)— 4.63 / 5.0
-
-> 衡量 Skill 在评测运行中的**稳定性、可复现性和交付可靠性**。
-
-| 子项 | 得分 | 关键证据 | 风险/建议 |
-|------|:----:|------|------|
-| **R1 异常处理** | **4.5** | 11 条领域专属 Gotchas("DDD = COLA误解"、"一上来就搞 CQRS" 等),每条含具体纠正建议;代码示例展示异常处理(throw OrderException)。基分 4.0 + validation(+0.5) = 4.5 | Gotchas 缺少"信息不足时先给假设版本"的交互式引导模板 |
-| **R2 可运行性** | **4.5** | 4 步结构化工作流(理解上下文→评估适用性→推荐路径→输出格式);3 个 examples 覆盖考勤/电商/保险。基分 4.5(steps=4 < 5) | 增加第 5 步:"当用户输入不足以判断适用性时,先给出假设版本的评估结果" |
-| **R3 交付物完整性** | **4.5** | Gotchas + 代码反例对比 + 输出格式模板(4步骤结构)+ 充血模型代码。基分 4.0 + gotchas(+0.3) + validation(+0.2) = 4.5 | 缺少明确的 plan-validate-execute 循环或校验清单 |
-| **R4 降级处理** | **5.0** | "When NOT to Use This Skill" 表格(5 场景)均有替代方案引导:"Already know DDD well → Jump to architecture-selector"、"Existing project → architecture-evaluator"。输入模糊时 Decision Flowchart 可给初步判断。**基分校准:** 脚本因 `boundary=false` 给 3.5,但正文有完整的降级替代方案(5场景),手动校准 +1.5 | — |
-
-### R 维总结
-
-| 亮点 | 待改进 |
-|------|--------|
-| Gotchas 质量高(11条具体领域陷阱+纠正);降级兜底优秀(每场景有替代 Skill 引导) | 缺少交互式引导模板;steps=4 未达 5 step 满分阈值 |
-
----
-
-## 🎯 A · Adaptability(适用性)— 4.63 / 5.0
-
-> 衡量 Skill 是否适合其声明的使用场景,以及在真实候选环境中是否容易被**正确识别和调用**。
-
-| 子项 | 得分 | 关键证据 | 风险/建议 |
-|------|:----:|------|------|
-| **A1 边界清晰度** | **4.8** | 双重边界 + 场景化路由:entry 级 "When to Use / When NOT to" 表 + "When to trigger" 触发词清单 + Reference Library 表每条有触发条件。近失覆盖完整。**基分校准:** 脚本因 `boundary=false` 给 4.0,但正文有完整的 "When to Use / When NOT to" + 触发词列表,手动校准 +0.8 | T3 同样的问题:边界信息分散,整合为独立 Boundary 三分类章节可达到 5.0 |
-| **A2 Description 触发质量** | **5.0** | 653 chars(在 1024 限制内),祈使句 "Use when...",覆盖 DDD 核心关键词,中英文触发信号 | — |
-| **A3 国内适用性** | **4.5** | 全篇中英双语关键词 + 触发词;但未显式声明目标受众类型(新手/架构师/开发者)或提供不同经验级别的使用路径。基分 4.0 + chinese(+0.3) = 4.3,受众细分可上调到 4.5 | 增加 "受众分级" 段落:新手路径 / 架构师路径 / 开发者路径 |
-| **A4 场景覆盖广度** | **4.2** | 3 examples 覆盖考勤/电商/保险,27 refs 覆盖 6 主题域。基分 4.0,27 refs 在 prompt 型中算丰富,上调 +0.2 | 增加 IoT/金融交易等更高复杂度场景的 example |
-
-### A 维总结
-
-| 亮点 | 待改进 |
-|------|--------|
-| Description 触发质量完美(653 chars + 中英关键词 + 祈使句);边界近失场景覆盖完整 | 缺少显式受众分级;场景覆盖面可进一步扩展 |
-
----
-
-## 📐 C · Convention(规范性)— 4.75 / 5.0
-
-> 衡量 Skill 是否具备清晰、可维护、可复用的**结构基础**。
-
-| 子项 | 得分 | 关键证据 | 风险/建议 |
-|------|:----:|------|------|
-| **C1 用途/适用说明** | **4.7** | 三重用途:"When to trigger" + "When to Use/When NOT to" + "Reference Library" 每条带触发条件。基分 4.5,明确性优秀上调 +0.2 | — |
-| **C2 渐进披露** | **4.5** | 6 个 references 子目录按 01-07 序号分类;27 文件每条有触发条件;SKILL.md 505 行接近 500 上限。基分 4.2,渐进披露质量好上调 +0.3 | SKILL.md 505 行略超推荐上限 500,考虑将 Sources 章节(30+行URL列表)移到 references |
-| **C3 元信息结构** | **5.0** | name=docker-architecture-awesome 有效且匹配目录;license=Apache-2.0;6 子目录 + 3 examples 编号有序 | — |
-| **C4 Gotchas 与指令规范** | **4.8** | 11 条领域专属 Gotchas,每条精确反映该领域最常见具体错误 + 纠正建议(非泛泛的 "handle errors appropriately") | — |
-
-### C 维总结
-
-| 亮点 | 待改进 |
-|------|--------|
-| 渐进披露优秀(27 文件 6 级分类 + 逐一触发条件);Gotchas 精准实用 | SKILL.md 505 行略超推荐 500 上限 |
-
----
-
-## ⚡ E · Effectiveness(有效性)— 4.65 / 5.0
-
-> 衡量 Skill 是否**真正提升任务结果**,以及这种提升是否值得付出相应代价。
-
-| 子项 | 得分 | 关键证据 | 风险/建议 |
-|------|:----:|------|------|
-| **E1 任务完成度** | **4.8** | 12 个章节完整覆盖:DDD 定义→决策树→复杂度阶梯→架构全景→核心概念→充血模型对比→反模式→实施顺序→学习路径→Sources→Reference Library→Gotchas | — |
-| **E2 正确性/权威性** | **4.3** | 引用 Evans、Vernon、Fowler、Cockburn、R.C. Martin、Brandolini 等权威源;Jackson 充血模型代码正确;基分 4.0,权威源引用 + 代码正确上调 +0.3 | 部分 ASCII 架构图在 < 80 列终端下有轻微对齐问题 |
-| **E3 交付物质量** | **4.7** | 27 refs 形成 6 层知识体系(战略→战术→架构→速查→实施→企业级);3 examples 含结构化表格 + 决策树 + 代码模板 | — |
-| **E4 增益归因** | **4.8** | vs no-skill 基线:① 27 文件库支持精确查询 ② 6 级分类体系 ③ 11 条领域 Gotchas 避免常见错误 ④ 3 个完整案例 ⑤ 结构化决策树替代泛泛建议。增益明显且可归因于 skill | — |
-
-### E 维总结
-
-| 亮点 | 待改进 |
-|------|--------|
-| 12 章完整知识链条;27 refs 知识库可追溯;增益对比 no-skill 明显 | E2 ASCII 图小瑕疵 |
-
----
-
-## 📊 no-skill 基线对比
-
-| 对比维度 | no-skill(裸模型) | 启用此 skill | 增益 |
-|----------|:---:|:---:|:---:|
-| DDD 概念准确性 | 中等(依赖训练数据) | 高(Evans/Vernon/Fowler 等权威源 + 完整概念体系) | ↑↑ |
-| 适用场景判断 | 通用化建议 | 结构化决策树 + 四维度评估表 + 决策流程图 | ↑↑ |
-| 架构选型指导 | 可能偏颇(倾向 Clean/Hexagonal) | 5 种架构平等对比 + COLA 中文生态适配 | ↑↑↑ |
-| 反模式检测 | 泛泛而谈 | 10 条精确反模式 + 修复方案 + 代码正反对比 | ↑↑↑ |
-| 知识可追溯性 | 无 | 27 reference 文件 + 完整 Sources 引用链 + 多语言参考实现 | ↑↑↑ |
-| Token 成本 | 0 | SKILL.md ~505 lines ≈ 3000 tokens | 中等 |
-
----
-
-## 📋 官方规范合规(agentskills.io)
-
-| # | 检查项 | 结果 | 证据 |
-|---|--------|:----:|------|
-| 1 | SKILL.md 存在 | ✅ | SKILL.md 位于技能根目录 |
-| 2 | Name 与目录名一致 | ✅ | name=ddd-architecture-awesome |
-| 3 | Name 格式有效(kebab-case) | ✅ | 小写字母+连字符,<64 字符 |
-| 4 | Description 有效(1-1024 chars) | ✅ | 653 chars,描述做什么 + 何时使用 |
-| 5 | License 字段 | ✅ | Apache-2.0 |
-| 6 | 目录结构规范 | ✅ | references=true(6 subdirs/27 files),examples=true(3 files) |
-| 7 | 渐进式披露质量 | ✅ | SKILL.md ~505 lines;Reference Library 每条带触发条件 |
-| 8 | Description 触发质量 | ✅ | 祈使句 "Use when...",覆盖中英文触发词 |
-| 9 | 脚本安全性 | ✅ N/A | 无 scripts/ 目录 |
-| 10 | 密钥/敏感信息扫描 | ✅ | 未检出任何 secret 模式 |
-
----
-
-## 💡 优化建议(优先级排序)
-
-| 优先级 | 维度 | 建议 |
-|:--:|------|------|
-| **P1** | T3/A1 (边界) | 将分散的边界信息(When to Use / When NOT to / When to trigger)整合为一个独立的 "Boundary" 三分类章节(✅ 擅长 / ⚠️ 需条件 / ❌ 超范围),每类 ≥ 3 例 |
-| **P2** | R1 (异常) | 为 Gotchas 增加交互式引导模板:"信息不足时先给假设版本的 DDD 适用性评估 + 列具体缺少什么信息",替代笼统的"请提供更多信息" |
-| **P3** | A3 (受众) | 增加 "受众分级" 段落:DDD 新手路径(awesome → selector → layered → domain-designer)vs 架构师路径(selector → hexagonal/clean → evaluator) |
-
----
-
-## 📦 Skill 基础画像
-
-| 指标 | 值 |
-|------|-----|
-| 路径 | `skills/ddd-skills/ddd-architecture-awesome` |
-| SKILL.md | 505 lines · 29,480 chars |
-| References | 27 files · 6 subdirectories |
-| Examples | 3 end-to-end cases |
-| Scripts | 0 |
-| License | Apache-2.0 |
-| Secrets | 0 detected |
-| Gotchas | 11 domain-specific |
-| 中文化 | English + 中文双语(触发词+术语+描述) |
-| Skill Type | prompt(知识 + 学习路径引导) |
-
----
-
-> 评测基于 **SkillHub TRACE 严选评测体系**(腾讯科技、SkillHub、腾讯玄武实验室联合发布)
-> 官方规范合规检查基于 **agentskills.io** 标准
-> Generated 2026-05-29 · ddd-architecture-awesome

+ 165 - 341
skills/ddd-skills/ddd-architecture-clean/SKILL.md

@@ -1,376 +1,200 @@
 ---
 name: ddd-architecture-clean
-description: Provides comprehensive guidance for Clean Architecture implementation in DDD. Based on Robert C. Martin's Clean Architecture, organized around UseCases with strict dependency rules. Covers Enterprise Business Rules (Entities), Application Business Rules (UseCases), Interface Adapters, and Frameworks & Drivers layers. Includes complete directory structure, code templates with Interactor pattern, Input/Output ports, testing strategy, and implementation guide. Use when the user asks about clean architecture, 整洁架构, Robert Martin, Uncle Bob, use case driven design, needs enterprise-level strict module isolation, or large team DDD standardization.
+description: Comprehensive guidance for Clean Architecture (整洁架构) — Robert C. Martin's Clean Architecture with Enterprise Business Rules, Use Cases, Interface Adapters, and Frameworks layers. Covers core entities, use case interactors, dependency rules, and full implementation steps with Java/Spring Boot examples. Use when user asks about Clean Architecture, 整洁架构, Robert Martin, Uncle Bob, use case driven architecture, or needs to implement DDD with clean architecture.
 license: Apache-2.0
 ---
 
-# DDD Architecture - Clean
+# DDD Architecture  Clean
 
-Clean Architecture implementation guide — organized around UseCases with strict dependency rules. Based on Robert C. Martin's "Clean Architecture".
+> Clean Architecture by Robert C. Martin (Uncle Bob): UseCase-centric, strict dependency rule — source code dependencies must point only inward.
 
-## When to use this skill
+## Quick Start
 
-**ALWAYS use this skill when the user mentions:**
-- "整洁架构"、"Clean Architecture"、"Robert Martin"、"Uncle Bob"
-- "用例驱动"、"use case driven"
-- "企业级架构"、"enterprise architecture"
-- "严格模块隔离"、"strict module isolation"
-- Large team (15-50 people) DDD standardization
-- Core enterprise systems (order, payment, etc.)
-- Business rules independent of delivery mechanism
-- Need physical module isolation with strict boundaries
+直接说明你的需求,例如: "帮我建整洁架构项目骨架" / "订单模块实现 CreateOrder UseCase,从实体到控制器" / "检查项目依赖方向是否正确" / "从三层迁移到整洁架构,先迁订单"。
 
-## Architecture Overview
+信息不足时我先给参考版本,再列出需要补充的具体信息。
 
-### Core Concept
+## Workflow
 
-```
-Clean Architecture: UseCase-centric, strict dependency rules
-
-                    ┌──────────────────────┐
-                    │    Frameworks &       │
-                    │    Drivers             │
-                    │  ┌────────────────┐   │
-                    │  │  Interface      │   │
-                    │  │  Adapters       │   │
-                    │  │  ┌──────────┐   │   │
-                    │  │  │   App    │   │   │
-                    │  │  │ Business │   │   │
-                    │  │  │  Rules   │   │   │
-                    │  │  │ ┌──────┐ │   │   │
-                    │  │  │ │Entity│ │   │   │
-                    │  │  │ │  ★   │ │   │   │
-                    │  │  │ └──────┘ │   │   │
-                    │  │  └──────────┘   │   │
-                    │  └────────────────┘   │
-                    └──────────────────────┘
-```
-
-**Dependency Rule**: Source code dependencies must point only inward. Outer layers can depend on inner layers; inner layers never know about outer layers.
-
-### Four Layer Structure
-
-| Layer (outer → inner) | Responsibility | Depends On |
-|------------------------|---------------|------------|
-| Frameworks & Drivers | Web framework, DB, UI | → Adapters |
-| Interface Adapters | Controller, Gateway, Presenter | → Application |
-| Application Business Rules | Use Cases (orchestration) | → Enterprise |
-| Enterprise Business Rules | Entity, core business rules ★ | Nothing |
-
-## Applicability Check
-
-| ✓ Applicable | ✗ Not Applicable |
-|--------------|-------------------|
-| Enterprise core systems (order, payment) | Temporary scripts, small tools |
-| Business rules independent of delivery | Frontend-heavy, backend-light CRUD |
-| Need strict module physical isolation | Team < 5, rapid iteration |
-| Microservice internal standardization | Simple 3-layer suffices |
-
-## Complete Directory Structure
+### Step 1: 确认基础概念
+确保团队对 DDD 实体、值对象、聚合根有一致理解。不清晰则先参考 `ddd-architecture-awesome`。
 
-```
-{project}/
-├── {project}-core/                    # Enterprise Business Rules
-│   ├── entity/                        # ★ Core Entities
-│   │   ├── Order.java
-│   │   ├── OrderId.java
-│   │   ├── OrderStatus.java
-│   │   └── Money.java
-│   ├── rule/                          # ★ Enterprise Business Rules
-│   │   ├── OrderValidationRule.java
-│   │   └── PricingRule.java
-│   └── exception/                     # ★ Domain Exceptions
-├── {project}-usecase/                 # Application Business Rules (UseCase)
-│   ├── port/                          # UseCase Input/Output Ports
-│   │   ├── input/                     # Input Ports (UseCase interfaces)
-│   │   │   ├── CreateOrderUseCase.java
-│   │   │   └── PayOrderUseCase.java
-│   │   └── output/                    # Output Ports (Repository/Gateway interfaces)
-│   │       ├── OrderRepository.java
-│   │       └── PaymentGateway.java
-│   ├── interactor/                    # UseCase Implementation (Interactor)
-│   │   ├── CreateOrderInteractor.java
-│   │   └── PayOrderInteractor.java
-│   └── dto/                           # UseCase-specific DTOs
-│       ├── CreateOrderRequest.java
-│       └── PayOrderResponse.java
-├── {project}-adapter/                 # Interface Adapters Layer
-│   ├── controller/                    # REST / gRPC Controllers
-│   ├── presenter/                     # Response format conversion
-│   ├── repository/                    # DB implementation (implements UseCase output ports)
-│   ├── gateway/                       # External API implementation
-│   └── converter/                     # DTO/PO ↔ Entity conversion
-└── {project}-framework/               # Frameworks & Drivers Layer
-    ├── config/                        # Spring/DI configuration
-    ├── persistence/                   # JPA Entity, Mapper
-    └── web/                           # Web config (CORS, Security)
-```
-
-## Code Templates
-
-### Enterprise Layer (Core)
+### Step 2: 定义 Enterprise Business Rules
+识别聚合根 → 设计实体 + 值对象 → 实现业务规则 → 定义领域事件。参考 [01-core-entities](references/01-core-entities.md)、[order-entity example](examples/01-order-entity.md)
 
-```java
-// ★ Core Entity — zero framework dependencies
-public class Order {
-    private final OrderId id;
-    private Money totalAmount;
-    private OrderStatus status;
-
-    public void pay() {
-        if (!this.status.canPay()) {
-            throw new OrderDomainException("Cannot pay in current status");
-        }
-        this.status = OrderStatus.PAID;
-    }
-}
-```
-
-### UseCase Layer (Application)
-
-```java
-// ★ Input Port (UseCase interface)
-public interface CreateOrderUseCase {
-    CreateOrderOutput execute(CreateOrderInput input);
-}
-
-// ★ Output Port (Repository interface)
-public interface OrderRepository {
-    Order save(Order order);
-    Optional<Order> findById(OrderId id);
-}
-
-// ★ Interactor (UseCase implementation)
-public class CreateOrderInteractor implements CreateOrderUseCase {
-    private final OrderRepository orderRepository;
-
-    @Override
-    public CreateOrderOutput execute(CreateOrderInput input) {
-        Order order = Order.create(/* ... */);   // Enterprise layer
-        orderRepository.save(order);              // Through port
-        return CreateOrderOutput.from(order);
-    }
-}
-```
-
-### Adapter Layer
-
-```java
-// Controller
-@RestController
-public class OrderController {
-    private final CreateOrderUseCase createOrderUseCase;
-
-    @PostMapping("/orders")
-    public ResponseEntity<CreateOrderResponse> createOrder(
-            @RequestBody CreateOrderRequest request) {
-        var input = request.toInput();
-        var output = createOrderUseCase.execute(input);
-        return ResponseEntity.ok(CreateOrderResponse.from(output));
-    }
-}
-
-// Repository Implementation
-@Repository
-public class JpaOrderRepository implements OrderRepository {
-    private final JpaOrderRepo jpaRepo;
-    private final OrderMapper mapper;
-
-    @Override
-    public Order save(Order order) {
-        return mapper.toDomain(jpaRepo.save(mapper.toPO(order)));
-    }
-
-    @Override
-    public Optional<Order> findById(OrderId id) {
-        return jpaRepo.findById(id.getValue()).map(mapper::toDomain);
-    }
-}
-```
-
-### Framework Layer
-
-```java
-@Configuration
-public class UseCaseConfig {
-    @Bean
-    public CreateOrderUseCase createOrderUseCase(OrderRepository repo) {
-        return new CreateOrderInteractor(repo);
-    }
-}
-```
-
-## Testing Strategy
-
-```
-Enterprise Layer (Unit Test):
-  ✓ Entity business rules
-  ✓ Validation rules
-  ✓ No mocking needed (pure logic)
-
-UseCase Layer (Integration Test):
-  ✓ Interactor with Mock output ports
-  ✓ Verify correct Entity interaction
-
-Adapter Layer (Integration Test):
-  ✓ Controller with Mock UseCase
-  ✓ Repository with Testcontainers
-
-Framework Layer (E2E Test):
-  ✓ Complete request → response
-```
-
-## Implementation Phases
-
-```
-Phase 1: Enterprise Business Rules (1-3 days)
-  → Core entities → Business rules → Domain exceptions
+### Step 3: 定义 UseCase 端口
+为每个 UseCase 定义独立 Input Port → Output Port → UseCase DTO。参考 [02-usecase-ports](references/02-usecase-ports.md)
 
-Phase 2: UseCase + Ports (1-2 days)
-  → Input ports (UseCase) → Output ports (Repository/Gateway)
+### Step 4: 实现 UseCase Interactor
+编写 Interactor → 编排实体 + 端口调用 → 发布领域事件。参考 [03-interactors](references/03-interactors.md)、[create-order example](examples/02-create-order-usecase.md)
 
-Phase 3: UseCase Interactors (1-2 days)
-  → UseCase implementations → DTO definitions
+### Step 5: 实现适配器层
+Controller → Presenter → Repository Impl → Gateway Impl → DI 配置。参考 [04-adapters](references/04-adapters.md)、[05-framework-config](references/05-framework-config.md)
 
-Phase 4: Adapters + Framework (2-3 days)
-  → Controllers/Gateways → Repository implementations → DI config
+### Step 6: 验证与测试
+Enterprise 单元测试 → UseCase 集成测试 → Adapter 集成测试 → ArchUnit 验证。参考 [06-dependency-rules](references/06-dependency-rules.md)、[07-testing-strategy](references/07-testing-strategy.md)
 
-Phase 5: Testing (1-2 days)
-  → Enterprise unit tests → UseCase integration tests (mock ports) → Adapter E2E tests
-```
+## When to Use / When NOT to
 
-## Quick Decision: Where Does This Code Go?
+| ✅ 适用 | ❌ 不适用 |
+|----------|-----------|
+| 企业级核心系统(订单、支付、库存) | 临时脚本、小工具 |
+| 业务规则独立于交付机制 | 前端重后端轻的简单 CRUD |
+| 需要严格模块物理隔离(15-50 人团队) | 团队 < 5 人、需快速迭代 |
+| 微服务内部标准化架构 | 简单三层架构已足够 |
+| UseCase 驱动的复杂业务编排 | 无复杂业务逻辑的管理后台 |
+
+## Boundary
+
+| 类别 | 能力 | 说明 |
+|------|------|------|
+| ✅ 擅长 | 严格分层的企业级系统 | 15-50 人团队,模块间强隔离 |
+| ✅ 擅长 | UseCase 驱动设计 | 每个用例独立 Interactor + Port |
+| ✅ 擅长 | 依赖规则自动化检查 | ArchUnit 全自动验证分层合规 |
+| ✅ 擅长 | 多语言落地 | Java/Go/TypeScript/C# 均可实现 |
+| ⚠️ 需条件 | 团队理解 Interactor 模式 | 否则学习成本高,需培训 |
+| ⚠️ 需条件 | 项目有一定规模 | 小项目用 Layered/Onion 更合适 |
+| ⚠️ 需条件 | 需配合 DDD 领域模型 | 单独使用 Clean Architecture 过于抽象 |
+| ❌ 超出范围 | 简单 CRUD 项目 | 用 `ddd-architecture-layered` |
+| ❌ 超出范围 | 中文 Spring Boot 生态 | 用 `ddd-architecture-cola` |
+| ❌ 超出范围 | 需要可视化环状模型 | 用 `ddd-architecture-onion` |
+| ❌ 超出范围 | 需要端口适配器概念 | 用 `ddd-architecture-hexagonal` |
+
+## 受众说明
+
+| 用户类型 | 使用方式 |
+|---------|---------|
+| **后端架构师 / 技术负责人** | 直接使用,选型并按照 Workflow 6 步落地 |
+| **Java 开发者** | 参考 examples/ 代码模板,按步骤实现 UseCase |
+| **DDD 初学者** | 先读 `ddd-architecture-awesome` 了解概念,再回来看本 Skill |
+| **多语言团队(Go/TypeScript/C#)** | 架构规则通用,参考 references/ 中语言无关的部分 |
+
+定制化:触发时说明你的技术栈(Java/Go/TS)、模块名称(如订单/支付),我会针对性地生成代码模板。
+
+## 核心架构
 
 ```
-├─ Is it a core business rule with NO external knowledge? → Enterprise layer (core/entity, core/rule)
-├─ Is it a business validation or invariant? → Enterprise layer (core/exception)
-├─ Is it a UseCase input interface? → UseCase layer (usecase/port/input)
-├─ Is it a Repository or Gateway interface? → UseCase layer (usecase/port/output)
-├─ Is it implementing a UseCase (orchestrating entities + ports)? → UseCase layer (usecase/interactor)
-├─ Is it an HTTP/gRPC/CLI entry point? → Adapter layer (adapter/controller, adapter/presenter)
-├─ Is it implementing a DB/Gateway? → Adapter layer (adapter/repository, adapter/gateway)
-├─ Is it Spring/DI wiring, JPA entities, Web config? → Framework layer (framework/config, framework/persistence)
-└─ Golden rule: "Source code dependencies must point only inward"
+Enterprise ← UseCase ← Adapter ← Framework
 ```
 
-## Sources
+详细原理(四层结构、架构对比、数据流转)参考 [architecture-principles](references/architecture-principles.md)。目录结构参考 [directory-structure](references/directory-structure.md)。
+
+## 开发规范
+
+| 规范 | 说明 | 违规示例 |
+|------|------|---------|
+| Entity 零框架依赖 | 不可 import Spring/JPA/Jackson | `@Entity` 出现在 `core/entity/` |
+| 每个 UseCase 独立端口 | 一个 UseCase = 一个 Input Port 接口 | 多个 UseCase 共享同一个接口 |
+| Interactor 只编排不做业务 | 业务 if/else 必须在 Entity 中 | Interactor 中有状态机判断 |
+| Output Port 在 UseCase 定义 | Repository 接口定义在 usecase 层 | Adapter 定义 Repository 接口 |
+| 数据转换在 Adapter 层 | Controller DTO 不可穿越到 UseCase | `@RequestBody` DTO 直接传入 Interactor |
+| 事务在 Framework 层管理 | @Transactional 只在 adapter/repository | Entity 方法上有 @Transactional |
+
+详细规范请参考 [references/06-dependency-rules.md](references/06-dependency-rules.md)。
+
+## Gotchas
+
+| # | 陷阱 | 现象 | 正确做法 |
+|---|------|------|---------|
+| 1 | UseCase 包含业务逻辑 | Interactor 中有 if/else 状态判断 | 抽到 Entity/Domain Service |
+| 2 | Input Port 共享 | 多个 UseCase 共用一个接口 | 每个 UseCase 独立 Input Port |
+| 3 | Controller DTO 穿越层 | 框架 DTO 传入 UseCase 层 | Adapter 层完成 DTO ↔ Domain 转换 |
+| 4 | Entity 上有 @Entity 注解 | JPA 注解泄露到 Enterprise 层 | 在 Adapter 层创建独立的 JPA Entity |
+| 5 | Interactor 直接调 Adapter | 跳过 Output Port 调用实现类 | 通过 Output Port 接口调用 |
+| 6 | Output Port 放在 Adapter 层 | UseCase 依赖 Adapter 包 | Output Port 接口定义在 UseCase 层 |
+| 7 | UseCase 返回 Entity 对象 | Interactor 返回 `Order` 而非 DTO | 返回 UseCase 专属 Output DTO |
+| 8 | 过度设计简单查询 | 读操作也走完整 Input→Interactor→Output | 简单查询直接走 Repository |
+| 9 | Adapter 包含业务逻辑 | Controller 中有 if/else | 业务逻辑全在 Enterprise 层 |
+| 10 | 缺少 ArchUnit 检查 | 依赖违规无法自动发现 | CI 中集成 ArchUnit 测试 |
+| 11 | 领域对象可变 | ValueObject 有 setter 方法 | 所有值对象不可变 (record/final) |
+| 12 | UseCase 粒度不当 | Interactor 过大 (200+ 行) | 一个 Interactor 只做一个业务操作 |
+| 13 | 忽略领域事件 | 关键操作后无事件发布 | 状态变更必须产生领域事件 |
+| 14 | 事务在 UseCase 层 | Interactor 上有 @Transactional | 事务在 Adapter/Repository 层 |
+| 15 | Entity 构造函数暴露 | Entity 用 public 构造函数 | 使用 static factory 方法(如 Order.create()) |
+
+## FAQ
+
+| # | 问题 | 回答 |
+|---|------|------|
+| 1 | Clean Architecture 和六边形架构有什么区别? | 整洁架构以 UseCase 为组织核心,强调四层严格隔离;六边形以 Port/Adapter 为抽象,强调驱动/被驱动端口对称性。核心目标一致:内层不依赖外层。 |
+| 2 | 什么时候用 Interactor vs Domain Service? | Interactor 在 UseCase 层做编排(调 Entity + 调 Port);Domain Service 在 Enterprise 层封装跨实体的业务规则(如 PricingService)。 |
+| 3 | Service 在哪里写业务逻辑? | 都没有。Entity 中有业务方法(pay/cancel),DomainService 封装跨实体规则,Interactor 只编排不决策。 |
+| 4 | 每个 UseCase 都要有独立的 Input Port 吗? | 是。这遵循接口隔离原则(ISP)。IOrderService 这种大接口是反模式。 |
+| 5 | 一个 UseCase 有多个输出怎么办? | 每个输出独立为一个 Output Port。如 OrderRepository 为持久化,EventPublisher 为事件,PaymentGateway 为支付。 |
+| 6 | Entity 层可以引用 Repository 接口吗? | 不可以。Enterprise 层不能知道任何 Output Port 的存在。Repository 接口在 UseCase 层定义。 |
+| 7 | 简单查询也走 UseCase 层吗? | 不。纯读操作可以直接调用 Repository(查询不改变状态)。写操作必须走 UseCase。 |
+| 8 | 如何组织多个 UseCase? | 按业务聚合组织:`order/usecase/` 下放所有 Order 相关的 CreateOrder/PayOrder/CancelOrder。 |
+| 9 | Interactor 中如何做事务? | Framework 层通过声明式事务(@Transactional)包裹 Interactor 调用。 |
+| 10 | JPA Entity 和 Domain Entity 要分开吗? | 要。JPA Entity(@Entity)在 Adapter 层,Domain Entity(纯 POJO)在 Enterprise 层。通过 Converter 转换。 |
+| 11 | 项目从三层架构迁移要多久? | 小型 (6 周) / 中型 (12 周) / 大型 (20 周)。使用 Strangler Fig 模式按 UseCase 逐步迁移。 |
+| 12 | 如何保证依赖规则不被破坏? | 在 Framework 模块中写 ArchUnit 测试(参考 examples/04-archunit-test.md),CI 中每次提交自动检查。 |
+| 13 | 值对象和实体的区别? | 值对象不可变、无 ID、按属性相等(如 Money);实体可变、有唯一 ID、按 ID 相等(如 Order)。 |
+| 14 | 领域事件是同步还是异步发布? | Interactor 中同步收集事件并发布到 EventPublisher Port。异步处理由 Adapter 实现(写消息队列)。 |
+| 15 | 适配器层可以有多个实现吗? | 可以。一个 Output Port 可以有多个 Adapter 实现:JPA/MyBatis/InMemory,通过 Spring Profile 切换。 |
+
+## Keywords
+
+Clean Architecture, 整洁架构, Robert C. Martin, Uncle Bob, Enterprise Business Rules, Use Case, Interactor, Input Port, Output Port, Interface Adapter, Dependency Rule, 依赖倒置, 接口隔离, DDD, 领域驱动设计, 分层架构, 严格分层, 用例驱动, 领域模型, 实体, 值对象, 聚合根, 领域事件, ArchUnit, 依赖规则检查
+
+## References
+### Internal
+
+| 文件 | 内容 |
+|------|------|
+| [references/architecture-principles.md](references/architecture-principles.md) | 四层结构、依赖规则、架构对比、数据流转、目录结构 |
+| [references/01-core-entities.md](references/01-core-entities.md) | Enterprise 层实体、值对象、领域事件、异常模板与测试 |
+| [references/02-usecase-ports.md](references/02-usecase-ports.md) | Input/Output Port 定义、DTO 设计、端口设计规则 |
+| [references/03-interactors.md](references/03-interactors.md) | Interactor 实现模板、复杂编排、查询 Interactor、测试 |
+| [references/04-adapters.md](references/04-adapters.md) | Controller、Repository Impl、Gateway 适配器实现 |
+| [references/05-framework-config.md](references/05-framework-config.md) | Spring DI 配置、Security、Persistence、多 Profile |
+| [references/06-dependency-rules.md](references/06-dependency-rules.md) | 依赖规则矩阵、ArchUnit 全量测试集、CI 集成 |
+| [references/07-testing-strategy.md](references/07-testing-strategy.md) | 分层测试策略、Test Doubles、覆盖率目标 |
+| [references/08-migration-guide.md](references/08-migration-guide.md) | 三层→整洁架构迁移指南、Strangler Fig 模式 |
+| [examples/01-order-entity.md](examples/01-order-entity.md) | 完整 Order 实体代码 + 状态机 + 单元测试 |
+| [examples/02-create-order-usecase.md](examples/02-create-order-usecase.md) | 完整 CreateOrder UseCase 实现 + 测试 + Test Doubles |
+| [examples/03-repository-implementation.md](examples/03-repository-implementation.md) | Repository Adapter JPA 实现 + 集成测试 |
+| [examples/04-archunit-test.md](examples/04-archunit-test.md) | 完整 ArchUnit 依赖规则测试套件 |
+| [examples/05-domain-event-handling.md](examples/05-domain-event-handling.md) | 领域事件定义、发布、消费完整实现 |
+| [examples/06-monolith-simple.md](examples/06-monolith-simple.md) | 单体 Clean 简单版:单模块包级四层,目录树+依赖方向+ArchUnit |
+| [examples/07-monolith-complex.md](examples/07-monolith-complex.md) | 单体 Clean 复杂版:多聚合+多 Interactor,共享内核+领域隔离 |
+| [examples/08-monolith-multi-module.md](examples/08-monolith-multi-module.md) | 单体 Clean 多模块版:Maven 模块级分层,编译期强制依赖方向 |
+| [examples/09-microservice-simple.md](examples/09-microservice-simple.md) | 微服务 Clean 简单版:包级四层+事件总线+Kafka 适配器 |
+| [examples/10-microservice-complex.md](examples/10-microservice-complex.md) | 微服务 Clean 复杂版:CQRS + Saga + Outbox + 多子域 |
+| [examples/11-microservice-multi-module.md](examples/11-microservice-multi-module.md) | 微服务 Clean 多模块版:6 模块+API 契约独立发布 |
+| [examples/12-microservice-complex-multi.md](examples/12-microservice-complex-multi.md) | 微服务 Clean 复杂多模块:8 模块+全模式矩阵+子域编排 |
+
+### External
 
-### Primary Sources
 - [The Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) — Robert C. Martin (2012)
 - [Clean Architecture: A Craftsman's Guide](https://www.oreilly.com/library/view/clean-architecture-a/9780134494272/) — Robert C. Martin (2017)
 - [Domain-Driven Design: The Blue Book](https://www.domainlanguage.com/ddd/blue-book/) — Eric Evans (2003)
-- [Explicit Architecture](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together/) — Herberto Graça
-
-### Implementation Guides
 - [Get Your Hands Dirty on Clean Architecture](https://reflectoring.io/book/) — Tom Hombergs
-
-### Reference Implementations
-| Language | Repository |
-|----------|-----------|
-| Java | [thombergs/buckpal](https://github.com/thombergs/buckpal) |
-| Go | [bxcodec/go-clean-arch](https://github.com/bxcodec/go-clean-arch) |
-| .NET | [jasontaylordev/CleanArchitecture](https://github.com/jasontaylordev/CleanArchitecture) |
-
-## Output
-
-When assisting with this skill, provide:
-- Complete Clean Architecture project directory structure
-- Enterprise entity base classes + rule templates
-- UseCase ports (Input/Output) + Interactor templates
-- Adapter layer code templates
-- Framework layer DI configuration
-- Complete testing strategy (unit → integration → E2E)
-
----
-
-## clean-ddd-hexagonal References
-
-| File | Purpose |
-|------|--------|
-| [references/clean-ddd-hexagonal-hexagonal.md](references/clean-ddd-hexagonal-hexagonal.md) | Hexagonal Architecture ports & adapters — driver/driven ports, naming conventions, configurability |
-
-## Skill Boundary
-
-### ✅ 擅长处理
-1. 严格分层的大型企业系统(15-50 人团队)
-2. UseCase 驱动的设计:每个用例有独立 Interactor + Port
-3. 模块间强隔离:外圆永远不能影响内圆
-4. 多语言落地:Go/Java/TypeScript/C# 均可实现
-
-### ⚠️ 需要条件
-1. 团队理解 Interactor 模式:否则学习成本高
-2. 项目有一定规模:小项目用 Layered/Onion 更合适
-3. 需要配合 DDD 领域模型:单独使用 Clean Architecture 过于抽象
-
-### ❌ 超出范围
-1. 简单 CRUD 项目 → 用 `ddd-architecture-layered`
-2. 中文 Spring Boot 生态 → 用 `ddd-architecture-cola`
-3. 需要可视化的环状模型 → 用 `ddd-architecture-onion`
-
-
-## Security & Stability
-
-- All code templates are educational. Replace placeholder credentials with environment variables.
-- Clean Architecture's dependency rule (only inward) prevents domain code from accessing I/O — built-in security advantage.
-- Interactor pattern ensures each UseCase is independently testable without framework dependencies.
-- No executable scripts bundled. This skill provides architecture guidance and code generation patterns only.
-
-
-## Gotchas — Common Pitfalls
-
-- **UseCase 包含业务逻辑**: UseCase(Interactor)只做编排,不包含业务规则。业务规则在 Entity(Enterprise Business Rule)层。如果 UseCase 中有状态转移判断,抽到 Domain Service。
-- **Input/Output Port 滥用**: 每个 UseCase 应有独立的 Input Port 和 Output Port。不要多个 UseCase 共享同一个 Port 接口 — 违反了接口隔离原则。
-- **跨层类型转换遗漏**: Adapter 层返回给 UseCase 的数据必须转换为领域类型。不要让 Controller 的 DTO 直接穿越到 UseCase 层。
-- **Framework 层代码泄露**: Entity 层(最内层)绝不能 import Spring、JPA、Jackson 等框架类。如果 Entity 中有 `@Entity` 注解,整洁架构就破了。
-- **过度设计**: 简单 CRUD 操作不需要完整的 Input Port → Interactor → Output Port → Presenter 链路。简单查询可以跳过 Interactor 直接使用 Repository。
-
-## When NOT to Use This Skill
-
-| ❌ Skip | ✅ Use Instead |
-|---------|---------------|
-| Simple CRUD, few business rules | `architecture-layered` (much simpler) |
-| Need visual clarity (rings model) | `architecture-onion` (easier to explain to team) |
-| Chinese enterprise Spring Boot stack | `architecture-cola` (better ecosystem fit) |
-| Team unfamiliar with UseCase pattern | `architecture-hexagonal` or `architecture-layered` |
-| Single service, no multi-module need | `architecture-layered` (single module suffices) |
-
-## Security & Stability
-
-- All code templates are educational. Replace placeholder credentials with environment variables or secrets management.
-- Clean Architecture's strict dependency rule (only inward) naturally prevents domain code from accessing I/O — this isolation is a security advantage.
-- Interactor pattern ensures each UseCase is independently testable. Unit test UseCases without any framework or database dependencies.
-- No executable scripts bundled. This skill provides architecture guidance and code generation patterns only.
+- [thombergs/buckpal](https://github.com/thombergs/buckpal) — Java Reference Implementation
+- [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) — Alistair Cockburn
+### DDD Skills 生态
+
+| 前置/后续 | Skill |
+|-----------|-------|
+| ← 前置 | [ddd-architecture-selector](../ddd-architecture-selector/) — 架构选型 |
+| → 后续 | [ddd-domain-designer](../ddd-domain-designer/) — 领域建模 |
+| → 后续 | [ddd-code-reviewer](../ddd-code-reviewer/) — 代码审查 |
+| → 后续 | [ddd-architecture-evaluator](../ddd-architecture-evaluator/) — 架构评估 |
+| 🔗 相关 | [ddd-architecture-hexagonal](../ddd-architecture-hexagonal/) — 六边形架构 |
+| 🔗 相关 | [ddd-architecture-layered](../ddd-architecture-layered/) — 分层架构 |
 
 ## 🧭 DDD Skills Journey
 
 > 📍 **You are here: `ddd-architecture-clean` — Step 3: 整洁架构落地**
 
-```mermaid
-flowchart LR
-    S1["Step 1<br/>awesome<br/>入门与全景"] --> S2["Step 2<br/>selector<br/>架构选型"]
-    S2 --> S3A["Step 3<br/>layered<br/>分层架构"]
-    S2 --> S3B["Step 3<br/>onion<br/>洋葱架构"]
-    S2 --> S3C["Step 3<br/>hexagonal<br/>六边形架构"]
-    S2 --> S3D["⭐ Step 3<br/>clean<br/>整洁架构"]
-    S2 --> S3E["Step 3<br/>cola<br/>COLA v5"]
-    S3A & S3B & S3C & S3D & S3E --> S4A["Step 4<br/>domain-designer<br/>领域建模"]
-    S3A & S3B & S3C & S3D & S3E --> S4B["Step 4<br/>cqrs-architecture<br/>CQRS"]
-    S3A & S3B & S3C & S3D & S3E --> S4C["Step 4<br/>api-designer<br/>API设计"]
-    S4A & S4B & S4C --> S5["Step 5<br/>code-reviewer<br/>代码审查"]
-    S5 --> S6A["Step 6<br/>event-storming<br/>事件风暴"]
-    S5 --> S6B["Step 6<br/>testing-strategist<br/>测试策略"]
-    S5 --> S6C["Step 6<br/>devops-integration<br/>DevOps"]
-    S5 --> S6D["Step 6<br/>evaluator<br/>架构评估"]
-    S6A & S6B & S6C & S6D --> S7["🏁 Step 7<br/>architecture-doc<br/>架构文档"]
-
-    style S3D fill:#3b82f6,stroke:#2563eb,color:white,stroke-width:3px
-```
+`awesome(入门)` → `selector(选型)` → **`clean(整洁架构)`** + `layered/onion/hexagonal/cola` → `domain-designer/cqrs/api-designer` → `code-reviewer` → `testing/devops/evaluator` → `architecture-doc`
 
-**← Previous**: [selector](../ddd-architecture-selector/) — 为什么选整洁架构?
-**→ Next**: [domain-designer](../ddd-domain-designer/) — 为整洁架构设计 Enterprise 实体和 UseCase
-**🔗 Related**: [api-designer](../ddd-api-designer/) — 设计 API 接口 | [testing-strategist](../ddd-testing-strategist/) — 分层测试策略
-**🏠 Home**: [awesome](../ddd-architecture-awesome/) — DDD 概念全景
+**← [selector](../ddd-architecture-selector/) | → [domain-designer](../ddd-domain-designer/) | 🔗 [api-designer](../ddd-api-designer/) · [testing-strategist](../ddd-testing-strategist/) | 🏠 [awesome](../ddd-architecture-awesome/)
 
-💡 整洁架构黄金法则:源码依赖只能指向内层。Enterprise → UseCase → Adapter → Framework,永远向内。
+---
+
+## Security & Stability
 
-> 📋 See [DESIGN.md](../DESIGN.md) for the complete 16-skill ecosystem map.
+- 所有代码模板为教育用途。生产环境请用环境变量替换占位凭证。
+- 整洁架构的依赖规则(只能向内)天然阻止领域代码访问 I/O — 内置安全优势。
+- Interactor 模式确保每个 UseCase 可独立测试,无需框架或数据库依赖。
+- 不包含可执行脚本。本 Skill 仅提供架构指导和代码生成模式。

+ 341 - 0
skills/ddd-skills/ddd-architecture-clean/examples/01-order-entity.md

@@ -0,0 +1,341 @@
+# Example: Order Entity (Enterprise Business Rules Layer)
+
+## File: `order-core/src/main/java/com/example/core/entity/Order.java`
+
+A complete rich domain model for an Order entity following Clean Architecture principles.
+
+```java
+package com.example.core.entity;
+
+import com.example.core.valueobject.*;
+import com.example.core.exception.OrderDomainException;
+import com.example.core.event.*;
+
+import java.time.Instant;
+import java.util.*;
+
+/**
+ * ★ Order — Core Enterprise Business Rule Entity.
+ * Zero framework dependencies. Pure business logic.
+ */
+public class Order {
+
+    private final OrderId id;
+    private final CustomerId customerId;
+    private final List<OrderItem> items;
+    private Money totalAmount;
+    private OrderStatus status;
+    private final List<DomainEvent> domainEvents;
+    private final Instant createdAt;
+    private Instant updatedAt;
+
+    // ── Constructor (factory method preferred) ──
+
+    private Order(OrderId id, CustomerId customerId) {
+        this.id = Objects.requireNonNull(id, "OrderId must not be null");
+        this.customerId = Objects.requireNonNull(customerId, "CustomerId must not be null");
+        this.items = new ArrayList<>();
+        this.totalAmount = Money.ZERO;
+        this.status = OrderStatus.DRAFT;
+        this.domainEvents = new ArrayList<>();
+        this.createdAt = Instant.now();
+        this.updatedAt = this.createdAt;
+    }
+
+    /**
+     * ★ Static factory — preferred over public constructor.
+     * Enforces creation rules and records the OrderCreated event.
+     */
+    public static Order create(OrderId id, CustomerId customerId) {
+        Order order = new Order(id, customerId);
+        order.addEvent(new OrderCreatedEvent(id, customerId));
+        return order;
+    }
+
+    // ── Business Behavior (Rich Domain Model) ──
+
+    /**
+     * Add an item to this order.
+     * Items can only be added while the order is in DRAFT status.
+     */
+    public void addItem(OrderItem item) {
+        assertDraftStatus("add items");
+        this.items.add(Objects.requireNonNull(item, "Item must not be null"));
+        recalculateTotal();
+        this.updatedAt = Instant.now();
+    }
+
+    /**
+     * Remove an item from this order.
+     * Only allowed in DRAFT status.
+     */
+    public void removeItem(ProductId productId) {
+        assertDraftStatus("remove items");
+        boolean removed = this.items.removeIf(item -> item.productId().equals(productId));
+        if (!removed) {
+            throw new OrderDomainException(
+                "Product " + productId.value() + " not found in order " + id.value());
+        }
+        recalculateTotal();
+        this.updatedAt = Instant.now();
+    }
+
+    /**
+     * Submit the order — transitions from DRAFT to SUBMITTED.
+     * Validates that the order has at least one item.
+     */
+    public void submit() {
+        assertDraftStatus("submit");
+        if (items.isEmpty()) {
+            throw new OrderDomainException("Cannot submit empty order " + id.value());
+        }
+        this.status = OrderStatus.SUBMITTED;
+        this.updatedAt = Instant.now();
+        addEvent(new OrderSubmittedEvent(id, customerId, totalAmount));
+    }
+
+    /**
+     * Pay for this order. Requires SUBMITTED status.
+     */
+    public void pay(PaymentId paymentId) {
+        assertStatus(OrderStatus.SUBMITTED, "pay");
+        this.status = OrderStatus.PAID;
+        this.updatedAt = Instant.now();
+        addEvent(new OrderPaidEvent(id, paymentId));
+    }
+
+    /**
+     * Cancel the order. Allowed from DRAFT or SUBMITTED.
+     */
+    public void cancel(String reason) {
+        if (status == OrderStatus.PAID || status == OrderStatus.CANCELLED) {
+            throw new OrderDomainException(
+                "Cannot cancel order " + id.value() + " in status " + status);
+        }
+        this.status = OrderStatus.CANCELLED;
+        this.updatedAt = Instant.now();
+        addEvent(new OrderCancelledEvent(id, reason));
+    }
+
+    /**
+     * Ship the order (triggered by warehouse system).
+     */
+    public void ship(TrackingId trackingId) {
+        assertStatus(OrderStatus.PAID, "ship");
+        this.status = OrderStatus.SHIPPED;
+        this.updatedAt = Instant.now();
+        addEvent(new OrderShippedEvent(id, trackingId));
+    }
+
+    /**
+     * Mark as delivered.
+     */
+    public void deliver() {
+        assertStatus(OrderStatus.SHIPPED, "deliver");
+        this.status = OrderStatus.DELIVERED;
+        this.updatedAt = Instant.now();
+        addEvent(new OrderDeliveredEvent(id));
+    }
+
+    // ── Internal Helpers ──
+
+    private void recalculateTotal() {
+        this.totalAmount = items.stream()
+            .map(OrderItem::subtotal)
+            .reduce(Money.ZERO, Money::add);
+    }
+
+    private void assertDraftStatus(String action) {
+        if (this.status != OrderStatus.DRAFT) {
+            throw new OrderDomainException(
+                "Cannot " + action + " on order " + id.value()
+                + " in status " + status + " (must be DRAFT)");
+        }
+    }
+
+    private void assertStatus(OrderStatus expected, String action) {
+        if (this.status != expected) {
+            throw new OrderDomainException(
+                "Cannot " + action + " order " + id.value()
+                + " in status " + status + " (must be " + expected + ")");
+        }
+    }
+
+    private void addEvent(DomainEvent event) {
+        this.domainEvents.add(Objects.requireNonNull(event));
+    }
+
+    // ── Getters (no setters — behavior is in methods) ──
+
+    public OrderId id()               { return id; }
+    public CustomerId customerId()    { return customerId; }
+    public List<OrderItem> items()    { return Collections.unmodifiableList(items); }
+    public Money totalAmount()        { return totalAmount; }
+    public OrderStatus status()       { return status; }
+    public Instant createdAt()        { return createdAt; }
+    public Instant updatedAt()        { return updatedAt; }
+
+    public List<DomainEvent> domainEvents() {
+        return Collections.unmodifiableList(domainEvents);
+    }
+
+    public void clearEvents() {
+        domainEvents.clear();
+    }
+
+    // ── equals/hashCode based on identity ──
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        Order order = (Order) o;
+        return id.equals(order.id);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(id);
+    }
+
+    @Override
+    public String toString() {
+        return "Order{id=" + id.value()
+            + ", status=" + status
+            + ", total=" + totalAmount
+            + ", items=" + items.size()
+            + "}";
+    }
+}
+```
+
+## Unit Test
+
+```java
+package com.example.core.entity;
+
+import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.*;
+
+class OrderTest {
+
+    @Test
+    void shouldCreateOrder() {
+        Order order = Order.create(OrderId.generate(), CustomerId.of("CUST-001"));
+        assertThat(order.status()).isEqualTo(OrderStatus.DRAFT);
+        assertThat(order.items()).isEmpty();
+        assertThat(order.totalAmount()).isEqualTo(Money.ZERO);
+        assertThat(order.domainEvents()).hasSize(1);
+    }
+
+    @Test
+    void shouldAddItem() {
+        Order order = givenDraftOrder();
+        order.addItem(new OrderItem(ProductId.of("PROD-001"), 2, Money.of(10, "USD")));
+
+        assertThat(order.items()).hasSize(1);
+        assertThat(order.totalAmount()).isEqualTo(Money.of(20, "USD"));
+    }
+
+    @Test
+    void shouldSubmit() {
+        Order order = givenDraftOrder();
+        order.addItem(new OrderItem(ProductId.of("PROD-001"), 1, Money.of(10, "USD")));
+        order.submit();
+
+        assertThat(order.status()).isEqualTo(OrderStatus.SUBMITTED);
+    }
+
+    @Test
+    void shouldNotSubmitEmptyOrder() {
+        Order order = givenDraftOrder();
+        assertThatThrownBy(order::submit)
+            .isInstanceOf(OrderDomainException.class)
+            .hasMessageContaining("Cannot submit empty order");
+    }
+
+    @Test
+    void shouldPay() {
+        Order order = givenSubmittedOrder();
+        order.pay(PaymentId.generate());
+
+        assertThat(order.status()).isEqualTo(OrderStatus.PAID);
+    }
+
+    @Test
+    void shouldNotPayWhenNotSubmitted() {
+        Order order = givenDraftOrder();
+        assertThatThrownBy(() -> order.pay(PaymentId.generate()))
+            .isInstanceOf(OrderDomainException.class);
+    }
+
+    @Test
+    void shouldCancelDraftOrder() {
+        Order order = givenDraftOrder();
+        order.cancel("Changed mind");
+        assertThat(order.status()).isEqualTo(OrderStatus.CANCELLED);
+    }
+
+    @Test
+    void shouldNotCancelPaidOrder() {
+        Order order = givenSubmittedOrder();
+        order.pay(PaymentId.generate());
+
+        assertThatThrownBy(() -> order.cancel("No reason"))
+            .isInstanceOf(OrderDomainException.class);
+    }
+
+    @Test
+    void shouldEmitEventsThroughLifecycle() {
+        Order order = givenDraftOrder();
+        order.addItem(new OrderItem(ProductId.of("PROD-001"), 1, Money.of(10, "USD")));
+        order.submit();
+        order.pay(PaymentId.generate());
+
+        assertThat(order.domainEvents())
+            .extracting("class")
+            .containsExactly(
+                OrderCreatedEvent.class,
+                OrderSubmittedEvent.class,
+                OrderPaidEvent.class
+            );
+    }
+
+    private Order givenDraftOrder() {
+        return Order.create(OrderId.generate(), CustomerId.of("CUST-001"));
+    }
+
+    private Order givenSubmittedOrder() {
+        Order order = givenDraftOrder();
+        order.addItem(new OrderItem(ProductId.of("PROD-001"), 1, Money.of(10, "USD")));
+        order.submit();
+        order.clearEvents(); // start fresh
+        return order;
+    }
+}
+```
+
+## State Machine
+
+```
+                    ┌──────────┐
+                    │  DRAFT   │
+                    └────┬─────┘
+                         │ submit()
+                    ┌────▼─────┐
+                    │SUBMITTED │
+                    └────┬─────┘
+                         │ pay()
+                    ┌────▼─────┐
+                    │  PAID    │
+                    └────┬─────┘
+                         │ ship()
+                    ┌────▼─────┐
+                    │ SHIPPED  │
+                    └────┬─────┘
+                         │ deliver()
+                    ┌────▼──────┐
+                    │ DELIVERED │
+                    └───────────┘
+    cancel() allowed: DRAFT, SUBMITTED
+```

+ 449 - 0
skills/ddd-skills/ddd-architecture-clean/examples/02-create-order-usecase.md

@@ -0,0 +1,449 @@
+# Example: CreateOrder UseCase Implementation
+
+## Files in this UseCase
+
+```
+order-usecase/
+├── port/
+│   ├── input/
+│   │   └── CreateOrderUseCase.java       ← Input Port (interface)
+│   └── output/
+│       ├── OrderRepository.java          ← Output Port (interface)
+│       ├── EventPublisher.java           ← Output Port (interface)
+│       └── InventoryGateway.java         ← Output Port (interface)
+├── interactor/
+│   └── CreateOrderInteractor.java        ← UseCase Implementation
+└── dto/
+    ├── CreateOrderInput.java             ← Input DTO
+    └── CreateOrderOutput.java            ← Output DTO
+```
+
+## Input Port
+
+```java
+package com.example.usecase.port.input;
+
+import com.example.usecase.dto.input.CreateOrderInput;
+import com.example.usecase.dto.output.CreateOrderOutput;
+
+/**
+ * ★ Input Port — UseCase interface.
+ * One UseCase = One Port (Interface Segregation Principle).
+ */
+public interface CreateOrderUseCase {
+    CreateOrderOutput execute(CreateOrderInput input);
+}
+```
+
+## Input DTO
+
+```java
+package com.example.usecase.dto.input;
+
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.*;
+import java.math.BigDecimal;
+import java.util.Currency;
+import java.util.List;
+
+/**
+ * UseCase-specific input data.
+ * No HTTP/DTO framework types — pure data carrier.
+ */
+public record CreateOrderInput(
+    @NotBlank String customerId,
+    @NotEmpty List<@Valid OrderItemInput> items
+) {
+    /**
+     * Nested record for each order item.
+     */
+    public record OrderItemInput(
+        @NotBlank String productId,
+        @Min(1) int quantity,
+        @NotNull BigDecimal unitPrice,
+        @NotBlank String currency
+    ) {}
+}
+```
+
+## Output DTO
+
+```java
+package com.example.usecase.dto.output;
+
+import com.example.core.entity.Order;
+import com.example.core.event.OrderCreatedEvent;
+import com.example.core.valueobject.Money;
+import com.example.core.valueobject.OrderId;
+import com.example.core.valueobject.OrderStatus;
+
+/**
+ * UseCase-specific output data.
+ * Created from the entity after the UseCase executes.
+ */
+public record CreateOrderOutput(
+    OrderId orderId,
+    Money totalAmount,
+    OrderStatus status,
+    int itemCount
+) {
+    public static CreateOrderOutput from(Order order) {
+        return new CreateOrderOutput(
+            order.id(),
+            order.totalAmount(),
+            order.status(),
+            order.items().size()
+        );
+    }
+}
+```
+
+## Output Ports
+
+```java
+package com.example.usecase.port.output;
+
+import com.example.core.entity.Order;
+import com.example.core.valueobject.OrderId;
+import java.util.Optional;
+
+/**
+ * ★ Output Port — what the UseCase needs from outside.
+ * Implemented by the Adapter layer.
+ */
+public interface OrderRepository {
+    Order save(Order order);
+    Optional<Order> findById(OrderId id);
+    void delete(OrderId id);
+}
+
+public interface EventPublisher {
+    void publish(DomainEvent event);
+    void publishAll(List<DomainEvent> events);
+}
+
+public interface InventoryGateway {
+    boolean reserveStock(ProductId productId, int quantity);
+    void releaseStock(ProductId productId, int quantity);
+}
+```
+
+## Interactor (UseCase Implementation)
+
+```java
+package com.example.usecase.interactor;
+
+import com.example.core.entity.Order;
+import com.example.core.entity.OrderItem;
+import com.example.core.valueobject.*;
+import com.example.core.exception.OrderDomainException;
+import com.example.usecase.dto.input.CreateOrderInput;
+import com.example.usecase.dto.output.CreateOrderOutput;
+import com.example.usecase.port.input.CreateOrderUseCase;
+import com.example.usecase.port.output.OrderRepository;
+import com.example.usecase.port.output.EventPublisher;
+import com.example.usecase.port.output.InventoryGateway;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Currency;
+import java.util.List;
+
+/**
+ * ★ Interactor — implements CreateOrder UseCase.
+ * Orchestrates the flow: validate → create → persist → publish events.
+ * Does NOT contain business logic (that's in the Entity).
+ */
+public class CreateOrderInteractor implements CreateOrderUseCase {
+
+    private static final Logger log = LoggerFactory.getLogger(CreateOrderInteractor.class);
+
+    private final OrderRepository orderRepository;
+    private final EventPublisher eventPublisher;
+    private final InventoryGateway inventoryGateway;
+
+    public CreateOrderInteractor(
+            OrderRepository orderRepository,
+            EventPublisher eventPublisher,
+            InventoryGateway inventoryGateway) {
+        this.orderRepository = orderRepository;
+        this.eventPublisher = eventPublisher;
+        this.inventoryGateway = inventoryGateway;
+    }
+
+    @Override
+    public CreateOrderOutput execute(CreateOrderInput input) {
+        // 1. Validate input (basic validation via records, detailed validation here)
+        validateInput(input);
+
+        // 2. Create the Order entity (Enterprise Business Rules)
+        OrderId orderId = OrderId.generate();
+        CustomerId customerId = CustomerId.of(input.customerId());
+        Order order = Order.create(orderId, customerId);
+
+        // 3. Add items (delegates to Entity behavior)
+        for (CreateOrderInput.OrderItemInput itemInput : input.items()) {
+            OrderItem item = OrderItem.create(
+                ProductId.of(itemInput.productId()),
+                itemInput.quantity(),
+                Money.of(itemInput.unitPrice(), Currency.getInstance(itemInput.currency()))
+            );
+            order.addItem(item);
+        }
+
+        // 4. Reserve inventory (through Output Port)
+        for (CreateOrderInput.OrderItemInput itemInput : input.items()) {
+            boolean reserved = inventoryGateway.reserveStock(
+                ProductId.of(itemInput.productId()),
+                itemInput.quantity()
+            );
+            if (!reserved) {
+                // Rollback previous reservations
+                rollbackReservations(input);
+                throw new OrderDomainException(
+                    "Insufficient stock for product: " + itemInput.productId());
+            }
+        }
+
+        // 5. Submit the order (entity handles state transition)
+        order.submit();
+
+        // 6. Persist (through Output Port)
+        Order savedOrder = orderRepository.save(order);
+
+        // 7. Publish domain events (through Output Port)
+        eventPublisher.publishAll(order.domainEvents());
+        order.clearEvents();
+
+        // 8. Return result
+        log.info("Order created: {} for customer {}",
+            savedOrder.id().value(), input.customerId());
+
+        return CreateOrderOutput.from(savedOrder);
+    }
+
+    private void validateInput(CreateOrderInput input) {
+        if (input.customerId() == null || input.customerId().isBlank()) {
+            throw new IllegalArgumentException("Customer ID is required");
+        }
+        if (input.items() == null || input.items().isEmpty()) {
+            throw new IllegalArgumentException("At least one item is required");
+        }
+        for (CreateOrderInput.OrderItemInput item : input.items()) {
+            if (item.unitPrice().compareTo(java.math.BigDecimal.ZERO) <= 0) {
+                throw new IllegalArgumentException(
+                    "Unit price must be positive for product: " + item.productId());
+            }
+        }
+    }
+
+    private void rollbackReservations(CreateOrderInput input) {
+        for (CreateOrderInput.OrderItemInput itemInput : input.items()) {
+            try {
+                inventoryGateway.releaseStock(
+                    ProductId.of(itemInput.productId()),
+                    itemInput.quantity()
+                );
+            } catch (Exception e) {
+                log.warn("Failed to rollback inventory for product: {}", itemInput.productId(), e);
+            }
+        }
+    }
+}
+```
+
+## Unit Test
+
+```java
+package com.example.usecase.interactor;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import static org.assertj.core.api.Assertions.*;
+
+class CreateOrderInteractorTest {
+
+    private InMemoryOrderRepository orderRepo;
+    private SpyEventPublisher eventPublisher;
+    private SpyInventoryGateway inventoryGateway;
+    private CreateOrderInteractor interactor;
+
+    @BeforeEach
+    void setUp() {
+        orderRepo = new InMemoryOrderRepository();
+        eventPublisher = new SpyEventPublisher();
+        inventoryGateway = new SpyInventoryGateway();
+        interactor = new CreateOrderInteractor(
+            orderRepo, eventPublisher, inventoryGateway);
+    }
+
+    @Test
+    void shouldCreateOrder() {
+        var input = new CreateOrderInput(
+            "CUST-001",
+            List.of(new OrderItemInput("PROD-001", 2, new BigDecimal("10.00"), "USD"))
+        );
+
+        var output = interactor.execute(input);
+
+        assertThat(output.orderId()).isNotNull();
+        assertThat(output.status()).isEqualTo(OrderStatus.SUBMITTED);
+        assertThat(output.itemCount()).isEqualTo(1);
+        assertThat(output.totalAmount()).isEqualTo(Money.of(20, "USD"));
+    }
+
+    @Test
+    void shouldReserveInventory() {
+        var input = validInput();
+        interactor.execute(input);
+
+        assertThat(inventoryGateway.reservations())
+            .containsEntry("PROD-001", 2);
+    }
+
+    @Test
+    void shouldPublishEvents() {
+        var input = validInput();
+        interactor.execute(input);
+
+        assertThat(eventPublisher.publishedEvents())
+            .hasSize(2) // OrderCreated + OrderSubmitted
+            .anyMatch(e -> e instanceof OrderCreatedEvent)
+            .anyMatch(e -> e instanceof OrderSubmittedEvent);
+    }
+
+    @Test
+    void shouldPersistOrder() {
+        var input = validInput();
+        var output = interactor.execute(input);
+
+        var saved = orderRepo.findById(output.orderId());
+        assertThat(saved).isPresent();
+        assertThat(saved.get().status()).isEqualTo(OrderStatus.SUBMITTED);
+    }
+
+    @Test
+    void shouldFailForEmptyItems() {
+        var input = new CreateOrderInput("CUST-001", List.of());
+        assertThatThrownBy(() -> interactor.execute(input))
+            .isInstanceOf(IllegalArgumentException.class);
+    }
+
+    @Test
+    void shouldFailWhenStockInsufficient() {
+        inventoryGateway.shouldFailFor("PROD-001");
+
+        var input = validInput();
+        assertThatThrownBy(() -> interactor.execute(input))
+            .isInstanceOf(OrderDomainException.class)
+            .hasMessageContaining("Insufficient stock");
+    }
+
+    @Test
+    void shouldRollbackReservationsOnFailure() {
+        inventoryGateway.shouldFailFor("PROD-002");
+
+        var input = new CreateOrderInput("CUST-001", List.of(
+            new OrderItemInput("PROD-001", 1, BigDecimal.TEN, "USD"),
+            new OrderItemInput("PROD-002", 1, BigDecimal.TEN, "USD") // this fails
+        ));
+
+        assertThatThrownBy(() -> interactor.execute(input))
+            .isInstanceOf(OrderDomainException.class);
+
+        // PROD-001 reservation should be rolled back
+        assertThat(inventoryGateway.releasedStock())
+            .containsEntry("PROD-001", 1);
+    }
+
+    private CreateOrderInput validInput() {
+        return new CreateOrderInput(
+            "CUST-001",
+            List.of(new OrderItemInput("PROD-001", 2, new BigDecimal("10.00"), "USD"))
+        );
+    }
+}
+```
+
+## In-Memory Test Doubles
+
+```java
+// InMemoryOrderRepository.java
+public class InMemoryOrderRepository implements OrderRepository {
+    private final Map<OrderId, Order> store = new HashMap<>();
+
+    @Override
+    public Order save(Order order) {
+        store.put(order.id(), order);
+        return order;
+    }
+
+    @Override
+    public Optional<Order> findById(OrderId id) {
+        return Optional.ofNullable(store.get(id));
+    }
+
+    @Override
+    public void delete(OrderId id) {
+        store.remove(id);
+    }
+
+    public void clear() { store.clear(); }
+}
+
+// SpyEventPublisher.java
+public class SpyEventPublisher implements EventPublisher {
+    private final List<DomainEvent> events = new ArrayList<>();
+
+    @Override
+    public void publish(DomainEvent event) {
+        events.add(event);
+    }
+
+    @Override
+    public void publishAll(List<DomainEvent> events) {
+        this.events.addAll(events);
+    }
+
+    public List<DomainEvent> publishedEvents() { return List.copyOf(events); }
+    public void clear() { events.clear(); }
+}
+
+// SpyInventoryGateway.java
+public class SpyInventoryGateway implements InventoryGateway {
+    private final Map<String, Integer> reservations = new HashMap<>();
+    private final Map<String, Integer> released = new HashMap<>();
+    private final Set<String> failFor = new HashSet<>();
+
+    @Override
+    public boolean reserveStock(ProductId productId, int quantity) {
+        if (failFor.contains(productId.value())) {
+            return false;
+        }
+        reservations.merge(productId.value(), quantity, Integer::sum);
+        return true;
+    }
+
+    @Override
+    public void releaseStock(ProductId productId, int quantity) {
+        released.merge(productId.value(), quantity, Integer::sum);
+    }
+
+    public void shouldFailFor(String productId) {
+        failFor.add(productId);
+    }
+
+    public Map<String, Integer> reservations() { return Map.copyOf(reservations); }
+    public Map<String, Integer> releasedStock() { return Map.copyOf(released); }
+}
+```
+
+## Key Points
+
+| Concept | How It's Applied Here |
+|---------|----------------------|
+| **Dependency Rule** | Interactor depends on Enterprise (Order) and Output Ports (interfaces), not on implementations |
+| **Single Responsibility** | Interactor only orchestrates; entity contains business rules |
+| **Interface Segregation** | Each UseCase gets its own Input Port interface |
+| **Dependency Inversion** | Output Ports defined in UseCase layer, implemented in Adapter layer |
+| **Event Sourcing** | Domain events collected in entity, published after persistence |

+ 425 - 0
skills/ddd-skills/ddd-architecture-clean/examples/03-repository-implementation.md

@@ -0,0 +1,425 @@
+# Example: Repository Implementation (Adapter Layer)
+
+## Overview
+
+This example shows the complete chain from Output Port interface → JPA Entity → Repository Implementation → Unit Test.
+
+## Package Structure
+
+```
+order-adapter/
+├── repository/
+│   ├── JpaOrderRepository.java          ← Implements OrderRepository Output Port
+│   └── entity/
+│       └── OrderEntity.java             ← JPA persistence entity
+├── converter/
+│   └── OrderPersistenceConverter.java   ← Domain ↔ Persistence mapping
+└── gateway/
+    └── EventPublisherAdapter.java       ← Implements EventPublisher Output Port
+```
+
+## Step 1: Output Port (UseCase Layer — what adapter implements)
+
+```java
+// File: order-usecase/src/main/java/.../port/output/OrderRepository.java
+package com.example.usecase.port.output;
+
+import com.example.core.entity.Order;
+import com.example.core.valueobject.OrderId;
+import java.util.Optional;
+
+/**
+ * ★ Output Port — defined in UseCase layer.
+ * The Adapter implements this interface.
+ */
+public interface OrderRepository {
+    Order save(Order order);
+    Optional<Order> findById(OrderId id);
+    void delete(OrderId id);
+    boolean existsByCustomerId(CustomerId customerId);
+}
+```
+
+## Step 2: JPA Entity (Adapter Layer)
+
+```java
+// File: order-adapter/src/main/java/.../repository/entity/OrderEntity.java
+package com.example.adapter.repository.entity;
+
+import jakarta.persistence.*;
+import java.math.BigDecimal;
+import java.time.Instant;
+
+/**
+ * ★ JPA Entity — lives in the Adapter layer.
+ * This is SEPARATE from the domain Order entity.
+ * Framework annotations are confined here.
+ */
+@Entity
+@Table(name = "orders")
+public class OrderEntity {
+
+    @Id
+    @Column(length = 36)
+    private String id;
+
+    @Column(name = "customer_id", length = 36, nullable = false)
+    private String customerId;
+
+    @Column(name = "total_amount", precision = 19, scale = 2, nullable = false)
+    private BigDecimal totalAmount;
+
+    @Column(name = "currency", length = 3, nullable = false)
+    private String currency;
+
+    @Enumerated(EnumType.STRING)
+    @Column(name = "status", length = 20, nullable = false)
+    private OrderStatus status;
+
+    @Column(name = "created_at", nullable = false)
+    private Instant createdAt;
+
+    @Column(name = "updated_at", nullable = false)
+    private Instant updatedAt;
+
+    @Version
+    private Long version;
+
+    // JPA requires default constructor
+    protected OrderEntity() {}
+
+    public OrderEntity(String id, String customerId,
+                       BigDecimal totalAmount, String currency,
+                       OrderStatus status,
+                       Instant createdAt, Instant updatedAt) {
+        this.id = id;
+        this.customerId = customerId;
+        this.totalAmount = totalAmount;
+        this.currency = currency;
+        this.status = status;
+        this.createdAt = createdAt;
+        this.updatedAt = updatedAt;
+    }
+
+    // ── Getters (used by converter) ──
+    public String getId() { return id; }
+    public String getCustomerId() { return customerId; }
+    public BigDecimal getTotalAmount() { return totalAmount; }
+    public String getCurrency() { return currency; }
+    public OrderStatus getStatus() { return status; }
+    public Instant getCreatedAt() { return createdAt; }
+    public Instant getUpdatedAt() { return updatedAt; }
+    public Long getVersion() { return version; }
+
+    public void setStatus(OrderStatus status) { this.status = status; }
+    public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
+}
+
+/**
+ * JPA Entity for order items (part of Order aggregate).
+ */
+@Entity
+@Table(name = "order_items")
+public class OrderItemEntity {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+
+    @Column(name = "order_id", length = 36, nullable = false)
+    private String orderId;
+
+    @Column(name = "product_id", length = 36, nullable = false)
+    private String productId;
+
+    @Column(nullable = false)
+    private int quantity;
+
+    @Column(name = "unit_price", precision = 19, scale = 2, nullable = false)
+    private BigDecimal unitPrice;
+
+    @Column(name = "unit_currency", length = 3, nullable = false)
+    private String unitCurrency;
+
+    protected OrderItemEntity() {}
+
+    // Constructor, getters...
+}
+```
+
+## Step 3: Spring Data JPA Repository
+
+```java
+// File: order-adapter/src/main/java/.../repository/SpringDataOrderJpaRepository.java
+package com.example.adapter.repository;
+
+import com.example.adapter.repository.entity.OrderEntity;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+/**
+ * ★ Spring Data JPA Repository — framework-specific.
+ * Not to be confused with the domain Output Port.
+ */
+@Repository
+public interface SpringDataOrderJpaRepository extends JpaRepository<OrderEntity, String> {
+    boolean existsByCustomerId(String customerId);
+}
+```
+
+## Step 4: Persistence Converter
+
+```java
+// File: order-adapter/src/main/java/.../converter/OrderPersistenceConverter.java
+package com.example.adapter.converter;
+
+import com.example.core.entity.Order;
+import com.example.core.entity.OrderItem;
+import com.example.core.valueobject.*;
+import com.example.adapter.repository.entity.OrderEntity;
+import org.springframework.stereotype.Component;
+
+import java.util.Currency;
+import java.util.stream.Collectors;
+
+/**
+ * ★ Converter — maps between Domain Entity and JPA Entity.
+ * This is the ONLY place that knows about both representations.
+ */
+@Component
+public class OrderPersistenceConverter {
+
+    public OrderEntity toPersistence(Order order) {
+        return new OrderEntity(
+            order.id().value(),
+            order.customerId().value(),
+            order.totalAmount().amount(),
+            order.totalAmount().currency().getCurrencyCode(),
+            order.status(),
+            order.createdAt(),
+            order.updatedAt()
+        );
+    }
+
+    public Order toDomain(OrderEntity entity) {
+        // Reconstruct domain entity from persistence state
+        OrderId id = OrderId.from(entity.getId());
+        CustomerId customerId = CustomerId.of(entity.getCustomerId());
+        Order order = Order.reconstruct(
+            id,
+            customerId,
+            Money.of(entity.getTotalAmount(), Currency.getInstance(entity.getCurrency())),
+            entity.getStatus(),
+            entity.getCreatedAt(),
+            entity.getUpdatedAt()
+        );
+
+        // Note: OrderItems would be loaded via a separate query or join
+        return order;
+    }
+}
+```
+
+## Step 5: Repository Implementation (Impl)
+
+```java
+// File: order-adapter/src/main/java/.../repository/JpaOrderRepository.java
+package com.example.adapter.repository;
+
+import com.example.core.entity.Order;
+import com.example.core.valueobject.CustomerId;
+import com.example.core.valueobject.OrderId;
+import com.example.usecase.port.output.OrderRepository;
+import com.example.adapter.converter.OrderPersistenceConverter;
+import com.example.adapter.repository.entity.OrderEntity;
+import jakarta.persistence.EntityNotFoundException;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.Optional;
+
+/**
+ * ★ Repository Implementation — Adapter Layer.
+ * Implements the Output Port defined in the UseCase layer.
+ * All JPA/framework concerns are confined to this class.
+ */
+@Repository
+@Transactional
+public class JpaOrderRepository implements OrderRepository {
+
+    private final SpringDataOrderJpaRepository jpaRepo;
+    private final OrderPersistenceConverter converter;
+
+    public JpaOrderRepository(
+            SpringDataOrderJpaRepository jpaRepo,
+            OrderPersistenceConverter converter) {
+        this.jpaRepo = jpaRepo;
+        this.converter = converter;
+    }
+
+    @Override
+    @Transactional
+    public Order save(Order order) {
+        OrderEntity entity = converter.toPersistence(order);
+        OrderEntity saved = jpaRepo.save(entity);
+        return converter.toDomain(saved);
+    }
+
+    @Override
+    @Transactional(readOnly = true)
+    public Optional<Order> findById(OrderId id) {
+        return jpaRepo.findById(id.value())
+            .map(converter::toDomain);
+    }
+
+    @Override
+    @Transactional
+    public void delete(OrderId id) {
+        jpaRepo.deleteById(id.value());
+    }
+
+    @Override
+    @Transactional(readOnly = true)
+    public boolean existsByCustomerId(CustomerId customerId) {
+        return jpaRepo.existsByCustomerId(customerId.value());
+    }
+}
+```
+
+## Step 6: Repository Integration Test
+
+```java
+// File: order-adapter/src/test/java/.../repository/JpaOrderRepositoryTest.java
+package com.example.adapter.repository;
+
+import com.example.core.entity.Order;
+import com.example.core.valueobject.*;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
+import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
+import org.springframework.context.annotation.Import;
+import org.springframework.test.context.ActiveProfiles;
+
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.*;
+
+/**
+ * ★ Integration test for the repository implementation.
+ * Uses a real (in-memory) database via @DataJpaTest.
+ */
+@DataJpaTest
+@Import({JpaOrderRepository.class, OrderPersistenceConverter.class})
+@ActiveProfiles("test")
+class JpaOrderRepositoryTest {
+
+    @Autowired
+    private JpaOrderRepository repository;
+
+    @Autowired
+    private TestEntityManager em;
+
+    @Test
+    void shouldSaveAndFindOrder() {
+        Order order = givenOrder();
+
+        repository.save(order);
+
+        Optional<Order> found = repository.findById(order.id());
+        assertThat(found).isPresent();
+        assertThat(found.get().id()).isEqualTo(order.id());
+        assertThat(found.get().status()).isEqualTo(OrderStatus.DRAFT);
+        assertThat(found.get().totalAmount()).isEqualTo(Money.of(100, "USD"));
+    }
+
+    @Test
+    void shouldDeleteOrder() {
+        Order order = givenOrder();
+        repository.save(order);
+
+        repository.delete(order.id());
+
+        assertThat(repository.findById(order.id())).isEmpty();
+    }
+
+    @Test
+    void shouldReturnEmptyForMissingOrder() {
+        Optional<Order> found = repository.findById(OrderId.generate());
+        assertThat(found).isEmpty();
+    }
+
+    private Order givenOrder() {
+        return Order.create(
+            OrderId.generate(),
+            CustomerId.of("CUST-001")
+        );
+    }
+}
+```
+
+## Event Publisher Adapter
+
+```java
+// File: order-adapter/src/main/java/.../gateway/EventPublisherAdapter.java
+package com.example.adapter.gateway;
+
+import com.example.core.event.DomainEvent;
+import com.example.usecase.port.output.EventPublisher;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.amqp.rabbit.core.RabbitTemplate;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+/**
+ * ★ Driven Adapter — implements EventPublisher Output Port.
+ * Uses RabbitMQ for production, configurable per profile.
+ */
+@Component
+public class EventPublisherAdapter implements EventPublisher {
+
+    private static final Logger log = LoggerFactory.getLogger(EventPublisherAdapter.class);
+    private static final String EXCHANGE = "domain.events";
+
+    private final RabbitTemplate rabbitTemplate;
+    private final ObjectMapper objectMapper;
+
+    public EventPublisherAdapter(RabbitTemplate rabbitTemplate, ObjectMapper objectMapper) {
+        this.rabbitTemplate = rabbitTemplate;
+        this.objectMapper = objectMapper;
+    }
+
+    @Override
+    public void publish(DomainEvent event) {
+        try {
+            String json = objectMapper.writeValueAsString(event);
+            String routingKey = event.getClass().getSimpleName();
+            rabbitTemplate.convertAndSend(EXCHANGE, routingKey, json);
+            log.info("Published event: {} (key={})", event.eventId(), routingKey);
+        } catch (JsonProcessingException e) {
+            log.error("Failed to serialize event: {}", event.eventId(), e);
+            throw new EventPublishException("Failed to publish event", e);
+        }
+    }
+
+    @Override
+    public void publishAll(List<DomainEvent> events) {
+        events.forEach(this::publish);
+    }
+}
+```
+
+## Key Design Decisions
+
+| Decision | Rationale |
+|----------|-----------|
+| **Separate JPA Entity from Domain Entity** | Domain Order is pure POJO; JPA OrderEntity has @Entity annotation. Prevents framework leak. |
+| **Converter in Adapter layer** | Only the adapter knows about both representations. UseCase layer only sees Domain types. |
+| **Output Port as interface** | UseCase defines what it needs; Adapter implements it. Full Dependency Inversion. |
+| **@Transactional at repository level** | Transaction management is an infrastructure concern, not domain. |
+| **Spring Data JPA confined to Adapter** | No @Repository or JPA annotations leak into UseCase or Enterprise layers. |

+ 460 - 0
skills/ddd-skills/ddd-architecture-clean/examples/04-archunit-test.md

@@ -0,0 +1,460 @@
+# Example: ArchUnit Dependency Verification Test
+
+## File: `order-framework/src/test/java/.../archunit/CleanArchitectureTest.java`
+
+Complete ArchUnit test suite for verifying Clean Architecture dependency rules automatically.
+
+## Complete Test Suite
+
+```java
+package com.example.framework.archunit;
+
+import com.tngtech.archunit.core.domain.JavaClasses;
+import com.tngtech.archunit.core.importer.ClassFileImporter;
+import com.tngtech.archunit.core.importer.ImportOption;
+import com.tngtech.archunit.lang.ArchRule;
+import com.tngtech.archunit.lang.syntax.ArchRuleDefinition;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
+import static com.tngtech.archunit.library.Architectures.*;
+import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.*;
+
+/**
+ * Automated Clean Architecture dependency verification.
+ * Run as part of CI/CD pipeline. Fails build on violations.
+ */
+class CleanArchitectureTest {
+
+    private static JavaClasses classes;
+
+    @BeforeAll
+    static void setUp() {
+        classes = new ClassFileImporter()
+            .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
+            .importPackages("com.example..");
+    }
+
+    // ─────────────────────────────────────────────
+    // Layer Dependency Rules
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("Layer Dependency Rules")
+    class LayerDependencyTests {
+
+        @Test
+        @DisplayName("Enterprise layer must not depend on outer layers")
+        void enterpriseShouldNotDependOnOuterLayers() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.core..")
+                .should().dependOnClassesThat()
+                .resideInAnyPackage(
+                    "com.example.usecase..",
+                    "com.example.adapter..",
+                    "com.example.framework.."
+                )
+                .because("Enterprise Business Rules (core) must be completely "
+                    + "independent of outer layers (Clean Architecture rule)")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("UseCase layer must not depend on Adapter or Framework")
+        void useCaseShouldNotDependOnAdapterOrFramework() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.usecase..")
+                .should().dependOnClassesThat()
+                .resideInAnyPackage(
+                    "com.example.adapter..",
+                    "com.example.framework.."
+                )
+                .because("UseCase layer must only depend on Enterprise layer "
+                    + "and its own packages")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("Adapter layer must not depend on Framework")
+        void adapterShouldNotDependOnFramework() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.adapter..")
+                .should().dependOnClassesThat()
+                .resideInAnyPackage("com.example.framework..")
+                .because("Adapter layer must not know about framework configuration");
+        }
+
+        @Test
+        @DisplayName("No layer should have circular dependencies")
+        void noCircularDependencies() {
+            slices().matching("com.example.(*)..")
+                .should().beFreeOfCycles()
+                .because("Cycles between layers violate the Dependency Rule");
+        }
+    }
+
+    // ─────────────────────────────────────────────
+    // Layer Architecture Definition
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("Clean Architecture Layers")
+    class CleanArchitectureDefinitionTests {
+
+        @Test
+        @DisplayName("All layers follow Clean Architecture dependency direction")
+        void shouldFollowCleanArchitecture() {
+            layeredArchitecture()
+                .consideringAllDependencies()
+
+                // Define layers
+                .layer("Enterprise")
+                    .definedBy("com.example.core..")
+                .layer("UseCase")
+                    .definedBy("com.example.usecase..")
+                .layer("Adapter")
+                    .definedBy("com.example.adapter..")
+                .layer("Framework")
+                    .definedBy("com.example.framework..")
+
+                // Dependency constraints: outer can depend on inner, NOT reverse
+                .whereLayer("Enterprise")
+                    .mayOnlyBeAccessedByLayers("UseCase", "Adapter", "Framework")
+                .whereLayer("UseCase")
+                    .mayOnlyBeAccessedByLayers("Adapter", "Framework")
+                .whereLayer("Adapter")
+                    .mayOnlyBeAccessedByLayers("Framework")
+
+                .because("Clean Architecture: source code dependencies "
+                    + "must point only inward")
+                .check(classes);
+        }
+    }
+
+    // ─────────────────────────────────────────────
+    // Enterprise Layer Purity
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("Enterprise Layer Purity")
+    class EnterprisePurityTests {
+
+        @Test
+        @DisplayName("Enterprise entities must not use Spring annotations")
+        void entitiesShouldNotUseSpringAnnotations() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.core.entity..")
+                .should().beAnnotatedWith("org.springframework.stereotype.Service")
+                .orShould().beAnnotatedWith("org.springframework.stereotype.Component")
+                .orShould().beAnnotatedWith("org.springframework.web.bind.annotation.RestController")
+                .orShould().beAnnotatedWith("org.springframework.stereotype.Repository")
+                .because("Enterprise entities must be pure POJOs — "
+                    + "no framework annotations allowed")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("Enterprise layer must not use JPA annotations")
+        void entitiesShouldNotUseJpaAnnotations() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.core..")
+                .should().beAnnotatedWith("jakarta.persistence.Entity")
+                .orShould().beAnnotatedWith("jakarta.persistence.Table")
+                .orShould().beAnnotatedWith("jakarta.persistence.Column")
+                .orShould().beAnnotatedWith("jakarta.persistence.Id")
+                .because("Enterprise layer must be JPA-free — "
+                    + "persistence is an infrastructure concern")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("Enterprise layer must not import framework packages")
+        void entitiesShouldNotImportFrameworkPackages() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.core..")
+                .should().dependOnClassesThat()
+                .resideInAnyPackage(
+                    "org.springframework..",
+                    "jakarta.persistence..",
+                    "jakarta.servlet..",
+                    "com.fasterxml.jackson..",
+                    "org.apache..",
+                    "org.hibernate.."
+                )
+                .because("Enterprise Business Rules must have zero framework dependencies")
+                .check(classes);
+        }
+    }
+
+    // ─────────────────────────────────────────────
+    // UseCase Layer Rules
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("UseCase Layer Rules")
+    class UseCaseLayerTests {
+
+        @Test
+        @DisplayName("UseCase ports must be interfaces")
+        void portsShouldBeInterfaces() {
+            classes()
+                .that().resideInAnyPackage("com.example.usecase.port..")
+                .should().beInterfaces()
+                .because("Ports are contracts — must be interfaces")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("UseCase interactors must implement a port interface")
+        void interactorsShouldImplementPort() {
+            classes()
+                .that().resideInAnyPackage("com.example.usecase.interactor..")
+                .should().implement(
+                    (java.lang.reflect.Type) null // simplified: check naming convention instead
+                )
+                .because("Every Interactor must implement an Input Port")
+                .check(classes);
+
+            // Alternative: check naming convention
+            classes()
+                .that().resideInAnyPackage("com.example.usecase.interactor..")
+                .should().haveSimpleNameEndingWith("Interactor")
+                .because("UseCase implementations should be named *Interactor")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("UseCase must not import Spring's @Service annotation")
+        void useCaseShouldNotUseServiceAnnotation() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.usecase..")
+                .should().beAnnotatedWith("org.springframework.stereotype.Service")
+                .because("UseCase layer uses @Service from Spring — "
+                    + "use framework config for wiring instead")
+                .allowEmptyShould(true)
+                .check(classes);
+        }
+    }
+
+    // ─────────────────────────────────────────────
+    // Adapter Layer Rules
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("Adapter Layer Rules")
+    class AdapterLayerTests {
+
+        @Test
+        @DisplayName("Adapters implementing Output Ports must have matching names")
+        void repositoryImplementationsShouldHaveCorrectSuffix() {
+            classes()
+                .that().resideInAnyPackage("com.example.adapter.repository..")
+                .and().areNotInterfaces()
+                .should().haveSimpleNameEndingWith("Repository")
+                .orShould().haveSimpleNameEndingWith("Impl")
+                .because("Repository adapters should be named *Repository or *Impl")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("Controllers must be in the adapter layer")
+        void controllersShouldBeInAdapterLayer() {
+            classes()
+                .that().areAnnotatedWith("org.springframework.web.bind.annotation.RestController")
+                .or().areAnnotatedWith("org.springframework.stereotype.Controller")
+                .should().resideInAnyPackage("com.example.adapter.controller..")
+                .because("Controllers belong in the Adapter layer, not UseCase or Enterprise")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("JPA entities must be in the adapter layer")
+        void jpaEntitiesShouldBeInAdapterLayer() {
+            classes()
+                .that().areAnnotatedWith("jakarta.persistence.Entity")
+                .should().resideInAnyPackage("com.example.adapter..")
+                .because("JPA entities belong in the Adapter layer, "
+                    + "separate from domain entities")
+                .check(classes);
+        }
+    }
+
+    // ─────────────────────────────────────────────
+    // Naming Conventions
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("Naming Conventions")
+    class NamingConventionTests {
+
+        @Test
+        @DisplayName("Enterprise entities should not be suffixed with 'Entity'")
+        void domainEntitiesShouldNotBeNamedEntity() {
+            classes()
+                .that().resideInAnyPackage("com.example.core.entity..")
+                .should().haveSimpleNameNotEndingWith("Entity")
+                .because("Domain entities are just domain classes; "
+                    + "'Entity' suffix implies JPA Entity (which is in adapter)")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("Value objects should be immutable (final fields)")
+        void valueObjectsShouldBeFinal() {
+            // Simplified check: value objects should have 'final' modifier
+            // or be Java records
+            noClasses()
+                .that().resideInAnyPackage("com.example.core.valueobject..")
+                .should().haveOnlyFinalFields()
+                .orShould().beRecords();
+        }
+
+        @Test
+        @DisplayName("Repository interfaces should be in port.output package")
+        void repositoryInterfacesShouldBeInPortOutput() {
+            classes()
+                .that().haveSimpleNameEndingWith("Repository")
+                .and().areInterfaces()
+                .and().resideInAnyPackage("com.example.usecase..")
+                .should().resideInAnyPackage("com.example.usecase.port.output..")
+                .because("Repository interfaces (Output Ports) belong in "
+                    + "usecase.port.output package")
+                .check(classes);
+        }
+    }
+
+    // ─────────────────────────────────────────────
+    // Anti-pattern Detection
+    // ─────────────────────────────────────────────
+
+    @Nested
+    @DisplayName("Anti-pattern Detection")
+    class AntiPatternTests {
+
+        @Test
+        @DisplayName("No domain service should have @Transactional")
+        void domainServiceShouldNotBeTransactional() {
+            noMethods()
+                .that().areDeclaredInClassesThat()
+                .resideInAnyPackage("com.example.core..")
+                .should().beAnnotatedWith("org.springframework.transaction.annotation.Transactional")
+                .because("Transactions belong in the Adapter/Infrastructure layer, "
+                    + "not in Enterprise Business Rules")
+                .check(classes);
+        }
+
+        @Test
+        @DisplayName("Enterprise services should not autowire")
+        void enterpriseLayerShouldNotAutowired() {
+            noClasses()
+                .that().resideInAnyPackage("com.example.core..")
+                .should().beAnnotatedWith("org.springframework.beans.factory.annotation.Autowired")
+                .because("Enterprise layer uses constructor injection via framework config, "
+                    + "not field injection with @Autowired")
+                .check(classes);
+        }
+    }
+}
+```
+
+## Maven Setup
+
+```xml
+<!-- pom.xml -->
+<dependency>
+    <groupId>com.tngtech.archunit</groupId>
+    <artifactId>archunit-junit5</artifactId>
+    <version>1.3.0</version>
+    <scope>test</scope>
+</dependency>
+```
+
+## Test Execution
+
+```bash
+# Run ArchUnit tests only
+./mvnw test -pl order-framework -Dtest=CleanArchitectureTest
+
+# Include as part of the verify lifecycle
+./mvnw verify
+```
+
+## CI Pipeline Integration
+
+```yaml
+# .github/workflows/architecture.yml
+name: Architecture Compliance
+on: [pull_request]
+
+jobs:
+  archunit:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - name: Set up JDK 21
+        uses: actions/setup-java@v4
+        with:
+          java-version: '21'
+      - name: Cache Maven
+        uses: actions/cache@v3
+        with:
+          path: ~/.m2/repository
+          key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
+
+      - name: Run ArchUnit Tests
+        run: |
+          ./mvnw test -pl order-framework \
+            -Dtest=CleanArchitectureTest \
+            -DfailIfNoTests=false
+
+      - name: Generate Report (on failure)
+        if: failure()
+        run: echo "Architecture violations found. Check test output above."
+```
+
+## Expected Output
+
+```
+CleanArchitectureTest -
+  ✔ Layer Dependency Rules
+    ✔ Enterprise layer must not depend on outer layers
+    ✔ UseCase layer must not depend on Adapter or Framework
+    ✔ Adapter layer must not depend on Framework
+    ✔ No layer should have circular dependencies
+  ✔ Clean Architecture Layers
+    ✔ All layers follow Clean Architecture dependency direction
+  ✔ Enterprise Layer Purity
+    ✔ Enterprise entities must not use Spring annotations
+    ✔ Enterprise layer must not use JPA annotations
+    ✔ Enterprise layer must not import framework packages
+  ✔ UseCase Layer Rules
+    ✔ UseCase ports must be interfaces
+    ✔ UseCase interactors must implement a port interface
+    ✔ UseCase must not import Spring's @Service annotation
+  ✔ Adapter Layer Rules
+    ✔ Repository implementations should have correct suffix
+    ✔ Controllers must be in the adapter layer
+    ✔ JPA entities must be in the adapter layer
+  ✔ Naming Conventions
+    ✔ Enterprise entities should not be suffixed with 'Entity'
+    ✔ Value objects should be immutable
+    ✔ Repository interfaces should be in port.output package
+  ✔ Anti-pattern Detection
+    ✔ No domain service should have @Transactional
+    ✔ Enterprise layer should not autowire
+```
+
+## Key Points
+
+| Test Category | Why It Matters |
+|---------------|----------------|
+| **Layer Dependencies** | Enforces the Clean Architecture dependency rule at compile level |
+| **Enterprise Purity** | Prevents framework leaks into the most critical layer |
+| **Port Interfaces** | Ensures the interface-segregation principle is followed |
+| **Name Conventions** | Makes architecture violations obvious from file names alone |
+| **Anti-patterns** | Catches common mistakes that violate DDD principles |
+
+> Run ArchUnit tests in CI on every pull request. If a violation is found, the build fails before the code reaches production.

+ 197 - 0
skills/ddd-skills/ddd-architecture-clean/examples/05-domain-event-handling.md

@@ -0,0 +1,197 @@
+# 领域事件处理示例
+
+> 展示整洁架构中领域事件的定义、发布与消费的完整实现。
+
+## 1. Enterprise 层 — 领域事件定义
+
+```java
+// core/event/DomainEvent.java — 抽象基类(零框架依赖)
+public abstract class DomainEvent {
+    private final String eventId;
+    private final String aggregateId;
+    private final Instant occurredOn;
+
+    protected DomainEvent(String aggregateId) {
+        this.eventId = UUID.randomUUID().toString();
+        this.aggregateId = aggregateId;
+        this.occurredOn = Instant.now();
+    }
+
+    public String getEventId() { return eventId; }
+    public String getAggregateId() { return aggregateId; }
+    public Instant getOccurredOn() { return occurredOn; }
+}
+
+// core/event/OrderCreatedEvent.java
+public class OrderCreatedEvent extends DomainEvent {
+    private final OrderId orderId;
+    private final Money totalAmount;
+    private final List<OrderItem> items;
+
+    public OrderCreatedEvent(Order order) {
+        super(order.getId().getValue());
+        this.orderId = order.getId();
+        this.totalAmount = order.getTotalAmount();
+        this.items = new ArrayList<>(order.getItems());
+    }
+
+    public OrderId getOrderId() { return orderId; }
+    public Money getTotalAmount() { return totalAmount; }
+    public List<OrderItem> getItems() { return items; }
+}
+
+// core/event/OrderPaidEvent.java
+public class OrderPaidEvent extends DomainEvent {
+    private final OrderId orderId;
+    private final Money paidAmount;
+
+    public OrderPaidEvent(Order order) {
+        super(order.getId().getValue());
+        this.orderId = order.getId();
+        this.paidAmount = order.getPaidAmount();
+    }
+}
+```
+
+## 2. UseCase 层 — 事件发布端口
+
+```java
+// usecase/port/output/EventPublisher.java
+public interface EventPublisher {
+    void publish(DomainEvent event);
+}
+
+// usecase/port/output/EventBus.java — 批量发布(性能优化)
+public interface EventBus {
+    void publishAll(List<DomainEvent> events);
+}
+```
+
+## 3. Enterprise 层 — 实体中产生事件
+
+```java
+// core/entity/Order.java
+public class Order {
+    private OrderId id;
+    private OrderStatus status;
+    private List<DomainEvent> domainEvents = new ArrayList<>();
+
+    // 公有工厂方法(非公开构造函数)
+    public static Order create(OrderId id, CustomerId customerId, List<OrderItem> items) {
+        Order order = new Order(id, customerId, items);
+        order.status = OrderStatus.CREATED;
+        order.addDomainEvent(new OrderCreatedEvent(order));
+        return order;
+    }
+
+    public void pay(Money amount) {
+        if (status != OrderStatus.CREATED) {
+            throw new OrderDomainException("只有 CREATED 状态的订单可以支付");
+        }
+        this.paidAmount = amount;
+        this.status = OrderStatus.PAID;
+        addDomainEvent(new OrderPaidEvent(this));
+    }
+
+    // 内部收集事件,Interactor 通过 drain 获取
+    private void addDomainEvent(DomainEvent event) {
+        this.domainEvents.add(event);
+    }
+
+    public List<DomainEvent> drainEvents() {
+        var events = List.copyOf(this.domainEvents);
+        this.domainEvents.clear();
+        return events;
+    }
+}
+```
+
+## 4. UseCase 层 — Interactor 发布事件
+
+```java
+// usecase/interactor/PayOrderInteractor.java
+public class PayOrderInteractor implements PayOrderUseCase {
+    private final OrderRepository orderRepository;
+    private final EventPublisher eventPublisher;
+
+    public PayOrderInteractor(OrderRepository orderRepository, EventPublisher eventPublisher) {
+        this.orderRepository = orderRepository;
+        this.eventPublisher = eventPublisher;
+    }
+
+    @Override
+    public PayOrderOutput execute(PayOrderInput input) {
+        // 1. 加载实体
+        Order order = orderRepository.findById(new OrderId(input.getOrderId()))
+            .orElseThrow(() -> new OrderDomainException("订单不存在"));
+
+        // 2. 执行业务方法(内部产生事件)
+        order.pay(new Money(input.getAmount()));
+
+        // 3. 持久化
+        orderRepository.save(order);
+
+        // 4. 发布领域事件(Interactor 只编排不处理事件)
+        order.drainEvents().forEach(eventPublisher::publish);
+
+        // 5. 返回 DTO
+        return new PayOrderOutput(order.getId().getValue(), order.getStatus().name());
+    }
+}
+```
+
+## 5. Adapter 层 — 事件发布实现
+
+```java
+// adapter/event/RabbitMqEventPublisher.java
+@Component
+public class RabbitMqEventPublisher implements EventPublisher {
+    @Autowired
+    private RabbitTemplate rabbitTemplate;
+
+    @Override
+    public void publish(DomainEvent event) {
+        // 同步发布到消息队列
+        String routingKey = event.getClass().getSimpleName();
+        rabbitTemplate.convertAndSend("domain-events", routingKey, event);
+    }
+}
+
+// adapter/event/InMemoryEventPublisher.java — 测试用
+public class InMemoryEventPublisher implements EventPublisher {
+    private final List<DomainEvent> publishedEvents = new ArrayList<>();
+
+    @Override
+    public void publish(DomainEvent event) {
+        publishedEvents.add(event);
+    }
+
+    public List<DomainEvent> getPublishedEvents() { return List.copyOf(publishedEvents); }
+    public void clear() { publishedEvents.clear(); }
+}
+```
+
+## 6. 事件消费(在 Adapter 层)
+
+```java
+// adapter/listener/OrderEventListener.java
+@Component
+public class OrderEventListener {
+    private final PaymentGateway paymentGateway;
+    private final NotificationService notificationService;
+
+    @EventListener
+    public void handleOrderPaid(OrderPaidEvent event) {
+        // 异步处理:发发票、通知仓库、更新物流
+        notificationService.sendOrderConfirmation(event.getOrderId());
+    }
+}
+```
+
+## 验证要点
+
+- **依赖规则**:EventPublisher 接口在 UseCase 层,实现类在 Adapter 层
+- **实体不依赖事件基础设施**:Entity 只用 `List<DomainEvent>` 收集,不 import 任何消息中间件
+- **Interactor 不处理事件**:只负责 drain 和 publish,具体处理在 Adapter 层
+- **Drain 模式**:Entity 的 drainEvents() 在持久化后调用,确保不丢失事件
+- **可测试性**:InMemoryEventPublisher 让单元测试零依赖

+ 151 - 0
skills/ddd-skills/ddd-architecture-clean/examples/06-monolith-simple.md

@@ -0,0 +1,151 @@
+# 06 — 单体 Clean 架构(简单版)
+
+> 单一 Maven 模块内按包名划分四层:entities + usecases + interface-adapters + frameworks。
+
+## 目录树
+
+```
+order-service/
+├── src/main/java/com/example/order/
+│   ├── enterprise/                  # Enterprise Business Rules
+│   │   ├── entity/
+│   │   │   ├── Order.java           # 聚合根
+│   │   │   └── OrderItem.java       # 值对象
+│   │   ├── vo/
+│   │   │   ├── OrderId.java
+│   │   │   ├── Money.java
+│   │   │   └── OrderStatus.java
+│   │   └── event/
+│   │       ├── DomainEvent.java
+│   │       └── OrderCreatedEvent.java
+│   │
+│   ├── usecase/                     # Application Business Rules
+│   │   ├── port/
+│   │   │   ├── input/
+│   │   │   │   └── CreateOrderUseCase.java
+│   │   │   └── output/
+│   │   │       ├── OrderRepository.java
+│   │   │       ├── PaymentGateway.java
+│   │   │       └── EventPublisher.java
+│   │   ├── dto/
+│   │   │   ├── CreateOrderRequest.java
+│   │   │   └── CreateOrderResponse.java
+│   │   └── interactor/
+│   │       └── CreateOrderInteractor.java
+│   │
+│   ├── adapter/                     # Interface Adapters
+│   │   ├── controller/
+│   │   │   └── OrderController.java
+│   │   ├── repository/
+│   │   │   ├── OrderJpaRepository.java
+│   │   │   └── OrderRepositoryImpl.java
+│   │   ├── gateway/
+│   │   │   └── PaymentGatewayImpl.java
+│   │   └── presenter/
+│   │       └── CreateOrderPresenter.java
+│   │
+│   └── framework/                   # Frameworks & Drivers
+│       └── config/
+│           ├── PersistenceConfig.java
+│           ├── UseCaseConfig.java
+│           └── WebConfig.java
+│
+├── src/test/java/com/example/order/
+│   ├── enterprise/entity/OrderTest.java
+│   ├── usecase/interactor/CreateOrderInteractorTest.java
+│   ├── adapter/repository/OrderRepositoryImplTest.java
+│   └── architecture/
+│       └── ArchitectureTest.java
+│
+└── pom.xml
+```
+
+## 包结构关系
+
+```
+┌─────────────────────────────────────────────────┐
+│  framework                                       │
+│  ┌──────────┐  ┌──────────┐  ┌──────────┐      │
+│  │ Config   │  │ Spring DI│  │ DevTools │      │
+│  └────┬─────┘  └──────────┘  └──────────┘      │
+│       │ 依赖                                     │
+├───────▼─────────────────────────────────────────┤
+│  adapter                                         │
+│  ┌──────────┐  ┌──────────┐  ┌──────────┐      │
+│  │Controller│  │Repository│  │ Gateway  │      │
+│  │          │  │ Impl     │  │ Impl     │      │
+│  └────┬─────┘  └────┬─────┘  └────┬─────┘      │
+│       │              │              │            │
+├───────▼──────────────▼──────────────▼───────────┤
+│  usecase                                         │
+│  ┌──────────┐  ┌──────────┐  ┌──────────┐      │
+│  │Interactor│  │Port(input│  │Port(out) │      │
+│  │          │  │ /output) │  │          │      │
+│  └────┬─────┘  └──────────┘  └──────────┘      │
+│       │                                          │
+├───────▼─────────────────────────────────────────┤
+│  enterprise                                      │
+│  ┌──────────┐  ┌──────────┐  ┌──────────┐      │
+│  │ Entity   │  │ ValueObj │  │ Event    │      │
+│  └──────────┘  └──────────┘  └──────────┘      │
+└─────────────────────────────────────────────────┘
+```
+
+## 依赖方向
+
+```
+framework ──► adapter ──► usecase ──► enterprise
+   │              │            │
+   └── 只依赖外层 ─┴── 不依赖内层 ─┘
+```
+
+- **enterprise**: 零依赖(不依赖任何外部包,只依赖 Java 标准库)
+- **usecase**: 只依赖 `enterprise` 包
+- **adapter**: 依赖 `usecase` 端口 + `enterprise` 实体
+- **framework**: 依赖 `adapter` + Spring Boot
+
+## ArchUnit 验证规则
+
+```java
+@AnalyzeClasses(packages = "com.example.order")
+public class ArchitectureTest {
+
+    @ArchTest
+    static final ArchRule enterprise_no_deps = classes()
+        .that().resideInAPackage("..enterprise..")
+        .should().onlyDependOnClassesThat()
+        .resideInAnyPackage("java..", "..enterprise..");
+
+    @ArchTest
+    static final ArchRule usecase_no_framework = classes()
+        .that().resideInAPackage("..usecase..")
+        .should().onlyDependOnClassesThat()
+        .resideInAnyPackage("..enterprise..", "..usecase..", "java..");
+
+    @ArchTest
+    static final ArchRule adapter_no_web = classes()
+        .that().resideInAPackage("..adapter.repository..")
+        .should().onlyHaveDependentClassesThat()
+        .resideInAPackage("..adapter..");
+}
+```
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 3-8 人,单团队维护 |
+| 项目复杂度 | 1-3 个聚合根,< 20 个 UseCase |
+| 模块数 | 单一 Maven 模块(单仓库) |
+| 部署方式 | 单体部署,一个 Spring Boot JAR |
+| 演进路径 | 简单版 → 复杂版(07)→ 多模块(08)→ 微服务拆分 |
+| 典型业务 | 中小型电商后台、CMS、内部工具系统 |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| 包级隔离,结构清晰 | 编译期无法强制分层约束(需 ArchUnit 补救) |
+| 学习成本低,团队快速上手 | 包依赖靠约定,新人可能放错位置 |
+| 一套 CI 管道,部署简单 | 单一模块耦合,难以模块级独立发布 |
+| 适合从三层架构渐进迁移 | 大型项目包膨胀,定位文件困难 |

+ 199 - 0
skills/ddd-skills/ddd-architecture-clean/examples/07-monolith-complex.md

@@ -0,0 +1,199 @@
+# 07 — 单体 Clean 架构(复杂版)
+
+> 多聚合根 + 多 Interactor,单模块内按领域划分子包,每个领域独立四层。
+
+## 目录树
+
+```
+order-service/
+├── src/main/java/com/example/
+│   └── order/
+│       ├── shared/                          # 共享内核
+│       │   ├── domain/
+│       │   │   ├── Identifier.java          # 通用 ID 基类
+│       │   │   ├── Money.java
+│       │   │   └── DomainEvent.java
+│       │   └── event/
+│       │       └── EventPublisher.java      # 事件发布端口
+│       │
+│       ├── order/                           # 订单领域
+│       │   ├── enterprise/
+│       │   │   ├── entity/
+│       │   │   │   ├── Order.java           # 聚合根
+│       │   │   │   └── OrderItem.java
+│       │   │   ├── vo/
+│       │   │   │   ├── OrderId.java
+│       │   │   │   └── OrderStatus.java
+│       │   │   └── event/
+│       │   │       ├── OrderCreatedEvent.java
+│       │   │       └── OrderPaidEvent.java
+│       │   ├── usecase/
+│       │   │   ├── port/input/
+│       │   │   │   ├── CreateOrderUseCase.java
+│       │   │   │   ├── PayOrderUseCase.java
+│       │   │   │   └── QueryOrderUseCase.java
+│       │   │   ├── port/output/
+│       │   │   │   └── OrderRepository.java
+│       │   │   ├── dto/
+│       │   │   │   ├── CreateOrderRequest.java
+│       │   │   │   ├── CreateOrderResponse.java
+│       │   │   │   └── OrderDTO.java
+│       │   │   └── interactor/
+│       │   │       ├── CreateOrderInteractor.java
+│       │   │       ├── PayOrderInteractor.java
+│       │   │       └── QueryOrderInteractor.java
+│       │   ├── adapter/
+│       │   │   ├── controller/
+│       │   │   │   └── OrderController.java
+│       │   │   ├── repository/
+│       │   │   │   ├── OrderJpaEntity.java
+│       │   │   │   ├── OrderItemJpaEntity.java
+│       │   │   │   └── OrderRepositoryImpl.java
+│       │   │   └── presenter/
+│       │   │       └── OrderPresenter.java
+│       │   └── framework/
+│       │       └── config/
+│       │           └── OrderDomainConfig.java
+│       │
+│       ├── payment/                         # 支付领域
+│       │   ├── enterprise/
+│       │   │   ├── entity/
+│       │   │   │   └── Payment.java         # 聚合根
+│       │   │   ├── vo/
+│       │   │   │   ├── PaymentId.java
+│       │   │   │   └── PaymentStatus.java
+│       │   │   └── event/
+│       │   │       └── PaymentCompletedEvent.java
+│       │   ├── usecase/
+│       │   │   ├── port/input/
+│       │   │   │   └── ProcessPaymentUseCase.java
+│       │   │   ├── port/output/
+│       │   │   │   ├── PaymentRepository.java
+│       │   │   │   └── PaymentGateway.java
+│       │   │   ├── dto/
+│       │   │   │   └── PaymentRequest.java
+│       │   │   └── interactor/
+│       │   │       └── ProcessPaymentInteractor.java
+│       │   ├── adapter/
+│       │   │   ├── controller/
+│       │   │   │   └── PaymentController.java
+│       │   │   ├── repository/
+│       │   │   │   └── PaymentRepositoryImpl.java
+│       │   │   └── gateway/
+│       │   │       └── AlipayGatewayImpl.java
+│       │   └── framework/
+│       │       └── config/
+│       │           └── PaymentDomainConfig.java
+│       │
+│       └── inventory/                       # 库存领域
+│           ├── enterprise/
+│           │   ├── entity/
+│           │   │   └── Inventory.java
+│           │   └── vo/
+│           │       ├── SkuId.java
+│           │       └── Quantity.java
+│           ├── usecase/
+│           │   ├── port/input/
+│           │   │   ├── ReserveInventoryUseCase.java
+│           │   │   └── ReleaseInventoryUseCase.java
+│           │   ├── port/output/
+│           │   │   └── InventoryRepository.java
+│           │   └── interactor/
+│           │       ├── ReserveInventoryInteractor.java
+│           │       └── ReleaseInventoryInteractor.java
+│           ├── adapter/
+│           │   └── repository/
+│           │       └── InventoryRepositoryImpl.java
+│           └── framework/
+│               └── config/
+│                   └── InventoryDomainConfig.java
+│
+├── src/test/java/com/example/order/
+│   ├── order/enterprise/entity/OrderTest.java
+│   ├── order/usecase/interactor/
+│   │   ├── CreateOrderInteractorTest.java
+│   │   └── PayOrderInteractorTest.java
+│   ├── payment/usecase/interactor/
+│   │   └── ProcessPaymentInteractorTest.java
+│   ├── architecture/
+│   │   └── ArchitectureTest.java
+│   └── integration/
+│       └── OrderPaymentIntegrationTest.java
+│
+└── pom.xml
+```
+
+## 领域间交互规则
+
+```
+┌──────────────────────────────────────────────────────┐
+│                   shared 共享内核                      │
+│  DomainEvent, Money, Identifier                      │
+└──┬─────────────────┬──────────────────┬──────────────┘
+   │                 │                  │
+   ▼                 ▼                  ▼
+┌──────────┐   ┌──────────┐   ┌──────────────┐
+│  order   │   │ payment  │   │  inventory   │
+│ 领域     │◄──│ 领域     │──►│  领域         │
+│          │   │          │   │              │
+└──────────┘   └──────────┘   └──────────────┘
+    │               │                │
+    └─────── 通过事件异步通信 ────────┘
+```
+
+- **领域间不得直接依赖**:order 不能 import payment 的类
+- **共享内核**:shared 包放跨领域共用类型(Money、DomainEvent)
+- **领域通信**:通过领域事件异步解耦(OrderCreated → ReserveInventory)
+- **UseCase 编排跨领域**:上级编排 Interactor 可依赖多个领域的 output port
+
+## 依赖方向(领域内 + 领域间)
+
+```
+framework ──► adapter ──► usecase ──► enterprise
+   │              │            │
+   └── 仅依赖适配层 ─┴── 仅依赖端口 ─┘
+
+领域间:
+order ──► shared ◄── payment ──► shared ◄── inventory
+   └── 不得互相 import ──────────┘
+```
+
+## ArchUnit 验证(领域隔离)
+
+```java
+@ArchTest
+static final ArchRule no_domain_dependency = classes()
+    .that().resideInAPackage("..order..")
+    .should().onlyDependOnClassesThat()
+    .resideInAnyPackage(
+        "..order..",          // 同领域
+        "..shared..",         // 共享内核
+        "java.."
+    );
+
+@ArchTest
+static final ArchRule order_not_depend_payment = noClasses()
+    .that().resideInAPackage("..order..")
+    .should().dependOnClassesThat()
+    .resideInAPackage("..payment..");
+```
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 8-20 人,多团队协作 |
+| 项目复杂度 | 3-8 个聚合根,20-60 个 UseCase |
+| 领域数 | 3-6 个核心领域 |
+| 部署方式 | 单体部署 |
+| 演进方向 | 复杂版 → 多模块版(08)→ 领域拆分微服务 |
+| 典型业务 | 中型电商平台(订单+支付+库存+物流)、SaaS 后台 |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| 领域隔离清晰,适合多人并行开发 | 编译期无法防止领域间直接依赖 |
+| 事件驱动解耦,领域独立性强 | shared 包膨胀风险(垃圾场效应) |
+| 为微服务拆分做好领域边界准备 | 共享内核变更影响所有领域 |
+| 单一构建,CI 简单 | 领域边界依赖 ArchUnit 人工维护 |

+ 176 - 0
skills/ddd-skills/ddd-architecture-clean/examples/08-monolith-multi-module.md

@@ -0,0 +1,176 @@
+# 08 — 单体 Clean 架构(多模块版)
+
+> 每层一个 Maven 模块,编译期强制依赖方向,适合需要物理隔离的单体项目。
+
+## 目录树
+
+```
+order-platform/
+├── pom.xml                               # 父 POM(module 聚合)
+│
+├── order-enterprise/                     # 模块1: Enterprise Business Rules
+│   ├── pom.xml                           # 零外部依赖
+│   └── src/main/java/com/example/order/enterprise/
+│       ├── entity/
+│       │   ├── Order.java
+│       │   └── OrderItem.java
+│       ├── vo/
+│       │   ├── OrderId.java
+│       │   ├── Money.java
+│       │   └── OrderStatus.java
+│       └── event/
+│           ├── DomainEvent.java
+│           └── OrderCreatedEvent.java
+│
+├── order-usecase/                        # 模块2: Application Business Rules
+│   ├── pom.xml                           # 只依赖 order-enterprise
+│   └── src/main/java/com/example/order/usecase/
+│       ├── port/input/
+│       │   ├── CreateOrderUseCase.java
+│       │   └── QueryOrderUseCase.java
+│       ├── port/output/
+│       │   ├── OrderRepository.java
+│       │   └── PaymentGateway.java
+│       ├── dto/
+│       │   ├── CreateOrderRequest.java
+│       │   ├── CreateOrderResponse.java
+│       │   └── OrderSummaryDTO.java
+│       └── interactor/
+│           ├── CreateOrderInteractor.java
+│           └── QueryOrderInteractor.java
+│
+├── order-adapter/                        # 模块3: Interface Adapters
+│   ├── pom.xml                           # 依赖 order-usecase + order-enterprise
+│   └── src/main/java/com/example/order/adapter/
+│       ├── controller/
+│       │   └── OrderController.java
+│       ├── repository/
+│       │   ├── OrderJpaEntity.java
+│       │   ├── OrderJpaRepository.java
+│       │   └── OrderRepositoryImpl.java
+│       └── gateway/
+│           └── AlipayGatewayImpl.java
+│
+├── order-boot/                           # 模块4: Frameworks & Drivers
+│   ├── pom.xml                           # 依赖 order-adapter + Spring Boot
+│   └── src/main/java/com/example/order/boot/
+│       ├── OrderApplication.java         # @SpringBootApplication
+│       └── config/
+│           ├── UseCaseConfig.java        # @Configuration: Bean 装配
+│           ├── PersistenceConfig.java
+│           └── SecurityConfig.java
+│
+├── order-acceptance/                     # 模块5: 验收测试(可选)
+│   ├── pom.xml                           # 依赖 order-boot (test scope)
+│   └── src/test/java/com/example/order/acceptance/
+│       └── OrderAcceptanceTest.java
+│
+└── order-arch-test/                      # 模块6: 架构测试(可选)
+    ├── pom.xml                           # 依赖所有模块 (test scope)
+    └── src/test/java/com/example/order/arch/
+        └── DependencyRuleTest.java
+```
+
+## Maven 依赖关系
+
+```xml
+<!-- order-enterprise/pom.xml -->
+<!-- 零外部依赖,只含 Java 标准库 -->
+<dependencies>
+    <!-- 无 -->
+</dependencies>
+
+<!-- order-usecase/pom.xml -->
+<dependencies>
+    <dependency>
+        <groupId>com.example</groupId>
+        <artifactId>order-enterprise</artifactId>
+    </dependency>
+</dependencies>
+
+<!-- order-adapter/pom.xml -->
+<dependencies>
+    <dependency>
+        <groupId>com.example</groupId>
+        <artifactId>order-usecase</artifactId>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-web</artifactId>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-data-jpa</artifactId>
+    </dependency>
+</dependencies>
+
+<!-- order-boot/pom.xml -->
+<dependencies>
+    <dependency>
+        <groupId>com.example</groupId>
+        <artifactId>order-adapter</artifactId>
+    </dependency>
+    <dependency>
+        <groupId>com.example</groupId>
+        <artifactId>order-usecase</artifactId>
+    </dependency>
+    <!-- Spring Boot Starter -->
+</dependencies>
+```
+
+## 依赖方向图
+
+```
+┌────────────────────────────────────────────┐
+│              order-boot                     │
+│   SpringBoot App + DI Config               │
+│   依赖: adapter, usecase, enterprise        │
+└────────────────┬───────────────────────────┘
+                 │
+┌────────────────▼───────────────────────────┐
+│              order-adapter                   │
+│   Controller, Repository Impl, Gateway      │
+│   依赖: usecase, enterprise                 │
+└────────────────┬───────────────────────────┘
+                 │
+┌────────────────▼───────────────────────────┐
+│              order-usecase                  │
+│   Interactor, Port (in/out), DTO           │
+│   依赖: enterprise                          │
+└────────────────┬───────────────────────────┘
+                 │
+┌────────────────▼───────────────────────────┐
+│            order-enterprise                 │
+│   Entity, Value Object, Domain Event       │
+│   零外部依赖                                │
+└────────────────────────────────────────────┘
+```
+
+## 编译期强制 vs 运行时检查
+
+| 机制 | 简单版(06) | 多模块版(08) |
+|------|------------|---------------|
+| 分层隔离 | 包名约定 | Maven 模块依赖 |
+| 违规检测 | ArchUnit 运行时 | **编译期报错** |
+| usecase 引用 Spring | ArchUnit 拦截 | Maven 不解析类,编译失败 |
+| 循环依赖 | 可能发生 | Maven 拒绝构建 |
+| 构建速度 | 快 | 增量构建后可接受 |
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 8-25 人,多团队协作 |
+| 项目复杂度 | 3-8 个聚合根,30-80 个 UseCase |
+| 隔离要求 | 需要编译期强制分层隔离 |
+| 演进方向 | 可进一步拆分为领域模块 + 微服务 |
+| 典型业务 | 企业级中台、大型电商、金融核心系统 |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| 编译期强制依赖方向,杜绝腐化 | 模块数多,构建配置复杂 |
+| 各模块可独立构建、测试 | 新人上手成本较高 |
+| 为微服务拆分提供天然的模块边界 | 跨模块测试配置繁琐 |
+| 适合大型团队并行开发 | 单体中过度模块化增加维护成本 |

+ 168 - 0
skills/ddd-skills/ddd-architecture-clean/examples/09-microservice-simple.md

@@ -0,0 +1,168 @@
+# 09 — 微服务 Clean 架构(简单版)
+
+> 单个微服务内按包名划分四层,适用单体拆分后的第一个独立微服务。
+
+## 目录树
+
+```
+order-service/                              # 独立微服务
+├── Dockerfile
+├── pom.xml
+├── src/main/java/com/example/order/
+│   ├── enterprise/                         # Enterprise Business Rules
+│   │   ├── entity/
+│   │   │   └── Order.java
+│   │   ├── vo/
+│   │   │   ├── OrderId.java
+│   │   │   ├── Money.java
+│   │   │   └── OrderStatus.java
+│   │   └── event/
+│   │       ├── DomainEvent.java
+│   │       └── OrderCreatedEvent.java
+│   │
+│   ├── usecase/                            # Application Business Rules
+│   │   ├── port/input/
+│   │   │   ├── CreateOrderUseCase.java
+│   │   │   └── QueryOrderUseCase.java
+│   │   ├── port/output/
+│   │   │   ├── OrderRepository.java
+│   │   │   └── EventBus.java              # 发布事件到 MQ
+│   │   ├── dto/
+│   │   │   ├── CreateOrderRequest.java
+│   │   │   └── OrderDTO.java
+│   │   └── interactor/
+│   │       ├── CreateOrderInteractor.java
+│   │       └── QueryOrderInteractor.java
+│   │
+│   ├── adapter/                            # Interface Adapters
+│   │   ├── controller/
+│   │   │   └── OrderController.java
+│   │   ├── repository/
+│   │   │   ├── OrderJpaEntity.java
+│   │   │   └── OrderRepositoryImpl.java
+│   │   ├── messaging/
+│   │   │   ├── KafkaEventBus.java
+│   │   │   └── OrderEventConsumer.java    # 消费其他服务事件
+│   │   └── client/                        # 外部服务调用适配器
+│   │       └── InventoryServiceClient.java
+│   │
+│   └── framework/                          # Frameworks & Drivers
+│       └── config/
+│           ├── OrderApplication.java
+│           ├── UseCaseConfig.java
+│           ├── PersistenceConfig.java
+│           ├── KafkaConfig.java
+│           └── FeignClientConfig.java
+│
+├── src/main/resources/
+│   ├── application.yml
+│   └── db/migration/                       # Flyway 迁移脚本
+│       └── V1__create_order_table.sql
+│
+└── src/test/java/com/example/order/
+    ├── enterprise/entity/OrderTest.java
+    ├── usecase/interactor/CreateOrderInteractorTest.java
+    ├── adapter/repository/OrderRepositoryImplTest.java
+    ├── integration/
+    │   └── OrderServiceIntegrationTest.java
+    └── architecture/
+        └── ArchitectureTest.java
+```
+
+## 服务拓扑
+
+```
+                    ┌──────────────┐
+                    │  API Gateway │
+                    └──────┬───────┘
+                           │ HTTP/REST
+          ┌────────────────┼────────────────┐
+          │                │                │
+    ┌─────▼─────┐   ┌─────▼─────┐   ┌─────▼─────┐
+    │  order    │   │ payment   │   │ inventory │
+    │  service  │   │  service  │   │  service  │
+    └─────┬─────┘   └─────┬─────┘   └─────┬─────┘
+          │                │                │
+          └────────────────┼────────────────┘
+                           │ Async Events
+                    ┌──────▼───────┐
+                    │    Kafka     │
+                    └──────────────┘
+
+每个微服务内部使用整洁架构四层结构
+```
+
+## 依赖方向(微服务内 + 微服务间)
+
+**微服务内**(同 06-monolith-simple):
+```
+framework ──► adapter ──► usecase ──► enterprise
+```
+
+**微服务间**:
+```
+order ◄──► payment (通过 REST API 同步调用 + Kafka 异步事件)
+order ◄──► inventory (通过 REST API 同步调用 + Kafka 异步事件)
+禁止:微服务间直接共享代码/实体,只通过 API Contract 通信
+```
+
+## 微服务特有关注点
+
+### 1. 远程调用适配器
+
+```java
+// adapter/client/InventoryServiceClient.java
+@Component
+public class InventoryServiceClient implements ReserveInventoryPort {
+    private final InventoryFeignClient feignClient;
+
+    @Override
+    public ReserveResult reserve(ReserveCommand cmd) {
+        // 将领域命令转为 HTTP DTO
+        var request = InventoryReserveRequest.from(cmd);
+        var response = feignClient.reserve(request);
+        return response.toDomain();  // 转回领域对象
+    }
+}
+```
+
+### 2. 事件总线适配器
+
+```java
+// adapter/messaging/KafkaEventBus.java
+@Component
+public class KafkaEventBus implements EventBus {
+    private final KafkaTemplate<String, DomainEvent> kafka;
+
+    @Override
+    public void publish(DomainEvent event) {
+        kafka.send("order-events", event.getAggregateId(), event);
+    }
+}
+```
+
+### 3. 分布式事务
+
+- **Saga 编排**:由 UseCase Interactor 编排本地事务 + 补偿逻辑
+- **Outbox 模式**:领域事件先写本地 outbox 表,再异步投递到 Kafka
+- **幂等消费**:消费者按 eventId 去重
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 4-10 人/服务 |
+| 项目复杂度 | 1-2 个聚合根/服务,< 15 个 UseCase/服务 |
+| 服务数 | 3-8 个微服务 |
+| 通信方式 | REST(同步)+ Kafka(异步) |
+| 部署方式 | Docker + K8s,独立部署 |
+| 典型业务 | 从单体拆分出的核心领域微服务(订单/支付/库存) |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| 独立部署、扩展、技术栈选择 | 分布式复杂度(网络、事务、一致性) |
+| 整洁架构保证微服务内部质量 | 重复的四层结构模板代码 |
+| 清晰的服务边界 | 需额外处理服务发现、配置中心 |
+| 适合小团队独立交付 | 跨服务调试困难 |

+ 204 - 0
skills/ddd-skills/ddd-architecture-clean/examples/10-microservice-complex.md

@@ -0,0 +1,204 @@
+# 10 — 微服务 Clean 架构(复杂版)
+
+> 单微服务内含多聚合根 + 多 Interactor + 领域事件 + CQRS + Saga 编排。
+
+## 目录树
+
+```
+order-service/
+├── Dockerfile
+├── pom.xml
+├── src/main/java/com/example/order/
+│   ├── shared/                              # 微服务内共享内核
+│   │   ├── domain/
+│   │   │   ├── Identifier.java
+│   │   │   ├── Money.java
+│   │   │   └── DomainEvent.java
+│   │   └── event/
+│   │       └── EventPublisher.java
+│   │
+│   ├── order/                               # 订单子域
+│   │   ├── enterprise/
+│   │   │   ├── entity/Order.java
+│   │   │   ├── entity/OrderItem.java
+│   │   │   ├── vo/OrderId.java
+│   │   │   ├── vo/OrderStatus.java
+│   │   │   └── event/
+│   │   │       ├── OrderCreatedEvent.java
+│   │   │       ├── OrderPaidEvent.java
+│   │   │       └── OrderCancelledEvent.java
+│   │   ├── usecase/
+│   │   │   ├── port/input/
+│   │   │   │   ├── CreateOrderUseCase.java
+│   │   │   │   ├── PayOrderUseCase.java
+│   │   │   │   └── CancelOrderUseCase.java
+│   │   │   ├── port/output/
+│   │   │   │   ├── OrderRepository.java
+│   │   │   │   └── PaymentPort.java
+│   │   │   ├── dto/
+│   │   │   │   ├── CreateOrderRequest.java
+│   │   │   │   └── OrderDTO.java
+│   │   │   └── interactor/
+│   │   │       ├── CreateOrderInteractor.java
+│   │   │       └── PayOrderSagaInteractor.java  # Saga 编排器
+│   │   ├── adapter/
+│   │   │   ├── controller/OrderController.java
+│   │   │   ├── repository/
+│   │   │   │   ├── OrderJpaEntity.java
+│   │   │   │   └── OrderRepositoryImpl.java
+│   │   │   └── messaging/
+│   │   │       ├── OrderEventPublisher.java
+│   │   │       └── PaymentEventConsumer.java
+│   │   └── framework/
+│   │       └── config/OrderDomainConfig.java
+│   │
+│   ├── fulfillment/                          # 履约子域
+│   │   ├── enterprise/
+│   │   │   ├── entity/FulfillmentOrder.java
+│   │   │   ├── vo/FulfillmentId.java
+│   │   │   ├── vo/FulfillmentStatus.java
+│   │   │   └── event/
+│   │   │       └── FulfillmentStartedEvent.java
+│   │   ├── usecase/
+│   │   │   ├── port/input/
+│   │   │   │   ├── StartFulfillmentUseCase.java
+│   │   │   │   └── CompleteFulfillmentUseCase.java
+│   │   │   ├── port/output/
+│   │   │   │   └── FulfillmentRepository.java
+│   │   │   └── interactor/
+│   │   │       └── StartFulfillmentInteractor.java
+│   │   └── adapter/repository/
+│   │       └── FulfillmentRepositoryImpl.java
+│   │
+│   └── query/                               # CQRS 查询端
+│       ├── dto/
+│       │   ├── OrderSummaryDTO.java
+│       │   └── OrderDetailDTO.java
+│       ├── port/
+│       │   ├── QueryOrderUseCase.java
+│       │   └── QueryFulfillmentUseCase.java
+│       ├── interactor/
+│       │   ├── QueryOrderInteractor.java
+│       │   └── QueryFulfillmentInteractor.java
+│       └── adapter/
+│           ├── controller/
+│           │   ├── OrderQueryController.java
+│           │   └── FulfillmentQueryController.java
+│           └── repository/
+│               ├── OrderReadRepository.java
+│               └── FulfillmentReadRepository.java
+│
+├── src/main/resources/
+│   ├── application.yml
+│   ├── application-kafka.yml
+│   └── db/migration/
+│       ├── V1__create_order_table.sql
+│       ├── V2__create_outbox_table.sql
+│       └── V3__create_fulfillment_table.sql
+│
+└── src/test/java/com/example/order/
+    ├── order/usecase/interactor/
+    │   ├── CreateOrderInteractorTest.java
+    │   └── PayOrderSagaInteractorTest.java
+    ├── integration/
+    │   ├── OrderSagaIntegrationTest.java
+    │   └── EventPublishingIntegrationTest.java
+    └── architecture/
+        └── ArchitectureTest.java
+```
+
+## 核心模式
+
+### 1. CQRS 分离
+
+```
+┌─────────────────────────────────────────────────┐
+│                   Order Service                  │
+│                                                  │
+│  ┌──────────────────┐   ┌──────────────────┐    │
+│  │  Command Side    │   │   Query Side     │    │
+│  │                  │   │                  │    │
+│  │ OrderController  │   │ OrderQueryCtrl   │    │
+│  │      │           │   │      │           │    │
+│  │      ▼           │   │      ▼           │    │
+│  │ Interactor       │   │ QueryInteractor  │    │
+│  │      │           │   │      │           │    │
+│  │      ▼           │   │      ▼           │    │
+│  │ OrderRepository  │   │ OrderReadRepo    │    │
+│  │   (JPA Entity)   │   │  (Native SQL)    │    │
+│  └──────────────────┘   └──────────────────┘    │
+│                                                  │
+│  同一张 MySQL 表,但读写使用不同数据模型          │
+└─────────────────────────────────────────────────┘
+```
+
+### 2. Saga 编排
+
+```java
+// order/usecase/interactor/PayOrderSagaInteractor.java
+public class PayOrderSagaInteractor implements PayOrderUseCase {
+
+    @Override
+    public PayOrderResponse execute(PayOrderRequest request) {
+        // Step 1: 锁定库存(调用 inventory service)
+        var reserveResult = reserveInventoryPort.reserve(request);
+        if (reserveResult.isFailure()) return PayOrderResponse.failed();
+
+        // Step 2: 扣款(调用 payment service)
+        var paymentResult = paymentPort.charge(request);
+        if (paymentResult.isFailure()) {
+            // 补偿: 释放库存
+            releaseInventoryPort.release(request.getOrderId());
+            return PayOrderResponse.failed();
+        }
+
+        // Step 3: 更新订单状态
+        var order = orderRepository.findById(request.getOrderId());
+        order.markAsPaid();
+        orderRepository.save(order);
+
+        // Step 4: 发布事件
+        eventPublisher.publish(new OrderPaidEvent(order));
+
+        return PayOrderResponse.success(order);
+    }
+}
+```
+
+### 3. Outbox 模式(事件可靠性)
+
+```java
+// Saga Interactor 发布事件时同步写 outbox
+order.markAsPaid();
+order.addEvent(new OrderPaidEvent(order));  // 添加到 outbox 列表
+orderRepository.save(order);                 // 事务提交,事件落表
+
+// OutboxScheduler 异步轮询投递到 Kafka
+@Scheduled(fixedDelay = 1000)
+public void publishOutboxEvents() {
+    var events = outboxRepository.findUnpublished(100);
+    events.forEach(e -> {
+        kafkaTemplate.send(e.getTopic(), e.getPayload());
+        outboxRepository.markAsPublished(e.getId());
+    });
+}
+```
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 8-20 人/服务 |
+| 项目复杂度 | 3-5 个聚合根/服务,15-40 个 UseCase/服务 |
+| 架构模式 | CQRS + Saga + Outbox + Event-Driven |
+| 通信方式 | REST(同步)+ Kafka(异步事件总线) |
+| 典型业务 | 复杂电商订单、物流履约、保险理赔 |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| CQRS 读写分离,性能可独立优化 | 架构复杂度高,需团队有成熟 DDD 经验 |
+| Saga 保证跨服务数据一致性 | 最终一致性增加业务复杂度 |
+| 事件驱动解耦,可扩展性强 | Outbox 调度器增加运维负担 |
+| 子域内整洁架构,子域间事件通信 | 需要可靠的消息基础设施 |

+ 156 - 0
skills/ddd-skills/ddd-architecture-clean/examples/11-microservice-multi-module.md

@@ -0,0 +1,156 @@
+# 11 — 微服务 Clean 架构(多模块版)
+
+> 单微服务按四层拆分为 Maven 模块,编译期强制依赖方向。
+
+## 目录树
+
+```
+order-service/
+├── pom.xml                                  # 父 POM
+├── Dockerfile
+│
+├── order-enterprise/                        # 模块1: Enterprise
+│   ├── pom.xml                              # 零框架依赖
+│   └── src/main/java/com/example/order/enterprise/
+│       ├── entity/Order.java
+│       ├── entity/OrderItem.java
+│       ├── vo/OrderId.java
+│       ├── vo/Money.java
+│       ├── vo/OrderStatus.java
+│       ├── event/DomainEvent.java
+│       └── event/OrderCreatedEvent.java
+│
+├── order-usecase/                           # 模块2: Application
+│   ├── pom.xml                              # 只依赖 order-enterprise
+│   └── src/main/java/com/example/order/usecase/
+│       ├── port/input/
+│       │   ├── CreateOrderUseCase.java
+│       │   └── QueryOrderUseCase.java
+│       ├── port/output/
+│       │   ├── OrderRepository.java
+│       │   └── EventBus.java
+│       ├── dto/
+│       │   ├── CreateOrderRequest.java
+│       │   └── CreateOrderResponse.java
+│       └── interactor/
+│           ├── CreateOrderInteractor.java
+│           └── QueryOrderInteractor.java
+│
+├── order-adapter/                           # 模块3: Adapters
+│   ├── pom.xml                              # 依赖 usecase + enterprise + Spring
+│   └── src/main/java/com/example/order/adapter/
+│       ├── controller/OrderController.java
+│       ├── repository/
+│       │   ├── OrderJpaEntity.java
+│       │   ├── OrderJpaRepository.java
+│       │   └── OrderRepositoryImpl.java
+│       └── messaging/
+│           ├── KafkaEventBus.java
+│           └── OrderEventConsumer.java
+│
+├── order-client/                            # 模块4: 对外 API(可选)
+│   ├── pom.xml                              # 只含 DTO,无内部依赖
+│   └── src/main/java/com/example/order/client/
+│       ├── dto/
+│       │   ├── CreateOrderRequest.java
+│       │   └── OrderResponse.java
+│       └── api/
+│           └── OrderServiceApi.java         # Feign Interface
+│
+├── order-boot/                              # 模块5: Boot & Config
+│   ├── pom.xml                              # 依赖所有模块
+│   └── src/main/java/com/example/order/boot/
+│       ├── OrderApplication.java
+│       └── config/
+│           ├── UseCaseConfig.java
+│           ├── PersistenceConfig.java
+│           └── KafkaConfig.java
+│
+└── order-integration-test/                  # 模块6: 集成测试
+    ├── pom.xml                              # 依赖所有模块 (test scope)
+    └── src/test/java/com/example/order/it/
+        ├── OrderServiceIntegrationTest.java
+        └── KafkaEventIntegrationTest.java
+```
+
+## 模块依赖关系
+
+```
+┌──────────────────┐
+│   order-client   │  ← 对外暴露的 API 契约(纯 DTO + Feign Interface)
+└────────┬─────────┘     无内部依赖,可独立发布给消费者
+         │
+┌────────▼─────────┐
+│   order-boot     │  ← Spring Boot 启动 + DI 配置
+└────────┬─────────┘     依赖: adapter, usecase, enterprise, client
+         │
+┌────────▼─────────┐
+│  order-adapter   │  ← Controller, Repository Impl, Kafka Adapter
+└────────┬─────────┘     依赖: usecase, enterprise
+         │
+┌────────▼─────────┐
+│  order-usecase   │  ← Interactor, Port 接口
+└────────┬─────────┘     依赖: enterprise
+         │
+┌────────▼─────────┐
+│ order-enterprise │  ← Entity, VO, Domain Event
+└──────────────────┘     零外部依赖
+```
+
+## Maven 模块职责矩阵
+
+| 模块 | 分层 | Spring 依赖 | 可独立构建 | 可独立测试 |
+|------|------|------------|-----------|-----------|
+| `order-enterprise` | Enterprise | ❌ 无 | ✅ | ✅ 纯单元测试 |
+| `order-usecase` | Application | ❌ 无 | ✅ | ✅ Mock 端口 |
+| `order-adapter` | Interface Adapters | ✅ Web+JPA+Kafka | ✅ | ✅ Testcontainers |
+| `order-client` | 对外 API | ❌ 无 | ✅ | N/A |
+| `order-boot` | Frameworks | ✅ Spring Boot | ✅ | ✅ 集成测试 |
+| `order-integration-test` | 测试 | ✅ 所有 | ✅ | ✅ 全链路 |
+
+## 微服务特有关系
+
+### client 模块:API 契约独立发布
+
+```
+order-service 发布时:
+  order-client-1.0.1.jar → Maven 仓库
+
+payment-service 依赖:
+  <dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-client</artifactId>
+    <version>1.0.1</version>
+  </dependency>
+```
+
+其他服务通过 `order-client` 获得类型安全的 Feign 接口,无需手写 HTTP 调用。
+
+### 独立构建优化
+
+```bash
+# 只构建 usecase 层(不触发 adapter 的 JPA/Kafka 编译)
+cd order-usecase && mvn test -pl .
+
+# 全量构建(含集成测试)
+mvn verify -pl order-integration-test
+```
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 8-20 人/服务,模块级独立开发 |
+| 项目复杂度 | 2-4 个聚合根/服务,15-30 个 UseCase/服务 |
+| 隔离要求 | 编译期强制四层隔离 + 模块间 API 契约化 |
+| 发布策略 | 各模块独立版本,API 契约独立演进 |
+| 典型业务 | 平台型微服务、多消费者 SaaS API |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| 编译期绝对隔离,零腐化风险 | 6 个模块维护成本高 |
+| API 契约独立发布,消费者解耦 | 模块间版本依赖管理复杂 |
+| 各层独立编译、测试、发布 | 新人需要理解完整的模块图 |
+| 天然适配 CI/CD 增量构建 | 小服务过度工程化风险 |

+ 261 - 0
skills/ddd-skills/ddd-architecture-clean/examples/12-microservice-complex-multi.md

@@ -0,0 +1,261 @@
+# 12 — 微服务 Clean 架构(复杂多模块版)
+
+> 多子域 + 多模块 + CQRS + Saga + Outbox + API 契约独立发布。Clean Architecture 微服务的最高复杂度形态。
+
+## 目录树
+
+```
+order-service/
+├── pom.xml                                     # 父 POM
+├── Dockerfile
+├── docker-compose.yml                          # 本地开发:MySQL + Kafka + Redis
+│
+├── order-shared/                               # 模块1: 共享内核
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/shared/
+│       ├── domain/
+│       │   ├── Identifier.java
+│       │   ├── Money.java
+│       │   └── DomainEvent.java
+│       └── event/
+│           └── EventPublisher.java
+│
+├── order-domain/                               # 模块2: 领域层(Enterprise)
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/domain/
+│       ├── order/
+│       │   ├── entity/Order.java
+│       │   ├── entity/OrderItem.java
+│       │   ├── vo/OrderId.java
+│       │   ├── vo/OrderStatus.java
+│       │   └── event/
+│       │       ├── OrderCreatedEvent.java
+│       │       └── OrderPaidEvent.java
+│       ├── delivery/
+│       │   ├── entity/Delivery.java
+│       │   ├── vo/DeliveryId.java
+│       │   └── vo/DeliveryStatus.java
+│       └── invoice/
+│           ├── entity/Invoice.java
+│           ├── vo/InvoiceId.java
+│           └── vo/InvoiceStatus.java
+│
+├── order-usecase/                              # 模块3: 用例层(Application)
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/usecase/
+│       ├── order/
+│       │   ├── port/input/
+│       │   │   ├── CreateOrderUseCase.java
+│       │   │   ├── PayOrderUseCase.java
+│       │   │   └── CancelOrderUseCase.java
+│       │   ├── port/output/
+│       │   │   ├── OrderRepository.java
+│       │   │   └── PaymentPort.java
+│       │   ├── dto/
+│       │   │   ├── CreateOrderRequest.java
+│       │   │   └── OrderResponse.java
+│       │   └── interactor/
+│       │       ├── CreateOrderInteractor.java
+│       │       └── PayOrderSagaInteractor.java
+│       ├── delivery/
+│       │   ├── port/input/
+│       │   │   ├── ScheduleDeliveryUseCase.java
+│       │   │   └── TrackDeliveryUseCase.java
+│       │   ├── port/output/
+│       │   │   └── DeliveryRepository.java
+│       │   └── interactor/
+│       │       └── ScheduleDeliveryInteractor.java
+│       └── invoice/
+│           ├── port/input/
+│           │   └── GenerateInvoiceUseCase.java
+│           ├── port/output/
+│           │   └── InvoiceRepository.java
+│           └── interactor/
+│               └── GenerateInvoiceInteractor.java
+│
+├── order-adapter-persistence/                  # 模块4A: 持久化适配
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/adapter/persistence/
+│       ├── order/
+│       │   ├── OrderJpaEntity.java
+│       │   ├── OrderItemJpaEntity.java
+│       │   ├── OrderJpaRepository.java
+│       │   └── OrderRepositoryImpl.java
+│       ├── delivery/
+│       │   ├── DeliveryJpaEntity.java
+│       │   └── DeliveryRepositoryImpl.java
+│       └── invoice/
+│           ├── InvoiceJpaEntity.java
+│           └── InvoiceRepositoryImpl.java
+│
+├── order-adapter-web/                          # 模块4B: Web 适配
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/adapter/web/
+│       ├── order/
+│       │   └── OrderController.java
+│       ├── delivery/
+│       │   └── DeliveryController.java
+│       └── invoice/
+│           └── InvoiceController.java
+│
+├── order-adapter-messaging/                    # 模块4C: 消息适配
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/adapter/messaging/
+│       ├── publisher/
+│       │   └── KafkaEventPublisher.java
+│       └── consumer/
+│           ├── PaymentEventConsumer.java
+│           └── InventoryEventConsumer.java
+│
+├── order-query/                                # 模块5: CQRS 查询端
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/query/
+│       ├── dto/
+│       │   ├── OrderSummaryDTO.java
+│       │   └── OrderDetailDTO.java
+│       ├── port/
+│       │   ├── QueryOrderPort.java
+│       │   └── QueryDeliveryPort.java
+│       ├── interactor/
+│       │   ├── QueryOrderInteractor.java
+│       │   └── QueryDeliveryInteractor.java
+│       └── adapter/
+│           ├── controller/
+│           │   ├── OrderQueryController.java
+│           │   └── DeliveryQueryController.java
+│           └── persistence/
+│               └── OrderReadRepository.java
+│
+├── order-client/                               # 模块6: API 契约
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/client/
+│       ├── dto/
+│       │   ├── CreateOrderRequest.java
+│       │   └── OrderResponse.java
+│       ├── api/
+│       │   └── OrderServiceApi.java
+│       └── event/
+│           └── OrderEventSchema.java
+│
+├── order-boot/                                 # 模块7: 启动配置
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/boot/
+│       ├── OrderApplication.java
+│       └── config/
+│           ├── UseCaseConfig.java
+│           ├── PersistenceConfig.java
+│           ├── KafkaConfig.java
+│           └── SwaggerConfig.java
+│
+└── order-integration-test/                     # 模块8: 集成测试
+    ├── pom.xml
+    └── src/test/java/com/example/order/it/
+        ├── OrderSagaIntegrationTest.java
+        ├── EventDrivenIntegrationTest.java
+        └── CqrsIntegrationTest.java
+```
+
+## 模块依赖图
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│                      order-boot                              │
+│   Spring Boot App + DI Config                               │
+│   依赖: 所有模块                                              │
+└──┬──────────┬──────────┬──────────┬──────────┬──────────────┘
+   │          │          │          │          │
+   ▼          ▼          ▼          ▼          ▼
+┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────────┐
+│adapter│ │adapter│ │adapter│ │query │ │  client  │
+│web    │ │persist│ │msging │ │      │ │          │
+└──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──────────┘
+   │        │        │        │
+   └────────┼────────┼────────┘
+            │        │
+            ▼        ▼
+      ┌──────────────┐
+      │  order-usecase│
+      └──────┬───────┘
+             │
+             ▼
+      ┌──────────────┐        ┌──────────────┐
+      │ order-domain │◄───────│ order-shared │
+      └──────────────┘        └──────────────┘
+
+依赖方向始终向内:boot → adapters → usecase → domain → shared
+```
+
+## 子域间通信(微服务内)
+
+```
+┌──────────────────────────────────────────────────────┐
+│                   Order Service                       │
+│                                                       │
+│  ┌──────────┐   event    ┌──────────┐   event        │
+│  │  order   │───────────►│ delivery │───────────►    │
+│  │  created │            │ schedule │               │
+│  └──────────┘            └──────────┘               │
+│        │                      │                      │
+│        │ event                │ event                │
+│        ▼                      ▼                      │
+│  ┌──────────┐           ┌──────────┐                │
+│  │ invoice  │           │inventory │ (external)      │
+│  │ generate │           │  reserve │                │
+│  └──────────┘           └──────────┘                │
+│                                                       │
+│  同一服务内子域通过 In-Memory EventBus 通信             │
+└──────────────────────────────────────────────────────┘
+```
+
+### 服务内事件总线
+
+```java
+// order-shared/event/EventPublisher.java
+public interface EventPublisher {
+    void publish(DomainEvent event);
+    <T extends DomainEvent> void subscribe(Class<T> type, Consumer<T> handler);
+}
+
+// order-boot/config/UseCaseConfig.java
+@Bean
+public EventPublisher eventPublisher() {
+    var bus = new InMemoryEventBus();
+    // order created → schedule delivery
+    bus.subscribe(OrderCreatedEvent.class, deliveryScheduler::onOrderCreated);
+    // order paid → generate invoice
+    bus.subscribe(OrderPaidEvent.class, invoiceGenerator::onOrderPaid);
+    return bus;
+}
+```
+
+## 对比:12 种规模选型矩阵
+
+| # | 名称 | 模块数 | 聚合/服务 | 适用团队 | 关键特征 |
+|---|------|--------|----------|---------|---------|
+| 06 | 单体简单 | 1 | 1-3 | 3-8人 | 包级分层,单模块 |
+| 07 | 单体复杂 | 1 | 3-8 | 8-20人 | 多领域包隔离 |
+| 08 | 单体多模块 | 4-6 | 3-8 | 8-25人 | 编译期强制分层 |
+| 09 | 微服务简单 | 1/服务 | 1-2/服务 | 4-10人/服务 | 包级分层,独立部署 |
+| 10 | 微服务复杂 | 1/服务 | 3-5/服务 | 8-20人/服务 | CQRS + Saga + Outbox |
+| 11 | 微服务多模块 | 5-6/服务 | 2-4/服务 | 8-20人/服务 | 编译期强制 + API 契约 |
+| 12 | 微服务复杂多模块 | 7-8/服务 | 3-5/服务 | 10-30人/服务 | 全模式:子域+模块+CQRS+Saga+API |
+
+## 适用场景
+
+| 维度 | 说明 |
+|------|------|
+| 团队规模 | 10-30 人/服务 |
+| 项目复杂度 | 3-5 个子域/服务,20-50 个 UseCase |
+| 架构模式 | Clean Architecture + DDD + CQRS + Event-Driven + Saga + Outbox |
+| 通信方式 | 服务内 In-Memory EventBus + 服务间 Kafka |
+| 部署方式 | Docker + K8s + 独立 CI/CD 管道 |
+| 典型业务 | 大型电商订单中台、金融交易核心、保险理赔系统 |
+
+## 优缺点
+
+| ✅ 优点 | ❌ 缺点 |
+|---------|---------|
+| 编译期 100% 架构合规 | 8 个模块维护成本极高 |
+| 子域隔离 + 分层隔离,双重保护 | 新人需要极长时间上手 |
+| API 契约独立版本演进 | 过度工程化风险(小团队不适用) |
+| 全链路可测试 | 构建时间较长,需要模块级缓存优化 |

+ 148 - 0
skills/ddd-skills/ddd-architecture-clean/references/02-usecase-ports.md

@@ -0,0 +1,148 @@
+# UseCase Input/Output Ports
+
+## Location: `{project}-usecase/port/input/` and `{project}-usecase/port/output/`
+
+The UseCase layer defines two types of ports:
+
+| Port Type | Location | Purpose | Direction |
+|-----------|----------|---------|-----------|
+| **Input Port** | `port/input/` | UseCase interfaces — what the app **offers** | Called by adapters (inward) |
+| **Output Port** | `port/output/` | Repository/Gateway interfaces — what the app **needs** | Implemented by adapters (outward) |
+
+## Input Port (UseCase Interface)
+
+```java
+package com.example.usecase.port.input;
+
+/**
+ * ★ Input Port — defines what the application offers.
+ * Each UseCase gets its own Input Port interface
+ * (Interface Segregation Principle).
+ */
+public interface CreateOrderUseCase {
+    /**
+     * @param input  UseCase-specific input data
+     * @return       UseCase-specific output data
+     */
+    CreateOrderOutput execute(CreateOrderInput input);
+}
+
+public interface PayOrderUseCase {
+    PayOrderOutput execute(PayOrderInput input);
+}
+
+public interface CancelOrderUseCase {
+    CancelOrderOutput execute(CancelOrderInput input);
+}
+```
+
+## Input DTOs (UseCase-specific)
+
+```java
+package com.example.usecase.dto.input;
+
+import com.example.core.valueobject.OrderId;
+import java.util.List;
+
+public record CreateOrderInput(
+    String customerId,
+    List<OrderItemInput> items
+) {
+    public record OrderItemInput(
+        String productId,
+        int quantity,
+        MoneyInput unitPrice
+    ) {}
+}
+
+public record PayOrderInput(
+    OrderId orderId,
+    String paymentMethodId
+) {}
+
+public record CancelOrderInput(
+    OrderId orderId,
+    String reason
+) {}
+```
+
+## Output DTOs (UseCase-specific)
+
+```java
+package com.example.usecase.dto.output;
+
+import com.example.core.valueobject.Money;
+import com.example.core.valueobject.OrderId;
+import com.example.core.valueobject.OrderStatus;
+
+public record CreateOrderOutput(
+    OrderId orderId,
+    Money totalAmount,
+    OrderStatus status
+) {}
+
+public record PayOrderOutput(
+    OrderId orderId,
+    OrderStatus status,
+    String transactionId
+) {}
+```
+
+## Output Port (Repository/Gateway Interface)
+
+```java
+package com.example.usecase.port.output;
+
+import com.example.core.valueobject.OrderId;
+import java.util.Optional;
+
+/**
+ * ★ Output Port — defines what the application needs
+ * from the outside world. Implemented by infrastructure layer.
+ */
+public interface OrderRepository {
+    Order save(Order order);
+    Optional<Order> findById(OrderId id);
+    void delete(OrderId id);
+}
+
+public interface PaymentGateway {
+    PaymentResult charge(Money amount, PaymentMethod method);
+    RefundResult refund(PaymentId paymentId, Money amount);
+}
+
+public interface EventPublisher {
+    void publish(DomainEvent event);
+    void publishAll(List<DomainEvent> events);
+}
+
+public interface NotificationPort {
+    void sendEmail(Email to, String subject, String body);
+}
+```
+
+## Port Design Rules
+
+| Rule | Description |
+|------|-------------|
+| **One UseCase = One Port** | Each UseCase gets its own Input Port interface |
+| **Technology-agnostic** | No framework types in port signatures |
+| **Domain types only** | Parameter types must be from Enterprise or simple Java types |
+| **No `@` annotations** | Ports are pure interfaces, no annotations |
+| **Output Ports reflect real needs** | Define exactly what the UseCase needs, not what the DB can do |
+
+## Clean Architecture Compatibility
+
+```yaml
+Clean Architecture:
+  Enterprise Layer: core/entity    (no interfaces, just business rules)
+  UseCase Layer:    usecase/port/   (Interfaces)
+                    usecase/interactor/ (Implementations)
+
+  Dependency Rule:
+    Controller (Adapter) → Input Port (UseCase interface)
+    Interactor (UseCase)  → Output Port (Repository interface)
+    Repository Impl (Infra) → implements Output Port
+```
+
+> **Key insight**: In Clean Architecture, the `Input Port` defines the contract for what a UseCase does, while the `Output Port` defines the contract for what the UseCase needs from outside. Both are owned by the UseCase layer.

+ 271 - 0
skills/ddd-skills/ddd-architecture-clean/references/03-interactors.md

@@ -0,0 +1,271 @@
+# UseCase Interactors
+
+## Location: `{project}-usecase/interactor/`
+
+**Interactors** are the implementations of Input Ports. They orchestrate the flow:
+1. Receive Input DTO
+2. Load/validate Enterprise entities
+3. Execute business behavior on entities
+4. Persist through Output Ports
+5. Publish domain events
+6. Return Output DTO
+
+## Key Rule
+
+> Interactors do NOT contain business logic. Business logic lives in Entity/Enterprise layer.
+> Interactors ORCHESTRATE — they call entities and ports.
+
+## Standard Interactor Template
+
+```java
+package com.example.usecase.interactor;
+
+import com.example.core.entity.Order;
+import com.example.core.exception.OrderDomainException;
+import com.example.core.valueobject.Money;
+import com.example.core.valueobject.OrderId;
+import com.example.usecase.dto.input.CreateOrderInput;
+import com.example.usecase.dto.output.CreateOrderOutput;
+import com.example.usecase.port.input.CreateOrderUseCase;
+import com.example.usecase.port.output.OrderRepository;
+import com.example.usecase.port.output.EventPublisher;
+import com.example.usecase.port.output.NotificationPort;
+
+import java.util.List;
+
+/**
+ * ★ Interactor — implements the Input Port.
+ * Pure orchestration, no business logic.
+ */
+public class CreateOrderInteractor implements CreateOrderUseCase {
+
+    private final OrderRepository orderRepository;
+    private final EventPublisher eventPublisher;
+    private final NotificationPort notificationPort;
+
+    // Constructor injection via framework (set up in Framework layer)
+    public CreateOrderInteractor(
+            OrderRepository orderRepository,
+            EventPublisher eventPublisher,
+            NotificationPort notificationPort) {
+        this.orderRepository = orderRepository;
+        this.eventPublisher = eventPublisher;
+        this.notificationPort = notificationPort;
+    }
+
+    @Override
+    public CreateOrderOutput execute(CreateOrderInput input) {
+        // 1. Create entity (Enterprise layer — encapsulates creation logic)
+        OrderId orderId = OrderId.generate();
+        Money total = calculateTotal(input.items());
+        Order order = new Order(orderId, total);
+
+        // 2. Add items
+        for (CreateOrderInput.OrderItemInput itemInput : input.items()) {
+            order.addItem(new OrderItem(
+                ProductId.of(itemInput.productId()),
+                itemInput.quantity(),
+                new Money(itemInput.unitPrice().amount(), Currency.getInstance(itemInput.unitPrice().currency()))
+            ));
+        }
+
+        // 3. Save through Output Port
+        Order saved = orderRepository.save(order);
+
+        // 4. Publish events (side effects)
+        eventPublisher.publishAll(order.domainEvents());
+        order.clearEvents();
+
+        // 5. Send notification (side effect through port)
+        notificationPort.sendEmail(
+            Email.of(input.customerId()),
+            "Order Created",
+            "Your order " + orderId.value() + " has been created."
+        );
+
+        // 6. Return Output DTO
+        return new CreateOrderOutput(
+            saved.id(),
+            saved.totalAmount(),
+            saved.status()
+        );
+    }
+
+    // Orchestration helper (NOT business logic)
+    private Money calculateTotal(List<CreateOrderInput.OrderItemInput> items) {
+        return items.stream()
+            .map(item -> new Money(
+                item.unitPrice().amount(),
+                Currency.getInstance(item.unitPrice().currency()))
+                .multiply(item.quantity()))
+            .reduce(Money.ZERO, Money::add);
+    }
+}
+```
+
+## Complex Interactor with Transaction
+
+```java
+public class PayOrderInteractor implements PayOrderUseCase {
+
+    private final OrderRepository orderRepository;
+    private final PaymentGateway paymentGateway;
+    private final EventPublisher eventPublisher;
+
+    public PayOrderInteractor(
+            OrderRepository orderRepository,
+            PaymentGateway paymentGateway,
+            EventPublisher eventPublisher) {
+        this.orderRepository = orderRepository;
+        this.paymentGateway = paymentGateway;
+        this.eventPublisher = eventPublisher;
+    }
+
+    @Override
+    public PayOrderOutput execute(PayOrderInput input) {
+        // 1. Load entity
+        Order order = orderRepository.findById(input.orderId())
+            .orElseThrow(() -> new OrderNotFoundException(input.orderId()));
+
+        // 2. Charge payment (through Output Port)
+        PaymentResult result = paymentGateway.charge(
+            order.totalAmount(),
+            PaymentMethod.fromId(input.paymentMethodId())
+        );
+
+        if (result.isFailed()) {
+            throw new PaymentFailedException(result.errorMessage());
+        }
+
+        // 3. Execute business behavior on entity
+        order.pay();
+
+        // 4. Save
+        orderRepository.save(order);
+
+        // 5. Publish events
+        eventPublisher.publishAll(order.domainEvents());
+        order.clearEvents();
+
+        // 6. Return result
+        return new PayOrderOutput(
+            order.id(),
+            order.status(),
+            result.transactionId()
+        );
+    }
+}
+```
+
+## Query Interactor (Read Model)
+
+```java
+public class GetOrderInteractor implements GetOrderUseCase {
+
+    private final OrderRepository orderRepository;
+
+    public GetOrderInteractor(OrderRepository orderRepository) {
+        this.orderRepository = orderRepository;
+    }
+
+    @Override
+    public GetOrderOutput execute(GetOrderInput input) {
+        return orderRepository.findById(input.orderId())
+            .map(order -> new GetOrderOutput(
+                order.id(),
+                order.status(),
+                order.totalAmount(),
+                order.items().stream()
+                    .map(item -> new GetOrderOutput.OrderItemOutput(
+                        item.productId().value(),
+                        item.quantity(),
+                        item.subtotal()
+                    )).toList()
+            ))
+            .orElseThrow(() -> new OrderNotFoundException(input.orderId()));
+    }
+}
+```
+
+## Testing Interactors
+
+```java
+class CreateOrderInteractorTest {
+
+    private InMemoryOrderRepository orderRepo;
+    private SpyEventPublisher eventPublisher;
+    private SpyNotificationPort notificationPort;
+    private CreateOrderInteractor interactor;
+
+    @BeforeEach
+    void setUp() {
+        orderRepo = new InMemoryOrderRepository();
+        eventPublisher = new SpyEventPublisher();
+        notificationPort = new SpyNotificationPort();
+        interactor = new CreateOrderInteractor(
+            orderRepo, eventPublisher, notificationPort);
+    }
+
+    @Test
+    void shouldCreateOrder() {
+        var input = new CreateOrderInput("CUST-001", List.of(
+            new OrderItemInput("PROD-001", 2, new MoneyInput("10.00", "USD"))
+        ));
+
+        var output = interactor.execute(input);
+
+        assertThat(output.status()).isEqualTo(OrderStatus.DRAFT);
+        assertThat(orderRepo.findById(output.orderId())).isPresent();
+        assertThat(eventPublisher.publishedEvents()).hasSize(1);
+    }
+
+    @Test
+    void shouldFailForInvalidInput() {
+        var input = new CreateOrderInput("CUST-001", List.of());
+        assertThatThrownBy(() -> interactor.execute(input))
+            .isInstanceOf(DomainException.class);
+    }
+}
+```
+
+## In-Memory Test Repositories
+
+```java
+package com.example.test;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+public class InMemoryOrderRepository implements OrderRepository {
+    private final Map<OrderId, Order> store = new HashMap<>();
+
+    @Override
+    public Order save(Order order) {
+        store.put(order.id(), order);
+        return order;
+    }
+
+    @Override
+    public Optional<Order> findById(OrderId id) {
+        return Optional.ofNullable(store.get(id));
+    }
+
+    @Override
+    public void delete(OrderId id) {
+        store.remove(id);
+    }
+
+    public void clear() { store.clear(); }
+}
+```
+
+## Interactor Anti-patterns
+
+| Anti-pattern | Problem | Solution |
+|---|---|---|
+| **Fat Interactor** | Contains business if/else logic | Move to Entity/Domain Service |
+| **Transaction in Interactor** | Mixes infrastructure concern | Use Framework @Transactional wrapper |
+| **Accessing external APIs directly** | Breaks dependency rule | Go through Output Ports |
+| **Catching and swallowing exceptions** | Hides errors | Let exceptions propagate or wrap in domain exception |
+| **Returning Entity directly** | Exposes internals | Always return Output DTO |

+ 314 - 0
skills/ddd-skills/ddd-architecture-clean/references/04-adapters.md

@@ -0,0 +1,314 @@
+# Interface Adapters Layer
+
+## Location: `{project}-adapter/`
+
+The **Interface Adapters** layer converts data between the UseCase layer (DTOs) and the outside world (HTTP, DB, MQ). It consists of:
+
+| Sub-module | Responsibility |
+|------------|---------------|
+| `controller/` | REST/gRPC controllers — receive HTTP, call Input Ports |
+| `presenter/` | Response format conversion — Output DTO → HTTP response |
+| `repository/` | DB implementation — implements Output Ports |
+| `gateway/` | External API implementation — implements Output Ports |
+| `converter/` | DTO/PO ↔ Entity/VO conversion |
+
+## Controller Template
+
+```java
+package com.example.adapter.controller;
+
+import com.example.usecase.port.input.CreateOrderUseCase;
+import com.example.usecase.port.input.GetOrderUseCase;
+import com.example.usecase.dto.input.CreateOrderInput;
+import com.example.usecase.dto.input.GetOrderInput;
+import com.example.usecase.dto.output.CreateOrderOutput;
+import com.example.usecase.dto.output.GetOrderOutput;
+import com.example.core.valueobject.OrderId;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.http.ResponseEntity;
+
+/**
+ * ★ Controller — Interface Adapter.
+ * Converts HTTP requests → UseCase calls → HTTP responses.
+ */
+@RestController
+@RequestMapping("/api/v1/orders")
+public class OrderController {
+
+    private final CreateOrderUseCase createOrderUseCase;
+    private final GetOrderUseCase getOrderUseCase;
+
+    public OrderController(
+            CreateOrderUseCase createOrderUseCase,
+            GetOrderUseCase getOrderUseCase) {
+        this.createOrderUseCase = createOrderUseCase;
+        this.getOrderUseCase = getOrderUseCase;
+    }
+
+    @PostMapping
+    public ResponseEntity<CreateOrderResponse> createOrder(
+            @Valid @RequestBody CreateOrderRequest request) {
+
+        // Convert HTTP request → UseCase Input DTO
+        CreateOrderInput input = request.toInput();
+
+        // Call UseCase through Input Port
+        CreateOrderOutput output = createOrderUseCase.execute(input);
+
+        // Convert Output DTO → HTTP response via Presenter
+        CreateOrderResponse response = CreateOrderResponse.from(output);
+
+        return ResponseEntity.status(201).body(response);
+    }
+
+    @GetMapping("/{id}")
+    public ResponseEntity<GetOrderResponse> getOrder(
+            @PathVariable String id) {
+
+        GetOrderInput input = new GetOrderInput(OrderId.of(id));
+        GetOrderOutput output = getOrderUseCase.execute(input);
+        GetOrderResponse response = GetOrderResponse.from(output);
+
+        return ResponseEntity.ok(response);
+    }
+}
+```
+
+## Request/Response DTOs
+
+```java
+package com.example.adapter.dto.request;
+
+import com.example.usecase.dto.input.CreateOrderInput;
+import jakarta.validation.constraints.*;
+import java.util.List;
+
+public record CreateOrderRequest(
+    @NotBlank String customerId,
+    @NotEmpty List<CreateOrderRequestItem> items
+) {
+    public CreateOrderInput toInput() {
+        return new CreateOrderInput(
+            this.customerId,
+            this.items.stream()
+                .map(i -> new CreateOrderInput.OrderItemInput(
+                    i.productId, i.quantity, new CreateOrderInput.MoneyInput(
+                        String.valueOf(i.unitPrice), "USD")))
+                .toList()
+        );
+    }
+
+    public record CreateOrderRequestItem(
+        @NotBlank String productId,
+        @Min(1) int quantity,
+        @NotNull Double unitPrice
+    ) {}
+}
+
+package com.example.adapter.dto.response;
+
+public record CreateOrderResponse(
+    String orderId,
+    String totalAmount,
+    String status
+) {
+    public static CreateOrderResponse from(CreateOrderOutput output) {
+        return new CreateOrderResponse(
+            output.orderId().value(),
+            output.totalAmount().amount().toPlainString(),
+            output.status().name()
+        );
+    }
+}
+```
+
+## Repository Implementation (Output Port Adapter)
+
+```java
+package com.example.adapter.repository;
+
+import com.example.core.entity.Order;
+import com.example.core.valueobject.OrderId;
+import com.example.usecase.port.output.OrderRepository;
+import com.example.adapter.converter.OrderPersistenceConverter;
+import jakarta.persistence.EntityNotFoundException;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.Optional;
+
+/**
+ * ★ Repository Implementation — Driven Adapter.
+ * Implements the Output Port defined in the UseCase layer.
+ */
+@Repository
+@Transactional
+public class JpaOrderRepository implements OrderRepository {
+
+    private final SpringDataOrderJpaRepository jpaRepo;
+    private final OrderPersistenceConverter converter;
+
+    public JpaOrderRepository(
+            SpringDataOrderJpaRepository jpaRepo,
+            OrderPersistenceConverter converter) {
+        this.jpaRepo = jpaRepo;
+        this.converter = converter;
+    }
+
+    @Override
+    public Order save(Order order) {
+        OrderEntity entity = converter.toPersistence(order);
+        OrderEntity saved = jpaRepo.save(entity);
+        return converter.toDomain(saved);
+    }
+
+    @Override
+    public Optional<Order> findById(OrderId id) {
+        return jpaRepo.findById(id.value())
+            .map(converter::toDomain);
+    }
+
+    @Override
+    public void delete(OrderId id) {
+        jpaRepo.deleteById(id.value());
+    }
+}
+```
+
+## Persistence Entity (Framework Layer)
+
+```java
+package com.example.adapter.repository.entity;
+
+import com.example.core.valueobject.OrderStatus;
+import jakarta.persistence.*;
+import java.math.BigDecimal;
+
+/**
+ * ★ JPA Entity — lives in the Adapter/Infrastructure layer.
+ * Separate from the Domain Entity. Framework annotations
+ * are confined to this layer.
+ */
+@Entity
+@Table(name = "orders")
+public class OrderEntity {
+
+    @Id
+    private String id;
+
+    @Enumerated(EnumType.STRING)
+    private OrderStatus status;
+
+    private BigDecimal totalAmount;
+    private String currency;
+
+    private String customerId;
+
+    @Version
+    private Long version;
+
+    // JPA requires default constructor
+    protected OrderEntity() {}
+
+    public OrderEntity(String id, OrderStatus status,
+                       BigDecimal totalAmount, String currency,
+                       String customerId) {
+        this.id = id;
+        this.status = status;
+        this.totalAmount = totalAmount;
+        this.currency = currency;
+        this.customerId = customerId;
+    }
+
+    // Getters and setters...
+}
+```
+
+## Persistence Converter
+
+```java
+package com.example.adapter.converter;
+
+import com.example.core.entity.Order;
+import com.example.core.valueobject.Money;
+import com.example.core.valueobject.OrderId;
+import com.example.core.valueobject.OrderStatus;
+import com.example.adapter.repository.entity.OrderEntity;
+import org.springframework.stereotype.Component;
+
+import java.util.Currency;
+
+@Component
+public class OrderPersistenceConverter {
+
+    public OrderEntity toPersistence(Order order) {
+        return new OrderEntity(
+            order.id().value(),
+            order.status(),
+            order.totalAmount().amount(),
+            order.totalAmount().currency().getCurrencyCode(),
+            order.customerId()  // assuming Order has customerId
+        );
+    }
+
+    public Order toDomain(OrderEntity entity) {
+        return new Order(
+            new OrderId(entity.getId()),
+            new Money(entity.getTotalAmount(),
+                Currency.getInstance(entity.getCurrency()))
+        );
+    }
+}
+```
+
+## External Gateway Adapter
+
+```java
+package com.example.adapter.gateway;
+
+import com.example.core.valueobject.Money;
+import com.example.usecase.port.output.PaymentGateway;
+import org.springframework.stereotype.Component;
+
+@Component
+public class StripePaymentGateway implements PaymentGateway {
+
+    private final StripeClient stripeClient;
+
+    public StripePaymentGateway(StripeClient stripeClient) {
+        this.stripeClient = stripeClient;
+    }
+
+    @Override
+    public PaymentResult charge(Money amount, PaymentMethod method) {
+        try {
+            StripePaymentIntent intent = stripeClient.paymentIntents.create(
+                PaymentIntentCreateParams.builder()
+                    .setAmount(amount.amount().longValue())
+                    .setCurrency(amount.currency().getCurrencyCode())
+                    .setPaymentMethod(method.id())
+                    .setConfirm(true)
+                    .build()
+            );
+            return PaymentResult.success(PaymentId.from(intent.getId()));
+        } catch (StripeException e) {
+            return PaymentResult.failed(e.getMessage());
+        }
+    }
+
+    @Override
+    public RefundResult refund(PaymentId paymentId, Money amount) {
+        // Implementation...
+        return null;
+    }
+}
+```
+
+## Adapter Anti-patterns
+
+| Anti-pattern | Problem | Solution |
+|---|---|---|
+| **Business logic in Controller** | Controller contains if/else business rules | Move to UseCase/Entity |
+| **Framework annotations in domain** | Domain knows about JPA/Spring | Keep domain POJO, annotations only in adapter |
+| **Repository returns Entity directly** | Breaks persistence mapping | Always convert PO ↔ Domain in adapter |
+| **Conversions in Controller** | Violates SRP | Use dedicated converter/assembler |

+ 359 - 0
skills/ddd-skills/ddd-architecture-clean/references/05-framework-config.md

@@ -0,0 +1,359 @@
+# Framework & Drivers Layer Configuration
+
+## Location: `{project}-framework/config/`
+
+The **Frameworks & Drivers** layer is the outermost layer — it wires everything together using dependency injection (Spring Boot), configures web/server settings, and bootstraps the application.
+
+## DI Configuration — Wiring the Layers
+
+```java
+package com.example.framework.config;
+
+import com.example.adapter.repository.JpaOrderRepository;
+import com.example.adapter.gateway.StripePaymentGateway;
+import com.example.core.entity.Order;
+import com.example.usecase.interactor.CreateOrderInteractor;
+import com.example.usecase.interactor.PayOrderInteractor;
+import com.example.usecase.interactor.GetOrderInteractor;
+import com.example.usecase.port.input.CreateOrderUseCase;
+import com.example.usecase.port.input.PayOrderUseCase;
+import com.example.usecase.port.input.GetOrderUseCase;
+import com.example.usecase.port.output.OrderRepository;
+import com.example.usecase.port.output.PaymentGateway;
+import com.example.usecase.port.output.EventPublisher;
+import com.example.usecase.port.output.NotificationPort;
+import com.example.adapter.gateway.RabbitMQEventPublisher;
+import com.example.adapter.gateway.EmailNotificationAdapter;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * ★ Framework Layer — Dependency Injection configuration.
+ * This is where the outermost layer wires all inner layers together.
+ * The Interactors and Entities know nothing about Spring.
+ */
+@Configuration
+public class UseCaseConfig {
+
+    // ── Output Port implementations (Adapters) ──
+    @Bean
+    public OrderRepository orderRepository(
+            JpaOrderRepository jpaOrderRepository) {
+        return jpaOrderRepository;    // Adapter implements Output Port
+    }
+
+    @Bean
+    public PaymentGateway paymentGateway(
+            StripePaymentGateway stripePaymentGateway) {
+        return stripePaymentGateway;
+    }
+
+    @Bean
+    public EventPublisher eventPublisher(
+            RabbitMQEventPublisher rabbitMQEventPublisher) {
+        return rabbitMQEventPublisher;
+    }
+
+    @Bean
+    public NotificationPort notificationPort(
+            EmailNotificationAdapter emailAdapter) {
+        return emailAdapter;
+    }
+
+    // ── UseCase Interactors (Application Business Rules) ──
+    @Bean
+    public CreateOrderUseCase createOrderUseCase(
+            OrderRepository orderRepository,
+            EventPublisher eventPublisher,
+            NotificationPort notificationPort) {
+        return new CreateOrderInteractor(
+            orderRepository, eventPublisher, notificationPort);
+    }
+
+    @Bean
+    public PayOrderUseCase payOrderUseCase(
+            OrderRepository orderRepository,
+            PaymentGateway paymentGateway,
+            EventPublisher eventPublisher) {
+        return new PayOrderInteractor(
+            orderRepository, paymentGateway, eventPublisher);
+    }
+
+    @Bean
+    public GetOrderUseCase getOrderUseCase(
+            OrderRepository orderRepository) {
+        return new GetOrderInteractor(orderRepository);
+    }
+}
+```
+
+## Web Configuration
+
+```java
+package com.example.framework.config.web;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class WebConfig implements WebMvcConfigurer {
+
+    @Bean
+    public CorsFilter corsFilter() {
+        CorsConfiguration config = new CorsConfiguration();
+        config.setAllowCredentials(true);
+        config.addAllowedOriginPattern("*");
+        config.addAllowedHeader("*");
+        config.addAllowedMethod("*");
+
+        UrlBasedCorsConfigurationSource source =
+            new UrlBasedCorsConfigurationSource();
+        source.registerCorsConfiguration("/api/**", config);
+        return new CorsFilter(source);
+    }
+}
+```
+
+## Security Configuration
+
+```java
+package com.example.framework.config.security;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+
+@Configuration
+@EnableWebSecurity
+public class SecurityConfig {
+
+    private final JwtAuthenticationFilter jwtFilter;
+
+    public SecurityConfig(JwtAuthenticationFilter jwtFilter) {
+        this.jwtFilter = jwtFilter;
+    }
+
+    @Bean
+    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
+        http
+            .csrf(csrf -> csrf.disable())
+            .authorizeHttpRequests(auth -> auth
+                .requestMatchers("/api/v1/auth/**").permitAll()
+                .requestMatchers("/api/v1/**").authenticated()
+                .anyRequest().permitAll()
+            )
+            .addFilterBefore(jwtFilter,
+                UsernamePasswordAuthenticationFilter.class);
+
+        return http.build();
+    }
+}
+```
+
+## Persistence Configuration
+
+```java
+package com.example.framework.config.persistence;
+
+import org.springframework.boot.autoconfigure.domain.EntityScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+@Configuration
+@EnableJpaRepositories(basePackages = "com.example.adapter.repository")
+@EntityScan(basePackages = "com.example.adapter.repository.entity")
+@EnableTransactionManagement
+public class PersistenceConfig {
+
+    // Spring Boot auto-configures DataSource from application.yml
+    // Additional JPA tuning can go here.
+}
+```
+
+## Application Entry Point
+
+```java
+package com.example.framework;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+/**
+ * ★ Application entry point — Framework Layer.
+ * Scans all layers for Spring-managed beans.
+ */
+@SpringBootApplication
+@ComponentScan(basePackages = {
+    "com.example.framework.config",
+    "com.example.adapter",
+    "com.example.usecase.interactor"
+})
+public class Application {
+
+    public static void main(String[] args) {
+        SpringApplication.run(Application.class, args);
+    }
+}
+```
+
+## Application Configuration
+
+```yaml
+# src/main/resources/application.yml
+spring:
+  datasource:
+    url: jdbc:postgresql://localhost:5432/orderdb
+    username: ${DB_USERNAME:app}
+    password: ${DB_PASSWORD:secret}
+  jpa:
+    hibernate:
+      ddl-auto: validate
+    show-sql: false
+    properties:
+      hibernate:
+        format_sql: true
+
+server:
+  port: 8080
+
+app:
+  payment:
+    stripe-api-key: ${STRIPE_API_KEY}
+  notification:
+    email-from: orders@example.com
+
+---
+
+spring:
+  config:
+    activate:
+      on-profile: test
+
+  datasource:
+    url: jdbc:h2:mem:testdb
+  jpa:
+    hibernate:
+      ddl-auto: create-drop
+```
+
+## Global Exception Handler (Adapter Layer)
+
+```java
+package com.example.adapter.presenter;
+
+import com.example.core.exception.DomainException;
+import com.example.usecase.exception.UseCaseException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import java.time.Instant;
+
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+
+    @ExceptionHandler(DomainException.class)
+    public ResponseEntity<ErrorResponse> handleDomain(DomainException ex) {
+        return ResponseEntity
+            .status(HttpStatus.UNPROCESSABLE_ENTITY)
+            .body(new ErrorResponse("DOMAIN_ERROR", ex.getMessage()));
+    }
+
+    @ExceptionHandler(UseCaseException.class)
+    public ResponseEntity<ErrorResponse> handleUseCase(UseCaseException ex) {
+        return ResponseEntity
+            .status(HttpStatus.BAD_REQUEST)
+            .body(new ErrorResponse("USE_CASE_ERROR", ex.getMessage()));
+    }
+
+    @ExceptionHandler(Exception.class)
+    public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) {
+        return ResponseEntity
+            .status(HttpStatus.INTERNAL_SERVER_ERROR)
+            .body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred"));
+    }
+
+    public record ErrorResponse(
+        String code,
+        String message,
+        Instant timestamp
+    ) {
+        public ErrorResponse(String code, String message) {
+            this(code, message, Instant.now());
+        }
+    }
+}
+```
+
+## Multi-Profile Configuration
+
+| Profile | Purpose | Database | External Services |
+|---------|---------|----------|-------------------|
+| `dev` | Development | H2 in-memory | Mock endpoints |
+| `test` | Automated tests | H2 file-based | WireMock stubs |
+| `staging` | Pre-production | PostgreSQL staging | Sandbox APIs |
+| `prod` | Production | PostgreSQL cluster | Live APIs |
+
+## Layer Diagram with DI Wiring
+
+```
+┌─ Framework (Spring Boot) ─────────────────────┐
+│  @Configuration beans wire everything together  │
+│  Application.java                              │
+│                                                  │
+│  ┌─ Adapter (Controller/Repository/Gateway) ─┐ │
+│  │  @RestController OrderController            │ │
+│  │  @Repository JpaOrderRepository           │ │
+│  │     ┌─ UseCase (Interactor + Ports) ──┐   │ │
+│  │     │  CreateOrderInteractor           │   │ │
+│  │     │  OrderRepository (interface)     │   │ │
+│  │     │  CreateOrderUseCase (interface)  │   │ │
+│  │     │     ┌─ Enterprise (Entity) ─┐   │   │ │
+│  │     │     │  Order.java          │   │   │ │
+│  │     │     │  Money.java          │   │   │ │
+│  │     │     └──────────────────────┘   │   │ │
+│  │     └─────────────────────────────────┘   │ │
+│  └───────────────────────────────────────────┘ │
+└────────────────────────────────────────────────┘
+```
+
+## Module Dependencies (Maven/Gradle)
+
+```xml
+<!-- pom.xml — multi-module project -->
+<modules>
+    <module>order-core</module>         <!-- Enterprise layer -->
+    <module>order-usecase</module>      <!-- UseCase layer -->
+    <module>order-adapter</module>      <!-- Adapter layer -->
+    <module>order-framework</module>    <!-- Framework layer -->
+</modules>
+
+<!-- order-framework/pom.xml depends on all inner layers -->
+<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-usecase</artifactId>
+</dependency>
+<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-adapter</artifactId>
+</dependency>
+```
+
+## Key Rules
+
+| Rule | Description |
+|------|-------------|
+| **No circular deps** | Framework can depend on Adapter, UseCase, Enterprise. Never the reverse. |
+| **DI Config owns composition** | Only Framework layer knows how all pieces fit together. |
+| **Profiles for environments** | Use Spring profiles to swap adapter implementations (e.g., MockPaymentGateway for test). |
+| **Secrets externalized** | API keys, DB passwords via env vars, never hardcoded. |

+ 294 - 0
skills/ddd-skills/ddd-architecture-clean/references/06-dependency-rules.md

@@ -0,0 +1,294 @@
+# Dependency Rules & ArchUnit Verification
+
+## The Golden Rule
+
+> **Source code dependencies must point only inward.**
+> Outer layers can depend on inner layers.
+> Inner layers never know about outer layers.
+
+Formally: `Enterprise → UseCase → Adapter → Framework`
+
+## Layer Dependency Matrix
+
+```
+                    Can depend on:
+Layer               Ent    UC     Adap   Fram
+────────────────────────────────────────────
+Enterprise (★)      ✓      ✗      ✗      ✗
+UseCase             ✓      ✓      ✗      ✗
+Adapter             ✓      ✓      ✓      ✗
+Framework           ✓      ✓      ✓      ✓
+
+Legend:
+  ✓ = allowed
+  ✗ = prohibited
+```
+
+## Concrete Rules for Java Projects
+
+```yaml
+Enterprise Layer:
+  Cannot import:  org.springframework.*, javax.persistence.*,
+                  com.example.usecase.*, com.example.adapter.*
+  Can import:     java.util.*, java.math.*, java.time.*
+  Package name:   com.example.core
+
+UseCase Layer:
+  Cannot import:  org.springframework.stereotype.*, javax.persistence.*,
+                  com.example.adapter.*, com.example.framework.*
+  Can import:     com.example.core.* (Enterprise)
+  Package name:   com.example.usecase
+
+Adapter Layer:
+  Cannot import:  com.example.framework.*
+  Can import:     com.example.core.*, com.example.usecase.*
+  Package names:  com.example.adapter.controller,
+                  com.example.adapter.repository,
+                  com.example.adapter.gateway
+
+Framework Layer:
+  Can import:     ALL layers
+  Package names:  com.example.framework.config
+```
+
+## ArchUnit Test — Automated Dependency Verification
+
+```java
+package com.example.framework.archunit;
+
+import com.tngtech.archunit.core.domain.JavaClasses;
+import com.tngtech.archunit.core.importer.ClassFileImporter;
+import com.tngtech.archunit.lang.ArchRule;
+import org.junit.jupiter.api.Test;
+
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
+import static com.tngtech.archunit.library.Architectures.*;
+
+/**
+ * ★ Automated Clean Architecture dependency verification.
+ * Fails the build if any layer violates the dependency rule.
+ */
+class CleanArchitectureTest {
+
+    private final JavaClasses classes = new ClassFileImporter()
+        .importPackages("com.example..");
+
+    // ── Layer Dependency Rules ──
+
+    @Test
+    void enterpriseLayerShouldNotDependOnOuterLayers() {
+        noClasses()
+            .that().resideInAnyPackage("com.example.core..")
+            .should().dependOnClassesThat()
+            .resideInAnyPackage(
+                "com.example.usecase..",
+                "com.example.adapter..",
+                "com.example.framework..",
+                "org.springframework..",
+                "jakarta.persistence.."
+            )
+            .check(classes);
+    }
+
+    @Test
+    void useCaseLayerShouldNotDependOnAdapterOrFramework() {
+        noClasses()
+            .that().resideInAnyPackage("com.example.usecase..")
+            .should().dependOnClassesThat()
+            .resideInAnyPackage(
+                "com.example.adapter..",
+                "com.example.framework..",
+                "org.springframework.stereotype..",
+                "jakarta.persistence.."
+            )
+            .check(classes);
+    }
+
+    @Test
+    void useCaseLayerShouldOnlyDependOnCore() {
+        classes()
+            .that().resideInAnyPackage("com.example.usecase..")
+            .should().onlyDependOnClassesThat()
+            .resideInAnyPackage(
+                "com.example.usecase..",
+                "com.example.core..",
+                "java..",
+                "java.time.."
+            )
+            .check(classes);
+    }
+
+    @Test
+    void adapterLayerShouldNotDependOnFramework() {
+        noClasses()
+            .that().resideInAnyPackage("com.example.adapter..")
+            .should().dependOnClassesThat()
+            .resideInAnyPackage("com.example.framework..")
+            .check(classes);
+    }
+
+    // ── Layer Architecture Verification ──
+
+    @Test
+    void shouldFollowCleanArchitecture() {
+        layeredArchitecture()
+            .consideringAllDependencies()
+
+            // Define layers
+            .layer("Enterprise")
+                .definedBy("com.example.core..")
+            .layer("UseCase")
+                .definedBy("com.example.usecase..")
+            .layer("Adapter")
+                .definedBy("com.example.adapter..")
+            .layer("Framework")
+                .definedBy("com.example.framework..")
+
+            // Define dependency constraints
+            .whereLayer("Enterprise")
+                .mayOnlyBeAccessedByLayers("UseCase", "Adapter", "Framework")
+            .whereLayer("UseCase")
+                .mayOnlyBeAccessedByLayers("Adapter", "Framework")
+            .whereLayer("Adapter")
+                .mayOnlyBeAccessedByLayers("Framework")
+
+            .check(classes);
+    }
+
+    // ── Specific Anti-pattern Checks ──
+
+    @Test
+    void domainShouldNotUseSpringAnnotations() {
+        // Domain entities must be plain POJOs
+        noClasses()
+            .that().resideInAnyPackage("com.example.core..")
+            .should().beAnnotatedWith("org.springframework.stereotype.Service")
+            .orShould().beAnnotatedWith("org.springframework.stereotype.Component")
+            .orShould().beAnnotatedWith("org.springframework.web.bind.annotation.RestController")
+            .orShould().beAnnotatedWith("jakarta.persistence.Entity")
+            .check(classes);
+    }
+
+    @Test
+    void useCaseInteractorsShouldHaveProperSuffix() {
+        classes()
+            .that().resideInAnyPackage("com.example.usecase.interactor..")
+            .should().haveSimpleNameEndingWith("Interactor")
+            .orShould().haveSimpleNameEndingWith("Service")
+            .check(classes);
+    }
+
+    @Test
+    void useCasePortsShouldBeInterfaces() {
+        classes()
+            .that().resideInAnyPackage("com.example.usecase.port..")
+            .should().beInterfaces()
+            .check(classes);
+    }
+
+    // ── Naming Conventions ──
+
+    @Test
+    void entityClassesShouldNotHoldJpaAnnotations() {
+        noClasses()
+            .that().resideInAnyPackage("com.example.core.entity..")
+            .should().beAnnotatedWith("jakarta.persistence.Entity")
+            .check(classes);
+    }
+
+    @Test
+    void repositoryImplementationsShouldBeInAdapterPackage() {
+        classes()
+            .that().haveSimpleNameEndingWith("RepositoryImpl")
+            .or().haveSimpleNameEndingWith("JpaRepository")
+            .or().haveSimpleNameEndingWith("MyBatisRepository")
+            .should().resideInAnyPackage("com.example.adapter.repository..")
+            .check(classes);
+    }
+}
+```
+
+## Adding ArchUnit to Your Build
+
+```xml
+<!-- Maven dependency -->
+<dependency>
+    <groupId>com.tngtech.archunit</groupId>
+    <artifactId>archunit-junit5</artifactId>
+    <version>1.3.0</version>
+    <scope>test</scope>
+</dependency>
+```
+
+```groovy
+// Gradle
+testImplementation 'com.tngtech.archunit:archunit-junit5:1.3.0'
+```
+
+## Module Dependency Rules (Multi-Module Maven/Gradle)
+
+```xml
+<!-- order-core/pom.xml — no dependencies on other modules -->
+<dependency>
+    <groupId>org.apache.commons</groupId>
+    <artifactId>commons-lang3</artifactId>
+</dependency>
+
+<!-- order-usecase/pom.xml — depends on core only -->
+<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-core</artifactId>
+</dependency>
+
+<!-- order-adapter/pom.xml — depends on usecase and core -->
+<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-usecase</artifactId>
+</dependency>
+<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-core</artifactId>
+</dependency>
+<dependency>
+    <groupId>org.springframework.boot</groupId>
+    <artifactId>spring-boot-starter-web</artifactId>
+</dependency>
+<dependency>
+    <groupId>org.springframework.boot</groupId>
+    <artifactId>spring-boot-starter-data-jpa</artifactId>
+</dependency>
+
+<!-- order-framework/pom.xml — depends on all -->
+<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>order-adapter</artifactId>
+</dependency>
+```
+
+## CI Integration
+
+```yaml
+# .github/workflows/architecture-check.yml
+name: Architecture Check
+on: [push, pull_request]
+jobs:
+  archunit:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - name: Set up JDK 21
+        uses: actions/setup-java@v4
+        with:
+          java-version: '21'
+      - name: Run ArchUnit Tests
+        run: ./mvnw test -pl order-framework -Dtest=CleanArchitectureTest
+```
+
+## Violation Examples
+
+| Violation | Example | Fix |
+|-----------|---------|-----|
+| Entity uses `@Entity` | `com.example.core.entity.Order` has `@Entity` | Move annotation to Adapter's `OrderEntity` |
+| UseCase imports `@Autowired` | `CreateOrderInteractor` uses `@Autowired` | Remove; inject via constructor in Framework config |
+| Adapter imports Framework | `JpaOrderRepository` imports `com.example.framework.config.*` | Remove dependency |
+| Core imports UseCase | `Order.java` imports `CreateOrderInput` | Enterprise must not know about UseCases |

+ 348 - 0
skills/ddd-skills/ddd-architecture-clean/references/07-testing-strategy.md

@@ -0,0 +1,348 @@
+# Testing Strategy for Clean Architecture
+
+## Pyramid Overview
+
+```
+         ╱╲
+        ╱ E2E ╲              Framework Layer
+       ╱────────╲            Full request → response
+      ╱Integration╲
+     ╱──────────────╲        Adapter Layer
+    ╱  Unit + Mock  ╲
+   ╱──────────────────╲      UseCase Layer
+  ╱    Pure Unit       ╲
+ ╱────────────────────────╲  Enterprise Layer
+╱                          ╲ Zero mocking needed
+```
+
+## Testing by Layer
+
+### Enterprise Layer — Pure Unit Tests
+
+```java
+class OrderTest {
+
+    @Test
+    void shouldCreateOrderWithDraftStatus() {
+        Order order = new Order(OrderId.generate(), Money.ZERO);
+        assertThat(order.status()).isEqualTo(OrderStatus.DRAFT);
+    }
+
+    @Test
+    void shouldTransitionToPaid() {
+        Order order = new Order(OrderId.generate(), Money.ZERO);
+        order.pay();
+        assertThat(order.status()).isEqualTo(OrderStatus.PAID);
+    }
+
+    @Test
+    void shouldNotPayCancelledOrder() {
+        Order order = new Order(OrderId.generate(), Money.ZERO);
+        order.cancel();
+        assertThatThrownBy(order::pay)
+            .isInstanceOf(OrderDomainException.class)
+            .hasMessageContaining("cannot transition");
+    }
+
+    @Test
+    void shouldCalculateTotalFromItems() {
+        Order order = new Order(OrderId.generate(), Money.ZERO);
+        order.addItem(new OrderItem("PROD-1", 2, new Money("50.00")));
+        order.addItem(new OrderItem("PROD-2", 1, new Money("30.00")));
+        assertThat(order.calculateTotal()).isEqualTo(new Money("130.00"));
+    }
+
+    @Test
+    void shouldEmitDomainEvents() {
+        Order order = new Order(OrderId.generate(), Money.ZERO);
+        order.pay();
+        assertThat(order.domainEvents())
+            .hasSize(2) // Created + Paid
+            .anyMatch(e -> e instanceof OrderCreatedEvent)
+            .anyMatch(e -> e instanceof OrderPaidEvent);
+    }
+}
+```
+
+### UseCase Layer — Mock Output Ports
+
+```java
+class CreateOrderInteractorTest {
+
+    private InMemoryOrderRepository orderRepo;
+    private SpyEventPublisher eventPublisher;
+    private SpyNotificationPort notificationPort;
+    private CreateOrderInteractor interactor;
+
+    @BeforeEach
+    void setUp() {
+        orderRepo = new InMemoryOrderRepository();
+        eventPublisher = new SpyEventPublisher();
+        notificationPort = new SpyNotificationPort();
+        interactor = new CreateOrderInteractor(
+            orderRepo, eventPublisher, notificationPort);
+    }
+
+    @Test
+    void shouldCreateOrderSuccessfully() {
+        CreateOrderInput input = new CreateOrderInput(
+            "CUST-001",
+            List.of(new OrderItemInput("PROD-001", 2, new MoneyInput("10.00", "USD")))
+        );
+
+        CreateOrderOutput output = interactor.execute(input);
+
+        assertThat(output.status()).isEqualTo(OrderStatus.DRAFT);
+        assertThat(output.totalAmount()).isEqualTo(new Money("20.00", "USD"));
+    }
+
+    @Test
+    void shouldPersistOrder() {
+        CreateOrderInput input = validInput();
+        CreateOrderOutput output = interactor.execute(input);
+
+        Order saved = orderRepo.findById(output.orderId()).orElseThrow();
+        assertThat(saved.status()).isEqualTo(OrderStatus.DRAFT);
+    }
+
+    @Test
+    void shouldPublishDomainEvents() {
+        CreateOrderInput input = validInput();
+        interactor.execute(input);
+
+        assertThat(eventPublisher.publishedEvents())
+            .hasSize(1)
+            .allMatch(e -> e instanceof OrderCreatedEvent);
+    }
+
+    @Test
+    void shouldSendNotification() {
+        CreateOrderInput input = validInput();
+        interactor.execute(input);
+
+        assertThat(notificationPort.sentEmails()).hasSize(1);
+    }
+
+    @Test
+    void shouldFailForEmptyOrder() {
+        CreateOrderInput input = new CreateOrderInput("CUST-001", List.of());
+        assertThatThrownBy(() -> interactor.execute(input))
+            .isInstanceOf(DomainException.class);
+    }
+
+    private CreateOrderInput validInput() {
+        return new CreateOrderInput(
+            "CUST-001",
+            List.of(new OrderItemInput("PROD-001", 1, new MoneyInput("10.00", "USD")))
+        );
+    }
+}
+```
+
+### PayOrderInteractor Test
+
+```java
+class PayOrderInteractorTest {
+
+    private InMemoryOrderRepository orderRepo;
+    private SpyPaymentGateway paymentGateway;
+    private SpyEventPublisher eventPublisher;
+    private PayOrderInteractor interactor;
+
+    @BeforeEach
+    void setUp() {
+        orderRepo = new InMemoryOrderRepository();
+        paymentGateway = new SpyPaymentGateway();
+        eventPublisher = new SpyEventPublisher();
+        interactor = new PayOrderInteractor(
+            orderRepo, paymentGateway, eventPublisher);
+    }
+
+    @Test
+    void shouldPayOrderSuccessfully() {
+        Order order = givenCreatedOrder();
+        PayOrderOutput output = interactor.execute(
+            new PayOrderInput(order.id(), "pm_card_visa"));
+
+        assertThat(output.status()).isEqualTo(OrderStatus.PAID);
+        assertThat(output.transactionId()).isNotBlank();
+    }
+
+    @Test
+    void shouldFailWhenPaymentDeclined() {
+        Order order = givenCreatedOrder();
+        paymentGateway.shouldFail(true);
+
+        assertThatThrownBy(() -> interactor.execute(
+            new PayOrderInput(order.id(), "pm_card_declined")))
+            .isInstanceOf(PaymentFailedException.class);
+    }
+
+    private Order givenCreatedOrder() {
+        Order order = new Order(OrderId.generate(), new Money("99.00"));
+        orderRepo.save(order);
+        return order;
+    }
+}
+```
+
+### Adapter Layer — Integration Tests
+
+```java
+@SpringBootTest
+@AutoConfigureMockMvc
+class OrderControllerTest {
+
+    @Autowired
+    private MockMvc mockMvc;
+
+    @Autowired
+    private OrderRepository orderRepository;
+    // Uses in-memory test implementation via @Profile("test")
+
+    @Test
+    void shouldCreateOrder() throws Exception {
+        String requestJson = """
+            {
+                "customerId": "CUST-001",
+                "items": [
+                    {"productId": "PROD-001", "quantity": 1, "unitPrice": 10.00}
+                ]
+            }
+            """;
+
+        mockMvc.perform(post("/api/v1/orders")
+                .contentType(MediaType.APPLICATION_JSON)
+                .content(requestJson))
+            .andExpect(status().isCreated())
+            .andExpect(jsonPath("$.orderId").isNotEmpty())
+            .andExpect(jsonPath("$.status").value("DRAFT"));
+    }
+
+    @Test
+    void shouldGetOrder() throws Exception {
+        // Arrange: create order first
+        CreateOrderOutput output = givenOrderExists();
+
+        mockMvc.perform(get("/api/v1/orders/{id}", output.orderId().value()))
+            .andExpect(status().isOk())
+            .andExpect(jsonPath("$.status").value("DRAFT"));
+    }
+
+    @Test
+    void shouldReturn404ForUnknownOrder() throws Exception {
+        mockMvc.perform(get("/api/v1/orders/UNKNOWN"))
+            .andExpect(status().isNotFound());
+    }
+
+    private CreateOrderOutput givenOrderExists() {
+        CreateOrderInput input = new CreateOrderInput(
+            "CUST-001",
+            List.of(new OrderItemInput("PROD-001", 1, new MoneyInput("10.00", "USD"))));
+        return createOrderInteractor.execute(input);
+    }
+}
+```
+
+### Repository Integration Test
+
+```java
+@DataJpaTest
+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
+@ActiveProfiles("test")
+class JpaOrderRepositoryTest {
+
+    @Autowired
+    private SpringDataOrderJpaRepository jpaRepo;
+
+    private JpaOrderRepository repository;
+
+    @BeforeEach
+    void setUp() {
+        repository = new JpaOrderRepository(jpaRepo, new OrderPersistenceConverter());
+    }
+
+    @Test
+    void shouldSaveAndFindOrder() {
+        Order order = new Order(OrderId.generate(), Money.ZERO);
+        repository.save(order);
+
+        Optional<Order> found = repository.findById(order.id());
+        assertThat(found).isPresent();
+        assertThat(found.get().status()).isEqualTo(OrderStatus.DRAFT);
+    }
+}
+```
+
+## Test Double Recommendations
+
+| Test Double | Layer | Purpose |
+|---|---|---|
+| **InMemoryRepository** | UseCase tests | Fast, reliable repository mock |
+| **SpyEventPublisher** | UseCase tests | Verify events were published |
+| **StubPaymentGateway** | UseCase tests | Control payment outcomes |
+| **MockMvc** | Adapter tests | Controller HTTP integration |
+| **Testcontainers** | Adapter tests | Real DB repository tests |
+| **WireMock** | Adapter tests | External API gateway tests |
+
+## In-Memory Test Doubles
+
+```java
+public class InMemoryOrderRepository implements OrderRepository {
+    private final Map<OrderId, Order> store = new HashMap<>();
+
+    @Override
+    public Order save(Order order) {
+        store.put(order.id(), order);
+        return order;
+    }
+
+    @Override
+    public Optional<Order> findById(OrderId id) {
+        return Optional.ofNullable(store.get(id));
+    }
+
+    @Override
+    public void delete(OrderId id) {
+        store.remove(id);
+    }
+
+    public void clear() { store.clear(); }
+}
+
+public class SpyEventPublisher implements EventPublisher {
+    private final List<DomainEvent> events = new ArrayList<>();
+
+    @Override
+    public void publish(DomainEvent event) {
+        events.add(event);
+    }
+
+    @Override
+    public void publishAll(List<DomainEvent> events) {
+        this.events.addAll(events);
+    }
+
+    public List<DomainEvent> publishedEvents() { return Collections.unmodifiableList(events); }
+    public void clear() { events.clear(); }
+}
+```
+
+## Coverage Targets
+
+| Layer | Coverage Target | Testing Focus |
+|---|---|---|
+| Enterprise | > 95% | Entity behaviors, state transitions, invariants |
+| UseCase | > 90% | Orchestration logic, port interaction, error paths |
+| Adapter | > 80% | HTTP mapping, persistence mapping, gateway calls |
+| Framework | > 70% | DI wiring, configuration, security filters |
+
+## Testing Anti-patterns
+
+| Anti-pattern | Problem | Fix |
+|---|---|---|
+| **Spring Boot test for Entity** | Slow, framework-dependent | Pure JUnit test |
+| **Mocking everything** | Brittle tests, false confidence | Use InMemory doubles for repos |
+| **Testing private methods** | Tests tied to implementation | Test through public behavior |
+| **No error path tests** | Code works only in happy path | Test domain exceptions, payment failures |
+| **Over-mocking** | Tests mock too many dependencies | Integration test through adapter |

+ 371 - 0
skills/ddd-skills/ddd-architecture-clean/references/08-migration-guide.md

@@ -0,0 +1,371 @@
+# Migration Guide: Layered Architecture → Clean Architecture
+
+## Overview
+
+Migrating from traditional 3-layer architecture (Controller → Service → Repository) to Clean Architecture (Enterprise → UseCase → Adapter → Framework) is a gradual process. This guide provides a step-by-step approach using the **Strangler Fig pattern**.
+
+## Migration Complexity Assessment
+
+```
+Assessment Score:
+  Low (1-5):   Direct migration, low risk
+  Medium (6-10): Incremental migration, moderate risk
+  High (11-15):  Phased migration over weeks/months
+```
+
+| Factor | Score | Assessment |
+|--------|-------|------------|
+| Codebase size | 1 (< 50K) / 2 (50-200K) / 3 (> 200K) | ____ |
+| Test coverage | 1 (> 80%) / 2 (50-80%) / 3 (< 50%) | ____ |
+| Team experience | 1 (Has Clean Architecture exp) / 2 (Has DDD exp) / 3 (New to DDD) | ____ |
+| Business criticality | 1 (Low) / 2 (Medium) / 3 (High) | ____ |
+| External dependencies | 1 (Few) / 2 (Moderate) / 3 (Many) | ____ |
+| **Total** | | ____ / 15 |
+
+## Migration Phases
+
+### Phase 1: Preparation (1-2 weeks)
+
+**Goals**: Understand current code, set up ArchUnit, add test coverage.
+
+```yaml
+Steps:
+  1. Map current architecture:
+     - Identify current layers and their responsibilities
+     - Document existing dependency directions
+     - Identify anti-patterns (fat services, anemic models)
+
+  2. Add ArchUnit tests:
+     - Tag existing violations with @ArchIgnore
+     - Prevent new violations
+     - Track violation count over time
+
+  3. Add critical tests:
+     - Add integration tests for core business flows
+     - Ensure current behavior is captured before refactoring
+
+  4. Set up multi-module project:
+     - Create Maven/Gradle modules: core, usecase, adapter, framework
+     - Configure module dependencies following Clean Architecture rules
+```
+
+### Phase 2: Extract Enterprise Layer (1-2 weeks)
+
+**Goals**: Identify and extract core business entities and rules.
+
+```
+Before:                                After:
+OrderService.java                      order-core/
+  ├── createOrder()                        ├── entity/
+  ├── payOrder()                           │   ├── Order.java
+  └── cancelOrder()                        │   ├── OrderItem.java
+ProcessPaymentService.java                 ├── valueobject/
+  └── processPayment()                     │   ├── OrderId.java
+Order.java                                 │   ├── Money.java
+  ├── Long id                              │   └── OrderStatus.java
+  ├── String status                        ├── exception/
+  └── getters/setters                      │   └── OrderDomainException.java
+                                           └── event/
+                                               ├── DomainEvent.java
+                                               ├── OrderCreatedEvent.java
+                                               └── OrderPaidEvent.java
+```
+
+```java
+// Step 1: Make Order a rich domain model (was anemic)
+// BEFORE
+public class Order {
+    private Long id;
+    private String status; // String! Not type-safe
+    // only getters/setters
+}
+
+// AFTER
+public class Order {
+    private final OrderId id;
+    private OrderStatus status; // Value Object!
+
+    public void pay() {
+        if (!status.canPay()) {
+            throw new OrderDomainException("Cannot pay order in status: " + status);
+        }
+        this.status = OrderStatus.PAID;
+        addDomainEvent(new OrderPaidEvent(this.id));
+    }
+}
+```
+
+### Phase 3: Extract UseCase Layer (1-2 weeks)
+
+**Goals**: Define Input/Output ports, create Interactors.
+
+```java
+// Step 1: Define ports
+// order-usecase/src/main/java/.../port/input/CreateOrderUseCase.java
+public interface CreateOrderUseCase {
+    CreateOrderOutput execute(CreateOrderInput input);
+}
+
+// Step 2: Move orchestration from old Service to Interactor
+// BEFORE
+@Service
+public class OrderService {
+    @Autowired private OrderRepository orderRepo;
+    @Autowired private PaymentClient paymentClient;
+
+    @Transactional
+    public OrderDTO createOrder(CreateOrderRequest req) {
+        // ... 50 lines of mixed orchestration + business logic
+    }
+}
+
+// AFTER
+public class CreateOrderInteractor implements CreateOrderUseCase {
+    private final OrderRepository orderRepo;
+    private final PaymentGateway paymentGateway;
+    private final EventPublisher eventPublisher;
+
+    @Override
+    public CreateOrderOutput execute(CreateOrderInput input) {
+        // Pure orchestration — business logic is in Enterprise entities
+        OrderId orderId = OrderId.generate();
+        Order order = new Order(orderId, Money.ZERO);
+
+        input.items().forEach(item ->
+            order.addItem(OrderItem.create(item)));
+
+        Order saved = orderRepo.save(order);
+        eventPublisher.publishAll(order.domainEvents());
+        order.clearEvents();
+
+        return CreateOrderOutput.from(saved);
+    }
+}
+```
+
+### Phase 4: Extract Adapter Layer (1-2 weeks)
+
+**Goals**: Move implementation details to adapters.
+
+```java
+// Step 1: Extract repository implementation
+// BEFORE — mixed with domain
+@Repository
+public class OrderRepository {
+    @PersistenceContext
+    private EntityManager em;
+
+    public Order findById(Long id) {
+        OrderEntity entity = em.find(OrderEntity.class, id);
+        // conversion logic here
+    }
+}
+
+// AFTER — adapter implements output port
+@Repository
+public class JpaOrderRepository implements OrderRepository {
+    private final SpringDataOrderJpaRepository jpaRepo;
+    private final OrderPersistenceConverter converter;
+
+    @Override
+    public Order findById(OrderId id) {
+        return jpaRepo.findById(id.value())
+            .map(converter::toDomain)
+            .orElseThrow(() -> new OrderNotFoundException(id));
+    }
+}
+
+// Step 2: Extract controller
+@RestController
+@RequestMapping("/api/v1/orders")
+public class OrderController {
+    private final CreateOrderUseCase createOrderUseCase;
+
+    @PostMapping
+    public ResponseEntity<CreateOrderResponse> create(
+            @RequestBody CreateOrderRequest request) {
+        CreateOrderInput input = request.toInput();
+        CreateOrderOutput output = createOrderUseCase.execute(input);
+        return ResponseEntity.status(201)
+            .body(CreateOrderResponse.from(output));
+    }
+}
+```
+
+### Phase 5: DI Assembly & Verification (1 week)
+
+**Goals**: Wire everything through Framework layer, verify architecture.
+
+```java
+@Configuration
+public class UseCaseConfig {
+    @Bean
+    public CreateOrderUseCase createOrderUseCase(
+            OrderRepository orderRepository,
+            PaymentGateway paymentGateway,
+            EventPublisher eventPublisher) {
+        return new CreateOrderInteractor(
+            orderRepository, paymentGateway, eventPublisher);
+    }
+}
+```
+
+## Migration Patterns
+
+### Strangler Fig Pattern
+
+```
+Gradual replacement per UseCase:
+
+Phase 2:                     Phase 3-4:                     Phase 5:
+┌──────────────────┐        ┌──────────────────┐           ┌──────────────────┐
+│ Old OrderService │        │ Old OrderService │           │ Old OrderService │
+│ (still handles   │        │ (handles 50%     │           │ (removed!)       │
+│  all use cases)  │        │  of use cases)   │           │                  │
+└──────────────────┘        └──────────────────┘           └──────────────────┘
+       │                            │                              │
+       │ CreateOrder → new          │ CreateOrder → new            │ ALL → new
+       │ PayOrder → old             │ PayOrder → new               │
+                                    │ CancelOrder → old            │
+```
+
+### Branch by Abstraction
+
+```java
+// 1. Create abstraction interface
+public interface OrderServiceFacade {
+    OrderDTO createOrder(CreateOrderRequest req);
+}
+
+// 2. Implement both old and new
+public class LegacyOrderService implements OrderServiceFacade { /* old impl */ }
+public class CleanOrderService implements OrderServiceFacade { /* new impl */ }
+
+// 3. Toggle with feature flag
+@Component
+public class OrderServiceRouter implements OrderServiceFacade {
+    private final LegacyOrderService legacy;
+    private final CleanOrderService clean;
+
+    public OrderDTO createOrder(CreateOrderRequest req) {
+        if (FeatureFlags.USE_CLEAN_ARCH_FOR_ORDERS) {
+            return clean.createOrder(req);
+        }
+        return legacy.createOrder(req);
+    }
+}
+
+// 4. Remove feature flag and legacy code when confident
+```
+
+## Common Migration Scenarios
+
+### Scenario 1: Fat Service → Multiple Interactors
+
+```
+ORDER SERVICE (500+ lines, all logic in one class)
+├── createOrder() → CreateOrderInteractor
+├── payOrder() → PayOrderInteractor
+├── cancelOrder() → CancelOrderInteractor
+├── getOrder() → GetOrderInteractor
+└── searchOrders() → SearchOrdersInteractor
+```
+
+### Scenario 2: Anemic Entity → Rich Domain Model
+
+```java
+// BEFORE — anemic model
+public class Order {
+    private Long id;
+    private String status;       // string comparison everywhere!
+    private BigDecimal amount;   // no currency!
+
+    public void setStatus(String status) { this.status = status; }
+}
+
+// AFTER — rich domain model
+public class Order {
+    private final OrderId id;
+    private OrderStatus status;  // value object!
+    private Money amount;        // value object with currency!
+
+    public void pay() {
+        if (!status.canTransitionTo(OrderStatus.PAID)) {
+            throw new OrderDomainException("...");
+        }
+        this.status = OrderStatus.PAID;
+        addDomainEvent(new OrderPaidEvent(this.id));
+    }
+}
+```
+
+### Scenario 3: Direct DB Access → Repository Pattern
+
+```java
+// BEFORE — Service directly accesses DB
+@Service
+public class OrderService {
+    @Autowired
+    private JdbcTemplate jdbc;
+
+    public OrderDTO getOrder(Long id) {
+        return jdbc.queryForObject(
+            "SELECT * FROM orders WHERE id = ?",
+            orderRowMapper, id);
+    }
+}
+
+// AFTER — Repository as port interface
+public class GetOrderInteractor implements GetOrderUseCase {
+    private final OrderRepository orderRepo; // interface!
+
+    @Override
+    public GetOrderOutput execute(GetOrderInput input) {
+        return orderRepo.findById(input.orderId())
+            .map(order -> new GetOrderOutput(...))
+            .orElseThrow(() -> new OrderNotFoundException(input.orderId()));
+    }
+}
+```
+
+## Validation Checklist
+
+```
+Before deployment:
+  □ ArchUnit tests pass for all layers
+  □ No Enterprise layer imports Spring/JPA/Jackson
+  □ No UseCase layer imports Adapter/Spring Web
+  □ Each UseCase has its own Input Port interface
+  □ Core business rules tested independently
+  □ Test coverage >= 80% for Enterprise, >= 70% for UseCase
+  □ All old Service classes marked @Deprecated
+  □ Feature flag ready for rollback
+  □ Performance benchmark — no regression
+
+After migration:
+  □ Old code removed
+  □ ArchUnit in CI pipeline
+  □ Team trained on Clean Architecture
+  □ Documentation updated
+  □ Migration documented in ADR
+```
+
+## Rollback Plan
+
+If issues arise during migration:
+
+1. **Toggle feature flag** → switch back to old implementation
+2. **Fix issues** while production runs on old code
+3. **Retry migration** with fixes applied
+4. **Run both in parallel** for critical use cases during transition phase
+
+## Time Estimates
+
+| Phase | Small (< 50K LOC) | Medium (50-200K) | Large (> 200K) |
+|-------|:---:|:---:|:---:|
+| Preparation | 1 week | 2 weeks | 3 weeks |
+| Extract Enterprise | 1 week | 2 weeks | 4 weeks |
+| Extract UseCase | 1 week | 2 weeks | 4 weeks |
+| Extract Adapter | 1 week | 2 weeks | 3 weeks |
+| DI + Verification | 0.5 week | 1 week | 2 weeks |
+| **Total** | **4.5 weeks** | **9 weeks** | **16 weeks** |

+ 89 - 0
skills/ddd-skills/ddd-architecture-clean/references/09-architecture-principles.md

@@ -0,0 +1,89 @@
+# 整洁架构核心原理详解
+
+> 本文包含 SKILL.md 主文档中移入的详细架构原理内容,供深度阅读。
+
+## 四层结构
+
+| 层(外→内) | 职责 | 依赖方向 |
+|:---|------|------|
+| Frameworks & Drivers | Web 框架、DB、UI、DI 配置 | → Adapter |
+| Interface Adapters | Controller、Gateway、Presenter、Repository Impl | → UseCase |
+| Application Business Rules | UseCase Interactor(编排实体+端口调用) | → Enterprise |
+| Enterprise Business Rules | Entity、ValueObject、DomainEvent、业务规则 ★ | 无依赖 |
+
+## 依赖规则(Gold Rule)
+
+> 源码依赖只能指向内层。Enterprise 是中心,Framework 是最外圈。
+
+```
+Enterprise ← UseCase ← Adapter ← Framework
+   (纯POJO)  (Port+Interactor) (转换+实现) (DI配置+启动)
+```
+
+## 架构对比
+
+| 维度 | 整洁架构 | 六边形 | 洋葱 | COLA v5 |
+|------|:---:|:---:|:---:|:---:|
+| 核心概念 | UseCase + Entity | Port + Adapter | Domain 同心圆 | 菱形架构 |
+| 层数 | 4 层 | 3 层(核心+端口+适配器) | 3+ 层 | 4 层 |
+| 抽象层级 | 最高 | 高 | 高 | 中 |
+| 学习成本 | ★★★ | ★★★ | ★★★ | ★★☆ |
+| 适用场景 | 大型企业级 UseCase 驱动 | 多入口微服务 | 基础设施频繁变更 | 国内 Spring Boot 生态 |
+| 模块隔离 | 极严格 | 严格 | 严格 | 严格 |
+| 代表作 | Robert C. Martin | Alistair Cockburn | Jeffrey Palermo | 阿里 COLA |
+
+## 四层间数据流转
+
+```
+HTTP Request
+  → Controller (Adapter) 接收, 转为 Input DTO
+    → UseCase Port (interface) 定义 Input
+      → Interactor (UseCase Impl) 编排:
+          1. 调 Entity 执行业务规则
+          2. 调 Output Port 持久化/发消息
+          3. 发布领域事件
+    → UseCase Port 返回 Output DTO
+  → Presenter/Response (Adapter) 转为 HTTP Response
+```
+
+## 完整目录结构
+
+```
+{project}/
+├── {project}-core/                      # Enterprise Business Rules
+│   ├── entity/                          # ★ 核心实体
+│   │   ├── Order.java                   # 充血模型, 零框架依赖
+│   │   └── OrderItem.java
+│   ├── valueobject/                     # ★ 不可变值对象
+│   │   ├── OrderId.java, Money.java, OrderStatus.java
+│   ├── event/                           # ★ 领域事件
+│   │   ├── DomainEvent.java (abstract)
+│   │   ├── OrderCreatedEvent.java
+│   │   └── OrderPaidEvent.java
+│   ├── exception/                       # ★ 领域异常
+│   │   ├── DomainException.java
+│   │   └── OrderDomainException.java
+│   └── service/                         # ★ 领域服务(无状态)
+├── {project}-usecase/                   # Application Business Rules
+│   ├── port/
+│   │   ├── input/                       # ★ 输入端口(UseCase 接口)
+│   │   │   ├── CreateOrderUseCase.java
+│   │   │   └── PayOrderUseCase.java
+│   │   └── output/                      # ★ 输出端口(Repository/Gateway 接口)
+│   │       ├── OrderRepository.java
+│   │       └── PaymentGateway.java
+│   ├── interactor/                      # ★ UseCase 实现
+│   │   ├── CreateOrderInteractor.java
+│   │   └── PayOrderInteractor.java
+│   └── dto/                             # UseCase 专用 DTO
+├── {project}-adapter/                   # Interface Adapters
+│   ├── controller/                      # REST Controller
+│   ├── presenter/                       # 响应格式转换
+│   ├── repository/                      # DB 实现(实现 Output Port)
+│   ├── gateway/                         # 外部 API 实现
+│   └── converter/                       # DTO ↔ Entity 转换
+└── {project}-framework/                 # Frameworks & Drivers
+    ├── config/                          # Spring DI 配置
+    ├── persistence/                     # JPA Entity, Mapper
+    └── web/                             # Web 配置 (CORS, Security)
+```

+ 0 - 0
skills/ddd-skills/ddd-architecture-clean/references/clean-ddd-hexagonal-hexagonal.md → skills/ddd-skills/ddd-architecture-clean/references/10-clean-ddd-hexagonal-hexagonal.md


+ 0 - 0
skills/ddd-skills/ddd-architecture-clean/references/ddd4j-clean-structure.md → skills/ddd-skills/ddd-architecture-clean/references/11-ddd4j-clean-structure.md


+ 0 - 0
skills/ddd-skills/ddd-architecture-clean/references/directory-structure.md → skills/ddd-skills/ddd-architecture-clean/references/12-directory-structure.md


+ 155 - 340
skills/ddd-skills/ddd-architecture-cola/SKILL.md

@@ -1,400 +1,215 @@
 ---
 name: ddd-architecture-cola
-description: Provides comprehensive guidance for COLA v5 (Clean Object-oriented Layered Architecture) — Alibaba's DDD architecture framework. Merges project scaffolding (cola-creator) and architecture validation (cola-validator) into one skill. Covers diamond architecture pattern with Adapter/Application/Domain/Infrastructure layers, multi-module Maven/Gradle project generation, ArchUnit dependency validation, coding conventions, and CI/CD integration. Use when the user asks about COLA architecture, COLA 5.0, wants to create a COLA project, needs COLA project validation, uses Spring Boot + MyBatis in Chinese enterprise context, or wants automated architecture compliance checking.
+description: Comprehensive guidance for COLA v5 Architecture (菱形架构) — Alibaba's COLA framework with adapter/application/domain/infrastructure layers. Covers full project scaffolding, architecture validation (cola-creator + cola-validator combined), dependency rule checking with ArchUnit, CQRS integration, and multi-module Maven/Gradle project generation. Use when user asks about COLA architecture, 菱形架构, cola-creator, cola-validator, 创建 COLA 项目, or needs Alibaba DDD framework.
 license: Apache-2.0
 ---
+# DDD Architecture — COLA v5(菱形架构)
 
-# DDD Architecture - COLA v5
+COLA v5 是阿里巴巴开源的 DDD 架构框架,采用**菱形架构**——Domain 居中,Adapter 和 Infrastructure 分居两侧。本 Skill 合并 cola-creator(脚手架生成)和 cola-validator(架构校验),提供从创建到持续校验的全流程能力。
 
-COLA v5 (Clean Object-oriented Layered Architecture) implementation guide — Alibaba's DDD architecture framework. Merges project scaffolding + architecture validation.
-
-## When to use this skill
-
-**ALWAYS use this skill when the user mentions:**
-- "COLA 架构"、"COLA v5"、"cola architecture"、"Alibaba COLA"
-- "创建 COLA 项目"、"cola creator"、"COLA 脚手架"
-- "COLA 校验"、"cola validator"、"检查 COLA 架构"
-- "依赖方向检查"、"dependency direction check"
-- Spring Boot + MyBatis Chinese enterprise projects
-- Wants automated architecture compliance in CI/CD
-- Needs archunit validation for DDD layering
-
-## Architecture Overview
-
-### COLA v5 Diamond Architecture
+## Workflow
 
 ```
-                ┌──────────────┐
-                │   Adapter    │  ← Adapter Layer: HTTP, MQ, RPC
-                └──────┬───────┘
-                       │
-                ┌──────▼───────┐
-                │   Application│  ← Application Layer: orchestration, transaction, CQRS routing
-        ┌───────┴───────┬───────┴───────┐
-        ▼               ▼               ▼
-  ┌──────────┐   ┌──────────┐   ┌──────────┐
-  │  Domain  │   │  Domain  │   │  Domain  │  ← Domain Layer: core business logic
-  │   ★      │   │   ★      │   │   ★      │
-  └──────────┘   └──────────┘   └──────────┘
-        ▲               ▲               ▲
-        └───────────────┴───────────────┘
-                       │
-                ┌──────▼───────┐
-                │Infrastructure│  ← Infrastructure Layer: DB, MQ, Cache, External API
-                └──────────────┘
+输入 → 意图识别
+  ├─ "创建 COLA 项目" → Creator 流程(5 步)
+  │   Step 1: 确认项目名/包名/语言/Spring Boot 版本/CQRS 开关
+  │   Step 2: 生成多模块 Maven/Gradle 骨架
+  │   Step 3: 生成基类(AggregateRoot/Entity/VO/DomainEvent)
+  │   Step 4: 生成 Demo 聚合代码(四层完整链路)
+  │   Step 5: 生成 ArchUnit 测试 + check_cola.py 脚本
+  └─ "检查架构合规" → Validator 流程(4 步)
+      Step 1: 接收项目路径或代码片段
+      Step 2: 执行 6 项合规检查
+      Step 3: P0/P1/P2 权重扣分,输出评分报告
+      Step 4: 输出违规清单 + 修复建议
+完成后引导 → ddd-domain-designer / ddd-api-designer / ddd-code-reviewer
 ```
 
-### Four Core Constraints
+## When to Use / Boundary
 
-1. **Domain Zero Dependency**: No Spring/JPA/MyBatis imports in Domain layer
-2. **App No Business Logic**: No if/else business judgments in App layer
-3. **Adapter No SQL/Business**: No SQL or business logic in Adapter layer
-4. **No Circular Dependencies**: No cyclic dependencies between modules
+### 什么时候该用(适用场景)
+- Java + Spring Boot 企业级项目,MyBatis/JPA 技术栈
+- 需要脚手架自动生成多模块 COLA 项目
+- 需要 ArchUnit 自动校验架构合规
+- 国内阿里系技术生态(Dubbo/RocketMQ/Nacos)
+- 团队 5-50 人,业务中高复杂度
 
-## Part A: Project Scaffolding (cola-creator)
+### 不适用场景
+- 非 Java 项目 → 不适用,推荐 `ddd-architecture-clean` / `ddd-architecture-hexagonal`
+- 非 Spring Boot → 不适用,COLA 强绑定 Spring 生态
+- 2-3 人团队简单 CRUD → 不适用,`ddd-architecture-layered` 更轻量
+- 已有整洁/六边形架构正常运行 → 不适用,无需迁移
+- 快速原型/PoC 阶段 → 不适用,架构成本过高
 
-### Interactive Setup Flow
+## 菱形架构核心原理
 
 ```
-User: "Create a COLA project"
-  →
-Confirmation questions:
-  1. Project name and package base
-  2. Java/Kotlin language
-  3. Spring Boot version
-  4. Enable CQRS? (default: no)
-  5. Include Demo code? (default: Order example)
-  →
-Generate:
-  ├── Complete pom.xml / build.gradle (multi-module)
-  ├── COLA standard directory structure
-  ├── Base classes: Entity/AggregateRoot/ValueObject/DomainEvent
-  ├── Demo aggregate (Order complete example)
-  ├── DDD middleware config (DomainEventBus, etc.)
-  └── ArchUnit tests (automated dependency direction checks)
+          ┌──────────────┐
+          │   Adapter    │  ← 适配层:HTTP/MQ/RPC 协议适配与 DTO 转换
+          └──────┬───────┘
+          ┌──────▼───────┐
+          │   Application│  ← 应用层:用例编排、事务管理、CQRS 执行器
+  ┌───────┴───────┬───────┴───────┐
+  ▼               ▼               ▼
+┌──────────┐ ┌──────────┐ ┌──────────┐
+│  Domain  │ │  Domain  │ │  Domain  │  ← 领域层:业务规则 ★ 零框架依赖
+│   ★      │ │   ★      │ │   ★      │
+└──────────┘ └──────────┘ └──────────┘
+  ▲               ▲               ▲
+  └───────────────┴───────────────┘
+                 │
+          ┌──────▼───────┐
+          │Infrastructure│  ← 基础设施层:DB/MQ/缓存/外部 API 实现
+          └──────────────┘
 ```
 
-### Directory Structure (COLA v5 Multi-Module)
+| 层 | 模块 | 职责 | 依赖 |
+|---|------|------|------|
+| **Adapter** | `{p}-adapter` | REST/RPC/MQ 协议适配、DTO 转换、参数校验 | → app, domain |
+| **Application** | `{p}-app` | Command/Query 执行器、事务编排、扩展点路由 | → domain, infra |
+| **Domain** | `{p}-domain` | 聚合/E/VO、领域事件、Repository/Gateway 接口、Ability | 无依赖 |
+| **Infrastructure** | `{p}-infrastructure` | Repository/Gateway 实现、PO↔DO 转换、配置、组件 | → domain |
+
+**v5 新增特性**:Extension Point(@ExtensionPoint + @Extension(bizId) 多租户差异化)、Ability(领域能力抽象)、组件化基础设施(分布式锁/限流/熔断)、CQRS 强化(command/query 执行器严格分离)
+
+## 生成能力:cola-creator
 
 ```
-{project}/
-├── {project}-adapter/               # Adapter Layer
-│   ├── web/                         # REST Controllers
-│   │   ├── controller/
-│   │   └── dto/                     # Interface layer DTOs
-│   └── consumer/                    # Message consumers
-├── {project}-app/                   # Application Layer
-│   ├── service/                     # Application services (orchestration, no business logic)
-│   ├── command/                     # Command objects
-│   ├── query/                       # Query objects
-│   └── event/                       # Event handlers
-├── {project}-domain/                # Domain Layer (Core, zero dependencies)
-│   ├── {aggregate}/                 # By aggregate package
-│   │   ├── entity/                  # Entity + Aggregate Root
-│   │   ├── valueobject/             # Value Objects
-│   │   ├── event/                   # Domain Events
-│   │   ├── service/                 # Domain Services
-│   │   └── repository/              # Repository interfaces (definition only)
-│   ├── gateway/                     # Anti-corruption layer interfaces
-│   └── shared/                      # Shared value objects/enums/exceptions
-├── {project}-infrastructure/        # Infrastructure Layer
-│   ├── repository/                  # Repository implementations
-│   ├── gateway/                     # Anti-corruption layer implementations
-│   ├── converter/                   # PO ↔ DO converter
-│   └── config/                      # Configuration
-└── start/                           # Bootstrap module
-    └── Application.java
+AI 交互确认 → 项目名/包名(com.example.order) / 语言(Java 17+/Kotlin) / Spring Boot(3.2+/3.1) / CQRS(否/L1/L2) / Demo(默认Order)
+生成内容:
+  ├── pom.xml/build.gradle(6 模块:start/adapter/app/domain/infrastructure/common)
+  ├── COLA v5 标准目录结构 + 基类(AggregateRoot/Entity/VO/DomainEvent)
+  ├── Demo 聚合(Order 四层完整示例)
+  ├── DDD 中间件配置(DomainEventBus、ExtensionExecutor)
+  ├── ArchUnit 测试 + check_cola.py 脚本
+  └── .gitignore + README
 ```
 
-### Generated Content
+两种方式:`mvn archetype:generate -DarchetypeGroupId=com.alibaba.cola -DarchetypeArtifactId=cola-archetype-web -DarchetypeVersion=5.0.0`(快速)或手动多模块(生产推荐,详见 references/02)。
 
-| Item | Description |
-|------|-------------|
-| Directory Structure | Complete Maven/Gradle multi-module structure |
-| Base Classes | Entity, AggregateRoot, ValueObject, DomainEvent base classes |
-| Dependencies | pom.xml / build.gradle with COLA + Spring dependencies |
-| Demo Code | Simple Order aggregate (entity, repository, app service, controller) |
-| Unit Test Skeletons | Domain layer + Application layer test templates |
-| ArchUnit Tests | Automated dependency direction validation |
-| .gitignore / README | Project configuration |
+## 校验能力:cola-validator
 
-## Part B: Architecture Validation (cola-validator)
+| 检查项 | 级别 | 说明 | 检测方式 |
+|--------|:----:|------|---------|
+| 依赖方向 | P0 | Domain 不可依赖 Infrastructure/App/Adapter | import 解析 |
+| Domain 纯净度 | P0 | Domain 无 Spring/JPA/MyBatis/Hibernate import | import 扫描 |
+| 层职责 | P0 | Adapter 无 SQL、App 无业务 if/else | AST 分析 |
+| 包命名规范 | P1 | 按 COLA 约定命名 | 正则匹配 |
+| 模块循环依赖 | P1 | DFS 检测依赖图 | 图遍历 |
+| 聚合设计 | P1 | 聚合>5 实体、跨聚合引用、值对象可变性 | AST 分析 |
 
-### Validation Checklist
+评分模型:`评分 = 100 - 扣分(P0=10分/项,P1=5分/项,P2=2分/项)`。≥90→A,70-89→B,50-69→C,<50→D。
 
-| Check Item | Severity | Description |
-|------------|:--:|-------------|
-| **Dependency Direction** | P0 | Domain must not depend on infrastructure/app/adapter |
-| **Package Naming** | P1 | Must conform to COLA package naming conventions |
-| **Layer Responsibility** | P0 | Adapter no business logic, App no SQL |
-| **Domain Purity** | P0 | Domain layer zero framework dependencies (no Spring/JPA/MyBatis imports) |
-| **Module Dependencies** | P1 | No cyclic dependencies between modules |
-| **Aggregate Design** | P1 | Aggregate size, cross-aggregate references |
+运行:`mvn test -Dtest=ArchitectureComplianceTest`(ArchUnit Java 测试)或 `python scripts/check_cola.py /path/to/project`(Python 轻量校验)。
 
-### Dependency Direction Check Algorithm
+## 目录结构(COLA v5 多模块)
 
 ```
-Rules:
-  domain/          → must not depend on any other module
-  infrastructure/  → can depend on domain/
-  app/             → can depend on domain/ + infrastructure/
-  adapter/         → can depend on app/ + domain/
-
-Detection method:
-  1. Parse import statements of each module
-  2. Check domain/ for import com.example.infrastructure.* → P0 violation
-  3. Check domain/ for import org.springframework.*     → P0 violation
-  4. Check domain/ for import javax.persistence.*        → P0 violation
-  5. Check app/ for import java.sql.*                    → P1 violation
-  6. Check adapter/ for if-else business branches        → P0 violation
+{project}/
+├── start/               — 启动模块:Application.java(@EnableCola), config/
+├── adapter/             — 适配器层
+│   ├── web/             — controller/dto/advice(GlobalExceptionHandler)
+│   ├── rpc/             — Dubbo/gRPC provider/consumer/facade
+│   ├── job/             — 定时任务调度
+│   └── message/         — MQ consumer/producer
+├── app/                 — 应用层
+│   ├── executor/        — command/query/event/extension 执行器
+│   ├── model/           — command/query/event/dto 对象
+│   ├── eventhandler/    — 事件处理器
+│   └── extension/       — 扩展点(point/biz/impl)
+├── domain/ ★            — 领域层(零框架依赖)
+│   ├── model/           — entity/vo/aggregate/event/enums
+│   ├── service/         — 领域服务
+│   ├── ability/         — 领域能力(v5 新概念)
+│   ├── gateway/         — 防腐层接口
+│   └── repository/      — 仓储接口
+├── infrastructure/      — 基础设施层
+│   ├── config/          — DB/缓存/MQ/RPC 配置
+│   ├── persistence/     — repositoryimpl/mapper/dao/entity(PO)
+│   ├── gatewayimpl/     — 网关实现
+│   ├── external/        — 外部服务客户端
+│   └── component/       — 分布式锁/限流/熔断/重试
+└── common/              — 常量/异常/工具/注解/上下文
 ```
 
-### Compliance Scoring
+## 落地步骤
 
-```
-Compliance = (passed checks / total checks) * 100%
+Phase 1 [1天] 脚手架 → Phase 2 [2-3天] 领域建模(配合 ddd-domain-designer)→ Phase 3 [2-3天] 基础设施(Repository/Gateway/PO)→ Phase 4 [1-2天] 应用+适配(Executor → Controller)→ Phase 5 [0.5天] 架构校验 → Phase 6 [持续] CI/CD 自动校验
 
-≥ 90%  → 🟢 Excellent
-70-89% → 🟡 Good
-50-69% → 🟠 Fair
-< 50%  → 🔴 Failed, recommend rebuild
-```
+## 核心规则(Core Rules)
 
-## Implementation Phases
+**四大约束(P0)**:①Domain 零框架依赖(禁止 Spring/JPA/MyBatis)②App 层无业务 if/else ③Adapter 无 SQL/业务判断 ④模块间无循环依赖
 
-```
-Phase 1: Project Scaffolding (1 day)
-  → Use ddd-architecture-cola creator → Generate complete project skeleton
+**依赖方向**:`adapter → app → domain ← infrastructure`(domain 不依赖任何人)
 
-Phase 2: Domain Modeling (2-3 days)
-  → Pair with ddd-domain-designer → Generate aggregate code
+## Gotchas — 常见坑(15条)
 
-Phase 3: Infrastructure Implementation (2-3 days)
-  → Repository implementation → Gateway implementation → Config
+1. **Domain 层放 Controller** — Controller 在 Adapter 层。Domain 下出现 `@RestController` 说明分层全错。
+2. **App 层直接操作 Mapper** — 必须通过 Repository 接口:`orderRepository.save(order)` 而非 `orderMapper.insert()`。
+3. **模块命名不匹配 COLA** — 必须为 `{project}-adapter/app/domain/infrastructure`,否则 ArchUnit 校验失败。
+4. **Command/Query 放 Domain 层** — 应放 `app/model/command/` 和 `app/model/query/`。
+5. **Archetype 版本不匹配** — cola-archetype-web 5.0.0 要求 Spring Boot 3.x,2.x 需手动适配。
+6. **Domain 层用 JPA @Entity** — 持久化映射在 Infrastructure 层用 PO 类。
+7. **App 层抛框架异常** — 应抛 `BizException`,Adapter 层统一转换。
+8. **跨聚合直接引用对象** — 聚合间通过 ID 引用,不直接 `Order.getCustomer()`。
+9. **值对象带 setter** — ValueObject 应不可变(final + 无 setter),修改返回新对象。
+10. **缺少领域事件** — 创建订单/支付/取消等关键操作必须发布领域事件。
+11. **Adapter 层有业务判断** — Controller/Consumer 不应有任何 if-else。
+12. **God Service 反模式** — Service 超 500 行应按聚合拆分。
+13. **扩展点无默认实现** — 每个 `ExtensionPoint` 需有默认 `@Extension`。
+14. **@EnableCola 缺失** — 启动类必须加 `@EnableCola` 启用的扩展点和事件总线。
+15. **PO 与 DO 混用** — 持久化对象和领域对象必须分离,用 Converter 转换。
 
-Phase 4: Application + Adapter (1-2 days)
-  → AppService → Controller → DTO
+## FAQ(15条)
 
-Phase 5: Architecture Validation (0.5 day)
-  → Use ddd-architecture-cola validator → Fix violations
+**Q1: COLA v5 和整洁架构的关系?** COLA v5 是整洁架构的阿里化实现,增加包命名规范、扩展点机制、CQRS 强化和脚手架。
 
-Phase 6: Continuous Validation
-  → CI/CD integration with ArchUnit → Auto-check on every commit
-```
+**Q2: 为何不用 cola-archetype 直接生成?** Archetype 快速但固定,手动搭建更适合生产定制。
 
-## Code Templates
-
-### Domain Layer
-
-```java
-// Aggregate Root — zero framework dependencies
-public class Order extends AggregateRoot<OrderId> {
-    private OrderStatus status;
-    private Money totalAmount;
-    private List<OrderItem> items;
-
-    public void pay() {
-        if (!status.canPay()) {
-            throw new OrderDomainException("Cannot pay in current status");
-        }
-        this.status = OrderStatus.PAID;
-        addDomainEvent(new OrderPaidEvent(this.id));
-    }
-}
-
-// Repository Interface — defined in Domain
-public interface OrderRepository {
-    Optional<Order> findById(OrderId id);
-    void save(Order order);
-}
-```
+**Q3: COLA 支持微服务吗?** 支持。每个微服务内部按 COLA 四层组织,服务间通过 RPC/MQ 通信。
 
-### Application Layer
-
-```java
-// Application Service — pure orchestration
-@Service
-public class OrderApplicationService {
-    private final OrderRepository orderRepository;
-
-    @Transactional
-    public void payOrder(PayOrderCommand command) {
-        Order order = orderRepository.findById(new OrderId(command.getOrderId()))
-            .orElseThrow(() -> new OrderNotFoundException(command.getOrderId()));
-        order.pay();
-        orderRepository.save(order);
-    }
-}
-```
+**Q4: CQRS 强制吗?** 否。简单场景用 `app/service/` 编排,复杂场景切到 CQRS executor。
 
-### ArchUnit Validation
-
-```java
-@Test
-public void domainShouldNotDependOnInfrastructure() {
-    noClasses()
-        .that().resideInAPackage("..domain..")
-        .should().dependOnClassesThat()
-        .resideInAPackage("..infrastructure..")
-        .because("Domain layer must not depend on infrastructure")
-        .check(classes);
-}
-
-@Test
-public void domainShouldNotDependOnSpring() {
-    noClasses()
-        .that().resideInAPackage("..domain..")
-        .should().dependOnClassesThat()
-        .resideInAPackage("org.springframework..")
-        .because("Domain layer must have zero framework dependencies")
-        .check(classes);
-}
-```
+**Q5: check_cola.py 和 ArchUnit 区别?** check_cola.py 轻量 import 扫描适合 CI,ArchUnit 强大 AST 分析需 Java 环境。
 
-## CI/CD Integration
+**Q6: Domain 层 @Autowired 怎么处理?** Domain 禁止 @Autowired,通过方法参数或构造器注入接口。
 
-```yaml
-# GitHub Actions Example
-- name: COLA Architecture Check
-  run: mvn test -pl {project}-domain -Dtest=ArchitectureComplianceTest
-```
+**Q7: 领域事件送达保证?** App 层事务提交后 `EventBus.publish()`,生产配合 Transactional Outbox 模式。
 
-## Quick Decision: Where Does This Code Go?
+**Q8: COLA 和 Spring Cloud 关系?** COLA 是架构规范,Spring Cloud 是基础设施,可完全集成使用。
 
-```
-├─ Is it handling HTTP/RPC/MQ protocol? → Adapter layer (adapter/web, adapter/consumer)
-├─ Is it orchestrating a use case (transaction boundary)? → Application layer (app/service)
-├─ Is it a CQRS command? → Application layer (app/command)
-├─ Is it a CQRS query? → Application layer (app/query)
-├─ Is it a business rule, entity, value object, domain event? → Domain layer (domain/{aggregate}/)
-├─ Is it a Repository interface? → Domain layer (domain/{aggregate}/repository/)
-├─ Is it implementing a Repository? → Infrastructure layer (infrastructure/repository/)
-├─ Is it a Gateway interface? → Domain layer (domain/gateway/)
-├─ Is it implementing a Gateway? → Infrastructure layer (infrastructure/gateway/)
-├─ Is it PO ↔ DO conversion? → Infrastructure layer (infrastructure/converter/)
-└─ ArchUnit test: "Domain must not import org.springframework.*"
-```
+**Q9: 值对象存 JSON 还是拆列?** 简单值对象拆列,复杂嵌套存 JSON + Converter 类型转换。
 
-## Sources
+**Q10: 聚合太大怎么办?** ≤ 5 实体,按业务操作频率拆分。
 
-### Primary Sources
-- [COLA 5.0 Architecture](https://github.com/alibaba/COLA) — Alibaba
-- [Domain-Driven Design: The Blue Book](https://www.domainlanguage.com/ddd/blue-book/) — Eric Evans (2003)
-- [The Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) — Robert C. Martin (2012)
-- [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) — Alistair Cockburn (2005)
+**Q11: 扩展点 bizId 来源?** 前端请求头、登录会员等级、租户 ID 路由。
 
-### Chinese Resources
-- [COLA 5.0 架构设计文档](https://wiki.hiwepy.com/docs/ddd/ddd-1gvro1llhtqni)
-- [PartMe DDD 实战: COLA 完整代码示例](https://wiki.hiwepy.com/docs/llm-app)
-- [ArchUnit User Guide](https://www.archunit.org/userguide/html/000_Index.html)
+**Q12: 无扩展点需求可删吗?** 可。`app/extension/` 和 `domain/ability/` 可不创建。
 
-## Output
+**Q13: common 模块内容?** 常量、异常基类、DTO 基类、上下文(UserContext/TenantContext)、自定义注解。
 
-When assisting with this skill, provide:
-- Complete COLA v5 project scaffolding
-- Architecture validation report (violation list + fix suggestions)
-- Compliance score
-- ArchUnit automated validation configuration
-- CI/CD integration guide
+**Q14: start 和 adapter 关系?** start 启动入口 + 全局配置,adapter 协议适配,start 依赖 adapter。
 
-## References
+**Q15: 如何确保不泄露敏感配置?** 外部化配置 + 环境变量,禁止硬编码密钥,Domain 层不读写配置文件。
 
-See `references/` directory for:
-- `cola-structure.md` — Complete COLA v5 directory structure reference
-- `cola-conventions.md` — Coding conventions and best practices
-- `cola-migration.md` — Migration guide from other architectures
+## Keywords
 
-## Next Steps
+`COLA` `COLA v5` `菱形架构` `diamond architecture` `cola-creator` `cola-validator` `ArchUnit` `CQRS` `Extension Point` `扩展点` `Ability` `领域能力` `Aggregate Root` `Entity` `Value Object` `Domain Event` `Repository` `Gateway` `防腐层` `DDD` `Spring Boot` `MyBatis` `@EnableCola` `CommandExecutor` `QueryExecutor`
+## Project Scaffolding
 
-After project setup:
-1. [ddd-domain-designer](../ddd-domain-designer/) — Design your domain aggregates
-2. [ddd-api-designer](../ddd-api-designer/) — Design your API layer
-3. [ddd-code-reviewer](../ddd-code-reviewer/) — Review your COLA compliance
+**ddd4j Boot** 是 COLA v5 架构的 Java 参考实现,基于 Spring Boot 3.5.x,集成 ddd-4-java 和 cqrs-4-java 轻量库,完整实现 DDD、CQRS 和 Event Sourcing 模式。
 
----
+- **项目生成**: 使用 `scripts/init_project.py` 可自动生成 COLA 多模块项目结构,支持单模块单体、多模块单体和微服务三种项目类型,涵盖 pom.xml、package-info.java、.gitignore、mvnw 等必需文件
+- **合规验证**: 使用 `scripts/check_project.py` 可验证项目的 DDD 分层合规性、依赖方向正确性和包命名规范,输出详细的违规报告和修复建议
+- **场景示例**: 参考 `examples/13-architecture-patterns.md`(四种架构模式)、`examples/14-single-module.md`(单模块单体)、`examples/15-multi-module.md`(多模块单体)、`examples/16-microservices.md`(微服务)
+- **详细说明**: 参考 `references/14-ddd4j-scaffold.md` 了解完整的项目生成流程、验证规则、层依赖关系和包命名规范
 
-## Skill Boundary
-
-### ✅ 擅长处理
-1. 中文企业 Spring Boot + MyBatis 技术栈
-2. 需要脚手架自动生成项目的团队
-3. 需要 ArchUnit 自动校验架构合规
-4. COLA v5 菱形架构(Adapter→App→Domain←Infrastructure)
-
-### ⚠️ 需要条件
-1. Java + Spring Boot 项目:COLA 强绑定 Spring 生态
-2. 团队愿意接受 COLA 的包命名约定
-3. 需要配合 DDD 领域建模使用
-
-### ❌ 超出范围
-1. Go/Python/TypeScript 项目 → 用 `ddd-architecture-clean` 或 `ddd-architecture-hexagonal`
-2. 非 Spring Boot → COLA 强绑定 Spring
-3. 2 人创业团队简单 CRUD → 用 `ddd-architecture-layered`
-
-
-## Security & Stability
-
-- All code templates are educational. Replace database credentials and external URLs with environment variables.
-- COLA's ArchUnit validation enforces layer boundaries at build time. Add check_cola.py (bundled in scripts/) to CI.
-- The diamond architecture isolates domain logic from infrastructure — reducing attack surface.
-- Script: scripts/check_cola.py validates COLA package naming and dependency rules. Run in CI to prevent violations.
-
-
-## Gotchas — Common Pitfalls
-
-- **Domain 层存放 Controller 接口**: COLA 的 Controller 接口定义在 Adapter 层,而不是 Domain 层。Domain 层只放领域对象。如果 Domain 中有 `@RestController`,分层就错了。
-- **App 层直接操作数据库**: App 层(Application)通过 Gateway 接口访问数据,不能直接使用 Mapper/JdbcTemplate。Gateway 接口在 Domain 层定义,实现在 Infrastructure 层。
-- **Module 命名不匹配 COLA 约定**: COLA v5 有严格的模块命名规范:`{project}-adapter`、`{project}-app`、`{project}-domain`、`{project}-infrastructure`。随机命名会导致 ArchUnit 校验失败。
-- **Command/Query 放在 Domain 层**: COLA 的 Command 和 Query 对象属于 App 层(Application),用于 DTO 传输。不要把它们和 Domain 的 Entity/ValueObject 混淆。
-- **忘记 COLA Archetype 版本**: 使用 `cola-archetype` 生成项目时注意 Spring Boot 和 COLA 版本匹配。不匹配的版本会导致编译失败。
-
-## When NOT to Use This Skill
-
-| ❌ Skip | ✅ Use Instead |
-|---------|---------------|
-| Non-Java project (Go, Python, TypeScript) | `architecture-clean` or `architecture-hexagonal` (language-agnostic) |
-| Non-Spring Boot project | COLA is tightly coupled to Spring Boot |
-| Simple CRUD, 2-person team | `architecture-layered` (much lower ceremony) |
-| Already on Clean Architecture | COLA is an opinionated Clean variant — stay if Clean works |
-| Startup prototyping, not enterprise | Skip DDD, use simple Spring Boot MVC |
-
-## Security & Stability
-
-- All code templates are educational. Replace database credentials and external service URLs with environment variables.
-- COLA's ArchUnit-based validation enforces layer boundaries at build time. Add `check_cola.py` (bundled in `scripts/`) to CI for automated compliance checking.
-- The diamond architecture isolates domain logic from infrastructure — reducing attack surface and making security audits focused.
-- Script: `scripts/check_cola.py` validates COLA package naming conventions and dependency rules. Run in CI to prevent architectural violations.
-
-## 🧭 DDD Skills Journey
-
-> 📍 **You are here: `ddd-architecture-cola` — Step 3: COLA v5 架构落地**
-
-```mermaid
-flowchart LR
-    S1["Step 1<br/>awesome<br/>入门与全景"] --> S2["Step 2<br/>selector<br/>架构选型"]
-    S2 --> S3A["Step 3<br/>layered<br/>分层架构"]
-    S2 --> S3B["Step 3<br/>onion<br/>洋葱架构"]
-    S2 --> S3C["Step 3<br/>hexagonal<br/>六边形架构"]
-    S2 --> S3D["Step 3<br/>clean<br/>整洁架构"]
-    S2 --> S3E["⭐ Step 3<br/>cola<br/>COLA v5"]
-    S3A & S3B & S3C & S3D & S3E --> S4A["Step 4<br/>domain-designer<br/>领域建模"]
-    S3A & S3B & S3C & S3D & S3E --> S4B["Step 4<br/>cqrs-architecture<br/>CQRS"]
-    S3A & S3B & S3C & S3D & S3E --> S4C["Step 4<br/>api-designer<br/>API设计"]
-    S4A & S4B & S4C --> S5["Step 5<br/>code-reviewer<br/>代码审查"]
-    S5 --> S6A["Step 6<br/>event-storming<br/>事件风暴"]
-    S5 --> S6B["Step 6<br/>testing-strategist<br/>测试策略"]
-    S5 --> S6C["Step 6<br/>devops-integration<br/>DevOps"]
-    S5 --> S6D["Step 6<br/>evaluator<br/>架构评估"]
-    S6A & S6B & S6C & S6D --> S7["🏁 Step 7<br/>architecture-doc<br/>架构文档"]
-
-    style S3E fill:#3b82f6,stroke:#2563eb,color:white,stroke-width:3px
-```
+## References
+
+详细参考见 `references/` 目录:01-architecture-principles(架构原理)、02-project-scaffold(脚手架)、03-domain-layer(领域层)、04-app-layer(应用层)、05-adapter-layer(适配层)、06-infrastructure(基础设施)、07-archunit-validation(ArchUnit 校验)、08-cqrs-integration(CQRS 集成)
 
-**← Previous**: [selector](../ddd-architecture-selector/) — 为什么选 COLA?
-**→ Next**: [domain-designer](../ddd-domain-designer/) — 为 COLA 项目设计聚合和领域模型
-**🔗 Related**: [api-designer](../ddd-api-designer/) — 设计 API 接口 | [code-reviewer](../ddd-code-reviewer/) — ArchUnit 合规检查
-**🏠 Home**: [awesome](../ddd-architecture-awesome/) — DDD 概念全景
+## Examples
 
-💡 COLA 是国内企业的最佳选择:脚手架 + 校验 + Spring Boot 生态。先运行 `scripts/check_cola.py` 做一次合规检查,再开始写领域代码。
+完整代码见 `examples/` 目录:01-quickstart-order(Order 聚合完整实现)、02-customer-crud(CRUD 入门)、03-extension-point(扩展点机制)、04-cqrs-separation(CQRS 分离)、05-archunit-config(ArchUnit 校验 CI/CD 集成)
 
-> 📋 See [DESIGN.md](../DESIGN.md) for the complete 16-skill ecosystem map.
+项目规模示例见 `examples/` 目录:06-monolith-simple(单体简单项目)、07-monolith-complex(单体复杂项目)、08-monolith-multi-module(单体多模块项目)、09-microservice-simple-monolith(微服务简单的单体项目)、10-microservice-complex-monolith(微服务复杂的单体项目,基于 ddd4j-gateway)、11-microservice-simple-multi-module(微服务简单的多模块项目,基于 ddd4j-rednote)、12-microservice-complex-multi-module(微服务复杂的多模块项目,基于 ddd4j-pay)

+ 255 - 0
skills/ddd-skills/ddd-architecture-cola/examples/01-quickstart-order.md

@@ -0,0 +1,255 @@
+# COLA 示例:Order 订单聚合完整实现
+
+> 本节展示一个完整的订单聚合,涵盖 Domain/App/Adapter/Infrastructure 四层。
+
+## 领域层 (domain)
+
+```java
+// === 聚合根 ===
+public class Order extends AggregateRoot<OrderId> {
+    private OrderId id;
+    private CustomerId customerId;
+    private OrderStatus status;
+    private Money totalAmount;
+    private List<OrderItem> items;
+    private LocalDateTime createdAt;
+
+    public static Order create(OrderId id, CustomerId customerId, List<OrderItem> items) {
+        Order order = new Order();
+        order.id = id;
+        order.customerId = customerId;
+        order.status = OrderStatus.DRAFT;
+        order.items = new ArrayList<>(items);
+        order.totalAmount = calculateTotal(items);
+        order.createdAt = LocalDateTime.now();
+        order.addDomainEvent(new OrderCreatedEvent(id, customerId, order.totalAmount));
+        return order;
+    }
+
+    public void pay() {
+        if (!status.canPay()) throw new OrderDomainException("不可支付");
+        this.status = OrderStatus.PAID;
+        addDomainEvent(new OrderPaidEvent(this.id, this.totalAmount));
+    }
+
+    public void cancel() {
+        if (!status.canCancel()) throw new OrderDomainException("不可取消");
+        this.status = OrderStatus.CANCELLED;
+        addDomainEvent(new OrderCancelledEvent(this.id));
+    }
+
+    private static Money calculateTotal(List<OrderItem> items) {
+        return items.stream()
+            .map(OrderItem::getSubtotal)
+            .reduce(Money.ZERO, Money::add);
+    }
+
+    // getter 省略
+}
+
+// === 值对象 ===
+public class OrderId {
+    private final String value;
+    public OrderId(String value) {
+        this.value = Objects.requireNonNull(value);
+    }
+    public String getValue() { return value; }
+    @Override public boolean equals(Object o) { /* 按值比较 */ }
+    @Override public int hashCode() { return value.hashCode(); }
+}
+
+// === 实体 ===
+public class OrderItem {
+    private ProductId productId;
+    private int quantity;
+    private Money unitPrice;
+
+    public Money getSubtotal() {
+        return unitPrice.multiply(quantity);
+    }
+}
+
+// === 仓储接口 ===
+public interface OrderRepository {
+    Optional<Order> findById(OrderId id);
+    Order save(Order order);
+    Page<Order> findByCustomerId(CustomerId customerId, Pageable pageable);
+}
+```
+
+## 应用层 (app)
+
+```java
+// === 命令对象 ===
+public class OrderCreateCmd {
+    @NotBlank private String customerId;
+    @NotEmpty private List<OrderItemDTO> items;
+    // getter/setter
+}
+
+// === 命令执行器 ===
+@Component
+@CommandExecutor
+public class OrderCreateCmdExe implements CommandExecutor<OrderCreateCmd, OrderDTO> {
+    @Resource private OrderRepository orderRepository;
+    @Resource private ProductGateway productGateway;
+
+    @Override
+    @Transactional
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        // 校验库存
+        for (OrderItemDTO item : cmd.getItems()) {
+            InventoryInfo inv = productGateway.checkInventory(
+                new ProductId(item.getProductId()), item.getQuantity());
+            if (!inv.isAvailable()) throw new BizException("库存不足: " + item.getProductId());
+        }
+
+        // 创建订单
+        Order order = Order.create(
+            new OrderId(UUID.randomUUID().toString()),
+            new CustomerId(cmd.getCustomerId()),
+            cmd.getItems().stream().map(this::toItem).collect(Collectors.toList())
+        );
+
+        orderRepository.save(order);
+        return OrderAssembler.toDTO(order);
+    }
+}
+
+// === 查询执行器 ===
+@Component
+public class OrderGetQryExe implements QueryExecutor<OrderGetQry, OrderDTO> {
+    @Resource private OrderRepository orderRepository;
+
+    @Override
+    public OrderDTO execute(OrderGetQry qry) {
+        return orderRepository.findById(new OrderId(qry.getOrderId()))
+            .map(OrderAssembler::toDTO)
+            .orElseThrow(() -> new OrderNotFoundException(qry.getOrderId()));
+    }
+}
+```
+
+## 适配层 (adapter)
+
+```java
+@RestController
+@RequestMapping("/api/v1/orders")
+public class OrderController {
+    @Resource private OrderCreateCmdExe orderCreateCmdExe;
+    @Resource private OrderGetQryExe orderGetQryExe;
+
+    @PostMapping
+    public Response<OrderDTO> create(@Valid @RequestBody OrderCreateRequest request) {
+        return Response.success(orderCreateCmdExe.execute(request.toCommand()));
+    }
+
+    @GetMapping("/{id}")
+    public Response<OrderDTO> get(@PathVariable String id) {
+        OrderGetQry qry = new OrderGetQry();
+        qry.setOrderId(id);
+        return Response.success(orderGetQryExe.execute(qry));
+    }
+
+    @PostMapping("/{id}/pay")
+    public Response<Void> pay(@PathVariable String id) {
+        OrderPayCmd cmd = new OrderPayCmd();
+        cmd.setOrderId(id);
+        orderPayCmdExe.execute(cmd);
+        return Response.success();
+    }
+}
+```
+
+## 基础设施层 (infrastructure)
+
+```java
+// === 持久化 PO ===
+@Table(name = "t_order")
+public class OrderPO {
+    @Id private String id;
+    private String customerId;
+    private String status;
+    private BigDecimal totalAmount;
+    private String currency;
+    private LocalDateTime createdAt;
+}
+
+// === MyBatis Mapper ===
+@Mapper
+public interface OrderMapper {
+    @Insert("INSERT INTO t_order(id, customer_id, status, total_amount, currency, created_at) " +
+            "VALUES(#{id}, #{customerId}, #{status}, #{totalAmount}, #{currency}, #{createdAt})")
+    void insert(OrderPO po);
+
+    @Select("SELECT * FROM t_order WHERE id = #{id}")
+    OrderPO selectById(String id);
+}
+
+// === 仓储实现 ===
+@Repository
+public class OrderRepositoryImpl implements OrderRepository {
+    @Resource private OrderMapper orderMapper;
+    @Resource private OrderConverter orderConverter;
+
+    @Override
+    public Order save(Order order) {
+        OrderPO po = orderConverter.toPO(order);
+        orderMapper.insert(po);
+        return orderConverter.toDomain(po);
+    }
+
+    @Override
+    public Optional<Order> findById(OrderId id) {
+        return Optional.ofNullable(orderMapper.selectById(id.getValue()))
+            .map(orderConverter::toDomain);
+    }
+}
+
+// === PO ↔ Domain 转换 ===
+@Component
+public class OrderConverter {
+    public OrderPO toPO(Order order) {
+        OrderPO po = new OrderPO();
+        po.setId(order.getId().getValue());
+        po.setStatus(order.getStatus().name());
+        po.setTotalAmount(order.getTotalAmount().getAmount());
+        po.setCurrency(order.getTotalAmount().getCurrency().getCurrencyCode());
+        return po;
+    }
+
+    public Order toDomain(OrderPO po) {
+        // 注意:领域对象的完整重建需要 items 等关联数据
+        return Order.builder()
+            .id(new OrderId(po.getId()))
+            .status(OrderStatus.valueOf(po.getStatus()))
+            .totalAmount(new Money(po.getTotalAmount(), Currency.getInstance(po.getCurrency())))
+            .build();
+    }
+}
+```
+
+## 数据库 DDL
+
+```sql
+CREATE TABLE t_order (
+    id          VARCHAR(64) PRIMARY KEY,
+    customer_id VARCHAR(64) NOT NULL,
+    status      VARCHAR(16) NOT NULL DEFAULT 'DRAFT',
+    total_amount DECIMAL(12,2) NOT NULL,
+    currency    VARCHAR(3) NOT NULL DEFAULT 'CNY',
+    created_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    updated_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    INDEX idx_customer (customer_id),
+    INDEX idx_status (status)
+);
+
+CREATE TABLE t_order_item (
+    id          BIGINT AUTO_INCREMENT PRIMARY KEY,
+    order_id    VARCHAR(64) NOT NULL,
+    product_id  VARCHAR(64) NOT NULL,
+    quantity    INT NOT NULL,
+    unit_price  DECIMAL(12,2) NOT NULL,
+    INDEX idx_order (order_id)
+);
+```

+ 209 - 0
skills/ddd-skills/ddd-architecture-cola/examples/02-customer-crud.md

@@ -0,0 +1,209 @@
+# COLA 示例:Customer 客户管理完整实现
+
+> 展示一个相对简单的单实体聚合的 CRUD 操作,适合初学者理解 COLA 四层交互。
+
+## 领域层
+
+```java
+// === 聚合根 ===
+public class Customer extends AggregateRoot<CustomerId> {
+    private CustomerId id;
+    private String name;
+    private Email email;
+    private PhoneNumber phone;
+    private CustomerType type;
+    private CustomerStatus status;
+    private LocalDateTime createdAt;
+
+    public static Customer create(CustomerId id, String name, Email email) {
+        Customer customer = new Customer();
+        customer.id = id;
+        customer.name = name;
+        customer.email = email;
+        customer.type = CustomerType.NORMAL;
+        customer.status = CustomerStatus.ACTIVE;
+        customer.createdAt = LocalDateTime.now();
+        customer.addDomainEvent(new CustomerCreatedEvent(id, name, email));
+        return customer;
+    }
+
+    public void changeEmail(Email newEmail) {
+        this.email = newEmail;
+        addDomainEvent(new CustomerEmailChangedEvent(this.id, this.email));
+    }
+
+    public void deactivate() {
+        if (this.status == CustomerStatus.INACTIVE) return;
+        this.status = CustomerStatus.INACTIVE;
+        addDomainEvent(new CustomerDeactivatedEvent(this.id));
+    }
+}
+
+// === 值对象 ===
+public final class Email {
+    private final String value;
+    private static final Pattern PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@(.+)$");
+
+    public Email(String value) {
+        if (value == null || !PATTERN.matcher(value).matches()) {
+            throw new IllegalArgumentException("Invalid email: " + value);
+        }
+        this.value = value;
+    }
+    public String getValue() { return value; }
+    // equals/hashCode 省略
+}
+
+// === 仓储接口 ===
+public interface CustomerRepository {
+    Optional<Customer> findById(CustomerId id);
+    Customer save(Customer customer);
+    void delete(CustomerId id);
+    Page<Customer> search(String keyword, Pageable pageable);
+}
+```
+
+## 应用层
+
+```java
+// === 命令对象 ===
+public class CustomerCreateCmd {
+    @NotBlank private String name;
+    @Email @NotBlank private String email;
+    // getter/setter
+}
+
+public class CustomerUpdateEmailCmd {
+    @NotBlank private String customerId;
+    @Email @NotBlank private String newEmail;
+    // getter/setter
+}
+
+// === 命令执行器 ===
+@Component
+public class CustomerCreateCmdExe implements CommandExecutor<CustomerCreateCmd, CustomerDTO> {
+    @Resource private CustomerRepository customerRepository;
+
+    @Override
+    @Transactional
+    public CustomerDTO execute(CustomerCreateCmd cmd) {
+        Customer customer = Customer.create(
+            new CustomerId(UUID.randomUUID().toString()),
+            cmd.getName(),
+            new Email(cmd.getEmail())
+        );
+        customerRepository.save(customer);
+        return CustomerAssembler.toDTO(customer);
+    }
+}
+
+// === 查询执行器 ===
+@Component
+public class CustomerSearchQryExe implements QueryExecutor<CustomerSearchQry, PageResult<CustomerDTO>> {
+    @Resource private CustomerRepository customerRepository;
+
+    @Override
+    public PageResult<CustomerDTO> execute(CustomerSearchQry qry) {
+        return customerRepository.search(qry.getKeyword(), qry.toPageable())
+            .map(CustomerAssembler::toDTO);
+    }
+}
+```
+
+## 适配层
+
+```java
+@RestController
+@RequestMapping("/api/v1/customers")
+public class CustomerController {
+    @Resource private CustomerCreateCmdExe customerCreateCmdExe;
+    @Resource private CustomerSearchQryExe customerSearchQryExe;
+
+    @PostMapping
+    public Response<CustomerDTO> create(@Valid @RequestBody CustomerCreateRequest request) {
+        return Response.success(customerCreateCmdExe.execute(request.toCommand()));
+    }
+
+    @GetMapping
+    public Response<PageResult<CustomerDTO>> search(
+            @RequestParam(required = false) String keyword,
+            @RequestParam(defaultValue = "1") int page,
+            @RequestParam(defaultValue = "20") int pageSize) {
+        CustomerSearchQry qry = new CustomerSearchQry();
+        qry.setKeyword(keyword);
+        qry.setPage(page);
+        qry.setPageSize(pageSize);
+        return Response.success(customerSearchQryExe.execute(qry));
+    }
+}
+```
+
+## 基础设施层
+
+```java
+// 持久化 PO
+@Table(name = "t_customer")
+public class CustomerPO {
+    @Id private String id;
+    private String name;
+    private String email;
+    private String phone;
+    private String type;
+    private String status;
+    private LocalDateTime createdAt;
+}
+
+// Mapper
+@Mapper
+public interface CustomerMapper {
+    @Insert("INSERT INTO t_customer(id, name, email, phone, type, status, created_at) " +
+            "VALUES(#{id}, #{name}, #{email}, #{phone}, #{type}, #{status}, #{createdAt})")
+    void insert(CustomerPO po);
+
+    @Select("SELECT * FROM t_customer WHERE id = #{id}")
+    CustomerPO selectById(String id);
+
+    @Select("<script>SELECT * FROM t_customer " +
+            "WHERE 1=1 " +
+            "<if test='keyword != null'>AND (name LIKE #{keyword} OR email LIKE #{keyword})</if> " +
+            "ORDER BY created_at DESC</script>")
+    List<CustomerPO> search(@Param("keyword") String keyword);
+}
+
+// 仓储实现
+@Repository
+public class CustomerRepositoryImpl implements CustomerRepository {
+    @Resource private CustomerMapper customerMapper;
+    @Resource private CustomerConverter converter;
+
+    @Override
+    public Customer save(Customer customer) {
+        CustomerPO po = converter.toPO(customer);
+        customerMapper.insert(po);
+        return converter.toDomain(po);
+    }
+
+    @Override
+    public Optional<Customer> findById(CustomerId id) {
+        return Optional.ofNullable(customerMapper.selectById(id.getValue()))
+            .map(converter::toDomain);
+    }
+}
+```
+
+## 数据库 DDL
+
+```sql
+CREATE TABLE t_customer (
+    id          VARCHAR(64) PRIMARY KEY,
+    name        VARCHAR(128) NOT NULL,
+    email       VARCHAR(256) NOT NULL UNIQUE,
+    phone       VARCHAR(32),
+    type        VARCHAR(16) NOT NULL DEFAULT 'NORMAL',
+    status      VARCHAR(16) NOT NULL DEFAULT 'ACTIVE',
+    created_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    updated_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    INDEX idx_email (email),
+    INDEX idx_status (status)
+);
+```

+ 115 - 0
skills/ddd-skills/ddd-architecture-cola/examples/03-extension-point.md

@@ -0,0 +1,115 @@
+# COLA 示例:Extension Point 扩展点机制
+
+> COLA v5 最核心的新特性。通过扩展点实现业务维度的差异化逻辑。
+
+## 场景说明
+
+订单价格计算规则,不同会员级别(普通/VIP/企业)有不同的折扣策略。
+
+## 扩展点定义
+
+```java
+// 1. 定义扩展点接口(放在 app/extension/point/)
+@ExtensionPoint
+public interface OrderPriceCalculateExtPt {
+    /**
+     * 计算订单最终价格
+     * @param order 订单领域对象
+     * @param basePrice 基础价格
+     * @return 最终价格
+     */
+    Money calculate(Order order, Money basePrice);
+}
+```
+
+## 扩展点实现
+
+```java
+// 2. 普通会员 —— 无折扣
+@Extension(bizId = "normalOrder")
+public class NormalOrderPriceCalculateExt implements OrderPriceCalculateExtPt {
+    @Override
+    public Money calculate(Order order, Money basePrice) {
+        return basePrice;  // 原价
+    }
+}
+
+// 3. VIP 会员 —— 9 折
+@Extension(bizId = "vipOrder")
+public class VipOrderPriceCalculateExt implements OrderPriceCalculateExtPt {
+    @Override
+    public Money calculate(Order order, Money basePrice) {
+        return basePrice.multiply(0.9)  // 九折
+            .setScale(2, RoundingMode.HALF_UP);
+    }
+}
+
+// 4. 企业会员 —— 8 折 + 满减
+@Extension(bizId = "enterpriseOrder")
+public class EnterpriseOrderPriceCalculateExt implements OrderPriceCalculateExtPt {
+    @Override
+    public Money calculate(Order order, Money basePrice) {
+        Money afterDiscount = basePrice.multiply(0.8);  // 八折
+        if (afterDiscount.compareTo(new Money(10000, Currency.getInstance("CNY"))) >= 0) {
+            afterDiscount = afterDiscount.subtract(new Money(500, Currency.getInstance("CNY")));
+            // 满 10000 减 500
+        }
+        return afterDiscount.setScale(2, RoundingMode.HALF_UP);
+    }
+}
+```
+
+## 扩展点调用
+
+```java
+// 5. 在 App 层注入 ExtensionExecutor
+@Component
+public class OrderCreateCmdExe implements CommandExecutor<OrderCreateCmd, OrderDTO> {
+    @Resource
+    private ExtensionExecutor extensionExecutor;
+
+    @Override
+    @Transactional
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        Order order = Order.create(/* ... */);
+        Money basePrice = order.getTotalAmount();
+
+        // 根据业务身份(bizId)自动路由到对应的扩展实现
+        Money finalPrice = extensionExecutor.execute(
+            OrderPriceCalculateExtPt.class,   // 扩展点接口
+            cmd.getBizId(),                    // 业务身份(normal/vip/enterprise)
+            ext -> ext.calculate(order, basePrice)
+        );
+
+        // 使用 finalPrice 进行后续处理
+        return OrderAssembler.toDTO(order);
+    }
+}
+```
+
+## 业务身份注入
+
+```java
+// 6. 前端请求携带业务身份
+@RestController
+@RequestMapping("/api/v1/orders")
+public class OrderController {
+    @PostMapping
+    public Response<OrderDTO> create(
+            @RequestHeader(value = "X-Biz-Id", defaultValue = "normalOrder") String bizId,
+            @Valid @RequestBody OrderCreateRequest request) {
+        request.setBizId(bizId);
+        return Response.success(orderCreateCmdExe.execute(request.toCommand()));
+    }
+}
+```
+
+## 扩展点最佳实践
+
+| 实践 | 说明 |
+|------|------|
+| **接口粒度** | 一个扩展点只做一件事,如价格计算、库存校验 |
+| **默认实现** | 必须提供默认实现(普通场景),新增扩展不影响已有逻辑 |
+| **测试覆盖** | 每个扩展实现都应有独立单元测试 |
+| **无状态** | 扩展实现应为无状态,通过参数传递上下文 |
+| **日志记录** | 在扩展执行器层记录扩展路由日志,便于排查 |

+ 198 - 0
skills/ddd-skills/ddd-architecture-cola/examples/04-cqrs-separation.md

@@ -0,0 +1,198 @@
+# COLA 示例:CQRS 读写分离完整实现
+
+> 基于 COLA v5 的 CQRS 强化目录结构,展示命令/查询的严格分离。
+
+## 写模型(Command Side)
+
+### 命令对象
+
+```java
+// app/model/command/OrderCreateCmd.java
+@Data
+@Command
+public class OrderCreateCmd {
+    @NotBlank private String customerId;
+    @NotEmpty private List<OrderItemDTO> items;
+    private String remark;
+    private String bizId;   // 业务身份(用于扩展点路由)
+
+    public void validate() {
+        Assert.notEmpty(items, "订单项不能为空");
+        Assert.isTrue(items.size() <= 50, "单笔订单最多 50 项");
+    }
+}
+```
+
+### 命令执行器
+
+```java
+// app/executor/command/order/OrderCreateCmdExe.java
+@Component
+@CommandExecutor
+public class OrderCreateCmdExe implements CommandExecutor<OrderCreateCmd, OrderDTO> {
+    @Resource private OrderRepository orderRepository;
+    @Resource private ProductGateway productGateway;
+    @Resource private IdGenerator idGenerator;
+    @Resource private ExtensionExecutor extensionExecutor;
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        cmd.validate();
+
+        // 1. 校验库存
+        for (OrderItemDTO item : cmd.getItems()) {
+            InventoryInfo inv = productGateway.checkInventory(
+                new ProductId(item.getProductId()), item.getQuantity());
+            if (!inv.isAvailable()) {
+                throw new BizException("库存不足: " + item.getProductId());
+            }
+        }
+
+        // 2. 创建订单(领域逻辑)
+        Order order = Order.create(
+            new OrderId(idGenerator.nextId()),
+            new CustomerId(cmd.getCustomerId()),
+            cmd.getItems().stream().map(this::toItem).collect(Collectors.toList())
+        );
+
+        // 3. 应用扩展点(价格计算等)
+        Money finalPrice = extensionExecutor.execute(
+            OrderPriceCalculateExtPt.class, cmd.getBizId(),
+            ext -> ext.calculate(order, order.getTotalAmount())
+        );
+
+        // 4. 保存订单
+        orderRepository.save(order);
+
+        // 5. 发布领域事件(异步处理后续逻辑)
+        order.getDomainEvents().forEach(eventBus::publish);
+
+        return OrderAssembler.toDTO(order);
+    }
+
+    private OrderItem toItem(OrderItemDTO dto) {
+        return new OrderItem(
+            new ProductId(dto.getProductId()),
+            dto.getQuantity(),
+            new Money(dto.getUnitPrice(), Currency.getInstance("CNY"))
+        );
+    }
+}
+```
+
+## 读模型(Query Side)
+
+### 查询对象
+
+```java
+// app/model/query/OrderListQry.java
+@Data
+public class OrderListQry {
+    private String customerId;
+    private String status;
+    private LocalDateTime startTime;
+    private LocalDateTime endTime;
+    private int page = 1;
+    private int pageSize = 20;
+
+    public Pageable toPageable() {
+        return PageRequest.of(page - 1, pageSize, Sort.by("createdAt").descending());
+    }
+
+    public void validate() {
+        Assert.isTrue(page >= 1, "页码从 1 开始");
+        Assert.isTrue(pageSize <= 100, "每页最多 100 条");
+    }
+}
+```
+
+### 查询执行器
+
+```java
+// app/executor/query/order/OrderListQryExe.java
+@Component
+public class OrderListQryExe implements QueryExecutor<OrderListQry, PageResult<OrderDTO>> {
+    @Resource
+    private OrderRepository orderRepository;
+
+    @Override
+    public PageResult<OrderDTO> execute(OrderListQry qry) {
+        qry.validate();
+
+        // 查询通过 Repository 接口(非事务)
+        Page<Order> orders = orderRepository.search(qry.toCriteria(), qry.toPageable());
+
+        return PageResult.of(
+            orders.getContent().stream()
+                .map(OrderAssembler::toDTO)
+                .collect(Collectors.toList()),
+            orders.getTotalElements(),
+            qry.getPage(),
+            qry.getPageSize()
+        );
+    }
+}
+```
+
+## 适配层 API
+
+```java
+@RestController
+@RequestMapping("/api/v1/orders")
+public class OrderController {
+    @Resource private OrderCreateCmdExe orderCreateCmdExe;  // Command Executor
+    @Resource private OrderListQryExe orderListQryExe;      // Query Executor
+
+    // 命令 API(写操作)
+    @PostMapping
+    public Response<OrderDTO> create(@Valid @RequestBody OrderCreateRequest request) {
+        return Response.success(orderCreateCmdExe.execute(request.toCommand()));
+    }
+
+    // 查询 API(读操作)
+    @GetMapping
+    public Response<PageResult<OrderDTO>> list(OrderListQry qry) {
+        return Response.success(orderListQryExe.execute(qry));
+    }
+
+    @GetMapping("/{id}")
+    public Response<OrderDTO> get(@PathVariable String id) {
+        OrderGetQry qry = new OrderGetQry();
+        qry.setOrderId(id);
+        return Response.success(orderGetQryExe.execute(qry));
+    }
+}
+```
+
+## 命令 vs 查询 API 设计对比
+
+| 维度 | 命令 API(写) | 查询 API(读) |
+|------|---------------|---------------|
+| HTTP 方法 | POST, PUT, DELETE | GET |
+| 请求体 | Command 对象(业务语义) | Query 参数(过滤条件) |
+| 返回值 | 有限字段(操作结果 + ID) | 完整数据(DTO) |
+| 幂等 | 必须支持 | 天然幂等 |
+| 事务 | 需要 | 不需要 |
+| 扩展点 | 经常使用 | 基本不用 |
+| 限流 | 严格限流 | 宽松限流 |
+| 缓存 | 不适用(写入后失效) | 适用 |
+
+## 事件驱动同步(L2 数据库分离)
+
+```java
+// 当需要使用领域事件同步读写模型时
+@Component
+public class OrderPaidEventExe implements EventExecutor<OrderPaidEvent> {
+    @Resource private OrderReadModelRepository readModelRepository;
+
+    @Override
+    public void execute(OrderPaidEvent event) {
+        // 更新读模型(从库/ES)
+        OrderReadModel readModel = readModelRepository.findById(event.getOrderId());
+        readModel.setStatus("PAID");
+        readModel.setPaidAt(LocalDateTime.now());
+        readModelRepository.save(readModel);
+    }
+}
+```

+ 174 - 0
skills/ddd-skills/ddd-architecture-cola/examples/05-archunit-config.md

@@ -0,0 +1,174 @@
+# Example 5: ArchUnit 校验完整配置 + CI/CD 流水线集成
+
+本示例展示如何在 COLA v5 项目中配置 ArchUnit 架构合规测试,并将其集成到 GitHub Actions / GitLab CI 流水线中。
+
+## 目录结构
+
+```
+project-root/
+├── start/
+├── adapter/
+├── app/
+├── domain/
+├── infrastructure/
+├── common/
+└── start/src/test/java/com/yourcompany/
+    └── ArchitectureComplianceTest.java   ← 架构校验测试类
+```
+
+## ArchUnit 校验测试
+
+```java
+package com.yourcompany;
+
+import com.tngtech.archunit.junit.AnalyzeClasses;
+import com.tngtech.archunit.junit.ArchTest;
+import com.tngtech.archunit.lang.ArchRule;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
+
+@AnalyzeClasses(packages = "com.yourcompany")
+public class ArchitectureComplianceTest {
+
+    // ── P0: Domain 层零依赖 ──
+
+    @ArchTest
+    static final ArchRule domain_not_depend_infrastructure =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..infrastructure..")
+            .because("Domain 层不能依赖 Infrastructure");
+
+    @ArchTest
+    static final ArchRule domain_not_depend_app =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..app..")
+            .because("Domain 层不能依赖 App");
+
+    @ArchTest
+    static final ArchRule domain_not_depend_adapter =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..adapter..")
+            .because("Domain 层不能依赖 Adapter");
+
+    // ── P0: Domain 无框架依赖 ──
+
+    @ArchTest
+    static final ArchRule domain_no_spring =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAnyPackage("org.springframework..", "org.springframework.stereotype..")
+            .because("Domain 层禁止 Spring 依赖");
+
+    @ArchTest
+    static final ArchRule domain_no_jpa =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAnyPackage("javax.persistence..", "jakarta.persistence..")
+            .because("Domain 层禁止 JPA 依赖");
+
+    @ArchTest
+    static final ArchRule domain_no_mybatis =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAnyPackage("org.apache.ibatis..")
+            .because("Domain 层禁止 MyBatis 依赖");
+
+    // ── P0: Adapter 层不应访问 Infrastructure ──
+
+    @ArchTest
+    static final ArchRule adapter_not_depend_infrastructure =
+        noClasses()
+            .that().resideInAPackage("..adapter..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..infrastructure..")
+            .because("Adapter 必须通过 App 层访问基础设施");
+
+    // ── P1: 包命名合规 ──
+
+    @ArchTest
+    static final ArchRule domain_no_controller =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().resideInAPackage("..controller..")
+            .because("Controller 属于 Adapter 层");
+
+    @ArchTest
+    static final ArchRule adapter_no_repository =
+        noClasses()
+            .that().resideInAPackage("..adapter..")
+            .should().resideInAPackage("..repository..")
+            .because("Repository 属于 Domain 或 Infrastructure 层");
+}
+```
+
+## Maven 依赖
+
+```xml
+<dependency>
+    <groupId>com.tngtech.archunit</groupId>
+    <artifactId>archunit-junit5</artifactId>
+    <version>1.2.0</version>
+    <scope>test</scope>
+</dependency>
+```
+
+## CI/CD 集成
+
+### GitHub Actions
+
+```yaml
+name: COLA Architecture Check
+on: [push, pull_request]
+jobs:
+  architecture-check:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - name: Set up JDK 17
+        uses: actions/setup-java@v4
+        with:
+          java-version: '17'
+          distribution: 'temurin'
+      - name: Run Architecture Tests
+        run: mvn test -Dtest=ArchitectureComplianceTest
+      - name: Check Score
+        run: python scripts/check_cola.py .
+```
+
+### GitLab CI
+
+```yaml
+cola-architecture-check:
+  stage: test
+  image: eclipse-temurin:17
+  script:
+    - mvn test -Dtest=ArchitectureComplianceTest
+    - python3 scripts/check_cola.py .
+  only:
+    - merge_requests
+    - main
+```
+
+## 运行方式
+
+```bash
+# 本地运行
+mvn test -Dtest=ArchitectureComplianceTest
+
+# Python 轻量校验(无需编译)
+python scripts/check_cola.py src/
+
+# 查看评分
+# 输出示例:
+# 模块: adapter, app, domain, infrastructure, start
+# 违规: 2 (P0:0, P1:2)
+# 评分: 90 → A(优秀)
+```

+ 122 - 0
skills/ddd-skills/ddd-architecture-cola/examples/06-monolith-simple.md

@@ -0,0 +1,122 @@
+# COLA 项目规模示例:单体简单项目
+
+> 适用场景:小型单体应用,单一业务域,2-5 人团队,CRUD 为主,无需微服务拆分。
+
+## 项目目录树
+
+```
+order-service/                         # 单体项目,spring-boot-maven-plugin 打包
+├── pom.xml                            # 单模块,无多模块划分
+├── src/
+│   ├── main/java/com/example/order/
+│   │   ├── OrderApplication.java      # @SpringBootApplication + @EnableCola 启动入口
+│   │   │
+│   │   ├── adapter/                   # 适配层
+│   │   │   ├── web/
+│   │   │   │   ├── OrderController.java
+│   │   │   │   └── dto/
+│   │   │   │       ├── OrderCreateRequest.java
+│   │   │   │       └── OrderResponse.java
+│   │   │   └── advice/
+│   │   │       └── GlobalExceptionHandler.java
+│   │   │
+│   │   ├── app/                       # 应用层
+│   │   │   ├── executor/
+│   │   │   │   ├── command/
+│   │   │   │   │   └── OrderCreateCmdExe.java
+│   │   │   │   └── query/
+│   │   │   │       └── OrderGetQryExe.java
+│   │   │   └── model/
+│   │   │       ├── command/
+│   │   │       │   └── OrderCreateCmd.java
+│   │   │       └── query/
+│   │   │           └── OrderGetQry.java
+│   │   │
+│   │   ├── domain/                    # 领域层 ★ 零框架依赖
+│   │   │   ├── model/
+│   │   │   │   ├── Order.java         # 聚合根
+│   │   │   │   ├── OrderItem.java     # 实体
+│   │   │   │   ├── OrderId.java       # 值对象
+│   │   │   │   ├── OrderStatus.java   # 枚举
+│   │   │   │   ├── Money.java         # 值对象
+│   │   │   │   └── event/
+│   │   │   │       ├── OrderCreatedEvent.java
+│   │   │   │       └── OrderPaidEvent.java
+│   │   │   └── repository/
+│   │   │       └── OrderRepository.java  # 仓储接口
+│   │   │
+│   │   └── infrastructure/            # 基础设施层
+│   │       ├── config/
+│   │       │   └── DataSourceConfig.java
+│   │       ├── persistence/
+│   │       │   ├── OrderRepositoryImpl.java
+│   │       │   ├── OrderMapper.java       # MyBatis Mapper
+│   │       │   ├── OrderPO.java           # 持久化对象
+│   │       │   └── OrderConverter.java    # PO ↔ DO 转换
+│   │       └── util/
+│   │           └── SnowflakeIdGenerator.java
+│   │
+│   ├── main/resources/
+│   │   ├── application.yml
+│   │   └── db/migration/
+│   │       └── V1__create_order_table.sql
+│   └── test/java/com/example/order/
+│       ├── ArchitectureComplianceTest.java  # ArchUnit 校验
+│       └── domain/
+│           └── OrderTest.java
+```
+
+## 包结构说明
+
+| 包 | 内容 | 说明 |
+|----|------|------|
+| `adapter/` | Controller、DTO、ExceptionHandler | HTTP 协议适配,请求/响应转换 |
+| `app/` | Command/Query Executor | 用例编排,事务管理 |
+| `domain/` | Entity、VO、Aggregate、Repository 接口 | 核心业务逻辑,零框架依赖 |
+| `infrastructure/` | RepositoryImpl、Mapper、PO、Config | 持久化实现、外部调用、配置 |
+
+## COLA 四层职责分工
+
+| 层 | 职责 | 禁止事项 |
+|----|------|---------|
+| **Adapter** | 接收 HTTP 请求,DTO 校验与转换,调用 App 层 | 禁止包含业务逻辑、禁止直接操作 Mapper |
+| **Application** | 用例编排,事务边界控制,领域事件发布 | 禁止包含业务 if/else 判断 |
+| **Domain** ★ | 实体行为、值对象不变性、领域事件定义 | 禁止依赖 Spring/MyBatis/JPA |
+| **Infrastructure** | Repository 实现,PO↔Domain 转换,外部服务调用 | 禁止包含业务规则 |
+
+## 模块间依赖关系
+
+```
+┌──────────┐
+│  adapter  │────依赖──→┐
+└──────────┘           │
+                       ▼
+┌──────────┐     ┌──────────┐
+│    app    │────→│  domain   │←────┌──────────────────┐
+└──────────┘     └──────────┘     │  infrastructure    │
+                                 └──────────────────┘
+```
+
+依赖方向:`adapter → app → domain ← infrastructure`
+
+## 适用场景
+
+- 项目总代码量 < 5 万行
+- 单一业务上下文(如订单服务只有一个 Bounded Context)
+- 团队 2-5 人,后端开发 1-3 人
+- 无微服务拆分需求
+- 快速原型验证 / MVP 阶段
+- CRUD 操作为主,业务规则较简单
+
+## 优点
+
+- 结构简单,新人快速上手
+- 构建速度快,无模块间编译依赖
+- 单 jar 部署,运维成本低
+- 开发初期迭代效率高
+
+## 缺点
+
+- 无法按模块限制依赖方向(需 ArchUnit 强制)
+- 代码量增大后包内文件过多
+- 不易拆分为微服务

+ 242 - 0
skills/ddd-skills/ddd-architecture-cola/examples/07-monolith-complex.md

@@ -0,0 +1,242 @@
+# COLA 项目规模示例:单体复杂项目
+
+> 适用场景:中型单体应用,多聚合根,多业务上下文,5-15 人团队,有复杂业务编排需求。
+
+## 项目目录树
+
+```
+mall-service/                                     # 单体项目,多聚合
+├── pom.xml
+├── src/main/java/com/example/mall/
+│   ├── MallApplication.java                      # @SpringBootApplication + @EnableCola
+│   │
+│   ├── adapter/                                  # 适配层
+│   │   ├── web/
+│   │   │   ├── order/
+│   │   │   │   └── OrderController.java
+│   │   │   ├── product/
+│   │   │   │   └── ProductController.java
+│   │   │   ├── customer/
+│   │   │   │   └── CustomerController.java
+│   │   │   ├── payment/
+│   │   │   │   └── PaymentController.java
+│   │   │   └── dto/
+│   │   │       ├── common/
+│   │   │       │   ├── PageRequest.java
+│   │   │       │   └── ApiResponse.java
+│   │   │       ├── order/
+│   │   │       │   ├── OrderCreateRequest.java
+│   │   │       │   └── OrderResponse.java
+│   │   │       └── product/
+│   │   │           └── ProductResponse.java
+│   │   ├── job/                                  # 定时任务
+│   │   │   ├── OrderExpireJob.java
+│   │   │   └── DailyReportJob.java
+│   │   ├── message/                              # MQ 消费者
+│   │   │   ├── PaymentResultConsumer.java
+│   │   │   └── InventoryChangeConsumer.java
+│   │   └── rpc/                                  # RPC 接口
+│   │       └── OrderQueryFacade.java
+│   │
+│   ├── app/                                      # 应用层
+│   │   ├── executor/
+│   │   │   ├── command/
+│   │   │   │   ├── order/
+│   │   │   │   │   ├── OrderCreateCmdExe.java
+│   │   │   │   │   ├── OrderCancelCmdExe.java
+│   │   │   │   │   └── OrderPayCmdExe.java
+│   │   │   │   ├── product/
+│   │   │   │   │   └── ProductDeductStockCmdExe.java
+│   │   │   │   └── customer/
+│   │   │   │       └── CustomerRegisterCmdExe.java
+│   │   │   ├── query/
+│   │   │   │   ├── order/
+│   │   │   │   │   ├── OrderDetailQryExe.java
+│   │   │   │   │   └── OrderListQryExe.java
+│   │   │   │   └── product/
+│   │   │   │       └── ProductSearchQryExe.java
+│   │   │   └── event/
+│   │   │       └── handler/
+│   │   │           ├── PaymentCompletedHandler.java
+│   │   │           └── InventoryDeductedHandler.java
+│   │   ├── model/
+│   │   │   ├── command/
+│   │   │   │   ├── order/
+│   │   │   │   │   ├── OrderCreateCmd.java
+│   │   │   │   │   ├── OrderCancelCmd.java
+│   │   │   │   │   └── OrderPayCmd.java
+│   │   │   │   └── product/
+│   │   │   │       └── ProductDeductStockCmd.java
+│   │   │   ├── query/
+│   │   │   │   ├── order/
+│   │   │   │   │   ├── OrderDetailQry.java
+│   │   │   │   │   └── OrderListQry.java
+│   │   │   │   └── product/
+│   │   │   │       └── ProductSearchQry.java
+│   │   │   └── dto/
+│   │   │       ├── OrderDTO.java
+│   │   │       └── ProductDTO.java
+│   │   ├── service/                              # 非 CQRS 的服务编排
+│   │   │   ├── OrderPlacementService.java        # 下单流程编排:校验+锁库存+创建订单+发事件
+│   │   │   └── PaymentReconciliationService.java # 对账编排
+│   │   └── extension/                            # COLA 扩展点
+│   │       ├── point/
+│   │       │   └── PaymentMethodExtPt.java       # 支付方式扩展点
+│   │       └── impl/
+│   │           ├── AlipayPaymentExtension.java
+│   │           └── WechatPaymentExtension.java
+│   │
+│   ├── domain/                                   # 领域层 ★
+│   │   ├── order/                                # 订单聚合
+│   │   │   ├── Order.java                       # 聚合根
+│   │   │   ├── OrderItem.java                   # 实体
+│   │   │   ├── OrderId.java                     # 值对象
+│   │   │   ├── OrderStatus.java                 # 枚举
+│   │   │   ├── event/
+│   │   │   │   ├── OrderCreatedEvent.java
+│   │   │   │   ├── OrderPaidEvent.java
+│   │   │   │   └── OrderCancelledEvent.java
+│   │   │   └── repository/
+│   │   │       └── OrderRepository.java
+│   │   ├── product/                              # 商品聚合
+│   │   │   ├── Product.java
+│   │   │   ├── ProductId.java
+│   │   │   ├── Stock.java                       # 值对象
+│   │   │   ├── Category.java
+│   │   │   └── repository/
+│   │   │       └── ProductRepository.java
+│   │   ├── customer/                             # 客户聚合
+│   │   │   ├── Customer.java
+│   │   │   ├── CustomerId.java
+│   │   │   ├── Address.java
+│   │   │   └── repository/
+│   │   │       └── CustomerRepository.java
+│   │   ├── payment/                              # 支付领域(弱实体)
+│   │   │   ├── Payment.java
+│   │   │   ├── PaymentId.java
+│   │   │   ├── PaymentResult.java
+│   │   │   └── repository/
+│   │   │       └── PaymentRepository.java
+│   │   ├── shared/                               # 共享值对象
+│   │   │   ├── Money.java
+│   │   │   ├── Quantity.java
+│   │   │   └── Pageable.java
+│   │   ├── gateway/                              # 防腐层接口
+│   │   │   ├── InventoryGateway.java
+│   │   │   └── PaymentGateway.java
+│   │   └── ability/                              # 领域能力 (v5)
+│   │       ├── StockReservationAbility.java
+│   │       └── PriceCalculationAbility.java
+│   │
+│   └── infrastructure/                           # 基础设施层
+│       ├── config/
+│       │   ├── DataSourceConfig.java
+│       │   ├── CacheConfig.java
+│       │   ├── MQConfig.java
+│       │   └── RpcConfig.java
+│       ├── persistence/
+│       │   ├── order/
+│       │   │   ├── OrderRepositoryImpl.java
+│       │   │   ├── OrderMapper.java
+│       │   │   ├── OrderPO.java
+│       │   │   └── OrderConverter.java
+│       │   ├── product/
+│       │   │   ├── ProductRepositoryImpl.java
+│       │   │   ├── ProductMapper.java
+│       │   │   ├── ProductPO.java
+│       │   │   └── ProductConverter.java
+│       │   ├── customer/
+│       │   │   ├── CustomerRepositoryImpl.java
+│       │   │   ├── CustomerMapper.java
+│       │   │   ├── CustomerPO.java
+│       │   │   └── CustomerConverter.java
+│       │   └── payment/
+│       │       ├── PaymentRepositoryImpl.java
+│       │       ├── PaymentMapper.java
+│       │       ├── PaymentPO.java
+│       │       └── PaymentConverter.java
+│       ├── gatewayimpl/
+│       │   ├── InventoryGatewayImpl.java         # 调用外部库存系统
+│       │   └── PaymentGatewayImpl.java           # 调用微信/支付宝
+│       ├── external/
+│       │   ├── WechatPayClient.java
+│       │   ├── AlipayClient.java
+│       │   └── LogisticsClient.java
+│       └── component/
+│           ├── DistributedLock.java
+│           └── RateLimiter.java
+```
+
+## 包结构说明
+
+| 包 | 内容 | 说明 |
+|----|------|------|
+| `adapter/` | 按业务域分组的 Controller + 消息消费者 + 定时任务 + RPC Facade | 多协议适配入口 |
+| `app/` | 按业务域分组的 Executor + Service + Extension | 复杂业务编排,扩展点路由 |
+| `domain/` | 按聚合根分组的 Entity/VO/Repository 接口 + Shared 共享值对象 | 多聚合,聚合间通过 ID 引用 |
+| `infrastructure/` | 按业务域分组的 RepositoryImpl/Mapper/PO + 公共组件 | 持久化实现 + 外部服务 + 基础设施组件 |
+
+## COLA 四层职责分工
+
+| 层 | 职责 | 复杂单体特殊注意 |
+|----|------|----------------|
+| **Adapter** | 多协议适配 (HTTP/MQ/RPC/Job) | 按业务域分 controller 包,避免单文件过大 |
+| **Application** | 跨聚合业务编排、事件驱动流程 | `app/service/` 承担 Saga 编排,Executor 只做单聚合操作 |
+| **Domain** ★ | 多聚合独立建模,聚合间通过 ID 间接引用 | 严禁跨聚合对象直接引用 (如 `Order.getCustomer()`) |
+| **Infrastructure** | 多数据源、外部服务调用、分布式组件 | PO 与 Domain 必须分离,用 Converter 转换 |
+
+## 模块间依赖关系
+
+```
+         ┌─────────────────────────────────┐
+         │           adapter                │
+         │  HTTP / MQ / RPC / Job          │
+         └───────────────┬─────────────────┘
+                         │ depends
+                         ▼
+         ┌─────────────────────────────────┐
+         │             app                  │
+         │  Executor / Service / Extension  │
+         └───────┬─────────────────────────┘
+                 │ depends
+                 ▼
+         ┌─────────────────────────────────┐
+         │           domain  ★              │
+         │  Order / Product / Customer /    │
+         │  Payment / Shared               │
+         └─────────────────────────────────┘
+                         ▲
+                         │ depends
+         ┌───────────────┴─────────────────┐
+         │        infrastructure            │
+         │  RepositoryImpl / Gateway /      │
+         │  External / Component            │
+         └─────────────────────────────────┘
+```
+
+依赖方向:`adapter → app → domain ← infrastructure`
+
+聚合间依赖约束:订单聚合通过 `ProductId` 引用商品,不直接持有 `Product` 对象。
+
+## 适用场景
+
+- 项目总代码量 5-15 万行
+- 多个 Bounded Context 但共享同一数据库(演进阶段)
+- 有复杂业务编排(下单流程涉及订单+库存+支付+物流)
+- 团队 5-15 人,后端开发 3-8 人
+- 业务规则较复杂,多聚合交互频繁
+- 未来可能拆分为微服务,但目前各聚合内聚在单体中
+
+## 优点
+
+- 多聚合在单体中紧密协作,无需 RPC 开销
+- 事务管理简单(同数据库本地事务)
+- 相比单聚合单体,代码组织更清晰
+- 为未来微服务拆分做包级别准备
+
+## 缺点
+
+- App 层编排可能随着业务增长变得复杂(需引入 Saga 模式)
+- 单 jar 体积增大,冷启动耗时增加
+- 多团队协作时 Git 冲突增加
+- 无法独立部署单一聚合

+ 180 - 0
skills/ddd-skills/ddd-architecture-cola/examples/08-monolith-multi-module.md

@@ -0,0 +1,180 @@
+# COLA 项目规模示例:单体多模块项目
+
+> 适用场景:中型单体应用,需要 Maven 多模块强制隔离依赖方向,5-15 人团队,对架构约束要求高。
+
+## 项目目录树
+
+```
+order-system/                                   # 父 POM,packaging=pom
+├── pom.xml                                     # 父 POM,定义 modules + dependencyManagement
+│
+├── order-start/                                # 启动模块
+│   ├── pom.xml                                 # 依赖所有其他模块,含 spring-boot-maven-plugin
+│   └── src/main/java/com/example/order/
+│       ├── OrderApplication.java               # @SpringBootApplication + @EnableCola
+│       └── config/
+│           ├── CorsConfig.java
+│           └── SwaggerConfig.java
+│
+├── order-adapter/                              # 适配层模块
+│   ├── pom.xml                                 # 依赖 order-app、order-domain
+│   └── src/main/java/com/example/order/adapter/
+│       ├── web/
+│       │   ├── OrderController.java
+│       │   └── dto/
+│       │       ├── OrderCreateRequest.java
+│       │       └── OrderResponse.java
+│       ├── rpc/
+│       │   └── OrderQueryFacade.java
+│       └── advice/
+│           └── GlobalExceptionHandler.java
+│
+├── order-app/                                  # 应用层模块
+│   ├── pom.xml                                 # 依赖 order-domain、order-infrastructure
+│   └── src/main/java/com/example/order/app/
+│       ├── executor/
+│       │   ├── command/
+│       │   │   └── OrderCreateCmdExe.java
+│       │   └── query/
+│       │       └── OrderGetQryExe.java
+│       ├── model/
+│       │   ├── command/
+│       │   │   └── OrderCreateCmd.java
+│       │   └── query/
+│       │       └── OrderGetQry.java
+│       ├── service/
+│       │   └── OrderPlacementService.java
+│       └── assembler/
+│           └── OrderAssembler.java
+│
+├── order-domain/                               # 领域层模块 ★ 零 external 依赖
+│   ├── pom.xml                                 # 零外部依赖(仅 lombok、validation-api)
+│   └── src/main/java/com/example/order/domain/
+│       ├── model/
+│       │   ├── Order.java                      # 聚合根
+│       │   ├── OrderItem.java                  # 实体
+│       │   ├── OrderId.java                    # 值对象
+│       │   ├── OrderStatus.java
+│       │   ├── Money.java
+│       │   └── event/
+│       │       ├── OrderCreatedEvent.java
+│       │       └── OrderPaidEvent.java
+│       ├── repository/
+│       │   └── OrderRepository.java            # 仓储接口
+│       ├── gateway/
+│       │   └── InventoryGateway.java           # 防腐层接口
+│       └── ability/
+│           └── PriceCalculationAbility.java
+│
+├── order-infrastructure/                       # 基础设施层模块
+│   ├── pom.xml                                 # 依赖 order-domain
+│   └── src/main/java/com/example/order/infrastructure/
+│       ├── config/
+│       │   ├── DataSourceConfig.java
+│       │   └── CacheConfig.java
+│       ├── persistence/
+│       │   ├── OrderRepositoryImpl.java
+│       │   ├── OrderMapper.java
+│       │   ├── OrderPO.java
+│       │   └── OrderConverter.java
+│       └── gatewayimpl/
+│           └── InventoryGatewayImpl.java
+│
+└── order-common/                               # 公共模块(可选)
+    ├── pom.xml                                 # 无内部模块依赖
+    └── src/main/java/com/example/order/common/
+        ├── constant/
+        │   └── BizConstants.java
+        ├── exception/
+        │   ├── BizException.java
+        │   └── ErrorCode.java
+        └── context/
+            └── UserContext.java
+```
+
+## 各模块的包结构说明
+
+| 模块 | 包路径 | 内容 | Maven ArtifactId |
+|------|--------|------|-----------------|
+| **启动模块** | `com.example.order` | Application 启动类 + 全局配置 | `order-start` |
+| **适配层** | `com.example.order.adapter` | Controller / RPC / DTO / ExceptionHandler | `order-adapter` |
+| **应用层** | `com.example.order.app` | Executor / Service / Assembler / Model | `order-app` |
+| **领域层** | `com.example.order.domain` | Entity / VO / Aggregate / Repository 接口 | `order-domain` |
+| **基础设施层** | `com.example.order.infrastructure` | RepositoryImpl / Mapper / PO / GatewayImpl | `order-infrastructure` |
+| **公共模块** | `com.example.order.common` | 常量 / 异常基类 / 上下文 / 工具 | `order-common` |
+
+## COLA 四层职责分工
+
+| 层 | 对应模块 | 职责 | Maven 依赖约束 |
+|----|---------|------|---------------|
+| **Adapter** | `order-adapter` | HTTP/RPC 协议适配,DTO 转换 | 可引用 app + domain + common |
+| **Application** | `order-app` | 用例编排,事务管理,扩展点 | 可引用 domain + infrastructure + common |
+| **Domain** ★ | `order-domain` | 核心业务规则 | **零外部依赖**,仅可引用 common |
+| **Infrastructure** | `order-infrastructure` | 持久化、外部服务、组件 | 可引用 domain + common |
+| **启动** | `order-start` | 启动入口、全局配置 | 引用所有其他模块 |
+| **公共** | `order-common` | 常量、异常、上下文 | 无项目内依赖 |
+
+## 模块间依赖关系图
+
+```
+┌──────────────────────────────────────────────────────────────────┐
+│                        order-start                               │
+│          (启动模块 — 引用所有其他模块)                               │
+└────┬───────────┬──────────┬──────────┬──────────┬───────────────┘
+     │           │          │          │          │
+     ▼           ▼          ▼          ▼          ▼
+┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
+│ adapter │ │   app   │ │ domain  │ │  infra  │ │ common  │
+│         │ │         │ │    ★    │ │         │ │         │
+└────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ └─────────┘
+     │           │           │           │           ▲
+     │      ┌────┘           │           │           │
+     │      │                │           │           │
+     ▼      ▼                ▼           ▼           │
+┌───────────────────────────────────────────────────┐│
+│              Maven 依赖关系图                      ││
+│                                                   ││
+│  adapter ───→ app ───→ domain ←─── infrastructure ││
+│     │         │         ▲              │          ││
+│     └────┬────┘         │              │          ││
+│          └──────────────┼──────────────┘          ││
+│                         └── common ←──────────────┘│
+└────────────────────────────────────────────────────┘
+```
+
+**硬约束**(由 Maven compile-scope 依赖保证):
+- `order-domain` 的 pom.xml 中不出现 `order-adapter`、`order-app`、`order-infrastructure`、`spring-boot-starter`、`mybatis-spring-boot-starter` 等依赖
+- `order-app` 不直接引用 `order-adapter`
+- `order-infrastructure` 不引用 `order-app`、`order-adapter`
+
+**验证方式**:
+```xml
+<!-- order-domain/pom.xml: 领域层只能依赖这些 -->
+<dependency>
+    <groupId>com.example.order</groupId>
+    <artifactId>order-common</artifactId>
+</dependency>
+<!-- 不允许出现 spring-boot-starter、mybatis、jpa 等 -->
+```
+
+## 适用场景
+
+- 需要 Maven 模块编译时强制依赖约束(比 ArchUnit 更早发现问题)
+- 团队 5-15 人,多人并行开发同一项目
+- 业务复杂度中等,单一 Bounded Context 但有丰富行为
+- 需要确保架构不被新手开发者破坏
+- 单个 Git 仓库管理,不想拆分为多仓库
+
+## 优点
+
+- Maven 编译时即发现依赖违规(比 ArchUnit 运行时更早)
+- 各模块独立编译,仅需重新编译变更模块
+- 团队可按模块分工(Domain 资深开发 / Infra 一般开发)
+- 为未来微服务拆分做模块级准备
+
+## 缺点
+
+- 模块间接口变化影响编译范围增大
+- Maven 多模块构建时间比单模块长
+- 新手需要理解模块间的接口抽象(如 Repository 接口在 Domain,实现在 Infra)
+- Common 模块容易变成"垃圾桶"(需严格控制内容)

+ 141 - 0
skills/ddd-skills/ddd-architecture-cola/examples/09-microservice-simple-monolith.md

@@ -0,0 +1,141 @@
+# COLA 项目规模示例:微服务简单的单体项目
+
+> 适用场景:微服务架构,每个微服务内部采用 COLA 单体结构(非多模块),服务边界清晰,业务简单。
+
+## 项目目录树
+
+```
+├── order-service/                              # 订单微服务 (COLA 单体)
+│   ├── pom.xml
+│   └── src/main/java/com/example/order/
+│       ├── OrderApplication.java
+│       ├── adapter/
+│       │   ├── web/OrderController.java         # 对前端暴露 REST
+│       │   └── rpc/OrderQueryFacade.java         # 对其他微服务暴露 Dubbo/gRPC
+│       ├── app/
+│       │   ├── executor/command/OrderCreateCmdExe.java
+│       │   └── executor/query/OrderGetQryExe.java
+│       ├── domain/
+│       │   ├── Order.java
+│       │   ├── OrderItem.java
+│       │   └── repository/OrderRepository.java
+│       └── infrastructure/
+│           ├── persistence/OrderRepositoryImpl.java
+│           └── external/ProductServiceClient.java  # 调用商品微服务
+│
+├── product-service/                            # 商品微服务 (COLA 单体)
+│   ├── pom.xml
+│   └── src/main/java/com/example/product/
+│       ├── ProductApplication.java
+│       ├── adapter/
+│       │   ├── web/ProductController.java
+│       │   └── rpc/ProductRpcFacade.java
+│       ├── app/
+│       │   ├── executor/command/ProductCreateCmdExe.java
+│       │   └── executor/query/ProductSearchQryExe.java
+│       ├── domain/
+│       │   ├── Product.java
+│       │   ├── Stock.java
+│       │   └── repository/ProductRepository.java
+│       └── infrastructure/
+│           ├── persistence/ProductRepositoryImpl.java
+│           └── search/ProductElasticsearchRepo.java
+│
+├── customer-service/                           # 客户微服务 (COLA 单体)
+│   ├── pom.xml
+│   └── src/main/java/com/example/customer/
+│       ├── CustomerApplication.java
+│       ├── adapter/
+│       │   └── web/CustomerController.java
+│       ├── app/
+│       │   └── executor/command/CustomerRegisterCmdExe.java
+│       ├── domain/
+│       │   ├── Customer.java
+│       │   └── repository/CustomerRepository.java
+│       └── infrastructure/
+│           └── persistence/CustomerRepositoryImpl.java
+│
+├── gateway-service/                            # API 网关 (可选)
+│   └── ...
+│
+└── common/                                     # 公共组件(共享 DTO、工具类)
+    ├── common-api/                             # 服务间通信 DTO
+    │   ├── OrderDTO.java
+    │   └── ProductDTO.java
+    └── common-util/
+        ├── ApiResponse.java
+        └── BizException.java
+```
+
+## 各服务的包结构说明
+
+每个微服务内部采用与示例 06 相同的 COLA 单体包结构:
+
+| 微服务 | Adapter 协议 | 领域聚合 | 对外依赖 |
+|--------|-------------|---------|---------|
+| `order-service` | REST + Dubbo RPC | Order + OrderItem | product-service, customer-service |
+| `product-service` | REST + Dubbo RPC | Product + Stock | — (被调用方) |
+| `customer-service` | REST | Customer | — (被调用方) |
+
+## COLA 四层职责分工
+
+| 层 | 职责 | 微服务环境特殊注意 |
+|----|------|------------------|
+| **Adapter** | REST (对外) + RPC/Dubbo (服务间) + MQ Consumer | Adapter 同时暴露 Web API 和 RPC API |
+| **Application** | 单聚合用例编排 | 涉及调用其他微服务时通过 Gateway/防腐层,不在 Executor 直接调用 |
+| **Domain** ★ | 服务内的业务规则 | 聚合不可直接引用其他微服务的 Domain 对象 |
+| **Infrastructure** | 本地持久化 + 外部微服务调用 | external/ 封装对其他微服务的调用,不暴露技术细节 |
+
+## 服务间依赖关系
+
+```
+                    ┌──────────────────┐
+                    │   order-service  │
+                    │                  │
+                    │  adapter (REST)  │←─ 前端请求
+                    │  adapter (RPC)   │←─ 其他服务调用
+                    │  app             │
+                    │  domain          │
+                    │  infra (DB +     │
+                    │    FeignClient   │─────── 调用 ───────┐
+                    │  → ProductSvc)   │                    │
+                    └──────────────────┘                    │
+                                                            ▼
+┌──────────────────┐        ┌──────────────────┐  ┌──────────────────┐
+│ customer-service │        │ product-service  │  │   common-api     │
+│                  │        │                  │  │                  │
+│  adapter (REST)  │        │  adapter (REST)  │  │  共享 DTO         │
+│  app             │        │  adapter (RPC)   │  │  OrderDTO        │
+│  domain          │        │  app             │  │  ProductDTO      │
+│  infra           │        │  domain          │  │  ApiResponse     │
+└──────────────────┘        │  infra           │  └──────────────────┘
+                            └──────────────────┘
+```
+
+**依赖原则**:
+- 每个微服务独立数据库,不共享表
+- 服务间通过 RPC/MQ 通信,不直接访问对方数据库
+- `common-api` 发布为 Maven 坐标,各服务通过依赖引用共享 DTO
+- 服务内的 COLA 分层规则不变:Domain 仍然零框架依赖
+
+## 适用场景
+
+- 微服务已经拆分完成,每个服务职责单一
+- 每个微服务代码量 < 3 万行
+- 每个微服务内业务逻辑相对简单(1-2 个聚合)
+- 服务间通过 RPC (Dubbo/gRPC) 或 MQ (RocketMQ/Kafka) 通信
+- 团队 10-30 人,每个服务由 2-3 人小团队负责
+
+## 优点
+
+- 每个服务简单,新人快速上手
+- 独立部署、独立扩缩容
+- 单模块构建快,CI 效率高
+- 技术栈可按服务选择(如商品服务用 Elasticsearch,订单服务用 MySQL)
+
+## 缺点
+
+- 服务内无法用编译时约束防止架构腐化(单模块)
+- `common-api` 修改影响所有服务
+- 需要处理分布式事务(Saga/最终一致性)
+- 服务数量增多后运维成本高

+ 231 - 0
skills/ddd-skills/ddd-architecture-cola/examples/10-microservice-complex-monolith.md

@@ -0,0 +1,231 @@
+# COLA 项目规模示例:微服务复杂的单体项目
+
+> 适用场景:微服务架构,网关/核心服务内部采用 COLA 单体结构,基础设施复杂(认证、限流、加密、路由),基于 ddd4j-gateway 真实结构。
+
+## 参考项目
+
+本示例基于真实项目 `ddd4j-gateway`(`io.ddd4j:ddd4j-gateway`)的结构提取。
+
+## 项目目录树
+
+```
+ddd4j-gateway/                                     # API 网关微服务 — 单体 COLA 结构
+├── pom.xml                                        # 继承 ddd4j-boot-parent
+│                                                  # 依赖:spring-boot, spring-cloud-gateway,
+│                                                  #       sa-token, redisson, fastjson2,
+│                                                  #       guava, hutool, kaptcha, commons-lang3
+├── src/
+│   ├── main/java/io/ddd4j/gateway/
+│   │   │
+│   │   ├── start/                                 # 启动 + 装配
+│   │   │   ├── GatewayApplication.java            # @EnableCola 启动类
+│   │   │   └── assembler/
+│   │   │       └── GatewayAssembler.java          # 启动时的组件装配
+│   │   │
+│   │   ├── adapter/                               # 适配层 (6 个 Java 文件)
+│   │   │   ├── web/
+│   │   │   │   ├── route/
+│   │   │   │   │   └── GatewayRouteController.java   # 路由管理 REST 接口
+│   │   │   │   └── dto/
+│   │   │   │       ├── request/
+│   │   │   │       │   ├── RouteSaveRequest.java
+│   │   │   │       │   └── CryptoKeyRequest.java
+│   │   │   │       └── response/
+│   │   │   │           ├── RouteResponse.java
+│   │   │   │           └── CryptoKeyResponse.java
+│   │   │   └── advice/
+│   │   │       └── GlobalExceptionHandler.java    # 统一异常处理
+│   │   │
+│   │   ├── app/                                   # 应用层 (11 个 Java 文件)
+│   │   │   ├── executor/
+│   │   │   │   ├── command/                       # 命令执行器
+│   │   │   │   │   ├── crypto/
+│   │   │   │   │   │   ├── GenerateKeyCmdExe.java      # 生成密钥
+│   │   │   │   │   │   └── RotateKeyCmdExe.java        # 密钥轮转
+│   │   │   │   │   └── route/
+│   │   │   │   │       ├── SaveRouteCmdExe.java        # 保存路由配置
+│   │   │   │   │       └── RefreshRouteCmdExe.java     # 刷新路由缓存
+│   │   │   │   └── query/                        # 查询执行器
+│   │   │   │       ├── crypto/
+│   │   │   │       │   └── QueryKeyQryExe.java
+│   │   │   │       └── route/
+│   │   │   │           └── QueryRouteQryExe.java
+│   │   │   ├── model/                            # 命令/查询/DTO 对象
+│   │   │   │   ├── command/
+│   │   │   │   │   ├── GenerateKeyCmd.java
+│   │   │   │   │   ├── SaveRouteCmd.java
+│   │   │   │   │   └── RefreshRouteCmd.java
+│   │   │   │   └── query/
+│   │   │   │       ├── QueryKeyQry.java
+│   │   │   │       └── QueryRouteQry.java
+│   │   │   ├── handler/                          # 处理器
+│   │   │   │   └── GatewayRouteHandler.java
+│   │   │   ├── extension/                        # COLA 扩展点
+│   │   │   │   └── RateLimitExtension.java
+│   │   │   └── config/
+│   │   │       └── AppConfig.java
+│   │   │
+│   │   ├── domain/                                # 领域层 ★ (30 个 Java 文件)
+│   │   │   ├── repository/                        # 仓储接口
+│   │   │   │   ├── RouteRepository.java          # 路由仓储
+│   │   │   │   └── CryptoKeyRepository.java      # 密钥仓储
+│   │   │   └── util/
+│   │   │       ├── RouteValidator.java            # 路由校验逻辑
+│   │   │       └── CryptoAlgorithm.java           # 加密算法领域逻辑
+│   │   │
+│   │   └── infrastructure/                        # 基础设施层 (52 个 Java 文件)
+│   │       ├── config/                            # 配置
+│   │       │   ├── GatewayConfig.java
+│   │       │   ├── RedisConfig.java
+│   │       │   └── ThreadPoolConfig.java
+│   │       ├── component/                         # 技术组件
+│   │       │   ├── crypto/                        # 加密组件
+│   │       │   │   ├── CryptoComponent.java       # 加解密主组件
+│   │       │   │   ├── cache/
+│   │       │   │   │   └── CryptoKeyCache.java    # 密钥缓存
+│   │       │   │   └── strategy/
+│   │       │   │       ├── AesCryptoStrategy.java
+│   │       │   │       └── RsaCryptoStrategy.java
+│   │       │   ├── ratelimit/                     # 限流组件
+│   │       │   │   ├── RateLimitManager.java
+│   │       │   │   └── key/
+│   │       │   │       ├── IpRateLimitKeyResolver.java
+│   │       │   │       └── UserRateLimitKeyResolver.java
+│   │       │   ├── satoken/                       # 认证/鉴权
+│   │       │   │   ├── SaTokenConfig.java
+│   │       │   │   └── StpInterfaceImpl.java
+│   │       │   ├── filter/                        # 网关过滤器 (Spring Cloud Gateway)
+│   │       │   │   ├── log/
+│   │       │   │   │   └── AccessLogFilter.java
+│   │       │   │   ├── global/
+│   │       │   │   │   ├── AuthGlobalFilter.java
+│   │       │   │   │   └── RateLimitGlobalFilter.java
+│   │       │   │   ├── factory/
+│   │       │   │   │   └── CryptoGatewayFilterFactory.java
+│   │       │   │   └── gateway/
+│   │       │   │       └── RouteCacheGatewayFilter.java
+│   │       │   └── error/
+│   │       │       └── GatewayErrorHandler.java
+│   │       ├── constant/                          # 常量
+│   │       │   └── redis/
+│   │       │       └── RedisKeyConstants.java
+│   │       ├── persistence/                       # 持久化
+│   │       │   ├── RouteRepositoryImpl.java
+│   │       │   └── CryptoKeyRepositoryImpl.java
+│   │       └── util/
+│   │           ├── IpUtils.java
+│   │           └── RouteUtils.java
+│   │
+│   ├── main/resources/
+│   │   ├── application.yml                        # 主配置
+│   │   ├── i18n/                                  # 国际化
+│   │   │   ├── messages_zh_CN.properties
+│   │   │   └── messages_en_US.properties
+│   │   └── conf/
+│   │       └── logback-spring.xml
+│   └── test/java/io/ddd4j/gateway/
+│       └── start/
+│           └── GatewayApplicationTest.java
+```
+
+## 包结构分析
+
+ddd4j-gateway 是典型的"微服务复杂的单体"COLA 项目,具有以下特点:
+
+| 层级 | 文件数 | 复杂度特征 |
+|------|:------:|-----------|
+| **start** | 2 | 标准启动入口,带 Assembler 组件装配 |
+| **adapter** | 6 | REST 接口少,主要是路由管理和密钥管理 |
+| **app** | 11 | CQRS 执行器分离,按 crypto/route 子域分组 |
+| **domain** | 30 | 领域对象丰富,Repository 接口 + 领域工具类 |
+| **infrastructure** | 52 | **最复杂层**:加密/限流/认证/过滤器/持久化等大量技术组件 |
+
+文件分布比例:`infrastructure(52) > domain(30) > app(11) > adapter(6) > start(2)`
+
+## COLA 四层职责分工
+
+| 层 | 职责 | 网关服务特殊性 |
+|----|------|--------------|
+| **Adapter** | 路由管理 API、密钥管理 API | 网关的 Adapter 提供管理面 REST 接口,数据面由 Spring Cloud Gateway 过滤器处理 |
+| **Application** | 路由和密钥的 CRUD 编排、缓存刷新 | 命令执行器内触发路由刷新、密钥轮转等副作用 |
+| **Domain** ★ | 路由校验规则、加密算法选择 | 网关的路由合法性校验、加密策略选择体现在领域层 |
+| **Infrastructure** | 过滤器链、加密实现(AES/RSA)、限流、认证(Sa-Token)、Redis 缓存 | Gateway 高度依赖过滤器链路,Infrastructure 承载大量技术基础设施 |
+
+## 模块间依赖关系
+
+```
+┌─────────┐     ┌──────────┐
+│  start   │────→│ adapter  │
+└─────────┘     └────┬─────┘
+                      │
+                      ▼
+┌────────────────────────────────────┐
+│              app                   │
+│  GenerateKeyCmdExe                 │
+│  SaveRouteCmdExe                   │
+│  RefreshRouteCmdExe                │
+│  QueryKeyQryExe / QueryRouteQryExe │
+└──────┬─────────────────────────────┘
+       │
+       ▼
+┌──────────────────────────────────────────────┐
+│                  domain ★                     │
+│  RouteRepository (接口)                       │
+│  CryptoKeyRepository (接口)                   │
+│  RouteValidator / CryptoAlgorithm             │
+└──────────────────────────────────────────────┘
+       ▲
+       │
+┌──────┴──────────────────────────────────────┐
+│              infrastructure                  │
+│  RouteRepositoryImpl                         │
+│  CryptoKeyRepositoryImpl                     │
+│  CryptoComponent (Aes/Rsa)                   │
+│  RateLimitManager                            │
+│  SaTokenConfig (认证)                         │
+│  AuthGlobalFilter / RateLimitGlobalFilter     │
+│  CryptoGatewayFilterFactory                  │
+└──────────────────────────────────────────────┘
+```
+
+## 适用场景
+
+- 网关类微服务(API Gateway / BFF),需要丰富的过滤器链
+- 认证授权服务(OAuth2 / Sa-Token)
+- 基础设施复杂度高(加密/限流/断路器/日志/链路追踪)
+- 业务逻辑相对简单但技术组件非常丰富
+- 单模块即可容纳所有功能区(Maven 多模块反而增加模块间协调成本)
+
+## ddd4j-gateway 的技术栈
+
+| 组件 | 用途 | 所在层 |
+|------|------|--------|
+| Spring Cloud Gateway | API 网关核心 | Infrastructure (filter/) |
+| Sa-Token | 认证鉴权 | Infrastructure (component/satoken/) |
+| Redisson | 分布式锁 + 缓存 | Infrastructure (component/crypto/cache/) |
+| Fastjson2 | JSON 序列化 | 全局(common 依赖) |
+| Guava | 本地缓存、集合工具 | Infrastructure (component/) |
+| Hutool | 通用工具 | Infrastructure (util/) |
+| Kaptcha | 验证码 | Infrastructure (component/) |
+
+## 相比 ddd4j-rednote/ddd4j-pay 的区别
+
+| 特征 | ddd4j-gateway (单体) | ddd4j-rednote/ddd4j-pay (多模块) |
+|------|:---------------------:|:---------------------------------:|
+| 模块数 | 1 | 5+ (含 BOM + Dependencies) |
+| 业务复杂度 | 低(路由管理) | 中-高(业务领域) |
+| 基础设施复杂度 | 极高(过滤器、加密、限流) | 中 |
+| 适用场景 | 网关/基础设施服务 | 业务服务 |
+
+## 优点
+
+- 对于基础设施密集型微服务,单体结构避免模块间接口抽象开销
+- 过滤器、组件、配置集中在同一代码库,调试方便
+- 构建和部署简单(单 jar)
+- Spring Cloud Gateway 的过滤器链天然适合在 Infrastructure 层实现
+
+## 缺点
+
+- Infrastructure 层文件过多(52/101 = 51%),需要严格 package 划分
+- 纯业务逻辑少的服务容易演变为"重量级基础设施+空领域",违背 DDD 初衷
+- 缺少 Maven 编译时依赖约束,需依赖 ArchUnit 运行时校验

+ 209 - 0
skills/ddd-skills/ddd-architecture-cola/examples/11-microservice-simple-multi-module.md

@@ -0,0 +1,209 @@
+# COLA 项目规模示例:微服务简单的多模块项目
+
+> 适用场景:微服务架构,每个业务服务内部采用 Maven 多模块 COLA 结构,业务简单但对架构约束有高要求,基于 ddd4j-rednote 真实结构。
+
+## 参考项目
+
+本示例基于真实项目 `ddd4j-rednote`(`io.ddd4j.rednote:ddd4j-rednote`)的结构提取。
+
+## 项目目录树
+
+```
+ddd4j-rednote/                                      # 父 POM, packaging=pom
+├── pom.xml                                         # 继承 ddd4j-boot-parent, modules=4
+│   <modules>
+│     <module>ddd4j-rednote-bom</module>
+│     <module>ddd4j-rednote-dependencies</module>
+│     <module>ddd4j-rednote-api</module>
+│     <module>ddd4j-rednote-common</module>
+│   </modules>
+│
+├── ddd4j-rednote-bom/                              # BOM (Bill of Materials)
+│   └── pom.xml                                     # 统一版本管理, packaging=pom
+│
+├── ddd4j-rednote-dependencies/                     # 依赖管理
+│   └── pom.xml                                     # 集中管理外部依赖版本, packaging=pom
+│
+├── ddd4j-rednote-api/                              # 业务接口模块 (聚合子模块)
+│   ├── pom.xml                                     # packaging=pom, modules=5
+│   │   <modules>
+│   │     <module>ddd4j-rednote-api-adapter</module>
+│   │     <module>ddd4j-rednote-api-client</module>
+│   │     <module>ddd4j-rednote-api-app</module>
+│   │     <module>ddd4j-rednote-api-domain</module>
+│   │     <module>ddd4j-rednote-api-infrastructure</module>
+│   │   </modules>
+│   │
+│   ├── ddd4j-rednote-api-adapter/                  # 适配层
+│   │   ├── pom.xml                                 # 依赖 api-app, api-domain
+│   │   └── src/main/java/io/ddd4j/rednote/api/
+│   │       └── adapter/
+│   │           └── ...                             # Controller / RPC / DTO
+│   │
+│   ├── ddd4j-rednote-api-client/                   # 客户端 SDK
+│   │   ├── pom.xml                                 # 依赖 api-domain (仅接口)
+│   │   └── src/main/java/io/ddd4j/rednote/api/
+│   │       └── client/
+│   │           └── ...                             # Feign Client / Dubbo 接口
+│   │
+│   ├── ddd4j-rednote-api-app/                      # 应用层
+│   │   ├── pom.xml                                 # 依赖 api-domain, api-infrastructure
+│   │   └── src/main/java/io/ddd4j/rednote/api/
+│   │       └── app/
+│   │           └── ...                             # Executor / Service / Assembler
+│   │
+│   ├── ddd4j-rednote-api-domain/                   # 领域层 ★
+│   │   ├── pom.xml                                 # 零外部依赖
+│   │   └── src/main/java/io/ddd4j/rednote/api/
+│   │       └── domain/
+│   │           └── ...                             # Entity / VO / Repository 接口
+│   │
+│   └── ddd4j-rednote-api-infrastructure/           # 基础设施层
+│       ├── pom.xml                                 # 依赖 api-domain, common-infrastructure
+│       └── src/main/java/io/ddd4j/rednote/api/
+│           └── infrastructure/
+│               └── ...                             # RepositoryImpl / Mapper / PO
+│
+└── ddd4j-rednote-common/                           # 公共模块 (聚合子模块)
+    ├── pom.xml                                     # packaging=pom, modules=2
+    │   <modules>
+    │     <module>ddd4j-rednote-common-domain</module>
+    │     <module>ddd4j-rednote-common-infrastructure</module>
+    │   </modules>
+    │
+    ├── ddd4j-rednote-common-domain/                # 公共领域对象
+    │   ├── pom.xml                                 # 零外部依赖
+    │   └── src/main/java/io/ddd4j/rednote/common/
+    │       └── domain/
+    │           └── ...                             # 共享值对象、公共枚举
+    │
+    └── ddd4j-rednote-common-infrastructure/        # 公共基础设施
+        ├── pom.xml                                 # 依赖 common-domain
+        └── src/main/java/io/ddd4j/rednote/common/
+            └── infrastructure/
+                └── ...                             # 公共配置、工具类、组件
+```
+
+## 模块结构总结
+
+ddd4j-rednote 采用**三级模块层级**:
+
+```
+Level 1: ddd4j-rednote (父 POM)
+├── Level 2: ddd4j-rednote-bom           (版本管理)
+├── Level 2: ddd4j-rednote-dependencies  (依赖管理)
+├── Level 2: ddd4j-rednote-api           (业务接口聚合)
+│   ├── Level 3: ddd4j-rednote-api-adapter
+│   ├── Level 3: ddd4j-rednote-api-client        ← 特有模块:给其他服务用的 SDK
+│   ├── Level 3: ddd4j-rednote-api-app
+│   ├── Level 3: ddd4j-rednote-api-domain
+│   └── Level 3: ddd4j-rednote-api-infrastructure
+└── Level 2: ddd4j-rednote-common        (公共模块聚合)
+    ├── Level 3: ddd4j-rednote-common-domain
+    └── Level 3: ddd4j-rednote-common-infrastructure
+```
+
+总计 10 个 Maven 模块(含 pom 类型)。
+
+## 各模块的包结构说明
+
+| Level 2 模块 | Level 3 模块 | 包路径 | 职责 |
+|-------------|-------------|--------|------|
+| `rednote-bom` | — | — | 统一管理所有模块版本号 |
+| `rednote-dependencies` | — | — | 集中管理外部依赖版本 (scope=import) |
+| `rednote-api` | `rednote-api-adapter` | `io.ddd4j.rednote.api.adapter` | REST/RPC 适配 |
+| `rednote-api` | `rednote-api-client` | `io.ddd4j.rednote.api.client` | 其他微服务调用本服务的 Feign/Dubbo 接口 |
+| `rednote-api` | `rednote-api-app` | `io.ddd4j.rednote.api.app` | 用例编排 + CQRS |
+| `rednote-api` | `rednote-api-domain` | `io.ddd4j.rednote.api.domain` | 核心领域对象 + Repository 接口 |
+| `rednote-api` | `rednote-api-infrastructure` | `io.ddd4j.rednote.api.infrastructure` | 持久化 + 外部调用实现 |
+| `rednote-common` | `rednote-common-domain` | `io.ddd4j.rednote.common.domain` | 跨微服务共享的值对象、枚举 |
+| `rednote-common` | `rednote-common-infrastructure` | `io.ddd4j.rednote.common.infrastructure` | 共享配置、工具类 |
+
+**核心理念**:`rednote-api-client` 模块是本项目的关键设计——它为其他微服务提供**零依赖领域接口**的 SDK,调用方只需依赖 client 模块即可调用本服务。
+
+## COLA 四层职责分工
+
+| 层 | 对应模块 | 职责 | 微服务环境特点 |
+|----|---------|------|--------------|
+| **Adapter** | `api-adapter` | HTTP/RPC 适配入口 | 同时提供 REST 和 Dubbo 协议 |
+| **Application** | `api-app` | 用例编排 | 可依赖 common-infrastructure 使用共享组件 |
+| **Domain** ★ | `api-domain` + `common-domain` | 核心领域 + 共享值对象 | `api-domain` 依赖 `common-domain`(唯一允许的领域间依赖) |
+| **Infrastructure** | `api-infrastructure` + `common-infrastructure` | 持久化 + 共享工具 | 共享基础设施减少重复代码 |
+
+## 模块间依赖关系图
+
+```
+ddd4j-rednote-bom ──────────────────────────────────────────────┐
+ddd4j-rednote-dependencies ─────────────────────────────────────┤
+                                                                 │
+┌────────────────────────────────────────────────────────────────┤
+│                        rednote-api                             │
+│                                                                 │
+│  ┌──────────────────────┐                                      │
+│  │   api-adapter         │                                     │
+│  │   (REST/RPC 入口)     │                                     │
+│  └───────┬──────────────┘                                     │
+│          │ depends                                              │
+│          ▼                                                     │
+│  ┌──────────────────────┐                                      │
+│  │   api-app             │───── depends ────┐                  │
+│  │   (用例编排)           │                  │                   │
+│  └───────┬──────────────┘                  │                   │
+│          │ depends                          │                   │
+│          ▼                                 │                   │
+│  ┌──────────────────────┐                  ▼                   │
+│  │   api-domain  ★       │   ┌──────────────────────┐         │
+│  │   (核心领域)           │   │  api-infrastructure  │         │
+│  └───────┬──────────────┘   │  (持久化实现)         │         │
+│          │ depends           └──────────────────────┘         │
+│          ▼                                                      │
+│  ┌──────────────────────┐                                      │
+│  │   api-client          │← 其他微服务依赖此模块                       │
+│  │   (对外 SDK)           │                                      │
+│  └──────────────────────┘                                      │
+│                                                                 │
+├────────────────────────────────────────────────────────────────┤
+│                       rednote-common                           │
+│                                                                 │
+│  ┌──────────────────────┐     ┌──────────────────────────────┐ │
+│  │ common-domain         │     │ common-infrastructure        │ │
+│  │ (共享值对象)           │──→  │ (共享配置/工具)               │ │
+│  └──────────────────────┘     └──────────────────────────────┘ │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+**关键依赖规则**:
+- `api-domain` → `common-domain`(领域层共享值对象)
+- `api-infrastructure` → `common-infrastructure`(共享技术组件)
+- `api-client` → `api-domain`(对外 SDK 仅暴露领域对象,不暴露基础设施)
+- `common-infrastructure` → `common-domain`(基础设施依赖领域)
+
+## 适用场景
+
+- 微服务数量较多 (5+),需要一个服务提供 SDK 给其他服务调用
+- 需要 Maven 编译时强制依赖约束
+- 团队 5-15 人,对代码质量要求高
+- 有跨微服务共享的公共值对象和工具
+- BOM + Dependencies 统一管理全项目依赖版本
+
+## ddd4j-rednote 的设计精髓
+
+1. **BOM + Dependencies 双重版本管理**:BOM 管理模块版本,Dependencies 管理外部依赖版本
+2. **Client 模块**:为其他微服务提供类型安全的调用 SDK,避免硬编码 URL
+3. **Common 分层**:Common 也按 Domain/Infrastructure 拆分,保持架构一致性
+4. **三级模块层级**:Parent → API/Common → COLA 四层,结构清晰
+
+## 优点
+
+- 编译时依赖约束(Maven 模块级隔离,比 ArchUnit 更早发现问题)
+- Client 模块让其他服务调用方无需了解内部实现
+- BOM + Dependencies 统一版本管理,避免依赖冲突
+- Common 模块按分层拆分,避免 common 变"垃圾桶"
+- 每个微服务可独立发布 Client 模块给依赖方
+
+## 缺点
+
+- 10 个 Maven 模块增加构建复杂度
+- 新手需要理解模块间的依赖关系
+- 模块间接口变化影响范围大
+- BOM/Dependencies 维护需要专人负责

+ 251 - 0
skills/ddd-skills/ddd-architecture-cola/examples/12-microservice-complex-multi-module.md

@@ -0,0 +1,251 @@
+# COLA 项目规模示例:微服务复杂的多模块项目
+
+> 适用场景:大型微服务系统,多个业务域(如支付-API 和支付-Admin),每个业务域内部 Maven 多模块 COLA 结构,15-50 人团队,基于 ddd4j-pay 真实结构。
+
+## 参考项目
+
+本示例基于真实项目 `ddd4j-pay`(`io.ddd4j.pay:ddd4j-pay`)的结构提取。
+
+## 项目目录树
+
+```
+ddd4j-pay/                                            # 父 POM, packaging=pom
+├── pom.xml                                           # 继承 ddd4j-boot-parent, modules=5
+│   <modules>
+│     <module>ddd4j-pay-bom</module>
+│     <module>ddd4j-pay-dependencies</module>
+│     <module>ddd4j-pay-api</module>
+│     <module>ddd4j-pay-admin</module>
+│     <module>ddd4j-pay-common</module>
+│   </modules>
+│
+├── ddd4j-pay-bom/                                    # BOM
+│   └── pom.xml                                       # 统一版本管理
+│
+├── ddd4j-pay-dependencies/                           # 依赖管理
+│   └── pom.xml                                       # 集中管理外部依赖版本
+│
+├── ddd4j-pay-api/                                    # 支付对外接口域 (Level 2)
+│   ├── pom.xml                                       # packaging=pom, modules=5
+│   │   <modules>
+│   │     <module>ddd4j-pay-api-adapter</module>
+│   │     <module>ddd4j-pay-api-client</module>
+│   │     <module>ddd4j-pay-api-app</module>
+│   │     <module>ddd4j-pay-api-domain</module>
+│   │     <module>ddd4j-pay-api-infrastructure</module>
+│   │   </modules>
+│   │
+│   ├── ddd4j-pay-api-adapter/                        # 支付 API 适配层
+│   │   └── src/main/java/io/ddd4j/pay/api/
+│   │       └── adapter/
+│   │           └── ...                               # 支付接口 Controller / RPC
+│   │
+│   ├── ddd4j-pay-api-client/                         # 支付 API 客户端 SDK
+│   │   └── src/main/java/io/ddd4j/pay/api/
+│   │       └── client/
+│   │           └── ...                               # Feign Client / 调用接口
+│   │
+│   ├── ddd4j-pay-api-app/                            # 支付 API 应用层
+│   │   └── src/main/java/io/ddd4j/pay/api/
+│   │       └── app/
+│   │           └── ...                               # 支付流程编排 / 对账 / 退款
+│   │
+│   ├── ddd4j-pay-api-domain/                         # 支付 API 领域层 ★
+│   │   └── src/main/java/io/ddd4j/pay/api/
+│   │       └── domain/
+│   │           └── ...                               # Payment / Refund / Transaction
+│   │
+│   └── ddd4j-pay-api-infrastructure/                 # 支付 API 基础设施层
+│       └── src/main/java/io/ddd4j/pay/api/
+│           └── infrastructure/
+│               └── ...                               # 支付网关接入 / 银行接口 / 证书管理
+│
+├── ddd4j-pay-admin/                                  # 支付管理后台域 (Level 2)
+│   ├── pom.xml                                       # packaging=pom, modules=5
+│   │   <modules>
+│   │     <module>ddd4j-pay-admin-adapter</module>
+│   │     <module>ddd4j-pay-admin-client</module>
+│   │     <module>ddd4j-pay-admin-app</module>
+│   │     <module>ddd4j-pay-admin-domain</module>
+│   │     <module>ddd4j-pay-admin-infrastructure</module>
+│   │   </modules>
+│   │
+│   ├── ddd4j-pay-admin-adapter/                      # Admin 适配层
+│   │   └── src/main/java/io/ddd4j/pay/admin/
+│   │       └── adapter/
+│   │           └── ...                               # 管理后台 Controller
+│   │
+│   ├── ddd4j-pay-admin-client/                       # Admin 客户端 SDK
+│   │   └── src/main/java/io/ddd4j/pay/admin/
+│   │       └── client/
+│   │           └── ...                               # Admin 调用接口
+│   │
+│   ├── ddd4j-pay-admin-app/                          # Admin 应用层
+│   │   └── src/main/java/io/ddd4j/pay/admin/
+│   │       └── app/
+│   │           └── ...                               # 商户管理 / 费率配置 / 风控
+│   │
+│   ├── ddd4j-pay-admin-domain/                       # Admin 领域层 ★
+│   │   └── src/main/java/io/ddd4j/pay/admin/
+│   │       └── domain/
+│   │           └── ...                               # Merchant / FeeRule / RiskRule
+│   │
+│   └── ddd4j-pay-admin-infrastructure/               # Admin 基础设施层
+│       └── src/main/java/io/ddd4j/pay/admin/
+│           └── infrastructure/
+│               └── ...                               # 商户数据持久化 / 风控引擎
+│
+├── ddd4j-pay-common/                                 # 公共模块 (Level 2)
+│   ├── pom.xml                                       # packaging=pom, modules=2
+│   │   <modules>
+│   │     <module>ddd4j-pay-common-domain</module>
+│   │     <module>ddd4j-pay-common-infrastructure</module>
+│   │   </modules>
+│   │
+│   ├── ddd4j-pay-common-domain/                      # 公共领域对象
+│   │   └── src/main/java/io/ddd4j/pay/common/
+│   │       └── domain/
+│   │           └── ...                               # Money / Currency / PayChannel 枚举
+│   │
+│   └── ddd4j-pay-common-infrastructure/              # 公共基础设施
+│       └── src/main/java/io/ddd4j/pay/common/
+│           └── infrastructure/
+│               └── ...                               # 分布式锁 / 幂等组件 / 日志
+│
+├── libs/                                             # 本地 jar 依赖 (如银行 SDK)
+├── docs/                                             # 文档
+│   └── icons/
+└── ...
+```
+
+## 模块完整层级结构
+
+```
+ddd4j-pay (父 POM)
+├── Level 2: ddd4j-pay-bom               — BOM 版本管理
+├── Level 2: ddd4j-pay-dependencies      — 外部依赖版本管理
+├── Level 2: ddd4j-pay-api               — 支付接口域 (5 个 Level 3 子模块)
+├── Level 2: ddd4j-pay-admin             — 管理后台域 (5 个 Level 3 子模块)
+└── Level 2: ddd4j-pay-common            — 公共模块 (2 个 Level 3 子模块)
+                                               │
+            ┌──────────────────────────────────┘
+            ▼
+    总计 14 个 Maven 模块 (含 pom 类型)
+```
+
+**两层业务域**:
+- `ddd4j-pay-api`:面向 C 端用户/商户的支付接口(下单、支付、退款、查询)
+- `ddd4j-pay-admin`:面向运营/管理员的后台管理(商户管理、费率配置、风控规则)
+
+## 各模块的包结构说明
+
+| Level 2 模块 | Level 3 模块 | 包路径 | 职责 |
+|-------------|-------------|--------|------|
+| `pay-bom` | — | — | 统一管理 14 个模块版本号 |
+| `pay-dependencies` | — | — | 集中管理外部依赖版本 |
+| `pay-api` | `pay-api-adapter` | `io.ddd4j.pay.api.adapter` | 支付 REST/RPC 接口 |
+| `pay-api` | `pay-api-client` | `io.ddd4j.pay.api.client` | 支付服务 SDK(给其他系统调用) |
+| `pay-api` | `pay-api-app` | `io.ddd4j.pay.api.app` | 支付流程编排(下单/退款/对账) |
+| `pay-api` | `pay-api-domain` | `io.ddd4j.pay.api.domain` | 支付核心领域(Payment/Refund/Transaction) |
+| `pay-api` | `pay-api-infrastructure` | `io.ddd4j.pay.api.infrastructure` | 支付网关接入/银行接口/证书管理 |
+| `pay-admin` | `pay-admin-adapter` | `io.ddd4j.pay.admin.adapter` | 管理后台 Controller |
+| `pay-admin` | `pay-admin-client` | `io.ddd4j.pay.admin.client` | Admin SDK |
+| `pay-admin` | `pay-admin-app` | `io.ddd4j.pay.admin.app` | 商户管理/费率/风控编排 |
+| `pay-admin` | `pay-admin-domain` | `io.ddd4j.pay.admin.domain` | 商户/费率/风控领域 |
+| `pay-admin` | `pay-admin-infrastructure` | `io.ddd4j.pay.admin.infrastructure` | 商户数据/风控引擎实现 |
+| `pay-common` | `pay-common-domain` | `io.ddd4j.pay.common.domain` | 共享值对象(Money/Currency) |
+| `pay-common` | `pay-common-infrastructure` | `io.ddd4j.pay.common.infrastructure` | 分布式锁/幂等/日志组件 |
+
+## COLA 四层职责分工
+
+| 层 | pay-api 职责 | pay-admin 职责 |
+|----|-------------|---------------|
+| **Adapter** | 支付下单/退款/查询 REST API | 商户管理/费率配置/风控规则 REST API |
+| **Application** | 支付流程编排(下单→风控→扣款→通知) | 商户入驻/费率变更/风控策略编排 |
+| **Domain** ★ | Payment / Refund / Transaction 核心模型 | Merchant / FeeRule / RiskRule 核心模型 |
+| **Infrastructure** | 银行网关实现 / 支付回调处理 / 证书管理 | 商户数据持久化 / 风控规则引擎 / 审计日志 |
+
+## 模块间依赖关系图
+
+```
+┌──────────────────────────────────────────────────────────────────┐
+│                         ddd4j-pay-bom                             │
+│                         ddd4j-pay-dependencies                    │
+├──────────────────────────────────────────────────────────────────┤
+│                                                                   │
+│  ┌─────────────────────────────┐  ┌──────────────────────────────┐│
+│  │       ddd4j-pay-api         │  │      ddd4j-pay-admin         ││
+│  │                             │  │                              ││
+│  │  api-adapter                │  │  admin-adapter               ││
+│  │     ↓                       │  │     ↓                        ││
+│  │  api-app ──→ api-domain ★   │  │  admin-app ──→ admin-domain ★││
+│  │     ↓                  ↑    │  │     ↓                   ↑    ││
+│  │  api-infrastructure ────┘   │  │  admin-infrastructure ───┘   ││
+│  │     ↓                       │  │     ↓                        ││
+│  │  api-client                 │  │  admin-client                ││
+│  └─────────┬───────────────────┘  └─────────┬────────────────────┘│
+│            │                                 │                     │
+│            │          ┌──────────┐           │                     │
+│            └──────────→ common   ←──────────┘                    │
+│                       │          │                                │
+│                       │ common-  │                                │
+│                       │ domain   │                                │
+│                       │    ↓     │                                │
+│                       │ common-  │                                │
+│                       │ infra    │                                │
+│                       └──────────┘                                │
+│                                                                   │
+│  关键依赖:                                                        │
+│  • api-domain ──→ common-domain  (共享值对象)                     │
+│  • admin-domain ──→ common-domain (共享值对象)                    │
+│  • api-infrastructure ──→ common-infrastructure (共享组件)        │
+│  • admin-infrastructure ──→ common-infrastructure (共享组件)      │
+│  • api-app ──→ admin-client (调用管理后台服务)                    │
+└──────────────────────────────────────────────────────────────────┘
+```
+
+**跨域依赖规则**:
+- `pay-api` 和 `pay-admin` 是两个独立的 Bounded Context
+- 它们通过 `common-*` 共享值对象和基础设施
+- 两个域的应用层可以通过各自的 `client` 模块相互调用
+- **严禁** `pay-api-domain` 直接依赖 `pay-admin-domain`(跨域聚合隔离)
+- **严禁** 通过数据库层面实现跨域数据访问(各自独立表空间)
+
+## 适用场景
+
+- 大型支付/金融系统,需要严格的域隔离
+- 多业务域共存(如支付接口 + 管理后台 + 对账 + 风控)
+- 团队 15-50 人,按业务域分小组
+- 需要 Bounded Context 级别的模块隔离
+- 需要独立发布 Client SDK 给多个下游系统
+- 对代码质量和架构一致性有极高要求
+
+## 与 ddd4j-rednote 的结构对比
+
+| 维度 | ddd4j-rednote (简单) | ddd4j-pay (复杂) |
+|------|:---------------------:|:-----------------:|
+| Level 2 业务域数 | 1 (api) | 2 (api + admin) |
+| Level 3 子模块数 | 7 | 12 |
+| 总模块数 | 10 | 14 |
+| 跨域依赖 | 无 | 通过 client 相互调用 |
+| Common 共享范围 | 单域内共享 | 跨域共享 |
+| BOM 管理复杂度 | 低 | 中 |
+| 适用团队规模 | 5-15 人 | 15-50 人 |
+
+## 优点
+
+- 编译时强约束:`pay-api-domain` 和 `pay-admin-domain` 完全隔离
+- 每个业务域可独立发布 Client SDK
+- Common 模块按 Domain/Infrastructure 分层,避免成为"大垃圾桶"
+- BOM + Dependencies 统一 14 个模块的版本,避免依赖地狱
+- 高粒度模块可独立测试、独立编译
+- 为大团队并行开发提供清晰的模块边界
+
+## 缺点
+
+- 14 个 Maven 模块维护成本高
+- 新人学习曲线陡峭(需要理解 API/Admin 两个域的边界)
+- Client 模块的接口变化需要协调多个服务同时升级
+- BOM 版本发布需要严格的版本管理流程
+- 构建时间较长(14 个模块需要全部编译)
+- 模块间过度拆分可能导致过早抽象

+ 0 - 0
skills/ddd-skills/ddd4j-project-creator/examples/architecture-patterns.md → skills/ddd-skills/ddd-architecture-cola/examples/13-architecture-patterns.md


+ 0 - 0
skills/ddd-skills/ddd4j-project-creator/examples/single-module.md → skills/ddd-skills/ddd-architecture-cola/examples/14-single-module.md


+ 0 - 0
skills/ddd-skills/ddd4j-project-creator/examples/multi-module.md → skills/ddd-skills/ddd-architecture-cola/examples/15-multi-module.md


+ 0 - 0
skills/ddd-skills/ddd4j-project-creator/examples/microservices.md → skills/ddd-skills/ddd-architecture-cola/examples/16-microservices.md


+ 57 - 0
skills/ddd-skills/ddd-architecture-cola/references/01-architecture-principles.md

@@ -0,0 +1,57 @@
+# COLA v5 菱形架构核心原理
+
+## 菱形架构全景
+
+COLA v5(Clean Object-oriented Layered Architecture)采用"菱形架构"——以 Domain 为中心,Adapter 和 Infrastructure 分居两侧:
+
+```
+          ┌──────────────┐
+          │   Adapter    │  ← 适配层:HTTP、MQ、RPC 协议适配
+          └──────┬───────┘
+                 │
+          ┌──────▼───────┐
+          │   Application│  ← 应用层:编排、事务、CQRS 分流
+  ┌───────┴───────┬───────┴───────┐
+  ▼               ▼               ▼
+┌──────────┐ ┌──────────┐ ┌──────────┐
+│  Domain  │ │  Domain  │ │  Domain  │  ← 领域层:核心业务逻辑 ★
+│   ★      │ │   ★      │ │   ★      │
+└──────────┘ └──────────┘ └──────────┘
+  ▲               ▲               ▲
+  └───────────────┴───────────────┘
+                 │
+          ┌──────▼───────┐
+          │Infrastructure│  ← 基础设施层:DB、MQ、缓存、外部 API
+          └──────────────┘
+```
+
+## 四层职责
+
+| 层 | 模块名 | 核心职责 | 依赖方向 |
+|---|--------|---------|---------|
+| **Adapter** | `{project}-adapter` | HTTP/RPC/MQ 协议适配,DTO 转换 | → app, domain |
+| **Application** | `{project}-app` | 用例编排,事务管理,CQRS 执行器 | → domain, infrastructure |
+| **Domain** | `{project}-domain` | 领域模型、业务规则、Repository/Gateway 接口 | 无(零依赖) |
+| **Infrastructure** | `{project}-infrastructure` | 技术实现(DB/MQ/缓存)、Repository/Gateway 实现 | → domain |
+
+## 四大核心约束(P0)
+
+1. **Domain 零依赖** — Domain 层不允许 import Spring/JPA/MyBatis 等框架注解
+2. **App 层无业务逻辑** — App 层仅编排,不放 if/else 业务判断
+3. **Adapter 层无 SQL/业务** — Adapter 只做协议转换和数据映射
+4. **模块间无循环依赖** — 四层之间只允许单向依赖
+
+## 依赖方向规则
+
+```
+adapter → app → domain ← infrastructure
+                        ↑
+                    domain 不依赖任何人
+```
+
+## v5 新增概念
+
+- **Extension Point(扩展点)**:通过 `@ExtensionPoint` + `@Extension(bizId = "...")` 实现业务维度的扩展
+- **Ability(领域能力)**:`domain/ability/` 为领域层提供能力抽象
+- **组件化基础设施**:分布式锁、限流器、熔断器作为基础设施组件
+- **CQRS 强化**:`app/executor/command/` 和 `app/executor/query/` 严格分离

+ 117 - 0
skills/ddd-skills/ddd-architecture-cola/references/02-project-scaffold.md

@@ -0,0 +1,117 @@
+# COLA v5 项目脚手架
+
+## Maven Archetype 快速创建
+
+```bash
+mvn archetype:generate \
+  -DarchetypeGroupId=com.alibaba.cola \
+  -DarchetypeArtifactId=cola-archetype-web \
+  -DarchetypeVersion=5.0.0 \
+  -DgroupId=com.yourcompany \
+  -DartifactId=your-project \
+  -Dversion=1.0.0-SNAPSHOT
+```
+
+## 手动搭建(推荐生产使用)
+
+### 多模块 Maven 配置
+
+```xml
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
+         http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.yourcompany</groupId>
+    <artifactId>your-project</artifactId>
+    <version>1.0.0-SNAPSHOT</version>
+    <packaging>pom</packaging>
+
+    <modules>
+        <module>start</module>
+        <module>adapter</module>
+        <module>app</module>
+        <module>domain</module>
+        <module>infrastructure</module>
+        <module>common</module>
+    </modules>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>3.2.0</version>
+    </parent>
+
+    <properties>
+        <java.version>17</java.version>
+        <cola.version>5.0.0</cola.version>
+        <mybatis.version>3.0.3</mybatis.version>
+    </properties>
+
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>com.alibaba.cola</groupId>
+                <artifactId>cola-component-dto</artifactId>
+                <version>${cola.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.cola</groupId>
+                <artifactId>cola-component-domain-starter</artifactId>
+                <version>${cola.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>com.alibaba.cola</groupId>
+                <artifactId>cola-component-catchlog-starter</artifactId>
+                <version>${cola.version}</version>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+</project>
+```
+
+### 各模块依赖
+
+| 模块 | 依赖 | 说明 |
+|------|------|------|
+| start | adapter, common | 启动模块,依赖所有非 domain 模块 |
+| adapter | app, domain | 适配层,可调用应用层和领域层 |
+| app | domain, infrastructure | 应用层,编排领域层 + 基础设施 |
+| domain | (none) | 领域层,纯 POJO,零框架依赖 |
+| infrastructure | domain | 基础设施实现领域层接口 |
+| common | (none) | 通用工具和常量 |
+
+### Gradle 版本
+
+```groovy
+// settings.gradle
+rootProject.name = 'your-project'
+include 'start', 'adapter', 'app', 'domain', 'infrastructure', 'common'
+
+// build.gradle (根)
+subprojects {
+    apply plugin: 'java'
+    apply plugin: 'org.springframework.boot'
+    apply plugin: 'io.spring.dependency-management'
+
+    group = 'com.yourcompany'
+    version = '1.0.0-SNAPSHOT'
+    sourceCompatibility = '17'
+}
+```
+
+## 启动模块 (start)
+
+```java
+@SpringBootApplication(scanBasePackages = "com.yourcompany")
+@EnableCola
+public class Application {
+    public static void main(String[] args) {
+        SpringApplication.run(Application.class, args);
+    }
+}
+```
+
+> `@EnableCola` 是 COLA v5 新增注解,启动 COLA 扩展点机制和领域事件总线。

+ 133 - 0
skills/ddd-skills/ddd-architecture-cola/references/03-domain-layer.md

@@ -0,0 +1,133 @@
+# COLA v5 领域层详解
+
+## 领域层目录结构
+
+```
+{project}-domain/
+├── model/                         # 领域模型
+│   ├── entity/                    # 实体 + 聚合根(充血模型)
+│   ├── vo/                        # 值对象(不可变)
+│   ├── aggregate/                 # 聚合(v5 明确分离)
+│   ├── event/                     # 领域事件
+│   └── enums/                     # 领域枚举
+├── service/                       # 领域服务(跨实体的复杂业务逻辑)
+├── ability/                       # 领域能力(v5 新概念)
+├── gateway/                       # 领域网关(端口,与外部交互的抽象)
+├── repository/                    # 仓储接口(数据持久化抽象)
+└── extension/                     # 领域扩展点
+```
+
+## 核心实现规则
+
+### 1. 零框架依赖(P0)
+
+Domain 层绝不允许出现以下 import:
+```java
+// ❌ 禁止
+import org.springframework.stereotype.Service;
+import javax.persistence.Entity;
+import jakarta.persistence.*;
+import org.apache.ibatis.annotations.Mapper;
+
+// ✅ 允许
+import java.util.Optional;
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+```
+
+### 2. 充血模型
+
+```java
+// Order 是聚合根(Aggregate Root),包含业务行为
+public class Order extends AggregateRoot<OrderId> {
+    private OrderStatus status;       // 枚举/值对象,不是 String
+    private Money totalAmount;        // 值对象,不是 BigDecimal
+    private List<OrderItem> items;    // 实体集合
+
+    // 业务行为在实体中
+    public void pay() {
+        if (!status.canPay()) {
+            throw new OrderDomainException("当前状态不可支付");
+        }
+        this.status = OrderStatus.PAID;
+        addDomainEvent(new OrderPaidEvent(this.id));
+    }
+
+    public void cancel(String reason) {
+        if (status.isFinalState()) {
+            throw new OrderDomainException("终态订单不可取消");
+        }
+        this.status = OrderStatus.CANCELLED;
+        addDomainEvent(new OrderCancelledEvent(this.id, reason));
+    }
+}
+```
+
+### 3. 值对象不可变
+
+```java
+public class Money {
+    private final BigDecimal amount;
+    private final Currency currency;
+
+    public Money(BigDecimal amount, Currency currency) {
+        this.amount = amount.setScale(2, RoundingMode.HALF_UP);
+        this.currency = currency;
+    }
+
+    // 无 setter,操作返回新对象
+    public Money add(Money other) {
+        if (!this.currency.equals(other.currency)) {
+            throw new IllegalArgumentException("币种不一致");
+        }
+        return new Money(this.amount.add(other.amount), this.currency);
+    }
+
+    public BigDecimal getAmount() { return amount; }
+    public Currency getCurrency() { return currency; }
+
+    @Override
+    public boolean equals(Object o) { /* 按值比较 */ }
+    @Override
+    public int hashCode() { /* 按值计算 */ }
+}
+```
+
+### 4. 仓储接口
+
+```java
+public interface OrderRepository {
+    Optional<Order> findById(OrderId id);
+    Order save(Order order);
+    void delete(OrderId id);
+    // 查询方法使用值对象作为参数
+    Page<Order> findByStatus(OrderStatus status, Pageable pageable);
+}
+```
+
+### 5. 领域网关(防腐层)
+
+```java
+// 定义在 domain,实现在 infrastructure
+public interface ProductGateway {
+    ProductInfo getProduct(ProductId productId);
+    InventoryInfo checkInventory(ProductId productId, int quantity);
+}
+```
+
+### 6. 领域能力(v5 新特性)
+
+```java
+public interface OrderAbility {
+    boolean canBeCancelled(Order order);
+    boolean canApplyPromotion(Order order, String promotionId);
+}
+```
+
+## 领域层最佳实践
+
+- **聚合大小**:一个聚合 ≤ 5 个实体,过大考虑拆分
+- **聚合间引用**:通过 ID 引用,不是对象引用
+- **一致性边界**:聚合内强一致,聚合间最终一致(通过领域事件)
+- **仓储接口**:只定义在 Domain,不在 Domain 层实现
+- **领域事件**:关键业务操作必须发布领域事件

+ 138 - 0
skills/ddd-skills/ddd-architecture-cola/references/04-app-layer.md

@@ -0,0 +1,138 @@
+# COLA v5 应用层详解
+
+## 应用层目录结构
+
+```
+{project}-app/
+├── executor/                     # 执行器(v5 CQRS 强化)
+│   ├── command/                  # 命令执行器(写操作)
+│   ├── query/                    # 查询执行器(读操作)
+│   ├── event/                    # 事件执行器(v5 新增)
+│   ├── extension/                # 扩展执行器
+│   └── interceptor/              # 执行器拦截器(日志、监控、校验)
+├── model/                        # 应用模型(v5 明确分离)
+│   ├── command/                  # 命令对象(写请求 DTO)
+│   ├── query/                    # 查询对象(读请求 DTO)
+│   ├── event/                    # 应用事件
+│   └── dto/                      # 应用层 DTO
+├── service/                      # 应用服务(传统编排方式)
+├── eventhandler/                 # 事件处理器(v5 重组)
+└── extension/                    # 扩展点
+    ├── point/                    # 扩展点定义
+    ├── biz/                      # 业务扩展点
+    └── impl/                     # 扩展实现
+```
+
+## 核心规则
+
+### 1. App 层不放业务逻辑(P0)
+
+```java
+// ✅ 正确:App 层只编排
+@CommandExecutor
+public class OrderCreateCmdExe {
+    @Resource
+    private OrderRepository orderRepository;
+    @Resource
+    private ProductGateway productGateway;
+
+    @Override
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        // 校验库存(调用领域网关)
+        InventoryInfo inventory = productGateway.checkInventory(cmd.getProductId(), cmd.getQuantity());
+        if (!inventory.isAvailable()) {
+            throw new BizException("库存不足");
+        }
+
+        // 创建订单(领域逻辑在 Order 实体中)
+        Order order = Order.create(cmd.toOrderCreation());
+
+        // 保存订单
+        orderRepository.save(order);
+
+        // 返回 DTO
+        return OrderAssembler.toDTO(order);
+    }
+}
+```
+
+### 2. App 层不直接操作数据库(P0)
+
+```java
+// ❌ 错误:App 层直接操作 Mapper
+@CommandExecutor
+public class OrderCreateCmdExe {
+    @Resource
+    private OrderMapper orderMapper;  // ← 禁止!应通过 Repository 接口
+
+    @Override
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        // ...
+        orderMapper.insert(order);    // ← P0 违规
+    }
+}
+```
+
+### 3. CQRS 执行器模式(推荐)
+
+**命令执行器**(写操作):
+
+```java
+@Component
+public class CustomerCreateCmdExe implements CommandExecutor<CustomerCreateCmd, CustomerDTO> {
+    @Resource
+    private CustomerRepository customerRepository;
+
+    @Override
+    @Transactional
+    public CustomerDTO execute(CustomerCreateCmd cmd) {
+        Customer customer = new Customer(cmd.getCustomerName(), cmd.getEmail());
+        customerRepository.save(customer);
+        return CustomerAssembler.toDTO(customer);
+    }
+}
+```
+
+**查询执行器**(读操作):
+
+```java
+@Component
+public class CustomerGetQryExe implements QueryExecutor<CustomerGetQry, CustomerDTO> {
+    @Resource
+    private CustomerRepository customerRepository;
+
+    @Override
+    public CustomerDTO execute(CustomerGetQry qry) {
+        return customerRepository.findById(new CustomerId(qry.getId()))
+            .map(CustomerAssembler::toDTO)
+            .orElseThrow(() -> new BizException("客户不存在"));
+    }
+}
+```
+
+### 4. 应用服务(传统编排)
+
+适用于不需要 CQRS 分离的简单场景:
+
+```java
+@Service
+public class OrderAppService {
+    @Resource
+    private OrderRepository orderRepository;
+
+    @Transactional
+    public void payOrder(PayOrderCommand command) {
+        Order order = orderRepository.findById(new OrderId(command.getOrderId()))
+            .orElseThrow(() -> new OrderNotFoundException(command.getOrderId()));
+        order.pay();                // 领域逻辑在实体中
+        orderRepository.save(order);
+    }
+}
+```
+
+## 应用层最佳实践
+
+- **事务边界**:事务在 App 层,不在 Domain 层
+- **命令/查询分离**:写操作走 Command Executor,读操作走 Query Executor
+- **参数校验**:格式校验在 Adapter 层,业务校验在 App/Domain 层
+- **DTO 转换**:使用 Assembler/Converter,不作为 Domain 对象暴露

+ 125 - 0
skills/ddd-skills/ddd-architecture-cola/references/05-adapter-layer.md

@@ -0,0 +1,125 @@
+# COLA v5 适配层详解
+
+## 适配层目录结构
+
+```
+{project}-adapter/
+├── web/                           # Web 适配器
+│   ├── controller/                # REST 控制器
+│   ├── api/                       # API 适配器(v5 强调)
+│   ├── dto/                       # 请求/响应 DTO
+│   │   ├── request/
+│   │   ├── response/
+│   │   └── converter/             # DTO 转换器
+│   ├── validator/                 # 请求校验器
+│   └── advice/                    # 全局异常处理
+├── rpc/                           # RPC 适配器
+│   ├── provider/                  # RPC 服务提供者
+│   ├── consumer/                  # RPC 服务消费者
+│   ├── facade/                    # RPC 门面(v5 新概念)
+│   └── dto/                       # RPC DTO
+├── job/                           # 定时任务
+│   ├── scheduler/                 # 调度器
+│   └── task/                      # 具体任务
+├── message/                       # 消息适配器
+│   ├── consumer/                  # 消息消费者
+│   ├── producer/                  # 消息生产者
+│   └── listener/                  # 事件监听器
+├── graphql/                       # GraphQL 适配器(v5 增强)
+│   ├── resolver/
+│   └── dto/
+└── mobile/                        # 移动端适配器
+```
+
+## 核心规则
+
+### 1. Adapter 层无业务逻辑(P0)
+
+```java
+// ✅ 正确:Controller 只做协议转换
+@RestController
+@RequestMapping("/api/v1/orders")
+public class OrderController {
+    @Resource
+    private OrderCreateCmdExe orderCreateCmdExe;
+
+    @PostMapping
+    public Response<OrderDTO> create(@Valid @RequestBody OrderCreateRequest request) {
+        OrderCreateCmd cmd = request.toCommand();    // 协议 → 命令
+        OrderDTO dto = orderCreateCmdExe.execute(cmd); // 委托给 executor
+        return Response.success(dto);
+    }
+}
+```
+
+### 2. 全局异常处理
+
+```java
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+    @ExceptionHandler(BizException.class)
+    public Response<Void> handleBizException(BizException e) {
+        return Response.fail(e.getCode(), e.getMessage());
+    }
+
+    @ExceptionHandler(ValidationException.class)
+    public Response<Void> handleValidation(ValidationException e) {
+        return Response.fail(400, e.getMessage());
+    }
+
+    @ExceptionHandler(Exception.class)
+    public Response<Void> handleUnknown(Exception e) {
+        log.error("Unexpected error", e);
+        return Response.fail(500, "系统繁忙,请稍后重试");
+    }
+}
+```
+
+### 3. DTO 转换
+
+```java
+// Adapter 层 DTO,与 Domain 对象分离
+public class OrderCreateRequest {
+    @NotBlank
+    private String productId;
+    @Min(1)
+    private Integer quantity;
+    @NotNull
+    private BigDecimal unitPrice;
+
+    // 转换到 Command 对象(App 层)
+    public OrderCreateCmd toCommand() {
+        OrderCreateCmd cmd = new OrderCreateCmd();
+        cmd.setProductId(this.productId);
+        cmd.setQuantity(this.quantity);
+        cmd.setUnitPrice(this.unitPrice);
+        return cmd;
+    }
+}
+```
+
+### 4. RPC 适配器示例
+
+```java
+// RPC 提供者
+@DubboService
+public class CustomerRpcProviderImpl implements CustomerRpcProvider {
+    @Resource
+    private CustomerCreateCmdExe customerCreateCmdExe;
+
+    @Override
+    public CustomerRpcResponse createCustomer(CustomerRpcRequest request) {
+        CustomerCreateCmd cmd = request.toCommand();
+        CustomerDTO dto = customerCreateCmdExe.execute(cmd);
+        return CustomerRpcResponse.from(dto);
+    }
+}
+```
+
+## 适配层最佳实践
+
+- **Controller 职责**:只做 HTTP 协议转换,不放任何业务判断
+- **DTO 独立**:Adapter 层 DTO 与应用层 DTO 分离,不混用
+- **参数校验**:使用 `@Valid` + JSR-303 做格式校验
+- **统一响应**:统一使用 `Response<T>` 包装返回
+- **版本管理**:URL 路径版本 `/api/v1/` → `/api/v2/`

+ 154 - 0
skills/ddd-skills/ddd-architecture-cola/references/06-infrastructure.md

@@ -0,0 +1,154 @@
+# COLA v5 基础设施层详解
+
+## 基础设施层目录结构
+
+```
+{project}-infrastructure/
+├── config/                        # 配置中心(v5 增强)
+│   ├── database/                  # 数据库配置(DataSource、MyBatis、JPA)
+│   ├── cache/                     # 缓存配置(Redis、LocalCache)
+│   ├── message/                   # 消息配置(Kafka、RocketMQ、RabbitMQ)
+│   ├── rpc/                       # RPC 配置(Dubbo、gRPC、Feign)
+│   ├── external/                  # 外部服务配置(支付、邮件、OSS)
+│   └── monitor/                   # 监控配置(Metrics、Log、Tracing)
+├── persistence/                   # 持久化实现
+│   ├── repositoryimpl/            # 仓储实现类
+│   ├── mapper/                    # MyBatis Mapper
+│   ├── dao/                       # 数据访问对象
+│   └── entity/                    # 持久化实体(PO/DO)
+├── gatewayimpl/                   # 网关实现
+│   ├── customer/
+│   ├── order/
+│   └── external/                  # 外部网关实现
+├── external/                      # 外部服务客户端
+│   ├── payment/                   # 支付(Alipay、WechatPay)
+│   ├── message/                   # 消息(SMS、Email)
+│   └── storage/                   # 存储(OSS)
+├── util/                          # 基础设施工具
+│   ├── IdGenerator.java
+│   ├── JsonUtils.java
+│   └── CryptoUtils.java
+└── component/                     # 基础设施组件(v5 新增)
+    ├── lock/                      # 分布式锁
+    ├── rateLimiter/               # 限流器
+    ├── circuitbreaker/            # 熔断器
+    └── retry/                     # 重试模板
+```
+
+## 核心实现规则
+
+### 1. 实现 Domain 层接口
+
+```java
+// Domain 定义接口
+public interface OrderRepository {
+    Optional<Order> findById(OrderId id);
+    Order save(Order order);
+}
+
+// Infrastructure 实现
+@Repository
+public class OrderRepositoryImpl implements OrderRepository {
+    @Resource
+    private OrderMapper orderMapper;
+    @Resource
+    private OrderConverter orderConverter;
+
+    @Override
+    public Order save(Order order) {
+        OrderPO po = orderConverter.toPO(order);
+        orderMapper.insert(po);
+        return orderConverter.toDomain(po);
+    }
+
+    @Override
+    public Optional<Order> findById(OrderId id) {
+        return Optional.ofNullable(orderMapper.selectById(id.getValue()))
+            .map(orderConverter::toDomain);
+    }
+}
+```
+
+### 2. PO ↔ Domain 转换
+
+```java
+@Component
+public class OrderConverter {
+    // Domain → PO(写方向)
+    public OrderPO toPO(Order order) {
+        OrderPO po = new OrderPO();
+        po.setId(order.getId().getValue());
+        po.setStatus(order.getStatus().name());
+        po.setTotalAmount(order.getTotalAmount().getAmount());
+        po.setCurrency(order.getTotalAmount().getCurrency().getCurrencyCode());
+        return po;
+    }
+
+    // PO → Domain(读方向)
+    public Order toDomain(OrderPO po) {
+        return Order.builder()
+            .id(new OrderId(po.getId()))
+            .status(OrderStatus.valueOf(po.getStatus()))
+            .totalAmount(new Money(po.getTotalAmount(), Currency.getInstance(po.getCurrency())))
+            .build();
+    }
+}
+```
+
+### 3. Gateway 实现(防腐层)
+
+```java
+// Domain 定义
+public interface PaymentGateway {
+    PaymentResult doPay(PayCommand command);
+    RefundResult doRefund(RefundCommand command);
+}
+
+// Infrastructure 实现
+@Component
+public class PaymentGatewayImpl implements PaymentGateway {
+    @Value("${payment.alipay.app-id}")
+    private String appId;
+
+    @Resource
+    private AlipayClient alipayClient;
+
+    @Override
+    public PaymentResult doPay(PayCommand command) {
+        AlipayRequest request = buildAlipayRequest(command);
+        AlipayResponse response = alipayClient.pay(request);
+        return PaymentResult.of(response);
+    }
+}
+```
+
+### 4. 基础设施组件(v5 新增)
+
+```java
+// 分布式锁组件
+@Component
+public class RedisDistributedLock implements DistributedLock {
+    @Resource
+    private StringRedisTemplate redisTemplate;
+
+    @Override
+    public boolean tryLock(String key, long timeout, TimeUnit unit) {
+        return Boolean.TRUE.equals(
+            redisTemplate.opsForValue()
+                .setIfAbsent(key, "locked", timeout, unit)
+        );
+    }
+
+    @Override
+    public void unlock(String key) {
+        redisTemplate.delete(key);
+    }
+}
+```
+
+## 基础设施层最佳实践
+
+- **纯技术实现**:不包含任何业务判断或规则
+- **PO 独立**:持久化 PO 与 Domain Entity 分离,使用 Converter 转换
+- **配置外置**:数据库、MQ 等连接信息放在 `application.yml`,不使用硬编码
+- **可替换性**:所有基础设施实现都面向 Domain 接口编程,支持替换

+ 163 - 0
skills/ddd-skills/ddd-architecture-cola/references/07-archunit-validation.md

@@ -0,0 +1,163 @@
+# COLA v5 ArchUnit 架构校验
+
+## 依赖方向校验
+
+```java
+import com.tngtech.archunit.junit.AnalyzeClasses;
+import com.tngtech.archunit.junit.ArchTest;
+import com.tngtech.archunit.lang.ArchRule;
+import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*;
+
+@AnalyzeClasses(packages = "com.yourcompany")
+public class ArchitectureComplianceTest {
+
+    // 规则 1:Domain 层不能依赖 Infrastructure
+    @ArchTest
+    static final ArchRule domain_should_not_depend_on_infrastructure =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..infrastructure..")
+            .because("Domain layer must not depend on infrastructure");
+
+    // 规则 2:Domain 层不能依赖 App
+    @ArchTest
+    static final ArchRule domain_should_not_depend_on_app =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..app..")
+            .because("Domain layer must not depend on application");
+
+    // 规则 3:Domain 层不能依赖 Adapter
+    @ArchTest
+    static final ArchRule domain_should_not_depend_on_adapter =
+        noClasses()
+            .that().resideInAPackage("..domain..")
+            .should().dependOnClassesThat()
+            .resideInAPackage("..adapter..")
+            .because("Domain layer must not depend on adapter");
+}
+```
+
+## 框架依赖校验
+
+```java
+// 规则 4:Domain 层不能有 Spring Framework 依赖
+@ArchTest
+static final ArchRule domain_should_not_depend_on_spring =
+    noClasses()
+        .that().resideInAPackage("..domain..")
+        .should().dependOnClassesThat()
+        .resideInAnyPackage("org.springframework..", "org.springframework.stereotype..")
+        .because("Domain layer must have zero framework dependencies");
+
+// 规则 5:Domain 层不能有 JPA 依赖
+@ArchTest
+static final ArchRule domain_should_not_depend_on_jpa =
+    noClasses()
+        .that().resideInAPackage("..domain..")
+        .should().dependOnClassesThat()
+        .resideInAnyPackage("javax.persistence..", "jakarta.persistence..")
+        .because("Domain layer must not depend on JPA");
+
+// 规则 6:Domain 层不能有 MyBatis 依赖
+@ArchTest
+static final ArchRule domain_should_not_depend_on_mybatis =
+    noClasses()
+        .that().resideInAPackage("..domain..")
+        .should().dependOnClassesThat()
+        .resideInAnyPackage("org.apache.ibatis..", "org.mybatis..")
+        .because("Domain layer must not depend on MyBatis");
+```
+
+## 层职责校验
+
+```java
+// 规则 7:Adapter 层不能依赖 Infrastructure
+@ArchTest
+static final ArchRule adapter_should_not_depend_on_infrastructure =
+    noClasses()
+        .that().resideInAPackage("..adapter..")
+        .should().dependOnClassesThat()
+        .resideInAPackage("..infrastructure..")
+        .because("Adapter must go through App layer");
+
+// 规则 8:App 层可以依赖 Domain 和 Infrastructure
+@ArchTest
+static final ArchRule app_should_only_depend_on_domain_and_infra =
+    classes()
+        .that().resideInAPackage("..app..")
+        .should().onlyDependOnClassesThat()
+        .resideInAnyPackage(
+            "..app..", "..domain..", "..infrastructure..",
+            "java..", "lombok..", "org.springframework.."
+        ).because("App should only depend on domain and infrastructure");
+```
+
+## 包命名校验
+
+```java
+// 规则 9:Domain 层不应该包含 controller
+@ArchTest
+static final ArchRule domain_package_should_not_contain_controller =
+    noClasses()
+        .that().resideInAPackage("..domain..")
+        .should().resideInAPackage("..controller..")
+        .because("Controller belongs in adapter layer");
+
+// 规则 10:Adapter 层不应该包含 repository
+@ArchTest
+static final ArchRule adapter_should_not_contain_repository =
+    noClasses()
+        .that().resideInAPackage("..adapter..")
+        .should().resideInAPackage("..repository..")
+        .because("Repository belongs in domain or infrastructure");
+```
+
+## CI/CD 集成
+
+### GitHub Actions
+
+```yaml
+name: COLA Architecture Check
+on: [push, pull_request]
+jobs:
+  architecture-check:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - name: Set up JDK 17
+        uses: actions/setup-java@v4
+        with:
+          java-version: '17'
+          distribution: 'temurin'
+      - name: Run Architecture Tests
+        run: mvn test -Dtest=ArchitectureComplianceTest
+```
+
+### Python 校验脚本
+
+提供 `scripts/check_cola.py` 进行静态分析:
+```bash
+python scripts/check_cola.py /path/to/project
+```
+
+## 评分模型
+
+| 分级 | 分数 | 含义 |
+|------|:----:|------|
+| A (Excellent) | ≥ 90 | 合规优秀,无违规或少量 P2 |
+| B (Good) | 70-89 | 基本合规,有改进空间 |
+| C (Fair) | 50-69 | 存在明显违规,需修复 P0 |
+| D (Needs Refactoring) | < 50 | 架构严重违规,建议重建 |
+
+## check_cola.py 校验
+
+`scripts/check_cola.py` 提供以下校验能力:
+
+1. **Domain 纯净度检查**:扫描 Domain 层的 import 语句,检测框架依赖
+2. **依赖方向检查**:检测 Domain → Infrastructure/App/Adapter 的反向依赖
+3. **包命名规范**:检查包名是否符合 COLA 约定
+4. **循环依赖检测**:DFS 遍历模块依赖图,检测环
+5. **合规评分**:P0 = 10分,P1 = 5分,P2 = 2分的扣分模型

+ 213 - 0
skills/ddd-skills/ddd-architecture-cola/references/08-cqrs-integration.md

@@ -0,0 +1,213 @@
+# COLA v5 CQRS 集成模式
+
+## CQRS 在 COLA 中的目录体现
+
+```
+{project}-app/
+├── executor/
+│   ├── command/         # 写操作执行器(CQRS 的 Command Side)
+│   │   ├── customer/
+│   │   │   ├── CustomerCreateCmdExe.java
+│   │   │   ├── CustomerUpdateCmdExe.java
+│   │   │   └── CustomerDeleteCmdExe.java
+│   │   └── order/
+│   │       ├── OrderCreateCmdExe.java
+│   │       ├── OrderPayCmdExe.java
+│   │       └── OrderCancelCmdExe.java
+│   └── query/           # 读操作执行器(CQRS 的 Query Side)
+│       ├── customer/
+│       │   ├── CustomerGetQryExe.java
+│       │   └── CustomerSearchQryExe.java
+│       └── order/
+│           ├── OrderGetQryExe.java
+│           └── OrderListQryExe.java
+├── model/
+│   ├── command/         # 命令对象(写请求 DTO)
+│   │   ├── CustomerCreateCmd.java
+│   │   ├── OrderPayCmd.java
+│   │   └── OrderCancelCmd.java
+│   └── query/           # 查询对象(读请求 DTO)
+│       ├── CustomerGetQry.java
+│       ├── CustomerSearchQry.java
+│       └── OrderListQry.java
+└── service/             # 可选:传统编排方式(非 CQRS 场景)
+```
+
+## CQRS 三级落地策略
+
+### L1 — 模型分离(推荐起步)
+
+同一数据源,仅代码层面分离命令和查询:
+
+```java
+// 命令执行器(写)
+@CommandExecutor
+public class OrderCreateCmdExe {
+    @Resource
+    private OrderRepository orderRepository;
+
+    @Override
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        Order order = Order.create(cmd);
+        orderRepository.save(order);
+        return OrderAssembler.toDTO(order);
+    }
+}
+
+// 查询执行器(读)
+@QueryExecutor
+public class OrderGetQryExe {
+    @Resource
+    private OrderRepository orderRepository;
+
+    @Override
+    public OrderDTO execute(OrderGetQry qry) {
+        return orderRepository.findById(new OrderId(qry.getId()))
+            .map(OrderAssembler::toDTO)
+            .orElseThrow(() -> new OrderNotFoundException(qry.getId()));
+    }
+}
+```
+
+### L2 — 数据库分离(中级)
+
+命令写主库,查询读从库/ES:
+
+```java
+// 命令执行器 → 写主库
+@CommandExecutor
+public class OrderCreateCmdExe {
+    @Resource
+    @Qualifier("primaryOrderRepository")  // 主库
+    private OrderRepository orderRepository;
+
+    @Override
+    @Transactional
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        Order order = Order.create(cmd);
+        order.addDomainEvent(new OrderCreatedEvent(order));
+        orderRepository.save(order);
+        return OrderAssembler.toDTO(order);
+    }
+}
+
+// 查询执行器 → 读从库
+@QueryExecutor
+public class OrderListQryExe {
+    @Resource
+    @Qualifier("readonlyOrderRepository")  // 从库
+    private OrderRepository orderRepository;
+
+    @Override
+    public PageResult<OrderDTO> execute(OrderListQry qry) {
+        return orderRepository.findByPage(qry.toPageRequest());
+    }
+}
+```
+
+### L3 — Event Sourcing(高级)
+
+事件溯源 + 物化视图:
+
+```java
+// 命令执行器 → 只写事件流
+@CommandExecutor
+public class OrderCreateCmdExe {
+    @Resource
+    private EventStore eventStore;
+
+    @Override
+    public OrderDTO execute(OrderCreateCmd cmd) {
+        OrderCreated event = new OrderCreated(
+            new OrderId(UUID.randomUUID().toString()),
+            cmd.getCustomerId(),
+            cmd.getItems()
+        );
+        eventStore.append(event);  // 只追加,不保存状态
+        return OrderDTO.from(event);
+    }
+}
+
+// 查询执行器 → 读物化视图
+@QueryExecutor
+public class OrderGetQryExe {
+    @Resource
+    private OrderProjectionRepository projectionRepo;
+
+    @Override
+    public OrderDTO execute(OrderGetQry qry) {
+        return projectionRepo.findById(qry.getId())
+            .orElseThrow(() -> new OrderNotFoundException(qry.getId()));
+    }
+}
+```
+
+## 幂等设计
+
+### 1. 事件表去重
+
+```sql
+CREATE TABLE idempotent_event (
+    event_id    VARCHAR(64) PRIMARY KEY,   -- 唯一事件 ID
+    event_type  VARCHAR(64) NOT NULL,
+    status      VARCHAR(16) NOT NULL,      -- PROCESSED / PENDING
+    created_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+```
+
+### 2. 状态机防护
+
+```java
+public enum OrderStatus {
+    DRAFT {          // 草稿
+        @Override
+        public boolean canPay() { return true; }
+        @Override
+        public boolean canCancel() { return true; }
+    },
+    PAID {           // 已支付(终态)
+        @Override
+        public boolean canPay() { return false; }
+        @Override
+        public boolean canCancel() { return true; }
+    },
+    CANCELLED {      // 已取消(终态)
+        @Override
+        public boolean canPay() { return false; }
+        @Override
+        public boolean canCancel() { return false; }
+    };
+
+    public abstract boolean canPay();
+    public abstract boolean canCancel();
+}
+```
+
+### 3. Redis 轻量去重
+
+```java
+@Component
+public class IdempotentHelper {
+    @Resource
+    private StringRedisTemplate redisTemplate;
+
+    public boolean tryProcess(String eventId) {
+        return Boolean.TRUE.equals(
+            redisTemplate.opsForValue()
+                .setIfAbsent("idempotent:" + eventId, "1", Duration.ofHours(24))
+        );
+    }
+}
+```
+
+## CQRS 各层职责总结
+
+| 组件 | 目录 | 职责 |
+|------|------|------|
+| Command Object | `app/model/command/` | 写操作请求 DTO,包含 `validate()` |
+| Query Object | `app/model/query/` | 读操作请求 DTO |
+| Command Executor | `app/executor/command/` | 写操作编排(事务) |
+| Query Executor | `app/executor/query/` | 读操作编排(无事务) |
+| Event Executor | `app/executor/event/` | 领域事件处理 |
+| Event Handler | `app/eventhandler/` | 事件监听处理器 |
+| App Service | `app/service/` | 非 CQRS 的传统编排方式 |

+ 0 - 0
skills/ddd-skills/ddd-architecture-cola/references/ddd4j-cola-structure.md → skills/ddd-skills/ddd-architecture-cola/references/09-ddd4j-cola-structure.md


+ 0 - 0
skills/ddd-skills/ddd-architecture-cola/references/directory-structure.md → skills/ddd-skills/ddd-architecture-cola/references/10-directory-structure.md


+ 105 - 0
skills/ddd-skills/ddd-architecture-cola/references/14-ddd4j-scaffold.md

@@ -0,0 +1,105 @@
+# DDD4j 项目脚手架(Project Scaffolding)
+
+ddd4j Boot 是 COLA v5 的 Java 参考实现,提供完整的项目生成和验证工具链。
+
+## 项目生成流程
+
+### Step 1: 确认项目类型
+
+从用户需求中识别项目类型:
+- **Single-module monolith** (`single-module`): 中小型应用,单个业务领域,团队规模 5-15 人
+- **Multi-module monolith** (`multi-module`): 中大型应用,多个业务域,团队规模 15-50 人
+- **Microservices** (`microservices`): 大型电商平台,多个业务域,团队规模 50+ 人
+
+### Step 2: 加载对应的示例
+
+从 `examples/` 目录加载合适的项目结构示例:
+- `examples/13-architecture-patterns.md` — DDD、Hexagonal、Clean、COLA V5 四种架构模式
+- `examples/14-single-module.md` — 单模块单体结构
+- `examples/15-multi-module.md` — 多模块单体结构
+- `examples/16-microservices.md` — 微服务结构
+
+### Step 3: 收集项目信息
+
+- `groupId`: Maven group ID(如 `com.github.hiwepy`)
+- `artifactId`: Maven artifact ID(如 `ddd4j-douyin`)
+- `version`: 项目版本(如 `1.0.0-SNAPSHOT`)
+- `packageBase`: 基础包名(如 `io.ddd4j.douyin`)
+- `modules`: 业务模块列表(多模块/微服务场景)
+- `architecture`: 架构模式(DDD Classic、Hexagonal、Clean、COLA V5)
+
+### Step 4: 生成项目结构
+
+- 根据所选类型创建目录结构
+- 生成 `pom.xml` 文件(父模块和子模块)
+- 为每个模块创建 `package-info.java` 文件
+- 生成 `.gitignore`、`LICENSE`、`mvnw`、`mvnw.cmd`
+- 创建基础目录结构 `src/main/java` 和 `src/test/java`
+
+### Step 5: 保存到项目目录
+
+- **默认位置**: 直接保存到命令执行目录(与命令同级)
+- **目录创建**: 自动创建项目目录结构(如不存在)
+- **文件命名**: 使用 artifactId 作为项目根目录名
+
+## 项目结构标准
+
+### 包命名规范
+
+多模块项目遵循:
+```
+{basePackage}.{moduleName}.{layerName}
+```
+
+示例:
+- `io.ddd4j.douyin.api.domain` — API 模块领域层
+- `io.ddd4j.douyin.api.application` — API 模块应用层
+- `io.ddd4j.douyin.api.interfaces` — API 模块接口层
+- `io.ddd4j.douyin.api.infrastructure` — API 模块基础设施层
+
+### 必需文件清单
+
+每个模块必须包含:
+- `pom.xml` — Maven 配置
+- `src/main/java/{package}/package-info.java` — 包文档
+- `src/test/java/` — 测试目录结构
+- `.gitignore` — Git 忽略规则(根目录)
+- `LICENSE` — 许可证文件(根目录)
+- `mvnw`、`mvnw.cmd` — Maven Wrapper(根目录)
+
+### 层依赖关系
+
+正确的依赖方向:
+```
+interfaces → application → domain ← infrastructure
+```
+
+规则:
+- **Domain 层**不得依赖任何其他层
+- **Infrastructure 层**实现 Domain 层定义的接口
+- **Application 层**依赖 Domain 层
+- **Interfaces 层**依赖 Application 层
+
+## 验证规则
+
+对已有项目进行合规检查时,验证以下方面:
+
+### 1. 结构合规性
+- 分层组织是否正确
+- 模块划分是否合理
+- 包命名是否符合规范
+
+### 2. 依赖规则
+- Domain 层无外部依赖
+- Infrastructure 正确实现 Domain 接口
+- 依赖方向正确(interfaces → application → domain ← infrastructure)
+
+### 3. 文件组织
+- 必需目录是否存在
+- `package-info.java` 文件是否存在
+- Maven 配置是否正确
+
+### 4. 命名规范
+- 包名是否遵循 `{basePackage}.{module}.{layer}` 约定
+- 模块名称是否描述性明确
+- 层名称是否标准化

+ 0 - 0
skills/ddd-skills/ddd4j-project-creator/scripts/check_project.py → skills/ddd-skills/ddd-architecture-cola/scripts/check_project.py


+ 0 - 0
skills/ddd-skills/ddd4j-project-creator/scripts/init_project.py → skills/ddd-skills/ddd-architecture-cola/scripts/init_project.py


+ 148 - 364
skills/ddd-skills/ddd-architecture-doc/SKILL.md

@@ -1,437 +1,221 @@
 ---
 name: ddd-architecture-doc
-description: Provides comprehensive guidance for DDD architecture documentation — ADR (Architecture Decision Records), C4 model diagrams (System Context, Container, Component, Code), architecture document templates, decision tracking, and architecture review checklists. Covers DDD-to-C4 mapping (L1=All BCs, L2=Per-BC deployment, L3=Module structure, L4=Aggregate internals), ADR templates with status tracking, and Mermaid diagram generation for all C4 levels. Use when the user asks about architecture documentation, ADR, C4 model, 架构文档, architecture decision record, 技术文档, or needs to document DDD architecture for the team.
+description: DDD architecture documentation generation — C4 model diagrams (Context/Container/Component/Code), ADR (Architecture Decision Records), domain model documentation, API documentation, architecture decision log, and team communication templates. Use when user asks about architecture documentation, 架构文档, ADR, C4 diagram, domain model doc, 架构决策记录, or needs to document DDD architecture for team.
 license: Apache-2.0
 ---
 
 # DDD Architecture Documentation
 
-Architecture documentation — ADR + C4 Model + Decision Tracking for DDD systems.
+Generate comprehensive DDD architecture documentation: C4 model diagrams (L1-L4), ADRs, domain model docs, API docs, decision logs, and team communication templates.
 
-## When to use this skill
+## Workflow
 
-**ALWAYS use this skill when the user mentions:**
-- "架构文档"、"architecture documentation"、"architecture doc"
-- "ADR"、"Architecture Decision Record"、"架构决策记录"
-- "C4 模型"、"C4 model"、"C4 diagram"
-- "架构图"、"architecture diagram"、"system context"
-- "技术文档"、"technical documentation"
-- "怎么把架构讲清楚"、"how to document architecture"
-- "架构评审"、"architecture review checklist"
+Follow this 5-step workflow when generating architecture documentation:
 
-## ADR (Architecture Decision Record)
-
-### ADR Template
-
-```markdown
-# ADR-{NNN}: {Short Descriptive Title}
-
-## Status
-{Proposed / Accepted / Deprecated / Superseded}
-
-## Context
-Why do we need this decision? What forces are at play?
-
-## Decision
-What did we decide to do?
+```
+Step 1: Understand Context — Project size, team, tech stack, domain
+Step 2: Identify Audiences — Business / dev / ops
+Step 3: Select C4 Level — L1 for business, L2 for ops, L3 for dev team
+Step 4: Check Decisions — Any existing ADRs? Need to create new ones?
+Step 5: Generate Output — Combine diagrams + ADRs + templates into one doc
+```
 
-## Alternatives Considered
-| Option | Pros | Cons | Decision |
-|--------|------|------|:--------:|
-| Option A | ... | ... | ✗ |
-| Option B | ... | ... | ✗ |
-| **Option C** | ... | ... | ✓ |
+**When info is insufficient**: give a best-guess version first based on common patterns (e.g., e-commerce) + list what specific information is still needed. Never just say "请提供更多信息".
 
-## Consequences
-What becomes easier? What becomes harder?
-- Positive: ...
-- Negative: ...
-- Neutral: ...
+## Boundary
 
-## Related
-- ADR-{NNN}: {related decision}
-```
+### ✅ 擅长处理
+1. **C4 模型图生成** — L1 System Context / L2 Container / L3 Component / L4 Code(Mermaid)
+2. **ADR 架构决策记录** — 模板 + 索引 + 状态追踪
+3. **领域模型文档** — 聚合描述 + 实体/值对象/事件列表
+4. **API 文档** — CQRS 命令/查询分离的 API 规范
 
-### ADR Example
+### ⚠️ 需要条件
+1. **已有架构决策** — 需要先有决策才能记录 ADR
+2. **已识别限界上下文** — 至少知道系统有哪些 BC 才能画 C4 L1 图
+3. **技术栈已知** — 需要知道框架/数据库/中间件才能生成 L2 容器图
 
-```markdown
-# ADR-001: Choose COLA Architecture as Project Foundation
+### ❌ 超出范围(不适用场景)
+1. **无架构决策 → 先做决策再文档**(路由到 `ddd-architecture-selector`)
+2. **单人项目 → README + 行内注释即可**
+3. **需架构选型 → `ddd-architecture-selector`**
+4. **需代码审查 → `ddd-code-reviewer`**
 
-## Status
-Accepted (2024-03-15)
-
-## Context
-E-commerce platform project, estimated 5 bounded contexts,
-team of 8 (4 backend + 2 frontend + 1 PM + 1 QA).
-Needs unified architecture conventions.
-
-## Decision
-Adopt COLA v5 architecture (diamond pattern), simplified single-module version.
-
-## Alternatives Considered
-| Option | Pros | Cons | Decision |
-|--------|------|------|:--------:|
-| Traditional 3-Layer | Team familiar | Hard to maintain complex business | ✗ |
-| Hexagonal | Excellent testability | High learning curve | ✗ |
-| Clean Architecture | Enterprise standard | Overly complex for team size | ✗ |
-| **COLA v5** | Strong Chinese ecosystem | — | ✓ |
-
-## Consequences
-- Modules increase from 1 to 4 (adapter/app/domain/infrastructure)
-- New team members need 1-week DDD + COLA training
-- CI/CD must add ArchUnit check step
-- Domain layer zero-dependency enforced
-
-## Related
-- ADR-002: CQRS Implementation Strategy
-- ADR-003: Domain Event Middleware Selection
-```
+## Audience
 
-### ADR Status Tracking
+This skill is designed for: **Backend developers** (implementing DDD architectures), **Software architects** (evaluating and selecting patterns), **Tech leads** (reviewing team implementations), and **DDD beginners** (learning domain-driven design fundamentals).
 
-```markdown
-## ADR Index
+## Rules
 
-| ADR# | Title | Status | Date | Superseded By |
-|------|-------|--------|------|---------------|
-| 001 | Choose COLA Architecture | Accepted | 2024-03-15 | — |
-| 002 | CQRS Strategy L1 | Accepted | 2024-03-20 | — |
-| 003 | Event Middleware: Spring Events | Accepted | 2024-03-25 | WIP |
-| 004 | MySQL over PostgreSQL | Deprecated | 2024-02-01 | ADR-006 |
-| 005 | Monolith over Microservices | Accepted | 2024-04-01 | — |
-```
+1. Every architecture decision must be documented as an ADR.
+2. C4 diagrams must follow Level 1→4 hierarchy.
+3. Domain model documentation must reference bounded contexts.
+4. All decision logs must include date, context, options, and rationale.
 
-## C4 Model Diagrams
+## C4 模型四层
 
-### DDD to C4 Mapping
+### DDD → C4 Mapping
 
 ```
-C4 Level     | DDD Context               | Audience
-─────────────┼───────────────────────────┼──────────
-L1: System   | Entire system with all    | Business,
-   Context   | bounded contexts           | Architecture
-L2: Container| Per-BC independent        | Architecture,
-             | deployment units           | DevOps
-L3: Component| BC internal module        | Development
-             | structure (Adapter/App/    | Team
-             | Domain/Infra)
-L4: Code     | Aggregate internals        | Developers
-             | (entities, VOs, events)
+C4 Level     | DDD Context                   | Audience
+─────────────┼───────────────────────────────┼────────────────
+L1 Context   | All bounded contexts + externals | Business, Architects
+L2 Container | Per-BC deployment units        | Architects, DevOps
+L3 Component | BC internal layers (Adapter/App/Domain/Infra) | Dev Team
+L4 Code      | Aggregate internals (entities, VOs, events) | Developers
 ```
 
-### L1: System Context Diagram (Mermaid)
+### L1: System Context — 展示系统与外部关系
 
 ```mermaid
 graph TB
-    Customer["👤 Customer"]
-    Admin["👤 Admin"]
-    Logistics["🚚 Logistics Partner"]
-    PaymentGateway["💳 Payment Gateway"]
-
-    subgraph System["E-Commerce Platform"]
-        direction TB
-        OrderBC["Order Context"]
-        PaymentBC["Payment Context"]
-        ProductBC["Product Context"]
-    end
-
-    Customer -->|Places orders| OrderBC
-    Customer -->|Makes payment| PaymentBC
-    Admin -->|Manages products| ProductBC
-    OrderBC -->|Notifies| Logistics
-    PaymentBC -->|Processes via| PaymentGateway
-    OrderBC <-->|Coordinates| PaymentBC
+    Customer["👤 Customer"] --> BC1["Bounded Context 1"]
+    Customer --> BC2["Bounded Context 2"]
+    Admin["👤 Admin"] --> BC3["Bounded Context 3"]
+    BC1 --> PaymentGW["💳 Payment Gateway"]
 ```
 
-### L2: Container Diagram (Mermaid)
+### L2: Container — 单个 BC 的部署单元
 
 ```mermaid
 graph TB
-    subgraph OrderContext["Order Context"]
-        OrderAPI["Order API\n(Spring Boot)"]
-        OrderDB[("Order DB\n(PostgreSQL)")]
-        OrderEvents["Order Events\n(RabbitMQ)"]
-    end
-
-    subgraph PaymentContext["Payment Context"]
-        PaymentAPI["Payment API\n(Spring Boot)"]
-        PaymentDB[("Payment DB\n(PostgreSQL)")]
-    end
-
-    WebApp["Web App\n(React)"]
-    MobileApp["Mobile App\n(React Native)"]
-
-    WebApp -->|REST| OrderAPI
-    MobileApp -->|REST| OrderAPI
-    OrderAPI --> OrderDB
-    OrderAPI --> OrderEvents
-    OrderEvents --> PaymentAPI
-    PaymentAPI --> PaymentDB
+    Web["Web App"] --> API["API (Spring Boot)"]
+    API --> DB[("Database (PostgreSQL)")]
+    API --> Queue["Event Queue (RabbitMQ)"]
 ```
 
-### L3: Component Diagram — Order Context (Mermaid)
+L3/L4 完整 Mermaid 代码示例见 `references/01-c4-examples.md`。
 
-```mermaid
-graph TB
-    subgraph Adapter["Adapter Layer"]
-        OrderController["OrderController"]
-        OrderDTO["OrderDTO"]
-    end
-
-    subgraph App["Application Layer"]
-        OrderAppService["OrderAppService"]
-        CreateOrderCmd["CreateOrderCommand"]
-        OrderQuery["OrderQueryService"]
-    end
-
-    subgraph Domain["Domain Layer"]
-        Order["Order (Aggregate Root)"]
-        OrderItem["OrderItem (Entity)"]
-        Money["Money (VO)"]
-        OrderRepository["OrderRepository (Interface)"]
-        OrderPaidEvent["OrderPaidEvent"]
-    end
-
-    subgraph Infra["Infrastructure Layer"]
-        JpaOrderRepo["JpaOrderRepository"]
-        OrderPO["OrderPO"]
-    end
-
-    OrderController --> OrderAppService
-    OrderController --> OrderQuery
-    OrderAppService --> CreateOrderCmd
-    OrderAppService --> OrderRepository
-    OrderAppService --> Order
-    Order --> OrderItem
-    Order --> Money
-    Order --> OrderPaidEvent
-    JpaOrderRepo -.->|implements| OrderRepository
-    JpaOrderRepo --> OrderPO
-```
+**When to use each level**: L1 for project kickoff, L2 for ops handover, L3 for daily dev reference, L4 for complex aggregates only.
 
-### L4: Code Diagram — Order Aggregate (Mermaid)
+## ADR (Architecture Decision Record)
 
-```mermaid
-classDiagram
-    class Order {
-        -OrderId id
-        -OrderStatus status
-        -Money totalAmount
-        -List~OrderItem~ items
-        +pay() void
-        +cancel(reason) void
-        +addItem(item) void
-        +calculateTotal() Money
-    }
-    class OrderItem {
-        -ProductId productId
-        -Money unitPrice
-        -int quantity
-        +getSubtotal() Money
-    }
-    class Money {
-        -BigDecimal amount
-        -String currency
-        +add(other) Money
-        +multiply(n) Money
-    }
-    class OrderId {
-        -String value
-    }
-    class OrderStatus {
-        <<enumeration>>
-        DRAFT
-        PAID
-        SHIPPED
-        DELIVERED
-        CANCELLED
-        +canPay() boolean
-        +canCancel() boolean
-    }
-    class OrderPaidEvent {
-        +OrderId orderId
-        +Money amount
-    }
-
-    Order "1" --> "*" OrderItem
-    Order --> Money
-    Order --> OrderId
-    Order --> OrderStatus
-    Order ..> OrderPaidEvent : publishes
+### ADR Template
+
+```markdown
+# ADR-{NNN}: {Short Title}
+
+## Status
+{Proposed / Accepted / Deprecated / Superseded}
+
+## Context / Decision / Alternatives / Consequences
+- **Context**: Why is this decision needed?
+- **Decision**: What did we decide?
+- **Alternatives**: Options considered with pros/cons, mark chosen
+- **Consequences**: Positive + negative impacts
+- **Related**: ADR-{NNN}: {related}
 ```
 
-## Architecture Document Template
+### ADR Status Tracking Table
 
 ```markdown
-# {Project Name} Architecture Document
-
-## 1. Architecture Overview
-- Architecture Pattern: {Layered/Onion/Hexagonal/Clean/COLA}
-- CQRS Level: {None/L1/L2/L3}
-- Architecture Diagram (C4 L1 + L2)
-
-## 2. Bounded Contexts
-| Context | Type | Responsibility | Microservice |
-|---------|------|----------------|:-----------:|
-| Order | Core | Order management | ✓ |
-| Payment | Core | Payment processing | ✓ |
-| Product | Supporting | Product catalog | ✓ |
-| Auth | Generic | Authentication | Shared |
-
-## 3. Layering Conventions
-(Reference specific Architecture Skill conventions)
-
-## 4. Technology Stack
-| Component | Technology | Version |
-|-----------|-----------|---------|
-| Framework | Spring Boot | 3.4.x |
-| ORM | MyBatis Plus | 3.5.x |
-| Database | PostgreSQL | 16 |
-| Cache | Redis | 7.x |
-| Message Queue | RabbitMQ | 3.13 |
-| Search | Elasticsearch | 8.x |
-
-## 5. Deployment Architecture
-(K8s/Docker Compose deployment diagrams)
-
-## 6. Architecture Decision Records
-(ADR list + index)
-
-## 7. Security Architecture
-(Authentication/Authorization/Data Protection)
-
-## 8. Operations Manual
-(Monitoring/Alerting/Logging/Disaster Recovery)
-
-## 9. Architecture Review Checklist
-- [ ] Dependency direction correct
-- [ ] Domain layer zero framework dependencies
-- [ ] No circular module dependencies
-- [ ] Rich domain models for core aggregates
-- [ ] Domain events for key business operations
-- [ ] ADR records up to date
+| ADR# | Title | Status | Date | Superseded By |
+|------|-------|:------:|:----:|:----:|
+| 001 | Choose COLA Architecture | Accepted | 2024-03-15 | — |
+| 002 | CQRS Strategy L2 | Accepted | 2024-03-20 | — |
+| 003 | MySQL over PostgreSQL | Deprecated | 2024-02-01 | ADR-005 |
 ```
 
-## Architecture Review Checklist
+## Domain Model Documentation
 
-```
-□ Architecture pattern clearly documented and communicated
-□ Bounded contexts identified with clear boundaries
-□ Context mapping relationships defined (ACL, OHS, Partnership, etc.)
-□ Layer dependencies follow defined direction
-□ Domain layer is free of framework dependencies
-□ Key aggregates have rich domain models
-□ Cross-aggregate operations use domain events
-□ ADRs recorded for all significant decisions
-□ C4 diagrams kept up to date with code
-□ Architecture validation automated in CI/CD
-□ New team members have onboarding guide
-```
+Document each aggregate:
 
-## Diagram Generation Guidelines
+```markdown
+## Aggregate: {Name}
+- **Root**: {ClassName} | **Id**: {IdType}
+- **Entities**: Table of entity / owner / lifecycle
+- **Value Objects**: Table of VO / fields / immutable
+- **Domain Events**: Table of event / trigger / consumer
+- **Invariants**: 1. {Invariant 1}
+- **State Machine**: ```mermaid stateDiagram-v2```
+```
 
-### When to Use Each Diagram Type
+## API Documentation — CQRS 命令/查询分离
 
-| Diagram | When | Mermaid Type |
-|---------|------|-------------|
-| System Context | Show overall system + external actors | `graph TB` |
-| Container | Show deployment units + communication | `graph TB` |
-| Component | Show module internals (Adapter→App→Domain←Infra) | `graph TB` |
-| Code / Class | Show aggregate structure (entities, VOs, events) | `classDiagram` |
-| Sequence | Show domain event flow across contexts | `sequenceDiagram` |
-| ER | Show database schema | `erDiagram` |
-| Context Map | Show bounded context relationships | `graph LR` |
-| State | Show aggregate lifecycle (status transitions) | `stateDiagram-v2` |
+| API Type | Method | Example | CQRS Model |
+|----------|--------|---------|:----------:|
+| Command | POST/PUT/DELETE | `POST /orders` | Command Model |
+| Query | GET | `GET /orders?status=PAID` | Query Model |
 
-## Output
+**Command API**: triggers domain behavior, publishes domain events, idempotent key required.
+**Query API**: reads from query model (may be separate read DB), no side effects.
 
-When assisting with this skill, provide:
-- Architecture Decision Records (ADR template + examples)
-- C4 model L1/L2/L3 diagrams (Mermaid format)
-- Complete architecture document template
-- ADR index + status tracking table
-- Architecture review checklist
+## Architecture Decision Log
 
-## Related Skills
+Maintain a central index:
 
-- [ddd-architecture-selector](../ddd-architecture-selector/) — Initial architecture selection
-- [ddd-architecture-evaluator](../ddd-architecture-evaluator/) — Periodic architecture assessment
-- [ddd-code-reviewer](../ddd-code-reviewer/) — Code-level compliance check
+```
+docs/adrs/
+├── README.md          ← Auto-generated ADL index
+├── ADR-001-title.md
+└── ...
+```
 
----
+**Best practices**: one ADR file = one decision; ADR in the same repo as code; CI auto-generates the index.
 
-## Skill Boundary
+## 文档维护策略
 
-### ✅ 擅长处理
-1. 架构文档生成(C4 模型 L1-L4)
-2. ADR(架构决策记录)模板和状态追踪
-3. Mermaid 图表生成(DDD→C4 映射)
-4. 架构审查检查清单
+| 策略 | 频率 | 谁负责 |
+|------|:----:|--------|
+| PR 时同步更新 ADR + 图 | 每次代码变更 | 开发者 |
+| C4 图季度审计 | 每季度 | 架构师 |
+| ADL 索引自动生成 | 每次 ADR 变更 | CI |
+| 全量架构文档 Review | 每月 | 架构组 |
 
-### ⚠️ 需要条件
-1. 已有架构决策需要记录
-2. 团队需要文档共享和评审
+**Golden rule**: if code changes the architecture, the doc changes in the same PR.
 
-### ❌ 超出范围
-1. 无架构决策 → 先做决策再文档
-2. 单人项目 → README + 行内注释即可
-3. 需架构选型 → `ddd-architecture-selector`
+## Gotchas — Common Pitfalls
 
+1. **C4 层级乱用** — 每层有明确定义,不要混用。
+2. **ADR 写太晚** — 决策时同步记录,哪怕只写一句话。
+3. **文档与代码不同步** — 每次架构变更后必须更新。
+4. **只画图不写决策理由** — C4 展示 What,ADR 解释 Why。
+5. **图过于复杂** — 每张图 5-7 节点为限。
+6. **过度文档** — 聚焦"别人需要知道什么才能开发"。
+7. **ADR 不写备选** — 必须记录为什么没选其他方案。
+8. **忽略受众** — 不同受众用不同 C4 级别。
 
-## Security & Stability
+## FAQ
 
-- Architecture docs may contain system topology and deployment configs. Store in private repos only.
-- C4 diagrams and ADRs should not include credentials or internal IPs in public documents.
-- When generating Mermaid diagrams, ensure they don't expose internal service URLs.
-- No executable scripts bundled. This skill provides documentation templates and patterns.
+**Q1: 文档应该用什么工具?** 先用 Mermaid,复杂度上升后考虑 Structurizr。
 
+**Q2: 需要画哪些 C4 层级?** L1 + L2 是必须的,L3 视团队规模(>5 人推荐)。
 
-## Gotchas — Common Pitfalls
+**Q3: 怎么保证文档不过期?** PR 勾选框 + CI 检查 ADR 一致性 + 月度 Review。
 
-- **C4 Level 不对应**: L1(System Context)画了模块内部细节,L2(Container)跳到代码级别。C4 每层有明确定义:L1=系统与外部关系,L2=容器/服务,L3=组件/模块,L4=代码/类。
-- **ADR 写太晚**: 架构决策做完几个月后才补写 ADR。ADR 应该在决策时同步记录,否则记忆会失真,决策上下文丢失。
-- **文档与代码不同步**: 文档写了 Hexagonal 但代码实际是 Layered。每次架构变更后必须更新文档。推荐在 CI 中加入 ArchUnit 检查,确保文档和代码一致。
-- **只画图不写决策理由**: C4 图只展示结构,不说明为什么这样设计。图 + ADR 组合才完整:图展示 What,ADR 解释 Why。
-- **Mermaid 图过于复杂**: 把 10+ 个 bounded context 全塞进一张图。复杂系统应该分层画:总览图 → 逐 BC 展开图。一张图不应超过 5-7 个节点。
+**Q4: 遗留系统没有文档怎么办?** 先画 AS-IS 的 L1 图 → 记录关键 ADR → 每 sprint 完善一个 BC。
 
-## When NOT to Use This Skill
+**Q5: ADR 需要写多详细?** 至少包含背景、决策、备选方案(≥2 个)和影响。
 
-| ❌ Skip | ✅ Use Instead |
-|---------|---------------|
-| No architecture decisions made yet | Build the system first, document later |
-| Solo developer, no team | Minimal README + inline comments suffice |
-| Need architecture selection first | `architecture-selector` |
-| Want to review architecture quality | `architecture-evaluator` |
-| Just started coding, architecture fluid | Wait until key decisions stabilize |
+**Q6: 多人同时改一个 BC 的文档怎么处理?** Git 冲突解决机制即可,PR Review 时同步 Review 文档。
 
-## Security & Stability
+## Security & Safety
 
-- Architecture documentation may contain system topology, technology choices, and deployment configurations. Store these in private team repositories only.
-- C4 diagrams and ADRs should not include credentials, internal IP addresses, or security-sensitive infrastructure details in public-facing documents.
-- When generating Mermaid diagrams, ensure they don't expose internal service URLs or security group configurations.
-- No executable scripts bundled. This skill provides documentation templates and diagram generation patterns.
+This skill is pure documentation. It does not collect user data, does not access external services or networks, and contains no executable scripts.
 
-## 🧭 DDD Skills Journey
+## Keywords
 
-> 📍 **You are here: `ddd-architecture-doc` — 🏁 Step 7: 架构文档输出**
+- Keywords: architecture documentation, 架构文档, ADR, C4 diagram, C4 模型, architecture decision record, 架构决策记录, domain model doc, 领域模型文档, 技术文档, 架构图, system context, container diagram, component diagram, code diagram, 架构评审, 文档模板, architecture decision log
 
-```mermaid
-flowchart LR
-    S1["Step 1<br/>awesome"] --> S2["Step 2<br/>selector"]
-    S2 --> S3["Step 3<br/>5架构 Skill"]
-    S3 --> S4["Step 4<br/>domain/cqrs/api"]
-    S4 --> S5["Step 5<br/>code-reviewer"]
-    S5 --> S6["Step 6<br/>辅助能力"]
-    S6 --> S7["🏁⭐ Step 7<br/>architecture-doc"]
-
-    style S7 fill:#10b981,stroke:#059669,color:white,stroke-width:3px
-```
+## References
 
-**← Previous**: [evaluator](../ddd-architecture-evaluator/) — 先完成架构评估,再输出文档
-**→ Next**: 🏁 终点 — 也可以回到 [awesome](../ddd-architecture-awesome/) 回顾全景
-**🔗 Related**: [awesome](../ddd-architecture-awesome/) — 回顾 DDD 概念全景 | [selector](../ddd-architecture-selector/) — 记录 ADR 选型决策
-**🏠 Home**: [awesome](../ddd-architecture-awesome/) — DDD 概念全景
+| File | Content | When to Reference |
+|------|---------|-------------------|
+| `references/01-c4-examples.md` | Full C4 L1-L4 Mermaid examples for e-commerce | User needs complete C4 diagrams to copy-paste |
+| `references/02-adr-templates.md` | 3 ADR template variants (standard, lightweight, tech) | User needs to write a new ADR |
+| `references/03-doc-templates.md` | 3 architecture doc templates (full, lightweight, onboarding) | User needs a document structure to start with |
+| `references/04-toolchain.md` | Tool recommendations (Structurizr, Mermaid, PlantUML, ArchUnit) | User asks about tools or automation |
+| `references/05-team-templates.md` | Team communication templates (review request, change notice) | User needs to notify or review with team |
+| `references/06-arch-decision-log.md` | ADL index format + CI automation | User needs to maintain or automate ADR tracking |
+| `references/07-domain-model-doc.md` | Aggregate/BC documentation patterns | User needs to document domain models |
+| `references/08-api-doc-patterns.md` | CQRS API documentation patterns + OpenAPI spec | User needs to document APIs with CQRS |
+| `references/09-trace-anti-patterns.md` | Architecture doc anti-patterns (5 categories) | User needs to avoid common documentation mistakes |
+| `references/10-faq-deep.md` | In-depth FAQ (microservices ADR, legacy systems, security) | User has advanced or edge-case questions |
 
-💡 ADR + C4 模型 + 架构评审 Checklist。这是 DDD 旅程最后一站——把架构讲清楚给团队看。
+## Related Skills
 
-> 📋 See [DESIGN.md](../DESIGN.md) for the complete 16-skill ecosystem map.
+- [ddd-architecture-selector](../ddd-architecture-selector/) — Architecture selection (before you document, make decisions)
+- [ddd-architecture-evaluator](../ddd-architecture-evaluator/) — Periodic architecture health check
+- [ddd-code-reviewer](../ddd-code-reviewer/) — Code-level DDD compliance check
+- [ddd-cqrs-architecture](../ddd-cqrs-architecture/) — CQRS detail for API documentation
+- [awesome](../ddd-architecture-awesome/) — DDD concept overview

+ 108 - 0
skills/ddd-skills/ddd-architecture-doc/examples/01-adr-examples.md

@@ -0,0 +1,108 @@
+# ADR 完整示例 — 电商平台
+
+> 本文档提供电商平台的 3 个完整 ADR 示例,覆盖架构选型、CQRS、技术选型三类场景。
+
+---
+
+### ADR-001: 选择 COLA v5 作为基础架构
+
+**状态**: 已采纳 (2024-03-15)
+
+**背景**: 电商中台项目,5 个限界上下文(订单、支付、商品、库存、用户),团队 8 人(4 后端 + 2 前端 + 1 PM + 1 QA)。需要统一的架构规范来约束开发行为。
+
+**决策**: 采用 COLA v5 架构(菱形架构),单模块简化版。
+
+**备选方案**:
+
+| 方案 | 优点 | 缺点 | 决定 |
+|------|------|------|:----:|
+| 传统三层 | 团队熟悉,学习成本低 | 复杂业务难维护 | ✗ |
+| 六边形 | 可测试性强,Port/Adapter 清晰 | 学习成本高,门槛高 | ✗ |
+| 整洁架构 | 企业级规范,分层严格 | 过度设计,团队 8 人扛不住 | ✗ |
+| **COLA v5** | 国内生态好,文档齐全 | — | ✓ |
+
+**决策理由**:
+1. 团队使用 Spring Boot + MyBatis,COLA 对此生态最佳支持
+2. COLA 5.0 中文文档齐全,降低团队学习成本
+3. 具备内置的架构校验能力,可持续约束开发行为
+4. 单模块简化版不引入过多模块 Maven 管理成本
+
+**影响**:
+- 正向:统一了团队架构规范,新人按 COLA 目录结构即可理解代码
+- 正向:层次清晰,领域层纯净无框架依赖
+- 负向:模块数从 1 增加到 4(adapter/app/domain/infrastructure)
+- 负向:新人上手需要 1 周 DDD + COLA 培训
+- 中性:CI/CD 需增加 ArchUnit 检查步骤
+
+**关联**:
+- ADR-002: CQRS 实施策略
+- ADR-003: 事件中间件选型
+
+---
+
+### ADR-002: CQRS L2 策略(数据库分离)
+
+**状态**: 已采纳 (2024-03-20)
+
+**背景**: 订单查询 QPS 从 500 增长到 3000+,而写操作 QPS 仅 200。当前的读写混合模型导致:
+- 复杂查询(跨聚合 JOIN、聚合统计)需要多表查询,性能差
+- 查询缓存方案复杂,缓存一致性难以保证
+- 读模式(DTO/VO)与领域模型(Domain Entity)混用,违反分层原则
+
+**决策**: 采用 CQRS L2 策略,命令模型用 PostgreSQL,查询模型用 Elasticsearch。
+
+**备选方案**:
+
+| 方案 | 优点 | 缺点 | 决定 |
+|------|------|------|:----:|
+| L1 模型分离 | 简单,不增加基础设施 | 还是读同一个 DB,性能瓶颈不解决 | ✗ |
+| **L2 DB 分离** | 读写独立扩展,查询优化灵活 | 增加 ES 运维 | ✓ |
+| L3 Event Sourcing | 完整审计追踪 | 学习成本极高,复杂度过高 | ✗ |
+
+**同步机制**:
+```
+写操作 → Command DB (PostgreSQL) → 领域事件 → RabbitMQ → Projector → Query DB (ES)
+```
+
+**影响**:
+- 正向:查询性能提升 10x(从 50ms → 5ms P99)
+- 正向:读模型可独立优化,不影响写模型的领域逻辑
+- 负向:引入 ES 运维成本和数据同步延迟(< 1s)
+- 负向:需要处理同步失败和补偿逻辑
+
+**关联**:
+- ADR-001: COLA v5 架构
+- ADR-003: 事件中间件选型
+
+---
+
+### ADR-003: 领域事件中间件选型
+
+**状态**: 已采纳 (2024-03-25)
+
+**背景**: 跨聚合/跨服务操作需要领域事件实现最终一致性。团队已有消息中间件经验,但需要选择合适的消息方案。
+
+**决策**: 微服务内使用 Spring ApplicationEvent,跨微服务使用 RabbitMQ + Outbox 表。
+
+**备选方案**:
+
+| 方案 | 优点 | 缺点 | 决定 |
+|------|------|------|:----:|
+| 纯 Spring Event | 简单,零依赖 | 不支持跨服务 | ✗ |
+| 纯 Kafka | 高吞吐,持久化好 | 运维复杂,团队不熟 | ✗ |
+| **Spring Event + RabbitMQ + Outbox** | 渐进式,团队熟悉 | — | ✓ |
+| 纯 RabbitMQ | 统一消息通道 | 微服务内也用 MQ 太重 | ✗ |
+
+**Outbox 模式说明**:
+```
+业务操作 → 写 DB(含 Outbox 表) → Outbox Poller → 发 RabbitMQ → 消费者
+                                                                    ↓
+                                                             处理成功后删除 Outbox 记录
+```
+
+**影响**:
+- 正向:微服务内事件零额外成本(Spring Event)
+- 正向:Outbox 模式保证"业务操作"和"事件发布"的原子性
+- 正向:RabbitMQ 团队已有运维经验
+- 负向:需要 Outbox Poller 组件(可选 Debezium CDC)
+- 负向:RabbitMQ 相比 Kafka 在追数据场景能力弱

+ 226 - 0
skills/ddd-skills/ddd-architecture-doc/examples/02-c4-diagrams.md

@@ -0,0 +1,226 @@
+# C4 图完整示例 — 电商平台
+
+> 本文档展示电商平台完整的 C4 四层图示例。
+> 所有图表使用 Mermaid 格式,可直接嵌入架构文档。
+
+---
+
+## L1: System Context — 电商平台全景
+
+```mermaid
+graph TB
+    Customer["👤 顾客"]
+    Admin["👤 管理员"]
+    Supplier["🏭 供应商"]
+    Logistics["🚚 物流系统"]
+    PaymentGW["💳 支付网关"]
+    SMSService["📱 短信服务"]
+
+    subgraph Platform["🧩 电商平台"]
+        direction TB
+        BC1["订单系统"]
+        BC2["支付系统"]
+        BC3["商品系统"]
+        BC4["库存系统"]
+        BC5["用户系统"]
+    end
+
+    Admin -->|管理商品/订单| BC3
+    Customer -->|浏览下单| BC1
+    Customer -->|支付| BC2
+    Supplier -->|供货| BC4
+    BC1 -->|发货| Logistics
+    BC2 -->|调用| PaymentGW
+    BC1 -->|短信通知| SMSService
+```
+
+**说明**:L1 图展示电商平台与外部角色的交互。这是给业务方和架构师看的"电梯演讲"图。
+
+---
+
+## L2: Container — 订单系统内部容器
+
+```mermaid
+graph TB
+    subgraph OrderSystem["📦 订单系统"]
+        OrderAPI["Order API\n(Spring Boot)"]
+        OrderWorker["Order Worker\n(Spring Boot)"]
+        OrderDB[("Order DB\n(PostgreSQL 16)")]
+        OrderCache[("Order Cache\n(Redis 7.x)")]
+        OrderQueue["Order Event Queue\n(RabbitMQ 3.13)"]
+    end
+
+    Web["Web App\n(React)"]
+    Mobile["Mobile App\n(React Native)"]
+    PaymentSystem["支付系统"]
+    InventorySystem["库存系统"]
+
+    Web -->|REST/JSON| OrderAPI
+    Mobile -->|REST/JSON| OrderAPI
+    OrderAPI -->|读写| OrderDB
+    OrderAPI -->|缓存| OrderCache
+    OrderAPI -->|发事件| OrderQueue
+    OrderWorker -->|消费| OrderQueue
+    OrderWorker -->|写| OrderDB
+    OrderQueue -->|事件| PaymentSystem
+    OrderQueue -->|事件| InventorySystem
+```
+
+**说明**:L2 图展示订单系统内部的容器划分和技术选型。开发者和 DevOps 关注的层面。
+
+---
+
+## L3: Component — 订单 API 的 COLA 四层
+
+```mermaid
+graph TB
+    subgraph Adapter["适配层\n(adapter)"]
+        direction TB
+        Controller["OrderController"]
+        ReqDTO["CreateOrderRequest"]
+        RespDTO["OrderResponse"]
+    end
+
+    subgraph App["应用层\n(app)"]
+        direction TB
+        AppService["OrderAppService"]
+        Cmd["CreateOrderCommand"]
+        Query["OrderQueryService"]
+    end
+
+    subgraph Domain["领域层\n(domain)"]
+        direction TB
+        OrderAgg["Order (聚合根)"]
+        OrderItem["OrderItem (实体)"]
+        Money["Money (值对象)"]
+        OrderStatus["OrderStatus (枚举)"]
+        DomainEvent["OrderCreatedEvent"]
+        Repo["OrderRepository (接口)"]
+        DomainSvc["OrderDomainService"]
+    end
+
+    subgraph Infra["基础设施层\n(infrastructure)"]
+        direction TB
+        JpaRepo["JpaOrderRepository"]
+        EventPub["RabbitMqEventPublisher"]
+        CacheSvc["RedisCacheService"]
+    end
+
+    Controller --> AppService
+    Controller --> Query
+    AppService --> Cmd
+    AppService --> Repo
+    AppService --> DomainSvc
+    DomainSvc --> OrderAgg
+    OrderAgg --> OrderItem
+    OrderAgg --> Money
+    OrderAgg --> OrderStatus
+    OrderAgg --> DomainEvent
+    JpaRepo -.->|实现| Repo
+    EventPub --> OrderQueue
+```
+
+**说明**:L3 图展示 COLA 四层架构中每个层的核心组件及其依赖关系。这是开发者日常工作的主要参考图。
+
+---
+
+## L4: Code — 订单聚合类图
+
+```mermaid
+classDiagram
+    class Order {
+        -OrderId id
+        -CustomerId customerId
+        -OrderStatus status
+        -Money totalAmount
+        -List~OrderItem~ items
+        -Address shippingAddress
+        -LocalDateTime createdAt
+        +pay() void
+        +cancel(String reason) void
+        +addItem(ProductId, Money, int) void
+        +removeItem(ProductId) void
+        +calculateTotal() Money
+        +canBePaid() boolean
+    }
+
+    class OrderItem {
+        -ProductId productId
+        -String productName
+        -Money unitPrice
+        -int quantity
+        +getSubtotal() Money
+        +updateQuantity(int) void
+    }
+
+    class Money {
+        -BigDecimal amount
+        -Currency currency
+        +add(Money) Money
+        +subtract(Money) Money
+        +multiply(int) Money
+        +equals(Object) boolean
+    }
+
+    class OrderStatus {
+        <<enumeration>>
+        PENDING_PAYMENT
+        PAID
+        SHIPPED
+        DELIVERED
+        CANCELLED
+        +canPay() boolean
+        +canCancel() boolean
+        +nextStatus() OrderStatus
+    }
+
+    class OrderId {
+        -String value
+        +generate() OrderId
+        +fromString(String) OrderId
+        +toString() String
+    }
+
+    class Address {
+        -String province
+        -String city
+        -String district
+        -String detail
+        -String zipCode
+        +getFullAddress() String
+    }
+
+    class OrderCreatedEvent {
+        -OrderId orderId
+        -CustomerId customerId
+        -Money totalAmount
+        -LocalDateTime occurredOn
+    }
+
+    class OrderPaidEvent {
+        -OrderId orderId
+        -Money amount
+        -LocalDateTime paidAt
+    }
+
+    Order "1" --> "*" OrderItem
+    Order --> Money
+    Order --> OrderId
+    Order --> OrderStatus
+    Order --> Address
+    Order ..> OrderCreatedEvent : 发布
+    Order ..> OrderPaidEvent : 发布
+```
+
+**说明**:L4 图展示 Order 聚合的内部类结构。开发者实现具体功能时的参考。
+
+---
+
+## 关键映射:DDD ↔ C4
+
+| DDD 概念 | C4 级别 | 谁看 |
+|---------|---------|------|
+| 全系统所有限界上下文 | L1 System Context | 业务方、架构师 |
+| 每个限界上下文部署单元 | L2 Container | 架构师、DevOps |
+| 每个容器的 Adapter/App/Domain/Infra | L3 Component | 开发团队 |
+| 聚合内部结构(实体、值对象、事件) | L4 Code | 开发者 |

+ 144 - 0
skills/ddd-skills/ddd-architecture-doc/examples/03-architecture-document.md

@@ -0,0 +1,144 @@
+# 完整架构文档示例 — 电商平台
+
+> 本文档展示一个完整的电商平台架构文档。
+
+---
+
+# 电商平台架构文档
+
+> 版本: v2.1 | 最后更新: 2024-06-01 | 负责人: 架构组
+
+---
+
+## 1. 架构概览
+
+### 1.1 架构模式
+- **架构**: COLA v5(菱形架构)
+- **CQRS 级别**: L2(数据库分离 — 写库 PostgreSQL / 读库 Elasticsearch)
+- **微服务**: 5 个服务(订单、支付、商品、库存、用户)
+
+### 1.2 架构约束
+1. **依赖规则**: 领域层不依赖任何外部框架
+2. **聚合规则**: 聚合之间通过 ID 引用,不直接引用对象
+3. **事务规则**: 一个事务只修改一个聚合
+4. **事件规则**: 跨聚合操作通过领域事件实现最终一致性
+
+---
+
+## 2. 限界上下文
+
+| 上下文 | 类型 | 职责 | 微服务 | 语言 |
+|--------|------|------|:------:|:----:|
+| Order | 核心域 | 订单创建/支付/退款 | ✓ | Java |
+| Payment | 核心域 | 支付渠道对接/对账 | ✓ | Java |
+| Product | 支撑域 | 商品信息/分类/搜索 | ✓ | Java |
+| Inventory | 支撑域 | 库存管理/锁定/释放 | ✓ | Java |
+| User | 通用域 | 用户注册/认证/权限 | ✓ | Java |
+
+### 上下文映射
+
+```mermaid
+graph LR
+    Order -->|OHS| Payment
+    Order -->|ACL| Inventory
+    Product -->|Partnership| Inventory
+    User -->|OHS| Order
+    User -->|OHS| Payment
+```
+
+**图例**: OHS=开放主机服务, ACL=防腐层, Partnership=伙伴关系
+
+---
+
+## 3. C4 模型
+
+### L1: System Context
+
+```mermaid
+graph TB
+    Customer["👤 顾客"]
+    Admin["👤 管理员"]
+    Logistics["🚚 物流系统"]
+    PaymentGW["💳 支付网关"]
+
+    subgraph Platform["电商平台"]
+        Order["订单服务"]
+        Payment["支付服务"]
+        Product["商品服务"]
+        Inventory["库存服务"]
+        User["用户服务"]
+    end
+
+    Customer -->|"HTTP"| Order
+    Customer -->|"HTTP"| Payment
+    Admin -->|"HTTP"| Product
+    Order -->|"RPC"| Inventory
+    Order -->|"事件"| Payment
+    Payment -->|"HTTP"| PaymentGW
+    Order -->|"HTTP"| Logistics
+```
+
+### L2: Container — 订单服务
+
+```mermaid
+graph TB
+    subgraph OrderSvc["订单服务"]
+        OrderAPI["Order API\n(Spring Boot)"]
+        OrderWorker["Order Worker\n(Spring Boot)"]
+        OrderDB[("Order DB\n(PostgreSQL)")]
+        OrderCache[("Redis")]
+        OrderQueue[("RabbitMQ")]
+    end
+
+    Web["Web App\n(React)"]
+    Mobile["Mobile App\n(React Native)"]
+
+    Web --> OrderAPI
+    Mobile --> OrderAPI
+    OrderAPI <--> OrderDB
+    OrderAPI <--> OrderCache
+    OrderAPI --> OrderQueue
+    OrderWorker <--> OrderQueue
+    OrderWorker --> OrderDB
+```
+
+---
+
+## 4. 技术栈
+
+| 组件 | 技术 | 版本 | 说明 |
+|------|------|:----:|------|
+| 开发语言 | Java | 21 | — |
+| 框架 | Spring Boot | 3.4.x | — |
+| ORM | MyBatis Plus | 3.5.x | — |
+| 数据库 | PostgreSQL | 16 | 写库 |
+| 搜索引擎 | Elasticsearch | 8.x | 读库 |
+| 缓存 | Redis | 7.x | 会话 + 缓存 |
+| 消息队列 | RabbitMQ | 3.13 | 事件驱动 |
+| 注册中心 | Nacos | 2.x | 服务发现 |
+| 网关 | Spring Cloud Gateway | 4.x | — |
+| 部署 | Kubernetes | 1.28 | — |
+
+---
+
+## 5. ADR 索引
+
+| ADR# | 标题 | 状态 | 日期 | 负责人 |
+|------|------|:----:|:----:|:------:|
+| 001 | 选择 COLA v5 作为基础架构 | 已采纳 | 2024-03-15 | 张三 |
+| 002 | CQRS L2 策略(DB 分离) | 已采纳 | 2024-03-20 | 李四 |
+| 003 | 事件中间件: RabbitMQ | 已采纳 | 2024-03-25 | 王五 |
+| 004 | MySQL → PostgreSQL 迁移 | 已采纳 | 2024-04-01 | 张三 |
+| 005 | 单体 → 微服务拆分方案 | 已采纳 | 2024-05-01 | 赵六 |
+
+---
+
+## 6. 架构评审 Checklist
+
+- [x] 依赖方向正确(Domain 零框架依赖)
+- [x] 聚合间 ID 引用(无直接对象引用)
+- [x] 关键操作有领域事件(OrderCreated, OrderPaid)
+- [x] 跨聚合操作使用事件(下单 → 锁定库存)
+- [x] ADR 记录完整(5 个决策)
+- [x] C4 图与代码一致(已验证)
+- [x] ArchUnit 集成 CI(通过)

+ 131 - 0
skills/ddd-skills/ddd-architecture-doc/examples/04-domain-model-documentation.md

@@ -0,0 +1,131 @@
+# 领域模型文档示例
+
+> 本文档展示电商平台 Order 和 Payment 两个主要聚合的领域模型文档。
+
+---
+
+## 聚合:订单(Order)
+
+### 概述
+订单是电商平台的核心聚合,管理订单从创建到完成的整个生命周期。
+
+### 聚合根
+- **类名**: `Order`
+- **标识**: `OrderId`(值对象,UUID 格式)
+- **业务标识**: `orderNumber`(人工可读,如 "ORD-20240501-00001")
+
+### 业务规则(不变式 Invariants)
+1. **不可重复支付**: 订单只能支付一次,PAID 后不能再次支付
+2. **金额一致性**: 订单总金额 = 所有 OrderItem 金额之和
+3. **合法状态转换**: 状态机必须经过 PENDING_PAYMENT → PAID → SHIPPED → DELIVERED
+4. **取消条件**: 只有 PENDING_PAYMENT 和 PAID 状态的订单可以取消(PAID 取消需退款)
+5. **商品数量限制**: 单笔订单最多 50 个商品
+
+### 状态机
+
+```mermaid
+stateDiagram-v2
+    [*] --> PENDING_PAYMENT : 创建订单
+    PENDING_PAYMENT --> PAID : 支付成功
+    PENDING_PAYMENT --> CANCELLED : 用户取消
+    PAID --> SHIPPED : 发货
+    PAID --> CANCELLED : 退款取消
+    SHIPPED --> DELIVERED : 确认收货
+    SHIPPED --> RETURNING : 申请退货
+    RETURNING --> CANCELLED : 退货完成
+```
+
+### 实体(Entity)
+
+| 实体 | 聚合内唯一 | 生命周期 | 说明 |
+|------|:---------:|---------|------|
+| Order | ✓(聚合根) | 从创建到完成 | 订单主体 |
+| OrderItem | ✓ | 随 Order | 订单中的商品行 |
+
+### 值对象(Value Object)
+
+| 值对象 | 包含字段 | 不可变 | 说明 |
+|--------|---------|:------:|------|
+| OrderId | value: UUID | ✓ | 订单唯一标识 |
+| Money | amount, currency | ✓ | 金额(BigDecimal + Currency) |
+| OrderStatus | status: Enum | ✓ | 订单状态 |
+| Address | province, city, district, detail | ✓ | 收货地址 |
+
+### 领域事件
+
+| 事件 | 触发条件 | 包含数据 | 消费者 |
+|------|---------|---------|--------|
+| OrderCreatedEvent | 订单创建成功 | orderId, customerId, totalAmount | 库存服务(锁定库存) |
+| OrderPaidEvent | 支付成功 | orderId, amount, paidAt | 物流服务(准备发货) |
+| OrderCancelledEvent | 订单取消 | orderId, reason | 库存服务(释放库存) |
+| OrderShippedEvent | 已发货 | orderId, trackingNumber | 用户通知服务 |
+
+### 领域服务
+
+| 服务 | 职责 | 为什么不是实体方法 |
+|------|------|------------------|
+| OrderPricingService | 计算订单价格(考虑优惠券、积分、会员折扣) | 涉及多个外部策略,不是订单自身的逻辑 |
+| OrderValidationService | 验证下单(用户限购、商品限购、风控) | 跨多个聚合(User、Product)的校验 |
+
+---
+
+## 聚合:支付记录(PaymentRecord)
+
+### 概述
+支付记录聚合管理每笔支付的生命周期,包括支付、退款、对账。
+
+### 聚合根
+- **类名**: `PaymentRecord`
+- **标识**: `PaymentId`(值对象)
+- **业务标识**: `paymentNo`(支付单号)
+
+### 业务规则
+1. **支付金额一致性**: 支付金额必须等于对应订单的待支付金额
+2. **不可重复支付**: 一个订单只能有一笔成功的支付记录
+3. **退款金额上限**: 退款金额 ≤ 已支付金额
+4. **渠道幂等**: 同一个支付渠道流水号只能处理一次
+
+### 状态机
+
+```mermaid
+stateDiagram-v2
+    [*] --> PENDING : 创建支付单
+    PENDING --> SUCCESS : 支付成功回调
+    PENDING --> FAILED : 支付失败
+    SUCCESS --> REFUNDING : 申请退款
+    REFUNDING --> REFUNDED : 退款成功
+    REFUNDING --> FAILED : 退款失败
+```
+
+### 值对象
+
+| 值对象 | 说明 |
+|--------|------|
+| PaymentId | 支付唯一标识 |
+| Money | 金额(与 Order 共享) |
+| PaymentChannel | 支付渠道枚举(WeChat/AliPay/UnionPay) |
+| PaymentStatus | 支付状态枚举 |
+
+### 领域事件
+
+| 事件 | 触发条件 | 消费者 |
+|------|---------|--------|
+| PaymentSucceededEvent | 支付成功 | Order(更新订单为已支付) |
+| PaymentRefundedEvent | 退款成功 | Order(更新订单为已取消) |
+
+---
+
+## 聚合间关系
+
+```mermaid
+graph LR
+    Order -->|通过 orderId 引用| PaymentRecord
+    Order -->|通过 customerId 引用| Customer
+    Order -->|通过 productId 引用| Product
+    PaymentRecord -->|通过 orderId 关联| Order
+```
+
+**关键设计决策**:
+- 所有跨聚合引用使用 ID(值对象),不使用对象引用
+- Order 和 PaymentRecord 通过异步事件(OrderPaidEvent / PaymentSucceededEvent)协作
+- Order 不直接持有 PaymentRecord 的引用,而是通过领域事件驱动协作

+ 106 - 0
skills/ddd-skills/ddd-architecture-doc/examples/05-maintenance-guide.md

@@ -0,0 +1,106 @@
+# 架构文档维护指南示例
+
+> 本文档展示一个实际的架构文档维护计划。
+
+---
+
+## 架构文档维护计划
+
+### 基本原则
+1. **代码变更先改文档**:文档在代码仓库中与代码一起 PR
+2. **ADR 在决策时记录**:不做"后补" ADR
+3. **C4 图季度审查**:每季度检查图与实际架构的一致性
+4. **文档 Review 纳入开发流程**:PR Review 时同步 Review 文档变更
+
+### 维护节奏
+
+| 频率 | 任务 | 负责人 | 触发条件 |
+|:----:|------|--------|---------|
+| 每次提交 | ADR 更新 | 开发者 | 架构变更 |
+| 每次提交 | C4 图更新 | 开发者 | 模块/接口变更 |
+| 每周 | ADL 索引更新 | CI | 自动检测 ADR 目录变更 |
+| 每月 | 架构文档 Review | 架构师 | 月度架构会议 |
+| 每季度 | 全量架构审计 | 架构组 | 季度回顾 |
+
+---
+
+## 变更流程示例
+
+### 场景:增加 Redis 缓存层
+
+**步骤 1: 评估影响**
+- 影响 C4 L2 图(订单服务容器图增加 Redis)
+- 涉及架构决策(是否用缓存、选 Redis 的原因)
+- 需要 ADR
+
+**步骤 2: 创建 ADR**
+
+```markdown
+# ADR-006: 订单服务增加 Redis 缓存层
+
+## 状态
+已采纳 (2024-06-01)
+
+## 背景
+订单查询 QPS 从 500 增长到 3000,当前每次查询都走 DB,DB CPU 已达 70%。
+
+## 决策
+在订单服务中增加 Redis 缓存层,缓存订单读模型数据。
+
+## 备选方案
+| 方案 | 优点 | 缺点 | 决定 |
+|------|------|------|:----:|
+| Local Cache | 简单 | 多实例不一致 | ✗ |
+| Redis Cluster | 高性能、成熟 | 运维增加 | ✓ |
+
+## 影响
+- 读操作:先查 Redis → 未命中再查 DB → 回填 Redis
+- 写操作:更新 DB 后删除对应缓存
+- 缓存 TTL:订单数据 5 分钟,热数据 30 秒
+```
+
+**步骤 3: 更新 C4 L2 图**
+在订单服务容器图中增加 Redis 容器节点。
+
+**步骤 4: 提交 PR**
+- 代码变更 + 文档变更 + ADR
+- PR 描述包含架构变更声明
+
+---
+
+## 定期审查结果模板
+
+```markdown
+# 架构文档 6 月审查报告
+
+## 审查时间
+2024-06-28 | 审查人: 架构组
+
+## 审查结果
+
+| 文档 | 状态 | 问题 |
+|------|:----:|------|
+| 架构概览 | ✅ | 最新 |
+| C4 L1 图 | ✅ | 最新 |
+| C4 L2 图(订单服务) | ⚠️ | 未包含新增的 Redis |
+| C4 L2 图(支付服务) | ✅ | 最新 |
+| ADR 索引 | ✅ | 最新(含 ADR-006) |
+| 领域模型文档 | ⚠️ | Order 新增了优惠券字段 |
+
+## 行动计划
+
+| 优先级 | 任务 | 负责人 | 截止 |
+|:------:|------|--------|:----:|
+| P0 | 更新 C4 L2 订单->增加 Redis | 张三 | 2024-07-05 |
+| P1 | 更新 Order 领域模型文档 | 李四 | 2024-07-10 |
+```
+
+## 文档健康度指标
+
+| 指标 | 目标 | 当前 | 状态 |
+|------|:----:|:----:|:----:|
+| 文档与代码仓库同步 | 100% | 95% | 🟢 |
+| ADR 记录时效性 | 决策后 1 天内 | <1 天 | 🟢 |
+| C4 图季度更新 | 100% | 80% | 🟡 |
+| 团队文档阅读率 | 80% | 60% | 🟡 |
+| 新人 onboarding 时间 | <3 天 | 2.5 天 | 🟢 |

+ 0 - 0
skills/ddd-skills/ddd-architecture-doc/examples/adr-examples.md → skills/ddd-skills/ddd-architecture-doc/examples/06-adr-examples.md


+ 170 - 0
skills/ddd-skills/ddd-architecture-doc/references/01-c4-examples.md

@@ -0,0 +1,170 @@
+# C4 模型示例 — 电商平台完整四层图
+
+> 本文档提供电商平台的 C4 模型全四层 Mermaid 图例,可直接嵌入架构文档。
+
+---
+
+## L1: System Context Diagram
+
+```mermaid
+graph TB
+    Customer["👤 顾客"]
+    Admin["👤 管理员"]
+    Logistics["🚚 物流系统"]
+    PaymentGateway["💳 支付网关"]
+    SMS["📱 短信服务"]
+
+    subgraph Platform["电商平台"]
+        OrderBC["订单上下文"]
+        PaymentBC["支付上下文"]
+        ProductBC["商品上下文"]
+        InventoryBC["库存上下文"]
+    end
+
+    Customer -->|"下订单"| OrderBC
+    Customer -->|"支付"| PaymentBC
+    Admin -->|"管理商品"| ProductBC
+    OrderBC -->|"发货通知"| Logistics
+    PaymentBC -->|"调用"| PaymentGateway
+    OrderBC -->|"验证库存"| InventoryBC
+    OrderBC -->|"短信通知"| SMS
+```
+
+## L2: Container Diagram — 订单上下文
+
+```mermaid
+graph TB
+    subgraph OrderContext["订单上下文"]
+        OrderAPI["订单 API\n(Spring Boot)"]
+        OrderDB[("订单数据库\n(PostgreSQL)")]
+        OrderCache["订单缓存\n(Redis)"]
+        OrderQueue["订单事件队列\n(RabbitMQ)"]
+        Worker["订单处理 Worker\n(Spring Boot)"]
+    end
+
+    WebApp["Web App\n(React)"]
+    MobileApp["移动 App\n(React Native)"]
+
+    WebApp -->|REST API| OrderAPI
+    MobileApp -->|REST API| OrderAPI
+    OrderAPI -->|读写| OrderDB
+    OrderAPI -->|缓存查询| OrderCache
+    OrderAPI -->|发布事件| OrderQueue
+    Worker -->|消费事件| OrderQueue
+    Worker --> OrderDB
+    OrderQueue -->|同步| PaymentContext["支付上下文"]
+    OrderQueue -->|通知| Logistics
+```
+
+## L3: Component Diagram — 订单上下文的 COLA 四层
+
+```mermaid
+graph TB
+    subgraph Adapter["适配层"]
+        OrderController["OrderController"]
+        OrderDTO["OrderDTO"]
+    end
+
+    subgraph App["应用层"]
+        OrderAppService["OrderAppService"]
+        CreateOrderCmd["CreateOrderCommand"]
+        CancelOrderCmd["CancelOrderCommand"]
+        OrderQueryService["OrderQueryService"]
+    end
+
+    subgraph Domain["领域层"]
+        Order["Order (聚合根)"]
+        OrderItem["OrderItem (实体)"]
+        Money["Money (值对象)"]
+        OrderRepository["OrderRepository (接口)"]
+        OrderDomainService["OrderDomainService"]
+        OrderPaidEvent["OrderPaidEvent"]
+    end
+
+    subgraph Infra["基础设施层"]
+        JpaOrderRepo["JpaOrderRepository"]
+        EventPublisher["RabbitMqEventPublisher"]
+    end
+
+    OrderController --> OrderAppService
+    OrderController --> OrderQueryService
+    OrderAppService --> CreateOrderCmd
+    OrderAppService --> OrderRepository
+    OrderAppService --> OrderDomainService
+    Order --> OrderItem
+    Order --> Money
+    Order --> OrderPaidEvent
+    JpaOrderRepo -.->|implements| OrderRepository
+    EventPublisher --> OrderQueue
+```
+
+## L4: Code Diagram — 订单聚合内部结构
+
+```mermaid
+classDiagram
+    class Order {
+        -OrderId id
+        -OrderStatus status
+        -Money totalAmount
+        -List~OrderItem~ items
+        -CustomerId customerId
+        -Address shippingAddress
+        +pay() void
+        +cancel(String reason) void
+        +addItem(OrderItem) void
+        +removeItem(ProductId) void
+        +calculateTotal() Money
+        +canBePaid() boolean
+    }
+
+    class OrderItem {
+        -ProductId productId
+        -String productName
+        -Money unitPrice
+        -int quantity
+        +getSubtotal() Money
+        +updateQuantity(int) void
+    }
+
+    class Money {
+        -BigDecimal amount
+        -Currency currency
+        +add(Money) Money
+        +subtract(Money) Money
+        +multiply(BigDecimal) Money
+        +isGreaterThan(Money) boolean
+    }
+
+    class OrderStatus {
+        <<enumeration>>
+        PENDING_PAYMENT
+        PAID
+        SHIPPED
+        DELIVERED
+        CANCELLED
+        RETURNING
+        +canPay() boolean
+        +canCancel() boolean
+        +canShip() boolean
+    }
+
+    class OrderId {
+        -String value
+        +generate() OrderId
+        +fromString(String) OrderId
+    }
+
+    class OrderPaidEvent {
+        -OrderId orderId
+        -Money amount
+        -LocalDateTime paidAt
+        +occurredOn() LocalDateTime
+    }
+
+    Order "1" --> "*" OrderItem
+    Order --> Money
+    Order --> OrderId
+    Order --> OrderStatus
+    Order --> Address
+    Order ..> OrderPaidEvent : publishes
+```

+ 138 - 0
skills/ddd-skills/ddd-architecture-doc/references/02-adr-templates.md

@@ -0,0 +1,138 @@
+# ADR 模板合集
+
+> 提供 3 种 ADR 模板:标准版、轻量版、技术决策版。
+
+---
+
+## 模板一:标准版 ADR(推荐)
+
+适用于大多数架构决策场景。
+
+```markdown
+# ADR-{NNN}: {简短描述性标题}
+
+## 状态
+{Proposed / Accepted / Deprecated / Superseded by ADR-XXX}
+
+## 背景
+为什么需要做这个决策?当前面临什么问题或约束?
+- 业务背景:...
+- 技术背景:...
+- 约束条件:...
+
+## 决策
+我们决定做什么?
+- 具体方案:...
+- 实施范围:...
+
+## 备选方案
+| 方案 | 优点 | 缺点 | 决定 |
+|------|------|------|:----:|
+| 方案 A | ... | ... | ✗ |
+| 方案 B | ... | ... | ✗ |
+| **方案 C** | ... | ... | ✓ |
+
+## 决策理由
+为什么选择这个方案?
+1. ...
+2. ...
+
+## 影响
+- 正面影响:...
+- 负面影响:...
+- 中性影响:...
+
+## 关联 ADR
+- ADR-{NNN}: {关联决策}
+- ADR-{NNN}: {被替代的决策}
+```
+
+## 模板二:轻量版 ADR
+
+适用于小型决策或技术选型。
+
+```markdown
+# ADR-{NNN}: {标题}
+
+**状态**: {Proposed/Accepted/Deprecated}
+**日期**: {YYYY-MM-DD}
+**决策人**: {姓名}
+
+**背景**: 一句话描述为什么需要这个决策。
+
+**决策**: 我们决定采用 {方案}。
+
+**理由**: {为什么选择这个方案}
+
+**影响范围**: {哪些模块/团队受影响}
+```
+
+## 模板三:技术方案 ADR
+
+适用于详细技术方案评审。
+
+```markdown
+# ADR-{NNN}: {技术方案标题}
+
+## 状态
+{Proposed / Accepted / Deprecated}
+
+## 问题描述
+{清晰描述要解决的技术问题}
+
+## 方案对比
+
+### 方案 A: {方案名称}
+- **架构**: ...
+- **关键技术**: ...
+- **复杂度**: 高/中/低
+- **维护成本**: 高/中/低
+- **风险**: ...
+
+### 方案 B: {方案名称}
+- **架构**: ...
+- **关键技术**: ...
+- **复杂度**: 高/中/低
+- **维护成本**: 高/中/低
+- **风险**: ...
+
+### 方案 C: {方案名称}
+- **架构**: ...
+- **关键技术**: ...
+- **复杂度**: 高/中/低
+- **维护成本**: 高/中/低
+- **风险**: ...
+
+## 选择决策
+**选定方案**: {方案名称}
+**评分对比**:
+
+| 维度 | 方案 A | 方案 B | 方案 C |
+|------|:------:|:------:|:------:|
+| 业务匹配度 | 7/10 | 9/10 | 6/10 |
+| 技术可行性 | 8/10 | 8/10 | 9/10 |
+| 团队适配度 | 6/10 | 9/10 | 5/10 |
+| 迁移成本 | 5/10 | 7/10 | 8/10 |
+
+**理由**: ...
+
+## 实施计划
+1. {步骤 1}: {时间}
+2. {步骤 2}: {时间}
+3. {步骤 3}: {时间}
+
+## 回退方案
+{如果决策失败,如何回退}
+
+## 关联
+- ADR-{NNN}: {关联决策}
+```
+
+## 选择指南
+
+| 场景 | 推荐模板 |
+|------|---------|
+| 重大架构决策(选架构、换 DB) | 标准版 |
+| 日常技术选型(框架选择、库选择) | 轻量版 |
+| 需跨团队评审的技术方案 | 技术方案版 |
+| 快速记录(一人决策) | 轻量版 |

+ 170 - 0
skills/ddd-skills/ddd-architecture-doc/references/03-doc-templates.md

@@ -0,0 +1,170 @@
+# 架构文档模板合集
+
+> 提供 3 种不同用途的架构文档模板:完整版、轻量版、快速入门版。
+
+---
+
+## 模板一:完整架构文档(推荐)
+
+适用于中大型项目,团队文档标准化。
+
+```markdown
+# {项目名称} 架构文档
+
+> 版本: v{版本号} | 最后更新: {YYYY-MM-DD} | 负责人: {姓名}
+
+---
+
+## 1. 架构概览
+
+### 1.1 架构模式
+- **架构**: {Layered / Onion / Hexagonal / Clean / COLA}
+- **CQRS 级别**: {None / L1 / L2 / L3}
+- **微服务拆分**: {单体 / 微服务}
+
+### 1.2 架构图
+> 嵌入 C4 L1(System Context)图
+
+### 1.3 核心约束
+- 领域层零框架依赖
+- 依赖方向始终指向内层
+- 聚合之间通过 ID 引用
+- 跨聚合操作使用领域事件
+
+## 2. 限界上下文
+
+| 上下文 | 类型 | 职责 | 部署方式 |
+|--------|------|------|:--------:|
+| Order | 核心域 | 订单全生命周期管理 | 独立服务 |
+| Payment | 核心域 | 支付处理与退款 | 独立服务 |
+| Product | 支撑域 | 商品信息管理 | 独立服务 |
+| Auth | 通用域 | 用户认证授权 | 共享库 |
+
+### 上下文映射
+
+> 嵌入 Context Map 图(Mermaid)
+
+## 3. 分层规范
+
+### 3.1 依赖方向
+详见 `{项目名}/layer-dependencies.md`
+
+### 3.2 层职责
+| 层 | 允许 | 禁止 |
+|---|------|------|
+| Interface | 协议转换、参数校验 | 业务判断 |
+| Application | 编排、事务、权限 | 业务 if/else |
+| Domain | 业务规则、领域建模 | 框架依赖 |
+| Infrastructure | 技术实现 | 业务逻辑 |
+
+## 4. 技术栈
+
+| 组件 | 技术 | 版本 | 用途 |
+|------|------|:----:|------|
+| 框架 | Spring Boot | 3.4.x | Web 服务 |
+| ORM | MyBatis Plus | 3.5.x | 数据访问 |
+| 数据库 | PostgreSQL | 16 | 持久化 |
+| 缓存 | Redis | 7.x | 会话/缓存 |
+| 消息队列 | RabbitMQ | 3.13 | 事件驱动 |
+| 搜索引擎 | Elasticsearch | 8.x | 全文搜索 |
+
+## 5. 部署架构
+
+> 嵌入部署图(K8s / Docker Compose)
+
+## 6. 架构决策记录(ADRs)
+
+### ADR 索引
+
+| ADR# | 标题 | 状态 | 日期 |
+|------|------|:----:|:----:|
+| 001 | 选择 COLA v5 架构 | 已采纳 | 2024-03-15 |
+| 002 | CQRS L1 策略 | 已采纳 | 2024-03-20 |
+| 003 | 事件中间件选型 | 已采纳 | 2024-03-25 |
+
+### 完整 ADR
+> 链接到 `adrs/ADR-{NNN}-{title}.md`
+
+## 7. 安全架构
+- 认证方式:JWT + OAuth2
+- 授权模型:RBAC(按限界上下文分权)
+- 数据加密:传输 TLS 1.3 / 存储 AES-256
+- 审计日志:所有写操作记录
+
+## 8. 运维手册
+- 监控:Prometheus + Grafana
+- 日志:ELK Stack
+- 告警:PagerDuty
+- 灾备:跨 AZ 部署 + 数据库主从
+
+## 9. 架构评审 Checklist
+
+- [ ] 依赖方向正确
+- [ ] Domain 层零框架依赖
+- [ ] 无循环依赖
+- [ ] 聚合间 ID 引用
+- [ ] 关键操作有领域事件
+- [ ] ADR 记录完整
+- [ ] 架构图与代码一致
+```
+
+## 模板二:轻量架构文档
+
+适用于小团队或快速迭代项目。
+
+```markdown
+# {项目名称} 轻量架构文档
+
+## 架构快照
+- **模式**: ...
+- **CQRS**: ...
+- **关键技术**: ...
+
+## 模块结构
+> 项目目录树(核心模块)
+
+## 技术栈清单
+> 技术选型表
+
+## 关键 ADR
+- ADR-001: ...
+- ADR-002: ...
+
+## 架构图
+> 嵌入 C4 L1 图
+```
+
+## 模板三:新成员快速入门文档
+
+适用于团队新人 onboarding。
+
+```markdown
+# {项目名称} 架构快速入门
+
+## 五分钟理解架构
+- 我们用了什么架构模式?
+- 代码模块怎么组织的?
+- 核心业务链路是什么?
+
+## 开发环境搭建
+1. clone 仓库
+2. 配置本地环境
+3. 启动项目
+
+## 提交代码流程
+- 分支策略
+- 提交流程
+- Code Review 要点
+
+## 常用文档链接
+- 架构文档
+- API 文档
+- ADR 记录
+- 数据库设计
+
+## 找谁帮忙
+| 领域 | 负责人 |
+|------|--------|
+| 订单 | @张三 |
+| 支付 | @李四 |
+```

+ 117 - 0
skills/ddd-skills/ddd-architecture-doc/references/04-toolchain.md

@@ -0,0 +1,117 @@
+# 架构文档工具链
+
+> 推荐的工具和最佳实践,帮助团队高效维护架构文档。
+
+---
+
+## 1. 图表工具
+
+### Structurizr(推荐)
+- **类型**: C4 模型专用工具
+- **特点**: 代码定义架构图、版本控制友好、支持多视图
+- **适用**: 中大型项目,需要 C4 模型全量维护
+- **地址**: [structurizr.com](https://structurizr.com)
+
+```java
+// Structurizr DSL 示例
+workspace {
+    model {
+        user = person "顾客" "系统用户"
+        softwareSystem = softwareSystem "电商平台" "在线购物系统"
+        user -> softwareSystem "下订单"
+    }
+    views {
+        systemContext softwareSystem {
+            include *
+        }
+    }
+}
+```
+
+### Mermaid(轻量)
+- **类型**: Markdown 内嵌图表
+- **特点**: 无额外工具、直接写在 Markdown 中
+- **适用**: 小型项目,文档与代码同仓库
+- **支持**: GitHub / GitLab / 多数 Markdown 编辑器
+
+### PlantUML(开发者友好)
+- **类型**: 代码驱动图表
+- **特点**: 丰富的图类型(时序、活动、组件、类图)
+- **适用**: 需要多种 UML 图型的项目
+- **集成**: VS Code 插件、CI/CD 自动渲染
+
+### draw.io / diagrams.net
+- **类型**: 可视化拖拽工具
+- **特点**: 操作直观、开源、可嵌入 Confluence
+- **适用**: 快速原型、非技术团队合作
+
+## 2. ADR 管理工具
+
+### ADR Tools(CLI)
+- **特点**: 命令行创建和管理 ADR
+- **安装**: `npm install -g adr-tools`
+- **用法**:
+  ```bash
+  adr new "选择 COLA 架构"
+  adr list
+  adr supersede 4 6  # ADR-4 被 ADR-6 替代
+  ```
+
+### Log4brains
+- **特点**: ADR Web 界面 + 自动索引
+- **安装**: `npm init log4brains`
+- **适用**: 团队需要可视化的 ADR 浏览
+
+## 3. 文档平台
+
+| 平台 | 适用场景 | 优势 |
+|------|---------|------|
+| GitHub Wiki | 开发者团队 | 代码同仓库,PR 驱动文档变更 |
+| Confluence | 大型团队 | 富文本编辑,跨团队可见 |
+| Notion | 中等团队 | 灵活排版,数据库视图 |
+| 语雀 | 国内团队 | 中文友好,知识库管理 |
+| MkDocs | 技术团队 | Markdown 驱动,自动部署 |
+
+## 4. 自动化检查
+
+### ArchUnit
+- **用途**: Java 层依赖方向自动检查
+- **集成**: JUnit 测试 + CI/CD
+
+```java
+@Test
+void testLayerDependencies() {
+    layeredArchitecture()
+        .layer("Adapter").definedBy("..adapter..")
+        .layer("App").definedBy("..app..")
+        .layer("Domain").definedBy("..domain..")
+        .layer("Infrastructure").definedBy("..infrastructure..")
+        .whereLayer("Adapter").mayOnlyBeAccessedByLayers("App")
+        .whereLayer("App").mayOnlyBeAccessedByLayers("Adapter")
+        .whereLayer("Domain").mayOnlyBeAccessedByLayers("App", "Infrastructure")
+        .check(importedClasses);
+}
+```
+
+### ADR 合规检查
+- ADR 必须与代码一致
+- 定期 CI 检查 ADR 索引 vs 实际代码实现
+- 架构变更必须有对应的 ADR 更新
+
+## 5. 推荐工作流
+
+```
+代码变更 → 影响架构?→ 是 → 更新 ADR / 更新 C4 图 / 更新架构文档
+                                  ↓
+                               PR 评审包含文档变更
+                                  ↓
+                              合并后自动部署文档站
+```
+
+### 文档与代码同步策略
+
+| 策略 | 适用 | 执行方式 |
+|------|------|---------|
+| PR 强制关联 | 严格团队 | PR 模板含文档更新确认框 |
+| 文档 AI 检测 | 自动化 | CI 检测代码架构变更 → 自动提示更新文档 |
+| 定期人工审查 | 宽松团队 | 每 sprint 审查一次架构文档 |

+ 110 - 0
skills/ddd-skills/ddd-architecture-doc/references/05-team-templates.md

@@ -0,0 +1,110 @@
+# 团队沟通模板
+
+> 架构文档不仅仅是技术文档,还包括团队之间的沟通模板。
+
+---
+
+## 1. 架构评审请求模板
+
+用于发起架构评审。
+
+```markdown
+# 架构评审请求
+
+## 基本信息
+- **发起人**: {姓名}
+- **日期**: {YYYY-MM-DD}
+- **评审范围**: {模块/服务名称}
+
+## 变更内容
+{简要描述要评审的架构变更}
+
+## 前置材料
+- [ ] 架构变更说明(本请求)
+- [ ] ADR 草案(链接)
+- [ ] C4 图(L1/L2 变更部分)
+- [ ] 受影响模块清单
+
+## 评审要点
+1. {要点 1}
+2. {要点 2}
+
+## 期望评审人
+- @{架构师}
+- @{相关模块负责人}
+```
+
+## 2. 架构变更通知模板
+
+架构变更通过后通知团队。
+
+```markdown
+## 🔔 架构变更通知
+
+**变更**: {简洁描述}
+**ADR**: ADR-{NNN}
+**生效日期**: {YYYY-MM-DD}
+**影响范围**: {清单}
+
+### 变更内容
+{详细描述}
+
+### 开发者需要做什么
+- {行动项 1}
+- {行动项 2}
+
+### 回退方案
+{如果出问题怎么办}
+
+### 问题反馈
+请回复此帖子或联系 @{负责人}
+```
+
+## 3. 架构文档 Review 模板
+
+定期审查架构文档的更新情况。
+
+```markdown
+# 架构文档 Review - {月份}
+
+## 文档完整性
+
+| 文档 | 最新版本 | 最后更新 | 状态 |
+|------|---------|:--------:|:----:|
+| 架构概览 | v2.3 | 2024-03-15 | ✅ 最新 |
+| ADR 索引 | v1.8 | 2024-02-28 | ⚠️ 需更新 |
+| C4 图 | v2.1 | 2024-01-20 | ❌ 过期 |
+
+## 过期项详情
+1. ADR 索引缺少 ADR-005、ADR-006
+2. C4 L2 图与实际部署不一致(新增了 Redis 集群)
+
+## 行动计划
+| 任务 | 负责人 | 截止日期 |
+|------|--------|:--------:|
+| 补充 ADR-005/006 | @张三 | 2024-04-01 |
+| 更新 C4 L2 图 | @李四 | 2024-04-05 |
+```
+
+## 4. Onboarding 文档清单
+
+新成员需要阅读的架构文档。
+
+```markdown
+## 新成员架构文档阅读清单
+
+### 第一天
+1. [ ] 架构概览文档(30 分钟)
+2. [ ] C4 L1 系统上下文图(15 分钟)
+3. [ ] 核心业务流文档(30 分钟)
+
+### 第一周
+4. [ ] 当前服务 C4 L2/L3 图(1 小时)
+5. [ ] 关键 ADR(3-5 个主要决策)
+6. [ ] 开发环境搭建文档
+
+### 第一个月
+7. [ ] 全部 ADR 索引 + 重要 ADR 详情
+8. [ ] C4 L4 代码级理解
+9. [ ] 参与一次架构评审
+```

+ 102 - 0
skills/ddd-skills/ddd-architecture-doc/references/06-arch-decision-log.md

@@ -0,0 +1,102 @@
+# 架构决策日志(ADL)格式
+
+> 架构决策日志(Architecture Decision Log, ADL)是 ADR 的索引和管理系统。
+> 本文档提供 ADL 的创建、维护和自动化方案。
+
+---
+
+## 1. ADL 索引表
+
+```markdown
+# 架构决策日志(ADL)
+
+> 最后更新: {YYYY-MM-DD} | 总 ADR 数: {N}
+
+## 活跃决策
+
+| ADR# | 标题 | 状态 | 采纳日期 | 负责人 | 标签 |
+|------|------|:----:|:--------:|:------:|:----:|
+| 001 | 选择 COLA v5 架构 | ✅ 已采纳 | 2024-03-15 | @张三 | 架构选型 |
+| 002 | CQRS L1 策略 | ✅ 已采纳 | 2024-03-20 | @李四 | CQRS |
+| 003 | 事件中间件选型 | ✅ 已采纳 | 2024-03-25 | @王五 | 技术选型 |
+| 004 | MySQL 选择 | ❌ 已废弃 | 2024-02-01 | @张三 | DB选型 |
+| 005 | 单体 vs 微服务 | ✅ 已采纳 | 2024-04-01 | @赵六 | 架构 |
+
+## 已废弃/已替代
+
+| ADR# | 标题 | 被替代 | 替代者为 |
+|------|------|:------:|:--------:|
+| 004 | MySQL 选择 | ADR-006 | PostgreSQL 选型 |
+```
+
+## 2. ADR 目录结构
+
+```
+docs/
+└── adrs/
+    ├── README.md                 # ADL 索引(自动生成)
+    ├── ADR-001-choose-cola.md
+    ├── ADR-002-cqrs-l1-strategy.md
+    ├── ADR-003-event-middleware.md
+    ├── ADR-004-deprecated-mysql.md
+    └── ADR-005-monolith-vs-microservices.md
+```
+
+### 文件命名规范
+- 格式: `ADR-{NNN}-{kebab-case-title}.md`
+- NNN: 从 001 开始的三位编号
+- 标题: 英文 kebab-case,简短描述
+
+## 3. ADL 自动化维护
+
+### GitHub Actions 示例
+
+```yaml
+name: Update ADL Index
+on:
+  push:
+    paths:
+      - 'docs/adrs/**'
+
+jobs:
+  update-adl:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v3
+      - name: Generate ADL Index
+        run: |
+          echo "# 架构决策日志" > docs/adrs/README.md
+          echo "" >> docs/adrs/README.md
+          echo "| ADR# | 标题 | 状态 | 日期 |" >> docs/adrs/README.md
+          echo "|------|------|:----:|:----:|" >> docs/adrs/README.md
+          for f in docs/adrs/ADR-*.md; do
+            title=$(head -1 "$f" | sed 's/# ADR-...: //')
+            status=$(grep -A1 "^## 状态" "$f" | tail -1)
+            num=$(echo "$f" | grep -oP 'ADR-\K\d+')
+            echo "| $num | $title | $status | - |" >> docs/adrs/README.md
+          done
+          mv docs/adrs/README.md docs/adrs/README.md
+      - name: Commit changes
+        uses: stefanzweifel/git-auto-commit-action@v4
+```
+
+## 4. ADL 最佳实践
+
+| 实践 | 说明 |
+|------|------|
+| **编号唯一** | ADR 编号全局唯一,废弃后不重用 |
+| **索引自动化** | CI/CD 自动生成 ADL 索引 |
+| **标签分类** | 为 ADR 打标签(架构选型/DB选型/安全决策) |
+| **定期审查** | 每季度审查 ADL,标记过时的决策 |
+| **PR 关联** | 代码 PR 关联相关 ADR |
+
+## 5. ADL 状态机
+
+```
+                → Accepted(已采纳)
+Proposed ──────┤                    Deprecated(已废弃)
+    ↓          → Rejected(已拒绝)       ↓
+修改后重新提交                              Superseded(已替代)
+                                            ↓
+                                       保留引用
+```

+ 100 - 0
skills/ddd-skills/ddd-architecture-doc/references/07-domain-model-doc.md

@@ -0,0 +1,100 @@
+# 领域模型文档化模式
+
+> 本文档提供领域模型文档化的最佳实践和模板。
+
+---
+
+## 1. 聚合文档模板
+
+```markdown
+## 聚合:{聚合名称}
+
+### 概述
+{一句话描述这个聚合负责什么业务}
+
+### 聚合根
+- **类名**: {ClassName}
+- **标识**: {IdType}
+- **业务标识**: {业务主键,如订单号}
+
+### 实体
+| 实体 | 父聚合根 | 生命周期 |
+|------|---------|---------|
+| {Entity1} | {AggregateRoot} | 随聚合根 |
+
+### 值对象
+| 值对象 | 包含字段 | 不可变 |
+|--------|---------|:------:|
+| {ValueObject1} | {field1}, {field2} | ✅ |
+
+### 领域事件
+| 事件 | 触发条件 | 消费者 |
+|------|---------|--------|
+| {Event1} | {条件} | {谁处理} |
+
+### 业务不变式(Invariants)
+1. {不变式 1}
+2. {不变式 2}
+```
+
+## 2. 限界上下文文档模板
+
+```markdown
+## 限界上下文:{上下文名称}
+
+### 基本信息
+- **类型**: {核心域 / 支撑域 / 通用域}
+- **负责人**: {团队名称}
+- **代码仓库**: {repository URL}
+
+### 领域模型概览
+> 嵌入聚合关系图(Mermaid)
+
+```mermaid
+graph LR
+    Aggregate1["聚合1\n(聚合根)"]
+    Aggregate2["聚合2\n(聚合根)"]
+    Aggregate1 -->|"ID 引用"| Aggregate2
+```
+
+### 聚合清单
+| 聚合 | 聚合根 | 说明 |
+|------|--------|------|
+| {Aggregate1} | {Class1} | {说明} |
+
+### 上下文映射
+| 上游上下文 | 下游 | 关系类型 |
+|-----------|------|---------|
+| {上游BC} | {下游BC} | ACL/OHS/Partnership |
+
+### 领域服务
+| 服务名 | 职责 | 位置 |
+|--------|------|:----:|
+| {Service1} | {职责} | Domain 层 |
+
+### 仓储接口
+| 仓库 | 对应聚合 | 主要查询 |
+|------|---------|---------|
+| {Repository1} | {Aggregate1} | findByXXX, save |
+```
+
+## 3. 文档化最佳实践
+
+| 实践 | 反例 | 正例 |
+|------|------|------|
+| 用业务语言 | "Order 有 status 字段" | "订单状态决定了用户可以执行的操作" |
+| 说明业务规则 | "pay() 方法更新状态" | "只有 DRAFT 状态的订单才能支付,支付后状态变为 PAID" |
+| 明确聚合边界 | "Order 引用 Customer 对象" | "Order 通过 customerId 引用 Customer 聚合" |
+| 记录领域事件 | 不写事件触发条件 | "当订单支付成功时发布 OrderPaidEvent" |
+| 解释值对象 | "Money 是 BigDecimal" | "Money 封装金额计算(加、减、乘、比较),保证金额精确计算" |
+
+## 4. 领域模型变更记录
+
+```markdown
+# {聚合名称} 领域模型变更日志
+
+| 日期 | 版本 | 变更内容 | 原因 | ADR |
+|:----:|:----:|---------|------|:---:|
+| 2024-03-15 | v2.0 | Order 增加 shippingAddress 字段 | 支持多地址发货 | ADR-012 |
+| 2024-02-01 | v1.5 | OrderItem 从实体改为值对象 | 订单项不可修改 | ADR-008 |
+```

+ 162 - 0
skills/ddd-skills/ddd-architecture-doc/references/08-api-doc-patterns.md

@@ -0,0 +1,162 @@
+# API 文档化模式
+
+> DDD 架构下的 API 文档规范,面向 CQRS 模式的命令/查询分离。
+
+---
+
+## 1. 命令 API 文档模板
+
+```markdown
+## POST /api/v1/{resource}/{action}
+
+**命令**: {CommandName}
+**ID 支持**: {幂等键}
+
+### 请求体
+```json
+{
+    "idempotentKey": "{唯一请求 ID}",
+    "data": { ... }
+}
+```
+
+### 响应
+```json
+{
+    "code": 0,
+    "message": "success",
+    "data": {
+        "id": "{资源 ID}",
+        "status": "{结果状态}"
+    }
+}
+```
+
+### 业务规则
+1. {规则 1}
+2. {规则 2}
+
+### 领域事件
+- 成功触发:{EventName}
+```
+
+## 2. 查询 API 文档模板
+
+```markdown
+## GET /api/v1/{resource}s
+
+**查询**: {QueryName}
+**CQRS 模型**: {QueryModel}
+
+### 参数
+| 参数 | 类型 | 必填 | 说明 |
+|------|:----:|:----:|------|
+| {param1} | {type} | 是 | {说明} |
+
+### 响应
+```json
+{
+    "code": 0,
+    "data": {
+        "records": [],
+        "total": 100,
+        "page": 1,
+        "pageSize": 20
+    }
+}
+```
+
+### 说明
+- 查询不走领域模型,直接从读模型返回
+- 不触发领域事件
+- 不改变系统状态
+```
+
+## 3. OpenAPI 规范参考
+
+```yaml
+openapi: 3.0.3
+info:
+  title: 电商平台 API
+  version: 1.0.0
+paths:
+  /api/v1/orders:
+    post:
+      summary: 创建订单(命令)
+      operationId: createOrder
+      x-cqrs-type: command
+      requestBody:
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/CreateOrderRequest'
+      responses:
+        '200':
+          description: 订单创建成功
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/OrderCreatedResponse'
+
+components:
+  schemas:
+    CreateOrderRequest:
+      type: object
+      required:
+        - customerId
+        - items
+      properties:
+        customerId:
+          type: string
+          description: 客户 ID
+        items:
+          type: array
+          items:
+            $ref: '#/components/schemas/OrderItem'
+    OrderCreatedResponse:
+      type: object
+      properties:
+        orderId:
+          type: string
+        status:
+          type: string
+```
+
+## 4. API 文档章节结构
+
+```
+API 文档标准章节:
+
+1. {资源} Overview
+   - 所属限界上下文
+   - CQRS 类型(命令/查询)
+   
+2. Endpoints
+   - 命令类(POST/PUT/DELETE)
+   - 查询类(GET)
+   
+3. 请求/响应格式
+   - 统一响应格式
+   - 错误码说明
+   
+4. 业务规则
+   - 命令的业务规则(哪些状态可操作)
+   - 查询的过滤/排序/分页规则
+   
+5. 限流策略
+   - 命令 API:较低 QPS
+   - 查询 API:较高 QPS
+   
+6. 安全要求
+   - 认证方式
+   - 权限要求
+```
+
+## 5. DDD 与非 DDD API 文档差异
+
+| 维度 | 传统 API 文档 | DDD API 文档 |
+|------|-------------|-------------|
+| 关注点 | HTTP 端点 + 参数 | 业务能力 + 领域语义 |
+| 命令描述 | "POST /orders 创建订单" | "下单命令:创建新订单,触发订单已创建事件" |
+| 参数说明 | "status: 订单状态" | "订单状态:业务状态机,包含 DRAFT→PAID→SHIPPED 等" |
+| 事件关联 | 无 | "成功触发 OrderCreatedEvent,由库存消费" |

+ 100 - 0
skills/ddd-skills/ddd-architecture-doc/references/09-trace-anti-patterns.md

@@ -0,0 +1,100 @@
+# 架构文档反模式
+
+> 本文档列出 DDD 架构文档中的常见反模式、改进对比和禁忌清单。
+
+---
+
+## 反模式一:死文档(写一次就过期)
+
+### 症状
+- 文档创建后从未更新
+- 代码已经重构多次,文档还是最初版本
+- 新成员只能看代码,不能信文档
+
+### 改进对比
+| 维度 | 反模式 | 推荐做法 |
+|------|--------|---------|
+| 更新频率 | 写一次,永不更新 | PR 时必须同步更新文档 |
+| 关联方式 | 文档和代码独立 | 文档在代码仓库中,变更时一起 PR |
+| 验证方式 | 无 | CI 检查 ADR 与代码的一致性 |
+
+### 禁忌清单
+- ❌ 把文档放在和代码无关的独立 Wiki 中(容易忘记更新)
+- ❌ 文档只有 PDF 版本(无法版本控制和 diff)
+- ❌ 文档没有版本号或最后更新时间
+
+## 反模式二:假图(图不反映真实架构)
+
+### 症状
+- C4 图里的容器数和实际部署不一致
+- 图看起来很美,但跟代码结构对不上
+- 图是用 Visio 手动画的,没法自动验证
+
+### 改进对比
+| 维度 | 反模式 | 推荐做法 |
+|------|--------|---------|
+| 图表工具 | Visio/Keynote 手绘 | Mermaid/Structurizr 代码驱动 |
+| 更新方式 | 每次手动拖拽 | 改了代码就是改了图 |
+| 验证方式 | 人工核对 | ArchUnit + CI 验证 |
+
+### 禁忌清单
+- ❌ 使用不可版本控制的二进制图文件(.vsdx/.drawio 不 diff)
+- ❌ 一张图包含所有细节(超过 7 个节点)
+- ❌ 图的颜色/样式没有统一的规范
+
+## 反模式三:ADR 不写理由
+
+### 症状
+- ADR 只写了"选了什么",没写"为什么"
+- 几个月后回看 ADR,完全记不得当时的考虑
+- 新人问"为什么这里用 RabbitMQ 而不是 Kafka",没人能答
+
+### 改进对比
+| 维度 | 反模式 | 推荐做法 |
+|------|--------|---------|
+| 内容 | "选了 RabbitMQ" | "选了 RabbitMQ:因为团队已经部署、运维熟悉、QPS < 5000 足够" |
+| 备选方案 | 无 | 至少列出 2-3 个备选 + 优缺点 |
+| 决策背景 | 无 | 写明当时的业务场景和约束 |
+
+### 禁忌清单
+- ❌ ADR 不写备选方案
+- ❌ ADR 只有标题,没有背景和影响分析
+- ❌ 决策理由用"大家都觉得"、"业界主流"等空话
+
+## 反模式四:过度文档(写太多没人读)
+
+### 症状
+- 架构文档 100 页以上,没人完整读过
+- 文档包含太多实现细节(每个方法的参数说明)
+- 新成员 onboarding 时被告知"看看文档",但看了也没用
+
+### 改进对比
+| 维度 | 反模式 | 推荐做法 |
+|------|--------|---------|
+| 粒度 | 每个方法的参数都写 | 写聚合边界、关键业务规则、架构决策 |
+| 长度 | > 50 页 | 核心文档 < 10 页,详细信息分到子文档 |
+| 用途 | 力图覆盖一切 | 聚焦"别人需要知道什么才能开发" |
+
+### 禁忌清单
+- ❌ 把代码注释复制到文档中
+- ❌ 文档包含敏感的凭证、IP、配置
+- ❌ 文档沦为"为了有文档而写文档"
+
+## 反模式五:无图(只有文字描述)
+
+### 症状
+- 架构文档纯文字,没有一张图
+- "订单模块调用支付模块"这种关系全靠文字描述
+- 新人看完文档还得自己画图才能理解
+
+### 改进对比
+| 维度 | 反模式 | 推荐做法 |
+|------|--------|---------|
+| 顶层架构 | 文字描述 | C4 L1 System Context 图 |
+| 服务关系 | "A 服务通过 RPC 调用 B 服务" | C4 L2 Container 图 |
+| 模块结构 | 目录列表 | C4 L3 Component 图 |
+
+### 禁忌清单
+- ❌ 只有文字没有图的架构文档
+- ❌ 图不在文档中,而是"麻烦你去看 X 文档里的图"
+- ❌ 图太大/太小,导致无法阅读

+ 73 - 0
skills/ddd-skills/ddd-architecture-doc/references/10-faq-deep.md

@@ -0,0 +1,73 @@
+# 架构文档 FAQ(深入篇)
+
+> 边缘场景、工具兼容、安全合规相关的深度问题。
+
+---
+
+## Q1: 微服务架构下 ADR 归哪个团队维护?
+
+**每个微服务独立维护自己的 ADR**,同时在架构文档中维护一个全局 ADR 索引。
+
+- 各服务 ADR:在各自代码仓库的 `docs/adrs/` 下
+- 全局 ADL:在架构文档中引用各服务的 ADR 链接
+- 跨服务决策(如服务间协议、消息格式)放在 Team-level 的 ADR
+
+## Q2: C4 图需要覆盖所有限界上下文吗?
+
+**不需要**。C4 图的推荐粒度:
+- L1:覆盖全系统(所有限界上下文)
+- L2-L4:按限界上下文或微服务独立维护
+- 每个图控制在 5-7 个节点内,复杂系统应该分层展开
+
+## Q3: 遗留系统没有架构文档,从哪里开始?
+
+渐进式文档化策略:
+1. 先画当前实际部署的 C4 L1 图("AS-IS")
+2. 识别关键 ADR(最大的 3-5 个历史决策)
+3. 只为核心限界上下文写 L2/L3 图
+4. 每 sprint 完善一部分
+5. 目标:从 AS-IS 到 TO-BE 的演进路线图
+
+## Q4: 架构文档放在哪里最合适?
+
+| 存储方式 | 适用 | 不适用 |
+|---------|------|--------|
+| 代码仓库 `docs/` | 开发团队维护 | 产品/业务需要访问 |
+| Wiki(Confluence/语雀) | 跨团队可见 | 文档与代码脱节 |
+| 文档站(MkDocs/GitBook) | 公开文档 | 非技术团队编辑 |
+| **推荐:代码仓库 + Wiki 双同步** | 开发者 PR 维护,定期同步到 Wiki | 需要额外 CI 步骤 |
+
+## Q5: 如何处理被废弃的 ADR?
+
+**保留但标记**。废弃的 ADR 不应删除:
+- 状态标记为 `Deprecated` 或 `Superseded by ADR-XXX`
+- ADL 索引中保留,但"活跃决策"表中不显示
+- 已废弃的 ADR 从 ADR 编号序列中跳过(不重用编号)
+- 通过 ADL 索引可以追溯"为什么这个决策不再有效"
+
+## Q6: C4 和 UML 的关系是什么?
+
+| 维度 | C4 模型 | UML |
+|------|---------|-----|
+| 定位 | 架构级沟通 | 设计级细节 |
+| 受众 | 全团队(含非技术) | 开发者 |
+| 粒度 | 粗到细 4 层 | 细粒度 |
+| 自动检查 | 困难 | ArchUnit 支持 |
+| **推荐做法** | C4 用于架构文档 | UML 用于设计文档 |
+
+## Q7: 架构文档需要包含性能指标吗?
+
+**需要,但作为参考而非承诺**。推荐包含:
+- 当前性能基线(P99 延迟、QPS)
+- 架构决策对性能的影响(如 CQRS L2 的同步延迟)
+- 容量规划信息(预估增长、扩展策略)
+- 不建议包含:精确的 SLO(应放在运维监控文档)
+
+## Q8: 架构文档如何保护敏感信息?
+
+| 信息类型 | 保护方式 |
+|---------|---------|
+| 内网 IP/域名 | 使用占位符(如 `{service-name}:{port}`) |
+| 数据库密码/凭证 | 绝不写入文档 |
+| 安全组规则 | 使用 "基于角色的访问控制" 描述替代具体规则 |
+| 部署拓扑 | 敏感拓扑不使用公开文档 |

Some files were not shown because too many files changed in this diff