agentleFS
dung204dung204/hono-starter-template/CLAUDE.md

hono-starter-template

CLAUDE.md1 starsChanged 3 months agoMITView on GitHub

A Bun + Hono + Drizzle (Postgres) API starter built around Spec-Driven TDD and a strictly enforced functional Clean Architecture. The books module (src/modules/books/) is the canonical reference implementation — every rule below is extracted from it, and when in doubt, read that module. Run a single test file: bun test tests/modules/books/books.service.spec.ts (unit) or bun test --preload ./tests/testcontainers-setup.ts tests/modules/books/books.controller.e2e.spec.ts (integration — needs the Testcontainers preload since Docker-backed Postgres has to be up before the file's imports resolve). lefthook runs biome…

  • Reads credentials

The file

We split this CLAUDE.md into the rules it gives an agent

4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Run a single test file: bun test tests/modules/books/books.service.spec.ts (unit) or bun test --preload ./tests/testcontainers-setup.ts …

    line 34
  2. Very specific:

    Every feature lives in src/modules/<feature>/, built from up to 7 file kinds, each named <module>.<kind>.ts even when flat:

    line 56
  3. Very specific:

    No relative imports beyond one level (../../x is banned) — use the @/* (src) / @tests/* (tests) path aliases instead.

    line 103
  4. Very specific:

    No default exports anywhere except src/index.ts (Bun's implicit HTTP-server-from-default-export convention) — Biome overrides carve out …

    line 104

≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

What this is

A Bun + Hono + Drizzle (Postgres) API starter built around Spec-Driven TDD and a strictly enforced functional Clean Architecture. The books module (src/modules/books/) is the canonical reference implementation — every rule below is extracted from it, and when in doubt, read that module.

Commands

bun install                    # install deps
cp .env.example .env           # configure env
docker compose -f resources/docker/docker-compose.local.yml up -d   # local Postgres/Redis/SeaweedFS

bun run db:migrate             # apply migrations (runtime migrator)
bun run dev                    # dev server, --hot, http://localhost:3000 (Swagger at /docs/openapi, AsyncAPI at /docs/asyncapi)

bun test                       # run everything (bare — see test-suffix warning below)
bun run test:unit              # unit only (*.spec.ts, excludes *.e2e.spec.ts)
bun run test:e2e               # integration only (e2e/**/*.e2e.spec.ts, spins up Testcontainers)
bun run test:unit:cov          # unit + lcov coverage
bun run test:e2e:cov           # e2e + lcov coverage

bunx biome check .             # lint + format check
bunx biome check --write .     # lint + format, autofix
bunx tsc --noEmit              # typecheck

bunx drizzle-kit generate --name=<snake_case_slug>   # generate a migration from schema.ts changes — never omit --name
bunx drizzle-kit migrate                              # apply pending migrations locally (drizzle-kit CLI form)
bunx squawk migrations/**/*.sql                        # lint generated SQL (also runs in pre-commit)

Run a single test file: bun test tests/modules/books/books.service.spec.ts (unit) or bun test --preload ./tests/testcontainers-setup.ts tests/modules/books/books.controller.e2e.spec.ts (integration — needs the Testcontainers preload since Docker-backed Postgres has to be up before the file's imports resolve).

lefthook runs biome check --write (staged src/**) and squawk (staged migrations/**/*.sql) on every commit.

AI workflow (skills)

This repo ships Claude Code skills that drive a feature through Red→Green→Refactor. For a new feature end to end:

/feature-flow <name>

This chains feature-plan (design, pausing for approval) → test-badass in Spec-Driven TDD mode (RED — failing tests from the plan) → gen-module (GREEN — code to satisfy them) → arch-audit (REFACTOR — fix architecture violations, keep tests green). Each phase also works standalone. arch-audit is the project-specific conventions linter (distinct from /code-review) — run it after hand-writing or editing anything under src/modules/, src/shared/, or src/configs/.

Never run gcloud directly — write the command into a plan section for the user to run themselves. Deploys/GCP bootstrap are documented in docs/plans/devops.md's "Manual GCP Setup" and are explicitly a manual, one-time step never executed by Claude Code.

Architecture

Full spec: docs/ARCHITECTURE.md (index) → docs/01-module-layout.md through docs/06-database-migrations.md (binding rules) → docs/07–docs/12 (per-subsystem operational reference: auth, pagination, logging, file upload, devops/CI, websockets) → docs/plans/*.md (design history/rationale, not binding). The condensed version:

Module layout

Every feature lives in src/modules/<feature>/, built from up to 7 file kinds, each named <module>.<kind>.ts even when flat:

KindFileOwns
schema<module>.schema.tsDrizzle table def + inferred row types. Only file in the module that imports Drizzle.
entity<module>.entity.tsZod-validated domain object — business rules, DB/HTTP-independent.
dto<module>.dto.tsZod request/response schemas + OpenAPI docs — the wire contract.
repository<module>.repository.tsData access via a curried factory.
errors<module>.errors.tsModule-specific domain errors (optional — only once src/shared/errors.ts isn't enough).
service<module>.service.tsUse-case layer — business logic, pure, framework-free.
controller<module>.controller.tsOpenAPIHono sub-router, inline handlers — never an extracted handler function.

schema/entity/dto are deliberately separate and allowed to diverge even in simple CRUD — don't collapse them for convenience. A kind stays a single flat file until it exceeds 2 files, then only that kind moves into a <kind>/ subfolder (nesting is per-kind, not per-module).

src/shared/ = reusable cross-cutting code (columns, base entity, generateId(), error factories, createController()). src/configs/ = central state/connections (db, env, redis, s3, logger). No top-level src/controllers/, src/services/, etc.

Functional Clean Architecture — no classes

Services, repositories, entities: plain functions and plain data only. No class, this, or inheritance in code we write — instantiating a framework's own class (new OpenAPIHono()) is glue, not business logic. Repositories are curried factory closures: createBookRepository(db: Db = defaultDb) returns an object of closures; service.ts hard-imports the resulting singleton (bookRepository) directly — no DI container. The db parameter is the only injectable seam, because DB clients (not repositories) are what actually get swapped in tests.

Shared fields (id, createdAt, updatedAt) compose via object spread (...idColumn, ...timestampColumns in Drizzle) and Zod .extend() (baseEntitySchema.extend({...})) — never redeclared per module, never inheritance.

IDs are app-generated (generateId() → Bun.randomUUIDv7()), assigned in the service layer, never DB-generated — idColumn has no default, so a forgotten generateId() call is a type error, not a silent bug. Timestamps are UTC, millisecond precision, ISO 8601 with trailing Z (timestamptz + precision: 3 in the DB, z.date() in the domain, z.iso.datetime({ precision: 3 }) on the wire, .toISOString() for the domain→wire mapping).

Errors

One JSON contract everywhere: { error: { code, message, details? } }. Built via createDomainError(code, message, statusCode, details?) — no Error subclass hierarchy, no instanceof; discriminate with the structural isDomainError() guard. service.ts throws domain errors directly (no Either/result wrapping); controllers stay branch-free. Every module's controller.ts must use createController() (never new OpenAPIHono() directly) — it wires both onError (thrown errors) and defaultHook (request-validation failures) to the same contract; missing either leaks an unformatted error shape. Never use c.notFound().

Testing

Testing Trophy — integration-first, unit as the exception. Tests live in tests/, mirroring src/modules/, never colocated with source; inside tests/modules/<module>/ files stay flat regardless of count. *.spec.ts = unit, *.e2e.spec.ts = integration — the dot before spec is load-bearing (bun test only auto-discovers .test/.spec/_test_/_spec_; .e2e-spec.ts with a hyphen is silently never run). Integration tests hit a real ephemeral Postgres via Testcontainers (tests/testcontainers-setup.ts, preloaded via bunfig.toml) and the real Hono router (someController.request(...)) — no mocking. Unit tests use spyOn() directly on the exported repository singleton (e.g. spyOn(bookRepository, 'findByIsbn')), restored with mock.restore() in afterEach. describe/it/expect/spyOn are named imports from 'bun:test', never ambient globals. The test-badass skill owns the detailed layer-choice/GWT/routing logic; the docs above cover only the mechanics.

Database migrations

Generated only, never hand-written: bunx drizzle-kit generate --name=<snake_case_slug> (always pass --name explicitly — the tool's random default is meaningless). .sql-only (linted by squawk, .squawk.toml at root), one directory per migration under migrations/. Naming: snake_case, 3-5 words, action-based for single-purpose changes (create_books_table) or intent-based for multi-column changes (update_user_profile_fields, not a chain of column names). The one hand-edit exception: adding a fixed lock_timeout/statement_timeout preamble and IF NOT EXISTS to CREATE TABLE statements immediately after generating — never a DDL logic change. Forward-only — no rollback tooling; fix a bad migration with a new forward migration. Production applies migrations via scripts/migrate.ts (the runtime migrator, a regular drizzle-orm dependency) as an explicit deploy step — never from inside src/index.ts, never on app boot.

Other subsystems (see the linked doc for the full contract before touching these)

  • Auth (docs/07) — users (profile identity) vs accounts (one row per login method) split; JWTs validated structurally with z.jwt(...) before signature verification; dual token delivery via X-Client-Type (cookies for web, JSON body otherwise); six Redis TTL keys built exclusively through redisKey(), never raw template strings.
  • Pagination (docs/08) — offset-based (page/pageSize) is the live default; multi-field whitelisted sort via createSortableQueryDto; flat exact-match filters; id (UUIDv7) is the deterministic default sort/tiebreaker. Response envelope always has data + fully-populated meta.{pagination,sort,filter}.
  • Logging (docs/09) — logger from src/configs/logger.ts (pino) only, never console.* (enforced by Biome noConsole). Audit logging is a separate AuditBus (publish/subscribe) seam, fire-and-forget, triggered only for authenticated mutating requests (POST/PATCH/PUT/DELETE), with redactSensitiveFields() always applied before persistence.
  • File upload (docs/10) — files module is intentionally generic (no owner/uploader columns); presigned S3-compatible URLs (Bun.S3Client) are the primary upload path (presign → client PUT → confirm), backed locally by SeaweedFS. A consumer module owns its own FK + access rules on top.
  • DevOps/CI (docs/11) — deploys to Cloud Run (Preview/Staging/Production) via two functionally-equivalent CI providers (GitHub Actions + GitLab CI) sharing one set of scripts under scripts/ci/. GCP bootstrap is manual, one-time, and never run by Claude Code (see AI workflow section above).
  • WebSockets (docs/12) — hono/bun's native upgradeWebSocket/websocket; any new route needs Object.assign(app, { websocket }) already wired in src/index.ts (it is) or upgrades silently fail at runtime with no type error. Redis Pub/Sub fans messages out across Cloud Run's non-sticky instances.

Code style (Biome-enforced, non-obvious ones)

  • No relative imports beyond one level (../../x is banned) — use the @/* (src) / @tests/* (tests) path aliases instead.
  • No default exports anywhere except src/index.ts (Bun's implicit HTTP-server-from-default-export convention) — Biome overrides carve out that one file plus a short list of scripts/config files for noConsole.
  • entity.ts imports plain zod; dto.ts is the only file that imports @hono/zod-openapi's z.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.