> ## 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.

# How to write Nika

> The twelve patterns of well-written Nika: each one taught by a canonical example, each anti-pattern named.

Nika is a small language (4 verbs, 6
namespaces, one expression surface), so good Nika is mostly about
shape: where the determinism lives, where the model is allowed to
think, and how data crosses task boundaries. These twelve patterns
(plus the corpus-folding variant 5b) are how the 29
showcase workflows are written. Each links the canonical example that
embodies it. From an app, the same files run through
`@supernovae-st/nika` (`run()` admits, `run.result()` settles).

> [!TIP]
>
> The spec's normative cousin of this page is the
> [one-obvious-way table](https://github.com/supernovae-st/nika-spec/blob/main/spec/03-dag.md)
> (linter rules `one-obvious-way/002-007` + `/010` — `/001` is retired,
> rule ids are never reused). This page is the engineering judgment
> *around* those rules.

## 1 · Deterministic core, model at the edges

jq decides; the model explains. Anything that can be computed
(filtering, sums, diffs, ranking) happens in `nika:jq` or a data
builtin, deterministically and for free. The model gets the jobs only
a model can do: judgment, language, synthesis.

```yaml theme={"system"}
# ✅ jq filters · the model only explains what survived
urgent:
  with:
    tickets: ${{ tasks.triage.output.tickets }}
  invoke:
    tool: "nika:jq"
    args: { input: "${{ with.tickets }}", expression: 'map(select(.urgency == "critical"))' }
explain:
  with:
    urgent: ${{ tasks.urgent.output }}
  when: ${{ size(with.urgent) > 0 }}
  infer: { prompt: "Explain these critical tickets · ${{ with.urgent }}" }
```

**Anti-pattern** · asking the model to « pick the urgent ones » from a
list it already returned typed. You pay tokens for worse determinism.

Taught by · [Price watch](https://docs.nika.sh/examples/price-watch.md) (zero model calls) ·
[Config drift sentinel](https://docs.nika.sh/examples/config-drift-sentinel.md) ·
[ETL quarantine](https://docs.nika.sh/examples/etl-quarantine.md).

## 2 · Parallelism is the default · edges are the only ordering

Tasks with no edge between them run together. Don't serialize out of
habit: a `with:` binding IS the data edge (data and dependency are one
declaration) and an `after:` entry is the control edge — the engine
computes the graph from those two doors and schedules the waves. The
DAG has no invisible edges: a `tasks.*` reference outside the boundary
is `NIKA-VAR-021` (the fix is machine-applicable — hoist into `with:`).

**Anti-pattern** · a linear chain of tasks that never read each
other's output. That is wall-clock spent on nothing.

Taught by · [Standup digest](https://docs.nika.sh/examples/standup-digest.md) ·
[Social repurpose](https://docs.nika.sh/examples/social-repurpose.md) (the diamond) ·
[CEO Monday brief](https://docs.nika.sh/examples/ceo-monday-brief.md) (3-branch gather).

## 3 · Type the boundaries

Every place data crosses from a model into the deterministic world gets
a contract: `schema:` on `infer`/`agent` (the model must return that
shape), `nika:validate` for second opinions, `nika:assert` as the hard
gate. Enums kill « kinda-strong » ratings.

**Anti-pattern** · prose in, prose out, regex in the middle. If a
downstream task indexes into a field, the producer needs a schema.

Taught by · [Meeting actions](https://docs.nika.sh/examples/meeting-actions.md) ·
[Contract guard](https://docs.nika.sh/examples/contract-guard.md) (schema + validate + assert,
belt-and-braces) · [Support triage](https://docs.nika.sh/examples/support-triage.md) (enums).

## 4 · Fan out with a leash

`for_each` over a runtime collection is the power move. The leash lives
*inside the block* (`items` · `max_parallel` · `max_items` ·
`fail_fast`) — a bare `${{ }}` after `for_each:` is `NIKA-PARSE-019`, and
knobs as task siblings are `NIKA-PARSE-005`. Bound `max_parallel`
(providers rate-limit, GPUs thrash), cap the count with `max_items` (a
longer collection fails the task before its first item, `NIKA-VAR-006`,
never a silent truncation), set `fail_fast: false` (collect errors
instead of aborting the batch) and give each iteration its own `retry`
and `timeout`.

**Anti-pattern** · an unbounded fan-out against a rate-limited API, or
leaving `fail_fast` on its default (true) for a batch where one bad
item is normal.

Taught by · [Competitor radar](https://docs.nika.sh/examples/competitor-radar.md) ·
[Localization factory](https://docs.nika.sh/examples/localization-factory.md) ·
[Resume screener](https://docs.nika.sh/examples/resume-screener.md).

## 5 · Plan, then execute

For open-ended work: a fast model writes a typed plan, an `agent:`
executes it under budgets, a thinking model synthesizes. Three stages,
three cost profiles, every intermediate auditable on disk.

**Anti-pattern** · one giant agent loop with no plan, no budget and no
typed output. Nothing about it can be audited or bounded.

Taught by · [Deep research brief](https://docs.nika.sh/examples/deep-research-brief.md) ·
[Corpus digest](https://docs.nika.sh/examples/corpus-digest.md).

## 5b · Context folding · fresh windows over a folded corpus

The corpus-scale variant of « plan, then execute »: when the input is
too big for one window, never let any window hold it. A fast pass plans
a focus per unit **from identifiers alone** (paths, titles, ids · never
contents), a `for_each` wave processes each unit in its **own fresh
window** (one slice, one focus, zero history), jq merges and ranks the
typed results deterministically, and the synthesis reads only that
deck. The corpus lives in the dataflow; window size stops scaling with
corpus size, and the deck in `outputs:` is an audit surface: everything
the synthesis saw, nothing it didn't.

Two disciplines make the fold sovereign. The discovered collection is
the spine · model assignments join it by key, so a hallucinated
identifier drives nothing. And the per-unit schema carries **no
identifier** · transpose re-attaches identity, so a model cannot
misfile its own result.

**Anti-pattern** · concatenating the corpus into one prompt and asking
for a summary. Past a few documents you pay more for worse recall, and
nothing in the middle was actually read.

Taught by · [Corpus digest](https://docs.nika.sh/examples/corpus-digest.md) ·
[Localization factory](https://docs.nika.sh/examples/localization-factory.md) (the mechanical
fold · no plan stage).

## 6 · Three gates, three meanings

* `when:` · the **skip** gate. Routing, not failure (skipped ≠ failed).
* `nika:assert` · the **fail-fast** gate. The run is wrong, stop loudly.
* `nika:prompt` · the **human** gate. Blocks until a person decides.

Pick the gate that matches the meaning. A workflow that sends drafts
without a `prompt` gate, or claims success without an `assert`, is
promising more than it checks.

**Anti-pattern** · a `tasks.*` status test inside `when:` as a plain
success gate. That form is refused (`NIKA-VAR-021`): the gate
lives on the edges — a value edge already admits on `{success, skipped}`,
and `after: { a: success }` is the strict form. `when:` decides
*business* conditions on local values, post-gate.

Taught by · [Invoice chaser](https://docs.nika.sh/examples/invoice-chaser.md) (human gate) ·
[Incident war room](https://docs.nika.sh/examples/incident-war-room.md) (assert refuses
optimistic postmortems) · [Release train](https://docs.nika.sh/examples/release-train.md)
(all three in one file).

## 7 · Sovereignty is a `model:` line

Sensitive data (contracts, CVs, medical, financial) runs on a local
provider, `ollama/…` or `lmstudio/…`. Same file shape, zero cloud. The
18 canonical providers make this a one-line decision,
not an architecture meeting.

Taught by · [Contract guard](https://docs.nika.sh/examples/contract-guard.md) ·
[Resume screener](https://docs.nika.sh/examples/resume-screener.md).

## 8 · Agents get budgets, tools get grants

`agent:` is default-deny: no `tools:` means no tools at all. Grant the
minimum (`nika:read` + `nika:done` makes a read-only reviewer), cap
the loop (`max_turns` · `max_tokens_total`), and let `nika:done` end
it cleanly.

**Anti-pattern** · `tools: ["nika:*", "mcp:*/*"]` on an agent that
only needed to read. Least privilege costs one line less.

Taught by · [PR review fan-out](https://docs.nika.sh/examples/pr-review-fanout.md) (the
read-only swarm) · [Code review](https://github.com/supernovae-st/nika-spec/blob/main/examples/06-code-review.nika)
(foundation).

## 9 · Evidence always lands · `unwind` and `terminal`

Two predicates, one rule. **An `after: {…: unwind}` task** is per-task
cleanup: it runs once its producer has *settled*, whatever happened
(success, failure, timeout, mid-flight cancel), and it is the only task
allowed to read that producer's record while siblings may still be
running — `graph_format: 3` projects it as a `finally` node. **A
terminal `after: {…: terminal}` task** is the always-pattern: it runs
once its producers settle, whatever happened — `terminal` admits every
terminal state (success · failure · skipped · cancelled). Pair it with a
`.status` observation in `with:` when the body branches on the outcome.
Cleanup is a task joined by `unwind` (the old `on_finally:` list inside a
task body is gone); the record that must land at 3am belongs to a
terminal task.

Taught by · [Incident war room](https://docs.nika.sh/examples/incident-war-room.md) ·
[Release train](https://docs.nika.sh/examples/release-train.md) (the departure record is an
`after: { live: terminal }` task: it lands even when the train aborts).

## 10 · One data language · jq, once

`extract:` bindings, `nika:jq`, the fan-in zip (`transpose`), the
state diff: all of it is the same jq. Don't invent per-task string
parsing and don't ask the model to reshape JSON. One transform
language is already there.

Taught by · [Localization factory](https://docs.nika.sh/examples/localization-factory.md)
(the transpose zip) · [ETL quarantine](https://docs.nika.sh/examples/etl-quarantine.md)
(group\_by accounting).

## 11 · Workflows are callable · type the `outputs:`

A workflow with typed `outputs:` is a building block: another workflow
(or a human, or CI) consumes a contract, not a log. Name what comes
out, type it, describe it.

Taught by · [Deep research brief](https://docs.nika.sh/examples/deep-research-brief.md)
(`{brief, sources}`) · [Schema retry](https://github.com/supernovae-st/nika-spec/blob/main/examples/04-schema-retry.nika)
(foundation · the typed-outputs shape).

## 12 · Mock-first · runnable with zero keys

`model: mock/echo` makes a workflow CI-runnable and demo-safe. Write
it mock-first and swap the provider when it ships. Every example in
this documentation that can run without keys does.

**Anti-pattern** · a workflow you can't validate without spending real
tokens. The conformance gate runs every example on every push, and
yours should pass the same way.

Taught by · the whole [examples pack](https://docs.nika.sh/examples/overview.md), and the
[state-file pattern](https://docs.nika.sh/examples/release-radar.md) makes even stateful
workflows replayable.

***

## The shape of a well-written file

```yaml the shape · illustration, not a runnable file theme={"system"}
# one honest sentence about the workflow · prose lives above the mark
nika: kebab-case-name         # the mark AND the name · one line

model: mock/echo              # mock-first · sovereignty is one line away

inputs:                       # typed · what the CALLER supplies · a deployment dial is an input with a default
const:                        # fixed in the file · the destinations the boundary pins
secrets:                      # env- or file-backed · never inline

permits:                      # the blast radius · absent = zero authority

tasks:                        # the DAG · true dependencies only ·
  # deterministic core (jq · builtins) · model at the edges ·
  # gates that match their meaning · leashed fan-outs · budgeted agents

outputs:                      # the callable contract · typed
```

***

## Four recipes the patterns compose into

The twelve patterns are the values; these are the moves you reach for when a
real integration pushes back. Each is canonical in the spec: linked, not
improvised. The YAML below is **fragments** — paste them into a nine-key
file with `permits:` covering the tools they reach.

### Poll until ready

`retry:` fires on errors, never on values, so make « not ready » an error
*inside* the task. A jq-mode fetch whose program errors on the pending shape
turns polling into typed, bounded retry:

```yaml theme={"system"}
await_export:
  invoke:
    tool: "nika:fetch"
    args:
      url: "https://api.example.com/jobs/${{ inputs.job_id }}"
      mode: jq
      jq: 'if .status == "done" then . else error("not ready") end'
  retry:
    max_attempts: 20
    backoff_strategy: fixed
    backoff_ms: 30000          # every 30s · 20 attempts · 10-minute ceiling
```

Bounded, deterministic, zero LLM. There is no `retry_when:`: `retry:`
fires on errors only (`on_codes:` narrows which ones), so a value you want
to wait on has to become an error, as above.

### Diamond join

Two exclusive `when:` branches, one consumer. A skipped branch's output is
**defined `null`** (never an error), so the join is one jq filter:

```yaml theme={"system"}
pick:
  with:                          # value edges pass on skipped · the skipped one reads null
    prod: ${{ tasks.build_prod.output }}
    dev: ${{ tasks.build_dev.output }}
  invoke:
    tool: nika:jq
    args:
      input: [ "${{ with.prod }}", "${{ with.dev }}" ]
      expression: "[ .[] | select(. != null) ] | first"
```

### Fan-out that survives partial failure

A failed iteration contributes `null` at its index: positions stay aligned
with the input. Recover per-iteration when a placeholder is acceptable,
filter downstream. The same `on_error: recover:` mechanism also degrades a
single task to a declared fallback — the run completes and the output says
what it is:

```yaml theme={"system"}
scrape_all:
  with:
    pages: ${{ tasks.discover.output.pages }}
  for_each:
    items: ${{ with.pages }}
    max_parallel: 5
    max_items: 50                    # a longer list fails before the first fetch
    fail_fast: false
  on_error: { recover: null }        # this iteration yields null · the batch lives
  invoke:
    tool: "nika:fetch"
    args: { url: "${{ item }}", mode: article }

digest:
  with:
    scraped: ${{ tasks.scrape_all.output }}
  invoke:
    tool: nika:jq
    args:
      input: ${{ with.scraped }}
      expression: "[ .[] | select(. != null) ]"   # the survivors · order preserved
```

<video autoPlay muted loop playsInline controls poster="/images/posters/on-error-recover.png" aria-label="A missing live feed absorbed by on_error recover: the run finishes on cached data and its trace records the failure" alt="A missing live feed absorbed by on_error recover: the run finishes on cached data and its trace records the failure">
  <source src="https://mintcdn.com/supernovae-acdf3706/3tG2rJOQxMP3h2LO/videos/on-error-recover.webm?fit=max&auto=format&n=3tG2rJOQxMP3h2LO&q=85&s=4a0d463ace232b1a73927492fe396d57" type="video/webm" />

  <source src="https://mintcdn.com/supernovae-acdf3706/3tG2rJOQxMP3h2LO/videos/on-error-recover.mp4?fit=max&auto=format&n=3tG2rJOQxMP3h2LO&q=85&s=8e3c97c62100cac7283fc1d27c1a4561" type="video/mp4" />
</video>

**Resilience you declare.** The live rates feed is missing, so `on_error: recover:` hands the next task yesterday's cached rates instead. The run still finishes (exit 0), its output says it is stale, and the trace records the failure it absorbed. *Captured from the real CLI on nika 0.121.0, offline.*

### Matrix expansion

A matrix is precomputed data, not control flow. Build the product with jq,
fan out over it:

```yaml theme={"system"}
build_matrix:
  invoke:
    tool: nika:jq
    args:
      input: { os: ["linux", "macos"], ver: ["18", "20", "22"] }
      expression: "[ .os[] as $o | .ver[] as $v | {os: $o, ver: $v} ]"

test_all:
  with:
    matrix: ${{ tasks.build_matrix.output }}
  for_each:
    items: ${{ with.matrix }}
    max_parallel: 3
  exec:
    command: ["./test.sh", "--os", "${{ item.os }}", "--node", "${{ item.ver }}"]
```

Include/exclude rules are jq filters on the product: no second syntax to
learn.

> [card] [See every pattern live](https://docs.nika.sh/examples/overview.md)
>
> The examples gallery: 29 real jobs, every construct taught,
> every file conformance-validated.


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