Implements an automation slice (a processor that watches a TODO queue, calls an external system and records the result as our own fact) in Elixir with the FACT event store, from a slice.json
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Build Automation?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ortegacmanuel-build-automation)
---
name: build-automation
description: Implements an automation slice (a processor that watches a TODO queue, calls an external system and records the result as our own fact) in Elixir with the FACT event store, from a slice.json
---
# Build an automation slice
Written for **Datumo 0.6** (`{:datumo, "~> 0.6"}`). The framework's source is in
`deps/datumo/lib/datumo/`; its docs at https://hexdocs.pm/datumo.
> First, read the slice definition from `.slices/{Context}/{slicename}/slice.json` before doing anything else
> (in this kit, `.build-kit/.slices/…`). That file is the **source of
> truth**. Never invent fields that aren't there.
> **Comments**: every element carries `comments: string[]`. Use them as hints.
> If a comment raises an **open decision** rather than a hint — "rate limiting
> still undecided", "own stream or the main registry?" — don't decide it
> yourself: invoke `request-feedback`. Resolve the ones you consume:
> `POST <BASE_URL>/api/org/<ORG_ID>/boards/<BOARD_ID>/nodes/<nodeId>/comments/<commentId>/resolve`.
> And read `.build-kit/CLAUDE.md`. This slice shape deviates most from what the
> board appears to say, so those three rules matter double here.
---
## What an automation slice is
Nobody clicks anything. A processor watches a **TODO queue** — which is a read
model, not a table — does the work, and **writes a fact of our own**.
```
TODO queue (STATE_VIEW) → Processor (GenServer)
→ Task.Supervisor.async_nolink
→ external call
→ Context.execute(...) → Decide → event
```
Five files: the four of a write slice, plus `processor.ex`.
**Build the four first with `/build-state-change`**, then come back here for the
processor. This skill only covers what that one doesn't.
---
## Step 1 — The TODO queue is another slice, read through `pending/0`
`processors[].dependencies` points at a READMODEL that is the queue: the
board's `READMODEL → AUTOMATION` edge. It's a separate state-view slice, with
its own `slice.json`, and this slice doesn't build it.
**The queue is always read through `MyApp.Slices.<Queue>.Context.pending/0`**,
which returns a list of maps with the read model's fields. `/build-state-view`
gives every queue that function, so both sides agree on it whichever is built
first.
**If the queue slice isn't built yet, build this one anyway** — an unbuilt
dependency is never a reason to stop. Hold the queue as a value in the
processor's state (`Keyword.get(opts, :queue, Queue)`, Step 3), so this slice
compiles before the queue exists, and note in the progress log that it is
built against `<Queue>.Context.pending/0`. Until the queue is built, every poll
logs a warning; that's expected. The `:automation_queue` rule (`Datumo.Rules`)
checks the two agree as soon as both exist. Invoke `request-feedback` only if
the queue isn't on the board at all.
A TODO queue is "what was asked minus what was resolved": it folds the event that
opens the work and the one that closes it, and leaves out the ones already
closed. **It's a query, not a subtraction** — don't keep a counter.
---
## Step 2 — The anti-corruption layer, and which way it points
**The board has to name the external system.** The AUTOMATION's description says
what is called and with what (a mailer, an API, a file), or that it's a fake
(e.g. a mailer that only logs). If the slice doesn't say, don't skip the call:
build it as a fake that logs one line per call, and leave a comment on the slice
saying the external system is a fake until the board names it. A processor that
records our fact without making the call passes every scenario and does nothing.
When the slice calls an external system, the temptation is to model "we received
this". **Don't.**
> **Our domain fact leads and the external response fills it in**, not the other
> way round.
This isn't a style preference. If the event is "X's response minus some fields",
a change in X propagates through the whole system. If the event is our fact and X
is the input, a change in X only moves the mapping, in one place.
Concrete consequences:
- **One event, not two.** Don't emit an `XResponseReceived` alongside the domain
fact: "we received this" isn't a business fact, and giving it its own node
drags the foreign shape onto the timeline — which is exactly what an
anti-corruption layer prevents.
- **The raw body travels as a technical attribute** (`rawResponse`,
`technicalAttribute: true`) for forensics and for re-derivation. It is not
projected into any view.
- **Field names are domain names**, not the external API's. Never `risk_pcrop`:
`verdict`. Which layer measured it travels in a provenance field, not in the
name.
- **The event name's preposition matters.** `…EvaluatedWithX` says X computed and
we judged. `…EvaluatedByX` would say X made our judgement. The board already
chose: match it exactly.
### Where the source goes: in the name or in a field
| who judges | where it goes |
|---|---|
| a third party evaluates and returns a verdict | in the **event name** |
| we compute it ourselves against a file | in a **provenance field** (`dataVersion`) |
In the second case there is **no `source` field**: it would be a category error,
implying an external evaluator where there is none. And the provenance field is
self-describing — `"Provita ANP 2023-07-29"`, not `"2023-07-29"`.
#### If you compute against a file, the file is an interface
A data file you read at runtime is as much an external system as an HTTP API —
it has a shape you don't control, and it can drift from what your code expects.
The difference is that HTTP gives you a status code and a file gives you
`nil`.
**Never hand-write the fixture for a reader of a deployed artefact.** Derive it
from the artefact, and add a test that compares the two:
```elixir
test "the fixture's keys are the real file's keys" do
path = Application.get_env(:my_app, :layer, [])[:path]
if File.exists?(path) do
keys = path |> File.read!() |> Jason.decode!() |> ... |> MapSet.new()
assert MapSet.new(@keys_from_the_file) == keys,
"the deployed file changed vocabulary: #{inspect(MapSet.to_list(keys))}"
else
# A large artefact often lives outside the repo. Absent is not a failure.
assert true
end
end
```
The failure this prevents is worth spelling out, because it is quiet and it
passes review. A hand-written fixture asserts the reader against *itself*: both
sides of the test share the author's belief about the file's shape, so the test
proves the reader is self-consistent and proves nothing about the file. If the
belief is wrong, every test is green and every field comes back `""`.
Then watch where those empty fields go. If the write command validates required
fields — and it should — the command rejects, the item stays in the queue, and
**the automation silently never produces a result**. Worse, it usually splits:
the empty path (nothing found, no fields to fill) keeps working while the
populated path (something found) hangs. The half that works is the half nobody
was worried about.
And write the guard so it **skips** when the artefact is absent rather than
failing. A clean clone that doesn't ship a 30 MB layer is not a broken build.
### Translation happens inline
The board may show four or six slices for one external call (request → external
event → response view → translator → internal command → internal event). **In
code it's one processor that calls and records.** The model prioritises
conceptual clarity and making the system boundary visible; the implementation
prioritises not having handlers that do nothing.
If the external call were genuinely asynchronous — an inbound webhook — the entry
point is a **Phoenix controller**, not a processor. Use `/build-webhook`.
---
## Step 3 — `processor.ex`
**File:** `lib/my_app/slices/<slice>/processor.ex`
The processor is the only file in a slice that may name another slice: the
`Context` of its queue, of the slice whose command it issues, and of a view it
consults. Never a `Decider` or a `ReadModel`, never a struct. Whatever it reads from a view is not
in the command's append condition, so a rule that matters is checked again in
that command's `execute/2`.
```elixir
defmodule MyApp.Slices.<Slice>.Processor do
use GenServer
require Logger
alias MyApp.Slices.<Queue>.Context, as: Queue
alias MyApp.Slices.<Slice>.Context, as: <Slice>
# <the measurement that justifies it>
@poll_interval :timer.seconds(5)
# 1 unless there is evidence for more — see "How many at a time".
# <where the number comes from: none stated, so 1 | the board: "…" | the provider's docs: "…">
@in_flight 1
def start_link(opts), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
# The queue is held as a value, not called through the alias: the slice
# compiles before the queue slice exists, and a test can pass its own.
@impl true
def init(opts) do
if Keyword.get(opts, :start?, true), do: schedule()
{:ok, %{queue: Keyword.get(opts, :queue, Queue), in_flight: %{}}}
end
@impl true
def handle_info(:poll, state) do
schedule()
{:noreply, launch(state)}
end
# Tasks use `async_nolink`: their result and their crash arrive as messages,
# and you have to handle them or the GenServer fills up with unread mail.
def handle_info({ref, result}, state) when is_reference(ref) do
Process.demonitor(ref, [:flush])
state = %{state | in_flight: Map.delete(state.in_flight, ref)}
# A success pulls the next item at once; a failure waits for the poll.
{:noreply, if(result == :ok, do: launch(state), else: state)}
end
def handle_info({:DOWN, ref, :process, _pid, reason}, state) do
Logger.error("<slice> task failed: #{inspect(reason)}")
{:noreply, %{state | in_flight: Map.delete(state.in_flight, ref)}}
end
def handle_info(_other, state), do: {:noreply, state}
# Pure: whether one more item may start. Tested without the network.
def room_for?(in_flight, item_id) do
map_size(in_flight) < @in_flight and item_id not in Map.values(in_flight)
end
defp schedule, do: Process.send_after(self(), :poll, @poll_interval)
# An item not launched stays pending in the durable queue for the next poll.
defp launch(state) do
in_flight =
Enum.reduce(state.queue.pending(), state.in_flight, fn item, in_flight ->
if room_for?(in_flight, item.<id>) do
task = Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn -> process(item) end)
Map.put(in_flight, task.ref, item.<id>)
else
in_flight
end
end)
%{state | in_flight: in_flight}
rescue
e ->
Logger.warning("poll failed: #{Exception.message(e)}")
state
end
# :ok or :error — the processor needs to tell them apart (see above).
defp process(item) do
with {:ok, response} <- call_external(item),
{:ok, _id} <- <Slice>.execute(to_command(item, response)) do
:ok
else
error ->
Logger.error("<external> failed for #{item.<id>}: #{inspect(error)}")
:error
end
end
end
```
Non-negotiable rules:
- **The external call goes inside the `Task`, never in the `GenServer`.** A
`Req.post` in `handle_info` blocks the whole poll.
- **`start?: true` by default, configurable.** Switch it off in tests: a live
processor during the suite makes real network calls.
- **`Req`, never anything else.** With an explicit `receive_timeout` if the call
is slow.
- **Add it to the supervision tree** in `lib/my_app/application.ex`, after
`Fact.Supervisor` and `Task.Supervisor`, with
`Application.get_env(:my_app, :<slice>, [])`.
- **Secrets come from `config/runtime.exs`**, never from code. If the key is
missing, the processor should start and log the failure — not take down the
whole application's boot.
- **At most `@in_flight` calls at once, 1 unless there is evidence for more.**
See below. "As many as the queue holds" is never the answer.
### How many at a time
A processor that sweeps its queue on boot will fire **every pending item at
once**. That is the moment the limit of the external system shows up, and it
shows up in production, on a restart, when the queue happens to be deep.
Assume the service has a concurrency or rate limit **and that it is not
documented**. Most aren't. You find them by hitting them: a burst comes back
`429`, and the same call made alone succeeds — which is exactly the shape that
makes it look like the service is broken rather than that you are being rude.
So **the ceiling is 1 unless there is evidence for more**, and it's a module
attribute with a comment saying where the number came from. Evidence is one of
two things:
- **the board says so** — the AUTOMATION's description states a limit or a
volume that needs more ("up to 5 calls at a time", "the provider allows
10/s");
- **the external system documents it** — its rate or concurrency limit, cited
in the comment.
Without either, it's 1. Don't guess a higher number: a guess shows up as a
burst of `429`s on the first restart with a deep queue. If the volume clearly
needs more and nothing says how much, that's a decision for the board — ask
with `request-feedback`.
```elixir
# 1: neither the board nor the provider states a limit.
@in_flight 1
```
Then keep the rule in a **pure function**, so it can be tested without the
network:
```elixir
def room_for?(in_flight, item_id) do
map_size(in_flight) < @in_flight and item_id not in Map.values(in_flight)
end
```
Two things follow, and both matter more than the ceiling itself:
- **Don't build a second queue in memory.** You already have a durable one — the
TODO read model. An item you decline to launch stays pending there, so a
restart loses nothing and doesn't replay the burst. An in-memory backlog gives
up both properties.
- **On success, pull the next item immediately; on failure, don't.** Waiting for
the next poll after every success leaves the queue idle most of the time. But
chaining after a *failure* turns a rejected call into a tight loop against
someone else's API — let the poll interval be the backoff. This means
`process/1` has to return something that distinguishes the two; `:ok` for both
is a bug you won't see until you're the one being rate-limited.
### What a poll costs
`Queue.pending()` is a view, so every poll **reads the queue's whole history**:
every event that ever opened or closed an item, from position 1, folded from
scratch. The cost grows with the history, not with what is pending: a queue
with nothing to do still reads every item it ever did.
That is the right default. It keeps the queue a query with no state of its own,
so a restart, a crash or a redeploy can't make it forget or repeat anything.
And while the history is small, the read takes milliseconds.
Watch two numbers: how long one `pending()` takes, and the poll interval. When
the read becomes a noticeable fraction of the interval — or every processor
together keeps the store busy between polls — switch that one queue to
**reading from the last position seen**:
- the processor keeps, in its own state, the folded queue and the
`store_position` of the last event it folded;
- each poll reads only the events after it (`Fact.read/3` takes a
`position:` option) and folds them onto what it has;
- on start it has nothing, so the first poll reads everything, as today. A
restart costs one full read, not one per poll.
The queue stays a fold of the store; the processor only stops starting it over.
Don't do this up front, and don't do it by keeping a counter or a list of
"done" ids next to the store — that is the second queue the rule above forbids.
### The external system failing is a domain case
If `slice.json` models a failure event, emit it. If it doesn't, **log it and
leave the item in the queue** — don't invent a failure event: that's a modelling
decision, not an implementation one, and it belongs to the board.
And if the external system failing produces a **reassuring** result rather than a
visible error, say so in a one-line comment where it's handled. That's the class of
failure nobody discovers in time.
---
## Step 4 — Tests
**The processor isn't tested with the network.** What gets tested is its write
slice's `Decider`, via `/build-state-change`, plus:
- That the queue returns what's pending and **stops returning it** once resolved.
- The mapping from external response to domain fields, as a pure function. Pull
it out into its own function (`defp to_domain(response)`) precisely so it can
be tested without the network.
- **The decision of when to launch** — `room_for?/2` from Step 3. This is the one
people skip, because it is neither the mapping nor the write, so it falls
through the gap between them and ends up as the only untested logic in the
slice. It is also the logic that fails in production rather than in the suite.
Four assertions cover it: nothing in flight launches; something in flight
doesn't; the same item already in flight doesn't; releasing one makes room
again.
"Not tested with the network" means the *call* isn't tested. It does not mean
the processor is exempt. If a rule inside the `GenServer` can't be reached
without the network, that's a sign it should be a pure function, not a sign it
shouldn't be tested.
With `start?: false` in `config/test.exs` for this slice.
None of these is a board scenario, so they go in their own file with
`@moduletag :extra`, outside the default suite (`mix test --include extra`).
---
## Step 5 — Quality gate
```
mix precommit
mix test test/my_app/slices/<slice>/
```
---
## Final check against `slice.json`
- [ ] The four write files exist, built with `/build-state-change`.
- [ ] The queue is read through `<Queue>.Context.pending/0`, held as a value in
the processor's state (`alias …, as: Queue`), never called through the alias.
- [ ] **One domain event**, not a "response received" one.
- [ ] Field names are domain names, not the external API's.
- [ ] The raw body is a technical attribute and is **not** projected.
- [ ] The event name's preposition matches the board (`With…` / `By…`).
- [ ] The external call is inside the `Task`, not in the `GenServer`.
- [ ] All three task `handle_info` clauses are present (`{ref, _}`, `:DOWN`
normal, `:DOWN` with a reason).
- [ ] The processor is in the supervision tree and switched off in tests.
- [ ] Secrets come from `runtime.exs`.
- [ ] The response → domain mapping is a pure function and has a test.
- [ ] If the slice reads a deployed file: the fixture is derived from it, and a
guard test compares their vocabulary (skipping when the file is absent).
- [ ] The in-flight ceiling is a module attribute: 1, or more only with the
evidence (the board, or the provider's documented limit) cited in its
comment.
- [ ] The launch decision is a pure function and has a test.
- [ ] Declining to launch leaves the item in the durable queue — there is no
second queue in memory.
- [ ] `process/1` distinguishes success from failure, and only success chains
into the next item.