Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

docs: record the code writing style in one guide and in CLAUDE.md

spacesdrivec7cbd0cc0983
diff --git a/claude.md b/claude.md
index 6e51c32..82ba4e3 100644
--- a/claude.md
+++ b/claude.md
@@ -61,10 +61,11 @@ Before implementing any feature or fix, read these documents in this exact order
3. `docs/WRITING_STANDARDS.md` - typography, icons, writing style, UI copy rules
4. `docs/architecture/OVERVIEW.md` - system topology and request flow
5. `docs/guidelines/TYPESCRIPT.md` - code standards and typing rules (always apply)
-6. Relevant architecture doc - backend, frontend, database, or cloudflare
-7. Relevant feature guide - if one exists in `docs/features/`
-8. Relevant engineering guideline - if the task touches a specific layer
-9. `ROADMAP.md` - if the task is a planned item, link its issue there
+6. `docs/guidelines/CODE_STYLE.md` - how code reads here: layer shapes, comments, naming, messages, tests (always apply; its checklist runs before every commit)
+7. Relevant architecture doc - backend, frontend, database, or cloudflare
+8. Relevant feature guide - if one exists in `docs/features/`
+9. Relevant engineering guideline - if the task touches a specific layer
+10. `ROADMAP.md` - if the task is a planned item, link its issue there
For MCP usage, read `docs/mcp/OVERVIEW.md` before using any MCP server.
@@ -107,6 +108,7 @@ docs/
ANALYTICS.md YouTube and Instagram analytics fetch and compute
SCHEDULING.md Scheduled post lifecycle, dual-scheduler design
guidelines/
+ CODE_STYLE.md How code reads: the shapes to copy per layer, comments, naming, messages, tests, pre-commit checklist
TYPESCRIPT.md Compiler settings, typing rules, where types live, code style, comments policy
REACT.md Component rules, hooks, JSX conventions
HONO.md Route handlers, middleware, context usage
@@ -183,6 +185,21 @@ Never implement the quickest solution when a significantly better architecture e
---
+## Code Style
+
+Read `docs/guidelines/CODE_STYLE.md` before writing code and run its checklist before every commit. The non-negotiable rules:
+
+- Match the nearest existing file of the same kind before inventing a shape: open a sibling and copy its imports, exports, naming and comment density
+- One job per file and per layer: route tables map, controllers translate HTTP, services decide, repositories query, components render, `lib/` helpers compute; services are `createXService(deps)` factories with an `XService` and an `XDeps` interface
+- Comments explain why in one lowercase line above the code; never restate the code, reference a task, or write JSDoc or multi-line blocks; a constant with a number in it gets its reason
+- Backend failures are typed errors from `lib/errors.ts` with a message a person can act on; frontend failures are toasts that start with what failed (`Couldn't save the password.`) and add the reason; success toasts confirm in past tense (`Password saved`)
+- Formatting follows the file: 4 spaces in `backend/`, 2 elsewhere, single quotes, semicolons, trailing commas
+- Pure logic goes in a plain `.ts` helper (`lib/`) so Node can test it; markup used twice becomes a component; copy that changes by mode lives in a typed table
+- Tests use `node:test` with sentence names that describe behaviour, live in `tests/` mirroring the source path, and use the smallest typed fake
+- When the code and `CODE_STYLE.md` disagree, update the guide in the same change
+
+---
+
## MCP Usage Rules
### Context7 - Library and API documentation
@@ -364,6 +381,7 @@ When anything changes, update every relevant docs file from the table below. The
| Release tagged | `CHANGELOG.md` (convert Unreleased to version number with date) |
| Any planned feature added or changed | `ROADMAP.md` |
| Writing or design rule changed | `docs/WRITING_STANDARDS.md`, this file (Writing and Design Standards section) |
+| Code style or a layer's shape changed (a new pattern to copy, a naming, comment or message rule) | `docs/guidelines/CODE_STYLE.md`, the guideline it details (`TYPESCRIPT.md`, `REACT.md`, `HONO.md`, `NAMING.md`), this file (Code Style section) |
| MCP usage rule changed | `docs/mcp/OVERVIEW.md`, this file (MCP Usage Rules section) |
| Engineering standard changed | `docs/philosophy/ARCHITECTURE.md`, this file (Engineering Standards section) |
| Security model changed | `docs/philosophy/SECURITY.md`, `docs/architecture/database/SECURITY.md` |
diff --git a/docs/features/NEW_API_ENDPOINT.md b/docs/features/NEW_API_ENDPOINT.md
index ef47081..dcf8cef 100644
--- a/docs/features/NEW_API_ENDPOINT.md
+++ b/docs/features/NEW_API_ENDPOINT.md
@@ -1,5 +1,7 @@
# Guide: Adding a New API Endpoint
+Write the code in the style described in `docs/guidelines/CODE_STYLE.md` and run its checklist before each commit.
+
Follow this guide when adding a route to the Hono backend. Read `docs/architecture/backend/REQUEST_PIPELINE.md` for the layers, then the tracked content feature as a reference implementation: `backend/validators/trackedContentValidators.ts`, `repositories/trackedPostRepository.ts`, `services/trackedContentService.ts`, `controllers/trackedContentController.ts` and `routes/trackedContentRoutes.ts`. `docs/guidelines/TYPESCRIPT.md` has the typing rules.
## Files to Create or Modify
diff --git a/docs/features/NEW_REACT_PAGE.md b/docs/features/NEW_REACT_PAGE.md
index 0844f90..de5326c 100644
--- a/docs/features/NEW_REACT_PAGE.md
+++ b/docs/features/NEW_REACT_PAGE.md
@@ -1,5 +1,7 @@
# Guide: Adding a New React Page
+Write the code in the style described in `docs/guidelines/CODE_STYLE.md` and run its checklist before each commit.
+
Read `frontend/src/features/analytics/channel/ChannelAnalytics.tsx` as a reference implementation before starting.
## Files to Create or Modify
diff --git a/docs/guidelines/CODE_STYLE.md b/docs/guidelines/CODE_STYLE.md
new file mode 100644
index 0000000..aed7bff
--- /dev/null
+++ b/docs/guidelines/CODE_STYLE.md
@@ -0,0 +1,151 @@
+# Code Style
+
+How code in this repository reads. Every change follows it, so a file written today looks like the files around it. The detailed rules live in the guides linked from each section; this page is the one to read first and the checklist to run last.
+
+When this page and the code disagree, the code in the newest reviewed files wins: fix this page in the same change.
+
+## The Short Version
+
+1. **Match the nearest example.** Before writing a file, open its closest sibling (the same layer, the same kind of component) and copy its shape: imports, exports, naming, comment density, error handling.
+2. **One job per file and per layer.** A route table maps, a controller translates HTTP, a service decides, a repository queries, a component renders, a `lib/` helper computes.
+3. **Comments say why, in one lowercase line.** Never what the code does.
+4. **Failures are typed and written for people.** Throw a typed error with a message that says what happened and what to do; never "Something went wrong".
+5. **Strict TypeScript with erasable syntax.** No `any`, no enums, `import type` for types, `.ts` on relative imports.
+6. **Design tokens and shared components only** in the UI. No hex or palette colours, no one-off cards.
+7. **Tests describe behaviour in a sentence** and live in `tests/`, mirroring the source path.
+8. **No em dashes, en dashes, emoji or exclamation marks** in code, copy, docs or commits.
+
+## Formatting
+
+Prettier settings in `.prettierrc.json` and `.editorconfig` describe the layout; match the file you edit rather than reformatting it.
+
+| | Backend, scripts | Frontend, docs TSX |
+|---|---|---|
+| Indentation | 4 spaces | 2 spaces |
+| Quotes | single | single (JSX attributes use double) |
+| Semicolons, trailing commas | yes | yes |
+| Line length | up to about 120 columns; long JSX props go one per line | same |
+
+## Files and Imports
+
+- One exported unit per file: a component, a hook, a service factory, a repository factory, a route table. Small helpers used only in that file stay unexported beside it.
+- Names follow `docs/guidelines/NAMING.md` and the table in `docs/guidelines/TYPESCRIPT.md` (`accountService.ts`, `PasswordSection.tsx`, `useChannelVideos.ts`, `use-mobile.ts`).
+- Import order: packages first, then project modules. Backend files put every `import type` line after the value imports, as below; frontend files may keep a type import next to the value import from the same module.
+
+```ts
+import { NotConfiguredError, RateLimitedError, UpstreamError } from '../lib/errors.ts';
+import { composeAuthEmails } from './email/authEmails.ts';
+import { sendEmail } from './email/resendApi.ts';
+import type { AuthEmail } from './email/authEmails.ts';
+import type { EmailQuotaRepository } from '../repositories/emailQuotaRepository.ts';
+```
+
+- Backend and test imports are relative and end in `.ts`. Frontend imports use `@/` for `src/` (no extension) and `./` for siblings; files that Node tests import use relative `.ts` paths only.
+- Pure logic that can be tested goes in a plain `.ts` file with no JSX (`frontend/src/lib/passwords.ts`, `backend/services/email/authEmails.ts`), so Node can run its test directly.
+
+## Comments
+
+Write a comment only when the reason is not visible in the code: a constraint from outside (a provider's limit, a browser quirk), an invariant, or behaviour that would surprise a reader. One line, lowercase start, no full stop needed, placed above the line it explains.
+
+```ts
+// Supabase gives the whole hook call 5 seconds, so a slow send is abandoned before Supabase gives up on the Worker
+const SEND_TIMEOUT_MS = 4000;
+
+// a refused send increments nothing, so one address asking again and again cannot use up the day's allowance
+```
+
+Do not write comments that restate the code (`// send the email`), name the task or issue, describe callers, or document parameters (types do that). No JSDoc and no multi-line blocks. A module-level constant with a number in it nearly always needs its one-line reason.
+
+## Naming Inside Functions
+
+- Event handlers in components: `handleSubmit`, `handleResend`, `handleSave`. Mode-specific steps they call: `submitLogin`, `submitReset`.
+- Booleans read as questions or states: `loading`, `saving`, `isLogin`, `emailLimitReached`, `configured`.
+- Lookups keyed by a union are typed records, not `switch` chains, when each case is a value: `const FAILURE_PREFIX: Record<LoginMode, string> = { ... }`.
+- Functions that return a reason or `null` say so: `newPasswordProblem(password, confirmation): string | null`.
+
+## Backend Patterns
+
+The layers are in `docs/architecture/backend/REQUEST_PIPELINE.md`; the recipes are in `docs/features/NEW_API_ENDPOINT.md` and `docs/guidelines/HONO.md`. The shapes to copy:
+
+| Layer | Shape | Example |
+|---|---|---|
+| Route table | `const router = new Hono<AppEnv>(); router.post(path, ...middleware, ...controller)` | `routes/authHookRoutes.ts` |
+| Controller | `controller.createHandlers(validator, async c => { one service call; return c.json(... satisfies Type) })` | `controllers/settingsController.ts` |
+| Validator | `parseX(fields: Fields): XRequest` with the helpers in `validators/fields.ts` | `validators/authHookValidators.ts` |
+| Service | `interface XService`, `interface XDeps`, `export function createXService(deps): XService` returning an object literal | `services/authEmailService.ts` |
+| Repository | `interface XRepository`, `createXRepository(client)`, one method per query, `...ForUser` for user-scoped methods | `repositories/emailQuotaRepository.ts` |
+| Platform module | plain functions taking config and an optional trailing `signal`, throwing `UpstreamError` and `UpstreamTimeoutError` | `services/email/resendApi.ts` |
+
+- Services never import `hono`. They receive repositories, `AppConfig` and the `RequestContext`, and log through `context.log` with a short lowercase message and fields: `context.log.warn('auth email skipped', { action, reason: 'limit reached' })`.
+- Every platform `fetch` gets `context.signal` (plus its own timeout when the caller has a budget).
+- Redis code catches every failure and falls back; nothing else swallows errors.
+- No new runtime dependency in the Worker without approval: call HTTP APIs with `fetch` (Resend is called this way, not through its SDK).
+
+## Errors and Messages
+
+Messages are UI copy. Follow `docs/WRITING_STANDARDS.md` (UI Copy) and `docs/guidelines/ERROR_HANDLING.md`.
+
+- Backend: throw the typed error whose code matches the failure (`ValidationError`, `NotFoundError`, `RateLimitedError`, `NotConfiguredError`, `UpstreamError`), with a message a person can act on: `'This address has received the most codes allowed today. Use the latest code you received, or try again tomorrow.'` A missing secret names the secret: `'Email sending is not set up: the RESEND_API_KEY and EMAIL_FROM Worker secrets are required'`.
+- Frontend failures: a toast that starts with what failed and adds the reason: `` `Couldn't save the password. ${reason}` ``. Map provider error codes to plain sentences in a `lib/` helper (`lib/authErrors.ts`) and keep the provider's own message when it already says what to do.
+- Frontend success: confirm what happened in past tense, sentence case, no exclamation mark: `'Password saved'`, `'New code sent'`.
+- Never reveal more than the user should know: the password reset message reads `If an account uses <email>, a code is on its way.` because the server does not say whether the account exists.
+
+## Frontend Patterns
+
+Rules in `docs/guidelines/REACT.md`, `docs/guidelines/TAILWIND.md`, `docs/guidelines/SHADCN.md` and `docs/architecture/frontend/DESIGN_SYSTEM.md`. The shapes to copy:
+
+```tsx
+export interface LoginEmailFormProps {
+ copy: LoginCopy;
+ email: string;
+ onEmailChange: (value: string) => void;
+ loading: boolean;
+ onSubmit: (e: FormEvent<HTMLFormElement>) => void;
+}
+
+export default function LoginEmailForm({ copy, email, onEmailChange, loading, onSubmit }: LoginEmailFormProps) {
+ return (
+ <form onSubmit={onSubmit} className="flex flex-col gap-4">
+ <FieldRow label="Email" htmlFor="email">
+ <Input id="email" type="email" className="h-(--control-h-lg)" value={email} onChange={e => onEmailChange(e.target.value)} required />
+ </FieldRow>
+ <Button type="submit" size="lg" className="mt-2 w-full" disabled={loading}>
+ {loading && <Spinner className="size-4" />}
+ {loading ? copy.busy : copy.submit}
+ </Button>
+ </form>
+ );
+}
+```
+
+- Presentational components get values and callbacks as props; the page or section owns state and calls `useAuth()`, `useAppContext()` or `api`.
+- Forms: `FieldRow` for label and hint, shadcn `Input` and `Button`, `Spinner` in the button while busy, the action named for what it does (`Save password`, `Send code`).
+- Sections of a settings-style page use `SettingsSection` and `SurfaceBox`; pages use `PageHeader`; toasts go through `showToast` inside the app shell (the login page uses `toast` from `sonner` directly).
+- Icons are Lucide with `data-icon="inline-start"` or `inline-end` in buttons.
+- When markup repeats in two places, extract it (`PasswordInput.tsx` for the password field with its show button) rather than copying it.
+- Copy that changes by mode lives in a typed table (`loginCopy.ts`, `LOGIN_COPY: Record<LoginMode, LoginCopy>`).
+
+## Tests
+
+Rules in `docs/workflows/TESTING.md`.
+
+- `node:test` with `assert from 'node:assert/strict'`; no other framework.
+- Test names are sentences about behaviour, not function names: `'past the daily cap nothing is sent and the error tells the person to use Google'`.
+- One behaviour per test, with the smallest fake that exercises it, cast once to the interface it stands in for. Shared fakes and fixtures live in `backend/tests/fixtures/`.
+- Every new pure helper, validator, service and route gets a test in the mirrored `tests/` path.
+
+## Docs and Commits
+
+- Docs follow `docs/WRITING_STANDARDS.md`: short declarative sentences, tables for structured facts, code blocks for commands, no marketing words.
+- Commits follow `docs/workflows/GIT.md`: `type(scope): imperative summary`, a body that says why, and `Refs #N` or `Closes #N`. No AI attribution lines.
+- Every change is tracked by an issue (`docs/workflows/ISSUES.md`) and lands on `main` through a pull request that passed CI.
+
+## Before Every Commit
+
+- [ ] The new file looks like its nearest sibling: imports, exports, naming, comments
+- [ ] Comments only explain why; no restated code, no task references
+- [ ] Errors are typed (backend) or toasts with a reason (frontend), and every message says what to do
+- [ ] No `any`, enums, `@ts-ignore`, hex colours, emoji, em dashes or exclamation marks
+- [ ] Tests added in the mirrored `tests/` path, with behaviour sentences as names
+- [ ] `npm run typecheck`, `npm run lint`, `npm test` and `npm run build` pass
+- [ ] Docs in the Documentation Maintenance Policy updated in the same change
diff --git a/docs/guidelines/HONO.md b/docs/guidelines/HONO.md
index 8ca34fd..1103748 100644
--- a/docs/guidelines/HONO.md
+++ b/docs/guidelines/HONO.md
@@ -1,5 +1,7 @@
# Hono Guidelines
+Start with `docs/guidelines/CODE_STYLE.md`, which shows how code reads across the repository and ends with the checklist to run before every commit; this page has the detailed rules for its area.
+
The backend is split into layers: middleware, route tables, controllers, services and repositories. `docs/architecture/backend/REQUEST_PIPELINE.md` describes each layer and the order a request passes through them. These rules cover the Hono-facing parts: route tables, controllers and middleware.
## Controller Structure
diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.md
index 843095c..2d404e1 100644
--- a/docs/guidelines/NAMING.md
+++ b/docs/guidelines/NAMING.md
@@ -1,5 +1,7 @@
# Naming Conventions
+Start with `docs/guidelines/CODE_STYLE.md`, which shows how code reads across the repository and ends with the checklist to run before every commit; this page has the detailed rules for its area.
+
## Files
| Location | Convention | Examples |
diff --git a/docs/guidelines/REACT.md b/docs/guidelines/REACT.md
index f9cf7a5..4dbfb04 100644
--- a/docs/guidelines/REACT.md
+++ b/docs/guidelines/REACT.md
@@ -1,5 +1,7 @@
# React Standards
+Start with `docs/guidelines/CODE_STYLE.md`, which shows how code reads across the repository and ends with the checklist to run before every commit; this page has the detailed rules for its area.
+
## Component Rules
**Function components only.** No class components.
diff --git a/docs/guidelines/TYPESCRIPT.md b/docs/guidelines/TYPESCRIPT.md
index a9594a6..bdd420f 100644
--- a/docs/guidelines/TYPESCRIPT.md
+++ b/docs/guidelines/TYPESCRIPT.md
@@ -1,5 +1,7 @@
# TypeScript Standards
+Start with `docs/guidelines/CODE_STYLE.md`, which shows how code reads across the repository and ends with the checklist to run before every commit; this page has the detailed rules for its area.
+
The whole project is TypeScript in `strict` mode: the Worker (`backend/`), the React app (`frontend/`), the shared API types (`shared/types/`), the scheduled publisher (`scripts/`) and every test. These rules apply everywhere.
Nothing compiles TypeScript to JavaScript ahead of time. Wrangler and Vite strip the types while bundling, and Node strips them when it runs the tests and the publisher script. Type checking is a separate step, `npm run typecheck`, which CI runs before every deploy.
diff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.md
index c93837a..e34e760 100644
--- a/docs/workflows/FEATURE_DEVELOPMENT.md
+++ b/docs/workflows/FEATURE_DEVELOPMENT.md
@@ -1,5 +1,7 @@
# Feature Development Workflow
+Write the code in the style described in `docs/guidelines/CODE_STYLE.md` and run its checklist before each commit.
+
Every feature - large or small - follows this sequence. Steps that don't apply to a specific feature can be skipped, but must be consciously skipped (not forgotten).
---