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

# Workflows

> A .nika file: schema · metadata · tasks. Parsed into a DAG, executed with structured concurrency.

What is a `.nika` file, and what happens when you run it?

A workflow is a YAML contract: identity, model, permits, tasks, outputs.
The engine admits it (`nika check` / the check inside `nika run`), then
executes the task graph. Four verbs only: `infer` · `exec` · `invoke` ·
`agent`. Fetching a URL is `invoke: { tool: "nika:fetch" }`, not a fifth
verb.

Qualified on `nika {STATUS.version} ({STATUS.engineSha})` with `mock/echo`
(a local simulation: output is prefixed `mock(echo) ·`):

```yaml theme={"system"}
# hello.nika
nika: hello
model: mock/echo
permits: {}
tasks:
  greet:
    infer:
      prompt: "Say hi in one line."
      max_tokens: 16
outputs:
  greeting: ${{ tasks.greet.output }}
```

```bash theme={"system"}
nika check hello.nika   # clean
nika run hello.nika --max-cost-usd 0
# said "mock(echo) · Say hi in one line."
```

Swap `model:` later for a local model, or a provider you have a key or a
signed-in agent app for ([Model and access](https://docs.nika.sh/concepts/providers.md#model-and-access)).
The file is the contract; `--var` and the SDK's `inputs` supply caller values.

> [!NOTE]
>
> Envelope law: [nika-spec 01-envelope](https://github.com/supernovae-st/nika-spec/blob/main/spec/01-envelope.md).
> [Live binary](https://docs.nika.sh/reference/status.md) is the implementation you download.

## Why the mark is the name (not a K8s envelope, not a version)

The envelope is **one header line** · `nika: <identifier>` — the language
name as the key, the workflow's own name as the value. Earlier drafts
explored a Kubernetes-style `apiVersion` + `kind` + `metadata` + `spec`
envelope, and until 0.108 the line read `nika: v1` with a separate
`workflow: { id }` object; the nine-key envelope (0.109) folded the identity
onto the mark and dropped the version: a grammar change ships with its
migration (`nika check --fix` moves the id, keeps the description as a
comment), so a version number the author types would carry no information.

* No separate `kind:` field: the presence of `tasks:` is itself the
  document-type discriminator. A `tasks:` key makes a workflow; its absence
  makes the project file (`nika.yaml`, whose `nika:` key is the project's
  name, for example `nika: my-project`; its schema version rides on the
  editor's `$schema` comment line). `nika: v1` is refused in both. The rule
  holds without the filename: a registry blob, an HTTP body, a stdin pipe
  still say what they are.
* The engine's internal canonical URI stays `https://nika.sh/spec/v1` for
  RDF / conformance tooling, but the author never types a URL.

A `.nika` file holds **one** workflow. Do not separate several with `---`:
0.124.1 reads only the first document and ignores the rest without a
warning, even an invalid one.

## Anatomy of a workflow

The workflow AST (`nika-schema::raw::RawWorkflow`) models exactly the
envelope's fields — nothing hidden, nothing extra:

| Field | Purpose |
| - | - |
| `nika` | The mark AND the name — a kebab-case identifier; the `tasks:` key below is the document-type discriminator. |
| `model` | Workflow-level default `<provider>/<name>` for `infer` / `agent` tasks. |
| `inputs` | **Value authority** · typed parameters the caller supplies at launch (`--var key=value`) · a deployment knob is an input with a `default:` · `${{ inputs.X }}`. |
| `const` | **Value authority** · named constants fixed in the file, never caller-supplied · `${{ const.X }}`. |
| `secrets` | **Value authority** · masked store references · `${{ secrets.X }}`. |
| `permits` | The declared capability boundary. Absent = **zero** authority; present = default-deny per category. |
| `run` | The run's entropy + clock declaration — randomness and time are declared, never ambient. |
| `tasks` | The DAG payload — a non-empty map, the key IS the task id. |
| `outputs` | The workflow's return contract. |

Nine keys, closed. The three value authorities are a **closed family**:
`inputs` · `const` · `secrets`. The pre-flip `vars:`, `env:` and `config:`
blocks are dead (`NIKA-VALUES-001` / `NIKA-VALUES-002` / `NIKA-PARSE-005`)
and no alias survives — each old use classifies into the authority its role
commands (a deployment dial becomes an `inputs:` entry with `required: false`
and a `default:`). The `workflow:` object, `types:`, `policy:` and `assert:`
left the envelope with the same release; every refusal names where the role
went (see the [reference](https://docs.nika.sh/reference/yaml-syntax.md#what-left-the-envelope-0-109)).
(The `env:` field *inside* an `exec:` block is a different thing and is
alive: it is the child process's environment map.)

<video autoPlay muted loop playsInline controls poster="/images/posters/spec-anatomy.png" aria-label="A .nika workflow dissected: its nine envelope keys light up one by one with the spec's own words, the four verbs fly to the tasks that bind them, nika check says run ready, and the file folds to a labelled skeleton" alt="A .nika workflow dissected: its nine envelope keys light up one by one with the spec's own words, the four verbs fly to the tasks that bind them, nika check says run ready, and the file folds to a labelled skeleton">
  <source src="https://mintcdn.com/supernovae-acdf3706/3tG2rJOQxMP3h2LO/videos/spec-anatomy.webm?fit=max&auto=format&n=3tG2rJOQxMP3h2LO&q=85&s=7678719c2863589ba1d1a3bbe3d8e455" type="video/webm" />

  <source src="https://mintcdn.com/supernovae-acdf3706/3tG2rJOQxMP3h2LO/videos/spec-anatomy.mp4?fit=max&auto=format&n=3tG2rJOQxMP3h2LO&q=85&s=336f9d9d870192c6224acd02be088043" type="video/mp4" />
</video>

**What a `.nika` file is made of.** One file that uses all nine envelope keys and binds each of the four verbs once. Every label is the specification's own wording, and the verdict is the real `nika check` of that exact file. *Labels and verdict captured on nika 0.121.0; the camera and the fold are illustration.*

## Parser internals (after the useful envelope)

Every field is span-carrying (`Spanned<T>`): source spans survive
all the way into the diagnostic layer (ADR-010 miette bridge). The
`RawWorkflow` AST matches the nine envelope keys — nothing hidden.

## Execution pipeline

```
         ┌───────────────┐
 .nika   │  nika-schema  │   RawWorkflow
  ─────► │     parser    │ ──────────────┐
         │ (marked-yaml) │               │
         └───────────────┘               ▼
                                 ┌────────────────┐
                                 │  nika-check    │   DAG · typed
                                 │    analyzer    │   scope · taint
                                 │ (`nika check`) │   permits · cost
                                 └────────────────┘
                                          │
                                          ▼
                                 ┌────────────────┐
                                 │  nika-runtime  │
                                 │  (L3 · live)   │
                                 │                │
                                 │ topo-sort ──►  │   ┌─ exec   L2
                                 │ dispatch  ──►  │   ├─ invoke L2
                                 │ events    ──►  │   ├─ infer  L2
                                 │ checkpoint ──► │   └─ agent L2
                                 └────────────────┘
                                          │
                                          ▼
                       journal (.nika/traces) · --json stream
```

ASCII by intent: Mintlify renders fine, but the diagram above is plain
text and pastes into terminals and issue trackers without a renderer.

## Tasks, edges, fan-out

`tasks.*` crosses a task boundary through exactly **two doors** — `with:`
(data) and `after:` (control) — and the engine computes the graph FROM
those doors: a `with:` binding referencing `${{ tasks.X.* }}` both names
the data the task consumes and declares a typed edge; an `after:` entry
(`{producer: predicate}`) orders on state and carries no data. There is no
third way to connect two tasks — `depends_on` is dead (`NIKA-PARSE-024` ·
`nika check --fix` migrates it). Nika builds the DAG, topologically sorts,
and runs tasks in parallel where the graph allows.

<video autoPlay muted loop playsInline controls poster="/images/posters/dag-execution.png" aria-label="nika inspect drawing a workflow as a graph, and nika check planning the waves it runs in" alt="nika inspect drawing a workflow as a graph, and nika check planning the waves it runs in">
  <source src="https://mintcdn.com/supernovae-acdf3706/3tG2rJOQxMP3h2LO/videos/dag-execution.webm?fit=max&auto=format&n=3tG2rJOQxMP3h2LO&q=85&s=babe822c70666ac5612e40f551945f59" type="video/webm" />

  <source src="https://mintcdn.com/supernovae-acdf3706/3tG2rJOQxMP3h2LO/videos/dag-execution.mp4?fit=max&auto=format&n=3tG2rJOQxMP3h2LO&q=85&s=0e0d73b344fb0209b8cbd27c7e0f0990" type="video/mp4" />
</video>

**A workflow is a graph.** `nika inspect` draws the tasks and edges of the built-in `pr-review-fanout` example; `nika check` plans them in waves, and tasks that share a wave run side by side. *Output captured from the real CLI on nika 0.121.0; the waves lighting up illustrate the plan, and nothing runs.*

```yaml theme={"system"}
tasks:
  fetch_data:
    invoke:
      tool: nika:fetch
      args:
        url: https://example.com/data.json

  analyze:
    with:
      data: ${{ tasks.fetch_data.output }}    # the binding IS the edge
    infer:
      model: ollama/<model>      # <provider>/<name>
      prompt: "${{ with.data }}"

  notify:
    with:
      analysis: ${{ tasks.analyze.output }}
    exec:
      command: ["echo", "${{ with.analysis }}"]
```

The task's **body consumes its bindings** (`${{ with.data }}`), never the
global `tasks.*` namespace: a reference outside the boundary is
`NIKA-VAR-021`, and `nika check --fix` hoists it into `with:` for you.

For an ordering with **no data** (run the deploy after the tests, consume
nothing), use `after:` — a map `{producer: predicate}` whose predicate
names the producer states that admit this task:

```yaml theme={"system"}
deploy:
  after:
    tests: success      # control edge · state, never data
  exec:
    command: ["./deploy.sh"]
```

The predicate set is **closed** (`NIKA-DAG-005` otherwise): `success` ·
`failure` · `skipped` · `terminal` · `unwind`. `terminal` admits any
terminal state, `cancelled` included (the always-pattern: « run once X is
settled, whatever happened »). The participial spellings `succeeded` and
`failed` are dead; `nika check --fix` respells them.

### Cleanup: unwind

`after: { x: unwind }` is the cleanup edge. The task runs once after a
producer that **started**, whether it succeeded or failed, and its body may
read that producer. A producer that never started unwinds nothing. It is not
the same as a `terminal` report task, which also runs after a producer that
was skipped or never ran:

```yaml unwind-cleanup.nika theme={"system"}
nika: work-with-cleanup
model: mock/echo
permits:
  tools: ["nika:assert", "nika:log"]
tasks:
  work:
    invoke:
      tool: nika:assert
      args:
        condition: false
        message: "the work failed"
  cleanup:
    after: { work: unwind }
    invoke:
      tool: nika:log
      args:
        level: info
        message: "cleanup ran"
```

The run fails (`work` failed, exit 1), and `cleanup` still runs and logs.
[Spec 03 · unwind](https://github.com/supernovae-st/nika-spec/blob/main/spec/03-dag.md)
has the full rule.

### Fan-in: group

Tasks that share a `group:` name can be read together: `${{ group.<name> }}`
in a `with:` value folds every member's record (`id`, `status`, `output`,
`error`, `duration_ms`) into one array.

```yaml group-fan-in.nika theme={"system"}
nika: probes
model: mock/echo
permits: {}
tasks:
  check_api:
    group: probes
    infer:
      prompt: "Is the API healthy?"
      max_tokens: 32
  check_db:
    group: probes
    infer:
      prompt: "Is the database healthy?"
      max_tokens: 32
  report:
    with:
      legs: ${{ group.probes }}
    infer:
      prompt: "Summarize these probe results: ${{ with.legs }}"
      max_tokens: 64
outputs:
  report: ${{ tasks.report.output }}
```

Fan-out over a collection (`files` here is a jq
[extract binding](https://docs.nika.sh/concepts/bindings.md) on `list_files`, e.g.
`extract: { files: 'split("\n")' }` — the collection crosses the boundary
through `with:`, then `for_each:` reads the binding):

```yaml theme={"system"}
analyze_each:
  with:
    files: ${{ tasks.list_files.files }}
  for_each:
    items: ${{ with.files }}
  infer:
    model: ollama/<model>        # <provider>/<name>
    prompt: "Review this file: ${{ item }}"
```

Conditional execution: `when:` is a **local business condition**, evaluated
*after* the gate admits the task. It reads local namespaces only (`inputs` ·
`const` · `secrets` · `with` · the `for_each` locals) — a `tasks.*` reference inside
`when:` is refused at parse time (`NIKA-VAR-021`): the binding creates the
edge, `when:` reads the binding.

```yaml theme={"system"}
deploy:
  with:
    passed: ${{ tasks.tests.output.passed }}
  when: "${{ with.passed == true }}"
  exec:
    command: ["./deploy.sh"]
```

`when:` evaluating `false` settles the task **`skipped`** (a decision —
downstream value edges pass, reading `null`), and the gate always applies:
`when:` refines it, never replaces it. To run a task *whatever happened*
upstream (the report / cleanup class), say it in the graph —
`after: { pipeline: terminal }` — and observe the outcome through
`with: { outcome: ${{ tasks.pipeline.status }} }` when the body branches
on it.

Retry on failure: `retry:` is the one shape (and `on_error:` catches
what retries can't fix):

```yaml theme={"system"}
flaky_api:
  invoke:
    tool: nika:fetch
    args:
      url: https://example.com/api
  retry:
    max_attempts: 5
    backoff_strategy: exponential
    jitter: true
```

> [!NOTE]
>
> Field names are the spec's: the map key is the task's identity (no
> `id:`/`name:` field), `when:` (not `condition:`), `with:`/`after:`
> (not `depends_on:`), `retry.max_attempts` (not `max_retries:`). The
> [JSON Schema](https://nika.sh/spec/v1/workflow.schema.json) rejects the wrong
> names at check time.

## Inputs · `inputs`

Workflow inputs live in `inputs:`, available in every task via
`${{ inputs.<name> }}`. Every entry is a **typed declaration** (`type:` is
required, and speaks the full type grammar): that is what lets the engine
validate what a caller passes, from `--var`, `--inputs-json -`, the SDK's
`inputs` or a `nika serve` job.

A value the caller may override belongs here — a deployment dial too, as an
input with `required: false` and a `default:`. A value the file owns and
nobody overrides is a `const:` entry; a credential is a `secrets:` reference.
Three authorities, one role each — pick by the role the value plays.

```yaml research-brief.nika theme={"system"}
# Bullet-point brief on a topic supplied at launch.
nika: research-brief

model: mock/echo                       # swap for ollama/qwen3.5:4b or any provider

inputs:
  topic:
    type: string                       # typed · validated + schema-gen
    required: true
    description: "Subject to research"
  bullets:
    type: integer
    default: 3

tasks:
  brief:
    infer:
      prompt: "Write ${{ inputs.bullets }} bullet points on ${{ inputs.topic }}."

outputs:
  brief: "${{ tasks.brief.output }}"
```

This file declares no `permits:` block and needs none: it runs zero shells,
touches no file, reaches no host. Every effect-bearing workflow carries one —
absent means **zero** authority, and the check refuses the body with
`NIKA-AUTH-006` before a single token is spent.

> [!NOTE]
>
> There is no `include:` / `import:` — a workflow never splices another
> file's text into its own. Reuse happens through **composition**: one
> workflow *calls* another as a typed, bounded step. See below.

## Composition: one workflow calls another

`invoke:` is a **tagged union**: exactly one of `tool:` (a builtin or an MCP
tool) or `workflow:` (another workflow). Same verb, same call site — the
field IS the semantics. There is no fifth verb and no `nika:*` builtin that
launches a workflow.

The child is an ordinary workflow. Nothing marks it as "a child":

```yaml word-count.nika theme={"system"}
# Count the words in a piece of text · the reusable child.
nika: word-count

inputs:
  text: { type: string, required: true }

permits:
  tools: ["nika:jq"]

tasks:
  count:
    invoke:
      tool: "nika:jq"
      args:
        input: { text: "${{ inputs.text }}" }
        expression: '{ words: (.text | split(" ") | length) }'
    returns:
      object:
        words: integer

outputs:
  words: "${{ tasks.count.output.words }}"
```

The parent calls it by **static path**, passes `args:` that fit the child's
`inputs:`, and reads the child's `outputs:` back as that task's output:

```yaml brief-with-stats.nika theme={"system"}
# Write a brief, then measure it by calling a child workflow.
nika: brief-with-stats

model: mock/echo

inputs:
  topic: { type: string, required: true }

permits:
  tools: ["nika:jq"]           # the child's tools, hoisted · see the boundary note

tasks:
  brief:
    infer:
      prompt: "Write three bullet points on ${{ inputs.topic }}."

  measure:
    with:
      body: "${{ tasks.brief.output }}"
    invoke:
      workflow: "./word-count.nika"
      args:
        text: "${{ with.body }}"
    returns:
      object:
        words: integer

outputs:
  brief: "${{ tasks.brief.output }}"
  words: "${{ tasks.measure.output.words }}"
```

```bash theme={"system"}
nika run brief-with-stats.nika --var topic="local-first AI"
```

### The rules the checker enforces

* **Static target** — `workflow:` is a static filesystem path. A
  `${{ }}`-templated target is refused (`NIKA-COMP-001`): a call graph you
  cannot draw before the run is a call graph you cannot bound. A
  `registry:` child is refused the same way in 0.124.1
  ([Known limits](https://docs.nika.sh/changelog/known-limits.md)).
* **Typed call** — the parent's `args:` must fit the child's `inputs:`, and
  what the parent declares in `returns:` must fit the child's `outputs:`
  (`NIKA-COMP-004`). The child's contract is *derived from its body*, never
  annotated twice.
* **Zero implicit authority** — a child never gains a capability its parent
  lacks (`NIKA-COMP-002`).
* **Acyclic** — a static cycle or self-launch is refused (`NIKA-COMP-003`).
* **Judged through the call** — the lethal trifecta (`NIKA-SEC-009`) and the
  consent law (`NIKA-SEC-014`) judge a call as the tasks its child stands
  for: a parent that reads private data and sends it out through a child is
  refused unless a blocking `nika:prompt` of its own gates the path, and a
  child the check cannot resolve counts as doing all of it
  ([Security](https://docs.nika.sh/concepts/security.md#the-trifecta-across-files-and-child-workflows)).

> [!WARNING]
>
> **The parent's `permits:` must cover the child's effects.** Authority flows
> down, never up: the child above invokes `nika:jq`, so the parent declares
> `nika:jq` too — drop it and the check fails `NIKA-COMP-002`. `nika check`
> reads the child, so it counts that entry as used: `NIKA-DRIFT-001` never
> tells you to remove a grant a child needs (its program, its tools, the files
> and hosts its own `permits:` lets it reach). A check of the source alone (an
> editor, the MCP `nika_check` tool) reads no child, and its `NIKA-DRIFT-001`
> makes no `permits:` claim on a file that calls one.

Each child keeps its **own** hash-chained trace; the parent's trace records
the child's outcome, so a run is a forest of chains rather than one flattened
stream. Full contract: [spec 14 · Composition](https://github.com/supernovae-st/nika-spec/blob/main/spec/14-composition.md).

### Supply values at launch · `--var`

`nika run` takes one `--var key=value` per input (repeatable):

```bash theme={"system"}
nika run research-brief.nika --var topic="local-first AI" --var bullets=5
```

Four rules govern the flag, and the file stays the contract — every input a
caller can pass is declared in `inputs:`:

* **A supplied value overrides a declared `default:`.** `--var bullets=5`
  wins over `default: 3` for this run.
* **It satisfies `required: true`.** A required input with no default must
  be supplied at launch. On 0.124.1, `nika check` stays clean and
  prints `HINT [inputs] required input(s) with no default · pass at run
  time: --var name=…`. `nika run` refuses before any task:
  `NIKA-1708 · missing required inputs` (exit 3). The SDK throws
  `NikaOperationError` with that code. This is admission, not a
  task-level `NIKA-VAR-001`.
* **The value parses as JSON when it parses.** `--var bullets=5` arrives as
  a number, `--var deep=true` as a boolean, `--var tags='["a","b"]'` as an
  array. Anything that does not parse as JSON rides as a string — no
  quoting gymnastics for the common case.
* **An unknown key is refused before the run**, with the declared set
  listed — a typo that silently did nothing would be the worst outcome:

```text theme={"system"}
$ nika run research-brief.nika --var topic=x --var oops=1
nika run: --var oops: unknown input — the workflow declares: topic · bullets
```

`--var` reaches `inputs:` and nothing else. A `const:` entry is immutable
across the run by construction and is never a launch flag; a deployment's
value is an input with a `default:`, so `--var` may still override it.

## Outputs and events

Every run writes its events, hash-chained, to a journal under
`.nika/traces/`. Add `--json` and `nika run` also prints one NDJSON object per
event on stdout, ending with a `run_settled` frame; without it, `nika run`
prints the human storyboard. `--output json` prints only the typed `outputs:`.
See [Events](https://docs.nika.sh/concepts/events.md) for the event model, [Traces](https://docs.nika.sh/concepts/traces.md)
for the journal, and [Bindings](https://docs.nika.sh/concepts/bindings.md) for how the DAG
propagates values.

> [!NOTE]
>
> The workflow grammar is implemented in the `nika-schema` crate (the
> envelope and its parser); `nika-check` runs the analyzer and semantic
> validation (type-checked bindings, secret-flow audit, cycle detection,
> permits and cost). That is exactly what `nika check` runs on your file.

## Read next

> [card] [Bindings](https://docs.nika.sh/concepts/bindings.md)
>
> Template expressions: `${{ }}` syntax, scopes, CEL + jq, taint.

> [card] [Events](https://docs.nika.sh/concepts/events.md)
>
> The typed event stream every run emits.

> [card] [Verbs](https://docs.nika.sh/concepts/verbs.md)
>
> The 4 verbs each task picks from.

> [card] [YAML reference](https://docs.nika.sh/reference/yaml-syntax.md)
>
> Full schema specification (generated from AST).


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