PROJECT 04

E-Commerce Cart

Complex domain: products, cart, checkout, payments โ€” story splitting and security

โฑ ~90 min ยท 3 Sprints ยท Advanced

What's New in This Project

๐Ÿ†• Building on Projects 01-03

Projects 01-03 had simple domains. E-commerce has interconnected concerns: inventory, pricing, cart state, checkout validation, payment processing. You'll split complex stories multiple times using different strategies, and run a full security audit before shipping payment code.

Roles You'll See in Action

RoleWhat they do in this projectWhen
๐Ÿ“‹ @poCreates stories, splits oversized epics using multiple strategies, accepts completed workStory creation, splitting, sprint review, acceptance
๐Ÿ—๏ธ @archEvaluates monolith vs modular monolith vs microservices, runs architecture health check after 3 sprintsBrainstorm, architecture audit
๐Ÿ›ก๏ธ @secSTRIDE threat model on checkout flow, OWASP Top 10 audit on payment code, validates security fixesSprint 3 security phase
๐Ÿ—„๏ธ @dbaDesigns products, carts, cart_items, orders, order_items schema with proper foreign keys and indexesSetup, each sprint as schema evolves
โŒจ๏ธ @devImplements features with TDD, refactors oversized modules using Tidy FirstImplementation, refactoring
๐Ÿ‘จโ€๐Ÿ’ป @leadReviews code quality, plans implementations, oversees refactoringCode review, story planning, refactor review
๐Ÿงช @qaVerifies Definition of Done across 10+ stories and 3 sprintsDoD verification
๐Ÿ”„ @smFacilitates 3 sprints, tracks velocity trends, mid-sprint status checks, flags at-risk storiesSprint ceremonies, status tracking

Phase 1: Project Setup + Architecture

E-commerce has more moving parts than a todo API. The architecture decision matters more here โ€” get it wrong and you'll pay for it across 3 sprints.

Step 1: Tell Claude what you want to build

๐Ÿ’ฌ You say

"I want to build an e-commerce cart system: product catalog, shopping cart, checkout, payment processing."

Step 2: Brainstorm the architecture โ€” /agile-explore-brainstorm

๐Ÿ’ฌ You type

/agile-explore-brainstorm I need an e-commerce system with product catalog, shopping cart, checkout, and payment processing. Needs to handle inventory, pricing, and order management. Should be maintainable across multiple sprints.

๐Ÿ—๏ธ @arch evaluates 3 architectural approaches โ€” this time the choice has real consequences because the domain is complex:

๐Ÿ—๏ธ @arch responds with a scoring matrix:

## /agile-explore-brainstorm โ€” Results

### Problem Statement
E-commerce cart system with catalog, cart, checkout, payments.
Constraints: maintainable across 3 sprints, clear module boundaries,
testable in isolation.

### Scoring Matrix

| Approach             | Feasibility | Maintainability | Performance | Risk | Total |
|----------------------|------------|-----------------|-------------|------|-------|
| Monolith (single module) | 9/10   | 5/10            | 8/10        | 7/10 | 29    |
| Modular Monolith     | 8/10       | 9/10            | 8/10        | 8/10 | 33    |
| Microservices        | 5/10       | 9/10            | 7/10        | 4/10 | 25    |

### Recommendation
Modular Monolith โ€” clear module boundaries (catalog, cart, checkout,
payment) but single deployable. Best balance of maintainability and
complexity for a solo developer.

### What Would Change This
- If team has 4+ devs โ†’ consider microservices
- If prototype/throwaway โ†’ plain monolith is fine
- If each module scales independently โ†’ microservices
โœ… You decide

"Let's go with the modular monolith. Clear boundaries but one deployment."

Step 3: Database schema design

๐Ÿ—„๏ธ @dba designs the initial schema before any code is written. E-commerce needs careful data modeling โ€” products, carts, and orders are interconnected:

๐Ÿ—„๏ธ @dba designs the schema:

## Initial Schema Design

### Tables

products
  id          INTEGER PRIMARY KEY
  name        TEXT NOT NULL
  description TEXT
  price       DECIMAL(10,2) NOT NULL
  stock       INTEGER NOT NULL DEFAULT 0
  category    TEXT
  created_at  DATETIME DEFAULT CURRENT_TIMESTAMP

carts
  id          INTEGER PRIMARY KEY
  session_id  TEXT UNIQUE NOT NULL
  created_at  DATETIME DEFAULT CURRENT_TIMESTAMP
  updated_at  DATETIME DEFAULT CURRENT_TIMESTAMP

cart_items
  id          INTEGER PRIMARY KEY
  cart_id     INTEGER NOT NULL โ†’ carts(id) ON DELETE CASCADE
  product_id  INTEGER NOT NULL โ†’ products(id)
  quantity    INTEGER NOT NULL DEFAULT 1
  UNIQUE(cart_id, product_id)

orders
  id          INTEGER PRIMARY KEY
  cart_id     INTEGER NOT NULL โ†’ carts(id)
  status      TEXT NOT NULL DEFAULT 'pending'
  total       DECIMAL(10,2) NOT NULL
  shipping_address TEXT NOT NULL
  created_at  DATETIME DEFAULT CURRENT_TIMESTAMP

order_items
  id          INTEGER PRIMARY KEY
  order_id    INTEGER NOT NULL โ†’ orders(id) ON DELETE CASCADE
  product_id  INTEGER NOT NULL โ†’ products(id)
  quantity    INTEGER NOT NULL
  unit_price  DECIMAL(10,2) NOT NULL

### Indexes
- idx_products_category ON products(category)
- idx_cart_items_cart ON cart_items(cart_id)
- idx_orders_status ON orders(status)

Step 4: Initialize the framework

/agile-setup-init       โ†’ Memory populated (project, architecture, conventions)
/agile-setup-onboard    โ†’ Coding rules generated from detected conventions
/agile-setup-health     โ†’ โœ… All checks pass

Phase 1 complete. Modular monolith architecture chosen, schema designed, framework initialized. Now we plan 3 sprints of work.

Phase 2: Sprint 1 โ€” Product Catalog (~10 pts)

Start with the foundation: products. No cart, no checkout โ€” just a solid catalog module.

Step 5: Create product catalog stories

๐Ÿ’ฌ You type

/agile-story-create I need CRUD endpoints for products: create a product with name, description, price, stock quantity, and category. Update and delete products. Return proper error codes.

๐Ÿ“‹ @po responds:

## /agile-story-create โ€” Story Created

### Story US-001
**As a** store administrator,
**I want** to create, read, update, and delete products,
**so that** I can manage the product catalog.

### Acceptance Criteria

**AC-1: Create product with all fields**
- **Given** the API is running
- **When** I send POST /products with name, description, price,
  stock, and category
- **Then** I receive 201 with the created product including an ID

**AC-2: Validation โ€” missing required fields**
- **Given** the API is running
- **When** I send POST /products without name or price
- **Then** I receive 400 with specific validation errors

**AC-3: Update product**
- **Given** a product exists with ID 1
- **When** I send PUT /products/1 with updated fields
- **Then** I receive 200 with the updated product

**AC-4: Delete product**
- **Given** a product exists with ID 1
- **When** I send DELETE /products/1
- **Then** I receive 204 and the product is removed

### INVEST Check: โœ… All criteria pass
### Metadata: 3 points | Status: Unrefined
๐Ÿ’ฌ /agile-story-create I need to search products by name
   and filter by category. Support pagination for large catalogs.

   โ†’ ๐Ÿ“‹ @po creates US-002: "Search and filter products" โ€” 5 pts

๐Ÿ’ฌ /agile-story-create I need to organize products into
   categories and list all available categories.

   โ†’ ๐Ÿ“‹ @po creates US-003: "Product categories" โ€” 2 pts

Step 6: Sprint 1 planning โ€” /agile-sprint-planning

๐Ÿ’ฌ You type

/agile-sprint-planning

๐Ÿ”„ @sm facilitates:

## Sprint Planning Output

### Sprint Goal
"Deliver a working product catalog with CRUD, search, and categories"

### Sprint Backlog
| Story  | Title                   | Points | Priority |
|--------|-------------------------|--------|----------|
| US-001 | Product CRUD            | 3      | P1       |
| US-002 | Search and filter       | 5      | P1       |
| US-003 | Product categories      | 2      | P2       |

### Capacity Check
- Team velocity (first sprint): 10 points (conservative)
- Committed this sprint: 10 points
- Capacity utilization: 100%

Step 7: Build Sprint 1 stories (abbreviated)

US-001: Product CRUD (3 pts)

/agile-code-branch feature US-001 product-crud
/agile-story-plan US-001
/agile-code-tdd US-001
  ๐Ÿ”ด Test: POST /products creates product โ†’ โŒ
  ๐ŸŸข Implement create handler with validation โ†’ โœ…
  ๐Ÿ”ด Test: POST /products without name returns 400 โ†’ โŒ
  ๐ŸŸข Add field validation โ†’ โœ…
  ๐Ÿ”ด Test: PUT /products/:id updates product โ†’ โŒ
  ๐ŸŸข Implement update handler โ†’ โœ…
  ๐Ÿ”ด Test: DELETE /products/:id removes product โ†’ โŒ
  ๐ŸŸข Implement delete handler โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green (8/8 tests passing)
/agile-code-commit       โ†’ feat(catalog): add product CRUD endpoints
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved (๐ŸŸก S2: extract validation to middleware)
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (3 points)

US-002: Search and filter products (5 pts)

/agile-code-branch feature US-002 product-search
/agile-story-plan US-002
/agile-code-tdd US-002
  ๐Ÿ”ด Test: GET /products?q=shirt returns matching products โ†’ โŒ
  ๐ŸŸข Implement text search with LIKE query โ†’ โœ…
  ๐Ÿ”ด Test: GET /products?category=electronics filters โ†’ โŒ
  ๐ŸŸข Add category filter to query builder โ†’ โœ…
  ๐Ÿ”ด Test: GET /products?page=2&limit=10 paginates โ†’ โŒ
  ๐ŸŸข Add pagination with offset/limit โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green
/agile-code-commit       โ†’ feat(catalog): add product search, filter, pagination
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (5 points)

US-003: Product categories (2 pts)

/agile-code-branch feature US-003 categories
/agile-story-plan US-003
/agile-code-tdd US-003
  ๐Ÿ”ด Test: GET /categories returns distinct categories โ†’ โŒ
  ๐ŸŸข Implement categories endpoint โ†’ โœ…
  ๐Ÿ”ด Test: GET /products?category=shoes filters correctly โ†’ โŒ
  ๐ŸŸข Verify integration with search filter โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green
/agile-code-commit       โ†’ feat(catalog): add category listing endpoint
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (2 points)

Step 8: Sprint 1 ceremonies (abbreviated)

/agile-sprint-review
  Sprint Goal: "Deliver a working product catalog" โ†’ โœ… Met
  Velocity: 10/10 points (100%)
  All 3 stories accepted.

/agile-sprint-retro
  What went well: clean module boundaries from day 1
  What to improve: need shared validation middleware
  Action: extract common validation before Sprint 2

/agile-memory-learn
  โ†’ Sprint 1 velocity baseline: 10 points

Phase 3: Sprint 2 โ€” Cart & Checkout (The Complex Sprint)

โš ๏ธ This is the KEY teaching phase

Sprint 2 introduces the hardest skill in agile: breaking down complex features into small, independent stories. You'll see what happens when a story is too big, and learn to split it using /agile-story-split with different strategies.

Step 9: Create the checkout story โ€” the oversized story

๐Ÿ’ฌ You type

/agile-story-create I need a complete checkout flow: add items to cart, update quantities, validate stock availability, calculate total with tax, collect shipping address, process payment

๐Ÿ“‹ @po creates the story โ€” but flags a serious problem:

๐Ÿ“‹ @po responds:

## /agile-story-create โ€” Story Created

### Story US-007
**As a** shopper,
**I want** to add items to my cart, manage quantities, validate
stock, calculate totals with tax, enter my shipping address,
and process payment,
**so that** I can purchase products from the store.

### Acceptance Criteria
AC-1: Add product to cart
AC-2: Update item quantity in cart
AC-3: Remove item from cart
AC-4: Validate stock availability before checkout
AC-5: Calculate total with tax
AC-6: Collect and validate shipping address
AC-7: Process payment and create order
AC-8: Reduce stock after successful payment
AC-9: Handle payment failure gracefully

### INVEST Check
| Criterion   | Status |
|-------------|--------|
| Independent | โœ…     |
| Negotiable  | โœ…     |
| Valuable    | โœ…     |
| Estimable   | โš ๏ธ     |
| Small       | โŒ FAIL |
| Testable    | โœ…     |

### Metadata
- **Estimate**: 21 points
- **Status**: Unrefined
- โš ๏ธ WARNING: This story violates the "Small" criterion.
  21 points is too large for a single sprint.
๐Ÿšซ 21 points is a mini-project, not a story

INVEST says stories must be Small. A 21-point story can't be estimated with confidence, can't be completed in one sprint, and can't be tested in isolation. This needs /agile-story-split.

Step 10: Split the story โ€” /agile-story-split with workflow-steps strategy

๐Ÿ’ฌ You type

/agile-story-split US-007 --strategy workflow-steps

๐Ÿ“‹ @po decomposes US-007 along the natural workflow: cart management โ†’ validation โ†’ checkout form โ†’ payment. Each step is independently valuable:

๐Ÿ“‹ @po responds:

## /agile-story-split โ€” Results

### Strategy: workflow-steps
Split along the user's natural workflow through checkout.

### Original Story
US-007: Complete checkout flow โ€” 21 points โŒ Too large

### Split Into

**US-007a: Cart management (add/remove/update quantities)**
- **As a** shopper, **I want** to add products to my cart,
  update quantities, and remove items,
  **so that** I can build my order before checking out.
- ACs: add item, update quantity, remove item, view cart
- **Estimate**: 5 points

**US-007b: Stock validation (check availability before checkout)**
- **As a** shopper, **I want** the system to verify items are
  in stock before I proceed to checkout,
  **so that** I don't pay for unavailable products.
- ACs: block checkout if out of stock, show availability warning
- **Estimate**: 3 points

**US-007c: Checkout form (shipping address, total with tax)**
- **As a** shopper, **I want** to enter my shipping address
  and see the order total including tax,
  **so that** I know exactly what I'm paying before confirming.
- ACs: address form validation, tax calculation, order summary
- **Estimate**: 5 points

**US-007d: Payment processing (charge card, create order)**
- **As a** shopper, **I want** to submit payment and receive
  an order confirmation,
  **so that** my purchase is completed.
- ACs: process payment, create order record, reduce stock,
  handle payment failure
- **Estimate**: 5 points

### INVEST Validation (each sub-story)
| Story   | I  | N  | V  | E  | S  | T  |
|---------|----|----|----|----|----|----|
| US-007a | โœ… | โœ… | โœ… | โœ… | โœ… | โœ… |
| US-007b | โœ… | โœ… | โœ… | โœ… | โœ… | โœ… |
| US-007c | โœ… | โœ… | โœ… | โœ… | โœ… | โœ… |
| US-007d | โœ… | โœ… | โœ… | โœ… | โš ๏ธ | โœ… |

### Note on US-007d
US-007d includes payment processing AND stock reduction AND
error handling โ€” still 5 points but at the upper boundary.
Consider splitting further if complexity grows during
implementation.
๐Ÿ’ก Why workflow-steps?

The workflow-steps strategy follows the user's natural journey: first they fill a cart, then they validate, then they checkout, then they pay. Each step delivers independent value โ€” a cart without checkout is still useful for "save for later" functionality. Other strategies (business-rules, data-variations) split differently. The right strategy depends on the domain.

Step 11: Sprint 2 planning โ€” /agile-sprint-planning

๐Ÿ’ฌ You type

/agile-sprint-planning

๐Ÿ”„ @sm facilitates:

## Sprint Planning Output

### Sprint Goal
"Deliver cart management and checkout โ€” from add-to-cart to payment"

### Sprint Backlog
| Story   | Title                         | Points | Priority |
|---------|-------------------------------|--------|----------|
| US-007a | Cart management               | 5      | P1       |
| US-007b | Stock validation              | 3      | P1       |
| US-007c | Checkout form + tax           | 5      | P1       |
| US-007d | Payment processing            | 5      | P2       |

### Capacity Check
- Historical velocity: 10 points (Sprint 1)
- Committed this sprint: 18 points
- Capacity utilization: 180% โš ๏ธ OVER-COMMITTED

### Risk Mitigation
- US-007d marked P2 โ€” can be deferred to Sprint 3 if needed
- Core flow (US-007a โ†’ US-007c) is 13 points โ€” within reach

Step 12: Build US-007a โ€” Cart Management (5 pts)

๐Ÿ—„๏ธ @dba designs the cart_items table with proper foreign keys before implementation begins:

๐Ÿ—„๏ธ @dba validates schema for cart module:

cart_items table:
  - cart_id FK โ†’ carts(id) ON DELETE CASCADE
  - product_id FK โ†’ products(id) โ€” no cascade (preserve history)
  - UNIQUE(cart_id, product_id) โ€” prevents duplicate entries
  - quantity CHECK(quantity > 0) โ€” no zero-quantity items

Index: idx_cart_items_cart_product ON cart_items(cart_id, product_id)
โ†’ Covers the most common query pattern
/agile-code-branch feature US-007a cart-management
/agile-story-plan US-007a
/agile-code-tdd US-007a
  ๐Ÿ”ด Test: POST /cart/items adds product to cart โ†’ โŒ
  ๐ŸŸข Implement add-to-cart with cart creation โ†’ โœ…
  ๐Ÿ”ด Test: PUT /cart/items/:id updates quantity โ†’ โŒ
  ๐ŸŸข Implement quantity update โ†’ โœ…
  ๐Ÿ”ด Test: DELETE /cart/items/:id removes item โ†’ โŒ
  ๐ŸŸข Implement remove from cart โ†’ โœ…
  ๐Ÿ”ด Test: GET /cart returns all items with subtotals โ†’ โŒ
  ๐ŸŸข Implement cart summary with price calculation โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green (12/12 tests)
/agile-code-commit       โ†’ feat(cart): add cart management endpoints
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (5 points)

Step 13: Mid-sprint status โ€” /agile-sprint-status

๐Ÿ’ฌ You type

/agile-sprint-status

๐Ÿ”„ @sm provides a real-time dashboard of sprint progress:

๐Ÿ”„ @sm responds:

## /agile-sprint-status โ€” Sprint 2 Dashboard

### Burndown
Day 1: โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ 18 pts remaining
Day 2: โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ 13 pts remaining  (US-007a done)
Day 3: โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ 10 pts remaining     โ† YOU ARE HERE

### Stories by Status
| Story   | Title                  | Points | Status       |
|---------|------------------------|--------|--------------|
| US-007a | Cart management        | 5      | โœ… Accepted   |
| US-007b | Stock validation       | 3      | ๐Ÿ”จ In Progress|
| US-007c | Checkout form + tax    | 5      | ๐Ÿ“‹ To Do     |
| US-007d | Payment processing     | 5      | ๐Ÿ“‹ To Do     |

### Velocity Tracking
- Completed: 5/18 points (28%)
- Sprint progress: 50% of time elapsed
- Projected: ~14 points by sprint end

### Blockers
โš ๏ธ US-007d at risk โ€” may not fit in this sprint.
   Recommendation: focus on US-007b and US-007c first.
   Defer US-007d to Sprint 3 if needed.

Step 14: Build remaining Sprint 2 stories (abbreviated)

US-007b: Stock validation (3 pts)

/agile-code-branch feature US-007b stock-validation
/agile-story-plan US-007b
/agile-code-tdd US-007b
  ๐Ÿ”ด Test: checkout blocked when item out of stock โ†’ โŒ
  ๐ŸŸข Add stock check before checkout proceeds โ†’ โœ…
  ๐Ÿ”ด Test: warning shown when stock is low โ†’ โŒ
  ๐ŸŸข Add low-stock threshold check โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green
/agile-code-commit       โ†’ feat(cart): add stock validation on checkout
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (3 points)

US-007c: Checkout form + tax calculation (5 pts)

/agile-code-branch feature US-007c checkout-form
/agile-story-plan US-007c
/agile-code-tdd US-007c
  ๐Ÿ”ด Test: POST /checkout validates shipping address โ†’ โŒ
  ๐ŸŸข Add address validation (required fields) โ†’ โœ…
  ๐Ÿ”ด Test: checkout calculates tax correctly โ†’ โŒ
  ๐ŸŸข Implement tax calculation by region โ†’ โœ…
  ๐Ÿ”ด Test: order summary shows items + tax + total โ†’ โŒ
  ๐ŸŸข Build order summary endpoint โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green
/agile-code-commit       โ†’ feat(checkout): add checkout form with tax calculation
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved
  (๐ŸŸก S2: tax rates should come from config, not hardcoded)
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (5 points)

US-007d: Payment processing (5 pts) โ€” deferred

๐Ÿ”„ @sm: US-007d deferred to Sprint 3.
  Sprint 2 committed 18 points but velocity is 10.
  Core checkout flow (US-007aโ€“c) complete at 13 points.
  Payment processing moves to Sprint 3 alongside security work.

Step 15: Sprint 2 ceremonies

๐Ÿ’ฌ You type

/agile-sprint-review

## Sprint Review Report

### Sprint Goal: "Deliver cart management and checkout"
### Sprint Goal Met: โš ๏ธ Partial โ€” cart + checkout delivered,
                        payment deferred to Sprint 3

| Story   | Title                  | Points | Status      |
|---------|------------------------|--------|-------------|
| US-007a | Cart management        | 5      | โœ… Accepted  |
| US-007b | Stock validation       | 3      | โœ… Accepted  |
| US-007c | Checkout form + tax    | 5      | โœ… Accepted  |
| US-007d | Payment processing     | 5      | โณ Deferred  |

### Velocity
- Committed: 18 points
- Completed: 13 points (72%)
- Running average: (10 + 13) / 2 = 11.5 points
/agile-sprint-retro
  What went well: story splitting prevented a 21-point disaster
  What to improve: over-committed by 80% โ€” use velocity data
  Action: Sprint 3 commit to โ‰ค12 points

/agile-memory-learn
  โ†’ Sprint 2 velocity: 13 points
  โ†’ Lesson: workflow-steps splitting worked well for checkout

Phase 4: Sprint 3 โ€” Security + Polish

Sprint 3 completes the payment flow and then hardens everything. Payment code without security review is a liability.

Step 16: Build US-007d โ€” Payment Processing (5 pts)

/agile-code-branch feature US-007d payment-processing
/agile-story-plan US-007d
/agile-code-tdd US-007d
  ๐Ÿ”ด Test: POST /checkout/pay processes payment โ†’ โŒ
  ๐ŸŸข Implement payment gateway integration โ†’ โœ…
  ๐Ÿ”ด Test: successful payment creates order record โ†’ โŒ
  ๐ŸŸข Create order + order_items on success โ†’ โœ…
  ๐Ÿ”ด Test: successful payment reduces stock โ†’ โŒ
  ๐ŸŸข Decrement product stock after payment โ†’ โœ…
  ๐Ÿ”ด Test: payment failure returns error, no order created โ†’ โŒ
  ๐ŸŸข Add transaction rollback on failure โ†’ โœ…
/agile-code-ci           โ†’ โœ… All green (24/24 tests)
/agile-code-commit       โ†’ feat(payment): add payment processing with order creation
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved
/agile-code-merge        โ†’ Squash merged to develop
/agile-story-dod         โ†’ โœ… DONE
/agile-story-accept      โ†’ โœ… ACCEPTED (5 points)

Step 17: Threat modeling โ€” /agile-security-threat-model (STRIDE)

Before shipping payment code, ๐Ÿ›ก๏ธ @sec analyzes the attack surface using the STRIDE framework.

๐Ÿ’ฌ You type

/agile-security-threat-model Analyze the checkout and payment flow for security threats

๐Ÿ›ก๏ธ @sec responds:

## /agile-security-threat-model โ€” STRIDE Analysis

### Scope: Checkout and Payment Flow
Components analyzed: cart โ†’ stock validation โ†’ checkout form โ†’
payment processing โ†’ order creation

### STRIDE Threat Table

| Category             | Threat                        | Risk   | Mitigation                      |
|----------------------|-------------------------------|--------|---------------------------------|
| **S**poofing         | Fake user places order        | ๐ŸŸ  Med | Session validation, CSRF tokens |
|                      | with someone else's cart       |        |                                 |
| **T**ampering        | Price manipulated client-side | ๐Ÿ”ด High| Server-side price calculation   |
|                      | before payment submission      |        |                                 |
| **R**epudiation      | User denies placing order     | ๐ŸŸก Low | Audit log with timestamps       |
| **I**nfo Disclosure  | Payment data leaked in logs   | ๐Ÿ”ด High| Never log card numbers,         |
|                      | or error messages              |        | mask in responses               |
| **D**enial of Service| Cart bombing โ€” thousands      | ๐ŸŸ  Med | Rate limiting on cart/checkout   |
|                      | of items added via script      |        | endpoints                       |
| **E**levation of     | Regular user accesses admin   | ๐ŸŸ  Med | Role-based access control on    |
| Privilege            | product management endpoints   |        | product CRUD                    |

### Priority Actions
1. ๐Ÿ”ด Verify price is calculated server-side (not from client)
2. ๐Ÿ”ด Ensure payment data is never logged
3. ๐ŸŸ  Add rate limiting to checkout endpoints
4. ๐ŸŸ  Implement CSRF protection
5. ๐ŸŸก Add audit logging for orders

Step 18: Security audit โ€” /agile-security-audit (OWASP Top 10)

๐Ÿ’ฌ You type

/agile-security-audit Scan the payment and checkout code

๐Ÿ›ก๏ธ @sec scans the codebase against the OWASP Top 10 and finds real vulnerabilities:

๐Ÿ›ก๏ธ @sec responds:

## /agile-security-audit โ€” OWASP Top 10 Scan

### Scope: src/modules/checkout/, src/modules/payment/

### Findings

๐Ÿ”ด S0 โ€” CRITICAL: Price calculated client-side
  File: src/modules/checkout/checkoutHandler.js:42
  Issue: Total is taken from request body (req.body.total)
         instead of calculated from cart_items ร— product prices.
  Risk: Attacker can submit total: 0.01 for a $500 order.
  Fix: Calculate total server-side from DB prices. Never trust
       client-submitted totals.
  OWASP: A04 โ€” Insecure Design

๐ŸŸ  S1 โ€” HIGH: SQL injection in product search
  File: src/modules/catalog/searchHandler.js:18
  Issue: Query uses string concatenation:
         `WHERE name LIKE '%${req.query.q}%'`
  Risk: Attacker can extract or modify database contents.
  Fix: Use parameterized queries:
       `WHERE name LIKE ?` with `%${q}%` as parameter.
  OWASP: A03 โ€” Injection

๐ŸŸก S2 โ€” MEDIUM: No rate limiting on checkout endpoint
  File: src/modules/checkout/routes.js
  Issue: POST /checkout has no rate limiting.
  Risk: Automated scripts can spam checkout attempts.
  Fix: Add express-rate-limit middleware (e.g., 5 req/min).
  OWASP: A05 โ€” Security Misconfiguration

### Summary
| Severity | Count | Action Required         |
|----------|-------|-------------------------|
| ๐Ÿ”ด S0   | 1     | MUST FIX before release |
| ๐ŸŸ  S1   | 1     | MUST FIX before release |
| ๐ŸŸก S2   | 1     | Should fix              |
| ๐Ÿ”ต S3   | 0     | โ€”                       |

### Verdict: โŒ BLOCKED โ€” 2 critical/high findings must be fixed

Step 19: Fix security findings with TDD

Security fixes get the same TDD treatment as features. Write a test that exploits the vulnerability, then fix it.

Fix S0: Server-side price calculation

๐Ÿ”ด RED โ€” Write test that exploits the vulnerability
test('POST /checkout/pay ignores client-submitted total', async () => {
  // Add item worth $50.00 to cart
  await addToCart(cart.id, product.id, 1);

  const res = await request(app)
    .post('/checkout/pay')
    .send({ total: 0.01, shippingAddress: validAddress });

  // Should charge $50.00 + tax, NOT $0.01
  expect(res.body.total).toBeCloseTo(53.50); // $50 + 7% tax
});

// Result: โŒ FAIL โ€” currently accepts client total of $0.01

๐ŸŸข GREEN โ€” Calculate total server-side
// checkoutHandler.js โ€” FIXED
const cartItems = db.getCartItems(cartId);
const subtotal = cartItems.reduce(
  (sum, item) => sum + (item.price * item.quantity), 0
);
const tax = subtotal * TAX_RATE;
const total = subtotal + tax;
// NEVER use req.body.total

// Result: โœ… PASS โ€” attacker's $0.01 is ignored

Fix S1: Parameterized queries

๐Ÿ”ด RED โ€” Write test that attempts SQL injection
test('GET /products?q= handles SQL injection safely', async () => {
  const res = await request(app)
    .get("/products?q=' OR 1=1 --");

  expect(res.status).toBe(200);
  expect(res.body.length).toBe(0); // No results, not all rows
});

// Result: โŒ FAIL โ€” returns ALL products (injection works!)

๐ŸŸข GREEN โ€” Switch to parameterized query
// searchHandler.js โ€” FIXED
const products = db.prepare(
  'SELECT * FROM products WHERE name LIKE ?'
).all(`%${q}%`);

// Result: โœ… PASS โ€” injection attempt returns empty results
/agile-code-ci           โ†’ โœ… All green (28/28 tests)
/agile-code-commit       โ†’ fix(security): server-side pricing, parameterized queries
/agile-code-pr           โ†’ PR created
/agile-code-pr-review    โ†’ โœ… Approved by ๐Ÿ‘จโ€๐Ÿ’ป @lead and ๐Ÿ›ก๏ธ @sec

Re-audit after fixes

๐Ÿ’ฌ You type

/agile-security-audit Re-scan after security fixes

๐Ÿ›ก๏ธ @sec: Re-audit Results

| Finding | Previous | Current | Status     |
|---------|----------|---------|------------|
| S0      | ๐Ÿ”ด Open  | โœ… Fixed | Server-side pricing verified |
| S1      | ๐ŸŸ  Open  | โœ… Fixed | Parameterized queries confirmed |
| S2      | ๐ŸŸก Open  | ๐ŸŸก Open | Rate limiting โ€” deferred to backlog |

### Verdict: โœ… PASSED โ€” No S0/S1 findings remaining

Step 20: Code refactoring โ€” /agile-code-refactor

After 3 sprints, the checkout module has grown organically. Time to clean up.

๐Ÿ’ฌ You type

/agile-code-refactor The checkout module has grown to 400 lines. Apply Tidy First to break it down.

โŒจ๏ธ @dev responds:

## /agile-code-refactor โ€” Tidy First Analysis

### Current State
src/modules/checkout/checkoutHandler.js โ€” 400 lines
Responsibilities: cart logic, validation, tax calculation,
payment processing, order creation, stock management

### Violations
- Single Responsibility: 6 concerns in one file
- God Object: handler knows about cart, products, orders,
  payments, tax, AND stock
- Hard to test: each test needs full checkout context

### Refactoring Plan (Tidy First)

Step 1: Extract CartService
  โ†’ addItem(), removeItem(), getCart(), calculateSubtotal()
  โ†’ 85 lines extracted

Step 2: Extract CheckoutValidator
  โ†’ validateStock(), validateAddress(), validateCart()
  โ†’ 60 lines extracted

Step 3: Extract PaymentGateway
  โ†’ processPayment(), handleFailure(), createRefund()
  โ†’ 70 lines extracted

### Before/After Metrics
| Metric                | Before | After  |
|-----------------------|--------|--------|
| Largest file (lines)  | 400    | 120    |
| Number of modules     | 1      | 4      |
| Avg cyclomatic complexity | 12 | 4      |
| Test isolation         | Poor   | Strong |

All existing tests pass after refactoring โœ…
No behavior changes โ€” purely structural improvement.

Step 21: Architecture health check โ€” /agile-explore-audit

๐Ÿ’ฌ You type

/agile-explore-audit scope=architecture Check overall architecture health after 3 sprints

๐Ÿ—๏ธ @arch responds:

## /agile-explore-audit โ€” Architecture Health Report

### Module Coupling Analysis
| Module     | Dependencies            | Coupling |
|------------|-------------------------|----------|
| catalog    | (none โ€” independent)    | โœ… Low    |
| cart       | catalog (reads prices)  | โœ… Low    |
| checkout   | cart, catalog           | ๐ŸŸก Medium|
| payment    | checkout (via interface) | โœ… Low    |

### Dependency Graph
catalog โ† cart โ† checkout โ†’ payment
                     โ†“
                   orders

### Patterns Detected
โœ… Repository pattern for DB access
โœ… Service layer separation after refactor
โœ… Interface-based payment gateway (swappable)
โš ๏ธ Checkout still has direct dependency on cart internals

### Recommendations
1. Introduce cart interface to decouple checkout โ†’ cart
2. Consider event-driven pattern for stock updates
3. Overall: healthy modular monolith โ€” boundaries are clear

### Health Score: 8/10

Step 22: Sprint 3 ceremonies

๐Ÿ’ฌ You type

/agile-sprint-review

## Sprint Review Report

### Sprint Goal: "Complete payment flow, security audit, refactoring"
### Sprint Goal Met: โœ… Yes

| Story/Task       | Points | Status      |
|------------------|--------|-------------|
| US-007d Payment  | 5      | โœ… Accepted  |
| Security fixes   | 3      | โœ… Accepted  |
| Code refactoring | 2      | โœ… Accepted  |

### Velocity
- Sprint 1: 10 points
- Sprint 2: 13 points
- Sprint 3: 10 points
- Average velocity: 11 points
/agile-sprint-retro
  What went well: STRIDE caught price tampering before it shipped,
    refactoring improved testability significantly
  What to improve: security audit should happen earlier in the project
  Action: in future projects, run threat model during Sprint 1

/agile-memory-learn
  โ†’ Sprint 3 velocity: 10 points
  โ†’ Lesson: security audit found 2 critical issues that would
    have shipped without it

Phase 5: Release

Step 23: Changelog, release, deploy

## /agile-ship-changelog โ€” v1.0.0

### Added
- Product catalog with CRUD, search, filter, categories (US-001โ€“003)
- Shopping cart: add, remove, update quantities (US-007a)
- Stock validation before checkout (US-007b)
- Checkout with shipping address and tax calculation (US-007c)
- Payment processing with order creation (US-007d)

### Security
- Server-side price calculation (prevents price tampering)
- Parameterized queries (prevents SQL injection)
- STRIDE threat model documented
- OWASP Top 10 audit passed (0 S0/S1 findings)

### Improved
- Checkout module refactored: CartService, CheckoutValidator,
  PaymentGateway extracted (400 โ†’ 120 lines)
/agile-ship-release
  ๐Ÿš€ @devops: Release v1.0.0
    Branch: release/v1.0.0 from develop
    CI: โœ… Green (28 tests passing)
    Merged to main โœ…
    Tagged: v1.0.0 โœ…
    Back-merged to develop โœ…

/agile-ship-deploy
  ๐Ÿš€ @devops: Deployed v1.0.0
    Smoke tests: โœ… All endpoints responding
    Security scan: โœ… No vulnerabilities
    Health check: โœ…

What You Built

MetricValue
Sprints completed3
Stories completed7 (US-001โ€“003, US-007aโ€“d)
Story points delivered33
Average velocity11 points/sprint
Security findings fixed2 critical (S0 + S1)
Threat modelSTRIDE โ€” 6 threats identified
Release versionv1.0.0
Architecture health8/10
Roles involved@po, @arch, @sec, @dba, @dev, @lead, @qa, @sm

The Story Splitting Pattern

This project taught the most important skill for complex domains:

๐Ÿšซ
Too Big21-point story
โœ‚๏ธ
Split/agile-story-split
โœ…
INVESTEach story passes
๐Ÿƒ
SprintBuild incrementally
๐Ÿ›ก๏ธ
Threat Model/agile-security-threat-model
๐Ÿ”
Audit/agile-security-audit
๐Ÿ”ง
Fix + TDDTest the exploit first
๐Ÿš€
Ship SecureRe-audit passes

New Commands vs Projects 01-03

CommandWhat it doesWhen to use
โœ… /agile-story-splitDecomposes oversized stories using strategies (workflow-steps, business-rules, data-variations)When a story estimate exceeds 8 points or fails INVEST "Small"
โœ… /agile-security-threat-modelSTRIDE analysis of attack surface โ€” identifies spoofing, tampering, info disclosure, etc.Before shipping code that handles sensitive data (auth, payments)
โœ… /agile-security-auditOWASP Top 10 scan โ€” finds injection, broken auth, insecure design, misconfigurationsBefore any release that includes security-sensitive code
โœ… /agile-code-refactorApplies Tidy First to break down oversized modules โ€” extract services, reduce complexityWhen a module grows beyond ~200 lines or has multiple responsibilities
โœ… /agile-explore-auditArchitecture health check โ€” coupling analysis, dependency graph, pattern complianceAfter multiple sprints to verify architecture hasn't degraded
โœ… Key Takeaway

Complex domains need disciplined decomposition. A 21-point story is not a failure โ€” it's a signal to split. The framework's splitting strategies (workflow-steps, business-rules, data-variations) turn overwhelming features into manageable increments.

Security is not optional for payment code. The STRIDE threat model identifies categories of attack; the OWASP audit finds specific vulnerabilities in your code. Together they caught price tampering and SQL injection that would have shipped without review.

๐Ÿง  Knowledge Check

A story is estimated at 21 points. What should you do?

๐Ÿง  Knowledge Check

The security audit finds that the checkout total comes from req.body.total (client-submitted). Why is this a critical (S0) finding?

๐Ÿง  Knowledge Check

What is the difference between /agile-security-threat-model and /agile-security-audit?