# Context management in workflows

Use context to supply workflow input and pass named results between steps. Each step can read the values produced by earlier steps in its sequence.

## What is context?

Context is a JSON object containing:

* **Input data:** Values supplied when the workflow starts.
* **Step outputs:** Results stored under each step's `output` name.
* **Iteration data:** `item` and `itemIndex` inside a Map step.

## Context structure

Output structure depends on the step type. Request results contain `status`, `data`, and `headers` directly. Agent results have their own `success`, `output`, and `metadata` fields.

```json
{
  "userId": "123",
  "user_data": {
    "status": 200,
    "data": { "name": "Alice", "email": "alice@example.com" },
    "headers": {}
  },
  "analysis": {
    "success": true,
    "output": { "sentiment": "positive" },
    "metadata": { "mode": "single" }
  }
}
```

There is no universal `success` or `output` wrapper added around every step result.

## How context evolves

### Initial context

For this execution request, the initial context is the supplied `context` object:

```json
{
  "steps": [
    {
      "type": "request",
      "output": "customer_data",
      "config": {
        "url": "https://api.example.com/customers/{{ customerId }}",
        "method": "GET"
      }
    },
    {
      "type": "request",
      "output": "order_data",
      "config": {
        "url": "https://api.example.com/orders/{{ orderId }}",
        "method": "GET"
      }
    }
  ],
  "context": {
    "orderId": "ORD-001",
    "customerId": "CUST-456"
  }
}
```

### After first step

The request result is stored directly as `customer_data`:

```json
{
  "orderId": "ORD-001",
  "customerId": "CUST-456",
  "customer_data": {
    "status": 200,
    "data": {
      "id": "CUST-456",
      "name": "John Doe",
      "email": "john@example.com"
    },
    "headers": {}
  }
}
```

### After multiple steps

The second result is added as `order_data`:

```json
{
  "orderId": "ORD-001",
  "customerId": "CUST-456",
  "customer_data": {
    "status": 200,
    "data": {
      "id": "CUST-456",
      "name": "John Doe",
      "email": "john@example.com"
    },
    "headers": {}
  },
  "order_data": {
    "status": 200,
    "data": { "id": "ORD-001", "total": 299.99 },
    "headers": {}
  }
}
```

A step without an `output` still runs, but its return value is not added to context.

## Accessing context data

### Using Morpher templates

Use `{{ }}` for both text interpolation and typed values:

```text
Customer: {{ customer_data.data.name }}
{{ order_data.data.total }}
{{ analysis.output.sentiment }}
```

Text surrounding a template makes the result a string. A field containing only one template preserves the value's type, so `"{{ order_data.data.total }}"` produces a number when the source value is numeric. Legacy `<< >>` expressions are not evaluated.

### Nested access

```text
{{ user.profile.address.city }}
{{ api_response.data.items[0].name }}
```

### With helpers

```text
{{ user.name | capitalize }}
{{ user.email | lower | trim }}
{{ items | join(', ') }}
```

Morpher supports paths and helper pipelines. Use a Rule step for comparisons; JavaScript expressions and method calls are not supported in templates.

### In Rule conditions

A condition's `source` is a path in context:

```json
{
  "source": "customer_data.data.tier",
  "filter": "EQUALS",
  "value": "premium"
}
```

## Context in different steps

### Map step

Each iteration receives the parent context plus `item` and the zero-based `itemIndex`. Nested steps execute sequentially within that iteration.

```json
{
  "type": "map",
  "output": "processed",
  "config": {
    "source": "products",
    "steps": [
      {
        "type": "request",
        "output": "enriched",
        "config": {
          "url": "{{ apiUrl }}/products/{{ item.id }}",
          "method": "GET"
        }
      }
    ]
  }
}
```

The Map result contains the complete context from every iteration, including parent data, `item`, `itemIndex`, and `enriched`. Read the first request's response body with `{{ processed[0].enriched.data }}`.

Every iteration starts with the same parent values. Outputs from one iteration are not available to another. By default, Map returns an array of iteration contexts. With `indexBy`, it returns an object keyed by the selected item property.

### Batch step

Batch child steps receive the same parent context. They cannot read one another's results. In `all` mode, their named results are collected in the Batch output:

```json
{
  "type": "batch",
  "output": "user_data",
  "config": {
    "steps": [
      {
        "type": "request",
        "output": "profile",
        "config": {
          "url": "{{ apiUrl }}/users/{{ userId }}/profile",
          "method": "GET"
        }
      },
      {
        "type": "request",
        "output": "orders",
        "config": {
          "url": "{{ apiUrl }}/users/{{ userId }}/orders",
          "method": "GET"
        }
      }
    ]
  }
}
```

Use `{{ user_data.profile.data }}` and `{{ user_data.orders.data }}` afterwards. Those child results are not added as top-level `profile` and `orders` keys.

With `failFast: false`, a failed child has an `error` string instead of its normal result. Inspect it before using that child's data.

### Rule step

Rule branches can read the parent context. The first matching rule executes its nested steps and returns their complete final context. If the Rule has an `output` name, that returned context is stored under it.

```json
{
  "type": "rule",
  "output": "features",
  "config": {
    "rules": [
      {
        "conditions": [
          { "source": "user.tier", "filter": "EQUALS", "value": "premium" }
        ],
        "then": [
          {
            "type": "request",
            "output": "selected_features",
            "config": {
              "url": "{{ baseUrl }}/features/premium",
              "method": "GET"
            }
          }
        ]
      },
      {
        "then": [
          {
            "type": "request",
            "output": "selected_features",
            "config": {
              "url": "{{ baseUrl }}/features/standard",
              "method": "GET"
            }
          }
        ]
      }
    ]
  }
}
```

Read the selected features with `{{ features.selected_features.data }}`. Nested outputs do not become top-level context keys.

If a rule's conditions do not match, evaluation continues to the next rule. A final rule without `conditions` supplies the fallback. An `else` attached to a conditional rule is ignored.

### Respond step

Respond can use all context accumulated in its sequence. It returns the configured HTTP response instead of adding an output:

```json
{
  "type": "respond",
  "config": {
    "status": 200,
    "body": {
      "success": true,
      "customer": "{{ customer_data.data }}",
      "order": "{{ order_data.data }}"
    }
  }
}
```

Place Respond in the top-level sequence or a Rule branch. Keep it outside Batch, which handles child errors internally and does not cancel parallel operations.

## Context scope rules

### Output names can be reused

A later output with the same name replaces the previous value, including an input value with that name. This is a top-level replacement, not a deep merge. Prefer distinct names when both values are needed later.

### Parent context access

Nested Map and Rule sequences receive a copy of the parent context. Their final context becomes their return value; it does not replace the parent automatically. Batch child results are collected under the Batch output.

### Steps execute sequentially

Within each sequence, a step can use input data and outputs from earlier steps. It cannot use outputs from steps that have not executed. Batch is the explicit parallel execution step.

## Best practices

* Use descriptive output names such as `customer_profile` and `payment_confirmation`.
* Check each handler's return shape before writing paths. Request results use `.data`; structured Agent results use `.output`.
* Keep output names distinct unless replacing an earlier value is intentional.
* Supply timestamps and calculated values in context when your workflow needs them; variables such as `currentTimestamp` are not injected automatically.
* Use `default(...)` when a missing value needs a fallback. A missing sole template otherwise returns `undefined`, and object fields with that result are omitted.
* Remember that Map and Rule results contain parent context too, which can make large nested results expensive to return.

## Debugging context

Return selected values with Respond while testing:

```json
{
  "type": "respond",
  "config": {
    "body": {
      "requestResult": "{{ customer_data }}",
      "agentResult": "{{ analysis }}"
    }
  }
}
```

Inspect the returned object before writing deeper paths. Request stores its response body at `customer_data.data`, without an `output` wrapper. Agent stores its structured result at `analysis.output`.

For equality conditions, match the type as well as the value: `EQUALS` uses strict equality, so numeric `200` and string `"200"` differ.
