elixir-phoenix-conventions
Team conventions for our Elixir/Phoenix apps. Use when writing or editing any `.ex` or `.exs` file, a `docs/` page a change ships with, running `mix precommit`, or editing guardrail config (`.credo.exs`, `.sobelow-conf`, `.sobelow-skips`, `.dialyzer_ignore.exs`, CI workflows).
- License 许可
- MIT
- 最近更新
- 2026-11-11
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- elixir-phoenix-conventions
- description
- Team conventions for our Elixir/Phoenix apps. Use when writing or editing any `.ex` or `.exs` file, a `docs/` page a change ships with, running `mix precommit`, or editing guardrail config (`.credo.exs`, `.sobelow-conf`, `.sobelow-skips`, `.dialyzer_ignore.exs`, CI workflows).
02 资源文件 5
- 参考文档concurrency.md7.8 KB
- 参考文档docs.md8.0 KB
- 参考文档graphql.md4.2 KB
- 参考文档reference.md6.0 KB
- 参考文档testing.md5.4 KB
03 SKILL.md 正文
Elixir/Phoenix Conventions
Code that breaks these rules still compiles and passes its tests, so only this list catches it. Hold every line you write or edit to the rules below; where they are silent, do the job the way the app already does it (#64).
MyApp/MyAppWebstand for the app's namespace.- Rules are cited by number (
#18), and the numbers are stable. AnEP-…id names the matching language-agnostic rule in theengineering-principlesskill of theengineering-reviewplugin, where that plugin is installed. - Broken most often, so check them first: #2, #13, #18, #23, #31, #59.
Read first, when it applies
Each file sits next to this one and holds the detail and worked code for one kind of work.
| Before you | Read |
|---|---|
| add a feature that has no sibling module to copy | reference.md: one feature wired through every layer |
| write or change a test | testing.md |
| write an operation with more than one write, a write whose value was read earlier, a lock, a transaction or a Service | concurrency.md |
| write a resolver, a mutation, a GraphQL type or a GraphQL test | graphql.md |
| change what the app does or how it is wired | docs.md: the page and the map the change ships with |
Before you say done
- Every function you touched is re-read, and what the edit made pointless is deleted (#56).
docs/describes the app after the change, or the PR description names the page you checked (#59).- Every character of the diff is English (Rule 0).
mix precommitexits 0 on a run started after your last edit (#60). A red run is reported with its output.
Rule 0 — everything is in English
Every character we author is English (EP-0): module, function and variable names, @moduledoc and @doc text, comments, describe/test names, error messages and typed-error fields, log and telemetry messages, migration and index names, seed labels, TODOs, commit messages and PR descriptions. This holds whoever wrote the surrounding code and however short the snippet.
The only other language allowed is translated copy, which is data: message catalogues (Gettext .po files or equivalent) whose source locale is English. Their keys, and every comment around them, are English.
Code you touch that is in another language is renamed and its comments rewritten in English, in the same change (#56).
The rules
A. Context architecture & layering
- Four tiers: facade (
MyApp.Accounts) → sub-module (Accounts.Users) →Query(accounts/users/query.ex) → schema (Accounts.User). - The facade is the context's public API and nothing else: it
defdelegates to sub-modules, and every new public context function gets itsdefdelegate(defdelegate create_referral(attrs, opts \\ []), to: Referrals). Callers outside the context (resolvers, workers, other contexts) call the facade,Accounts.create_referral(attrs, opts); a sub-module is private to its context. Substantial cross-context or multi-step orchestration lives in a Service (#4), not inline in the facade. - Sub-modules hold CRUD and business logic and carry a domain name (
Users,Confirmations); the nameImplbelongs to adapters only (#5). - Context and sub-module functions stay thin: take a struct and an attrs map, apply the schema changeset, call
Repo.insert/update/delete. Anything more (a multi-stepEcto.Multi, cross-context orchestration, computation, an external side effect, a branching workflow) is a Service:MyApp.Services.*when it crosses contexts,MyApp.{Context}.Services.*when it stays in one. A Service has exactly one public function,run/…, takingopts \\ [], with as many heads as it needs; a second job is a Service of its own. Its@moduledocstates its single responsibility, it is built from pattern-matched heads and extracteddefps, and it returns{:ok, _}/{:error, _}. Callers invokeService.run(...)directly: a Service is neverdefdelegated or wrapped by a facade or another module. - External services and adapters are a behaviour +
Impl+StubImpl/Mock, swapped via config (Geocoding,PaymentProvider,StripeClient). The behaviour's callbacks return the app's structs: a webhook comes back as{:ok, %Connection{}}, not as the provider's decoded map. Only the implementation names the provider; controllers, plugs, routes, assigns and log lines say what they do (MediaServerController,/webhooks/media-server). The implementation reads its settings from its own key (config :my_app, MyApp.Live.Adapters.LiveKit, …), andconfig/runtime.exsrequires each one, counting a blank value as missing, wherever that implementation is the configured one (EP-D6, EP-E6). - Schemas
use MyApp.Schema, :schema(binary_id UUID primary keys), in place of a bareuse Ecto.Schema. - Changesets live in the schema module (
changeset/2, or intent-named likearchive_changeset/2); sub-modules call them. A changeset declares every constraint of its table that the write can hit (unique_constraint,foreign_key_constraint,check_constraint), so the write returns{:error, changeset}for the caller to map to a typed error (#38) in place of raisingEcto.ConstraintError(EP-H3). @derive {JSON.Encoder, except: [...]}on schemas controls which fields are exposed.- Soft-delete, and every other lifecycle stamp, is a nullable datetime (
archived_at/deleted_at/flagged_at/…), not a database delete. A lifecycle mutator takes attrs,fn(%Schema{} = struct, attrs \\ %{}, opts \\ []), so the same function stamps and resets the field: pass%{field: nil}to clear it. The changesetput_changes the timestamp, thencast(attrs, [field])so attrs can override, guarded byvalidate_no_override/2. That guard is built onvalidate_change, which Ecto skips when the new value is nil, so setting a field that is already set fails and resetting it to nil succeeds. - Context directory layout:
context.ex,supervisor.ex,events.ex,event_handler/,services/(Service objects), schema files, and one directory per sub-module, each with itsquery.ex.
B. Ecto / Query / Repo
-
Query modules
use MyApp.Query, which givesfiltered_by/2,ordered_by/2,with_id(s)/2,paginate/4andcount/1. -
Custom query functions are chainable and return queryables, with guards and a fallthrough clause (
def filtered_by(q, _), do: q). Build each one by piping the queryable through Ecto's macro forms:where(q, [m], …),order_by/3,join(q, :inner, [m], t in assoc(m, :thread), as: :thread),select/3,limit/2. Every function is then a single composable pipe step. A join usesassoc(m, :name)whenever the schema declares the association, which reuses its foreign key and conditions; an expliciton:is for a join with no association (computed or cross-schema).from(...)is reserved for the three things the pipe forms cannot express:- naming the root binding:
from(t in Thing, as: :things)forbase/0, orfrom(q, as: :things)inside ahas_named_binding?/maybe_alias_*guard; - a standalone subquery or
exists/not existsexpression (subquery(...),parent_as(...)); - an
update:or fragment atomic write.
A table name inside a
fragmentstring means the builder was skipped: write the subquery withexists/subqueryandparent_asover the schema, and keep infragmentonly what the builder cannot express, such as a row comparison(?, ?) > (?, ?)or a cast (EP-K11). - naming the root binding:
-
import Ecto.Query, and with itwhere/from/order_by/join/preload/lock, appears only in*/query.exmodules. Context and sub-modules pipe a schema throughQuery.*functions, then callRepo.*. -
Read chain:
Schema |> Query.filtered_by(args) |> Query.ordered_by(o) |> Query.paginate(...)/Repo.one. -
Read by id through a context getter (
get_*/get_*!). Callers outside the context use the getter and neverRepo.*. Inside the getter,Repo.get/Repo.get_byis fine; useSchema |> Query.with_id(id) |> Repo.onewhen you need the Query layer's standard filters, such as soft-deletes. Everyget_*, private ones included, returns{:ok, struct}or{:error, %Errors.NotFoundError{}}. A unique-constraint race recovers through the getter and returns its result as is, never{:ok, get_*(...)}around a lookup that may returnnil(EP-A2, EP-C2). -
Preloads are opt-in through the
:preloadsoption: a list of association atoms, default[], so nothing is loaded unless the caller asks.- A getter or list function reads
preloads = Keyword.get(opts, :preloads, [])and threads it through one privatemaybe_preload/2per module. Itsis_listheadEnum.reduces the list, mapping each supported atom to aQuery.preload_<assoc>/1call (:referrer, acc -> Query.preload_referrer(acc)) with a_, acc -> accfallthrough; a second head,maybe_preload(queryable, _), do: queryable, takes non-list input. preload/2itself is called only in the Query module (#13), as chainablepreload_<assoc>/1functions. Atom names mirror association names; nested and keyword preloads are fine (preload_driver/1→preload(q, driver: :user)). The function's@doclists the supported atoms.- One query wherever a join can do it. For a to-one association (
belongs_to/has_one), create the binding withwith_named_binding/3, wrapped in a chainablewith_<assoc>_binding/1helper, andpreloadoff that named binding: one round-trip, and the join is reused if a filter already added it. A separate-querypreload/2is for the cases where a join is the wrong tool: a to-many association a join would multiply, or alimited or paginated query a join would break. - Gotcha: when the result feeds a GraphQL or JSON field that reads the struct directly, with no field resolver, the caller passes the
:preloadsit needs, or the field is%Ecto.Association.NotLoaded{}. reference.mdshows both modules.
- A getter or list function reads
-
List queries paginate through
Query.paginate.
C. Idiomatic Elixir
-
Dispatch by pattern matching: function heads, guards,
caseandwith, in place ofif/else, and nevercond. Map a result withcaseclauses or function heads that match its shape, such as{:error, %Ecto.Changeset{errors: [{:referrer_id, {_, [{:constraint, :unique} | _]}} | _]}}, not with anifon the contents of an error.ifis for a simple boolean business decision only: it never dispatches on a type or a result, and never has anelsereturning a different shape. A branch driven by a boolean predicate becomes a privatemaybe_<verb>/Nwithtrueandfalseheads, the boolean as the last argument (the subject leads), in place of acaseon the boolean:maybe_moderate(message, urls, skip_moderation?(message.body, urls)) defp maybe_moderate(%Message{} = message, _urls, true), do: {:ok, message} defp maybe_moderate(%Message{} = message, urls, false), do: moderate(message, urls) -
withfor happy-path{:ok, _}/{:error, _}chains;elseonly for error mapping. -
Be exhaustive in
case/with: list the real result shapes ({:error, X},{:error, Y}, …) so every outcome is handled on purpose. An unexpected shape crashes; a blanket_ ->would mishandle it silently. The chainable query fallthrough of #12 is the one deliberate exception. -
Propagate fallible results. When a function's final action is a fallible call (
Repo.insert/update/delete,Oban.insert, another{:ok, _}|{:error, _}function), it returns that call's result. Running it for effect and returning a literal:okhides the failure: the caller sees success and cannot retry. Every head has the same return shape: a no-op or short-circuit head returns the matching{:ok, nil}-style tuple, not a bare:ok. (#20 covers unforeseen shapes; this covers a known fallible result.) -
Tagged tuples
{:ok, _}/{:error, reason}for fallible functions; mutation resolvers wrap the value in a map ({:ok, %{user: user}}). -
Single level of abstraction: each function does one thing at one altitude, in about 10–30 lines, with its steps extracted into well-named
defps and no nested conditionals. -
Pipe two or more chained calls; a single call is written as a plain call.
-
alias/import/require/@attrat the top of the module only. -
Naming: predicates end in
?, raising functions in!; snake_case functions, PascalCase modules, no abbreviations. -
@impl trueon every behaviour, OTP and Phoenix callback. -
@moduledocon every module (falsefor an internal one);@docand@specon the public API. -
Ecto.Multifor multi-step transactions; #55 says when one is required and which lock goes with it. -
Context function names:
list_*,get_*,create_*,update_*,delete_*,count_*. -
JSON goes through the built-in
JSONmodule (JSON.encode!/1,JSON.decode!/1,@derive {JSON.Encoder, ...}), neverJason. -
Take an id, not a struct, when you only need the id. A function that reads only
entity.idaccepts the bare id (abinary), so a caller that already holds the id does not load the struct. When some callers hold the struct and others the id, add a struct head that delegates to the id head:def f(%Schema{id: id}, x), do: f(id, x), thendef f(id, x) when is_binary(id), do: …. -
Bind a computed value to a variable before placing it in a map, struct or keyword list.
member_wish_ids = unserved_wish_ids_for_cluster(id)above the literal, then%{cluster_id: id, member_wish_ids: member_wish_ids}. The literal stays a flat shape and the value carries a name; a function call is not written inline as a value. -
Read and write maps and keyword lists through their module functions:
Map.get/2,3,Map.fetch/2,Map.fetch!/2,Map.put/3,Map.merge/2,Map.update/4, … andKeyword.get/2,3,Keyword.fetch/2,Keyword.fetch!/2,Keyword.put/3, …, never bracket (Access) syntax such asattrs[:x]oropts[:x], which returnsnilfor a missing key and breaks on structs.fetch!when the key must be present,get/3with an explicit default when it is optional. Destructuring in a function head or awith/casepattern (def build(%{user_id: id, text: text})) is as good and often clearer. Nested access still usesget_in/put_in/update_in.
D. GraphQL / web layer
Worked resolver, mutation type and GraphQL test: graphql.md.
- One schema per endpoint or audience (
/api,/admin); shared types and middleware underapi/shared/. - Naming:
MyAppWeb.Api.{Endpoint}.Resolvers.{Domain}.{Name},.Schema.{Queries,Mutations,Types,Middlewares}.…. - Resolvers return tagged tuples and use
withchains; authorization is middleware at the entry plus the resolver for business rules. - Typed errors:
MyApp.Errors.*withuse MyApp.ExErrors+defexerror, returned as{:error, Errors.X.new(...)}, not as raw strings. Define, then return: the error module exists in the project (lib/my_app/errors/<name>_error.ex) before any code returns it, so createErrors.Xfirst when it is missing. An error may carry structured fields,defexerror([:resource_type, :resource_id, message: "..."], required_fields: [:resource_type]), which surface in the GraphQL response underextensions.fieldsbesideextensions.errorCode. - Global middleware
SafeResolution.apply(…) ++ [ErrorHandler]normalizes errors toextensions.errorCode. - Mutations use
payload fieldwithinput/output, and apply their auth middleware inline. - Resolvers pass event metadata,
EventMetadata.build_opts(res), into context functions. - Nested lists go through a Dataloader-backed connection (
Dataloader.Ecto), so GraphQL has no N+1.
E. Events & workers
- Eventing is the
ex_event_bushex dependency (Oban-backed, exactly-once delivery). The bus module isMyApp.EventBus(use ExEventBus, otp_app: :my_app); events live inMyApp.{Context}.Eventsviause ExEventBus.Event+defevents([...]). Everyex_event_bususemacro requires its option (otp_app:orex_event_bus:) and raisesArgumentErrorat compile time without it. - Every domain create, update or delete emits on success:
Repo.insert/update/delete(cs, success_event: Events.X, event_opts: opts), in a function that takesopts \\ [].Repoacceptssuccess_event:/event_opts:because it doesuse ExEventBus.EctoRepoWrapper, ex_event_bus: MyApp.EventBus; that wrapper publishes the event when the write succeeds. - Handlers are
MyApp.{Context}.EventHandler.{Name}:use ExEventBus.EventHandler, ex_event_bus: MyApp.EventBus, events: ["Elixir.MyApp.{Context}.Events.{Name}"](both options required). They implementhandle_event/1, returning:ok | {:ok, any} | :error | {:error, any}, pattern-match the aggregate and changes (string keys, after the JSON round-trip), and enqueue work withOban.insert(). The aggregate carries the facts the handler acts on, who acted and as what ("user_id","role"), so the handler calls no getter to learn them (EP-H14). One handler per rule: a variant by actor is a field of the aggregate, not a second event (EP-D10). A stamp written on every request or cron tick (host_last_seen_at) takes nosuccess_event:(EP-H10). - Handler supervision:
EventHandlerdelegateschild_specto itsSupervisor(:one_for_one). - Cross-context communication goes through events, for decoupled reactions. The one exception is a Service (#4) orchestrating a synchronous cross-context transaction. Direct calls otherwise stay within a context.
- Workers live in
lib/my_app/workers/:use MyApp.Worker+use Oban.Worker, queue:, max_attempts:, an@implperform(%Oban.Job{args: %{"k" => v}})returning:ok/{:error}/{:cancel}/{:snooze}, andtags:.
F. Testing
Detail, worked tests and the reasons: testing.md.
- Case templates:
MyApp.DataCase(contexts, changesets),MyAppWeb.ConnCase(HTTP),*GqlCase(GraphQL). - Factories: ExMachina
{name}_factory,insert/2overbuild/2,sequence/2for uniqueness. - Mocking: Mox with behaviours,
defmockcentralized intest_helper.exs,setup [:set_mox_from_context, :verify_on_exit!]. - Event testing:
use ExEventBus.Testing, ex_event_bus: MyApp.EventBus(the option is required) givesassert_event_received(Events.X, args: …),refute_event_received/2,all_received/1andexecute_events/0,1. Events are Oban jobs on the:ex_event_busqueue, soassert_event_receivedisOban.Testing.assert_enqueuedunderneath and proves only that the event was enqueued.execute_events()drains that queue and runs the handlers; assert on its result,assert %{success: 1, failure: 0} = execute_events(), or scope it withexecute_events(event_handler: MyApp.{Context}.EventHandler.{Name}). Worker testing:use Oban.Testing,perform_job/2,assert_enqueued/1. - One
describeper function, and one function perdescribe, nameddescribe "fun/arity"after the function under test; everytestinside exercises that function only, and all of a function's tests sit in its onedescribe. Tests readtest "when <condition>".async: truefor pure tests. GraphQL tests go throughquery_gql(...)+load_gql_file, and there thedescribenames the.gqlfile: one operation. - Self-contained tests: everything that drives the assertion, the input data and the expected values, is visible in the
testbody. Build the entities under assertion inside the test, with the fields the assertion depends on passed explicitly and inline.setupis for harness wiring that is never asserted on: Mox mode, aconn, sandbox or config, a feature flag. Inline literal values in place of module attributes (@valid_attrs,@user_id). When repetition hurts, extract a named helper or a factory (#50) that the test calls. Set the environment the behaviour depends on, a time zone or a locale, inside the test (EP-G4).
G. Concurrency
- Assume a concurrent writer: make the operation atomic, and put the invariant in the database. More than one write in one logical operation, or a single write whose value came from a row read moments earlier, runs as one
Ecto.Multiin a singleRepo.transaction/1(#29), in a Service (#4), with the{:error, step, value, changes}4-tuple mapped back to{:ok, _}/{:error, _}. "The second write can't realistically fail" is not an argument: a constraint, a race or a restart makes it fail, and nothing undoes the first. Nothing external runs inside a transaction: an HTTP call, an email or a payment is an Oban job enqueued as a Multi step.concurrency.mdgives the protection for each thing at risk (counter, upsert, state transition,FOR UPDATE, optimistic lock, advisory lock, claim row, Obanunique:), the lock order, how Services compose and how to test the invariant.
H. Change hygiene
- After editing, above all after removing logic, re-read the code you touched and, in the same change, delete whatever the edit made pointless. A helper collapsed to
x -> xis inlined at its lone call site and removed; a clause that became unreachable and an unused@attrare deleted. Comments stay useful and current: drop any that no longer matches the code, and keep none that says what the code used to be or used to do, since that history is in git. What a change adds is held to the same bar (EP-D8): an event indefeventsthat noEventHandlerlists, a schema field that is onlycastand written, adefordefdelegateno production code calls, a status string nothing writes and the clause that matches it — each ships with the change that reads it.
I. Application boundaries
- An app knows everything inside its own boundary and nothing outside it (EP-E1 to EP-E4). This backend owns its domain, its database and the contract it publishes, and encodes no knowledge of another application: a client app's screens, navigation, local state or release cadence; another service's modules, tables or file layout.
- Another app's data arrives through its API or as an event. There is no second
Repoon another service's database, no schema mirroring a table we don't own, no SQL across a boundary. #47 is the same principle one level down, between contexts. - The domain does not know who is calling.
if client == "mobile"in a context is a boundary leak. Shaping for an audience is the web layer's job, which is what the per-endpoint schema split (#35) is for. - One side owns each rule. A caller that needs a computed value or a decision gets it as a field, a mutation result or a typed error (#38), and a client is not left to re-implement ours: two copies of one rule drift.
- Docs and comments describe what this code guarantees, never what a client does with it ("the mobile app shows this on the profile screen"). Nothing in this repo can verify such a sentence, and nobody updates it when that app changes.
- Another app's data arrives through its API or as an event. There is no second
J. Comments & prose
-
No comment unless the code cannot say it. The default is zero inline comments: names, small single-altitude functions (#23), pattern-matched heads and typed errors (#38) carry the meaning.
- The code says the what. A comment restating the function name or the next line (
# fetch the user,# build the changeset), or walking through a pipe step by step, is deleted; when the code needs that prose to be followed, the fix is a better name or an extracteddefp. - A comment earns its place for a why the code cannot show: a workaround for an external system's quirk, a non-obvious constraint (a lock order, a provider's idempotency rule, #55), a deliberate deviation from a rule in this skill (name the rule), or the ticket that decided it. One or two lines, at the line it explains; a paragraph belongs in the
@moduledocor the PR description. @moduledoc/@docstay mandatory (#28) and describe the contract: what the function guarantees, its options, its return shapes. Thedefps it calls and the queries it runs are implementation, and change while the doc does not.@moduledoc falseis a complete doc for an internal module.- No structural or decorative prose: no banner or section comments (
# ---- Helpers ----), no# TODOfor something doable in this change, no commented-out code (git keeps it, #56). In tests thedescribe/testnames are the documentation (#53); a comment explaining what a test checks means its name is wrong.
# Stripe redelivers webhooks for up to 3 days; `on_conflict: :nothing` makes a replay a no-op. Repo.insert(changeset, on_conflict: :nothing) - The code says the what. A comment restating the function name or the next line (
K. Documentation
- Every PR ships its documentation, describing the app after the change.
docs/README.mdis the system map: every feature, and every edge between features.docs/<context>/<feature>.mdis one living page per feature, with mermaid diagrams. A change to behaviour or wiring updates the page(s), and the map when an edge appeared or disappeared, in the same PR. A change that alters nothing documented (formatting, a version bump) says in the PR description which page was checked and why it needed no change. Nodocs/diff and no such statement is an incomplete PR, exactly like a missing test.docs.mdhas the page skeleton, the writing rules and a worked page.
L. Guardrails
- Green before done. Before saying any Elixir work is finished, run
mix precommitafter your last edit and read its output; a red run is reported with that output, not summarised as done. An app with noprecommitalias → run what it has (mix format,mix credo --strict,mix test) and say the app is missing guardrails; theelixir-guardrailsskill installs them. No check covers Rule 0 or #59: English-only code and a behaviour change shipped without itsdocs/change are caught only by reading, so read every diff for both. - Never weaken a guardrail to get green. No
# credo:disable-*,@dialyzer {:nowarn_function, …},# sobelow_skip,# excellent_migrations:safety-assured-for-next-line, new entry in a baseline (the# >>> baselineblock of.credo.exsor of ause Boundary,.dialyzer_ignore.exs,.sobelow-skips), raised--fail-above, advisory ignore,precommitor CI step removed or made non-blocking, or@tag :skip. Fix the code instead. A genuine exception needs the person's approval, a one-line comment naming the rule (#58 allows that comment), and theguardrails-changedlabel on the PR. Baselines only shrink: a change that edits a file listed in a baseline fixes that file's issues and deletes its entry in the same change. Deleting entries needs no label; the CI gate lets it through. - Write code that passes the checks the first time. Each item names the check that enforces it:
Taskonly under a supervisor,Task.Supervisor.async_nolink/3, and in LiveViewstart_async/3withhandle_async/3(UnmanagedTask, MissingHandleAsync, SyncOverAsync).- A
rescuenever discards the error: return{:error, reason}, re-raise, or log with the exception (SwallowingException; extends #20 and #21). The check only sees an explicittry … rescue, and Credo's PreferImplicitTry turns that into a function-levelrescueit cannot see, so read everyrescueyou write or move. - No blocking call (HTTP,
Process.sleep, a slow query) inside a Plug'scall/2(BlockingInPlug). - A
caseontrue/false(CaseTrueFalse) is fixed with amaybe_*helper (#18), never with theif/elsethe check's message suggests. - No
raw/1in a.heexfile or a~Htemplate (Sobelow XSS.Raw). - Every test asserts an outcome, a value or stored state and not only
{:ok, _}; every selector can fail; noopen_browseris committed (VacuousTest, TestHasNoAssertions, WeakAssertion, AssertElementSelectorCanNeverFail, NoOpenBrowser; complements #53 and #54). - Every LiveView assign is rendered (UnusedLiveViewAssign).
- No query per item and no missing preload: use #16's opt-in preloads (NPlusOneQuery, MissingPreload). Filter in the query, never with
Enum.filterafterRepo.all(InefficientFilter). - Migrations:
create index(…, concurrently: true)with@disable_ddl_transaction trueand@disable_migration_lock true; no column type changed in place; backfills outside schema migrations (MigrationsSafety). - No new compile-time dependency: no call to another app module in a module attribute or module body, no
import/useof an app module without a real need (xref compile-connected). - Callers outside a context use its facade (#2). Boundary's
exportsenforce it at compile time; a new cross-context dependency goes indeps:and is justified by #47. - Every
`Mod.fun/n`in a@docor@moduledocexists (docs--warnings-as-errors). - Public
@specs (#28) stay true; a Dialyzer warning is fixed, never silenced.
M. Migrations
- A migration in
priv/repo/migrationsis final once it is on main or pushed (EP-I6). Change the schema with a new migration, so every database runs the same files in the same order: production, staging, CI and each teammate's. A column added too soon is dropped by a new migration (remove :host_last_seen_at, :utc_datetime_usec, with its type so it rolls back) and added back by the change that reads it.
N. The app's idioms
- Do a job the way the app already does it (EP-D13). Read config through the app's config module when it has one (
MyApp.Config.fetch_env!/2, which async tests override per process) rather thanApplication.fetch_env!; default an environment variable inconfig/runtime.exsthe way the file already does (String.to_integer(System.get_env("NAME") || "15")); name operations with the app's verbs (tokens areissue_*d where the app says so, EP-A2). Before writing a helper, find how two existing modules do the same job.
04 同仓库更多 Skills
flutter-conventions-guide
Team conventions for our Flutter apps. Use when writing or editing any `.dart` or `.arb` file.
review-report
Report template, finding card and diagram guide for the review-companion skill, which loads this when it writes its report. Not a review on its own.
review-passes
The checklist for each of the eight passes of the review-companion skill, which loads this when its passes start. Not a review on its own.
review-companion
Code review of a change (a branch, PR or commit range) in any language, as a report for the human reviewer, who decides. Use when asked to review a change.
pr-description
The standard for a pull request's title and description (EP-F5). Use when writing, checking or rewriting a PR title or description.
engineering-principles
Language-agnostic engineering rules, cited by ID (EP-0 to EP-K11). Use when writing or reviewing code in any language.