# io8 System Architect Agent - Customized for This Project

## Project-Specific Instructions


# Architecture Document
Generated: 2025-10-06T07:45:00Z

## System Overview
The Notes Application extends an existing Angular Clarity frontend boilerplate with a new, dedicated RESTful API backend and a PostgreSQL database. The system is designed as a secure, personal information management tool enabling users to create, view, edit, and delete their private notes. It incorporates robust user authentication and strict authorization to ensure data ownership and privacy. The architecture facilitates a clear separation of concerns between the client-side UI, server-side business logic, and data persistence layers, aiming for high maintainability and scalability.

## Architecture Pattern
**Rich Client - API Gateway - Backend Services - Database**

This project adopts a layered architecture pattern, specifically a rich client (Angular) interacting with a backend API (functioning as an API Gateway for initial MVP) that handles business logic and data persistence. This approach leverages the strengths of a modern frontend framework for an intuitive user experience and a powerful, scalable backend for secure data management.

*   **Client Layer (Frontend):** The Angular application, built upon the Clarity Boilerplate, serves as the rich client. It handles all UI rendering, user interaction, client-side routing, and makes API calls to the backend.
*   **API Gateway Layer (Backend API):** For the MVP, the backend RESTful API service acts as a de-facto API Gateway. It exposes all necessary endpoints for user authentication and note management, serving as the single entry point for client requests. It encapsulates business logic and interacts with the database.
*   **Backend Services Layer (within API):** Logical separation of services within the backend (e.g., `UserService`, `NoteService`) to handle specific domains. This allows for clear organization and future refactoring into distinct microservices if the application complexity grows.
*   **Data Layer (Database):** PostgreSQL is used for persistent storage of user and note data.

**Justification:** This pattern is chosen for its clear separation of concerns, which enhances maintainability, testability, and allows for independent scaling of frontend and backend components. It provides a solid foundation that can evolve towards a more granular microservices architecture in future phases if needed, without requiring a complete rewrite of the core components. The existing Angular Clarity boilerplate naturally fits the rich client model.

## Component Design

### Frontend Components (Angular - Clarity Boilerplate Extension)
*   **AppModule:** Root module, responsible for bootstrapping the application and configuring global services and routes. Integrates `CoreModule`, `SharedModule`, and feature modules.
*   **CoreModule:** (Already exists) Provides singleton services (e.g., `AuthService`, `NoteService`, `HttpInterceptor` for error handling and JWT attachment), guards (e.g., `AuthGuard`), and ensures they are instantiated once. Responsible for application-wide functionalities like authentication token management.
*   **SharedModule:** (Already exists) Contains reusable UI components (e.g., custom form controls, loading indicators), directives, and pipes that are used across multiple feature modules. It will be extended to include any new generic components useful for the notes app.
*   **AuthModule:** A lazy-loaded feature module for all authentication-related components and routing.
    *   **LoginComponent:** Handles user login using email and password (FR-002).
    *   **RegisterComponent:** Handles new user registration (FR-001).
    *   **PasswordResetComponent:** Initiates password reset (FR-003).
    *   **AuthService:** Manages user authentication state, interacts with backend auth API, stores/retrieves JWT.
*   **NotesModule:** A lazy-loaded feature module for all note management functionality.
    *   **NoteListComponent:** Displays a paginated/sortable list of user's notes (FR-005).
    *   **NoteDetailComponent:** Displays the full content of a single note (FR-006).
    *   **NoteEditorComponent:** Provides an interface for creating and editing notes (FR-004, FR-007).
    *   **NoteService:** Manages CRUD operations for notes, interacts with backend notes API, enforces note ownership (FR-009).

### Backend Components (FastAPI)
*   **Main Application:** Entry point for the FastAPI application.
*   **Routers/Controllers:** Handle incoming HTTP requests, validate input, and delegate to service layers.
    *   **AuthRouter:** Endpoints for `/auth/register`, `/auth/login`, `/auth/password-reset`.
    *   **NotesRouter:** Endpoints for `/notes` (GET, POST), `/notes/{id}` (GET, PUT, DELETE).
*   **Services:** Contain the core business logic and interact with the repository layer.
    *   **UserService:** Manages user creation, authentication, password hashing, and user data retrieval.
    *   **NoteService:** Manages note CRUD operations, ensures note ownership for all actions.
*   **Repositories/Data Access Layer:** Abstract database interactions, mapping Python objects to database records.
    *   **UserRepository:** CRUD operations for `User` entity.
    *   **NoteRepository:** CRUD operations for `Note` entity.
*   **Models:** Pydantic models for request/response data validation and SQLAlchemy models for database schema definition.
*   **Security Utilities:** Functions for password hashing (bcrypt), JWT encoding/decoding, and dependency injection for authentication/authorization checks.

### Database Components (PostgreSQL)
*   **Users Table:** Stores user information (`id`, `email`, `password_hash`, `created_at`, `updated_at`).
*   **Notes Table:** Stores note information (`id`, `user_id`, `title`, `content`, `created_at`, `updated_at`).
*   **Indexes:** Optimized indexes on `user_id` in the `notes` table for efficient retrieval of user-specific notes, and on `email` in the `users` table for unique login identification.

## Data Architecture

### Data Model (Entities and Relationships)
*   **User:**
    *   `id` (UUID, PK)
    *   `email` (String, Unique, Required)
    *   `password_hash` (String, Required - salted and hashed)
    *   `created_at` (Timestamp, Auto)
    *   `updated_at` (Timestamp, Auto)
*   **Note:**
    *   `id` (UUID, PK)
    *   `user_id` (UUID, FK to User.id, Required)
    *   `title` (String, Required, Max 255)
    *   `content` (Text, Optional - rich-text)
    *   `created_at` (Timestamp, Auto)
    *   `updated_at` (Timestamp, Auto)

**Relationship:** `User` 1 -- M `Note` (One user can have many notes; each note belongs to exactly one user).

### Data Flow
1.  **User Authentication:**
    *   User enters credentials on Frontend `LoginComponent`.
    *   `AuthService` sends `POST /auth/login` to Backend API.
    *   Backend `AuthRouter` validates credentials, hashes password, compares with `password_hash` in `Users` table via `UserService` and `UserRepository`.
    *   On success, Backend generates JWT and sends it back to Frontend.
    *   Frontend `AuthService` stores JWT securely (e.g., in `localStorage` or `HttpOnly` cookie for refresh tokens) and updates authentication state.

2.  **Note Management (e.g., Create Note):**
    *   Authenticated user interacts with `NoteEditorComponent` to create a new note.
    *   `NoteService` sends `POST /notes` to Backend API, including JWT in `Authorization` header.
    *   Backend `NotesRouter` intercepts request:
        *   Validates JWT and extracts `user_id` (AuthN/AuthZ).
        *   Validates input `title` and `content`.
        *   `NoteService` creates new note record, associating it with the extracted `user_id`, and saves to `Notes` table via `NoteRepository`.
    *   Backend returns new note details to Frontend.
    *   Frontend `NoteService` updates local state, `NoteListComponent` refreshes.

3.  **Secure Access Control (FR-009):**
    *   All API endpoints for note management (`/notes`, `/notes/{id}`) require a valid JWT.
    *   Backend middleware or dependencies ensure the `user_id` extracted from the JWT matches the `user_id` associated with the requested note for all GET, PUT, DELETE operations.

## API Design

**RESTful API Principles:** Adheres to RESTful principles for resource-oriented design, statelessness, and standard HTTP methods.

**Base URL:** `/api/v1` for versioning.

**Authentication:** JWT (JSON Web Tokens) passed in the `Authorization: Bearer <token>` header for all protected endpoints.

**Data Format:** All requests and responses will use `application/json`.

**Error Handling:** Standard HTTP status codes will be used to indicate success or failure, with JSON bodies providing more detailed error messages.
*   `200 OK`, `201 Created`, `204 No Content` for success.
*   `400 Bad Request` for invalid input.
*   `401 Unauthorized` for missing/invalid JWT.
*   `403 Forbidden` for insufficient permissions (e.g., accessing another user's note).
*   `404 Not Found` for non-existent resources.
*   `429 Too Many Requests` for rate limiting.
*   `500 Internal Server Error` for unexpected server issues.

### Key Endpoints (as per `requirements_document.md`)
*   **User Authentication:**
    *   `POST /auth/register`: Register new user, returns token and user info.
    *   `POST /auth/login`: Login user, returns token and user info.
    *   `POST /auth/password-reset`: Initiate password reset, returns message.
*   **Note Management (Protected):**
    *   `GET /notes`: Retrieve list of current user's notes (with sorting, pagination).
    *   `GET /notes/{id}`: Retrieve a specific note by ID (owned by user).
    *   `POST /notes`: Create a new note for the current user.
    *   `PUT /notes/{id}`: Update an existing note by ID (owned by user).
    *   `DELETE /notes/{id}`: Delete a note by ID (owned by user).

## Security Architecture

1.  **Authentication (FR-001, FR-002, NFR-002):**
    *   **JWT-based Authentication:** Backend issues short-lived JWTs upon successful login. Tokens are signed with a strong secret key. Frontend stores tokens securely (e.g., `localStorage` for access token, `HttpOnly` cookies for refresh token if implemented later) and attaches them to `Authorization` headers for API requests.
    *   **Password Hashing:** User passwords are never stored in plain text. `bcrypt` (or similar strong, adaptive hashing algorithm) is used to hash passwords with a unique salt before storage in PostgreSQL (NFR-002).
    *   **Rate Limiting:** Backend implements rate limiting on login and registration endpoints to mitigate brute-force attacks (NFR-002).

2.  **Authorization (FR-009, NFR-002):**
    *   **Role-Based Access Control (RBAC):** Not strictly required for MVP, but the framework for user-specific ownership is in place. Each note is explicitly linked to a `user_id`.
    *   **Note Ownership Enforcement:** All CRUD operations on notes on the backend verify that the `user_id` extracted from the authenticated JWT matches the `user_id` of the note being accessed/modified/deleted. Attempts to access notes not owned by the user result in `403 Forbidden` (FR-009).

3.  **Data Protection (NFR-002):**
    *   **HTTPS/TLS:** All data in transit between the frontend and backend is encrypted using HTTPS/TLS to prevent eavesdropping and tampering.
    *   **Input Validation:** Comprehensive input validation on both frontend and backend (using Angular forms validation and FastAPI Pydantic models) to prevent common vulnerabilities like SQL Injection, XSS, and buffer overflows (NFR-002).
    *   **Environment Variables:** Sensitive configurations (e.g., database credentials, JWT secret) are managed via environment variables and are not hardcoded in the application (NFR-002).

## Scalability Considerations

1.  **Stateless Backend (NFR-004):** The FastAPI backend will be designed to be completely stateless. All session-related data is handled by JWTs, allowing any instance of the backend service to handle any request, facilitating easy horizontal scaling.
2.  **Containerization (NFR-004):** Docker will be used to containerize the frontend, backend, and database services. This provides isolated, consistent, and portable environments, making it straightforward to deploy multiple instances of the backend service behind a load balancer.
3.  **Database Optimization (NFR-004):**
    *   **Indexing:** Appropriate database indexes (e.g., on `user_id` in the `notes` table) will be created to speed up query performance for retrieving user-specific notes.
    *   **Connection Pooling:** Backend will use connection pooling to efficiently manage database connections, reducing overhead.
    *   **Query Optimization:** SQL queries will be optimized for performance, especially for fetching lists of notes and individual notes (NFR-001).
4.  **API Design for Scale:** Pagination and sorting parameters will be implemented for `GET /notes` endpoint to efficiently handle a large number of notes without overwhelming the client or server (NFR-004).
5.  **Frontend Performance (NFR-001):** Lazy loading of Angular feature modules (`AuthModule`, `NotesModule`) will be implemented to minimize initial bundle size and improve load times.



# Technology Stack Document
Generated: 2025-10-06T07:45:00Z

## Frontend Technologies
-   **Framework:** Angular (v16+ recommended for current boilerplate compatibility)
-   **Language:** TypeScript
-   **UI Library/Styling:** VMware Clarity Design System (Integrated via `@clr/angular`, `@clr/ui`, `@cds/core`), SCSS for custom styles.
-   **State Management:** RxJS Observables and Angular Services for managing application state and data flow.
-   **HTTP Client:** Angular's `HttpClient` for secure communication with the backend API.
-   **Routing:** Angular Router for client-side navigation.
-   **Forms:** Angular Reactive Forms for robust form validation and management.
-   **Rich-Text Editor:** A lightweight Angular-compatible rich-text editor (e.g., `ngx-quill` or `tinymce-angular`) will be integrated for note content editing (FR-004).

## Backend Technologies
-   **Language:** Python (v3.9+)
-   **Framework:** FastAPI (for building high-performance RESTful APIs)
-   **Asynchronous Support:** Async/Await using `asyncio` for non-blocking I/O operations.
-   **API:** RESTful API using FastAPI's automatic OpenAPI/Swagger UI generation.
-   **ORM/Database Toolkit:** SQLAlchemy (for database interactions) with `asyncpg` driver for async PostgreSQL connections.
-   **Authentication:** PyJWT for JSON Web Token handling; `passlib` (with `bcrypt`) for secure password hashing.
-   **Validation:** Pydantic for data validation and serialization.

## Database Technologies
-   **Primary Database:** PostgreSQL (v14+ recommended for Docker compatibility and features)
    *   **Purpose:** Relational database for persistent storage of `User` and `Note` data.
-   **Caching (Future Consideration):** Redis (for session management, token blacklisting, or general-purpose caching to improve API response times for frequently accessed data, not MVP).

## Infrastructure
-   **Containerization:** Docker (for isolating and packaging frontend, backend, and database services).
-   **Orchestration (Local Dev):** Docker Compose (for defining and running multi-container Docker applications locally).
-   **Hosting (Production Strategy):** Cloud platforms like AWS (ECS/EKS, RDS, EC2), Azure (App Service, AKS, PostgreSQL Flexible Server), or Google Cloud (Cloud Run, GKE, Cloud SQL for PostgreSQL) would be suitable for production deployment, leveraging managed services for scalability and reliability.
-   **Web Server (Frontend):** Nginx or Caddy within the Angular Docker container for serving static files in production.
-   **Web Server (Backend):** Uvicorn (ASGI server) for serving FastAPI applications.
-   **Network:** HTTPS/TLS for all communication.

## Development Tools
-   **Version Control:** Git
-   **IDE:** Visual Studio Code (with extensions for Angular, Python, Docker, PostgreSQL)
-   **Frontend CLI:** Angular CLI (for scaffolding, building, and serving the Angular application).
-   **Python Package Management:** Poetry or Pipenv (for dependency management and virtual environments).
-   **Database Migration:** Alembic (for managing database schema changes with SQLAlchemy).
-   **API Testing:** Postman, Insomnia, or built-in FastAPI Swagger UI for testing API endpoints.
-   **Frontend Testing:** Karma/Jasmine (unit testing), Cypress (E2E testing) based on Angular best practices.
-   **Backend Testing:** Pytest (for unit and integration tests).
-   **CI/CD:** GitHub Actions or GitLab CI for automated testing and deployment pipelines.


## Base Agent Prompt Reference

This agent is based on the standard io8architect agent with project-specific customizations above.
Refer to the base io8architect agent prompt for general principles and workflow instructions.
