# Defining Schemas

> Use when Phase 4 technical solution is approved and concrete schema files need to be generated before behavior contracts (SDD) and coding. Use when tempted to write code without formal interface definitions, database schemas, or error catalogs. Schema定义, proto生成, DDL, 错误码, openapi, asyncapi, event schema.

- **Type:** Skill
- **Install:** `agentstack add skill-lockp111-agent-ddd-engineering-defining-schemas`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [lockp111](https://agentstack.voostack.com/s/lockp111)
- **Installs:** 0
- **Category:** [Databases](https://agentstack.voostack.com/c/databases)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [lockp111](https://github.com/lockp111)
- **Source:** https://github.com/lockp111/agent-ddd-engineering/tree/main/skills/defining-schemas

## Install

```sh
agentstack add skill-lockp111-agent-ddd-engineering-defining-schemas
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Defining Schemas

## Overview
This skill generates concrete, toolchain-consumable schema files from Phase 3 logical contracts and Phase 4 technical decisions. The output — proto files, OpenAPI specs, DDL, event schemas, and error code catalogs — are **permanent project infrastructure**, not DDD process documents. They live in project-natural directories (e.g., `proto/`, `api/`, `docs/migrations/`), not in `docs/ddd/`.

**Foundational Principle:** All rules in this skill are mandatory constraints. Schema files must exist before any domain code is written. Code conforms to schemas, not the other way around. Generating schemas during coding creates implementation-first coupling that undermines the entire DDD pipeline.

**Schema Format References:** When generating specific schema formats, load the corresponding reference for detailed conventions and patterns:
- [proto-reference.md](proto-reference.md) — Proto3 conventions: service/message/enum naming, field numbering, import structure
- [openapi-reference.md](openapi-reference.md) — OpenAPI 3.x conventions: path structure, schema components, error responses
- [asyncapi-reference.md](asyncapi-reference.md) — AsyncAPI conventions: channel naming, message payload, binding patterns

**Relationship to SDD (Phase 6):** This skill produces **structural definitions** — the shape of interfaces, data, events, and errors. SDD produces **behavioral specifications** — what the system must do, invariants, state machines, and coding conventions. Schema files define *what things look like*; behavior contracts define *how things must behave*. Phase 6 references Phase 5 schemas as anchors (e.g., "The `CreateOrder` RPC in `ordering_service.proto:L12` MUST validate items non-empty").

## When to Use
- After Phase 4 technical solution is approved; before SDD (Phase 6) behavior contracts.
- When Phase 3 contracts exist as logical interfaces but no concrete schema files (proto, openapi, DDL) have been generated.
- When iterating: Phase 3 or Phase 4 decisions changed and existing schemas need updating (Merge mode).

**Do NOT use when:** Phase 3 contracts do not exist (**REQUIRED PREREQUISITE:** [designing-contracts-first](../designing-contracts-first/SKILL.md)), Phase 4 technical solution is not yet complete (**REQUIRED PREREQUISITE:** [architecting-technical-solution](../architecting-technical-solution/SKILL.md)), or schema files already exist and were NOT generated by this skill (use Mode Detection's "Generate with warning" path instead of overwriting).

**Additional input:** `docs/ddd/phase-1-domain-events.md` is read in Step 1 for event schema generation. Phase 1 is not a blocking prerequisite (Phase 3 already depends on it), but it must exist when this skill runs.

## Quick Reference

| Step | Action | Output |
|:---|:---|:---|
| 1 | INVENTORY — scan Phase 3 + Phase 4 | Schema inventory (context × type × format × path) |
| 2 | PLAN — determine directory structure | Directory plan table |
| 3 | GENERATE / MERGE — produce schema files | Schema files in project directories |
| 4 | VALIDATE — cross-check completeness | Completeness report |
| 5 | Persist Manifest | `docs/ddd/schema-manifest.md` |

## Ambiguity Handling

Follow the [Ambiguity Handling Protocol](../ddd-protocol/ambiguity-handling-reference.md) throughout this phase.

**Phase 5 STOP triggers — confirm immediately:**

| Ambiguity | Why STOP |
|:----------|:---------|
| Schema format unclear (Phase 4 did not specify gRPC vs REST for a context) | Wrong format → all schema files for that context must be redone |
| Entity relationship design (1:N vs N:N, embedding vs referencing) | DDL structure cascades to all downstream phases |
| Event ownership ambiguity (which context publishes which event) | Event schema in wrong directory → cross-context coupling |
| Shared type scope (which types belong in common/ vs context-specific) | Wrong scope → tight coupling or unnecessary duplication |
| Schema files exist with uncommitted manual modifications (Merge mode, autonomous) | Manual customizations may be overwritten — human must decide whether to discard or incorporate before merge proceeds |
| Cross-context import creates a circular dependency | Design error — STOP and ask the human to restructure context boundaries |

**Phase 5 ASSUME & RECORD — proceed with explicit assumption:**

| Ambiguity | Default assumption |
|:----------|:------------------|
| Proto field naming | snake_case (proto3 convention) |
| Proto package naming | `{context}.v1` |
| DDL table naming | snake_case, plural (e.g., `orders`, `line_items`) |
| DDL column naming | snake_case |
| Error code format | `{CONTEXT}_{ERROR_NAME}` (e.g., `ORDERING_NOT_FOUND`) |
| Default ID field type | `string` (UUID-friendly) |
| Timestamp field type | `google.protobuf.Timestamp` (proto) / `TIMESTAMPTZ` (SQL) |
| Proto field numbering start | 1, sequential, no gaps |
| API versioning path | `/v1/` prefix or `v1` package |
| Migration file naming | `{NNN}_{description}.sql` (e.g., `001_create_orders.sql`) |

### Orchestrator Mode Exception

When invoked by an orchestrator (`full-ddd`, `iterating-ddd`, `piloting-ddd`, `restructuring-ddd`, `importing-technical-solution`) in **Autonomous Mode**, the interactive Q&A steps (2, 4) are replaced by autonomous execution:

- **Skip** interactive human confirmation of the directory plan (Step 2) and validation review (Step 4). Instead, execute INVENTORY → PLAN → GENERATE/MERGE → VALIDATE → PERSIST in a single autonomous pass.
- **Apply** STOP/ASSUME protocol: STOP for Phase 5 STOP triggers (above), ASSUME & RECORD for Phase 5 ASSUME items (above).
- **Self-check replaces human validation (Step 4):** The agent performs the VALIDATE completeness cross-check autonomously — verifying Phase 3 contract coverage, Phase 1 event coverage, Phase 4 Dimension 1 coverage, and error completeness. Missing items are flagged in the manifest's Untraced Items section; the human confirmation prompt is skipped.
- **Mode Detection proceeds autonomously:** Generate or Merge mode is determined by file existence checks without asking the user. Three cases: (1) no schema files → Generate mode; (2) schema files + manifest exist → Merge mode; (3) schema files exist but no manifest → Generate mode with WARNING (existing files may be overwritten). If schema files exist with uncommitted manual modifications (Merge mode conflict), treat as a STOP trigger — return the conflict to the orchestrator instead of asking the user interactively.
- **Persist** schema files (proto, OpenAPI, DDL, AsyncAPI) and `docs/ddd/schema-manifest.md` immediately (Step 5). Do NOT wait for human approval — the orchestrator manages the approval gate.
- **Return** the schema manifest to the orchestrator. If STOP was triggered, return the STOP reason instead.

This exception applies ONLY when dispatched as a subagent by an orchestrator. When invoked standalone (user directly asks for schema generation), the full interactive Q&A session is mandatory.

## Loading Guidance

This skill references supporting files on demand — do not preload them all:

- **During Step 1 (INVENTORY)**: read Phase 1-4 artifacts (see Step 1 for the specific files and their purposes).
- **During Step 2-3 (PLAN / GENERATE)**: load the format-specific reference for the tech stack selected in Phase 4 — `./proto-reference.md`, `./openapi-reference.md`, or `./asyncapi-reference.md`. Load only the relevant format(s), not all three.
- **On first STOP/ASSUME decision**: read `../ddd-protocol/ambiguity-handling-reference.md`.
- **Merge mode**: read `docs/ddd/schema-manifest.md` (check existence first).
- **Language conventions** (Go): read `../language-conventions/go-conventions.md`. For other languages: read `../language-conventions/SKILL.md` to detect and load.

## Implementation (Interactive Q&A Session)

**CRITICAL RULE:** Do NOT just generate all schema files in one batch. Guide the user through the INVENTORY and PLAN steps, present the directory plan for confirmation, then generate. Schema directory structure is a critical architectural decision — the user must approve it.

### Mode Detection

| Condition | Mode | Behavior |
|:----------|:-----|:---------|
| No schema files exist AND no `schema-manifest.md` | **Generate** | Create all schema files from scratch |
| Schema files exist AND `schema-manifest.md` exists | **Merge** | Diff-based delta, apply changes, preserve manual customizations |
| Schema files exist but no `schema-manifest.md` | **Generate** (with warning) | Treat existing files as manual; generate manifest only, do NOT overwrite |

### Step 1: INVENTORY

Read `docs/ddd/phase-1-domain-events.md` (for event schemas), `docs/ddd/phase-2-context-map.md` (for BC structure and classification), `docs/ddd/phase-3-contracts.md`, and `docs/ddd/phase-4-technical-solution.md`. For each bounded context, determine what schema files are needed:

| Phase Source | Schema Type | Format Decision |
|:-------------|:------------|:----------------|
| Phase 3 contracts + Phase 4 Dimension 2 (Interface Type) | Service interface | gRPC → `.proto`, REST → OpenAPI `.yaml`, GraphQL → `.graphql` |
| Phase 1 events + Phase 4 Dimension 2 | Event schema | Protobuf events → `.proto`, JSON events → AsyncAPI `.yaml` |
| Phase 4 Dimension 1 (Data Model & Persistence) | DDL / data schema | PostgreSQL → `.sql`, MongoDB → JSON schema, Redis → none |
| Phase 4 Dimension 6 (Error Handling) | Error code catalog | Follows interface format: proto → `enum` in `.proto`, REST → error schema in OpenAPI |

**Output:** Schema Inventory Table

```markdown
| # | Context | Scope | Schema Type | Format | Target Path | Source |
|---|---------|-------|-------------|--------|-------------|--------|
| 1 | ordering | ordering | service | proto | proto/ordering/v1/ordering_service.proto | Phase 3 #1 |
| 2 | ordering | ordering | types | proto | proto/ordering/v1/ordering_types.proto | Phase 3 #1 |
| 3 | ordering | ordering | events | proto | proto/ordering/v1/ordering_events.proto | Phase 1 |
| 4 | ordering | ordering | errors | proto | proto/ordering/v1/ordering_errors.proto | Phase 4 D6 |
| 5 | ordering | ordering | DDL | sql | docs/migrations/001_create_orders.sql | Phase 4 D1 |
| 6 | common | shared | types | proto | proto/common/v1/common_types.proto | Phase 3 |
```

**Rule:** If a Phase 3 contract has no corresponding row in the inventory, it MUST be flagged. No contract may be silently skipped.

### Step 2: PLAN

Determine target directory structure based on the tech stack. The directory structure is NOT hardcoded — it follows what the project's toolchain expects. Load the format-specific reference for directory layout examples:
- gRPC stack → [proto-reference.md](./proto-reference.md) § Directory Layout
- REST stack → [openapi-reference.md](./openapi-reference.md) § Directory Layout
- Async events → [asyncapi-reference.md](./asyncapi-reference.md) § Directory Layout

**Output:** Directory Plan table (target path → schema type → status).

**Rule:** Present the directory plan to the user for confirmation before generating files. If the project already has a directory convention (e.g., existing `proto/` folder), follow it.

**Default convention (when no project convention exists):** Use `proto/{context}/v1/` for gRPC, `api/{context}/v1/` for REST, `events/{context}/` for async events, `docs/migrations/` for SQL DDL, `db/schemas/` for NoSQL schemas. Record this as an `[ASSUMPTION]` entry.

### Step 3: GENERATE / MERGE

#### Generate Mode

For each schema file in the inventory:

1. **Map Phase 3 logical interface → concrete schema.** The Phase 3 boundary struct becomes the proto message or OpenAPI schema. The Phase 3 port interface becomes the proto service or REST path. See [proto-reference.md](./proto-reference.md) § Phase 3 → Proto Mapping for the concrete mapping example.

2. **Add traceability header** to every generated file linking back to Phase 3 contracts and Phase 4 decisions. See [proto-reference.md](./proto-reference.md) § Traceability Header for the header format (adapt for OpenAPI/AsyncAPI YAML `info.description`).

3. **Apply conventions** from ASSUME decisions (naming, field types, numbering).
4. **Manifest draft:** After generating each schema file, immediately append its entry to the manifest draft (in-memory or scratch). Do not wait until Step 5 to build the manifest from scratch.

5. **Scope column:** For each schema entry, fill the Scope column in the manifest: use the bounded context name if the schema belongs to a single context, or `shared` if it is used across multiple contexts (e.g., common types proto).

6. **Size limit:** Single file ≤ 200 lines. If a file exceeds 200 lines, split by responsibility (service vs types vs events). If a single aggregate's types exceed 200 lines, this signals the aggregate may need splitting — flag to the user.

7. **Error definitions:** Every service method MUST define ≥ 1 domain-specific error. Generic errors (INTERNAL, UNAVAILABLE) are NOT sufficient. Error codes follow the ASSUME convention: `{CONTEXT}_{ERROR_NAME}`.

8. **Cross-context imports:** When a consumer context references a publisher's event or shared type, use an explicit proto import: `import "{publisher}/v1/{publisher}_events.proto";`. The consumer's service proto depends on the publisher's event proto — this import dependency must appear in the generated file. Do NOT copy event message definitions into the consumer's package (duplication = drift). If the import creates a circular dependency between two contexts, this is a design error — STOP and ask the human to resolve the dependency direction.

9. **DDL generation rules:**
   - One migration file per bounded context (initial schema).
   - Include primary keys, foreign keys, indexes, and constraints.
   - Include `created_at` and `updated_at` timestamps.
   - State fields use enum types or CHECK constraints matching Phase 1 state machines.
   - Do NOT include application-level business logic in DDL (triggers, stored procedures) unless Phase 4 Dimension 1 explicitly specifies them.

#### Merge Mode

When Phase 3 or Phase 4 artifacts have changed since last generation:

1. **Detect changes:** Compare Phase 3 + Phase 4 artifacts against their last committed versions using `git diff`. Use `schema-manifest.md` Source column to identify which artifacts map to which schema files.
2. **Identify affected schemas:** Map changed contracts/decisions to specific schema files via the manifest's Source column.
3. **Generate delta:** For each affected file, produce a delta description:
   - `ADDED`: New RPCs, messages, fields, tables, columns.
   - `MODIFIED`: Changed types, renamed fields, altered constraints.
   - `REMOVED`: Deprecated methods, dropped columns.
4. **Apply delta:** Update the schema file, preserving sections not affected by the delta. If a file has been manually modified (check `git diff` against last committed version), flag the conflict and ask the user.
5. **Update manifest** after successful merge.

**Rule:** Never silently overwrite a file that has been manually modified (check `git diff`). This indicates manual customization that must be preserved or explicitly discarded.

### Step 4: VALIDATE

Cross-check completeness:

| Check | Source | Expected |
|:------|:-------|:---------|
| Phase 3 contract coverage | `phase-3-contracts.md` | Every contract → ≥ 1 interface schema |
| Phase 1 event coverage | `phase-1-domain-events.md` | Every domain event → event schema message/channel |
| Phase 4 Dimension 1 coverage | `phase-4-technical-solution.md` | Every persisted entity → DDL table/collection |
| Error completeness | All interface schemas | Every RPC/endpoint → ≥ 1 domain error |

**Output:** Completeness report embedded in the manifest. Missing items are listed in the `## Untraced Items` section — they are flagged, not auto-generated (the omission may be intentional).

### Step 5: Persist Manifest

**Persist to Filesystem:** Write `docs/ddd/schema-manifest.md` using the

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [lockp111](https://github.com/lockp111)
- **Source:** [lockp111/agent-ddd-engineering](https://github.com/lockp111/agent-ddd-engineering)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-lockp111-agent-ddd-engineering-defining-schemas
- Seller: https://agentstack.voostack.com/s/lockp111
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
