# Snapshotting Code Context

> Use when iterating on an existing codebase (DDD-structured or partially-structured) where docs/ddd/ is empty (archived or never generated). Use when code exists but phase artifacts are missing — the code IS the source of truth, not old documents. Use when asked to "understand the current state", "rebuild context from code", or "prepare for iteration". Also used by restructuring-ddd as Step 1 on n…

- **Type:** Skill
- **Install:** `agentstack add skill-lockp111-agent-ddd-engineering-snapshotting-code-context`
- **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/snapshotting-code-context

## Install

```sh
agentstack add skill-lockp111-agent-ddd-engineering-snapshotting-code-context
```

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

## About

# Snapshotting Code Context

## Overview
This skill reads an existing codebase (DDD-structured, partially-structured, or being evaluated for DDD adoption) and reverse-engineers the four phase artifacts (`phase-1-domain-events.md`, `phase-2-context-map.md`, `phase-3-contracts.md`, `phase-4-technical-solution.md`) from the code itself. The code is the source of truth — not archived documents, not chat history, not memory.

Every inference is marked with `[INFERRED]` and a confidence level. The human reviews and confirms before any downstream skill consumes the artifacts.

**Foundational Principle:** Code is the only reliable baseline for iteration. Archived documents may be stale, chat history is volatile, and agent memory is unreliable. The skill reads code structure, type definitions, and package layout to reconstruct what the pipeline would have produced — then asks the human to verify. There is no confidence threshold below which human review may be skipped. Violating the letter of the rules is violating the spirit of the rules.

## When to Use

- When `docs/ddd/` is empty (archived or never generated) and the codebase follows DDD/hexagonal architecture patterns (fully or partially structured).
- When preparing for an iteration cycle — this skill provides the baseline for [iterating-ddd](../iterating-ddd/SKILL.md).
- When preparing for a full restructure — this skill is Step 1 of [restructuring-ddd](../restructuring-ddd/SKILL.md).
- When asked to "understand what contexts exist in this code" or "rebuild the DDD artifacts from source."

**Do NOT use when:** starting a greenfield project from requirements (use [full-ddd](../full-ddd/SKILL.md)), importing an existing technical document (use [importing-technical-solution](../importing-technical-solution/SKILL.md)), the codebase is non-DDD legacy code (use [mapping-legacy-landscape](../mapping-legacy-landscape/SKILL.md)), or when `docs/ddd/phase-*.md` files already exist and are current (just read them directly).

## Quick Reference

| Step | Action | Output |
|:---|:---|:---|
| 1 | Detect project structure + spec inventory | Directory mapping + spec file inventory + STOP confirmation |
| 2 | Rebuild Phase 2 (Context Map) | `[INFERRED]` BC boundaries, classifications, relationships, UL |
| 3 | Rebuild Phase 3 (Contracts) | `[INFERRED]` port interfaces and boundary structs |
| 4 | Rebuild Phase 4 (Tech Solution) | `[INFERRED]` 7-dimension decisions from adapter code |
| 5 | Rebuild Phase 1 (Events) | `[INFERRED]` events from event types and command handlers |
| 6 | Human review & persist | Confirmed artifacts written to `docs/ddd/phase-*.md`; spec inventory noted |

**Schema & behavior contract inventory note:** If Phase 5 schema files (proto/openapi/asyncapi/DDL) or Phase 6 behavior contracts (`docs/ddd/phase-6/`) exist, these are ACTIVE artifacts — do NOT attempt to rebuild them. Report their presence so [iterating-ddd](../iterating-ddd/SKILL.md) can trigger Merge mode in Steps 7-8.

## Ambiguity Handling

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

### Snapshot STOP Triggers

| Ambiguity | Why STOP |
|:---|:---|
| Package structure doesn't match any recognizable DDD layout | Cannot infer BC boundaries from non-standard structure — need human to explain organization |
| A directory could belong to two different Bounded Contexts | BC boundary assignment has high change cost — wrong assignment cascades to contracts and tech decisions |
| Cannot determine if a package is Core Domain vs Supporting | Strategic classification drives depth decisions in Phase 4 — guessing wrong wastes significant effort |
| Event types are absent or use generic names (`Event`, `Message`) | Cannot distinguish domain events from infrastructure events without domain context |

### Snapshot ASSUME & RECORD

| Ambiguity | Default assumption |
|:---|:---|
| Package naming suggests a BC name but doesn't match domain language exactly | ASSUME package name is the BC name; record for UL review |
| Adapter directory implies technology choice (e.g., `postgres/` → PostgreSQL) | ASSUME the directory name reflects the actual technology |
| A struct implements multiple interfaces | ASSUME each interface maps to one contract; record for human verification |
| No explicit event types but command handlers exist | ASSUME one event per command handler (happy path); record that failure/compensating events need human input |

### Orchestrator Mode Exception

When invoked by an orchestrator (`iterating-ddd`, `restructuring-ddd`) as a subagent, the snapshot process runs identically — all interactive checkpoints (Steps 1-6 human reviews) remain mandatory. The orchestrator controls the overall workflow; the snapshot skill controls the internal code scanning and human review cycle. No steps are skipped.

## Implementation (Interactive Code Reading Session)

**CRITICAL RULE:** Do NOT read archived documents (`docs/ddd/archive/`). Do NOT present archive as an option to the human ("Should I use the archive as a baseline?" is itself a violation — it frames archive as a legitimate alternative to code scanning, which it is not). Do NOT guess the project structure from memory. You must scan the actual code using Glob and Read tools, mark every inference with `[INFERRED]`, and present each rebuilt artifact for human review before persisting.

**Rebuild order is 2 → 3 → 4 → 1 (not 1 → 2 → 3 → 4).** When reading from code, BC boundaries (Phase 2) must be established first to distinguish domain events from infrastructure events (Phase 1). The pipeline's natural order assumes requirements as input; the snapshot's reverse order assumes code as input.

### Step 1: Detect Project Structure

Scan the codebase to identify the DDD layout pattern:

1. **Glob scan:** Search for common DDD directory patterns:
   - `internal/biz/*/`, `internal/domain/*/` (Go hexagonal)
   - `src/*/domain/`, `src/*/application/` (Java/TypeScript layered)
   - `pkg/*/`, `services/*/` (alternative Go layouts)
   - `**/aggregate/`, `**/entity/`, `**/valueobject/`, `**/port/`, `**/adapter/`

2. **Produce a directory map** showing each candidate Bounded Context directory and its sub-packages.

3. **Scan for existing schema files and behavior contracts:** Check if Phase 5 schema files (proto/, api/, events/, db/) or Phase 6 behavior contracts (`docs/ddd/phase-6/`) exist. List any found. Do NOT attempt to re-generate or rebuild — they are active artifacts managed by Phase 5/6 skills.

4. **STOP — present the directory map to the human:**

**Checkpoint:** "I detected the following project structure. Does this accurately represent your Bounded Context layout? Are there directories I missed or misidentified?"

If schema files or behavior contracts were found, add: "I also found existing schema files and/or Phase 6 behavior contracts. These will be used by Merge mode in the upcoming iteration."

If the human corrects the mapping, update before proceeding. If the structure is unrecognizable as DDD, STOP — this skill cannot proceed.

**Important:** Matching a glob pattern in step 1 does NOT mean the directory is a confirmed Bounded Context. Directories like `services/*/`, `pkg/*/`, or `modules/*/` may reflect technical grouping (by layer, by team, by deployment) rather than domain boundaries. The human checkpoint is mandatory regardless of how "obviously" the structure maps to DDD patterns. A `services/order/` directory with `logic.go`, `handlers/`, and `store/` MIGHT be an Order BC — or it might be a CRUD module with no domain boundary intent. Only the human knows.

### Step 2: Rebuild Phase 2 — Context Map

For each identified BC directory:

1. **Infer BC boundary** from the directory scope (what entities, aggregates, and value objects live inside).
2. **Infer strategic classification:**
   - **Core Domain:** High behavior density (many methods on aggregates), complex invariants, domain-specific types.
   - **Supporting:** Moderate behavior, serves Core Domain, fewer invariants.
   - **Generic:** Thin wrappers, standard CRUD, could be replaced by off-the-shelf.
3. **Infer relationships** from import graphs:
   - If Context A imports types from Context B's port interfaces → Upstream/Downstream relationship.
   - If cross-aggregate types exist in `domain/` root package (e.g., `enums.go`, `types.go`) → cross-context shared types.
   - If an anti-corruption layer adapter exists → ACL relationship.
4. **Infer Ubiquitous Language** from type names, method names, and constants within each BC.

Mark every inference. **Evidence MUST list specific files read with method/test counts.** Prose descriptions ("the order package has rich behavior") do NOT qualify as evidence.

```
[INFERRED: OrderContext is Core Domain]
  Evidence: read order.go (8 methods), item.go (3 methods), repository.go (1 interface), order_test.go (12 tests)
  Confidence: HIGH
  Verify: Is Order your Core Domain?
```

Confidence levels (determined by scanning coverage, not subjective judgment):
- **HIGH** → 3+ files scanned with method-level evidence. ASSUME & RECORD.
- **MEDIUM** → 1-2 files scanned. ASSUME & RECORD, but highlight at Final Review.
- **LOW** → No direct file scanning evidence, or evidence contradicts the inference. **STOP** — must confirm before proceeding.

**Checkpoint:** "Here is the reconstructed Context Map with all `[INFERRED]` markers. Please review each inference — especially any marked MEDIUM or LOW confidence."

### Step 3: Rebuild Phase 3 — Contracts

For each BC, scan for port interfaces and boundary structs:

1. **Port interfaces:** Files in `port/`, `ports/`, or interfaces named `*Port`, `*Service`, `*Repository`, `*Gateway`.
2. **Boundary structs/DTOs:** Types in `dto/`, `boundary/`, or types used as port method parameters/returns that are not domain entities.
3. **Cross-context contracts:** Imports between BC port packages indicate cross-context communication. For each, record:
   - Direction (which BC calls which)
   - Sync vs Async (method call vs event/message)
   - Data shape (the boundary struct)

Mark each contract with `[INFERRED]` using the same evidence format as Step 2 — list specific files read with counts. The same confidence thresholds apply (HIGH: 3+ files, MEDIUM: 1-2, LOW: STOP).

**Checkpoint:** "Here are the reconstructed interface contracts. Do these reflect your actual cross-context communication patterns?"

### Step 4: Rebuild Phase 4 — Technical Solution

For each BC, scan adapter directories to infer the 7 technical dimensions:

| Dimension | Where to Look |
|:---|:---|
| 1. Data Model & Persistence | `adapter/persistence/`, `adapter/repo/`, `*_repo.go`, ORM config files |
| 2. Interface Type | `adapter/http/`, `adapter/grpc/`, route definitions |
| 3. Consistency Strategy | Transaction usage, saga patterns, event sourcing markers |
| 4. External Dependencies | `adapter/*/` directories for third-party integrations |
| 5. Observability | Logging, metrics, tracing imports and middleware |
| 6. Error Handling | Error type definitions, error mapping layers |
| 7. Test Strategy | Test file patterns, test helper packages, mock directories |

For each dimension, record what was found and what was absent. Use the same evidence format as Step 2 — list specific files with counts. The same confidence thresholds apply (HIGH: 3+ files, MEDIUM: 1-2, LOW: STOP).

```
[INFERRED: OrderContext uses PostgreSQL for persistence]
  Evidence: read postgres/order_repo.go (4 methods), postgres/converter.go (2 funcs), sqlc.yaml (config)
  Confidence: HIGH

[INFERRED: OrderContext observability is UNKNOWN]
  Evidence: No observability adapter directory found, no logging imports in domain/
  Confidence: LOW — STOP
  Verify: What observability stack does OrderContext use?
```

**Checkpoint:** "Here are the reconstructed technical decisions. Dimensions marked UNKNOWN need your input."

### Step 5: Rebuild Phase 1 — Domain Events

Scan for event definitions and command handlers:

1. **Explicit events:** Types named `*Event`, `*Created`, `*Updated`, `*Cancelled`, `*Failed` in domain packages.
2. **Command handlers:** Functions/methods named `Handle*`, `Create*`, `Process*`, `Execute*` on aggregates or application services.
3. **For each event, infer:**
   - Command that triggers it
   - Actor (from handler context/auth parameters)
   - Happy path vs failure/compensating (from error paths in handlers)

**Important:** Infrastructure events (audit logs, CDC events, metric emissions) are NOT domain events. Only include events that represent business state transitions.

Mark each with `[INFERRED]` and evidence.

**Checkpoint:** "Here is the reconstructed domain events table. Are there business events missing that aren't reflected in the code yet?"

### Step 6: Human Review & Persist

1. Present a **consolidated summary** of all 4 rebuilt artifacts with their `[INFERRED]` markers.
2. Group by confidence: LOW items first (require confirmation), then MEDIUM, then HIGH.
3. The human reviews each `[INFERRED]` entry: ✅ Confirm | ✏️ Revise | ❌ Remove.
4. For any REVISED entry, update the artifact.
5. **Persist all confirmed artifacts** to `docs/ddd/`:
   - `docs/ddd/phase-1-domain-events.md` (from template: `../full-ddd/templates/phase-1-domain-events.md`)
   - `docs/ddd/phase-2-context-map.md` (from template: `../full-ddd/templates/phase-2-context-map.md`)
   - `docs/ddd/phase-3-contracts.md` (from template: `../full-ddd/templates/phase-3-contracts.md`)
   - `docs/ddd/phase-4-technical-solution.md` (from template: `../full-ddd/templates/phase-4-technical-solution.md`)
6. **This step is mandatory — do not skip even if the artifacts are already visible in the conversation.**

**Checkpoint:** "All snapshot artifacts have been persisted to `docs/ddd/`. Please verify the files exist before proceeding to iteration."

If schema files or behavior contracts were found: "**Note:** Existing schema files and/or Phase 6 behavior contracts detected. When [iterating-ddd](../iterating-ddd/SKILL.md) runs, Steps 7-8 (Schema Merge + Behavior Contracts Merge) will automatically reconcile new contracts with these existing artifacts."

**NEXT STEP:** Return to the caller. When invoked by [iterating-ddd](../iterating-ddd/SKILL.md), return snapshot artifacts and continue with Route evaluation. When invoked by [restructuring-ddd](../restructuring-ddd/SKILL.md), return to Step 2 (Human Review Snapshot).

### Loading Guidance

This skill reads Phase artifacts during rebuild — load per-step, not upfront:

- **Step 1**: Glob/Read project structure only. Do NOT read any `docs/ddd/` files yet.
- **Step 2 (rebuild Phase 2)**: read [snapshot-extraction-reference.md](./snapshot-extraction-reference.md) § Pattern Recognition: Bounded Contexts and § Evidence Standards.
- **Step 3-4 (rebuild Phase 3-4)**: read [snapshot-extraction-reference.md](./snapshot-extraction-reference.md) § Pattern Recognition: Contracts / Tech Decisions as needed.
- **Step 5 (rebuild Phase 1)**: read [snapshot-extraction-reference.md](./snapshot-extraction-reference.md) § Pattern Recognition: Domain Events.
- **Non-DDD codebase detected**: read [snapshot-extraction-reference.md](./snapshot-extraction-reference.md) § Strategies for Non-DDD Codebases.
- **Steps 2-4**: Read each Phase artifact as you rebuild it (Phase 2 context map, Phase 3 contracts, Phase 4 tech decisions). Do not preload all Phase files.
- **If existing Phase 5/6 files found**: Report presence, do NOT read or rebuild — they are active artifacts for Merge mode.
- **On first STOP/ASSUME decision**: read `../ddd-protocol/ambiguity-handling-reference.md`.

## Session Recovery

If a code scanning session is interrupted mid-snapshot:

1. Check if any `docs/ddd/phase-*.md` files already exist.
2. **If some exist:** Read them to determine which steps completed. Resume from the first missing artifact. Do NOT re-scan code for completed steps — the persisted artifacts are authoritative.
3. **If none exist:** Restart from

…

## 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-snapshotting-code-context
- 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%.
