==================== START: architecture-tmpl ====================
# {Project Name} Architecture Document

## Introduction / Preamble

{This document outlines the overall project architecture, including backend systems, shared services, and non-UI specific concerns. Its primary goal is to serve as the guiding architectural blueprint for AI-driven development, ensuring consistency and adherence to chosen patterns and technologies.

**Relationship to Frontend Architecture:**
If the project includes a significant user interface, a separate Frontend Architecture Document (typically named `front-end-architecture-tmpl.txt` or similar, and linked in the "Key Reference Documents" section) details the frontend-specific design and MUST be used in conjunction with this document. Core technology stack choices documented herein (see "Definitive Tech Stack Selections") are definitive for the entire project, including any frontend components.}

## Table of Contents

{ Update this if sections and subsections are added or removed }

## Technical Summary

{ Provide a brief paragraph overview of the system's architecture, key components, technology choices, and architectural patterns used. Reference the goals from the PRD. }

## High-Level Overview

{ Describe the main architectural style (e.g., Monolith, Microservices, Serverless, Event-Driven), reflecting the decision made in the PRD. Explain the repository structure (Monorepo/Polyrepo). Explain the primary user interaction or data flow at a conceptual level. }

{ Insert high-level mermaid system context or interaction diagram here - e.g., Mermaid Class C4 Models Layer 1 and 2 }

## Architectural / Design Patterns Adopted

{ List the key high-level patterns chosen for the architecture. These foundational patterns should be established early as they guide component design, interactions, and technology choices. }

- **Pattern 1:** {e.g., Serverless, Event-Driven, Microservices, CQRS} - _Rationale/Reference:_ {Briefly why, or link to a more detailed explanation if needed}
- **Pattern 2:** {e.g., Dependency Injection, Repository Pattern, Module Pattern} - _Rationale/Reference:_ {...}
- **Pattern N:** {...}

## Component View

{ Describe the major logical components or services of the system and their responsibilities, reflecting the decided overall architecture (e.g., distinct microservices, modules within a monolith, packages within a monorepo) and the architectural patterns adopted. Explain how they collaborate. }

- Component A: {Description of responsibility}

{Insert component diagram here if it helps - e.g., using Mermaid graph TD or C4 Model Container/Component Diagram}

- Component N...: {Description of responsibility}

{ Insert component diagram here if it helps - e.g., using Mermaid graph TD or C4 Model Container/Component Diagram }

## Project Structure

{Provide an ASCII or Mermaid diagram representing the project's folder structure. The following is a general example. If a `front-end-architecture-tmpl.txt` (or equivalent) is in use, it will contain the detailed structure for the frontend portion (e.g., within `src/frontend/` or a dedicated `frontend/` root directory). Shared code structure (e.g., in a `packages/` directory for a monorepo) should also be detailed here.}

```plaintext
{project-root}/
 .github/                    # CI/CD workflows (e.g., GitHub Actions)
    workflows/
        main.yml
 .vscode/                    # VSCode settings (optional)
    settings.json
 build/                      # Compiled output (if applicable, often git-ignored)
 config/                     # Static configuration files (if any)
 docs/                       # Project documentation (PRD, Arch, etc.)
    index.md
    ... (other .md files)
 infra/                      # Infrastructure as Code (e.g., CDK, Terraform)
    lib/
    bin/
 node_modules/ / venv / target/ # Project dependencies (git-ignored)
 scripts/                    # Utility scripts (build, deploy helpers, etc.)
 src/                        # Application source code
    backend/                # Backend-specific application code (if distinct frontend exists)
       core/               # Core business logic, domain models
       services/           # Business services, orchestrators
       adapters/           # Adapters to external systems (DB, APIs)
       controllers/ / routes/ # API endpoint handlers
       main.ts / app.py    # Backend application entry point
    frontend/               # Placeholder: See Frontend Architecture Doc for details if used
    shared/ / common/       # Code shared (e.g., types, utils, domain models if applicable)
       types/
    main.ts / index.ts / app.ts # Main application entry point (if not using backend/frontend split above)
 stories/                    # Generated story files for development (optional)
    epic1/
 test/                       # Automated tests
    unit/                   # Unit tests (mirroring src structure)
    integration/            # Integration tests
    e2e/                    # End-to-end tests
 .env.example                # Example environment variables
 .gitignore                  # Git ignore rules
 package.json / requirements.txt / pom.xml # Project manifest and dependencies
 tsconfig.json / pyproject.toml # Language-specific configuration (if applicable)
 Dockerfile                  # Docker build instructions (if applicable)
 README.md                   # Project overview and setup instructions
```

(Adjust the example tree based on the actual project type - e.g., Python would have requirements.txt, etc. The structure above illustrates a potential separation for projects with distinct frontends; for simpler projects or APIs, the `src/` structure might be flatter.)

### Key Directory Descriptions

- docs/: Contains all project planning and reference documentation.
- infra/: Holds the Infrastructure as Code definitions (e.g., AWS CDK, Terraform).
- src/: Contains the main application source code. May be subdivided (e.g., `backend/`, `frontend/`, `shared/`) depending on project complexity and whether a separate frontend architecture document is in use.
- src/backend/core/ / src/core/ / src/domain/: Core business logic, entities, use cases, independent of frameworks/external services.
- src/backend/adapters/ / src/adapters/ / src/infrastructure/: Implementation details, interactions with databases, cloud SDKs, frameworks.
- src/backend/controllers/ / src/routes/ / src/pages/: Entry points for API requests or UI views (if UI is simple and not in a separate frontend structure).
- test/: Contains all automated tests, mirroring the src/ structure where applicable.

### Notes

{Mention any specific build output paths, compiler configuration pointers, or other relevant structural notes.}

## API Reference

### External APIs Consumed

{Repeat this section for each external API the system interacts with.}

#### {External Service Name} API

- **Purpose:** {Why does the system use this API?}
- **Base URL(s):**
  - Production: `{URL}`
  - Staging/Dev: `{URL}`
- **Authentication:** {Describe method - e.g., API Key in Header (Header Name: `X-API-Key`), OAuth 2.0 Client Credentials, Basic Auth. Reference `docs/environment-vars.md` for key names.}
- **Key Endpoints Used:**
  - **`{HTTP Method} {/path/to/endpoint}`:**
    - Description: {What does this endpoint do?}
    - Request Parameters: {Query params, path params}
    - Request Body Schema: {Provide JSON schema inline, or link to a detailed definition in `docs/data-models.md` only if the schema is exceptionally large or complex.}
    - Example Request: `{Code block}`
    - Success Response Schema (Code: `200 OK`): {Provide JSON schema inline, or link to a detailed definition in `docs/data-models.md` only if very complex.}
    - Error Response Schema(s) (Codes: `4xx`, `5xx`): {Provide JSON schema inline, or link to a detailed definition in `docs/data-models.md` only if very complex.}
    - Example Response: `{Code block}`
  - **`{HTTP Method} {/another/endpoint}`:** {...}
- **Rate Limits:** {If known}
- **Link to Official Docs:** {URL}

### Internal APIs Provided (If Applicable)

{If the system exposes its own APIs (e.g., in a microservices architecture or for a UI frontend). Repeat for each API.}

#### {Internal API / Service Name} API

- **Purpose:** {What service does this API provide?}
- **Base URL(s):** {e.g., `/api/v1/...`}
- **Authentication/Authorization:** {Describe how access is controlled.}
- **Endpoints:**
  - **`{HTTP Method} {/path/to/endpoint}`:**
    - Description: {What does this endpoint do?}
    - Request Parameters: {...}
    - Request Body Schema: {Provide JSON schema inline, or link to a detailed definition in `docs/data-models.md` only if very complex.}
    - Success Response Schema (Code: `200 OK`): {Provide JSON schema inline, or link to a detailed definition in `docs/data-models.md` only if very complex.}
    - Error Response Schema(s) (Codes: `4xx`, `5xx`): {Provide JSON schema inline, or link to a detailed definition in `docs/data-models.md` only if very complex.}
  - **`{HTTP Method} {/another/endpoint}`:** {...}

## Data Models

### Core Application Entities / Domain Objects

{Define the main objects/concepts the application works with. Repeat subsection for each key entity.}

#### {Entity Name, e.g., User, Order, Product}

- **Description:** {What does this entity represent?}
- **Schema / Interface Definition:**
  ```typescript
  // Example using TypeScript Interface
  export interface {EntityName} {
    id: string; // {Description, e.g., Unique identifier}
    propertyName: string; // {Description}
    optionalProperty?: number; // {Description}
    // ... other properties
  }
  ```
- **Validation Rules:** {List any specific validation rules beyond basic types - e.g., max length, format, range.}

### API Payload Schemas (If distinct)

{Define schemas here only if they are distinct from core entities AND not fully detailed under the API endpoint definitions in the API Reference section. Prefer detailing request/response schemas directly with their APIs where possible. This section is for complex, reusable payload structures that might be used across multiple internal APIs or differ significantly from core persisted entities.}

#### {API Endpoint / Purpose, e.g., Create Order Request, repeat the section as needed}

- **Schema / Interface Definition:**
  ```typescript
  // Example
  export interface CreateOrderRequest {
    customerId: string;
    items: { productId: string; quantity: number }[];
    // ...
  }
  ```

### Database Schemas (If applicable)

{If using a database, define table structures or document database schemas. repeat as needed}

#### {Table / Collection Name}

- **Purpose:** {What data does this table store?}
- **Schema Definition:**
  ```sql
  -- Example SQL
  CREATE TABLE {TableName} (
    id VARCHAR(36) PRIMARY KEY,
    column_name VARCHAR(255) NOT NULL,
    numeric_column DECIMAL(10, 2),
    -- ... other columns, indexes, constraints
  );
  ```
  _(Alternatively, use ORM model definitions, NoSQL document structure, etc.)_

## Core Workflow / Sequence Diagrams

{ Illustrate key or complex workflows using mermaid sequence diagrams. Can have high level tying the full project together, and also smaller epic level sequence diagrams. }

## Definitive Tech Stack Selections

{ This section outlines the definitive technology choices for the project. These selections should be made after a thorough understanding of the project's requirements, components, data models, and core workflows. The Architect Agent should guide the user through these decisions, ensuring each choice is justified and recorded accurately in the table below.

This table is the **single source of truth** for all technology selections. Other architecture documents (e.g., Frontend Architecture) must refer to these choices and elaborate on their specific application rather than re-defining them.

Key decisions to discuss and finalize here, which will then be expanded upon and formally documented in the detailed stack table below, include considerations such as:

- Preferred Starter Template Frontend: { Url to template or starter, if used }
- Preferred Starter Template Backend: { Url to template or starter, if used }
- Primary Language(s) & Version(s): {e.g., TypeScript 5.x, Python 3.11 - Specify exact versions, e.g., `5.2.3`}
- Primary Runtime(s) & Version(s): {e.g., Node.js 22.x - Specify exact versions, e.g., `22.0.1`}

Must be definitive selections; do not list open-ended choices (e.g., for web scraping, pick one tool, not two). Specify exact versions (e.g., `18.2.0`). If 'Latest' is used, it implies the latest stable version _at the time of this document's last update_, and the specific version (e.g., `xyz-library@2.3.4`) should be recorded. Pinning versions is strongly preferred to avoid unexpected breaking changes for the AI agent. }

| Category             | Technology              | Version / Details | Description / Purpose                   | Justification (Optional) |
| :------------------- | :---------------------- | :---------------- | :-------------------------------------- | :----------------------- |
| **Languages**        | {e.g., TypeScript}      | {e.g., 5.x}       | {Primary language for backend/frontend} | {Why this language?}     |
|                      | {e.g., Python}          | {e.g., 3.11}      | {Used for data processing, ML}          | {...}                    |
| **Runtime**          | {e.g., Node.js}         | {e.g., 22.x}      | {Server-side execution environment}     | {...}                    |
| **Frameworks**       | {e.g., NestJS}          | {e.g., 10.x}      | {Backend API framework}                 | {Why this framework?}    |
|                      | {e.g., React}           | {e.g., 18.x}      | {Frontend UI library}                   | {...}                    |
| **Databases**        | {e.g., PostgreSQL}      | {e.g., 15}        | {Primary relational data store}         | {...}                    |
|                      | {e.g., Redis}           | {e.g., 7.x}       | {Caching, session storage}              | {...}                    |
| **Cloud Platform**   | {e.g., AWS}             | {N/A}             | {Primary cloud provider}                | {...}                    |
| **Cloud Services**   | {e.g., AWS Lambda}      | {N/A}             | {Serverless compute}                    | {...}                    |
|                      | {e.g., AWS S3}          | {N/A}             | {Object storage for assets/state}       | {...}                    |
|                      | {e.g., AWS EventBridge} | {N/A}             | {Event bus / scheduled tasks}           | {...}                    |
| **Infrastructure**   | {e.g., AWS CDK}         | {e.g., Latest}    | {Infrastructure as Code tool}           | {...}                    |
|                      | {e.g., Docker}          | {e.g., Latest}    | {Containerization}                      | {...}                    |
| **UI Libraries**     | {e.g., Material UI}     | {e.g., 5.x}       | {React component library}               | {...}                    |
| **State Management** | {e.g., Redux Toolkit}   | {e.g., Latest}    | {Frontend state management}             | {...}                    |
| **Testing**          | {e.g., Jest}            | {e.g., Latest}    | {Unit/Integration testing framework}    | {...}                    |
|                      | {e.g., Playwright}      | {e.g., Latest}    | {End-to-end testing framework}          | {...}                    |
| **CI/CD**            | {e.g., GitHub Actions}  | {N/A}             | {Continuous Integration/Deployment}     | {...}                    |
| **Other Tools**      | {e.g., LangChain.js}    | {e.g., Latest}    | {LLM interaction library}               | {...}                    |
|                      | {e.g., Cheerio}         | {e.g., Latest}    | {HTML parsing/scraping}                 | {...}                    |

## Infrastructure and Deployment Overview

- Cloud Provider(s): {e.g., AWS, Azure, GCP, On-premise}
- Core Services Used: {List key managed services - e.g., Lambda, S3, Kubernetes Engine, RDS, Kafka}
- Infrastructure as Code (IaC): {Tool used - e.g., AWS CDK, Terraform...} - Location: {Link to IaC code repo/directory}
- Deployment Strategy: {e.g., CI/CD pipeline with automated promotions, Blue/Green, Canary} - Tools: {e.g., Jenkins, GitHub Actions, GitLab CI}
- Environments: {List environments - e.g., Development, Staging, Production}
- Environment Promotion: {Describe steps, e.g., `dev` -\> `staging` (manual approval / automated tests pass) -\> `production` (automated after tests pass and optional manual approval)}
- Rollback Strategy: {e.g., Automated rollback on health check failure post-deployment, Manual trigger via CI/CD job, IaC state rollback. Specify primary mechanism.}

## Error Handling Strategy

- **General Approach:** {e.g., Use exceptions as primary mechanism, return error codes/tuples for specific modules, clearly defined custom error types hierarchy.}
- **Logging:**
  - Library/Method: {e.g., `console.log/error` (Node.js), Python `logging` module with `structlog`, dedicated logging library like `Pino` or `Serilog`. Specify the chosen library.}
  - Format: {e.g., JSON, plain text with timestamp and severity. JSON is preferred for structured logging.}
  - Levels: {e.g., DEBUG, INFO, WARN, ERROR, CRITICAL. Specify standard usage for each.}
  - Context: {What contextual information must be included? e.g., Correlation ID, User ID (if applicable and safe), Service Name, Operation Name, Key Parameters (sanitized).}
- **Specific Handling Patterns:**
  - External API Calls: {Define retry mechanisms (e.g., exponential backoff, max retries - specify library if one is mandated like `Polly` or `tenacity`), circuit breaker pattern usage (e.g., using `resilience4j` or equivalent - specify if and how), timeout configurations (connect and read timeouts). How are API errors (4xx, 5xx) translated or propagated?}
  - Internal Errors / Business Logic Exceptions: {How to convert internal errors to user-facing errors if applicable (e.g., generic error messages with a unique ID for support, specific error codes). Are there defined business exception classes?}
  - Transaction Management: {Approach to ensure data consistency in case of errors during multi-step operations, e.g., database transactions (specify isolation levels if non-default), Saga pattern for distributed transactions (specify orchestrator/choreography and compensation logic).}

## Coding Standards

{These standards are mandatory for all code generation by AI agents and human developers. Deviations are not permitted unless explicitly approved and documented as an exception in this section or a linked addendum.}

- **Primary Runtime(s):** {e.g., Node.js 22.x, Python Runtime for Lambda - refer to Definitive Tech Stack}
- **Style Guide & Linter:** {e.g., ESLint with Airbnb config + Prettier; Black, Flake8, MyPy; Go fmt, golint. Specify chosen tools and link to configuration files (e.g., `.eslintrc.js`, `pyproject.toml`). Linter rules are mandatory and must not be disabled without cause.}
- **Naming Conventions:**
  - Variables: `{e.g., camelCase (JavaScript/TypeScript/Java), snake_case (Python/Ruby)}`
  - Functions/Methods: `{e.g., camelCase (JavaScript/TypeScript/Java), snake_case (Python/Ruby)}`
  - Classes/Types/Interfaces: `{e.g., PascalCase}`
  - Constants: `{e.g., UPPER_SNAKE_CASE}`
  - Files: `{e.g., kebab-case.ts (TypeScript), snake_case.py (Python), PascalCase.java (Java). Be specific per language.}`
  - Modules/Packages: `{e.g., camelCase or snake_case. Be specific per language.}`
- **File Structure:** Adhere to the layout defined in the "Project Structure" section and the Frontend Architecture Document if applicable.
- **Unit Test File Organization:** {e.g., `*.test.ts`/`*.spec.ts` co-located with source files; `test_*.py` in a parallel `tests/` directory. Specify chosen convention.}
- **Asynchronous Operations:** {e.g., Always use `async`/`await` in TypeScript/JavaScript/Python for promise-based operations; Goroutines/Channels in Go with clear patterns for error propagation and completion; Java `CompletableFuture` or Project Reactor/RxJava if used.}
- **Type Safety:** {e.g., Leverage TypeScript strict mode (all flags enabled); Python type hints (enforced by MyPy); Go static typing; Java generics and avoidance of raw types. All new code must be strictly typed.}
  - _Type Definitions:_ {Location, e.g., `src/common/types.ts`, shared packages, or co-located. Policy on using `any` or equivalent (strongly discouraged, requires justification).}
- **Comments & Documentation:**
  - Code Comments: {Expectations for code comments: Explain _why_, not _what_, for complex logic. Avoid redundant comments. Use standard formats like JSDoc, TSDoc, Python docstrings (Google/NumPy style), GoDoc, JavaDoc.}
  - READMEs: {Each module/package/service should have a README explaining its purpose, setup, and usage if not trivial.}
- **Dependency Management:** {Tool used - e.g., npm/yarn, pip/poetry, Go modules, Maven/Gradle. Policy on adding new dependencies (e.g., approval process, check for existing alternatives, security vulnerability scans). Specify versioning strategy (e.g., prefer pinned versions, use tilde `~` for patches, caret `^` for minor updates - be specific).}

### Detailed Language & Framework Conventions

{For each primary language and framework selected in the "Definitive Tech Stack Selections", the following specific conventions **must** be adhered to. If a chosen technology is not listed below, it implies adherence to its standard, widely accepted best practices and the general guidelines in this document.}

#### `{Language/Framework 1 Name, e.g., TypeScript/Node.js}` Specifics:

- **Immutability:** `{e.g., "Always prefer immutable data structures. Use `Readonly\<T\>`, `ReadonlyArray\<T\>`, `as const` for object/array literals. Avoid direct mutation of objects/arrays passed as props or state. Consider libraries like Immer for complex state updates."}`
- **Functional vs. OOP:** `{e.g., "Favor functional programming constructs (map, filter, reduce, pure functions) for data transformation and business logic where practical. Use classes for entities, services with clear state/responsibilities, or when framework conventions (e.g., NestJS) demand."}`
- **Error Handling Specifics:** `{e.g., "Always use `Error`objects or extensions thereof for`throw`. Ensure `Promise`rejections are always`Error`objects. Use custom error classes inheriting from a base`AppError` for domain-specific errors."}`
- **Null/Undefined Handling:** `{e.g., "Strict null checks (`strictNullChecks`) must be enabled. Avoid `\!` non-null assertion operator; prefer explicit checks, optional chaining (`?.`), or nullish coalescing (`??`). Define clear strategies for optional function parameters and return types."}`
- **Module System:** `{e.g., "Use ESModules (`import`/`export`) exclusively. Avoid CommonJS (`require`/`module.exports`) in new code."}`
- **Logging Specifics:** `{e.g., "Use the chosen structured logging library. Log messages must include a correlation ID. Do not log sensitive PII. Use appropriate log levels."}`
- **Framework Idioms (e.g., for NestJS/Express):** `{e.g., "NestJS: Always use decorators for defining modules, controllers, services, DTOs. Adhere strictly to the defined module structure and dependency injection patterns. Express: Define middleware patterns, routing structure."}`
- **Key Library Usage Conventions:** `{e.g., "When using Axios, create a single configured instance. For date/time, use {date-fns/Luxon/Day.js} and avoid native `Date` object for manipulations."}`
- **Code Generation Anti-Patterns to Avoid:** `{e.g., "Avoid overly nested conditional logic (max 2-3 levels). Avoid single-letter variable names (except for trivial loop counters like `i`, `j`, `k`). Do not write code that bypasses framework security features (e.g., ORM query builders)."}`

#### `{Language/Framework 2 Name, e.g., Python}` Specifics:

- **Immutability:** `{e.g., "Use tuples for immutable sequences. For classes, consider `@dataclass(frozen=True)`. Be mindful of mutable default arguments."}`
- **Functional vs. OOP:** `{e.g., "Employ classes for representing entities and services. Use functions for stateless operations. List comprehensions/generator expressions are preferred over `map/filter` for readability."}`
- **Error Handling Specifics:** `{e.g., "Always raise specific, custom exceptions inheriting from a base `AppException`. Use `try-except-else-finally`blocks appropriately. Avoid broad`except Exception:` clauses without re-raising or specific handling."}`
- **Resource Management:** `{e.g., "Always use `with` statements for resources like files or DB connections to ensure they are properly closed."}`
- **Type Hinting:** `{e.g., "All new functions and methods must have full type hints. Run MyPy in CI. Strive for `disallow_untyped_defs = True`."}`
- **Logging Specifics:** `{e.g., "Use the `logging`module configured for structured output (e.g., with`python-json-logger`). Include correlation IDs."}`
- **Framework Idioms (e.g., for Django/Flask/FastAPI):** `{e.g., "Django: Follow fat models, thin views pattern. Use ORM conventions. FastAPI: Utilize Pydantic for request/response models and dependency injection for services."}`
- **Key Library Usage Conventions:** `{e.g., "For HTTP requests, use `httpx`or`requests`with explicit timeout settings. For data manipulation, prefer`pandas` where appropriate but be mindful of performance."}`

#### `{Add more Language/Framework sections as needed...}`

- **{Consider other things that the trained LLM Dev Agent could potentially be random about specific to the chosen language technologies and platforms that it should be reminded of here}**

## Overall Testing Strategy

{This section outlines the project's comprehensive testing strategy, which all AI-generated and human-written code must adhere to. It complements the testing tools listed in the "Definitive Tech Stack Selections".}

- **Tools:** {Reiterate primary testing frameworks and libraries from Tech Stack, e.g., Jest, Playwright, PyTest, JUnit, Testcontainers.}
- **Unit Tests:**
  - **Scope:** {Test individual functions, methods, classes, or small modules in isolation. Focus on business logic, algorithms, and transformation rules.}
  - **Location:** {e.g., `*.test.ts`/`*.spec.ts` co-located with source files; `test_*.py` in a parallel `tests/` directory, following language conventions.}
  - **Mocking/Stubbing:** {Specify chosen mocking library (e.g., Jest mocks, `unittest.mock` in Python, Mockito for Java). Mock all external dependencies (network calls, file system, databases, time).}
  - **AI Agent Responsibility:** {AI Agent must generate unit tests covering all public methods, significant logic paths, edge cases, and error conditions for any new or modified code.}
- **Integration Tests:**
  - **Scope:** {Test the interaction between several components or services within the application boundary. E.g., API endpoint to service layer to database (using a test database or in-memory version).}
  - **Location:** {e.g., `/tests/integration` or `/src/integration-test` (Java).}
  - **Environment:** {Specify how dependencies are handled (e.g., Testcontainers for databases/external services, in-memory databases, dedicated test environment).}
  - **AI Agent Responsibility:** {AI Agent may be tasked with generating integration tests for key service interactions or API endpoints based on specifications.}
- **End-to-End (E2E) Tests:**
  - **Scope:** {Validate complete user flows or critical paths through the system from the user's perspective (e.g., UI interaction, API call sequence).}
  - **Tools:** {Reiterate E2E testing tools from Tech Stack (e.g., Playwright, Cypress, Selenium).}
  - **AI Agent Responsibility:** {AI Agent may be tasked with generating E2E test stubs or scripts based on user stories or BDD scenarios. Focus on critical happy paths and key error scenarios.}
- **Test Coverage:**
  - **Target:** {Specify target code coverage if any (e.g., 80% line/branch coverage for unit tests). This is a guideline; quality of tests is paramount over raw coverage numbers.}
  - **Measurement:** {Tool used for coverage reports (e.g., Istanbul/nyc, Coverage.py, JaCoCo).}
- **Mocking/Stubbing Strategy (General):** {Beyond specific test types, outline general principles. e.g., "Prefer fakes or test doubles over extensive mocking where it improves test clarity and maintainability. Strive for tests that are fast, reliable, and isolated."}
- **Test Data Management:** {How is test data created, managed, and isolated? E.g., factories, fixtures, setup/teardown scripts, dedicated test data generation tools.}

## Security Best Practices

{Outline key security considerations relevant to the codebase. These are mandatory and must be actively addressed by the AI agent during development.}

- **Input Sanitization/Validation:** {Specify library/method for ALL external inputs (API requests, user-provided data, file uploads). E.g., 'Use class-validator with NestJS DTOs for all API inputs; all validation rules must be defined in DTOs.' For other languages, 'Use {validation_library} for all external inputs; define schemas and constraints.' Validation must occur at the boundary before processing.}
- **Output Encoding:** {Specify where and how output encoding should be performed to prevent XSS and other injection attacks. E.g., 'All dynamic data rendered in HTML templates must be contextually auto-escaped by the template engine (specify engine and confirm default behavior). If generating HTML/XML/JSON manually, use approved encoding libraries like {encoder_library_name}.'}
- **Secrets Management:** {Reference `docs/environment-vars.md` regarding storage for different environments. In code, access secrets _only_ through a designated configuration module/service. Never hardcode secrets, include them in source control, or log them. Use specific tools for local development if applicable (e.g., Doppler, .env files NOT committed).}
- **Dependency Security:** {Policy on checking for vulnerable dependencies. E.g., 'Run automated vulnerability scans (e.g., `npm audit`, `pip-audit`, Snyk, Dependabot alerts) as part of CI. Update vulnerable dependencies promptly based on severity.' Policy on adding new dependencies (vetting process).}
- **Authentication/Authorization Checks:** {Where and how should these be enforced? E.g., 'All API endpoints (except explicitly public ones) must enforce authentication using the central auth module/middleware. Authorization (permission/role checks) must be performed at the service layer or entry point for protected resources.' Define patterns for implementing these checks.}
- **Principle of Least Privilege (Implementation):** {e.g., 'Database connection users must have only the necessary permissions (SELECT, INSERT, UPDATE, DELETE) for the specific tables/schemas they access. IAM roles for cloud services must be narrowly scoped to the required actions and resources.'}
- **API Security (General):** {e.g., 'Enforce HTTPS. Implement rate limiting and throttling (specify tool/method). Use standard HTTP security headers (CSP, HSTS, X-Frame-Options, etc. - specify which ones and their configuration). Follow REST/GraphQL security best practices.'}
- **Error Handling & Information Disclosure:** {Ensure error messages do not leak sensitive information (stack traces, internal paths, detailed SQL errors) to the end-user. Log detailed errors server-side, provide generic messages or error IDs to the client.}
- **Regular Security Audits/Testing:** {Mention if planned, e.g., penetration testing, static/dynamic analysis tool usage in CI (SAST/DAST).}
- **{Other relevant practices, e.g., File upload security, Session management security, Data encryption at rest and in transit beyond HTTPS if specific requirements exist.}**

## Key Reference Documents

{ if any }

## Change Log

| Change | Date | Version | Description | Author |
| ------ | ---- | ------- | ----------- | ------ |

--- Below, Prompt for Design Architect (If Project has UI) To Produce Front End Architecture ----

==================== END: architecture-tmpl ====================


==================== START: doc-sharding-tmpl ====================
# Document Sharding Plan Template

This plan directs the agent on how to break down large source documents into smaller, granular files during its Librarian Phase. The agent will refer to this plan to identify source documents, the specific sections to extract, and the target filenames for the sharded content.

---

## 1. Source Document: PRD (Project Requirements Document)

- **Note to Agent:** Confirm the exact filename of the PRD with the user (e.g., `PRD.md`, `ProjectRequirements.md`, `prdx.y.z.md`).

### 1.1. Epic Granulation

- **Instruction:** For each Epic identified within the PRD:
- **Source Section(s) to Copy:** The complete text for the Epic, including its main description, goals, and all associated user stories or detailed requirements under that Epic. Ensure to capture content starting from a heading like "**Epic X:**" up to the next such heading or end of the "Epic Overview" section.
- **Target File Pattern:** `docs/epic-<id>.md`
  - _Agent Note: `<id>` should correspond to the Epic number._

---

## 2. Source Document: Main Architecture Document

- **Note to Agent:** Confirm the exact filename with the user (e.g., `architecture.md`, `SystemArchitecture.md`).

### 2.1. Core Architecture Granules

- **Source Section(s) to Copy:** Section(s) detailing "API Reference", "API Endpoints", or "Service Interfaces".
- **Target File:** `docs/api-reference.md`

- **Source Section(s) to Copy:** Section(s) detailing "Data Models", "Database Schema", "Entity Definitions".
- **Target File:** `docs/data-models.md`

- **Source Section(s) to Copy:** Section(s) titled "Environment Variables Documentation", "Configuration Settings", "Deployment Parameters", or relevant subsections within "Infrastructure and Deployment Overview" if a dedicated section is not found.
- **Target File:** `docs/environment-vars.md`

  - _Agent Note: Prioritize a dedicated 'Environment Variables' section or linked 'environment-vars.md' source if available. If not, extract relevant configuration details from 'Infrastructure and Deployment Overview'. This shard is for specific variable definitions and usage._

- **Source Section(s) to Copy:** Section(s) detailing "Project Structure".
- **Target File:** `docs/project-structure.md`

  - _Agent Note: If the project involves multiple repositories (not a monorepo), ensure this file clearly describes the structure of each relevant repository or links to sub-files if necessary._

- **Source Section(s) to Copy:** Section(s) detailing "Technology Stack", "Key Technologies", "Libraries and Frameworks", or "Definitive Tech Stack Selections".
- **Target File:** `docs/tech-stack.md`

- **Source Section(s) to Copy:** Sections detailing "Coding Standards", "Development Guidelines", "Best Practices", "Testing Strategy", "Testing Decisions", "QA Processes", "Overall Testing Strategy", "Error Handling Strategy", and "Security Best Practices".
- **Target File:** `docs/operational-guidelines.md`

  - _Agent Note: This file consolidates several key operational aspects. Ensure that the content from each source section ("Coding Standards", "Testing Strategy", "Error Handling Strategy", "Security Best Practices") is clearly delineated under its own H3 (###) or H4 (####) heading within this document._

- **Source Section(s) to Copy:** Section(s) titled "Component View" (including sub-sections like "Architectural / Design Patterns Adopted").
- **Target File:** `docs/component-view.md`

- **Source Section(s) to Copy:** Section(s) titled "Core Workflow / Sequence Diagrams" (including all sub-diagrams).
- **Target File:** `docs/sequence-diagrams.md`

- **Source Section(s) to Copy:** Section(s) titled "Infrastructure and Deployment Overview".
- **Target File:** `docs/infra-deployment.md`

  - _Agent Note: This is for the broader overview, distinct from the specific `docs/environment-vars.md`._

- **Source Section(s) to Copy:** Section(s) titled "Key Reference Documents".
- **Target File:** `docs/key-references.md`

---

## 3. Source Document(s): Front-End Specific Documentation

- **Note to Agent:** Confirm filenames with the user (e.g., `front-end-architecture.md`, `front-end-spec.md`, `ui-guidelines.md`). Multiple FE documents might exist.

### 3.1. Front-End Granules

- **Source Section(s) to Copy:** Section(s) detailing "Front-End Project Structure" or "Detailed Frontend Directory Structure".
- **Target File:** `docs/front-end-project-structure.md`

- **Source Section(s) to Copy:** Section(s) detailing "UI Style Guide", "Brand Guidelines", "Visual Design Specifications", or "Styling Approach".
- **Target File:** `docs/front-end-style-guide.md`

  - _Agent Note: This section might be a sub-section or refer to other documents (e.g., `ui-ux-spec.txt`). Extract the core styling philosophy and approach defined within the frontend architecture document itself._

- **Source Section(s) to Copy:** Section(s) detailing "Component Library", "Reusable UI Components Guide", "Atomic Design Elements", or "Component Breakdown & Implementation Details".
- **Target File:** `docs/front-end-component-guide.md`

- **Source Section(s) to Copy:** Section(s) detailing "Front-End Coding Standards" (specifically for UI development, e.g., JavaScript/TypeScript style, CSS naming conventions, accessibility best practices for FE).
- **Target File:** `docs/front-end-coding-standards.md`

  - _Agent Note: A dedicated top-level section for this might not exist. If not found, this shard might be empty or require cross-referencing with the main architecture's coding standards. Extract any front-end-specific coding conventions mentioned._

- **Source Section(s) to Copy:** Section(s) titled "State Management In-Depth".
- **Target File:** `docs/front-end-state-management.md`

- **Source Section(s) to Copy:** Section(s) titled "API Interaction Layer".
- **Target File:** `docs/front-end-api-interaction.md`

- **Source Section(s) to Copy:** Section(s) titled "Routing Strategy".
- **Target File:** `docs/front-end-routing-strategy.md`

- **Source Section(s) to Copy:** Section(s) titled "Frontend Testing Strategy".
- **Target File:** `docs/front-end-testing-strategy.md`

---

CRITICAL: **Index Management:** After creating the files, update `docs/index.md` as needed to reference and describe each doc - do not mention granules or where it was sharded from, just doc purpose - as the index also contains other doc references potentially.

==================== END: doc-sharding-tmpl ====================


==================== START: front-end-architecture-tmpl ====================
# {Project Name} Frontend Architecture Document

## Table of Contents

{ Update this if sections and subsections are added or removed }

- [Introduction](#introduction)
- [Overall Frontend Philosophy & Patterns](#overall-frontend-philosophy--patterns)
- [Detailed Frontend Directory Structure](#detailed-frontend-directory-structure)
- [Component Breakdown & Implementation Details](#component-breakdown--implementation-details)
  - [Component Naming & Organization](#component-naming--organization)
  - [Template for Component Specification](#template-for-component-specification)
- [State Management In-Depth](#state-management-in-depth)
  - [Store Structure / Slices](#store-structure--slices)
  - [Key Selectors](#key-selectors)
  - [Key Actions / Reducers / Thunks](#key-actions--reducers--thunks)
- [API Interaction Layer](#api-interaction-layer)
  - [Client/Service Structure](#clientservice-structure)
  - [Error Handling & Retries (Frontend)](#error-handling--retries-frontend)
- [Routing Strategy](#routing-strategy)
  - [Route Definitions](#route-definitions)
  - [Route Guards / Protection](#route-guards--protection)
- [Build, Bundling, and Deployment](#build-bundling-and-deployment)
  - [Build Process & Scripts](#build-process--scripts)
  - [Key Bundling Optimizations](#key-bundling-optimizations)
  - [Deployment to CDN/Hosting](#deployment-to-cdnhosting)
- [Frontend Testing Strategy](#frontend-testing-strategy)
  - [Component Testing](#component-testing)
  - [UI Integration/Flow Testing](#ui-integrationflow-testing)
  - [End-to-End UI Testing Tools & Scope](#end-to-end-ui-testing-tools--scope)
- [Accessibility (AX) Implementation Details](#accessibility-ax-implementation-details)
- [Performance Considerations](#performance-considerations)
- [Internationalization (i18n) and Localization (l10n) Strategy](#internationalization-i18n-and-localization-l10n-strategy)
- [Feature Flag Management](#feature-flag-management)
- [Frontend Security Considerations](#frontend-security-considerations)
- [Browser Support and Progressive Enhancement](#browser-support-and-progressive-enhancement)
- [Change Log](#change-log)

## Introduction

{ This document details the technical architecture specifically for the frontend of {Project Name}. It complements the main {Project Name} Architecture Document and the UI/UX Specification. This document details the frontend architecture and **builds upon the foundational decisions** (e.g., overall tech stack, CI/CD, primary testing tools) defined in the main {Project Name} Architecture Document (`docs/architecture.md` or linked equivalent). **Frontend-specific elaborations or deviations from general patterns must be explicitly noted here.** The goal is to provide a clear blueprint for frontend development, ensuring consistency, maintainability, and alignment with the overall system design and user experience goals. }

- **Link to Main Architecture Document (REQUIRED):** {e.g., `docs/architecture.md`}
- **Link to UI/UX Specification (REQUIRED if exists):** {e.g., `docs/front-end-spec.md`}
- **Link to Primary Design Files (Figma, Sketch, etc.) (REQUIRED if exists):** {From UI/UX Spec}
- **Link to Deployed Storybook / Component Showcase (if applicable):** {URL}

## Overall Frontend Philosophy & Patterns

{ Describe the core architectural decisions and patterns chosen for the frontend. This should align with the "Definitive Tech Stack Selections" in the main architecture document and consider implications from the overall system architecture (e.g., monorepo vs. polyrepo, backend service structure). }

- **Framework & Core Libraries:** {e.g., React 18.x with Next.js 13.x, Angular 16.x, Vue 3.x with Nuxt.js}. **These are derived from the 'Definitive Tech Stack Selections' in the main Architecture Document.** This section elaborates on *how* these choices are applied specifically to the frontend.
- **Component Architecture:** {e.g., Atomic Design principles, Presentational vs. Container components, use of specific component libraries like Material UI, Tailwind CSS for styling approach. Specify chosen approach and any key libraries.}
- **State Management Strategy:** {e.g., Redux Toolkit, Zustand, Vuex, NgRx. Briefly describe the overall approach  global store, feature stores, context API usage. **Referenced from main Architecture Document and detailed further in "State Management In-Depth" section.**}
- **Data Flow:** {e.g., Unidirectional data flow (Flux/Redux pattern), React Query/SWR for server state. Describe how data is fetched, cached, passed to components, and updated.}
- **Styling Approach:** **{Chosen Styling Solution, e.g., Tailwind CSS / CSS Modules / Styled Components}**. Configuration File(s): {e.g., `tailwind.config.js`, `postcss.config.js`}. Key conventions: {e.g., "Utility-first approach for Tailwind. Custom components defined in `src/styles/components.css`. Theme extensions in `tailwind.config.js` under `theme.extend`. For CSS Modules, files are co-located with components, e.g., `MyComponent.module.css`.}
- **Key Design Patterns Used:** {e.g., Provider pattern, Hooks, Higher-Order Components, Service patterns for API calls, Container/Presentational. These patterns are to be consistently applied. Deviations require justification and documentation.}

## Detailed Frontend Directory Structure

{ Provide an ASCII diagram representing the frontend application\'s specific folder structure (e.g., within `src/` or `app/` or a dedicated `frontend/` root directory if part of a monorepo). This should elaborate on the frontend part of the main project structure outlined in the architecture document. Highlight conventions for organizing components, pages/views, services, state, styles, assets, etc. For each key directory, provide a one-sentence mandatory description of its purpose.}

### EXAMPLE - Not Prescriptive (for a React/Next.js app)

```plaintext
src/
 app/                        # Next.js App Router: Pages/Layouts/Routes. MUST contain route segments, layouts, and page components.
    (features)/             # Feature-based routing groups. MUST group related routes for a specific feature.
       dashboard/
           layout.tsx      # Layout specific to the dashboard feature routes.
           page.tsx        # Entry page component for a dashboard route.
    api/                    # API Routes (if using Next.js backend features). MUST contain backend handlers for client-side calls.
    globals.css             # Global styles. MUST contain base styles, CSS variable definitions, Tailwind base/components/utilities.
    layout.tsx              # Root layout for the entire application.
 components/                 # Shared/Reusable UI Components.
    ui/                     # Base UI elements (Button, Input, Card). MUST contain only generic, reusable, presentational UI elements, often mapped from a design system. MUST NOT contain business logic.
       Button.tsx
       ...
    layout/                 # Layout components (Header, Footer, Sidebar). MUST contain components structuring page layouts, not specific page content.
       Header.tsx
       ...
    (feature-specific)/     # Components specific to a feature but potentially reusable within it. This is an alternative to co-locating within features/ directory.
        user-profile/
            ProfileCard.tsx
 features/                   # Feature-specific logic, hooks, non-global state, services, and components solely used by that feature.
    auth/
        components/         # Components used exclusively by the auth feature. MUST NOT be imported by other features.
        hooks/              # Custom React Hooks specific to the 'auth' feature. Hooks reusable across features belong in `src/hooks/`.
        services/           # Feature-specific API interactions or orchestrations for the 'auth' feature.
        store.ts            # Feature-specific state slice (e.g., Redux slice) if not part of a global store or if local state is complex.
 hooks/                      # Global/sharable custom React Hooks. MUST be generic and usable by multiple features/components.
    useAuth.ts
 lib/ / utils/             # Utility functions, helpers, constants. MUST contain pure functions and constants, no side effects or framework-specific code unless clearly named (e.g., `react-helpers.ts`).
    utils.ts
 services/                   # Global API service clients or SDK configurations. MUST define base API client instances and core data fetching/mutation services.
    apiClient.ts
 store/                      # Global state management setup (e.g., Redux store, Zustand store).
    index.ts                # Main store configuration and export.
    rootReducer.ts          # Root reducer if using Redux.
    (slices)/               # Directory for global state slices (if not co-located in features).
 styles/                     # Global styles, theme configurations (if not using `globals.css` or similar, or for specific styling systems like SCSS partials).
 types/                      # Global TypeScript type definitions/interfaces. MUST contain types shared across multiple features/modules.
     index.ts
```

### Notes on Frontend Structure:

{ Explain any specific conventions or rationale behind the structure. e.g., "Components are co-located with their feature if not globally reusable to improve modularity." AI Agent MUST adhere to this defined structure strictly. New files MUST be placed in the appropriate directory based on these descriptions. }

## Component Breakdown & Implementation Details

{ This section outlines the conventions and templates for defining UI components. Detailed specification for most feature-specific components will emerge as user stories are implemented. The AI agent MUST follow the "Template for Component Specification" below whenever a new component is identified for development. }

### Component Naming & Organization

- **Component Naming Convention:** **{e.g., PascalCase for files and component names: `UserProfileCard.tsx`}**. All component files MUST follow this convention.
- **Organization:** {e.g., "Globally reusable components in `src/components/ui/` or `src/components/layout/`. Feature-specific components co-located within their feature directory, e.g., `src/features/feature-name/components/`. Refer to Detailed Frontend Directory Structure.}

### Template for Component Specification

{ For each significant UI component identified from the UI/UX Specification and design files (Figma), the following details MUST be provided. Repeat this subsection for each component. The level of detail MUST be sufficient for an AI agent or developer to implement it with minimal ambiguity. }

#### Component: `{ComponentName}` (e.g., `UserProfileCard`, `ProductDetailsView`)

- **Purpose:** {Briefly describe what this component does and its role in the UI. MUST be clear and concise.}
- **Source File(s):** {e.g., `src/components/user-profile/UserProfileCard.tsx`. MUST be the exact path.}
- **Visual Reference:** {Link to specific Figma frame/component, or Storybook page. REQUIRED.}
- **Props (Properties):**
  { List each prop the component accepts. For each prop, all columns in the table MUST be filled. }
  | Prop Name | Type                                      | Required? | Default Value | Description                                                                                                |
  | :-------------- | :---------------------------------------- | :-------- | :------------ | :--------------------------------------------------------------------------------------------------------- |
  | `userId`        | `string`                                  | Yes       | N/A           | The ID of the user to display. MUST be a valid UUID.                                                     |
  | `avatarUrl`     | `string \| null`                          | No        | `null`        | URL for the user\'s avatar image. MUST be a valid HTTPS URL if provided.                                    |
  | `onEdit`        | `() => void`                              | No        | N/A           | Callback function when an edit action is triggered.                                                        |
  | `variant`       | `\'compact\' \| \'full\'`                     | No        | `\'full\'`        | Controls the display mode of the card.                                                                   |
  | `{anotherProp}` | `{Specific primitive, imported type, or inline interface/type definition}` | {Yes/No}  | {If any}    | {MUST clearly state the prop\'s purpose and any constraints, e.g., \'Must be a positive integer.\'}         |
- **Internal State (if any):**
  { Describe any significant internal state the component manages. Only list state that is *not* derived from props or global state. If state is complex, consider if it should be managed by a custom hook or global state solution instead. }
  | State Variable | Type      | Initial Value | Description                                                                    |
  | :-------------- | :-------- | :------------ | :----------------------------------------------------------------------------- |
  | `isLoading`     | `boolean` | `false`       | Tracks if data for the component is loading.                                   |
  | `{anotherState}`| `{type}`  | `{value}`     | {Description of state variable and its purpose.}                               |
- **Key UI Elements / Structure:**
  { Provide a pseudo-HTML or JSX-like structure representing the component\'s DOM. Include key conditional rendering logic if applicable. **This structure dictates the primary output for the AI agent.** }
  ```html
  <div> <!-- Main card container with specific class e.g., styles.cardFull or styles.cardCompact based on variant prop -->
    <img src="{avatarUrl || defaultAvatar}" alt="User Avatar" class="{styles.avatar}" />
    <h2>{userName}</h2>
    <p class="{variant === 'full' ? styles.emailFull : styles.emailCompact}">{userEmail}</p>
    {variant === 'full' && onEdit && <button onClick={onEdit} class="{styles.editButton}">Edit</button>}
  </div>
  ```
- **Events Handled / Emitted:**
  - **Handles:** {e.g., `onClick` on the edit button (triggers `onEdit` prop).}
  - **Emits:** {If the component emits custom events/callbacks not covered by props, describe them with their exact signature. e.g., `onFollow: (payload: { userId: string; followed: boolean }) => void`}
- **Actions Triggered (Side Effects):**
  - **State Management:** {e.g., "Dispatches `userSlice.actions.setUserName(newName)` from `src/store/slices/userSlice.ts`. Action payload MUST match the defined action creator." OR "Calls `updateUserProfileOptimistic(newData)` from a local `useReducer` hook."}
  - **API Calls:** {Specify which service/function from the "API Interaction Layer" is called. e.g., "Calls `userService.fetchUser(userId)` from `src/services/userService.ts` on mount. Request payload: `{ userId }`. Success response populates internal state `userData`. Error response dispatches `uiSlice.actions.showErrorToast({ message: 'Failed to load user details' })`.}
- **Styling Notes:**
  - {MUST reference specific Design System component names (e.g., "Uses `<Button variant='primary'>` from UI library") OR specify Tailwind CSS classes / CSS module class names to be applied (e.g., "Container uses `p-4 bg-white rounded-lg shadow-md`. Title uses `text-xl font-semibold`.") OR specify SCSS custom component classes to be applied (e.g., "Container uses `@apply p-4 bg-white rounded-lg shadow-md`. Title uses `@apply text-xl font-semibold`."). Any dynamic styling logic based on props or state MUST be described. If Tailwind CSS is used, list primary utility classes or `@apply` directives for custom component classes. AI Agent should prioritize direct utility class usage for simple cases and propose reusable component classes/React components for complex styling patterns.}
- **Accessibility Notes:**
  - {MUST list specific ARIA attributes and their values (e.g., `aria-label="User profile card"`, `role="article"`), required keyboard navigation behavior (e.g., "Tab navigates to avatar, name, email, then edit button. Edit button is focusable and activated by Enter/Space."), and any focus management requirements (e.g., "If this component opens a modal, focus MUST be trapped inside. On modal close, focus returns to the trigger element.").}

---

_Repeat the above template for each significant component._

---

## State Management In-Depth

{ This section expands on the State Management strategy. **Refer to the main Architecture Document for the definitive choice of state management solution.** }

- **Chosen Solution:** {e.g., Redux Toolkit, Zustand, Vuex, NgRx - As defined in main arch doc.}
- **Decision Guide for State Location:**
    - **Global State (e.g., Redux/Zustand):** Data shared across many unrelated components; data persisting across routes; complex state logic managed via reducers/thunks. **MUST be used for session data, user preferences, application-wide notifications.**
    - **React Context API:** State primarily passed down a specific component subtree (e.g., theme, form context). Simpler state, fewer updates compared to global state. **MUST be used for localized state not suitable for prop drilling but not needed globally.**
    - **Local Component State (`useState`, `useReducer`):** UI-specific state, not needed outside the component or its direct children (e.g., form input values, dropdown open/close status). **MUST be the default choice unless criteria for Context or Global State are met.**

### Store Structure / Slices

{ Describe the conventions for organizing the global state (e.g., "Each major feature requiring global state will have its own Redux slice located in `src/features/[featureName]/store.ts`"). }

- **Core Slice Example (e.g., `sessionSlice` in `src/store/slices/sessionSlice.ts`):**
  - **Purpose:** {Manages user session, authentication status, and basic user profile info accessible globally.}
  - **State Shape (Interface/Type):**
    ```typescript
    interface SessionState {
      currentUser: { id: string; name: string; email: string; roles: string[]; } | null;
      isAuthenticated: boolean;
      token: string | null;
      status: "idle" | "loading" | "succeeded" | "failed";
      error: string | null;
    }
    ```
  - **Key Reducers/Actions (within `createSlice`):** {Briefly list main synchronous actions, e.g., `setCurrentUser`, `clearSession`, `setAuthStatus`, `setAuthError`.}
  - **Async Thunks (if any):** {List key async thunks, e.g., `loginUserThunk`, `fetchUserProfileThunk`.}
  - **Selectors (memoized with `createSelector`):** {List key selectors, e.g., `selectCurrentUser`, `selectIsAuthenticated`.}
- **Feature Slice Template (e.g., `{featureName}Slice` in `src/features/{featureName}/store.ts`):**
  - **Purpose:** {To be filled out when a new feature requires its own state slice.}
  - **State Shape (Interface/Type):** {To be defined by the feature.}
  - **Key Reducers/Actions (within `createSlice`):** {To be defined by the feature.}
  - **Async Thunks (if any, defined using `createAsyncThunk`):** {To be defined by the feature.}
  - **Selectors (memoized with `createSelector`):** {To be defined by the feature.}
  - **Export:** {All actions and selectors MUST be exported.}

### Key Selectors

{ List important selectors for any core, upfront slices. For emergent feature slices, selectors will be defined with the slice. **ALL selectors deriving data or combining multiple state pieces MUST use `createSelector` from Reselect (or equivalent for other state libraries) for memoization.** }

- **`selectCurrentUser` (from `sessionSlice`):** {Returns the `currentUser` object.}
- **`selectIsAuthenticated` (from `sessionSlice`):** {Returns `isAuthenticated` boolean.}
- **`selectAuthToken` (from `sessionSlice`):** {Returns the `token` from `sessionSlice`.}

### Key Actions / Reducers / Thunks

{ Detail more complex actions for core, upfront slices, especially asynchronous thunks or sagas. Each thunk MUST clearly define its purpose, parameters, API calls made (referencing the API Interaction Layer), and how it updates the state on pending, fulfilled, and rejected states. }

- **Core Action/Thunk Example: `authenticateUser(credentials: AuthCredentials)` (in `sessionSlice.ts`):**
  - **Purpose:** {Handles user login by calling the auth API and updating the `sessionSlice`.}
  - **Parameters:** `credentials: { email: string; password: string }`
  - **Dispatch Flow (using Redux Toolkit `createAsyncThunk`):**
    1. On `pending`: Dispatches `sessionSlice.actions.setAuthStatus('loading')`.
    2. Calls `authService.login(credentials)` (from `src/services/authService.ts`).
    3. On `fulfilled` (success): Dispatches `sessionSlice.actions.setCurrentUser(response.data.user)`, `sessionSlice.actions.setToken(response.data.token)`, `sessionSlice.actions.setAuthStatus('succeeded')`.
    4. On `rejected` (error): Dispatches `sessionSlice.actions.setAuthError(error.message)`, `sessionSlice.actions.setAuthStatus('failed')`.
- **Feature Action/Thunk Template: `{featureActionName}` (in `{featureName}Slice.ts`):**
  - **Purpose:** {To be filled out for feature-specific async operations.}
  - **Parameters:** {Define specific parameters with types.}
  - **Dispatch Flow (using `createAsyncThunk`):** {To be defined by the feature, following similar patterns for pending, fulfilled, rejected states, including API calls and state updates.}

## API Interaction Layer

{ Describe how the frontend communicates with the backend APIs defined in the main Architecture Document. }

### Client/Service Structure

- **HTTP Client Setup:** {e.g., Axios instance in `src/services/apiClient.ts`. **MUST** include: Base URL (from environment variable `NEXT_PUBLIC_API_URL` or equivalent), default headers (e.g., `Content-Type: 'application/json'`), interceptors for automatic auth token injection (from state management, e.g., `sessionSlice.token`) and standardized error handling/normalization (see below).}
- **Service Definitions (Example):**
  - **`userService.ts` (in `src/services/userService.ts`):**
    - **Purpose:** {Handles all API interactions related to users.}
    - **Functions:** Each service function MUST have explicit parameter types, a return type (e.g., `Promise<User>`), JSDoc/TSDoc explaining purpose, params, return value, and any specific error handling. It MUST call the configured HTTP client (`apiClient`) with correct endpoint, method, and payload.
      - `fetchUser(userId: string): Promise<User>`
      - `updateUserProfile(userId: string, data: UserProfileUpdateDto): Promise<User>`
  - **`productService.ts` (in `src/services/productService.ts`):**
    - **Purpose:** {...}
    - **Functions:** {...}

### Error Handling & Retries (Frontend)

- **Global Error Handling:** {How are API errors caught globally? (e.g., Via Axios response interceptor in `apiClient.ts`). How are they presented/logged? (e.g., Dispatches `uiSlice.actions.showGlobalErrorBanner({ message: error.message })`, logs detailed error to console/monitoring service). Is there a global error state? (e.g., `uiSlice.error`).}
- **Specific Error Handling:** {Components MAY handle specific API errors locally for more contextual feedback (e.g., displaying an inline message on a form field: "Invalid email address"). This MUST be documented in the component's specification if it deviates from global handling.}
- **Retry Logic:** {Is client-side retry logic implemented (e.g., using `axios-retry` with `apiClient`)? If so, specify configuration: max retries (e.g., 3), retry conditions (e.g., network errors, 5xx server errors), retry delay (e.g., exponential backoff). **MUST apply only to idempotent requests (GET, PUT, DELETE).**}

## Routing Strategy

{ Detail how navigation and routing are handled in the frontend application. }

- **Routing Library:** {e.g., React Router, Next.js App Router, Vue Router, Angular Router. As per main Architecture Document.}

### Route Definitions

{ List the main routes of the application and the primary component/page rendered for each. }

| Path Pattern           | Component/Page (`src/app/...` or `src/pages/...`) | Protection                      | Notes                                                 |
| :--------------------- | :-------------------------------------------------- | :------------------------------ | :---------------------------------------------------- |
| `/`                    | `app/page.tsx` or `pages/HomePage.tsx`              | `Public`                        |                                                       |
| `/login`               | `app/login/page.tsx` or `pages/LoginPage.tsx`       | `Public` (redirect if auth)     | Redirects to `/dashboard` if already authenticated.   |
| `/dashboard`           | `app/dashboard/page.tsx` or `pages/DashboardPage.tsx` | `Authenticated`                 |                                                       |
| `/products`            | `app/products/page.tsx`                             | `Public`                        |                                                       |
| `/products/:productId` | `app/products/[productId]/page.tsx`                 | `Public`                        | Parameter: `productId` (string)                       |
| `/settings/profile`    | `app/settings/profile/page.tsx`                     | `Authenticated`, `Role:[USER]`  | Example of role-based protection.                   |
| `{anotherRoute}`       | `{ComponentPath}`                                   | `{Public/Authenticated/Role:[ROLE_NAME]}` | {Notes, parameter names and types}                    |

### Route Guards / Protection

- **Authentication Guard:** {Describe how routes are protected based on authentication status. **Specify the exact HOC, hook, layout, or middleware mechanism and its location** (e.g., `src/guards/AuthGuard.tsx`, or Next.js middleware in `middleware.ts`). Logic MUST use authentication state from the `sessionSlice` (or equivalent). Unauthenticated users attempting to access protected routes MUST be redirected to `/login` (or specified login path).}
- **Authorization Guard (if applicable):** {Describe how routes might be protected based on user roles or permissions. **Specify the exact mechanism**, similar to Auth Guard. Unauthorized users (authenticated but lacking permissions) MUST be shown a "Forbidden" page or redirected to a safe page.}

## Build, Bundling, and Deployment

{ Details specific to the frontend build and deployment process, complementing the "Infrastructure and Deployment Overview" in the main architecture document. }

### Build Process & Scripts

- **Key Build Scripts (from `package.json`):** {e.g., `"build": "next build"`. What do they do? Point to `package.json` scripts. `"dev": "next dev"`, `"start": "next start"`.}. **AI Agent MUST NOT generate code that hardcodes environment-specific values. All such values MUST be accessed via the defined environment configuration mechanism.** Specify the exact files and access method.
- **Environment Configuration Management:** {How are `process.env.NEXT_PUBLIC_API_URL` (or equivalent like `import.meta.env.VITE_API_URL`) managed for different environments (dev, staging, prod)? (e.g., `.env`, `.env.development`, `.env.production` files for Next.js/Vite; build-time injection via CI variables). Specify the exact files and access method.}

### Key Bundling Optimizations

- **Code Splitting:** {How is it implemented/ensured? (e.g., "Next.js/Vite handles route-based code splitting automatically. For component-level code splitting, dynamic imports `React.lazy(() => import('./MyComponent'))` or `import('./heavy-module')` MUST be used for non-critical large components/libraries.")}
- **Tree Shaking:** {How is it implemented/ensured? (e.g., "Ensured by modern build tools like Webpack/Rollup (used by Next.js/Vite) when using ES Modules. Avoid side-effectful imports in shared libraries.")}
- **Lazy Loading (Components, Images, etc.):** {Strategy for lazy loading. (e.g., "Components: `React.lazy` with `Suspense`. Images: Use framework-specific Image component like `next/image` which handles lazy loading by default, or `loading='lazy'` attribute for standard `<img>` tags.")}
- **Minification & Compression:** {Handled by build tools (e.g., Webpack/Terser, Vite/esbuild)? Specify if any specific configuration is needed. Compression (e.g., Gzip, Brotli) is typically handled by the hosting platform/CDN.}

### Deployment to CDN/Hosting

- **Target Platform:** {e.g., Vercel, Netlify, AWS S3/CloudFront, Azure Static Web Apps. As per main Architecture Document.}
- **Deployment Trigger:** {e.g., Git push to `main` branch via GitHub Actions (referencing main CI/CD pipeline).}
- **Asset Caching Strategy:** {How are static assets cached? (e.g., "Immutable assets (JS/CSS bundles with content hashes) have `Cache-Control: public, max-age=31536000, immutable`. HTML files have `Cache-Control: no-cache` or short max-age (e.g., `public, max-age=0, must-revalidate`) to ensure users get fresh entry points. Configured via {hosting platform settings / `next.config.js` headers / CDN rules}.}

## Frontend Testing Strategy

{ This section elaborates on the "Testing Strategy" from the main architecture document, focusing on frontend-specific aspects. **Refer to the main Architecture Document for definitive choices of testing tools.** }

- **Link to Main Overall Testing Strategy:** {Reference the main `docs/architecture.md#overall-testing-strategy` or equivalent.}

### Component Testing

- **Scope:** {Testing individual UI components in isolation (similar to unit tests for components).}
- **Tools:** {e.g., React Testing Library with Jest, Vitest, Vue Test Utils, Angular Testing Utilities. As per main Arch Doc.}
- **Focus:** {Rendering with various props, user interactions (clicks, input changes using `fireEvent` or `userEvent`), event emission, basic internal state changes. **Snapshot testing MUST be used sparingly and with clear justification (e.g., for very stable, purely presentational components with complex DOM structure); prefer explicit assertions.**}
- **Location:** {e.g., `*.test.tsx` or `*.spec.tsx` co-located alongside components, or in a `__tests__` subdirectory.}

### Feature/Flow Testing (UI Integration)

- **Scope:** {Testing how multiple components interact to fulfill a small user flow or feature within a page, potentially mocking API calls or global state management. e.g., testing a complete form submission within a feature, including validation and interaction with a mocked service layer.}
- **Tools:** {Same as component testing (e.g., React Testing Library with Jest/Vitest), but with more complex setups involving mock providers for routing, state, API calls.}
- **Focus:** {Data flow between components, conditional rendering based on interactions, navigation within a feature, integration with mocked services/state.}

### End-to-End UI Testing Tools & Scope

- **Tools:** {Reiterate from main Testing Strategy, e.g., Playwright, Cypress, Selenium.}
- **Scope (Frontend Focus):** {Define 3-5 key user journeys that MUST be covered by E2E UI tests from a UI perspective, e.g., "User registration and login flow", "Adding an item to cart and proceeding to the checkout page summary", "Submitting a complex multi-step form and verifying success UI state and data persistence (via API mocks or a test backend)."}
- **Test Data Management for UI:** {How is consistent test data seeded or mocked for UI E2E tests? (e.g., API mocking layer like MSW, backend seeding scripts, dedicated test accounts).}

## Accessibility (AX) Implementation Details

{ Based on the AX requirements in the UI/UX Specification, detail how these will be technically implemented. }

- **Semantic HTML:** {Emphasis on using correct HTML5 elements. **AI Agent MUST prioritize semantic elements (e.g., `<nav>`, `<button>`, `<article>`) over generic `<div>`/`<span>` with ARIA roles where a native element with the correct semantics exists.**}
- **ARIA Implementation:** {Specify common custom components and their required ARIA patterns (e.g., "Custom select dropdown MUST follow ARIA Combobox pattern including `aria-expanded`, `aria-controls`, `role='combobox'`, etc. Custom Tabs MUST follow ARIA Tabbed Interface pattern."). Link to ARIA Authoring Practices Guide (APG) for reference.}
- **Keyboard Navigation:** {Ensuring all interactive elements are focusable and operable via keyboard. Focus order MUST be logical. Custom components MUST implement keyboard interaction patterns as per ARIA APG (e.g., arrow keys for radio groups/sliders).**}
- **Focus Management:** {How is focus managed in modals, dynamic content changes, route transitions? (e.g., "Modals MUST trap focus. On modal open, focus moves to the first focusable element or the modal container. On close, focus returns to the trigger element. Route changes SHOULD move focus to the main content area or H1 of the new page.")}
- **Testing Tools for AX:** {e.g., Axe DevTools browser extension, Lighthouse accessibility audit. **Automated Axe scans (e.g., using `jest-axe` for component tests, or Playwright/Cypress Axe integration for E2E tests) MUST be integrated into the CI pipeline and fail the build on new violations of WCAG AA (or specified level).** Manual testing procedures: {List key manual checks, e.g., keyboard-only navigation for all interactive elements, screen reader testing (e.g., NVDA/JAWS/VoiceOver) for critical user flows.}}

## Performance Considerations

{ Highlight frontend-specific performance optimization strategies. }

- **Image Optimization:** {Formats (e.g., WebP), responsive images (`<picture>`, `srcset`), lazy loading.}
  - Implementation Mandate: {e.g., "All images MUST use `<Image>` component from Next.js (or equivalent framework-specific optimizer). SVGs for icons. WebP format preferred where supported."}
- **Code Splitting & Lazy Loading (reiterate from Build section if needed):** {How it impacts perceived performance.}
  - Implementation Mandate: {e.g., "Next.js handles route-based code splitting automatically. Dynamic imports `import()` MUST be used for component-level lazy loading."}
- **Minimizing Re-renders:** {Techniques like `React.memo`, `shouldComponentUpdate`, optimized selectors.}
  - Implementation Mandate: {e.g., "`React.memo` MUST be used for components that render frequently with same props. Selectors for global state MUST be memoized (e.g., with Reselect). Avoid passing new object/array literals or inline functions as props directly in render methods where it can cause unnecessary re-renders."}
- **Debouncing/Throttling:** {For event handlers like search input or window resize.}
  - Implementation Mandate: {e.g., "Use a utility like `lodash.debounce` or `lodash.throttle` for specified event handlers. Define debounce/throttle wait times."}
- **Virtualization:** {For long lists or large data sets (e.g., React Virtualized, TanStack Virtual).}
  - Implementation Mandate: {e.g., "MUST be used for any list rendering more than {N, e.g., 100} items if performance degradation is observed."}
- **Caching Strategies (Client-Side):** {Use of browser cache, service workers for PWA capabilities (if applicable).}
  - Implementation Mandate: {e.g., "Configure service worker (if PWA) to cache application shell and key static assets. Leverage HTTP caching headers for other assets as defined in Deployment section."}
- **Performance Monitoring Tools:** {e.g., Lighthouse, WebPageTest, browser DevTools performance tab. Specify which ones are primary and any automated checks in CI.}

## Internationalization (i18n) and Localization (l10n) Strategy

{This section defines the strategy for supporting multiple languages and regional differences if applicable. If not applicable, state "Internationalization is not a requirement for this project at this time."}

- **Requirement Level:** {e.g., Not Required, Required for specific languages [list them], Fully internationalized for future expansion.}
- **Chosen i18n Library/Framework:** {e.g., `react-i18next`, `vue-i18n`, `ngx-translate`, framework-native solution like Next.js i18n routing. Specify the exact library/mechanism.}
- **Translation File Structure & Format:** {e.g., JSON files per language per feature (`src/features/{featureName}/locales/{lang}.json`), or global files (`public/locales/{lang}.json`). Define the exact path and format (e.g., flat JSON, nested JSON).}
- **Translation Key Naming Convention:** {e.g., `featureName.componentName.elementText`, `common.submitButton`. MUST be a clear, consistent, and documented pattern.}
- **Process for Adding New Translatable Strings:** {e.g., "AI Agent MUST add new keys to the default language file (e.g., `en.json`) and use the i18n library's functions/components (e.g., `<Trans>` component, `t()` function) to render text. Keys MUST NOT be constructed dynamically at runtime in a way that prevents static analysis."}
- **Handling Pluralization:** {Specify method/syntax, e.g., using ICU message format via the chosen library (e.g., `t('key', { count: N })`).}
- **Date, Time, and Number Formatting:** {Specify if the i18n library handles this, or if another library (e.g., `date-fns-tz` with locale support, `Intl` API directly) and specific formats/styles should be used for each locale.}
- **Default Language:** {e.g., `en-US`}
- **Language Switching Mechanism (if applicable):** {How is the language changed by the user and persisted? e.g., "Via a language selector component that updates a global state/cookie and potentially alters the URL route."}

## Feature Flag Management

{This section outlines how conditionally enabled features are managed. If not applicable, state "Feature flags are not a primary architectural concern for this project at this time."}

- **Requirement Level:** {e.g., Not Required, Used for specific rollouts, Core part of development workflow.}
- **Chosen Feature Flag System/Library:** {e.g., LaunchDarkly, Unleash, Flagsmith, custom solution using environment variables or a configuration service. Specify the exact tool/method.}
- **Accessing Flags in Code:** {e.g., "Via a custom hook `useFeatureFlag('flag-name'): boolean` or a service `featureFlagService.isOn('flag-name')`. Specify the exact interface, location, and initialization of the service/provider."}
- **Flag Naming Convention:** {e.g., `[SCOPE]_[FEATURE_NAME]_[TARGET_GROUP_OR_TYPE]`, e.g., `CHECKOUT_NEW_PAYMENT_GATEWAY_ROLLOUT`, `USER_PROFILE_BETA_AVATAR_UPLOAD`. MUST be documented and consistently applied.}
- **Code Structure for Flagged Features:** {e.g., "Use conditional rendering (`{isFeatureEnabled && <NewComponent />}`). For larger features, conditionally import components (`React.lazy` with flag check) or routes. Avoid complex branching logic deep within shared components; prefer to flag at higher levels."}
- **Strategy for Code Cleanup (Post-Flag Retirement):** {e.g., "Once a flag is fully rolled out (100% users) and deemed permanent, or fully removed, all conditional logic, old code paths, and the flag itself MUST be removed from the codebase within {N, e.g., 2} sprints. This is a mandatory tech debt item."}
- **Testing Flagged Features:** {How are different flag variations tested? e.g., "QA team uses a debug panel to toggle flags. Automated E2E tests run with specific flag configurations."}

## Frontend Security Considerations

{This section highlights mandatory frontend-specific security practices, complementing the main Architecture Document. AI Agent MUST adhere to these guidelines.}

- **Cross-Site Scripting (XSS) Prevention:**
  - Framework Reliance: {e.g., "React's JSX auto-escaping MUST be relied upon for rendering dynamic content. Vue's `v-html` MUST be avoided unless content is explicitly sanitized."}
  - Explicit Sanitization: {If direct DOM manipulation is unavoidable (strongly discouraged), use {specific sanitization library/function like DOMPurify}. Specify its configuration.}
  - Content Security Policy (CSP): {Is a CSP implemented? How? e.g., "CSP is enforced via HTTP headers set by the backend/CDN as defined in the main Architecture doc. Frontend MAY need to ensure nonce usage for inline scripts if `unsafe-inline` is not allowed." Link to CSP definition if available.}
- **Cross-Site Request Forgery (CSRF) Protection (if applicable for session-based auth):**
  - Mechanism: {e.g., "Backend uses synchronizer token pattern. Frontend ensures tokens are included in state-changing requests if not handled automatically by HTTP client or forms." Refer to main Architecture Document for backend details.}
- **Secure Token Storage & Handling (for client-side tokens like JWTs):**
  - Storage Mechanism: {**MUST specify exact mechanism**: e.g., In-memory via state management (e.g., Redux/Zustand store, cleared on tab close), `HttpOnly` cookies (if backend sets them and frontend doesn't need to read them), `sessionStorage`. **`localStorage` is STRONGLY DISCOURAGED for token storage.**}
  - Token Refresh: {Describe client-side involvement, e.g., "Interceptor in `apiClient.ts` handles 401 errors to trigger token refresh endpoint."}
- **Third-Party Script Security:**
  - Policy: {e.g., "All third-party scripts (analytics, ads, widgets) MUST be vetted for necessity and security. Load scripts asynchronously (`async/defer`)."}
  - Subresource Integrity (SRI): {e.g., "SRI hashes MUST be used for all external scripts and stylesheets loaded from CDNs where the resource is stable."}
- **Client-Side Data Validation:**
  - Purpose: {e.g., "Client-side validation is for UX improvement (immediate feedback) ONLY. **All critical data validation MUST occur server-side** (as defined in the main Architecture Document)."}
  - Implementation: {e.g., "Use {form_library_name like Formik/React Hook Form} for form validation. Rules should mirror server-side validation where appropriate."}
- **Preventing Clickjacking:**
  - Mechanism: {e.g., "Primary defense is `X-Frame-Options` or `frame-ancestors` CSP directive, set by backend/CDN. Frontend code should not rely on frame-busting scripts."}
- **API Key Exposure (for client-side consumed services):**
  - Restriction: {e.g., "API keys for services like Google Maps (client-side JS SDK) MUST be restricted (e.g., HTTP referrer, IP address, API restrictions) via the service provider's console."}
  - Backend Proxy: {e.g., "For keys requiring more secrecy or involving sensitive operations, a backend proxy endpoint MUST be created; frontend calls the proxy, not the third-party service directly."}
- **Secure Communication (HTTPS):**
  - Mandate: {e.g., "All communication with backend APIs MUST use HTTPS. Mixed content (HTTP assets on HTTPS page) is forbidden."}
- **Dependency Vulnerabilities:**
  - Process: {e.g., "Run `npm audit --audit-level=high` (or equivalent) in CI. High/critical vulnerabilities MUST be addressed before deployment. Monitor Dependabot/Snyk alerts."}

## Browser Support and Progressive Enhancement

{This section defines the target browsers and how the application should behave in less capable or non-standard environments.}

- **Target Browsers:** {e.g., "Latest 2 stable versions of Chrome, Firefox, Safari, Edge. Specific versions can be listed if required by project constraints. Internet Explorer (any version) is NOT supported." MUST be explicit.}
- **Polyfill Strategy:**
  - Mechanism: {e.g., "Use `core-js@3` imported at the application entry point. Babel `preset-env` is configured with the above browser targets to include necessary polyfills."}
  - Specific Polyfills (if any beyond `core-js`): {List any other polyfills required for specific features, e.g., `smoothscroll-polyfill`.}
- **JavaScript Requirement & Progressive Enhancement:**
  - Baseline: {e.g., "Core application functionality REQUIRES JavaScript enabled in the browser." OR "Key content (e.g., articles, product information) and primary navigation MUST be accessible and readable without JavaScript. Interactive features and enhancements are layered on top with JavaScript (Progressive Enhancement approach)." Specify the chosen approach.}
  - No-JS Experience (if Progressive Enhancement): {Describe what works without JS. e.g., "Users can view pages and navigate. Forms may not submit or will use standard HTML submission."}
- **CSS Compatibility & Fallbacks:**
  - Tooling: {e.g., "Use Autoprefixer (via PostCSS) configured with the target browser list to add vendor prefixes."}
  - Feature Usage: {e.g., "Avoid CSS features not supported by >90% of target browsers unless a graceful degradation or fallback is explicitly defined and tested (e.g., using `@supports` queries)."}
- **Accessibility Fallbacks:** {Consider how features behave if certain ARIA versions or advanced accessibility features are not supported by older assistive technologies within the support matrix.}

## Change Log

| Change | Date | Version | Description | Author |
| ------ | ---- | ------- | ----------- | ------ |

==================== END: front-end-architecture-tmpl ====================


==================== START: front-end-spec-tmpl ====================
# {Project Name} UI/UX Specification

## Introduction

{State the purpose - to define the user experience goals, information architecture, user flows, and visual design specifications for the project's user interface.}

- **Link to Primary Design Files:** {e.g., Figma, Sketch, Adobe XD URL}
- **Link to Deployed Storybook / Design System:** {URL, if applicable}

## Overall UX Goals & Principles

- **Target User Personas:** {Reference personas or briefly describe key user types and their goals.}
- **Usability Goals:** {e.g., Ease of learning, efficiency of use, error prevention.}
- **Design Principles:** {List 3-5 core principles guiding the UI/UX design - e.g., "Clarity over cleverness", "Consistency", "Provide feedback".}

## Information Architecture (IA)

- **Site Map / Screen Inventory:**
  ```mermaid
  graph TD
      A[Homepage] --> B(Dashboard);
      A --> C{Settings};
      B --> D[View Details];
      C --> E[Profile Settings];
      C --> F[Notification Settings];
  ```
  _(Or provide a list of all screens/pages)_
- **Navigation Structure:** {Describe primary navigation (e.g., top bar, sidebar), secondary navigation, breadcrumbs, etc.}

## User Flows

{Detail key user tasks. Use diagrams or descriptions.}

### {User Flow Name, e.g., User Login}

- **Goal:** {What the user wants to achieve.}
- **Steps / Diagram:**
  ```mermaid
  graph TD
      Start --> EnterCredentials[Enter Email/Password];
      EnterCredentials --> ClickLogin[Click Login Button];
      ClickLogin --> CheckAuth{Auth OK?};
      CheckAuth -- Yes --> Dashboard;
      CheckAuth -- No --> ShowError[Show Error Message];
      ShowError --> EnterCredentials;
  ```
  _(Or: Link to specific flow diagram in Figma/Miro)_

### {Another User Flow Name}

{...}

## Wireframes & Mockups

{Reference the main design file link above. Optionally embed key mockups or describe main screen layouts.}

- **Screen / View Name 1:** {Description of layout and key elements. Link to specific Figma frame/page.}
- **Screen / View Name 2:** {...}

## Component Library / Design System Reference

## Branding & Style Guide Reference

{Link to the primary source or define key elements here.}

- **Color Palette:** {Primary, Secondary, Accent, Feedback colors (hex codes).}
- **Typography:** {Font families, sizes, weights for headings, body, etc.}
- **Iconography:** {Link to icon set, usage notes.}
- **Spacing & Grid:** {Define margins, padding, grid system rules.}

## Accessibility (AX) Requirements

- **Target Compliance:** {e.g., WCAG 2.1 AA}
- **Specific Requirements:** {Keyboard navigation patterns, ARIA landmarks/attributes for complex components, color contrast minimums.}

## Responsiveness

- **Breakpoints:** {Define pixel values for mobile, tablet, desktop, etc.}
- **Adaptation Strategy:** {Describe how layout and components adapt across breakpoints. Reference designs.}

## Change Log

| Change        | Date       | Version | Description         | Author         |
| ------------- | ---------- | ------- | ------------------- | -------------- |

==================== END: front-end-spec-tmpl ====================


==================== START: infrastructure-architecture-tmpl ====================
# {Project Name} Infrastructure Architecture

## Infrastructure Overview

- Cloud Provider(s)
- Core Services & Resources
- Regional Architecture
- Multi-environment Strategy

## Infrastructure as Code (IaC)

- Tools & Frameworks
- Repository Structure
- State Management
- Dependency Management

## Environment Configuration

- Environment Promotion Strategy
- Configuration Management
- Secret Management
- Feature Flag Integration

## Environment Transition Strategy

- Development to Production Pipeline
- Deployment Stages and Gates
- Approval Workflows and Authorities
- Rollback Procedures
- Change Cadence and Release Windows
- Environment-Specific Configuration Management

## Network Architecture

- VPC/VNET Design
- Subnet Strategy
- Security Groups & NACLs
- Load Balancers & API Gateways
- Service Mesh (if applicable)

## Compute Resources

- Container Strategy
- Serverless Architecture
- VM/Instance Configuration
- Auto-scaling Approach

## Data Resources

- Database Deployment Strategy
- Backup & Recovery
- Replication & Failover
- Data Migration Strategy

## Security Architecture

- IAM & Authentication
- Network Security
- Data Encryption
- Compliance Controls
- Security Scanning & Monitoring

## Shared Responsibility Model

- Cloud Provider Responsibilities
- Platform Team Responsibilities
- Development Team Responsibilities
- Security Team Responsibilities
- Operational Monitoring Ownership
- Incident Response Accountability Matrix

## Monitoring & Observability

- Metrics Collection
- Logging Strategy
- Tracing Implementation
- Alerting & Incident Response
- Dashboards & Visualization

## CI/CD Pipeline

- Pipeline Architecture
- Build Process
- Deployment Strategy
- Rollback Procedures
- Approval Gates

## Disaster Recovery

- Backup Strategy
- Recovery Procedures
- RTO & RPO Targets
- DR Testing Approach

## Cost Optimization

- Resource Sizing Strategy
- Reserved Instances/Commitments
- Cost Monitoring & Reporting
- Optimization Recommendations

## Infrastructure Verification

### Validation Framework

This infrastructure architecture will be validated using the comprehensive `infrastructure-checklist.md`, with particular focus on Section 12: Architecture Documentation Validation. The checklist ensures:

- Completeness of architecture documentation
- Consistency with broader system architecture
- Appropriate level of detail for different stakeholders
- Clear implementation guidance
- Future evolution considerations

### Validation Process

The architecture documentation validation should be performed:

- After initial architecture development
- After significant architecture changes
- Before major implementation phases
- During periodic architecture reviews

The Platform Engineer should use the infrastructure checklist to systematically validate all aspects of this architecture document.

## Infrastructure Evolution

- Technical Debt Inventory
- Planned Upgrades and Migrations
- Deprecation Schedule
- Technology Roadmap
- Capacity Planning
- Scalability Considerations

## Integration with Application Architecture

- Service-to-Infrastructure Mapping
- Application Dependency Matrix
- Performance Requirements Implementation
- Security Requirements Implementation
- Data Flow to Infrastructure Correlation
- API Gateway and Service Mesh Integration

## Cross-Team Collaboration

- Platform Engineer and Developer Touchpoints
- Frontend/Backend Integration Requirements
- Product Requirements to Infrastructure Mapping
- Architecture Decision Impact Analysis
- Design Architect UI/UX Infrastructure Requirements
- Analyst Research Integration

## Infrastructure Change Management

- Change Request Process
- Risk Assessment
- Testing Strategy
- Validation Procedures

==================== END: infrastructure-architecture-tmpl ====================


==================== START: prd-tmpl ====================
# {{Project Name}} Product Requirements Document (PRD)

[[LLM: If available, review any provided document or ask if any are optionally available: Project Brief]]

## Goals and Background Context

[[LLM: Populate the 2 child sections based on what we have received from user description or the provided brief. Allow user to review the 2 sections and offer changes before proceeding]]

### Goals

[[LLM: Bullet list of 1 line desired outcomes the PRD will deliver if successful - user and project desires]]

### Background Context

[[LLM: 1-2 short paragraphs summarizing the background context, such as what we learned in the brief without being redundant with the goals, what and why this solves a problem, what the current landscape or need is etc...]]

## Requirements

[[LLM: Draft the list of functional and non functional requirements under the two child sections, and immediately execute tasks#advanced-elicitation display]]

### Functional

[[LLM: Each Requirement will be a bullet markdown and an identifier sequence starting with FR`.]]
@{example: - FR6: The Todo List uses AI to detect and warn against adding potentially duplicate todo items that are worded differently.}

### Non Functional

[[LLM: Each Requirement will be a bullet markdown and an identifier sequence starting with NFR`.]]
@{example: - NFR1: AWS service usage **must** aim to stay within free-tier limits where feasible.}

^^CONDITION: has_ui^^

## User Interface Design Goals

[[LLM: Capture high-level UI/UX vision to guide Design Architect and to inform story creation. Steps:

1. Pre-fill all subsections with educated guesses based on project context
2. Present the complete rendered section to user
3. Clearly let the user know where assumptions were made
4. Ask targeted questions for unclear/missing elements or areas needing more specification
5. This is NOT detailed UI spec - focus on product vision and user goals
6. After section completion, immediately apply `tasks#advanced-elicitation` protocol]]

### Overall UX Vision

### Key Interaction Paradigms

### Core Screens and Views

[[LLM: From a product perspective, what are the most critical screens or views necessary to deliver the the PRD values and goals? This is meant to be Conceptual High Level to Drive Rough Epic or User Stories]]

@{example}

- Login Screen
- Main Dashboard
- Item Detail Page
- Settings Page
  @{/example}

### Accessibility: { None, WCAG, etc }

### Branding

[[LLM: Any known branding elements or style guides that must be incorporated?]]

@{example}

- Replicate the look and feel of early 1900s black and white cinema, including animated effects replicating film damage or projector glitches during page or state transitions.
- Attached is the full color pallet and tokens for our corporate branding.
  @{/example}

### Target Device and Platforms

@{example}
"Web Responsive, and all mobile platforms", "IPhone Only", "ASCII Windows Desktop"
@{/example}

^^/CONDITION: has_ui^^

## Technical Assumptions

[[LLM: Gather technical decisions that will guide the Architect. Steps:

1. Check if `data#technical-preferences` file exists - use it to pre-populate choices
2. Ask user about: languages, frameworks, starter templates, libraries, APIs, deployment targets
3. For unknowns, offer guidance based on project goals and MVP scope
4. Document ALL technical choices with rationale (why this choice fits the project)
5. These become constraints for the Architect - be specific and complete
6. After section completion, apply `tasks#advanced-elicitation` protocol.]]

### Repository Structure: { Monorepo, Polyrepo, etc...}

### Service Architecture

[[LLM: CRITICAL DECISION - Document the high-level service architecture (e.g., Monolith, Microservices, Serverless functions within a Monorepo).]]

### Testing requirements

[[LLM: CRITICAL DECISION - Document the testing requirements, unit only, integration, e2e, manual, need for manual testing convenience methods).]]

### Additional Technical Assumptions and Requests

[[LLM: Throughout the entire process of drafting this document, if any other technical assumptions are raised or discovered appropriate for the architect, add them here as additional bulleted items]]

## Epics

[[LLM: First, present a high-level list of all epics for user approval, the epic_list and immediately execute tasks#advanced-elicitation display. Each epic should have a title and a short (1 sentence) goal statement. This allows the user to review the overall structure before diving into details.

CRITICAL: Epics MUST be logically sequential following agile best practices:

- Each epic should deliver a significant, end-to-end, fully deployable increment of testable functionality
- Epic 1 must establish foundational project infrastructure (app setup, Git, CI/CD, core services) unless we are adding new functionality to an existing app, while also delivering an initial piece of functionality, even as simple as a health-check route or display of a simple canary page
- Each subsequent epic builds upon previous epics' functionality delivering major blocks of functionality that provide tangible value to users or business when deployed
- Not every project needs multiple epics, an epic needs to deliver value. For example, an API completed can deliver value even if a UI is not complete and planned for a separate epic.
- Err on the side of less epics, but let the user know your rationale and offer options for splitting them if it seems some are too large or focused on disparate things.
- Cross Cutting Concerns should flow through epics and stories and not be final stories. For example, adding a logging framework as a last story of an epic, or at the end of a project as a final epic or story would be terrible as we would not have logging from the beginning.]]

<<REPEAT: epic_list>>

- Epic{{epic_number}} {{epic_title}}: {{short_goal}}

<</REPEAT>>

@{example: epic_list}

1. Foundation & Core Infrastructure: Establish project setup, authentication, and basic user management
2. Core Business Entities: Create and manage primary domain objects with CRUD operations
3. User Workflows & Interactions: Enable key user journeys and business processes
4. Reporting & Analytics: Provide insights and data visualization for users

@{/example}

[[LLM: After the epic list is approved, present each `epic_details` with all its stories and acceptance criteria as a complete review unit and immediately execute tasks#advanced-elicitation display, before moving on to the next epic.]]

<<REPEAT: epic_details>>

## Epic {{epic_number}} {{epic_title}}

{{epic_goal}} [[LLM: Expanded goal - 2-3 sentences describing the objective and value all the stories will achieve]]

[[LLM: CRITICAL STORY SEQUENCING REQUIREMENTS:

- Stories within each epic MUST be logically sequential
- Each story should be a "vertical slice" delivering complete functionality
- No story should depend on work from a later story or epic
- Identify and note any direct prerequisite stories
- Focus on "what" and "why" not "how" (leave technical implementation to Architect) yet be precise enough to support a logical sequential order of operations from story to story.
- Ensure each story delivers clear user or business value, try to avoid enablers and build them into stories that deliver value.
- Size stories for AI agent execution: Each story must be completable by a single AI agent in one focused session without context overflow
- Think "junior developer working for 2-4 hours" - stories must be small, focused, and self-contained
- If a story seems complex, break it down further as long as it can deliver a vertical slice
- Each story should result in working, testable code before the agent's context window fills]]

<<REPEAT: story>>

### Story {{epic_number}}.{{story_number}} {{story_title}}

As a {{user_type}},
I want {{action}},
so that {{benefit}}.

#### Acceptance Criteria

[[LLM: Define clear, comprehensive, and testable acceptance criteria that:

- Precisely define what "done" means from a functional perspective
- Are unambiguous and serve as basis for verification
- Include any critical non-functional requirements from the PRD
- Consider local testability for backend/data components
- Specify UI/UX requirements and framework adherence where applicable
- Avoid cross-cutting concerns that should be in other stories or PRD sections]]

<<REPEAT: criteria>>

- {{criterion number}}: {{criteria}}

<</REPEAT>>
<</REPEAT>>
<</REPEAT>>

## Change Log

| Change | Date | Version | Description | Author |
| ------ | ---- | ------- | ----------- | ------ |

----- END PRD START CHECKLIST OUTPUT ------

## Checklist Results Report

[[LLM: Before running the checklist and drafting the prompts, offer to output the full updated PRD. If outputting it, confirm with the user that you will be proceeding to run the checklist and produce the report. Once the user confirms, execute the `pm-checklist` and populate the results in this section.]]

----- END Checklist START Design Architect `UI/UX Specification Mode` Prompt ------

## Design Architect Prompt

[[LLM: This section will contain the prompt for the Design Architect, keep it short and to the point to initiate create architecture mode using this document as input.]]

----- END Design Architect `UI/UX Specification Mode` Prompt START Architect Prompt ------

## Architect Prompt

[[LLM: This section will contain the prompt for the Architect, keep it short and to the point to initiate create architecture mode using this document as input.]]

----- END Architect Prompt ------

==================== END: prd-tmpl ====================


==================== START: project-brief-tmpl ====================
# Project Brief: {Project Name}

## Introduction / Problem Statement

{Describe the core idea, the problem being solved, or the opportunity being addressed. Why is this project needed?}

## Vision & Goals

- **Vision:** {Describe the high-level desired future state or impact of this project.}
- **Primary Goals:** {List 2-5 specific, measurable, achievable, relevant, time-bound (SMART) goals for the Minimum Viable Product (MVP).}
  - Goal 1: ...
  - Goal 2: ...
- **Success Metrics (Initial Ideas):** {How will we measure if the project/MVP is successful? List potential KPIs.}

## Target Audience / Users

{Describe the primary users of this product/system. Who are they? What are their key characteristics or needs relevant to this project?}

## Key Features / Scope (High-Level Ideas for MVP)

{List the core functionalities or features envisioned for the MVP. Keep this high-level; details will go in the PRD/Epics.}

- Feature Idea 1: ...
- Feature Idea 2: ...
- Feature Idea N: ...

## Post MVP Features / Scope and Ideas

{List the core functionalities or features envisioned as potential for POST MVP. Keep this high-level; details will go in the PRD/Epics/Architecture.}

- Feature Idea 1: ...
- Feature Idea 2: ...
- Feature Idea N: ...

## Known Technical Constraints or Preferences

- **Constraints:** {List any known limitations and technical mandates or preferences - e.g., budget, timeline, specific technology mandates, required integrations, compliance needs.}
- **Initial Architectural Preferences (if any):** {Capture any early thoughts or strong preferences regarding repository structure (e.g., monorepo, polyrepo) and overall service architecture (e.g., monolith, microservices, serverless components). This is not a final decision point but for initial awareness.}
- **Risks:** {Identify potential risks - e.g., technical challenges, resource availability, market acceptance, dependencies.}
- **User Preferences:** {Any specific requests from the user that are not a high level feature that could direct technology or library choices, or anything else that came up in the brainstorming or drafting of the PRD that is not included in prior document sections}

## Relevant Research (Optional)

{Link to or summarize findings from any initial research conducted (e.g., `deep-research-report-BA.md`).}

## PM Prompt

This Project Brief provides the full context for {Project Name}. Please start in 'PRD Generation Mode', review the brief thoroughly to work with the user to create the PRD section by section as the template indicates, asking for any necessary clarification or suggesting improvements as your mode 1 programming allows.

<example_handoff_prompt>
This Project Brief provides the full context for Mealmate. Please start in 'PRD Generation Mode', review the brief thoroughly to work with the user to create the PRD section by section 1 at a time, asking for any necessary clarification or suggesting improvements as your mode 1 programming allows.</example_handoff_prompt>

==================== END: project-brief-tmpl ====================


==================== START: story-tmpl ====================
# Story {EpicNum}.{StoryNum}: {Short Title Copied from Epic File}

## Status: { Draft | Approved | InProgress | Review | Done }

## Story

- As a [role]
- I want [action]
- so that [benefit]

## Acceptance Criteria (ACs)

{ Copy the Acceptance Criteria numbered list }

## Tasks / Subtasks

- [ ] Task 1 (AC: # if applicable)
  - [ ] Subtask1.1...
- [ ] Task 2 (AC: # if applicable)
  - [ ] Subtask 2.1...
- [ ] Task 3 (AC: # if applicable)
  - [ ] Subtask 3.1...

## Dev Technical Guidance {detail not covered in tasks/subtasks}

## Story Progress Notes

### Agent Model Used: `<Agent Model Name/Version>`

### Completion Notes List

{Any notes about implementation choices, difficulties, or follow-up needed}

### Change Log

==================== END: story-tmpl ====================


==================== START: template-format ====================
# MD Template Format:

- {{placeholder}} = Simple text replacement placeholder
- [[LLM: instruction]] = Instructions for the LLM (not included in output)
- <<REPEAT: section_name>> ... <</REPEAT>> = Repeating section
- ^^CONDITION: condition_name^^ ... ^^/CONDITION: condition_name^^ = Conditional section that will render if the condition_name logically applies
- @{example: content} = Single line example content for LLM guidance - do not render
- @{example} ... @{/example} = Multi-line example content for LLM guidance - do not render

## Critical Template Usage Rules

- CRITICAL: Never display or output template markup formatting, LLM instructions or examples
  - they MUST be used by you the agent only, AND NEVER shown to users in chat or documented output\*\*
- Present only the final, clean content to users
- Replace template variables with actual project-specific content
- Show examples only when they add value, without the markup
- Process all conditional logic internally - show only relevant sections
- For Canvas mode: Update the document with clean, formatted content only

@{example}

# My Template Foo

[[LLM: Check the current system date and if the user name is unknown, just say hello]]
Hello {{users name}}, this is your foo report for {{todays date}}

<<REPEAT: single_foo>>
[[LLM: For Each Foo, Create a matching creative Bar]]

## Foo: {{Bar}}

<</REPEAT>>

^^CONDITION: if_BAZ_exists^^

## BAZ

### You haz BAZ! Here is your daily Baz Forecast!

[[LLM: Give the user their daily baz report here]]
^^/CONDITION: if_BAZ_exists^^

@{/example}

==================== END: template-format ====================
