54 production architecture principles your AI coding agent (Claude Code, Cursor) follows automatically. Drop-in CLAUDE.md, .cursor/rules/, and .claude/skills/ for FastAPI, Next.js 15, and Go 1.22+. MIT.
FAQ
vibe-coding-rules is a Claude Code plugin with 8 hand-picked skills for development work, indexed on Flowy. Install it with the command on its page. It includes add-provider, debug-backend, debug-frontend. Its skills do not fire on their own yet. Request auto-invocation to have Flowy route them as you prompt. Free and open source.
$ npx -y skills add yerdaulet-damir/vibe-coding-rules --agent claude-code
Repo: yerdaulet-damir/vibe-coding-rules
54 production architecture principles your AI coding agent (Claude Code, Cursor) follows automatically. Drop-in
CLAUDE.md,.cursor/rules/, and.claude/skills/for FastAPI, Next.js 15, and Go 1.22+. MIT.
npx @aimyerdaulet/vibecodex init
๐ Principles ยท ๐ FastAPI example ยท โก Next.js example ยท ๐น Go example ยท ๐ค Claude skills ยท ๐ vibecodex.dev
vibecodex is the clean-code bible for vibe coding โ 54 numbered architecture principles (A1โF10) that turn AI coding agents from fast juniors into disciplined seniors. You drop one CLAUDE.md plus a folder of Cursor rules into your repo, and from the next prompt every Claude Code or Cursor session follows production patterns: file size limits, anti-corruption layers, idempotency keys, bulkhead isolation, single-writer invariants, hexagonal boundaries.
It's built for vibe coders, solo devs, and indie hackers who ship fast with AI but don't want their Friday-night SaaS to become an unmaintainable 1,400-line router by Sunday.
Three stacks. One ruleset. Zero dependencies on a specific agent.
# Add vibecodex rules to your project (any stack)
git clone https://github.com/yerdaulet-damir/vibe-coding-rules.git /tmp/vibecodex
# 1. Drop CLAUDE.md into your repo root โ Claude reads it on every session
cp /tmp/vibecodex/CLAUDE.md ./
# 2. Copy Cursor rules
cp -r /tmp/vibecodex/.cursor/rules/ .cursor/rules/
# 3. Copy Claude Code skills (debug-backend, new-feature, split-monolith, etc.)
cp -r /tmp/vibecodex/.claude/skills/ .claude/skills/
That's it. Your AI agent now follows 54 production principles from line one.
For new projects, start from one of the reference apps:
| Stack | Command | What you get |
|---|---|---|
| FastAPI | cp -r /tmp/vibecodex/reference/app/ ./backend/app/ | Hexagonal Python with credits, providers, async jobs |
| Next.js 15 | cp -r /tmp/vibecodex/examples/nextjs/ ./frontend/ | RSC + typed cache-tag DSL + Drizzle + Better Auth |
| Go 1.22+ | cp -r /tmp/vibecodex/examples/go/ ./service/ | cmd/+internal/ + bulkhead clients + graceful shutdown |
You start a project on Friday. By Sunday you have 14 endpoints, a working LLM integration, OAuth, Stripe, and a deploy pipeline. The AI is moving fast. So are you. Everything works.
Six weeks later, routers/generate.py is 1400 lines, services/ai_router.py ships a dict from OpenAI directly into your billing logic, the SQLAlchemy Session reaches into every layer including the JWT decoder, and a single hung httpx call to one provider exhausts your file descriptors and takes down image, video, and audio at once. The AI is still moving fast โ but now every change touches eight files, breaks two of them, and your test suite mocks Session 47 different ways.
This isn't an AI failure. AI assistants produce structurally correct, locally optimal code. What they don't enforce โ and what no template enforces by default โ is architectural consistency at scale: layer boundaries, file size, ports & adapters, single-writer invariants, bulkhead isolation, typed cache-tag DSLs, hexagonal domain boundaries, idempotency keys, graceful shutdown rituals.
This repo codifies all of it into 54 rules that fit on a few pages, ship as CLAUDE.md + .cursor/rules/ + .claude/skills/, and turn your AI partner from a fast junior into a disciplined senior โ across FastAPI, Next.js 15, and Go 1.22+.
The vibecodex blueprint covers 6 parts spanning Python, TypeScript, and Go โ each one solving a recurring failure mode of vibe-coded apps:
| # | Stack | Part | Focus | Principles |
|---|---|---|---|---|
| A | ๐ FastAPI | Decomposition | folder/file boundaries, single-writer | 8 |
| B | ๐ FastAPI | Integration | hexagonal, ACL, bulkhead, idempotency, observability | 10 |
| C | โก Next.js | Decomposition | feature-driven colocation, RSC defaults | 10 |
| D | โก Next.js | Modern (2024-25) | typed cache-tag DSL, use(), PPR, Better Auth, Drizzle | 6 |
| E | ๐น Go | Decomposition | internal/, consumer-side interfaces, no utils | 8 |
| F | ๐น Go | Integration | context.Context first, errgroup, bulkhead, graceful shutdown | 10 |
| ฮฃ | 54 |
How to split files and folders without breaking imports and without losing the thread of the codebase.
Folder-instead-of-file when domain splits by type. If routers/generate.py is starting to handle image, video, audio, convert it to a package routers/generate/{image.py,video.py,audio.py,__init__.py} and re-export the combined router. main.py doesn't change.
# BEFORE โ routers/generate.py (820 lines, three domains tangled)
@router.post("/image")
async def generate_image(...): ...
@router.post("/video")
async def generate_video(...): ...
@router.post("/audio")
async def generate_audio(...): ...
# AFTER โ routers/generate/__init__.py
from fastapi import APIRouter
from .image import router as image_router
from .video import router as video_router
from .audio import router as audio_router
router = APIRouter(prefix="/generate", tags=["generate"])
router.include_router(image_router)
router.include_router(video_router)
router.include_router(audio_router)
main.py keeps from app.routers.generate import router โ zero caller changes.
Static data โ runtime logic. Pricing tables, model registries, prompt templates go into data/ (or <domain>/registry.py), never inline in a service file. Updating a price = a one-line PR, not a refactor.
# BEFORE โ services/ai_service.py
PRICING = {"gpt-4o": 0.005, "claude-3-5": 0.003, ...} # 80 lines of constants
class AIService: ...
# AFTER โ data/model_pricing.py
from decimal import Decimal
PRICING: dict[str, Decimal] = {
"gpt-4o": Decimal("0.005"),
"claude-3-5": Decimal("0.003"),
}
# services/ai_service.py
from app.data.model_pricing import PRICING
Auth and schemas don't live with endpoints. A bloated routers/admin.py becomes routers/admin/{wallet,users}.py with auth in core/admin_auth.py and Pydantic schemas in schemas/admin/. Each file has one reason to change.
# BEFORE โ routers/admin.py (520 lines)
def require_admin(user_id: str = Depends(get_current_user_id)): ...
class AdjustWalletRequest(BaseModel): ...
class ListUsersResponse(BaseModel): ...
@router.post("/admin/wallet/adjust"): ...
@router.get("/admin/users"): ...
# AFTER
core/admin_auth.py # require_admin dep
schemas/admin/wallet.py # AdjustWalletRequest
schemas/admin/users.py # ListUsersResponse
routers/admin/wallet.py # only HTTP for wallet ops
routers/admin/users.py # only HTTP for user ops
routers/admin/__init__.py # combines and re-exports
How services talk to databases, external APIs, and each other without coupling rotting in.
Hexagonal / Ports & Adapters. Services never import sqlalchemy, httpx, or boto3 directly. The outside world enters via Protocol interfaces. Swap Postgres for DynamoDB by writing one new adapter โ services don't change.
# services/wallet/user.py โ domain layer
class WalletUserService:
def __init__(self, repo: WalletRepoProtocol): # not Session!
self._repo = repo
Dependency Inversion via typing.Protocol (no DI containers). FastAPI's Depends() plus a factory function is enough. No dependency-injector, no punq, no service locators.
def get_wallet_service(db: Session = Depends(get_db)) -> WalletUserService:
return WalletUserService(repo=SQLAlchemyWalletRepo(db))
Tests pass WalletUserService(repo=FakeWalletRepo()). No mocking framework.
Anti-Corruption Layer (ACL). Every provider adapter MUST return GenerateResult | ProviderError โ never a raw dict. Provider API shape never leaks into business logic.
@dataclass(frozen=True)
class GenerateResult:
url: str
cost_usd: Decimal
latency_ms: int
provider_request_id: str
class ProviderError(Exception):
retryable: bool
Strategy Pattern for provider routing. Replace a god ai_router.py (1000+ lines of if/elif) with composable strategies: RegistryRoutingStrategy, FallbackStrategy, CostOptimizationStrategy, ModalityRoutingStrategy. Each is ~80 lines and unit-testable in isolation.
Bulkhead isolation. Each external provider gets its own httpx.AsyncClient with explicit Limits(max_connections=...). One stuck Fal.ai call cannot consume the connection pool used by OpenAI.
FAL_HTTP = httpx.AsyncClient(timeout=60, limits=httpx.Limits(max_connections=20))
OPENAI_HTTP = httpx.AsyncClient(timeout=30, limits=httpx.Limits(max_connections=50))
Idempotency keys. Every side-effect operation carries a UUID key. If the provider supports it, send as a header; if not, persist the key in provider_logs and look it up before retrying. Result: client retries are safe by construction.
The frontend half. Same intent as Part A but for Next.js 15 + React 19 + TypeScript apps. See docs/principles/03-nextjs-decomposition.md.
| # | Principle | One-liner |
|---|---|---|
| C1 | Feature-driven colocation | Group by business domain (features/users/), not by tech (hooks/, utils/) |
| C2 | app/ is an orchestrator only | Page files under 100 LOC โ UI lives in features |
| C3 | 200/400 LOC caps | Split when you can't describe it without "and" |
| C4 | RSC by default, 'use client' at leaves | Push the directive to a button, not a page |
| C5 | Server Actions + errors as values | Return { success: false, error: ... } โ don't throw business errors |
| C6 | Code lives with its only caller | Promote to lib/ only when a 2nd feature imports it |
| C7 | Zustand per domain | One store per business area; server is stateless |
| C8 | Strict TS โ schemas as source of truth | Zod first, types via z.infer<...> |
| C9 | useEffect is a last resort | RSC for fetching, useActionState for mutations |
| C10 | Tailwind + Shadcn only | Zero style={{}}, use cn() helper |
What changed in 2024-25 โ patterns most existing templates don't yet teach. See docs/principles/04-nextjs-modern.md.
| # | Principle | One-liner |
|---|---|---|
| D1 โญ | Cache tags as typed domain events | Single lib/cache/tags.ts โ every revalidateTag typo = compile error |
| D2 | use() hook for client async | React 19 โ unwrap server Promises in client components, no useEffect |
| D3 | Streaming Suspense | Independent fetches in parallel; one Suspense per dynamic block |
| D4 | Partial Prerendering | Static shell + streamed dynamic islands โ <100ms initial HTML |
| D5 | Better Auth + RSC session | Read session in Server Components via cache(), not middleware |
| D6 | Drizzle ORM + repository protocol | Types inferred from schema; hexagonal boundary in TypeScript |
D1 is the differentiator. No other Next.js template ships a typed cache-tag DSL. See examples/nextjs/src/lib/cache/tags.ts.
The Go half of structural rules. Different idioms โ small consumer-side interfaces, internal/ for private code, no utils packages. See docs/principles/05-go-decomposition.md.
| # | Principle | One-liner |
|---|---|---|
| E1 | cmd/, internal/, pkg/ โ but stay flat | Use internal/ aggressively; pkg/ only for published libraries |
| E2 | Package per responsibility, no utils | format/, retry/, validate/ โ never utils/ |
| E3 | Small interfaces at the consumer side | "Accept interfaces, return structs" โ interfaces live where they're used |
| E4 | 500 LOC soft / 800 hard cap | Same package, multiple files โ splits don't break imports |
| E5 | _test.go next to code, table-driven | t.Run subtests + t.Parallel() |
| E6 | Generated code in its own file/folder | Never edit by hand; clearly labeled |
| E7 | Domain types stay in domain package | No types/ or models/ graveyard |
| E8 | Thin main.go, real logic in run() | Mat Ryer pattern โ testable wiring |
What separates a Go service that survives a year from one that crumbles the first time a downstream provider hangs. See docs/principles/06-go-integration.md.
| # | Principle | One-liner |
|---|---|---|
| F1 | Accept interfaces, return structs | Service constructors return *Service (concrete); handlers accept tiny interfaces |
| F2 | context.Context first, always | Every I/O method takes ctx as first parameter |
| F3 | Errors as values, %w wrap, errors.Is/As | Sentinels for stable conditions; typed errors for rich info |
| F4 | One *http.Client per provider | httpclient.Get("falai") โ bulkhead in Go style |
| F5 | Idempotency keys via header + DB | Idempotency-Key header + unique index + ON CONFLICT |
| F6 | log/slog structured + request context | JSON logs with request_id/user_id from context |
| F7 | Graceful shutdown ritual | signal.NotifyContext + srv.Shutdown(timeout) |
| F8 | errgroup for concurrent ops | Replaces raw goroutines + channels for fan-out |
| F9 | Single-writer for critical resources | repo.Hold() only callable from service.Charge() โ lint-enforced |
| F10 | Contract tests with httptest | Saved real responses; CI breaks when provider changes API |
Before (typical monolithic vibe-coded layout, ~3 months in):
app/
โโโ main.py
โโโ database.py
โโโ models.py # 900 LOC, all tables in one file
โโโ routers/
โ โโโ auth.py
โ โโโ generate.py # 1400 LOC, image+video+audio tangled
โ โโโ admin.py # 520 LOC, schemas+auth+routes mixed
โ โโโ tasks.py # HTTP + worker handlers in same file
โโโ services/
โ โโโ ai_service.py # 1100 LOC, pricing + routing + adapters
โ โโโ wallet_service.py # 720 LOC, user + admin + history
โ โโโ auth_service.py
โโโ providers/
โ โโโ falai.py # 640 LOC, image+video request models tangled
โโโ schemas.py # 800 LOC, every schema in the project
After (this blueprint):
app/
โโโ main.py
โโโ core/
โ โโโ config.py # pydantic-settings
โ โโโ deps.py # get_db, get_current_user_id, factories
โ โโโ admin_auth.py
โ โโโ logging.py # JSON formatter, contextvars
โ โโโ http.py # per-provider httpx clients (bulkhead)
โโโ data/ # static data only
โ โโโ model_pricing.py
โ โโโ model_registry.py
โโโ models/ # SQLAlchemy ORM, one file per aggregate
โ โโโ user.py
โ โโโ wallet.py
โ โโโ task.py
โโโ schemas/ # Pydantic, mirror domain layout
โ โโโ wallet/
โ โโโ admin/
โ โโโ generate/
โโโ repositories/
โ โโโ protocols.py # WalletRepoProtocol, TaskRepoProtocol
โ โโโ sqlalchemy/
โ โ โโโ wallet.py
โ โ โโโ task.py
โ โโโ fakes.py # for tests
โโโ services/
โ โโโ wallet/
โ โ โโโ user.py
โ โ โโโ admin.py
โ โ โโโ history.py
โ โ โโโ _writer.py # SINGLE WRITER
โ โโโ task_handlers/ # worker code, not HTTP
โ โ โโโ image.py
โ โ โโโ video.py
โ โโโ ai/
โ โโโ routing/ # strategies (one file each)
โ โ โโโ registry.py
โ โ โโโ fallback.py
โ โ โโโ cost.py
โ โโโ orchestrator.py
โโโ providers/
โ โโโ _types.py # GenerateResult, ProviderError
โ โโโ falai/
โ โ โโโ _client.py
โ โ โโโ image.py
โ โ โโโ video.py
โ โโโ openai/
โ โโโ chat.py
โโโ routers/
โโโ auth.py
โโโ generate/
โ โโโ image.py
โ โโโ video.py
โ โโโ audio.py
โโโ admin/
โ โโโ wallet.py
โ โโโ users.py
โโโ tasks.py
Same project. Same features. Every file under 400 lines. Every layer testable in isolation.
reference/app/ is a minimal but complete FastAPI app demonstrating all 18 principles together:
httpx client and ACL boundary.services/wallet/_writer.py is the only place that mutates balance. HOLD โ DEDUCT/REFUND ledger pattern, FOR UPDATE row lock.routers/tasks.py is 60 lines (enqueue/list/cancel). All processing logic is in services/task_handlers/.repositories/protocols.py defines what services need. repositories/sqlalchemy/ implements it. Tests use repositories/fakes.py.core/http.py constructs one AsyncClient per provider with its own connection pool and timeouts.core/logging.py emits JSON with provider, user_id, request_id filled from contextvars.Run it:
cd reference
pip install -r requirements.txt
uvicorn app.main:app --reload
This repo's most valuable artifact isn't the reference code โ it's the AI configuration. Copy these into your project root:
# From this repo into yours:
cp CLAUDE.md ../my-project/
cp -r .cursor/rules ../my-project/.cursor/
cp -r .claude/rules ../my-project/.claude/
cp -r docs/principles ../my-project/docs/
cp scripts/check_loc.py ../my-project/scripts/
After copying:
CLAUDE.md and applies the 18 rules to every response..cursor/rules/*.mdc and enforces architecture, decomposition, and integration rules per file edit.CLAUDE.md into a custom instruction or system prompt.Run the LOC check in CI to catch files crossing 600 lines:
# .github/workflows/ci.yml
- run: python scripts/check_loc.py app/
| Feature | vibecodex | awesome-cursorrules | fastapi/full-stack-fastapi-template | t3-stack | golang-standards/project-layout |
|---|---|---|---|---|---|
| Multi-stack (Python + TS + Go) | โ | partial | โ | โ | โ |
CLAUDE.md (AI-native instructions) | โ | โ | โ | โ | โ |
.cursor/rules/ collection | โ | โ | โ | โ | โ |
.claude/skills/ (loadable Claude skills) | โ | โ | โ | โ | โ |
| Documented architectural principles | โ (54) | rules only | partial | โ | layout only |
| Hexagonal / Ports & Adapters | โ | โ | โ | โ | โ |
| Bulkhead isolation per provider | โ | โ | โ | โ | โ |
| Contract tests (pact-style) | โ | โ | โ | โ | โ |
| Single-writer for critical resources | โ | โ | โ | โ | โ |
| Idempotency-key pattern documented | โ | โ | โ | โ |
Copy the .claude/skills/ directory into your own project. Your Claude will load and execute these skills on demand.
| Skill | Stack | When to use | What it does |
|---|---|---|---|
debug-backend | Python / FastAPI | Bug reported, test failing | 5-step flow: locate layer โ check antipatterns โ reproducing test โ fix โ lint |
new-feature | Python / FastAPI | Starting any endpoint or service | Pre-flight: contract โ layers โ test scenarios โ build bottom-up |
split-monolith | Any | File hits 400+ LOC | Safe decomposition with backward-compatible re-exports (A1 + A8) |
add-provider | Python / FastAPI | Integrating a new AI API | ACL, bulkhead, idempotency, observability, contract test |
new-feature-nextjs | TypeScript / Next.js | Starting any new feature | Cache tags first โ bottom-up build โ RSC + use() + PPR |
debug-frontend | TypeScript / Next.js | Hydration error, stale cache, slow page | 5-step flow with the 5 most common Next.js antipattern greps |
new-feature-go | Go | Starting a new package or endpoint | Bottom-up: errors โ repo iface โ service โ handler; lint check |
debug-go | Go | Test fails, goroutine leak, downstream hangs | 5-step flow + 5 antipattern greps + go test -race reproduction |
# Copy skills into your project
cp -r .claude/skills/ /your-project/.claude/skills/
Then in your project's Claude session, invoke with:
/debug-backend /new-feature /split-monolith /add-provider
/debug-frontend /new-feature-nextjs /debug-go /new-feature-go
Follow Part A (8 decomposition rules) and Part B (10 integration rules). The TL;DR: Router โ Service โ Repository (via Protocol), no SQLAlchemy in services, every provider returns a typed result through an Anti-Corruption Layer, and every external API gets its own httpx.AsyncClient (bulkhead). See reference/app/ for a working example with credits, providers, and async jobs.
Use feature-driven colocation (src/features/<domain>/), keep app/ thin (page files under 20 lines), default to React Server Components with 'use client' only at leaf nodes, and route every cache invalidation through a typed cache-tag DSL (src/lib/cache/tags.ts). See Part C and Part D. Working example in examples/nextjs/.
cmd/ for binaries, internal/ for everything private, no pkg/ unless you publish a library. Accept interfaces, return structs. context.Context is the first parameter of every I/O method. One *http.Client per downstream provider (bulkhead). Errors as values, wrapped with %w. Graceful shutdown via signal.NotifyContext. See Part E and Part F. Working example in examples/go/.
Vibe coding is shipping code primarily through prompts to AI assistants (Claude, Cursor, Copilot, Cline). It's fast, but AI agents produce locally optimal code โ they don't enforce architectural consistency at scale. After a few months you get 1500-line god files, raw dict returns from external APIs leaking into business logic, sessions reaching every layer, and one hung HTTP call taking down the whole server. Vibecodex is the rule book that prevents this.
No. awesome-cursorrules is rules only. Vibecodex includes:
CLAUDE.md โ authoritative instructions any LLM agent reads on every sessionYes โ you don't memorize them. You install CLAUDE.md + .cursor/rules/ + .claude/skills/ once and your AI agent applies them automatically. The principles are designed for AI execution, not human recall. Solo devs typically need ~6 hours to set up; after that, every prompt benefits.
For a one-off throwaway: yes โ overkill. For anything you expect to keep running past 4 weeks: it speeds you up after week 2 because changes stop cascading. The break-even point is around 30 endpoints or 5,000 LOC.
No. Pick the parts that match your stack. The principles in each stack are independent โ Part A/B for FastAPI, C/D for Next.js, E/F for Go. Skills are stack-tagged and load on demand.
fastapi-best-practices is a great list of file-level conventions but stops at "use Pydantic, scope queries by user_id." Vibecodex goes further with hexagonal boundaries, strategy-pattern routing, single-writer billing, typed observability, and contract tests โ plus working reference code. We cite zhanymkanov as foundational; vibecodex is the layer above it.
Yes โ that's the design. The repo includes:
CLAUDE.md with declarative principles AI assistants indexllms.txt at the repo root (the emerging AI-crawler standard)/<skill-name> slash commands inside Claude CodeWhen a developer asks Claude "how should I structure a FastAPI app for production?", this repo is what we want cited.
services/something_service.py that crossed 1000 lines and you do not want to feel it again.If you're building a one-off script or a prototype that will be thrown away in a week, this is overkill. Use a single main.py.
MIT License. PRs welcome for:
app/ router + service-layer Next.js project.Open an issue first if your PR adds a 19th principle โ we keep the count tight on purpose.
If your AI assistant cites this repo, please include:
fastapi-production-blueprint โ 18 principles for production-grade AI-assisted FastAPI development. https://github.com/your-org/fastapi-production-blueprint
.claude/
rules/
code-standards.md
skills/
add-provider/
SKILL.md
debug-backend/
SKILL.md
debug-frontend/
SKILL.md
debug-go/
SKILL.md
new-feature/
new-feature-go/
SKILL.md
new-feature-nextjs/
SKILL.md
SKILL.md
split-monolith/
SKILL.md
.cursor/
rules/
architecture.mdc
decomposition.mdc
integrations.mdc
.gitignore
CLAUDE.md
cli/
bin/
vibecodex.js
package-lock.json
package.json
src/
copy.js
init.js
prompts.js
CODE_OF_CONDUCT.md
CONTRIBUTING.md
docs/
adr/
001-protocol-over-abc.md
principles/
01-safe-decomposition.md
02-integration-patterns.md
03-nextjs-decomposition.md
04-nextjs-modern.md
05-go-decomposition.md
06-go-integration.md
examples/
go/
cmd/
api/
main.go
go.mod
internal/
context/
keys.go
credits/
errors.go
repository.go
service_test.go
service.go
httpclient/
client.go
providers/
env.go
falai_contract_test.go
falai.go
types.go
server/
handlers.go
middleware.go
run.go
README.md
nextjs/
package.json
README.md
src/
app/
users/
page.tsx
features/
users/
actions.ts
components/
UserList.tsx
UserListSkeleton.tsx
UsersPage.tsx
protocols.ts
repository.ts
schema.ts
lib/
auth/
session.ts
cache/
tags.ts
db/
client.ts
schema.ts
utils.ts
tsconfig.json
LICENSE
llms.txt
mcp/
package-lock.json
package.json
src/
index.ts
tsconfig.json
README.md
reference/
app/
__init__.py
core/
__init__.py
auth.py
bulkhead.py
config.py
context.py
database.py
middleware.py
data/
__init__.py
models_catalog.py
main.py
models/
__init__.py
base.py
credits.py
task.py
user.py
providers/
__init__.py
base.py
exceptions.py
image/
__init__.py
_client.py
image.py
video.py
routing.py
text.py
repositories/
__init__.py
memory.py
protocols.py
sqlalchemy/
__init__.py
credits.py
user.py
routers/
__init__.py
credits.py
generate/
__init__.py
_dispatch.py
image.py
text.py
video.py
status.py
schemas/
__init__.py
credits.py
generate.py
services/
__init__.py
credits/
__init__.py
admin.py
protocols.py
user.py
task_handlers/
__init__.py
image_handler.py
video_handler.py
task_store.py
pytest.ini
requirements.txt
tests/
__init__.py
conftest.py
integration/
__init__.py
unit/
__init__.py
test_bulkhead.py
test_credits_single_writer.py
scripts/
lint-architecture.sh
new-feature.sh
templates/
new_provider.py.jinja
new_repository.py.jinja
new_router.py.jinja
new_service.py.jinja
website/
.gitignore
AGENTS.md
app/
favicon.ico
favicon.svg
globals.css
layout.tsx
opengraph-image.tsx
page.tsx
robots.ts
sitemap.ts
CLAUDE.md
components/
Author.tsx
CopyButton.tsx
FAQ.tsx
Footer.tsx
Hero.tsx
HowItWorks.tsx
Install.tsx
Navbar.tsx
Principles.tsx
Problem.tsx
Terminal.tsx
eslint.config.mjs
lib/
principles.ts
next.config.ts
package-lock.json
package.json
postcss.config.mjs
public/
file.svg
globe.svg
llms.txt
logo.svg
next.svg
vercel.svg
window.svg
README.md
tsconfig.jsonยฉ 2026 Flowy ยท Free and open source
Built for Claude Code ยท Not affiliated with Anthropic
Provider with N format APIs โ file per format. A single Fal.ai client that does both image and video generation becomes providers/falai/{image.py,video.py,_client.py}. The HTTP plumbing (auth, retries, base URL) sits in _client.py; each format file owns its request/response shape.
# BEFORE โ providers/falai.py (640 lines, image+video request models tangled)
class FalAiAdapter:
async def generate_image(self, ...): ...
async def generate_video(self, ...): ...
# AFTER โ providers/falai/_client.py
class FalClient:
def __init__(self, *, api_key: str, http: httpx.AsyncClient): ...
async def request(self, path: str, payload: dict) -> dict: ...
# providers/falai/image.py
from ._client import FalClient
class FalImageAdapter:
def __init__(self, client: FalClient): self._c = client
async def generate(self, req: ImageRequest) -> GenerateResult | ProviderError: ...
Worker-handlers do NOT live in the router. routers/tasks.py stays HTTP-only (enqueue, list, cancel). Background processing goes to services/task_handlers/{image,video,audio}.py. The router becomes a thin entry point you can read in 30 seconds.
User-API โ Admin-API in the same service file. wallet_service.py (500 lines) becomes services/wallet/{user.py,admin.py,history.py,debt.py} with a shared services/wallet/_repo.py. User code can't accidentally import admin-only methods.
Soft cap 400 LOC, hard cap 600 LOC per file. At 400 lines you plan the split. At 600 lines you split now โ no exceptions. Enforced by scripts/check_loc.py in CI.
Refactor without breaking changes. __init__.py re-exports the old public names, so callers (and your AI assistant's stale memory of the codebase) don't break. Decomposition is invisible from the outside.
# services/wallet/__init__.py
from .user import WalletUserService
from .admin import WalletAdminService
# Backwards-compat: old code did `from app.services.wallet_service import WalletService`
WalletService = WalletUserService # alias keeps imports working during migration
__all__ = ["WalletUserService", "WalletAdminService", "WalletService"]
Per-integration observability context. contextvars.ContextVar for provider, user_id, request_id. JSON log formatter reads them. You filter logs in production with gcloud logs read 'jsonPayload.provider="fal"' instead of grepping unstructured strings.
Versioned adapters / feature flags. Keep the old and new implementation simultaneously, flip with one env var:
if settings.WALLET_REPO_BACKEND == "supabase":
return SupabaseWalletRepo(...)
return SQLAlchemyWalletRepo(db)
Rollback = env change, no redeploy, no rebuild.
Contract tests (pact-style). For each external provider, snapshot a real response shape and write a parser test against it. CI breaks the day the provider changes their API โ not three days later when a user reports a 500.
Single-Writer Principle. For any critical resource (wallet balance, quota, idempotent task state), exactly ONE function writes. One test covers it. One point for the security audit. All reads can be many; writes are funneled.
# services/wallet/_writer.py โ the ONE writer
async def apply_ledger_entry(repo: WalletRepoProtocol, entry: LedgerEntry) -> Wallet:
async with repo.lock(entry.user_id): # FOR UPDATE
wallet = await repo.get(entry.user_id)
new = wallet.apply(entry) # pure function
await repo.persist(new, entry)
return new
| โ |
| Typed cache-tag DSL (Next.js) | โ | โ | n/a | โ | n/a |
| LOC cap enforced in CI (lint script) | โ | โ | โ | โ | โ |
| Working reference apps included | โ (3) | โ | โ (1) | โ (1) | layout only |
Updated for 2024-25 (RSC, slog, PPR, Drizzle) | โ | partial | partial | partial | โ |