Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
docs: add implementation plans (6 phases)
Gener1674ccb80146
diff --git a/docs/superpowers/plans/plan-00-index.md b/docs/superpowers/plans/plan-00-index.mdnew file mode 100644index 000000000..439a52fe8--- /dev/null+++ b/docs/superpowers/plans/plan-00-index.md@@ -0,0 +1,51 @@+# 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.mdnew file mode 100644index 000000000..6fb323b8e--- /dev/null+++ b/docs/superpowers/plans/plan-01-phase0-infra.md@@ -0,0 +1,256 @@+# 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.mdnew file mode 100644index 000000000..7cc91b8ae--- /dev/null+++ b/docs/superpowers/plans/plan-02-phase1-shared.md@@ -0,0 +1,461 @@+# 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.mdnew file mode 100644index 000000000..b699b1972--- /dev/null+++ b/docs/superpowers/plans/plan-03-phase2a-web.md@@ -0,0 +1,447 @@+# 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.mdnew file mode 100644index 000000000..3fc14412c--- /dev/null+++ b/docs/superpowers/plans/plan-04-phase2b-email.md@@ -0,0 +1,248 @@+# 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.mdnew file mode 100644index 000000000..d8e298635--- /dev/null+++ b/docs/superpowers/plans/plan-05-phase2c-wsdo.md@@ -0,0 +1,169 @@+# 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.mdnew file mode 100644index 000000000..84179f66b--- /dev/null+++ b/docs/superpowers/plans/plan-06-phase3-frontend.md@@ -0,0 +1,305 @@+# 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.