# Mapping Legacy Landscape

> Use when analyzing a non-DDD legacy codebase to understand its structure before introducing DDD. Use when the codebase is MVC, layered, monolithic, or unstructured ("屎山"). Use when asked to "understand the legacy code", "map the existing system", "find where to introduce DDD", or "analyze the codebase before adding a feature". 遗留地形图, 屎山分析, legacy analysis, brownfield mapping, 映射遗留代码, map legacy c…

- **Type:** Skill
- **Install:** `agentstack add skill-lockp111-agent-ddd-engineering-mapping-legacy-landscape`
- **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/mapping-legacy-landscape

## Install

```sh
agentstack add skill-lockp111-agent-ddd-engineering-mapping-legacy-landscape
```

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

## About

# Mapping Legacy Landscape

## Overview

Reads a non-DDD codebase and produces a structured legacy landscape map (`legacy-landscape.md`). Every observation is marked with `[OBSERVED]` and a confidence level; human reviews before downstream consumption.

**Foundational Principle:** Legacy code is what it is — observe honestly, don't project DDD concepts onto it. A Rails `Service` is not an "Application Service." An ActiveRecord `Model` is not an "Aggregate Root." The landscape map describes what exists using neutral terms. There is no familiarity threshold below which systematic scanning may be skipped. Violating the letter of the rules is violating the spirit of the rules.

**Scanning Scope:** Analysis is scoped to directories relevant to the new requirement — NOT the entire codebase.

## When to Use

- When preparing for a [piloting-ddd](../piloting-ddd/SKILL.md) workflow — this skill provides the landscape map for brownfield DDD introduction.
- When preparing for a [restructuring-ddd](../restructuring-ddd/SKILL.md) workflow on a large or complex codebase — this skill maps the legacy structure before the snapshot, improving confidence levels.
- When asked to "understand what this legacy code does" or "find where to add DDD" in an existing non-DDD codebase.
- When the codebase lacks DDD structure (no ports, adapters, aggregates, bounded contexts) but has business logic that needs to be understood.

**Do NOT use when:** the codebase already follows DDD patterns (use [snapshotting-code-context](../snapshotting-code-context/SKILL.md) to rebuild artifacts from existing DDD code), starting a greenfield project (use [full-ddd](../full-ddd/SKILL.md)), or when `docs/ddd/legacy-landscape.md` already exists and is current (just read it directly).

## Quick Reference

| Step | Action | Output |
|:---|:---|:---|
| 1 | Accept requirement + confirm scan scope | STOP: human confirms directory scope |
| 2 | Detect project structure | Technology stack summary |
| 3 | Map Entity/Model layer | Entity inventory with `[OBSERVED]` markers |
| 4 | Map business logic locations | Logic location map (which files/methods hold behavior) |
| 5 | Map data schema | Table structure overview + implicit relationships |
| 6 | Map external integrations | Integration inventory (APIs, queues, services) |
| 7 | Extract implicit domain concepts | Domain concept candidates from naming analysis |
| 8 | Identify natural seams + interaction analysis | Seam ratings + interaction direction + interaction type |
| 9 | Human review & persist | Confirmed map written to `docs/ddd/legacy-landscape.md` |

## Ambiguity Handling

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

### Landscape STOP Triggers

| Ambiguity | Why STOP |
|:---|:---|
| Cannot determine which directories are relevant to the requirement | Scanning wrong directories wastes effort and produces misleading landscape — need human to confirm scope |
| Business logic is scattered across multiple layers with no clear entry point | Cannot reliably map behavior locations — need human to explain the primary flow |
| Database schema is accessed through raw SQL in multiple locations with no ORM | Cannot reliably map entity-to-table relationships — need human to identify primary data access patterns |
| A service/class has 40+ methods mixing multiple domain concerns | Cannot determine seam strength without understanding which concerns should separate — need human domain input |

### Landscape ASSUME & RECORD

| Ambiguity | Default assumption |
|:---|:---|
| Class name suggests a domain concept but naming is ambiguous (e.g., `Manager`, `Handler`) | ASSUME class name reflects its primary responsibility; record for domain concept review |
| A table has foreign keys to multiple other tables | ASSUME the most-referenced table is the primary entity; record relationship for human verification |
| External API client exists but usage scope is unclear | ASSUME it is used only within the scanned directories; record for scope verification |
| A method name suggests business logic but body is simple delegation | ASSUME the delegation target contains the actual logic; record both locations |

### Orchestrator Mode Exception

When invoked by an orchestrator (`piloting-ddd`, `restructuring-ddd`) as a subagent, the landscape mapping runs identically — all interactive checkpoints (Step 1 scope confirmation, Step 9 human review) remain mandatory. The orchestrator controls the overall brownfield workflow; this skill controls the internal code scanning and human review cycle. No steps are skipped.

## Implementation (Interactive Legacy Reading Session)

**Graceful Degradation** — Not all codebases have every layer. Adapt steps to what exists:

| Missing Layer | Affected Step | Action |
|:---|:---|:---|
| No database / No ORM | Step 5 (Data Schema) | Mark "N/A — no persistence layer detected" and continue |
| No controllers / No HTTP layer | Step 4 (Business Logic) | Scan entry points that exist (CLI handlers, event handlers, cron jobs) |
| No external integrations | Step 6 (Integrations) | Mark "N/A — no external integrations in scanned scope" and continue |
| No tests | Step 3-4 (behavior inference) | Lower confidence levels; flag "no test evidence" in observations |

Do NOT STOP for missing layers — mark N/A and continue. STOP only if the **entire scope** appears empty (no code files found).

**CRITICAL RULE:** Do NOT project DDD terminology onto legacy code. Do NOT skip the systematic scan because "the structure looks standard." You must scan the actual code using Glob and Read tools within the confirmed scope, mark every observation with `[OBSERVED]`, and present the complete landscape map for human review before persisting.

### Step 1: Accept Requirement + Confirm Scan Scope

1. **Accept the new requirement** from the human (PRD, feature description, or task).
2. **Propose scan scope** based on the requirement:
   - Identify which top-level directories are likely relevant.
   - Propose a scope boundary (e.g., "I'll scan `app/models/order*.rb`, `app/controllers/orders_controller.rb`, `app/services/payment*.rb`, and `db/schema.rb` for order-related tables").
3. **STOP — present the proposed scope to the human:**

**Checkpoint:** "Based on the requirement, I propose scanning these directories/files: [list]. Does this cover the relevant areas? Are there directories I should add or exclude?"

If the human adjusts the scope, update before proceeding.

**Scanning Priority** — Within the confirmed scope, scan in this order (highest business logic density first):
1. Service/use-case files (business logic orchestration)
2. Model/entity files (domain state + behavior)
3. Controller/handler files (may contain leaked business logic)
4. Job/worker files (background business logic)
5. Configuration/schema files (structural context)
6. Utility/helper files (shared logic, lowest priority)

This order maximizes insight per file read. If the context window is tight, early files carry more weight.

### Step 2: Detect Project Structure

Scan the scoped directories to identify the technology stack:

1. **Framework detection:** Look for framework-specific files (`Gemfile`, `requirements.txt`, `go.mod`, `package.json`, `pom.xml`, `build.gradle`).
2. **Architecture pattern:** MVC, layered, service-oriented, monolithic, microservice, or no discernible pattern.
3. **ORM/data access:** ActiveRecord, Django ORM, GORM, Hibernate, raw SQL, mixed.
4. **Database:** PostgreSQL, MySQL, MongoDB, etc. (from config files or connection strings).

Produce a **Technology Stack Summary** — format: see [landscape-examples-reference.md](./landscape-examples-reference.md#step-2-technology-stack-summary).

### Step 3: Map Entity/Model Layer

For each entity/model in the scoped directories:

1. **Identify entities:** ORM models, database-mapped classes, domain objects.
2. **Record fields, associations, and validations.**
3. **Note where behavior lives** — on the model (rich) or external (anemic).

**`[OBSERVED]` marker format:** see [landscape-examples-reference.md](./landscape-examples-reference.md#step-3-entitymodel-observation).

Confidence levels:
- **HIGH** → Clear structural evidence (model file, ORM annotations, explicit associations).
- **MEDIUM** → Partial evidence (inferred from usage, naming conventions).
- **LOW** → Weak evidence. **STOP** — must confirm before proceeding.

### Step 4: Map Business Logic Locations

Legacy code scatters business logic across layers. For each business behavior relevant to the requirement:

1. **Scan controllers/handlers** for business logic that should be in domain.
2. **Scan services** (if a service layer exists) for orchestration vs domain behavior.
3. **Scan models** for behavior methods vs simple data holders.
4. **Scan jobs/workers** for background business logic.
5. **Scan stored procedures/database functions** if applicable.

Produce a **Business Logic Location Map** — format: see [landscape-examples-reference.md](./landscape-examples-reference.md#step-4-business-logic-location-map).

### Step 5: Map Data Schema

Scan for database schema information:

1. **Schema files:** `db/schema.rb`, `db/structure.sql`, migration files, ORM model definitions.
2. **Table structure:** For each relevant table, record columns, types, indexes, and constraints.
3. **Implicit relationships:** Foreign keys, join tables, polymorphic associations.
4. **Data patterns:** Soft deletes, status enums, audit columns, JSON blobs.

Format: see [landscape-examples-reference.md](./landscape-examples-reference.md#step-5-data-schema-observation).

**Focus Refresh** — Before continuing to Steps 6-8, re-read your Step 2 Technology Stack Summary. After scanning models, logic, and schema (Steps 3-5), your active awareness of the framework and architecture pattern has degraded. Re-reading prevents misattributing framework behavior to domain logic in the remaining steps.

### Step 6: Map External Integrations

Identify all external system integrations within the scanned scope:

1. **Third-party APIs:** Payment gateways, shipping providers, email services.
2. **Message queues:** Kafka, RabbitMQ, SQS producers/consumers.
3. **External databases:** Connections to other systems.
4. **Webhooks:** Inbound and outbound.

Format: see [landscape-examples-reference.md](./landscape-examples-reference.md#step-6-external-integration-observation).

### Step 7: Extract Implicit Domain Concepts

Analyze naming patterns across the scanned code to extract domain concepts that the legacy code expresses but doesn't explicitly define:

1. **Naming clusters:** Group related class/method/variable names by domain concept.
2. **State machines:** Identify status enums and their transitions.
3. **Business rules:** Extract validation rules, conditional logic, and invariants.
4. **Domain language candidates:** Terms used consistently across multiple locations.

**Naming degradation fallback:** If naming is meaningless (functions named `process`, `handle`, `doStuff`), skip naming cluster analysis. Instead focus on: (a) state machines from enum/constant definitions, (b) business rules from conditional logic, (c) data flow patterns from method signatures. Mark confidence as LOW and note "naming analysis not applicable — code uses generic names."

Format: see [landscape-examples-reference.md](./landscape-examples-reference.md#step-7-implicit-domain-concept).

### Step 8: Identify Natural Seams + Interaction Analysis

Identify points in the legacy code where an ACL adapter could attach — natural boundaries between concerns:

1. **Service boundaries:** Classes/modules with relatively clean interfaces.
2. **Data boundaries:** Tables/schemas that belong to a single domain concern.
3. **Integration boundaries:** External API clients that encapsulate third-party interactions.
4. **Namespace boundaries:** Packages/modules/namespaces that group related code.

**Seam Strength Rating:**
- **STRONG** — Already has a clean interface/facade. ACL can attach directly with minimal adapter work.
- **WEAK** — Partial separation exists but with coupling (shared state, direct model access). Adapter work needed.
- **NO SEAM** — Tightly coupled to surrounding code. ACL must create an entirely new boundary.

**Interaction Direction:**
- **Outbound** — DDD island → calls legacy code (island is active, legacy is passive)
- **Inbound** — Legacy code → triggers DDD island behavior (legacy is active, island is passive)
- **Bidirectional** — Both directions

**Interaction Type:**

| Type | Meaning | ACL Direction | Legacy Touch | Risk |
|:---|:---|:---|:---|:---|
| `READ` | Island queries legacy data | Outbound | None | LOW |
| `WRITE` | Island writes to legacy system | Outbound | None | LOW |
| `HOOK` | Legacy needs to trigger island behavior | Inbound | Add emit/callback | MEDIUM |
| `SHARED` | Same concept exists in both systems | Bidirectional | None (translation in ACL) | MEDIUM |
| `MODIFY` | New requirement changes legacy behavior | Bidirectional | Add delegate/decorator point | HIGH |

When HOOK or MODIFY interactions are detected, generate **Minimal Legacy Touch Register** entries — format: see [landscape-examples-reference.md](./landscape-examples-reference.md#step-8-seam-analysis).

**Minimal Legacy Touch Principles:**
- **Additive only** — only ADD code (hooks, callbacks, event emits, facade methods). Never modify existing logic.
- **Each touch point recorded** — file, line, what to add, confirmation that existing behavior is unchanged.
- **Human confirmed** — every legacy touch must be presented and approved in Step 9.

Seam observation format: see [landscape-examples-reference.md](./landscape-examples-reference.md#natural-seam-observation).

**Scope extension check:** If seam analysis reveals critical dependencies on code OUTSIDE the confirmed scope (e.g., a shared utility, a database table owned by another module), STOP: "Seam analysis found a dependency on [file/module] which is outside the confirmed scan scope. Should I extend the scope to include it?" Do NOT silently ignore out-of-scope dependencies or silently extend the scope.

**Checkpoint:** "Here is the complete seam analysis with interaction directions and types. For HOOK/MODIFY interactions, I've identified the minimal legacy touch points. Please review."

### Step 9: Human Review & Persist

1. Present the **complete legacy landscape map** with all `[OBSERVED]` markers.
2. Group by confidence: LOW items first (require confirmation), then MEDIUM, then HIGH.
3. **Highlight HOOK/MODIFY interactions** and their Minimal Legacy Touch Register entries — these require explicit human approval since they involve legacy code changes.
4. The human reviews each `[OBSERVED]` entry: ✅ Confirm | ✏️ Revise | ❌ Remove.
5. For any REVISED entry, update the landscape map.
6. **Persist the confirmed landscape map** to `docs/ddd/legacy-landscape.md` using the template (`../piloting-ddd/templates/legacy-landscape.md`).
7. **This step is mandatory — do not skip even if the landscape is already visible in the conversation.**

**Checkpoint:** "The legacy landscape map has been persisted to `docs/ddd/legacy-landscape.md`. Please verify the file exists before proceeding."

**NEXT STEP:** If invoked by [piloting-ddd](../piloting-ddd/SKILL.md) → hand off to Step 2 (Impact Analysis). If invoked by [restructuring-ddd](../restructuring-ddd/SKILL.md) → return to Step 1 (Snapshot) with the landscape map as supplementary context. If standalone → the landscape map is complete; inform the user and suggest [piloting-ddd](../piloting-ddd/SKILL.md) or [restructuring-ddd](../restructuring-ddd/SKILL.md) depending on scope.

### Loading Guidance

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

- **During Steps 2-8**: refer to [landscape-examples-reference.md](./landscape-examples-reference.md) for `[OBSERVED]` output format examples (read once, not per step).
- **During Step 9**: rea

…

## 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-mapping-legacy-landscape
- 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%.
