Coding standards
The conventions below exist so contributors don’t have to re-derive them each PR, and so the codebase stays readable as it grows.
Branching
Section titled “Branching”mainis stable-only: it receives only tested, working checkpoints fromdev. Force-pushing tomainis forbidden. Pushing tomaindirectly without prior reviewed merge fromdevis forbidden.devis the integration branch. Feature branches merge intodev;devflows intomainat release boundaries.feat/<scope>,fix/<scope>,chore/<scope>for working branches. Delete them immediately after merge; onlydevandmainare long-lived.
Commits
Section titled “Commits”- Format:
<area>: <imperative summary>. For example:assets: handle 0-byte uploads,web: fix viewer crash on EXR with no exif. - One logical change per commit. If a refactor and a fix landed together, split them.
- No Claude / AI co-authorship lines. The change is the contributor’s.
- Reference the issue/PR number in the body, not the subject.
- HEREDOC commit messages when multi-line: preserves formatting through shells.
Pull requests
Section titled “Pull requests”- Feature and fix PRs target
dev. The only PR intomainis thedev → mainrelease PR, opened as part of the release process (RELEASING.md). - The PR description explains why, not what. The diff already shows what.
- Reference any relevant ADR (
See ADR 0036) and any related issue. ./scripts/test.shmust be green locally before the PR opens. CI re-runs it; CI red is a blocker.- Squash-merge for feature branches; merge-commit for the
dev → mainrelease path.
Go style
Section titled “Go style”The non-obvious rules. CI enforces formatting with gofmt (the job fails if gofmt -l lists any file under app/) and runs no other Go linter.
- Errors return out. No silent swallows, no
_ = err. If an error is genuinely safe to ignore, write a comment saying why. - Trust internal code, validate at boundaries. Don’t re-validate inputs your own callers already validated. Do validate at HTTP entry points (handler functions) and at external-system entry points (storage backends, connectors).
- No defensive nil checks on guaranteed-non-nil values. If the type system or the framework guarantees a value is non-nil, don’t add a check that “can’t fire”; it makes the reader doubt the guarantee.
- Comments explain why, not what. Code that reads as code doesn’t need narration; code that has a hidden constraint, a workaround, a non-obvious invariant, does.
- Keep doc comments short. A line or two is usually enough for an exported symbol; the godoc reader is an engineer who already knows Go. Write more when callers need it: a non-obvious contract, a safety constraint, concurrency behaviour or an invariant, such as the advisory-lock behaviour documented on
db.Migrate. - Per-domain layout. Each domain owns its
internal/<domain>/directory. Cross-domain calls go through the handler layer or through small dependency-injected interfaces, never via grabbing another domain’s repository directly.
sqlc + pgx
Section titled “sqlc + pgx”- DOUBLE PRECISION over NUMERIC for floats. NUMERIC maps to
pgtype.Numericin pgx, which is a pain to work with from Go. - COALESCE PATCH pattern for partial updates:
UPDATE foo SET col = COALESCE(sqlc.narg('col'), col)and passnilto leave the column alone. - Regenerate with
./scripts/generate.shfrom the repository root after everyqueries.sqloropenapi.yamlchange. The sqlc and oapi-codegen steps run in containers; the wrapper also uses host shell utilities to regenerate the shared PanicShim. Don’t hand-editqueries.sql.goor any other generated file. - CI checks for stale generated code. The codegen drift job regenerates the Go code and fails if the result differs from what you committed. If it fails, rerun
./scripts/generate.sh, review the diff, and commit it.
Testing
Section titled “Testing”- Integration tests hit a real Postgres. No DB mocks. The mock/prod divergence has bitten us before; the test script (
./scripts/test.sh) runs every test against a disposable database in the Docker Compose stack’s Postgres. - The tests never touch your dev database.
./scripts/test.shruns them against a separate<db>_testdatabase that it resets at the start of each run, so your admin account and data are unaffected. - OpenAPI strict-server test shims embed the shared
strictservershim.PanicShim(see Things we don’t do below), so a new operation needs no per-package stub. - No mocks for “is this even called” assertions. If you want to assert a function was called, refactor so the side effect is observable (a row in a table, a job in a queue), then test the side effect.
Frontend style (Svelte 5)
Section titled “Frontend style (Svelte 5)”- Runes outside components go in
.svelte.tsmodules. Svelte 5 compiles runes ($state,$derived,$effect) in.sveltecomponents and in.svelte.jsor.svelte.tsmodules; in a plain.tsor.jsfile they aren’t compiled, so the code won’t behave as intended. Svelte accepts either module extension;.svelte.tsis this project’s convention, matching its TypeScript codebase. web/src/lib/components/is the shared component pool. Per-route components live next to the route they belong to.- Type-check before push. With the Compose stack running, the
webcontainer has the dependencies installed and mounts yourweb/directory at/app:docker compose exec -T web sh -c 'cd /app && npm run check'. To run it on the host instead, install the locked dependencies withnpm ciinweb/and runnpm run checkthere. - Regen the API schema after
openapi.yamlchanges:npm run generate:apifromweb/. The schema is gitignored, so a stale copy only affects your local checks: CI generates it fresh fromopenapi.yamland then runs svelte-check, vitest and a vite build. The Go side of the API is generated separately, by./scripts/generate.sh. - i18n strings live in
web/src/lib/i18n/<locale>.json. New surfaces add the English key; locale stubs follow../scripts/generate.shcopiesen.jsoninto the Go tree, so rerun it after changing English strings or CI’s drift check fails. - No
console.login committed code. Console statements are debugger noise.
Comments
Section titled “Comments”The default is no comment. Add one only when the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug, behaviour that would surprise a reader.
What not to write:
- What the code does: well-named identifiers already do that.
- References to current task / fix / callers (“used by X”, “added for the Y flow”, “handles the case from issue #123”): belongs in the PR description and rots in the codebase.
- Multi-paragraph commentary: if a thing needs three paragraphs to explain, it probably needs an ADR.
Test locally before pushing
Section titled “Test locally before pushing”Run ./scripts/test.sh from the repository root and ensure green before any push. The script:
- Needs the
.envthat./scripts/bootstrap.shcreates, and the Docker Compose stack already running (docker compose up -d). - Runs the Go tests against a separate
<db>_testdatabase in that stack’s Postgres, reset at the start of each run. In a linkedgit worktreethe database name gets a short hash of the checkout path, and that database is dropped when the run ends (AA_TEST_KEEP_DB=1keeps it). - Leaves your dev database untouched.
- Covers the Go suite only.
--with-s3also starts MinIO and runs the S3 storage tests.
The frontend checks are separate: npm run check, npm test (vitest) and npm run build, run from web/ or in the web container.
CI covers more than the local script. The integration job runs ./scripts/test.sh against a freshly built stack; other jobs check gofmt, regenerate code and fail on drift, and run the frontend type-check, unit tests and build. Pull requests that change only documentation skip these jobs. Running the matching steps locally first usually saves a round trip.
Database migrations
Section titled “Database migrations”Migrations live in app/internal/db/migrations/ as goose-managed NNNNN_*.sql files. app/schema.sql is a schema-only dump of a database built by running the migrations; sqlc reads that file, not the migrations, when it generates code.
- Through the beta (before v1.0.0): new migrations are appended as normal
NNNNN_*.sqlfiles on top of the v0.1.0 baseline, per ADR 0046. They are folded into a fresh baseline once more at the v1.0.0 tag. Existing installs upgrade by running the appended migrations, which happens automatically at boot. - Post-v1.0: forward-only forever. No more squashes. Real operators with real data depend on
goose upworking from any prior shipped version. - CHECK constraints mirror typed Go constants per ADR 0042. When the migration enforces a closed set at the DB layer, the same set lives as typed constants in the owning package; both halves land in the same PR.
- Regenerate
app/schema.sqlin the same commit that adds a migration (the file’s header gives the steps); don’t edit it by hand. CI doesn’t compare it with the migrations, so reviewers check that the two agree.
No product comparisons in source
Section titled “No product comparisons in source”Source code (Go, Svelte, SQL comments, OpenAPI) should not lean on direct named comparisons to competitor or inspiration products. Named comparisons age badly when the product changes and confuse readers who don’t know what “AFFiNE-shaped” means.
What this looks like in practice:
- Don’t write “Mastodon-shaped activity dispatch” → do write “ArchivePub activity dispatch”.
- Don’t write “the prior generation’s
resource_nodetable” → do state the design on its own terms. - Don’t write “AFFiNE’s element-typed model” → do write “an element-typed model”.
- Don’t write “Frame.io-style timestamped comments” → do write “asset-anchored timestamped comments”.
- Don’t write “PeerTube has to move every byte” → do drop the comparison; just describe what we do.
- Don’t keep
rs_user_id/rs_resource_idcolumn names; rename to neutralexternal_user_idor drop if the column is now unused.
Exemptions. Two places retain named upstream / competitor references intentionally:
- ADRs and
docs/research/: decision documents and historical record. - License attribution surfaces: third-party dependency notices required by their licenses (acknowledgment is not comparison). The former ResourceSpace fork-base attribution was removed once the RS-derived code was deleted and the project relicensed to AGPL-3.0 (ADR 0001 → superseded by ADR 0040).
Everything else in source stays neutral.
Things we don’t do
Section titled “Things we don’t do”- Backwards-compatibility shims for code that no real caller depends on. If you rename a function and nothing real consumed the old name, delete the old name. Don’t keep “for compat” zombies.
- Legacy fallback paths in wired handlers. Per ADR 0044, every handler that emits federation activities uses
WithEmission/WithEmissionFnas its single code path. The “if the activities writer isn’t wired, fall back to the domain write” pattern is forbidden: in production it never fires; in tests it hides the federation-delivery correctness invariant. Tests wire the activities writer in setup; there is no second path. - Test stubs that proliferate per-package. OpenAPI strict-server tests use the shared
internal/openapi/strictservershim.PanicShim. Embed it; override only the methods the test actually exercises. Do not create a new per-package shim file with N panic methods every time an OpenAPI operation lands. - Speculative abstractions. Three similar lines beats a premature abstraction for two. The third caller motivates the helper; the second doesn’t.
--no-verifyon commits. The repository doesn’t ship any Git hooks, but if you run your own, don’t bypass them: if a hook fails, fix the underlying problem.--force-recreateworkarounds for stale containers in production paths. It’s fine for local dev when Go binary changes don’t pick up; production has different lifecycle rules.
When in doubt
Section titled “When in doubt”Read recently-merged PRs to see how the current contributor base writes code. Reference the conventions ADR (0035) for documentation patterns. If the answer’s still unclear, ask in the PR or in an issue; the project lead would rather answer once than untangle ten divergent patterns later.