> Status: current
> Owns: the single cookbook dependency every service takes — parsing, validation, routing and template helpers re-exported under one name

<!-- BEGIN GENERATED: library-uniform — regenerate: npx oa-sync-template readme-uniform --all -->
Uniform: [library/orchestration](../conn-orch-validator/manifests/library.manifest.json)

Duty sections that apply:

- `all`: L-MAIN, L-ENGINES, L-TESTS, L-TEST-SCRIPT, L-PACK-TESTS, L-PINS, L-NO-FILE-RANGE, L-CHANGELOG, L-PACK-CHANGELOG, L-README, L-README-REGION, L-CONSUMER
<!-- END GENERATED: library-uniform -->

# @onlineapps/conn-orch-cookbook

> Cookbook toolkit for ALL services — one package that carries parsing, validation, routing and template helpers. It does **not** execute cookbooks.

## What this package is

`conn-orch-cookbook` is a thin wrapper: every implementation lives in the
`@onlineapps/cookbook-*` modules, and this package re-exports them under one
name so that every service — business services and infrastructure components
alike — depends on exactly one cookbook package.

### Who consumes it at runtime

`ServiceWrapper` injects this **whole module** as `config.cookbook` into
`WorkflowOrchestrator` (`shared/connector/service-wrapper/src/ServiceWrapper.js`,
`_initializeOrchestrator()` → `OrchestratorConnector.create({ cookbook: CookbookConnector, … })`),
and the orchestrator reads exactly three things off it
(`shared/connector/conn-orch-orchestrator/src/WorkflowOrchestrator.js`):

| Read | Where | What for |
|---|---|---|
| `createRouter` | the `WorkflowOrchestrator` constructor | publishing a step to the next service's queue |
| `validateCookbook` | `processWorkflowMessage()` | refusing an invalid cookbook before the step runs, on every message |
| `templateHelpers` | `_executeTemplateHelper()` | resolving `{{helper(...)}}` calls in step inputs |

Everything else this package exports is for direct use by tools that read or
check cookbooks (the validator, tests, scripts) — not for the workflow path.

### Execution has ONE owner

Cookbook execution belongs to `WorkflowOrchestrator` and to nothing else.
The second lane — `@onlineapps/cookbook-executor`, together with the
`createProcessor` factory and the `process` / `executeStep` / `executeWorkflow`
helpers built on it — was **deleted on 2026-08-31**; owner's decision, recorded
in `api/docs/governance/confirmations/cookbook-execution-owner.md` 001. It had
no runtime caller, and it disagreed with the orchestrator about what a cookbook
means, so keeping it meant two answers to one question.

The legacy OpenAPI-to-cookbook transformer (`CookbookGenerator`,
`ApiSpecAnalyzer`, `StepTranslator`, `ResponseMapper`, `createTransformer`) was
removed earlier, with the operations.json-first migration; cookbooks are
authored per biz-service against
[`registration-wire.md`](../../../docs/biz/30-operations/registration-wire.md) §3.

## 📦 Installation

```bash
npm install @onlineapps/conn-orch-cookbook
```

## 🔧 Quick Start

```javascript
const cookbook = require('@onlineapps/conn-orch-cookbook');

// Parse + validate an authored cookbook
const parsed = await cookbook.parseCookbookFromFile('./workflow.json');
cookbook.validateCookbook(parsed);
```

All exports are flat keys on the module — there is no `cookbook.executor` or
`cookbook.router` sub-object:

```javascript
const { CookbookRouter, createRouter, templateHelpers } = require('@onlineapps/conn-orch-cookbook');
```

## 📚 Included Modules

### 1. Core (`@onlineapps/cookbook-core`)
- JSON Schema validation
- Recursive step validation
- Parsing from file/object

### 2. Router (`@onlineapps/cookbook-router`)
- Service discovery
- Queue management (`createRouter` → `routeToService`)

### 3. Template helpers (`@onlineapps/cookbook-template-helpers`)
- The helper functions available inside `{{...}}` in step inputs
- Live example: `infra/api_doorman/static/cookbooks/tester-helpers.json`

## 📋 API Reference

### Parsing (from cookbook-core)
- `parseCookbookFromFile(path)` — parse from file (async)
- `parseCookbookFromFileSync(path)` — parse from file (sync)
- `parseCookbookFromObject(obj)` — parse from an in-memory object

### Validation (from cookbook-core)
- `validateCookbook(cookbook)` — validate the whole cookbook against the schema
  and cookbook-core's semantic checks, which include the `{{…}}` references in
  the fields the engine resolves (a root the step scope does not carry, a
  `steps.<id>` naming no step or skipping `output`, the epilogue failure outside
  the `compensationStep`) and the `global_error_handler` rules
- `validateStep(step)` — validate a single step
- `CookbookValidationError` — the error class all of the above throw
- `CookbookSchema`, `loadSchema()` — the schema itself

### Routing (from cookbook-router)
- `createRouter(mqClient, registryClient, options)` — factory used by the orchestrator
- `CookbookRouter` — one method, `routeToService(serviceName, message)`
- `ServiceDiscovery`, `QueueManager` — its two collaborators

Retry, DLQ, completion and step walking are NOT here: they belong to
`WorkflowOrchestrator` (confirmation
[`cookbook-execution-owner.md`](/api/docs/governance/confirmations/cookbook-execution-owner.md)
001), and the router's own copies of them were removed on 2026-09-02.

### Template helpers
- `templateHelpers` — the helper object `WorkflowOrchestrator._executeTemplateHelper()` looks a `{{helper(...)}}` call up in

### Version info
- `VERSION` — this package's published version, read from `package.json`
- `COMPATIBLE_FORMAT_VERSION`, `COMPATIBLE_SCHEMA_VERSION` — the cookbook FORMAT
  version (`'2.1.0'`), not the version of any package. `COMPATIBLE_FORMAT_VERSION`
  was called `COMPATIBLE_CORE_VERSION` until 2026-09-03; the old name read as
  "the cookbook-core version I am compatible with", which it never was (owner
  confirmation [`cookbook-format-constants.md`](/api/docs/governance/confirmations/cookbook-format-constants.md)
  001). No alias was kept.

Generated signature reference: [`API.md`](./API.md) (`npm run docs`).

## 📖 Cookbook Structure

### Basic Example (v2.1 Schema)
```json
{
  "version": "2.1.0",
  "api_input": {
    "customer": "ACME Corp",
    "amount": 1000
  },
  "steps": [
    {
      "step_id": "invoice_step",
      "type": "task",
      "service": "invoice-service",
      "operation": "createInvoice",
      "input": {
        "customer": "{{api_input.customer}}",
        "amount": "{{api_input.amount}}"
      }
    }
  ]
}
```

**A step has no authored `output` block.** `output` is a RESULT SLOT the
orchestrator writes: when the handler returns,
`WorkflowOrchestrator.processWorkflowMessage()` replaces the step with
`{ ...step, output: result, _execution: … }`. Anything an author put there is
overwritten, and it would never have resolved anyway — the reference resolver
runs over `step.input` (`_executeTaskStep()`), `step.iterator`
(`_executeForeach()`) and `switch.expression` (`_evaluateSwitchExpression()`)
only, and `response` is not a root of the step scope (the scope is the
`stepContext` `processWorkflowMessage()` builds; its roots are the norm's,
[variable-references.md](/api/docs/biz/40-cookbooks/variable-references.md)
§ Syntax). Since cookbook-core's static reference check, the validator refuses
such a reference in those fields before the step runs.

To hand a value to the client, name it in the top-level `delivery.output` block
below. That is where every live cookbook does it — `tester-delivery-webhook.json`,
`meditest-to-orion-grit-invoice.json` — and where a later step reads an earlier
one's result with `{{steps.<step_id>.output.<field>}}` in its own `input`.

## 📚 Step Types

The V2.1 schema defines five step types:

- **task** - Service operation execution
- **foreach** - Iteration over arrays
- **fork_join** - Parallel execution
- **switch** - Conditional branching
- **steps** - Nested workflows (replaces `sub_workflow`)

`wait` and `dispatch` are parked, not schema-defined — a step declaring either
type is rejected with `must match exactly one schema in oneOf`. See
[`format.md` § Parked](/api/docs/biz/40-cookbooks/format.md) and the register
[`parked-features.md`](/api/docs/architecture/parked-features.md).

## 📤 Delivery Block (v2.1)

Cookbook nově může definovat top-level sekci `delivery`, která popisuje způsob
doručení výsledku klientovi:

```json
"delivery": {
  "handler": "dispatcher",
  "allow_skip": false,
  "destinations": [
    {
      "type": "webhook",
      "url": "https://client.example.com/api/callback",
      "method": "POST",
      "retry": {
        "max_attempts": 5
      }
    },
    {
      "type": "public_url",
      "path": "result/${context.workflow_id}/invoice.pdf",
      "ttl_seconds": 86400,
      "access": "signed"
    }
  ],
  "output": {
    "workflow_id": "${context.workflow_id}",
    "invoice_id": "${steps.invoice_step.output.invoice_id}"
  }
}
```

- `handler`: `dispatcher` (výchozí), `service_step`, nebo `none`.
- `destinations`: konkrétní výstupy (`webhook`, `websocket`, `public_url`).
- `output`: mapování hodnot, které se mají doručit.

Detailní specifikaci vlastní
[Delivery Architecture § Cookbook delivery blok](/api/docs/architecture/delivery.md);
provozní pohled na službu je v
[API Delivery Dispatcher](/api/docs/operations/api-delivery-dispatcher.md).

## 🧪 Testing

```bash
npm test              # celá regrese balíčku — volá test:unit
npm run test:unit     # the same, explicitly (tests/unit/**)
```

Balíček má jediný tier: `tests/unit/**`. Integrační tier ani skript
`test:integration` zde neexistují — `npm test` tedy pouští úplnou regresi.

## ⚠️ Important Notes

### Cookbook format v2.1
The enforced format is **v2.1**. Versions 1.x and 2.0 are BANNED — the
validator rejects both by name before it looks at anything else
(`cookbook-core/src/parser/cookbookValidatorV2.js`).

**What v2.1 requires:**
- Keys are snake_case throughout the enforced schema.
- `steps` is an ARRAY, and every step carries `step_id` (the field 1.x called
  `id`). Nested steps are arrays too; `fork_join.branches` and `switch.cases`
  are objects keyed by branch/case name.
- A `task` step requires `step_id`, `type`, `service` and `operation`
  (schema `TaskStep.required`). There is no fallback to the step id: the
  orchestrator refuses a task step without an operation too
  (`WorkflowOrchestrator._requireStepOperation()`).
- A `switch` step does **not** have to declare `default`.
- There is no `queue` field; queue names come from the service, not the
  cookbook.

**Error handling — only the epilogue is live.** A cookbook may declare
`global_error_handler: { strategy: "compensate", compensationStep: "<step_id>" }`:
the step the engine runs when the run ends in DLQ or `declined`, with the
failure in `{{global_error_handler._failure.*}}` (owner decision
[`meditest-manual-trigger.md`](/api/docs/governance/confirmations/meditest-manual-trigger.md)
009). The validator refuses any other strategy and any `compensationStep` that
is not the last top-level step.

**What v2.1 does not carry:** per-step error handling (`on_error`), the
strategies other than `compensate`, `condition`, and the `wait` and `dispatch`
step types were PARKED out of the enforced schema — a step of either type is now
rejected. `retry` and `timeoutMs`/`timeout_ms` on a step (and `global_retry` /
`global_timeout` on the recipe) are not parked but refused by name since
`@onlineapps/cookbook-core` 8: a step's retry policy and attempt deadline are its
operation's `retry` / `timeout_ms` in `operations.json`, or the platform default. Their definitions are kept verbatim in
[`cookbook.v2.parked.json`](/api/shared/cookbook/cookbook-core/schemas/cookbook.v2.parked.json),
with the register
[`parked-features.md`](/api/docs/architecture/parked-features.md).

**Example v2.1 step:**
```javascript
{
  step_id: 'process_items',
  type: 'foreach',
  service: 'biz-hello',
  iterator: '{{api_input.items}}',
  body: [
    // nested steps; each iteration adds `current` and `index` to the context
    { step_id: 'echo_one', type: 'task', service: 'biz-hello',
      operation: 'echo', input: { text: '{{current}}' } }
  ]
}
```

A control-flow step names the service that executes it (`service` is required on
`foreach`, `switch`, `fork_join` and `steps`), and every step nested in it names the same
service — owner's decision
[`cookbook-execution-owner.md`](/api/docs/governance/confirmations/cookbook-execution-owner.md) 002.

The nested steps go in `body`, not `steps`: `WorkflowOrchestrator._executeForeach()` throws
`Foreach '<id>' invalid - Expected non-empty 'body' array` for anything else.
The live example is
[`infra/api_doorman/static/cookbooks/tester-foreach.json`](/api/infra/api_doorman/static/cookbooks/tester-foreach.json).

There is no `foreach.results` and no authored `output` here either. The step's
result is `{ type, step_id, count, iterations: [{ index, item, outputs }] }`
(the value `_executeForeach()` returns), where `outputs` is keyed by the nested
`step_id`.

The enforced contract is the schema itself —
[`cookbook.v2.schema.json`](/api/shared/cookbook/cookbook-core/schemas/cookbook.v2.schema.json),
the file Ajv compiles. Keys that used to be enforced and are no longer live
verbatim in [`cookbook.v2.parked.json`](/api/shared/cookbook/cookbook-core/schemas/cookbook.v2.parked.json)
with the register [`parked-features.md`](/api/docs/architecture/parked-features.md).

## 📄 License

PROPRIETARY - All rights reserved

## 🤝 Contributing

Internal package - contributions via internal GitLab only.

---
*For detailed documentation on individual modules, see their respective README files in the shared/ directory.*