[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75Y0GHJVKMPF3263KB0W9YE":3,"skill-same:01M75Y0GHJVKMPF3263KB0W9YE":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M75Y0GHJVKMPF3263KB0W9YE","elixir-phoenix-conventions",null,"Team conventions for our Elixir\u002FPhoenix apps. Use when writing or editing any `.ex` or `.exs` file, a `docs\u002F` page a change ships with, running `mix precommit`, or editing guardrail config (`.credo.exs`, `.sobelow-conf`, `.sobelow-skips`, `.dialyzer_ignore.exs`, CI workflows).","colette-club\u002Fcolette-marketplace","colette-club","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F59931915?v=4","01M75Y06SHY1G6DYGTBPZP6HSX","Colette Club","01M75Y06T72MFPEY3KY0FZWD0R",0,"MIT","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: elixir-phoenix-conventions\ndescription: Team conventions for our Elixir\u002FPhoenix apps. Use when writing or editing any `.ex` or `.exs` file, a `docs\u002F` page a change ships with, running `mix precommit`, or editing guardrail config (`.credo.exs`, `.sobelow-conf`, `.sobelow-skips`, `.dialyzer_ignore.exs`, CI workflows).\n---\n\n# Elixir\u002FPhoenix Conventions\n\nCode 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).\n\n- `MyApp`\u002F`MyAppWeb` stand for the app's namespace.\n- Rules are cited by number (`#18`), and the numbers are stable. An `EP-…` id names the matching language-agnostic rule in the `engineering-principles` skill of the `engineering-review` plugin, where that plugin is installed.\n- Broken most often, so check them first: #2, #13, #18, #23, #31, #59.\n\n## Read first, when it applies\n\nEach file sits next to this one and holds the detail and worked code for one kind of work.\n\n| Before you | Read |\n|---|---|\n| add a feature that has no sibling module to copy | `reference.md`: one feature wired through every layer |\n| write or change a test | `testing.md` |\n| write an operation with more than one write, a write whose value was read earlier, a lock, a transaction or a Service | `concurrency.md` |\n| write a resolver, a mutation, a GraphQL type or a GraphQL test | `graphql.md` |\n| change what the app does or how it is wired | `docs.md`: the page and the map the change ships with |\n\n## Before you say done\n\n1. Every function you touched is re-read, and what the edit made pointless is deleted (#56).\n2. `docs\u002F` describes the app after the change, or the PR description names the page you checked (#59).\n3. Every character of the diff is English (Rule 0).\n4. `mix precommit` exits 0 on a run started after your last edit (#60). A red run is reported with its output.\n\n## Rule 0 — everything is in English\n\n**Every character we author is English** (EP-0): module, function and variable names, `@moduledoc` and `@doc` text, comments, `describe`\u002F`test` names, error messages and typed-error fields, log and telemetry messages, migration and index names, seed labels, `TODO`s, commit messages and PR descriptions. This holds whoever wrote the surrounding code and however short the snippet.\n\nThe 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.\n\nCode you touch that is in another language is renamed and its comments rewritten in English, in the same change (#56).\n\n## The rules\n\n### A. Context architecture & layering\n1. Four tiers: facade (`MyApp.Accounts`) → sub-module (`Accounts.Users`) → `Query` (`accounts\u002Fusers\u002Fquery.ex`) → schema (`Accounts.User`).\n2. The facade is the context's public API and nothing else: it `defdelegate`s to sub-modules, and every new public context function gets its `defdelegate` (`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.\n3. Sub-modules hold CRUD and business logic and carry a domain name (`Users`, `Confirmations`); the name `Impl` belongs to adapters only (#5).\n4. **Context and sub-module functions stay thin**: take a struct and an attrs map, apply the schema changeset, call `Repo.insert\u002Fupdate\u002Fdelete`. Anything more (a multi-step `Ecto.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\u002F…`, taking `opts \\\\ []`, with as many heads as it needs; a second job is a Service of its own. Its `@moduledoc` states its single responsibility, it is built from pattern-matched heads and extracted `defp`s, and it returns `{:ok, _}`\u002F`{:error, _}`. **Callers invoke `Service.run(...)` directly: a Service is never `defdelegate`d or wrapped by a facade or another module.**\n5. **External services and adapters** are a behaviour + `Impl` + `StubImpl`\u002FMock, 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`, `\u002Fwebhooks\u002Fmedia-server`). The implementation reads its settings from its own key (`config :my_app, MyApp.Live.Adapters.LiveKit, …`), and `config\u002Fruntime.exs` requires each one, counting a blank value as missing, wherever that implementation is the configured one (EP-D6, EP-E6).\n6. Schemas `use MyApp.Schema, :schema` (binary_id UUID primary keys), in place of a bare `use Ecto.Schema`.\n7. Changesets live in the schema module (`changeset\u002F2`, or intent-named like `archive_changeset\u002F2`); 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 raising `Ecto.ConstraintError` (EP-H3).\n8. `@derive {JSON.Encoder, except: [...]}` on schemas controls which fields are exposed.\n9. Soft-delete, and every other lifecycle stamp, is a nullable datetime (`archived_at`\u002F`deleted_at`\u002F`flagged_at`\u002F…), 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 changeset `put_change`s the timestamp, then `cast(attrs, [field])` so attrs can override, guarded by `validate_no_override\u002F2`. That guard is built on `validate_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.\n10. Context directory layout: `context.ex`, `supervisor.ex`, `events.ex`, `event_handler\u002F`, `services\u002F` (Service objects), schema files, and one directory per sub-module, each with its `query.ex`.\n\n### B. Ecto \u002F Query \u002F Repo\n11. Query modules `use MyApp.Query`, which gives `filtered_by\u002F2`, `ordered_by\u002F2`, `with_id(s)\u002F2`, `paginate\u002F4` and `count\u002F1`.\n12. 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\u002F3`, `join(q, :inner, [m], t in assoc(m, :thread), as: :thread)`, `select\u002F3`, `limit\u002F2`. Every function is then a single composable pipe step. **A join uses `assoc(m, :name)` whenever the schema declares the association**, which reuses its foreign key and conditions; an explicit `on:` is for a join with no association (computed or cross-schema). `from(...)` is reserved for the three things the pipe forms cannot express:\n    - **naming the root binding**: `from(t in Thing, as: :things)` for `base\u002F0`, or `from(q, as: :things)` inside a `has_named_binding?`\u002F`maybe_alias_*` guard;\n    - a **standalone subquery or `exists`\u002F`not exists`** expression (`subquery(...)`, `parent_as(...)`);\n    - an **`update:` or fragment atomic write**.\n\n    A table name inside a `fragment` string means the builder was skipped: write the subquery with `exists`\u002F`subquery` and `parent_as` over the schema, and keep in `fragment` only what the builder cannot express, such as a row comparison `(?, ?) > (?, ?)` or a cast (EP-K11).\n13. `import Ecto.Query`, and with it `where`\u002F`from`\u002F`order_by`\u002F`join`\u002F`preload`\u002F`lock`, appears **only** in `*\u002Fquery.ex` modules. Context and sub-modules pipe a schema through `Query.*` functions, then call `Repo.*`.\n14. Read chain: `Schema |> Query.filtered_by(args) |> Query.ordered_by(o) |> Query.paginate(...)` \u002F `Repo.one`.\n15. Read by id through a context getter (`get_*`\u002F`get_*!`). Callers outside the context use the getter and never `Repo.*`. Inside the getter, `Repo.get`\u002F`Repo.get_by` is fine; use `Schema |> Query.with_id(id) |> Repo.one` when you need the Query layer's standard filters, such as soft-deletes. Every `get_*`, 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 return `nil` (EP-A2, EP-C2).\n16. **Preloads are opt-in through the `:preloads` option**: a list of association atoms, default `[]`, so nothing is loaded unless the caller asks.\n    - A getter or list function reads `preloads = Keyword.get(opts, :preloads, [])` and threads it through **one** private `maybe_preload\u002F2` per module. Its `is_list` head `Enum.reduce`s the list, mapping each supported atom to a `Query.preload_\u003Cassoc>\u002F1` call (`:referrer, acc -> Query.preload_referrer(acc)`) with a `_, acc -> acc` fallthrough; a second head, `maybe_preload(queryable, _), do: queryable`, takes non-list input.\n    - `preload\u002F2` itself is called only in the Query module (#13), as chainable `preload_\u003Cassoc>\u002F1` functions. Atom names mirror association names; nested and keyword preloads are fine (`preload_driver\u002F1` → `preload(q, driver: :user)`). The function's `@doc` lists the supported atoms.\n    - **One query wherever a join can do it.** For a to-one association (`belongs_to`\u002F`has_one`), create the binding with `with_named_binding\u002F3`, wrapped in a chainable `with_\u003Cassoc>_binding\u002F1` helper, and `preload` off that named binding: one round-trip, and the join is reused if a filter already added it. A separate-query `preload\u002F2` is for the cases where a join is the wrong tool: a to-many association a join would multiply, or a `limit`ed or paginated query a join would break.\n    - **Gotcha:** when the result feeds a GraphQL or JSON field that reads the struct directly, with no field resolver, the caller passes the `:preloads` it needs, or the field is `%Ecto.Association.NotLoaded{}`.\n    - `reference.md` shows both modules.\n17. List queries paginate through `Query.paginate`.\n\n### C. Idiomatic Elixir\n18. **Dispatch by pattern matching**: function heads, guards, `case` and `with`, in place of `if\u002Felse`, and never `cond`. Map a result with `case` clauses or function heads that match its shape, such as `{:error, %Ecto.Changeset{errors: [{:referrer_id, {_, [{:constraint, :unique} | _]}} | _]}}`, not with an `if` on the contents of an error. `if` is for a simple boolean business decision only: it never dispatches on a type or a result, and never has an `else` returning a different shape. A branch driven by a boolean predicate becomes a private `maybe_\u003Cverb>\u002FN` with `true` and `false` heads, the boolean as the **last** argument (the subject leads), in place of a `case` on the boolean:\n\n    ```elixir\n    maybe_moderate(message, urls, skip_moderation?(message.body, urls))\n\n    defp maybe_moderate(%Message{} = message, _urls, true), do: {:ok, message}\n    defp maybe_moderate(%Message{} = message, urls, false), do: moderate(message, urls)\n    ```\n19. `with` for happy-path `{:ok, _}`\u002F`{:error, _}` chains; `else` only for error mapping.\n20. Be exhaustive in `case`\u002F`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.\n21. **Propagate fallible results.** When a function's final action is a fallible call (`Repo.insert\u002Fupdate\u002Fdelete`, `Oban.insert`, another `{:ok, _}|{:error, _}` function), it returns *that call's* result. Running it for effect and returning a literal `:ok` hides 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.)\n22. Tagged tuples `{:ok, _}`\u002F`{:error, reason}` for fallible functions; mutation resolvers wrap the value in a map (`{:ok, %{user: user}}`).\n23. Single level of abstraction: each function does one thing at one altitude, in about 10–30 lines, with its steps extracted into well-named `defp`s and no nested conditionals.\n24. Pipe two or more chained calls; a single call is written as a plain call.\n25. `alias`\u002F`import`\u002F`require`\u002F`@attr` at the top of the module only.\n26. Naming: predicates end in `?`, raising functions in `!`; snake_case functions, PascalCase modules, no abbreviations.\n27. `@impl true` on every behaviour, OTP and Phoenix callback.\n28. `@moduledoc` on every module (`false` for an internal one); `@doc` and `@spec` on the public API.\n29. `Ecto.Multi` for multi-step transactions; #55 says when one is required and which lock goes with it.\n30. Context function names: `list_*`, `get_*`, `create_*`, `update_*`, `delete_*`, `count_*`.\n31. JSON goes through the built-in `JSON` module (`JSON.encode!\u002F1`, `JSON.decode!\u002F1`, `@derive {JSON.Encoder, ...}`), never `Jason`.\n32. **Take an id, not a struct, when you only need the id.** A function that reads only `entity.id` accepts the bare id (a `binary`), 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)`, then `def f(id, x) when is_binary(id), do: …`.\n33. **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.\n34. **Read and write maps and keyword lists through their module functions**: `Map.get\u002F2,3`, `Map.fetch\u002F2`, `Map.fetch!\u002F2`, `Map.put\u002F3`, `Map.merge\u002F2`, `Map.update\u002F4`, … and `Keyword.get\u002F2,3`, `Keyword.fetch\u002F2`, `Keyword.fetch!\u002F2`, `Keyword.put\u002F3`, …, never bracket (`Access`) syntax such as `attrs[:x]` or `opts[:x]`, which returns `nil` for a missing key and breaks on structs. `fetch!` when the key must be present, `get\u002F3` with an explicit default when it is optional. Destructuring in a function head or a `with`\u002F`case` pattern (`def build(%{user_id: id, text: text})`) is as good and often clearer. Nested access still uses `get_in`\u002F`put_in`\u002F`update_in`.\n\n### D. GraphQL \u002F web layer\n\nWorked resolver, mutation type and GraphQL test: `graphql.md`.\n\n35. One schema per endpoint or audience (`\u002Fapi`, `\u002Fadmin`); shared types and middleware under `api\u002Fshared\u002F`.\n36. Naming: `MyAppWeb.Api.{Endpoint}.Resolvers.{Domain}.{Name}`, `.Schema.{Queries,Mutations,Types,Middlewares}.…`.\n37. Resolvers return tagged tuples and use `with` chains; authorization is middleware at the entry plus the resolver for business rules.\n38. Typed errors: `MyApp.Errors.*` with `use MyApp.ExErrors` + `defexerror`, returned as `{:error, Errors.X.new(...)}`, not as raw strings. **Define, then return**: the error module exists in the project (`lib\u002Fmy_app\u002Ferrors\u002F\u003Cname>_error.ex`) before any code returns it, so create `Errors.X` first 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 under `extensions.fields` beside `extensions.errorCode`.\n39. Global middleware `SafeResolution.apply(…) ++ [ErrorHandler]` normalizes errors to `extensions.errorCode`.\n40. Mutations use `payload field` with `input`\u002F`output`, and apply their auth middleware inline.\n41. Resolvers pass event metadata, `EventMetadata.build_opts(res)`, into context functions.\n42. Nested lists go through a Dataloader-backed connection (`Dataloader.Ecto`), so GraphQL has no N+1.\n\n### E. Events & workers\n43. Eventing is the **`ex_event_bus` hex dependency** (Oban-backed, exactly-once delivery). The bus module is `MyApp.EventBus` (`use ExEventBus, otp_app: :my_app`); events live in `MyApp.{Context}.Events` via `use ExEventBus.Event` + `defevents([...])`. Every `ex_event_bus` `use` macro **requires** its option (`otp_app:` or `ex_event_bus:`) and raises `ArgumentError` at compile time without it.\n44. Every domain create, update or delete emits on success: `Repo.insert\u002Fupdate\u002Fdelete(cs, success_event: Events.X, event_opts: opts)`, in a function that takes `opts \\\\ []`. `Repo` accepts `success_event:`\u002F`event_opts:` because it does `use ExEventBus.EctoRepoWrapper, ex_event_bus: MyApp.EventBus`; that wrapper publishes the event when the write succeeds.\n45. Handlers are `MyApp.{Context}.EventHandler.{Name}`: `use ExEventBus.EventHandler, ex_event_bus: MyApp.EventBus, events: [\"Elixir.MyApp.{Context}.Events.{Name}\"]` (both options required). They implement `handle_event\u002F1`, returning `:ok | {:ok, any} | :error | {:error, any}`, pattern-match the aggregate and changes (string keys, after the JSON round-trip), and enqueue work with `Oban.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 no `success_event:` (EP-H10).\n46. Handler supervision: `EventHandler` delegates `child_spec` to its `Supervisor` (`:one_for_one`).\n47. **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.\n48. Workers live in `lib\u002Fmy_app\u002Fworkers\u002F`: `use MyApp.Worker` + `use Oban.Worker, queue:, max_attempts:`, an `@impl` `perform(%Oban.Job{args: %{\"k\" => v}})` returning `:ok`\u002F`{:error}`\u002F`{:cancel}`\u002F`{:snooze}`, and `tags:`.\n\n### F. Testing\n\nDetail, worked tests and the reasons: `testing.md`.\n\n49. Case templates: `MyApp.DataCase` (contexts, changesets), `MyAppWeb.ConnCase` (HTTP), `*GqlCase` (GraphQL).\n50. Factories: ExMachina `{name}_factory`, `insert\u002F2` over `build\u002F2`, `sequence\u002F2` for uniqueness.\n51. Mocking: Mox with behaviours, `defmock` centralized in `test_helper.exs`, `setup [:set_mox_from_context, :verify_on_exit!]`.\n52. Event testing: `use ExEventBus.Testing, ex_event_bus: MyApp.EventBus` (the option is required) gives `assert_event_received(Events.X, args: …)`, `refute_event_received\u002F2`, `all_received\u002F1` and `execute_events\u002F0,1`. Events are Oban jobs on the `:ex_event_bus` queue, so `assert_event_received` is `Oban.Testing.assert_enqueued` underneath 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 with `execute_events(event_handler: MyApp.{Context}.EventHandler.{Name})`. Worker testing: `use Oban.Testing`, `perform_job\u002F2`, `assert_enqueued\u002F1`.\n53. **One `describe` per function, and one function per `describe`**, named `describe \"fun\u002Farity\"` after the function under test; every `test` inside exercises that function only, and all of a function's tests sit in its one `describe`. Tests read `test \"when \u003Ccondition>\"`. `async: true` for pure tests. GraphQL tests go through `query_gql(...)` + `load_gql_file`, and there the `describe` names the `.gql` file: one operation.\n54. **Self-contained tests**: everything that drives the assertion, the input data *and* the expected values, is visible in the `test` body. Build the entities under assertion inside the test, with the fields the assertion depends on passed explicitly and inline. `setup` is for harness wiring that is never asserted on: Mox mode, a `conn`, 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).\n\n### G. Concurrency\n55. **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.Multi` in a single `Repo.transaction\u002F1` (#29), in a Service (#4), with the `{:error, step, value, changes}` 4-tuple mapped back to `{:ok, _}`\u002F`{: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.md` gives the protection for each thing at risk (counter, upsert, state transition, `FOR UPDATE`, optimistic lock, advisory lock, claim row, Oban `unique:`), the lock order, how Services compose and how to test the invariant.\n\n### H. Change hygiene\n56. **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 -> x` is inlined at its lone call site and removed; a clause that became unreachable and an unused `@attr` are 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 in `defevents` that no `EventHandler` lists, a schema field that is only `cast` and written, a `def` or `defdelegate` no production code calls, a status string nothing writes and the clause that matches it — each ships with the change that reads it.\n\n### I. Application boundaries\n57. **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.\n    - **Another app's data arrives through its API or as an event.** There is no second `Repo` on 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.\n    - **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.\n    - **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.\n    - **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.\n\n### J. Comments & prose\n58. **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.\n    - **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 extracted `defp`.\n    - **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 `@moduledoc` or the PR description.\n    - **`@moduledoc`\u002F`@doc` stay mandatory (#28) and describe the contract**: what the function guarantees, its options, its return shapes. The `defp`s it calls and the queries it runs are implementation, and change while the doc does not. `@moduledoc false` is a complete doc for an internal module.\n    - **No structural or decorative prose**: no banner or section comments (`# ---- Helpers ----`), no `# TODO` for something doable in this change, no commented-out code (git keeps it, #56). In tests the `describe`\u002F`test` names are the documentation (#53); a comment explaining what a test checks means its name is wrong.\n\n    ```elixir\n    # Stripe redelivers webhooks for up to 3 days; `on_conflict: :nothing` makes a replay a no-op.\n    Repo.insert(changeset, on_conflict: :nothing)\n    ```\n\n### K. Documentation\n59. **Every PR ships its documentation**, describing the app *after* the change. `docs\u002FREADME.md` is the system map: every feature, and every edge between features. `docs\u002F\u003Ccontext>\u002F\u003Cfeature>.md` is 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. No `docs\u002F` diff and no such statement is an incomplete PR, exactly like a missing test. `docs.md` has the page skeleton, the writing rules and a worked page.\n\n### L. Guardrails\n\n60. **Green before done.** Before saying any Elixir work is finished, run `mix precommit` after your last edit and read its output; a red run is reported with that output, not summarised as done. An app with no `precommit` alias → run what it has (`mix format`, `mix credo --strict`, `mix test`) and say the app is missing guardrails; the `elixir-guardrails` skill installs them. No check covers Rule 0 or #59: English-only code and a behaviour change shipped without its `docs\u002F` change are caught only by reading, so read every diff for both.\n61. **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 `# >>> baseline` block of `.credo.exs` or of a `use Boundary`, `.dialyzer_ignore.exs`, `.sobelow-skips`), raised `--fail-above`, advisory ignore, `precommit` or 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 the `guardrails-changed` label 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.\n62. **Write code that passes the checks the first time.** Each item names the check that enforces it:\n    - `Task` only under a supervisor, `Task.Supervisor.async_nolink\u002F3`, and in LiveView `start_async\u002F3` with `handle_async\u002F3` (UnmanagedTask, MissingHandleAsync, SyncOverAsync).\n    - A `rescue` never discards the error: return `{:error, reason}`, re-raise, or log with the exception (SwallowingException; extends #20 and #21). The check only sees an explicit `try … rescue`, and Credo's PreferImplicitTry turns that into a function-level `rescue` it cannot see, so read every `rescue` you write or move.\n    - No blocking call (HTTP, `Process.sleep`, a slow query) inside a Plug's `call\u002F2` (BlockingInPlug).\n    - A `case` on `true`\u002F`false` (CaseTrueFalse) is fixed with a `maybe_*` helper (#18), never with the `if`\u002F`else` the check's message suggests.\n    - No `raw\u002F1` in a `.heex` file or a `~H` template (Sobelow XSS.Raw).\n    - Every test asserts an outcome, a value or stored state and not only `{:ok, _}`; every selector can fail; no `open_browser` is committed (VacuousTest, TestHasNoAssertions, WeakAssertion, AssertElementSelectorCanNeverFail, NoOpenBrowser; complements #53 and #54).\n    - Every LiveView assign is rendered (UnusedLiveViewAssign).\n    - No query per item and no missing preload: use #16's opt-in preloads (NPlusOneQuery, MissingPreload). Filter in the query, never with `Enum.filter` after `Repo.all` (InefficientFilter).\n    - Migrations: `create index(…, concurrently: true)` with `@disable_ddl_transaction true` and `@disable_migration_lock true`; no column type changed in place; backfills outside schema migrations (MigrationsSafety).\n    - No new compile-time dependency: no call to another app module in a module attribute or module body, no `import`\u002F`use` of an app module without a real need (xref compile-connected).\n    - Callers outside a context use its facade (#2). Boundary's `exports` enforce it at compile time; a new cross-context dependency goes in `deps:` and is justified by #47.\n    - Every `` `Mod.fun\u002Fn` `` in a `@doc` or `@moduledoc` exists (docs `--warnings-as-errors`).\n    - Public `@spec`s (#28) stay true; a Dialyzer warning is fixed, never silenced.\n\n### M. Migrations\n\n63. **A migration in `priv\u002Frepo\u002Fmigrations` is 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\n### N. The app's idioms\n\n64. **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!\u002F2`, which async tests override per process) rather than `Application.fetch_env!`; default an environment variable in `config\u002Fruntime.exs` the way the file already does (`String.to_integer(System.get_env(\"NAME\") || \"15\")`); name operations with the app's verbs (tokens are `issue_*`d where the app says so, EP-A2). Before writing a helper, find how two existing modules do the same job.\n","# Elixir\u002FPhoenix Conventions\n\nCode 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).\n\n- `MyApp`\u002F`MyAppWeb` stand for the app's namespace.\n- Rules are cited by number (`#18`), and the numbers are stable. An `EP-…` id names the matching language-agnostic rule in the `engineering-principles` skill of the `engineering-review` plugin, where that plugin is installed.\n- Broken most often, so check them first: #2, #13, #18, #23, #31, #59.\n\n## Read first, when it applies\n\nEach file sits next to this one and holds the detail and worked code for one kind of work.\n\n| Before you | Read |\n|---|---|\n| add a feature that has no sibling module to copy | `reference.md`: one feature wired through every layer |\n| write or change a test | `testing.md` |\n| write an operation with more than one write, a write whose value was read earlier, a lock, a transaction or a Service | `concurrency.md` |\n| write a resolver, a mutation, a GraphQL type or a GraphQL test | `graphql.md` |\n| change what the app does or how it is wired | `docs.md`: the page and the map the change ships with |\n\n## Before you say done\n\n1. Every function you touched is re-read, and what the edit made pointless is deleted (#56).\n2. `docs\u002F` describes the app after the change, or the PR description names the page you checked (#59).\n3. Every character of the diff is English (Rule 0).\n4. `mix precommit` exits 0 on a run started after your last edit (#60). A red run is reported with its output.\n\n## Rule 0 — everything is in English\n\n**Every character we author is English** (EP-0): module, function and variable names, `@moduledoc` and `@doc` text, comments, `describe`\u002F`test` names, error messages and typed-error fields, log and telemetry messages, migration and index names, seed labels, `TODO`s, commit messages and PR descriptions. This holds whoever wrote the surrounding code and however short the snippet.\n\nThe 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.\n\nCode you touch that is in another language is renamed and its comments rewritten in English, in the same change (#56).\n\n## The rules\n\n### A. Context architecture & layering\n1. Four tiers: facade (`MyApp.Accounts`) → sub-module (`Accounts.Users`) → `Query` (`accounts\u002Fusers\u002Fquery.ex`) → schema (`Accounts.User`).\n2. The facade is the context's public API and nothing else: it `defdelegate`s to sub-modules, and every new public context function gets its `defdelegate` (`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.\n3. Sub-modules hold CRUD and business logic and carry a domain name (`Users`, `Confirmations`); the name `Impl` belongs to adapters only (#5).\n4. **Context and sub-module functions stay thin**: take a struct and an attrs map, apply the schema changeset, call `Repo.insert\u002Fupdate\u002Fdelete`. Anything more (a multi-step `Ecto.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\u002F…`, taking `opts \\\\ []`, with as many heads as it needs; a second job is a Service of its own. Its `@moduledoc` states its single responsibility, it is built from pattern-matched heads and extracted `defp`s, and it returns `{:ok, _}`\u002F`{:error, _}`. **Callers invoke `Service.run(...)` directly: a Service is never `defdelegate`d or wrapped by a facade or another module.**\n5. **External services and adapters** are a behaviour + `Impl` + `StubImpl`\u002FMock, 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`, `\u002Fwebhooks\u002Fmedia-server`). The implementation reads its settings from its own key (`config :my_app, MyApp.Live.Adapters.LiveKit, …`), and `config\u002Fruntime.exs` requires each one, counting a blank value as missing, wherever that implementation is the configured one (EP-D6, EP-E6).\n6. Schemas `use MyApp.Schema, :schema` (binary_id UUID primary keys), in place of a bare `use Ecto.Schema`.\n7. Changesets live in the schema module (`changeset\u002F2`, or intent-named like `archive_changeset\u002F2`); 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 raising `Ecto.ConstraintError` (EP-H3).\n8. `@derive {JSON.Encoder, except: [...]}` on schemas controls which fields are exposed.\n9. Soft-delete, and every other lifecycle stamp, is a nullable datetime (`archived_at`\u002F`deleted_at`\u002F`flagged_at`\u002F…), 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 changeset `put_change`s the timestamp, then `cast(attrs, [field])` so attrs can override, guarded by `validate_no_override\u002F2`. That guard is built on `validate_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.\n10. Context directory layout: `context.ex`, `supervisor.ex`, `events.ex`, `event_handler\u002F`, `services\u002F` (Service objects), schema files, and one directory per sub-module, each with its `query.ex`.\n\n### B. Ecto \u002F Query \u002F Repo\n11. Query modules `use MyApp.Query`, which gives `filtered_by\u002F2`, `ordered_by\u002F2`, `with_id(s)\u002F2`, `paginate\u002F4` and `count\u002F1`.\n12. 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\u002F3`, `join(q, :inner, [m], t in assoc(m, :thread), as: :thread)`, `select\u002F3`, `limit\u002F2`. Every function is then a single composable pipe step. **A join uses `assoc(m, :name)` whenever the schema declares the association**, which reuses its foreign key and conditions; an explicit `on:` is for a join with no association (computed or cross-schema). `from(...)` is reserved for the three things the pipe forms cannot express:\n    - **naming the root binding**: `from(t in Thing, as: :things)` for `base\u002F0`, or `from(q, as: :things)` inside a `has_named_binding?`\u002F`maybe_alias_*` guard;\n    - a **standalone subquery or `exists`\u002F`not exists`** expression (`subquery(...)`, `parent_as(...)`);\n    - an **`update:` or fragment atomic write**.\n\n    A table name inside a `fragment` string means the builder was skipped: write the subquery with `exists`\u002F`subquery` and `parent_as` over the schema, and keep in `fragment` only what the builder cannot express, such as a row comparison `(?, ?) > (?, ?)` or a cast (EP-K11).\n13. `import Ecto.Query`, and with it `where`\u002F`from`\u002F`order_by`\u002F`join`\u002F`preload`\u002F`lock`, appears **only** in `*\u002Fquery.ex` modules. Context and sub-modules pipe a schema through `Query.*` functions, then call `Repo.*`.\n14. Read chain: `Schema |> Query.filtered_by(args) |> Query.ordered_by(o) |> Query.paginate(...)` \u002F `Repo.one`.\n15. Read by id through a context getter (`get_*`\u002F`get_*!`). Callers outside the context use the getter and never `Repo.*`. Inside the getter, `Repo.get`\u002F`Repo.get_by` is fine; use `Schema |> Query.with_id(id) |> Repo.one` when you need the Query layer's standard filters, such as soft-deletes. Every `get_*`, 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 return `nil` (EP-A2, EP-C2).\n16. **Preloads are opt-in through the `:preloads` option**: a list of association atoms, default `[]`, so nothing is loaded unless the caller asks.\n    - A getter or list function reads `preloads = Keyword.get(opts, :preloads, [])` and threads it through **one** private `maybe_preload\u002F2` per module. Its `is_list` head `Enum.reduce`s the list, mapping each supported atom to a `Query.preload_\u003Cassoc>\u002F1` call (`:referrer, acc -> Query.preload_referrer(acc)`) with a `_, acc -> acc` fallthrough; a second head, `maybe_preload(queryable, _), do: queryable`, takes non-list input.\n    - `preload\u002F2` itself is called only in the Query module (#13), as chainable `preload_\u003Cassoc>\u002F1` functions. Atom names mirror association names; nested and keyword preloads are fine (`preload_driver\u002F1` → `preload(q, driver: :user)`). The function's `@doc` lists the supported atoms.\n    - **One query wherever a join can do it.** For a to-one association (`belongs_to`\u002F`has_one`), create the binding with `with_named_binding\u002F3`, wrapped in a chainable `with_\u003Cassoc>_binding\u002F1` helper, and `preload` off that named binding: one round-trip, and the join is reused if a filter already added it. A separate-query `preload\u002F2` is for the cases where a join is the wrong tool: a to-many association a join would multiply, or a `limit`ed or paginated query a join would break.\n    - **Gotcha:** when the result feeds a GraphQL or JSON field that reads the struct directly, with no field resolver, the caller passes the `:preloads` it needs, or the field is `%Ecto.Association.NotLoaded{}`.\n    - `reference.md` shows both modules.\n17. List queries paginate through `Query.paginate`.\n\n### C. Idiomatic Elixir\n18. **Dispatch by pattern matching**: function heads, guards, `case` and `with`, in place of `if\u002Felse`, and never `cond`. Map a result with `case` clauses or function heads that match its shape, such as `{:error, %Ecto.Changeset{errors: [{:referrer_id, {_, [{:constraint, :unique} | _]}} | _]}}`, not with an `if` on the contents of an error. `if` is for a simple boolean business decision only: it never dispatches on a type or a result, and never has an `else` returning a different shape. A branch driven by a boolean predicate becomes a private `maybe_\u003Cverb>\u002FN` with `true` and `false` heads, the boolean as the **last** argument (the subject leads), in place of a `case` on the boolean:\n\n    ```elixir\n    maybe_moderate(message, urls, skip_moderation?(message.body, urls))\n\n    defp maybe_moderate(%Message{} = message, _urls, true), do: {:ok, message}\n    defp maybe_moderate(%Message{} = message, urls, false), do: moderate(message, urls)\n    ```\n19. `with` for happy-path `{:ok, _}`\u002F`{:error, _}` chains; `else` only for error mapping.\n20. Be exhaustive in `case`\u002F`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.\n21. **Propagate fallible results.** When a function's final action is a fallible call (`Repo.insert\u002Fupdate\u002Fdelete`, `Oban.insert`, another `{:ok, _}|{:error, _}` function), it returns *that call's* result. Running it for effect and returning a literal `:ok` hides 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.)\n22. Tagged tuples `{:ok, _}`\u002F`{:error, reason}` for fallible functions; mutation resolvers wrap the value in a map (`{:ok, %{user: user}}`).\n23. Single level of abstraction: each function does one thing at one altitude, in about 10–30 lines, with its steps extracted into well-named `defp`s and no nested conditionals.\n24. Pipe two or more chained calls; a single call is written as a plain call.\n25. `alias`\u002F`import`\u002F`require`\u002F`@attr` at the top of the module only.\n26. Naming: predicates end in `?`, raising functions in `!`; snake_case functions, PascalCase modules, no abbreviations.\n27. `@impl true` on every behaviour, OTP and Phoenix callback.\n28. `@moduledoc` on every module (`false` for an internal one); `@doc` and `@spec` on the public API.\n29. `Ecto.Multi` for multi-step transactions; #55 says when one is required and which lock goes with it.\n30. Context function names: `list_*`, `get_*`, `create_*`, `update_*`, `delete_*`, `count_*`.\n31. JSON goes through the built-in `JSON` module (`JSON.encode!\u002F1`, `JSON.decode!\u002F1`, `@derive {JSON.Encoder, ...}`), never `Jason`.\n32. **Take an id, not a struct, when you only need the id.** A function that reads only `entity.id` accepts the bare id (a `binary`), 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)`, then `def f(id, x) when is_binary(id), do: …`.\n33. **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.\n34. **Read and write maps and keyword lists through their module functions**: `Map.get\u002F2,3`, `Map.fetch\u002F2`, `Map.fetch!\u002F2`, `Map.put\u002F3`, `Map.merge\u002F2`, `Map.update\u002F4`, … and `Keyword.get\u002F2,3`, `Keyword.fetch\u002F2`, `Keyword.fetch!\u002F2`, `Keyword.put\u002F3`, …, never bracket (`Access`) syntax such as `attrs[:x]` or `opts[:x]`, which returns `nil` for a missing key and breaks on structs. `fetch!` when the key must be present, `get\u002F3` with an explicit default when it is optional. Destructuring in a function head or a `with`\u002F`case` pattern (`def build(%{user_id: id, text: text})`) is as good and often clearer. Nested access still uses `get_in`\u002F`put_in`\u002F`update_in`.\n\n### D. GraphQL \u002F web layer\n\nWorked resolver, mutation type and GraphQL test: `graphql.md`.\n\n35. One schema per endpoint or audience (`\u002Fapi`, `\u002Fadmin`); shared types and middleware under `api\u002Fshared\u002F`.\n36. Naming: `MyAppWeb.Api.{Endpoint}.Resolvers.{Domain}.{Name}`, `.Schema.{Queries,Mutations,Types,Middlewares}.…`.\n37. Resolvers return tagged tuples and use `with` chains; authorization is middleware at the entry plus the resolver for business rules.\n38. Typed errors: `MyApp.Errors.*` with `use MyApp.ExErrors` + `defexerror`, returned as `{:error, Errors.X.new(...)}`, not as raw strings. **Define, then return**: the error module exists in the project (`lib\u002Fmy_app\u002Ferrors\u002F\u003Cname>_error.ex`) before any code returns it, so create `Errors.X` first 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 under `extensions.fields` beside `extensions.errorCode`.\n39. Global middleware `SafeResolution.apply(…) ++ [ErrorHandler]` normalizes errors to `extensions.errorCode`.\n40. Mutations use `payload field` with `input`\u002F`output`, and apply their auth middleware inline.\n41. Resolvers pass event metadata, `EventMetadata.build_opts(res)`, into context functions.\n42. Nested lists go through a Dataloader-backed connection (`Dataloader.Ecto`), so GraphQL has no N+1.\n\n### E. Events & workers\n43. Eventing is the **`ex_event_bus` hex dependency** (Oban-backed, exactly-once delivery). The bus module is `MyApp.EventBus` (`use ExEventBus, otp_app: :my_app`); events live in `MyApp.{Context}.Events` via `use ExEventBus.Event` + `defevents([...])`. Every `ex_event_bus` `use` macro **requires** its option (`otp_app:` or `ex_event_bus:`) and raises `ArgumentError` at compile time without it.\n44. Every domain create, update or delete emits on success: `Repo.insert\u002Fupdate\u002Fdelete(cs, success_event: Events.X, event_opts: opts)`, in a function that takes `opts \\\\ []`. `Repo` accepts `success_event:`\u002F`event_opts:` because it does `use ExEventBus.EctoRepoWrapper, ex_event_bus: MyApp.EventBus`; that wrapper publishes the event when the write succeeds.\n45. Handlers are `MyApp.{Context}.EventHandler.{Name}`: `use ExEventBus.EventHandler, ex_event_bus: MyApp.EventBus, events: [\"Elixir.MyApp.{Context}.Events.{Name}\"]` (both options required). They implement `handle_event\u002F1`, returning `:ok | {:ok, any} | :error | {:error, any}`, pattern-match the aggregate and changes (string keys, after the JSON round-trip), and enqueue work with `Oban.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 no `success_event:` (EP-H10).\n46. Handler supervision: `EventHandler` delegates `child_spec` to its `Supervisor` (`:one_for_one`).\n47. **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.\n48. Workers live in `lib\u002Fmy_app\u002Fworkers\u002F`: `use MyApp.Worker` + `use Oban.Worker, queue:, max_attempts:`, an `@impl` `perform(%Oban.Job{args: %{\"k\" => v}})` returning `:ok`\u002F`{:error}`\u002F`{:cancel}`\u002F`{:snooze}`, and `tags:`.\n\n### F. Testing\n\nDetail, worked tests and the reasons: `testing.md`.\n\n49. Case templates: `MyApp.DataCase` (contexts, changesets), `MyAppWeb.ConnCase` (HTTP), `*GqlCase` (GraphQL).\n50. Factories: ExMachina `{name}_factory`, `insert\u002F2` over `build\u002F2`, `sequence\u002F2` for uniqueness.\n51. Mocking: Mox with behaviours, `defmock` centralized in `test_helper.exs`, `setup [:set_mox_from_context, :verify_on_exit!]`.\n52. Event testing: `use ExEventBus.Testing, ex_event_bus: MyApp.EventBus` (the option is required) gives `assert_event_received(Events.X, args: …)`, `refute_event_received\u002F2`, `all_received\u002F1` and `execute_events\u002F0,1`. Events are Oban jobs on the `:ex_event_bus` queue, so `assert_event_received` is `Oban.Testing.assert_enqueued` underneath 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 with `execute_events(event_handler: MyApp.{Context}.EventHandler.{Name})`. Worker testing: `use Oban.Testing`, `perform_job\u002F2`, `assert_enqueued\u002F1`.\n53. **One `describe` per function, and one function per `describe`**, named `describe \"fun\u002Farity\"` after the function under test; every `test` inside exercises that function only, and all of a function's tests sit in its one `describe`. Tests read `test \"when \u003Ccondition>\"`. `async: true` for pure tests. GraphQL tests go through `query_gql(...)` + `load_gql_file`, and there the `describe` names the `.gql` file: one operation.\n54. **Self-contained tests**: everything that drives the assertion, the input data *and* the expected values, is visible in the `test` body. Build the entities under assertion inside the test, with the fields the assertion depends on passed explicitly and inline. `setup` is for harness wiring that is never asserted on: Mox mode, a `conn`, 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).\n\n### G. Concurrency\n55. **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.Multi` in a single `Repo.transaction\u002F1` (#29), in a Service (#4), with the `{:error, step, value, changes}` 4-tuple mapped back to `{:ok, _}`\u002F`{: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.md` gives the protection for each thing at risk (counter, upsert, state transition, `FOR UPDATE`, optimistic lock, advisory lock, claim row, Oban `unique:`), the lock order, how Services compose and how to test the invariant.\n\n### H. Change hygiene\n56. **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 -> x` is inlined at its lone call site and removed; a clause that became unreachable and an unused `@attr` are 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 in `defevents` that no `EventHandler` lists, a schema field that is only `cast` and written, a `def` or `defdelegate` no production code calls, a status string nothing writes and the clause that matches it — each ships with the change that reads it.\n\n### I. Application boundaries\n57. **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.\n    - **Another app's data arrives through its API or as an event.** There is no second `Repo` on 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.\n    - **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.\n    - **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.\n    - **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.\n\n### J. Comments & prose\n58. **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.\n    - **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 extracted `defp`.\n    - **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 `@moduledoc` or the PR description.\n    - **`@moduledoc`\u002F`@doc` stay mandatory (#28) and describe the contract**: what the function guarantees, its options, its return shapes. The `defp`s it calls and the queries it runs are implementation, and change while the doc does not. `@moduledoc false` is a complete doc for an internal module.\n    - **No structural or decorative prose**: no banner or section comments (`# ---- Helpers ----`), no `# TODO` for something doable in this change, no commented-out code (git keeps it, #56). In tests the `describe`\u002F`test` names are the documentation (#53); a comment explaining what a test checks means its name is wrong.\n\n    ```elixir\n    # Stripe redelivers webhooks for up to 3 days; `on_conflict: :nothing` makes a replay a no-op.\n    Repo.insert(changeset, on_conflict: :nothing)\n    ```\n\n### K. Documentation\n59. **Every PR ships its documentation**, describing the app *after* the change. `docs\u002FREADME.md` is the system map: every feature, and every edge between features. `docs\u002F\u003Ccontext>\u002F\u003Cfeature>.md` is 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. No `docs\u002F` diff and no such statement is an incomplete PR, exactly like a missing test. `docs.md` has the page skeleton, the writing rules and a worked page.\n\n### L. Guardrails\n\n60. **Green before done.** Before saying any Elixir work is finished, run `mix precommit` after your last edit and read its output; a red run is reported with that output, not summarised as done. An app with no `precommit` alias → run what it has (`mix format`, `mix credo --strict`, `mix test`) and say the app is missing guardrails; the `elixir-guardrails` skill installs them. No check covers Rule 0 or #59: English-only code and a behaviour change shipped without its `docs\u002F` change are caught only by reading, so read every diff for both.\n61. **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 `# >>> baseline` block of `.credo.exs` or of a `use Boundary`, `.dialyzer_ignore.exs`, `.sobelow-skips`), raised `--fail-above`, advisory ignore, `precommit` or 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 the `guardrails-changed` label 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.\n62. **Write code that passes the checks the first time.** Each item names the check that enforces it:\n    - `Task` only under a supervisor, `Task.Supervisor.async_nolink\u002F3`, and in LiveView `start_async\u002F3` with `handle_async\u002F3` (UnmanagedTask, MissingHandleAsync, SyncOverAsync).\n    - A `rescue` never discards the error: return `{:error, reason}`, re-raise, or log with the exception (SwallowingException; extends #20 and #21). The check only sees an explicit `try … rescue`, and Credo's PreferImplicitTry turns that into a function-level `rescue` it cannot see, so read every `rescue` you write or move.\n    - No blocking call (HTTP, `Process.sleep`, a slow query) inside a Plug's `call\u002F2` (BlockingInPlug).\n    - A `case` on `true`\u002F`false` (CaseTrueFalse) is fixed with a `maybe_*` helper (#18), never with the `if`\u002F`else` the check's message suggests.\n    - No `raw\u002F1` in a `.heex` file or a `~H` template (Sobelow XSS.Raw).\n    - Every test asserts an outcome, a value or stored state and not only `{:ok, _}`; every selector can fail; no `open_browser` is committed (VacuousTest, TestHasNoAssertions, WeakAssertion, AssertElementSelectorCanNeverFail, NoOpenBrowser; complements #53 and #54).\n    - Every LiveView assign is rendered (UnusedLiveViewAssign).\n    - No query per item and no missing preload: use #16's opt-in preloads (NPlusOneQuery, MissingPreload). Filter in the query, never with `Enum.filter` after `Repo.all` (InefficientFilter).\n    - Migrations: `create index(…, concurrently: true)` with `@disable_ddl_transaction true` and `@disable_migration_lock true`; no column type changed in place; backfills outside schema migrations (MigrationsSafety).\n    - No new compile-time dependency: no call to another app module in a module attribute or module body, no `import`\u002F`use` of an app module without a real need (xref compile-connected).\n    - Callers outside a context use its facade (#2). Boundary's `exports` enforce it at compile time; a new cross-context dependency goes in `deps:` and is justified by #47.\n    - Every `` `Mod.fun\u002Fn` `` in a `@doc` or `@moduledoc` exists (docs `--warnings-as-errors`).\n    - Public `@spec`s (#28) stay true; a Dialyzer warning is fixed, never silenced.\n\n### M. Migrations\n\n63. **A migration in `priv\u002Frepo\u002Fmigrations` is 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\n### N. The app's idioms\n\n64. **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!\u002F2`, which async tests override per process) rather than `Application.fetch_env!`; default an environment variable in `config\u002Fruntime.exs` the way the file already does (`String.to_integer(System.get_env(\"NAME\") || \"15\")`); name operations with the app's verbs (tokens are `issue_*`d where the app says so, EP-A2). Before writing a helper, find how two existing modules do the same job.\n",{"name":5,"description":7},"main","158b5fd99d588b223ab8b60b6e9e090ae46fc73e","plugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace","https:\u002F\u002Fgithub.com\u002Fcolette-club","www.colette.club","We are building the all-in-one app for seniors to help them age better and in a good health","2026-11-11 21:12:07",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add colette-club\u002Fcolette-marketplace --skill elixir-phoenix-conventions",{"tool":38,"command":39},"bunx","bunx skills add colette-club\u002Fcolette-marketplace --skill elixir-phoenix-conventions",{"tool":41,"command":42},"pnpm","pnpm dlx skills add colette-club\u002Fcolette-marketplace --skill elixir-phoenix-conventions","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002FSKILL.md",true,[46,52,56,60,64],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"concurrency.md","REFERENCE","参考文档",7960,"https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002Fconcurrency.md",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"docs.md",8188,"https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002Fdocs.md",{"path":57,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":58,"sourceHtmlUrl":59},"graphql.md",4260,"https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002Fgraphql.md",{"path":61,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":62,"sourceHtmlUrl":63},"reference.md",6144,"https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002Freference.md",{"path":65,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":66,"sourceHtmlUrl":67},"testing.md",5537,"https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Felixir-phoenix-conventions\u002Fskills\u002Felixir-phoenix-conventions\u002Ftesting.md",[69,76,83,90,97,104],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M75Y1B80BC78YKEE5XYJE2X9","flutter-conventions-guide","Team conventions for our Flutter apps. Use when writing or editing any `.dart` or `.arb` file.","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fflutter-conventions-guide\u002Fskills\u002Fflutter-conventions-guide\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M75Y19DXQ8T4DN7CRJMREWP5","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.","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-review\u002Fskills\u002Freview-report\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M75Y17GQ4D9F92VBH1TZNQQ0","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.","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-review\u002Fskills\u002Freview-passes\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M75Y1595YX4K87FVYGFWMKDH","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.","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-review\u002Fskills\u002Freview-companion\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M75Y13MCVKFKBXGF7VPVJ2F6","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.","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-review\u002Fskills\u002Fpr-description\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M75Y10EFJX8JSNXPZMPQ5WKS","engineering-principles","Language-agnostic engineering rules, cited by ID (EP-0 to EP-K11). Use when writing or reviewing code in any language.","https:\u002F\u002Fgithub.com\u002Fcolette-club\u002Fcolette-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fengineering-review\u002Fskills\u002Fengineering-principles\u002FSKILL.md",[],[]]