# Application Manifest Guide

These instructions apply to the current Admin Console.

Use `manifestVersion: 0` and give the Application an `application.id`. Keep the files the manifest reads inside its directory or a subdirectory. The CLI looks for `contextual.yaml` in the current directory. Use `--file path/to/contextual.yaml` to select another location.

## Choose what the Application manages

An entry's key gives it a name inside the manifest, such as `products` in `objectTypes.products`. The resource ID identifies what deploy reads or writes on the tenant. Two Applications that define the same kind of resource with the same ID can overwrite each other's changes when they deploy to the same target.

| Section | What deploy does |
| --- | --- |
| `objectTypes` | Creates or updates the Object Type from its `definition` file. An entry with only `id` requires that type to exist on the target. Optional `data` seeds missing rows by primary key. |
| `records` | Looks up a record by its Native Object URI. The record can already exist on the target or be a row this deployment seeds. |
| `connections` | Creates or updates a Connection from its `definition` and optional `secrets` bindings. The Connection's identity on the target is its `apiId`. |
| `flows` and `agents` | Saves the definitions. Set an Agent's `flow` to `!ref flows.<key>.id` to bind it to the Flow version deployed on that target. |
| `workers` | Creates or updates a Worker from a Compose file, an image, a local Docker build, another Worker's image (`imageFrom`), or a managed template (`template`). Set `size` or `resources` and include the full intended configuration. Omitted settings on a Worker save take their platform defaults. |

## Reference resources

If a Service or another pipeline manages a resource, use an `objectTypes` entry with only `id` for an Object Type, or a `records` entry with `uri` for a record such as a Connection. These lookups leave the resource in place. The [Service example](https://docs.contextual.io/build/applications/examples.md#deploy-alongside-an-existing-service) uses both forms.

Use one of these forms for `records.<key>.uri`.

| Look up | URI |
| --- | --- |
| By primary ID | `native-object:<type>/<id>` |
| By primary ID at a specific version | `native-object:<type>/<id>#<version>` |
| By a named key and its value | `native-object:<type>/<keyName>/<keyValue>` |

For a Connection, use `native-object:api-configuration/<apiId>`. An unversioned primary-ID URI can also reference a row from the Application's seed data. The CLI binds that reference after the data step confirms the row exists.

Use `!ref <section>.<key>.<field>` as the whole value of an environment entry for a Worker or Agent, or inside a managed-template Worker's `options`. For example, `!ref objectTypes.products.id` supplies an Object Type ID. With a named-key record lookup, use fields such as `uri` or `keyValue` because the alias has no `id`. In an Agent's `flow` setting, use `!ref flows.<key>.id` to bind a Flow from the manifest.

An unscheduled Compose Worker with one public service has an `origin`. The [two-Worker example](https://docs.contextual.io/build/applications/examples.md#deploy-two-workers-from-one-manifest) uses `!ref workers.api.origin` to pass that URL to another Worker.

## Write definition files

A `definition` path points to a JSON or YAML file containing the platform record or Object Type definition, without server-assigned metadata. Put per-stage values on the manifest entry for an Object Type, Flow, or Agent. A Connection definition can use `${var.name}` in string values.

In this example, the manifest binds an HTTP Agent to the Flow deployed by the same Application. Replace the empty `node_red_data.flows` list with your Flow's nodes before deploying. If the Flow file includes `id`, it must match the ID resolved from the manifest.

**`contextual.yaml`**

```yaml
manifestVersion: 0
application:
  id: catalog-intake
flows:
  intake:
    id: catalog-intake
    definition: ./flows/intake.json
agents:
  intake:
    id: catalog-intake-http
    definition: ./agents/intake.json
    flow: !ref flows.intake.id
```

**`flows/intake.json`**

```json
{
  "id": "catalog-intake",
  "name": "Catalog intake",
  "node_red_data": { "flows": [] }
}
```

**`agents/intake.json`**

```json
{
  "id": "catalog-intake-http",
  "type": "flow-http"
}
```

The Agent definition provides the Agent type. Put the Flow binding and any Agent `environment` values on its manifest entry. The CLI saves the Agent ID as its `name`. Deploy saves the Flow first and binds the Agent to the Flow version on the target.

### Verify the Flow and Agent binding

After deploying with `--json`, find the `agent` step under `steps`. Its `detail` shows `runs flow catalog-intake#<version>`. To confirm the saved binding on the tenant, read the Agent and check its `flow` field. Replace `my-config` with the configuration you deployed to.

```sh
ctxl records get native-object:agent/catalog-intake-http --config-id my-config --pretty
```

To test a Legacy Flow over HTTP, use the [HTTP In](https://docs.contextual.io/legacy/components-and-data/flows/node-reference/network/http-in.md) and [HTTP Response](https://docs.contextual.io/legacy/components-and-data/flows/node-reference/network/http-response.md) nodes. Call the deployed Agent's route and check the response.

## Define a Worker

Manifest v0 supports Workers defined by `build`, `image`, `imageFrom`, `compose`, or a platform-published managed `template: <name>:<version>`. Organization templates (`ctxl workers create --template`) deploy with the [Workers CLI](https://docs.contextual.io/build/contextual-workers/contextual-cli.md).

### Deploy a managed-template Worker

Set `template: <name>:<version>` without `compose`. Use `build`, `image`, or `imageFrom` (reusing another Worker's image in one build and push) to fill the template's single image option, and set the rest under `options`. For templates with multiple image options, set each image option under `options` directly. See [Templates and Options](https://docs.contextual.io/build/contextual-workers/managed-workers/templates-and-options.md).

```yaml
workers:
  intake:
    id: catalog-intake-${stage.name}
    template: managed-http-worker:0.10.0
    size: small
    build: ./.worker-image
    options:
      HANDLER: intake
      CONFIG:
        targetAgent: !ref workers.receipts.id
  receipts:
    id: catalog-receipts-${stage.name}
    template: managed-event-worker:0.10.0
    size: small
    imageFrom: intake
    options:
      HANDLER: receipt
      LAG_THRESHOLD: ${var.receiptLag}
```

Option values accept `${var.name}`, `${stage.name}`, and `!ref` (mappings and lists serialize as JSON, up to 4096 characters) and are saved in plain text; attach credentials with `secrets` instead. If preflight refuses a template or option, confirm the target config, published `<name>:<version>`, and option names, then rerun `ctxl app deploy --dry-run`.

### Pass manifest values to Compose

Use `compose: ./compose.yaml` in place of `build`. Set non-secret values in the Worker's `environment` and read them in Compose as `${NAME}` (for example, `${PRODUCT_TYPE}`). Compose variables resolve only from that Worker's resolved `environment`. They don't read from `secrets`, the host environment, or `.env`. Because the platform saves Compose as plain text, the CLI refuses `${NAME}` or `$NAME` references to any key in `workers.<key>.secrets`. See [Configure a Custom Compose Worker](https://docs.contextual.io/build/contextual-workers/connect-to-contextual.md#configure-a-custom-compose-worker).

#### Mount a secret in specific services

A secret in `workers.<key>.secrets` is stored encrypted and is available through the environment of every service by default. If only some services need it, declare a top-level Compose secret with the literal environment key (`environment: API_TOKEN`) and list that secret on those services.

Contextual creates and mounts the file when the Worker runs. You don't create a local secret file or add a `file:` entry. Only the listed services can read the file at `/run/secrets/<name>` (or the configured `target`), and `API_TOKEN` is omitted from every service's environment.

```yaml
# compose.yaml (with workers.api.environment.PRODUCT_TYPE and workers.api.secrets.API_TOKEN)
x-contextual:
  version: 1
services:
  web:
    build: ./web
    environment:
      PRODUCT_TYPE: "${PRODUCT_TYPE}"
    secrets:
      - source: api_token
        target: /run/secrets/api-token
  worker:
    build: ./worker
secrets:
  api_token:
    environment: API_TOKEN
```

## Configure stages and variables

A stage selects manifest values. The CLI configuration selects the destination tenant and silo. Use different IDs for resources that should coexist in the same tenant, and reference resources that should be shared.

For each non-secret variable, the CLI uses the first available source in this order.

1. A `--var NAME=VALUE` override.
2. The selected stage's literal value or `fromEnv` source.
3. The declaration's `fromEnv` or `default` source.

Read a variable with `${var.name}` and the selected stage with `${stage.name}`. This manifest gives `dev` and `staging` different Worker IDs in the same tenant. Both use an existing `product` Object Type. Put the [sample HTTP server and Dockerfile](https://docs.contextual.io/build/contextual-workers/quickstart.md#2-create-the-application-files) in `api/`. The sample server reads `GREETING`.

**`contextual.yaml`**

```yaml
manifestVersion: 0
application:
  id: catalog
variables:
  greeting:
    default: Hello from the catalog
stages:
  dev:
    variables:
      greeting: Hello from development
  staging: {}
objectTypes:
  products:
    id: product
workers:
  api:
    id: "catalog-api-${stage.name}"
    build: ./api
    size: small
    environment:
      GREETING: ${var.greeting}
      PRODUCT_TYPE: !ref objectTypes.products.id
```

Inspect the plans with the same CLI configuration. Replace `my-config` with the configuration for your tenant.

```sh
ctxl app print --config-id my-config --stage dev --pretty
ctxl app print --config-id my-config --stage staging --pretty
ctxl app print --config-id my-config --stage dev --var 'greeting=Hello from this run' --pretty
```

In each plan, check `workers[].id` and `workers[].environment`. The first resolves `catalog-api-dev` with `GREETING` set to `Hello from development`. The second resolves `catalog-api-staging` with the default `Hello from the catalog`. The third keeps `catalog-api-dev` and sets `GREETING` to `Hello from this run`. Each plan resolves `PRODUCT_TYPE` to `product`. The target must supply that type, and the Worker's runtime identity needs permissions for any calls its code makes.

### Declare and bind secrets

Declare each secret once under `variables` with `secret: true` (string only, no `default`) and optionally `fromEnv: ENV_NAME` (uppercase) as its default source. To use a different environment variable for a stage, set `fromEnv` under `stages.<stage>.variables.<name>`. The CLI reads the selected stage's `fromEnv` if set, otherwise the declaration's `fromEnv` (including with no stage selected). `--var` cannot set a secret. If `app print` or preflight reports a missing or unset secret, export the named environment variable or select a stage that sets `fromEnv`.

* **Workers and Agents:** Bind secrets in `workers.<key>.secrets` or `agents.<key>.secrets` using bare variable names (for example, `API_TOKEN: apiToken`). Deploy writes them to encrypted `envVars`; do not repeat the same name in `environment`. An Agent's `environment` can also interpolate a secret (for example, `API_AUTH: Bearer ${var.apiToken}`) when the target Agent type marks `envVars[*].value` encrypted; a Worker's `environment` cannot.
* **Connections:** Use `${var.name}` in string values in the Connection definition. In an encrypted field such as `headers[].value`, you can combine ordinary text with a secret, for example `"value": "Bearer ${var.apiToken}"`. Deploy resolves the value directly into the encrypted header. The definition contains the reference, not the credential.

  To bind a whole value instead, leave the field omitted or empty (`""`) and use a bare variable name under `connections.<key>.secrets`, for example `bearerToken: apiToken` for a raw bearer token. When updating a Connection, make sure each existing secret is supplied through a reference or binding. Don't copy `<ENCRYPTED>` placeholders into the definition.

**`contextual.yaml`**

```yaml
variables:
  apiToken:
    secret: true
    fromEnv: API_TOKEN
  partnerKey:
    secret: true
    fromEnv: PARTNER_KEY
stages:
  prod:
    variables:
      apiToken:
        fromEnv: PROD_API_TOKEN
connections:
  billing:
    id: billing-api
    definition: ./connections/billing.json
  erp:
    id: erp
    definition: ./connections/erp.json
    secrets:
      bearerToken: apiToken
      "headers[key=X-Api-Key].value": partnerKey
```

**`connections/billing.json`**

```json
{
  "apiId": "billing-api",
  "name": "Billing API",
  "type": "public",
  "endpoint": "https://billing.example.com",
  "headers": [
    {
      "key": "Authorization",
      "value": "Bearer ${var.apiToken}"
    },
    {
      "key": "Accept",
      "value": "application/json"
    }
  ]
}
```

## Preview and deploy

[Inspect the plan](https://docs.contextual.io/build/applications/contextual-cli.md#inspect-the-plan) with `app print`, then [preview changes in the target tenant](https://docs.contextual.io/build/applications/contextual-cli.md#preview-changes-in-the-target-tenant) with `app deploy --dry-run`. Keep the same file, stage, configuration, and variable overrides when applying the reviewed change. Removing an entry from the manifest leaves the resource on the tenant. The result can list it under `detached` when the local `.contextual/state.json` file tracked it for that target and stage.

For a Worker, inspect `readiness` in the deploy result and test the behavior your code provides. If the result reports a stopped Worker, check why it stopped. Use `--start` on an actual deploy when you intend to start it. See [Inspect and Verify](https://docs.contextual.io/build/contextual-workers/contextual-cli.md#inspect-and-verify).
