Spec-Driven Development
Spec-Driven Development › Module 3: From Spec to Plan — Systematic Execution
Module 3: From Spec to Plan — Systematic Execution

Chapter 9: Architecting the `.plan.md` : Mapping File Impact and Systems

By Muhammad Riaz

The Bridge Between Intent and Execution

If a specification document (01-spec.md) represents the product manager’s or systems architect's intent—defining WHAT needs to be built and WHAT NOT to build—the Architecture Plan (02-plan.md) represents the engineering blueprint. It defines HOW the existing software system will physically adapt to satisfy that specification.

In traditional software development, developers often skip formal architectural planning for medium-sized features, holding the mental model of file edits, imports, and schema changes entirely in their heads.

However, AI agents do not possess a persistent mental model of your codebase.

When you instruct an AI coding agent to execute a task based solely on a high-level specification, the agent is forced to scan the entire project directory tree dynamically, guessing which files need modifications and which patterns to emulate. This leads directly to Context Rot and Architectural Contagion:

  • The AI modifies shared global files unnecessarily.

  • The AI creates duplicate utility functions in new directories because it failed to notice existing helpers buried elsewhere in the codebase.

  • The AI breaches structural boundaries by mixing presentation components with database ORM calls.

Architecting a production-grade 02-plan.md file solves this by constructing a deterministic execution blueprint. It translates human- readable specifications into concrete technical decisions, dependency mappings, and file-level boundaries before a single line of executable code is generated.

Anatomy of an Enterprise .plan.md

A production-grade 02-plan.md consists of five technical components designed to guide AI agents with total structural precision:

┌─────────────────────────────────────────────────────────────────────────────┐
│                      ANATOMY OF AN ARCHITECTURE PLAN                        │
│                                                                             │
│  1. TECHNICAL APPROACH OVERVIEW ──> Design patterns, choices, frameworks    │
│  2. THE FILE IMPACT MAP         ──> Strict Write, Read-Only, & Forbidden    │
│  3. SCHEMA & DATA FLOW CONTRACT ──> Exact DTOs, migrations, & interfaces    │
│  4. VERIFICATION STRATEGY       ──> Automated tests, manual sanity gates    │
│  5. RISK & ROLLBACK MATRIX      ──> Potential regressions & safeguards       │
└─────────────────────────────────────────────────────────────────────────────┘

1. Technical Approach Overview

The technical approach overview acts as an executive summary for AI agents and human code reviewers. It anchors the architectural design patterns, framework choices, and internal abstractions that the implementation must follow.

## Technical Approach & Architectural Pattern

- **Design Pattern:** Repository-Service-Controller pattern adhering to our standard NestJS module layout.

- **Data Transport:** Expose API via REST using standard NestJS decorators and Zod validation pipes.

- **State Strategy:** Asynchronous processing via BullMQ queue; Redis used for job deduplication.

- **Concurrency Control:** Optimistic locking via PostgreSQL `version` column on the `orders` table.

2. The File Impact Map: The AI's Physical Sandbox

The File Impact Map is the single most important section inside the 02-plan.md file. It functions as an explicit permission list that locks down the AI agent's file system read and write operations.

When an AI agent receives a plan with a strict File Impact Map, it is forbidden from creating or modifying files outside the designated write list.

## File Impact Map

### Files to Create (NEW):

- `src/modules/refunds/refunds.controller.ts` (API route endpoints)

- `src/modules/refunds/refunds.service.ts` (Core business logic & idempotency checks)

- `src/modules/refunds/dto/process-refund.dto.ts` (Zod schema & TypeScript DTO)

- `tests/unit/refunds.service.spec.ts` (Unit test coverage >= 95%)

### Files to Modify (EDIT):

- `src/modules/refunds/refunds.module.ts` (Register new controller and service)

- `src/app.module.ts` (Import `RefundsModule`)

### Read-Only Context Files (READ ONLY):

- `src/common/middleware/auth.middleware.ts` (To verify request context payload shape)

- `src/database/schema/orders.schema.ts` (To inspect existing ORM relations)

### Explicitly Forbidden Paths (DO NOT TOUCH):

- `src/common/core/*`

- `prisma/migrations/*`

- `package.json`

3. Schema & Data Flow Mapping

The data flow mapping section bridges database tables, application interfaces, and client responses. It ensures that the AI agent does not guess field names, column types, or transformation rules.

## Data Flow & Schema Mapping

### Request / Response Lifecycle
1. `HTTP POST /api/v1/refunds`
 ├── Handler: `RefundsController.processRefund`
 ├── Pipe: Validate request body against `ProcessRefundDTO`
 ├── Service: `RefundsService.execute`
 │    ├── Transaction BEGIN
 │    ├── Query: Fetch Order where `id = payload.orderId AND tenant_id = ctx.tenantId`
 │    ├── Assertion: Verify `order.status === 'COMPLETED'`
 │    ├── Mutate: Decrement user credit balance & insert refund record
 │    └── Transaction COMMIT
 └── Response: `202 Accepted` with payload `{ "refundId": "ref_123", "status": "QUEUED" }`

4. Verification & Testing Strategy

AI agents perform drastically better when instructed to write unit and integration tests in tandem with implementation code. The plan file explicitly dictates test file locations, test frameworks, and coverage gates.

## Verification Strategy

- **Unit Testing Framework:** Vitest

- **Target Coverage:** 100% path coverage on `refunds.service.ts`

- **Mandatory Mocking:** External Stripe payment gateway calls MUST be mocked using `vi.fn()` fixtures defined in `tests/fixtures/stripe.fixture.ts`. Real network requests during test runs are strictly prohibited.

- **Integration Test Gate:** `npm run test:integration -- --filter=refunds` MUST pass cleanly before task completion.

Generating the Plan using AI (The Plan Prompt)

In a mature Spec-Driven Development workflow, you do not write the entire 02-plan.md file manually from scratch. Instead, you instruct an AI assistant to inspect your repository context alongside your hardened 01-spec.md file and draft the architecture plan for your approval.

Execute this prompt against your AI coding tool:

# TASK: Generate Architecture Plan (`02-plan.md`)

Read `.specs/01-spec.md` and inspect our codebase directory structure.

Draft a comprehensive `.specs/02-plan.md` file that translates the specification into a concrete technical strategy.

CRITICAL REQUIREMENTS:
1. Conduct a complete codebase scan to identify all existing utilities, schemas, and helper functions that can be REUSED.
2. Construct an explicit File Impact Map listing:
 - Files to Create
 - Files to Edit
 - Read-Only Context Files
 - Forbidden Paths
3. Define exact data flow pipelines and DTO schemas.
4. DO NOT write implementation code in source files yet. Output ONLY the `02-plan.md` document for my human review.

Real-World Case Study: Preventing Global Middleware Corruption

To understand the real-world value of the File Impact Map inside 02-plan.md, consider an engineering team adding tenant authorization to a multi-tenant SaaS application.

Scenario without File Impact Map

  • The developer prompts the AI: "Implement tenant authorization checks for the new billing routes."

  • What the AI did: To be "helpful," the AI modified the global src/server.ts entry point, adding a global Express middleware that parsed headers across all app routes.

  • The Result: The global middleware broke public webhook callbacks and health check probes, causing widespread staging environment outages.

Scenario with SDD File Impact Map

  • The developer runs the plan generation prompt first. The resulting 02-plan.md includes:
   ### Files to Modify:
   - `src/modules/billing/billing.router.ts` (Attach `tenantAuthGuard` to billing router ONLY)
   ### Explicitly Forbidden Paths:
   - `src/server.ts`
   - `src/common/middleware/global.ts`
  • The Result: The AI agent mounted the authorization middleware exclusively onto the isolated billing sub-router. Global routes remained completely untouched, preventing side-effect regressions.

Practical Exercises: Drafting an Architecture Plan

  1. Map a Feature's File Impact: Select a feature you built recently. Write down a list of every file you created, modified, or read. Notice how clearly defining this list upfront restricts an AI model's operating environment.

  2. Generate a Plan File: Take a completed .spec.md file from Module 2. Run the Plan Generation Prompt using your AI coding assistant. Review the generated 02-plan.md file to see if the AI selected the correct internal design patterns and helper modules.

  3. Verify File Boundaries: Inspect the generated File Impact Map. Are there any shared global files listed under "Files to Modify" that should be moved to "Forbidden Paths"? Adjust the plan accordingly.

Next Steps

Once your 02-plan.md file is finalized and approved by a human engineer, you have a complete architectural design. However, feeding an entire architecture plan to an AI agent in one monolithic prompt still invites context rot and execution fatigue.

In Chapter 10, we will explore Deconstructing Features into Atomic Checklists ( .tasks.md ) —learning how to break complex technical plans down into tiny, single-responsibility execution steps that AI agents can complete and verify sequentially.