17 KiB
AGENTS.md
Status
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 (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/<name>/<feature>/{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
- Package manager: Bun —
bun install,bun run <script>. Do not introduce npm/pnpm/yarn lockfiles. - The committed lockfile is the text one (
bun.lock), enabled by the repo-levelbunfig.toml(saveTextLockfile = true). Turborepo reads it to resolve the workspace graph, so keep it in sync and never hand-edit it. - 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. - Biome is the only JS/TS tooling: linting, formatting and import sorting. One
biome.jsonat the repo root applies to every workspace, and each package'slintscript isbiome check ..apps/web/src/components/ui/**is exempt from the recommended lint preset through anoverridesentry andnoArrayIndexKey/useExhaustiveDependenciesare 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:*useenv: ["DATABASE_URL"],testdeclares the API variables,devusespassThroughEnv(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 toturbo.jsonor the task will fail (or worse, hit a stale cache) in CI. - Env files:
cp apps/api/.env.example apps/api/.envandcp apps/web/.env.example apps/web/.env(both gitignored, and.env.exampleat the root documents every variable). Bun loads.envautomatically; the Prisma CLI does not, which is whyprisma.config.tsimportsdotenv/config. - Dev ports: API
4100, web7153. They live in the.env.examplefiles,apps/web/vite.config.tsand.github/workflows/ci.yml— change them together. - TypeScript 6 specifics:
baseUrlno longer exists (aliases are declared withpathsonly), andapps/web/tsconfig.app.jsonenableserasableSyntaxOnly— no enums, namespaces or constructor parameter properties in the web app. Both apps use@/*→src/*andverbatimModuleSyntax(useimport type). - CI (
.github/workflows/ci.yml) runs on PRs and pushes tomain: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 usesbun test(src/lib/result-json.test.ts, module-leveluse-case.test.ts); web and shared use Vitest.
Backend architecture (Hono)
Endpoints are grouped into modules, and each module into features. Example: an alerts module with
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
route.tsholds only the Hono route declaration, input validation (Zod), and the call to the use case'sexecute. No business logic, no DB access.- Business logic lives in a use case class with a single
executemethod (one class per feature), named 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/Resultfrom@superlist/shared). Never throw for expected outcomes; reserve exceptions for truly unexpected failures. - Failures are Problem Details payloads built with the
problemsfactories from@superlist/shared:problems.badRequest,problems.unauthorized,problems.forbidden,problems.notFound,problems.conflict,problems.validation(errors),problems.internal,problems.unavailable. - Routes never check
result.okby hand: every route ends withresultJson(c, result), which serializesOkas JSON (200 by default, override with{ status: 201 },204sends an empty body) and mapsFailureto the matching RFC 9457application/problem+jsonresponse. - Wire the module in
createApp()(apps/api/src/app.ts):app.route('/alerts', alertsModule).
// apps/api/src/modules/alerts/list/route.ts
import { resultJson } from '@/lib/result-json'
import { validate } from '@/lib/validate'
import type { AppEnv } from '@/types'
import { ListAlerts } from './use-case'
import { AlertQuerySchema } from './schema'
export const listAlertsRoute = new Hono<AppEnv>().get(
'/',
validate.query(AlertQuerySchema),
async (c) => {
const query = c.req.valid('query') // typed straight from the schema, no cast
const result = await new ListAlerts(prisma).execute(query)
return resultJson(c, result)
},
)
// apps/api/src/modules/alerts/create/use-case.ts
import { Failure, Ok, problems, type ProblemDetails, type Result } from '@superlist/shared'
import type { Database } from '@/lib/prisma'
export class CreateAlert {
constructor(private readonly db: Database) {}
async execute(input: CreateAlertInput): Promise<Result<Alert, ProblemDetails>> {
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-fielderrors(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+jsonmedia type withtype,title,status,detail, plus the optionalerrorsextension. The schema and theproblem/problemsbuilders live inpackages/shared/src/problem-details.ts; the HTTP helpers (problemResponse,notFoundHandler,errorHandler) inapps/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/sharedonly when more than one module needs them. - Logging: Pino — one shared logger in
apps/api/src/lib/logger.ts, reachable from handlers asc.get('logger')(already enriched with the request id); neverconsole.login the backend. Level comes fromLOG_LEVEL, defaulting todebug(pretty) outside production andinfo(JSON) in production. - Unexpected throws are turned into Problem Details by
app.onError; unmatched routes byapp.notFound(both inapps/api/src/lib/problem-details.ts). createApp()middleware order matters:secureHeaders→cors(origins fromCORS_ORIGIN, credentials on) →requestId→ request logger → BetterAuth → modules.- Auth: BetterAuth is configured in
apps/api/src/lib/auth.ts(Prisma adapter,baseURLfromBETTER_AUTH_URL,secretfromBETTER_AUTH_SECRET,trustedOriginsfromCORS_ORIGIN, email+password enabled) and owns every route under/api/auth/*. - Prisma 7: the generator is
prisma-clientand writes toapps/api/src/generated/prisma(gitignored), so import it as@/generated/prisma/client— never@prisma/clientdirectly. The client uses the@prisma/adapter-pgadapter withDATABASE_URLand is exported asprisma(plus theDatabasetype) fromapps/api/src/lib/prisma.ts; pass it into use cases instead of creating clients per request. - After changing
prisma/schema.prisma, runbun run db:migrate(fromapps/api, or at the root) and commit the generated migration underapps/api/prisma/migrations— never edit migration files by hand. The datasource has nourlin the schema: it comes fromprisma.config.ts(env('DATABASE_URL')). For production,apps/apialso hasdb: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@@maped 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 (
bunresolves the TypeScript through theexportsmap; there is no build step). Two entrypoints:@superlist/shared(everything) and@superlist/shared/problem-details. - Contents:
result.ts(Ok,Failure,Ok<T>,Failure<E>,Result<T, E>) andproblem-details.ts(Zod schema,ProblemDetailstype,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 (
zodonly) because both the API and the browser bundle it. - Tests use Vitest (
src/*.test.ts), so new test files here follow that runner, notbun test.
Frontend architecture (React + Vite)
apps/web/src/
routes/ # file-based TanStack Router routes; routeTree.gen.ts is generated
components/ui/ # shadcn/ui components (checked in, editable source)
components/layout # app shell: sidebar, header, user menu
hooks/ # query hooks (e.g. use-health.ts)
lib/ # api-client, auth-client, query-client, utils
- Routing: TanStack Router with file-based routes. Add a file under
src/routesand the route tree is regenerated (bun run routes:generate, also run bydev,buildandtypecheck; the Vite plugin watches the directory in dev). Never editrouteTree.gen.ts;tsr.config.jsonholds the generator config.(auth)/sign-in.tsx— public routes._authenticated/route.tsx— pathless layout for signed-in pages; it guards on the BetterAuth session (authClient.useSession()) and redirects to/sign-inwhen there is none. Add authenticated pages inside_authenticated/.
- Providers:
src/main.tsxcreates the router withcreateQueryClient()in its context (so loaders can prefetch), rendersQueryClientProvider+RouterProvider, and registers the router type.__root.tsxwraps everything inThemeProvider+TooltipProvider, mounts the SonnerToasterand lazy-loads the router and query devtools in development only. - Server state: TanStack Query only. Never call
fetchfrom a component; add a hook undersrc/hooksthat exportsqueryOptions(<entity>QueryOptions()) plus ause<Entity>()wrapper, and useapiFetchfromsrc/lib/api-client.tsas thequeryFn. Exporting the options lets route loaders prefetch withcontext.queryClient.ensureQueryData(...)(use-health.tsis the reference). apiFetchreturns parsed JSON, sendscredentials: 'include'(BetterAuth sessions are cookies) and throwsApiErrorcarrying the parsedProblemDetailsfor non-2xx responses;204resolves toundefined. Error UIs readerror.problem.detail.- Forms: React Hook Form + Zod (
zodResolver). Render errors with the shadcnField/FieldErrorcomponents — this registry version shipsfieldinstead of the olderformcomponent. - shadcn/ui: components live in
src/components/uiand are source, not generated output — edit them directly (then re-runbun run lint:fixso Biome's formatting sticks). Add new ones withcd apps/web && ../../node_modules/.bin/shadcn add <component>(this registry needs the@shadcn/prefix for some items, e.g.@shadcn/field). cncomes from thecnpackage;src/lib/utils.tsre-exports it for local imports.- Prefer small feature components over one large route file; route files export the
Routeobject, which Biome does not flag. - Tests use Vitest (
vitest run --passWithNoTests), currentlysrc/lib/api-client.test.ts.
This is NOT the Turborepo you know
Turborepo configuration, task behavior, and CLI commands can vary between installed versions and may differ from your training data. Resolve the turbo package from this file's directory or relevant workspace; in monorepos, it may not be visible from the repository root. For example, run node -p "require.resolve('turbo/package.json')" from a workspace that depends on turbo.
Read docs/README.md inside that installed package first, then read the relevant pages from its docs/ directory before changing Turborepo configuration or commands. Heed deprecation notices. These bundled docs match the installed package version and are available without network access.
This block is written and re-added by turbo before repository-scoped commands when an AI agent is detected. In the Turborepo source repository, its template is defined in crates/turborepo-cli/src/cli/agent_guidance.rs. Removing the managed block while updates are enabled means a later qualifying invocation will add it again. Set "agentGuidance": false in the root turbo.json or turbo.jsonc to opt out; this does not remove an existing block. Keep the block committed with your work to avoid an uncommitted change on the next agent invocation.