# io8 System Architect Agent - Customized for This Project

## Project-Specific Instructions


# Architecture Document
Generated: 2025-10-02T[CURRENT_TIMESTAMP]

## System Overview
The "Notes App" is a full-stack web application designed for personal note management. It enables users to securely register, log in, and perform CRUD (Create, Read, Update, Delete) operations on their notes. Phase 2 enhancements include advanced features such as search, filtering, rich text editing, and tagging for improved organization. The frontend is built with Angular, leveraging the Clarity Design System from the base project for a consistent and intuitive user interface. The backend will expose a RESTful API to manage user authentication, notes, and associated metadata, ensuring data persistence and security.

## Architecture Pattern
### Client-Server Architecture
The application will follow a classic client-server architecture, where the Angular frontend acts as the client consuming services provided by a dedicated backend API.

### Layered Backend Architecture
The backend will implement a layered architecture to ensure separation of concerns, maintainability, and scalability:
1.  **Presentation Layer (API/Controllers):** Handles HTTP requests, authentication, request parsing, and response formatting. Exposes RESTful endpoints.
2.  **Service/Business Logic Layer:** Contains the core business logic, orchestrates operations, and applies business rules (e.g., password policies, note ownership validation).
3.  **Data Access Layer (Repository/ORM):** Abstracts database interactions, performing CRUD operations, handling data mapping, and managing transactions.

## Component Design

### Frontend (Angular - Leveraging Clarity Boilerplate)
*   **Auth Module:** Encapsulates components for user registration, login, and potentially password reset/change. Includes `AuthService` for API interaction and `AuthGuard` for route protection.
*   **Notes Module:** Manages all note-related functionalities. Contains components for:
    *   `NotesListComponent`: Displays a paginated/filtered list of notes. Incorporates search and filter UI.
    *   `NoteDetailComponent`: Displays a single note's content.
    *   `NoteEditorComponent`: Used for creating and editing notes. Integrates a rich text editor and tag input.
*   **Core Module:** (From boilerplate) Provides singleton services like `AuthenticationService` (managing JWT tokens, user state), `ErrorInterceptor` (for global API error handling), and `LoggerService`.
*   **Shared Module:** (From boilerplate) Contains reusable UI components (e.g., custom card, loader, pagination controls), directives, and pipes that are used across multiple feature modules. Will include components related to tag display (e.g., Clarity labels).
*   **Layout Components:** (From boilerplate) `HeaderComponent` (with user profile/logout), `SidebarComponent` (for navigation to notes list, future dashboards).

### Backend (RESTful API)
*   **Authentication Service/Controller:** Endpoints for `/api/auth/register`, `/api/auth/login`, `/api/auth/logout`. Handles user creation, password hashing, JWT generation, and token validation.
*   **User Service/Controller:** Manages user-specific data (e.g., `/api/users/{id}`). Primarily for internal use or administrative purposes, potentially for user profile updates.
*   **Notes Service/Controller:** Provides CRUD operations for notes. Endpoints like `/api/notes`, `/api/notes/{id}`. Includes logic for search, filter, and tagging notes based on user ownership.
*   **Tag Service/Controller:** (If implemented as a separate entity) Manages user-defined tags. Endpoints like `/api/tags`.
*   **Data Access Layer:** Interfaces with the chosen database via an ORM (Object-Relational Mapper). Maps database entities to application objects (e.g., `User` entity, `Note` entity, `Tag` entity).

## Data Architecture
**Database Type:** Relational Database (e.g., PostgreSQL).

### Entities and Relationships:
1.  **User:**
    *   `id` (Primary Key, UUID)
    *   `username` (Unique, String)
    *   `password_hash` (String, for securely stored password)
    *   `email` (Unique, String, Optional if username is primary identifier for login)
    *   `created_at` (Timestamp)
    *   `updated_at` (Timestamp)
    *   *Relationship:* One User has many Notes.

2.  **Note:**
    *   `id` (Primary Key, UUID)
    *   `user_id` (Foreign Key to User.id, Required)
    *   `title` (String)
    *   `content` (Text type, to accommodate rich text/Markdown)
    *   `created_at` (Timestamp)
    *   `updated_at` (Timestamp)
    *   *Relationship:* One Note belongs to one User. Many-to-many with Tags (via `Note_Tag` join table).

3.  **Tag:** (For Phase 2 advanced tagging)
    *   `id` (Primary Key, UUID)
    *   `user_id` (Foreign Key to User.id, Required - Tags are user-specific)
    *   `name` (String, Unique per user)
    *   *Relationship:* Many-to-many with Notes (via `Note_Tag` join table).

4.  **Note_Tag (Join Table):**
    *   `note_id` (Foreign Key to Note.id)
    *   `tag_id` (Foreign Key to Tag.id)
    *   *Composite Primary Key:* (`note_id`, `tag_id`)

### Data Flow:
*   Frontend sends HTTP requests (JSON payload) to backend API.
*   Backend API processes requests, interacts with the database via DAL/ORM.
*   Database stores and retrieves data.
*   Backend sends HTTP responses (JSON payload) back to the frontend.
*   Frontend processes responses, updates UI, and displays data.

## API Design
RESTful API adhering to standard HTTP methods and resource-based URLs. JSON will be the primary data exchange format. All user-specific endpoints will require authentication.

### Authentication Endpoints (`/api/auth`)
*   `POST /api/auth/register`: Create a new user account.
    *   Request: `{ username, email, password }`
    *   Response: `{ userId, username }` (or JWT token directly)
*   `POST /api/auth/login`: Authenticate user and issue JWT.
    *   Request: `{ username, password }`
    *   Response: `{ accessToken, refreshToken (optional), expiresIn }`
*   `POST /api/auth/logout`: Invalidate current user session/token.
    *   Request: (Header: `Authorization: Bearer <token>`)
    *   Response: `{ message: "Logged out successfully" }`

### Notes Endpoints (`/api/notes`)
*   `GET /api/notes`: Retrieve all notes for the authenticated user. Supports query parameters for search and filter.
    *   Query Params: `?search={keyword}&tags={tag1,tag2}&startDate={date}&endDate={date}&page={num}&limit={num}`
    *   Response: `[{id, title, contentSnippet, tags, createdAt, updatedAt}]`
*   `POST /api/notes`: Create a new note for the authenticated user.
    *   Request: `{ title, content, tags: [tag_names] }`
    *   Response: `{id, title, content, tags, createdAt, updatedAt}`
*   `GET /api/notes/{id}`: Retrieve a specific note by ID for the authenticated user.
    *   Response: `{id, title, content, tags, createdAt, updatedAt}`
*   `PUT /api/notes/{id}`: Update an existing note by ID for the authenticated user.
    *   Request: `{ title, content, tags: [tag_names] }`
    *   Response: `{id, title, content, tags, createdAt, updatedAt}`
*   `DELETE /api/notes/{id}`: Delete a specific note by ID for the authenticated user.
    *   Response: `{ message: "Note deleted successfully" }`

### Tags Endpoints (`/api/tags`) - For user-specific tag management
*   `GET /api/tags`: Retrieve all tags for the authenticated user.
    *   Response: `[{id, name}]`
*   `POST /api/tags`: Create a new tag for the authenticated user.
    *   Request: `{ name }`
    *   Response: `{id, name}`
*   `DELETE /api/tags/{id}`: Delete a specific tag by ID for the authenticated user.
    *   Response: `{ message: "Tag deleted successfully" }`

## Security Architecture
*   **User Authentication:** JWT (JSON Web Tokens) will be used for stateless authentication. Access tokens will be short-lived, and optionally refresh tokens can be used for seamless re-authentication.
*   **Password Hashing:** User passwords will be hashed using a strong, adaptive hashing algorithm (e.g., bcrypt) with a sufficient salt value before storage in the database.
*   **Data in Transit:** All communication between the frontend and backend will be secured using HTTPS (TLS/SSL encryption).
*   **Authorization:** Backend API endpoints will implement authorization checks to ensure that a user can only access, modify, or delete their own notes and tags. This will be enforced by validating the JWT and verifying the `userId` associated with the request against the `userId` linked to the resource.
*   **Input Validation & Sanitization:** Both frontend and backend will perform rigorous input validation. Frontend validation provides immediate feedback, while backend validation is critical for security to prevent common vulnerabilities like SQL Injection, XSS (Cross-Site Scripting), and other data integrity issues. Rich text content will require careful sanitization to prevent XSS.
*   **Rate Limiting:** Authentication endpoints (`/api/auth/login`, `/api/auth/register`) will implement rate limiting to mitigate brute-force and denial-of-service attacks.
*   **CORS (Cross-Origin Resource Sharing):** The backend API will be configured to correctly handle CORS policies, allowing requests only from the trusted frontend application origin.

## Scalability Considerations
*   **Stateless Backend:** The use of JWT for authentication will keep the backend stateless, allowing for easy horizontal scaling of API instances.
*   **Database Optimization:** Use of a robust relational database (PostgreSQL) with proper indexing on `userId`, `createdAt`, `updatedAt`, `title`, and `content` (for search) will ensure efficient query performance even with large datasets.
*   **Caching:** For future scalability, a caching layer (e.g., Redis) could be introduced to cache frequently accessed notes or search results, reducing database load.
*   **Containerization:** The application components (frontend, backend, database) will be containerized using Docker, facilitating consistent deployment and scaling in environments like Kubernetes or Docker Swarm.
*   **Modular Frontend:** Angular's modular structure and lazy-loading for feature modules contribute to a scalable and performant frontend by reducing initial bundle size.



# Technology Stack Document
Generated: 2025-10-02T[CURRENT_TIMESTAMP]

## Frontend Technologies
-   **Framework:** Angular 16+ (leveraging the base boilerplate)
-   **UI Library/Styling:** VMware Clarity Design System (integrated in boilerplate)
-   **Language:** TypeScript
-   **State Management:** RxJS (built-in with Angular for reactive programming), potentially NgRx for larger state management needs in future phases.
-   **HTTP Client:** Angular's `HttpClient` module
-   **Rich Text Editor:** `@ckeditor/ckeditor5-angular` or similar Angular-compatible WYSIWYG editor library for Phase 2.

## Backend Technologies
-   **Language:** Python 3.9+
-   **Framework:** Flask (a lightweight and flexible microframework for RESTful APIs)
-   **Web Server Gateway Interface (WSGI):** Gunicorn
-   **API:** RESTful API
-   **Authentication:** `Flask-JWT-Extended` for JWT token management
-   **ORM (Object-Relational Mapper):** SQLAlchemy with `Flask-SQLAlchemy` extension
-   **Marshaling/Validation:** `Marshmallow` or `Pydantic` for data serialization/deserialization and request body validation
-   **Request Validation:** `Flask-WTF` for form validation or manual validation using schema libraries

## Database Technologies
-   **Primary Database:** PostgreSQL (a powerful, open-source relational database suitable for scale and complex queries)
-   **Database Driver:** `psycopg2` (for Python-PostgreSQL connection)
-   **Caching (Future Consideration):** Redis (for session management, token blacklisting, or general-purpose caching).

## Infrastructure
-   **Containerization:** Docker (for both frontend and backend services)
-   **Container Orchestration (Production):** Docker Compose (for local development and small-scale deployments), Kubernetes (for enterprise-grade scalability and management)
-   **Hosting:** AWS (Amazon Web Services) - e.g., EC2 for compute, RDS for PostgreSQL, ECR for Docker images, S3 for static assets (if any).

## Development Tools
-   **Version Control:** Git / GitHub / GitLab
-   **Code Editor:** Visual Studio Code (with Angular, Python, Docker extensions)
-   **Frontend Testing:** Karma & Jasmine (unit testing), Cypress/Playwright (e2e testing)
-   **Backend Testing:** Pytest (unit and integration testing)
-   **API Documentation:** Swagger/OpenAPI (e.g., `Flask-RESTX` integration or `Flask-Marshmallow-Swagger`)
-   **CI/CD:** GitHub Actions / GitLab CI / Jenkins (for automated testing, building, and deployment)
-   **Linting/Formatting:** ESLint/Prettier (Angular), Black/Flake8 (Python)


## 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.
