# Project inBOXER: Master Agent Manifest

## 1. System Architecture

- **Backend:** Go (Golang) compiled binary – **modular design** (each package does one specific task).
- **Frontend:** Embedded Go templates + CSS (mobile‑first, responsive). No heavy JavaScript frameworks.
- **Database:** SQLite (single file) with GORM.
- **Authentication:** Email address + OTP (one‑time password) sent via SMTP.  
  - One email address = one user.  
  - Session stored in a secure, http‑only cookie.
- **Core Logic:** IMAP fetching → DeepSeek LLM classification → IMAP folder move.

---

## 2. Directory Structure

The agent **must** create the following exact hierarchy inside the repository:

```text
~/inboxer/                     # Repository root
├── README.md
├── .env                       # ALL credentials (IMAP, SMTP, DeepSeek)
├── docs/
│   ├── CHANGELOG.md           # Updated with each version
│   └── LICENSE.md
├── src/
│   ├── cmd/
│   │   └── main.go            # Orchestrator (startup, workers, web server)
│   ├── internal/
│   │   ├── auth/              # OTP generation, email sending, session mgmt
│   │   ├── imap/              # IMAP client, batch fetching, folder ops
│   │   ├── ai/                # DeepSeek caller, prompt loader, result parser
│   │   ├── db/                # SQLite models & user settings
│   │   └── worker/            # Orchestrated cold‑start / steady‑state loop
│   ├── web/
│   │   ├── templates/         # .html files (login, dashboard, settings)
│   │   └── static/            # CSS (mobile‑first)
│   └── pkg/                   # Helpers (logging, config, OTP utils)
└── bin/
    ├── inboxer                # Compiled binary
    ├── config.yaml            # Global settings (poll intervals, batch sizes)
    ├── prompt.txt             # Classification prompt (loaded at runtime)
    └── db.sqlite              # User data & settings
```

---

## 3. Critical Agent Instructions

### A. Credentials – `.env` file

The agent **must** read `~/inboxer/.env` on startup. It contains:

```
DEEPSEEK_API_KEY=sk-...
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=noreply@example.com
SMTP_PASS=...
```

- No hardcoded secrets.  
- The `.env` file is **never** committed to the repository.

### B. Modularity & Testability

- Each sub‑package (`auth`, `imap`, `ai`, `db`, `worker`) must expose a small, focused interface.  
- The `main` package acts only as the orchestrator:  
  - Reads `config.yaml` and `.env`.  
  - Initialises database, AI client, IMAP client, OTP sender.  
  - Starts the web server and the background worker goroutine.  
- Unit tests can target any package in isolation (each module has its own `*_test.go`).

### C. Authentication – Email + OTP

- **Login flow:**  
  1. User enters email address on `/login`.  
  2. Backend generates a 6‑digit OTP, stores it (hashed) in the database with a 10‑minute expiry.  
  3. OTP is sent via SMTP (credentials from `.env`) to that email address.  
  4. User submits OTP on `/verify`.  
  5. If correct, a session cookie is created (user identified by email).  
- **One email = one user** – the database stores a single user’s own IMAP/SMTP mailbox settings (encrypted).  
- **Session management:** cookie with `HttpOnly`, `Secure`, and appropriate expiry.

### D. Classification Prompt Location

- The prompt text file **must** be placed in `bin/prompt.txt` (next to `bin/config.yaml`).  
- The binary reads this file at startup (or caches it).  
- This allows end‑users to modify the classification prompt without recompiling.

### E. Repository & Version Control

- **First step:** The agent creates a new repository named `inboxer` (on GitHub/GitLab, whichever is available).  
- **After each version increment** (i.e., completing a Phase task), the agent must:  
  - Update `docs/CHANGELOG.md` with the new version and changes.  
  - Commit all changes with a descriptive message.  
  - Push to the remote repository.

---

## 4. Phased Project Plan

### Phase 1: Foundation, OTP Auth & Mobile Frontend (Version: 2026-04.1)

- **1.1** Create repository `inboxer` and the exact folder structure.  
- **1.2** Go module init, add dependencies: `go-imap`, `gorm`, `sqlite`, `slog`, etc.  
- **1.3** Implement `.env` loader + `config.yaml` parser.  
- **1.4** **Modular auth package:**  
  - OTP generation & hashing (bcrypt)  
  - SMTP sender (using `.env` credentials)  
  - Session cookie management  
- **1.5** **Mobile‑first frontend** (Go templates + CSS grid/flex):  
  - `/login` – email input  
  - `/verify` – OTP input  
  - `/dashboard` – shows processing status, last run, folder counts  
  - `/settings` – user can set their own IMAP/SMTP credentials (encrypted in DB)  
- **1.6** SQLite schema: `users` (email, hashed_otp, otp_expiry), `mailbox_settings` (imap_host, imap_user, encrypted_pass, etc.).

### Phase 2: IMAP & Cold‑Start Worker (Version: 2026-04.2)

- **2.1** **Modular IMAP package** – connect, list folders, move messages, fetch batches.  
- **2.2** **Worker orchestrator:**  
  - Steady state: 10 emails every 5 minutes.  
  - Catch‑up mode (if `last_processed_uid` is null): batches of 50 emails, 5‑second cooldown between batches.  
- **2.3** Ensure folders `Important`, `eCommerce`, `Other`, `Spam` exist (create if missing).

### Phase 3: DeepSeek AI & Prompt Loading (Version: 2026-04.3)

- **3.1** **Modular AI package** – reads `bin/classify_prompt.txt` and caches it.  
- **3.2** Sends (sender, subject, body snippet) to DeepSeek, expects JSON: `{"folder": string, "score": int, "context": string}`.  
- **3.3** If AI fails (API error, invalid response), the email stays in `INBOX` (no guessing).  
- **3.4** Add “Test Mode” toggle in frontend – logs AI decisions without moving physical emails.

### Phase 4: Reporting, Logging & Final Polish (Version: 2026-04.4)

- **4.1** Weekly summary report – sent via SMTP (from `.env`) to the logged‑in user’s email.  
- **4.2** Structured logging (`slog`) to `bin/inboxer.log`.  
- **4.3** `Makefile` with targets: `build`, `run`, `test`.  
- **4.4** Final binary placed in `bin/` – ready for end‑user distribution.

---

## 5. Operational Guardrails for the AI Agent

1. **Versioning** – Increment the version in `docs/CHANGELOG.md` after every completed Phase task, then **commit and push**.  
2. **Safety** – Never delete emails. Only move from `INBOX` to subfolders.  
3. **OTP Security** – OTPs expire after 10 minutes; use bcrypt for storage; always send via TLS.  
4. **Error Handling** – If AI API or IMAP fails, log the error, keep the email in `INBOX`, and retry on the next cycle.  
5. **tmux sessions** – Do not kill the tmux session where the agent runs.  
6. **Testing** – Each modular function must have its own test file (`*_test.go`) that can be executed independently.  
7. **Frontend** – The web interface must be usable on mobile devices (responsive design, touch‑friendly inputs).  

---

## 6. Immediate Actions for the Agent (OpenCode)

1. **Create the repository** named `inboxer` on the available Git host.  
2. **Clone it** and create the exact folder structure shown above.  
3. **Place a sample `.env`** (with placeholder values) and a default `bin/classify_prompt.txt` (a basic classification prompt).  
4. **Begin Phase 1** – implement OTP authentication and the mobile‑first frontend.  
5. **After finishing Phase 1**, update `CHANGELOG.md` to version `2026-04.1`, then **commit and push**.  

The agent is now cleared to execute. All subsequent commits must follow the same pattern after each version increment.
