# Working in this codebase

A starting rulebook for a Phoenix + Ash application. Replace `MyApp`,
`MyAppWeb` and `my_app` with the project's names, keep the sections that apply,
and delete the rest. These rules describe how an Ash codebase is shaped and how
to prove work is done; when one of them and the surrounding code disagree, the
code is the better guide.

## Ground rules

- **When a rule and the surrounding code disagree, the code is the better
  guide**: say so, rather than silently picking one. Conventions exist to
  describe reality, and reality wins.
- **Never commit or push without being asked.** Commit locally, on the current
  branch, only when the user says so.
- **Commits are Conventional Commits**: `type(scope): summary`, lowercase,
  no trailing period, no `Co-Authored-By` or AI-session trailers. One logical
  change per commit, one concern per pull request: if a branch grows a second
  concern, split it.
- **Before claiming done, get a clean result** (reading the real exit code,
  never piping it away) from the format, compile, lint and test commands the
  project defines (in an Ash project: `mix format`, `mix compile
  --warnings-as-errors`, `mix credo --strict`, `mix test`).
- **Zero compiler warnings.** CI compiles with `--warnings-as-errors`, so a
  warning is a failure, not a nit.
- **No debugging artifacts** in committed code: no `dbg/1`, no `IO.inspect`,
  no `IEx.pry`, no `FIXME`. Ever.
- **Never commit a secret**, including in tests, fixtures, compose files and CI
  config. A secrets scan runs in CI.
- **Run every mix command through the toolchain.** Pin the Erlang/Elixir
  toolchain (`mise.toml`), load the environment (`direnv`), and route commands
  through it. A plain `mix` against the wrong OTP thrashes `_build`. Never
  inline environment variables.
- **`mix format` decides formatting.** Never hand-align code, DSL blocks or
  markup: the formatter is opinionated (it reorders resource block order and
  `.heex`); that is by design. Let it.
- **No `@spec`.** Add a custom `@type` only when it genuinely aids clarity.
- **Check the library documentation before building custom glue.** When a
  problem looks like it needs an ad-hoc helper (error remapping, hand-rolled
  validation plumbing, bespoke queries), read the library docs and `deps/`
  first. There is almost always a first-class option. Custom solutions are the
  last resort, only after the library option is ruled out.
- **Ship vertical slices** end to end, committed atomically.

## The call path

Every read and write follows one route, and the layers are not interchangeable:

```
UI (LiveView / controller / worker)
  → domain code interface   MyApp.<Domain>.<function>(..., scope: scope)
    → resource action       create/read/update/destroy/action
      → changes · validations · preparations · calculations · policies
```

Outside a resource's own internals, **never call `Ash.read/create/update/
destroy/get/…` against a resource module.** Direct `Ash.*` data calls belong
only inside the owning domain's directory. If the UI needs something no code
interface exposes, **add the action and its `define`**; don't reach around
the domain. The one routine exception is enrichment: fetch through the
interface, then `Ash.load/2`.

## Domains and code interfaces

- A parent module sits **beside** its child directory, never inside it:
  `MyApp.<Domain>` is `lib/my_app/<domain>.ex` next to `lib/my_app/<domain>/`.
  Cross-cutting infrastructure lives in top-level namespaces outside `MyApp`,
  mapped one-to-one onto directories (`Apis.*` in `lib/apis/`, and so on).
- Register the domain in `config :my_app, ash_domains` with `otp_app:` set. A
  domain missing from that list still compiles, but its Oban triggers never
  register: `otp_app:` is what turns that silent runtime hole into a compile
  error.
- **Always pass `action:` explicitly** on a `define`; never rely on the default.
- **Name the function from the caller's point of view.** Action names are
  written from inside the resource and are terse (`:search_by_name`); the
  exported function re-adds the resource noun (`search_events_by_name`).
- Optional `args:` go last, as `{:optional, :name}`.
- Every non-embedded resource belongs to **exactly one** domain. Only embedded
  resources are exempt.
- **Authorization lives on resources, not domains**: a domain body holds
  `resources do` and nothing else.
- Add `extensions: [AshPhoenix]` to any domain whose resources back forms.
- A plain public function on a domain is acceptable only for logic belonging to
  no single resource action. Keep it rare.

## The actor

The scope struct carries actor, tenant and locale together, and implements
`Ash.Scope.ToOpts`.

- **From the web layer, pass `scope: scope`**; never hand-assemble
  `actor:`/`tenant:` there, or you will drop the tenant or the locale.
- **Inside domain internals, workers and reactor steps**, pass `actor:`
  explicitly. Background work gets a real actor or an interaction context; it
  never bypasses policies.

## Resources

- Keep to the fixed block order, which the formatter enforces: `postgres` ·
  `actions` · `policies` · `changes` · `validations` · `multitenancy` ·
  `attributes` · `relationships` · `calculations` · `identities`.
- `uuid_v7_primary_key :id` first, then attributes, then timestamps.
- Keep `defaults` to the CRUD verbs that genuinely need no customisation;
  hand-write anything with arguments, changes or hooks.
- **Name read actions by intent, not by filter mechanics**: `search_by_<fields>`
  for paginated list screens, `get_by_<field>` (`get? true`) for single-record
  lookups, `list_for_<parent>` for scoped collections. Put a read action's own
  `prepare build(load: ..., sort: ..., limit: ...)` inside it rather than
  making every caller remember.
- **Add `require_atomic? false`** to any `update`/`destroy` that uses
  `manage_relationship`, a custom change module, or an inline change with
  lifecycle hooks.
- **Attributes are private by default.** Only set `public?: true` when the
  attribute is actually exposed through the web layer; don't blanket-mark new
  fields public.
- **Every enum-valued attribute gets its own `Ash.Type.Enum` module**; don't
  inline a list of atoms as a constraint.
- Declare relationships with explicit intent: every `belongs_to` states
  `allow_nil?`, and `on_delete:` is spelled out in the `references` block
  rather than left to the default.
- Model structured repeated values as **embedded resources**
  (`data_layer: :embedded`); lifecycle state with **AshStateMachine** rather
  than a bare status attribute plus ad-hoc guards; secrets at rest with
  **AshCloak** rather than encrypting by hand.
- Scope org-owned resources with attribute **multitenancy**, paired with a
  policy; multitenancy narrows queries, it does not authorize them.

## Calculations

- **A calculation is the default tool for derived values.** One that is
  computable from columns goes inline as `expr(...)` so it stays filterable and
  sortable in SQL; anything larger becomes a module under
  `lib/my_app/<domain>/calculations/<snake_name>.ex`. Reach for a plain module
  only when a calculation genuinely cannot express the logic, and even then it
  is called **through the domain**, never from the UI.
- **Declare data dependencies explicitly** with `load/3`, and verify them. A
  calculation that reads an unloaded relationship is a bug that only appears on
  some call paths.
- A runtime `calculate/3` **returns exactly one entry per input record, in
  order**: build it with `Enum.map(records, …)` and nothing that can reorder or
  drop.
- If a runtime calculation must hit the database, rebuild call options from its
  context with `Ash.Context.to_opts(context)` so the actor and tenant travel
  with it.
- Don't introduce an `aggregates do` block where the codebase has none, without
  a reason worth stating in the commit message.

## Authorization

- Every data-layer resource gets `authorizers: [Ash.Policy.Authorizer]` and a
  `policies` block; prefer the built-in checks (`actor_attribute_equals/2`,
  `expr(<fk> == ^actor(:id))`, `relates_to_actor_via/1`).
- **`authorize?: false` is banned in `lib/`.** Enforce it mechanically with a
  Credo check so the build fails on it (Stepp uses
  `Llamex.Check.NoAuthorizeBypass`, RedirRocks
  `TechForge.CredoChecks.Ash.NoAuthorizeFalse`); add one if the project has
  none. For unattended writes with no user actor, authorize against a **named
  private-context flag** policy; never widen a policy to cover one flow.
- **Tests do not get to bypass policies either.** A test that only passes
  because authorization was switched off is not exercising the code that
  ships. Give the scenario a real actor holding the rights it needs;
  `authorize?: false` only where there is genuinely no other way, with a
  comment saying what it is.
- Gate UI affordances on the generated `can_<code_interface_name>?` predicates
  instead of re-deriving permissions in the template.

## External service seams (`Apis.*`)

Model every third-party integration as an Ash seam: a domain of **virtual
resources** (`use Ash.Resource`, no data layer) whose actions do the raw work,
so business logic depends on a mockable boundary, not a module of functions.
Virtual resources key on the provider's own string IDs, not `uuid_v7`.

- Put the HTTP plumbing in one `Apis.<Service>.ApiRequest` client: `base_req/0`
  returns a preconfigured `Req.new`, shared helpers handle errors.
- An action pipes the standard Req flow and matches the real return:

```elixir
ApiRequest.base_req()
|> Req.post(url: "/path", json: payload)
|> handle_response()

defp handle_response({:ok, %Req.Response{status: s, body: b}}) when s in 200..299,
  do: {:ok, build(b)}
defp handle_response(other), do: ApiRequest.error(other)
```

- Map every non-2xx response and transport failure onto shared typed errors
  (`BadRequest`, `Unauthorized`, `RateLimited`, `ServiceUnavailable`,
  `Network…`), centralised in `ApiRequest`, not repeated per action.
- Tests mock the seam (`Req.Test.stub/2`, or Mimic for module-level stubbing),
  asserting on the request the code actually sends.

## Background jobs

- Workers live at `lib/my_app/<domain>/workers/<verb_noun>.ex` as
  `MyApp.<Domain>.Workers.<VerbNoun>`.
- **When the background work *is* an Ash action, declare it in the resource's
  `oban do` block** (`triggers`) rather than hand-writing a worker. Enqueue
  from inside an `after_action` hook, normally via a dedicated
  `Changes.<Verb>` module.
- **Treat `args` as plaintext JSON in Postgres: pass identifiers only**, never
  payloads or secrets.
- **Make `perform/1` safe to re-run.** Every attempt may be a retry: guard
  state transitions on the record's current state rather than assuming the
  initial one.
- Test workers with `use Oban.Testing, repo: MyApp.Repo`.

## Schema changes

- **Change the domain, then the resource, then generate**
  (`mix ash.codegen <change_name>`); apply with `mix ecto.migrate`.
- **Never hand-edit a generated migration; regenerate it.** Editing breaks
  Ash's snapshot tracking. The exception is a `backfill_*` data migration,
  hand-written and sequenced after the structural one.

## Web layer

- **Never define `render/1` on a LiveView**: colocate markup in a sibling
  `.html.heex`.
- Name modules from the feature, not the file:
  `MyAppWeb.Live.<Feature>.<Index|Form|Show>`.
- Compose from existing primitives before hand-rolling markup; check for a
  component before writing one, and register app-wide components centrally so
  templates need no import. Compute derived values before the `~H` sigil and
  fold them in with `assign/2`.
- **Generate every internal path with `~p`**, never an interpolated string.
  Express per-page prerequisites (load-this-record-or-redirect, feature flags,
  wizard steps) as their own hook module returning `{:cont, socket}` or a
  redirect, not as repeated `mount/3` code.
- **Every page must work on a phone.** Style mobile-first; give layouts that
  cannot shrink an explicit small-screen form rather than letting the page
  scroll sideways. Keep tap targets finger-sized. Check a narrow viewport
  before calling UI work done.
- **Keep list-page state in the URL.** Search, filters and pagination belong in
  query params; `AshPhoenix.LiveView.page_from_params/2` derives the page.
- Browser-side behaviour goes in `assets/js/hooks` attached with `phx-hook` on
  an element with a stable `id`, fed through `data-*` attributes.
- **Wrap every user-facing string in the project's i18n front-end** — `~t`
  (MF2) or `gettext/1`, whichever the app standardises on, in domain code as
  much as in web code. Keep user-facing wording out of the domain and worker
  layers: return machine-readable reasons (`{:error, :no_codes}`) and let the
  web layer choose the words.

### Forms

- Build from the domain's generated `form_to_<action>` interface, harden with
  `AshPhoenix.Form.ensure_can_submit!/1`, and wrap in `to_form/1` inside a
  private assign helper.
- Edit nested relations with `AshPhoenix.Form.add_form/3` / `remove_form/2`
  driven by dedicated `"add-<child>"` / `"remove-<child>"` events.
- Serve create and edit from a single `Form` LiveView routed at both
  `/<things>/new` and `/<things>/:id`.

### UI craft

UI work runs through the **Impeccable skill**: load its context first (product
and design docs, incumbent tokens and components), let the incumbent visual
world govern the change (refine, never redesign), and verify the real surface
at desktop and mobile before calling it done.

## Testing

- Mirror the `lib/` tree: `lib/<path>/<name>.ex` is tested by
  `test/<path>/<name>_test.exs`; default new test files to `async: true` and
  choose the case module by what the code actually touches.
- **Build every persisted record through a generator** built on
  `Ash.Generator`, via code interfaces, with a real actor and
  `authorize?: true`. Don't hand-roll fixtures.
- Feature tests use **PhoenixTest** (`visit`, `fill_in`, `click_button`,
  `assert_has`), not `Phoenix.LiveViewTest`. Select by semantic tag plus text
  or real form labels, never brittle CSS paths; authenticate with a `log_in_user`
  helper, never by driving the sign-in UI.
- Don't test private functions; exercise behaviour through the public interface.
  Unit-test change and validation modules as plain modules with no database.
- Assert on Ash failures by pattern-matching the error struct (errors carry no
  meaningful `.message`). Never compare a `:ci_string` directly to a binary, and
  `require Ash.Query` before using query macros.
- Test external clients at their seams, not over the network.
- Give resources whose policies matter their own `<resource>_policies_test.exs`,
  asserting with the generated `can_<code_interface_name>?` predicates; for role
  matrices, hold shared actors in a named setup under a `:users` key.
- Observe database state through Ash, never through the Repo directly.
