Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

chore: init migration execution branch with docs

Gener12f7471b4f94
diff --git a/.gitignore b/.gitignore
index e469c6b49..134bc8f28 100644
--- a/.gitignore
+++ b/.gitignore
@@ -198,3 +198,6 @@ Thumbs.db
# Plans (local only)
plans/
+
+# Temp
+temp/
diff --git a/docs/migration/00-overview.md b/docs/migration/00-overview.md
new file mode 100644
index 000000000..f20386f5a
--- /dev/null
+++ b/docs/migration/00-overview.md
@@ -0,0 +1,143 @@
+# 00 — Architecture Overview
+
+> Unified platform spec: combining main's features with spec-plans' Cloudflare edge architecture into the full Alook platform.
+> Sources: `origin/main` + `origin/chore/spec-plans` as of 2026-04-10.
+
+---
+
+## Goal
+
+Build the unified Alook platform on Cloudflare's edge stack by combining main's mature backend (Web Service, CLI daemon, shared library) with spec-plans' edge-native services (Email Worker, WS-DO). The target is 5 services on Cloudflare Workers / D1 / R2 / Durable Objects.
+
+---
+
+## Service Map
+
+```mermaid
+graph TD
+ subgraph CF["Cloudflare Edge"]
+ subgraph Workers
+ EW["Email Worker"]
+ WS["Web Service<br/>(Next.js via OpenNext)"]
+ DO["WS-DO<br/>(Durable Objects)"]
+ end
+ subgraph Infrastructure
+ D1["D1 Database"]
+ R2["R2 Bucket"]
+ end
+ BC["Web Dashboard"]
+ end
+
+ subgraph RM["Runtime Machine"]
+ CLI["CLI Daemon"]
+ end
+
+ EW -- "service binding" --> WS
+ WS -- "service binding" --> DO
+
+ EW -- "D1 r/w" --> D1
+ EW -- "R2 r/w" --> R2
+ WS -- "D1 r/w" --> D1
+ WS -- "R2 r/w" --> R2
+ DO -- "D1 read<br/>(token validation)" --> D1
+
+ BC -- "REST API<br/>(data)" --> WS
+ BC <-- "WebSocket<br/>(notifications only)" --> DO
+ CLI -- "REST API<br/>(poll + heartbeat)" --> WS
+```
+
+## Services
+
+| # | Service | Status on `main` | Source for Target | Doc |
+|---|---------|-------------------|-------------------|-----|
+| 1 | **Web Service** | Exists (Node.js + Postgres) | Migrate to Cloudflare Workers + D1 | [01-web-service.md](01-web-service.md) |
+| 2 | **Email Worker** | Not on main | Full implementation preserved from `chore/spec-plans` | [02-email-worker.md](02-email-worker.md) |
+| 3 | **WS-DO** | Not on main | Notification-only WebSocket for browser (simplified from spec-plans) | [03-ws-do.md](03-ws-do.md) |
+| 4 | **CLI Daemon** | Exists (Node.js / Commander.js) | Follows main branch | [04-cli-daemon.md](04-cli-daemon.md) |
+| 5 | **Shared Library** | Exists | No runtime change | [05-shared-library.md](05-shared-library.md) |
+
+> **Migration execution order:** See [06-migration-order.md](06-migration-order.md) for the phased dependency graph and step-by-step sequence.
+
+## Tech Stack — Main vs Target
+
+| Layer | `main` (current) | Target (Cloudflare edge) |
+|-------|-------------------|--------------------------|
+| Web runtime | Node.js (Next.js standalone) | Cloudflare Workers (OpenNext) |
+| Database | PostgreSQL 17 + Drizzle ORM | Cloudflare D1 (SQLite) |
+| File storage | None | Cloudflare R2 |
+| Real-time | HTTP polling only | WebSocket notifications via Durable Objects (browser re-fetches data via REST API) |
+| Email inbound | Not implemented | Cloudflare Email Routing + Worker |
+| Auth | Custom JWT + OTP (jose) | Better Auth (managed) |
+| CLI runtime | Node.js (tsx/tsup) | Node.js (Bun) — follows main |
+| CLI framework | Commander.js | Commander.js |
+| Build system | Makefile | Turborepo |
+| Dev environment | docker-compose (PostgreSQL) | Wrangler local dev (D1/R2) |
+
+## Monorepo Structure
+
+```
+alook/
+├── src/
+│ ├── web/ # [1] Web Service — Next.js app + API routes
+│ │ ├── app/ # Pages + API route handlers
+│ │ ├── lib/ # DB, auth, middleware, services, queries
+│ │ ├── components/# React components
+│ │ └── contexts/ # React context providers
+│ ├── cli/ # [4] CLI Daemon — commands + daemon + agent backends
+│ │ ├── commands/ # CLI commands (register, agent, daemon, etc.)
+│ │ ├── daemon/ # Daemon loop, client, agent backends
+│ │ └── lib/ # Config, logger, HTTP client
+│ └── shared/ # [5] Shared Library — types, schemas, constants
+├── package.json # Root workspace config
+└── pnpm-workspace.yaml
+```
+
+Services **not yet on main** (to be created):
+
+```
+src/
+├── email-worker/ # [2] Email Worker — Cloudflare Worker
+│ └── src/index.ts
+└── ws-do/ # [3] WS-DO — Durable Objects for WebSocket
+ └── src/
+ ├── index.ts
+ └── ws-durable.ts
+```
+
+## Key Workflows on Main
+
+### User Login
+1. Email + OTP: `POST /api/auth/send-code` -> `POST /api/auth/verify-code`
+2. JWT issued (HS256, 72h) + cookie set
+3. Frontend stores token in localStorage
+
+### Machine Registration
+1. Dashboard: `POST /api/machine-tokens` -> raw `al_*` token
+2. CLI: `alook register --token al_...` -> validates via `GET /api/me`
+3. CLI: `alook daemon start` -> `POST /api/daemon/register` with detected runtimes
+4. Daemon loop: heartbeat (15s) + task poll (3s)
+
+### Chat / Task Execution
+1. User sends message -> `POST /api/conversations/{id}/messages`
+2. Server creates message + enqueues task (status: `queued`)
+3. Daemon claims task via `POST /api/daemon/runtimes/{id}/tasks/claim` -> `dispatched`
+4. Daemon starts task -> `running`, spawns agent CLI
+5. Agent streams task messages (batched: 20 msgs / 2s flush)
+6. Agent completes -> `completed`, assistant message created
+7. Frontend receives `{ type: "task.updated", id }` via WebSocket → re-fetches `GET /api/tasks/{id}`
+
+### Stale Detection
+- Heartbeat endpoint marks runtimes with no heartbeat > 45s as offline
+- `failStaleDispatchedTasks()` fails tasks stuck in dispatched > 20s
+
+## What Needs to Change for Edge Deployment
+
+| Area | Migration Work |
+|------|---------------|
+| **Database** | PostgreSQL -> D1 (SQLite). Adapt Drizzle ORM to use `drizzle-orm/d1` adapter (Drizzle supports D1 natively). |
+| **Auth** | Custom JWT -> Better Auth. Add OAuth providers (GitHub, Google). Session-based instead of stateless JWT. |
+| **Real-time** | HTTP polling -> notification-only WebSocket via Durable Objects (browser-only). WS sends `{ type, id }` events, browser re-fetches data via REST API. See [03-ws-do.md](03-ws-do.md). |
+| **Email** | Port spec-plans Email Worker implementation (see [02-email-worker.md](02-email-worker.md)). Email Worker verifies agent + whitelist via D1 (read-only), stores raw email in R2, then calls `POST /api/email/notify` on Web Service which creates email records and tasks. No events table. Add `email_handle` column to agent, add `agent_whitelist` and `emails` tables. |
+| **Frontend** | Add mail inbox, whitelist management, WebSocket-driven updates. Replace polling with WS-DO push. |
+| **CLI** | Follows main branch. Node.js + Commander.js. Dev runs via `pnpm cli` from project root. `.alook/` config at project root in dev. |
+| **Infra** | Makefile -> Turborepo. docker-compose -> wrangler.toml per service. |
diff --git a/docs/migration/01-web-service.md b/docs/migration/01-web-service.md
new file mode 100644
index 000000000..e81b4a37d
--- /dev/null
+++ b/docs/migration/01-web-service.md
@@ -0,0 +1,506 @@
+# 01 — Web Service
+
+> `@alook/web` — Next.js App Router, frontend pages + API routes.
+> Location: `src/web/`
+> Runtime: Cloudflare Workers via OpenNext.
+
+---
+
+## Dependencies
+
+### Current (main)
+
+```
+next 16.2.2, react 19.2.4, drizzle-orm 0.39, postgres 3.4
+jose 6.0, resend 4.0, zod 3.25, sonner 2.0, streamdown 2.5
+shadcn 4.2, tailwind-merge 3.5, lucide-react 1.7, next-themes 0.4
+@base-ui/react 1.3, input-otp 1.4, class-variance-authority 0.7
+```
+
+### Target changes
+
+| Remove | Replace with |
+|--------|-------------|
+| `postgres` (pg driver) | `drizzle-orm/d1` (Drizzle's D1 adapter) |
+| `jose` (JWT library) | `better-auth` (managed auth) |
+| `input-otp` | Remove (Better Auth handles auth UI) |
+
+Add: `better-auth`, `@opennextjs/cloudflare`
+
+---
+
+## Database
+
+### Connection
+
+Target: Cloudflare D1 via Drizzle ORM (`drizzle-orm/d1` adapter).
+
+Schema, DB factory, and query modules live in `@alook/shared` (shared with Email Worker and WS-DO):
+
+```
+src/shared/db/index.ts — createDb(d1Binding) factory
+src/shared/db/schema.ts — Drizzle table definitions (single source of truth)
+src/shared/db/queries/*.ts — Query modules (one per domain)
+```
+
+Web Service owns migration execution:
+
+```
+src/web/drizzle/ — Generated migration files (drizzle-kit)
+src/web/drizzle.config.ts — drizzle-kit config pointing to @alook/shared schema
+```
+
+D1 binding name: `DB` (from wrangler.toml, database `alook-app`).
+
+### Current connection (main, to be replaced)
+
+PostgreSQL via `postgres` driver + Drizzle ORM.
+Env: `DATABASE_URL` (default: `postgres://postgres:postgres@localhost:5432/alook?sslmode=disable`)
+
+### D1 Adaptation Notes
+
+| PostgreSQL (main) | D1 / SQLite (target) |
+|-------------------|---------------------|
+| `uuid` PK with `defaultRandom()` | `text` PK with nanoid generation |
+| `timestamp` with timezone | `text` with `DEFAULT (datetime('now'))` |
+| `jsonb` columns | `text` columns (JSON serialized) |
+| `boolean` | `integer` (0/1) |
+| `SELECT ... FOR UPDATE SKIP LOCKED` (task claiming) | CAS-style `UPDATE ... WHERE status='queued'` (see Task Claiming Strategy below) |
+| `uniqueIndex().where()` (partial indexes) | Supported in SQLite via `CREATE UNIQUE INDEX ... WHERE` |
+| Drizzle `pgTable` | Drizzle `sqliteTable` |
+
+### Schema
+
+#### Better Auth Managed Tables (4 tables)
+
+These tables use camelCase columns as required by Better Auth. Better Auth manages them directly.
+
+| Table | PK | Key Columns |
+|-------|-----|-------------|
+| `user` | text | email (unique), name, emailVerified, image, createdAt, updatedAt |
+| `session` | text | userId (FK user), token (unique), expiresAt, ipAddress, userAgent |
+| `account` | text | userId (FK user), accountId, providerId, accessToken, refreshToken, password |
+| `verification` | text | identifier, value, expiresAt |
+
+#### Application Tables (11 tables)
+
+| Table | PK | Key Columns | Relationships |
+|-------|-----|-------------|---------------|
+| `workspace` | text | name, slug (unique) | - |
+| `member` | text | workspace_id, user_id, role | FK workspace, user. Unique (workspace_id, user_id) |
+| `agent_runtime` | text | workspace_id, daemon_id, provider, status, device_info, metadata, last_seen_at | FK workspace. Unique (workspace_id, daemon_id, provider) |
+| `agent` | text | workspace_id, name, instructions, email_handle (unique), runtime_id, status, max_concurrent_tasks, owner_id, runtime_config, tools, triggers, visibility, forward_to_email | FK workspace, agent_runtime, user |
+| `agent_whitelist` | text | agent_id, email | FK agent (cascade). Unique (agent_id, email) |
+| `conversation` | text | workspace_id, agent_id, user_id, title | FK workspace, agent, user (all cascade) |
+| `message` | text | conversation_id, role, content, task_id | FK conversation (cascade) |
+| `agent_task_queue` | text | agent_id, runtime_id, workspace_id, conversation_id, prompt, status, priority, result, session_id, work_dir | FK agent (cascade), agent_runtime, workspace, conversation |
+| `task_message` | text | task_id, seq, type, tool, content, input, output | FK agent_task_queue (cascade) |
+| `emails` | text | agent_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded | FK agent (cascade) |
+| `machine_token` | text | user_id, workspace_id, token_hash (unique), name, last_used_at | FK user, workspace (cascade) |
+
+> **Note:** Main's `verification_code` table is removed — Better Auth manages verification via its own `verification` table. The `agent` table gains `email_handle` and `forward_to_email` columns. New tables: `agent_whitelist`, `emails`.
+
+### Indexes
+
+- `idx_one_pending_per_conversation` — unique partial on `agent_task_queue.conversation_id` WHERE status IN ('queued','dispatched')
+- `idx_task_queue_pending` — on `agent_task_queue(agent_id, status)` WHERE status IN ('queued','dispatched')
+- `idx_task_message_task_seq` — on `task_message(task_id, seq)`
+- `idx_machine_token_hash` — on `machine_token(token_hash)`
+
+### Task Claiming Strategy (D1)
+
+PostgreSQL uses `SELECT ... FOR UPDATE SKIP LOCKED` for concurrent task claiming. D1 (SQLite) does not support row-level locking. Instead, use a **CAS (Compare-And-Swap) style conditional UPDATE**:
+
+```sql
+UPDATE agent_task_queue
+SET status = 'dispatched',
+ runtime_id = ?,
+ dispatched_at = datetime('now')
+WHERE id = (
+ SELECT id FROM agent_task_queue
+ WHERE agent_id = ? AND status = 'queued'
+ ORDER BY priority DESC, created_at ASC
+ LIMIT 1
+)
+AND status = 'queued'
+RETURNING *
+```
+
+If another worker claims the same task concurrently, the `AND status = 'queued'` guard causes the UPDATE to affect 0 rows — the caller retries with the next queued task. This works because:
+
+- D1 operates in **auto-commit mode** — each statement is atomic
+- D1's `batch()` API runs statements as an **implicit SQL transaction** (sequential, non-concurrent, rolls back on failure)
+- The `WHERE status = 'queued'` acts as the compare step — if status changed since the subquery, the update is a no-op
+- No explicit `BEGIN`/`COMMIT` needed; the single statement is atomic
+
+For the full `claimTask` flow that combines concurrent-task counting with the claim UPDATE, use `db.batch()` to wrap both statements in a single transaction.
+
+> **Reference:** [Cloudflare D1 Worker API — batch()](https://developers.cloudflare.com/d1/worker-api/d1-database/)
+
+---
+
+### Query Modules (in `@alook/shared`)
+
+All query modules now live in `@alook/shared/db/queries/` and are shared across Web Service, Email Worker, and WS-DO. See [05-shared-library.md](05-shared-library.md) for the full list.
+
+Key queries used by Web Service:
+
+| Module | Functions |
+|--------|-----------|
+| **user** | `getUser`, `getUserByEmail`, `createUser`, `updateUser` |
+| **workspace** | `getWorkspace`, `listWorkspaces(userId)`, `createWorkspace` |
+| **member** | `getMemberByUserAndWorkspace`, `listMembers`, `createMember` |
+| **agent** | `getAgent`, `getAgentByHandle`, `getAgentInWorkspace`, `listAgents(workspaceId)`, `createAgent`, `deleteAgent` (tx: deletes tasks first), `updateAgent`, `updateAgentStatus` |
+| **runtime** | `upsertAgentRuntime` (on-conflict update), `listAgentRuntimes`, `getAgentRuntime`, `updateAgentRuntimeHeartbeat`, `setAgentRuntimeOffline`, `deleteRuntimesByDaemonId`, `markStaleRuntimesOffline` (>45s) |
+| **conversation** | `createConversation`, `getConversation`, `listConversations`, `listConversationsByAgent` (with message count), `updateConversationTitle`, `deleteConversation` |
+| **message** | `createMessage`, `listMessages(conversationId)`, `getMessage` |
+| **task** | `createTask`, `getTask`, `claimTask`, `startTask`, `completeTask`, `failTask`, `getLastTaskSession`, `listPendingTasksByRuntime`, `failStaleDispatchedTasks(20s)`, `countRunningTasks`, ... |
+| **task-message** | `createTaskMessage`, `listTaskMessages`, `listTaskMessagesSince(afterSeq)`, `deleteTaskMessages` |
+| **machine-token** | `createMachineToken`, `getMachineTokenByHash`, `listMachineTokens`, `deleteMachineToken`, `updateMachineTokenLastUsed` |
+| **whitelist** | `getWhitelist`, `addWhitelist`, `removeWhitelist`, `isWhitelisted` |
+| **email** | `createEmail`, `getEmailById`, `getEmailsByAgent`, `getEmailsByUser` |
+
+> **Removed:** `verification-code` module — Better Auth manages verification internally.
+
+---
+
+## Authentication & Middleware
+
+### Target: Better Auth
+
+Replace main's custom JWT + OTP auth with Better Auth. Better Auth manages user, session, account, and verification tables directly in D1.
+
+#### Better Auth Setup (`lib/auth.ts`)
+
+```typescript
+import { betterAuth } from "better-auth"
+
+export function createAuth(env: Env) {
+ return betterAuth({
+ baseURL: env.BETTER_AUTH_URL,
+ database: env.DB, // D1 binding
+ secret: env.BETTER_AUTH_SECRET,
+ emailAndPassword: {
+ enabled: true,
+ requireEmailVerification: false,
+ },
+ socialProviders: {
+ github: {
+ clientId: env.GITHUB_CLIENT_ID,
+ clientSecret: env.GITHUB_CLIENT_SECRET,
+ },
+ google: {
+ clientId: env.GOOGLE_CLIENT_ID,
+ clientSecret: env.GOOGLE_CLIENT_SECRET,
+ },
+ },
+ })
+}
+```
+
+#### Auth Client (`lib/auth-client.ts`)
+
+```typescript
+import { createAuthClient } from "better-auth/react"
+
+export const authClient = createAuthClient({
+ baseURL: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
+})
+
+export const { signIn, signUp, signOut, useSession } = authClient
+```
+
+#### Auth Route (`app/api/auth/[...all]/route.ts`)
+
+Better Auth catch-all route handles all auth endpoints (sign-in, sign-up, sign-out, callback, session).
+
+#### Dual Auth Middleware
+
+Every API route uses dual auth — supports both browser sessions and machine tokens:
+
+```typescript
+// lib/dual-auth.ts
+export async function requireAuth(request: Request) {
+ // 1. Check for machine token (Bearer al_*)
+ const authHeader = request.headers.get("Authorization")
+ if (authHeader?.startsWith("Bearer ")) {
+ const token = authHeader.slice(7)
+ if (isValidToken(token)) {
+ const runtime = await db.getRuntimeByToken(token)
+ if (runtime) return { userId: runtime.user_id, db, error: null }
+ }
+ }
+
+ // 2. Fall back to Better Auth session (cookie-based)
+ const auth = createAuth(env)
+ const session = await auth.api.getSession({ headers: request.headers })
+ if (session) return { userId: session.user.id, db, error: null }
+
+ return { userId: null, db: null, error: new Response("Unauthorized", { status: 401 }) }
+}
+```
+
+#### Better Auth Managed Tables (in D1)
+
+| Table | Purpose |
+|-------|---------|
+| `user` | Users (id, name, email, emailVerified, image, createdAt, updatedAt) — camelCase columns as required by Better Auth |
+| `session` | DB-backed sessions (id, userId, token, expiresAt, ipAddress, userAgent) |
+| `account` | OAuth accounts (userId, accountId, providerId, accessToken, refreshToken, password) |
+| `verification` | Email verification tokens (identifier, value, expiresAt) |
+
+#### Auth Env Vars
+
+| Env Var | Purpose |
+|---------|---------|
+| `BETTER_AUTH_URL` | Base URL for auth endpoints |
+| `BETTER_AUTH_SECRET` | Session signing secret |
+| `GITHUB_CLIENT_ID` | GitHub OAuth client ID |
+| `GITHUB_CLIENT_SECRET` | GitHub OAuth client secret |
+| `GOOGLE_CLIENT_ID` | Google OAuth client ID |
+| `GOOGLE_CLIENT_SECRET` | Google OAuth client secret |
+
+#### What Changes from Main's Auth
+
+| Main (current) | Target (Better Auth) |
+|----------------|---------------------|
+| Custom JWT (HS256, 72h, jose library) | DB-backed sessions (Better Auth managed) |
+| OTP email verification (custom, Resend) | Email/password + GitHub + Google OAuth |
+| `verification_code` table (custom) | `verification` table (Better Auth managed) |
+| `machine_token` table (SHA256 hashed) | Machine tokens kept — dual auth checks token first, then session |
+| Stateless JWT in Authorization header | Session cookie (Better Auth) + machine token in Authorization header |
+| Custom `withAuth` middleware | `requireAuth()` dual-auth helper |
+| Frontend stores JWT in localStorage | Frontend uses `useSession()` hook from `better-auth/react` |
+| `/login` page (OTP input) | `/sign-in` and `/sign-up` pages (email/password + OAuth buttons) |
+
+### Middleware (kept from main)
+
+| Module | Location | Purpose |
+|--------|----------|---------|
+| **withWorkspaceMember** | `lib/middleware/workspace.ts` | Resolves workspace_id from query param, `X-Workspace-ID` header, or auth context. Checks membership in `member` table. Returns `{workspaceId}` or 400/401/404. |
+| **request-id** | `lib/middleware/request-id.ts` | `getRequestId()` from `X-Request-ID` header or random UUID. `setRequestIdHeader()` on response. |
+| **request-logger** | `lib/middleware/request-logger.ts` | `logRequest()` — structured JSON to stdout/stderr. Skips `/health`. |
+| **helpers** | `lib/middleware/helpers.ts` | `writeJSON()`, `writeError()`, `formatTimestamp()`, `formatTimestampNullable()`, `parseBody(req, zodSchema)` |
+
+### Task Service (`lib/services/task.ts`)
+
+| Method | Logic |
+|--------|-------|
+| `enqueueTask(agentId, conversationId, workspaceId, prompt)` | Validates agent exists + has runtime, creates task row |
+| `claimTask(agentId)` | Checks `countRunningTasks < maxConcurrentTasks`, calls `task.claimTask`, updates agent status to "working" |
+| `claimTaskForRuntime(runtimeId)` | Lists pending tasks for runtime, tries `claimTask` per agent (deduped) |
+| `startTask(taskId)` | Transitions dispatched -> running |
+| `completeTask(taskId, result, sessionId, workDir)` | Transitions running -> completed, creates assistant message if output present, reconciles agent status |
+| `failTask(taskId, error)` | Transitions dispatched/running -> failed, creates error message, reconciles agent status |
+| `reconcileAgentStatus(agentId)` | Sets agent to "working" if running tasks > 0, else "idle" |
+
+### Response Formatters (`lib/api/responses.ts`)
+
+Converts Drizzle camelCase rows to snake_case API responses: `userToResponse`, `workspaceToResponse`, `agentToResponse`, `taskToResponse`, `conversationToResponse`, `messageToResponse`, `taskMessageToResponse`, `runtimeToResponse`, `machineTokenToResponse`.
+
+### Client-Side API (`lib/api.ts`)
+
+`apiFetch<T>()` wrapper:
+- Reads `alook_workspace_id` from localStorage for `X-Workspace-ID` header
+- Session cookie sent automatically by browser (Better Auth manages this)
+- On 401: redirects to `/sign-in`
+- On 429: "Please wait" error
+- Exports typed functions for all endpoints (see API Endpoints below)
+
+### Error Class (`lib/errors.ts`)
+
+`ApiError(message, status, details?)` with helpers: `isNetworkError`, `isRateLimit`, `isUnauthorized`.
+
+### Logger (`lib/logger.ts`)
+
+Structured JSON logger. Levels: debug/info/warn/error/silent. Env: `ALOOK_LOG_LEVEL` (default: info). Errors to stderr, rest to stdout.
+
+---
+
+## API Endpoints (37 routes)
+
+### Authentication (Public)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| ALL | `/api/auth/[...all]` | **Better Auth catch-all.** Handles sign-in, sign-up, sign-out, session, OAuth callbacks. Replaces main's `/api/auth/send-code` and `/api/auth/verify-code`. |
+| GET | `/api/me` | Returns current user profile. Session auth. |
+| GET | `/api/health` | `{ status: "ok" }`. No auth. |
+
+### Workspaces (Session Auth)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | `/api/workspaces` | List user's workspaces (via member join) |
+| POST | `/api/workspaces` | Create workspace (name, slug). Handles slug collision with random hex suffix. Creates member with "owner" role. |
+| GET | `/api/workspaces/[id]` | Get workspace by ID |
+
+### Agents (Session Auth + Workspace Member)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | `/api/agents` | List agents in workspace |
+| POST | `/api/agents` | Create agent (name, description, instructions, runtime_id, runtime_config, max_concurrent_tasks). Validates runtime exists. Sets visibility "private", ownerId = current user. Reconciles agent status if runtime online. |
+| GET | `/api/agents/[id]` | Get agent in workspace |
+| PATCH | `/api/agents/[id]` | Partial update (name, description, instructions, runtime_id) |
+| DELETE | `/api/agents/[id]` | Delete agent (transaction: delete tasks first, then agent) |
+| GET | `/api/agents/[id]/conversations` | List conversations for agent (includes message count) |
+
+### Conversations & Messages (Session Auth + Workspace Member)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | `/api/conversations` | List user's conversations in workspace |
+| POST | `/api/conversations` | Create conversation (agent_id) |
+| GET | `/api/conversations/[id]` | Get conversation (validates workspace) |
+| DELETE | `/api/conversations/[id]` | Delete conversation (deletes tasks first, messages cascade) |
+| GET | `/api/conversations/[id]/messages` | List messages in conversation |
+| POST | `/api/conversations/[id]/messages` | Send message. Auto-titles conversation from first message (50 char truncate). Creates task via TaskService.enqueueTask. Returns `{ message, task }`. |
+
+### Tasks (Session Auth + Workspace Member)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | `/api/tasks/[id]` | Get task (validates workspace) |
+| GET | `/api/tasks/[id]/messages` | Get task messages. Supports `?since=N` for incremental polling. |
+
+### Machine Tokens (Session Auth + Workspace Member)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | `/api/machine-tokens` | List tokens for user in workspace |
+| POST | `/api/machine-tokens` | Create token (name, default: "default"). Returns raw token only at creation. Stores hashed. |
+| DELETE | `/api/machine-tokens/[id]` | Delete token (must be owned by user) |
+
+### Runtimes (Session Auth + Workspace Member)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| GET | `/api/runtimes` | List runtimes. Marks stale (>45s) as offline first. |
+| DELETE | `/api/runtimes/machine` | Delete all runtimes for `daemon_id` query param |
+
+### Daemon Endpoints (Machine Token Auth)
+
+| Method | Path | Handler |
+|--------|------|---------|
+| POST | `/api/daemon/register` | Register daemon with runtimes. Upserts runtime rows (on-conflict by workspace+daemon+provider). Body: `{ workspace_id, daemon_id, device_name, cli_version, runtimes[] }` |
+| POST | `/api/daemon/deregister` | Set runtimes offline. Body: `{ runtime_ids[] }` |
+| POST | `/api/daemon/heartbeat` | Update runtime heartbeat timestamp. Marks stale runtimes offline. Fails stuck dispatched tasks (>20s). Reconciles affected agents. Body: `{ runtime_id }` |
+| POST | `/api/daemon/runtimes/[runtimeId]/tasks/claim` | Claim next queued task. Returns task with agent instructions + prior session context (session_id, work_dir). Returns `{ task: null }` if none. |
+| POST | `/api/daemon/tasks/[taskId]/start` | Mark task as started (dispatched -> running) |
+| POST | `/api/daemon/tasks/[taskId]/complete` | Mark complete. Stores result, session_id, work_dir. Creates assistant message if output present. Reconciles agent status. Body: `{ output?, session_id?, work_dir?, branch_name? }` |
+| POST | `/api/daemon/tasks/[taskId]/fail` | Mark failed. Creates error message. Reconciles agent status. Body: `{ error? }` |
+| POST | `/api/daemon/tasks/[taskId]/progress` | No-op heartbeat for task progress |
+| GET | `/api/daemon/tasks/[taskId]/status` | Poll task status |
+| GET | `/api/daemon/tasks/[taskId]/messages` | Get task messages |
+| POST | `/api/daemon/tasks/[taskId]/messages` | Report messages batch. Body: `{ messages: [{ seq, type, tool?, content?, input?, output? }] }` |
+
+---
+
+## Frontend Pages
+
+### Layouts
+
+| Layout | Location | Purpose |
+|--------|----------|---------|
+| Root | `app/layout.tsx` | Fonts (DM Sans, DM Mono, Caveat), ThemeProvider, ToasterProvider |
+| App | `app/(app)/layout.tsx` | Auth guard (Better Auth `useSession()` check), AgentProvider context, AppSidebar + floating content panel with gradient background |
+
+### Pages
+
+| Route | File | Purpose |
+|-------|------|---------|
+| `/` | `app/page.tsx` | Redirect: has session -> `/home`, else -> `/sign-in` |
+| `/sign-in` | `app/(auth)/sign-in/page.tsx` | Email/password sign-in + GitHub + Google OAuth buttons (Better Auth) |
+| `/sign-up` | `app/(auth)/sign-up/page.tsx` | Email/password sign-up + OAuth (Better Auth) |
+| `/home` | `app/(app)/home/page.tsx` | Redirect to first agent's detail page (sorted by name). Empty states for no agents / no runtimes. |
+| `/agents` | `app/(app)/agents/page.tsx` | Redirect to `/home` |
+| `/agents/new` | `app/(app)/agents/new/page.tsx` | Create agent form (AgentEditForm). On save: create agent -> create conversation -> redirect to `/chat/{conversationId}?agent={agentId}` |
+| `/agents/[id]` | `app/(app)/agents/[id]/page.tsx` | Agent detail: runtime status indicator, inline edit (AgentEditForm), session list with message counts, new session button, delete agent |
+| `/chat/[id]` | `app/(app)/chat/[id]/page.tsx` | Chat UI: user messages (right-aligned), agent messages (left, Streamdown markdown). Active task: status badge, scrollable task message log (tool calls, thinking, text). Input textarea (Enter to send). Polls task messages every 1s. |
+| `/runtimes` | `app/(app)/runtimes/page.tsx` | Machine list grouped by daemon_id. Runtime cards with provider, version, status badge. "New machine" sheet: generate token, show CLI commands. |
+
+### Components
+
+| Component | Location | Purpose |
+|-----------|----------|---------|
+| `AgentEditForm` | `components/agent-edit-form.tsx` | Form for agent name, description, instructions, runtime select |
+| `AppSidebar` | `components/app-sidebar.tsx` | Narrow sidebar: agent avatar buttons (initial letter), create agent (+), runtimes (Monitor icon), sign out via `signOut()` from Better Auth client |
+| `GradientBackground` | `components/gradient-background.tsx` | Decorative background |
+| `Logo` | `components/logo.tsx` | Alook logo, supports `iconOnly` mode |
+| `RuntimeSelect` | `components/runtime-select.tsx` | Runtime picker dropdown |
+| `ThemeProvider` | `components/theme-provider.tsx` | next-themes wrapper |
+| `ThemeToggle` | `components/theme-toggle.tsx` | Light/dark toggle |
+| `ToasterProvider` | `components/toaster-provider.tsx` | Sonner toast wrapper |
+| `DashboardNavbar` | `components/dashboard-navbar.tsx` | Top navbar |
+| UI primitives | `components/ui/*` | avatar, badge, button, card, confirm-dialog, dialog, input-otp, input, label, scroll-area, select, separator, sheet, textarea |
+
+### Context
+
+`AgentProvider` (`contexts/agent-context.tsx`) — global state for the `(app)` route group:
+
+| Value | Type | Purpose |
+|-------|------|---------|
+| `agents` | Agent[] | All agents in workspace |
+| `runtimes` | Runtime[] | All runtimes in workspace |
+| `loading` | boolean | Initial load state |
+| `reload()` | async | Refresh agents + runtimes |
+| `handleCreateAgent(req)` | async -> Agent | Create agent + reload |
+| `handleUpdateAgent(id, req)` | async -> boolean | Update agent + reload |
+| `handleDeleteAgent(id)` | async -> boolean | Delete agent + reload |
+| `chatWithAgent(agentId)` | async -> string | Create conversation, return ID |
+| `getFirstOnlineRuntimeId()` | -> string | First online runtime ID |
+| `handleGenerateToken()` | async -> string | Create machine token |
+| `handleDeleteMachine(daemonId)` | async -> boolean | Delete machine + reload |
+
+---
+
+## Test Files
+
+### Existing tests (from main, to be adapted for D1)
+
+```
+app/api/agents/route.test.ts
+app/api/agents/[id]/route.test.ts
+app/api/agents/[id]/conversations/route.test.ts
+app/api/conversations/route.test.ts
+app/api/conversations/[id]/route.test.ts
+app/api/conversations/[id]/messages/route.test.ts
+app/api/daemon/routes.test.ts
+app/api/daemon/deregister/route.test.ts
+app/api/daemon/heartbeat/route.test.ts
+app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts
+app/api/daemon/tasks/[taskId]/start/route.test.ts
+app/api/daemon/tasks/[taskId]/status/route.test.ts
+app/api/health/route.test.ts
+app/api/machine-tokens/route.test.ts
+app/api/machine-tokens/[id]/route.test.ts
+app/api/me/route.test.ts
+app/api/runtimes/route.test.ts
+app/api/runtimes/machine/route.test.ts
+app/api/tasks/[id]/route.test.ts
+app/api/tasks/[id]/messages/route.test.ts
+app/api/workspaces/route.test.ts
+app/api/workspaces/[id]/route.test.ts
+lib/api.test.ts
+lib/api/responses.test.ts
+lib/logger.test.ts
+lib/middleware/helpers.test.ts
+lib/middleware/request-id.test.ts
+lib/middleware/request-logger.test.ts
+lib/middleware/workspace.test.ts
+lib/services/task.test.ts
+lib/db/queries/agent.integration.test.ts
+lib/db/queries/conversation.integration.test.ts
+lib/db/queries/conversation.test.ts
+lib/db/queries/machine-token.integration.test.ts
+lib/db/queries/runtime.integration.test.ts
+lib/db/queries/task-extended.integration.test.ts
+lib/db/queries/task.integration.test.ts
+lib/db/queries/task.test.ts
+lib/db/queries/task-queries.test.ts
+lib/db/queries/workspace.integration.test.ts
+```
+
+> **Removed:** `auth/send-code`, `auth/verify-code`, `auth/jwt`, `services/email`, `verification-code` tests — replaced by Better Auth.
+> **To add:** tests for dual-auth middleware, whitelist queries, email queries.
diff --git a/docs/migration/02-email-worker.md b/docs/migration/02-email-worker.md
new file mode 100644
index 000000000..ed94f766e
--- /dev/null
+++ b/docs/migration/02-email-worker.md
@@ -0,0 +1,260 @@
+# 02 — Email Worker
+
+> `@alook/email-worker` — Cloudflare Worker for inbound email handling.
+> Location: `src/email-worker/`
+> Status on `main`: **Not implemented.** This doc preserves the full spec-plans implementation.
+
+---
+
+## Overview
+
+The Email Worker receives inbound emails via Cloudflare Email Routing, verifies agent/whitelist via D1, stores raw email content in R2, and notifies the Web Service which handles task and email record creation. The Email Worker is the verification and storage layer — the Web Service is the task orchestration layer.
+
+```
+Inbound SMTP → Cloudflare Email Routing → Email Worker
+ → D1 via Drizzle (verify agent + whitelist)
+ → R2 (store raw email)
+ → Web Service (POST /api/email/notify via service binding — creates email record + task)
+```
+
+---
+
+## Dependencies
+
+```json
+{
+ "@alook/shared": "workspace:*",
+ "drizzle-orm": "^0.39.0",
+ "nanoid": "latest"
+}
+```
+
+- `@alook/shared` provides Drizzle schema, DB factory, types, and query functions (shared with Web Service and WS-DO)
+- `drizzle-orm` for type-safe D1 queries via the shared schema
+
+Dev: `wrangler`, `vitest`, `@cloudflare/workers-types`, `typescript`
+
+---
+
+## Wrangler Configuration
+
+```toml
+name = "alook-email-worker"
+main = "src/index.ts"
+compatibility_date = "2025-04-01"
+compatibility_flags = ["nodejs_compat"]
+
+[dev]
+port = 8788
+
+[[d1_databases]]
+binding = "DB"
+database_id = "FILL_AFTER_CREATE"
+database_name = "alook-app"
+
+[[r2_buckets]]
+binding = "EMAIL_BUCKET"
+bucket_name = "alook-emails"
+
+[[services]]
+binding = "WEB_SERVICE"
+service = "alook-web"
+```
+
+### Bindings
+
+| Binding | Type | Target |
+|---------|------|--------|
+| `DB` | D1 Database | `alook-app` (shared with Web Service) |
+| `EMAIL_BUCKET` | R2 Bucket | `alook-emails` |
+| `WEB_SERVICE` | Service Binding | `alook-web` (Web Service worker) |
+
+---
+
+## Environment Interface
+
+```typescript
+interface EmailEnv {
+ DB: D1Database
+ EMAIL_BUCKET: R2Bucket
+ WEB_SERVICE: Fetcher
+}
+```
+
+---
+
+## Handlers
+
+### `email(message, env)` — Inbound Email Handler
+
+Triggered by Cloudflare Email Routing when an email arrives at an `@alook.ai` address.
+
+**Flow:**
+
+```
+1. Parse handle from recipient address (message.to)
+ └── Uses @alook/shared parseEmailHandle()
+
+2. Look up agent by handle
+ └── queries.agent.getAgentByHandle(db, handle)
+ └── If not found → message.setReject("No agent found for this address")
+
+3. Check if sender is whitelisted
+ └── queries.whitelist.isWhitelisted(db, agentId, senderEmail)
+
+4. Store raw email in R2
+ └── Read message.raw stream → ArrayBuffer
+ └── PUT to R2 at "emails/{nanoid}/raw"
+ └── Content-Type: "message/rfc822"
+
+5a. If whitelisted:
+ └── Notify Web Service: POST http://internal/api/email/notify
+ Body: { agentId, r2Key, from, subject, isWhitelisted: true }
+ └── Web Service handles: create email record, create task, broadcast via WS-DO
+
+5b. If NOT whitelisted:
+ └── Resolve forward address: agent.forward_to_email, fallback to user.email
+ └── If forwardTo exists:
+ └── Notify Web Service: POST http://internal/api/email/notify
+ Body: { agentId, r2Key, from, subject, isWhitelisted: false, forwarded: true }
+ └── message.forward(forwardTo)
+ └── If no forwardTo:
+ └── Notify Web Service: POST http://internal/api/email/notify
+ Body: { agentId, r2Key, from, subject, isWhitelisted: false, forwarded: false }
+ └── NO task created by Web Service (non-whitelisted)
+```
+
+> **Design principle:** The Email Worker is responsible for verification (agent lookup, whitelist check) and storage (R2). The Web Service is responsible for persistence (email records, tasks) and orchestration (WS-DO broadcast). This keeps the Email Worker stateless beyond R2 and avoids duplicating task creation logic.
+
+### `fetch(request, env)` — HTTP Simulation Endpoint
+
+Development-only endpoint for testing email flow without real SMTP.
+
+- **POST `/simulate`** — Accepts `{ from, to, subject?, body? }`, constructs a fake `ForwardableEmailMessage`, and calls `this.email()`.
+- Returns `{ ok: true }` or `{ error: "..." }` (500).
+- All other routes return 404.
+
+---
+
+## Database Access
+
+The Email Worker uses Drizzle ORM via the shared schema and query functions from `@alook/shared` for **read-only verification** (agent lookup, whitelist check). It does **not** write email records or tasks — that is the Web Service's responsibility after receiving the `/api/email/notify` call.
+
+```typescript
+import { createDb, schema, queries } from "@alook/shared"
+
+const db = createDb(env.DB) // D1 binding → Drizzle instance
+```
+
+### Queries Used
+
+| Operation | Shared Query Function | Table | Access |
+|-----------|----------------------|-------|--------|
+| Look up agent by email handle | `queries.agent.getAgentByHandle(db, handle)` | `agent` | Read |
+| Get user email (for forward fallback) | `queries.user.getUser(db, userId)` | `user` | Read |
+| Check sender whitelist | `queries.whitelist.isWhitelisted(db, agentId, email)` | `agent_whitelist` | Read |
+
+> **All tables are defined and migrated by the Web Service.** The Email Worker only reads from them for verification. Email records and tasks are created by the Web Service upon receiving the `/api/email/notify` call. See [01-web-service.md](01-web-service.md) for the full schema definition.
+
+### Referenced Tables
+
+| Table | Access | Purpose |
+|-------|--------|---------|
+| `agent` | Read | Look up agent by `email_handle`, get `forward_to_email`, `runtime_id`, `owner_id` |
+| `user` | Read | Get owner email for forward fallback |
+| `agent_whitelist` | Read | Check if sender is whitelisted |
+
+---
+
+## Service Binding Notification
+
+The Email Worker notifies the Web Service after storing the raw email in R2. The Web Service handles all persistence and orchestration.
+
+```
+POST http://internal/api/email/notify
+Content-Type: application/json
+
+{
+ "agentId": "agent-1",
+ "r2Key": "emails/abc123/raw",
+ "from": "[email protected]",
+ "subject": "Hello",
+ "isWhitelisted": true,
+ "forwarded": false
+}
+```
+
+### What the Web Service does on `/api/email/notify`
+
+| Field | Web Service Action |
+|-------|-------------------|
+| `isWhitelisted: true` | Create email record + create task in `agent_task_queue` + broadcast `email.received` via WS-DO |
+| `isWhitelisted: false, forwarded: true` | Create email record only (forwarded, no task) |
+| `isWhitelisted: false, forwarded: false` | Create email record only (dropped, no task) |
+
+This keeps task creation logic in the Web Service (single owner of write operations) and the Email Worker focused on verification + R2 storage.
+
+---
+
+## R2 Storage Layout
+
+```
+alook-emails/
+ emails/{nanoid}/raw ← RFC 822 raw email bytes
+ Content-Type: message/rfc822
+```
+
+---
+
+## Test Coverage
+
+**File:** `src/email-worker/src/index.test.ts`
+
+### Test Groups
+
+| Group | Tests | What's Covered |
+|-------|-------|----------------|
+| Agent resolution | 3 | Reject on no agent, parse handle from alook.ai address, reject non-alook domain |
+| R2 storage | 2 | Correct R2 key + content-type, ArrayBuffer matches raw email |
+| Whitelisted path | 5 | R2 stored, Web Service notified with `isWhitelisted: true` + correct payload, empty subject default, no forward called |
+| Non-whitelisted path | 4 | R2 stored, Web Service notified with `isWhitelisted: false`, forward when `forward_to_email` set, no forward when empty |
+| Error propagation | 3 | D1 failure, R2 failure, web service binding failure |
+
+### Test Mocks (`src/email-worker/src/__mocks__/cf.ts`)
+
+| Mock | Factory | Purpose |
+|------|---------|---------|
+| `createMockD1(config)` | D1 Database | Configurable agents map + whitelist set. Tracks all SQL calls with bindings. To be adapted for Drizzle — mock the Drizzle DB instance instead of raw D1. |
+| `createMockR2()` | R2 Bucket | Mock `put()` method, tracks calls |
+| `createMockFetcher()` | Service Binding | Mock `fetch()`, tracks calls. Verify `/api/email/notify` is called with correct payload (agentId, r2Key, from, subject, isWhitelisted, forwarded). |
+| `createMockMessage(opts)` | ForwardableEmailMessage | Creates mock email with from, to, subject, body. Returns `setReject`, `forward`, `rawText` spies. |
+
+---
+
+## Migration Notes
+
+### Changes from spec-plans implementation
+
+| Spec-plans | Target |
+|------------|--------|
+| Raw D1 `db.prepare().bind()` queries | Drizzle ORM via shared schema from `@alook/shared` |
+| Inline `getDb()` helper with all queries | Import shared query modules from `@alook/shared` (read-only verification) |
+| Creates event in `events` table | Notifies Web Service via `POST /api/email/notify` — Web Service creates task |
+| Email Worker writes email records + tasks | Email Worker only reads (verify) + stores R2 — Web Service handles all writes |
+| `nanoid` for ID generation | Drizzle handles ID generation via schema defaults |
+| Table definitions duplicated in worker | Tables defined once in `@alook/shared` schema, migrated by Web Service |
+
+### Task Creation via Web Service API
+
+The Email Worker does not create tasks or email records directly. Instead:
+
+```
+Spec-plans: email → create event in events table → CLI polls events → CLI creates task
+Target: email → verify + store R2 → POST /api/email/notify → Web Service creates email record + task → CLI claims task
+```
+
+This keeps the Web Service as the single owner of write operations, avoiding duplicated task creation logic across services. The CLI daemon claims tasks through the existing `/api/daemon/runtimes/{id}/tasks/claim` endpoint. No events table needed.
+
+### Schema and queries are in `@alook/shared`
+
+All Drizzle schema definitions, the DB factory (`createDb(d1Binding)`), and query modules live in `@alook/shared`. The Email Worker imports them for **read-only verification** (agent lookup, whitelist check) — it does not write to D1. See [05-shared-library.md](05-shared-library.md) for the shared module structure.
diff --git a/docs/migration/03-ws-do.md b/docs/migration/03-ws-do.md
new file mode 100644
index 000000000..89e50cb5f
--- /dev/null
+++ b/docs/migration/03-ws-do.md
@@ -0,0 +1,347 @@
+# 03 — WS-DO (WebSocket Durable Objects)
+
+> `@alook/ws-do` — Cloudflare Durable Objects for real-time browser notifications.
+> Location: `src/ws-do/`
+> Status on `main`: **Not implemented** (main uses HTTP polling only). This doc preserves the spec-plans implementation with a simplified notification-only protocol.
+
+---
+
+## Overview
+
+WS-DO is a **notification-only** WebSocket channel for the browser frontend. It does not carry data payloads — it sends lightweight event notifications that tell the browser *what changed*, and the browser re-fetches the actual data via the REST API.
+
+```
+Browser ←── WebSocket (notifications only) ──→ Durable Object
+ ↑
+Web Service ── service binding POST /broadcast ──→ WS-DO Worker
+
+Browser ── REST API (data fetches) ──→ Web Service
+```
+
+This design keeps a single source of truth (the REST API) and avoids maintaining two data protocols. The WebSocket is purely a signal channel.
+
+### Why notification-only
+
+- **One data protocol** — REST API is the single source of truth for all data. No data duplication over WebSocket.
+- **More stable** — browser always fetches fresh data from the API after notification. No stale-cache issues.
+- **Simpler WS-DO** — no need to serialize full objects into broadcast messages. Just event type + resource ID.
+- **CLI not involved** — CLI daemon uses HTTP polling only. WebSocket is browser-only.
+
+---
+
+## Dependencies
+
+```json
+{
+ "@alook/shared": "workspace:*",
+ "drizzle-orm": "^0.39.0"
+}
+```
+
+- `@alook/shared` provides Drizzle schema, DB factory, and query functions (shared with Web Service and Email Worker)
+- `drizzle-orm` for type-safe D1 queries (token validation)
+
+Dev: `wrangler`, `@cloudflare/workers-types`, `typescript`
+
+---
+
+## Wrangler Configuration
+
+```toml
+name = "alook-ws-do"
+main = "src/index.ts"
+compatibility_date = "2025-04-01"
+compatibility_flags = ["nodejs_compat"]
+
+[dev]
+port = 8789
+inspector_port = 9230
+
+[[d1_databases]]
+binding = "DB"
+database_id = "FILL_AFTER_CREATE"
+database_name = "alook-app"
+
+[[durable_objects.bindings]]
+name = "WS_DO"
+class_name = "WebSocketDurableObject"
+
+[[migrations]]
+tag = "v1"
+new_sqlite_classes = ["WebSocketDurableObject"]
+```
+
+### Bindings
+
+| Binding | Type | Target |
+|---------|------|--------|
+| `DB` | D1 Database | `alook-app` (for token validation only) |
+| `WS_DO` | Durable Object | `WebSocketDurableObject` class |
+
+---
+
+## Environment Interface
+
+```typescript
+interface Env {
+ DB: D1Database
+ WS_DO: DurableObjectNamespace
+}
+```
+
+---
+
+## Notification Protocol
+
+### Message Format
+
+All WebSocket messages are JSON with `type` and `id` fields. No data payload.
+
+```typescript
+interface WsNotification {
+ type: string // event type
+ id: string // resource ID
+}
+```
+
+### Event Types
+
+| Type | Sent When | ID Field | Browser Action |
+|------|-----------|----------|----------------|
+| `task.updated` | Task status changes (started, progress, completed, failed) | task ID | `GET /api/tasks/{id}` |
+| `runtime.updated` | Runtime comes online, goes offline, registered, deleted | runtime ID | `GET /api/runtimes` |
+| `email.received` | New whitelisted email arrives | email ID | `GET /api/emails` |
+| `agent.updated` | Agent config changed, status changed | agent ID | `GET /api/agents/{id}` |
+
+### Browser Handling
+
+```typescript
+// Browser receives notification → re-fetches via REST API
+ws.onmessage = (event) => {
+ const { type, id } = JSON.parse(event.data)
+ switch (type) {
+ case "task.updated": refetchTask(id); break
+ case "runtime.updated": refetchRuntimes(); break
+ case "email.received": refetchEmails(); break
+ case "agent.updated": refetchAgent(id); break
+ }
+}
+```
+
+---
+
+## Architecture
+
+### Channel Model
+
+Each Durable Object instance represents a **channel**. Channels are identified by name:
+
+| Channel Type | DO Name | Purpose |
+|--------------|---------|---------|
+| User channel | `user:{userId}` | All notifications for a user (tasks, runtimes, emails, agents) |
+
+The DO name is used with `env.WS_DO.idFromName()` to get a deterministic ID.
+
+> **Why user-only channels (no agent channels):** Agent-scoped events (e.g. `email.received` for agent X, `task.updated` for agent Y) are routed through the agent's **owner's** user channel. The Web Service resolves `agent.owner_id` → `userId` and broadcasts to `user:{userId}`. The browser filters events client-side by agent ID if needed. This avoids managing a second channel tier and keeps the DO model simple — one DO per user, regardless of how many agents they own. Spec-plans implemented both user and agent channels, but the added complexity provided no benefit since the browser already knows which agents belong to the current user.
+
+### Connection Lifecycle
+
+```
+1. Browser → GET /?userId=xxx (WebSocket upgrade)
+2. Worker routes to user channel DO
+3. DO accepts WebSocket upgrade
+4. If X-Authenticated-User header present → auto-authenticated
+5. Otherwise → client sends { type: "auth", token: "..." }
+6. DO validates token against D1 (Better Auth session)
+7. Authenticated connections receive notifications
+8. Unauthenticated connections are closed on any non-auth message
+```
+
+---
+
+## Worker Entry Point (`src/index.ts`)
+
+### Routes
+
+| Method | Path Pattern | Action |
+|--------|-------------|--------|
+| POST | `/broadcast/user/:userId` | Send notification to user channel DO |
+| GET | `/?userId=xxx` | WebSocket connect to user channel |
+
+### Routing Logic
+
+```typescript
+// 1. Broadcast: POST /broadcast/user/:userId
+// → DO name: "user:{userId}"
+// → forward to DO: POST http://internal/broadcast
+
+// 2. WebSocket: GET /?userId=xxx
+// → DO name: "user:{userId}"
+// → forward original request (WebSocket upgrade)
+```
+
+---
+
+## Durable Object (`src/ws-durable.ts`)
+
+### Class: `WebSocketDurableObject extends DurableObject<Env>`
+
+#### Connection State
+
+Each WebSocket has serialized attachment state:
+
+```typescript
+interface ConnectionState {
+ userId: string
+ authenticated: boolean
+}
+```
+
+#### Methods
+
+**`fetch(request)`** — Handles both broadcast (POST) and WebSocket upgrade (GET).
+
+- POST `/broadcast`: reads body as text, calls `this.broadcast(body)`, returns "ok"
+- WebSocket upgrade: creates `WebSocketPair`, accepts server socket via `ctx.acceptWebSocket(server)`
+ - If `X-Authenticated-User` header present → pre-authenticated
+ - Otherwise → unauthenticated, client must send auth message
+ - Sets up auto ping/pong response: `WebSocketRequestResponsePair("ping", "pong")`
+ - Returns 101 with client socket
+
+**`webSocketMessage(ws, message)`** — Handles incoming messages from clients.
+
+- Parses JSON message
+- If `{ type: "auth", token: "..." }`:
+ - Validates token via `this.validateToken(token)`
+ - On success: updates attachment state to authenticated, sends `{ type: "auth.ok" }`
+ - On failure: closes with 1008 "Unauthorized"
+- Any other message from unauthenticated client: closes with 1008 "Not authenticated"
+- Authenticated clients have no other valid message types (notification-only = server-to-client)
+
+**`webSocketClose()`** — No-op (DO auto-cleans up).
+
+**`webSocketError(ws, error)`** — Logs error, closes with 1011.
+
+**`broadcast(message)`** — Private. Iterates all WebSockets via `ctx.getWebSockets()`, sends to authenticated + OPEN connections.
+
+**`validateToken(token)`** — Private. Validates session token via Drizzle queries from `@alook/shared`:
+
+```typescript
+import { createDb, queries } from "@alook/shared"
+
+const db = createDb(this.env.DB)
+
+// Browser session token (Better Auth)
+// → queries.session.getValidSession(db, token)
+// Returns userId string or null
+```
+
+> **Note:** Only browser session tokens are validated. CLI does not use WebSocket — it uses HTTP polling.
+
+---
+
+## How the Web Service Sends Notifications
+
+The Web Service calls WS-DO via service binding when state changes:
+
+```typescript
+// Helper function in Web Service
+async function notify(userId: string, type: string, id: string) {
+ await env.WS_DO_SERVICE.fetch(
+ `http://internal/broadcast/user/${userId}`,
+ {
+ method: "POST",
+ body: JSON.stringify({ type, id }),
+ }
+ )
+}
+
+// Usage examples:
+await notify(userId, "task.updated", taskId)
+await notify(userId, "runtime.updated", runtimeId)
+await notify(userId, "email.received", emailId)
+await notify(userId, "agent.updated", agentId)
+```
+
+Web Service wrangler.toml:
+```toml
+[[services]]
+binding = "WS_DO_SERVICE"
+service = "alook-ws-do"
+```
+
+### Where to call `notify()`
+
+| Web Service Location | Event Type |
+|---------------------|------------|
+| `TaskService.completeTask()` | `task.updated` |
+| `TaskService.failTask()` | `task.updated` |
+| `TaskService.startTask()` | `task.updated` |
+| Daemon heartbeat endpoint | `runtime.updated` |
+| Daemon register endpoint | `runtime.updated` |
+| Daemon deregister endpoint | `runtime.updated` |
+| Runtime delete endpoint | `runtime.updated` |
+| Email Worker notify endpoint | `email.received` |
+| Agent update endpoint | `agent.updated` |
+| Agent delete endpoint | `agent.updated` |
+
+---
+
+## Authentication Flow
+
+### Browser (Session Auth)
+
+```
+1. Browser gets WS auth token: GET /api/ws/token → { token }
+2. Browser opens WebSocket: ws://ws-do/?userId=xxx
+3. Client sends: { type: "auth", token: "session_token_here" }
+4. DO validates via queries.session.getValidSession(db, token)
+5. On success: { type: "auth.ok" } → connection authenticated
+6. Browser starts receiving notifications
+```
+
+---
+
+## Test Coverage
+
+No test files exist for WS-DO on spec-plans. Testing approach should cover:
+
+- WebSocket upgrade acceptance
+- Auth message validation (session tokens)
+- Rejection of unauthenticated connections
+- Broadcast delivery to authenticated connections only
+- Notification message format (`{ type, id }`)
+- Connection cleanup on close/error
+
+---
+
+## Migration Notes
+
+### What main's polling model does that WS-DO replaces
+
+| Main (HTTP Polling) | WS-DO (Notification Push) |
+|---------------------|--------------------------|
+| Frontend polls `GET /api/tasks/{id}/messages?since=N` every 1s | WS-DO sends `{ type: "task.updated", id }` → browser re-fetches |
+| No runtime status push — page reload to see changes | WS-DO sends `{ type: "runtime.updated", id }` → browser re-fetches |
+| No email notification in browser | WS-DO sends `{ type: "email.received", id }` → browser re-fetches |
+
+### Changes from spec-plans WS-DO
+
+| Spec-plans | Target |
+|------------|--------|
+| Full data payloads in broadcast messages (runtime status objects, task data, email details) | Notification-only: `{ type, id }` — browser fetches data via REST API |
+| Agent channels + user channels | User channels only (notifications scoped per user) |
+| CLI + browser both use WebSocket | Browser only — CLI uses HTTP polling |
+| Raw D1 queries for token validation | Drizzle queries from `@alook/shared` |
+| Validates both session tokens and runtime tokens (`alook_tk_*`) | Session tokens only (browser auth via Better Auth) |
+
+### Required changes to Web Service
+
+1. Add WS-DO service binding in Web Service wrangler.toml
+2. Add `notify(userId, type, id)` helper function
+3. Call `notify()` at state change points (see table above)
+4. Add `GET /api/ws/token` endpoint for browser WebSocket auth
+
+### Schema and queries are in `@alook/shared`
+
+All Drizzle schema definitions, the DB factory (`createDb(d1Binding)`), and query modules live in `@alook/shared`. WS-DO imports them for token validation only. See [05-shared-library.md](05-shared-library.md).
diff --git a/docs/migration/04-cli-daemon.md b/docs/migration/04-cli-daemon.md
new file mode 100644
index 000000000..dea0ee267
--- /dev/null
+++ b/docs/migration/04-cli-daemon.md
@@ -0,0 +1,367 @@
+# 04 — CLI Daemon
+
+> `@alook/cli` — Commander.js CLI + daemon that spawns agent subprocesses.
+> Location: `src/cli/`
+> Runtime: Node.js (Bun for dev and build). Follows main branch.
+
+---
+
+## Auth
+
+The CLI daemon continues using **machine tokens** (`Bearer al_*`) for all API communication. The Better Auth migration (JWT → session-based auth) affects the Web Service's browser authentication only — it does not change the CLI's auth flow. Machine tokens are validated independently of Better Auth sessions via the dual-auth middleware in the Web Service (see [01-web-service.md](01-web-service.md)).
+
+---
+
+## Dependencies
+
+```json
+{
+ "@alook/shared": "workspace:*",
+ "commander": "^13.0.0",
+ "dotenv": "^16.0.0"
+}
+```
+
+Dev: `eslint`, `typescript`, `typescript-eslint`
+
+Build: `bun build src/index.ts --outdir dist --target node`
+Binary: `dist/index.js` (ESM, exposed as `alook` in package.json `bin`)
+
+---
+
+## Commands
+
+Entry point: `src/cli/src/index.ts` — sets up Commander.js program "alook" with 6 subcommands.
+
+Global options: `--server <url>`, `--profile <name>`
+
+| Command | File | Purpose |
+|---------|------|---------|
+| `alook register --token <al_...>` | `commands/register.ts` | Validate token (must start `al_`), fetch user via `/api/me`, fetch workspaces via `/api/workspaces`, save config |
+| `alook status` | `commands/status.ts` | Display registration status and workspace info from config |
+| `alook agent list [--workspace] [--json]` | `commands/agent.ts` | List agents (table or JSON output) |
+| `alook agent create --name --runtime [--workspace]` | `commands/agent.ts` | Create agent via API |
+| `alook daemon start [--foreground] [--server]` | `commands/daemon.ts` | Start background daemon |
+| `alook daemon status` | `commands/daemon.ts` | Show daemon health URL |
+| `alook config show` | `commands/config.ts` | Display current config as JSON |
+| `alook config path` | `commands/config.ts` | Show config file path |
+| `alook version` | `commands/version.ts` | Read version from package.json |
+
+---
+
+## CLI Library (`src/cli/lib/`)
+
+### APIClient (`lib/client.ts`)
+
+HTTP client for CLI commands (not daemon).
+
+| Method | Purpose |
+|--------|---------|
+| `getJSON<T>(path)` | GET request with auth headers |
+| `postJSON<T>(path, body)` | POST request |
+| `deleteJSON<T>(path)` | DELETE request |
+| `healthCheck()` | Boolean health check |
+
+Headers set automatically: `Authorization: Bearer <token>`, `X-Workspace-ID: <workspaceId>` (if set).
+
+### Config (`lib/config.ts`)
+
+Config persistence at `~/.alook/config.json` (0o600 permissions).
+
+```typescript
+interface CLIConfig {
+ token?: string
+ server_url?: string
+ watched_workspaces?: { id: string; name: string }[]
+ default_profile?: string
+ profiles?: Record<string, ProfileConfig>
+}
+
+interface ProfileConfig {
+ token?: string
+ server_url?: string
+ watched_workspaces?: { id: string; name: string }[]
+}
+```
+
+Functions: `configPath()`, `loadCLIConfig()`, `loadCLIConfigForProfile(profile?)`, `saveCLIConfig(cfg)`, `saveCLIConfigForProfile(profile?, cfg)`
+
+### Logger (`lib/logger.ts`)
+
+Structured colored logging with timestamps (HH:MM:SS format).
+
+- Levels: debug, info, warn, error, silent
+- Env: `ALOOK_LOG_LEVEL` (default: info)
+- Respects `NO_COLOR` and `FORCE_COLOR`
+- Errors to stderr, rest to stdout
+
+### Output (`lib/output.ts`)
+
+- `printTable(headers, rows)` — aligned table with separators
+- `printJSON(data)` — JSON with 2-space indent
+
+### Flags (`lib/flags.ts`)
+
+- `flagOrEnv(cmd, flagName, envKey, fallback)` — resolves flag > env var > fallback
+
+---
+
+## Daemon (`src/cli/daemon/`)
+
+### Main Loop (`daemon/daemon.ts`)
+
+`startDaemon(profile?, serverUrl?)` — the core daemon process:
+
+```
+1. Load daemon config + CLI config
+2. Register with server: POST /api/daemon/register
+ - Detects installed agent CLIs (claude, codex, opencode) via `which`
+ - Sends workspace_id, daemon_id, device_name, cli_version, runtimes[]
+3. Start health server on port 19514
+4. Enter polling loop:
+ a. For each registered runtime → claimTask, handleTask
+ b. Sleep for pollInterval (default 3s)
+5. Heartbeat loop (separate interval, default 15s)
+6. On SIGTERM/SIGINT → graceful shutdown (deregister runtimes)
+```
+
+**`handleTask(task)`:**
+1. Claim task from server
+2. Start task (dispatched -> running)
+3. Run task (spawn agent backend)
+4. Complete or fail task
+5. Reconcile agent status
+
+**`runTask(task)`:**
+1. Create agent backend based on provider
+2. Build prompt from task
+3. Create working directory
+4. Execute agent session
+5. Batch and flush messages to server (batch size 20, flush interval 2s)
+6. Return result (status, comment, sessionId, workDir)
+
+### Daemon Client (`daemon/client.ts`)
+
+`DaemonClient` class — HTTP client for all `/api/daemon/*` endpoints:
+
+| Method | Endpoint | Purpose |
+|--------|----------|---------|
+| `register()` | POST `/api/daemon/register` | Register daemon + runtimes |
+| `deregister(runtimeIds)` | POST `/api/daemon/deregister` | Set runtimes offline |
+| `heartbeat(runtimeId)` | POST `/api/daemon/heartbeat` | Send heartbeat |
+| `claimTask(runtimeId)` | POST `/api/daemon/runtimes/{id}/tasks/claim` | Claim next task |
+| `startTask(taskId)` | POST `/api/daemon/tasks/{id}/start` | Mark started |
+| `completeTask(taskId, body)` | POST `/api/daemon/tasks/{id}/complete` | Mark complete |
+| `failTask(taskId, error)` | POST `/api/daemon/tasks/{id}/fail` | Mark failed |
+| `reportMessages(taskId, messages)` | POST `/api/daemon/tasks/{id}/messages` | Upload task messages |
+
+### Daemon Config (`daemon/config.ts`)
+
+`DaemonConfig` loaded from environment variables:
+
+| Env Var | Default | Purpose |
+|---------|---------|---------|
+| `ALOOK_SERVER_URL` | `http://localhost:8080` | API server URL |
+| `ALOOK_DAEMON_POLL_INTERVAL` | `3s` | Task polling interval |
+| `ALOOK_DAEMON_HEARTBEAT_INTERVAL` | `15s` | Heartbeat interval |
+| `ALOOK_AGENT_TIMEOUT` | `2h` | Agent execution timeout |
+| `ALOOK_DAEMON_MAX_CONCURRENT_TASKS` | `20` | Max parallel tasks |
+| `ALOOK_LOG_LEVEL` | `info` | Log level |
+
+Additional config: `claudePath`, `codexPath`, `opencodePath` (CLI paths), model overrides per provider, `daemonId`, `deviceName`, `runtimeName`, `workspacesRoot`, `keepEnvAfterTask`, `cliVersion`.
+
+Helper: `parseDuration(s)` — parses Go-style duration strings (ns, us, ms, s, m, h).
+Helper: `normalizeServerBaseURL()` — converts WS/WSS URLs to HTTP/HTTPS.
+
+### Health Server (`daemon/health.ts`)
+
+HTTP server on `127.0.0.1:19514`.
+
+- `GET /health` → `{ status: "ok", uptime: "Xs", runtimes: N }`
+- `setRuntimeCount(n)` method to update runtime count
+
+### Prompt Builder (`daemon/prompt.ts`)
+
+`buildPrompt(task)` — currently passthrough (returns `task.prompt` as-is).
+
+### Types (`daemon/types.ts`)
+
+| Type | Key Fields |
+|------|------------|
+| `Task` | agent, runtime, workspace, repos, prompt |
+| `TaskAgentData` | name, instructions |
+| `RepoData` | repository information |
+| `TaskResult` | status, comment, sessionId, workDir, branchName |
+| `RuntimeInfo` | runtime metadata |
+| `AgentMessage` | seq, type (text/thinking/tool-use/tool-result/status/error/log), tool?, content?, input?, output? |
+| `AgentResult` | status, output, error, durationMs, sessionId |
+| `ExecOptions` | cwd, model, systemPrompt, maxTurns, timeout, resumeSessionId |
+
+Conversion: `fromApiTask(api: TaskApi)` — converts wire format (snake_case) to internal format.
+
+---
+
+## Agent Backends (`daemon/agent/`)
+
+### Interface (`agent/index.ts`)
+
+```typescript
+interface AgentSession {
+ messages: AsyncIterable<AgentMessage>
+ result: Promise<AgentResult>
+}
+
+interface AgentBackend {
+ name: string
+ execute(prompt: string, options: ExecOptions): AgentSession
+}
+```
+
+Factory: `createBackend(provider, cliPath)` — returns backend for claude/codex/opencode.
+Detection: `detectVersion(cliPath)` — runs `<cliPath> --version`.
+
+### Claude Backend (`agent/claude.ts`)
+
+Spawns Claude CLI as subprocess with stream-json output.
+
+**Command:**
+```bash
+claude -p <prompt> \
+ --output-format stream-json \
+ --verbose \
+ --permission-mode bypassPermissions \
+ [--model <model>] \
+ [--max-turns <n>] \
+ [--append-system-prompt <instructions>] \
+ [--resume <sessionId>]
+```
+
+**JSON Stream Events:**
+
+| Event Type | Parsed As |
+|------------|-----------|
+| `assistant` | Text blocks, thinking blocks, tool_use blocks |
+| `result` | Final result + session_id |
+| `tool_result` | Tool invocation result |
+| `system` | Init events with session_id |
+| `control_request` | Permission requests (auto-approved via stdin) |
+
+Auto-approves control requests by writing `control_response` JSON to stdin.
+Timeout support: kills process on timeout.
+
+### Codex Backend (`agent/codex.ts`)
+
+Spawns Codex CLI with JSON-RPC 2.0 protocol over stdio.
+
+**Command:**
+```bash
+codex app-server --listen stdio://
+```
+
+**JSON-RPC Handshake:**
+1. Send `initialize` RPC
+2. Send `initialized` notification
+3. Send `thread/start` or `thread/resume` RPC
+4. Send `turn/start` RPC with prompt
+
+**Notifications Handled:**
+
+| Notification | Parsed As |
+|-------------|-----------|
+| `turn/started`, `turn/completed` | Turn lifecycle |
+| `thread/status/changed` | Thread status |
+| `item/started`, `item/completed` | Item execution (commandExecution, fileChange, agentMessage) |
+
+Auto-approves approval requests from server.
+Protocol detection: auto-detects legacy vs raw protocol.
+Deduplication: prevents duplicate turn_completed events.
+
+### OpenCode Backend (`agent/opencode.ts`)
+
+Spawns OpenCode CLI with JSON stream output.
+
+**Command:**
+```bash
+opencode run --format json <prompt> \
+ [--model <model>] \
+ [--prompt <systemPrompt>] \
+ [--session <resumeSessionId>]
+```
+
+Sets `OPENCODE_PERMISSION` env var to allow all operations.
+
+**JSON Stream Events:**
+
+| Event Type | Parsed As |
+|------------|-----------|
+| `session` | Session ID |
+| `message` | Assistant messages |
+| `thinking` | Thinking blocks |
+| `tool_call` | Tool invocation |
+| `tool_result` | Tool result |
+| `error` | Error events |
+| `done` / `complete` | Completion with status |
+
+---
+
+## Test Files
+
+```
+daemon/agent/__tests__/claude.test.ts
+daemon/agent/__tests__/codex.test.ts
+daemon/agent/__tests__/index.test.ts
+daemon/agent/__tests__/opencode.test.ts
+daemon/client.test.ts
+daemon/config.test.ts
+daemon/daemon.test.ts
+daemon/health.test.ts
+daemon/prompt.test.ts
+lib/config.test.ts
+lib/flags.test.ts
+lib/logger.test.ts
+lib/output.test.ts
+```
+
+---
+
+## Development
+
+### Running from monorepo root
+
+In development, the CLI can be executed via Bun from the project root directory without building first:
+
+```bash
+# From project root
+pnpm cli register --token al_...
+pnpm cli status
+pnpm cli daemon start --foreground
+pnpm cli agent list
+```
+
+Root `package.json` scripts:
+```json
+{
+ "scripts": {
+ "cli": "bun src/cli/src/index.ts"
+ }
+}
+```
+
+### Dev config directory
+
+In development, the `.alook/` config directory is located at the **project root** instead of `~/.alook/`:
+
+```
+alook/ # project root
+├── .alook/
+│ └── config.json # dev config (server URL, token, workspaces)
+├── src/
+│ ├── cli/
+│ ...
+```
+
+This keeps dev config isolated from any production config at `~/.alook/` and makes it easy to share dev settings across the team via `.gitignore` rules.
+
+### Production config
+
+In production (built binary), config is at `~/.alook/config.json` as documented in the Config section above.
diff --git a/docs/migration/05-shared-library.md b/docs/migration/05-shared-library.md
new file mode 100644
index 000000000..12614c67d
--- /dev/null
+++ b/docs/migration/05-shared-library.md
@@ -0,0 +1,277 @@
+# 05 — Shared Library
+
+> `@alook/shared` — Drizzle schema, DB factory, query modules, types, constants, and Zod validation schemas.
+> Location: `src/shared/`
+> No runtime — consumed as workspace dependency by web, cli, email-worker, and ws-do.
+
+---
+
+## Package Config
+
+```json
+{
+ "name": "@alook/shared",
+ "version": "0.1.0",
+ "type": "module",
+ "exports": { ".": "./index.ts" },
+ "dependencies": {
+ "drizzle-orm": "^0.39.0",
+ "zod": "^3.24"
+ }
+}
+```
+
+No build step — exports raw TypeScript via `"exports": { ".": "./index.ts" }`.
+
+---
+
+## Module Structure
+
+```
+src/shared/
+├── index.ts # Re-exports everything
+├── types.ts # Core domain types (interfaces)
+├── api-types.ts # API request/response wrapper types
+├── constants.ts # Status enums
+├── schemas.ts # Zod validation schemas
+├── db/
+│ ├── index.ts # createDb(d1Binding) factory, Database type export
+│ ├── schema.ts # Drizzle table definitions (all tables, single source of truth)
+│ └── queries/ # Query modules (one per domain)
+│ ├── user.ts
+│ ├── workspace.ts
+│ ├── member.ts
+│ ├── agent.ts
+│ ├── runtime.ts
+│ ├── conversation.ts
+│ ├── message.ts
+│ ├── task.ts
+│ ├── task-message.ts
+│ ├── machine-token.ts
+│ ├── whitelist.ts
+│ ├── email.ts
+│ └── session.ts
+├── utils/
+│ ├── email.ts # parseEmailHandle()
+│ └── validation.ts # isValidToken()
+├── schemas.test.ts
+├── package.json
+└── tsconfig.json
+```
+
+---
+
+## Database (NEW — moved from Web Service)
+
+### DB Factory (`db/index.ts`)
+
+```typescript
+import { drizzle } from "drizzle-orm/d1"
+import * as schema from "./schema"
+
+export function createDb(d1: D1Database) {
+ return drizzle(d1, { schema })
+}
+
+export type Database = ReturnType<typeof createDb>
+```
+
+All three D1 consumers create a Drizzle instance from their D1 binding:
+
+```typescript
+import { createDb } from "@alook/shared"
+const db = createDb(env.DB)
+```
+
+### Schema (`db/schema.ts`)
+
+Single source of truth for all Drizzle table definitions. Tables are owned and migrated by the Web Service, but defined here so all services share the same typed schema.
+
+See [01-web-service.md](01-web-service.md) for the full schema details (Better Auth tables + application tables).
+
+### Query Modules (`db/queries/`)
+
+Moved from `src/web/lib/db/queries/` into `@alook/shared` so all services share one implementation.
+
+| Module | Functions | Used by |
+|--------|-----------|---------|
+| `user` | getUser, getUserByEmail, createUser, updateUser | Web, Email Worker (read only) |
+| `workspace` | getWorkspace, listWorkspaces, createWorkspace | Web |
+| `member` | getMemberByUserAndWorkspace, listMembers, createMember | Web |
+| `agent` | getAgent, getAgentByHandle, getAgentInWorkspace, listAgents, createAgent, deleteAgent, updateAgent, updateAgentStatus | Web, Email Worker (read only) |
+| `runtime` | upsertAgentRuntime, listAgentRuntimes, getAgentRuntime, updateAgentRuntimeHeartbeat, setAgentRuntimeOffline, deleteRuntimesByDaemonId, markStaleRuntimesOffline | Web |
+| `conversation` | createConversation, getConversation, listConversations, listConversationsByAgent, updateConversationTitle, deleteConversation | Web |
+| `message` | createMessage, listMessages, getMessage | Web |
+| `task` | createTask, getTask, claimTask, startTask, completeTask, failTask, getLastTaskSession, listPendingTasksByRuntime, failStaleDispatchedTasks, countRunningTasks, ... | Web |
+| `task-message` | createTaskMessage, listTaskMessages, listTaskMessagesSince, deleteTaskMessages | Web |
+| `machine-token` | createMachineToken, getMachineTokenByHash, listMachineTokens, deleteMachineToken, updateMachineTokenLastUsed | Web, WS-DO |
+| `whitelist` | getWhitelist, addWhitelist, removeWhitelist, isWhitelisted | Web, Email Worker (read only) |
+| `email` | createEmail, getEmailById, getEmailsByAgent, getEmailsByUser | Web |
+| `session` | getValidSession | WS-DO |
+
+---
+
+## Types (`types.ts`)
+
+Core domain interfaces used across web, CLI, and workers.
+
+| Type | Key Fields |
+|------|------------|
+| `User` | id, name, email, avatar_url, created_at, updated_at |
+| `Workspace` | id, name, slug, created_at, updated_at |
+| `Agent` | id, workspace_id, runtime_id, name, description, instructions, runtime_mode, runtime_config, status, max_concurrent_tasks, created_at, updated_at |
+| `AgentRuntime` | id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at |
+| `Conversation` | id, agent_id, title, created_at |
+| `Message` | id, conversation_id, role ("user"\|"assistant"), content, task_id, created_at |
+| `AgentTask` | *deprecated — use TaskApiSchema* id, agent_id, runtime_id, conversation_id, workspace_id, prompt, status, priority, dispatched_at, started_at, completed_at, result, error, agent?, created_at, prior_session_id?, prior_work_dir? |
+| `TaskAgentData` | id, name, instructions |
+| `TaskMessage` | id, task_id, seq, type, tool, content, input?, output |
+| `MachineToken` | id, name, last_used_at, created_at |
+| `LoginResponse` | token, user (User) |
+| `CreateAgentRequest` | name, description?, instructions?, runtime_id, runtime_config?, max_concurrent_tasks? |
+
+---
+
+## API Types (`api-types.ts`)
+
+Generic wrapper types for API responses + typed request/response interfaces.
+
+### Generic Wrappers
+
+| Type | Shape |
+|------|-------|
+| `ApiResponse<T>` | `{ data: T }` |
+| `ApiListResponse<T>` | `{ data: T[], total?: number }` |
+| `ApiErrorResponse` | `{ error: string, code?: string }` |
+
+### Typed Responses
+
+| Type | Wraps |
+|------|-------|
+| `GetUserResponse` | `ApiResponse<User>` |
+| `ListWorkspacesResponse` | `ApiListResponse<Workspace>` |
+| `GetWorkspaceResponse` | `ApiResponse<Workspace>` |
+| `ListAgentsResponse` | `ApiListResponse<Agent>` |
+| `GetAgentResponse` | `ApiResponse<Agent>` |
+| `ListRuntimesResponse` | `ApiListResponse<AgentRuntime>` |
+| `GetRuntimeResponse` | `ApiResponse<AgentRuntime>` |
+| `ListConversationsResponse` | `ApiListResponse<Conversation>` |
+| `GetConversationResponse` | `ApiResponse<Conversation>` |
+| `ListMessagesResponse` | `ApiListResponse<Message>` |
+| `ListTasksResponse` | `ApiListResponse<AgentTask>` |
+| `GetTaskResponse` | `ApiResponse<AgentTask>` |
+| `ListTaskMessagesResponse` | `ApiListResponse<TaskMessage>` |
+| `ListMachineTokensResponse` | `ApiListResponse<MachineToken>` |
+
+### Request Types
+
+| Type | Fields |
+|------|--------|
+| `CreateWorkspaceRequest` | `{ name: string }` |
+| `UpdateAgentRequest` | `{ name?, description?, instructions?, runtime_config?, max_concurrent_tasks? }` |
+| `SendMessageRequest` | `{ content: string }` |
+| `CreateMachineTokenRequest` | `{ name: string }` |
+| `CreateMachineTokenResponse` | `{ token: string, id: string, name: string }` |
+
+---
+
+## Constants (`constants.ts`)
+
+Status enum objects with TypeScript type exports.
+
+| Constant | Values | Type |
+|----------|--------|------|
+| `AgentStatus` | ACTIVE, INACTIVE, ERROR | `AgentStatusType` |
+| `RuntimeStatus` | ONLINE, OFFLINE, ERROR | `RuntimeStatusType` |
+| `TaskStatus` | QUEUED, DISPATCHED, RUNNING, COMPLETED, FAILED, CANCELLED | `TaskStatusType` |
+| `MessageRole` | USER, ASSISTANT | `MessageRoleType` |
+
+Pattern: `const X = { ... } as const` + `type XType = (typeof X)[keyof typeof X]`
+
+---
+
+## Schemas (`schemas.ts`)
+
+Zod validation schemas for runtime validation. Used by both Web Service (API route validation) and CLI daemon (response parsing).
+
+### Task Schemas
+
+| Schema | Purpose |
+|--------|---------|
+| `TaskStatusSchema` | `z.enum(["queued","dispatched","running","completed","failed","cancelled"])` |
+| `ClaimedTaskRowSchema` | Raw SQL row from `agent_task_queue` — boundary between DB and app. All fields typed with coerce for dates. |
+| `TaskAgentDataApiSchema` | Agent data in task claim response: `{ instructions, name, runtime_config }` |
+| `TaskApiBaseSchema` | Base task fields in snake_case API format |
+| `TaskApiSchema` | Full task = base + optional `agent`, `prior_session_id`, `prior_work_dir` |
+| `ClaimTaskResponseSchema` | `{ task: TaskApi | null }` |
+
+### Daemon API Schemas
+
+| Schema | Purpose | Key Fields |
+|--------|---------|------------|
+| `RegisterResponseSchema` | Register response | `{ runtimes: [{ id }] }` |
+| `DaemonRuntimeItemSchema` | Single runtime in register request | type?, provider?, runtime_mode?, name?, version?, status?, model? |
+| `RegisterDaemonRequestSchema` | Register request body | workspace_id, daemon_id, device_name?, cli_version?, runtimes[] (min 1) |
+| `DeregisterRequestSchema` | Deregister request | `{ runtime_ids: string[] }` |
+| `HeartbeatRequestSchema` | Heartbeat request | `{ runtime_id: string }` (min 1 char) |
+| `CompleteTaskRequestSchema` | Complete task body | output?, session_id?, work_dir?, branch_name? |
+| `FailTaskRequestSchema` | Fail task body | error? (default: "") |
+| `MessageItemSchema` | Single task message | seq (number), type (string), tool?, content?, input? (record), output? |
+| `ReportMessagesRequestSchema` | Report messages batch | `{ messages: MessageItem[] }` |
+
+---
+
+## Exports (`index.ts`)
+
+All modules re-exported from the index:
+
+- **DB**: `createDb`, `Database` type, `schema` (all table definitions), `queries` (all query modules)
+- **Types**: User, Workspace, Agent, AgentRuntime, Conversation, Message, AgentTask, TaskAgentData, TaskMessage, MachineToken, LoginResponse, CreateAgentRequest
+- **API Types**: ApiResponse, ApiListResponse, ApiErrorResponse, all typed response/request types
+- **Constants**: AgentStatus, RuntimeStatus, TaskStatus, MessageRole (+ their type aliases)
+- **Schemas**: All Zod schemas and their inferred types
+- **Utils**: `parseEmailHandle`, `isValidToken`
+
+---
+
+## Test Files
+
+```
+src/shared/schemas.test.ts
+```
+
+---
+
+## Usage Across Packages
+
+| Consumer | What It Uses |
+|----------|-------------|
+| **Web Service** | `createDb` + `queries.*` for all DB operations, `schema` for migrations (drizzle-kit), types for API responses, schemas for request validation, constants for status comparisons |
+| **Email Worker** | `createDb` + `queries.agent.getAgentByHandle` (read), `queries.user.getUser` (read), `queries.whitelist.isWhitelisted` (read), `parseEmailHandle` utility. Email Worker does not write to D1 — it notifies Web Service via `POST /api/email/notify` which handles email record + task creation. |
+| **WS-DO** | `createDb` + `queries.machineToken.getMachineTokenByHash`, `queries.session.getValidSession` for token validation |
+| **CLI Daemon** | `TaskApiSchema` + `ClaimTaskResponseSchema` for parsing claim responses, `RegisterDaemonRequestSchema` for building register payload, `ReportMessagesRequestSchema` for message batch, types for internal data models |
+
+---
+
+## Migration Notes
+
+### What moves into `@alook/shared`
+
+| From | To | Content |
+|------|----|---------|
+| `src/web/lib/db/schema.ts` | `src/shared/db/schema.ts` | All Drizzle table definitions |
+| `src/web/lib/db/index.ts` | `src/shared/db/index.ts` | DB factory (adapted from postgres to D1) |
+| `src/web/lib/db/queries/*.ts` | `src/shared/db/queries/*.ts` | All query modules |
+
+### What stays in Web Service
+
+- Migration runner (`drizzle-kit` config and `drizzle/` migrations folder) — only Web Service runs migrations
+- Response formatters (`lib/api/responses.ts`) — Web-specific snake_case formatting
+- Service classes (`TaskService`, `EmailService`) — orchestration logic that uses queries
+- Middleware — Web-specific request handling
+
+### D1 compatibility
+
+- `ClaimedTaskRowSchema` uses `.coerce.date()` — works with D1's text dates
+- Drizzle's `sqliteTable` replaces `pgTable` in schema definitions
+- `SELECT FOR UPDATE SKIP LOCKED` (task claiming) not available in SQLite — replaced with CAS-style `UPDATE ... WHERE status='queued'` using `db.batch()` for atomicity. See [01-web-service.md](01-web-service.md) Task Claiming Strategy section.
diff --git a/docs/migration/06-migration-order.md b/docs/migration/06-migration-order.md
new file mode 100644
index 000000000..e555f64e8
--- /dev/null
+++ b/docs/migration/06-migration-order.md
@@ -0,0 +1,173 @@
+# 06 — Migration Order
+
+> Step-by-step execution sequence for the Cloudflare edge migration.
+> Dependencies between steps are explicit — work within a phase can be parallelized.
+
+---
+
+## Dependency Graph
+
+```mermaid
+graph TD
+ P0["Phase 0: Infra Setup"]
+ P1["Phase 1: Shared Library<br/>(schema + queries → @alook/shared)"]
+ P2W["Phase 2a: Web Service<br/>(D1 + Better Auth + OpenNext)"]
+ P2E["Phase 2b: Email Worker<br/>(new service)"]
+ P2D["Phase 2c: WS-DO<br/>(new service)"]
+ P3["Phase 3: Frontend<br/>(WebSocket + email UI)"]
+ P4["Phase 4: Integration + CLI"]
+
+ P0 --> P1
+ P1 --> P2W
+ P1 --> P2E
+ P1 --> P2D
+ P2W --> P3
+ P2D --> P3
+ P2W --> P4
+ P2E --> P4
+ P2D --> P4
+```
+
+---
+
+## Phase 0 — Infrastructure Setup
+
+**Goal:** Set up the Cloudflare project, monorepo tooling, and development environment.
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 0.1 | Create Cloudflare D1 database (`alook-app`) | — |
+| 0.2 | Create Cloudflare R2 bucket (`alook-emails`) | — |
+| 0.3 | Replace Makefile with Turborepo (`turbo.json`) | [00-overview.md](00-overview.md) |
+| 0.4 | Set up `pnpm-workspace.yaml` for all 5 packages | [00-overview.md](00-overview.md) |
+| 0.5 | Create `wrangler.toml` for each Cloudflare service (web, email-worker, ws-do) | [01](01-web-service.md), [02](02-email-worker.md), [03](03-ws-do.md) |
+| 0.6 | Set up local dev with `wrangler dev` replacing `docker-compose` | — |
+
+**Exit criteria:** `pnpm install` succeeds, `wrangler dev` starts with D1/R2 bindings available locally.
+
+---
+
+## Phase 1 — Shared Library (`@alook/shared`)
+
+**Goal:** Move schema, DB factory, and query modules from `src/web/lib/db/` into `src/shared/db/`. This is the foundation — all other phases depend on it.
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 1.1 | Add `drizzle-orm` dependency to `@alook/shared` package.json | [05-shared-library.md](05-shared-library.md) |
+| 1.2 | Create `src/shared/db/schema.ts` — convert all `pgTable` to `sqliteTable` (D1-compatible types) | [05-shared-library.md](05-shared-library.md) |
+| 1.3 | Create `src/shared/db/index.ts` — `createDb(d1Binding)` factory using `drizzle-orm/d1` | [05-shared-library.md](05-shared-library.md) |
+| 1.4 | Move query modules from `src/web/lib/db/queries/*.ts` to `src/shared/db/queries/*.ts` | [05-shared-library.md](05-shared-library.md) |
+| 1.5 | Adapt queries for D1/SQLite (nanoid PKs, text dates, integer booleans, CAS task claiming) | [01-web-service.md](01-web-service.md) |
+| 1.6 | Add `utils/email.ts` (`parseEmailHandle`) and `utils/validation.ts` (`isValidToken`) | [05-shared-library.md](05-shared-library.md) |
+| 1.7 | Update `src/shared/index.ts` to re-export db, queries, schema, utils | [05-shared-library.md](05-shared-library.md) |
+| 1.8 | Update Web Service to import from `@alook/shared` instead of local `lib/db/` | [01-web-service.md](01-web-service.md) |
+
+**Exit criteria:** `@alook/shared` exports `createDb`, `schema`, `queries`, all types/schemas. Web Service compiles against shared imports.
+
+---
+
+## Phase 2a — Web Service (D1 + Better Auth + OpenNext)
+
+**Goal:** Migrate the Web Service from Node.js/PostgreSQL to Cloudflare Workers/D1. Can start once Phase 1 is complete.
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 2a.1 | Remove `postgres`, `jose`, `input-otp` dependencies. Add `better-auth`, `@opennextjs/cloudflare`. | [01-web-service.md](01-web-service.md) |
+| 2a.2 | Configure `drizzle-kit` to point to `@alook/shared` schema. Generate D1 migration. | [01-web-service.md](01-web-service.md) |
+| 2a.3 | Implement Better Auth setup (`lib/auth.ts`, `lib/auth-client.ts`) | [01-web-service.md](01-web-service.md) |
+| 2a.4 | Implement dual-auth middleware (`lib/dual-auth.ts`) — machine tokens + Better Auth sessions | [01-web-service.md](01-web-service.md) |
+| 2a.5 | Replace `/api/auth/send-code` and `/api/auth/verify-code` with Better Auth catch-all `[...all]` route | [01-web-service.md](01-web-service.md) |
+| 2a.6 | Replace `/sign-in` and `/sign-up` pages with Better Auth forms (email/password + OAuth) | [01-web-service.md](01-web-service.md) |
+| 2a.7 | Add `POST /api/email/notify` endpoint (receives from Email Worker, creates email record + task) | [02-email-worker.md](02-email-worker.md) |
+| 2a.8 | Add WS-DO service binding + `notify()` helper for broadcasting events | [03-ws-do.md](03-ws-do.md) |
+| 2a.9 | Add `GET /api/ws/token` endpoint for browser WebSocket auth | [03-ws-do.md](03-ws-do.md) |
+| 2a.10 | Adapt all API route tests for D1 (replace PostgreSQL mocks) | [01-web-service.md](01-web-service.md) |
+| 2a.11 | Configure OpenNext for Cloudflare Workers deployment | [01-web-service.md](01-web-service.md) |
+
+**Exit criteria:** Web Service runs on `wrangler dev` with D1, Better Auth login works, all API routes pass tests.
+
+---
+
+## Phase 2b — Email Worker (new service)
+
+**Goal:** Build the Email Worker. Can start once Phase 1 is complete. Does not depend on Phase 2a.
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 2b.1 | Create `src/email-worker/` directory structure + `wrangler.toml` | [02-email-worker.md](02-email-worker.md) |
+| 2b.2 | Implement `email()` handler — parse handle, verify agent, check whitelist, store R2, notify Web Service | [02-email-worker.md](02-email-worker.md) |
+| 2b.3 | Implement `fetch()` handler — `/simulate` dev endpoint | [02-email-worker.md](02-email-worker.md) |
+| 2b.4 | Write tests (agent resolution, R2 storage, whitelisted/non-whitelisted paths, error propagation) | [02-email-worker.md](02-email-worker.md) |
+
+**Exit criteria:** Email Worker compiles, tests pass, `/simulate` endpoint works in local dev.
+
+> **Note:** End-to-end testing with the Web Service requires Phase 2a.7 (`POST /api/email/notify` endpoint) to be complete.
+
+---
+
+## Phase 2c — WS-DO (new service)
+
+**Goal:** Build the WebSocket Durable Objects service. Can start once Phase 1 is complete. Does not depend on Phase 2a.
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 2c.1 | Create `src/ws-do/` directory structure + `wrangler.toml` | [03-ws-do.md](03-ws-do.md) |
+| 2c.2 | Implement Worker entry point (`src/index.ts`) — broadcast + WebSocket upgrade routes | [03-ws-do.md](03-ws-do.md) |
+| 2c.3 | Implement Durable Object (`src/ws-durable.ts`) — connection state, auth, broadcast | [03-ws-do.md](03-ws-do.md) |
+| 2c.4 | Implement token validation via `@alook/shared` session queries | [03-ws-do.md](03-ws-do.md) |
+| 2c.5 | Write tests (upgrade, auth, broadcast, rejection, cleanup) | [03-ws-do.md](03-ws-do.md) |
+
+**Exit criteria:** WS-DO compiles, tests pass, WebSocket upgrade works in local dev.
+
+> **Note:** End-to-end testing with the Web Service requires Phase 2a.8 (service binding + `notify()` helper).
+
+---
+
+## Phase 3 — Frontend (WebSocket + Email UI)
+
+**Goal:** Update the browser frontend to use WebSocket notifications and add email management UI. Depends on Phase 2a (Web Service) and Phase 2c (WS-DO).
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 3.1 | Add WebSocket client hook — connect to WS-DO, handle auth, receive notifications | [03-ws-do.md](03-ws-do.md) |
+| 3.2 | Replace polling with WS-DO push for task messages, runtime status | [03-ws-do.md](03-ws-do.md) |
+| 3.3 | Add email inbox page (list emails per agent) | [00-overview.md](00-overview.md) |
+| 3.4 | Add whitelist management UI (add/remove sender emails per agent) | [00-overview.md](00-overview.md) |
+| 3.5 | Update `AgentEditForm` with `email_handle` and `forward_to_email` fields | [01-web-service.md](01-web-service.md) |
+
+**Exit criteria:** Browser receives real-time notifications via WebSocket, email management works end-to-end.
+
+---
+
+## Phase 4 — Integration & CLI
+
+**Goal:** End-to-end integration testing and CLI compatibility verification. Depends on all Phase 2 work.
+
+| Step | Description | Doc |
+|------|-------------|-----|
+| 4.1 | Verify CLI daemon works with new auth (machine tokens unchanged) | [04-cli-daemon.md](04-cli-daemon.md) |
+| 4.2 | End-to-end: email → Email Worker → Web Service → task → CLI daemon → complete | [02-email-worker.md](02-email-worker.md) |
+| 4.3 | End-to-end: send message → task → daemon claims → complete → WS-DO notification → browser refresh | [03-ws-do.md](03-ws-do.md) |
+| 4.4 | Verify stale detection (runtime heartbeat + task timeout) works on D1 | [01-web-service.md](01-web-service.md) |
+| 4.5 | Deploy all services to Cloudflare (wrangler deploy per service) | — |
+
+**Exit criteria:** All services deployed, all end-to-end flows work in production.
+
+---
+
+## Parallelism Summary
+
+```
+Phase 0 ─────────────────── (sequential)
+ │
+Phase 1 ─────────────────── (sequential, foundation)
+ │
+ ├── Phase 2a ───── (Web Service)
+ ├── Phase 2b ───── (Email Worker) ← can run in parallel
+ └── Phase 2c ───── (WS-DO)
+ │
+Phase 3 ─────────────────── (depends on 2a + 2c)
+Phase 4 ─────────────────── (depends on all Phase 2)
+```
+
+Phases 2a, 2b, and 2c are independent and can be developed in parallel once the shared library (Phase 1) is complete.