> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nika.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# PR review fan-out

> T3 · engineering: one read-only review agent per changed file. A swarm with a leash.

> **T3 · engineering**: `for_each` + `agent:` is the swarm pattern.
> Every changed file gets its own mini-agent with **read-only tools**
> (default-deny means exactly that), a turn budget and a token budget.
> jq flattens the typed findings; one model writes the summary.

## The job

Big PRs get shallow reviews because attention doesn't scale. Here it
does: each changed file is reviewed in isolation by an agent that can
READ and nothing else, in parallel, four at a time. A deterministic
`nika:grep` sweep counts the TODO debt beside the LLM pass, and the
final REVIEW\.md ends with a verdict.

> [!WARNING]
>
> **Limit on macOS in 0.124.3.** The sandbox confines `exec: git` to the
> workflow's declared filesystem boundary, which grants no read of `.git`
> or of git's global configuration. The confined `git` exits with status
> 128, even inside a real repository, so `changed` takes its
> `recover:` value: no file reaches the swarm, no agent runs, and the
> summary says the diff was unavailable instead of calling the branch
> clean. See
> [Known limits](https://docs.nika.sh/changelog/known-limits.md#git-inside-a-workflow-is-refused-on-macos).

## The shape

```mermaid theme={"system"}
flowchart TD
  approve["approve · nika:prompt"]:::invoke
  changed["changed · git"]:::exec
  files["files · nika:jq"]:::invoke
  todo_sweep["todo_sweep · nika:grep"]:::invoke
  reviews["reviews · ∥ for_each · 2 tools"]:::agent
  merged["merged · nika:jq"]:::invoke
  summary["summary"]:::infer
  save["save · nika:write"]:::invoke
  approve --> changed
  approve -.->|success| changed
  changed --> files
  approve --> todo_sweep
  approve -.->|success| todo_sweep
  files --> reviews
  reviews --> merged
  changed --> summary
  merged --> summary
  todo_sweep --> summary
  summary --> save
  classDef infer fill:#5b8cff22,stroke:#5b8cff,color:#5b8cff
  classDef exec fill:#ff7a3c22,stroke:#ff7a3c,color:#ff7a3c
  classDef invoke fill:#22d3ee22,stroke:#22d3ee,color:#22d3ee
  classDef agent fill:#b07bff22,stroke:#b07bff,color:#b07bff
```

The graph starts with the human gate, then independent branches run in
parallel behind it. The agent fans out mid-graph, and the join waits
for both branches before `summary`.

## The file

```yaml pr-review-fanout.nika theme={"system"}
nika: pr-review-fanout

model: ollama/qwen3.5:4b   # local tool-calling model · swap for anthropic/claude-sonnet-4-6 for depth

const:
  base_ref: "main"
  review_root: "src/"      # the swarm's territory · keep in step with permits.fs.read

permits:
  # The argv form (`exec.command:`) runs one named program with its arguments
  # and no shell between them, which is what makes a program allowlist mean
  # something. A `exec.shell:` task is refused against a list — measured:
  # `NIKA-SEC-004 · a shell-string command cannot be verified against a
  # permits.exec program allowlist (a pipeline can launch any program) — use
  # the array form`. Only `exec: true` admits a shell, and this workflow
  # deliberately never needs one.
  #
  # An allowlisted program is not an unconfined one: `git` runs inside the
  # `fs:` boundary below, which is why the header's second `Needs ·` line is
  # about git's global config rather than about git.
  exec: ["git"]
  tools: ["nika:done", "nika:grep", "nika:jq", "nika:prompt", "nika:read", "nika:write"]
  fs:
    # `./src/**` covers the directory AND every descendant at any depth, which
    # is what both consumers need: `nika:grep` opens `./src` itself, and the
    # swarm reads files nested under it. A bare `./src` would cover only the
    # directory entry and refuse every file inside it.
    #
    # This bound is why `files` below filters the diff down to `const.review_root`:
    # `git diff` happily reports `Cargo.toml` or `.github/workflows/ci.yml`, and
    # an agent handed one of those would die `NIKA-SEC-004` mid-swarm. The claim
    # and the territory are kept equal on purpose.
    read: ["./src/**"]
    write: ["./REVIEW.md"]

tasks:
  # The human gate (NEP-0002 · v2.2). `git diff` output is UNTRUSTED
  # content — a hostile branch names its own files — and this workflow
  # pairs it with a private `fs.read` and egress-capable tasks: the
  # lethal trifecta, unless a human dominates the path. The gate comes
  # FIRST so every task the diff output reaches descends from it (a gate
  # on a sibling branch dominates nothing — the data edge would bypass
  # it), and each root CONSUMES the answer affirmatively (NEP-0020 — a
  # bare `after:` admits the refusal: it settles success with value
  # false). Under `--answer approve=true` the CI one-pass answers it here.
  # The gate declares no `default:` on purpose: a default would answer for
  # the human it exists to ask. The one hint `nika check` prints, [consent]
  # on `save`, is the checker unable to prove the answer reaches the write
  # through `summary`; it does, through `todo_sweep`, so a « no » closes it.
  approve:
    invoke:
      tool: "nika:prompt"
      args:
        mode: "confirm"
        message: "diff ${{ const.base_ref }}...HEAD and fan out one review agent per changed file?"

  # `--diff-filter=d` drops deletions: a file that no longer exists cannot be
  # reviewed, and asking an agent to read it just burns a turn on an error.
  changed:
    after: { approve: success }
    with:
      go: ${{ tasks.approve.output }}
    when: ${{ with.go == true }}     # « no » at the gate → no diff, no swarm
    exec:
      command: ["git", "diff", "--name-only", "--diff-filter=d", "${{ const.base_ref }}...HEAD"]
    on_error:
      # Not an empty diff: the notice carries no `src/` line, so the swarm
      # has nothing to review, and `summary` repeats it instead of a verdict
      # earned on files nobody read.
      recover: "diff unavailable: git failed or was refused. No changed files were collected."

  files:
    with:
      changed: ${{ tasks.changed.output }}
    when: ${{ with.changed != null && size(with.changed) > 0 }}  # a refused gate skips the diff (null) · an empty diff has nothing to split
    invoke:
      tool: "nika:jq"
      args:
        input: "${{ with.changed }}"
        expression: >-
          split("\n")
          | map(select(length > 0))
          | map(select(startswith("${{ const.review_root }}")))

  # The deterministic pass. Debt does not need a model to be found, and this
  # runs whether or not anything changed. It too descends from the gate —
  # dominance is structural: a sibling branch that bypasses `approve`
  # would re-open the trifecta no matter how clean its own content is.
  todo_sweep:
    after: { approve: success }
    with:
      go: ${{ tasks.approve.output }}
    when: ${{ with.go == true }}     # the same « no » closes this branch too
    invoke:
      tool: "nika:grep"
      args:
        pattern: "TODO|FIXME|HACK"
        path: "./src"

  reviews:
    with:
      files: ${{ tasks.files.output }}
    # « no » at the gate skips `files` (null), and a fan-out over null fails
    # (NIKA-VAR-006): the swarm closes instead.
    when: ${{ with.files != null }}
    for_each:
      items: ${{ with.files }}
      max_parallel: 4                    # four reviewers in flight · not forty
      fail_fast: false                   # one reviewer's bad day is not the swarm's
    on_error:
      recover: null                    # a budget-exhausted review yields null · filtered below
    agent:
      system: >-
        You are a precise code reviewer. Read the file, then finish with ONLY
        the schema'd object ({file, findings: [{severity, message, line}]} ·
        severity exactly one of blocker|high|med|low), then call nika:done.
      prompt: "Review ${{ item }} · bugs first, then risky patterns. Read it before judging."
      tools:
        - "nika:read"                  # read-only swarm · least privilege
        - "nika:done"
      max_turns: 6                     # read · think · answer · a little slack
      max_tokens_total: 30000          # per reviewer · the swarm's ceiling is this × the file count
      # `additionalProperties: false` on BOTH object nodes. Without it on the
      # inner one, a provider may add keys to a finding and the sort below is
      # ordering a shape that changed between runs.
      schema:
        type: object
        additionalProperties: false
        required: [file, findings]
        properties:
          file: { type: string }
          findings:
            type: array
            items:
              type: object
              additionalProperties: false
              required: [severity, message]
              properties:
                severity: { type: string, enum: [blocker, high, med, low] }
                message: { type: string }
                line: { type: integer }

  # The fan-in.
  #   `. // []`      · a clean diff SKIPS the swarm (an empty for_each resolves
  #                    null), and so does a « no » at the gate: the fan-in has
  #                    to survive its own good news.
  #   `select(. != null)` · the reviewers that recovered leave here, by value.
  #   `.findings[] + {file}` · flatten [[finding]] → [finding], each carrying
  #                    the file it came from.
  #   the rank object · `sort_by(.severity)` would be ALPHABETICAL, which puts
  #                    `low` above `med`. Severity order is a decision, so it is
  #                    written down.
  merged:
    with:
      reviews: ${{ tasks.reviews.output }}
    invoke:
      tool: "nika:jq"
      args:
        input: "${{ with.reviews }}"
        expression: >-
          (. // [])
          | map(select(. != null))
          | map(.findings[] + { file: .file })
          | sort_by({ blocker: 0, high: 1, med: 2, low: 3 }[.severity])

  summary:
    with:
      changed: ${{ tasks.changed.output }}
      merged: ${{ tasks.merged.output }}
      todo_sweep: ${{ tasks.todo_sweep.output }}
    when: ${{ with.todo_sweep != null && size(with.todo_sweep) > 0 }}  # skipped (null) or an empty sweep · no page to write
    infer:
      # a reasoning model needs 16384 here, or a documented run.reasoning.effort: low
      max_tokens: 2500                 # a review page · not the whole diff back
      prompt: |
        Changed files, or the notice that the diff was unavailable ·
        ${{ with.changed }}
        Merge these review findings into REVIEW.md · blockers first ·
        ${{ with.merged }}
        Open TODO debt found by grep ·
        ${{ with.todo_sweep }}
        End with a verdict · ship / fix-first / redesign. If the diff was
        unavailable, say so and invent no findings.

  save:
    with:
      summary: ${{ tasks.summary.output }}
    when: ${{ with.summary != null && size(with.summary) > 0 }}   # skipped (null) or an EMPTY answer · never a 0-byte REVIEW.md
    invoke:
      tool: "nika:write"
      args:
        path: "./REVIEW.md"
        content: "${{ with.summary }}"

outputs:
  diff:
    value: ${{ tasks.changed.output }}
    description: "The changed-file list, or the explicit notice that Git was refused"
  findings:
    value: ${{ tasks.merged.output }}
    description: "Every finding, blockers first, each attributed to its file"
  review:
    value: ${{ tasks.summary.output }}
    description: "The page a human reads · also written to ./REVIEW.md"
```

## How it works

**1. exec output becomes a collection**

`git diff --name-only` is a string; the jq `split("\n")` turns it
into the array the fan-out iterates. Workflows turn ANY tool output
into a collection this way.

**2. Each agent is least-privilege**

`tools: ["nika:read", "nika:done"]`: the reviewer can read source
and end its loop. It cannot write, fetch, or wander. Budgets
(`max_turns: 6`, `max_tokens_total: 30000`) bound the worst case.

**3. Typed findings merge deterministically**

Every agent returns `{file, findings[]}` per its schema. The jq
fan-in flattens and sorts: blockers surface first in REVIEW\.md.

## Constructs you just used

| Construct | Where | Reference |
| - | - | - |
| `for_each` + `agent:` | `reviews` | [The 4 verbs](https://docs.nika.sh/concepts/verbs.md) |
| default-deny `tools:` | `reviews.agent.tools` | [The 4 verbs](https://docs.nika.sh/concepts/verbs.md) |
| `agent.schema:` | `reviews` | [The 4 verbs](https://docs.nika.sh/concepts/verbs.md) |
| `nika:grep` sweep | `todo_sweep` | [Builtins](https://docs.nika.sh/reference/builtins.md) |

## Run it

> [!NOTE]
>
> **What it needs:** A Git repository with changes under `./src` and a `const.base_ref` that exists, plus a local model ([Ollama](https://ollama.com) serving `qwen3.5:4b`). Git is refused on macOS in 0.124.3, so there the diff is reported unavailable and no agent runs ([Known limits](https://docs.nika.sh/changelog/known-limits.md#git-inside-a-workflow-is-refused-on-macos)).

**1. Rehearse it**

```bash theme={"system"}
nika try pr-review-fanout
```

A mock model answers and nothing is written in your folder. It stops at the `approve` gate, as a real run does.

**2. Get your own copy**

Save the file above as `pr-review-fanout.nika` at the root of the repository you want reviewed. It reads no sample file.

**3. Check it, then run it**

```bash theme={"system"}
nika check pr-review-fanout.nika
nika run pr-review-fanout.nika --model mock/echo   # a mock model, no key
ollama pull qwen3.5:4b   # once, for the real run
nika run pr-review-fanout.nika
```

The run writes `REVIEW.md`.

It asks at the `approve` gate before anything else runs. On a terminal you answer; in a script it pauses (exit 4) and prints the `--resume` line that continues it, or you answer up front with `--answer approve=true`.

Any other model works: pass `--model <provider>/<name>` with its key, and cap a cloud model with `--max-cost-usd`.

## Make it yours

* Specialize the swarm: route `*.rs` files to a Rust-prompted agent and `*.sql` to a migrations-prompted one with two filtered fan-outs.
* Let reviewers read blame and history (still no write): declare a Git MCP server in `.nika/mcp_servers.json`, pin its tools with `nika mcp approve <server>`, and add its read tools to the agent's `tools:` and to `permits.tools`.
* Fail CI on blockers: end with `nika:assert` on `size()` of the blocker slice.

> [card] [Level up · T4 epic](https://docs.nika.sh/examples/deep-research-brief.md)
>
> Final tier: multi-stage pipelines. A plan, a budgeted agent, a
> synthesis, and human gates where effects begin.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.