···4545pnpm test # run all tests across all packages
4646pnpm clean # remove all dist/ directories
4747devenv up # start appview + web servers via process manager
4848+pnpm --filter @atbb/appview db:migrate # run database migrations
4849pnpm --filter @atbb/appview dev # run a single package
4950pnpm --filter @atbb/appview test # run tests for a single package
5051pnpm --filter @atbb/spike spike # run the PDS spike script
···6061- `APPVIEW_URL` — URL the web package uses to reach the appview API
6162- `FORUM_HANDLE`, `FORUM_PASSWORD` — forum service account credentials (for spike/writes)
62636464+**OAuth & session management (required for production):**
6565+- `OAUTH_PUBLIC_URL` — public URL where AppView is accessible (used for client_id and redirect_uri)
6666+- `SESSION_SECRET` — signing key for session tokens (generate with `openssl rand -hex 32`)
6767+- `SESSION_TTL_DAYS` — session lifetime in days (default: 7)
6868+- `REDIS_URL` — optional Redis URL for session storage (recommended for multi-instance deployments)
6969+7070+## Deployment
7171+7272+### Docker
7373+7474+The project includes production-ready Docker infrastructure for single-container deployment:
7575+7676+```sh
7777+# Build the Docker image
7878+docker build -t atbb:latest .
7979+8080+# Run with docker-compose (recommended)
8181+cp docker-compose.example.yml docker-compose.yml
8282+# Edit docker-compose.yml with your DATABASE_URL, FORUM_DID, etc.
8383+docker compose up -d
8484+```
8585+8686+**What's included:**
8787+- Multi-stage Dockerfile (Node 22 Alpine, ~200MB final image)
8888+- Nginx reverse proxy serving both appview (port 3000) and web (port 3001) on port 80
8989+- Non-root user (`atbb:atbb`) for security
9090+- Health checks on `/api/healthz`
9191+- Production-ready entrypoint script
9292+9393+**Key files:**
9494+- `Dockerfile` — multi-stage build definition
9595+- `entrypoint.sh` — startup script (nginx + node servers)
9696+- `nginx.conf` — reverse proxy configuration
9797+- `docker-compose.example.yml` — orchestration template
9898+- `docs/deployment-guide.md` — comprehensive deployment instructions
9999+100100+**Database migrations:** The container does NOT auto-run migrations. Run manually before starting:
101101+```sh
102102+docker compose run --rm atbb pnpm --filter @atbb/appview db:migrate
103103+```
104104+63105## Pre-Commit Checks
6410665107Every commit automatically runs three checks in parallel via lefthook:
···9013291133Use sparingly — hooks catch issues that would fail in CI.
92134135135+## CI/CD
136136+137137+### GitHub Actions Workflows
138138+139139+**`.github/workflows/ci.yml`** — Runs on all pull requests (parallel jobs):
140140+- **Lint:** `pnpm exec oxlint .` — catches code quality issues
141141+- **Type Check:** `pnpm turbo lint` — verifies TypeScript types (allows failure due to 32 baseline errors in generated lexicon code)
142142+- **Test:** `pnpm test` — runs all tests with PostgreSQL 17 service container
143143+- **Build:** `pnpm build` — verifies compilation succeeds
144144+145145+**`.github/workflows/publish.yml`** — Runs on pushes to `main` branch:
146146+- Builds Docker image and publishes to GitHub Container Registry (GHCR)
147147+- Tags: `latest` (main branch) and `sha-<commit>` (specific commit)
148148+- Image: `ghcr.io/atbb-community/atbb:latest`
149149+150150+**All checks must pass before merging a PR.** The typecheck job is allowed to fail due to known baseline errors.
151151+93152### How Hooks Work
941539595-- **Lefthook** manages git hooks (`.lefthook.yml`)
154154+- **Lefthook** manages git hooks (`lefthook.yml`)
96155- **Oxlint** provides fast linting (`.oxlintrc.json`)
97156- **Turbo** filters checks to affected packages only
98157- Hooks auto-install after `pnpm install` via `prepare` script
···103162- 23 errors in generated lexicon code (`packages/lexicon/dist/types/**/*.ts`)
104163- 9 errors in source/test code (test context types, OAuth types)
105164106106-These are pre-existing issues that need to be resolved. Until fixed, use `--no-verify` when committing or temporarily disable the typecheck command in `.lefthook.yml`.
165165+These are pre-existing issues that need to be resolved. Until fixed, use `--no-verify` when committing or temporarily disable the typecheck command in `lefthook.yml`.
107166108167## Testing Standards
109168
+46-4
README.md
···8282### Other Commands
83838484```sh
8585-pnpm build # Build all packages
8686-pnpm clean # Remove all build artifacts
8787-pnpm lint # Type-check all packages
8585+pnpm build # Build all packages
8686+pnpm test # Run all tests
8787+pnpm clean # Remove all build artifacts
8888+pnpm lint # Type-check all packages
8989+pnpm --filter @atbb/appview db:migrate # Run database migrations
8890```
89919292+## Deployment
9393+9494+The project includes production-ready Docker infrastructure for containerized deployment.
9595+9696+### Quick Start with Docker
9797+9898+```sh
9999+# Copy and configure environment variables
100100+cp .env.example .env
101101+# Edit .env with production values (DATABASE_URL, FORUM_DID, OAUTH_PUBLIC_URL, etc.)
102102+103103+# Copy and configure docker-compose
104104+cp docker-compose.example.yml docker-compose.yml
105105+# Edit docker-compose.yml if needed
106106+107107+# Start services
108108+docker compose up -d
109109+110110+# Run database migrations
111111+docker compose exec atbb pnpm --filter @atbb/appview db:migrate
112112+```
113113+114114+### What's Included
115115+116116+- Multi-stage Dockerfile (Node 22 Alpine, ~200MB final image)
117117+- Nginx reverse proxy (serves both AppView and Web UI on port 80)
118118+- Health checks on `/api/healthz`
119119+- GitHub Actions CI/CD (automated testing and Docker image publishing)
120120+121121+See [`docs/deployment-guide.md`](docs/deployment-guide.md) for comprehensive deployment instructions.
122122+90123## Lexicons
9112492125atBB defines custom AT Proto record types under the `space.atbb.*` namespace:
···107140108141See [`docs/atproto-forum-plan.md`](docs/atproto-forum-plan.md) for the full project plan and current progress.
109142110110-**Current phase:** Phase 0 (Foundation) — complete. Monorepo scaffolding, lexicon definitions, and package stubs are in place. Phase 1 (AppView Core) is next.
143143+**Current phase:** Phase 2 (Auth & Membership) — nearing completion.
144144+145145+**Completed:**
146146+- ✅ Phase 0: Foundation (monorepo, lexicons, database schema)
147147+- ✅ Phase 1: AppView Core (firehose indexer, read/write API endpoints)
148148+- ✅ Phase 2: OAuth authentication (ATB-14), membership auto-creation (ATB-15)
149149+150150+**In progress:**
151151+- Role-based permissions (ATB-17)
152152+- Forum DID agent for moderation actions (ATB-18)
111153112154## Prior Art
113155
+6-6
docs/atproto-forum-plan.md
···189189- [ ] Basic responsive design
190190191191#### Phase 5: Packaging & Deployment (Week 9–10)
192192-- [ ] Dockerfiles for AppView and Web UI
193193-- [ ] Docker Compose with Postgres, AppView, Web UI
194194-- [ ] Config file: forum name, domain, admin DID, categories
195195-- [ ] README: setup guide, architecture overview
196196-- [ ] Seed script for initial forum + categories
197197-- [ ] Basic health check / status endpoint
192192+- [x] Dockerfiles for AppView and Web UI — **Complete:** Multi-stage Dockerfile with Node 22 Alpine, nginx reverse proxy, health checks (ATB-28)
193193+- [x] Docker Compose with Postgres, AppView, Web UI — **Complete:** `docker-compose.example.yml` with service orchestration (ATB-28)
194194+- [x] Config file: forum name, domain, admin DID, categories — **Complete:** `.env.example` with all required variables documented
195195+- [x] README: setup guide, architecture overview — **Complete:** README.md includes setup, architecture diagram, deployment instructions
196196+- [ ] Seed script for initial forum + categories — **Deferred:** Manual setup via spike script currently; automated wizard tracked in Future Roadmap
197197+- [x] Basic health check / status endpoint — **Complete:** `GET /api/healthz` and `GET /api/healthz/ready` implemented (ATB-9)
198198199199### Key Risks & Open Questions
200200
+10-10
docs/oauth-implementation-summary.md
···506506507507## Next Steps
508508509509-### Immediate (Phase 2 Continuation)
509509+### Completed Since This Document
510510511511-1. **ATB-15: Auto-Create Membership** — On first login, create `space.atbb.membership` record
512512-2. **ATB-16: Session Management Enhancements** — Redis-backed session store
513513-3. **ATB-17: Permission Middleware** — Role-based access control for protected routes
511511+1. ✅ **ATB-15: Auto-Create Membership** — Membership records now auto-created on first login (PR #27)
512512+2. ✅ **ATB-12: Write Endpoints** — Topic and reply creation endpoints implemented with OAuth sessions
514513515515-### Phase 3: Write Operations
514514+### Immediate (Phase 2 Continuation)
516515517517-1. **ATB-12: Write Endpoints** — Implement topic/reply creation using OAuth sessions
518518-2. **Test Write Flow** — Verify authenticated users can create posts on their PDS
519519-3. **Error Handling** — Handle PDS write failures, quota limits, network errors
516516+1. **ATB-16: Session Management Enhancements** — Redis-backed session store
517517+2. **ATB-17: Permission Middleware** — Role-based access control for protected routes
518518+3. **ATB-18: Forum DID Agent** — Dedicated agent for forum-level operations
520519521520### Phase 4: Web UI Integration
522521···562561### Related Issues
563562564563- [ATB-14: Implement AT Proto OAuth flow](https://linear.app/atbb/issue/ATB-14) (Complete ✅)
565565-- ATB-15: Auto-create membership on first login (Pending)
564564+- [ATB-15: Auto-create membership on first login](https://linear.app/atbb/issue/ATB-15) (Complete ✅)
565565+- [ATB-12: Write endpoints implementation](https://linear.app/atbb/issue/ATB-12) (Complete ✅)
566566- ATB-16: Redis-backed session storage (Pending)
567567- ATB-17: Permission middleware (Pending)
568568-- ATB-12: Write endpoints implementation (Blocked by ATB-14, now unblocked)
568568+- ATB-18: Forum DID agent (Pending)
569569570570## Contributors
571571
-259
docs/test-coverage-analysis.md
···11-# Test Coverage Analysis
22-33-## Current State: No Tests Exist
44-55-The monorepo has **zero test infrastructure**. No testing framework is installed, no test scripts exist in any `package.json`, and `turbo.json` has no `test` task. There are approximately **530 lines of source code** across 4 packages with 0% test coverage.
66-77----
88-99-## Recommended Test Framework Setup
1010-1111-**Vitest** is the best fit for this project:
1212-- Native ESM support (the repo uses `"type": "module"` everywhere)
1313-- Built-in TypeScript support via `tsx`/`esbuild` (no separate ts-jest config)
1414-- Workspace-aware — can share a root config while per-package configs override as needed
1515-- Fast, with watch mode out of the box
1616-1717-### Infrastructure needed
1818-1919-1. Install `vitest` as a root devDependency
2020-2. Add a root `vitest.workspace.ts` pointing at each package
2121-3. Add `"test": "vitest run"` scripts to each package's `package.json`
2222-4. Add a `"test"` task to `turbo.json` (with `dependsOn: ["^build"]` since appview/web depend on lexicon types)
2323-5. Add `pnpm test` as a root script
2424-2525----
2626-2727-## Package-by-Package Gaps and Recommendations
2828-2929-### 1. `@atbb/appview` — API Server (highest priority)
3030-3131-This is the most complex package (260 LOC) and where most business logic will land as stubs are implemented. It has the database schema, config loading, AT Protocol agent creation, and all API routes.
3232-3333-#### a) Route handler tests (high value)
3434-3535-**Files:** `src/routes/health.ts`, `src/routes/forum.ts`, `src/routes/categories.ts`, `src/routes/topics.ts`, `src/routes/posts.ts`
3636-3737-**What to test:**
3838-- `GET /api/healthz` returns `200` with `{ status: "ok", version: "0.1.0" }`
3939-- `GET /api/healthz/ready` returns `200` with `{ status: "ready" }`
4040-- `GET /api/forum` returns `200` with the expected forum shape
4141-- `GET /api/categories` returns `200` with `{ categories: [] }`
4242-- `GET /api/categories/:id/topics` returns `200` and echoes the `id` param
4343-- `POST /api/topics` returns `501` (not implemented)
4444-- `POST /api/posts` returns `501` (not implemented)
4545-4646-**How:** Use Hono's built-in `app.request()` test helper — no HTTP server needed:
4747-```ts
4848-import { describe, it, expect } from "vitest";
4949-import { apiRoutes } from "../src/routes/index.js";
5050-import { Hono } from "hono";
5151-5252-const app = new Hono().route("/api", apiRoutes);
5353-5454-describe("GET /api/healthz", () => {
5555- it("returns ok status", async () => {
5656- const res = await app.request("/api/healthz");
5757- expect(res.status).toBe(200);
5858- expect(await res.json()).toEqual({ status: "ok", version: "0.1.0" });
5959- });
6060-});
6161-```
6262-6363-**Why it matters:** As stubs are replaced with real implementations, having route-level tests in place catches regressions in response shape, status codes, and content-type headers. These tests are cheap to write now and will grow in value.
6464-6565-#### b) Config loading tests (medium value)
6666-6767-**File:** `src/lib/config.ts`
6868-6969-**What to test:**
7070-- Returns correct defaults when env vars are absent (`PORT` defaults to `3000`, `PDS_URL` defaults to `https://bsky.social`)
7171-- Parses `PORT` as an integer (not a string)
7272-- Returns provided env var values when set
7373-- Handles `PORT` set to a non-numeric string (currently `parseInt` would return `NaN` — should this throw?)
7474-7575-**Why it matters:** Config loading is the root of most "it works on my machine" bugs. The current implementation silently accepts empty strings for `forumDid` and `databaseUrl`, which will cause hard-to-debug runtime failures. Tests would document this behavior and motivate adding validation.
7676-7777-#### c) Database schema tests (medium value)
7878-7979-**File:** `src/db/schema.ts`
8080-8181-**What to test:**
8282-- Schema definitions export the expected table names
8383-- Column types match expectations (e.g., `posts.deleted` defaults to `false`)
8484-- Foreign key references are correct (`posts.did` → `users.did`, `posts.rootPostId` → `posts.id`, etc.)
8585-- Index names are correct and unique constraints are in place
8686-8787-**How:** These can be pure unit tests against the Drizzle schema objects — no database connection needed. Drizzle table objects expose `._.columns` and other metadata you can assert against.
8888-8989-**Why it matters:** Schema is the foundation. If someone accidentally removes an index or changes a foreign key, these tests catch it before it hits a migration.
9090-9191-#### d) Database integration tests (high value, but requires infrastructure)
9292-9393-**What to test:**
9494-- Insert/select/update/delete for each table
9595-- Foreign key constraints are enforced (e.g., inserting a post with a non-existent `did` fails)
9696-- Unique index violations behave as expected
9797-- The `createDb()` factory produces a working Drizzle client
9898-9999-**How:** Use a test PostgreSQL instance. Options:
100100-- **Testcontainers** (Docker-based, spins up a real Postgres per test suite)
101101-- **pg-mem** (in-memory Postgres emulator, faster but not 100% compatible)
102102-- A shared test database with transaction rollback between tests
103103-104104-**Why it matters:** This is where the most subtle bugs live — constraint violations, bad joins, missing indexes. As the appview stubs are fleshed out with real queries, these tests become critical.
105105-106106-#### e) AT Protocol agent factory test (low value now, higher later)
107107-108108-**File:** `src/lib/atproto.ts`
109109-110110-Currently just `new AtpAgent({ service: config.pdsUrl })` — not much to test. But as authentication and record-writing logic is added, this module should have tests verifying:
111111-- Agent is created with the correct service URL
112112-- Authentication errors are handled gracefully
113113-- Record write/read operations produce expected AT URI formats
114114-115115----
116116-117117-### 2. `@atbb/web` — Server-Rendered Web UI
118118-119119-#### a) API client tests (high value)
120120-121121-**File:** `src/lib/api.ts`
122122-123123-**What to test:**
124124-- `fetchApi("/categories")` calls the correct URL (`${appviewUrl}/api/categories`)
125125-- Throws an `Error` with status code and status text on non-2xx responses
126126-- Returns parsed JSON on success
127127-- Handles network failures (fetch throws)
128128-129129-**How:** Mock `global.fetch` with `vi.fn()` or use `msw` (Mock Service Worker):
130130-```ts
131131-import { describe, it, expect, vi, beforeEach } from "vitest";
132132-133133-// Mock fetch globally
134134-const mockFetch = vi.fn();
135135-vi.stubGlobal("fetch", mockFetch);
136136-137137-describe("fetchApi", () => {
138138- it("throws on non-ok response", async () => {
139139- mockFetch.mockResolvedValueOnce({
140140- ok: false, status: 500, statusText: "Internal Server Error",
141141- });
142142- const { fetchApi } = await import("../src/lib/api.js");
143143- await expect(fetchApi("/test")).rejects.toThrow("AppView API error: 500");
144144- });
145145-});
146146-```
147147-148148-**Why it matters:** `fetchApi` is the single point of contact between the web UI and the appview. Error handling here determines whether users see useful error messages or blank pages.
149149-150150-#### b) JSX component / layout tests (medium value)
151151-152152-**File:** `src/layouts/base.tsx`, `src/routes/home.tsx`
153153-154154-**What to test:**
155155-- `BaseLayout` renders valid HTML with the provided title
156156-- `BaseLayout` uses the default title "atBB Forum" when none is provided
157157-- `BaseLayout` includes the HTMX script tag
158158-- Home route returns `200` with `text/html` content type
159159-- Home page includes "Welcome to atBB" heading
160160-161161-**How:** Use Hono's `app.request()` and assert against the HTML string, or use a lightweight HTML parser. Hono JSX components can be tested by rendering them and checking the output string.
162162-163163-#### c) Config loading tests (low-medium value)
164164-165165-**File:** `src/lib/config.ts`
166166-167167-Same pattern as the appview config tests — verify defaults, parsing, and presence of required values.
168168-169169----
170170-171171-### 3. `@atbb/lexicon` — Lexicon Definitions
172172-173173-#### a) YAML-to-JSON build script tests (medium value)
174174-175175-**File:** `scripts/build.ts`
176176-177177-**What to test:**
178178-- Each YAML file in `lexicons/` produces valid JSON
179179-- Output JSON matches the expected Lexicon schema structure (has `lexicon`, `id`, `defs` fields)
180180-- No duplicate lexicon IDs across files
181181-- The `id` field in each lexicon matches its file path (e.g., `space/atbb/post.yaml` has `id: "space.atbb.post"`)
182182-183183-**How:** Rather than testing the build script directly (it's I/O-heavy), write validation tests that run against the YAML source files:
184184-```ts
185185-import { parse } from "yaml";
186186-import { readFileSync } from "fs";
187187-import { glob } from "glob";
188188-189189-describe("lexicon definitions", () => {
190190- const files = glob.sync("**/*.yaml", { cwd: "lexicons" });
191191-192192- it.each(files)("%s has a valid lexicon structure", (file) => {
193193- const content = readFileSync(`lexicons/${file}`, "utf-8");
194194- const parsed = parse(content);
195195- expect(parsed).toHaveProperty("lexicon", 1);
196196- expect(parsed).toHaveProperty("id");
197197- expect(parsed).toHaveProperty("defs");
198198- });
199199-});
200200-```
201201-202202-**Why it matters:** Lexicon definitions are the API contract for the entire AT Protocol integration. A malformed lexicon causes downstream build failures in type generation and runtime validation errors. Catching issues at the YAML level is far cheaper than debugging them at the API level.
203203-204204-#### b) Schema contract tests (high value)
205205-206206-**What to test:**
207207-- `space.atbb.post` has `text` as a required string field
208208-- `space.atbb.post` has optional `reply` with `root` and `parent` refs
209209-- `space.atbb.forum.forum` uses `key: literal:self`
210210-- `space.atbb.forum.category` uses `key: tid`
211211-- All `strongRef` usages have both `uri` and `cid` fields
212212-- `knownValues` are used (not `enum`) for extensible fields like `modAction.action`
213213-214214-**Why it matters:** These are the **contract tests** of the system. If a lexicon field is accidentally renamed or a required field becomes optional, it breaks interoperability with any PDS that stores atBB records. These tests protect the public API surface.
215215-216216----
217217-218218-### 4. `@atbb/spike` — PDS Integration Script
219219-220220-The spike is a manual integration test. It doesn't need unit tests itself, but:
221221-222222-#### Extractable test utilities (medium value)
223223-224224-The spike contains reusable patterns for:
225225-- Authenticating with a PDS
226226-- Creating/reading/deleting AT Protocol records
227227-- Generating TIDs
228228-229229-These should be extracted into a shared test utility module (e.g., `packages/test-utils/`) that integration tests across the monorepo can use.
230230-231231----
232232-233233-## Priority Matrix
234234-235235-| Priority | Area | Package | Effort | Impact |
236236-|----------|------|---------|--------|--------|
237237-| **P0** | Test infrastructure setup (vitest, turbo task, CI) | root | Low | Unblocks everything |
238238-| **P0** | Appview route handler tests | appview | Low | Catches regressions as stubs are implemented |
239239-| **P1** | Web API client tests (`fetchApi`) | web | Low | Validates the only web→appview boundary |
240240-| **P1** | Lexicon schema contract tests | lexicon | Low | Protects the AT Protocol API surface |
241241-| **P1** | Config loading tests (both packages) | appview, web | Low | Documents defaults, catches parse bugs |
242242-| **P2** | Database schema unit tests | appview | Medium | Catches accidental schema changes |
243243-| **P2** | JSX layout/component tests | web | Medium | Ensures correct HTML output |
244244-| **P2** | Lexicon build script validation | lexicon | Low | Catches YAML/JSON conversion issues |
245245-| **P3** | Database integration tests | appview | High | Requires Postgres test infra (Docker/testcontainers) |
246246-| **P3** | AT Protocol integration tests | appview | High | Requires PDS test instance or mock |
247247-| **P3** | Extract spike utilities into shared test-utils | spike | Medium | Enables reuse across integration tests |
248248-249249----
250250-251251-## Suggested Implementation Order
252252-253253-1. **Set up vitest** at the root + per-package, add `test` task to turbo.json
254254-2. **Appview route tests** — quick wins since Hono has a built-in test helper and the routes are simple right now
255255-3. **Lexicon contract tests** — validate YAML schema structure to protect the AT Protocol API
256256-4. **Web `fetchApi` tests** — mock fetch, verify URL construction and error handling
257257-5. **Config tests** for both packages — small but catches real bugs
258258-6. **Database schema tests** — assert on Drizzle metadata objects
259259-7. **Database integration tests** — add testcontainers or similar once there are real queries to test