# Restructuring Ddd

> Use when fully restructuring an existing non-DDD project into DDD hexagonal architecture. Big-bang approach — reverse-engineer, design, refactor entirely. Use when asked to "convert to DDD", "restructure to hexagonal", "rewrite properly", "migrate from MVC/monolith to DDD". 全面重构, 非DDD转DDD, MVC转六边形, 大重构, restructure to DDD, monolith to hexagonal.

- **Type:** Skill
- **Install:** `agentstack add skill-lockp111-agent-ddd-engineering-restructuring-ddd`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [lockp111](https://agentstack.voostack.com/s/lockp111)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **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/restructuring-ddd

## Install

```sh
agentstack add skill-lockp111-agent-ddd-engineering-restructuring-ddd
```

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

## About

# Restructuring DDD Workflow

## Overview

Full restructuring of an existing non-DDD project into DDD hexagonal architecture — snapshot existing code, design target architecture, refactor one BC at a time with coexistence, verify, then cleanup.

**Foundational Principle:** Restructuring is the highest-risk DDD workflow. Existing production behavior MUST be preserved throughout. Regression tests must exist BEFORE any refactoring begins. Old code coexists with new DDD code until verification proves equivalence. Cleanup only happens after all tests pass and with human approval. There is no complexity threshold below which the snapshot, regression tests, or coexistence strategy may be skipped. Violating the letter of the rules is violating the spirit of the rules.

## When to Use

- When converting an entire existing non-DDD codebase to DDD hexagonal architecture.
- When the project uses MVC, layered, or no discernible architecture and the decision is to restructure everything.
- When asked to "convert to DDD", "restructure to hexagonal", "rewrite properly", or "migrate from MVC/monolith to DDD".

**Do NOT use when:** the project already has DDD structure (use [iterating-ddd](../iterating-ddd/SKILL.md)), only adding a new feature to a non-DDD codebase without full conversion (use [piloting-ddd](../piloting-ddd/SKILL.md)), starting a greenfield project from requirements with no existing code (use [full-ddd](../full-ddd/SKILL.md)), or importing an existing technical solution document (use [importing-technical-solution](../importing-technical-solution/SKILL.md)).

## Quick Reference

| Step | Action | Output | Gate |
|:---|:---|:---|:---|
| 0 | Pre-flight checks (confirm non-DDD, has code, confirm restructure intent) | Confirmed status | — |
| 1 | Snapshot → `snapshotting-code-context` → Phase 1-4 artifacts `[INFERRED]` | `phase-1-domain-events.md`, `phase-2-context-map.md`, `phase-3-contracts.md`, `phase-4-technical-solution.md` (all `[INFERRED]`) | **Human confirms snapshot** |
| 2 | Human review snapshot — confirm `[INFERRED]` → `[CONFIRMED]` | Confirmed Phase 1-4 artifacts | **STOP: Human confirms or corrects** |
| 3 | Add regression tests to existing domain logic | `regression-test-baseline.md` + test files | **STOP: Human confirms coverage** |
| 4 | Phase 5 → `defining-schemas` (Autonomous, STOP/ASSUME) | Schema files + `schema-manifest.md` | Autonomous (STOP/ASSUME) |
| 5 | Phase 6 → `spec-driven-development` (Autonomous, STOP/ASSUME) | Behavior contracts + `phase-6-behavior-contracts.md` + `phase-6/` | Autonomous (STOP/ASSUME) |
| 6 | **Project Init Gate** (assumptions + refactoring plan + scaffold) | `refactoring-plan.md` + confirmed assumptions + compilable scaffold | **STOP: Human confirms "ready for refactoring"** |
| 7 | Phase 7 Refactoring → `coding-isolated-domains` + TDD (one BC at a time, Core→Supporting→Generic) | DDD domain code + tests (alongside old code) | Human checkpoint per BC |
| 8 | Verification — TDD + integration + regression all pass | All tests green | **Human confirms verification results** |
| 9 | Cleanup → produce `cleanup-manifest.md` → execute after approval | Old code removed, imports updated | **STOP: Human approves manifest** |
| 10 | Archive → `archive-artifacts.sh` | Artifacts archived to `docs/ddd/archive/v{N}/` | — |

```
Step 0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
```

## Subagent Dispatch I/O

All artifact paths below are relative to `docs/ddd/`. `decisions-log.md` and `assumptions-draft.md` are passed as context to every subagent and omitted from the table for brevity.

| Dispatch Step | Subagent Skill | Input Artifacts | Output Artifacts |
|:---|:---|:---|:---|
| Step 0.7 (optional) | mapping-legacy-landscape | Project codebase (Glob/Read scan) | `legacy-landscape.md` |
| Step 1 | snapshotting-code-context | Project codebase, `legacy-landscape.md` (if exists) | `phase-1-domain-events.md`, `phase-2-context-map.md`, `phase-3-contracts.md`, `phase-4-technical-solution.md` (all `[INFERRED]`) |
| Step 4 | defining-schemas | `phase-1-domain-events.md`, `phase-2-context-map.md`, `phase-3-contracts.md`, `phase-4-technical-solution.md` (confirmed), `regression-test-baseline.md` | Schema files + `schema-manifest.md` |
| Step 5 | spec-driven-development | `phase-1-domain-events.md`, `phase-2-context-map.md`, `phase-3-contracts.md`, `phase-4-technical-solution.md`, schema files (via `schema-manifest.md`) | `phase-6-behavior-contracts.md` + `phase-6/*.md` |
| Step 7 (per context) | coding-isolated-domains + test-driven-development | `phase-6-behavior-contracts.md`, `phase-6/{context}.md`, schema files (via `schema-manifest.md`), `refactoring-plan.md`, `regression-test-baseline.md` | DDD domain code + tests, `test-map.md`, `test-coverage.md` |

### Orchestrator-Executed Steps I/O

Steps executed directly by the orchestrator (not dispatched to a subagent skill):

| Step | Input | Output |
|:---|:---|:---|
| Step 2 — Human Review | Snapshot artifacts (Phase 1-4) | `[CONFIRMED]` annotations on snapshot artifacts |
| Step 3 — Regression Tests | Existing code + test infrastructure | `docs/ddd/regression-test-baseline.md` + test files |
| Step 8 — Verification | New DDD code + regression tests | Updated `ddd-progress.md` (verification status per BC) |
| Step 9 — Cleanup | `cleanup-manifest.md` (human-approved) | Executed deletions/updates per manifest |

## Ambiguity Handling

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

### Restructure STOP Triggers

| Ambiguity | Why STOP |
|:---|:---|
| Snapshot cannot determine Bounded Context boundaries — existing code has no logical grouping | BC boundaries define the entire restructuring target — wrong boundaries mean wrong refactoring scope and wrong contracts |
| Existing domain logic has undocumented behavior (side effects, implicit state, hidden coupling) discovered during regression test writing | Undocumented behavior may be intentional or accidental — refactoring must preserve intentional behavior and may safely remove accidental behavior, but only the human knows which is which |
| Existing code is untestable without significant refactoring (circular dependencies, global state, no seams) | Regression tests are the safety net — if they cannot be written, refactoring cannot be verified. Must discuss testing strategy alternatives with human |
| Refactoring order creates a temporary state where critical business logic has no test coverage | Gaps in test coverage during refactoring mean undetected regressions — must reorder or add bridge tests |
| Cleanup manifest includes files that are imported by code outside the project boundary | Deleting files used by external consumers breaks those consumers — must confirm external dependency scope |
| Existing code has database migrations or schema dependencies that conflict with new DDD schema design | Schema migration ordering determines data integrity — wrong order means data loss or corruption |

### Restructure ASSUME & RECORD

| Ambiguity | Default assumption |
|:---|:---|
| Existing technology stack (language, framework, DB) remains unchanged after restructuring | ASSUME same stack; record for Phase 4 review |
| Existing API contracts (REST endpoints, gRPC services) remain stable during restructuring | ASSUME external API shapes unchanged; record for contract review |
| Existing database schema can be mapped 1:1 to new DDD aggregate boundaries | ASSUME direct mapping; record for schema design review |
| Naming conventions in existing code reflect intended domain language | ASSUME existing names are the UL starting point; record for UL review |

**Autonomous Mode** applies to Steps 4-5 (Phase 5 and Phase 6). The agent executes each step, persists artifacts immediately, and continues without waiting for approval, using the STOP/ASSUME protocol for uncertainties.

## Session Recovery

**Before starting any step work**, check for an existing DDD workflow:

1. Check if `docs/ddd/ddd-progress.md` exists.
2. **If it exists** with `workflow_mode: restructure`: Read `ddd-progress.md` and ALL persisted artifact files — `phase-1-domain-events.md` through `phase-4-technical-solution.md` (snapshot, `[INFERRED]`/`[CONFIRMED]`), `regression-test-baseline.md` (Step 3), `schema-manifest.md`, `phase-6-behavior-contracts.md` + `phase-6/*.md`, `refactoring-plan.md`, `test-map.md` + `test-coverage.md`, `cleanup-manifest.md`, `assumptions-draft.md`, `decisions-log.md`. All paths under `docs/ddd/`. Resume from first incomplete step. Run `sh skills/full-ddd/scripts/session-recovery.sh` for a quick status report.
3. **If it does not exist:** Start at Step 0.

**Persisted artifacts contain human-approved decisions and are authoritative.** Do not discard or re-do completed steps unless the user explicitly requests a rollback.

**Cleanup interruption recovery:** If session was interrupted during Step 9 Cleanup execution, check `cleanup-manifest.md` for items already marked as executed vs pending. Resume from the first pending item.

## Implementation (Interactive Orchestration)

**CRITICAL RULE:** You are the orchestrator. The code snapshot (Step 1), human review (Step 2), and regression tests (Step 3) are **mandatory** — never skip them. Regression tests MUST exist before any refactoring begins. Old code coexists with new code until cleanup (Step 9). The Project Init Gate (Step 6) is a **mandatory hard stop** — never bypass it. Cleanup (Step 9) requires explicit human approval of the manifest before any deletion.

**CRITICAL RULE: Sub-Skill Loading.** Before executing any step that delegates to a sub-skill (linked via `[skill-name](path)`), you MUST read the sub-skill's SKILL.md file into your context using the Read tool. The markdown link is a file path — the sub-skill's rules, rationalization table, and red flags are binding constraints for that step. Operating without reading the sub-skill file means operating without anti-hallucination constraints for that step.

Follow the [Per-Phase Subagent Dispatch Protocol](../ddd-protocol/subagent-dispatch-reference.md).

### Step 0: Pre-flight Checks

1. **Check `docs/ddd/` state:** If `phase-*.md` files exist → STOP: "Current artifacts exist. Are these up to date, or should I proceed with a fresh restructure?"
2. **Verify NON-DDD structure:** Glob scan for domain directories (`internal/biz/`, `internal/domain/`, `src/*/domain/`, or similar). If DDD structure IS found → STOP: "This project appears to have DDD structure. Consider [iterating-ddd](../iterating-ddd/SKILL.md) instead." If no DDD but has code → proceed.
3. **Verify existing code:** Confirm the project has substantive source code files (not just config or boilerplate). If no meaningful code exists → STOP: "This project has no substantial code to restructure. Consider [full-ddd](../full-ddd/SKILL.md) for greenfield."
4. **Confirm restructure intent:** Present the scope to the human: "This workflow will restructure the ENTIRE codebase into DDD hexagonal architecture. This is a big-bang conversion — all existing code will eventually be replaced. If you only want to add a new DDD feature alongside existing code, use [piloting-ddd](../piloting-ddd/SKILL.md) instead. Confirm to proceed."
5. **Initialize progress tracker:** Create `docs/ddd/ddd-progress.md` from the restructure template (`templates/ddd-progress-restructure.md`).
6. **Enforce platform hooks:** Follow the [Hooks Enforcement Protocol](../ddd-protocol/persistence-defense-reference.md#hooks-enforcement-protocol) — detect platform, set up or merge hooks from templates, update the `Hooks` field in `ddd-progress.md`. **HARD STOP if setup fails.**
7. **Optional: Legacy Landscape Scan.** If the codebase is large (>50 source files) or has unclear module boundaries, offer a legacy landscape scan. If approved, dispatch [mapping-legacy-landscape](../mapping-legacy-landscape/SKILL.md) with the project codebase + `decisions-log.md`. Verify `docs/ddd/legacy-landscape.md` exists. Update `ddd-progress.md`. The landscape map is passed as supplementary context to Step 1.

### Step 1: Snapshot → `snapshotting-code-context` (subagent)

Dispatch [snapshotting-code-context](../snapshotting-code-context/SKILL.md) with the project codebase + `decisions-log.md` + `legacy-landscape.md` (if from Step 0). Expected output: `phase-1-domain-events.md` through `phase-4-technical-solution.md` (all `[INFERRED]`). Non-DDD code means lower confidence and likely STOP triggers.

**Gate:** After the subagent returns, the orchestrator presents the snapshot output to the human for review. Do NOT proceed to Step 2 until the human acknowledges receipt.

After acknowledgment, update `ddd-progress.md`: snapshot status = complete.

### Step 2: Human Review Snapshot

Present ALL `[INFERRED]` artifacts (Phase 1-4) to the human. For each item: CONFIRM / CORRECT / REMOVE. Walk Phase 1 → 2 → 3 → 4 systematically.

**Checkpoint:** "Please review and confirm/correct each `[INFERRED]` item. The restructuring plan will be built on these confirmed artifacts."

After review: replace `[INFERRED]` → `[CONFIRMED]`. Persist. Update `ddd-progress.md`.

**Generate constraint artifacts:** After Phase 2 confirmation, generate per-context constraint files (`.claude/rules/{context}.md`) and DDD Architecture section in `CLAUDE.md` per [mapping-bounded-contexts](../mapping-bounded-contexts/SKILL.md) Step 6 format — bidirectional import prohibitions, UL dictionary, relationship patterns.

### Step 3: Add Regression Tests to Existing Domain Logic

**MANDATORY before any refactoring begins.** The regression test suite is the safety net that proves the restructured code preserves existing behavior.

Write regression tests for existing business logic (domain rules, state transitions, validations, calculations). Scoping rules, baseline format, and test strategy: see [restructuring-strategy-reference.md](./restructuring-strategy-reference.md).

**Inline minimum criteria (if reference not loaded):** Test every public method that contains business logic (conditionals, calculations, state changes). Each test asserts current behavior — not desired behavior. Skip pure getters/setters and framework boilerplate. Target: ≥1 test per business method.

**STOP** if undocumented behavior found or code is untestable — see reference for options.

Persist to `docs/ddd/regression-test-baseline.md` (format in reference).

**STOP — present regression test summary:**

**Checkpoint:** "Regression tests are written. Here is the coverage summary. [N] business methods tested, [K] coverage gaps documented. Please review and confirm before refactoring begins."

Update `ddd-progress.md`: regression tests = complete.

### Step 4: Phase 5 → `defining-schemas` (subagent)

Dispatch [defining-schemas](../defining-schemas/SKILL.md) with confirmed Phase 1-4 artifacts + `regression-test-baseline.md`. Schema design MUST account for migration: map existing tables to new DDD schemas, generate as NEW files (do NOT modify existing schemas). **Verify:** `schema-manifest.md` exists + schema files written.

### Step 5: Phase 6 → `spec-driven-development` (subagent)

Dispatch [spec-driven-development](../spec-driven-development/SKILL.md) with Phase 1-5 artifacts. **Verify:** `phase-6-behavior-contracts.md` + `phase-6/` directory exist. Proceed to Project Init Gate.

### Step 6: Project Init Gate

**MANDATORY hard stop before any refactoring begins.**

Present to the developer:

**Part 1 — Assumption Review:**

1. Present `docs/ddd/assumptions-draft.md` (full contents — all accumulated ASSUME entries from Steps 1-5).
2. Developer reviews each `[ASSUMPTION]` entry: ✅ Keep | ✏️ Revise.
3. For REVISED entries, check upstream artifact impact. If schema files or behavior contracts are affected, re-run the affected phase.
4. Append to `docs/ddd/decisions-log.md`. Delete `docs/ddd/assumptions-draft.md`.

**Part 2 — Refactoring Plan:**

Produce `docs/ddd/refactoring-plan.md` per [restructuring-strategy-referenc

…

## 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-restructuring-ddd
- 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%.
