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
chore: remove legacy PostgreSQL code, add GitHub templates
Genera3f8725d3f87
diff --git a/.github/.git_commit_template.txt b/.github/.git_commit_template.txtnew file mode 100644index 000000000..f98a49027--- /dev/null+++ b/.github/.git_commit_template.txt@@ -0,0 +1,20 @@+# TYPE(SCOPE): DESCRIPTION+#+# TYPE: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert+# SCOPE: shared, web, cli, email-worker, ws-do, deps, config+#+# Examples:+# feat(web): add agent creation page+# fix(cli): resolve auth token refresh race condition+# chore(deps): update dependencies+#+# The first line is the subject (required).+# Leave a blank line before the body for more details.+#+# Body (optional):+# - Explain what and why vs. how+# - Reference issues: Closes #123+#+# Footer (optional):+# BREAKING CHANGE: description+diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSnew file mode 100644index 000000000..5fb7c8da0--- /dev/null+++ b/.github/CODEOWNERS@@ -0,0 +1,5 @@+# Default owners for the entire repository+* @alookai/core-dev++# CI/CD workflows require review+.github/ @alookai/core-devdiff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.mdnew file mode 100644index 000000000..8ef4df8e2--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.md@@ -0,0 +1,30 @@+---+name: Bug Report+about: Report a bug to help us improve+title: "[Bug]: "+labels: bug+assignees: ''+---++## Describe the Bug+A clear description of what the bug is.++## To Reproduce+1. ...+2. ...++## Expected Behavior+What you expected to happen.++## Environment+- **Package**: [e.g., @alook/web, @alook/cli]+- **OS**: [e.g., macOS, Ubuntu]+- **Node Version**: [e.g., 20.x]++## Error / Logs+```+Paste error output here+```++## Additional Context+Any other relevant info.diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 000000000..3ba13e0ce--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1 @@+blank_issues_enabled: falsediff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.mdnew file mode 100644index 000000000..6011c22b1--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.md@@ -0,0 +1,21 @@+---+name: Feature Request+about: Suggest a new feature or improvement+title: "[Feature]: "+labels: enhancement+assignees: ''+---++## Description+A clear description of what you want to happen.++## Impact Area+- [ ] Shared library (`@alook/shared`)+- [ ] Web app (`@alook/web`)+- [ ] CLI (`@alook/cli`)+- [ ] Email Worker (`@alook/email-worker`)+- [ ] WebSocket DO (`@alook/ws-do`)+- [ ] Other: ...++## Additional Context+Any mockups, examples, or references.diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 000000000..4b6fc0fce--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,19 @@+# Why we need this PR?+> Closes #++## What changed+...++## Checklist+- [ ] Tests added/updated as needed+- [ ] All CI checks pass+- [ ] PR targets the correct branch++## Impact Areas+- [ ] Shared library (`@alook/shared`)+- [ ] Web app (`@alook/web`)+- [ ] CLI (`@alook/cli`)+- [ ] Email Worker (`@alook/email-worker`)+- [ ] WebSocket DO (`@alook/ws-do`)+- [ ] CI/CD+- [ ] Other: ...diff --git a/.github/dependabot.yml b/.github/dependabot.ymlnew file mode 100644index 000000000..a1063c075--- /dev/null+++ b/.github/dependabot.yml@@ -0,0 +1,110 @@+version: 2+updates:+ - package-ecosystem: "npm"+ directory: "/"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"+ ignore:+ - dependency-name: "*"+ update-types: ["version-update:semver-major"]++ - package-ecosystem: "npm"+ directory: "/src/shared"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"+ ignore:+ - dependency-name: "*"+ update-types: ["version-update:semver-major"]++ - package-ecosystem: "npm"+ directory: "/src/web"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"+ ignore:+ - dependency-name: "*"+ update-types: ["version-update:semver-major"]++ - package-ecosystem: "npm"+ directory: "/src/cli"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"+ ignore:+ - dependency-name: "*"+ update-types: ["version-update:semver-major"]++ - package-ecosystem: "npm"+ directory: "/src/email-worker"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"+ ignore:+ - dependency-name: "*"+ update-types: ["version-update:semver-major"]++ - package-ecosystem: "npm"+ directory: "/src/ws-do"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"+ ignore:+ - dependency-name: "*"+ update-types: ["version-update:semver-major"]++ - package-ecosystem: "github-actions"+ directory: "/"+ schedule:+ interval: "weekly"+ open-pull-requests-limit: 5+ target-branch: "main"+ commit-message:+ prefix: "chore(deps):"+ groups:+ dependencies:+ patterns:+ - "*"diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5a2690ee9..a69c28caf 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -14,71 +14,41 @@ jobs:quality:name: Typecheck & Lintruns-on: ubuntu-latest+ timeout-minutes: 10steps:- uses: actions/checkout@v4- uses: pnpm/action-setup@v4- uses: actions/setup-node@v4with:- node-version: 20+ node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - run: pnpm tsc -b src/shared- - run: pnpm tsc --noEmit -p src/web/tsconfig.json- - run: pnpm tsc --noEmit -p src/cli/tsconfig.json- - run: cd src/web && pnpm eslint- - run: cd src/cli && pnpm eslint+ - run: pnpm typechecktest:name: Testsruns-on: ubuntu-latest- services:- postgres:- image: postgres:17- env:- POSTGRES_USER: postgres- POSTGRES_PASSWORD: postgres- POSTGRES_DB: alook- ports:- - 5432:5432- options: >-- --health-cmd "pg_isready -U postgres"- --health-interval 10s- --health-timeout 5s- --health-retries 5+ timeout-minutes: 10steps:- uses: actions/checkout@v4- uses: pnpm/action-setup@v4- uses: actions/setup-node@v4with:- node-version: 20+ node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - name: Unit tests- run: pnpm vitest run- - name: Create test database and push schema- env:- PGUSER: postgres- PGPASSWORD: postgres- PGHOST: localhost- PGPORT: "5432"- run: |- psql "postgres://postgres:postgres@localhost:5432/postgres" -c "CREATE DATABASE alook_test;"- cd src/web && DATABASE_URL="postgres://postgres:postgres@localhost:5432/alook_test?sslmode=disable" pnpm drizzle-kit push --force- - name: Integration tests- env:- DATABASE_URL: postgres://postgres:postgres@localhost:5432/alook_test?sslmode=disable- run: pnpm vitest run --config vitest.integration.config.ts+ - run: pnpm testbuild:name: Buildruns-on: ubuntu-latest+ timeout-minutes: 10steps:- uses: actions/checkout@v4- uses: pnpm/action-setup@v4- uses: actions/setup-node@v4with:- node-version: 20+ node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - run: cd src/web && pnpm build- - run: cd src/cli && pnpm build+ - run: pnpm builddiff --git a/.github/workflows/lint-workflows.yaml b/.github/workflows/lint-workflows.yamlnew file mode 100644index 000000000..be30af48e--- /dev/null+++ b/.github/workflows/lint-workflows.yaml@@ -0,0 +1,14 @@+name: Lint Workflows++on:+ pull_request:+ paths:+ - ".github/workflows/**"++jobs:+ actionlint:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v4+ - uses: raven-actions/actionlint@v2diff --git a/AGENTS.md b/AGENTS.mdindex 5a5b08f05..ef5c71120 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -2,9 +2,12 @@Alook's main purpose is to make the cli agent always on, and give it a email address.## Navigation-- `plans/`: place your dev plans-- `src/web`: landing page + user dashboard-- `src/cli`: cli + daemon+- `plans/`: place your dev plans (gitignored, local only)+- `src/shared`: shared types, schema, queries, validators+- `src/web`: Next.js app on Cloudflare Workers (D1 + R2)+- `src/cli`: CLI + daemon+- `src/email-worker`: inbound email Cloudflare Worker+- `src/ws-do`: WebSocket Durable Object worker## Plan-driven Development- You must make a markdown plan at `plans/` before you implement any my request, otherwise I will reject your implementation.@@ -23,49 +26,30 @@ Alook's main purpose is to make the cli agent always on, and give it a email add## Don't use plan MODE, try to write the plan md directly-## Database Queries — No Raw SQL+## Database — Cloudflare D1 (SQLite) + Drizzle ORM-Use Drizzle ORM operators for all queries. **Never use `sql` template literals** unless there is no ORM equivalent (atomic increment, upsert `excluded.*` references).--**Why:** Drizzle aliases tables internally (e.g. `conversation` → `t0`). Raw SQL like `` sql`"conversation"."id"` `` breaks silently because the alias doesn't match, returning wrong results with no error.+Schema lives in `src/shared/src/schema.ts` using `sqliteTable` from `drizzle-orm/sqlite-core`.+Queries use the shared query modules in `src/shared/src/queries/`.-### Bad — raw SQL-```ts-// Broken: Drizzle may alias the table, subquery returns 0-sql`(SELECT count(*) FROM message WHERE message.conversation_id = ${conversation.id})`+Use Drizzle ORM operators for all queries. **Never use `sql` template literals** unless there is no ORM equivalent (atomic increment, upsert `excluded.*` references).-// Broken: hardcoded table name won't match Drizzle alias-sql`${agentRuntime.lastSeenAt} < now() - interval '45 seconds'`--// Broken: no type safety, typos fail silently at runtime-sql`${verificationCode.expiresAt} > now()`-```+**Why:** Drizzle aliases tables internally. Raw SQL with hardcoded table/column names breaks silently.### Good — ORM operators```ts-// Use leftJoin + count for aggregations+// Aggregationsdb.select({ messageCount: count(message.id) }).from(conversation).leftJoin(message, eq(message.conversationId, conversation.id)).groupBy(conversation.id)-// Use lt/gt with Date objects for timestamp comparisons-const threshold = new Date(Date.now() - 45 * 1000);-lt(agentRuntime.lastSeenAt, threshold)--// Use gt/lt for value comparisons-gt(verificationCode.expiresAt, new Date())+// Comparisons with ISO strings (D1 stores timestamps as TEXT)+gt(verificationCode.expiresAt, new Date().toISOString())lt(verificationCode.attempts, 5)-// Use isNull/isNotNull instead of IS NULL+// Null checksisNull(agentRuntime.lastSeenAt)isNotNull(agentTaskQueue.sessionId)--// Use count() instead of COUNT(*)-db.select({ value: count() }).from(table).where(...)--// Use new Date() instead of sql`now()`-.set({ updatedAt: new Date() })```### Acceptable exceptionsdiff --git a/Dockerfile b/Dockerfiledeleted file mode 100644index 57d578b38..000000000--- a/Dockerfile+++ /dev/null@@ -1,30 +0,0 @@-# Stage 1: Build-FROM node:22-alpine AS builder--WORKDIR /app--RUN corepack enable && corepack prepare pnpm@latest --activate--COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./-COPY src/shared/package.json src/shared/-COPY src/web/package.json src/web/--RUN pnpm install --frozen-lockfile--COPY src/shared/ src/shared/-COPY src/web/ src/web/--RUN cd src/web && pnpm build--# Stage 2: Runtime-FROM node:22-alpine--WORKDIR /app--COPY --from=builder /app/src/web/.next/standalone ./-COPY --from=builder /app/src/web/.next/static src/web/.next/static-COPY --from=builder /app/src/web/public src/web/public--EXPOSE 3000--ENTRYPOINT ["node", "src/web/server.js"]diff --git a/Makefile b/Makefiledeleted file mode 100644index 49a40f81a..000000000--- a/Makefile+++ /dev/null@@ -1,59 +0,0 @@-.PHONY: setup start stop build test test-unit test-integration typecheck check daemon cli migrate-up migrate-down db-up db-down--setup: ## First-time setup- pnpm install- docker compose up -d postgres- @echo "Waiting for PostgreSQL to be ready..."- @until docker compose exec postgres pg_isready -U postgres > /dev/null 2>&1; do sleep 1; done- cd src/web && pnpm drizzle-kit push--start: ## Start everything (DB + schema + Next.js dev server)- -lsof -ti:3000 | xargs kill 2>/dev/null- docker compose up -d postgres- @echo "Waiting for PostgreSQL to be ready..."- @until docker compose exec postgres pg_isready -U postgres > /dev/null 2>&1; do sleep 1; done- cd src/web && pnpm drizzle-kit push- cd src/web && exec pnpm dev--stop: ## Kill dev server- -lsof -ti:3000 | xargs kill 2>/dev/null--build: ## Build Next.js + CLI- cd src/web && pnpm build- cd src/cli && pnpm build--test-unit: ## Run unit tests only (no DB required)- pnpm vitest run--test: test-unit test-integration ## Run all tests--typecheck: ## TypeScript type check- pnpm tsc -b src/shared- pnpm tsc --noEmit -p src/web/tsconfig.json- pnpm tsc --noEmit -p src/cli/tsconfig.json- cd src/web && pnpm eslint- cd src/cli && pnpm eslint--test-integration: ## Run integration tests (requires PostgreSQL)- bash scripts/setup-test-db.sh- pnpm vitest run --config vitest.integration.config.ts--check: typecheck build test ## CI gate--daemon: ## Start local daemon- cd src/cli && pnpm tsx src/index.ts daemon start --foreground--cli: ## Run CLI commands (e.g. make cli ARGS="agent list")- cd src/cli && pnpm tsx src/index.ts $(ARGS)--migrate-up: ## Run Drizzle migrations- cd src/web && pnpm drizzle-kit push--migrate-down: ## Generate migration SQL- cd src/web && pnpm drizzle-kit drop--db-up: ## Start PostgreSQL container- docker compose up -d postgres--db-down: ## Stop PostgreSQL container and remove volumes- docker compose down -v postgresdiff --git a/README.md b/README.mdindex e6f1da137..ff1d4cb68 100644--- a/README.md+++ b/README.md@@ -5,66 +5,45 @@ A stripped-down AI agent task execution platform. Chat with AI agents (Claude Co## Architecture```-Browser → Next.js (port 3000, API routes + frontend) → PostgreSQL- ↑- Daemon (polls for tasks, runs agent CLIs)+Browser → Next.js on Cloudflare Workers (D1 + R2) ← CLI Daemon+ ↕ ↕+ Email Worker (inbound) WebSocket DO (realtime)```| Package | Description ||---------|-------------|-| `src/web` | Next.js App Router — frontend pages + API routes, Drizzle ORM |+| `src/shared` | Shared types, D1 schema, query modules, validators (`@alook/shared`) |+| `src/web` | Next.js App Router on Cloudflare Workers — frontend + API routes || `src/cli` | Commander.js CLI + daemon that spawns agent subprocesses |-| `src/shared` | Shared types and constants (`@alook/shared`) |+| `src/email-worker` | Cloudflare Worker for inbound email handling |+| `src/ws-do` | Cloudflare Durable Object for WebSocket connections |## Quick Start```bash-make setup # Install deps, start Postgres, run migrations-make start # Start Next.js dev server (port 3000)-make daemon # In another terminal — registers runtimes, polls for tasks+pnpm install # Install deps+pnpm dev # Start dev servers (web + email-worker)+pnpm dev:cli # In another terminal — start CLI daemon```-Dev OTP code: `888888`-## Commands```bash-make setup # First-time setup-make start # Next.js dev server-make stop # Kill dev server-make daemon # Start local daemon-make build # Build web + CLI-make test # Run tests (vitest)-make typecheck # TypeScript check-make check # CI gate: typecheck + build + test-make migrate-up # Push Drizzle schema-make db-up # Start Postgres container-make db-down # Stop Postgres container+pnpm dev # Start all dev servers+pnpm dev:web # Web dev server only+pnpm dev:cli # CLI dev mode+pnpm dev:email # Email worker dev server+pnpm build # Build web + CLI+pnpm test # Run all tests (turbo)+pnpm typecheck # TypeScript check (turbo)+pnpm db:migrate # Apply D1 migrations locally+pnpm db:reset # Reset local D1 and re-apply migrations```-## CLI--```bash-make cli ARGS="register --token <machine-token>"-make cli ARGS="status"-make cli ARGS="agent list"-make cli ARGS="config show"-make cli ARGS="daemon start --foreground"-```--## Environment--| Variable | Default | Description |-|----------|---------|-------------|-| `DATABASE_URL` | `postgres://...localhost:5432/alook` | PostgreSQL connection |-| `JWT_SECRET` | `alook-dev-secret-change-in-production` | JWT signing key |-| `APP_ENV` | — | Set `production` for real emails |-| `RESEND_API_KEY` | — | Resend key; unset = OTP logged to console |-## How It Works1. Daemon detects installed agent CLIs (`claude`, `codex`, `opencode`) and registers runtimes with the server2. Create an agent in the UI and link it to a runtime3. Send a message in a conversation — server enqueues a task4. Daemon claims the task, runs the agent CLI, streams results back-5. Frontend polls for progress and displays output in real-time+5. Frontend receives updates via WebSocket and displays output in real-timediff --git a/docker-compose.yml b/docker-compose.ymldeleted file mode 100644index 15e1343ed..000000000--- a/docker-compose.yml+++ /dev/null@@ -1,14 +0,0 @@-services:- postgres:- image: postgres:17- ports:- - "5432:5432"- environment:- POSTGRES_USER: postgres- POSTGRES_PASSWORD: postgres- POSTGRES_DB: alook- volumes:- - pgdata:/var/lib/postgresql/data--volumes:- pgdata:diff --git a/scripts/setup-test-db.sh b/scripts/setup-test-db.shdeleted file mode 100755index 04a70cb83..000000000--- a/scripts/setup-test-db.sh+++ /dev/null@@ -1,33 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--# Idempotent test DB setup: ensures alook_test exists and schema is current.-# Uses docker compose exec to run commands inside the postgres container,-# so no local pg client tools are required.--PGUSER="${PGUSER:-postgres}"-PGPASSWORD="${PGPASSWORD:-postgres}"-PGHOST="${PGHOST:-localhost}"-PGPORT="${PGPORT:-5432}"-TEST_DB="alook_test"--echo "Waiting for PostgreSQL to be ready..."-until docker compose exec postgres pg_isready -U "$PGUSER" -q 2>/dev/null; do- sleep 1-done-echo "PostgreSQL is ready."--# Create test database if it doesn't exist-if ! docker compose exec postgres psql -U "$PGUSER" -lqt | cut -d \| -f 1 | grep -qw "$TEST_DB"; then- echo "Creating database $TEST_DB..."- docker compose exec postgres createdb -U "$PGUSER" "$TEST_DB"-else- echo "Database $TEST_DB already exists."-fi--# Push schema to test database-echo "Pushing Drizzle schema to $TEST_DB..."-cd src/web && DATABASE_URL="postgres://$PGUSER:$PGPASSWORD@$PGHOST:$PGPORT/$TEST_DB?sslmode=disable" \- pnpm drizzle-kit push --force--echo "Test database setup complete."diff --git a/src/web/app/api/agents/[id]/conversations/route.test.ts b/src/web/app/api/agents/[id]/conversations/route.test.tsdeleted file mode 100644index 142605e82..000000000--- a/src/web/app/api/agents/[id]/conversations/route.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/agent");-vi.mock("@/lib/db/queries/conversation");-vi.mock("@/lib/api/responses", () => ({- conversationToResponse: vi.fn((c: any) => ({- id: c.id,- agent_id: c.agentId,- title: c.title,- message_count: c.messageCount,- })),-}));--import { getAgentInWorkspace } from "@/lib/db/queries/agent";-import { listConversationsByAgent } from "@/lib/db/queries/conversation";--const mockGetAgent = vi.mocked(getAgentInWorkspace);-const mockListConvs = vi.mocked(listConversationsByAgent);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]/conversations", () => {- it("returns 200 with filtered conversations", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" } as any);- mockListConvs.mockResolvedValue([- { id: "c1", agentId: "a1", title: "Fix auth", messageCount: 5, createdAt: new Date() },- { id: "c2", agentId: "a1", title: "", messageCount: 0, createdAt: new Date() },- ] as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/agents/a1/conversations"),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(2);- expect(body[0].message_count).toBe(5);- expect(body[1].message_count).toBe(0);- });-- it("returns 404 for non-existent agent", async () => {- mockGetAgent.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/agents/nope/conversations"),- { params: Promise.resolve({ id: "nope" }) },- );- expect(res.status).toBe(404);- });-- it("returns empty array for agent with no conversations", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" } as any);- mockListConvs.mockResolvedValue([]);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/agents/a1/conversations"),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toEqual([]);- });-});diff --git a/src/web/app/api/agents/[id]/conversations/route.ts b/src/web/app/api/agents/[id]/conversations/route.tsdeleted file mode 100644index 4762205c5..000000000--- a/src/web/app/api/agents/[id]/conversations/route.ts+++ /dev/null@@ -1,31 +0,0 @@-import { db } from "@/lib/db";-import { getAgentInWorkspace } from "@/lib/db/queries/agent";-import { listConversationsByAgent } from "@/lib/db/queries/conversation";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const agent = await getAgentInWorkspace(db, id, ws.workspaceId);- if (!agent) {- return writeError("agent not found", 404);- }-- const conversations = await listConversationsByAgent(- db,- ws.workspaceId,- ctx.userId,- id- );-- return writeJSON(conversations.map(conversationToResponse));-});diff --git a/src/web/app/api/agents/[id]/route.test.ts b/src/web/app/api/agents/[id]/route.test.tsdeleted file mode 100644index 103de099b..000000000--- a/src/web/app/api/agents/[id]/route.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/agent");-vi.mock("@/lib/api/responses", () => ({- agentToResponse: vi.fn((a: any) => ({ id: a.id })),-}));--import { getAgentInWorkspace, deleteAgent, updateAgent } from "@/lib/db/queries/agent";-const mockGet = vi.mocked(getAgentInWorkspace);-const mockDelete = vi.mocked(deleteAgent);-const mockUpdate = vi.mocked(updateAgent);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]", () => {- it("returns agent", async () => {- mockGet.mockResolvedValue({ id: "a1" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/agents/a1?workspace_id=w1"),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(200);- });-- it("returns 404 when not found", async () => {- mockGet.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/agents/a1?workspace_id=w1"),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(404);- });-});--describe("DELETE /api/agents/[id]", () => {- it("returns 204 on successful deletion", async () => {- mockDelete.mockResolvedValue({ id: "a1" } as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" }),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(204);- expect(mockDelete).toHaveBeenCalledWith({}, "a1", "w1");- });-- it("returns 404 for non-existent agent", async () => {- mockDelete.mockResolvedValue(null as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/agents/nope", { method: "DELETE" }),- { params: Promise.resolve({ id: "nope" }) },- );- expect(res.status).toBe(404);- const body = await res.json();- expect(body.error).toBe("agent not found");- });-});--describe("PATCH /api/agents/[id]", () => {- it("updates agent and returns response", async () => {- mockUpdate.mockResolvedValue({ id: "a1", name: "Updated" } as any);- const { PATCH } = await import("./route");- const res = await PATCH(- new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ name: "Updated" }),- }),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "a1", "w1", { name: "Updated" });- });-- it("returns 404 for non-existent agent", async () => {- mockUpdate.mockResolvedValue(null as any);- const { PATCH } = await import("./route");- const res = await PATCH(- new NextRequest("http://localhost/api/agents/nope", {- method: "PATCH",- body: JSON.stringify({ name: "X" }),- }),- { params: Promise.resolve({ id: "nope" }) },- );- expect(res.status).toBe(404);- });-- it("returns 400 when no fields provided", async () => {- const { PATCH } = await import("./route");- const res = await PATCH(- new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({}),- }),- { params: Promise.resolve({ id: "a1" }) },- );- expect(res.status).toBe(400);- });-});diff --git a/src/web/app/api/agents/[id]/route.ts b/src/web/app/api/agents/[id]/route.tsdeleted file mode 100644index f8780f60d..000000000--- a/src/web/app/api/agents/[id]/route.ts+++ /dev/null@@ -1,74 +0,0 @@-import { db } from "@/lib/db";-import { getAgentInWorkspace, deleteAgent, updateAgent } from "@/lib/db/queries/agent";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { agentToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const agent = await getAgentInWorkspace(db, id, ws.workspaceId);- if (!agent) {- return writeError("agent not found", 404);- }-- return writeJSON(agentToResponse(agent));-});--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- let body: Record<string, unknown>;- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const data: Record<string, unknown> = {};- if (typeof body.name === "string") data.name = body.name;- if (typeof body.description === "string") data.description = body.description;- if (typeof body.instructions === "string") data.instructions = body.instructions;- if (typeof body.runtime_id === "string") data.runtimeId = body.runtime_id;-- if (Object.keys(data).length === 0) {- return writeError("no fields to update", 400);- }-- const updated = await updateAgent(db, id, ws.workspaceId, data as { name?: string; description?: string; instructions?: string; runtimeId?: string });- if (!updated) {- return writeError("agent not found", 404);- }-- return writeJSON(agentToResponse(updated));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const deleted = await deleteAgent(db, id, ws.workspaceId);- if (!deleted) {- return writeError("agent not found", 404);- }-- return new Response(null, { status: 204 });-});diff --git a/src/web/app/api/agents/route.test.ts b/src/web/app/api/agents/route.test.tsdeleted file mode 100644index 72eab4db5..000000000--- a/src/web/app/api/agents/route.test.ts+++ /dev/null@@ -1,82 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/agent");-vi.mock("@/lib/db/queries/runtime");-vi.mock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- reconcileAgentStatus: vi.fn(),- })),-}));-vi.mock("@/lib/api/responses", () => ({- agentToResponse: vi.fn((a: any) => ({ id: a.id, name: a.name })),-}));--import { listAgents, createAgent, getAgentInWorkspace } from "@/lib/db/queries/agent";-import { getAgentRuntimeForWorkspace } from "@/lib/db/queries/runtime";--const mockList = vi.mocked(listAgents);-const mockCreate = vi.mocked(createAgent);-const mockGetRuntime = vi.mocked(getAgentRuntimeForWorkspace);-const mockGetAgent = vi.mocked(getAgentInWorkspace);--beforeEach(() => vi.clearAllMocks());--function makeReq(body?: unknown) {- const opts: any = { method: body ? "POST" : "GET" };- if (body) {- opts.headers = { "Content-Type": "application/json" };- opts.body = JSON.stringify(body);- }- return new NextRequest("http://localhost/api/agents?workspace_id=w1", opts);-}--describe("GET /api/agents", () => {- it("lists agents in workspace", async () => {- mockList.mockResolvedValue([{ id: "a1", name: "Bot" }] as any);- const { GET } = await import("./route");- const res = await GET(makeReq());- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(1);- });-});--describe("POST /api/agents", () => {- it("creates agent with valid input", async () => {- mockGetRuntime.mockResolvedValue({ id: "rt1", runtimeMode: "local", status: "offline" } as any);- mockCreate.mockResolvedValue({ id: "a1", name: "Bot" } as any);- const { POST } = await import("./route");- const res = await POST(makeReq({ name: "Bot", runtime_id: "rt1" }));- expect(res.status).toBe(201);- });-- it("returns 400 for missing name", async () => {- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_id: "rt1" }));- expect(res.status).toBe(400);- });-- it("returns 400 for missing runtime_id", async () => {- const { POST } = await import("./route");- const res = await POST(makeReq({ name: "Bot" }));- expect(res.status).toBe(400);- });-- it("returns 404 when runtime not in workspace", async () => {- mockGetRuntime.mockResolvedValue(null as any);- const { POST } = await import("./route");- const res = await POST(makeReq({ name: "Bot", runtime_id: "rt-bad" }));- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/agents/route.ts b/src/web/app/api/agents/route.tsdeleted file mode 100644index 6c3849afa..000000000--- a/src/web/app/api/agents/route.ts+++ /dev/null@@ -1,88 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- listAgents,- createAgent,- getAgentInWorkspace,-} from "@/lib/db/queries/agent";-import { getAgentRuntimeForWorkspace } from "@/lib/db/queries/runtime";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { agentToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const agents = await listAgents(db, ws.workspaceId);- return writeJSON(agents.map(agentToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let body: {- name?: string;- description?: string;- instructions?: string;- runtime_id?: string;- runtime_config?: unknown;- max_concurrent_tasks?: number;- };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const name = (body.name || "").trim();- if (!name) {- return writeError("name is required", 400);- }-- const runtimeId = body.runtime_id || "";- if (!runtimeId) {- return writeError("runtime_id is required", 400);- }-- let maxConcurrentTasks = body.max_concurrent_tasks || 0;- if (maxConcurrentTasks <= 0) maxConcurrentTasks = 6;-- const runtime = await getAgentRuntimeForWorkspace(- db,- runtimeId,- ws.workspaceId- );- if (!runtime) {- return writeError("runtime not found in workspace", 404);- }-- const newAgent = await createAgent(db, {- workspaceId: ws.workspaceId,- name,- description: body.description || "",- instructions: body.instructions || "",- runtimeId,- runtimeMode: runtime.runtimeMode,- runtimeConfig: body.runtime_config ?? null,- visibility: "private",- maxConcurrentTasks,- ownerId: ctx.userId,- });-- if (runtime.status === "online") {- const taskService = new TaskService(db);- await taskService.reconcileAgentStatus(newAgent.id);- const updated = await getAgentInWorkspace(- db,- newAgent.id,- ws.workspaceId- );- if (updated) return writeJSON(agentToResponse(updated), 201);- }-- return writeJSON(agentToResponse(newAgent), 201);-});diff --git a/src/web/app/api/auth/send-code/route.test.ts b/src/web/app/api/auth/send-code/route.test.tsdeleted file mode 100644index 871bad7b9..000000000--- a/src/web/app/api/auth/send-code/route.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/verification-code");-vi.mock("@/lib/auth/jwt");-vi.mock("@/lib/services/email");--import {- createVerificationCode,- getLatestCodeByEmail,- deleteExpiredVerificationCodes,-} from "@/lib/db/queries/verification-code";-import { generateVerificationCode } from "@/lib/auth/jwt";-import { EmailService } from "@/lib/services/email";-import { POST } from "./route";--const mockGetLatest = vi.mocked(getLatestCodeByEmail);-const mockCreate = vi.mocked(createVerificationCode);-const mockGenerate = vi.mocked(generateVerificationCode);-const mockDelete = vi.mocked(deleteExpiredVerificationCodes);--function makeReq(body: unknown) {- return new NextRequest("http://localhost/api/auth/send-code", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });-}--beforeEach(() => {- vi.clearAllMocks();- delete process.env.APP_ENV;-});--describe("POST /api/auth/send-code", () => {- it("returns 400 for missing email", async () => {- const res = await POST(makeReq({}));- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("email is required");- });-- it("returns 400 for invalid JSON", async () => {- const req = new NextRequest("http://localhost/api/auth/send-code", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: "not json{{{",- });- const res = await POST(req);- expect(res.status).toBe(400);- });-- it("returns dev-mode message in non-production", async () => {- const res = await POST(makeReq({ email: "[email protected]" }));- expect(res.status).toBe(200);- const body = await res.json();- expect(body.message).toBe("Verification code sent");- });-- it("returns 429 when rate limited in production", async () => {- process.env.APP_ENV = "production";- mockGetLatest.mockResolvedValue({- createdAt: new Date(),- } as any);-- const res = await POST(makeReq({ email: "[email protected]" }));- expect(res.status).toBe(429);- });-- it("sends code and returns success in production", async () => {- process.env.APP_ENV = "production";- mockGetLatest.mockResolvedValue(null as any);- mockGenerate.mockReturnValue("123456");- mockCreate.mockResolvedValue(undefined as any);- mockDelete.mockResolvedValue(undefined as any);- (EmailService as any).mockImplementation(() => ({- sendVerificationCode: vi.fn().mockResolvedValue(undefined),- }));-- const res = await POST(makeReq({ email: "[email protected]" }));- expect(res.status).toBe(200);- const body = await res.json();- expect(body.message).toBe("Verification code sent");- });-- it("returns 500 when email service fails in production", async () => {- process.env.APP_ENV = "production";- mockGetLatest.mockResolvedValue(null as any);- mockGenerate.mockReturnValue("123456");- mockCreate.mockResolvedValue(undefined as any);- (EmailService as any).mockImplementation(() => ({- sendVerificationCode: vi.fn().mockRejectedValue(new Error("send failed")),- }));-- const res = await POST(makeReq({ email: "[email protected]" }));- expect(res.status).toBe(500);- });-});diff --git a/src/web/app/api/auth/send-code/route.ts b/src/web/app/api/auth/send-code/route.tsdeleted file mode 100644index 8a95e4c2f..000000000--- a/src/web/app/api/auth/send-code/route.ts+++ /dev/null@@ -1,55 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- createVerificationCode,- getLatestCodeByEmail,- deleteExpiredVerificationCodes,-} from "@/lib/db/queries/verification-code";-import { generateVerificationCode } from "@/lib/auth/jwt";-import { EmailService } from "@/lib/services/email";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { log } from "@/lib/logger";--export async function POST(req: NextRequest) {- let body: { email?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const email = (body.email || "").toLowerCase().trim();- if (!email) {- return writeError("email is required", 400);- }-- const appEnv = process.env.APP_ENV || "development";- if (appEnv !== "production") {- log.info("dev mode: use code 888888");- return writeJSON({ message: "Verification code sent" });- }-- const latest = await getLatestCodeByEmail(db, email);- if (latest) {- const elapsed = Date.now() - new Date(latest.createdAt).getTime();- if (elapsed < 10_000) {- return writeError("please wait before requesting another code", 429);- }- }-- const code = generateVerificationCode();- const expiresAt = new Date(Date.now() + 10 * 60 * 1000);- await createVerificationCode(db, { email, code, expiresAt });-- try {- const emailService = new EmailService();- await emailService.sendVerificationCode(email, code);- } catch (err) {- log.error("Failed to send verification email", { err });- return writeError("failed to send verification email", 500);- }-- deleteExpiredVerificationCodes(db).catch(() => {});-- return writeJSON({ message: "Verification code sent" });-}diff --git a/src/web/app/api/auth/verify-code/route.test.ts b/src/web/app/api/auth/verify-code/route.test.tsdeleted file mode 100644index 15efddca9..000000000--- a/src/web/app/api/auth/verify-code/route.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/db", () => ({- db: {- transaction: vi.fn(async (fn: any) => fn({})),- },-}));-vi.mock("@/lib/db/queries/verification-code");-vi.mock("@/lib/db/queries/user");-vi.mock("@/lib/db/queries/workspace");-vi.mock("@/lib/db/queries/member");-vi.mock("@/lib/auth/jwt");-vi.mock("@/lib/api/responses", () => ({- userToResponse: vi.fn((u: any) => ({- id: u.id,- name: u.name,- email: u.email,- })),-}));--import {- getLatestVerificationCode,- markVerificationCodeUsed,- incrementVerificationCodeAttempts,-} from "@/lib/db/queries/verification-code";-import { getUserByEmail, createUser } from "@/lib/db/queries/user";-import { listWorkspaces, createWorkspace } from "@/lib/db/queries/workspace";-import { createMember } from "@/lib/db/queries/member";-import { signJWT } from "@/lib/auth/jwt";-import { POST } from "./route";--const mockGetLatestCode = vi.mocked(getLatestVerificationCode);-const mockMarkUsed = vi.mocked(markVerificationCodeUsed);-const mockIncrementAttempts = vi.mocked(incrementVerificationCodeAttempts);-const mockGetUserByEmail = vi.mocked(getUserByEmail);-const mockCreateUser = vi.mocked(createUser);-const mockListWorkspaces = vi.mocked(listWorkspaces);-const mockCreateWorkspace = vi.mocked(createWorkspace);-const mockCreateMember = vi.mocked(createMember);-const mockSignJWT = vi.mocked(signJWT);--function makeRequest(body: unknown) {- return new NextRequest(new URL("http://localhost/api/auth/verify-code"), {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--beforeEach(() => {- vi.clearAllMocks();- process.env.APP_ENV = "development";-});--describe("POST /api/auth/verify-code", () => {- it("returns 400 for invalid body", async () => {- const req = new NextRequest(- new URL("http://localhost/api/auth/verify-code"),- {- method: "POST",- body: "not json",- headers: { "Content-Type": "application/json" },- }- );- const res = await POST(req);- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("invalid request body");- });-- it("returns 400 when email or code is missing", async () => {- const res = await POST(makeRequest({ email: "", code: "" }));- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("email and code are required");- });-- it("master code 888888 works in non-production", async () => {- process.env.APP_ENV = "development";- const fakeUser = {- id: "u1",- name: "test",- email: "[email protected]",- createdAt: new Date(),- updatedAt: new Date(),- };- mockGetUserByEmail.mockResolvedValue(fakeUser as any);- mockListWorkspaces.mockResolvedValue([{ id: "w1" }] as any);- mockSignJWT.mockResolvedValue("jwt-token-123");-- const res = await POST(- makeRequest({ email: "[email protected]", code: "888888" })- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body.token).toBe("jwt-token-123");- expect(body.user).toBeDefined();- expect(mockGetLatestCode).not.toHaveBeenCalled();- });-- it("returns 400 and increments attempts for invalid code", async () => {- mockGetLatestCode.mockResolvedValue({- id: "vc1",- code: "111111",- email: "[email protected]",- } as any);-- const res = await POST(- makeRequest({ email: "[email protected]", code: "999999" })- );- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("invalid or expired code");- expect(mockIncrementAttempts).toHaveBeenCalledWith(- expect.anything(),- "vc1"- );- });-- it("valid code marks used, creates user if needed, returns token", async () => {- mockGetLatestCode.mockResolvedValue({- id: "vc1",- code: "123456",- email: "[email protected]",- } as any);- mockGetUserByEmail.mockResolvedValue(null as any);- const createdUser = {- id: "u2",- name: "new",- email: "[email protected]",- createdAt: new Date(),- updatedAt: new Date(),- };- mockCreateUser.mockResolvedValue(createdUser as any);- mockListWorkspaces.mockResolvedValue([{ id: "w1" }] as any);- mockSignJWT.mockResolvedValue("jwt-new-user");-- const res = await POST(- makeRequest({ email: "[email protected]", code: "123456" })- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body.token).toBe("jwt-new-user");- expect(body.user).toBeDefined();- expect(mockMarkUsed).toHaveBeenCalledWith(expect.anything(), "vc1");- expect(mockCreateUser).toHaveBeenCalledWith(expect.anything(), {- name: "new",- email: "[email protected]",- });- });-});diff --git a/src/web/app/api/auth/verify-code/route.ts b/src/web/app/api/auth/verify-code/route.tsdeleted file mode 100644index 2b87417d7..000000000--- a/src/web/app/api/auth/verify-code/route.ts+++ /dev/null@@ -1,119 +0,0 @@-import { NextRequest } from "next/server";-import { timingSafeEqual, randomBytes } from "crypto";-import { db } from "@/lib/db";-import {- getLatestVerificationCode,- markVerificationCodeUsed,- incrementVerificationCodeAttempts,-} from "@/lib/db/queries/verification-code";-import { getUserByEmail, createUser } from "@/lib/db/queries/user";-import { listWorkspaces, createWorkspace } from "@/lib/db/queries/workspace";-import { createMember } from "@/lib/db/queries/member";-import { signJWT } from "@/lib/auth/jwt";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { userToResponse } from "@/lib/api/responses";-import { log } from "@/lib/logger";--export async function POST(req: NextRequest) {- let body: { email?: string; code?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const email = (body.email || "").toLowerCase().trim();- const code = (body.code || "").trim();- if (!email || !code) {- return writeError("email and code are required", 400);- }-- try {- const appEnv = process.env.APP_ENV || "development";- const isMasterCode = appEnv !== "production" && code === "888888";-- if (!isMasterCode) {- const stored = await getLatestVerificationCode(db, email);- if (!stored) {- return writeError("invalid or expired code", 400);- }-- const a = Buffer.from(code);- const b = Buffer.from(stored.code);- const match = a.length === b.length && timingSafeEqual(a, b);-- if (!match) {- await incrementVerificationCodeAttempts(db, stored.id);- return writeError("invalid or expired code", 400);- }-- await markVerificationCodeUsed(db, stored.id);- }-- let user = await getUserByEmail(db, email);- if (!user) {- const name = email.split("@")[0];- user = await createUser(db, { name, email });- }-- const userId = user.id;- const workspaces = await listWorkspaces(db, userId);- if (workspaces.length === 0) {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- await db.transaction(async (tx: any) => {- const ws = await listWorkspaces(tx, userId);- if (ws.length > 0) return;-- const baseSlug = email- .split("@")[0]- .replace(/[^a-z0-9-]/g, "-")- .substring(0, 24);- let slug = baseSlug;-- try {- const workspace = await createWorkspace(tx, {- name: "Personal",- slug,- });- await createMember(tx, {- workspaceId: workspace.id,- userId,- role: "owner",- });- } catch (err: unknown) {- if ((err as Record<string, unknown>).code === "23505") {- slug = `${baseSlug}-${randomBytes(3).toString("hex")}`;- const workspace = await createWorkspace(tx, {- name: "Personal",- slug,- });- await createMember(tx, {- workspaceId: workspace.id,- userId,- role: "owner",- });- } else {- throw err;- }- }- });- }-- const token = await signJWT({- sub: user.id,- email: user.email,- name: user.name,- });-- const response = writeJSON({ token, user: userToResponse(user) });- response.cookies.set("alook_session", "1", {- sameSite: "lax",- path: "/",- maxAge: 60 * 60 * 72, // 72h, matches JWT expiry- });- return response;- } catch (err) {- log.error("verify-code error", { err });- return writeError("internal server error", 500);- }-}diff --git a/src/web/app/api/conversations/[id]/messages/route.test.ts b/src/web/app/api/conversations/[id]/messages/route.test.tsdeleted file mode 100644index 24c9a5bcf..000000000--- a/src/web/app/api/conversations/[id]/messages/route.test.ts+++ /dev/null@@ -1,162 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/conversation");-vi.mock("@/lib/db/queries/message");-vi.mock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- enqueueTask: vi.fn(async () => ({- id: "t1", agentId: "a1", runtimeId: "r1", conversationId: "c1",- workspaceId: "w1", prompt: "hi", status: "queued", priority: 0,- dispatchedAt: null, startedAt: null, completedAt: null,- result: null, error: null, createdAt: new Date(),- })),- })),-}));-vi.mock("@/lib/api/responses", () => ({- messageToResponse: vi.fn((m: any) => ({ id: m.id })),- taskToResponse: vi.fn((t: any) => ({ id: t.id })),-}));--import { getConversation, updateConversationTitle } from "@/lib/db/queries/conversation";-import { listMessages, createMessage } from "@/lib/db/queries/message";--const mockGetConv = vi.mocked(getConversation);-const mockListMessages = vi.mocked(listMessages);-const mockCreateMessage = vi.mocked(createMessage);-const mockUpdateTitle = vi.mocked(updateConversationTitle);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/conversations/[id]/messages", () => {- it("lists messages", async () => {- mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1" } as any);- mockListMessages.mockResolvedValue([{ id: "m1" }] as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1"),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(1);- });-});--describe("POST /api/conversations/[id]/messages", () => {- it("sends message and enqueues task, returns 201", async () => {- mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1", agentId: "a1" } as any);- mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- mockUpdateTitle.mockResolvedValue(null as any);- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "hello" }),- }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(201);- const body = await res.json();- expect(body.message).toBeDefined();- expect(body.task).toBeDefined();- });-- it("auto-titles conversation with truncated first message", async () => {- mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1", agentId: "a1" } as any);- mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- mockUpdateTitle.mockResolvedValue({ id: "c1" } as any);- const { POST } = await import("./route");- await POST(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Fix the authentication middleware bug in the login flow for production users" }),- }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(mockUpdateTitle).toHaveBeenCalledWith(- {},- "c1",- expect.any(String),- );- // Title should be truncated to ~50 chars at word boundary- const titleArg = mockUpdateTitle.mock.calls[0][2];- expect(titleArg.length).toBeLessThanOrEqual(53); // 50 + "..."- expect(titleArg).toContain("...");- });-- it("auto-title does not fail if update returns null (title already set)", async () => {- mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1", agentId: "a1" } as any);- mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- mockUpdateTitle.mockResolvedValue(null as any); // title already set- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "hello again" }),- }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(201);- });-- it("short messages are not truncated", async () => {- mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1", agentId: "a1" } as any);- mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- mockUpdateTitle.mockResolvedValue({ id: "c1" } as any);- const { POST } = await import("./route");- await POST(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Fix the auth bug" }),- }),- { params: Promise.resolve({ id: "c1" }) },- );- const titleArg = mockUpdateTitle.mock.calls[0][2];- expect(titleArg).toBe("Fix the auth bug");- expect(titleArg).not.toContain("...");- });-- it("returns 400 for missing content", async () => {- mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1" } as any);- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(400);- });-- it("returns 404 when conversation not found", async () => {- mockGetConv.mockResolvedValue(null as any);- mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "hello" }),- }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/conversations/[id]/messages/route.ts b/src/web/app/api/conversations/[id]/messages/route.tsdeleted file mode 100644index 9fa5d42b1..000000000--- a/src/web/app/api/conversations/[id]/messages/route.ts+++ /dev/null@@ -1,97 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import { getConversation, updateConversationTitle } from "@/lib/db/queries/conversation";-import { listMessages, createMessage } from "@/lib/db/queries/message";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { messageToResponse, taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { log } from "@/lib/logger";--function truncateTitle(text: string, maxLen = 50): string {- const trimmed = text.replace(/\s+/g, " ").trim();- if (trimmed.length <= maxLen) return trimmed;- const cut = trimmed.slice(0, maxLen);- const lastSpace = cut.lastIndexOf(" ");- const title = lastSpace > 20 ? cut.slice(0, lastSpace) : cut;- return title + "...";-}--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await getConversation(db, id);- if (!conversation || conversation.workspaceId !== ws.workspaceId) {- return writeError("conversation not found", 404);- }-- const messages = await listMessages(db, id);- return writeJSON(messages.map(messageToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- let body: { content?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const content = body.content || "";- if (!content) {- return writeError("content is required", 400);- }-- const conversation = await getConversation(db, id);- if (!conversation || conversation.workspaceId !== ws.workspaceId) {- return writeError("conversation not found", 404);- }-- const message = await createMessage(db, {- conversationId: id,- role: "user",- content,- });-- // Auto-title: conditional WHERE title = '' ensures only the first message sets it- updateConversationTitle(db, id, truncateTitle(content)).catch(() => {});-- const taskService = new TaskService(db);- try {- const task = await taskService.enqueueTask(- conversation.agentId,- id,- ws.workspaceId,- content- );- return writeJSON(- { message: messageToResponse(message), task: taskToResponse(task) },- 201- );- } catch (err: unknown) {- log.error("enqueueTask error", { err });- return writeJSON(- {- message: messageToResponse(message),- task: null,- error: err instanceof Error ? err.message : "Unknown error",- },- 500- );- }-});diff --git a/src/web/app/api/conversations/[id]/route.test.ts b/src/web/app/api/conversations/[id]/route.test.tsdeleted file mode 100644index fb42293b1..000000000--- a/src/web/app/api/conversations/[id]/route.test.ts+++ /dev/null@@ -1,108 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/conversation");-vi.mock("@/lib/db/queries/task");-vi.mock("@/lib/api/responses", () => ({- conversationToResponse: vi.fn((c: any) => ({ id: c.id })),-}));--import { getConversation, deleteConversation } from "@/lib/db/queries/conversation";-import { deleteTasksByConversation } from "@/lib/db/queries/task";--const mockGet = vi.mocked(getConversation);-const mockDelete = vi.mocked(deleteConversation);-const mockDeleteTasks = vi.mocked(deleteTasksByConversation);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/conversations/[id]", () => {- it("returns conversation", async () => {- mockGet.mockResolvedValue({ id: "c1", workspaceId: "w1" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1?workspace_id=w1"),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(200);- });-- it("returns 404 when not found", async () => {- mockGet.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1?workspace_id=w1"),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(404);- });-- it("returns 404 when workspace mismatch", async () => {- mockGet.mockResolvedValue({ id: "c1", workspaceId: "other" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1?workspace_id=w1"),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(404);- });-});--describe("DELETE /api/conversations/[id]", () => {- it("returns 204 and removes conversation + tasks", async () => {- mockGet.mockResolvedValue({ id: "c1", workspaceId: "w1" } as any);- mockDeleteTasks.mockResolvedValue([{ id: "t1" }]);- mockDelete.mockResolvedValue({ id: "c1" } as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(204);- expect(mockDeleteTasks).toHaveBeenCalledWith({}, "c1");- expect(mockDelete).toHaveBeenCalledWith({}, "c1");- });-- it("deletes tasks in all statuses before conversation", async () => {- mockGet.mockResolvedValue({ id: "c1", workspaceId: "w1" } as any);- mockDeleteTasks.mockResolvedValue([{ id: "t1" }, { id: "t2" }, { id: "t3" }]);- mockDelete.mockResolvedValue({ id: "c1" } as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(204);- expect(mockDeleteTasks).toHaveBeenCalled();- });-- it("returns 404 when conversation not found", async () => {- mockGet.mockResolvedValue(null as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(404);- });-- it("returns 404 when workspace mismatch", async () => {- mockGet.mockResolvedValue({ id: "c1", workspaceId: "other" } as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- { params: Promise.resolve({ id: "c1" }) },- );- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/conversations/[id]/route.ts b/src/web/app/api/conversations/[id]/route.tsdeleted file mode 100644index 0c8839e75..000000000--- a/src/web/app/api/conversations/[id]/route.ts+++ /dev/null@@ -1,46 +0,0 @@-import { db } from "@/lib/db";-import { getConversation, deleteConversation } from "@/lib/db/queries/conversation";-import { deleteTasksByConversation } from "@/lib/db/queries/task";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await getConversation(db, id);- if (!conversation || conversation.workspaceId !== ws.workspaceId) {- return writeError("conversation not found", 404);- }-- return writeJSON(conversationToResponse(conversation));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await getConversation(db, id);- if (!conversation || conversation.workspaceId !== ws.workspaceId) {- return writeError("conversation not found", 404);- }-- // Delete tasks first (no cascade on FK)- await deleteTasksByConversation(db, id);- // Messages cascade automatically via schema- await deleteConversation(db, id);-- return new Response(null, { status: 204 });-});diff --git a/src/web/app/api/conversations/route.test.ts b/src/web/app/api/conversations/route.test.tsdeleted file mode 100644index 9eed69250..000000000--- a/src/web/app/api/conversations/route.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/conversation");-vi.mock("@/lib/api/responses", () => ({- conversationToResponse: vi.fn((c: any) => ({ id: c.id })),-}));--import { listConversations, createConversation } from "@/lib/db/queries/conversation";-const mockList = vi.mocked(listConversations);-const mockCreate = vi.mocked(createConversation);--beforeEach(() => vi.clearAllMocks());--function makeReq(body?: unknown) {- const opts: any = { method: body ? "POST" : "GET" };- if (body) {- opts.headers = { "Content-Type": "application/json" };- opts.body = JSON.stringify(body);- }- return new NextRequest("http://localhost/api/conversations?workspace_id=w1", opts);-}--describe("GET /api/conversations", () => {- it("lists conversations", async () => {- mockList.mockResolvedValue([{ id: "c1" }] as any);- const { GET } = await import("./route");- const res = await GET(makeReq());- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(1);- });-});--describe("POST /api/conversations", () => {- it("creates conversation with agent_id", async () => {- mockCreate.mockResolvedValue({ id: "c1" } as any);- const { POST } = await import("./route");- const res = await POST(makeReq({ agent_id: "a1" }));- expect(res.status).toBe(201);- });-- it("returns 400 for missing agent_id", async () => {- const { POST } = await import("./route");- const res = await POST(makeReq({}));- expect(res.status).toBe(400);- });-});diff --git a/src/web/app/api/conversations/route.ts b/src/web/app/api/conversations/route.tsdeleted file mode 100644index 4694d48b3..000000000--- a/src/web/app/api/conversations/route.ts+++ /dev/null@@ -1,48 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- listConversations,- createConversation,-} from "@/lib/db/queries/conversation";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const conversations = await listConversations(- db,- ws.workspaceId,- ctx.userId- );- return writeJSON(conversations.map(conversationToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let body: { agent_id?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const agentId = body.agent_id || "";- if (!agentId) {- return writeError("agent_id is required", 400);- }-- const conversation = await createConversation(db, {- workspaceId: ws.workspaceId,- agentId,- userId: ctx.userId,- title: "",- });-- return writeJSON(conversationToResponse(conversation), 201);-});diff --git a/src/web/app/api/daemon/deregister/route.test.ts b/src/web/app/api/daemon/deregister/route.test.tsdeleted file mode 100644index cf4a011d2..000000000--- a/src/web/app/api/daemon/deregister/route.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--function makeReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/deregister", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });-}--function setupMocks(opts: { workspaceId?: string } = { workspaceId: "w1" }) {- vi.resetModules();-- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: opts.workspaceId, params });- }),- }));- vi.doMock("@/lib/db", () => ({ db: {} }));- vi.doMock("@/lib/db/queries/runtime", () => ({- setAgentRuntimeOffline: vi.fn(async () => {}),- getAgentRuntimeForWorkspace: vi.fn(async () => ({ id: "rt1", workspaceId: "w1" })),- }));-}--describe("POST /api/daemon/deregister", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("sets owned runtimes offline", async () => {- setupMocks();- const { POST } = await import("./route");- const { setAgentRuntimeOffline } = await import("@/lib/db/queries/runtime");-- const res = await POST(makeReq({ runtime_ids: ["rt1"] }));- expect(res.status).toBe(200);- expect(setAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");- });-- it("skips unowned runtimes — setAgentRuntimeOffline not called for that ID", async () => {- setupMocks();- const { getAgentRuntimeForWorkspace, setAgentRuntimeOffline } =- await import("@/lib/db/queries/runtime");- vi.mocked(getAgentRuntimeForWorkspace).mockImplementation(async (_db, id) => {- if (id === "rt1") return { id: "rt1", workspaceId: "w1" } as any;- return null;- });-- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));- expect(res.status).toBe(200);- expect(setAgentRuntimeOffline).toHaveBeenCalledTimes(1);- expect(setAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");- });-- it("returns 200 with empty runtime_ids (no-op)", async () => {- setupMocks();- const { POST } = await import("./route");- const { setAgentRuntimeOffline } = await import("@/lib/db/queries/runtime");-- const res = await POST(makeReq({ runtime_ids: [] }));- expect(res.status).toBe(200);- expect(setAgentRuntimeOffline).not.toHaveBeenCalled();- });-- it("returns 403 when called without workspaceId", async () => {- setupMocks({ workspaceId: undefined });- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_ids: ["rt1"] }));- expect(res.status).toBe(403);- });-- it("continues processing remaining runtimes after DB error on one", async () => {- setupMocks();- const { getAgentRuntimeForWorkspace, setAgentRuntimeOffline } =- await import("@/lib/db/queries/runtime");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue({ id: "rt1", workspaceId: "w1" } as any);- vi.mocked(setAgentRuntimeOffline)- .mockRejectedValueOnce(new Error("db error"))- .mockResolvedValueOnce(undefined);-- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));- expect(res.status).toBe(200);- expect(setAgentRuntimeOffline).toHaveBeenCalledTimes(2);- });-});diff --git a/src/web/app/api/daemon/deregister/route.ts b/src/web/app/api/daemon/deregister/route.tsdeleted file mode 100644index 8165d27c8..000000000--- a/src/web/app/api/daemon/deregister/route.ts+++ /dev/null@@ -1,36 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- setAgentRuntimeOffline,- getAgentRuntimeForWorkspace,-} from "@/lib/db/queries/runtime";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { DeregisterRequestSchema } from "@alook/shared";-import { log } from "@/lib/logger";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const [body, err] = await parseBody(req, DeregisterRequestSchema);- if (err) return err;-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- for (const id of body.runtime_ids) {- const runtime = await getAgentRuntimeForWorkspace(- db,- id,- ctx.workspaceId- );- if (!runtime) continue;-- try {- await setAgentRuntimeOffline(db, id);- } catch (e) {- log.warn("Failed to set runtime offline", { runtimeId: id, err: e });- }- }-- return writeJSON({ status: "ok" });-});diff --git a/src/web/app/api/daemon/heartbeat/route.test.ts b/src/web/app/api/daemon/heartbeat/route.test.tsdeleted file mode 100644index 71383a6b9..000000000--- a/src/web/app/api/daemon/heartbeat/route.test.ts+++ /dev/null@@ -1,140 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--function makeReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/heartbeat", {- method: "POST",- body: JSON.stringify(body),- });-}--function setupMocks(opts: { workspaceId?: string } = { workspaceId: "w1" }) {- vi.resetModules();-- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: opts.workspaceId, params });- }),- }));- vi.doMock("@/lib/db", () => ({ db: {} }));- vi.doMock("@/lib/db/queries/runtime", () => ({- updateAgentRuntimeHeartbeat: vi.fn(async () => ({ id: "rt1" })),- getAgentRuntimeForWorkspace: vi.fn(async () => ({ id: "rt1", workspaceId: "w1" })),- markStaleRuntimesOffline: vi.fn(async () => {}),- }));- vi.doMock("@/lib/db/queries/task", () => ({- failStaleDispatchedTasks: vi.fn(async () => []),- }));- vi.doMock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- reconcileAgentStatus: vi.fn(),- })),- }));-}--describe("POST /api/daemon/heartbeat", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("succeeds for runtime in caller's workspace", async () => {- setupMocks();- const { POST } = await import("./route");- const { getAgentRuntimeForWorkspace, updateAgentRuntimeHeartbeat } =- await import("@/lib/db/queries/runtime");-- const res = await POST(makeReq({ runtime_id: "rt1" }));- expect(res.status).toBe(200);- expect(getAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1");- expect(updateAgentRuntimeHeartbeat).toHaveBeenCalledWith({}, "rt1");- });-- it("returns 404 when runtime not in caller's workspace", async () => {- setupMocks();- const { getAgentRuntimeForWorkspace } = await import("@/lib/db/queries/runtime");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null as any);-- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_id: "rt-other" }));- expect(res.status).toBe(404);- });-- it("returns 404 when runtime ID doesn't exist at all", async () => {- setupMocks();- const { getAgentRuntimeForWorkspace } = await import("@/lib/db/queries/runtime");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null as any);-- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_id: "nonexistent" }));- expect(res.status).toBe(404);- });-- it("returns 403 when called without workspaceId (JWT auth)", async () => {- setupMocks({ workspaceId: undefined });- const { POST } = await import("./route");- const res = await POST(makeReq({ runtime_id: "rt1" }));- expect(res.status).toBe(403);- });-- it("does NOT call updateAgentRuntimeHeartbeat, markStaleRuntimesOffline, or failStaleDispatchedTasks when ownership fails", async () => {- setupMocks();- const { getAgentRuntimeForWorkspace, updateAgentRuntimeHeartbeat, markStaleRuntimesOffline } =- await import("@/lib/db/queries/runtime");- const { failStaleDispatchedTasks } = await import("@/lib/db/queries/task");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null as any);-- const { POST } = await import("./route");- await POST(makeReq({ runtime_id: "rt-other" }));- expect(updateAgentRuntimeHeartbeat).not.toHaveBeenCalled();- expect(markStaleRuntimesOffline).not.toHaveBeenCalled();- expect(failStaleDispatchedTasks).not.toHaveBeenCalled();- });-- it("calls markStaleRuntimesOffline with (db, workspaceId)", async () => {- setupMocks();- const { POST } = await import("./route");- const { markStaleRuntimesOffline } = await import("@/lib/db/queries/runtime");-- await POST(makeReq({ runtime_id: "rt1" }));- expect(markStaleRuntimesOffline).toHaveBeenCalledWith({}, "w1");- });-- it("calls updateAgentRuntimeHeartbeat before markStaleRuntimesOffline", async () => {- setupMocks();- const { updateAgentRuntimeHeartbeat, markStaleRuntimesOffline } =- await import("@/lib/db/queries/runtime");-- const callOrder: string[] = [];- vi.mocked(updateAgentRuntimeHeartbeat).mockImplementation(async () => {- callOrder.push("heartbeat");- return { id: "rt1" } as any;- });- vi.mocked(markStaleRuntimesOffline).mockImplementation(async () => {- callOrder.push("markStale");- });-- const { POST } = await import("./route");- await POST(makeReq({ runtime_id: "rt1" }));- expect(callOrder).toEqual(["heartbeat", "markStale"]);- });-- it("calls failStaleDispatchedTasks and reconcileAgentStatus on happy path", async () => {- setupMocks();- const { failStaleDispatchedTasks } = await import("@/lib/db/queries/task");- const { TaskService } = await import("@/lib/services/task");-- const mockReconcile = vi.fn();- vi.mocked(TaskService).mockImplementation(() => ({ reconcileAgentStatus: mockReconcile }) as any);- vi.mocked(failStaleDispatchedTasks).mockResolvedValue([- { agentId: "a1" } as any,- { agentId: "a2" } as any,- ]);-- const { POST } = await import("./route");- await POST(makeReq({ runtime_id: "rt1" }));- expect(failStaleDispatchedTasks).toHaveBeenCalled();- expect(mockReconcile).toHaveBeenCalledWith("a1");- expect(mockReconcile).toHaveBeenCalledWith("a2");- });-});diff --git a/src/web/app/api/daemon/heartbeat/route.ts b/src/web/app/api/daemon/heartbeat/route.tsdeleted file mode 100644index 89c7353fc..000000000--- a/src/web/app/api/daemon/heartbeat/route.ts+++ /dev/null@@ -1,47 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- updateAgentRuntimeHeartbeat,- getAgentRuntimeForWorkspace,- markStaleRuntimesOffline,-} from "@/lib/db/queries/runtime";-import { failStaleDispatchedTasks } from "@/lib/db/queries/task";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { HeartbeatRequestSchema } from "@alook/shared";-import { TaskService } from "@/lib/services/task";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const [body, err] = await parseBody(req, HeartbeatRequestSchema);- if (err) return err;-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const runtime = await getAgentRuntimeForWorkspace(- db,- body.runtime_id,- ctx.workspaceId- );- if (!runtime) {- return writeError("Runtime not found", 404);- }-- await updateAgentRuntimeHeartbeat(db, body.runtime_id);-- // Mark runtimes that haven't sent a heartbeat in >45s as offline- await markStaleRuntimesOffline(db, ctx.workspaceId);-- // Fail tasks stuck in "dispatched" for >20s (daemon likely crashed)- const stale = await failStaleDispatchedTasks(db);- if (stale.length > 0) {- const taskService = new TaskService(db);- const agentIds = [...new Set(stale.map((r) => r.agentId))];- for (const agentId of agentIds) {- await taskService.reconcileAgentStatus(agentId);- }- }-- return writeJSON({ status: "ok" });-});diff --git a/src/web/app/api/daemon/register/route.ts b/src/web/app/api/daemon/register/route.tsdeleted file mode 100644index 96f42def2..000000000--- a/src/web/app/api/daemon/register/route.ts+++ /dev/null@@ -1,54 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import { upsertAgentRuntime } from "@/lib/db/queries/runtime";-import { getMemberByUserAndWorkspace } from "@/lib/db/queries/member";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, parseBody } from "@/lib/middleware/helpers";-import { runtimeToResponse } from "@/lib/api/responses";-import { RegisterDaemonRequestSchema } from "@alook/shared";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const [body, err] = await parseBody(req, RegisterDaemonRequestSchema);- if (err) return err;-- const { workspace_id: workspaceId, daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, runtimes } = body;-- const membership = await getMemberByUserAndWorkspace(- db,- ctx.userId,- workspaceId- );- if (!membership) {- return writeJSON({ error: "workspace not found" }, 404);- }-- const results = [];- for (const rt of runtimes) {- const provider = (rt.type || rt.provider || "unknown").trim();- const runtimeMode = rt.runtime_mode || "local";- let name = (rt.name || "").trim();- if (!name) {- name = deviceName ? `${provider} (${deviceName})` : provider;- }- const deviceInfo = deviceName.trim();- const status = rt.status === "offline" ? "offline" : "online";- const metadata: Record<string, unknown> = {- version: rt.version || "",- cli_version: cliVersion,- };-- const result = await upsertAgentRuntime(db, {- workspaceId,- daemonId,- name,- runtimeMode,- provider,- status,- deviceInfo,- metadata,- });- results.push(result);- }-- return writeJSON({ runtimes: results.map(runtimeToResponse) });-});diff --git a/src/web/app/api/daemon/routes.test.ts b/src/web/app/api/daemon/routes.test.tsdeleted file mode 100644index c91111d24..000000000--- a/src/web/app/api/daemon/routes.test.ts+++ /dev/null@@ -1,265 +0,0 @@-/**- * Route-level tests verifying that each daemon endpoint rejects invalid- * request bodies with 400 via parseBody + the correct Zod schema.- *- * We mock `withAuth` to bypass authentication and directly invoke handlers.- */-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--// Bypass auth: withAuth just calls the handler with a fake context-vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => {- return async (req: NextRequest, context?: any) => {- const params = context?.params- ? context.params instanceof Promise- ? await context.params- : context.params- : undefined;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });- };- },-}));--// Mock DB layer — we only care about request validation, not DB calls-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/runtime", () => ({- upsertAgentRuntime: vi.fn(async () => ({- id: "rt1", workspaceId: "w1", daemonId: "d1", name: "Rt",- runtimeMode: "local", provider: "claude", status: "online",- deviceInfo: "", metadata: {}, lastSeenAt: null,- createdAt: new Date(), updatedAt: new Date(),- })),- setAgentRuntimeOffline: vi.fn(async () => {}),- updateAgentRuntimeHeartbeat: vi.fn(async () => {}),- getAgentRuntimeForWorkspace: vi.fn(async () => ({ id: "rt1" })),- markStaleRuntimesOffline: vi.fn(async () => {}),-}));-vi.mock("@/lib/db/queries/task", () => ({- failStaleDispatchedTasks: vi.fn(async () => []),-}));-vi.mock("@/lib/db/queries/member", () => ({- getMemberByUserAndWorkspace: vi.fn(async () => ({ id: "m1" })),-}));-vi.mock("@/lib/db/queries/task-message", () => ({- listTaskMessages: vi.fn(async () => []),- createTaskMessage: vi.fn(async () => ({})),-}));-vi.mock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- completeTask: vi.fn(async () => ({- id: "t1", agentId: "a1", runtimeId: "r1", conversationId: "c1",- workspaceId: "w1", prompt: "p", status: "completed", priority: 0,- dispatchedAt: null, startedAt: null, completedAt: null,- result: null, error: null, createdAt: new Date(),- })),- failTask: vi.fn(async () => ({- id: "t1", agentId: "a1", runtimeId: "r1", conversationId: "c1",- workspaceId: "w1", prompt: "p", status: "failed", priority: 0,- dispatchedAt: null, startedAt: null, completedAt: null,- result: null, error: "err", createdAt: new Date(),- })),- })),-}));-vi.mock("@/lib/api/responses", () => ({- runtimeToResponse: vi.fn((r: any) => ({ id: r.id })),- taskToResponse: vi.fn((t: any) => ({ id: t.id, status: t.status })),-}));--function makeReq(body: unknown, url = "http://localhost/api/daemon/test"): NextRequest {- return new NextRequest(url, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });-}--function makeBadJsonReq(url = "http://localhost/api/daemon/test"): NextRequest {- return new NextRequest(url, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: "not json{{{",- });-}--// ----------------------------------------------------------------------------// /daemon/register-// -----------------------------------------------------------------------------describe("POST /daemon/register validation", () => {- let POST: any;- beforeEach(async () => {- ({ POST } = await import("./register/route"));- });-- it("returns 400 when workspace_id is empty", async () => {- const res = await POST(makeReq({- workspace_id: "",- daemon_id: "d1",- runtimes: [{ type: "claude" }],- }));- expect(res.status).toBe(400);- });-- it("returns 400 when runtimes is empty array", async () => {- const res = await POST(makeReq({- workspace_id: "w1",- daemon_id: "d1",- runtimes: [],- }));- expect(res.status).toBe(400);- });-- it("returns 400 on malformed JSON", async () => {- const res = await POST(makeBadJsonReq());- expect(res.status).toBe(400);- });-- it("stores deviceInfo as device_name only, without version", async () => {- const { upsertAgentRuntime } = await import("@/lib/db/queries/runtime");- (upsertAgentRuntime as any).mockClear();-- const res = await POST(makeReq({- workspace_id: "w1",- daemon_id: "d1",- device_name: "Gustavos-MacBook-Pro.local",- cli_version: "0.1.0",- runtimes: [{ type: "claude", version: "2.1.97 (Claude Code)" }],- }));- expect(res.status).toBe(200);- expect(upsertAgentRuntime).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- deviceInfo: "Gustavos-MacBook-Pro.local",- }),- );- });-- it("stores version in metadata, not in deviceInfo", async () => {- const { upsertAgentRuntime } = await import("@/lib/db/queries/runtime");- (upsertAgentRuntime as any).mockClear();-- await POST(makeReq({- workspace_id: "w1",- daemon_id: "d1",- device_name: "my-host",- cli_version: "0.1.0",- runtimes: [{ type: "claude", version: "2.1.97 (Claude Code)" }],- }));- expect(upsertAgentRuntime).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- deviceInfo: "my-host",- metadata: expect.objectContaining({- version: "2.1.97 (Claude Code)",- }),- }),- );- });-});--// ----------------------------------------------------------------------------// /daemon/heartbeat-// -----------------------------------------------------------------------------describe("POST /daemon/heartbeat validation", () => {- let POST: any;- beforeEach(async () => {- ({ POST } = await import("./heartbeat/route"));- });-- it("returns 400 when runtime_id is empty string", async () => {- const res = await POST(makeReq({ runtime_id: "" }));- expect(res.status).toBe(400);- });-- it("returns 400 when runtime_id is missing", async () => {- const res = await POST(makeReq({}));- expect(res.status).toBe(400);- });-});--// ----------------------------------------------------------------------------// /daemon/deregister-// -----------------------------------------------------------------------------describe("POST /daemon/deregister validation", () => {- let POST: any;- beforeEach(async () => {- ({ POST } = await import("./deregister/route"));- });-- it("returns 400 when runtime_ids contains non-strings", async () => {- const res = await POST(makeReq({ runtime_ids: [123, true] }));- expect(res.status).toBe(400);- });-- it("returns 400 on malformed JSON", async () => {- const res = await POST(makeBadJsonReq());- expect(res.status).toBe(400);- });-});--// ----------------------------------------------------------------------------// /daemon/tasks/:taskId/complete-// -----------------------------------------------------------------------------describe("POST /daemon/tasks/:taskId/complete validation", () => {- let POST: any;- beforeEach(async () => {- ({ POST } = await import("./tasks/[taskId]/complete/route"));- });-- it("returns 400 on malformed JSON", async () => {- const req = makeBadJsonReq();- const res = await POST(req, { params: Promise.resolve({ taskId: "t1" }) });- expect(res.status).toBe(400);- });-});--// ----------------------------------------------------------------------------// /daemon/tasks/:taskId/fail-// -----------------------------------------------------------------------------describe("POST /daemon/tasks/:taskId/fail validation", () => {- let POST: any;- beforeEach(async () => {- ({ POST } = await import("./tasks/[taskId]/fail/route"));- });-- it("returns 400 on malformed JSON", async () => {- const req = makeBadJsonReq();- const res = await POST(req, { params: Promise.resolve({ taskId: "t1" }) });- expect(res.status).toBe(400);- });-});--// ----------------------------------------------------------------------------// /daemon/tasks/:taskId/messages-// -----------------------------------------------------------------------------describe("POST /daemon/tasks/:taskId/messages validation", () => {- let postHandler: any;- beforeEach(async () => {- const mod = await import("./tasks/[taskId]/messages/route");- postHandler = mod.POST;- });-- it("returns 400 when message item missing seq", async () => {- const req = makeReq({ messages: [{ type: "text" }] });- const res = await postHandler(req, { params: Promise.resolve({ taskId: "t1" }) });- expect(res.status).toBe(400);- });-- it("returns 400 when message item missing type", async () => {- const req = makeReq({ messages: [{ seq: 1 }] });- const res = await postHandler(req, { params: Promise.resolve({ taskId: "t1" }) });- expect(res.status).toBe(400);- });-- it("returns 400 on malformed JSON", async () => {- const req = makeBadJsonReq();- const res = await postHandler(req, { params: Promise.resolve({ taskId: "t1" }) });- expect(res.status).toBe(400);- });-});diff --git a/src/web/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts b/src/web/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.tsdeleted file mode 100644index afc9bdb84..000000000--- a/src/web/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/agent");-vi.mock("@/lib/db/queries/task");-vi.mock("@/lib/services/task");-vi.mock("@/lib/api/responses", () => ({- taskToResponse: vi.fn((t: any) => ({- id: t.id, agent_id: t.agentId, runtime_id: t.runtimeId,- conversation_id: t.conversationId, workspace_id: t.workspaceId,- prompt: t.prompt, status: t.status, priority: t.priority,- dispatched_at: null, started_at: null, completed_at: null,- result: null, error: null, created_at: "2024-01-01T00:00:00Z",- })),-}));--import { TaskService } from "@/lib/services/task";-import { getAgent } from "@/lib/db/queries/agent";-import { getLastTaskSession } from "@/lib/db/queries/task";--const mockGetAgent = vi.mocked(getAgent);-const mockGetLastSession = vi.mocked(getLastTaskSession);--beforeEach(() => vi.clearAllMocks());--describe("POST /daemon/runtimes/[runtimeId]/tasks/claim", () => {- it("returns { task: null } when no task available", async () => {- (TaskService as any).mockImplementation(() => ({- claimTaskForRuntime: vi.fn(async () => null),- }));- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/daemon/runtimes/r1/tasks/claim", { method: "POST" }),- { params: Promise.resolve({ runtimeId: "r1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body.task).toBeNull();- });-- it("returns task with agent data and prior session", async () => {- const fakeTask = {- id: "t1", agentId: "a1", runtimeId: "r1", conversationId: "c1",- workspaceId: "w1", prompt: "do it", status: "dispatched", priority: 0,- };- (TaskService as any).mockImplementation(() => ({- claimTaskForRuntime: vi.fn(async () => fakeTask),- }));- mockGetAgent.mockResolvedValue({- instructions: "be helpful",- name: "Bot",- runtimeConfig: { model: "gpt-4" },- } as any);- mockGetLastSession.mockResolvedValue({- sessionId: "sess-old",- workDir: "/old/work",- } as any);-- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/daemon/runtimes/r1/tasks/claim", { method: "POST" }),- { params: Promise.resolve({ runtimeId: "r1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body.task).not.toBeNull();- expect(body.task.agent.name).toBe("Bot");- expect(body.task.prior_session_id).toBe("sess-old");- expect(body.task.prior_work_dir).toBe("/old/work");- });-});diff --git a/src/web/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts b/src/web/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.tsdeleted file mode 100644index 5d00c7c30..000000000--- a/src/web/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import { db } from "@/lib/db";-import { getAgent } from "@/lib/db/queries/agent";-import { getLastTaskSession } from "@/lib/db/queries/task";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";--export const POST = withAuth(async (_req, ctx) => {- const runtimeId = ctx.params?.runtimeId;- if (!runtimeId) {- return writeError("runtime_id is required", 400);- }-- const taskService = new TaskService(db);- const task = await taskService.claimTaskForRuntime(runtimeId);-- if (!task) {- return writeJSON({ task: null });- }-- const agent = await getAgent(db, task.agentId);- const priorSession = await getLastTaskSession(- db,- task.agentId,- task.conversationId- );-- return writeJSON({- task: {- ...taskToResponse(task),- agent: agent- ? {- instructions: agent.instructions,- name: agent.name,- runtime_config: agent.runtimeConfig || {},- }- : null,- prior_session_id: priorSession?.sessionId ?? null,- prior_work_dir: priorSession?.workDir ?? null,- },- });-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/complete/route.ts b/src/web/app/api/daemon/tasks/[taskId]/complete/route.tsdeleted file mode 100644index 1eb538a14..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/complete/route.ts+++ /dev/null@@ -1,34 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { CompleteTaskRequestSchema } from "@alook/shared";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const [body, err] = await parseBody(req, CompleteTaskRequestSchema);- if (err) return err;-- const result = JSON.stringify(body);- const sessionId = body.session_id || "";- const workDir = body.work_dir || "";-- const taskService = new TaskService(db);- try {- const task = await taskService.completeTask(- taskId,- result,- sessionId,- workDir- );- return writeJSON(taskToResponse(task));- } catch (e: unknown) {- return writeError(e instanceof Error ? e.message : "Unknown error", 400);- }-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/fail/route.ts b/src/web/app/api/daemon/tasks/[taskId]/fail/route.tsdeleted file mode 100644index d227987c3..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/fail/route.ts+++ /dev/null@@ -1,25 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { FailTaskRequestSchema } from "@alook/shared";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const [body, err] = await parseBody(req, FailTaskRequestSchema);- if (err) return err;-- const taskService = new TaskService(db);- try {- const task = await taskService.failTask(taskId, body.error);- return writeJSON(taskToResponse(task));- } catch (e: unknown) {- return writeError(e instanceof Error ? e.message : "Unknown error", 400);- }-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/app/api/daemon/tasks/[taskId]/messages/route.tsdeleted file mode 100644index c795c91a6..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/messages/route.ts+++ /dev/null@@ -1,51 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- listTaskMessages,- createTaskMessage,-} from "@/lib/db/queries/task-message";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { taskMessageToResponse } from "@/lib/api/responses";-import { ReportMessagesRequestSchema } from "@alook/shared";-import { log } from "@/lib/logger";--export const GET = withAuth(async (_req, ctx) => {- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const messages = await listTaskMessages(db, taskId);- return writeJSON(messages.map(taskMessageToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const [body, err] = await parseBody(req, ReportMessagesRequestSchema);- if (err) return err;-- if (body.messages.length === 0) {- return writeJSON({ status: "ok" });- }-- for (const m of body.messages) {- createTaskMessage(db, {- taskId,- seq: m.seq,- type: m.type,- tool: m.tool || "",- content: m.content || "",- input: m.input,- output: m.output || "",- }).catch((e) => {- log.warn("Failed to create task message", { taskId, err: e });- });- }-- return writeJSON({ status: "ok" });-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/start/route.test.ts b/src/web/app/api/daemon/tasks/[taskId]/start/route.test.tsdeleted file mode 100644index c45739c1d..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/start/route.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/services/task");-vi.mock("@/lib/api/responses", () => ({- taskToResponse: vi.fn((t: any) => ({ id: t.id, status: t.status })),-}));--import { TaskService } from "@/lib/services/task";--beforeEach(() => vi.clearAllMocks());--describe("POST /daemon/tasks/[taskId]/start", () => {- it("returns started task", async () => {- (TaskService as any).mockImplementation(() => ({- startTask: vi.fn(async () => ({ id: "t1", status: "running" })),- }));- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/start", { method: "POST" }),- { params: Promise.resolve({ taskId: "t1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body.status).toBe("running");- });-- it("returns 400 when task not in dispatched status", async () => {- (TaskService as any).mockImplementation(() => ({- startTask: vi.fn(async () => { throw new Error("task not in dispatched status"); }),- }));- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/start", { method: "POST" }),- { params: Promise.resolve({ taskId: "t1" }) },- );- expect(res.status).toBe(400);- });-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/start/route.ts b/src/web/app/api/daemon/tasks/[taskId]/start/route.tsdeleted file mode 100644index e13e83498..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/start/route.ts+++ /dev/null@@ -1,20 +0,0 @@-import { db } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";--export const POST = withAuth(async (_req, ctx) => {- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const taskService = new TaskService(db);- try {- const task = await taskService.startTask(taskId);- return writeJSON(taskToResponse(task));- } catch (err: unknown) {- return writeError(err instanceof Error ? err.message : "Unknown error", 400);- }-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/status/route.test.ts b/src/web/app/api/daemon/tasks/[taskId]/status/route.test.tsdeleted file mode 100644index 73800f55e..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/status/route.test.ts+++ /dev/null@@ -1,40 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/task");--import { getTaskStatus } from "@/lib/db/queries/task";-const mockGetStatus = vi.mocked(getTaskStatus);--beforeEach(() => vi.clearAllMocks());--describe("GET /daemon/tasks/[taskId]/status", () => {- it("returns task status", async () => {- mockGetStatus.mockResolvedValue("running" as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/daemon/tasks/t1/status"),- { params: Promise.resolve({ taskId: "t1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body.status).toBe("running");- });-- it("returns 404 when task not found", async () => {- mockGetStatus.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/daemon/tasks/t1/status"),- { params: Promise.resolve({ taskId: "t1" }) },- );- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/daemon/tasks/[taskId]/status/route.ts b/src/web/app/api/daemon/tasks/[taskId]/status/route.tsdeleted file mode 100644index 6fe3f7061..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/status/route.ts+++ /dev/null@@ -1,18 +0,0 @@-import { db } from "@/lib/db";-import { getTaskStatus } from "@/lib/db/queries/task";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (_req, ctx) => {- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const status = await getTaskStatus(db, taskId);- if (!status) {- return writeError("task not found", 404);- }-- return writeJSON({ status });-});diff --git a/src/web/app/api/machine-tokens/[id]/route.test.ts b/src/web/app/api/machine-tokens/[id]/route.test.tsdeleted file mode 100644index 922a5642f..000000000--- a/src/web/app/api/machine-tokens/[id]/route.test.ts+++ /dev/null@@ -1,33 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/machine-token");--import { deleteMachineToken } from "@/lib/db/queries/machine-token";-const mockDelete = vi.mocked(deleteMachineToken);--beforeEach(() => vi.clearAllMocks());--describe("DELETE /api/machine-tokens/[id]", () => {- it("deletes token and returns 204", async () => {- mockDelete.mockResolvedValue(undefined as any);- const { DELETE } = await import("./route");- const res = await DELETE(- new NextRequest("http://localhost/api/machine-tokens/mt1?workspace_id=w1", {- method: "DELETE",- }),- { params: Promise.resolve({ id: "mt1" }) },- );- expect(res.status).toBe(204);- });-});diff --git a/src/web/app/api/machine-tokens/[id]/route.ts b/src/web/app/api/machine-tokens/[id]/route.tsdeleted file mode 100644index 4b68e81ba..000000000--- a/src/web/app/api/machine-tokens/[id]/route.ts+++ /dev/null@@ -1,22 +0,0 @@-import { NextResponse } from "next/server";-import { db } from "@/lib/db";-import { deleteMachineToken } from "@/lib/db/queries/machine-token";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return NextResponse.json(- { error: "token id is required" },- { status: 400 }- );- }-- await deleteMachineToken(db, id, ctx.userId);-- return new NextResponse(null, { status: 204 });-});diff --git a/src/web/app/api/machine-tokens/route.test.ts b/src/web/app/api/machine-tokens/route.test.tsdeleted file mode 100644index 9ee280432..000000000--- a/src/web/app/api/machine-tokens/route.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/machine-token");-vi.mock("@/lib/auth/jwt", () => ({- generateMachineToken: vi.fn(() => "al_raw_token"),- hashToken: vi.fn(() => "hashed"),-}));-vi.mock("@/lib/api/responses", () => ({- machineTokenToResponse: vi.fn((t: any) => ({ id: t.id, name: t.name })),-}));--import { listMachineTokens, createMachineToken } from "@/lib/db/queries/machine-token";-const mockList = vi.mocked(listMachineTokens);-const mockCreate = vi.mocked(createMachineToken);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/machine-tokens", () => {- it("lists tokens", async () => {- mockList.mockResolvedValue([{ id: "mt1", name: "default" }] as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/machine-tokens?workspace_id=w1"),- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(1);- });-});--describe("POST /api/machine-tokens", () => {- it("creates token and returns raw token + 201", async () => {- mockCreate.mockResolvedValue({ id: "mt1", name: "mytoken" } as any);- const { POST } = await import("./route");- const res = await POST(- new NextRequest("http://localhost/api/machine-tokens?workspace_id=w1", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "mytoken" }),- }),- );- expect(res.status).toBe(201);- const body = await res.json();- expect(body.token).toBe("al_raw_token");- });-});diff --git a/src/web/app/api/machine-tokens/route.ts b/src/web/app/api/machine-tokens/route.tsdeleted file mode 100644index 4bdada577..000000000--- a/src/web/app/api/machine-tokens/route.ts+++ /dev/null@@ -1,46 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- listMachineTokens,- createMachineToken,-} from "@/lib/db/queries/machine-token";-import { generateMachineToken, hashToken } from "@/lib/auth/jwt";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { machineTokenToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const tokens = await listMachineTokens(db, ctx.userId, ws.workspaceId);- return writeJSON(tokens.map(machineTokenToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let name = "default";- try {- const body = await req.json();- if (body.name && typeof body.name === "string" && body.name.trim()) {- name = body.name.trim();- }- } catch {- // body parse error → use default name- }-- const raw = generateMachineToken();- const tokenHash = hashToken(raw);-- const mt = await createMachineToken(db, {- userId: ctx.userId,- workspaceId: ws.workspaceId,- tokenHash,- name,- });-- return writeJSON({ token: raw, ...machineTokenToResponse(mt) }, 201);-});diff --git a/src/web/app/api/me/route.test.ts b/src/web/app/api/me/route.test.tsdeleted file mode 100644index ada63dc09..000000000--- a/src/web/app/api/me/route.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/user");-vi.mock("@/lib/auth/jwt");-vi.mock("@/lib/db/queries/machine-token");--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => {- return async (req: any) => {- return handler(req, { userId: "u1", email: "[email protected]" });- };- }),-}));--vi.mock("@/lib/api/responses", () => ({- userToResponse: vi.fn((u: any) => ({- id: u.id,- name: u.name,- email: u.email,- avatar_url: u.avatarUrl || null,- created_at: "2024-01-01T00:00:00Z",- updated_at: "2024-01-01T00:00:00Z",- })),-}));--import { getUser } from "@/lib/db/queries/user";-import { GET } from "./route";--const mockGetUser = vi.mocked(getUser);--beforeEach(() => {- vi.clearAllMocks();-});--describe("GET /api/me", () => {- it("returns user data when authenticated", async () => {- mockGetUser.mockResolvedValue({- id: "u1",- name: "Alice",- email: "[email protected]",- avatarUrl: null,- createdAt: new Date(),- updatedAt: new Date(),- } as any);-- const req = new Request("http://localhost/api/me");- const res = await GET(req as any);- const body = await res.json();-- expect(body.id).toBe("u1");- expect(body.name).toBe("Alice");- expect(body.email).toBe("[email protected]");- expect(body.avatar_url).toBeNull();- expect(mockGetUser).toHaveBeenCalledWith(expect.anything(), "u1");- });-});diff --git a/src/web/app/api/me/route.ts b/src/web/app/api/me/route.tsdeleted file mode 100644index d3b586027..000000000--- a/src/web/app/api/me/route.ts+++ /dev/null@@ -1,13 +0,0 @@-import { db } from "@/lib/db";-import { getUser } from "@/lib/db/queries/user";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { userToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (_req, ctx) => {- const user = await getUser(db, ctx.userId);- if (!user) {- return writeError("user not found", 404);- }- return writeJSON(userToResponse(user));-});diff --git a/src/web/app/api/runtimes/machine/route.test.ts b/src/web/app/api/runtimes/machine/route.test.tsdeleted file mode 100644index 11dbd96f2..000000000--- a/src/web/app/api/runtimes/machine/route.test.ts+++ /dev/null@@ -1,117 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockDeleteRuntimes = vi.fn(async () => {});-const mockGetMember = vi.fn(async () => ({ id: "m1" }));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => {- return async (req: NextRequest, context?: any) => {- const params = context?.params- ? context.params instanceof Promise- ? await context.params- : context.params- : undefined;- return handler(req, { userId: "u1", email: "[email protected]", params });- };- },-}));--vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/runtime", () => ({- deleteRuntimesByDaemonId: (...args: Parameters<typeof mockDeleteRuntimes>) => mockDeleteRuntimes(...args),-}));-vi.mock("@/lib/db/queries/member", () => ({- getMemberByUserAndWorkspace: (...args: Parameters<typeof mockGetMember>) => mockGetMember(...args),-}));--describe("DELETE /api/runtimes/machine", () => {- let DELETE: any;- beforeEach(async () => {- mockDeleteRuntimes.mockClear();- mockGetMember.mockClear();- mockGetMember.mockResolvedValue({ id: "m1" });- mockDeleteRuntimes.mockResolvedValue(undefined);- ({ DELETE } = await import("./route"));- });-- it("returns 400 when daemon_id is missing", async () => {- const res = await DELETE(- new NextRequest("http://localhost/api/runtimes/machine?workspace_id=w1", {- method: "DELETE",- })- );- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("daemon_id is required");- });-- it("returns 400 when workspace_id is missing", async () => {- const res = await DELETE(- new NextRequest("http://localhost/api/runtimes/machine?daemon_id=d1", {- method: "DELETE",- })- );- expect(res.status).toBe(400);- });-- it("returns 404 when user is not a workspace member", async () => {- mockGetMember.mockResolvedValueOnce(null as any);- const res = await DELETE(- new NextRequest(- "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",- { method: "DELETE" }- )- );- expect(res.status).toBe(404);- });-- it("returns 204 on successful delete", async () => {- const res = await DELETE(- new NextRequest(- "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",- { method: "DELETE" }- )- );- expect(res.status).toBe(204);- expect(mockDeleteRuntimes).toHaveBeenCalledWith({}, "d1", "w1");- });-- it("passes correct daemon_id with dots and dashes", async () => {- const res = await DELETE(- new NextRequest(- "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=My-MacBook-Pro.local",- { method: "DELETE" }- )- );- expect(res.status).toBe(204);- expect(mockDeleteRuntimes).toHaveBeenCalledWith(- {},- "My-MacBook-Pro.local",- "w1"- );- });-- it("calls deleteRuntimesByDaemonId exactly once", async () => {- await DELETE(- new NextRequest(- "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",- { method: "DELETE" }- )- );- expect(mockDeleteRuntimes).toHaveBeenCalledTimes(1);- });-- it("returns 500 when deleteRuntimesByDaemonId throws", async () => {- mockDeleteRuntimes.mockRejectedValueOnce(new Error("FK violation"));- const res = await DELETE(- new NextRequest(- "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",- { method: "DELETE" }- )- );- expect(res.status).toBe(500);- const body = await res.json();- expect(body.error).toBe("Failed to remove machine");- });-});diff --git a/src/web/app/api/runtimes/machine/route.ts b/src/web/app/api/runtimes/machine/route.tsdeleted file mode 100644index 7efba8785..000000000--- a/src/web/app/api/runtimes/machine/route.ts+++ /dev/null@@ -1,26 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import { deleteRuntimesByDaemonId } from "@/lib/db/queries/runtime";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { log } from "@/lib/logger";--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const daemonId = req.nextUrl.searchParams.get("daemon_id");- if (!daemonId) {- return writeJSON({ error: "daemon_id is required" }, 400);- }-- try {- await deleteRuntimesByDaemonId(db, daemonId, ws.workspaceId);- } catch (e) {- log.error("Failed to delete machine", { err: e });- return writeJSON({ error: "Failed to remove machine" }, 500);- }-- return new Response(null, { status: 204 });-});diff --git a/src/web/app/api/runtimes/route.test.ts b/src/web/app/api/runtimes/route.test.tsdeleted file mode 100644index 04482ca92..000000000--- a/src/web/app/api/runtimes/route.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/runtime");-vi.mock("@/lib/api/responses", () => ({- runtimeToResponse: vi.fn((r: any) => ({ id: r.id })),-}));--import {- listAgentRuntimes,- markStaleRuntimesOffline,-} from "@/lib/db/queries/runtime";-const mockList = vi.mocked(listAgentRuntimes);-const mockMarkStale = vi.mocked(markStaleRuntimesOffline);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/runtimes", () => {- it("lists runtimes in workspace", async () => {- mockList.mockResolvedValue([{ id: "rt1" }, { id: "rt2" }] as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/runtimes?workspace_id=w1"),- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(2);- });-- it("marks stale runtimes offline before listing", async () => {- mockList.mockResolvedValue([{ id: "rt1" }] as any);- const { GET } = await import("./route");- await GET(- new NextRequest("http://localhost/api/runtimes?workspace_id=w1"),- );- expect(mockMarkStale).toHaveBeenCalledWith({}, "w1");- });-});diff --git a/src/web/app/api/runtimes/route.ts b/src/web/app/api/runtimes/route.tsdeleted file mode 100644index de7917c81..000000000--- a/src/web/app/api/runtimes/route.ts+++ /dev/null@@ -1,20 +0,0 @@-import { db } from "@/lib/db";-import {- listAgentRuntimes,- markStaleRuntimesOffline,-} from "@/lib/db/queries/runtime";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { runtimeToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- // Mark runtimes that haven't sent a heartbeat in >45s as offline- await markStaleRuntimesOffline(db, ws.workspaceId);-- const runtimes = await listAgentRuntimes(db, ws.workspaceId);- return writeJSON(runtimes.map(runtimeToResponse));-});diff --git a/src/web/app/api/tasks/[id]/messages/route.test.ts b/src/web/app/api/tasks/[id]/messages/route.test.tsdeleted file mode 100644index f049ac2cc..000000000--- a/src/web/app/api/tasks/[id]/messages/route.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/task");-vi.mock("@/lib/db/queries/task-message");-vi.mock("@/lib/api/responses", () => ({- taskMessageToResponse: vi.fn((m: any) => ({ id: m.id, seq: m.seq })),-}));--import { getTask } from "@/lib/db/queries/task";-import { listTaskMessages, listTaskMessagesSince } from "@/lib/db/queries/task-message";--const mockGetTask = vi.mocked(getTask);-const mockListAll = vi.mocked(listTaskMessages);-const mockListSince = vi.mocked(listTaskMessagesSince);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/tasks/[id]/messages", () => {- it("lists all messages", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1" } as any);- mockListAll.mockResolvedValue([{ id: "m1", seq: 1 }] as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?workspace_id=w1"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(1);- });-- it("filters by since parameter", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1" } as any);- mockListSince.mockResolvedValue([{ id: "m2", seq: 2 }] as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?workspace_id=w1&since=1"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(200);- expect(mockListSince).toHaveBeenCalledWith(expect.anything(), "t1", 1);- });-- it("returns 400 for invalid since parameter", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?workspace_id=w1&since=abc"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(400);- });-- it("returns 404 when task not found", async () => {- mockGetTask.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?workspace_id=w1"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/tasks/[id]/messages/route.ts b/src/web/app/api/tasks/[id]/messages/route.tsdeleted file mode 100644index 26c51a0f0..000000000--- a/src/web/app/api/tasks/[id]/messages/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { db } from "@/lib/db";-import { getTask } from "@/lib/db/queries/task";-import {- listTaskMessages,- listTaskMessagesSince,-} from "@/lib/db/queries/task-message";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskMessageToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("task id is required", 400);- }-- const task = await getTask(db, id);- if (!task || task.workspaceId !== ws.workspaceId) {- return writeError("task not found", 404);- }-- const sinceParam = req.nextUrl.searchParams.get("since");- let messages;-- if (sinceParam) {- const afterSeq = parseInt(sinceParam, 10);- if (isNaN(afterSeq)) {- return writeError("invalid since parameter", 400);- }- messages = await listTaskMessagesSince(db, id, afterSeq);- } else {- messages = await listTaskMessages(db, id);- }-- return writeJSON(messages.map(taskMessageToResponse));-});diff --git a/src/web/app/api/tasks/[id]/route.test.ts b/src/web/app/api/tasks/[id]/route.test.tsdeleted file mode 100644index df003de79..000000000--- a/src/web/app/api/tasks/[id]/route.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/task");-vi.mock("@/lib/api/responses", () => ({- taskToResponse: vi.fn((t: any) => ({ id: t.id })),-}));--import { getTask } from "@/lib/db/queries/task";-const mockGet = vi.mocked(getTask);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/tasks/[id]", () => {- it("returns task", async () => {- mockGet.mockResolvedValue({ id: "t1", workspaceId: "w1" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1?workspace_id=w1"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(200);- });-- it("returns 404 when not found", async () => {- mockGet.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1?workspace_id=w1"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(404);- });-- it("returns 404 when workspace mismatch", async () => {- mockGet.mockResolvedValue({ id: "t1", workspaceId: "other" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1?workspace_id=w1"),- { params: Promise.resolve({ id: "t1" }) },- );- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/tasks/[id]/route.ts b/src/web/app/api/tasks/[id]/route.tsdeleted file mode 100644index a194a0764..000000000--- a/src/web/app/api/tasks/[id]/route.ts+++ /dev/null@@ -1,23 +0,0 @@-import { db } from "@/lib/db";-import { getTask } from "@/lib/db/queries/task";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id;- if (!id) {- return writeError("task id is required", 400);- }-- const task = await getTask(db, id);- if (!task || task.workspaceId !== ws.workspaceId) {- return writeError("task not found", 404);- }-- return writeJSON(taskToResponse(task));-});diff --git a/src/web/app/api/workspaces/[id]/route.test.ts b/src/web/app/api/workspaces/[id]/route.test.tsdeleted file mode 100644index 2b03837b2..000000000--- a/src/web/app/api/workspaces/[id]/route.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/workspace");-vi.mock("@/lib/api/responses", () => ({- workspaceToResponse: vi.fn((w: any) => ({ id: w.id, name: w.name })),-}));--import { getWorkspace } from "@/lib/db/queries/workspace";-const mockGet = vi.mocked(getWorkspace);--beforeEach(() => vi.clearAllMocks());--describe("GET /api/workspaces/[id]", () => {- it("returns workspace", async () => {- mockGet.mockResolvedValue({ id: "w1", name: "WS" } as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/workspaces/w1"),- { params: Promise.resolve({ id: "w1" }) },- );- expect(res.status).toBe(200);- });-- it("returns 404 when not found", async () => {- mockGet.mockResolvedValue(null as any);- const { GET } = await import("./route");- const res = await GET(- new NextRequest("http://localhost/api/workspaces/w1"),- { params: Promise.resolve({ id: "w1" }) },- );- expect(res.status).toBe(404);- });-});diff --git a/src/web/app/api/workspaces/[id]/route.ts b/src/web/app/api/workspaces/[id]/route.tsdeleted file mode 100644index 4f729a152..000000000--- a/src/web/app/api/workspaces/[id]/route.ts+++ /dev/null@@ -1,19 +0,0 @@-import { db } from "@/lib/db";-import { getWorkspace } from "@/lib/db/queries/workspace";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { workspaceToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (_req, ctx) => {- const id = ctx.params?.id;- if (!id) {- return writeError("workspace id is required", 400);- }-- const workspace = await getWorkspace(db, id);- if (!workspace) {- return writeError("workspace not found", 404);- }-- return writeJSON(workspaceToResponse(workspace));-});diff --git a/src/web/app/api/workspaces/route.test.ts b/src/web/app/api/workspaces/route.test.tsdeleted file mode 100644index 69eb9fca5..000000000--- a/src/web/app/api/workspaces/route.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/db", () => ({- db: { transaction: vi.fn(async (fn: any) => fn({})) },-}));-vi.mock("@/lib/db/queries/workspace");-vi.mock("@/lib/db/queries/member");-vi.mock("@/lib/api/responses", () => ({- workspaceToResponse: vi.fn((w: any) => ({ id: w.id, name: w.name })),-}));--import { listWorkspaces, createWorkspace } from "@/lib/db/queries/workspace";-import { createMember } from "@/lib/db/queries/member";--const mockList = vi.mocked(listWorkspaces);-const mockCreate = vi.mocked(createWorkspace);-const mockCreateMember = vi.mocked(createMember);--beforeEach(() => vi.clearAllMocks());--function makeReq(body?: unknown) {- const opts: any = { method: body ? "POST" : "GET" };- if (body) {- opts.headers = { "Content-Type": "application/json" };- opts.body = JSON.stringify(body);- }- return new NextRequest("http://localhost/api/workspaces", opts);-}--describe("GET /api/workspaces", () => {- it("lists user workspaces", async () => {- mockList.mockResolvedValue([{ id: "w1", name: "WS" }] as any);- const { GET } = await import("./route");- const res = await GET(makeReq());- expect(res.status).toBe(200);- const body = await res.json();- expect(body).toHaveLength(1);- expect(body[0].id).toBe("w1");- });-});--describe("POST /api/workspaces", () => {- it("creates workspace with member, returns 201", async () => {- mockCreate.mockResolvedValue({ id: "w1", name: "Test" } as any);- mockCreateMember.mockResolvedValue({} as any);- const { POST } = await import("./route");- const res = await POST(makeReq({ name: "Test", slug: "test" }));- expect(res.status).toBe(201);- });-- it("returns 400 for missing name", async () => {- const { POST } = await import("./route");- const res = await POST(makeReq({ slug: "test" }));- expect(res.status).toBe(400);- });-- it("returns 400 for missing slug", async () => {- const { POST } = await import("./route");- const res = await POST(makeReq({ name: "Test" }));- expect(res.status).toBe(400);- });-- it("returns 409 on duplicate slug", async () => {- const err: any = new Error("dup");- err.code = "23505";- mockCreate.mockRejectedValue(err);- const { POST } = await import("./route");- const res = await POST(makeReq({ name: "Test", slug: "dup" }));- expect(res.status).toBe(409);- });-});diff --git a/src/web/app/api/workspaces/route.ts b/src/web/app/api/workspaces/route.tsdeleted file mode 100644index 9e171d342..000000000--- a/src/web/app/api/workspaces/route.ts+++ /dev/null@@ -1,53 +0,0 @@-import { NextRequest } from "next/server";-import { db } from "@/lib/db";-import {- listWorkspaces,- createWorkspace,-} from "@/lib/db/queries/workspace";-import { createMember } from "@/lib/db/queries/member";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { workspaceToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (_req, ctx) => {- const workspaces = await listWorkspaces(db, ctx.userId);- return writeJSON(workspaces.map(workspaceToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- let body: { name?: string; slug?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const name = (body.name || "").trim();- const slug = (body.slug || "").toLowerCase().trim();-- if (!name) {- return writeError("name is required", 400);- }- if (!slug) {- return writeError("slug is required", 400);- }-- try {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const workspace = await db.transaction(async (tx: any) => {- const ws = await createWorkspace(tx, { name, slug });- await createMember(tx, {- workspaceId: ws.id,- userId: ctx.userId,- role: "owner",- });- return ws;- });- return writeJSON(workspaceToResponse(workspace), 201);- } catch (err: unknown) {- if ((err as Record<string, unknown>).code === "23505") {- return writeError("workspace slug already exists", 409);- }- throw err;- }-});diff --git a/src/web/drizzle.config.ts b/src/web/drizzle.config.tsdeleted file mode 100644index d46fcb139..000000000--- a/src/web/drizzle.config.ts+++ /dev/null@@ -1,10 +0,0 @@-import { defineConfig } from "drizzle-kit";--export default defineConfig({- schema: "./lib/db/schema.ts",- out: "./drizzle",- dialect: "postgresql",- dbCredentials: {- url: process.env.DATABASE_URL || "postgres://postgres:postgres@localhost:5432/alook?sslmode=disable",- },-});diff --git a/src/web/drizzle/0000_known_diamondback.sql b/src/web/drizzle/0000_known_diamondback.sqldeleted file mode 100644index 51e2588dd..000000000--- a/src/web/drizzle/0000_known_diamondback.sql+++ /dev/null@@ -1,156 +0,0 @@-CREATE TABLE "agent" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "workspace_id" uuid NOT NULL,- "name" text NOT NULL,- "description" text DEFAULT '' NOT NULL,- "instructions" text DEFAULT '' NOT NULL,- "avatar_url" text,- "runtime_id" uuid,- "runtime_mode" text DEFAULT 'local' NOT NULL,- "runtime_config" jsonb,- "visibility" text DEFAULT 'private' NOT NULL,- "status" text DEFAULT 'idle' NOT NULL,- "max_concurrent_tasks" integer DEFAULT 6 NOT NULL,- "owner_id" uuid,- "tools" jsonb,- "triggers" jsonb,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- "updated_at" timestamp with time zone DEFAULT now() NOT NULL-);---> statement-breakpoint-CREATE TABLE "agent_runtime" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "workspace_id" uuid NOT NULL,- "daemon_id" text NOT NULL,- "name" text DEFAULT '' NOT NULL,- "runtime_mode" text DEFAULT 'local' NOT NULL,- "provider" text NOT NULL,- "status" text DEFAULT 'offline' NOT NULL,- "device_info" text DEFAULT '' NOT NULL,- "metadata" jsonb,- "last_seen_at" timestamp with time zone,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- "updated_at" timestamp with time zone DEFAULT now() NOT NULL,- CONSTRAINT "agent_runtime_workspace_daemon_provider" UNIQUE("workspace_id","daemon_id","provider")-);---> statement-breakpoint-CREATE TABLE "agent_task_queue" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "agent_id" uuid NOT NULL,- "runtime_id" uuid NOT NULL,- "workspace_id" uuid NOT NULL,- "conversation_id" uuid NOT NULL,- "prompt" text NOT NULL,- "status" text DEFAULT 'queued' NOT NULL,- "priority" integer DEFAULT 0 NOT NULL,- "result" jsonb,- "context" jsonb,- "session_id" text,- "work_dir" text,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- "dispatched_at" timestamp with time zone,- "started_at" timestamp with time zone,- "completed_at" timestamp with time zone,- "error" text-);---> statement-breakpoint-CREATE TABLE "conversation" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "workspace_id" uuid NOT NULL,- "agent_id" uuid NOT NULL,- "user_id" uuid NOT NULL,- "title" text DEFAULT '' NOT NULL,- "created_at" timestamp with time zone DEFAULT now() NOT NULL-);---> statement-breakpoint-CREATE TABLE "machine_token" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "user_id" uuid NOT NULL,- "workspace_id" uuid NOT NULL,- "token_hash" text NOT NULL,- "name" text DEFAULT '' NOT NULL,- "last_used_at" timestamp with time zone,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- CONSTRAINT "machine_token_token_hash_unique" UNIQUE("token_hash")-);---> statement-breakpoint-CREATE TABLE "member" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "workspace_id" uuid NOT NULL,- "user_id" uuid NOT NULL,- "role" text DEFAULT 'member' NOT NULL,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- CONSTRAINT "member_workspace_user" UNIQUE("workspace_id","user_id")-);---> statement-breakpoint-CREATE TABLE "message" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "conversation_id" uuid NOT NULL,- "role" text NOT NULL,- "content" text DEFAULT '' NOT NULL,- "task_id" uuid,- "created_at" timestamp with time zone DEFAULT now() NOT NULL-);---> statement-breakpoint-CREATE TABLE "task_message" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "task_id" uuid NOT NULL,- "seq" integer NOT NULL,- "type" text DEFAULT '' NOT NULL,- "tool" text DEFAULT '' NOT NULL,- "content" text DEFAULT '' NOT NULL,- "input" jsonb,- "output" text DEFAULT '' NOT NULL,- "created_at" timestamp with time zone DEFAULT now() NOT NULL-);---> statement-breakpoint-CREATE TABLE "user" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "name" text DEFAULT '' NOT NULL,- "email" text NOT NULL,- "avatar_url" text,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- "updated_at" timestamp with time zone DEFAULT now() NOT NULL,- CONSTRAINT "user_email_unique" UNIQUE("email")-);---> statement-breakpoint-CREATE TABLE "verification_code" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "email" text NOT NULL,- "code" text NOT NULL,- "used" boolean DEFAULT false NOT NULL,- "attempts" integer DEFAULT 0 NOT NULL,- "expires_at" timestamp with time zone NOT NULL,- "created_at" timestamp with time zone DEFAULT now() NOT NULL-);---> statement-breakpoint-CREATE TABLE "workspace" (- "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,- "name" text NOT NULL,- "slug" text NOT NULL,- "created_at" timestamp with time zone DEFAULT now() NOT NULL,- "updated_at" timestamp with time zone DEFAULT now() NOT NULL,- CONSTRAINT "workspace_slug_unique" UNIQUE("slug")-);---> statement-breakpoint-ALTER TABLE "agent" ADD CONSTRAINT "agent_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent" ADD CONSTRAINT "agent_runtime_id_agent_runtime_id_fk" FOREIGN KEY ("runtime_id") REFERENCES "public"."agent_runtime"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent" ADD CONSTRAINT "agent_owner_id_user_id_fk" FOREIGN KEY ("owner_id") REFERENCES "public"."user"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent_runtime" ADD CONSTRAINT "agent_runtime_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_agent_id_agent_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agent"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_runtime_id_agent_runtime_id_fk" FOREIGN KEY ("runtime_id") REFERENCES "public"."agent_runtime"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_conversation_id_conversation_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversation"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "conversation" ADD CONSTRAINT "conversation_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "conversation" ADD CONSTRAINT "conversation_agent_id_agent_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agent"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "conversation" ADD CONSTRAINT "conversation_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "machine_token" ADD CONSTRAINT "machine_token_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "machine_token" ADD CONSTRAINT "machine_token_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "member" ADD CONSTRAINT "member_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "member" ADD CONSTRAINT "member_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "message" ADD CONSTRAINT "message_conversation_id_conversation_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversation"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-ALTER TABLE "task_message" ADD CONSTRAINT "task_message_task_id_agent_task_queue_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."agent_task_queue"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint-CREATE UNIQUE INDEX "idx_one_pending_per_conversation" ON "agent_task_queue" USING btree ("conversation_id") WHERE status IN ('queued', 'dispatched');--> statement-breakpoint-CREATE INDEX "idx_task_queue_pending" ON "agent_task_queue" USING btree ("agent_id","status") WHERE status IN ('queued', 'dispatched');--> statement-breakpoint-CREATE INDEX "idx_machine_token_hash" ON "machine_token" USING btree ("token_hash");--> statement-breakpoint-CREATE INDEX "idx_task_message_task_seq" ON "task_message" USING btree ("task_id","seq");\ No newline at end of filediff --git a/src/web/drizzle/meta/0000_snapshot.json b/src/web/drizzle/meta/0000_snapshot.jsondeleted file mode 100644index f81703b28..000000000--- a/src/web/drizzle/meta/0000_snapshot.json+++ /dev/null@@ -1,1142 +0,0 @@-{- "id": "436de5d0-fe5b-4f08-a341-8e62b871314a",- "prevId": "00000000-0000-0000-0000-000000000000",- "version": "7",- "dialect": "postgresql",- "tables": {- "public.agent": {- "name": "agent",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "workspace_id": {- "name": "workspace_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true- },- "description": {- "name": "description",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "instructions": {- "name": "instructions",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "avatar_url": {- "name": "avatar_url",- "type": "text",- "primaryKey": false,- "notNull": false- },- "runtime_id": {- "name": "runtime_id",- "type": "uuid",- "primaryKey": false,- "notNull": false- },- "runtime_mode": {- "name": "runtime_mode",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'local'"- },- "runtime_config": {- "name": "runtime_config",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "visibility": {- "name": "visibility",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'private'"- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'idle'"- },- "max_concurrent_tasks": {- "name": "max_concurrent_tasks",- "type": "integer",- "primaryKey": false,- "notNull": true,- "default": 6- },- "owner_id": {- "name": "owner_id",- "type": "uuid",- "primaryKey": false,- "notNull": false- },- "tools": {- "name": "tools",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "triggers": {- "name": "triggers",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "updated_at": {- "name": "updated_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {- "agent_workspace_id_workspace_id_fk": {- "name": "agent_workspace_id_workspace_id_fk",- "tableFrom": "agent",- "tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- },- "agent_runtime_id_agent_runtime_id_fk": {- "name": "agent_runtime_id_agent_runtime_id_fk",- "tableFrom": "agent",- "tableTo": "agent_runtime",- "columnsFrom": [- "runtime_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "no action",- "onUpdate": "no action"- },- "agent_owner_id_user_id_fk": {- "name": "agent_owner_id_user_id_fk",- "tableFrom": "agent",- "tableTo": "user",- "columnsFrom": [- "owner_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "no action",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.agent_runtime": {- "name": "agent_runtime",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "workspace_id": {- "name": "workspace_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "daemon_id": {- "name": "daemon_id",- "type": "text",- "primaryKey": false,- "notNull": true- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "runtime_mode": {- "name": "runtime_mode",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'local'"- },- "provider": {- "name": "provider",- "type": "text",- "primaryKey": false,- "notNull": true- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'offline'"- },- "device_info": {- "name": "device_info",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "metadata": {- "name": "metadata",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "last_seen_at": {- "name": "last_seen_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "updated_at": {- "name": "updated_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {- "agent_runtime_workspace_id_workspace_id_fk": {- "name": "agent_runtime_workspace_id_workspace_id_fk",- "tableFrom": "agent_runtime",- "tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {- "agent_runtime_workspace_daemon_provider": {- "name": "agent_runtime_workspace_daemon_provider",- "nullsNotDistinct": false,- "columns": [- "workspace_id",- "daemon_id",- "provider"- ]- }- },- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.agent_task_queue": {- "name": "agent_task_queue",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "agent_id": {- "name": "agent_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "runtime_id": {- "name": "runtime_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "workspace_id": {- "name": "workspace_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "conversation_id": {- "name": "conversation_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "prompt": {- "name": "prompt",- "type": "text",- "primaryKey": false,- "notNull": true- },- "status": {- "name": "status",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'queued'"- },- "priority": {- "name": "priority",- "type": "integer",- "primaryKey": false,- "notNull": true,- "default": 0- },- "result": {- "name": "result",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "context": {- "name": "context",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "session_id": {- "name": "session_id",- "type": "text",- "primaryKey": false,- "notNull": false- },- "work_dir": {- "name": "work_dir",- "type": "text",- "primaryKey": false,- "notNull": false- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "dispatched_at": {- "name": "dispatched_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "started_at": {- "name": "started_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "completed_at": {- "name": "completed_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "error": {- "name": "error",- "type": "text",- "primaryKey": false,- "notNull": false- }- },- "indexes": {- "idx_one_pending_per_conversation": {- "name": "idx_one_pending_per_conversation",- "columns": [- {- "expression": "conversation_id",- "isExpression": false,- "asc": true,- "nulls": "last"- }- ],- "isUnique": true,- "where": "status IN ('queued', 'dispatched')",- "concurrently": false,- "method": "btree",- "with": {}- },- "idx_task_queue_pending": {- "name": "idx_task_queue_pending",- "columns": [- {- "expression": "agent_id",- "isExpression": false,- "asc": true,- "nulls": "last"- },- {- "expression": "status",- "isExpression": false,- "asc": true,- "nulls": "last"- }- ],- "isUnique": false,- "where": "status IN ('queued', 'dispatched')",- "concurrently": false,- "method": "btree",- "with": {}- }- },- "foreignKeys": {- "agent_task_queue_agent_id_agent_id_fk": {- "name": "agent_task_queue_agent_id_agent_id_fk",- "tableFrom": "agent_task_queue",- "tableTo": "agent",- "columnsFrom": [- "agent_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- },- "agent_task_queue_runtime_id_agent_runtime_id_fk": {- "name": "agent_task_queue_runtime_id_agent_runtime_id_fk",- "tableFrom": "agent_task_queue",- "tableTo": "agent_runtime",- "columnsFrom": [- "runtime_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "no action",- "onUpdate": "no action"- },- "agent_task_queue_workspace_id_workspace_id_fk": {- "name": "agent_task_queue_workspace_id_workspace_id_fk",- "tableFrom": "agent_task_queue",- "tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "no action",- "onUpdate": "no action"- },- "agent_task_queue_conversation_id_conversation_id_fk": {- "name": "agent_task_queue_conversation_id_conversation_id_fk",- "tableFrom": "agent_task_queue",- "tableTo": "conversation",- "columnsFrom": [- "conversation_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "no action",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.conversation": {- "name": "conversation",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "workspace_id": {- "name": "workspace_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "agent_id": {- "name": "agent_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "user_id": {- "name": "user_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "title": {- "name": "title",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {- "conversation_workspace_id_workspace_id_fk": {- "name": "conversation_workspace_id_workspace_id_fk",- "tableFrom": "conversation",- "tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- },- "conversation_agent_id_agent_id_fk": {- "name": "conversation_agent_id_agent_id_fk",- "tableFrom": "conversation",- "tableTo": "agent",- "columnsFrom": [- "agent_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- },- "conversation_user_id_user_id_fk": {- "name": "conversation_user_id_user_id_fk",- "tableFrom": "conversation",- "tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.machine_token": {- "name": "machine_token",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "user_id": {- "name": "user_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "workspace_id": {- "name": "workspace_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "token_hash": {- "name": "token_hash",- "type": "text",- "primaryKey": false,- "notNull": true- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "last_used_at": {- "name": "last_used_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {- "idx_machine_token_hash": {- "name": "idx_machine_token_hash",- "columns": [- {- "expression": "token_hash",- "isExpression": false,- "asc": true,- "nulls": "last"- }- ],- "isUnique": false,- "concurrently": false,- "method": "btree",- "with": {}- }- },- "foreignKeys": {- "machine_token_user_id_user_id_fk": {- "name": "machine_token_user_id_user_id_fk",- "tableFrom": "machine_token",- "tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- },- "machine_token_workspace_id_workspace_id_fk": {- "name": "machine_token_workspace_id_workspace_id_fk",- "tableFrom": "machine_token",- "tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {- "machine_token_token_hash_unique": {- "name": "machine_token_token_hash_unique",- "nullsNotDistinct": false,- "columns": [- "token_hash"- ]- }- },- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.member": {- "name": "member",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "workspace_id": {- "name": "workspace_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "user_id": {- "name": "user_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "role": {- "name": "role",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'member'"- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {- "member_workspace_id_workspace_id_fk": {- "name": "member_workspace_id_workspace_id_fk",- "tableFrom": "member",- "tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- },- "member_user_id_user_id_fk": {- "name": "member_user_id_user_id_fk",- "tableFrom": "member",- "tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {- "member_workspace_user": {- "name": "member_workspace_user",- "nullsNotDistinct": false,- "columns": [- "workspace_id",- "user_id"- ]- }- },- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.message": {- "name": "message",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "conversation_id": {- "name": "conversation_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "role": {- "name": "role",- "type": "text",- "primaryKey": false,- "notNull": true- },- "content": {- "name": "content",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "task_id": {- "name": "task_id",- "type": "uuid",- "primaryKey": false,- "notNull": false- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {- "message_conversation_id_conversation_id_fk": {- "name": "message_conversation_id_conversation_id_fk",- "tableFrom": "message",- "tableTo": "conversation",- "columnsFrom": [- "conversation_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.task_message": {- "name": "task_message",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "task_id": {- "name": "task_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "seq": {- "name": "seq",- "type": "integer",- "primaryKey": false,- "notNull": true- },- "type": {- "name": "type",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "tool": {- "name": "tool",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "content": {- "name": "content",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "input": {- "name": "input",- "type": "jsonb",- "primaryKey": false,- "notNull": false- },- "output": {- "name": "output",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {- "idx_task_message_task_seq": {- "name": "idx_task_message_task_seq",- "columns": [- {- "expression": "task_id",- "isExpression": false,- "asc": true,- "nulls": "last"- },- {- "expression": "seq",- "isExpression": false,- "asc": true,- "nulls": "last"- }- ],- "isUnique": false,- "concurrently": false,- "method": "btree",- "with": {}- }- },- "foreignKeys": {- "task_message_task_id_agent_task_queue_id_fk": {- "name": "task_message_task_id_agent_task_queue_id_fk",- "tableFrom": "task_message",- "tableTo": "agent_task_queue",- "columnsFrom": [- "task_id"- ],- "columnsTo": [- "id"- ],- "onDelete": "cascade",- "onUpdate": "no action"- }- },- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.user": {- "name": "user",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "''"- },- "email": {- "name": "email",- "type": "text",- "primaryKey": false,- "notNull": true- },- "avatar_url": {- "name": "avatar_url",- "type": "text",- "primaryKey": false,- "notNull": false- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "updated_at": {- "name": "updated_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {- "user_email_unique": {- "name": "user_email_unique",- "nullsNotDistinct": false,- "columns": [- "email"- ]- }- },- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.verification_code": {- "name": "verification_code",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "email": {- "name": "email",- "type": "text",- "primaryKey": false,- "notNull": true- },- "code": {- "name": "code",- "type": "text",- "primaryKey": false,- "notNull": true- },- "used": {- "name": "used",- "type": "boolean",- "primaryKey": false,- "notNull": true,- "default": false- },- "attempts": {- "name": "attempts",- "type": "integer",- "primaryKey": false,- "notNull": true,- "default": 0- },- "expires_at": {- "name": "expires_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.workspace": {- "name": "workspace",- "schema": "",- "columns": {- "id": {- "name": "id",- "type": "uuid",- "primaryKey": true,- "notNull": true,- "default": "gen_random_uuid()"- },- "name": {- "name": "name",- "type": "text",- "primaryKey": false,- "notNull": true- },- "slug": {- "name": "slug",- "type": "text",- "primaryKey": false,- "notNull": true- },- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "updated_at": {- "name": "updated_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {- "workspace_slug_unique": {- "name": "workspace_slug_unique",- "nullsNotDistinct": false,- "columns": [- "slug"- ]- }- },- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- }- },- "enums": {},- "schemas": {},- "sequences": {},- "roles": {},- "policies": {},- "views": {},- "_meta": {- "columns": {},- "schemas": {},- "tables": {}- }-}\ No newline at end of filediff --git a/src/web/drizzle/meta/_journal.json b/src/web/drizzle/meta/_journal.jsondeleted file mode 100644index 53d4110df..000000000--- a/src/web/drizzle/meta/_journal.json+++ /dev/null@@ -1,13 +0,0 @@-{- "version": "7",- "dialect": "postgresql",- "entries": [- {- "idx": 0,- "version": "7",- "when": 1775725287516,- "tag": "0000_known_diamondback",- "breakpoints": true- }- ]-}\ No newline at end of filediff --git a/src/web/lib/auth/.gitkeep b/src/web/lib/auth/.gitkeepdeleted file mode 100644index e69de29bb..000000000diff --git a/src/web/lib/auth/jwt.test.ts b/src/web/lib/auth/jwt.test.tsdeleted file mode 100644index 42167c4f0..000000000--- a/src/web/lib/auth/jwt.test.ts+++ /dev/null@@ -1,140 +0,0 @@-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";-import { SignJWT, jwtVerify, decodeJwt, decodeProtectedHeader } from "jose";-import {- getJWTSecret,- signJWT,- verifyJWT,- generateMachineToken,- hashToken,- generateVerificationCode,-} from "./jwt";--describe("JWT token generation and verification", () => {- const claims = { sub: "user-1", email: "[email protected]", name: "Alice" };-- it("sign then verify returns the same claims", async () => {- const token = await signJWT(claims);- const result = await verifyJWT(token);- expect(result).toEqual(claims);- });-- it("sets HS256 algorithm in the protected header", async () => {- const token = await signJWT(claims);- const header = decodeProtectedHeader(token);- expect((await header).alg).toBe("HS256");- });-- it("sets expiration to 72 hours", async () => {- const now = Math.floor(Date.now() / 1000);- const token = await signJWT(claims);- const decoded = decodeJwt(token);- const diff = decoded.exp! - now;- const seventyTwoHours = 72 * 60 * 60;- expect(diff).toBeGreaterThanOrEqual(seventyTwoHours - 5);- expect(diff).toBeLessThanOrEqual(seventyTwoHours + 5);- });-- it("includes iat claim", async () => {- const token = await signJWT(claims);- const decoded = decodeJwt(token);- expect(decoded.iat).toBeDefined();- expect(typeof decoded.iat).toBe("number");- });-- it("rejects tokens signed with a different secret", async () => {- const wrongSecret = new TextEncoder().encode("wrong-secret");- const token = await new SignJWT(claims)- .setProtectedHeader({ alg: "HS256" })- .setIssuedAt()- .setExpirationTime("72h")- .sign(wrongSecret);-- await expect(verifyJWT(token)).rejects.toThrow();- });-- it("rejects expired tokens", async () => {- const token = await new SignJWT(claims)- .setProtectedHeader({ alg: "HS256" })- .setIssuedAt()- .setExpirationTime("-1s")- .sign(getJWTSecret());-- await expect(verifyJWT(token)).rejects.toThrow();- });-});--describe("JWT secret handling", () => {- const original = process.env.JWT_SECRET;-- afterEach(() => {- if (original !== undefined) {- process.env.JWT_SECRET = original;- } else {- delete process.env.JWT_SECRET;- }- });-- it("uses JWT_SECRET env var when set", () => {- process.env.JWT_SECRET = "my-custom-secret";- const secret = getJWTSecret();- expect(secret).toEqual(new TextEncoder().encode("my-custom-secret"));- });-- it("falls back to default secret when JWT_SECRET is not set", () => {- delete process.env.JWT_SECRET;- const secret = getJWTSecret();- expect(secret).toEqual(- new TextEncoder().encode("alook-dev-secret-change-in-production")- );- });-});--describe("Machine token authentication", () => {- it("returns a string starting with 'al_'", () => {- expect(generateMachineToken().startsWith("al_")).toBe(true);- });-- it("has correct length (3 prefix + 48 hex = 51)", () => {- expect(generateMachineToken()).toHaveLength(51);- });-- it("generates unique tokens on each call", () => {- const tokens = new Set(Array.from({ length: 20 }, () => generateMachineToken()));- expect(tokens.size).toBe(20);- });-- it("hashToken returns consistent SHA-256 hex digest", () => {- const input = "al_abc123";- expect(hashToken(input)).toBe(hashToken(input));- expect(hashToken(input)).toHaveLength(64);- });-- it("hashToken produces different outputs for different inputs", () => {- expect(hashToken("token-a")).not.toBe(hashToken("token-b"));- });-});--describe("Verification code generation", () => {- it("returns a 6-character string", () => {- expect(generateVerificationCode()).toHaveLength(6);- });-- it("zero-pads small numbers", () => {- const code = generateVerificationCode();- expect(code).toMatch(/^\d{6}$/);- });-- it("is always between '000000' and '999999'", () => {- for (let i = 0; i < 50; i++) {- const code = generateVerificationCode();- const n = parseInt(code, 10);- expect(n).toBeGreaterThanOrEqual(0);- expect(n).toBeLessThanOrEqual(999999);- }- });-- it("generates different codes across multiple calls (high probability)", () => {- const codes = new Set(Array.from({ length: 20 }, () => generateVerificationCode()));- expect(codes.size).toBeGreaterThan(1);- });-});diff --git a/src/web/lib/auth/jwt.ts b/src/web/lib/auth/jwt.tsdeleted file mode 100644index 3c5c9f2f9..000000000--- a/src/web/lib/auth/jwt.ts+++ /dev/null@@ -1,49 +0,0 @@-import { SignJWT, jwtVerify } from "jose";-import { randomBytes, createHash } from "crypto";--const DEFAULT_SECRET = "alook-dev-secret-change-in-production";--export function getJWTSecret(): Uint8Array {- const secret = process.env.JWT_SECRET || DEFAULT_SECRET;- return new TextEncoder().encode(secret);-}--export async function signJWT(payload: {- sub: string;- email: string;- name: string;-}): Promise<string> {- return new SignJWT(payload)- .setProtectedHeader({ alg: "HS256" })- .setIssuedAt()- .setExpirationTime("72h")- .sign(getJWTSecret());-}--export async function verifyJWT(- token: string-): Promise<{ sub: string; email: string; name: string }> {- const { payload } = await jwtVerify(token, getJWTSecret(), {- algorithms: ["HS256"],- });- return {- sub: payload.sub as string,- email: payload.email as string,- name: payload.name as string,- };-}--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");-}--export function generateVerificationCode(): string {- const buf = randomBytes(4);- const n = buf.readUInt32BE(0) % 1000000;- return n.toString().padStart(6, "0");-}diff --git a/src/web/lib/db/.gitkeep b/src/web/lib/db/.gitkeepdeleted file mode 100644index e69de29bb..000000000diff --git a/src/web/lib/db/index.ts b/src/web/lib/db/index.tsdeleted file mode 100644index f3849ba9e..000000000--- a/src/web/lib/db/index.ts+++ /dev/null@@ -1,11 +0,0 @@-import { drizzle } from "drizzle-orm/postgres-js";-import postgres from "postgres";-import * as schema from "./schema";--const connectionString =- process.env.DATABASE_URL ||- "postgres://postgres:postgres@localhost:5432/alook?sslmode=disable";--const client = postgres(connectionString);-export const db = drizzle(client, { schema });-export type Database = typeof db;diff --git a/src/web/lib/db/migrate.ts b/src/web/lib/db/migrate.tsdeleted file mode 100644index a019ade7f..000000000--- a/src/web/lib/db/migrate.ts+++ /dev/null@@ -1,25 +0,0 @@-import { drizzle } from "drizzle-orm/postgres-js";-import { migrate } from "drizzle-orm/postgres-js/migrator";-import postgres from "postgres";-import { log } from "../logger";--const connectionString =- process.env.DATABASE_URL ||- "postgres://postgres:postgres@localhost:5432/alook?sslmode=disable";--async function main() {- const client = postgres(connectionString, { max: 1 });- const db = drizzle(client);-- log.info("Running migrations...");- await migrate(db, { migrationsFolder: "./drizzle" });- log.info("Migrations complete.");-- await client.end();- process.exit(0);-}--main().catch((err) => {- log.error("Migration failed", { err });- process.exit(1);-});diff --git a/src/web/lib/db/queries/.gitkeep b/src/web/lib/db/queries/.gitkeepdeleted file mode 100644index e69de29bb..000000000diff --git a/src/web/lib/db/queries/agent.integration.test.ts b/src/web/lib/db/queries/agent.integration.test.tsdeleted file mode 100644index f40a9b7c7..000000000--- a/src/web/lib/db/queries/agent.integration.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,- seedRuntime,- seedAgent,- seedConversation,-} from "../test-utils";-import { deleteAgent, getAgent } from "./agent";-import { createTask, getTask } from "./task";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--describe("deleteAgent", () => {- it("removes agent and its tasks in a transaction", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);- const conv = await seedConversation(tx, ws.id, agent.id, user.id);-- // Create a task for this agent- const task = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "orphan check",- });-- const deleted = await deleteAgent(tx, agent.id, ws.id);- expect(deleted).not.toBeNull();- expect(deleted!.id).toBe(agent.id);-- // Agent should be gone- const fetchedAgent = await getAgent(tx, agent.id);- expect(fetchedAgent).toBeNull();-- // Task should also be gone (deleted in the transaction)- const fetchedTask = await getTask(tx, task.id);- expect(fetchedTask).toBeNull();- });- });-- it("returns null for non-matching workspace", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- const ws2 = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- // Try to delete with wrong workspace- const result = await deleteAgent(tx, agent.id, ws2.id);- expect(result).toBeNull();-- // Agent should still exist- const fetched = await getAgent(tx, agent.id);- expect(fetched).not.toBeNull();- });- });-});diff --git a/src/web/lib/db/queries/agent.ts b/src/web/lib/db/queries/agent.tsdeleted file mode 100644index 77c472968..000000000--- a/src/web/lib/db/queries/agent.ts+++ /dev/null@@ -1,116 +0,0 @@-import { eq, and, desc } from "drizzle-orm";-import { agent, agentTaskQueue } from "../schema";-import type { Database } from "../index";--export async function getAgent(db: Database, id: string) {- const rows = await db.select().from(agent).where(eq(agent.id, id));- return rows[0] ?? null;-}--export async function getAgentInWorkspace(- db: Database,- id: string,- workspaceId: string-) {- const rows = await db- .select()- .from(agent)- .where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)));- return rows[0] ?? null;-}--export async function listAgents(db: Database, workspaceId: string) {- return db- .select()- .from(agent)- .where(eq(agent.workspaceId, workspaceId))- .orderBy(desc(agent.createdAt));-}--export async function createAgent(- db: Database,- data: {- workspaceId: string;- name: string;- description?: string;- instructions?: string;- avatarUrl?: string | null;- runtimeId?: string | null;- runtimeMode?: string;- runtimeConfig?: unknown;- visibility?: string;- maxConcurrentTasks?: number;- ownerId?: string | null;- tools?: unknown;- triggers?: unknown;- }-) {- const rows = await db- .insert(agent)- .values({- workspaceId: data.workspaceId,- name: data.name,- description: data.description ?? "",- instructions: data.instructions ?? "",- avatarUrl: data.avatarUrl ?? null,- runtimeId: data.runtimeId ?? null,- runtimeMode: data.runtimeMode ?? "local",- runtimeConfig: data.runtimeConfig ?? null,- visibility: data.visibility ?? "private",- maxConcurrentTasks: data.maxConcurrentTasks ?? 6,- ownerId: data.ownerId ?? null,- tools: data.tools ?? null,- triggers: data.triggers ?? null,- })- .returning();- return rows[0]!;-}--export async function deleteAgent(- db: Database,- id: string,- workspaceId: string-) {- return db.transaction(async (tx) => {- await tx- .delete(agentTaskQueue)- .where(eq(agentTaskQueue.agentId, id));- const rows = await tx- .delete(agent)- .where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)))- .returning();- return rows[0] ?? null;- });-}--export async function updateAgent(- db: Database,- id: string,- workspaceId: string,- data: {- name?: string;- description?: string;- instructions?: string;- runtimeId?: string | null;- }-) {- const rows = await db- .update(agent)- .set({ ...data, updatedAt: new Date() })- .where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)))- .returning();- return rows[0] ?? null;-}--export async function updateAgentStatus(- db: Database,- id: string,- status: string-) {- const rows = await db- .update(agent)- .set({ status, updatedAt: new Date() })- .where(eq(agent.id, id))- .returning();- return rows[0] ?? null;-}diff --git a/src/web/lib/db/queries/conversation.integration.test.ts b/src/web/lib/db/queries/conversation.integration.test.tsdeleted file mode 100644index d8fb2f030..000000000--- a/src/web/lib/db/queries/conversation.integration.test.ts+++ /dev/null@@ -1,297 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,- seedRuntime,- seedAgent,- seedConversation,-} from "../test-utils";-import {- createConversation,- getConversation,- listConversationsByAgent,- updateConversationTitle,- deleteConversation,-} from "./conversation";-import { createMessage } from "./message";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--describe("listConversationsByAgent", () => {- it("returns correct message_count for conversations with messages", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, {- workspaceId: ws.id,- agentId: agent.id,- userId: user.id,- title: "",- });-- await createMessage(tx, { conversationId: conv.id, role: "user", content: "hello" });- await createMessage(tx, { conversationId: conv.id, role: "assistant", content: "hi" });- await createMessage(tx, { conversationId: conv.id, role: "user", content: "bye" });-- const result = await listConversationsByAgent(tx, ws.id, user.id, agent.id);- expect(result).toHaveLength(1);- expect(result[0].messageCount).toBe(3);- });- });-- it("returns 0 message_count for empty conversations", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- await createConversation(tx, {- workspaceId: ws.id,- agentId: agent.id,- userId: user.id,- title: "",- });-- const result = await listConversationsByAgent(tx, ws.id, user.id, agent.id);- expect(result).toHaveLength(1);- expect(result[0].messageCount).toBe(0);- });- });-- it("filters by agent, workspace, and user correctly", async () => {- await withTestTransaction(db, async (tx) => {- const user1 = await seedUser(tx);- const user2 = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user1.id);- await seedMember(tx, ws.id, user2.id);- const rt = await seedRuntime(tx, ws.id);- const agent1 = await seedAgent(tx, ws.id, rt.id, user1.id);- const agent2 = await seedAgent(tx, ws.id, rt.id, user2.id);-- // Create conversations for different agents/users- await createConversation(tx, { workspaceId: ws.id, agentId: agent1.id, userId: user1.id, title: "" });- await createConversation(tx, { workspaceId: ws.id, agentId: agent2.id, userId: user1.id, title: "" });- await createConversation(tx, { workspaceId: ws.id, agentId: agent1.id, userId: user2.id, title: "" });-- const result = await listConversationsByAgent(tx, ws.id, user1.id, agent1.id);- expect(result).toHaveLength(1);- });- });-- it("orders by newest first", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- // Insert with explicit createdAt since now() is fixed within a transaction- const earlier = new Date("2024-01-01T00:00:00Z");- const later = new Date("2024-01-02T00:00:00Z");-- const conv1 = await seedConversation(tx, ws.id, agent.id, user.id, { title: "first", createdAt: earlier });- const conv2 = await seedConversation(tx, ws.id, agent.id, user.id, { title: "second", createdAt: later });-- const result = await listConversationsByAgent(tx, ws.id, user.id, agent.id);- expect(result).toHaveLength(2);- // Newest first- expect(result[0].id).toBe(conv2.id);- expect(result[1].id).toBe(conv1.id);- });- });-- it("returns empty array for non-existent agent", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);-- const result = await listConversationsByAgent(tx, ws.id, user.id, "00000000-0000-0000-0000-000000000000");- expect(result).toEqual([]);- });- });-});--describe("updateConversationTitle", () => {- it("sets title when current title is empty", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "" });-- const updated = await updateConversationTitle(tx, conv.id, "New Title");- expect(updated).not.toBeNull();- expect(updated!.title).toBe("New Title");- });- });-- it("returns null when title is already non-empty (no overwrite)", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "Existing" });-- const result = await updateConversationTitle(tx, conv.id, "Overwrite Attempt");- expect(result).toBeNull();-- // Verify title unchanged- const fetched = await getConversation(tx, conv.id);- expect(fetched!.title).toBe("Existing");- });- });-- it("concurrent calls — only first one wins", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "" });-- const [r1, r2] = await Promise.all([- updateConversationTitle(tx, conv.id, "Title A"),- updateConversationTitle(tx, conv.id, "Title B"),- ]);-- // Exactly one should succeed- const successes = [r1, r2].filter((r) => r !== null);- expect(successes).toHaveLength(1);-- const fetched = await getConversation(tx, conv.id);- expect(["Title A", "Title B"]).toContain(fetched!.title);- });- });-});--describe("deleteConversation", () => {- it("removes the conversation row", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "" });-- const deleted = await deleteConversation(tx, conv.id);- expect(deleted).not.toBeNull();- expect(deleted!.id).toBe(conv.id);-- const fetched = await getConversation(tx, conv.id);- expect(fetched).toBeNull();- });- });-- it("returns null for non-existent ID", async () => {- await withTestTransaction(db, async (tx) => {- const result = await deleteConversation(tx, "00000000-0000-0000-0000-000000000000");- expect(result).toBeNull();- });- });-});--describe("createConversation", () => {- it("inserts and returns with generated UUID", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, {- workspaceId: ws.id,- agentId: agent.id,- userId: user.id,- title: "My Conversation",- });-- expect(conv.id).toBeDefined();- expect(conv.title).toBe("My Conversation");- expect(conv.workspaceId).toBe(ws.id);- expect(conv.agentId).toBe(agent.id);- });- });-});--describe("getConversation", () => {- it("returns row by ID", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "Test" });-- const fetched = await getConversation(tx, conv.id);- expect(fetched).not.toBeNull();- expect(fetched!.id).toBe(conv.id);- expect(fetched!.title).toBe("Test");- });- });-- it("returns null for non-existent ID", async () => {- await withTestTransaction(db, async (tx) => {- const result = await getConversation(tx, "00000000-0000-0000-0000-000000000000");- expect(result).toBeNull();- });- });-});--describe("transaction rollback isolation", () => {- it("data inserted in one test is not visible in the next test", async () => {- let insertedId: string | undefined;-- // First transaction: insert a conversation- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);-- const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "ephemeral" });- insertedId = conv.id;-- // Visible inside the transaction- const fetched = await getConversation(tx, conv.id);- expect(fetched).not.toBeNull();- });-- // Second transaction: that ID should not exist- await withTestTransaction(db, async (tx) => {- const fetched = await getConversation(tx, insertedId!);- expect(fetched).toBeNull();- });- });-});diff --git a/src/web/lib/db/queries/conversation.test.ts b/src/web/lib/db/queries/conversation.test.tsdeleted file mode 100644index d2d3b3b41..000000000--- a/src/web/lib/db/queries/conversation.test.ts+++ /dev/null@@ -1,181 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--// Mock drizzle-orm operators to be pass-through-vi.mock("drizzle-orm", () => ({- eq: vi.fn((...args: any[]) => ({ _op: "eq", args })),- and: vi.fn((...args: any[]) => ({ _op: "and", args })),- desc: vi.fn((col: any) => ({ _op: "desc", col })),- count: vi.fn((col?: any) => ({ _op: "count", col, mapWith: vi.fn(() => ({ _op: "count_mapped", col })) })),-}));--vi.mock("@/lib/db/schema", () => ({- conversation: {- id: "conversation.id",- workspaceId: "conversation.workspaceId",- agentId: "conversation.agentId",- userId: "conversation.userId",- title: "conversation.title",- createdAt: "conversation.createdAt",- },- message: {- id: "message.id",- conversationId: "message.conversationId",- },-}));--beforeEach(() => vi.clearAllMocks());--function createMockDb(result: any = []) {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.orderBy = vi.fn(() => chain);- chain.leftJoin = vi.fn(() => chain);- chain.groupBy = vi.fn(() => chain);- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve(result));- chain.update = vi.fn(() => chain);- chain.set = vi.fn(() => chain);- chain.delete = vi.fn(() => chain);- // Make the chain itself thenable so await db.select()...orderBy() works- chain.then = (resolve: any) => resolve(result);- return chain;-}--describe("listConversationsByAgent", () => {- it("calls select with correct fields including message count", async () => {- const mockRows = [- { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1", title: "Test", createdAt: new Date(), messageCount: 3 },- { id: "c2", workspaceId: "w1", agentId: "a1", userId: "u1", title: "", createdAt: new Date(), messageCount: 0 },- ];- const db = createMockDb(mockRows);-- const { listConversationsByAgent } = await import("./conversation");- const result = await listConversationsByAgent(db as any, "w1", "u1", "a1");-- expect(result).toHaveLength(2);- expect(result[0].messageCount).toBe(3);- expect(result[1].messageCount).toBe(0);- expect(db.select).toHaveBeenCalled();- expect(db.from).toHaveBeenCalled();- expect(db.leftJoin).toHaveBeenCalled();- expect(db.groupBy).toHaveBeenCalled();- expect(db.where).toHaveBeenCalled();- expect(db.orderBy).toHaveBeenCalled();- });-- it("returns empty array when no conversations exist", async () => {- const db = createMockDb([]);-- const { listConversationsByAgent } = await import("./conversation");- const result = await listConversationsByAgent(db as any, "w1", "u1", "a1");-- expect(result).toEqual([]);- });-});--describe("updateConversationTitle", () => {- it("returns the updated row when title was empty", async () => {- const updated = { id: "c1", title: "New title" };- const db = createMockDb([updated]);-- const { updateConversationTitle } = await import("./conversation");- const result = await updateConversationTitle(db as any, "c1", "New title");-- expect(result).toEqual(updated);- expect(db.update).toHaveBeenCalled();- expect(db.set).toHaveBeenCalledWith({ title: "New title" });- });-- it("returns null when title was already set (no rows matched)", async () => {- const db = createMockDb([]);-- const { updateConversationTitle } = await import("./conversation");- const result = await updateConversationTitle(db as any, "c1", "New title");-- expect(result).toBeNull();- });-});--describe("deleteConversation", () => {- it("returns the deleted row", async () => {- const deleted = { id: "c1" };- const db = createMockDb([deleted]);-- const { deleteConversation } = await import("./conversation");- const result = await deleteConversation(db as any, "c1");-- expect(result).toEqual(deleted);- expect(db.delete).toHaveBeenCalled();- });-- it("returns null when conversation not found", async () => {- const db = createMockDb([]);-- const { deleteConversation } = await import("./conversation");- const result = await deleteConversation(db as any, "c999");-- expect(result).toBeNull();- });-});--describe("listConversations", () => {- it("returns conversations for workspace and user", async () => {- const rows = [{ id: "c1" }, { id: "c2" }];- const db = createMockDb(rows);-- const { listConversations } = await import("./conversation");- const result = await listConversations(db as any, "w1", "u1");-- expect(result).toHaveLength(2);- expect(db.select).toHaveBeenCalled();- expect(db.where).toHaveBeenCalled();- });-});--describe("createConversation", () => {- it("inserts and returns the new conversation", async () => {- const created = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1", title: "" };- const db = createMockDb([created]);-- const { createConversation } = await import("./conversation");- const result = await createConversation(db as any, {- workspaceId: "w1",- agentId: "a1",- userId: "u1",- title: "",- });-- expect(result).toEqual(created);- expect(db.insert).toHaveBeenCalled();- expect(db.values).toHaveBeenCalledWith({- workspaceId: "w1",- agentId: "a1",- userId: "u1",- title: "",- });- });-});--describe("getConversation", () => {- it("returns conversation when found", async () => {- const conv = { id: "c1", workspaceId: "w1" };- const db = createMockDb([conv]);-- const { getConversation } = await import("./conversation");- const result = await getConversation(db as any, "c1");-- expect(result).toEqual(conv);- });-- it("returns null when not found", async () => {- const db = createMockDb([]);-- const { getConversation } = await import("./conversation");- const result = await getConversation(db as any, "c999");-- expect(result).toBeNull();- });-});diff --git a/src/web/lib/db/queries/conversation.ts b/src/web/lib/db/queries/conversation.tsdeleted file mode 100644index b2f702b2c..000000000--- a/src/web/lib/db/queries/conversation.ts+++ /dev/null@@ -1,99 +0,0 @@-import { eq, and, desc, count } from "drizzle-orm";-import { conversation, message } from "../schema";-import type { Database } from "../index";--export async function createConversation(- db: Database,- data: {- workspaceId: string;- agentId: string;- userId: string;- title: string;- }-) {- const rows = await db- .insert(conversation)- .values({- workspaceId: data.workspaceId,- agentId: data.agentId,- userId: data.userId,- title: data.title,- })- .returning();- return rows[0]!;-}--export async function getConversation(db: Database, id: string) {- const rows = await db- .select()- .from(conversation)- .where(eq(conversation.id, id));- return rows[0] ?? null;-}--export async function listConversations(- db: Database,- workspaceId: string,- userId: string-) {- return db- .select()- .from(conversation)- .where(- and(- eq(conversation.workspaceId, workspaceId),- eq(conversation.userId, userId)- )- )- .orderBy(desc(conversation.createdAt));-}--export async function listConversationsByAgent(- db: Database,- workspaceId: string,- userId: string,- agentId: string-) {- return db- .select({- id: conversation.id,- workspaceId: conversation.workspaceId,- agentId: conversation.agentId,- userId: conversation.userId,- title: conversation.title,- createdAt: conversation.createdAt,- messageCount: count(message.id).mapWith(Number),- })- .from(conversation)- .leftJoin(message, eq(message.conversationId, conversation.id))- .where(- and(- eq(conversation.workspaceId, workspaceId),- eq(conversation.userId, userId),- eq(conversation.agentId, agentId)- )- )- .groupBy(conversation.id)- .orderBy(desc(conversation.createdAt));-}--export async function updateConversationTitle(- db: Database,- id: string,- title: string-) {- const rows = await db- .update(conversation)- .set({ title })- .where(and(eq(conversation.id, id), eq(conversation.title, "")))- .returning();- return rows[0] ?? null;-}--export async function deleteConversation(db: Database, id: string) {- const rows = await db- .delete(conversation)- .where(eq(conversation.id, id))- .returning();- return rows[0] ?? null;-}diff --git a/src/web/lib/db/queries/machine-token.integration.test.ts b/src/web/lib/db/queries/machine-token.integration.test.tsdeleted file mode 100644index 3b2f157bf..000000000--- a/src/web/lib/db/queries/machine-token.integration.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,-} from "../test-utils";-import { createMachineToken, getMachineTokenByHash } from "./machine-token";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--describe("getMachineTokenByHash", () => {- it("returns token with joined userEmail", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx, { email: "[email protected]" });- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);-- const token = await createMachineToken(tx, {- userId: user.id,- workspaceId: ws.id,- tokenHash: "hash-abc-123",- name: "My Token",- });-- const result = await getMachineTokenByHash(tx, "hash-abc-123");- expect(result).not.toBeNull();- expect(result!.id).toBe(token.id);- expect(result!.userEmail).toBe("[email protected]");- expect(result!.name).toBe("My Token");- expect(result!.workspaceId).toBe(ws.id);- });- });-- it("returns null for non-existent hash", async () => {- await withTestTransaction(db, async (tx) => {- const result = await getMachineTokenByHash(tx, "nonexistent-hash");- expect(result).toBeNull();- });- });-});diff --git a/src/web/lib/db/queries/machine-token.ts b/src/web/lib/db/queries/machine-token.tsdeleted file mode 100644index 35e1038fe..000000000--- a/src/web/lib/db/queries/machine-token.ts+++ /dev/null@@ -1,76 +0,0 @@-import { eq, and, desc } from "drizzle-orm";-import { machineToken, user } from "../schema";-import type { Database } from "../index";--export async function createMachineToken(- db: Database,- data: {- userId: string;- workspaceId: string;- tokenHash: string;- name: string;- }-) {- const rows = await db- .insert(machineToken)- .values({- userId: data.userId,- workspaceId: data.workspaceId,- tokenHash: data.tokenHash,- name: data.name,- })- .returning();- return rows[0]!;-}--export async function getMachineTokenByHash(db: Database, tokenHash: string) {- const rows = await db- .select({- id: machineToken.id,- userId: machineToken.userId,- workspaceId: machineToken.workspaceId,- tokenHash: machineToken.tokenHash,- name: machineToken.name,- lastUsedAt: machineToken.lastUsedAt,- createdAt: machineToken.createdAt,- userEmail: user.email,- })- .from(machineToken)- .innerJoin(user, eq(user.id, machineToken.userId))- .where(eq(machineToken.tokenHash, tokenHash));- return rows[0] ?? null;-}--export async function listMachineTokens(- db: Database,- userId: string,- workspaceId: string-) {- return db- .select()- .from(machineToken)- .where(- and(- eq(machineToken.userId, userId),- eq(machineToken.workspaceId, workspaceId)- )- )- .orderBy(desc(machineToken.createdAt));-}--export async function deleteMachineToken(- db: Database,- id: string,- userId: string-) {- await db- .delete(machineToken)- .where(and(eq(machineToken.id, id), eq(machineToken.userId, userId)));-}--export async function updateMachineTokenLastUsed(db: Database, id: string) {- await db- .update(machineToken)- .set({ lastUsedAt: new Date() })- .where(eq(machineToken.id, id));-}diff --git a/src/web/lib/db/queries/member.ts b/src/web/lib/db/queries/member.tsdeleted file mode 100644index 4c8ef68db..000000000--- a/src/web/lib/db/queries/member.ts+++ /dev/null@@ -1,34 +0,0 @@-import { eq, and } from "drizzle-orm";-import { member } from "../schema";-import type { Database } from "../index";--export async function getMemberByUserAndWorkspace(- db: Database,- userId: string,- workspaceId: string-) {- const rows = await db- .select()- .from(member)- .where(and(eq(member.userId, userId), eq(member.workspaceId, workspaceId)));- return rows[0] ?? null;-}--export async function listMembers(db: Database, workspaceId: string) {- return db.select().from(member).where(eq(member.workspaceId, workspaceId));-}--export async function createMember(- db: Database,- data: { workspaceId: string; userId: string; role: string }-) {- const rows = await db- .insert(member)- .values({- workspaceId: data.workspaceId,- userId: data.userId,- role: data.role,- })- .returning();- return rows[0]!;-}diff --git a/src/web/lib/db/queries/message.ts b/src/web/lib/db/queries/message.tsdeleted file mode 100644index 9fdbc524e..000000000--- a/src/web/lib/db/queries/message.ts+++ /dev/null@@ -1,37 +0,0 @@-import { eq, asc } from "drizzle-orm";-import { message } from "../schema";-import type { Database } from "../index";--export async function createMessage(- db: Database,- data: {- conversationId: string;- role: string;- content: string;- taskId?: string | null;- }-) {- const rows = await db- .insert(message)- .values({- conversationId: data.conversationId,- role: data.role,- content: data.content,- taskId: data.taskId ?? null,- })- .returning();- return rows[0]!;-}--export async function listMessages(db: Database, conversationId: string) {- return db- .select()- .from(message)- .where(eq(message.conversationId, conversationId))- .orderBy(asc(message.createdAt));-}--export async function getMessage(db: Database, id: string) {- const rows = await db.select().from(message).where(eq(message.id, id));- return rows[0] ?? null;-}diff --git a/src/web/lib/db/queries/runtime.integration.test.ts b/src/web/lib/db/queries/runtime.integration.test.tsdeleted file mode 100644index aa3320f53..000000000--- a/src/web/lib/db/queries/runtime.integration.test.ts+++ /dev/null@@ -1,218 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,- seedRuntime,- seedAgent,- seedConversation,-} from "../test-utils";-import {- upsertAgentRuntime,- getAgentRuntime,- deleteRuntimesByDaemonId,- markStaleRuntimesOffline,-} from "./runtime";-import { getAgent } from "./agent";-import { createTask, getTask } from "./task";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--describe("upsertAgentRuntime", () => {- it("inserts new runtime on first call", async () => {- await withTestTransaction(db, async (tx) => {- const ws = await seedWorkspace(tx);-- const rt = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "daemon-1",- name: "My Runtime",- runtimeMode: "local",- provider: "claude",- status: "online",- deviceInfo: "macOS",- });-- expect(rt.id).toBeDefined();- expect(rt.name).toBe("My Runtime");- expect(rt.status).toBe("online");- expect(rt.provider).toBe("claude");- });- });-- it("updates existing runtime on conflict (same workspace+daemon+provider)", async () => {- await withTestTransaction(db, async (tx) => {- const ws = await seedWorkspace(tx);-- const rt1 = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "daemon-1",- name: "Original",- runtimeMode: "local",- provider: "claude",- status: "online",- deviceInfo: "macOS",- });-- const rt2 = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "daemon-1",- name: "Updated",- runtimeMode: "remote",- provider: "claude",- status: "offline",- deviceInfo: "Linux",- });-- // Same ID (upsert, not new row)- expect(rt2.id).toBe(rt1.id);- // Fields updated- expect(rt2.name).toBe("Updated");- expect(rt2.status).toBe("offline");- expect(rt2.deviceInfo).toBe("Linux");- });- });-});--describe("deleteRuntimesByDaemonId", () => {- it("nulls agent.runtimeId, deletes tasks, deletes runtimes", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);- const conv = await seedConversation(tx, ws.id, agent.id, user.id);-- const task = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "will be deleted",- });-- await deleteRuntimesByDaemonId(tx, rt.daemonId, ws.id);-- // Runtime should be gone- const fetchedRt = await getAgentRuntime(tx, rt.id);- expect(fetchedRt).toBeNull();-- // Agent should still exist but runtimeId nulled- const fetchedAgent = await getAgent(tx, agent.id);- expect(fetchedAgent).not.toBeNull();- expect(fetchedAgent!.runtimeId).toBeNull();-- // Task should be gone- const fetchedTask = await getTask(tx, task.id);- expect(fetchedTask).toBeNull();- });- });-- it("is a no-op when no runtimes match", async () => {- await withTestTransaction(db, async (tx) => {- const ws = await seedWorkspace(tx);-- // Should not throw- await deleteRuntimesByDaemonId(tx, "nonexistent-daemon", ws.id);- });- });-});--describe("markStaleRuntimesOffline", () => {- it("marks online runtimes with old lastSeenAt as offline", async () => {- await withTestTransaction(db, async (tx) => {- const ws = await seedWorkspace(tx);-- // Create a runtime that was last seen 2 minutes ago- const rt = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "stale-daemon",- name: "Stale",- runtimeMode: "local",- provider: "claude",- status: "online",- deviceInfo: "macOS",- });-- // Manually backdate lastSeenAt by updating it- // We need to use the raw DB to set an old timestamp- const { agentRuntime } = await import("../schema");- const { eq } = await import("drizzle-orm");- const oldDate = new Date(Date.now() - 120 * 1000); // 2 minutes ago- await (tx as any).update(agentRuntime).set({ lastSeenAt: oldDate }).where(eq(agentRuntime.id, rt.id));-- await markStaleRuntimesOffline(tx, ws.id);-- const fetched = await getAgentRuntime(tx, rt.id);- expect(fetched!.status).toBe("offline");- });- });-- it("marks online runtimes with null lastSeenAt as offline", async () => {- await withTestTransaction(db, async (tx) => {- const ws = await seedWorkspace(tx);-- const rt = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "null-heartbeat",- name: "No Heartbeat",- runtimeMode: "local",- provider: "claude",- status: "online",- deviceInfo: "macOS",- });-- // Set lastSeenAt to null- const { agentRuntime } = await import("../schema");- const { eq } = await import("drizzle-orm");- await (tx as any).update(agentRuntime).set({ lastSeenAt: null }).where(eq(agentRuntime.id, rt.id));-- await markStaleRuntimesOffline(tx, ws.id);-- const fetched = await getAgentRuntime(tx, rt.id);- expect(fetched!.status).toBe("offline");- });- });-- it("does not affect recently seen or already offline runtimes", async () => {- await withTestTransaction(db, async (tx) => {- const ws = await seedWorkspace(tx);-- // Recently seen online runtime- const rtOnline = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "fresh-daemon",- name: "Fresh",- runtimeMode: "local",- provider: "claude",- status: "online",- deviceInfo: "macOS",- });-- // Already offline runtime- const rtOffline = await upsertAgentRuntime(tx, {- workspaceId: ws.id,- daemonId: "offline-daemon",- name: "Offline",- runtimeMode: "local",- provider: "claude",- status: "offline",- deviceInfo: "macOS",- });-- await markStaleRuntimesOffline(tx, ws.id);-- const fetchedOnline = await getAgentRuntime(tx, rtOnline.id);- expect(fetchedOnline!.status).toBe("online"); // still online (recent heartbeat)-- const fetchedOffline = await getAgentRuntime(tx, rtOffline.id);- expect(fetchedOffline!.status).toBe("offline"); // unchanged- });- });-});diff --git a/src/web/lib/db/queries/runtime.ts b/src/web/lib/db/queries/runtime.tsdeleted file mode 100644index cafcc7824..000000000--- a/src/web/lib/db/queries/runtime.ts+++ /dev/null@@ -1,160 +0,0 @@-import { eq, and, asc, or, lt, isNull } from "drizzle-orm";-import { agentRuntime, agent, agentTaskQueue } from "../schema";-import type { Database } from "../index";--export async function upsertAgentRuntime(- db: Database,- data: {- workspaceId: string;- daemonId: string;- name: string;- runtimeMode: string;- provider: string;- status: string;- deviceInfo: string;- metadata?: unknown;- }-) {- const now = new Date();- const rows = await db- .insert(agentRuntime)- .values({- workspaceId: data.workspaceId,- daemonId: data.daemonId,- name: data.name,- runtimeMode: data.runtimeMode,- provider: data.provider,- status: data.status,- deviceInfo: data.deviceInfo,- metadata: data.metadata ?? null,- lastSeenAt: now,- })- .onConflictDoUpdate({- target: [- agentRuntime.workspaceId,- agentRuntime.daemonId,- agentRuntime.provider,- ],- set: {- name: data.name,- runtimeMode: data.runtimeMode,- status: data.status,- deviceInfo: data.deviceInfo,- metadata: data.metadata ?? null,- lastSeenAt: now,- updatedAt: now,- },- })- .returning();- return rows[0]!;-}--export async function listAgentRuntimes(db: Database, workspaceId: string) {- return db- .select()- .from(agentRuntime)- .where(eq(agentRuntime.workspaceId, workspaceId))- .orderBy(asc(agentRuntime.createdAt));-}--export async function getAgentRuntime(db: Database, id: string) {- const rows = await db- .select()- .from(agentRuntime)- .where(eq(agentRuntime.id, id));- return rows[0] ?? null;-}--export async function getAgentRuntimeForWorkspace(- db: Database,- id: string,- workspaceId: string-) {- const rows = await db- .select()- .from(agentRuntime)- .where(- and(eq(agentRuntime.id, id), eq(agentRuntime.workspaceId, workspaceId))- );- return rows[0] ?? null;-}--export async function updateAgentRuntimeHeartbeat(db: Database, id: string) {- const now = new Date();- const rows = await db- .update(agentRuntime)- .set({ lastSeenAt: now, status: "online", updatedAt: now })- .where(eq(agentRuntime.id, id))- .returning();- return rows[0] ?? null;-}--export async function setAgentRuntimeOffline(db: Database, id: string) {- await db- .update(agentRuntime)- .set({ status: "offline", updatedAt: new Date() })- .where(eq(agentRuntime.id, id));-}--export async function deleteRuntimesByDaemonId(- db: Database,- daemonId: string,- workspaceId: string-) {- // Find runtime IDs to delete- const runtimes = await db- .select({ id: agentRuntime.id })- .from(agentRuntime)- .where(- and(- eq(agentRuntime.daemonId, daemonId),- eq(agentRuntime.workspaceId, workspaceId)- )- );-- if (runtimes.length === 0) return;-- const ids = runtimes.map((r) => r.id);-- // Null out agent references and delete tasks per runtime- for (const id of ids) {- await db- .update(agent)- .set({ runtimeId: null, updatedAt: new Date() })- .where(eq(agent.runtimeId, id));-- await db- .delete(agentTaskQueue)- .where(eq(agentTaskQueue.runtimeId, id));- }-- // Delete the runtimes- await db- .delete(agentRuntime)- .where(- and(- eq(agentRuntime.daemonId, daemonId),- eq(agentRuntime.workspaceId, workspaceId)- )- );-}--export async function markStaleRuntimesOffline(- db: Database,- workspaceId: string-) {- const threshold = new Date(Date.now() - 45 * 1000);- await db- .update(agentRuntime)- .set({ status: "offline", updatedAt: new Date() })- .where(- and(- eq(agentRuntime.workspaceId, workspaceId),- eq(agentRuntime.status, "online"),- or(- lt(agentRuntime.lastSeenAt, threshold),- isNull(agentRuntime.lastSeenAt)- )- )- );-}diff --git a/src/web/lib/db/queries/task-extended.integration.test.ts b/src/web/lib/db/queries/task-extended.integration.test.tsdeleted file mode 100644index 27ce71b91..000000000--- a/src/web/lib/db/queries/task-extended.integration.test.ts+++ /dev/null@@ -1,269 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,- seedRuntime,- seedAgent,- seedConversation,-} from "../test-utils";-import {- createTask,- claimTask,- startTask,- completeTask,- failTask,- cancelTask,- failStaleDispatchedTasks,- getLastTaskSession,- listPendingTasksByRuntime,-} from "./task";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--async function seedFullChain(tx: any) {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);- const conv = await seedConversation(tx, ws.id, agent.id, user.id);- return { user, ws, rt, agent, conv };-}--describe("claimTask", () => {- it("claims the highest-priority queued task", async () => {- await withTestTransaction(db, async (tx) => {- const { user, ws, rt, agent, conv } = await seedFullChain(tx);- const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);- const conv3 = await seedConversation(tx, ws.id, agent.id, user.id);-- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "low priority", priority: 1,- });- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv2.id, prompt: "high priority", priority: 10,- });- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv3.id, prompt: "medium priority", priority: 5,- });-- const claimed = await claimTask(tx, agent.id);- expect(claimed).not.toBeNull();- expect(claimed!.prompt).toBe("high priority");- expect(claimed!.status).toBe("dispatched");- });- });-- it("skips conversations that already have dispatched/running tasks", async () => {- await withTestTransaction(db, async (tx) => {- const { user, ws, rt, agent, conv } = await seedFullChain(tx);- const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);-- // Create and claim task in conv (now dispatched)- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "already active",- });- await claimTask(tx, agent.id);-- // Create queued task in conv2- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv2.id, prompt: "should be claimed",- });-- const claimed = await claimTask(tx, agent.id);- expect(claimed).not.toBeNull();- expect(claimed!.prompt).toBe("should be claimed");- });- });-- it("returns null when no queued tasks exist", async () => {- await withTestTransaction(db, async (tx) => {- const { agent } = await seedFullChain(tx);- const result = await claimTask(tx, agent.id);- expect(result).toBeNull();- });- });-});--describe("failTask", () => {- it("transitions dispatched/running task to failed with error message", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "will fail",- });-- const claimed = await claimTask(tx, agent.id);- const failed = await failTask(tx, claimed!.id, "something broke");- expect(failed).not.toBeNull();- expect(failed!.status).toBe("failed");- expect(failed!.error).toBe("something broke");- expect(failed!.completedAt).not.toBeNull();- });- });-- it("returns null for queued/completed tasks (wrong state)", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- const task = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "queued task",- });-- // Can't fail a queued task (must be dispatched or running)- const result = await failTask(tx, task.id, "nope");- expect(result).toBeNull();- });- });-});--describe("cancelTask", () => {- it("transitions queued/dispatched/running task to cancelled", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- const task = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "cancel me",- });-- const cancelled = await cancelTask(tx, task.id);- expect(cancelled).not.toBeNull();- expect(cancelled!.status).toBe("cancelled");- expect(cancelled!.completedAt).not.toBeNull();- });- });-- it("returns null for already completed/failed tasks", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "will complete",- });-- const claimed = await claimTask(tx, agent.id);- await startTask(tx, claimed!.id);- await completeTask(tx, claimed!.id, { result: {}, sessionId: null, workDir: null });-- const result = await cancelTask(tx, claimed!.id);- expect(result).toBeNull();- });- });-});--describe("failStaleDispatchedTasks", () => {- it("fails tasks dispatched more than N seconds ago", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "stale task",- });-- // Claim to get it dispatched- const claimed = await claimTask(tx, agent.id);- expect(claimed).not.toBeNull();-- // Use a very short staleSeconds (0) so the just-dispatched task is already stale- const failed = await failStaleDispatchedTasks(tx, 0);- expect(failed.length).toBe(1);- expect(failed[0].agentId).toBe(agent.id);- });- });-- it("does not fail recently dispatched tasks", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "fresh task",- });-- await claimTask(tx, agent.id);-- // Use a long staleSeconds so nothing is stale- const failed = await failStaleDispatchedTasks(tx, 9999);- expect(failed).toHaveLength(0);- });- });-});--describe("getLastTaskSession", () => {- it("returns sessionId/workDir from most recent completed task", async () => {- await withTestTransaction(db, async (tx) => {- const { user, ws, rt, agent, conv } = await seedFullChain(tx);-- // Create, claim, start, complete a task with session info- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "task with session",- });- const claimed = await claimTask(tx, agent.id);- await startTask(tx, claimed!.id);- await completeTask(tx, claimed!.id, {- result: { ok: true },- sessionId: "sess-123",- workDir: "/tmp/work",- });-- const session = await getLastTaskSession(tx, agent.id, conv.id);- expect(session).not.toBeNull();- expect(session!.sessionId).toBe("sess-123");- expect(session!.workDir).toBe("/tmp/work");- });- });-- it("returns null when no completed tasks with sessionId exist", async () => {- await withTestTransaction(db, async (tx) => {- const { agent, conv } = await seedFullChain(tx);-- const session = await getLastTaskSession(tx, agent.id, conv.id);- expect(session).toBeNull();- });- });-});--describe("listPendingTasksByRuntime", () => {- it("returns queued/dispatched tasks ordered by priority desc, createdAt asc", async () => {- await withTestTransaction(db, async (tx) => {- const { user, ws, rt, agent, conv } = await seedFullChain(tx);- const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);- const conv3 = await seedConversation(tx, ws.id, agent.id, user.id);-- const t1 = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "low", priority: 1,- });- const t2 = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv2.id, prompt: "high", priority: 10,- });- const t3 = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv3.id, prompt: "medium", priority: 5,- });-- const pending = await listPendingTasksByRuntime(tx, rt.id);- expect(pending).toHaveLength(3);- // Ordered by priority desc- expect(pending[0].id).toBe(t2.id);- expect(pending[1].id).toBe(t3.id);- expect(pending[2].id).toBe(t1.id);- });- });-});diff --git a/src/web/lib/db/queries/task-message.ts b/src/web/lib/db/queries/task-message.tsdeleted file mode 100644index a32169955..000000000--- a/src/web/lib/db/queries/task-message.ts+++ /dev/null@@ -1,54 +0,0 @@-import { eq, and, gt, asc } from "drizzle-orm";-import { taskMessage } from "../schema";-import type { Database } from "../index";--export async function createTaskMessage(- db: Database,- data: {- taskId: string;- seq: number;- type: string;- tool: string;- content: string;- input?: unknown;- output: string;- }-) {- const rows = await db- .insert(taskMessage)- .values({- taskId: data.taskId,- seq: data.seq,- type: data.type,- tool: data.tool,- content: data.content,- input: data.input ?? null,- output: data.output,- })- .returning();- return rows[0]!;-}--export async function listTaskMessages(db: Database, taskId: string) {- return db- .select()- .from(taskMessage)- .where(eq(taskMessage.taskId, taskId))- .orderBy(asc(taskMessage.seq));-}--export async function listTaskMessagesSince(- db: Database,- taskId: string,- afterSeq: number-) {- return db- .select()- .from(taskMessage)- .where(and(eq(taskMessage.taskId, taskId), gt(taskMessage.seq, afterSeq)))- .orderBy(asc(taskMessage.seq));-}--export async function deleteTaskMessages(db: Database, taskId: string) {- await db.delete(taskMessage).where(eq(taskMessage.taskId, taskId));-}diff --git a/src/web/lib/db/queries/task-queries.test.ts b/src/web/lib/db/queries/task-queries.test.tsdeleted file mode 100644index d9738f76d..000000000--- a/src/web/lib/db/queries/task-queries.test.ts+++ /dev/null@@ -1,184 +0,0 @@-/**- * Tests for task DB query functions (not Zod schema — that's in task.test.ts).- */-import { describe, it, expect, vi, beforeEach } from "vitest";--vi.mock("drizzle-orm", () => ({- eq: vi.fn((...args: any[]) => ({ _op: "eq", args })),- and: vi.fn((...args: any[]) => ({ _op: "and", args })),- desc: vi.fn((col: any) => ({ _op: "desc", col })),- asc: vi.fn((col: any) => ({ _op: "asc", col })),- inArray: vi.fn((...args: any[]) => ({ _op: "inArray", args })),- notInArray: vi.fn((...args: any[]) => ({ _op: "notInArray", args })),- isNotNull: vi.fn((col: any) => ({ _op: "isNotNull", col })),- count: vi.fn(() => "count(*)"),- lt: vi.fn((...args: any[]) => ({ _op: "lt", args })),-}));--vi.mock("@/lib/db/schema", () => ({- agentTaskQueue: {- id: "agentTaskQueue.id",- agentId: "agentTaskQueue.agentId",- runtimeId: "agentTaskQueue.runtimeId",- workspaceId: "agentTaskQueue.workspaceId",- conversationId: "agentTaskQueue.conversationId",- prompt: "agentTaskQueue.prompt",- status: "agentTaskQueue.status",- priority: "agentTaskQueue.priority",- dispatchedAt: "agentTaskQueue.dispatchedAt",- startedAt: "agentTaskQueue.startedAt",- completedAt: "agentTaskQueue.completedAt",- sessionId: "agentTaskQueue.sessionId",- workDir: "agentTaskQueue.workDir",- error: "agentTaskQueue.error",- result: "agentTaskQueue.result",- createdAt: "agentTaskQueue.createdAt",- },-}));--vi.mock("@alook/shared", () => ({- ClaimedTaskRowSchema: { parse: vi.fn((v: any) => v) },-}));--beforeEach(() => vi.clearAllMocks());--function createMockDb(result: any = []) {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.orderBy = vi.fn(() => chain);- chain.limit = vi.fn(() => chain);- chain.for = vi.fn(() => chain);- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve(result));- chain.update = vi.fn(() => chain);- chain.set = vi.fn(() => chain);- chain.delete = vi.fn(() => chain);- chain.then = (resolve: any) => resolve(result);- return chain;-}--describe("deleteTasksByConversation", () => {- it("deletes all tasks for a conversation", async () => {- const deleted = [{ id: "t1" }, { id: "t2" }];- const db = createMockDb(deleted);-- const { deleteTasksByConversation } = await import("./task");- const result = await deleteTasksByConversation(db as any, "c1");-- expect(result).toEqual(deleted);- expect(db.delete).toHaveBeenCalled();- expect(db.where).toHaveBeenCalled();- });-- it("returns empty array when no tasks exist", async () => {- const db = createMockDb([]);-- const { deleteTasksByConversation } = await import("./task");- const result = await deleteTasksByConversation(db as any, "c1");-- expect(result).toEqual([]);- });-});--describe("hasPendingTaskForConversation", () => {- it("returns true when pending tasks exist", async () => {- const db = createMockDb([{ id: "t1" }]);-- const { hasPendingTaskForConversation } = await import("./task");- const result = await hasPendingTaskForConversation(db as any, "c1");-- expect(result).toBe(true);- expect(db.limit).toHaveBeenCalledWith(1);- });-- it("returns false when no pending tasks", async () => {- const db = createMockDb([]);-- const { hasPendingTaskForConversation } = await import("./task");- const result = await hasPendingTaskForConversation(db as any, "c1");-- expect(result).toBe(false);- });-});--describe("countRunningTasks", () => {- it("returns count as a number", async () => {- const db = createMockDb([{ value: 3 }]);-- const { countRunningTasks } = await import("./task");- const result = await countRunningTasks(db as any, "a1");-- expect(result).toBe(3);- });-- it("returns 0 when no running tasks", async () => {- const db = createMockDb([{ value: 0 }]);-- const { countRunningTasks } = await import("./task");- const result = await countRunningTasks(db as any, "a1");-- expect(result).toBe(0);- });-- it("returns 0 when query returns no rows", async () => {- const db = createMockDb([]);-- const { countRunningTasks } = await import("./task");- const result = await countRunningTasks(db as any, "a1");-- expect(result).toBe(0);- });-});--describe("failStaleDispatchedTasks", () => {- it("fails dispatched tasks older than threshold", async () => {- const failed = [{ agentId: "a1" }, { agentId: "a2" }];- const db = createMockDb(failed);-- const { failStaleDispatchedTasks } = await import("./task");- const result = await failStaleDispatchedTasks(db as any, 20);-- expect(result).toEqual(failed);- expect(db.update).toHaveBeenCalled();- expect(db.set).toHaveBeenCalledWith(- expect.objectContaining({- status: "failed",- error: expect.stringContaining("timed out"),- })- );- });-- it("returns empty array when no stale tasks", async () => {- const db = createMockDb([]);-- const { failStaleDispatchedTasks } = await import("./task");- const result = await failStaleDispatchedTasks(db as any);-- expect(result).toEqual([]);- });-});--describe("getLastTaskSession", () => {- it("returns session info for completed task", async () => {- const session = { sessionId: "s1", workDir: "/tmp" };- const db = createMockDb([session]);-- const { getLastTaskSession } = await import("./task");- const result = await getLastTaskSession(db as any, "a1", "c1");-- expect(result).toEqual(session);- expect(db.limit).toHaveBeenCalledWith(1);- });-- it("returns null when no completed tasks", async () => {- const db = createMockDb([]);-- const { getLastTaskSession } = await import("./task");- const result = await getLastTaskSession(db as any, "a1", "c1");-- expect(result).toBeNull();- });-});diff --git a/src/web/lib/db/queries/task.integration.test.ts b/src/web/lib/db/queries/task.integration.test.tsdeleted file mode 100644index 91e6f25ec..000000000--- a/src/web/lib/db/queries/task.integration.test.ts+++ /dev/null@@ -1,251 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,- seedRuntime,- seedAgent,- seedConversation,-} from "../test-utils";-import {- createTask,- getTask,- getTaskStatus,- deleteTasksByConversation,- hasPendingTaskForConversation,- countRunningTasks,- claimTask,- startTask,- completeTask,-} from "./task";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--/** Shared helper: seeds the full FK chain and returns all entities. */-async function seedFullChain(tx: Parameters<Parameters<typeof withTestTransaction>[1]>[0]) {- const user = await seedUser(tx);- const ws = await seedWorkspace(tx);- await seedMember(tx, ws.id, user.id);- const rt = await seedRuntime(tx, ws.id);- const agent = await seedAgent(tx, ws.id, rt.id, user.id);- const conv = await seedConversation(tx, ws.id, agent.id, user.id);- return { user, ws, rt, agent, conv };-}--describe("createTask", () => {- it("inserts task with correct fields", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);-- const task = await createTask(tx, {- agentId: agent.id,- runtimeId: rt.id,- workspaceId: ws.id,- conversationId: conv.id,- prompt: "Do the thing",- priority: 5,- });-- expect(task.id).toBeDefined();- expect(task.prompt).toBe("Do the thing");- expect(task.priority).toBe(5);- expect(task.status).toBe("queued");- expect(task.agentId).toBe(agent.id);- expect(task.conversationId).toBe(conv.id);- });- });-});--describe("getTask", () => {- it("returns task by ID", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- const task = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "test",- });-- const fetched = await getTask(tx, task.id);- expect(fetched).not.toBeNull();- expect(fetched!.id).toBe(task.id);- });- });-- it("returns null for non-existent ID", async () => {- await withTestTransaction(db, async (tx) => {- const result = await getTask(tx, "00000000-0000-0000-0000-000000000000");- expect(result).toBeNull();- });- });-});--describe("getTaskStatus", () => {- it("returns status of existing task", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);- const task = await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "test",- });-- const status = await getTaskStatus(tx, task.id);- expect(status).toBe("queued");- });- });-- it("returns null for non-existent ID", async () => {- await withTestTransaction(db, async (tx) => {- const status = await getTaskStatus(tx, "00000000-0000-0000-0000-000000000000");- expect(status).toBeNull();- });- });-});--describe("deleteTasksByConversation", () => {- it("removes all tasks for a conversation", async () => {- await withTestTransaction(db, async (tx) => {- const { user, ws, rt, agent, conv } = await seedFullChain(tx);-- // Need separate conversations for multiple queued tasks (partial unique index)- const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);-- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "task 1",- });- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv2.id, prompt: "task 2",- });-- const deleted = await deleteTasksByConversation(tx, conv.id);- expect(deleted).toHaveLength(1);-- // conv2 task still exists- const pending = await hasPendingTaskForConversation(tx, conv2.id);- expect(pending).toBe(true);- });- });-- it("returns empty array when no tasks exist", async () => {- await withTestTransaction(db, async (tx) => {- const { conv } = await seedFullChain(tx);- const deleted = await deleteTasksByConversation(tx, conv.id);- expect(deleted).toEqual([]);- });- });-});--describe("hasPendingTaskForConversation", () => {- it("returns true when queued tasks exist", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);-- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "pending task",- });-- const result = await hasPendingTaskForConversation(tx, conv.id);- expect(result).toBe(true);- });- });-- it("returns false when only completed/failed tasks exist", async () => {- await withTestTransaction(db, async (tx) => {- const { ws, rt, agent, conv } = await seedFullChain(tx);-- // Create a task and transition it to completed: queued -> dispatched -> running -> completed- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "done task",- });-- const claimed = await claimTask(tx, agent.id);- expect(claimed).not.toBeNull();-- const started = await startTask(tx, claimed!.id);- expect(started).not.toBeNull();-- const completed = await completeTask(tx, started!.id, {- result: { output: "done" },- sessionId: null,- workDir: null,- });- expect(completed).not.toBeNull();-- // Now only a completed task exists — should return false- const result = await hasPendingTaskForConversation(tx, conv.id);- expect(result).toBe(false);- });- });-- it("returns false when no tasks exist", async () => {- await withTestTransaction(db, async (tx) => {- const { conv } = await seedFullChain(tx);- const result = await hasPendingTaskForConversation(tx, conv.id);- expect(result).toBe(false);- });- });-});--describe("countRunningTasks", () => {- it("returns correct count of dispatched+running tasks", async () => {- await withTestTransaction(db, async (tx) => {- const { user, ws, rt, agent, conv } = await seedFullChain(tx);-- // Create tasks in separate conversations (partial unique index constraint)- const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);- const conv3 = await seedConversation(tx, ws.id, agent.id, user.id);-- // Create queued tasks- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv.id, prompt: "task 1",- });- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv2.id, prompt: "task 2",- });- await createTask(tx, {- agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,- conversationId: conv3.id, prompt: "task 3",- });-- // queued tasks should not be counted- expect(await countRunningTasks(tx, agent.id)).toBe(0);-- // Claim one task (queued -> dispatched) — dispatched counts- const claimed1 = await claimTask(tx, agent.id);- expect(claimed1).not.toBeNull();- expect(await countRunningTasks(tx, agent.id)).toBe(1);-- // Start it (dispatched -> running) — running also counts- await startTask(tx, claimed1!.id);- expect(await countRunningTasks(tx, agent.id)).toBe(1);-- // Claim another (now 1 running + 1 dispatched = 2)- const claimed2 = await claimTask(tx, agent.id);- expect(claimed2).not.toBeNull();- expect(await countRunningTasks(tx, agent.id)).toBe(2);- });- });-- it("returns 0 when all tasks are completed", async () => {- await withTestTransaction(db, async (tx) => {- const { agent } = await seedFullChain(tx);-- // No tasks at all- const count = await countRunningTasks(tx, agent.id);- expect(count).toBe(0);- });- });-});diff --git a/src/web/lib/db/queries/task.test.ts b/src/web/lib/db/queries/task.test.tsdeleted file mode 100644index 20ed42ad3..000000000--- a/src/web/lib/db/queries/task.test.ts+++ /dev/null@@ -1,134 +0,0 @@-/**- * Tests that claimTask() wires ClaimedTaskRowSchema.parse() correctly.- * We mock the DB to return raw rows and verify Zod validation catches bad shapes.- */-import { describe, it, expect, vi, beforeEach } from "vitest";-import { ClaimedTaskRowSchema } from "@alook/shared";--// Mock drizzle — we control what the DB "returns"-const mockReturning = vi.fn();-const mockWhere2 = vi.fn(() => ({ returning: mockReturning }));-const mockSet = vi.fn(() => ({ where: mockWhere2 }));-const mockUpdate = vi.fn(() => ({ set: mockSet }));-const mockFor = vi.fn();-const mockLimit = vi.fn(() => ({ for: mockFor }));-const mockOrderBy = vi.fn(() => ({ limit: mockLimit }));-const mockWhere = vi.fn(() => ({ orderBy: mockOrderBy }));-const mockFrom = vi.fn(() => ({ where: mockWhere }));-const mockSelect = vi.fn(() => ({ from: mockFrom }));--vi.mock("@/lib/db/schema", () => ({- agentTaskQueue: {- id: "id",- agentId: "agentId",- status: "status",- conversationId: "conversationId",- priority: "priority",- createdAt: "createdAt",- },-}));--vi.mock("drizzle-orm", () => ({- eq: vi.fn(),- and: vi.fn(),- sql: vi.fn(),- desc: vi.fn(),- asc: vi.fn(),- inArray: vi.fn(),-}));--// We test the schema directly since the DB query is heavily coupled to Drizzle internals-describe("ClaimedTaskRowSchema in claimTask context", () => {- it("rejects a row missing runtimeId (the original bug scenario)", () => {- const badRow = {- id: "t1",- agentId: "a1",- // runtimeId is MISSING — this is exactly the snake_case bug- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- status: "dispatched",- priority: 0,- result: null,- context: null,- sessionId: null,- workDir: null,- createdAt: new Date(),- dispatchedAt: new Date(),- startedAt: null,- completedAt: null,- error: null,- };- expect(() => ClaimedTaskRowSchema.parse(badRow)).toThrow(/runtimeId/i);- });-- it("rejects a row with runtimeId as number instead of string", () => {- const badRow = {- id: "t1",- agentId: "a1",- runtimeId: 12345,- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- status: "dispatched",- priority: 0,- result: null,- context: null,- sessionId: null,- workDir: null,- createdAt: new Date(),- dispatchedAt: new Date(),- startedAt: null,- completedAt: null,- error: null,- };- expect(() => ClaimedTaskRowSchema.parse(badRow)).toThrow();- });-- it("rejects a row where id is missing", () => {- const badRow = {- agentId: "a1",- runtimeId: "r1",- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- status: "dispatched",- priority: 0,- result: null,- context: null,- sessionId: null,- workDir: null,- createdAt: new Date(),- dispatchedAt: new Date(),- startedAt: null,- completedAt: null,- error: null,- };- expect(() => ClaimedTaskRowSchema.parse(badRow)).toThrow();- });-- it("accepts a valid row and returns typed result", () => {- const goodRow = {- id: "t1",- agentId: "a1",- runtimeId: "r1",- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- status: "dispatched",- priority: 0,- result: null,- context: null,- sessionId: null,- workDir: null,- createdAt: new Date(),- dispatchedAt: new Date(),- startedAt: null,- completedAt: null,- error: null,- };- const parsed = ClaimedTaskRowSchema.parse(goodRow);- expect(parsed.runtimeId).toBe("r1");- expect(parsed.createdAt).toBeInstanceOf(Date);- });-});diff --git a/src/web/lib/db/queries/task.ts b/src/web/lib/db/queries/task.tsdeleted file mode 100644index 8d0a650a6..000000000--- a/src/web/lib/db/queries/task.ts+++ /dev/null@@ -1,259 +0,0 @@-import { eq, and, desc, asc, inArray, notInArray, isNotNull, count, lt } from "drizzle-orm";-import { agentTaskQueue } from "../schema";-import type { Database } from "../index";-import { ClaimedTaskRowSchema } from "@alook/shared";--export async function createTask(- db: Database,- data: {- agentId: string;- runtimeId: string;- workspaceId: string;- conversationId: string;- prompt: string;- priority?: number;- }-) {- const rows = await db- .insert(agentTaskQueue)- .values({- agentId: data.agentId,- runtimeId: data.runtimeId,- workspaceId: data.workspaceId,- conversationId: data.conversationId,- prompt: data.prompt,- priority: data.priority ?? 0,- })- .returning();- return rows[0]!;-}--export async function getTask(db: Database, id: string) {- const rows = await db- .select()- .from(agentTaskQueue)- .where(eq(agentTaskQueue.id, id));- return rows[0] ?? null;-}--export async function getTaskStatus(db: Database, id: string) {- const rows = await db- .select({ status: agentTaskQueue.status })- .from(agentTaskQueue)- .where(eq(agentTaskQueue.id, id));- return rows[0]?.status ?? null;-}--export async function claimTask(db: Database, agentId: string) {- // Step 1: Get conversations that have active (dispatched/running) tasks- const activeConversations = await db- .select({ conversationId: agentTaskQueue.conversationId })- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.agentId, agentId),- inArray(agentTaskQueue.status, ["dispatched", "running"])- )- );-- const activeConvIds = activeConversations.map((r) => r.conversationId);-- // Step 2: Find queued tasks not in those conversations- const candidateQuery = db- .select({ id: agentTaskQueue.id })- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.agentId, agentId),- eq(agentTaskQueue.status, "queued"),- ...(activeConvIds.length > 0- ? [notInArray(agentTaskQueue.conversationId, activeConvIds)]- : [])- )- )- .orderBy(desc(agentTaskQueue.priority), asc(agentTaskQueue.createdAt))- .limit(1)- .for("update", { skipLocked: true });-- const candidates = await candidateQuery;-- if (candidates.length === 0) return null;-- const rows = await db- .update(agentTaskQueue)- .set({ status: "dispatched", dispatchedAt: new Date() })- .where(- and(- eq(agentTaskQueue.id, candidates[0].id),- eq(agentTaskQueue.status, "queued")- )- )- .returning();-- const row = rows[0] ?? null;- if (!row) return null;- return ClaimedTaskRowSchema.parse(row);-}--export async function startTask(db: Database, id: string) {- const rows = await db- .update(agentTaskQueue)- .set({ status: "running", startedAt: new Date() })- .where(- and(eq(agentTaskQueue.id, id), eq(agentTaskQueue.status, "dispatched"))- )- .returning();- return rows[0] ?? null;-}--export async function completeTask(- db: Database,- id: string,- data: { result: unknown; sessionId: string | null; workDir: string | null }-) {- const rows = await db- .update(agentTaskQueue)- .set({- status: "completed",- completedAt: new Date(),- result: data.result,- sessionId: data.sessionId,- workDir: data.workDir,- })- .where(- and(eq(agentTaskQueue.id, id), eq(agentTaskQueue.status, "running"))- )- .returning();- return rows[0] ?? null;-}--export async function failTask(- db: Database,- id: string,- error: string-) {- const rows = await db- .update(agentTaskQueue)- .set({ status: "failed", completedAt: new Date(), error })- .where(- and(- eq(agentTaskQueue.id, id),- inArray(agentTaskQueue.status, ["dispatched", "running"])- )- )- .returning();- return rows[0] ?? null;-}--export async function getLastTaskSession(- db: Database,- agentId: string,- conversationId: string-) {- const rows = await db- .select({- sessionId: agentTaskQueue.sessionId,- workDir: agentTaskQueue.workDir,- })- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.agentId, agentId),- eq(agentTaskQueue.conversationId, conversationId),- eq(agentTaskQueue.status, "completed"),- isNotNull(agentTaskQueue.sessionId)- )- )- .orderBy(desc(agentTaskQueue.completedAt))- .limit(1);- return rows[0] ?? null;-}--export async function listPendingTasksByRuntime(- db: Database,- runtimeId: string-) {- return db- .select()- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.runtimeId, runtimeId),- inArray(agentTaskQueue.status, ["queued", "dispatched"])- )- )- .orderBy(desc(agentTaskQueue.priority), asc(agentTaskQueue.createdAt));-}--export async function hasPendingTaskForConversation(- db: Database,- conversationId: string-) {- const rows = await db- .select({ id: agentTaskQueue.id })- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.conversationId, conversationId),- inArray(agentTaskQueue.status, ["queued", "dispatched"])- )- )- .limit(1);- return rows.length > 0;-}--export async function cancelTask(db: Database, id: string) {- const rows = await db- .update(agentTaskQueue)- .set({ status: "cancelled", completedAt: new Date() })- .where(- and(- eq(agentTaskQueue.id, id),- inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])- )- )- .returning();- return rows[0] ?? null;-}--export async function failStaleDispatchedTasks(db: Database, staleSeconds = 20) {- const threshold = new Date(Date.now() - staleSeconds * 1000);- const rows = await db- .update(agentTaskQueue)- .set({- status: "failed",- completedAt: new Date(),- error: "timed out in dispatched state (daemon likely disconnected)",- })- .where(- and(- eq(agentTaskQueue.status, "dispatched"),- lt(agentTaskQueue.dispatchedAt, threshold)- )- )- .returning({ agentId: agentTaskQueue.agentId });- return rows;-}--export async function deleteTasksByConversation(- db: Database,- conversationId: string-) {- return db- .delete(agentTaskQueue)- .where(eq(agentTaskQueue.conversationId, conversationId))- .returning({ id: agentTaskQueue.id });-}--export async function countRunningTasks(db: Database, agentId: string) {- const rows = await db- .select({ value: count() })- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.agentId, agentId),- inArray(agentTaskQueue.status, ["dispatched", "running"])- )- );- return Number(rows[0]?.value ?? 0);-}diff --git a/src/web/lib/db/queries/user.ts b/src/web/lib/db/queries/user.tsdeleted file mode 100644index 592a2ab11..000000000--- a/src/web/lib/db/queries/user.ts+++ /dev/null@@ -1,37 +0,0 @@-import { eq } from "drizzle-orm";-import { user } from "../schema";-import type { Database } from "../index";--export async function getUser(db: Database, id: string) {- const rows = await db.select().from(user).where(eq(user.id, id));- return rows[0] ?? null;-}--export async function getUserByEmail(db: Database, email: string) {- const rows = await db.select().from(user).where(eq(user.email, email));- return rows[0] ?? null;-}--export async function createUser(- db: Database,- data: { name: string; email: string }-) {- const rows = await db- .insert(user)- .values({ name: data.name, email: data.email })- .returning();- return rows[0]!;-}--export async function updateUser(- db: Database,- id: string,- data: { name: string; avatarUrl: string | null }-) {- const rows = await db- .update(user)- .set({ name: data.name, avatarUrl: data.avatarUrl, updatedAt: new Date() })- .where(eq(user.id, id))- .returning();- return rows[0] ?? null;-}diff --git a/src/web/lib/db/queries/verification-code.integration.test.ts b/src/web/lib/db/queries/verification-code.integration.test.tsdeleted file mode 100644index 84405bb03..000000000--- a/src/web/lib/db/queries/verification-code.integration.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,-} from "../test-utils";-import {- createVerificationCode,- getLatestVerificationCode,- incrementVerificationCodeAttempts,-} from "./verification-code";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--describe("getLatestVerificationCode", () => {- it("returns valid code (unused, unexpired, under attempt limit)", async () => {- await withTestTransaction(db, async (tx) => {- const code = await createVerificationCode(tx, {- email: "[email protected]",- code: "123456",- expiresAt: new Date(Date.now() + 10 * 60 * 1000), // 10 min from now- });-- const result = await getLatestVerificationCode(tx, "[email protected]");- expect(result).not.toBeNull();- expect(result!.id).toBe(code.id);- expect(result!.code).toBe("123456");- });- });-- it("returns null for used code", async () => {- await withTestTransaction(db, async (tx) => {- const { markVerificationCodeUsed } = await import("./verification-code");-- await createVerificationCode(tx, {- email: "[email protected]",- code: "111111",- expiresAt: new Date(Date.now() + 10 * 60 * 1000),- });-- const fetched = await getLatestVerificationCode(tx, "[email protected]");- await markVerificationCodeUsed(tx, fetched!.id);-- const result = await getLatestVerificationCode(tx, "[email protected]");- expect(result).toBeNull();- });- });-- it("returns null for expired code", async () => {- await withTestTransaction(db, async (tx) => {- await createVerificationCode(tx, {- email: "[email protected]",- code: "222222",- expiresAt: new Date(Date.now() - 1000), // already expired- });-- const result = await getLatestVerificationCode(tx, "[email protected]");- expect(result).toBeNull();- });- });-- it("returns null for code at attempt limit", async () => {- await withTestTransaction(db, async (tx) => {- const code = await createVerificationCode(tx, {- email: "[email protected]",- code: "333333",- expiresAt: new Date(Date.now() + 10 * 60 * 1000),- });-- // Increment attempts to 5 (the limit)- for (let i = 0; i < 5; i++) {- await incrementVerificationCodeAttempts(tx, code.id);- }-- const result = await getLatestVerificationCode(tx, "[email protected]");- expect(result).toBeNull();- });- });-});--describe("incrementVerificationCodeAttempts", () => {- it("atomically increments the attempts counter", async () => {- await withTestTransaction(db, async (tx) => {- const { getLatestCodeByEmail } = await import("./verification-code");-- const code = await createVerificationCode(tx, {- email: "[email protected]",- code: "444444",- expiresAt: new Date(Date.now() + 10 * 60 * 1000),- });-- expect(code.attempts).toBe(0);-- await incrementVerificationCodeAttempts(tx, code.id);- await incrementVerificationCodeAttempts(tx, code.id);- await incrementVerificationCodeAttempts(tx, code.id);-- const fetched = await getLatestCodeByEmail(tx, "[email protected]");- expect(fetched!.attempts).toBe(3);- });- });-});diff --git a/src/web/lib/db/queries/verification-code.ts b/src/web/lib/db/queries/verification-code.tsdeleted file mode 100644index c9da9a84f..000000000--- a/src/web/lib/db/queries/verification-code.ts+++ /dev/null@@ -1,71 +0,0 @@-import { eq, and, desc, gt, lt, sql } from "drizzle-orm";-import { verificationCode } from "../schema";-import type { Database } from "../index";--export async function createVerificationCode(- db: Database,- data: { email: string; code: string; expiresAt: Date }-) {- const rows = await db- .insert(verificationCode)- .values({- email: data.email,- code: data.code,- expiresAt: data.expiresAt,- })- .returning();- return rows[0]!;-}--export async function getLatestVerificationCode(- db: Database,- email: string-) {- const rows = await db- .select()- .from(verificationCode)- .where(- and(- eq(verificationCode.email, email),- eq(verificationCode.used, false),- gt(verificationCode.expiresAt, new Date()),- lt(verificationCode.attempts, 5)- )- )- .orderBy(desc(verificationCode.createdAt))- .limit(1);- return rows[0] ?? null;-}--export async function markVerificationCodeUsed(db: Database, id: string) {- await db- .update(verificationCode)- .set({ used: true })- .where(eq(verificationCode.id, id));-}--export async function incrementVerificationCodeAttempts(- db: Database,- id: string-) {- await db- .update(verificationCode)- .set({ attempts: sql`${verificationCode.attempts} + 1` })- .where(eq(verificationCode.id, id));-}--export async function getLatestCodeByEmail(db: Database, email: string) {- const rows = await db- .select()- .from(verificationCode)- .where(eq(verificationCode.email, email))- .orderBy(desc(verificationCode.createdAt))- .limit(1);- return rows[0] ?? null;-}--export async function deleteExpiredVerificationCodes(db: Database) {- await db- .delete(verificationCode)- .where(lt(verificationCode.expiresAt, new Date()));-}diff --git a/src/web/lib/db/queries/workspace.integration.test.ts b/src/web/lib/db/queries/workspace.integration.test.tsdeleted file mode 100644index 0c7ff8a43..000000000--- a/src/web/lib/db/queries/workspace.integration.test.ts+++ /dev/null@@ -1,45 +0,0 @@-import { afterAll, describe, it, expect } from "vitest";-import {- getTestClient,- getTestDb,- withTestTransaction,- seedUser,- seedWorkspace,- seedMember,-} from "../test-utils";-import { listWorkspaces } from "./workspace";--const client = getTestClient();-const db = getTestDb(client);--afterAll(async () => {- await client.end();-});--describe("listWorkspaces", () => {- it("returns only workspaces the user is a member of", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- const ws1 = await seedWorkspace(tx, { name: "Joined" });- const ws2 = await seedWorkspace(tx, { name: "Not Joined" });-- // User is only a member of ws1- await seedMember(tx, ws1.id, user.id);-- const result = await listWorkspaces(tx, user.id);- expect(result).toHaveLength(1);- expect(result[0].id).toBe(ws1.id);- expect(result[0].name).toBe("Joined");- });- });-- it("returns empty array for user with no memberships", async () => {- await withTestTransaction(db, async (tx) => {- const user = await seedUser(tx);- await seedWorkspace(tx); // exists but user isn't a member-- const result = await listWorkspaces(tx, user.id);- expect(result).toEqual([]);- });- });-});diff --git a/src/web/lib/db/queries/workspace.ts b/src/web/lib/db/queries/workspace.tsdeleted file mode 100644index 1a3b439bd..000000000--- a/src/web/lib/db/queries/workspace.ts+++ /dev/null@@ -1,34 +0,0 @@-import { eq, asc } from "drizzle-orm";-import { workspace, member } from "../schema";-import type { Database } from "../index";--export async function getWorkspace(db: Database, id: string) {- const rows = await db.select().from(workspace).where(eq(workspace.id, id));- return rows[0] ?? null;-}--export async function listWorkspaces(db: Database, userId: string) {- return db- .select({- id: workspace.id,- name: workspace.name,- slug: workspace.slug,- createdAt: workspace.createdAt,- updatedAt: workspace.updatedAt,- })- .from(workspace)- .innerJoin(member, eq(member.workspaceId, workspace.id))- .where(eq(member.userId, userId))- .orderBy(asc(workspace.createdAt));-}--export async function createWorkspace(- db: Database,- data: { name: string; slug: string }-) {- const rows = await db- .insert(workspace)- .values({ name: data.name, slug: data.slug })- .returning();- return rows[0]!;-}diff --git a/src/web/lib/db/schema.ts b/src/web/lib/db/schema.tsdeleted file mode 100644index 294b3a448..000000000--- a/src/web/lib/db/schema.ts+++ /dev/null@@ -1,206 +0,0 @@-import {- pgTable,- uuid,- text,- timestamp,- boolean,- integer,- jsonb,- uniqueIndex,- index,- unique,-} from "drizzle-orm/pg-core";-import { sql } from "drizzle-orm";--export const user = pgTable("user", {- id: uuid("id").primaryKey().defaultRandom(),- name: text("name").notNull().default(""),- email: text("email").unique().notNull(),- avatarUrl: text("avatar_url"),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),-});--export const workspace = pgTable("workspace", {- id: uuid("id").primaryKey().defaultRandom(),- name: text("name").notNull(),- slug: text("slug").unique().notNull(),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),-});--export const member = pgTable(- "member",- {- id: uuid("id").primaryKey().defaultRandom(),- workspaceId: uuid("workspace_id")- .notNull()- .references(() => workspace.id, { onDelete: "cascade" }),- userId: uuid("user_id")- .notNull()- .references(() => user.id, { onDelete: "cascade" }),- role: text("role").notNull().default("member"),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- },- (t) => [unique("member_workspace_user").on(t.workspaceId, t.userId)]-);--export const agentRuntime = pgTable(- "agent_runtime",- {- id: uuid("id").primaryKey().defaultRandom(),- workspaceId: uuid("workspace_id")- .notNull()- .references(() => workspace.id, { onDelete: "cascade" }),- daemonId: text("daemon_id").notNull(),- name: text("name").notNull().default(""),- runtimeMode: text("runtime_mode").notNull().default("local"),- provider: text("provider").notNull(),- status: text("status").notNull().default("offline"),- deviceInfo: text("device_info").notNull().default(""),- metadata: jsonb("metadata"),- lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),- },- (t) => [- unique("agent_runtime_workspace_daemon_provider").on(- t.workspaceId,- t.daemonId,- t.provider- ),- ]-);--export const agent = pgTable("agent", {- id: uuid("id").primaryKey().defaultRandom(),- workspaceId: uuid("workspace_id")- .notNull()- .references(() => workspace.id, { onDelete: "cascade" }),- name: text("name").notNull(),- description: text("description").notNull().default(""),- instructions: text("instructions").notNull().default(""),- avatarUrl: text("avatar_url"),- runtimeId: uuid("runtime_id").references(() => agentRuntime.id),- runtimeMode: text("runtime_mode").notNull().default("local"),- runtimeConfig: jsonb("runtime_config"),- visibility: text("visibility").notNull().default("private"),- status: text("status").notNull().default("idle"),- maxConcurrentTasks: integer("max_concurrent_tasks").notNull().default(6),- ownerId: uuid("owner_id").references(() => user.id),- tools: jsonb("tools"),- triggers: jsonb("triggers"),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),-});--export const conversation = pgTable("conversation", {- id: uuid("id").primaryKey().defaultRandom(),- workspaceId: uuid("workspace_id")- .notNull()- .references(() => workspace.id, { onDelete: "cascade" }),- agentId: uuid("agent_id")- .notNull()- .references(() => agent.id, { onDelete: "cascade" }),- userId: uuid("user_id")- .notNull()- .references(() => user.id, { onDelete: "cascade" }),- title: text("title").notNull().default(""),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),-});--export const message = pgTable("message", {- id: uuid("id").primaryKey().defaultRandom(),- conversationId: uuid("conversation_id")- .notNull()- .references(() => conversation.id, { onDelete: "cascade" }),- role: text("role").notNull(),- content: text("content").notNull().default(""),- taskId: uuid("task_id"),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),-});--export const agentTaskQueue = pgTable(- "agent_task_queue",- {- id: uuid("id").primaryKey().defaultRandom(),- agentId: uuid("agent_id")- .notNull()- .references(() => agent.id, { onDelete: "cascade" }),- runtimeId: uuid("runtime_id")- .notNull()- .references(() => agentRuntime.id),- workspaceId: uuid("workspace_id")- .notNull()- .references(() => workspace.id),- conversationId: uuid("conversation_id")- .notNull()- .references(() => conversation.id),- prompt: text("prompt").notNull(),- status: text("status").notNull().default("queued"),- priority: integer("priority").notNull().default(0),- result: jsonb("result"),- context: jsonb("context"),- sessionId: text("session_id"),- workDir: text("work_dir"),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- dispatchedAt: timestamp("dispatched_at", { withTimezone: true }),- startedAt: timestamp("started_at", { withTimezone: true }),- completedAt: timestamp("completed_at", { withTimezone: true }),- error: text("error"),- },- (t) => [- uniqueIndex("idx_one_pending_per_conversation")- .on(t.conversationId)- .where(sql`status IN ('queued', 'dispatched')`),- index("idx_task_queue_pending")- .on(t.agentId, t.status)- .where(sql`status IN ('queued', 'dispatched')`),- ]-);--export const taskMessage = pgTable(- "task_message",- {- id: uuid("id").primaryKey().defaultRandom(),- taskId: uuid("task_id")- .notNull()- .references(() => agentTaskQueue.id, { onDelete: "cascade" }),- seq: integer("seq").notNull(),- type: text("type").notNull().default(""),- tool: text("tool").notNull().default(""),- content: text("content").notNull().default(""),- input: jsonb("input"),- output: text("output").notNull().default(""),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- },- (t) => [index("idx_task_message_task_seq").on(t.taskId, t.seq)]-);--export const verificationCode = pgTable("verification_code", {- id: uuid("id").primaryKey().defaultRandom(),- email: text("email").notNull(),- code: text("code").notNull(),- used: boolean("used").notNull().default(false),- attempts: integer("attempts").notNull().default(0),- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),-});--export const machineToken = pgTable(- "machine_token",- {- id: uuid("id").primaryKey().defaultRandom(),- userId: uuid("user_id")- .notNull()- .references(() => user.id, { onDelete: "cascade" }),- workspaceId: uuid("workspace_id")- .notNull()- .references(() => workspace.id, { onDelete: "cascade" }),- tokenHash: text("token_hash").unique().notNull(),- name: text("name").notNull().default(""),- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),- },- (t) => [index("idx_machine_token_hash").on(t.tokenHash)]-);diff --git a/src/web/lib/db/test-utils.ts b/src/web/lib/db/test-utils.tsdeleted file mode 100644index e573096ec..000000000--- a/src/web/lib/db/test-utils.ts+++ /dev/null@@ -1,133 +0,0 @@-import { drizzle } from "drizzle-orm/postgres-js";-import postgres from "postgres";-import * as schema from "./schema";-import type { Database } from "./index";--const TEST_DATABASE_URL =- process.env.DATABASE_TEST_URL ||- "postgres://postgres:postgres@localhost:5432/alook_test?sslmode=disable";--/**- * Creates a postgres client pointing at alook_test.- * Caller must call `client.end()` in afterAll.- */-export function getTestClient() {- return postgres(TEST_DATABASE_URL);-}--/**- * Wraps a postgres client in a Drizzle instance with schema.- */-export function getTestDb(client: postgres.Sql) {- return drizzle(client, { schema });-}--/**- * Runs `fn(tx)` inside a transaction, always rolls back after.- * Casts `tx` to `Database` for type compatibility with query functions.- */-export async function withTestTransaction(- db: ReturnType<typeof getTestDb>,- fn: (tx: Database) => Promise<void>-) {- await db- .transaction(async (tx) => {- await fn(tx as unknown as Database);- // Always rollback — throw a sentinel error- throw new RollbackError();- })- .catch((err) => {- if (err instanceof RollbackError) return;- throw err;- });-}--class RollbackError extends Error {- constructor() {- super("__test_rollback__");- }-}--// --------------- Fixture Factories -----------------export async function seedUser(tx: Database, overrides?: { email?: string; name?: string }) {- const rows = await (tx as any)- .insert(schema.user)- .values({- email: overrides?.email ?? `test-${crypto.randomUUID()}@test.com`,- name: overrides?.name ?? "Test User",- })- .returning();- return rows[0]!;-}--export async function seedWorkspace(tx: Database, overrides?: { name?: string; slug?: string }) {- const slug = overrides?.slug ?? `ws-${crypto.randomUUID().slice(0, 8)}`;- const rows = await (tx as any)- .insert(schema.workspace)- .values({- name: overrides?.name ?? "Test Workspace",- slug,- })- .returning();- return rows[0]!;-}--export async function seedMember(tx: Database, workspaceId: string, userId: string) {- const rows = await (tx as any)- .insert(schema.member)- .values({ workspaceId, userId })- .returning();- return rows[0]!;-}--export async function seedRuntime(tx: Database, workspaceId: string) {- const rows = await (tx as any)- .insert(schema.agentRuntime)- .values({- workspaceId,- daemonId: `daemon-${crypto.randomUUID().slice(0, 8)}`,- provider: "test",- name: "Test Runtime",- })- .returning();- return rows[0]!;-}--export async function seedAgent(- tx: Database,- workspaceId: string,- runtimeId: string,- ownerId?: string-) {- const rows = await (tx as any)- .insert(schema.agent)- .values({- workspaceId,- name: "Test Agent",- runtimeId,- ownerId: ownerId ?? null,- })- .returning();- return rows[0]!;-}--export async function seedConversation(- tx: Database,- workspaceId: string,- agentId: string,- userId: string,- overrides?: { title?: string; createdAt?: Date }-) {- const rows = await (tx as any)- .insert(schema.conversation)- .values({- workspaceId,- agentId,- userId,- title: overrides?.title ?? "",- ...(overrides?.createdAt ? { createdAt: overrides.createdAt } : {}),- })- .returning();- return rows[0]!;-}diff --git a/src/web/lib/middleware/auth.test.ts b/src/web/lib/middleware/auth.test.tsdeleted file mode 100644index 00c3f1306..000000000--- a/src/web/lib/middleware/auth.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest, NextResponse } from "next/server";--vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/auth/jwt");-vi.mock("@/lib/db/queries/machine-token");--import { verifyJWT, hashToken } from "@/lib/auth/jwt";-import {- getMachineTokenByHash,- updateMachineTokenLastUsed,-} from "@/lib/db/queries/machine-token";-import { withAuth } from "./auth";--const mockVerifyJWT = vi.mocked(verifyJWT);-const mockHashToken = vi.mocked(hashToken);-const mockGetMachineTokenByHash = vi.mocked(getMachineTokenByHash);-const mockUpdateMachineTokenLastUsed = vi.mocked(updateMachineTokenLastUsed);--function makeReq(headers: Record<string, string> = {}) {- return new NextRequest("http://localhost/api/test", { headers });-}--const handler = vi.fn(async (_req, ctx) =>- NextResponse.json({ userId: ctx.userId, email: ctx.email, workspaceId: ctx.workspaceId }),-);--beforeEach(() => {- vi.clearAllMocks();-});--describe("withAuth", () => {- it("returns 401 when Authorization header is missing", async () => {- const wrapped = withAuth(handler);- const res = await wrapped(makeReq());- expect(res.status).toBe(401);- const body = await res.json();- expect(body.error).toBe("missing authorization header");- });-- it("returns 401 when Authorization format is not Bearer", async () => {- const wrapped = withAuth(handler);- const res = await wrapped(makeReq({ Authorization: "Basic abc123" }));- expect(res.status).toBe(401);- const body = await res.json();- expect(body.error).toBe("invalid authorization format");- });-- it("returns 401 when Authorization has no token", async () => {- const wrapped = withAuth(handler);- const res = await wrapped(makeReq({ Authorization: "Bearer" }));- expect(res.status).toBe(401);- });-- it("authenticates valid JWT and passes userId/email to handler", async () => {- mockVerifyJWT.mockResolvedValue({ sub: "u1", email: "[email protected]", name: "" });- const wrapped = withAuth(handler);- const res = await wrapped(makeReq({ Authorization: "Bearer valid-jwt" }));- expect(res.status).toBe(200);- const body = await res.json();- expect(body.userId).toBe("u1");- expect(body.email).toBe("[email protected]");- });-- it("returns 401 for invalid/expired JWT", async () => {- mockVerifyJWT.mockRejectedValue(new Error("expired"));- const wrapped = withAuth(handler);- const res = await wrapped(makeReq({ Authorization: "Bearer bad-jwt" }));- expect(res.status).toBe(401);- const body = await res.json();- expect(body.error).toBe("invalid token");- });-- it("authenticates machine token (al_ prefix) via hash lookup", async () => {- mockHashToken.mockReturnValue("hashed");- mockGetMachineTokenByHash.mockResolvedValue({- id: "mt1",- userId: "u2",- userEmail: "[email protected]",- workspaceId: "w1",- } as any);- mockUpdateMachineTokenLastUsed.mockResolvedValue(undefined as any);-- const wrapped = withAuth(handler);- const res = await wrapped(makeReq({ Authorization: "Bearer al_test123" }));- expect(res.status).toBe(200);- const body = await res.json();- expect(body.userId).toBe("u2");- expect(body.email).toBe("[email protected]");- expect(body.workspaceId).toBe("w1");- });-- it("returns 401 for unknown machine token", async () => {- mockHashToken.mockReturnValue("hashed");- mockGetMachineTokenByHash.mockResolvedValue(null as any);-- const wrapped = withAuth(handler);- const res = await wrapped(makeReq({ Authorization: "Bearer al_unknown" }));- expect(res.status).toBe(401);- const body = await res.json();- expect(body.error).toBe("invalid token");- });-- it("updates lastUsedAt on machine token auth", async () => {- mockHashToken.mockReturnValue("hashed");- mockGetMachineTokenByHash.mockResolvedValue({- id: "mt1",- userId: "u2",- userEmail: "[email protected]",- workspaceId: "w1",- } as any);- mockUpdateMachineTokenLastUsed.mockResolvedValue(undefined as any);-- const wrapped = withAuth(handler);- await wrapped(makeReq({ Authorization: "Bearer al_test" }));- expect(mockUpdateMachineTokenLastUsed).toHaveBeenCalledWith(- expect.anything(),- "mt1",- );- });-- it("resolves dynamic params from context", async () => {- mockVerifyJWT.mockResolvedValue({ sub: "u1", email: "[email protected]", name: "" });- const paramHandler = vi.fn(async (_req, ctx) =>- NextResponse.json({ taskId: ctx.params?.taskId }),- );- const wrapped = withAuth(paramHandler);- const res = await wrapped(makeReq({ Authorization: "Bearer jwt" }), {- params: Promise.resolve({ taskId: "t99" }),- });- const body = await res.json();- expect(body.taskId).toBe("t99");- });-});diff --git a/src/web/lib/middleware/auth.ts b/src/web/lib/middleware/auth.tsdeleted file mode 100644index 42f969af3..000000000--- a/src/web/lib/middleware/auth.ts+++ /dev/null@@ -1,78 +0,0 @@-import { NextRequest, NextResponse } from "next/server";-import { verifyJWT, hashToken } from "@/lib/auth/jwt";-import { db } from "@/lib/db";--export interface AuthContext {- userId: string;- email: string;- workspaceId?: string;-}--export type AuthenticatedHandler = (- req: NextRequest,- ctx: AuthContext & { params?: Record<string, string> }-) => Promise<NextResponse | Response>;--export function withAuth(handler: AuthenticatedHandler) {- return async (- req: NextRequest,- context?: { params?: Promise<Record<string, string>> | Record<string, string> }- ) => {- const authHeader = req.headers.get("Authorization");- if (!authHeader) {- return NextResponse.json(- { error: "missing authorization header" },- { status: 401 }- );- }-- const parts = authHeader.split(" ");- if (parts.length !== 2 || parts[0] !== "Bearer") {- return NextResponse.json(- { error: "invalid authorization format" },- { status: 401 }- );- }-- const token = parts[1];- const resolvedParams = context?.params- ? context.params instanceof Promise- ? await context.params- : context.params- : undefined;-- try {- if (token.startsWith("al_")) {- const { getMachineTokenByHash, updateMachineTokenLastUsed } =- await import("@/lib/db/queries/machine-token");-- const hashed = hashToken(token);- const mt = await getMachineTokenByHash(db, hashed);- if (!mt) {- return NextResponse.json(- { error: "invalid token" },- { status: 401 }- );- }-- updateMachineTokenLastUsed(db, mt.id).catch(() => {});-- const authCtx: AuthContext = {- userId: mt.userId,- email: mt.userEmail,- workspaceId: mt.workspaceId,- };- return handler(req, { ...authCtx, params: resolvedParams });- }-- const claims = await verifyJWT(token);- const authCtx: AuthContext = {- userId: claims.sub,- email: claims.email,- };- return handler(req, { ...authCtx, params: resolvedParams });- } catch {- return NextResponse.json({ error: "invalid token" }, { status: 401 });- }- };-}diff --git a/src/web/lib/middleware/workspace.test.ts b/src/web/lib/middleware/workspace.test.tsdeleted file mode 100644index 60885c1bc..000000000--- a/src/web/lib/middleware/workspace.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@/lib/db", () => ({ db: {} }));-vi.mock("@/lib/db/queries/member");--import { getMemberByUserAndWorkspace } from "@/lib/db/queries/member";-import { withWorkspaceMember } from "./workspace";--const mockGetMember = vi.mocked(getMemberByUserAndWorkspace);--beforeEach(() => {- vi.clearAllMocks();-});--function makeReq(url = "http://localhost/api/test") {- return new NextRequest(url);-}--const auth = { userId: "u1", email: "[email protected]" };--describe("withWorkspaceMember", () => {- it("returns workspaceId from query param", async () => {- mockGetMember.mockResolvedValue({ id: "m1" } as any);- const result = await withWorkspaceMember(- makeReq("http://localhost/api/test?workspace_id=w1"),- auth,- );- expect(result).toEqual({ workspaceId: "w1" });- });-- it("returns workspaceId from X-Workspace-ID header", async () => {- mockGetMember.mockResolvedValue({ id: "m1" } as any);- const req = new NextRequest("http://localhost/api/test", {- headers: { "X-Workspace-ID": "w2" },- });- const result = await withWorkspaceMember(req, auth);- expect(result).toEqual({ workspaceId: "w2" });- });-- it("returns workspaceId from auth context (machine token)", async () => {- mockGetMember.mockResolvedValue({ id: "m1" } as any);- const result = await withWorkspaceMember(- makeReq(),- { ...auth, workspaceId: "w3" },- );- expect(result).toEqual({ workspaceId: "w3" });- });-- it("returns 400 when no workspace_id provided", async () => {- const result = await withWorkspaceMember(makeReq(), auth);- expect((result as any).status).toBe(400);- });-- it("returns 404 when user is not a member", async () => {- mockGetMember.mockResolvedValue(null as any);- const result = await withWorkspaceMember(- makeReq("http://localhost/api/test?workspace_id=w1"),- auth,- );- expect((result as any).status).toBe(404);- });-- it("returns 401 when userId is missing", async () => {- const result = await withWorkspaceMember(- makeReq("http://localhost/api/test?workspace_id=w1"),- { userId: "", email: "" },- );- expect((result as any).status).toBe(401);- });-});diff --git a/src/web/lib/middleware/workspace.ts b/src/web/lib/middleware/workspace.tsdeleted file mode 100644index 84190d449..000000000--- a/src/web/lib/middleware/workspace.ts+++ /dev/null@@ -1,49 +0,0 @@-import { NextRequest, NextResponse } from "next/server";-import type { AuthContext } from "./auth";-import { db } from "@/lib/db";--export interface WorkspaceContext extends AuthContext {- workspaceId: string;-}--export async function withWorkspaceMember(- req: NextRequest,- auth: AuthContext-): Promise<{ workspaceId: string } | NextResponse> {- const workspaceId =- req.nextUrl.searchParams.get("workspace_id") ||- req.headers.get("X-Workspace-ID") ||- auth.workspaceId;-- if (!workspaceId) {- return NextResponse.json(- { error: "workspace_id is required" },- { status: 400 }- );- }-- if (!auth.userId) {- return NextResponse.json(- { error: "user not authenticated" },- { status: 401 }- );- }-- const { getMemberByUserAndWorkspace } = await import(- "@/lib/db/queries/member"- );-- const membership = await getMemberByUserAndWorkspace(- db,- auth.userId,- workspaceId- );- if (!membership) {- return NextResponse.json(- { error: "workspace not found" },- { status: 404 }- );- }-- return { workspaceId };-}diff --git a/src/web/lib/services/task.test.ts b/src/web/lib/services/task.test.tsdeleted file mode 100644index 198c5d9e6..000000000--- a/src/web/lib/services/task.test.ts+++ /dev/null@@ -1,385 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--vi.mock("@/lib/db/queries/task");-vi.mock("@/lib/db/queries/agent");-vi.mock("@/lib/db/queries/message");--import * as taskQueries from "@/lib/db/queries/task";-import * as agentQueries from "@/lib/db/queries/agent";-import * as messageQueries from "@/lib/db/queries/message";-import { TaskService } from "./task";--const mockTaskQueries = vi.mocked(taskQueries);-const mockAgentQueries = vi.mocked(agentQueries);-const mockMessageQueries = vi.mocked(messageQueries);--function makeService() {- return new TaskService({} as any);-}--beforeEach(() => {- vi.clearAllMocks();-});--describe("TaskService", () => {- describe("enqueueTask", () => {- it("throws when agent not found", async () => {- mockAgentQueries.getAgent.mockResolvedValue(null as any);- const svc = makeService();- await expect(- svc.enqueueTask("a1", "c1", "w1", "do stuff")- ).rejects.toThrow("agent not found");- });-- it("throws when agent has no runtime", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- runtimeId: null,- maxConcurrentTasks: 5,- } as any);- const svc = makeService();- await expect(- svc.enqueueTask("a1", "c1", "w1", "do stuff")- ).rejects.toThrow("agent has no runtime");- });-- it("creates task with correct params on success", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- runtimeId: "rt1",- maxConcurrentTasks: 5,- } as any);- const fakeTask = { id: "t1", agentId: "a1", runtimeId: "rt1" };- mockTaskQueries.createTask.mockResolvedValue(fakeTask as any);-- const svc = makeService();- const result = await svc.enqueueTask("a1", "c1", "w1", "do stuff");-- expect(result).toBe(fakeTask);- expect(mockTaskQueries.createTask).toHaveBeenCalledWith(- expect.anything(),- {- agentId: "a1",- runtimeId: "rt1",- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- priority: 0,- }- );- });- });-- describe("claimTask", () => {- it("returns null when agent not found", async () => {- mockAgentQueries.getAgent.mockResolvedValue(null as any);- const svc = makeService();- expect(await svc.claimTask("a1")).toBeNull();- });-- it("returns null when at max capacity", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- maxConcurrentTasks: 2,- } as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(2);-- const svc = makeService();- expect(await svc.claimTask("a1")).toBeNull();- expect(mockTaskQueries.claimTask).not.toHaveBeenCalled();- });-- it("returns null when no queued tasks", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- maxConcurrentTasks: 5,- } as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- mockTaskQueries.claimTask.mockResolvedValue(null);-- const svc = makeService();- expect(await svc.claimTask("a1")).toBeNull();- });-- it("claims task and updates agent to working on success", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- maxConcurrentTasks: 5,- } as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(1);- const fakeTask = { id: "t1", agentId: "a1", runtimeId: "rt1" };- mockTaskQueries.claimTask.mockResolvedValue(fakeTask as any);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- const result = await svc.claimTask("a1");-- expect(result).toBe(fakeTask);- expect(mockAgentQueries.updateAgentStatus).toHaveBeenCalledWith(- expect.anything(),- "a1",- "working"- );- });- });-- describe("claimTaskForRuntime", () => {- it("returns null when no pending tasks", async () => {- mockTaskQueries.listPendingTasksByRuntime.mockResolvedValue([]);- const svc = makeService();- expect(await svc.claimTaskForRuntime("rt1")).toBeNull();- });-- it("deduplicates by agent ID", async () => {- mockTaskQueries.listPendingTasksByRuntime.mockResolvedValue([- { agentId: "a1", runtimeId: "rt1" },- { agentId: "a1", runtimeId: "rt1" },- { agentId: "a2", runtimeId: "rt1" },- ] as any);-- mockAgentQueries.getAgent.mockResolvedValue(null as any);-- const svc = makeService();- await svc.claimTaskForRuntime("rt1");-- // getAgent should only be called twice (a1 and a2), not three times- expect(mockAgentQueries.getAgent).toHaveBeenCalledTimes(2);- });- });-- describe("startTask", () => {- it("throws when not in dispatched status", async () => {- mockTaskQueries.startTask.mockResolvedValue(null as any);- const svc = makeService();- await expect(svc.startTask("t1")).rejects.toThrow(- "task not in dispatched status"- );- });-- it("returns started task on success", async () => {- const fakeTask = { id: "t1", status: "running" };- mockTaskQueries.startTask.mockResolvedValue(fakeTask as any);- const svc = makeService();- expect(await svc.startTask("t1")).toBe(fakeTask);- });- });-- describe("completeTask", () => {- it("creates assistant message from result.output", async () => {- const completedTask = {- id: "t1",- agentId: "a1",- conversationId: "c1",- };- mockTaskQueries.completeTask.mockResolvedValue(completedTask as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);- mockMessageQueries.createMessage.mockResolvedValue({} as any);-- const svc = makeService();- const result = JSON.stringify({ output: "Task done" });- await svc.completeTask("t1", result, "sess1", "/work");-- expect(mockMessageQueries.createMessage).toHaveBeenCalledWith(- expect.anything(),- {- conversationId: "c1",- role: "assistant",- content: "Task done",- taskId: "t1",- }- );- });-- it("does not create message when result has no output", async () => {- const completedTask = {- id: "t1",- agentId: "a1",- conversationId: "c1",- };- mockTaskQueries.completeTask.mockResolvedValue(completedTask as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- await svc.completeTask("t1", JSON.stringify({ foo: "bar" }), "s1", "/w");-- expect(mockMessageQueries.createMessage).not.toHaveBeenCalled();- });-- it("calls reconcileAgentStatus", async () => {- const completedTask = {- id: "t1",- agentId: "a1",- conversationId: "c1",- };- mockTaskQueries.completeTask.mockResolvedValue(completedTask as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(1);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- await svc.completeTask("t1", JSON.stringify({}), "s1", "/w");-- expect(mockAgentQueries.updateAgentStatus).toHaveBeenCalledWith(- expect.anything(),- "a1",- "working"- );- });- });-- describe("failTask", () => {- it("creates error message when error is non-empty", async () => {- const failedTask = { id: "t1", agentId: "a1", conversationId: "c1" };- mockTaskQueries.failTask.mockResolvedValue(failedTask as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);- mockMessageQueries.createMessage.mockResolvedValue({} as any);-- const svc = makeService();- await svc.failTask("t1", "something broke");-- expect(mockMessageQueries.createMessage).toHaveBeenCalledWith(- expect.anything(),- {- conversationId: "c1",- role: "assistant",- content: "Error: something broke",- taskId: "t1",- }- );- });-- it("does not create message when error is empty", async () => {- const failedTask = { id: "t1", agentId: "a1", conversationId: "c1" };- mockTaskQueries.failTask.mockResolvedValue(failedTask as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- await svc.failTask("t1", "");-- expect(mockMessageQueries.createMessage).not.toHaveBeenCalled();- });-- it("calls reconcileAgentStatus", async () => {- const failedTask = { id: "t1", agentId: "a1", conversationId: "c1" };- mockTaskQueries.failTask.mockResolvedValue(failedTask as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(2);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- await svc.failTask("t1", "err");-- expect(mockAgentQueries.updateAgentStatus).toHaveBeenCalledWith(- expect.anything(),- "a1",- "working"- );- });- });-- describe("claimTask Zod validation", () => {- it("returns properly typed camelCase object after Zod validation", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- maxConcurrentTasks: 5,- } as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- const fakeTask = {- id: "t1",- agentId: "a1",- runtimeId: "rt1",- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- status: "dispatched",- priority: 0,- result: null,- context: null,- sessionId: "sess-1",- workDir: "/tmp/work",- createdAt: new Date("2024-01-01"),- dispatchedAt: new Date("2024-01-01"),- startedAt: null,- completedAt: null,- error: null,- };- mockTaskQueries.claimTask.mockResolvedValue(fakeTask as any);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- const result = await svc.claimTask("a1");-- expect(result).not.toBeNull();- expect(result!.id).toBe("t1");- expect(result!.runtimeId).toBe("rt1");- });-- it("returns object with all expected fields including sessionId and workDir", async () => {- mockAgentQueries.getAgent.mockResolvedValue({- id: "a1",- maxConcurrentTasks: 5,- } as any);- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- const fakeTask = {- id: "t1",- agentId: "a1",- runtimeId: "rt1",- workspaceId: "w1",- conversationId: "c1",- prompt: "do stuff",- status: "dispatched",- priority: 0,- result: null,- context: { extra: true },- sessionId: "sess-99",- workDir: "/work/dir",- createdAt: new Date("2024-01-01"),- dispatchedAt: new Date("2024-01-01"),- startedAt: null,- completedAt: null,- error: null,- };- mockTaskQueries.claimTask.mockResolvedValue(fakeTask as any);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- const result = await svc.claimTask("a1");-- expect(result!.sessionId).toBe("sess-99");- expect(result!.workDir).toBe("/work/dir");- expect(result!.context).toEqual({ extra: true });- });- });-- describe("reconcileAgentStatus", () => {- it("sets working when running tasks > 0", async () => {- mockTaskQueries.countRunningTasks.mockResolvedValue(3);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- await svc.reconcileAgentStatus("a1");-- expect(mockAgentQueries.updateAgentStatus).toHaveBeenCalledWith(- expect.anything(),- "a1",- "working"- );- });-- it("sets idle when running tasks = 0", async () => {- mockTaskQueries.countRunningTasks.mockResolvedValue(0);- mockAgentQueries.updateAgentStatus.mockResolvedValue(null as any);-- const svc = makeService();- await svc.reconcileAgentStatus("a1");-- expect(mockAgentQueries.updateAgentStatus).toHaveBeenCalledWith(- expect.anything(),- "a1",- "idle"- );- });- });-});diff --git a/src/web/lib/services/task.ts b/src/web/lib/services/task.tsdeleted file mode 100644index bcea7a184..000000000--- a/src/web/lib/services/task.ts+++ /dev/null@@ -1,155 +0,0 @@-import type { Database } from "../db";-import * as taskQueries from "../db/queries/task";-import * as agentQueries from "../db/queries/agent";-import * as messageQueries from "../db/queries/message";-import { log } from "../logger";--export class TaskService {- constructor(private db: Database) {}-- async enqueueTask(- agentId: string,- conversationId: string,- workspaceId: string,- prompt: string- ) {- const agent = await agentQueries.getAgent(this.db, agentId);- if (!agent) {- throw new Error("agent not found");- }- if (!agent.runtimeId) {- throw new Error("agent has no runtime");- }-- return taskQueries.createTask(this.db, {- agentId,- runtimeId: agent.runtimeId,- workspaceId,- conversationId,- prompt,- priority: 0,- });- }-- async claimTask(agentId: string) {- const agent = await agentQueries.getAgent(this.db, agentId);- if (!agent) {- return null;- }-- const running = await taskQueries.countRunningTasks(this.db, agentId);- if (running >= agent.maxConcurrentTasks) {- return null;- }-- const task = await taskQueries.claimTask(this.db, agentId);- if (!task) {- return null;- }-- await agentQueries.updateAgentStatus(this.db, agentId, "working");- return task;- }-- async claimTaskForRuntime(runtimeId: string) {- const tasks = await taskQueries.listPendingTasksByRuntime(- this.db,- runtimeId- );- const triedAgents = new Set<string>();-- for (const candidate of tasks) {- if (triedAgents.has(candidate.agentId)) {- continue;- }- triedAgents.add(candidate.agentId);-- const task = await this.claimTask(candidate.agentId);- if (task && task.runtimeId === runtimeId) {- return task;- }- }-- return null;- }-- async startTask(taskId: string) {- const task = await taskQueries.startTask(this.db, taskId);- if (!task) {- throw new Error("task not in dispatched status");- }- return task;- }-- async completeTask(- taskId: string,- result: string,- sessionId: string,- workDir: string- ) {- let parsed: unknown;- try {- parsed = JSON.parse(result);- } catch {- parsed = { raw: result };- }-- const task = await taskQueries.completeTask(this.db, taskId, {- result: parsed,- sessionId: sessionId || null,- workDir: workDir || null,- });-- if (!task) {- const existing = await taskQueries.getTask(this.db, taskId);- const status = existing?.status ?? "unknown";- log.warn(`completeTask failed: task is in '${status}' status`, { taskId });- throw new Error(`cannot complete task in '${status}' status`);- }-- const payload = parsed as Record<string, unknown>;- const output =- typeof payload?.output === "string" ? payload.output : "";-- if (output) {- await messageQueries.createMessage(this.db, {- conversationId: task.conversationId,- role: "assistant",- content: output,- taskId,- });- }-- await this.reconcileAgentStatus(task.agentId);- return task;- }-- async failTask(taskId: string, error: string) {- const task = await taskQueries.failTask(this.db, taskId, error);-- if (!task) {- const existing = await taskQueries.getTask(this.db, taskId);- const status = existing?.status ?? "unknown";- log.warn(`failTask failed: task is in '${status}' status`, { taskId });- throw new Error(`cannot fail task in '${status}' status`);- }-- if (error) {- await messageQueries.createMessage(this.db, {- conversationId: task.conversationId,- role: "assistant",- content: `Error: ${error}`,- taskId,- });- }-- await this.reconcileAgentStatus(task.agentId);- return task;- }-- async reconcileAgentStatus(agentId: string) {- const running = await taskQueries.countRunningTasks(this.db, agentId);- const status = running > 0 ? "working" : "idle";- await agentQueries.updateAgentStatus(this.db, agentId, status);- }-}diff --git a/vitest.integration.config.ts b/vitest.integration.config.tsdeleted file mode 100644index 3e0986aa4..000000000--- a/vitest.integration.config.ts+++ /dev/null@@ -1,22 +0,0 @@-import { defineConfig } from "vitest/config";-import path from "path";--export default defineConfig({- test: {- globals: true,- environment: "node",- include: ["src/**/*.integration.test.ts"],- pool: "forks",- poolOptions: {- forks: {- singleFork: true,- },- },- fileParallelism: false,- },- resolve: {- alias: {- "@": path.resolve(__dirname, "src/web"),- },- },-});