Skip to content
MrLagavPublic

About

A todo app using the bmad spec driven development

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

TodoApp

A full-stack todo application built with React + FastAPI + PostgreSQL - developed end-to-end using the BMad AI agent framework and Claude Code as the AI pair programmer.

Stack

Layer Technology
Frontend React 19, TypeScript, Vite, TanStack Query 5, dnd-kit
Backend FastAPI 0.136, SQLModel, SQLAlchemy 2 (async), Alembic
Database PostgreSQL 16
Infrastructure Docker Compose
Testing (Frontend) Jest + React Testing Library + jest-axe + Playwright
Testing (Backend) pytest + pytest-asyncio + HTTPX

Features

  • Create, edit, complete, delete todos with optimistic UI updates
  • Drag-and-drop reordering with keyboard accessibility (dnd-kit)
  • Bulk clear completed todos
  • Persistent order stored in the database
  • WCAG 2.1 AA compliant - Lighthouse accessibility score 100/100
  • Zero known security vulnerabilities in all dependencies
  • ≥ 80% test coverage on core business logic

Quickstart

cp .env.example .env
docker compose up
Service URL
Frontend http://localhost:5173
Backend API http://localhost:8000
API Docs (Swagger) http://localhost:8000/docs

All three containers (frontend, backend, db) report healthy on startup. Alembic migrations run automatically before the API accepts requests.

Environment Variables

Copy .env.example to .env before running. All configuration is environment-driven - no hardcoded values in code.

cp .env.example .env

See .env.example for the full list of variables with descriptions.

Local Development (without Docker)

Backend

Requires Python 3.11+ and a running PostgreSQL instance.

cd backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
export DATABASE_URL=postgresql+asyncpg://todoapp:todoapp@localhost:5432/todoapp
uvicorn app.main:app --reload

Migrations run automatically on startup via the FastAPI lifespan hook.

Frontend

Requires Node 20+.

cd frontend
npm install
npm run dev

Set VITE_API_URL in .env to point to the backend (default: http://localhost:8000).

Testing

Backend (unit + integration)

# Start isolated test database
docker compose --profile test up db-test -d

# Run all backend tests with coverage
cd backend
uv run pytest --cov=app --cov-report=term-missing

# Or with plain pytest
pytest

The test database runs on port 5433, independent of the dev database on 5432.

Frontend (unit + axe accessibility)

cd frontend
npm test                  # Jest + RTL + jest-axe
npm run test:coverage     # With coverage report (≥ 80% threshold enforced)

E2E (Playwright)

# Full stack must be running (docker compose up)
cd frontend
npm run test:e2e          # 19 Playwright tests across all user flows

Quality Metrics

Metric Result
Backend test coverage 100% (services + routers)
Frontend branch coverage 81.75% (threshold: 80%)
Playwright E2E tests 19 passing
axe-core WCAG 2.1 AA 0 violations
Lighthouse accessibility 100 / 100
API response time (local) < 10ms avg (target: < 200ms)
npm vulnerabilities 0 high/critical
pip vulnerabilities 0 (post-remediation)

Project Structure

.
├── backend/
│   ├── app/
│   │   ├── core/           # config, async DB engine + session
│   │   ├── models/         # SQLModel table classes (Todo)
│   │   ├── routers/        # FastAPI route handlers
│   │   ├── schemas/        # Pydantic request/response schemas
│   │   ├── services/       # business logic
│   │   └── main.py         # FastAPI app, CORS, lifespan auto-migrate
│   ├── alembic/            # DB migrations
│   ├── tests/
│   │   ├── conftest.py     # async pytest fixtures (NullPool, per-test schema reset)
│   │   ├── test_todo_router.py
│   │   └── test_todo_service.py
│   ├── pyproject.toml      # pytest + coverage config
│   └── requirements.txt
├── frontend/
│   ├── src/
│   │   ├── api/            # single Axios instance + typed API functions
│   │   ├── components/     # AddTodo, TodoList, TodoItem, BulkActions, common/*
│   │   ├── hooks/          # useTodos, useCreateTodo, useUpdateTodo, useDeleteTodo,
│   │   │                   #   useBulkDelete, useDragReorder
│   │   └── types/          # Todo, CreateTodoPayload, UpdateTodoPayload
│   ├── e2e/                # Playwright specs + accessibility.spec.ts
│   ├── playwright.config.ts
│   └── jest.config.ts
├── _bmad-output/
│   └── implementation-artifacts/
│       ├── coverage-report.md
│       ├── accessibility-audit.md
│       ├── performance-report.md
│       └── security-review.md
├── docker-compose.yml
└── .env.example

Useful Commands

# View logs
docker compose logs -f backend

# Reset database (destroy volume, re-run migrations)
docker compose down -v && docker compose up

# Run Alembic migrations manually (inside backend container)
docker exec -it bmad_todoapp-backend-1 alembic upgrade head

# Check migration history
docker exec -it bmad_todoapp-backend-1 alembic history

# Inspect the todos table
docker exec -it bmad_todoapp-db-1 psql -U todoapp -d todoapp -c "\d todos"

# Start isolated test DB and run backend tests
docker compose --profile test up db-test -d
cd backend && uv run pytest

# Run Playwright E2E tests
cd frontend && npm run test:e2e

# Run axe accessibility audit (Playwright)
cd frontend && npm run test:e2e -- --grep "Accessibility"

AI Integration Documentation

This project was built using the BMad (Background Multi-Agent Development) framework with Claude Code (claude-opus-4-8) as the primary AI agent. The following documents how AI was used across all development phases.

Overview

Phase Approach
Planning BMad agents (PM, Architect, Analyst) created PRD, epics, architecture, and per-story specs
Implementation bmad-dev-story skill executed each story: red-green-refactor, tests, browser verification
Quality axe-core, Playwright E2E, coverage measurement, performance profiling, security audit

All implementation was AI-driven, with the human directing story selection and reviewing results. The human intervened on 4 occasions to correct course (documented below).


BMad Framework

BMad (Background Multi-Agent Development) is an AI-native development framework that structures work through:

  • Planning Artifacts - PRD, epics, architecture, per-story specs with complete code blueprints
  • Skills - reusable workflows like bmad-dev-story, bmad-create-story, bmad-code-review
  • Agent Personas - specialist agents (PM "John", Architect "Winston", Developer "Amelia")

The key insight: each story file contains complete Dev Notes with full code for every file, making the AI implementation agent largely deterministic. The AI reads the spec, follows the red-green-refactor cycle, runs tests, fixes failures, and marks tasks complete.

Story execution flow per story:

  1. Read story file (tasks + Dev Notes with complete code blueprints)
  2. Mark in-progress → implement → write tests → run tests → fix failures
  3. Browser verification via Chrome DevTools MCP
  4. Mark complete + update story file with findings

MCP Servers Used

1. chrome-devtools MCP - Most Used

What it is: Chrome DevTools Protocol via MCP - gives the AI direct browser access.

How it was configured:

claude mcp add chrome-devtools -s user -- npx -y chrome-devtools-mcp@latest

Tools used:

Tool Purpose
navigate_page Load app at http://localhost:5173
take_snapshot Read the a11y tree (faster + more reliable than screenshots for logic)
list_console_messages Verify zero JS errors after each story
list_network_requests Confirm correct API calls fired (POST, PATCH, DELETE)
click / fill / press_key Interact with the app to verify features
lighthouse_audit Accessibility score (100/100), best practices
resize_page Test 375px mobile viewport for responsive design
evaluate_script Run window.performance API for load timing

Key verifications it enabled:

  • Confirmed optimistic update for Create, Complete, Delete, Drag reorder all worked in-browser before marking stories done
  • Verified aria-live region announced "1 active todo" after adding
  • Confirmed WCAG AA violation (color contrast 2.53:1) via axe-core before the fix
  • Measured First Contentful Paint (100ms) with 20 todos loaded
  • Tab-cycled through all 7 interactive elements to verify keyboard navigation order

Note: Chrome DevTools MCP was not installed at the start of the session. It was configured mid-project when the AI attempted to use the chrome-devtools skill and discovered it wasn't registered. After claude mcp add chrome-devtools and a Claude restart, it became available.

2. ckreiling-mcp-server-docker MCP

What it is: Docker container management via MCP.

How it helped:

  • list_containers - verified all 3 services healthy before browser tests
  • fetch_container_logs - read backend logs when diagnosing the Alembic asyncio event loop conflict (Story 1.3)

Agent Usage - Which Tasks Used AI and What Worked Best

Story Implementation (bmad-dev-story skill)

Every story (1.1 through 4.5) was implemented by invoking:

/bmad-dev-story <story-file-path>

The AI read the story spec, implemented all code, ran tests, fixed failures, and updated the story file. Human interaction was limited to:

  • Typing dev <story-number> to start each story
  • Approving tool use permissions when prompted
  • Occasionally running fix when a tool call was rejected

What worked best:

  • Stories with complete code in Dev Notes (most Epic 2 stories) - AI executed them almost verbatim, with only minor adaptations for Python 3.14 compatibility
  • Browser verification via Chrome DevTools MCP - AI could see exactly what the app rendered, check network calls, and confirm features worked without relying on unit tests alone
  • Debugging via live DB inspection - for the Story 1.3 migration deadlock, AI ran SELECT ... FROM pg_stat_activity to confirm the exact deadlock mechanism before fixing

Planning Phase (BMad Agents)

The PRD, epics, architecture, and all 20 story spec files were created in an earlier session by BMad planning agents. These provided:

  • Complete Dev Notes sections with production-ready code for every file
  • Explicit architectural rules (single Axios instance, three-handler optimistic pattern, etc.)
  • Test patterns and expected outputs

This pre-planning made implementation highly reliable - the AI wasn't inventing patterns, it was implementing well-specified blueprints.


Test Generation - How AI Assisted and What It Missed

Backend Tests (AI-generated, all passing)

AI wrote all 24 backend tests following the red-green-refactor cycle:

  • test_todo_router.py - 12 integration tests via HTTPX AsyncClient
  • test_todo_service.py - 8 unit tests calling services directly

AI correctly identified:

  • Need for NullPool in test engine to avoid asyncio cross-loop issues
  • drop_all/create_all per-test isolation (instead of transactions) to avoid PostgreSQL lock deadlocks
  • The TESTING=1 env var guard to skip Alembic migrations in tests

What it missed (required human/AI iteration):

  • asyncio_default_fixture_loop_scope = "function" setting in pyproject.toml - took 3 iterations to diagnose the "Future attached to different loop" error
  • The PostgreSQL lock deadlock from unclosed sessions - diagnosed by snapshotting pg_stat_activity mid-hang

Frontend Tests (AI-generated)

AI wrote all 57 frontend unit tests using Jest + RTL + jest-axe:

  • 4 test files for components (AddTodo, BulkActions, TodoList, TodoItem)
  • 3 test files for common components (LoadingSpinner, EmptyState, ErrorMessage)
  • 1 hooks.test.ts covering all 6 hooks (added in Story 4.2 for coverage)
  • Axe accessibility tests added to each component (Story 2.7 + 4.3)

AI correctly identified:

  • Factory mock pattern for hooks to avoid import.meta.env under ts-jest's CJS transform
  • listWrapper for TodoItem axe tests (axe requires <li> inside <ul>)
  • asyncio_default_fixture_loop_scope issue required per-client engine with NullPool
  • useDragReorder needed empty-cache tests to cover ?? [] fallback branches

What it missed initially:

  • The setupFilesAfterEnv key name - the story spec had two wrong variants (setupFilesAfterEach and setupFilesAfterFramework). AI verified against jest-config defaults to find the real name
  • @testing-library/jest-dom types not visible to ts-jest - required adding to the explicit types array in jest config
  • Hook branch coverage: TanStack Query's onMutate/onError callbacks weren't being triggered in tests with pre-seeded cache - required rewriting hook tests to seed queryClient data before mutating

E2E Tests (AI-generated)

AI wrote 14 Playwright E2E tests + 5 axe-core accessibility specs:

  • Complete user journeys (create, edit, complete, delete, reorder, bulk clear)
  • Route interception for error state and loading state tests
  • API-level teardown via request.delete in beforeEach

AI correctly identified:

  • dnd-kit keyboard sensor doesn't work reliably in headless Playwright - replaced with API-level reorder verification
  • waitForResponse after keyboard drop times out if response already arrived - removed in favour of expect.toHaveText auto-retry
  • Playwright config location: frontend/playwright.config.ts not frontend/e2e/playwright.config.ts (story spec had an error - testDir: './e2e' from within e2e/ would double-nest)

Debugging with AI - Key Incidents

1. Alembic asyncio Event Loop Conflict (Story 1.3)

Problem: Alembic's asyncio.run() inside env.py conflicted with FastAPI's already-running event loop. Backend container hung at "Waiting for application startup."

AI diagnosis: Read Docker container logs, identified RuntimeWarning: coroutine 'run_async_migrations' was never awaited, traced to asyncio.run() being called inside an active loop.

Fix: Run _run_migrations() via loop.run_in_executor(None, ...) so Alembic gets its own clean thread with no active loop. Later switched to get_running_loop() for correctness.

2. PostgreSQL Lock Deadlock in Tests (Story 2.1)

Problem: Backend tests hung indefinitely. After 30+ seconds, test process had to be killed.

AI diagnosis: Ran SELECT pid, state, wait_event, query FROM pg_stat_activity mid-hang:

pid 22535 | idle in transaction | ... | SELECT todos...
pid 22536 | active (Lock wait) | ... | DROP TABLE todos

Confirmed: unclosed session from test 1 held ACCESS SHARE lock; test 2's drop_all needed ACCESS EXCLUSIVE - infinite deadlock.

Fix: Restore proper async with session_factory() context manager (which closes the session and releases locks on teardown). Root cause was earlier hack to avoid "different loop" teardown errors.

3. useDragReorder Bug - Bottom-to-Top Drag Not Working (Story 3.2 post-dev)

Problem: Dragging a todo from position 2 to position 0 appeared to work visually but reverted on page refresh.

AI diagnosis: The original spec said "only PATCH the moved item." But moving C from index 2 to index 0 sets C's order to 0 while A still has order 0 in the DB - ambiguous sort on next GET.

Fix: Changed to Promise.all(patches) - PATCH all items whose order value actually changed after arrayMove. This ensures the DB has sequential, unambiguous order values.

4. Jest setupFilesAfterEnv Key Name (Story 2.3)

Problem: Jest config validation warning - "Unknown option setupFilesAfterEach" and "Unknown option setupFilesAfterFramework".

AI diagnosis: Rather than guessing, queried the Jest config defaults directly:

node -e "const d=require('jest-config').defaults; console.log(Object.keys(d).filter(k=>/setup/i.test(k)))"
// ['setupFiles', 'setupFilesAfterEnv']

Fix: Used setupFilesAfterEnv - the authoritative source.

5. WCAG Color Contrast Violation (Story 4.3)

Problem: axe-core reported color-contrast violation on completed todo text.

AI diagnosis: axe output showed fgColor: #9ca3af, bgColor: #ffffff, contrastRatio: 2.53 - below 4.5:1 AA requirement.

Fix: Changed --color-completed-text from #9ca3af to #6b7280 (4.61:1 ratio). One-line CSS change; 0 violations after fix.


Limitations Encountered - Where Human Expertise Was Critical

1. Python 3.14 Compatibility (Recurring)

What the AI couldn't predict: The local development environment used Python 3.14, while Docker used Python 3.11. PEP 649 (lazy annotations) in Python 3.14 broke SQLModel's metaclass, import.meta.env under ts-jest's CJS transform, and asyncio.get_event_loop() behaviour.

Human role: Recognising the Python 3.14 vs 3.11 gap early. The AI found the fixes but needed context about the target runtime.

2. dnd-kit Keyboard Events in Headless Playwright

What the AI couldn't do: Make dnd-kit's KeyboardSensor work reliably via Playwright's synthetic Space/ArrowDown key events in headless Chromium. Three attempts; each failed.

Human role: The human interrupted the AI mid-attempt and prompted the AI to API-level reorder verification + drag handle presence check, which was more reliable and equally valid for the story's acceptance criteria.

3. Chrome DevTools MCP Setup

What AI couldn't do: The chrome-devtools MCP wasn't pre-installed. The AI skill invocation failed silently. Human role: Awareness that MCP servers need to be configured before skills that use them can work. Once installed the AI ran the MCP request successfully.


What Worked Exceptionally Well

  1. Story specs with complete Dev Notes - pre-written code blueprints made AI implementation near-deterministic. The AI was implementing, not designing.

  2. Chrome DevTools MCP for browser verification - replaced unreliable "describe what you see" with actual DOM queries, network inspection, and JS execution. Caught real bugs (color contrast, event loop conflicts) that unit tests missed.

  3. AI self-diagnosis via live data - running pg_stat_activity, jest-config queries, curl timing, pip-audit - the AI used first-principles tools rather than guessing.

  4. Iterative test fixing - the AI never gave up when tests failed. It read the error, traced the cause, fixed it, and re-ran. The asyncio loop-scope issue took few iterations but was solved correctly.

  5. The BMad skill system - short terse prompts (dev 2-1, fix, check with chrome devtools) triggering comprehensive workflows.

What Would Improve Future AI Development

  1. Specify Python version in story specs - avoid Python 3.14 vs 3.11 surprises by noting target runtime explicitly
  2. Pre-configure all MCP servers - add chrome-devtools to the project's Claude settings so it's always available
  3. Add dnd-kit test utilities to story spec - or explicitly note "Playwright synthetic events don't work with dnd-kit; use API verification"
  4. Seed test DB state in story specs - conftest patterns for async pytest with PostgreSQL should be project-standard boilerplate.

About

A todo app using the bmad spec driven development

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages