# Task 016 — IMAP Sync

## Objective

Synchronize inbound (and optionally sent) mail from IMAP into `email_messages` with deduplication and thread grouping.

## Scope

- IMAP client using env vars
- Sync job (cron API `POST /api/inbox/sync` admin-only)
- Dedupe by Message-ID
- Thread detection via In-Reply-To / References
- Match replies to `campaign_sends` when possible

**Out of scope:** Send via IMAP.

## Requirements

1. IMAP credentials from env only.
2. Sync idempotent on repeated runs.
3. Errors logged; partial folder sync acceptable with report.

## Files to create or modify

| Path | Action |
|------|--------|
| `src/lib/imap.ts` | Create |
| `src/jobs/imap-sync.job.ts` | Create |
| `src/app/api/inbox/sync/route.ts` | Create |
| `docs/05-email-system.md` | Inbound architecture |
| `docs/16-changelog.md` | Entry |

## Acceptance criteria

- [ ] Manual sync pulls new messages into inbox UI
- [ ] Duplicates not created on second sync
- [ ] Reply to campaign thread links to send record when matched

## Documentation updates required

- `docs/05-email-system.md`
- `docs/03-api-specification.md`
- `docs/16-changelog.md`
