Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

chore: gitignore docs/ and temp/, untrack docs

Generdc9a3324bcaf
diff --git a/.gitignore b/.gitignore
index 06c2d1488..da71f75cb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,5 +8,6 @@ dist/
.next/
.open-next/
temp/
+docs/
.DS_Store
plans/
diff --git a/docs/migration/00-overview.md b/docs/migration/00-overview.md
deleted file mode 100644
index f20386f5a..000000000
--- a/docs/migration/00-overview.md
+++ /dev/null
@@ -1,143 +0,0 @@
-# 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
deleted file mode 100644
index e81b4a37d..000000000
--- a/docs/migration/01-web-service.md
+++ /dev/null
@@ -1,506 +0,0 @@
-# 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
deleted file mode 100644
index ed94f766e..000000000
--- a/docs/migration/02-email-worker.md
+++ /dev/null
@@ -1,260 +0,0 @@
-# 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
deleted file mode 100644
index 89e50cb5f..000000000
--- a/docs/migration/03-ws-do.md
+++ /dev/null
@@ -1,347 +0,0 @@
-# 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
deleted file mode 100644
index dea0ee267..000000000
--- a/docs/migration/04-cli-daemon.md
+++ /dev/null
@@ -1,367 +0,0 @@
-# 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
deleted file mode 100644
index 12614c67d..000000000
--- a/docs/migration/05-shared-library.md
+++ /dev/null
@@ -1,277 +0,0 @@
-# 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
deleted file mode 100644
index e555f64e8..000000000
--- a/docs/migration/06-migration-order.md
+++ /dev/null
@@ -1,173 +0,0 @@
-# 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.
diff --git a/docs/superpowers/plans/plan-00-index.md b/docs/superpowers/plans/plan-00-index.md
deleted file mode 100644
index 439a52fe8..000000000
--- a/docs/superpowers/plans/plan-00-index.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# Cloudflare Edge Migration — Plan Index
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Migrate Alook from Node.js + PostgreSQL to Cloudflare Workers + D1 + R2 + Durable Objects.
-
-**Architecture:** 5-service monorepo (web, cli, email-worker, ws-do, shared) on pnpm + Turborepo. D1 via Drizzle ORM. Better Auth replaces custom JWT. OpenNext deploys Next.js to Workers.
-
-**Tech Stack:** Cloudflare Workers, D1, R2, Durable Objects, Next.js, OpenNext, Drizzle ORM, Better Auth, Turborepo, pnpm, Vitest
-
-**Spec:** `docs/superpowers/specs/2026-04-10-cloudflare-migration-design.md`
-
----
-
-## Plan Files
-
-| File | Phase | Dependencies | Parallelizable |
-|------|-------|-------------|----------------|
-| [plan-01-phase0-infra.md](plan-01-phase0-infra.md) | 0 — Infrastructure | None | No |
-| [plan-02-phase1-shared.md](plan-02-phase1-shared.md) | 1 — Shared Library | Phase 0 | No |
-| [plan-03-phase2a-web.md](plan-03-phase2a-web.md) | 2a — Web Service | Phase 1 | Yes (with 2b, 2c) |
-| [plan-04-phase2b-email.md](plan-04-phase2b-email.md) | 2b — Email Worker | Phase 1 | Yes (with 2a, 2c) |
-| [plan-05-phase2c-wsdo.md](plan-05-phase2c-wsdo.md) | 2c — WS-DO | Phase 1 | Yes (with 2a, 2b) |
-| [plan-06-phase3-frontend.md](plan-06-phase3-frontend.md) | 3 — Frontend | Phase 2a | No |
-
-## Execution Order
-
-```
-Phase 0 ──── single agent
-Phase 1 ──── single agent
-Phase 2a ─┐
-Phase 2b ─┼─ 3 parallel subagents
-Phase 2c ─┘
-Phase 3 ──── single agent
-```
-
-## Reference Material
-
-- `temp/main/` — current production codebase (origin/main)
-- `temp/spec-plans/` — Cloudflare edge reference (origin/chore/spec-plans)
-
-## Strategy
-
-**Hybrid: copy unchanged files from spec-plans, rewrite where migration docs diverge.**
-
-Key divergences requiring rewrites:
-1. Shared DB layer (new — schema + queries move into @alook/shared)
-2. Email Worker (Drizzle via shared, read-only D1, notify web service)
-3. WS-DO (session-only token validation, user channels only)
-4. Web API routes (main's routes adapted for D1/shared imports)
-5. Types/Constants (main's rich model, not spec-plans' simpler types)
diff --git a/docs/superpowers/plans/plan-01-phase0-infra.md b/docs/superpowers/plans/plan-01-phase0-infra.md
deleted file mode 100644
index 6fb323b8e..000000000
--- a/docs/superpowers/plans/plan-01-phase0-infra.md
+++ /dev/null
@@ -1,256 +0,0 @@
-# Phase 0 — Infrastructure Setup
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Scaffold the pnpm monorepo with Turborepo, create all 5 package directories with configs, wrangler.toml per Cloudflare service.
-
-**Strategy:** Copy from `temp/spec-plans/` — these configs match the migration docs.
-
----
-
-### Task 1: Root config files
-
-**Files:**
-- Create: `.gitignore`
-- Create: `pnpm-workspace.yaml`
-- Create: `package.json`
-- Create: `turbo.json`
-- Create: `vitest.config.ts`
-- Create: `vitest.shared.ts`
-
-- [ ] Copy root configs from spec-plans reference:
-
-```bash
-cp temp/spec-plans/pnpm-workspace.yaml .
-cp temp/spec-plans/package.json .
-cp temp/spec-plans/turbo.json .
-cp temp/spec-plans/vitest.config.ts .
-cp temp/spec-plans/vitest.shared.ts .
-```
-
-- [ ] Create `.gitignore` (merge main + spec-plans patterns):
-
-```
-node_modules/
-dist/
-.turbo/
-.wrangler/
-.env
-.env.*
-!.env.example
-.next/
-.open-next/
-temp/
-.DS_Store
-plans/
-```
-
-- [ ] Commit
-
-```bash
-git add .gitignore pnpm-workspace.yaml package.json turbo.json vitest.config.ts vitest.shared.ts
-git commit -m "chore: root monorepo configs"
-```
-
----
-
-### Task 2: Shared library scaffold
-
-**Files:**
-- Create: `src/shared/package.json`
-- Create: `src/shared/tsconfig.json`
-- Create: `src/shared/vitest.config.ts`
-- Create: `src/shared/src/index.ts` (placeholder)
-
-- [ ] Copy configs from spec-plans:
-
-```bash
-mkdir -p src/shared/src src/shared/test/utils
-cp temp/spec-plans/src/shared/package.json src/shared/
-cp temp/spec-plans/src/shared/tsconfig.json src/shared/
-cp temp/spec-plans/src/shared/vitest.config.ts src/shared/
-```
-
-- [ ] Update `src/shared/package.json` to add `drizzle-orm` dependency per migration docs. The spec-plans version has no drizzle — edit the file:
-
-Add to `"dependencies"`:
-```json
-"drizzle-orm": "^0.39.0",
-"zod": "^3.24"
-```
-
-Note: spec-plans' shared package.json uses `"exports": { ".": { "import": "./dist/index.js" } }` with a build step. Migration docs say `"exports": { ".": "./src/index.ts" }` (no build). Update to match the migration docs: change exports to `{ ".": "./src/index.ts" }`, remove `"main"` and `"types"` fields, remove `"build"` and `"dev"` scripts (keep `"test"` and `"typecheck"`).
-
-- [ ] Create placeholder `src/shared/src/index.ts`:
-
-```typescript
-// @alook/shared — populated in Phase 1
-export {}
-```
-
-- [ ] Commit
-
-```bash
-git add src/shared/
-git commit -m "chore: scaffold @alook/shared"
-```
-
----
-
-### Task 3: CLI scaffold
-
-**Files:**
-- Create: `src/cli/package.json`
-- Create: `src/cli/tsconfig.json`
-- Create: `src/cli/src/index.ts` (placeholder)
-
-- [ ] Copy from spec-plans:
-
-```bash
-mkdir -p src/cli/src
-cp temp/spec-plans/src/cli/package.json src/cli/
-cp temp/spec-plans/src/cli/tsconfig.json src/cli/
-```
-
-- [ ] Create placeholder `src/cli/src/index.ts`:
-
-```typescript
-console.log("alook cli")
-```
-
-- [ ] Commit
-
-```bash
-git add src/cli/
-git commit -m "chore: scaffold @alook/cli"
-```
-
----
-
-### Task 4: Web service scaffold
-
-**Files:**
-- Create: `src/web/package.json`
-- Create: `src/web/tsconfig.json`
-- Create: `src/web/next.config.ts`
-- Create: `src/web/open-next.config.ts`
-- Create: `src/web/postcss.config.mjs`
-- Create: `src/web/components.json`
-- Create: `src/web/wrangler.toml`
-- Create: `src/web/vitest.config.ts`
-- Create: `src/web/cloudflare-env.d.ts`
-- Create: `src/web/src/env.d.ts`
-
-- [ ] Copy config files from spec-plans:
-
-```bash
-mkdir -p src/web/src
-cp temp/spec-plans/src/web/package.json src/web/
-cp temp/spec-plans/src/web/tsconfig.json src/web/
-cp temp/spec-plans/src/web/next.config.ts src/web/
-cp temp/spec-plans/src/web/open-next.config.ts src/web/
-cp temp/spec-plans/src/web/postcss.config.mjs src/web/
-cp temp/spec-plans/src/web/components.json src/web/
-cp temp/spec-plans/src/web/wrangler.toml src/web/
-cp temp/spec-plans/src/web/vitest.config.ts src/web/
-cp temp/spec-plans/src/web/cloudflare-env.d.ts src/web/
-cp temp/spec-plans/src/web/src/env.d.ts src/web/src/
-```
-
-- [ ] Ensure `src/web/package.json` name is `@alook/web` and has `@alook/shared` as workspace dependency (it should from spec-plans, but verify).
-
-- [ ] Commit
-
-```bash
-git add src/web/
-git commit -m "chore: scaffold @alook/web"
-```
-
----
-
-### Task 5: Email worker scaffold
-
-**Files:**
-- Create: `src/email-worker/package.json`
-- Create: `src/email-worker/tsconfig.json`
-- Create: `src/email-worker/vitest.config.ts`
-- Create: `src/email-worker/wrangler.toml`
-- Create: `src/email-worker/src/index.ts` (placeholder)
-
-- [ ] Copy from spec-plans:
-
-```bash
-mkdir -p src/email-worker/src
-cp temp/spec-plans/src/email-worker/package.json src/email-worker/
-cp temp/spec-plans/src/email-worker/tsconfig.json src/email-worker/
-cp temp/spec-plans/src/email-worker/vitest.config.ts src/email-worker/
-cp temp/spec-plans/src/email-worker/wrangler.toml src/email-worker/
-```
-
-- [ ] Create placeholder `src/email-worker/src/index.ts`:
-
-```typescript
-export default {
- async email() {},
- async fetch() { return new Response("email-worker") },
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/email-worker/
-git commit -m "chore: scaffold @alook/email-worker"
-```
-
----
-
-### Task 6: WS-DO scaffold
-
-**Files:**
-- Create: `src/ws-do/package.json`
-- Create: `src/ws-do/tsconfig.json`
-- Create: `src/ws-do/wrangler.toml`
-- Create: `src/ws-do/src/index.ts` (placeholder)
-- Create: `src/ws-do/src/env.d.ts`
-
-- [ ] Copy from spec-plans:
-
-```bash
-mkdir -p src/ws-do/src
-cp temp/spec-plans/src/ws-do/package.json src/ws-do/
-cp temp/spec-plans/src/ws-do/tsconfig.json src/ws-do/
-cp temp/spec-plans/src/ws-do/wrangler.toml src/ws-do/
-cp temp/spec-plans/src/ws-do/src/env.d.ts src/ws-do/src/
-```
-
-- [ ] Create placeholder `src/ws-do/src/index.ts`:
-
-```typescript
-export default {
- async fetch() { return new Response("ws-do") },
-}
-export class WebSocketDurableObject {}
-```
-
-- [ ] Commit
-
-```bash
-git add src/ws-do/
-git commit -m "chore: scaffold @alook/ws-do"
-```
-
----
-
-### Task 7: Install dependencies and verify
-
-- [ ] Run `pnpm install` from project root
-- [ ] Verify all packages resolve: `pnpm ls --depth 0`
-- [ ] Commit lockfile
-
-```bash
-git add pnpm-lock.yaml
-git commit -m "chore: install dependencies"
-```
-
-**Exit criteria:** `pnpm install` succeeds. All 5 packages exist with configs. Lockfile committed.
diff --git a/docs/superpowers/plans/plan-02-phase1-shared.md b/docs/superpowers/plans/plan-02-phase1-shared.md
deleted file mode 100644
index 7cc91b8ae..000000000
--- a/docs/superpowers/plans/plan-02-phase1-shared.md
+++ /dev/null
@@ -1,461 +0,0 @@
-# Phase 1 — Shared Library (`@alook/shared`)
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Build `@alook/shared` with types, constants, Zod schemas, Drizzle D1 schema, DB factory, query modules, and utils.
-
-**Strategy:** Types/constants/schemas from `temp/main/src/shared/`. Utils from `temp/spec-plans/src/shared/`. DB layer is new — schema converted from main's pgTable to sqliteTable, queries migrated from `temp/main/src/web/lib/db/queries/`.
-
----
-
-### Task 1: Types, API types, constants from main
-
-**Files:**
-- Create: `src/shared/src/types.ts`
-- Create: `src/shared/src/api-types.ts`
-- Create: `src/shared/src/constants.ts`
-
-- [ ] Copy from main's shared (these are the rich types used by CLI and web):
-
-```bash
-cp temp/main/src/shared/types.ts src/shared/src/
-cp temp/main/src/shared/api-types.ts src/shared/src/
-cp temp/main/src/shared/constants.ts src/shared/src/
-```
-
-These files are pure TypeScript types — no PostgreSQL-specific code, so they work as-is.
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/types.ts src/shared/src/api-types.ts src/shared/src/constants.ts
-git commit -m "feat(shared): types, api-types, constants from main"
-```
-
----
-
-### Task 2: Zod schemas from main
-
-**Files:**
-- Create: `src/shared/src/schemas.ts`
-
-- [ ] Copy from main:
-
-```bash
-cp temp/main/src/shared/schemas.ts src/shared/src/
-```
-
-The schemas use `z.coerce.date()` which works with D1's text dates. No changes needed.
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/schemas.ts
-git commit -m "feat(shared): zod validation schemas from main"
-```
-
----
-
-### Task 3: Utils from spec-plans
-
-**Files:**
-- Create: `src/shared/src/utils/email.ts`
-- Create: `src/shared/src/utils/validation.ts`
-- Create: `src/shared/src/utils/status.ts`
-
-- [ ] Copy from spec-plans:
-
-```bash
-mkdir -p src/shared/src/utils
-cp temp/spec-plans/src/shared/src/utils/email.ts src/shared/src/utils/
-cp temp/spec-plans/src/shared/src/utils/validation.ts src/shared/src/utils/
-cp temp/spec-plans/src/shared/src/utils/status.ts src/shared/src/utils/
-```
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/utils/
-git commit -m "feat(shared): email, validation, status utils from spec-plans"
-```
-
----
-
-### Task 4: Tests from spec-plans
-
-**Files:**
-- Create: `src/shared/test/constants.test.ts`
-- Create: `src/shared/test/utils/email.test.ts`
-- Create: `src/shared/test/utils/status.test.ts`
-- Create: `src/shared/test/utils/validation.test.ts`
-
-- [ ] Copy test files from spec-plans:
-
-```bash
-cp temp/spec-plans/src/shared/test/constants.test.ts src/shared/test/
-cp temp/spec-plans/src/shared/test/utils/email.test.ts src/shared/test/utils/
-cp temp/spec-plans/src/shared/test/utils/status.test.ts src/shared/test/utils/
-cp temp/spec-plans/src/shared/test/utils/validation.test.ts src/shared/test/utils/
-```
-
-- [ ] The constants test imports `HEARTBEAT_INTERVAL_MS` etc. from spec-plans' constants. Main's constants are different (AgentStatus, RuntimeStatus, etc.). Fix the test to match main's constants, or add the spec-plans constants to main's constants file.
-
-**Decision:** Add spec-plans' timing constants to main's constants file. Edit `src/shared/src/constants.ts` to append:
-
-```typescript
-// Timing constants
-export const HEARTBEAT_INTERVAL_MS = 3_000;
-export const OFFLINE_THRESHOLD_MS = 9_000;
-export const EVENT_POLL_INTERVAL_MS = 2_000;
-export const AGENT_HANDLE_MIN_LENGTH = 4;
-```
-
-- [ ] Run tests: `cd src/shared && pnpm test`
-- [ ] Commit
-
-```bash
-git add src/shared/test/ src/shared/src/constants.ts
-git commit -m "feat(shared): tests and timing constants"
-```
-
----
-
-### Task 5: Drizzle D1 schema
-
-**Files:**
-- Create: `src/shared/src/db/schema.ts`
-
-- [ ] Create `src/shared/src/db/schema.ts` by converting main's `temp/main/src/web/lib/db/schema.ts` from `pgTable` to `sqliteTable`.
-
-**Reference:** Read `temp/main/src/web/lib/db/schema.ts` for the source, and `docs/migration/01-web-service.md` "Schema" section for the target table list.
-
-Key conversions:
-- `import { pgTable, uuid, text, timestamp, boolean, integer, jsonb } from "drizzle-orm/pg-core"` → `import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core"`
-- `uuid("id").primaryKey().defaultRandom()` → `text("id").primaryKey().$defaultFn(() => nanoid())`
-- `timestamp("created_at", { withTimezone: true }).notNull().defaultNow()` → `text("created_at").notNull().$defaultFn(() => new Date().toISOString())`
-- `boolean("used")` → `integer("used", { mode: "boolean" })`
-- `jsonb("metadata")` → `text("metadata", { mode: "json" })`
-- Remove `verificationCode` table (Better Auth manages verification)
-- Add Better Auth tables: `user` (with camelCase columns), `session`, `account`, `verification`
-- Add new tables per migration docs: `agentWhitelist`, `emails`
-- Add new columns: `agent.emailHandle`, `agent.forwardToEmail`
-
-Need `nanoid` dependency — add to `src/shared/package.json`:
-```json
-"nanoid": "^5.1.7"
-```
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/db/
-git commit -m "feat(shared): drizzle D1 schema (sqliteTable)"
-```
-
----
-
-### Task 6: DB factory
-
-**Files:**
-- Create: `src/shared/src/db/index.ts`
-
-- [ ] Create `src/shared/src/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>
-```
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/db/index.ts
-git commit -m "feat(shared): createDb D1 factory"
-```
-
----
-
-### Task 7: Query modules — user, workspace, member
-
-**Files:**
-- Create: `src/shared/src/db/queries/user.ts`
-- Create: `src/shared/src/db/queries/workspace.ts`
-- Create: `src/shared/src/db/queries/member.ts`
-
-- [ ] Migrate from `temp/main/src/web/lib/db/queries/`. Each file needs:
- 1. Change schema import from `"../schema"` to `"../schema"` (same relative path since we're in shared/src/db/queries/)
- 2. Change Database import from `"../index"` to `"../index"`
- 3. No PostgreSQL-specific changes — these queries use only Drizzle ORM operators
-
-Since main's queries already accept `db: Database` as the first parameter and use ORM operators (eq, and, asc, desc), they are D1-compatible as-is. Copy them:
-
-```bash
-mkdir -p src/shared/src/db/queries
-cp temp/main/src/web/lib/db/queries/user.ts src/shared/src/db/queries/
-cp temp/main/src/web/lib/db/queries/workspace.ts src/shared/src/db/queries/
-cp temp/main/src/web/lib/db/queries/member.ts src/shared/src/db/queries/
-```
-
-Fix imports in each file: change `"../schema"` and `"../index"` to match the new locations. Main's files use `import { user } from "../schema"` and `import type { Database } from "../index"` — these relative paths still work in `shared/src/db/queries/` pointing to `shared/src/db/schema` and `shared/src/db/index`.
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/db/queries/
-git commit -m "feat(shared): user, workspace, member queries"
-```
-
----
-
-### Task 8: Query modules — agent, runtime
-
-**Files:**
-- Create: `src/shared/src/db/queries/agent.ts`
-- Create: `src/shared/src/db/queries/runtime.ts`
-
-- [ ] Copy from main:
-
-```bash
-cp temp/main/src/web/lib/db/queries/agent.ts src/shared/src/db/queries/
-cp temp/main/src/web/lib/db/queries/runtime.ts src/shared/src/db/queries/
-```
-
-- [ ] The agent and runtime queries use Drizzle ORM operators and are D1-compatible. However, review for any PostgreSQL-specific features:
- - `agent.ts`: uses `db.transaction()` in `deleteAgent`. D1 supports transactions via `db.batch()` but Drizzle's `db.transaction()` also works with D1. Keep as-is.
- - `runtime.ts`: uses `.onConflictDoUpdate()` in `upsertAgentRuntime`. Drizzle's D1 adapter supports this via SQLite's `ON CONFLICT`. Keep as-is.
-
-- [ ] Add `getAgentByHandle` function to `agent.ts` (new, needed by email worker):
-
-```typescript
-export async function getAgentByHandle(db: Database, emailHandle: string) {
- const rows = await db
- .select()
- .from(agent)
- .where(eq(agent.emailHandle, emailHandle));
- return rows[0] ?? null;
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/db/queries/agent.ts src/shared/src/db/queries/runtime.ts
-git commit -m "feat(shared): agent, runtime queries"
-```
-
----
-
-### Task 9: Query modules — conversation, message, task, task-message
-
-**Files:**
-- Create: `src/shared/src/db/queries/conversation.ts`
-- Create: `src/shared/src/db/queries/message.ts`
-- Create: `src/shared/src/db/queries/task.ts`
-- Create: `src/shared/src/db/queries/task-message.ts`
-
-- [ ] Copy from main:
-
-```bash
-cp temp/main/src/web/lib/db/queries/conversation.ts src/shared/src/db/queries/
-cp temp/main/src/web/lib/db/queries/message.ts src/shared/src/db/queries/
-cp temp/main/src/web/lib/db/queries/task.ts src/shared/src/db/queries/
-cp temp/main/src/web/lib/db/queries/task-message.ts src/shared/src/db/queries/
-```
-
-- [ ] **Critical change in `task.ts`:** The `claimTask` function uses `.for("update", { skipLocked: true })` which is PostgreSQL-only. Replace with CAS-style UPDATE per migration docs:
-
-Remove the `.for("update", { skipLocked: true })` line from the candidate query. The D1 approach: the `UPDATE ... WHERE status='queued'` guard already provides atomicity since D1 auto-commits each statement. The existing code structure (find candidate, then update with status check) works for D1 — just remove the `.for()` call.
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/db/queries/conversation.ts src/shared/src/db/queries/message.ts src/shared/src/db/queries/task.ts src/shared/src/db/queries/task-message.ts
-git commit -m "feat(shared): conversation, message, task, task-message queries"
-```
-
----
-
-### Task 10: Query modules — machine-token, whitelist, email, session (new)
-
-**Files:**
-- Create: `src/shared/src/db/queries/machine-token.ts`
-- Create: `src/shared/src/db/queries/whitelist.ts` (new)
-- Create: `src/shared/src/db/queries/email.ts` (new)
-- Create: `src/shared/src/db/queries/session.ts` (new)
-
-- [ ] Copy machine-token from main:
-
-```bash
-cp temp/main/src/web/lib/db/queries/machine-token.ts src/shared/src/db/queries/
-```
-
-- [ ] Create `src/shared/src/db/queries/whitelist.ts` (new — referenced in migration docs):
-
-```typescript
-import { eq, and } from "drizzle-orm";
-import { agentWhitelist } from "../schema";
-import type { Database } from "../index";
-
-export async function getWhitelist(db: Database, agentId: string) {
- return db.select().from(agentWhitelist).where(eq(agentWhitelist.agentId, agentId));
-}
-
-export async function addWhitelist(db: Database, agentId: string, email: string) {
- const rows = await db
- .insert(agentWhitelist)
- .values({ agentId, email })
- .onConflictDoNothing()
- .returning();
- return rows[0] ?? null;
-}
-
-export async function removeWhitelist(db: Database, id: string) {
- await db.delete(agentWhitelist).where(eq(agentWhitelist.id, id));
-}
-
-export async function isWhitelisted(db: Database, agentId: string, email: string): Promise<boolean> {
- const rows = await db
- .select({ id: agentWhitelist.id })
- .from(agentWhitelist)
- .where(and(eq(agentWhitelist.agentId, agentId), eq(agentWhitelist.email, email)))
- .limit(1);
- return rows.length > 0;
-}
-```
-
-- [ ] Create `src/shared/src/db/queries/email.ts` (new):
-
-```typescript
-import { eq, desc } from "drizzle-orm";
-import { emails } from "../schema";
-import type { Database } from "../index";
-
-export async function createEmail(
- db: Database,
- data: {
- agentId: string;
- fromEmail: string;
- toEmail: string;
- subject: string;
- r2Key: string;
- isWhitelisted: boolean;
- forwarded: boolean;
- }
-) {
- const rows = await db.insert(emails).values(data).returning();
- return rows[0]!;
-}
-
-export async function getEmailById(db: Database, id: string) {
- const rows = await db.select().from(emails).where(eq(emails.id, id));
- return rows[0] ?? null;
-}
-
-export async function getEmailsByAgent(db: Database, agentId: string) {
- return db.select().from(emails).where(eq(emails.agentId, agentId)).orderBy(desc(emails.createdAt));
-}
-
-export async function getEmailsByUser(db: Database, agentIds: string[]) {
- // Called with agent IDs belonging to the user
- if (agentIds.length === 0) return [];
- const { inArray } = await import("drizzle-orm");
- return db.select().from(emails).where(inArray(emails.agentId, agentIds)).orderBy(desc(emails.createdAt));
-}
-```
-
-- [ ] Create `src/shared/src/db/queries/session.ts` (new — for WS-DO token validation):
-
-```typescript
-import { eq, gt } from "drizzle-orm";
-import { session } from "../schema";
-import type { Database } from "../index";
-
-export async function getValidSession(db: Database, token: string) {
- const rows = await db
- .select({ userId: session.userId })
- .from(session)
- .where(eq(session.token, token));
- if (rows.length === 0) return null;
- // Check expiry — Better Auth stores expiresAt as text ISO date
- const row = rows[0];
- return row.userId;
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/shared/src/db/queries/
-git commit -m "feat(shared): machine-token, whitelist, email, session queries"
-```
-
----
-
-### Task 11: Index re-exports
-
-**Files:**
-- Modify: `src/shared/src/index.ts`
-
-- [ ] Update `src/shared/src/index.ts` to re-export everything. Copy the exports structure from `temp/main/src/shared/index.ts` and add DB and utils exports:
-
-```typescript
-// Types
-export type { User, Workspace, Agent, AgentRuntime, Conversation, Message, AgentTask, TaskAgentData, TaskMessage, MachineToken, LoginResponse, CreateAgentRequest } from "./types";
-
-// API Types
-export type { ApiResponse, ApiListResponse, ApiErrorResponse, GetUserResponse, ListWorkspacesResponse, GetWorkspaceResponse, ListAgentsResponse, GetAgentResponse, ListRuntimesResponse, GetRuntimeResponse, ListConversationsResponse, GetConversationResponse, ListMessagesResponse, ListTasksResponse, GetTaskResponse, ListTaskMessagesResponse, ListMachineTokensResponse, CreateWorkspaceRequest, UpdateAgentRequest, SendMessageRequest, CreateMachineTokenRequest, CreateMachineTokenResponse } from "./api-types";
-
-// Constants
-export { AgentStatus, RuntimeStatus, TaskStatus, MessageRole, HEARTBEAT_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH } from "./constants";
-export type { AgentStatusType, RuntimeStatusType, TaskStatusType, MessageRoleType } from "./constants";
-
-// Schemas
-export { TaskStatusSchema, ClaimedTaskRowSchema, TaskAgentDataApiSchema, TaskApiBaseSchema, TaskApiSchema, ClaimTaskResponseSchema, RegisterResponseSchema, DaemonRuntimeItemSchema, RegisterDaemonRequestSchema, DeregisterRequestSchema, HeartbeatRequestSchema, CompleteTaskRequestSchema, FailTaskRequestSchema, MessageItemSchema, ReportMessagesRequestSchema } from "./schemas";
-export type { ClaimedTaskRow, TaskAgentDataApi, TaskApiBase, TaskApi, ClaimTaskResponse, RegisterResponse, DaemonRuntimeItem, RegisterDaemonRequest, DeregisterRequest, HeartbeatRequest, CompleteTaskRequest, FailTaskRequest, MessageItem, ReportMessagesRequest } from "./schemas";
-
-// Database
-export { createDb } from "./db/index";
-export type { Database } from "./db/index";
-export * as schema from "./db/schema";
-export * as queries from "./db/queries-index";
-
-// Utils
-export { parseEmailHandle, toAlookAddress, isValidHandle } from "./utils/email";
-export { isValidToken, isValidEmail } from "./utils/validation";
-export { isOnline, formatStatus } from "./utils/status";
-```
-
-- [ ] Create `src/shared/src/db/queries-index.ts` to barrel-export all query modules:
-
-```typescript
-export * as user from "./queries/user";
-export * as workspace from "./queries/workspace";
-export * as member from "./queries/member";
-export * as agent from "./queries/agent";
-export * as runtime from "./queries/runtime";
-export * as conversation from "./queries/conversation";
-export * as message from "./queries/message";
-export * as task from "./queries/task";
-export * as taskMessage from "./queries/task-message";
-export * as machineToken from "./queries/machine-token";
-export * as whitelist from "./queries/whitelist";
-export * as email from "./queries/email";
-export * as session from "./queries/session";
-```
-
-- [ ] Verify typecheck: `cd src/shared && pnpm tsc --noEmit`
-- [ ] Run tests: `cd src/shared && pnpm test`
-- [ ] Commit
-
-```bash
-git add src/shared/src/
-git commit -m "feat(shared): index re-exports and queries barrel"
-```
-
-**Exit criteria:** `@alook/shared` exports `createDb`, `schema`, `queries`, all types/schemas/constants/utils. Tests pass.
diff --git a/docs/superpowers/plans/plan-03-phase2a-web.md b/docs/superpowers/plans/plan-03-phase2a-web.md
deleted file mode 100644
index b699b1972..000000000
--- a/docs/superpowers/plans/plan-03-phase2a-web.md
+++ /dev/null
@@ -1,447 +0,0 @@
-# Phase 2a — Web Service
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Migrate the web service to D1 + Better Auth + OpenNext. All API routes adapted for shared imports.
-
-**Strategy:** Config files from spec-plans. Auth/session/broadcast from spec-plans. API routes from main, adapted to import from `@alook/shared` instead of local `lib/db/`.
-
-**Depends on:** Phase 1 (shared library must be complete)
-
----
-
-### Task 1: D1 migration SQL
-
-**Files:**
-- Create: `src/web/migrations/0001_schema.sql`
-
-- [ ] Copy from spec-plans:
-
-```bash
-mkdir -p src/web/migrations
-cp temp/spec-plans/src/web/migrations/0001_schema.sql src/web/migrations/
-```
-
-Review the SQL to ensure it matches the Drizzle schema created in Phase 1 Task 5. The spec-plans migration covers Better Auth tables + application tables.
-
-- [ ] Commit
-
-```bash
-git add src/web/migrations/
-git commit -m "feat(web): D1 schema migration SQL"
-```
-
----
-
-### Task 2: Auth and session libraries from spec-plans
-
-**Files:**
-- Create: `src/web/src/lib/auth.ts`
-- Create: `src/web/src/lib/auth-client.ts`
-- Create: `src/web/src/lib/session.ts`
-- Create: `src/web/src/lib/dual-auth.ts`
-- Create: `src/web/src/lib/api-auth.ts`
-
-- [ ] Copy from spec-plans:
-
-```bash
-mkdir -p src/web/src/lib
-cp temp/spec-plans/src/web/src/lib/auth.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/auth-client.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/session.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/dual-auth.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/api-auth.ts src/web/src/lib/
-```
-
-- [ ] Update `src/web/src/lib/dual-auth.ts` to use shared queries instead of local `getDb`. Replace the raw D1 `getDb` import with:
-
-```typescript
-import { createDb, queries } from "@alook/shared"
-```
-
-Then use `queries.machineToken.getMachineTokenByHash(db, hashedToken)` and `queries.machineToken.updateMachineTokenLastUsed(db, mt.id)` instead of the local getDb approach.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/lib/auth.ts src/web/src/lib/auth-client.ts src/web/src/lib/session.ts src/web/src/lib/dual-auth.ts src/web/src/lib/api-auth.ts
-git commit -m "feat(web): auth, session, dual-auth from spec-plans"
-```
-
----
-
-### Task 3: Broadcast, storage, utils from spec-plans
-
-**Files:**
-- Create: `src/web/src/lib/broadcast.ts`
-- Create: `src/web/src/lib/storage.ts`
-- Create: `src/web/src/lib/utils.ts`
-
-- [ ] Copy from spec-plans:
-
-```bash
-cp temp/spec-plans/src/web/src/lib/broadcast.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/storage.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/utils.ts src/web/src/lib/
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/lib/broadcast.ts src/web/src/lib/storage.ts src/web/src/lib/utils.ts
-git commit -m "feat(web): broadcast, storage, utils from spec-plans"
-```
-
----
-
-### Task 4: Middleware from main (adapted)
-
-**Files:**
-- Create: `src/web/src/lib/middleware/auth.ts`
-- Create: `src/web/src/lib/middleware/helpers.ts`
-- Create: `src/web/src/lib/middleware/workspace.ts`
-- Create: `src/web/src/lib/middleware/request-id.ts`
-- Create: `src/web/src/lib/middleware/request-logger.ts`
-
-- [ ] Copy from main:
-
-```bash
-mkdir -p src/web/src/lib/middleware
-cp temp/main/src/web/lib/middleware/helpers.ts src/web/src/lib/middleware/
-cp temp/main/src/web/lib/middleware/request-id.ts src/web/src/lib/middleware/
-cp temp/main/src/web/lib/middleware/request-logger.ts src/web/src/lib/middleware/
-```
-
-- [ ] `helpers.ts`, `request-id.ts`, `request-logger.ts` — these are pure Next.js utilities with no DB dependency. Copy as-is. Fix import paths if needed (main uses `@/lib/...` which maps to `src/web/src/lib/...` — same in the new structure since tsconfig paths `@/*` maps to `./src/*`).
-
-- [ ] **Rewrite `auth.ts`:** Main's `withAuth` uses JWT verification. Replace with dual-auth (Better Auth session + machine token). The new `withAuth` should:
- 1. Check for `Authorization: Bearer al_*` header → validate via `queries.machineToken.getMachineTokenByHash`
- 2. Fall back to Better Auth session via `createAuth(env).api.getSession({ headers })`
- 3. Return `AuthContext` with `userId`, `email`, `workspaceId` (for machine tokens)
-
-Reference `temp/main/src/web/lib/middleware/auth.ts` for the `withAuth` wrapper pattern and `AuthContext` interface. Reference `temp/spec-plans/src/web/src/lib/dual-auth.ts` for the D1/Better Auth auth logic.
-
-- [ ] **Rewrite `workspace.ts`:** Main's version imports `db` from `"@/lib/db"` (global PostgreSQL). Replace with getting DB from Cloudflare context:
-
-```typescript
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createDb, queries } from "@alook/shared"
-```
-
-Use `queries.member.getMemberByUserAndWorkspace(db, auth.userId, workspaceId)`.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/lib/middleware/
-git commit -m "feat(web): middleware adapted for D1/Better Auth"
-```
-
----
-
-### Task 5: Services and response formatters from main
-
-**Files:**
-- Create: `src/web/src/lib/services/task.ts`
-- Create: `src/web/src/lib/api/responses.ts`
-- Create: `src/web/src/lib/errors.ts`
-- Create: `src/web/src/lib/logger.ts`
-
-- [ ] Copy from main:
-
-```bash
-mkdir -p src/web/src/lib/services src/web/src/lib/api
-cp temp/main/src/web/lib/services/task.ts src/web/src/lib/services/
-cp temp/main/src/web/lib/api/responses.ts src/web/src/lib/api/
-cp temp/main/src/web/lib/errors.ts src/web/src/lib/errors.ts 2>/dev/null || true
-cp temp/main/src/web/lib/logger.ts src/web/src/lib/logger.ts 2>/dev/null || true
-```
-
-- [ ] **Adapt `task.ts`:** Change imports from local DB queries to shared:
-
-```typescript
-import type { Database } from "@alook/shared"
-import { queries } from "@alook/shared"
-```
-
-Replace `import * as taskQueries from "../db/queries/task"` with `const taskQueries = queries.task`, etc. The `TaskService` constructor takes `db: Database` — this stays the same.
-
-- [ ] **`responses.ts`:** No changes needed — it uses `formatTimestamp` from helpers and types from `@alook/shared`.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/lib/services/ src/web/src/lib/api/ src/web/src/lib/errors.ts src/web/src/lib/logger.ts
-git commit -m "feat(web): task service, response formatters, errors, logger"
-```
-
----
-
-### Task 6: Next.js middleware from spec-plans
-
-**Files:**
-- Create: `src/web/src/middleware.ts`
-
-- [ ] Copy from spec-plans:
-
-```bash
-cp temp/spec-plans/src/web/src/middleware.ts src/web/src/
-```
-
-This guards `/dashboard/*` routes with Better Auth session check. Works as-is.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/middleware.ts
-git commit -m "feat(web): Next.js auth middleware"
-```
-
----
-
-### Task 7: API routes — auth, health, me
-
-**Files:**
-- Create: `src/web/src/app/api/auth/[...all]/route.ts`
-- Create: `src/web/src/app/api/health/route.ts`
-- Create: `src/web/src/app/api/me/route.ts`
-
-- [ ] Copy auth catch-all from spec-plans:
-
-```bash
-mkdir -p src/web/src/app/api/auth/\[...all\]
-cp temp/spec-plans/src/web/src/app/api/auth/\[...all\]/route.ts src/web/src/app/api/auth/\[...all\]/
-```
-
-- [ ] Copy health from main (no auth, no DB):
-
-```bash
-mkdir -p src/web/src/app/api/health
-cp temp/main/src/web/app/api/health/route.ts src/web/src/app/api/health/
-```
-
-- [ ] Copy `/api/me` from main, adapt DB import. Change `import { db } from "@/lib/db"` to get DB from Cloudflare context via `createDb`:
-
-```bash
-mkdir -p src/web/src/app/api/me
-cp temp/main/src/web/app/api/me/route.ts src/web/src/app/api/me/
-```
-
-Edit to use shared queries instead of local DB.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/api/
-git commit -m "feat(web): auth, health, me routes"
-```
-
----
-
-### Task 8: API routes — workspaces, agents, conversations, messages
-
-**Files:**
-- Create: `src/web/src/app/api/workspaces/route.ts`
-- Create: `src/web/src/app/api/workspaces/[id]/route.ts`
-- Create: `src/web/src/app/api/agents/route.ts`
-- Create: `src/web/src/app/api/agents/[id]/route.ts`
-- Create: `src/web/src/app/api/agents/[id]/conversations/route.ts`
-- Create: `src/web/src/app/api/conversations/route.ts`
-- Create: `src/web/src/app/api/conversations/[id]/route.ts`
-- Create: `src/web/src/app/api/conversations/[id]/messages/route.ts`
-
-- [ ] Copy all from main and adapt each file:
-
-For each route file from `temp/main/src/web/app/api/`:
-1. Copy to `src/web/src/app/api/` (note the extra `src/` in path)
-2. Replace `import { db } from "@/lib/db"` with getting DB from Cloudflare context
-3. Replace `import { someQuery } from "@/lib/db/queries/foo"` with `import { queries, createDb } from "@alook/shared"`
-4. Keep the `withAuth` wrapper — it's our adapted middleware
-
-Pattern for each route:
-```typescript
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createDb, queries } from "@alook/shared"
-// ... other imports stay the same
-
-export const GET = withAuth(async (req, ctx) => {
- const { env } = getCloudflareContext()
- const db = createDb((env as Env).DB)
- // ... use queries.foo.bar(db, ...) instead of fooQuery(db, ...)
-})
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/api/
-git commit -m "feat(web): workspace, agent, conversation, message routes"
-```
-
----
-
-### Task 9: API routes — daemon endpoints
-
-**Files:**
-- Create: `src/web/src/app/api/daemon/register/route.ts`
-- Create: `src/web/src/app/api/daemon/deregister/route.ts`
-- Create: `src/web/src/app/api/daemon/heartbeat/route.ts`
-- Create: `src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts`
-- Create: `src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts`
-- Create: `src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts`
-- Create: `src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts`
-- Create: `src/web/src/app/api/daemon/tasks/[taskId]/progress/route.ts`
-- Create: `src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts`
-- Create: `src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts`
-
-- [ ] Copy all daemon routes from main and adapt with same pattern as Task 8.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/api/daemon/
-git commit -m "feat(web): daemon API routes (register, heartbeat, tasks)"
-```
-
----
-
-### Task 10: API routes — tasks, machine-tokens, runtimes
-
-**Files:**
-- Create: `src/web/src/app/api/tasks/[id]/route.ts`
-- Create: `src/web/src/app/api/tasks/[id]/messages/route.ts`
-- Create: `src/web/src/app/api/machine-tokens/route.ts`
-- Create: `src/web/src/app/api/machine-tokens/[id]/route.ts`
-- Create: `src/web/src/app/api/runtimes/route.ts`
-- Create: `src/web/src/app/api/runtimes/machine/route.ts`
-
-- [ ] Copy from main, adapt DB imports.
-
-- [ ] For `machine-tokens/route.ts`: the `generateMachineToken` and `hashToken` functions are in main's `lib/auth/jwt.ts`. Since we're removing jose, extract just these two functions into a new `src/web/src/lib/token.ts`:
-
-```typescript
-import { randomBytes, createHash } from "crypto";
-
-export function generateMachineToken(): string {
- const bytes = randomBytes(24);
- return "al_" + bytes.toString("hex");
-}
-
-export function hashToken(raw: string): string {
- return createHash("sha256").update(raw).digest("hex");
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/api/tasks/ src/web/src/app/api/machine-tokens/ src/web/src/app/api/runtimes/ src/web/src/lib/token.ts
-git commit -m "feat(web): tasks, machine-tokens, runtimes routes + token utils"
-```
-
----
-
-### Task 11: New API routes — email notify, WS token
-
-**Files:**
-- Create: `src/web/src/app/api/email/notify/route.ts` (new per migration docs)
-- Create: `src/web/src/app/api/ws/token/route.ts` (from spec-plans)
-
-- [ ] Copy WS token route from spec-plans:
-
-```bash
-mkdir -p src/web/src/app/api/ws/token
-cp temp/spec-plans/src/web/src/app/api/ws/token/route.ts src/web/src/app/api/ws/token/
-```
-
-- [ ] Create `POST /api/email/notify` per migration docs (02-email-worker.md). This endpoint is called by the Email Worker via service binding:
-
-```typescript
-import { NextRequest } from "next/server";
-import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { createDb, queries } from "@alook/shared";
-import { writeJSON, writeError } from "@/lib/middleware/helpers";
-import { TaskService } from "@/lib/services/task";
-
-export async function POST(req: NextRequest) {
- const { env } = getCloudflareContext();
- const db = createDb((env as Env).DB);
-
- let body: {
- agentId: string;
- r2Key: string;
- from: string;
- subject: string;
- isWhitelisted: boolean;
- forwarded?: boolean;
- };
- try {
- body = await req.json();
- } catch {
- return writeError("invalid request body", 400);
- }
-
- // Create email record
- await queries.email.createEmail(db, {
- agentId: body.agentId,
- fromEmail: body.from,
- toEmail: "", // filled by caller context
- subject: body.subject,
- r2Key: body.r2Key,
- isWhitelisted: body.isWhitelisted,
- forwarded: body.forwarded ?? false,
- });
-
- // Only create task for whitelisted emails
- if (body.isWhitelisted) {
- const agent = await queries.agent.getAgent(db, body.agentId);
- if (agent && agent.runtimeId) {
- // Create a conversation for this email task
- const conv = await queries.conversation.createConversation(db, {
- workspaceId: agent.workspaceId,
- agentId: agent.id,
- userId: agent.ownerId!,
- title: `Email: ${body.subject}`.slice(0, 50),
- });
- const taskService = new TaskService(db);
- await taskService.enqueueTask(
- agent.id, conv.id, agent.workspaceId,
- `New email from ${body.from}: ${body.subject}`
- );
- }
- }
-
- return writeJSON({ ok: true });
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/api/email/ src/web/src/app/api/ws/
-git commit -m "feat(web): email notify + WS token routes"
-```
-
----
-
-### Task 12: Client-side API wrapper
-
-**Files:**
-- Create: `src/web/src/lib/api.ts`
-
-- [ ] Copy from main and adapt for Better Auth (remove JWT header, use cookie auth):
-
-```bash
-cp temp/main/src/web/lib/api.ts src/web/src/lib/
-```
-
-Edit: Remove `Authorization: Bearer ${token}` header for browser requests (Better Auth sends session cookie automatically). Keep the `X-Workspace-ID` header. Change redirect from `/login` to `/sign-in`.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/lib/api.ts
-git commit -m "feat(web): client-side API wrapper adapted for Better Auth"
-```
-
-**Exit criteria:** All API routes compile. Imports resolve against `@alook/shared`. No direct PostgreSQL references remain.
diff --git a/docs/superpowers/plans/plan-04-phase2b-email.md b/docs/superpowers/plans/plan-04-phase2b-email.md
deleted file mode 100644
index 3fc14412c..000000000
--- a/docs/superpowers/plans/plan-04-phase2b-email.md
+++ /dev/null
@@ -1,248 +0,0 @@
-# Phase 2b — Email Worker
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Build the Email Worker that receives inbound emails, verifies agents via D1, stores in R2, and notifies the web service.
-
-**Strategy:** Rewrite from migration docs. Use `@alook/shared` for Drizzle queries (read-only). Spec-plans code as structural reference.
-
-**Depends on:** Phase 1 (shared library must be complete)
-
-**Can run in parallel with:** Phase 2a, Phase 2c
-
----
-
-### Task 1: Email handler implementation
-
-**Files:**
-- Modify: `src/email-worker/src/index.ts` (replace placeholder)
-
-- [ ] Write the email worker following `docs/migration/02-email-worker.md` spec.
-
-**Key differences from spec-plans' `temp/spec-plans/src/email-worker/src/index.ts`:**
-1. Use `createDb` and `queries` from `@alook/shared` instead of local `getDb` with raw SQL
-2. Read-only D1 access — no `createEmail`, no `createEvent`
-3. Notify web service via `POST /api/email/notify` — web service handles all writes
-
-```typescript
-import { createDb, queries, parseEmailHandle } from "@alook/shared"
-import { nanoid } from "nanoid"
-
-interface EmailEnv {
- DB: D1Database
- EMAIL_BUCKET: R2Bucket
- WEB_SERVICE: Fetcher
-}
-
-export default {
- async fetch(request: Request, env: EmailEnv): Promise<Response> {
- const url = new URL(request.url)
- if (url.pathname !== "/simulate" || request.method !== "POST") {
- return new Response("POST /simulate to send a test email", { status: 404 })
- }
-
- const body = await request.json() as { from: string; to: string; subject?: string; body?: string }
- if (!body.from || !body.to) {
- return new Response("from and to required", { status: 400 })
- }
-
- const raw = [
- `From: ${body.from}`,
- `To: ${body.to}`,
- `Subject: ${body.subject ?? "(test)"}`,
- `Date: ${new Date().toUTCString()}`,
- "",
- body.body ?? "",
- ].join("\r\n")
-
- const rawStream = new ReadableStream({
- start(controller) {
- controller.enqueue(new TextEncoder().encode(raw))
- controller.close()
- },
- })
-
- const headers = new Headers()
- headers.set("subject", body.subject ?? "(test)")
-
- const fakeMessage = {
- from: body.from,
- to: body.to,
- raw: rawStream,
- headers,
- setReject(reason: string) { console.log("Rejected:", reason) },
- forward(_to: string) { console.log("Forwarded to:", _to); return Promise.resolve() },
- } as unknown as ForwardableEmailMessage
-
- try {
- await this.email(fakeMessage, env)
- return Response.json({ ok: true })
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e)
- return Response.json({ error: msg }, { status: 500 })
- }
- },
-
- async email(message: ForwardableEmailMessage, env: EmailEnv): Promise<void> {
- const db = createDb(env.DB)
- const handle = parseEmailHandle(message.to)
-
- // 1. Look up agent by handle
- const agent = await queries.agent.getAgentByHandle(db, handle)
- if (!agent) {
- message.setReject("No agent found for this address")
- return
- }
-
- // 2. Check whitelist
- const whitelisted = await queries.whitelist.isWhitelisted(
- db, agent.id, message.from
- )
-
- // 3. Store raw email in R2
- const rawBytes = await new Response(message.raw).arrayBuffer()
- const r2Key = `emails/${nanoid()}/raw`
- await env.EMAIL_BUCKET.put(r2Key, rawBytes, {
- httpMetadata: { contentType: "message/rfc822" },
- })
-
- const subject = message.headers.get("subject") ?? ""
-
- // 4. Notify web service (it handles all writes)
- if (whitelisted) {
- await env.WEB_SERVICE.fetch("http://internal/api/email/notify", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- agentId: agent.id,
- r2Key,
- from: message.from,
- subject,
- isWhitelisted: true,
- }),
- })
- } else {
- // Resolve forward address
- const forwardTo = (agent.forwardToEmail as string) ||
- (await queries.user.getUser(db, agent.ownerId as string))?.email || ""
- const forwarded = !!forwardTo
-
- await env.WEB_SERVICE.fetch("http://internal/api/email/notify", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- agentId: agent.id,
- r2Key,
- from: message.from,
- subject,
- isWhitelisted: false,
- forwarded,
- }),
- })
-
- if (forwardTo) {
- await message.forward(forwardTo)
- }
- }
- },
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/email-worker/src/index.ts
-git commit -m "feat(email-worker): inbound email handler with shared queries"
-```
-
----
-
-### Task 2: Test mocks
-
-**Files:**
-- Create: `src/email-worker/src/__mocks__/cf.ts`
-
-- [ ] Create mocks for D1, R2, Fetcher, and ForwardableEmailMessage. Reference `temp/spec-plans/src/email-worker/src/__mocks__/cf.ts` for structure, but adapt for Drizzle:
-
-Since the email worker now uses `createDb` from `@alook/shared` instead of raw D1, tests need to mock at the Drizzle query level. Use `vi.mock("@alook/shared")` to mock `createDb` and `queries`.
-
-```typescript
-import { vi } from "vitest"
-
-export function createMockR2() {
- return { put: vi.fn().mockResolvedValue(undefined) } as unknown as R2Bucket
-}
-
-export function createMockFetcher() {
- const fetcher = {
- fetch: vi.fn().mockResolvedValue(new Response("ok")),
- }
- return fetcher as unknown as Fetcher
-}
-
-export function createMockMessage(opts: {
- from: string
- to: string
- subject?: string
- body?: string
-}) {
- const raw = [
- `From: ${opts.from}`,
- `To: ${opts.to}`,
- `Subject: ${opts.subject ?? ""}`,
- "",
- opts.body ?? "",
- ].join("\r\n")
-
- const rawStream = new ReadableStream({
- start(c) { c.enqueue(new TextEncoder().encode(raw)); c.close() },
- })
-
- const headers = new Headers()
- headers.set("subject", opts.subject ?? "")
-
- return {
- from: opts.from,
- to: opts.to,
- raw: rawStream,
- headers,
- setReject: vi.fn(),
- forward: vi.fn().mockResolvedValue(undefined),
- } as unknown as ForwardableEmailMessage
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/email-worker/src/__mocks__/
-git commit -m "feat(email-worker): test mocks"
-```
-
----
-
-### Task 3: Tests
-
-**Files:**
-- Create: `src/email-worker/src/index.test.ts`
-
-- [ ] Write tests covering the flows from `docs/migration/02-email-worker.md`:
-
-Test groups:
-1. **Agent resolution:** reject when no agent found, parse handle correctly
-2. **R2 storage:** correct key format, content-type set
-3. **Whitelisted path:** stores R2, notifies web service with `isWhitelisted: true`
-4. **Non-whitelisted path:** stores R2, notifies with `isWhitelisted: false`, forwards when forward_to_email set
-5. **Error propagation:** D1 failure, R2 failure
-
-Mock `@alook/shared`'s `createDb` and `queries` at the module level. Mock the env bindings (R2, Fetcher) using the helpers from Task 2.
-
-- [ ] Run tests: `cd src/email-worker && pnpm test`
-- [ ] Commit
-
-```bash
-git add src/email-worker/src/index.test.ts
-git commit -m "feat(email-worker): tests for email handler"
-```
-
-**Exit criteria:** Email worker compiles, tests pass. Uses `@alook/shared` for D1 reads, notifies web service for writes.
diff --git a/docs/superpowers/plans/plan-05-phase2c-wsdo.md b/docs/superpowers/plans/plan-05-phase2c-wsdo.md
deleted file mode 100644
index d8e298635..000000000
--- a/docs/superpowers/plans/plan-05-phase2c-wsdo.md
+++ /dev/null
@@ -1,169 +0,0 @@
-# Phase 2c — WS-DO (WebSocket Durable Objects)
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Build the notification-only WebSocket service using Cloudflare Durable Objects.
-
-**Strategy:** Copy from spec-plans, adapt per migration docs: session-only token validation, user channels only.
-
-**Depends on:** Phase 1 (shared library must be complete)
-
-**Can run in parallel with:** Phase 2a, Phase 2b
-
----
-
-### Task 1: Worker entry point
-
-**Files:**
-- Modify: `src/ws-do/src/index.ts` (replace placeholder)
-
-- [ ] Adapt from spec-plans (`temp/spec-plans/src/ws-do/src/index.ts`). Simplify per migration docs (03-ws-do.md):
-
-**Remove:** Agent channel broadcast routes (`/broadcast/:agentId`), agent channel WebSocket (`?agentId=xxx`)
-**Keep:** User channel broadcast (`/broadcast/user/:userId`), user channel WebSocket (`?userId=xxx`)
-
-```typescript
-export { WebSocketDurableObject } from "./ws-durable"
-
-export default {
- async fetch(request: Request, env: Env): Promise<Response> {
- const url = new URL(request.url)
-
- // Broadcast to user channel: POST /broadcast/user/:userId
- const userBroadcast = url.pathname.match(/^\/broadcast\/user\/(.+)$/)
- if (userBroadcast && request.method === "POST") {
- const userId = userBroadcast[1]
- const doId = env.WS_DO.idFromName("user:" + userId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(new Request("http://internal/broadcast", {
- method: "POST",
- body: request.body,
- }))
- }
-
- // WebSocket connect to user channel: GET /?userId=xxx
- const userId = url.searchParams.get("userId")
- if (!userId) {
- return new Response("userId required", { status: 400 })
- }
- const doId = env.WS_DO.idFromName("user:" + userId)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(request)
- },
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/ws-do/src/index.ts
-git commit -m "feat(ws-do): worker entry point (user channels only)"
-```
-
----
-
-### Task 2: Durable Object
-
-**Files:**
-- Create: `src/ws-do/src/ws-durable.ts`
-
-- [ ] Adapt from spec-plans (`temp/spec-plans/src/ws-do/src/ws-durable.ts`). Changes per migration docs:
-
-**Remove:** Runtime token (`alook_tk_*`) validation — WS-DO only handles browser sessions
-**Change:** Token validation to use `queries.session.getValidSession` from `@alook/shared` instead of raw D1
-
-```typescript
-import { DurableObject } from "cloudflare:workers"
-import { createDb, queries } from "@alook/shared"
-
-interface ConnectionState {
- userId: string
- authenticated: boolean
-}
-
-export class WebSocketDurableObject extends DurableObject<Env> {
- async fetch(request: Request): Promise<Response> {
- const url = new URL(request.url)
-
- if (url.pathname === "/broadcast" && request.method === "POST") {
- const body = await request.text()
- this.broadcast(body)
- return new Response("ok")
- }
-
- if (request.headers.get("Upgrade") !== "websocket") {
- return new Response("Expected WebSocket", { status: 426 })
- }
-
- const pair = new WebSocketPair()
- const [client, server] = Object.values(pair)
-
- this.ctx.acceptWebSocket(server)
-
- const preAuthUserId = request.headers.get("X-Authenticated-User")
- const state: ConnectionState = preAuthUserId
- ? { userId: preAuthUserId, authenticated: true }
- : { userId: "", authenticated: false }
- server.serializeAttachment(state)
-
- this.ctx.setWebSocketAutoResponse(
- new WebSocketRequestResponsePair("ping", "pong")
- )
-
- return new Response(null, { status: 101, webSocket: client })
- }
-
- async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
- if (typeof message !== "string") return
-
- let parsed: unknown
- try { parsed = JSON.parse(message) } catch { ws.close(1008, "Invalid JSON"); return }
-
- const state = ws.deserializeAttachment() as ConnectionState
- const msg = parsed as { type: string; token?: string }
-
- if (msg.type === "auth") {
- const userId = await this.validateToken(msg.token!)
- if (!userId) { ws.close(1008, "Unauthorized"); return }
- ws.serializeAttachment({ userId, authenticated: true } as ConnectionState)
- ws.send(JSON.stringify({ type: "auth.ok" }))
- return
- }
-
- if (!state.authenticated) {
- ws.close(1008, "Not authenticated")
- }
- }
-
- async webSocketClose(): Promise<void> {}
-
- async webSocketError(ws: WebSocket, error: unknown): Promise<void> {
- console.error("WS error:", error)
- try { ws.close(1011, "Internal error") } catch {}
- }
-
- private broadcast(message: string): void {
- for (const ws of this.ctx.getWebSockets()) {
- const state = ws.deserializeAttachment() as ConnectionState
- if (state.authenticated && ws.readyState === WebSocket.OPEN) {
- ws.send(message)
- }
- }
- }
-
- private async validateToken(token: string): Promise<string | null> {
- // Session tokens only (browser auth via Better Auth)
- const db = createDb(this.env.DB)
- return queries.session.getValidSession(db, token)
- }
-}
-```
-
-- [ ] Commit
-
-```bash
-git add src/ws-do/src/ws-durable.ts
-git commit -m "feat(ws-do): durable object with session-only auth"
-```
-
-**Exit criteria:** WS-DO compiles. Worker routes to user channel DOs. Durable Object handles WebSocket upgrade, auth, and broadcast. Session-only token validation via shared queries.
diff --git a/docs/superpowers/plans/plan-06-phase3-frontend.md b/docs/superpowers/plans/plan-06-phase3-frontend.md
deleted file mode 100644
index 84179f66b..000000000
--- a/docs/superpowers/plans/plan-06-phase3-frontend.md
+++ /dev/null
@@ -1,305 +0,0 @@
-# Phase 3 — Frontend (Pages + Components)
-
-> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development or superpowers:executing-plans
-
-**Goal:** Copy frontend pages, components, contexts, and CSS from main. Adapt auth for Better Auth. Add WebSocket hooks from spec-plans.
-
-**Strategy:** Bulk copy from `temp/main/`, then make targeted edits for auth changes. New auth pages from spec-plans.
-
-**Depends on:** Phase 2a (web service API routes must exist)
-
----
-
-### Task 1: Global CSS and public assets
-
-**Files:**
-- Create: `src/web/src/app/globals.css`
-- Create: `src/web/public/` assets
-
-- [ ] Copy from main:
-
-```bash
-mkdir -p src/web/src/app src/web/public
-cp temp/main/src/web/app/globals.css src/web/src/app/
-cp -r temp/main/src/web/public/* src/web/public/ 2>/dev/null || true
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/globals.css src/web/public/
-git commit -m "feat(web): global CSS and public assets"
-```
-
----
-
-### Task 2: UI components (copy as-is)
-
-**Files:**
-- Create: `src/web/src/components/ui/*.tsx` (all UI primitives)
-
-- [ ] Copy all UI components from main:
-
-```bash
-mkdir -p src/web/src/components/ui
-cp temp/main/src/web/components/ui/button.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/input.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/textarea.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/label.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/badge.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/card.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/dialog.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/confirm-dialog.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/select.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/sheet.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/scroll-area.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/separator.tsx src/web/src/components/ui/
-cp temp/main/src/web/components/ui/avatar.tsx src/web/src/components/ui/
-```
-
-Do NOT copy `input-otp.tsx` — OTP is no longer needed with Better Auth.
-
-- [ ] Fix import paths: main uses `@/components/ui/...` and `@/lib/utils`. In the new structure, the `@/*` alias maps to `./src/*`, so paths like `@/components/ui/button` resolve to `src/web/src/components/ui/button`. This matches main's pattern — no changes needed.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/components/ui/
-git commit -m "feat(web): UI component primitives from main"
-```
-
----
-
-### Task 3: Feature components
-
-**Files:**
-- Create: `src/web/src/components/theme-provider.tsx`
-- Create: `src/web/src/components/toaster-provider.tsx`
-- Create: `src/web/src/components/logo.tsx`
-- Create: `src/web/src/components/theme-toggle.tsx`
-- Create: `src/web/src/components/gradient-background.tsx`
-- Create: `src/web/src/components/dashboard-navbar.tsx`
-- Create: `src/web/src/components/agent-edit-form.tsx`
-- Create: `src/web/src/components/runtime-select.tsx`
-- Create: `src/web/src/components/app-sidebar.tsx`
-
-- [ ] Copy from main:
-
-```bash
-cp temp/main/src/web/components/theme-provider.tsx src/web/src/components/
-cp temp/main/src/web/components/toaster-provider.tsx src/web/src/components/
-cp temp/main/src/web/components/logo.tsx src/web/src/components/
-cp temp/main/src/web/components/theme-toggle.tsx src/web/src/components/
-cp temp/main/src/web/components/gradient-background.tsx src/web/src/components/
-cp temp/main/src/web/components/dashboard-navbar.tsx src/web/src/components/
-cp temp/main/src/web/components/agent-edit-form.tsx src/web/src/components/
-cp temp/main/src/web/components/runtime-select.tsx src/web/src/components/
-cp temp/main/src/web/components/app-sidebar.tsx src/web/src/components/
-```
-
-- [ ] **Edit `app-sidebar.tsx`:** Replace the signOut logic. Main likely clears localStorage JWT. Replace with Better Auth signOut:
-
-```typescript
-import { signOut } from "@/lib/auth-client"
-// In the sign-out handler:
-await signOut()
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/components/
-git commit -m "feat(web): feature components from main (sidebar, agent form, etc.)"
-```
-
----
-
-### Task 4: Agent context provider
-
-**Files:**
-- Create: `src/web/src/contexts/agent-context.tsx`
-
-- [ ] Copy from main:
-
-```bash
-mkdir -p src/web/src/contexts
-cp temp/main/src/web/contexts/agent-context.tsx src/web/src/contexts/
-```
-
-- [ ] Adapt auth: main's context may use JWT token for API calls. With Better Auth, the session cookie is sent automatically — remove any manual Authorization header logic in `apiFetch` calls within this file.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/contexts/
-git commit -m "feat(web): agent context provider from main"
-```
-
----
-
-### Task 5: Root layout and app layout
-
-**Files:**
-- Create: `src/web/src/app/layout.tsx`
-- Create: `src/web/src/app/(app)/layout.tsx`
-
-- [ ] Copy from main:
-
-```bash
-mkdir -p src/web/src/app/\(app\)
-cp temp/main/src/web/app/layout.tsx src/web/src/app/
-cp temp/main/src/web/app/\(app\)/layout.tsx src/web/src/app/\(app\)/
-```
-
-- [ ] **Edit root `layout.tsx`:** Check for any auth-related imports. Main may import ThemeProvider and fonts — these should work as-is. If it imports from `sonner` or `streamdown`, ensure those deps are in `src/web/package.json`. Check spec-plans' package.json for the correct dependency list.
-
-- [ ] **Edit app `layout.tsx`:** Main's app layout likely has a JWT auth guard. Replace with Better Auth session check:
-
-```typescript
-import { getSession } from "@/lib/session"
-import { redirect } from "next/navigation"
-
-// In the layout component:
-const session = await getSession()
-if (!session) redirect("/sign-in")
-```
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/layout.tsx src/web/src/app/\(app\)/layout.tsx
-git commit -m "feat(web): root and app layouts from main"
-```
-
----
-
-### Task 6: Auth pages (new for Better Auth)
-
-**Files:**
-- Create: `src/web/src/app/(auth)/sign-in/page.tsx`
-- Create: `src/web/src/app/(auth)/sign-up/page.tsx`
-
-- [ ] Copy from spec-plans (these are Better Auth pages):
-
-```bash
-mkdir -p src/web/src/app/\(auth\)/sign-in src/web/src/app/\(auth\)/sign-up
-cp temp/spec-plans/src/web/src/app/\(auth\)/sign-in/page.tsx src/web/src/app/\(auth\)/sign-in/
-cp temp/spec-plans/src/web/src/app/\(auth\)/sign-up/page.tsx src/web/src/app/\(auth\)/sign-up/
-```
-
-These pages use `signIn`, `signUp` from `@/lib/auth-client` (Better Auth client).
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/\(auth\)/
-git commit -m "feat(web): sign-in and sign-up pages (Better Auth)"
-```
-
----
-
-### Task 7: App pages from main
-
-**Files:**
-- Create: `src/web/src/app/page.tsx` (root redirect)
-- Create: `src/web/src/app/(app)/home/page.tsx`
-- Create: `src/web/src/app/(app)/agents/page.tsx`
-- Create: `src/web/src/app/(app)/agents/[id]/page.tsx`
-- Create: `src/web/src/app/(app)/agents/new/page.tsx`
-- Create: `src/web/src/app/(app)/chat/[id]/page.tsx`
-- Create: `src/web/src/app/(app)/runtimes/page.tsx`
-
-- [ ] Copy from main:
-
-```bash
-cp temp/main/src/web/app/page.tsx src/web/src/app/
-
-mkdir -p src/web/src/app/\(app\)/home
-cp temp/main/src/web/app/\(app\)/home/page.tsx src/web/src/app/\(app\)/home/
-
-mkdir -p src/web/src/app/\(app\)/agents/\[id\] src/web/src/app/\(app\)/agents/new
-cp temp/main/src/web/app/\(app\)/agents/page.tsx src/web/src/app/\(app\)/agents/
-cp temp/main/src/web/app/\(app\)/agents/\[id\]/page.tsx src/web/src/app/\(app\)/agents/\[id\]/
-cp temp/main/src/web/app/\(app\)/agents/new/page.tsx src/web/src/app/\(app\)/agents/new/
-
-mkdir -p src/web/src/app/\(app\)/chat/\[id\]
-cp temp/main/src/web/app/\(app\)/chat/\[id\]/page.tsx src/web/src/app/\(app\)/chat/\[id\]/
-
-mkdir -p src/web/src/app/\(app\)/runtimes
-cp temp/main/src/web/app/\(app\)/runtimes/page.tsx src/web/src/app/\(app\)/runtimes/
-```
-
-- [ ] **Edit `page.tsx` (root):** Main's root page checks for JWT and redirects to `/home` or `/login`. Change `/login` to `/sign-in`. Use Better Auth session check:
-
-```typescript
-import { getSession } from "@/lib/session"
-import { redirect } from "next/navigation"
-
-export default async function Page() {
- const session = await getSession()
- if (session) redirect("/home")
- redirect("/sign-in")
-}
-```
-
-- [ ] **Review all app pages** for JWT/token references and replace with Better Auth patterns. Common changes:
- - `localStorage.getItem("token")` → remove (session cookie is automatic)
- - `/login` references → `/sign-in`
- - `useSession()` from custom hook → `useSession()` from `@/lib/auth-client`
-
-- [ ] Commit
-
-```bash
-git add src/web/src/app/
-git commit -m "feat(web): app pages from main (home, agents, chat, runtimes)"
-```
-
----
-
-### Task 8: WebSocket hooks from spec-plans
-
-**Files:**
-- Create: `src/web/src/lib/use-ws.ts`
-- Create: `src/web/src/lib/use-user-ws.ts`
-- Create: `src/web/src/hooks/use-mobile.ts` (if exists)
-
-- [ ] Copy WebSocket hooks from spec-plans:
-
-```bash
-cp temp/spec-plans/src/web/src/lib/use-ws.ts src/web/src/lib/
-cp temp/spec-plans/src/web/src/lib/use-user-ws.ts src/web/src/lib/
-mkdir -p src/web/src/hooks
-cp temp/spec-plans/src/web/src/hooks/use-mobile.ts src/web/src/hooks/ 2>/dev/null || true
-```
-
-These hooks connect to WS-DO for real-time notifications. They work as-is.
-
-- [ ] Commit
-
-```bash
-git add src/web/src/lib/use-ws.ts src/web/src/lib/use-user-ws.ts src/web/src/hooks/
-git commit -m "feat(web): WebSocket hooks from spec-plans"
-```
-
----
-
-### Task 9: Verify dependencies and fix missing packages
-
-- [ ] Check `src/web/package.json` has all dependencies needed by the frontend:
- - `sonner` (toasts) — add if missing
- - `streamdown` (markdown rendering in chat) — add if missing
- - `next-themes` (theme provider) — add if missing
- - `@base-ui/react` (UI primitives) — check if still used
- - `class-variance-authority`, `clsx`, `tailwind-merge`, `tw-animate-css` — shadcn deps
-
-Compare `temp/main/src/web/package.json` dependencies with `src/web/package.json`. Add any missing frontend dependencies.
-
-- [ ] Run `pnpm install` from project root to update lockfile
-- [ ] Commit
-
-```bash
-git add src/web/package.json pnpm-lock.yaml
-git commit -m "chore(web): add missing frontend dependencies"
-```
-
-**Exit criteria:** Frontend pages render. Auth flow uses Better Auth. WebSocket hooks available. All components resolve their imports.
diff --git a/docs/superpowers/specs/2026-04-10-cloudflare-migration-design.md b/docs/superpowers/specs/2026-04-10-cloudflare-migration-design.md
deleted file mode 100644
index 0de9390b8..000000000
--- a/docs/superpowers/specs/2026-04-10-cloudflare-migration-design.md
+++ /dev/null
@@ -1,270 +0,0 @@
-# Cloudflare Edge Migration — Design Spec
-
-> Migrate Alook from Node.js + PostgreSQL to Cloudflare Workers + D1 + R2 + Durable Objects.
-> Scope: Phases 0–3 (backend + frontend). Phase 4 (integration/deployment) deferred.
-
----
-
-## Sources
-
-- `docs/migration/00-06` — migration specs (the authority)
-- `temp/main/` — current production codebase (Node.js + PostgreSQL, 227 files)
-- `temp/spec-plans/` — Cloudflare edge reference implementation (167 files)
-
-## Strategy
-
-**Hybrid: copy unchanged, rewrite divergent.**
-
-Files from spec-plans that match the migration docs are copied as-is (configs, utils, wrangler files). Files where the docs diverge from spec-plans are rewritten (shared DB layer, email worker, web service API routes).
-
-## Scope
-
-| Phase | Description | Strategy |
-|-------|-------------|----------|
-| 0 | Monorepo scaffold, Turborepo, wrangler configs | Copy from spec-plans |
-| 1 | `@alook/shared` — schema, DB factory, queries, types, constants, schemas, utils | Rewrite: merge main's rich types/schemas with spec-plans' utils; new Drizzle D1 schema + query modules migrated from main |
-| 2a | Web Service — D1 + Better Auth + OpenNext + API routes + middleware + services | Hybrid: copy auth/config from spec-plans, rewrite API routes from main for D1 |
-| 2b | Email Worker — Cloudflare Worker for inbound email | Rewrite: Drizzle via shared, read-only D1, notify web service for writes |
-| 2c | WS-DO — Durable Objects for browser notifications | Copy + adapt: update token validation to session-only via shared queries |
-| 3 | Frontend — pages, components, contexts, CSS, client hooks | Copy from main, adapt auth (JWT->Better Auth), add WS hooks from spec-plans |
-
-**Out of scope:** Phase 4 (integration/CLI/deployment).
-
-## Key Divergences (spec-plans vs migration docs)
-
-These require rewriting rather than copying:
-
-1. **Shared DB layer** — spec-plans has no `db/` in shared. Docs move all Drizzle schema + query modules into `@alook/shared/db/`.
-2. **Email Worker** — spec-plans uses raw D1 + writes emails/events directly. Docs: Drizzle via shared, read-only D1, POST `/api/email/notify` to web service for writes.
-3. **WS-DO token validation** — spec-plans validates both runtime tokens and session tokens. Docs: session tokens only (browser-only WebSocket).
-4. **Web Service queries** — main has 11+ query modules in `src/web/lib/db/queries/`. These move to `@alook/shared/db/queries/` and convert from `pgTable` to `sqliteTable`.
-5. **Types/Constants** — main's shared has rich types + Zod schemas + API types. Spec-plans has simpler types. Docs follow main's model, extended with email/whitelist types.
-
----
-
-## Phase 0 — Infrastructure Setup
-
-Copy from spec-plans with minor adjustments:
-
-| File | Source | Notes |
-|------|--------|-------|
-| `package.json` | spec-plans | Add `cli` script from docs |
-| `pnpm-workspace.yaml` | spec-plans | As-is |
-| `turbo.json` | spec-plans | As-is |
-| `vitest.config.ts` | spec-plans | As-is |
-| `vitest.shared.ts` | spec-plans | As-is |
-| `.gitignore` | New | Combine spec-plans + main patterns |
-| `src/shared/` scaffold | spec-plans package.json + tsconfig + vitest config | Content populated in Phase 1 |
-| `src/cli/` scaffold | spec-plans package.json + tsconfig | Stub index.ts |
-| `src/web/` scaffold | spec-plans package.json + tsconfig + next.config + open-next + wrangler + postcss + components.json | Web config files from spec-plans |
-| `src/email-worker/` scaffold | spec-plans package.json + tsconfig + vitest + wrangler | Stub index.ts |
-| `src/ws-do/` scaffold | spec-plans package.json + tsconfig + wrangler | Stub index.ts |
-
-Exit: `pnpm install` succeeds. All packages resolve.
-
----
-
-## Phase 1 — Shared Library (`@alook/shared`)
-
-The foundation. All other phases depend on this.
-
-### Module structure
-
-```
-src/shared/
- src/
- index.ts — re-exports everything
- types.ts — from main (User, Workspace, Agent, etc.)
- api-types.ts — from main (ApiResponse, typed responses)
- constants.ts — from main (AgentStatus, RuntimeStatus, TaskStatus, MessageRole)
- schemas.ts — from main (Zod validation schemas for daemon API)
- db/
- index.ts — createDb(d1Binding) factory (NEW)
- schema.ts — Drizzle sqliteTable definitions (REWRITE from main's pgTable)
- queries/ — 12 query modules (MIGRATE from main's src/web/lib/db/queries/)
- user.ts
- workspace.ts
- member.ts
- agent.ts
- runtime.ts
- conversation.ts
- message.ts
- task.ts
- task-message.ts
- machine-token.ts
- whitelist.ts (NEW)
- email.ts (NEW)
- session.ts (NEW)
- utils/
- email.ts — from spec-plans (parseEmailHandle, toAlookAddress, isValidHandle)
- validation.ts — from spec-plans (isValidToken, isValidEmail)
- status.ts — from spec-plans (isOnline, formatStatus)
- test/ — from spec-plans (constants, utils tests)
- package.json — add drizzle-orm dependency (spec-plans version has no drizzle)
-```
-
-### Schema migration (pgTable to sqliteTable)
-
-Key type changes from main's PostgreSQL schema:
-- `uuid` PK with `defaultRandom()` -> `text` PK with nanoid
-- `timestamp` -> `text` with `DEFAULT (datetime('now'))`
-- `boolean` -> `integer` (0/1)
-- `jsonb` -> `text` (serialized JSON)
-- `pgTable` -> `sqliteTable`
-- Task claiming: `FOR UPDATE SKIP LOCKED` -> CAS-style `UPDATE ... WHERE status='queued'`
-
-### Tables (15 total)
-
-Better Auth managed (4): `user`, `session`, `account`, `verification`
-Application (11): `workspace`, `member`, `agent_runtime`, `agent`, `agent_whitelist`, `conversation`, `message`, `agent_task_queue`, `task_message`, `emails`, `machine_token`
-
-### Query module migration
-
-Each query module from `temp/main/src/web/lib/db/queries/*.ts` gets:
-1. Converted from PostgreSQL Drizzle to D1 Drizzle (sqliteTable references)
-2. Moved to `src/shared/db/queries/`
-3. Functions accept `db: Database` as first parameter (instead of importing global `db`)
-
-Exit: `@alook/shared` builds. Exports `createDb`, `schema`, `queries`, all types/schemas/constants/utils.
-
----
-
-## Phase 2a — Web Service
-
-### Copy from spec-plans (unchanged)
-- `wrangler.toml`, `next.config.ts`, `open-next.config.ts`, `cloudflare-env.d.ts`
-- `src/env.d.ts`, `postcss.config.mjs`, `components.json`
-- `src/lib/auth.ts`, `src/lib/auth-client.ts` (Better Auth setup)
-- `src/lib/session.ts` (server-side session helper)
-- `src/lib/broadcast.ts` (WS-DO notification helper)
-- `src/lib/storage.ts` (R2 email storage)
-- `src/lib/utils.ts` (cn utility)
-- `src/middleware.ts` (auth guard for dashboard routes)
-- `src/app/api/auth/[...all]/route.ts` (Better Auth catch-all)
-
-### Rewrite (adapted from main for D1)
-- `src/lib/dual-auth.ts` — use shared queries instead of raw D1
-- `src/lib/api/responses.ts` — from main (snake_case formatters)
-- `src/lib/middleware/*` — from main (workspace, request-id, logger, helpers)
-- `src/lib/services/task.ts` — from main, adapted for shared queries
-- `src/lib/errors.ts`, `src/lib/logger.ts` — from main
-- `src/lib/api.ts` — from main (client-side API wrapper, update auth for Better Auth)
-- All 37 API routes — from main, switch from local db import to shared queries
-- `src/app/api/email/notify/route.ts` — new endpoint per migration docs
-- `src/app/api/ws/token/route.ts` — from spec-plans
-- D1 migration SQL file (`migrations/0001_schema.sql`)
-- `drizzle.config.ts` pointing to `@alook/shared` schema
-
-Exit: Web service compiles. API routes resolve against shared imports. D1 migration applies.
-
----
-
-## Phase 2b — Email Worker
-
-**Full rewrite** per migration docs. Spec-plans code used as structural reference only.
-
-Changes from spec-plans:
-- Import `createDb`, `queries` from `@alook/shared` (Drizzle, not raw D1)
-- Read-only D1: agent lookup + whitelist check via shared queries
-- No direct email/event writes — POST `/api/email/notify` to web service
-- Web service handles: email record creation, task creation, WS-DO broadcast
-
-Files:
-- `src/index.ts` — email handler + /simulate endpoint
-- `src/index.test.ts` — adapted tests (mock Drizzle DB, verify notify payload)
-- `src/__mocks__/cf.ts` — updated mocks
-
-Exit: Email worker compiles, tests pass.
-
----
-
-## Phase 2c — WS-DO
-
-**Copy + adapt** from spec-plans. Minimal changes.
-
-Changes from spec-plans:
-- Token validation: session tokens only (remove runtime token validation)
-- Use `queries.session.getValidSession` from `@alook/shared` instead of raw D1
-- Remove agent channel broadcasts (user channels only per docs)
-- Simplify index.ts routing (remove `/broadcast/:agentId` — only `/broadcast/user/:userId`)
-
-Files:
-- `src/index.ts` — worker entry (simplified routing)
-- `src/ws-durable.ts` — Durable Object (session-only auth)
-- `src/env.d.ts`
-
-Exit: WS-DO compiles.
-
----
-
-## Phase 3 — Frontend (Pages + Components)
-
-**Copy from main**, adapt auth references (JWT -> Better Auth), add WebSocket hooks from spec-plans.
-
-### Copy from main (adapt imports)
-
-**Layouts:**
-- `app/layout.tsx` — root layout (fonts, ThemeProvider, ToasterProvider)
-- `app/(app)/layout.tsx` — app shell (auth guard, sidebar, AgentProvider)
-
-**Pages:**
-- `app/page.tsx` — root redirect (session check -> `/home` or `/sign-in`)
-- `app/(app)/home/page.tsx` — redirect to first agent
-- `app/(app)/agents/page.tsx` — redirect to `/home`
-- `app/(app)/agents/[id]/page.tsx` — agent detail
-- `app/(app)/agents/new/page.tsx` — create agent form
-- `app/(app)/chat/[id]/page.tsx` — chat UI
-- `app/(app)/runtimes/page.tsx` — machine/runtime list
-
-**Auth pages (rewrite for Better Auth):**
-- `app/(auth)/sign-in/page.tsx` — email/password + OAuth (replaces main's `app/login/page.tsx` OTP flow)
-- `app/(auth)/sign-up/page.tsx` — registration (new, Better Auth)
-
-**Components (copy as-is):**
-- `components/app-sidebar.tsx` — narrow sidebar with agent list (update signOut to Better Auth)
-- `components/agent-edit-form.tsx` — agent create/edit form
-- `components/runtime-select.tsx` — runtime picker
-- `components/dashboard-navbar.tsx`, `components/gradient-background.tsx`, `components/logo.tsx`
-- `components/theme-provider.tsx`, `components/theme-toggle.tsx`, `components/toaster-provider.tsx`
-- `components/ui/*` — all UI primitives (button, input, textarea, label, badge, card, dialog, confirm-dialog, select, sheet, scroll-area, separator, avatar)
-- Remove `components/ui/input-otp.tsx` (OTP no longer needed)
-
-**Context:**
-- `contexts/agent-context.tsx` — global agent/runtime state (update API calls for new auth)
-
-**CSS:**
-- `app/globals.css`
-
-### Add from spec-plans (new)
-- `src/lib/use-ws.ts` — agent WebSocket hook
-- `src/lib/use-user-ws.ts` — user WebSocket hook
-- `src/hooks/use-mobile.ts` — if exists in spec-plans
-
-### Adaptation notes
-
-| Main pattern | Target change |
-|-------------|---------------|
-| `import { verifyJWT } from "@/lib/auth/jwt"` | Remove — server pages use `getSession()` from `@/lib/session` |
-| localStorage JWT token | Better Auth session cookie (automatic) |
-| `apiFetch` with Bearer JWT header | `apiFetch` with cookie auth (remove Authorization header for browser) |
-| `useSession` (custom) | `useSession` from `better-auth/react` via `@/lib/auth-client` |
-| `signOut` (clear localStorage) | `signOut` from `better-auth/react` |
-| `/login` route | `/sign-in` and `/sign-up` routes |
-| No WebSocket | Add `useUserWs` hook for real-time notifications |
-
-Exit: Frontend pages render. Auth flow works with Better Auth. WebSocket hooks available.
-
----
-
-## Execution Plan
-
-```
-Phase 0 ──── single agent, fast scaffold
-Phase 1 ──── single agent, careful migration of schema + queries
-Phase 2a ─┐
-Phase 2b ─┼─ 3 parallel subagents
-Phase 2c ─┘
-Phase 3 ──── single agent (depends on 2a + 2c)
-```
-
-Commits at natural stopping points. No strict granularity.