From 0955c6fda3b426caae84bd2a32fbd5ce01d74663 Mon Sep 17 00:00:00 2001 From: Brian Madison Date: Tue, 13 May 2025 19:05:18 -0500 Subject: [PATCH] formatting more verbose info about not wrapping output parent in markdown --- ...references.md => technical-preferences.md} | 0 BETA-V3/templates/architecture-tmpl.txt | 277 +++++++++---- .../templates/front-end-architecture-tmpl.txt | 378 +++++++++++------- BETA-V3/templates/prd-tmpl.txt | 8 +- BETA-V3/templates/story-tmpl.txt | 2 + BETA-V3/web-agent-modes/1-analyst.md | 19 + BETA-V3/web-agent-modes/2-pm.md | 63 ++- BETA-V3/web-agent-modes/3-architect.md | 50 ++- BETA-V3/web-agent-modes/4-design-architect.md | 19 + BETA-V3/web-agent-modes/5-posm.md | 19 + BETA-V3/web-agent-modes/6-rte.md | 19 + 11 files changed, 586 insertions(+), 268 deletions(-) rename BETA-V3/docs/{preferred-patterns-and-preferences.md => technical-preferences.md} (100%) diff --git a/BETA-V3/docs/preferred-patterns-and-preferences.md b/BETA-V3/docs/technical-preferences.md similarity index 100% rename from BETA-V3/docs/preferred-patterns-and-preferences.md rename to BETA-V3/docs/technical-preferences.md diff --git a/BETA-V3/templates/architecture-tmpl.txt b/BETA-V3/templates/architecture-tmpl.txt index 6dccde9b..c60dba25 100644 --- a/BETA-V3/templates/architecture-tmpl.txt +++ b/BETA-V3/templates/architecture-tmpl.txt @@ -1,39 +1,16 @@ # {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](#technical-summary) -- [High-Level Overview](#high-level-overview) -- [Component View](#component-view) - - [Architectural / Design Patterns Adopted](#architectural--design-patterns-adopted) -- [API Reference](#api-reference) - - [External APIs Consumed](#external-apis-consumed) - - [{Another External Service Name} API](#another-external-service-name-api) - - [Internal APIs Provided (If Applicable)](#internal-apis-provided-if-applicable) -- [Data Models](#data-models) - - [Core Application Entities / Domain Objects](#core-application-entities--domain-objects) - - [API Payload Schemas (If distinct)](#api-payload-schemas-if-distinct) - - [Database Schemas (If applicable)](#database-schemas-if-applicable) - - [State File Schemas (If applicable)](#state-file-schemas-if-applicable) -- [Core Workflow / Sequence Diagrams](#core-workflow--sequence-diagrams) -- [Definitive Tech Stack Selections](#definitive-tech-stack-selections) -- [Infrastructure and Deployment Overview](#infrastructure-and-deployment-overview) -- [Error Handling Strategy](#error-handling-strategy) -- [Environment Vars Templates](#environment-vars-templates) - - [Configuration Loading Mechanism](#configuration-loading-mechanism) - - [Required Variables](#required-variables) - - [Env Var Notes](#env-var-notes) -- [Security Best Practices](#security-best-practices) -- [Testing Strategy](#testing-strategy) - - [Overall Philosophy & Goals](#overall-philosophy--goals) - - [Testing Levels](#testing-levels) - - [Specialized Testing Types (Add section as needed)](#specialized-testing-types-add-section-as-needed) - - [Test Data Management](#test-data-management) -- [Key Reference Documents](#key-reference-documents) -- [Change Log](#change-log) - ## 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. } @@ -64,6 +41,68 @@ - **Pattern 2:** {e.g., Dependency Injection, Repository Pattern, Module Pattern} - _Rationale/Reference:_ {...} - **Pattern N:** {...} +## 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 @@ -90,10 +129,6 @@ - **Rate Limits:** {If known} - **Link to Official Docs:** {URL} -### {Another External Service Name} API - -{...} - ### 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.} @@ -134,15 +169,11 @@ _(Alternatively, use JSON Schema, class definitions, or other relevant format)_ - **Validation Rules:** {List any specific validation rules beyond basic types - e.g., max length, format, range.} -#### {Another Entity Name} - -{...} - ### 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} +#### {API Endpoint / Purpose, e.g., Create Order Request, repeat the section as needed} - **Schema / Interface Definition:** ```typescript @@ -154,13 +185,9 @@ } ``` -#### {Another API Payload} - -{...} - ### Database Schemas (If applicable) -{If using a database, define table structures or document database schemas.} +{If using a database, define table structures or document database schemas. repeat as needed} #### {Table / Collection Name} @@ -177,36 +204,6 @@ ``` _(Alternatively, use ORM model definitions, NoSQL document structure, etc.)_ -#### {Another Table / Collection Name} - -{...} - -### State File Schemas (If applicable) - -{If the application uses files for persisting state.} - -#### {State File Name / Purpose, e.g., processed_items.json} - -- **Purpose:** {What state does this file track?} -- **Format:** {e.g., JSON} -- **Schema Definition:** - ```json - { - "type": "object", - "properties": { - "processedIds": { - "type": "array", - "items": { - "type": "string" - }, - "description": "List of IDs that have been processed." - } - // ... other state properties - }, - "required": ["processedIds"] - } - ``` - ## 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. } @@ -215,14 +212,16 @@ { 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} -- Primary Runtime(s) & Version(s): {e.g., Node.js 22.x} +- 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 versions or clearly state "Latest," but be cautious with "Latest" if dependency issues are a concern. } +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) | | :------------------- | :---------------------- | :---------------- | :-------------------------------------- | :----------------------- | @@ -252,16 +251,126 @@ Must be definitive selections; do not list open-ended choices (e.g., for web scr - 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, Manual deployment steps, Blue/Green, Canary} - Tools: {e.g., Jenkins, GitHub Actions, GitLab CI} +- 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, return error codes/tuples, specific error types.} +- **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`, Python `logging` module, dedicated logging library} - - Format: {e.g., JSON, plain text} - - Levels: {e.g., DEBUG, INFO, WARN, ERROR} - - Context: {What contextual information should be included?} + - 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: {e.g., Use ` \ No newline at end of file + - 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`, `ReadonlyArray`, `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 ---- + diff --git a/BETA-V3/templates/front-end-architecture-tmpl.txt b/BETA-V3/templates/front-end-architecture-tmpl.txt index f70623f4..7ffec383 100644 --- a/BETA-V3/templates/front-end-architecture-tmpl.txt +++ b/BETA-V3/templates/front-end-architecture-tmpl.txt @@ -30,134 +30,136 @@ - [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. 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. } +{ 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:** {e.g., `docs/architecture.md`} (Note: The overall system architecture, including Monorepo/Polyrepo decisions and backend structure, will influence frontend choices, especially around shared code or API interaction patterns.) -- **Link to UI/UX Specification:** {e.g., `docs/front-end-spec.md`} -- **Link to Primary Design Files (Figma, Sketch, etc.):** {From UI/UX Spec} +- **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. Briefly reiterate why these were chosen if not detailed enough in the main arch doc.} -- **Component Architecture:** {e.g., Atomic Design principles, Presentational vs. Container components, use of specific component libraries like Material UI, Tailwind CSS for styling approach.} -- **State Management Strategy:** {e.g., Redux Toolkit, Zustand, Vuex, NgRx. Briefly describe the overall approach – global store, feature stores, context API usage. More details in "State Management In-Depth" section.} -- **Data Flow:** {e.g., Unidirectional data flow, how data is fetched, passed to components, and updated.} -- **Styling Approach:** {e.g., CSS Modules, Styled Components, SCSS with BEM, Tailwind CSS. Link to configuration if applicable.} -- **Key Design Patterns Used:** {e.g., Provider pattern, Hooks, Higher-Order Components, Service patterns for API calls.} +- **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/`). 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. } +{ 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 -│ ├── (features)/ # Feature-based routing groups +├── 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 -│ │ └── page.tsx -│ ├── api/ # API Routes (if using Next.js backend features) -│ ├── globals.css -│ └── layout.tsx # Root layout -├── components/ # Shared/Reusable UI Components -│ ├── ui/ # Base UI elements (Button, Input, Card - often from a library) +│ │ ├── 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) +│ ├── 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 +│ └── (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 +├── features/ # Feature-specific logic, hooks, non-global state, services, and components solely used by that feature. │ └── auth/ -│ ├── components/ # Components used only by the auth feature -│ ├── hooks/ # Feature-specific hooks -│ ├── services/ # Feature-specific API interactions -│ └── store.ts # Feature-specific state slice (if applicable) -├── hooks/ # Global/sharable custom hooks +│ ├── 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/ # Utility functions, helpers, constants +├── 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 +├── 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 (e.g., Redux store setup) -│ ├── index.ts -│ ├── rootReducer.ts -│ └── (slices)/ -├── styles/ # Global styles, theme configurations (if not using `globals.css` or similar) -└── types/ # Global TypeScript type definitions +├── 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. For example, "Components are co-located with their feature if not globally reusable." } +{ 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. While a few globally shared or foundational components (e.g., core UI elements if not from a library, main layout structures) might be specified here upfront to ensure consistency, the detailed specification for most feature-specific components will emerge as user stories are implemented. The key is for the development team (or AI agent) to follow the "Template for Component Specification" below whenever a new component is identified for development. } +{ 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 -{ Briefly describe conventions for naming components (e.g., PascalCase, `feature-ComponentName.tsx`). How are components organized on the filesystem (reiterate from directory structure if needed)? Are components grouped by feature, type (UI, layout), etc.? } +- **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), provide the following details. Repeat this subsection for each component. The level of detail should be sufficient for an AI agent or developer to implement it with minimal ambiguity. } +{ 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.} -- **Source File(s):** {e.g., `src/components/user-profile/UserProfileCard.tsx`} -- **Visual Reference:** {Link to specific Figma frame/component, or Storybook page.} +- **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. } - | Prop Name | Type | Required? | Default Value | Description | - | :-------------- | :--------------------------- | :-------- | :------------ | :---------------------------------------------- | - | `userId` | `string` | Yes | N/A | The ID of the user to display. | - | `avatarUrl` | `string` | No | `null` | URL for the user\'s avatar image. | - | `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}` | `{type (e.g., number, boolean, customType)}` | {Yes/No} | {If any} | {Description} | + { 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. Minor UI state (e.g., `isDropdownOpen`) might not need explicit listing unless complex. } - | State Variable | Type | Initial Value | Description | - | :-------------- | :--------- | :------------ | :-------------------------------------------- | - | `isLoading` | `boolean` | `false` | Tracks if data for the component is loading. | - | `{anotherState}`| `{type}` | `{value}` | {Description} | + { 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:** - { Describe the main visual parts of the component and their general layout. This can be a brief textual description or a very simple pseudo-HTML 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 -
- -

-

- }

``` - **Events Handled / Emitted:** - - **Handles:** {e.g., `onClick` on the edit button.} - - **Emits:** {If the component emits custom events, describe them. e.g., `onFollow: (userId: string) => void`} + - **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 `fetchUserDetails(userId)` action on mount." "Calls `userSlice.actions.setUserName(newName)`."} - - **API Calls:** {Specify which service/function from the "API Interaction Layer" is called. e.g., "Calls `userService.fetchUser(userId)`." What data is passed? How is the response (success/error) handled? How does it update internal state or global state?} + - **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:** - - {Reference to Design System components used (e.g., "Uses `