Course navigationPhase 35
Volume 08 · Phase 35

Architecture Review & Refactoring

Review and refactor TaskFlow architecture using evidence: dependency direction, duplication, tests, complexity, security, and operational boundaries.

16lessons + labs
4klesson words
12source references
What you will ship

Phase outcome and project increment

Learning outcome

Review and refactor TaskFlow architecture using evidence: dependency direction, duplication, tests, complexity, security, and operational boundaries.

Concrete deliverable

Architecture review report plus one behavior-preserving refactor backed by tests and an ADR.

Figure 35.1 — Where this phase lives in TaskFlow
observe architecture
identify smell/risk
establish tests
small refactor
verify behavior
document decision
Trace the flow left-to-right for implementation and right-to-left for debugging. At every arrow, ask what data crosses the boundary and what proves it is trustworthy.
Instructor mental model

Principles to keep while coding

01

Refactoring should improve boundaries and clarity while preserving externally observable behavior.

02

Use tests and architecture checks as safety nets before moving responsibilities across modules.

03

Remove abstractions that no longer earn their complexity instead of only adding new layers.

04

Document significant architectural decisions so future maintainers understand the trade-offs that shaped the system.

Code-along path

Guided phase lab

Do these in order. Each step should end with evidence before the next one starts.

  1. 01

    Draw the current dependency graph from UI to database and mark places responsibilities leak across boundaries.

  2. 02

    Find one duplication or accidental abstraction whose cost is visible in real code.

  3. 03

    Create/strengthen tests around the behavior before moving code.

  4. 04

    Refactor in small commits, verifying typecheck/tests after each conceptual move.

  5. 05

    Measure whether the result reduced coupling/duplication or merely moved files.

  6. 06

    Write a short ADR recording context, decision, alternatives, consequences, and when to revisit.

Debugging studio

Failures you should know how to diagnose

Failure drill 1

Big-bang rewrite

Predict the symptom, capture evidence at the nearest boundary, change one variable, and verify the same reproduction after the fix.

Failure drill 2

Refactor with no behavioral safety net

Predict the symptom, capture evidence at the nearest boundary, change one variable, and verify the same reproduction after the fix.

Failure drill 3

Adding layers because they look enterprise

Predict the symptom, capture evidence at the nearest boundary, change one variable, and verify the same reproduction after the fix.

Failure drill 4

Confusing folder count with architecture quality

Predict the symptom, capture evidence at the nearest boundary, change one variable, and verify the same reproduction after the fix.

Watch-order style

Lessons

The source chapters come first. Every phase now ends with a guided build, a debugging workshop, and an independent challenge so reading turns into transferable skill.

01

Full System Architecture Inventory

Full-System Architecture Inventory Before changing architecture, document what actually exists. Review runtime boundaries, dependency direction, ownership, and operational dependencies inste

2 min
02

Dependency Direction and Accidental Coupling

Dependency Direction and Accidental Coupling Dependencies should point toward the layer that owns the contract. A useful review looks for framework details leaking upward, business decisions

2 min
03

Controller Service Repository Responsibility Review

Controller, Service, and Repository Responsibility Review Phase 24 introduced repositories only after persistence complexity earned the abstraction. Phase 35 reviews whether that boundary st

2 min
04

Validation Contracts and Duplication Review

Validation, Contracts, and Duplication Review TaskFlow intentionally validates at more than one layer. The review distinguishes necessary repeated trust checks from accidental schema duplica

2 min
05

Transactions Business Rules and Persistence Boundaries

Transactions, Business Rules, and Persistence Boundaries Transactions are one of the fastest ways an otherwise clean layering model can become dishonest. Review where atomicity actually belo

2 min
06

Frontend State and Server Client Boundary Review

Frontend State and Server/Client Boundary Review Volumes 06 and 07 created several legitimate state owners. Phase 35 checks for accidental duplication and client-boundary growth after forms,

2 min
07

Authentication Authorization and Security Boundary Review

Authentication, Authorization, and Security Boundary Review Security architecture is reviewed as a chain. Each layer must still make an independent, explicit decision after later refactors a

2 min
08

Monorepo Packages Configuration and Boundary Review

Monorepo, Packages, Configuration, and Boundary Review Monorepos make sharing easy, which also makes inappropriate sharing easy. Review package direction, duplicated configuration, environme

2 min
09

Testing Observability and Operational Debt

Testing, Observability, and Operational Debt A refactor is safest when tests and telemetry cover the seams being changed. Review whether the system can prove behavior before, during, and aft

2 min
10

Dead Abstractions Overengineering and Simplification

Dead Abstractions, Overengineering, and Simplification A mature review removes complexity as aggressively as it adds structure. Every abstraction has carrying cost: naming, navigation, indir

2 min
11

Refactoring Strategy ADRs and Change Safety

Refactoring Strategy, ADRs, and Change Safety Architecture review produces a backlog, not a giant rewrite. Refactor one bounded pressure point at a time, record consequential decisions, and

2 min
12

Hands On Lab and Phase Exit

Hands-On Architecture Review Lab and Phase Exit The lab produces concrete review artifacts for TaskFlow and prepares the final phase. The learner should finish with a map, prioritized backlo

2 min
LAB

Guided Build Lab

Purpose Review and refactor TaskFlow architecture using evidence: dependency direction, duplication, tests, complexity, security, and operational boundaries.

3 min
LAB

Debugging Workshop

Goal Learn to diagnose this phase's failures systematically instead of reinstalling packages, changing random configuration, or copying a fix without understanding it.

2 min
LAB

Phase Synthesis & Independent Challenge

Mission Rebuild the capability of Phase 35 without following the exact code line-by-line. The goal is transfer: can you use the ideas when the variable names, UI, or route shape changes?

2 min
LAB

Mastery Capstone Lab

Integrate Phase 35 without following a transcript.

2 min
Practice ladder

Exercises that increase independence

Guided

Draw the current dependency graph from UI to database and mark places responsibilities leak across boundaries.

Practice

Create/strengthen tests around the behavior before moving code.

Debug

reproduce and diagnose — Big-bang rewrite.

Independent

deliver Architecture review report plus one behavior-preserving refactor backed by tests and an ADR.

Explain-back

Can identify architectural smell with evidence and Can preserve behavior while refactoring.

Mastery gate

Do not leave the phase only because you reached the bottom

Phase exit criteria

Knowledge check

Scenario and concept quiz

These questions test engineering choices rather than whether you remember a lesson title.

0/0 correct · 0/8 answered
01Which practice best matches Phase 35's engineering goal?
02Which practice best matches Phase 35's engineering goal?
03Which practice best matches Phase 35's engineering goal?
04Which practice best matches Phase 35's engineering goal?
05You are working through the Phase 35 lab. Which next action is the most disciplined step?
06You are working through the Phase 35 lab. Which next action is the most disciplined step?
07You are working through the Phase 35 lab. Which next action is the most disciplined step?
08You are working through the Phase 35 lab. Which next action is the most disciplined step?
Source snapshot

Reference files

Attempt the work first. Use snapshots to compare a checkpoint, not as a substitute for understanding.

reference/TaskFlow_Architecture_Review_Snapshot/ADR_TEMPLATE.md
# ADR-XXXX: <Decision Title>

## Status
Proposed | Accepted | Superseded

## Context
What pressure or constraint caused this decision? Include observed evidence.

## Decision
What are we choosing?

## Alternatives Considered
- Alternative A
- Alternative B

## Consequences
### Positive
- ...

### Negative / Cost
reference/TaskFlow_Architecture_Review_Snapshot/ARCHITECTURE_MAP.md
# TaskFlow Architecture Map - Phase 35

## Primary request path

Browser -> Next.js -> authenticated API client -> NestJS/Fastify -> auth guard -> authorization -> application service -> repository -> Prisma -> PostgreSQL

## Supporting infrastructure

- Supabase Auth: external identity/session provider
- Supabase Storage: attachment bytes; PostgreSQL stores attachment meaning/metadata
- Supabase Realtime: freshness signal; HTTP/NestJS remains authoritative
- TanStack Query: browser server-state cache
- React Hook Form: unsaved form draft state
- GitHub Actions + Docker + deployment platforms: delivery/operations
- Sentry/logs/metrics/traces: observability

## Dependency rules

1. Controllers do not query Prisma directly.
2. Services own business workflow and policy decisions.
reference/TaskFlow_Architecture_Review_Snapshot/ARCHITECTURE_REVIEW_CHECKLIST.md
# Architecture Review Checklist

## Backend
- [ ] Controllers stay transport-focused.
- [ ] Services own business workflow/invariants.
- [ ] Repositories hide meaningful persistence mechanics.
- [ ] Transactions match business atomicity.
- [ ] HTTP exceptions do not leak into persistence adapters.

## Frontend
- [ ] Server state is not duplicated into local state.
- [ ] URL state remains deep-linkable.
- [ ] Form drafts stay in React Hook Form.
- [ ] Client boundaries are as small as practical.
- [ ] Auth/session state is not duplicated.

## Security
- [ ] Identity comes from verified token claims.
- [ ] Tenant scope is enforced server-side.
- [ ] Storage/Realtime do not replace application authorization.
reference/TaskFlow_Architecture_Review_Snapshot/DEPENDENCY_RULES.md
# Dependency Rules

## Allowed
- apps/web -> packages/validators
- apps/api -> packages/validators
- TasksService -> TaskRepository contract
- PrismaTaskRepository -> PrismaService

## Avoid / reject
- apps/web -> apps/api source imports
- shared package -> apps/web or apps/api
- service -> Fastify Reply/Request
- repository -> NestJS HTTP exceptions
- UI -> Prisma-generated model as public API contract

Every exception should be documented with a reason and revisit trigger.
reference/TaskFlow_Architecture_Review_Snapshot/PACKAGE_BOUNDARIES.md
# Package Boundary Review

## packages/validators
Earned because both web and API consume transport-neutral field rules. It must not become a dumping ground for server-only DTO semantics or UI code.

## Future package rule
Create a shared package only when:
1. There are at least two real consumers or a clear independent ownership boundary.
2. The package has a coherent responsibility.
3. Moving code there reduces coupling rather than hiding it.

Do not create generic `shared`, `common`, or `utils` packages without an explicit responsibility statement.
reference/TaskFlow_Architecture_Review_Snapshot/README.md
# TaskFlow Architecture Review Snapshot

This package contains review artifacts rather than a replacement application architecture.

Use it to:
- document the current system,
- identify actual pressure points,
- prioritize debt,
- record decisions with ADRs, and
- verify refactors without changing observable behavior accidentally.

The default stance is incremental improvement, not rewrite.
reference/TaskFlow_Architecture_Review_Snapshot/REFACTORING_BACKLOG.md
# Refactoring Backlog Template

| Priority | Area | Evidence | Risk | Proposed change | Verification |
|---|---|---|---|---|---|
| P0 | Example: tenant query | Cross-workspace test missing | Security | Add scoped repository test before any query refactor | Integration + E2E |
| P1 | Example: transaction workflow | Repeated multi-repository orchestration | Correctness | Evaluate explicit transaction boundary | Service + repository integration |
| P2 | Example: duplicated field rules | Same title limits in web/API | Drift | Move neutral field rule to validators package | Unit + form + API validation |
| P3 | Example: naming | Inconsistent helper names | Cosmetic | Rename when touching area | Typecheck/tests |

Priority is based on system pressure, not aesthetic preference.
reference/TaskFlow_Architecture_Review_Snapshot/SOURCES.md
# Source Basis

Phase 35 is an internal synthesis of the TaskFlow architecture established throughout Phases 00-34. It intentionally introduces no new framework dependency.

Review evidence should come from:
- the current repository,
- tests,
- runtime telemetry,
- deployment incidents,
- change frequency,
- security findings, and
- developer/operator friction.

If framework/provider behavior materially changes in the future, verify the relevant official documentation before altering architecture decisions based on it.
reference/TaskFlow_Architecture_Review_Snapshot/apps/api/architecture-review.example.md
# API Review Example

Trace one endpoint end-to-end:

`PATCH /tasks/:id/status`

1. Controller: parse validated route/body and current user.
2. Authorization: verified identity and resource scope.
3. Service: status transition invariant and completedAt behavior.
4. Repository: scoped Task lookup/update query.
5. Prisma/PostgreSQL: persistence and constraints.
6. Exception filter: stable HTTP error contract.
7. Observability: requestId, timing, safe error classification.

If a responsibility appears in two incompatible owners, add it to the refactoring backlog.
reference/TaskFlow_Architecture_Review_Snapshot/apps/web/state-review.example.md
# Frontend State Review Example

For `/tasks?status=DONE&page=2`:

- URL state: status=DONE, page=2
- TanStack Query: fetched page result
- React Hook Form: only create/edit draft
- Supabase Auth: session
- Local React state: menu/dialog/selection only where local
- Derived values: compute from current data; do not persist another copy

Reject any new store unless it solves a real state-ownership problem not already covered above.
reference/TaskFlow_Architecture_Review_Snapshot/scripts/architecture-audit.ps1
Write-Host "TaskFlow Architecture Audit"
Write-Host "1. Search direct Prisma imports outside repository/infrastructure areas"
Write-Host "2. Search apps/web imports that reference apps/api"
Write-Host "3. Search repositories throwing HTTP exceptions"
Write-Host "4. Compare env variable names across local, CI, Docker, and deployment templates"
Write-Host "5. Run lint, typecheck, tests, production builds, and critical smoke tests"
Write-Host "This script is a checklist launcher, not an automatic architecture judge."
reference/TaskFlow_Architecture_Review_Snapshot/tests/architecture-refactor-test-matrix.md
# Architecture Refactor Verification Matrix

| Refactor area | Minimum verification |
|---|---|
| Business policy extraction | Pure unit tests |
| Service/repository boundary | Service tests + repository integration tests |
| Tenant query restructure | Real PostgreSQL cross-workspace tests + HTTP E2E |
| Validation sharing | Browser form tests + API validation tests |
| Frontend state ownership | Component/query tests + critical Playwright flow |
| Authentication/authorization changes | 401/403/404 E2E matrix |
| Transaction changes | Integration tests with rollback/failure scenarios |
| Deployment/config refactor | CI build + staging smoke tests |
| Observability refactor | Synthetic error + requestId correlation check |