Skip to content

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.

  • main is stable-only: it receives only tested, working checkpoints from dev. Force-pushing to main is forbidden. Pushing to main directly without prior reviewed merge from dev is forbidden.
  • dev is the integration branch. Feature branches merge into dev; dev flows into main at release boundaries.
  • feat/<scope>, fix/<scope>, chore/<scope> for working branches. Delete them immediately after merge; only dev and main are long-lived.
  • 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.
  • Feature and fix PRs target dev. The only PR into main is the dev → main release 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.sh must 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 → main release path.

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.
  • DOUBLE PRECISION over NUMERIC for floats. NUMERIC maps to pgtype.Numeric in 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 pass nil to leave the column alone.
  • Regenerate with ./scripts/generate.sh from the repository root after every queries.sql or openapi.yaml change. The sqlc and oapi-codegen steps run in containers; the wrapper also uses host shell utilities to regenerate the shared PanicShim. Don’t hand-edit queries.sql.go or 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.
  • 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.sh runs them against a separate <db>_test database 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.
  • Runes outside components go in .svelte.ts modules. Svelte 5 compiles runes ($state, $derived, $effect) in .svelte components and in .svelte.js or .svelte.ts modules; in a plain .ts or .js file they aren’t compiled, so the code won’t behave as intended. Svelte accepts either module extension; .svelte.ts is 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 web container has the dependencies installed and mounts your web/ 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 with npm ci in web/ and run npm run check there.
  • Regen the API schema after openapi.yaml changes: npm run generate:api from web/. The schema is gitignored, so a stale copy only affects your local checks: CI generates it fresh from openapi.yaml and 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.sh copies en.json into the Go tree, so rerun it after changing English strings or CI’s drift check fails.
  • No console.log in committed code. Console statements are debugger noise.

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.

Run ./scripts/test.sh from the repository root and ensure green before any push. The script:

  • Needs the .env that ./scripts/bootstrap.sh creates, and the Docker Compose stack already running (docker compose up -d).
  • Runs the Go tests against a separate <db>_test database in that stack’s Postgres, reset at the start of each run. In a linked git worktree the database name gets a short hash of the checkout path, and that database is dropped when the run ends (AA_TEST_KEEP_DB=1 keeps it).
  • Leaves your dev database untouched.
  • Covers the Go suite only. --with-s3 also 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.

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_*.sql files 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 up working 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.sql in 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.

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_node table” → 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_id column names; rename to neutral external_user_id or 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.

  • 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 / WithEmissionFn as 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-verify on 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-recreate workarounds 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.

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.