From 964a3c721741af637611726a9c07a8e94a619800 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Thu, 15 Oct 2026 16:08:14 -0300 Subject: [PATCH] docs: refresh agents.md to match the current scaffold --- .env.example | 2 + AGENTS.md | 217 +++++++++++++++++++++++++++++++----------- apps/api/.env.example | 2 + 3 files changed, 166 insertions(+), 55 deletions(-) diff --git a/.env.example b/.env.example index c2c445a..4900783 100644 --- a/.env.example +++ b/.env.example @@ -11,6 +11,8 @@ BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32" BETTER_AUTH_URL="http://localhost:4100" # "development" enables pretty logs, "production" emits JSON NODE_ENV="development" +# Optional: Pino log level (defaults to "debug" outside production, "info" in production) +# LOG_LEVEL="info" # --- apps/web --- # Public URL of the API consumed by the frontend diff --git a/AGENTS.md b/AGENTS.md index e8558e8..d5c8c87 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,15 +2,57 @@ ## Status -Scaffold is in place: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`. -No CI, no database migrations and no product features yet. +Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`, +CI on GitHub Actions, Biome as the only JS/TS tool and the text Bun lockfile committed. + +Not done yet: no database migrations (`prisma/migrations` does not exist — no Postgres has been run against +the schema) and no product features. The only backend module is `health`, used as the reference example. ## Stack (source of truth: `STACK.md`) -- Monorepo orchestrated with **Turborepo** -- Backend: **Bun** + **Hono**, **Prisma** against **Postgres**, **Zod** for validation, **Pino** for logging -- Frontend: **React + Vite + TypeScript**, UI components from **shadcn/ui** -- Auth: **BetterAuth** +- Monorepo orchestrated with **Turborepo** (see the managed block at the end of this file) +- Backend: **Bun** + **Hono**, **Prisma 7** against **Postgres** (via `@prisma/adapter-pg`), **Zod** for + validation, **Pino** for logging, **BetterAuth** for auth +- Frontend: **React + Vite + TypeScript**, **Tailwind v4**, UI components from **shadcn/ui** +- Frontend routing: **TanStack Router** (file-based) · server state: **TanStack Query** · + forms: **React Hook Form + Zod** +- Tooling: Bun workspaces, **Biome** (lint + format + import sorting), **TypeScript 6** + +## Repository layout + +``` +apps/api/ Bun + Hono API (owns the Prisma schema and migrations) + prisma/ schema.prisma and (once created) migrations/ + src/app.ts createApp(): middleware chain, BetterAuth mount, module mounting + src/index.ts Bun entrypoint: exports { port, fetch } + src/lib/ logger, prisma, auth, problem-details, validate, result-json + src/modules/ modules///{route.ts,use-case.ts} (+ schema.ts, *.test.ts) + src/types.ts AppEnv: c.get('logger') / c.get('requestId') +apps/web/ React + Vite frontend + src/routes/ file-based routes; routeTree.gen.ts is generated + src/components/ ui/ (shadcn, vendored source) + layout/ (app shell) + src/hooks/ TanStack Query hooks (e.g. use-health.ts) + src/lib/ api-client, auth-client, query-client, utils +packages/shared/ @superlist/shared: Result pattern + Problem Details helpers/types +``` + +## Commands + +Run from the repo root. Verification order is `build`, then `lint` → `typecheck` → `test`. + +| Command | Effect | +| --------------------- | ----------------------------------------------------------------------------- | +| `bun run dev` | API on `:4100`, web on `:7153` (`bun run dev --filter=@superlist/web` for one) | +| `bun run build` | `turbo run build` (API bundle + web production build) | +| `bun run lint` | `biome check .` per package via turbo — fails on lint, format or import order | +| `bun run lint:fix` | `biome check --write .` across the repo (lint fixes, formatting, imports) | +| `bun run lint:ci` | `biome ci .` — whole repo, exactly what CI runs | +| `bun run format` | `biome format --write .` (`format:check` to verify only) | +| `bun run typecheck` | `tsc` per package (`apps/web` regenerates the route tree first) | +| `bun run test` | `bun test` in the API, `vitest` in web and shared | +| `bun run db:generate` | `prisma generate` (also needed after a fresh clone, before typechecking the API) | +| `bun run db:migrate` | `prisma migrate dev` — needs a reachable Postgres | +| `bun run db:studio` | Prisma Studio (long-running) | ## Conventions @@ -21,28 +63,31 @@ No CI, no database migrations and no product features yet. - Bun is configured with `minimumReleaseAge` (see `~/.bunfig.toml`), so brand new releases are rejected during install. If a dependency fails to resolve, pin the newest version that is at least a few days old instead of reaching for the very latest. -- Workspaces: - - `apps/api` — Bun backend (Prisma schema + migrations live here) - - `apps/web` — React/Vite frontend - - `packages/shared` — shared code (`@superlist/shared`: Result pattern, Problem Details helpers/types) -- Verification commands, run from the repo root: - - `bun run build` - - `bun run lint` → `bun run typecheck` → `bun run test` (in that order) - **Biome is the only JS/TS tooling: linting, formatting and import sorting.** One `biome.json` at the repo - root applies to every workspace. - - `bun run lint` → `biome check .` per package through turbo, so it also fails on formatting drift. - - `bun run lint:fix` → `biome check --write .` applies lint fixes, formatting and `organizeImports` across - the whole repo. - - `bun run lint:ci` → `biome ci .` is the whole-repo check used by CI. - - `bun run format` / `bun run format:check` are formatting-only. -- Markdown (`README.md`, `AGENTS.md`) is not covered: Biome does not format prose. -- `apps/web/src/components/ui/**` is excluded from Biome's recommended lint preset through an `overrides` entry: - those files are vendored shadcn/ui source regenerated by the CLI. They are still formatted. -- CI (`.github/workflows/ci.yml`) runs `db:generate` → `lint:ci` → `typecheck` → `test` → `build`. + root applies to every workspace, and each package's `lint` script is `biome check .`. + - `apps/web/src/components/ui/**` is exempt from the recommended lint preset through an `overrides` entry and + `noArrayIndexKey` / `useExhaustiveDependencies` are off there: those files are vendored shadcn/ui source + regenerated by the CLI. They are still formatted. + - Markdown (`README.md`, `AGENTS.md`) is not covered: Biome does not format prose. +- **Environment variables and Turborepo Strict Mode.** Turbo only passes the variables a task declares, so + every task that needs one lists it in `turbo.json`: `db:*` use `env: ["DATABASE_URL"]`, `test` declares the + API variables, `dev` uses `passThroughEnv` (they must reach the process but don't change its output). + `VITE_*` is covered by Vite framework inference. **When you introduce a new variable, add it to `turbo.json`** + or the task will fail (or worse, hit a stale cache) in CI. +- Env files: `cp apps/api/.env.example apps/api/.env` and `cp apps/web/.env.example apps/web/.env` (both + gitignored, and `.env.example` at the root documents every variable). Bun loads `.env` automatically; the + Prisma CLI does not, which is why `prisma.config.ts` imports `dotenv/config`. - Dev ports: API `4100`, web `7153`. They live in the `.env.example` files, `apps/web/vite.config.ts` and `.github/workflows/ci.yml` — change them together. +- **TypeScript 6 specifics:** `baseUrl` no longer exists (aliases are declared with `paths` only), and + `apps/web/tsconfig.app.json` enables `erasableSyntaxOnly` — no enums, namespaces or constructor parameter + properties in the web app. Both apps use `@/*` → `src/*` and `verbatimModuleSyntax` (use `import type`). +- CI (`.github/workflows/ci.yml`) runs on PRs and pushes to `main`: `bun install --frozen-lockfile` → + `db:generate` → `lint:ci` → `typecheck` → `test` → `build`, with Bun 1.4.0 and Node 22 for the Prisma CLI. - Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`, `apps/api/src/generated/`. +- Tests live next to the code as `*.test.ts`. The API uses `bun test` (`src/lib/result-json.test.ts`, + module-level `use-case.test.ts`); web and shared use Vitest. ## Backend architecture (Hono) @@ -51,9 +96,11 @@ features `list`, `create`, `update`, `delete`: ``` apps/api/src/modules/alerts/ + index.ts # exports alertsModule: mounts every feature route list/ route.ts # Hono route declaration + Zod validation + call to the use case use-case.ts # class with a single execute() method + schema.ts # Zod schemas for this feature (when it has input) create/ route.ts use-case.ts @@ -62,22 +109,26 @@ apps/api/src/modules/alerts/ - `route.ts` holds **only** the Hono route declaration, input validation (Zod), and the call to the use case's `execute`. No business logic, no DB access. - Business logic lives in a **use case class with a single `execute` method** (one class per feature), named - after the action: `ListAlerts`, `CreateAlert`. Dependencies (e.g. the Prisma client) are injected through the - constructor and instantiated in the route. -- Use cases return the **Result** pattern (`Ok` / `Failure` from `@superlist/shared`). Never throw for expected - outcomes; reserve exceptions for truly unexpected failures. -- Failures are Problem Details payloads built with the `problems` factories from `@superlist/shared` - (`problems.notFound(...)`, `problems.validation(...)`, `problems.conflict(...)`, …). + after the action: `ListAlerts`, `CreateAlert`, `GetStatus`. Dependencies (e.g. the shared Prisma client) are + injected through the constructor and instantiated in the route. +- Use cases return the **Result** pattern (`Ok` / `Failure` / `Result` from `@superlist/shared`). Never throw + for expected outcomes; reserve exceptions for truly unexpected failures. +- Failures are Problem Details payloads built with the `problems` factories from `@superlist/shared`: + `problems.badRequest`, `problems.unauthorized`, `problems.forbidden`, `problems.notFound`, + `problems.conflict`, `problems.validation(errors)`, `problems.internal`, `problems.unavailable`. - **Routes never check `result.ok` by hand**: every route ends with `resultJson(c, result)`, which serializes - `Ok` as JSON (200 by default, override with `{ status: 201 }`) and maps `Failure` to the matching RFC 9457 - `application/problem+json` response. + `Ok` as JSON (200 by default, override with `{ status: 201 }`, `204` sends an empty body) and maps `Failure` + to the matching RFC 9457 `application/problem+json` response. +- Wire the module in `createApp()` (`apps/api/src/app.ts`): `app.route('/alerts', alertsModule)`. ```ts // apps/api/src/modules/alerts/list/route.ts -import { validate } from '@/lib/validate' import { resultJson } from '@/lib/result-json' -import { AlertQuerySchema } from './schema' +import { validate } from '@/lib/validate' +import type { AppEnv } from '@/types' + import { ListAlerts } from './use-case' +import { AlertQuerySchema } from './schema' export const listAlertsRoute = new Hono().get( '/', @@ -91,20 +142,68 @@ export const listAlertsRoute = new Hono().get( ) ``` -- Validation always goes through `validate.*` (`validate.query`, `validate.json`, `validate.param`, - `validate.header`, `validate.cookie`, `validate.form`). It answers invalid input with a 422 Problem Details - payload containing per-field `errors`. -- **All responses follow RFC 9457 (Problem Details)** — errors use the `application/problem+json` media type - with `type`, `title`, `status`, `detail` fields. Problem builders live in - `packages/shared/src/problem-details.ts`; the HTTP helpers in `apps/api/src/lib/`. -- Zod is the only validation library. Define schemas next to the feature that uses them; share them through - `@superlist/shared` only when more than one module needs them. -- **Logging: Pino** — one shared logger in `apps/api/src/lib/logger.ts`, reachable from handlers as - `c.get('logger')`; never `console.log` in the backend. -- Unexpected throws are turned into Problem Details by `app.onError` in `apps/api/src/app.ts`. +```ts +// apps/api/src/modules/alerts/create/use-case.ts +import { Failure, Ok, problems, type ProblemDetails, type Result } from '@superlist/shared' -- Prisma: after changing the schema, run `bun run db:migrate` (from `apps/api`, or `bun run db:migrate` at the - root) and commit the generated migration — never edit migration files by hand. +import type { Database } from '@/lib/prisma' + +export class CreateAlert { + constructor(private readonly db: Database) {} + + async execute(input: CreateAlertInput): Promise> { + const existing = await this.db.alert.findUnique({ where: { slug: input.slug } }) + + if (existing) return Failure(problems.conflict('An alert with that slug already exists.')) + + const alert = await this.db.alert.create({ data: input }) + + return Ok(alert) + } +} +``` + +- Validation always goes through `validate.*` (`validate.json`, `validate.query`, `validate.param`, + `validate.header`, `validate.cookie`, `validate.form`). It answers invalid input with a 422 Problem Details + payload containing per-field `errors` (built from the Zod issues; nested paths are dotted, root issues land + under `_root`). +- **All responses follow RFC 9457 (Problem Details)** — errors use the `application/problem+json` media type + with `type`, `title`, `status`, `detail`, plus the optional `errors` extension. The schema and the `problem` / + `problems` builders live in `packages/shared/src/problem-details.ts`; the HTTP helpers + (`problemResponse`, `notFoundHandler`, `errorHandler`) in `apps/api/src/lib/problem-details.ts`. +- Zod is the only validation library, and Zod 4 is what is installed. Define schemas next to the feature that + uses them (`schema.ts`); share them through `@superlist/shared` only when more than one module needs them. +- **Logging: Pino** — one shared logger in `apps/api/src/lib/logger.ts`, reachable from handlers as + `c.get('logger')` (already enriched with the request id); never `console.log` in the backend. Level comes from + `LOG_LEVEL`, defaulting to `debug` (pretty) outside production and `info` (JSON) in production. +- Unexpected throws are turned into Problem Details by `app.onError`; unmatched routes by `app.notFound` + (both in `apps/api/src/lib/problem-details.ts`). +- `createApp()` middleware order matters: `secureHeaders` → `cors` (origins from `CORS_ORIGIN`, credentials on) + → `requestId` → request logger → BetterAuth → modules. +- **Auth**: BetterAuth is configured in `apps/api/src/lib/auth.ts` (Prisma adapter, `baseURL` from + `BETTER_AUTH_URL`, `secret` from `BETTER_AUTH_SECRET`, `trustedOrigins` from `CORS_ORIGIN`, + email+password enabled) and owns every route under `/api/auth/*`. +- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so + import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the + `@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from + `apps/api/src/lib/prisma.ts`; pass it into use cases instead of creating clients per request. +- After changing `prisma/schema.prisma`, run `bun run db:migrate` (from `apps/api`, or at the root) and commit + the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The + datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For + production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet. +- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema with lowercase + `@@map`ed table names; regenerate them with the BetterAuth CLI rather than by hand if the auth config changes. + +## Shared package (`@superlist/shared`) + +- Source-only internal package (`bun` resolves the TypeScript through the `exports` map; there is no build step). + Two entrypoints: `@superlist/shared` (everything) and `@superlist/shared/problem-details`. +- Contents: `result.ts` (`Ok`, `Failure`, `Ok`, `Failure`, `Result`) and `problem-details.ts` + (Zod schema, `ProblemDetails` type, `PROBLEM_CONTENT_TYPE`, `problemTypes`, `FieldErrors`, `problem()`, + `problems.*`). +- Add code here only when more than one workspace needs it; feature-specific schemas stay next to the feature. + It is dependency-light on purpose (`zod` only) because both the API and the browser bundle it. +- Tests use Vitest (`src/*.test.ts`), so new test files here follow that runner, not `bun test`. ## Frontend architecture (React + Vite) @@ -118,25 +217,33 @@ apps/web/src/ ``` - **Routing: TanStack Router with file-based routes.** Add a file under `src/routes` and the route tree is - regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`). Never edit - `routeTree.gen.ts`. + regenerated (`bun run routes:generate`, also run by `dev`, `build` and `typecheck`; the Vite plugin watches + the directory in dev). Never edit `routeTree.gen.ts`; `tsr.config.json` holds the generator config. - `(auth)/sign-in.tsx` — public routes. - - `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session and - redirects to `/sign-in` when there is none. + - `_authenticated/route.tsx` — pathless layout for signed-in pages; it guards on the BetterAuth session + (`authClient.useSession()`) and redirects to `/sign-in` when there is none. Add authenticated pages inside + `_authenticated/`. +- **Providers**: `src/main.tsx` creates the router with `createQueryClient()` in its context (so loaders can + prefetch), renders `QueryClientProvider` + `RouterProvider`, and registers the router type. `__root.tsx` + wraps everything in `ThemeProvider` + `TooltipProvider`, mounts the Sonner `Toaster` and lazy-loads the router + and query devtools in development only. - **Server state: TanStack Query only.** Never call `fetch` from a component; add a hook under `src/hooks` that exports `queryOptions` (`QueryOptions()`) plus a `use()` wrapper, and use `apiFetch` from `src/lib/api-client.ts` as the `queryFn`. Exporting the options lets route loaders prefetch with - `context.queryClient.ensureQueryData(...)` (the client is passed through the router context from `main.tsx`). + `context.queryClient.ensureQueryData(...)` (`use-health.ts` is the reference). +- `apiFetch` returns parsed JSON, sends `credentials: 'include'` (BetterAuth sessions are cookies) and throws + `ApiError` carrying the parsed `ProblemDetails` for non-2xx responses; `204` resolves to `undefined`. Error + UIs read `error.problem.detail`. - **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError` components — this registry version ships `field` instead of the older `form` component. - **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them - directly. Add new ones with + directly (then re-run `bun run lint:fix` so Biome's formatting sticks). Add new ones with `cd apps/web && ../../node_modules/.bin/shadcn add ` (this registry needs the `@shadcn/` prefix for some items, e.g. `@shadcn/field`). - `cn` comes from the `cn` package; `src/lib/utils.ts` re-exports it for local imports. -- Prefer small feature components over one large route file. -- Biome does not flag the `Route` export of route files, so route files stay clean; only the vendored - `components/ui` files are exempted from the recommended lint preset. +- Prefer small feature components over one large route file; route files export the `Route` object, which Biome + does not flag. +- Tests use Vitest (`vitest run --passWithNoTests`), currently `src/lib/api-client.test.ts`. diff --git a/apps/api/.env.example b/apps/api/.env.example index 0c00185..bd62cf3 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -4,3 +4,5 @@ CORS_ORIGIN="http://localhost:7153" BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32" BETTER_AUTH_URL="http://localhost:4100" NODE_ENV="development" +# Optional: Pino log level (defaults to "debug" outside production, "info" in production) +# LOG_LEVEL="info"