# branchd Docs

> Documentation for branchd.

# Home

> branchd is Xeonr's git host. These pages cover access and tokens, packages, and pipelines.
branchd ([branchd.run](https://branchd.run)) hosts git repositories for Xeonr
teams: repositories in groups, pull requests, reviews, branch rules and
checks. Each repository can hold packages beside its code (container
images, generic packages and npm packages), and can describe pipelines that
branchd runs on its pushes, pull requests, schedules and manual starts.

- [Access and tokens](https://docs.branchd.run/branchd/access): Scopes and levels, personal API keys, bots limited to groups and repositories, and scoped CLI logins.
- [Packages](https://docs.branchd.run/branchd/packages): Generic packages and an npm registry on registry.branchd.run, beside a repository's container images, and who may read and publish them.
- [Terraform state](https://docs.branchd.run/branchd/terraform-state): Terraform and OpenTofu state in a repository, through their http backend, with locking, every version kept, and restore in the console.
- [Pipelines](https://docs.branchd.run/branchd/pipelines): Write .branchd/pipelines/\*.yaml: tests, builds, deploys, reuse and the complete reference.

Source: https://docs.branchd.run/branchd

---

# Access and tokens

> How branchd decides what a key, a bot or a sign-in may do, and which credential to use for which job.
Every request to branchd, whether through the API, git over HTTPS, the
container registry, generic and npm packages or Go modules, is allowed only when **all** of these
allow it:

1. **Scopes: which features, at which level.** Every credential carries
   scopes such as `forge:contents:read` (clone) or `forge:package:edit`
   (push images). See [Scopes and levels](https://docs.branchd.run/branchd/access/scopes).
2. **Resources: which repositories and groups.** A credential either
   reaches everything its owner can, or is limited to named repositories
   and groups. A group covers everything under it.
3. **The owner's current role.** A key or token never does more than the
   person or bot it belongs to may do today. Lose a role, and every
   credential you hold loses it at once.

A level such as _read_ or _write_ is only a shortcut for a set of scopes.
What a credential stores, and what branchd checks, is always the scopes.

## Which credential to use

| You want to…                                                                                         | Use                                                                                           |
| ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| Work from your own machine with the `branchd` CLI, git and Docker                                    | [`branchd auth login`](https://docs.branchd.run/branchd/access/cli-login). It signs you in and keeps the token fresh. |
| Give one script or tool a narrow login that reaches only some repositories                           | A [scoped login](https://docs.branchd.run/branchd/access/cli-login#scoped-logins) (`--repo`, `--group`, `--scopes`)   |
| Give a script, CI system or registry client a long-lived credential that acts as **you**             | A [personal API key](https://docs.branchd.run/branchd/access/personal-keys) (`xk_…`)                                  |
| Give automation a credential that belongs to a **team**, not a person                                | A [bot](https://docs.branchd.run/branchd/access/bots) and one of its keys                                             |
| Let another application with its own Xeonr Auth service account call branchd, with no branchd secret | Its [own token](https://docs.branchd.run/branchd/access/services), and grants to it                                   |
| Let another company's application act for branchd users                                              | [OAuth, with the least scopes it needs](https://docs.branchd.run/branchd/access/third-party-apps)                     |
| Run a job in a branchd pipeline                                                                      | The [job token](https://docs.branchd.run/branchd/pipelines/job-token), already in `$BRANCHD_TOKEN`                    |

## Sending a credential

| Where                                             | How                                                                                                                                                  |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| API                                               | `Authorization: Bearer <token or xk_ key>`                                                                                                           |
| git over HTTPS                                    | The key or token as the password. The username is ignored.                                                                                           |
| Container registry (`registry.branchd.run`)       | `docker login registry.branchd.run -u token --password-stdin`, with the key on stdin. The username is ignored.                                       |
| Generic and npm packages (`registry.branchd.run`) | The key or token as the password with `curl --user`, or as `_authToken` in `.npmrc`. See [Access to packages](https://docs.branchd.run/branchd/packages/access#which-token). |

Source: https://docs.branchd.run/branchd/access

---

# Bots

> Team-owned bots, limited to groups and repositories, and their keys limited further by scope and binding.
A bot is an account that belongs to a **team**, not a person, for
automation that should keep working when people come and go. Every bot
has a role (**read**, **write** or **maintain**), which caps everything
its keys can do. A bot is never an administrator.

## Limiting a bot to groups and repositories

By default a bot reaches every repository of its team. You can limit it
to some groups and repositories (up to 50). A group covers everything
under it. This is a ceiling for all of the bot's keys:

- a key's bindings must sit inside the bot's resources when it is issued;
- on every request, branchd intersects the key's bindings with the bot's
  **current** resources, so narrowing a bot cuts its existing keys at once.

```sh
# Create a bot that may reach only one group
branchd bot create acme/deployer --role write --group acme/services

# Narrow it to one repository, or widen it back to the whole team
branchd bot update acme/deployer --repo acme/services/api
branchd bot update acme/deployer --whole-team
```

In the console, this is under the group's **Bots** settings.

## Bot keys

A bot key carries scopes and, optionally, bindings:

```sh
# The git preset: clone (and push, if the bot's role is above read)
branchd bot token acme/deployer --kind git

# Exactly the scopes a job needs, on one repository
branchd bot token acme/deployer --scopes forge:package:read --repo acme/services/api

# A level, never above the bot's role
branchd bot token acme/deployer --level write --group acme/services
```

| Flag                          | Meaning                                                                                    |
| ----------------------------- | ------------------------------------------------------------------------------------------ |
| `--kind git`                  | `forge:contents:read`, plus `forge:contents:edit` when the bot's role is write or maintain |
| `--kind api`                  | The API preset: the read level, or the write level for a write or maintain bot             |
| `--level LEVEL`               | `read`, `write` or `maintain`, never above the bot's role                                  |
| `--scopes S,...`              | Exactly these scopes                                                                       |
| `--repo PATH`, `--group PATH` | Bind the key to these, inside the bot's own resources. Repeatable.                         |
| `--name NAME`                 | A label for the key (default: its kind and the time)                                       |
| `--expires DURATION`          | How long until it stops working, as a duration such as `2160h` (90 days)                   |

Use one of `--kind`, `--level` or `--scopes`. Without `--repo` or
`--group`, a limited bot's key is bound to all of the bot's resources, and
a whole-team bot's key reaches the whole team.

In the API, `CreateBot` and `UpdateBot` take `resources[]`
(`{kind: GROUP or REPOSITORY, path}`; empty means the whole team, and
`update_mask` `resources` changes it). `CreateBotCredential` takes
`kind`, or `level` and/or `scopes`, and `bindings[]` with optional
per-binding scopes, each inside the key's own scopes.

## SSH deploy keys

A bot can also hold SSH public keys for git over SSH. This is branchd's
deploy key: a key that clones one repository or group (or pushes to it) and
nothing else, owned by the team rather than a person.

```sh
# Read and write on one repository (the bot's role must be write or maintain)
branchd bot token acme/deployer --kind ssh --key-file deploy_key.pub --repo acme/services/api

# Read only, from stdin, on a group
cat ci_key.pub | branchd bot token acme/deployer --kind ssh --key-file - --level read --group acme/services
```

- branchd stores only the public key, so nothing secret is printed. The
  command prints the key's fingerprint, as `ssh-keygen -l` shows it.
- `--level read` makes the key clone and fetch only. Without it, a write
  or maintain bot's key can also push, and branch rules still apply.
- `--repo`, `--group` and `--expires` work as for any bot key. A key can
  never reach past the bot's role or resources, and narrowing or disabling
  the bot narrows or stops its keys at once.
- A key can belong to only one person or bot. RSA keys under 3072 bits are
  refused.
- Clone with `ssh://git@branchd.run:2222/<repo>.git`.
- `branchd bot show` lists a bot's SSH keys by fingerprint, and `branchd bot
  revoke <team>/<name> <id>` removes one, after which the same key can be
  added again.

In the console, this is the **SSH deploy keys** section of a bot's page. In
the API, `CreateBotCredential` takes `kind: SSH` with `public_key`, and
optionally `level` (`read` or `write`) and `bindings[]`.

Source: https://docs.branchd.run/branchd/access/bots

---

# Signing in with the CLI

> branchd auth login, scoped logins with --repo, --group, --scopes and --wait, and branchd auth token.
## Your everyday login

```sh
branchd auth login
```

This signs you in with Xeonr Auth's device-code flow: open the printed
URL, confirm the code, and the sign-in is stored in your OS keychain (or a
`0600` file under `~/.config/branchd`). The CLI refreshes it silently, and
`branchd auth setup-git` and `branchd registry setup-docker` let git and
Docker use it too. `--no-browser` prints the URL without opening a
browser. That is also what happens when there is no terminal.

To use the current token from a script:

```sh
curl -H "Authorization: Bearer $(branchd auth token)" https://branchd.run/…
```

## Agent sessions

An AI agent session on your machine (Claude Code, T3 Code, Codex, or an AI
Sessions run) that runs `branchd`, `git` over HTTPS or `docker` against
branchd acts **as you, with your full permissions**, as soon as you are
signed in: there is nothing to set up, no flag and no variable.

The CLI does not send your login itself. It exchanges it at Xeonr Auth for
a short-lived token for that one session: you are its subject, the branchd
CLI is its actor, and it names the session (`t3:<thread>`,
`aisessions:<session>`, `codex:<thread>` or `claude-code:<session>`). The
token is cached for the session and renewed from your login without a
prompt. Everything done with it, from an API call to a push, a pull
request, a merge or a grant, is recorded as **an agent acting for you, in
that session**, never as you alone:

```sh
$ branchd auth status
signed in as   you@example.com
credential     agent-session
actor          agent session t3:thread-… (client …), acting for the subject
```

Approving what the agent does is your agent tool's job: its permission
prompts are where you allow or refuse a command. branchd checks only what
you yourself may do, and an agent acting for you may do all of it:
changing who has access, issuing personal API keys, approving pull
requests and environment gates (it counts as you, so it never approves your
own work), deleting a published version tag, making something public, and
administering branchd if you do. The same holds for the Xeonr MCP gateway's
branchd tools, within the toolsets you ticked.

- **Not signed in?** The CLI says to run `branchd auth login`, which the
  agent may start for you to approve in your browser.
- **Want a session to reach less?** Give it a session credential
  (`forge_create_session_credential` on the Xeonr MCP gateway) limited to
  some repositories and refs, or a [scoped login](https://docs.branchd.run/branchd/access/cli-login#scoped-logins) with
  `--profile`.
- **In a pipeline job** nothing changes: the job's own token is used, never
  a person's login.
- The session is recognised from the agent tool's environment variables.
  They label the token; they are not a security boundary.

## Scoped logins

A scoped login asks for less than your everyday one. It is a **separate**
login, named with `--profile`, so your default login is untouched:

```sh
# A login that can read one repository: clone it, pull its images, read its pull requests
branchd auth login --profile api --repo acme/api
branchd --profile api repo list acme

# The same, but only for cloning and pulling images
branchd auth login --profile api-pull --repo acme/api --scopes forge:contents:read,forge:package:read
```

| Flag              | Meaning                                                                                                  |
| ----------------- | -------------------------------------------------------------------------------------------------------- |
| `--profile NAME`  | Required. The name of this login. Use it with `--profile` on any command.                                |
| `--repo PATH`     | Limit the login to this repository. Repeat, or separate with commas.                                     |
| `--group PATH`    | Limit the login to this group and everything under it. Repeat, or separate with commas.                  |
| `--scopes S,...`  | Ask for only these `forge:` [scopes](https://docs.branchd.run/branchd/access/scopes). Repeat, or separate with commas or spaces. |
| `--wait DURATION` | How long to wait for the browser, for a link that will be opened later (e.g. `4h`). Default `30m`.       |

**Without `--scopes`**, a scoped login asks for the [Read level](https://docs.branchd.run/branchd/access/scopes):
`forge:repository:read forge:contents:read forge:release:read forge:package:read forge:pipeline:read forge:pull-request:read forge:review:read forge:check:read forge:branch-rule:read`
(plus `forge:group:read` on a group). So it can clone and fetch, pull
images, and read releases, pipeline runs, pull requests, reviews, checks
and branch rules, on its repositories and groups only. Pass `--scopes` to
ask for less, or for write scopes such as `forge:contents:edit`.

`forge:repository:read` on its own reaches repository metadata and
settings, not git contents or images: cloning needs `forge:contents:read`
and pulling needs `forge:package:read`. branchd CLI releases before 0.50
asked only for `forge:repository:read forge:pull-request:read
forge:review:read forge:check:read` by default, so a scoped login made with
one of them cannot clone; sign in again with a current CLI.

A scoped login signs in through the **browser**: it pushes its request to
Xeonr Auth ([PAR](https://docs.xeonr.io/auth/guides/rar#using-par)) with each repository
and group as [`authorization_details`](https://docs.xeonr.io/auth/guides/rar) and
branchd as the RFC 8707 `resource`. So it needs a browser that can reach
this machine's loopback address. On the consent screen you can narrow it
further ([what the person grants](https://docs.xeonr.io/auth/guides/consent-narrowing)).

### Using a scoped login with git and Docker

```sh
branchd auth setup-git --profile api
branchd registry setup-docker --profile api
```

`registry setup-docker --profile api` records the profile for
`registry.branchd.run`, so Docker's credential helper answers with that
login, and the registry then serves only its own repositories' images.

Source: https://docs.branchd.run/branchd/access/cli-login

---

# Personal API keys

> Create xk_ keys that act as you, limited to repositories, groups and scopes, for scripts, git over HTTPS and the registry.
A personal API key (`xk_…`) is a long-lived credential that acts as
**you**. Use one where a sign-in that refreshes itself won't do: a script,
a CI system outside branchd, or a Docker or git client on a server.

A personal key:

- acts as you, and never does more than your **current** role allows;
- reaches **everything** you can reach, or only the repositories and
  groups you bind it to (at most 50; a group covers everything under it);
- carries only the [scopes](https://docs.branchd.run/branchd/access/scopes) you give it, picked by level or one
  by one;
- **expires within 365 days**. Only an organisation administrator may
  issue a key that never expires;
- stops working when you revoke it, or if your account is deactivated;
- can never manage keys, SSH keys, session credentials, bots or access
  grants.

You create a key signed in as yourself, or an agent acting for you does
(an [agent session](https://docs.branchd.run/branchd/access/cli-login#agent-sessions), or the
Xeonr MCP gateway's `create_personal_key` with _credentials_ ticked); the
key records the agent that made it. A bot, a pipeline job or another key
cannot make one. You can't give a key a scope your own sign-in doesn't hold.

The secret is shown **once**, when the key is created. branchd keeps only
its prefix.

## In the console

Open **API keys** in your settings (`/-/settings/tokens`). Choose a name,
whether it reaches everything or only some repositories and groups, a
level or individual scopes, and an expiry.

## With the CLI

```sh
# A key that pulls images from one repository, for 30 days
branchd token create ci-pull --repo acme/api --scopes forge:package:read --expires 30d

# Clone everything in a group, at the read level (the default), for 90 days (the default)
branchd token create build-clone --group acme

# List your keys, then revoke one
branchd token list
branchd token revoke 0b6c1d2e-3f40-4a5b-8c6d-7e8f90a1b2c3
```

`branchd token create <name>` takes:

| Flag                  | Meaning                                                                                                   |
| --------------------- | --------------------------------------------------------------------------------------------------------- |
| `--repo PATH`         | Bind the key to this repository. Repeat for more.                                                         |
| `--group PATH`        | Bind the key to this group and everything under it. Repeat for more.                                      |
| `--level LEVEL`       | `read` (default), `write`, `maintain` or `admin`. See [levels](https://docs.branchd.run/branchd/access/scopes#levels).            |
| `--scopes S,...`      | Exactly these scopes, instead of a level                                                                  |
| `--expires WHEN`      | `<n>d` (up to `365d`), a date `YYYY-MM-DD`, or `never` (organisation administrators only). Default `90d`. |
| `-d`, `--description` | A note for yourself                                                                                       |
| `--json`              | Print the whole response                                                                                  |

Without `--repo` or `--group`, the key reaches everything you can. Only the
secret goes to standard output, so it can be piped:

```sh
branchd token create ci-push --repo acme/api --scopes forge:package:edit --expires 30d \
  | docker login registry.branchd.run -u token --password-stdin
```

`branchd token list` shows your keys with their prefix, what they reach,
their scopes (or level), expiry, last use and state. `--all` includes
revoked ones. `branchd token revoke <id>` takes the key's id or its full
`urn:xeonr:auth:api-key:…` name. `--yes` is needed when there is no
terminal to confirm on.

## Using a key

| Where                    | How                                                                                                                                         |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| API                      | `Authorization: Bearer xk_…`                                                                                                                |
| git over HTTPS           | The key as the password. The username is ignored.                                                                                           |
| Registry                 | `docker login registry.branchd.run -u token --password-stdin`                                                                               |
| Generic and npm packages | The key as the password with `curl --user`, or as `_authToken` in `.npmrc`. See [Access to packages](https://docs.branchd.run/branchd/packages/access#which-token). |

## The API

`xeonr.forge.v1.PersonalKeyService`:

| Method                  | Does                                                                                                                                                                                                                                          |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GetPersonalKeyOptions` | The scopes you may issue, with descriptions; the levels; the maximum lifetime; whether you may omit an expiry; the maximum number of bindings                                                                                                 |
| `CreatePersonalKey`     | `name` (1–64 characters), `description`, either `everything: true` or `bindings[]` (each `{type: REPOSITORY or GROUP, path, scopes[]}`; a binding with no scopes takes the key's), `level` and/or `scopes[]`, and `expires_at` or `no_expiry` |
| `ListPersonalKeys`      | Your keys. `include_revoked` adds revoked ones.                                                                                                                                                                                               |
| `RevokePersonalKey`     | By `key` (`urn:xeonr:auth:api-key:<uuid>`). Revoking twice is not an error.                                                                                                                                                                   |

A binding to a repository or group you can't read is refused as not found.
An expiry more than 365 days away is refused, and so is `no_expiry` from
anyone but an organisation administrator.

Source: https://docs.branchd.run/branchd/access/personal-keys

---

# Scopes and levels

> branchd's feature scopes, what each one allows, and the read, write, maintain and admin levels that bundle them.
A scope names **one feature at one level**. The verbs are `read`, `edit`
and `admin`, and each implies the ones before it: `admin` ⊃ `edit` ⊃
`read`. Ask for, or issue, only the scopes the job needs. A key that can
pull images cannot clone, and a token that can clone cannot push.

The same scopes are checked everywhere: the API, git over HTTPS, the
container registry, Go modules and release downloads.

## Feature scopes

| Scope                         | Allows                                                                                                                                                                                                        |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `forge:contents:read`         | Clone and fetch, read files, commits and blame, compare, fetch Go modules                                                                                                                                     |
| `forge:contents:edit`         | Push, and create or delete branches and tags                                                                                                                                                                  |
| `forge:repository:read`       | Read repositories and their settings                                                                                                                                                                          |
| `forge:repository:edit`       | Change repository settings                                                                                                                                                                                    |
| `forge:repository:admin`      | Create, delete, rename and transfer repositories; visibility, access and grants, webhooks and mirrors                                                                                                         |
| `forge:group:read`            | See groups and their settings                                                                                                                                                                                 |
| `forge:group:edit`            | Create and change groups, their labels and settings                                                                                                                                                           |
| `forge:group:admin`           | A group's access, bots and runner pools                                                                                                                                                                       |
| `forge:pull-request:read`     | Read pull requests and their comments                                                                                                                                                                         |
| `forge:pull-request:edit`     | Open, edit, close and comment on pull requests                                                                                                                                                                |
| `forge:pull-request:merge`    | Merge pull requests, where branch rules allow                                                                                                                                                                 |
| `forge:review:read`           | Read reviews                                                                                                                                                                                                  |
| `forge:review:edit`           | Review and approve pull requests                                                                                                                                                                              |
| `forge:check:read`            | Read checks on commits                                                                                                                                                                                        |
| `forge:check:edit`            | Report checks on commits. A check reported this way never counts as a required check.                                                                                                                         |
| `forge:branch-rule:read`      | Read branch rules                                                                                                                                                                                             |
| `forge:branch-rule:edit`      | Change branch rules                                                                                                                                                                                           |
| `forge:release:read`          | Read releases and download their assets                                                                                                                                                                       |
| `forge:release:edit`          | Create, edit and publish releases                                                                                                                                                                             |
| `forge:package:read`          | Pull container images, download generic packages and install npm packages; see tags, versions and retention                                                                                                   |
| `forge:package:edit`          | Push container images; publish generic and npm packages; move aliases and dist-tags                                                                                                                           |
| `forge:package:admin`         | Set and apply retention; delete images and generic packages; deprecate and unpublish npm versions; claim npm scopes. Deleting also needs a key at the maintain level (it must hold `forge:branch-rule:edit`). |
| `forge:terraform-state:read`  | Read Terraform states, secrets included (also needs write access on the repository)                                                                                                                           |
| `forge:terraform-state:edit`  | Write, lock and unlock Terraform states, as Terraform does                                                                                                                                                    |
| `forge:terraform-state:admin` | Download, restore and delete Terraform state versions and states; force-unlock them                                                                                                                           |
| `forge:pipeline:read`         | Read runs, logs and drafts                                                                                                                                                                                    |
| `forge:pipeline:edit`         | Run, retry and cancel pipelines, fire schedules, edit drafts                                                                                                                                                  |
| `forge:pipeline:admin`        | Change pipeline settings, variables and secrets                                                                                                                                                               |

Webhooks and mirrors are under `forge:repository:admin` because both hold
or send secrets.

Some scopes are never put on a key: your SSH keys (`forge:ssh-key:*`),
session credentials and your profile. A key can never manage keys, SSH
keys, session credentials, bots or access grants, whatever scopes it has.

## Levels

A level is a named bundle of scopes, offered by the console and by the
CLI's `--level` as a shortcut. Each level contains the one before it.

| Level        | Adds                                                                                                                                                               |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **read**     | Every feature's `:read`: `group`, `repository`, `contents`, `pull-request`, `review`, `check`, `branch-rule`, `release`, `package`, `pipeline`                     |
| **write**    | `contents:edit`, `pull-request:edit`, `review:edit`, `check:edit`, `release:edit`, `package:edit`, `pipeline:edit`, `terraform-state:read`, `terraform-state:edit` |
| **maintain** | `pull-request:merge`, `branch-rule:edit`, `repository:edit`, `pipeline:admin`, `terraform-state:admin`                                                             |
| **admin**    | `repository:admin`, `group:edit`, `group:admin`, `package:admin`                                                                                                   |

A key below the maintain level stays at write access even where your role
is higher. It cannot create or force-update protected branches or tags, or
delete images.

## Choosing scopes: examples

| Job                                                                            | Scopes                                                     |
| ------------------------------------------------------------------------------ | ---------------------------------------------------------- |
| Clone repositories in CI                                                       | `forge:contents:read`                                      |
| Pull images from the registry, download generic packages, install npm packages | `forge:package:read`                                       |
| Push images, publish generic and npm packages                                  | `forge:package:edit`                                       |
| Run `terraform plan` and `apply` against a [state](https://docs.branchd.run/branchd/terraform-state)   | `forge:terraform-state:read`, `forge:terraform-state:edit` |
| Publish releases from a build                                                  | `forge:release:edit`, `forge:contents:read`                |
| Report a status check from an external system                                  | `forge:check:edit`                                         |
| A review bot that comments on pull requests                                    | `forge:pull-request:edit`, `forge:contents:read`           |

Source: https://docs.branchd.run/branchd/access/scopes

---

# Services

> An application with its own Xeonr Auth service account calls branchd with its own token, reaching only what teams grant it.
An application that already has an **Xeonr Auth service account** can call
branchd with that account's own token, instead of holding a bot key. It
holds no branchd secret at all: it asks Xeonr Auth for a short-lived token
whenever it needs one.

A service reaches nothing until it is granted access. Each team that wants
it grants it **read** or **write** on its root, a group or a repository,
and an administrator of a company can grant it **read** on every team the
company owns, now and later. Its token's scopes still cap it, and branch
rules still apply: a service is never a person, so it cannot approve a pull
request or push past a protected branch.

## 1. Let the service account ask for branchd's scopes

In Xeonr Auth, give the service account an approved binding to the
**branchd** application with the scopes it needs, for example
`forge:repository:read` and `forge:contents:read` to read code, and
`forge:package:read` to pull images and packages. A service that opens pull
requests also needs `forge:contents:edit` and `forge:pull-request:edit`.
See [Scopes and levels](https://docs.branchd.run/branchd/access/scopes).

## 2. Get a token for branchd

Exchange the service account's assertion for a token whose audience is
branchd (`resource=https://branchd.run`), with the jwt-bearer grant:

```go
ts, err := authn.NewTokenSource(authn.TokenSourceConfig{
	TokenURL:  "https://auth.xeonr.io/api/v1/oauth/token",
	Grant:     authn.GrantJWTBearer,
	Assertion: serviceAccountToken,
	Resource:  "https://branchd.run",
	Scopes:    []string{"forge:repository:read", "forge:contents:read"},
})
client := ts.Client(http.DefaultClient) // every request carries the token
```

The token works everywhere a key does: as `Authorization: Bearer` on the
API, and as the password for git over HTTPS, the container registry, generic
and npm packages and Go modules.

## 3. Grant it access

Name the service by its service account's URN:

```sh
# One team gives it read on its whole team
branchd access grant acme --to service:urn:xeonr:auth:uid:service_account:48 --role read

# Write on one repository, to push branches and open pull requests
branchd access grant acme/tools/fixer --to service:urn:xeonr:auth:uid:service_account:48 --role write

# A company administrator gives it read on every team the company owns
branchd access grant company:acme --to service:urn:xeonr:auth:uid:service_account:48 --role read
```

A team keeps a company grant out of its own repositories with a limit on
the service at its root:

```sh
branchd access limit acme --to service:urn:xeonr:auth:uid:service_account:48 --role none
```

`branchd access explain <path> --for service:<URN>` says why the service
reaches what it does, `branchd access list company:<slug>` lists a
company's grants, and every grant and revocation is in the audit log, with
the service as the actor of everything it does.

Source: https://docs.branchd.run/branchd/access/services

---

# Third-party applications

> Integrate with branchd over OAuth, asking for the least scopes and resources you need.
An application that acts for branchd users signs them in with
[Xeonr Auth](https://docs.xeonr.io/auth/guides/authorization-code) and calls branchd with
the access token. branchd gives a third-party token **exactly the scopes
it was granted**, never more, and always within the person's own role.

## Ask for the least

- **Ask for feature scopes**, not levels: `forge:contents:read` to clone,
  `forge:package:read` to pull images, `forge:check:edit` to report a
  check. See [Scopes and levels](https://docs.branchd.run/branchd/access/scopes).
- **Name the scopes you can't work without** in
  [`required_scope`](https://docs.xeonr.io/auth/guides/consent-narrowing#marking-scopes-as-required-required_scope).
  The person may untick the rest.
- **Limit to resources when you can.** Push `authorization_details`
  through [PAR](https://docs.xeonr.io/auth/guides/rar#using-par), with
  `resource=https://branchd.run`:

```json
[
  { "type": "forge:repository", "identifier": "acme/api", "actions": ["forge:contents:read"] },
  { "type": "forge:group", "identifier": "acme/docs", "actions": ["forge:contents:read", "forge:pull-request:edit"] }
]
```

Each action must be one of the scopes you asked for, or implied by one.

## Read what was granted

The person may untick scopes, drop resources you pushed, or limit an
unlimited request to some groups and repositories on the consent screen.
Read the `scope` and `authorization_details` in the token response, and
build your UI from those. See
[What the person grants](https://docs.xeonr.io/auth/guides/consent-narrowing).

A request outside the token's resources is refused, even where the
person's own role would allow it.

Source: https://docs.branchd.run/branchd/access/third-party-apps

---

# Packages

> What branchd stores beside a repository's code, on one host. Container images, generic packages (any file, by package and version) and npm packages.
Every repository on branchd can hold packages beside its code. They are all
served from one host, `registry.branchd.run`, and a repository's packages
follow one set of access rules.

| Kind                                          | What it holds                                                             | Where                                                                          |
| --------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Container images                              | Images and Helm charts, pushed and pulled with Docker                     | `registry.branchd.run/<repository>`                                            |
| [Generic packages](https://docs.branchd.run/branchd/packages/generic) | Any files, grouped by package and version, each with its size and SHA-256 | `https://registry.branchd.run/generic/<repository>/<package>/<version>/<file>` |
| [npm packages](https://docs.branchd.run/branchd/packages/npm)         | Scoped npm packages (`@scope/name`), for npm and pnpm                     | `https://registry.branchd.run/npm/`                                            |

A package always **belongs to one repository**. There are no packages owned
by a group or by branchd as a whole. Who may read, publish and delete a
package is decided by its repository: see [Access](https://docs.branchd.run/branchd/packages/access).

- [Generic packages](https://docs.branchd.run/branchd/packages/generic): Publish and download files with curl, the CLI or a pipeline step. Aliases such as latest, and retention.
- [npm packages](https://docs.branchd.run/branchd/packages/npm): Claim a scope, grant who may install and publish under it, and publish with npm or pnpm from your machine or a pipeline.
- [Access](https://docs.branchd.run/branchd/packages/access): Scopes, tokens, public packages and anonymous reads, and CI grants for another repository's jobs.

## In the console

A repository's packages are under **Releases**: the Releases page has an
**Images** button and a **Packages** button, and the two pages link to each
other. The Packages page lists the repository's generic packages, and the
npm packages its pipelines have published. Open a generic package to see its
versions, files and checksums, copy the commands to download it, and (with
the access to do so) move an alias or delete a version.

An npm package belongs to its scope, so its page is on the group that holds
the scope: versions, dist-tags, where each version was published from, and
who may install and publish it.

- **Retention** for generic packages is on the repository's
  **Settings › Releases and registry** tab.
- **npm scopes** are on a group's **Settings › General** tab. Each opens
  its own page: its packages, and the pipelines and people who may install
  and publish under it.

## Limits

| Limit                                          | Value                                                                                |
| ---------------------------------------------- | ------------------------------------------------------------------------------------ |
| One generic package file                       | 5 GiB                                                                                |
| A generic package, version, alias or file name | 200 characters: letters, digits and `.` `_` `+` `-`, starting with a letter or digit |
| One npm tarball                                | 32 MiB                                                                               |
| An npm package name, with its scope            | 214 characters                                                                       |
| An npm scope                                   | 100 characters                                                                       |

Reads with no credential, where a repository's packages are public, are rate
limited by client address.

## What is not supported

- **Overwriting.** A published generic file and a published npm version are
  never replaced. Publish a new version.
- **Unscoped npm names.** Every npm package is `@scope/name`.
- **npm search, `npm audit`, provenance and web login** (`npm login`). Use a
  token in `.npmrc`.
- **Packages owned by a group**, or a registry URL per group. A scope
  belongs to a group; each package under it belongs to a repository.
- **Other package formats** (PyPI, Maven, NuGet and so on). Use a generic
  package for their files. Go modules are served from the repository itself
  and need no package.

Source: https://docs.branchd.run/branchd/packages

---

# Access to packages

> Who may read, publish and delete packages. Scopes and roles, which token to use, access to an npm scope or package, public packages and anonymous reads, and CI grants for another repository's jobs.
A repository's container images and generic packages share **one** set of
rules: if you can pull a repository's images, you can download its generic
packages, and the same goes for publishing and deleting.

**npm packages are different: they belong to a scope, not to a repository.**
The levels and tokens on this page are the same, but they are held on the
scope's group, on the scope or on one package. See
[npm scopes and packages](https://docs.branchd.run/branchd/packages/access#npm-scopes-and-packages).

## What you need

Three things decide a request, and all of them must allow it (see
[Access and tokens](https://docs.branchd.run/branchd/access)): the credential's scopes, the
repositories it reaches, and its owner's role today.

| To…                                                                                     | Scope                 | Role on the repository (for npm, on the scope or package) |
| --------------------------------------------------------------------------------------- | --------------------- | --------------------------------------------------------- |
| Download a generic package, install an npm package, list packages and versions          | `forge:package:read`  | read                                                      |
| Publish a file or an npm version; move an alias or a dist-tag                           | `forge:package:edit`  | write                                                     |
| Delete a file, version or package; deprecate or unpublish an npm version; set retention | `forge:package:admin` | maintain                                                  |
| Claim or release an npm scope                                                           | `forge:package:admin` | admin, on the group                                       |

A package you may not read answers as one that does not exist: `404` with a
credential, `401` without one.

## Which token

| Where                             | Use                                                                                                                                                                        |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Your own machine                  | `export BRANCHD_TOKEN=$(branchd auth token)`, after [`branchd auth login`](https://docs.branchd.run/branchd/access/cli-login)                                                                      |
| A script or a server              | A [personal API key](https://docs.branchd.run/branchd/access/personal-keys), bound to the repositories it needs: `branchd token create ci-pull --repo acme/tools/core --scopes forge:package:read` |
| Automation that belongs to a team | A [bot](https://docs.branchd.run/branchd/access/bots) key                                                                                                                                          |
| A branchd pipeline job            | Its [job token](https://docs.branchd.run/branchd/pipelines/job-token), already in `$BRANCHD_TOKEN`, with `permissions: packages: read` or `write`                                                  |

How each client sends it:

| Client                       | How                                                                                                       |
| ---------------------------- | --------------------------------------------------------------------------------------------------------- |
| `curl`, for generic packages | `--user "token:$BRANCHD_TOKEN"` (the username is ignored), or `-H "Authorization: Bearer $BRANCHD_TOKEN"` |
| npm and pnpm                 | `//registry.branchd.run/npm/:_authToken=${BRANCHD_TOKEN}` in `.npmrc` (for pnpm, in your own `~/.npmrc`)  |
| Docker                       | `docker login registry.branchd.run -u token --password-stdin`                                             |
| The `branchd` CLI            | Its own sign-in, or `BRANCHD_TOKEN` in a job                                                              |

With `curl -L`, prefer `--user` to a bearer header: curl does not send
`--user` on to the storage host a download redirects to.

## A pipeline job

A job's token reaches **its own repository's** images and generic packages,
at the level its `permissions:` ask for. npm packages it reaches through a
[CI grant](https://docs.branchd.run/branchd/packages/access#npm-scopes-and-packages) on their scope or on the package:

- **`packages: read`** downloads and installs.
- **`packages: write`** also publishes, and moves aliases and dist-tags. It
  needs a run of a **protected branch**, started by a push or by hand. On a
  pull request's run and on unprotected branches a job only reads.
- **A job never deletes, deprecates or unpublishes**, whatever it declares.

Every download and publish a job makes is recorded against its run.

## Another repository's jobs

A job's token reaches no other repository's private packages. To let the
jobs of one repository **read** another's, a maintainer of the repository
that owns the packages makes a **CI grant**:

```sh
branchd repo grant create acme/tools/core \
  --title "Core for the app's builds" \
  --to repo:acme/app --may packages=read --when protected
```

- **`--to`** is who: `repo:<path>`, `group:<path>` (every repository under
  it) or `team:<slug>`.
- **`--may packages=read`** is what. `packages=write` lets them publish too;
  a grant never lets a job delete.
  The same grant can carry other areas, such as `terraform-state=outputs`
  for [Terraform state](https://docs.branchd.run/branchd/terraform-state#let-another-repositorys-jobs-in).
- **`--when`** is on which runs: `protected` (runs of the grantee's protected
  branches), `any` (pull requests too), or `owner`, the default: whoever the
  run answers to must have that access to this repository themselves.
- **A person with maintain access makes a grant**, or an agent acting for
  them (an [agent session](https://docs.branchd.run/branchd/access/cli-login#agent-sessions)),
  which the grant records as its grantor. A bot or a job cannot.
- `branchd group grant create <group> …` grants on every repository under a
  group at once. `branchd repo grant list` shows a repository's grants,
  `branchd repo grant revoke <id>` ends one, and
  `branchd repo grant explain acme/tools/core --from acme/app` says what a
  job of `acme/app` would get, and why.

The job in `acme/app` then names the other repository: the `repository:`
input of the [package steps](https://docs.branchd.run/branchd/packages/generic#in-a-pipeline), or the other
repository's path in a generic package URL. It still declares
`permissions: packages: read`.

A repository's CI grants cover its images and generic packages. They do not
cover npm packages, which no repository owns.

## npm scopes and packages

An npm package belongs to its scope, and the scope to the group that
[claimed it](https://docs.branchd.run/branchd/packages/npm#claim-a-scope). Access is granted on the scope (every
package under it) or on one package, with the same two commands as above
and an npm name in place of a repository:

```sh
# pipelines: a CI grant
branchd npm grant create @acme --to team:partners --may read --when any
branchd npm grant create @acme/sdk --to repo:partner/sdk --may write

# people: an access grant
branchd npm access grant @acme --to @ana --role write
```

| Who                               | Reaches a scope's packages by                               |
| --------------------------------- | ----------------------------------------------------------- |
| A member of the group's team      | Their team role, as for anything in that group              |
| Anyone else                       | An access grant on the scope or on one package              |
| A pipeline job, of any repository | A CI grant on the scope or on one package, and nothing else |
| Anyone at all                     | The group showing packages publicly: read only              |

- **Claiming a scope makes the first CI grant**, to the claiming group: its
  repositories' jobs publish and install.
- **A job has no access through people.** The person who started a run may
  be able to publish; the job still needs the grant.
- **A job publishes only from a protected run**, with `permissions:
  packages: write`. It never deprecates or unpublishes.
- **Only a person makes a grant.**

[Who may install and publish](https://docs.branchd.run/branchd/packages/npm#who-may-install-and-publish) has every
option, and how to list, revoke and explain grants.

## Public packages

A repository can show its images and generic packages to people who are not
members. Two settings make that so:

1. the repository is **public** (its own setting, or inherited from its
   group), and
2. its **Packages** feature is public. Packages are members-only by default,
   even in a public repository.

In the console, both are on the repository's **Settings › General**, in the
visibility card. With the CLI:

```sh
branchd repo visibility acme/tools/core            # show it
branchd repo visibility acme/tools/core --set public --confirm-public-path acme/tools/core
branchd repo visibility acme/tools/core --feature packages=public --confirm-public-path acme/tools/core
```

A group's setting is inherited by every repository under it that inherits,
so a whole group can be made public at once:

```sh
branchd group visibility acme/tools                 # show it
branchd group visibility acme/tools --set public --feature packages=public --confirm-public-path acme/tools
```

- **A person with maintain access may make something public**, or an agent
  acting for them: through the branchd CLI in its
  [session](https://docs.branchd.run/branchd/access/cli-login#agent-sessions), or the Xeonr MCP
  gateway's `forge_update_repository` and `forge_update_group` with _write_
  ticked (with `confirm_public_path`). A bot, a job or an API key cannot.
- **It applies to the repository's images and generic packages together.**
- **It covers every version already published**, not only what is published
  from now on.

Once packages are public, anyone can read them with **no credential**:

```sh
curl -fL -O https://registry.branchd.run/generic/acme/tools/core/core/latest/core.so
```

- **Reads only.** Publishing, aliases, dist-tags and deletes always need a
  credential with access.
- **Anonymous reads are rate limited.** Use a token in CI.
- **A visitor sees less.** Who published a file or a version is shown to
  members only, and so are retention settings.
- **A credential that is wrong is refused**, not treated as anonymous: an
  expired token gets `401` even on a public package.

A repository can also show its packages to everyone signed in to its
company or its organisation without being public (`--set company`,
`--set organisation`).

### Public npm packages

npm packages read as the **group that holds their scope** shows packages:
there is no repository to ask. Make that group public, with its Packages
feature public, in the visibility card on its **Settings › General** tab.

Anyone then installs every package under the scopes it holds with the
registry line alone:

```ini
@acme:registry=https://registry.branchd.run/npm/
```

- **It is per group, so per scope.** To publish some packages publicly and
  keep others private, hold two scopes in two groups.
- **A repository's visibility does not make an npm package public**, even
  the repository that published it.
- Publishing, dist-tags and unpublishing still need a credential with
  access.

Source: https://docs.branchd.run/branchd/packages/access

---

# Generic packages

> Publish any file to a repository as a versioned package, and download it by version or by an alias such as latest, with curl, the CLI or a pipeline step.
A generic package is a set of files with a name and versions: a compiled
library, a data bundle, an installer. Use one for anything that is built once
and fetched by something else, and that is not an image or an npm package.

```
https://registry.branchd.run/generic/<repository>/<package>/<version>/<file>
```

- **`<repository>`** is the repository's full path, such as `acme/tools/core`.
  The package belongs to it.
- **`<package>`, `<version>` and `<file>`** are names you choose: letters,
  digits and `.` `_` `+` `-`, starting with a letter or digit, at most 200
  characters, never a slash. Names are not case-sensitive. A version can be a
  release number or a commit id.
- **Every file records its size and SHA-256** when it is published.
- **A published file is never overwritten.** Publishing the same name again
  in the same version is refused. Publish a new version.

The examples below read a token from `BRANCHD_TOKEN`. On your own machine,
set it to a [personal API key](https://docs.branchd.run/branchd/access/personal-keys) or to
`$(branchd auth token)`. In a pipeline job it is already set. See
[Access](https://docs.branchd.run/branchd/packages/access) for which token may do what.

## Publish a file

```sh
curl -f --user "token:$BRANCHD_TOKEN" --upload-file core.so \
  https://registry.branchd.run/generic/acme/tools/core/core/1.4.2/core.so
```

The username is ignored. The answer is the file as recorded:

```json
{"package":"core","version":"1.4.2","file":"core.so","size":18734112,"sha256":"95346e21…"}
```

- **The package and the version are created by the first file** published to
  them. Publish a version's other files the same way.
- **To have branchd check the bytes**, send their SHA-256 in an
  `X-Checksum-Sha256` header. A mismatch is refused and nothing is stored.
- **A second publish of the same file answers `409`**, whatever its bytes.
- **`latest` is never a version.** It is an [alias](https://docs.branchd.run/branchd/packages/generic#aliases), and a publish
  to it is refused.
- **One file is at most 5 GiB.** A `PUT` passes through branchd. For large
  files prefer the CLI or the pipeline step, which send the bytes straight to
  storage.

With the CLI (`branchd` 0.63 or later), which checks each file's SHA-256 on
arrival and can point an alias at the version once every file is up:

```sh
branchd package upload core 1.4.2 core.so core.info --alias latest -R acme/tools/core
```

Inside a clone of the repository, `-R` can be left out.

## Download a file

```sh
curl -fL --user "token:$BRANCHD_TOKEN" -O \
  https://registry.branchd.run/generic/acme/tools/core/core/1.4.2/core.so
```

- **`-L` is needed**: the answer is a redirect to a short-lived signed URL.
- **`<version>` may be an alias**: `…/core/latest/core.so`.
- **The checksum comes with the answer**, in `X-Checksum-Sha256`, with the
  version an alias resolved to in `X-Package-Version`. A `HEAD` request
  answers both, and the size, without downloading:

```sh
curl -sI --user "token:$BRANCHD_TOKEN" \
  https://registry.branchd.run/generic/acme/tools/core/core/latest/core.so
```

- **Where the repository's packages are public**, leave the credential out.
  See [Public packages](https://docs.branchd.run/branchd/packages/access#public-packages).

With the CLI, which downloads every file of a version and verifies each
against its recorded SHA-256:

```sh
branchd package download core latest -R acme/tools/core            # every file, into the current directory
branchd package download core 1.4.2 core.so --dir vendor -R acme/tools/core
```

`branchd package list` shows a repository's packages, and
`branchd package view core` one package's aliases and versions.

## Aliases

An alias is a movable name for one version of a package. `latest` is the
usual one; `stable`, `beta` or anything else works the same. A download URL,
the CLI and the pipeline step take an alias wherever they take a version.

- **Publishing a file never moves an alias.** You move it once the version
  is complete, so nobody downloads half of a version through `latest`.
- **An alias cannot have the name of one of the package's versions**, and a
  version cannot be named `latest`.
- **Removing an alias keeps the version.** Deleting a version removes the
  aliases that named it.

```sh
branchd package alias set core latest 1.4.2 -R acme/tools/core
branchd package alias remove core stable -R acme/tools/core
```

In the console, open the package and use **Set an alias**, or the edit and
delete buttons on an alias's row.

## In a pipeline

Two steps publish and download generic packages with the job's own token.
This pipeline publishes a build's file under the commit's short id, points
`latest` at it, and downloads it again by alias in a second job:

```yaml title=".branchd/pipelines/packages.yaml"
# .branchd/pipelines/packages.yaml
# Publishes a build's files as a generic package and points latest at it,
# then downloads them again by alias in a second job.
name: Packages
on:
  push:
    branches: [main]
permissions:
  packages: write
jobs:
  publish:
    image: alpine:3.22
    outputs:
      version: ${{ steps.publish.outputs.version }}
    steps:
      - run: |
          mkdir -p dist
          echo "built from $CI_COMMIT_SHA" > dist/hello.txt
      - id: publish
        uses: branchd/steps/forge/package-publish@v1
        isolated: true
        workspace: [dist/**]
        with:
          package: hello
          version: $CI_COMMIT_SHORT_SHA
          files: [dist/hello.txt]
          aliases: [latest]
  fetch:
    needs: [publish]
    image: alpine:3.22
    permissions:
      packages: read
    steps:
      - run: mkdir -p vendor && touch vendor/.keep
      - uses: branchd/steps/forge/package-download@v1
        isolated: true
        workspace: [vendor/**]
        with:
          package: hello
          version: latest
          path: vendor
      - run: cat vendor/hello.txt
```

- **`permissions: packages: write`** lets the job's token publish.
  `packages: read` is enough to download. A write needs a run of a protected
  branch: see [The job token](https://docs.branchd.run/branchd/pipelines/job-token).
- **`branchd/steps/forge/package-publish@v1`** takes `package`, `files` (paths or
  globs, each published under its base name, or `<name>=<path>`), and
  `version` or `version_file` (a file holding the version, for one an earlier
  step computes). `aliases` are pointed at the version once every file is
  published. `if_exists: keep` leaves an already published file alone instead
  of failing, for a re-run of the same commit. Its outputs are `version` and
  `files`.
- **`branchd/steps/forge/package-download@v1`** takes `package`, and optionally
  `version` (a version or an alias; `latest` when left out), `files` (every
  file of the version when left out) and `path` (the directory to write
  into). Each file is checked against its recorded SHA-256.
- **Both are typed steps**, so among `run:` steps they are marked
  `isolated: true`, and `workspace:` names the directory they share with the
  other steps. See
  [Isolate a step from the job](https://docs.branchd.run/branchd/pipelines/isolated-steps).
- **`repository:`** on either step names another repository's package. That
  needs a [CI grant](https://docs.branchd.run/branchd/packages/access#another-repositorys-jobs) there.

A `run:` step can also use `curl` exactly as above: `$BRANCHD_TOKEN` is the
job's token.

## Delete

Deleting is permanent: the stored bytes go, and download links stop working
at once. It needs maintain access to the repository.

```sh
branchd package delete core 1.4.0 core.info -R acme/tools/core   # one file
branchd package delete core 1.4.0 -R acme/tools/core             # one version, its files and aliases
branchd package delete core -R acme/tools/core                   # the whole package
```

- **A version left with no file is removed**, with the aliases that named it.
- **A deleted version's name can be published again.**
- **A pipeline job never deletes.**

In the console, each needs its name typed to confirm.

## Retention

By default nothing is ever deleted. A repository can set a retention policy
for its generic packages, on its **Settings › Releases and registry** tab:

- **Keep the newest _N_ versions** of each package;
- **Keep everything published within _D_ days**;
- a version **an alias names is always kept**.

A version is deleted only when none of the three keeps it. **Dry run** on the
same panel lists what the policy would delete now, without deleting anything.
branchd applies the policy on a schedule; there is no button to apply it now. Setting or
removing a policy needs maintain access.

## The API

`xeonr.forge.v1.GenericPackageService` does everything above, and is what the
console and the CLI use:

| Method                                                                                                                                       | Does                                                                                                                                       |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `ListGenericPackages`, `GetGenericPackage`                                                                                                   | A repository's packages: aliases, newest version, version count and download prefix                                                        |
| `ListGenericPackageVersions`, `GetGenericPackageVersion`                                                                                     | Versions with their files: name, size, SHA-256 and download URL                                                                            |
| `GetGenericPackageFileDownload`                                                                                                              | A short-lived signed URL for one file, which needs no credential                                                                           |
| `CreateGenericPackageFile`, `CompleteGenericPackageFile`                                                                                     | Declare a file with its size and SHA-256, `PUT` the bytes to the upload URL it answers, then complete it. How the CLI and the step upload. |
| `SetGenericPackageAlias`, `DeleteGenericPackageAlias`                                                                                        | Move or remove an alias                                                                                                                    |
| `DeleteGenericPackageFile`, `DeleteGenericPackageVersion`, `DeleteGenericPackage`                                                            | Delete; each takes the name again as `confirm_file`, `confirm_version` or `confirm_package`                                                |
| `GetGenericPackageRetentionPolicy`, `SetGenericPackageRetentionPolicy`, `DeleteGenericPackageRetentionPolicy`, `PlanGenericPackageRetention` | The retention policy and its dry run                                                                                                       |

Calls are made as on [The job token](https://docs.branchd.run/branchd/pipelines/job-token#calling-the-api)
page: an HTTP `POST` of JSON with a bearer token.

Source: https://docs.branchd.run/branchd/packages/generic

---

# npm packages

> Publish scoped npm packages to branchd and install them with npm or pnpm. Claiming a scope, who may install and publish under it, .npmrc, pipelines of other teams, dist-tags, deprecating and unpublishing.
branchd serves an npm registry for **scoped** packages (`@scope/name`):

```
https://registry.branchd.run/npm/
```

npm and pnpm install from it and publish to it themselves. There is nothing
to install on top of them.

- **A scope belongs to one group.** A group's administrator
  [claims it](https://docs.branchd.run/branchd/packages/npm#claim-a-scope).
- **A package belongs to its scope**, and so to that group. No repository
  owns a package: a repository is only where a version was published from.
- **Who may install and publish is granted**, on the scope or on one
  package: to people, and to the pipelines of repositories. See
  [Who may install and publish](https://docs.branchd.run/branchd/packages/npm#who-may-install-and-publish).
- **A version is published once.** Its number is never used again, even
  after it is unpublished.

The examples read a token from `BRANCHD_TOKEN`. On your own machine, set it
to a [personal API key](https://docs.branchd.run/branchd/access/personal-keys) or to
`$(branchd auth token)`. In a pipeline job it is already set.

## Claim a scope

Before the first publish, a group claims the scope. It needs **admin**
access to the group. A team's root group is named by the team's slug.

```sh
branchd npm scope claim acme @acme         # the team acme's root group
branchd npm scope claim acme/tools @tools  # a group
branchd npm scope list acme
```

Or in the console: the group's **Settings › General**, **npm scopes**,
**Claim a scope**.

- **A scope has one owner on the whole of branchd.** Claiming one another
  group holds is refused.
- **A scope name** is lower-case letters, digits and `.` `_` `-`, starting
  with a letter or digit, at most 100 characters. It does not have to match
  the group's name.
- **Claiming makes one grant**: the pipelines of the group's own
  repositories may publish and install under the scope. It is listed with
  the scope's other grants, and can be revoked like them.
- **Releasing a scope** (`branchd npm scope release @acme`) is refused while
  a package under it still has a published version. Its grants go with it.
- **Deleting the group** is refused the same way while one of its scopes has
  a published version.

## Install a package

Two lines of `.npmrc`: where the scope lives, and the credential for it.

```ini
@acme:registry=https://registry.branchd.run/npm/
//registry.branchd.run/npm/:_authToken=${BRANCHD_TOKEN}
```

```sh
npm install @acme/widgets
pnpm add @acme/widgets
```

- **Put the token line in your own `~/.npmrc`.** npm also reads it from a
  project's `.npmrc`, but **pnpm does not**: it ignores a credential with a
  variable in a project's `.npmrc`, and the install fails with `401`. The
  `@acme:registry=` line can live in either file, so a project can commit it.
- **Never commit a token.** `${BRANCHD_TOKEN}` is read from the environment
  when npm or pnpm runs.
- **Where the scope's group shows packages publicly**, the registry line
  alone is enough. See [Public packages](https://docs.branchd.run/branchd/packages/access#public-npm-packages).
- **Other scopes and unscoped packages** still come from the registry you
  already use. Only `@acme` is sent to branchd.

`branchd npm view @acme/widgets` prints a package's owner, your own level on
it, its dist-tags, versions and these lines, ready to copy. So does the
package's page in the console.

## Publish a package

Everyone publishes at the registry itself, with the same two `.npmrc` lines
that install. Nothing in `package.json` says where:

```sh
npm publish
pnpm publish
```

- **You need write access to the scope**, or to the package. See
  [Who may install and publish](https://docs.branchd.run/branchd/packages/npm#who-may-install-and-publish).
- **A new name under the scope** needs access to the scope itself. Access
  to one package publishes new versions of that package only.
- **The first publish gets the `latest` dist-tag.** Later publishes move
  `latest` unless you pass `--tag`: `npm publish --tag next`.
- **A tarball is at most 32 MiB.**
- **Publishing a version that exists is refused** (`403`, "You cannot
  publish over the previously published versions").
- **A scope nobody has claimed is refused**, with the command that claims it.

`https://registry.branchd.run/npm/-/repository/<repository>/` still answers:
it is the same registry. Packages belonged to repositories at first and a
publish went through that URL. You no longer need it, or a `publishConfig`.

## Who may install and publish

Access is on a **scope** (every package under it, new names included) or on
**one package**.

| Level    | For people                                            | For pipelines                                |
| -------- | ----------------------------------------------------- | -------------------------------------------- |
| read     | Install; see versions and dist-tags                   | Install                                      |
| write    | Publish; move dist-tags                               | Publish; move dist-tags; install             |
| maintain | Deprecate and unpublish; manage the scope's CI grants | Never: a job does not deprecate or unpublish |
| admin    | Also manage people's access                           |                                              |

### People

- **Members of the group's team** have their team role on every scope the
  group holds, as on anything else in that group. Access grants and limits
  set on the group apply too.
- **Anyone else** is given a level on the scope or on one package: a person,
  every person in a Xeonr Auth team, a bot, or someone invited by email.

```sh
branchd npm access grant @acme --to @ana --role write
branchd npm access grant @acme/widgets --to team:partners --role read
branchd npm access list @acme/widgets --inherited
branchd npm access explain @acme/widgets --for @ana
branchd npm access revoke @acme --to @ana
```

- These are [`branchd access`](https://docs.branchd.run/branchd/access) with an npm name. A
  limit (`branchd npm access limit`) caps what someone has from above.
- **Changing access needs admin** on the scope, as yourself or an agent
  acting for you: a bot or an API key cannot.
- **A grant on one package needs the package to exist.**

### Pipelines

A job's token reaches a scope or a package **only through a CI grant** on
it: who (whose jobs), may (read or write), when (on which runs). A job has
no access because the person who started it does.

```sh
# every repository of two other teams installs the whole scope, on any run
branchd npm grant create @acme --to team:tmpsn --to team:upl-im --may read --when any

# one repository installs one package
branchd npm grant create @acme/sekrit-tools --to repo:upl-im/api --may read --when any

# one repository publishes one package, from its protected branches
branchd npm grant create @acme/private-tools --to repo:upl-im/api --may write

# a team, or one group, publishes anything under the scope
branchd npm grant create @acme --to team:acme --may write
branchd npm grant create @acme --to group:acme/test --may write
```

- **`--to`** is `repo:<path>`, `group:<path>` (every repository under it),
  `team:<slug>` or `company:<urn>`. Repeat it for several.
- **`--may read`** installs. **`--may write`** publishes new versions (on a
  scope, new packages too), moves dist-tags and installs.
- **`--when`** is `protected` (runs of the grantee's protected branches, the
  default), `any` (pull requests too), or `owner`: whoever the run answers
  to must have that access to the package themselves.
- **A job publishes only from a protected run**, whatever the grant says: a
  push or a manual run of a protected branch, with `permissions: packages:
  write`. `--when any` on a write grant adds installing from every run, not
  publishing.
- **A grant on a package can be made before its first version**, so the
  repository that will publish it, and the ones that will install it, are
  let in first.
- **A person with maintain access to the scope makes or revokes a grant**,
  or an agent acting for them, recorded as the grant's actor. A bot or a job
  cannot.

```sh
branchd npm grant list @acme
branchd npm grant list @acme/widgets --inherited   # with its scope's
branchd npm grant revoke <id>
branchd npm grant explain @acme/widgets --from upl-im/api --protected
branchd repo grant reaches upl-im/api              # everything that repository's jobs reach
```

`explain` says whether a job of that repository would install or publish,
and which grant or rule decided. A job that is refused is told the grant it
needs, in the error npm prints and in its run's record.

In the console, a scope's page (the group's **Settings › General**, **npm
scopes**) and each package's page list **Pipelines** and **People**, with
the same controls.

## In a pipeline

A job publishes with its own token and plain `npm publish`. No secret is
stored:

```yaml title=".branchd/pipelines/publish.yaml"
# .branchd/pipelines/publish.yaml
# Publishes the npm package in this repository to branchd's npm registry with
# the job's own token: no stored secret. @acme is a scope whose CI grants let
# this repository publish: one a group above it claimed, or one another team
# granted it.
name: Publish
on:
  push:
    branches: [main]
permissions:
  packages: write
jobs:
  publish:
    image: node:22-alpine
    steps:
      - run: |
          printf '@acme:registry=https://registry.branchd.run/npm/\n//registry.branchd.run/npm/:_authToken=${BRANCHD_TOKEN}\n' > .npmrc
          npm publish
```

- **`permissions: packages: write`** lets the job's token publish, on a run
  of a protected branch. `packages: read` is enough to install. See
  [The job token](https://docs.branchd.run/branchd/pipelines/job-token).
- **The repository needs a CI grant on the scope or the package.** A
  repository in the group that claimed the scope has one from the claim.
- **Give each run a new version**, or publish from a tag: a version that
  exists is refused.
- **A job never deprecates or unpublishes.**
- **Each version records where it was published from**: the repository,
  branch, commit and run. `branchd npm view` and the console show it.

### From another team

A repository in another team publishes under your scope, and installs from
it, once you grant it. Say team `acme` holds `@acme`, `partner/sdk`
publishes `@acme/sdk`, and `partner/app` installs it:

```sh
branchd npm grant create @acme/sdk --to repo:partner/sdk --may write
branchd npm grant create @acme/sdk --to repo:partner/app --may read --when any
```

- **`partner/sdk`** then runs `npm publish` on its protected branch, with
  `permissions: packages: write` and the two `.npmrc` lines above.
- **`partner/app`** runs `npm install` with `permissions: packages: read`.
- **The package is `acme`'s.** Its people manage it; the people of
  `partner` have no access to it unless you give them some.

The typed step `branchd/steps/node/npm-package-publish@v1` builds and publishes a
package in one step. With no `registry:` input it publishes to branchd with
the job's token, and its `package_scopes:` input lists scopes to install from
branchd the same way.

## Dist-tags

A dist-tag is a movable name for a version: `npm install @acme/widgets@next`.
`latest` is what an install with no tag or version gets.

```sh
npm dist-tag add @acme/widgets@2.0.0-rc.1 next
npm dist-tag ls @acme/widgets

branchd npm dist-tag set @acme/widgets next 2.0.0-rc.1
branchd npm dist-tag remove @acme/widgets next
```

- **A dist-tag is a name starting with a letter**, never something that
  reads as a version or a range (`1.4.2`, `v1`).
- **`latest` moves but is never removed.**
- Moving a dist-tag needs write access to the package or its scope. In the
  console, use **Add a dist-tag** or the edit button on a tag's row.

## Deprecate and unpublish

Both need **maintain** access to the package or its scope.

```sh
npm deprecate @acme/widgets@1.3.0 "Use 1.4 or later"
branchd npm deprecate @acme/widgets 1.3.0 "Use 1.4 or later"
branchd npm deprecate @acme/widgets 1.3.0 --clear

branchd npm unpublish @acme/widgets 1.4.1
```

- **Deprecating** sets the message every install of that version prints.
  The version still installs. An empty message clears it.
- **Unpublishing** deletes the version's tarball. Installs that pin it fail,
  lockfiles included. Its number is never used again. A dist-tag that
  pointed at it is removed, and `latest` moves to the highest version left.
  This cannot be undone: to warn people off a version, deprecate it instead.
- **A package's name stays its scope's** after every version is
  unpublished. Deleting a repository that published it changes nothing.

## What branchd checks

- **Names.** `@scope/name`, lower case, at most 214 characters. An unscoped
  name is refused.
- **Versions.** Full semantic versions (`1.4.2`, `2.0.0-rc.1`), with no
  leading `v`.
- **Checksums.** branchd computes each version's `shasum` and `integrity`
  from the bytes it stored. It does not take them from the client.

## The API

`xeonr.forge.v1.NpmPackageService` is what the console and the CLI use for
everything npm itself has no command for:

| Method                                                             | Does                                                                                                                                                                    |
| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ListNpmPackages`, `GetNpmPackage`                                 | The packages of a scope, of a group's scopes, or the ones a repository published; or one by name: its owning group, your level, `registry`, dist-tags and version count |
| `ListNpmPackageVersions`                                           | Versions, newest first: size, `shasum`, `integrity`, dist-tags, deprecation, where it was published from, and whether it was unpublished                                |
| `SetNpmDistTag`, `DeleteNpmDistTag`                                | Move or remove a dist-tag                                                                                                                                               |
| `DeprecateNpmPackageVersion`, `UnpublishNpmPackageVersion`         | Deprecate (an empty `message` clears it), or unpublish with `confirm_version`                                                                                           |
| `ListNpmScopes`, `GetNpmScope`, `ClaimNpmScope`, `ReleaseNpmScope` | A group's scopes                                                                                                                                                        |

Grants are `GrantService` (`CreateGrant`, `ListGrants`, `RevokeGrant`,
`ExplainCIAccess`) and `AccessService` (`GrantAccess`, `ListAccess`,
`ExplainAccess`), with `npm` set to `@scope` or `@scope/name`.

Source: https://docs.branchd.run/branchd/packages/npm

---

# Your personal namespace

> Every person has their own space in branchd at /<username>, for repositories that are theirs rather than a team's.
> **Available** (personal namespaces): branchd serves them. Your account has one once Xeonr Auth has given you a personal team, which is still being rolled out to accounts. `branchd whoami` (CLI 0.76.0 or later) says whether yours exists yet.

Your personal namespace is your own space in branchd, at
`https://branchd.run/<your username>`. It is not a team: nobody else is a
member of it, and it never appears in the team switcher. You reach it from
**Personal repositories** in the sidebar of your Home, and the card at the
top of the sidebar says **You** while you are in it.

Xeonr Auth makes it for you when your account becomes active. Its name is
your username, so a repository `dots` in it clones as:

```sh
git clone https://branchd.run/<your username>/dots.git
```

## Create a repository in it

In the console, choose **New repository** in your Home's sidebar. From a
terminal, give the CLI a name with no team:

```sh
branchd repo create dots
branchd whoami      # your account and your personal namespace
```

`branchd repo create <team>/<name>` still creates one in a team. An agent
using branchd's MCP tools sets `personal` on `create_repository`, or reads
`get_personal_namespace` first.

## What it has, and what it does not

A personal namespace works like a team for your own work: repositories,
groups, pull requests, branch rules, releases, packages, pipelines,
visibility and access. It leaves out what only makes sense for a team:

|                                | In a team                  | In your personal namespace                                                |
| ------------------------------ | -------------------------- | ------------------------------------------------------------------------- |
| Members                        | The team's people          | Only you                                                                  |
| Sharing a repository           | Team membership or a grant | A grant to a person, on the repository or a group (**Settings › Access**) |
| Team bots                      | Yes                        | No: make a bot in a team                                                  |
| Trellis project binding        | Yes                        | No                                                                        |
| Company runner pools           | The team's company's       | None: [bring your own runner](https://docs.branchd.run/branchd/pipelines/bring-your-own-runner)   |
| Personal API keys and SSH keys | Yours, across your teams   | The same keys reach it                                                    |

branchd refuses the team-only operations on a personal namespace with an
error that says it is a personal namespace.

## Someone else's

Anyone can open another person's namespace at `/<their username>`. Signed
in or not, they see only what that person made public, and the page names
the person, not a team.

## If your username changes

An administrator can change a username in Xeonr Auth. Your namespace moves
with it: every repository's path starts with the new name, and the old paths
keep working as redirects, for git and in the console, until something new is
created at them.

Source: https://docs.branchd.run/branchd/personal-namespace

---

# Pipelines

> What a branchd pipeline is, what is available today, and where each task and key is documented.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

A pipeline is a YAML file in your repository, `.branchd/pipelines/<name>.yaml`,
that says when it runs (`on:`) and which jobs it runs (`jobs:`). Each job runs
its steps in a container, with your repository already checked out. Jobs run
in parallel unless one `needs` another. Everything about which jobs run is
decided before the run starts, so `branchd ci plan` can tell you, for any
branch or event, which jobs will run and why.

The syntax follows GitHub Actions closely: `on`, `jobs`, `steps`, `needs`,
`if`, `matrix`, `${{ }}` expressions and `uses:`. It is not GitHub Actions:
the differences are in [Coming from GitLab CI](https://docs.branchd.run/branchd/pipelines/from-gitlab-ci)
and throughout the [reference](https://docs.branchd.run/branchd/pipelines/reference).

## For agents and editors

- **The complete reference in one file**, as Markdown:
  [`/branchd/pipelines/reference.md`](https://docs.branchd.run/branchd/pipelines/reference.md).
  Every key, every refusal rule and every limit, on one page.
- **Every page of this section in one file**:
  [`/branchd/pipelines/llms-full.txt`](https://docs.branchd.run/branchd/pipelines/llms-full.txt),
  with an index at [`/branchd/pipelines/llms.txt`](https://docs.branchd.run/branchd/pipelines/llms.txt).
  The site's own index is [`/llms.txt`](https://docs.branchd.run/llms.txt).
- **The JSON Schema** of a pipeline file, for editors:
  [`https://docs.xeonr.io/schemas/branchd/pipeline.json`](https://docs.branchd.run/schemas/branchd/pipeline.json)
  (and [`step.json`](https://docs.branchd.run/schemas/branchd/step.json), [`packages.json`](https://docs.branchd.run/schemas/branchd/packages.json)).
  See [Editor support and the schema](https://docs.branchd.run/branchd/pipelines/schema).
- **The loop for an agent writing a pipeline**: [Writing pipelines with an AI agent](https://docs.branchd.run/branchd/pipelines/ai-agents).

Every YAML example in these pages is a file that branchd's compiler accepts:
the examples are compiled for every event they list before the pages change.

## Start here

- [Quick start (five minutes)](https://docs.branchd.run/branchd/pipelines/quickstart): Add a pipeline, check it locally, push it, and read its checks.
- [Concepts](https://docs.branchd.run/branchd/pipelines/concepts): Pipeline, run, job, step, needs, the checkout, and what is decided before a run starts.

## Tasks

Each page is one task and one complete file you can copy.

- [Run tests on a pull request](https://docs.branchd.run/branchd/pipelines/test-on-pull-request)
- [Build and push an image](https://docs.branchd.run/branchd/pipelines/build-and-push-an-image)
- [Run a job for several versions (matrix)](https://docs.branchd.run/branchd/pipelines/matrix)
- [Reuse a step](https://docs.branchd.run/branchd/pipelines/composite-steps)
- [Call a pipeline](https://docs.branchd.run/branchd/pipelines/reusable-pipelines)
- [Run on a schedule](https://docs.branchd.run/branchd/pipelines/schedules)
- [Trigger another repository's pipeline](https://docs.branchd.run/branchd/pipelines/trigger-another-repository)
- [A manual pipeline with inputs](https://docs.branchd.run/branchd/pipelines/manual-runs)
- [Use the job token (curl and git)](https://docs.branchd.run/branchd/pipelines/job-token)
- [Isolate a step from the job](https://docs.branchd.run/branchd/pipelines/isolated-steps)

More tasks: [a Go service with a database](https://docs.branchd.run/branchd/pipelines/test-go-with-database),
[a Node.js project](https://docs.branchd.run/branchd/pipelines/test-node),
[deploy](https://docs.branchd.run/branchd/pipelines/deploy),
[caches and artifacts](https://docs.branchd.run/branchd/pipelines/caches-and-artifacts),
[outputs](https://docs.branchd.run/branchd/pipelines/outputs),
[secrets](https://docs.branchd.run/branchd/pipelines/secrets),
[environments and approval](https://docs.branchd.run/branchd/pipelines/environments-and-approval),
[paths](https://docs.branchd.run/branchd/pipelines/paths),
[several pipelines](https://docs.branchd.run/branchd/pipelines/several-pipelines),
[steps and pipelines of another repository](https://docs.branchd.run/branchd/pipelines/other-repositories),
[presets](https://docs.branchd.run/branchd/pipelines/presets).

## Reference

- [Pipeline file reference](https://docs.branchd.run/branchd/pipelines/reference): Every key, in one page.
- [Expressions](https://docs.branchd.run/branchd/pipelines/expressions): ${{ }}, contexts, functions and variables.
- [Step files](https://docs.branchd.run/branchd/pipelines/step-files): step.yaml and .branchd/packages.yaml.
- [Limits](https://docs.branchd.run/branchd/pipelines/limits)
- [Refusals](https://docs.branchd.run/branchd/pipelines/errors): What the compiler refuses, and what to write instead.
- [Troubleshooting](https://docs.branchd.run/branchd/pipelines/troubleshooting): A refused push, a job that does not run, a check that never reports.

## What is available

Pipeline files are on in production, and branchd is switching repositories
to them one at a time. A repository that is not switched on runs its
`.forge-ci.yaml` or `.xeonr-ci.yaml` exactly as before, and ignores
`.branchd/pipelines/`. In a repository that is switched on:

| Part                                                                                                             | State     |
| ---------------------------------------------------------------------------------------------------------------- | --------- |
| Jobs, steps, `needs`, `if`, matrix, services, caches, artifacts, secrets, environments, manual jobs, superseding | Available |
| The automatic checkout (no git needed in the image)                                                              | Available |
| Push checks: a push whose changed pipeline file does not compile is refused, with file and line                  | Available |
| Manual runs with inputs, schedules, triggers of this repository's own pipelines                                  | Available |
| Composite steps and reusable pipelines, of this repository or another                                            | Available |
| Typed steps (`uses: branchd/steps/<step>@v1`), alone or `isolated: true` among `run:` steps                      | Available |
| The job token and `permissions:`                                                                                 | Available |
| Presets of another repository (`preset: {uses: <group>/<repo>/<path>@v1}`)                                       | Available |
| Optional secrets of a step                                                                                       | Available |

**Not available yet**, each said again on the page it concerns:

- **Triggering another repository's pipeline** works only when that
  repository is switched on too; today a trigger to any other repository is
  refused. A repository triggering its own pipelines works.
- **A preset of the same repository** (`preset: {uses: ./<path>}`) is
  refused; a preset comes from another repository.
- **Starting a manual run with inputs from the console**: the console starts
  a run of a branch only. Use the CLI or the API ([Manual runs](https://docs.branchd.run/branchd/pipelines/manual-runs)).
- **The CLI features these pages use**, `branchd run start --pipeline … --input …` and `branchd ci lint` checking every event a file lists, are in
  the next CLI release (0.39.0). `branchd ci lint` and `ci plan` of earlier
  releases (0.33.0 and later) read pipeline files, but check fewer situations.
- **Refused for now**, each with a clear message: `max-parallel`,
  `fail-fast: true`, a `matrix:` on a job that calls a pipeline, a lock over
  a whole pipeline (`concurrency.group` at the top level), `checkout:
  {submodules}`, a job `if:` that reads another job's outputs, a step `if:`
  that reads `steps.*.outputs`.
- **Steps published by other products** (`uses: strata/migrate@1`).
- **A `run:` job's outputs as an `image:` or a typed step's `with:`**: only a
  typed step's outputs reach those ([Outputs](https://docs.branchd.run/branchd/pipelines/outputs)).
- **The branchd CLI inside a job**: it is not in job images. A job can
  install it with `curl -fsSL https://updater.xeonr.io/96/install.sh -o
  install.sh && env -u BRANCHD_TOKEN sh install.sh` (the installer reads
  `BRANCHD_TOKEN` as its own token, so the job's token is left out). The job
  token also works with `curl` and `git`
  ([The job token](https://docs.branchd.run/branchd/pipelines/job-token)).

Source: https://docs.branchd.run/branchd/pipelines

---

# Writing pipelines with an AI agent

> What to give an AI agent so it writes correct pipeline files, and the loop it should follow.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

> **Not yet available** (cli 0.39.0): `branchd ci lint` checking every event a file lists (as the push check does) and `branchd run start --pipeline … --input …` are in the next CLI release. `ci lint` and `ci plan` from 0.33.0 read pipeline files; `branchd upgrade` updates.

## Give it three things

1. **The complete reference, one file**:
   `https://docs.xeonr.io/branchd/pipelines/reference.md`: every key,
   rule and limit in plain Markdown. For worked examples too, every page of
   the section in one fetch:
   `https://docs.xeonr.io/branchd/pipelines/llms-full.txt` (index:
   `…/pipelines/llms.txt`).
2. **The schema**: `https://docs.xeonr.io/schemas/branchd/pipeline.json` (and
   `step.json`, `packages.json`).
3. **The commands** it may run: `branchd ci lint` and `branchd ci plan`, from
   the repository's root.

A prompt that works:

```text
Write .branchd/pipelines/ci.yaml for this repository. Read
https://docs.xeonr.io/branchd/pipelines/llms-full.txt first and use only
keys it documents (the reference alone is …/pipelines/reference.md); the schema is
https://docs.xeonr.io/schemas/branchd/pipeline.json. After each change, run
`branchd ci lint` and fix every refusal it prints, then run
`branchd ci plan` for a push to main and for a pull request
(`branchd ci plan --event pull_request`) and check that the jobs I expect run.
Do not push until lint passes.
```

## The loop

1. **Write** the file, starting from the closest guide's example. Every
   example names its path on its first line.
2. **`branchd ci lint`**: compiles every pipeline file for a push to the
   default branch, to `stage`, to a feature branch, a `v` tag, a pull request,
   a scheduled run and a manual run of each pipeline that has one, then each
   file for every event its `on:` lists (as branchd checks a push). Exit code 1
   means at least one case was refused; each refusal names the file and line,
   and most say what to write instead
   ([Refusals](https://docs.branchd.run/branchd/pipelines/errors)).
3. **`branchd ci plan`**: lists every job, whether it runs for that ref and
   event, and why. `--ref <branch or tag>`, `--event push|pull_request|schedule|manual|trigger`,
   `--pipeline <name>` and `--input k=v` choose the case. `--json` prints it for a program to read.
4. **Push.** branchd compiles the changed files again for every event; a
   file the push breaks refuses the push with `file:line:column: message`.
   Fix it and push again; do not use `-o ci.allow-invalid`. Then read the
   run: `branchd run watch <n>`, then
   `branchd run failure <n>` if it fails.

## Things agents get wrong

- **GitHub Actions habits.** There is no `actions/checkout` (the checkout is
  automatic), no `runs-on: ubuntu-latest` (jobs name an `image:`), no
  `github.*` context (use `branch`, `sha`, `event`, `pr.number`), no
  `hashFiles()` (use `cache.files`), and no `${{ secrets.X }}` (list the secret
  under the job's `secrets:` and read `$X`).
- **GitLab CI habits.** `stages`, `script`, `rules`, `variables` and `extends`
  are refused, each with its replacement in the message.
- **`if:` on outputs.** `if:` is decided before the run starts and cannot read
  `steps.*` or `needs.*` outputs.
- **A need on a job that does not run.** Give both jobs the same `if:`, or mark
  the need `optional: true`.
- **`.yml`.** Files end in `.yaml`.
- **`${{ secrets.X }}` and `github.token`.** The job token is
  `$BRANCHD_TOKEN`, and it reads only its own repository; ask for more with
  `permissions:`.
- **A typed step among `run:` steps** needs `isolated: true` and a
  `workspace:`.
- **Assuming the CLI is in the job.** It is not; use `curl` and `git` with
  `$BRANCHD_TOKEN`.

Source: https://docs.branchd.run/branchd/pipelines/ai-agents

---

# Bring your own runner

> Run a personal namespace's pipelines, or any group's, on a runner pool you register yourself.
> **Available** for any group's pool today. Personal namespaces are being turned on for everyone; until yours exists, register a pool on a team's group instead.

A job runs on a runner from a **runner pool** that reaches its repository: a
pool on the repository's group or any group above it, a pool shared with
one of those, or a pool of the team's company. A
[personal namespace](https://docs.branchd.run/branchd/personal-namespace) has no company, so
no company pool reaches it: its pipelines run only on a pool you register
yourself.

Until a pool reaches a repository, its jobs wait with the reason **No runner
pool reaches this repository** and then fail, saying that no runner pool can
take the job. Nothing else picks them up.

## 1. Make a pool

With a signed-in [branchd CLI](https://docs.branchd.run/branchd/pipelines/quickstart), create
a pool on your namespace (or on one of its groups), with the labels your
jobs' `runs-on` will name:

```sh
branchd pool create <your username> laptop --labels linux --description "My workstation"
```

It prints the pool's registration token (`fpt_…`) once.
`branchd pool rotate-token <pool>` prints a new one. In the console the same
is under **Settings › Runners** of your namespace.

## 2. Run a runner for it

Register a machine with the token. On a Mac, follow
[Run a runner on a Mac](https://docs.branchd.run/branchd/pipelines/mac-runner). Check the
pool and its runners with:

```sh
branchd pool show <your username>:laptop
branchd runner list <your username>:laptop
branchd pool inheritance show <your username>    # which pools reach it, and from where
```

## 3. Point jobs at it

A job runs on a pool whose labels include all of its `runs-on` labels. With
the pool above, `runs-on: [linux]` runs there. A job with no `runs-on` runs
on a pool labelled `untagged`; add that label if you want unlabelled jobs on
your runner too.

Your runner runs your jobs with whatever access the machine has. Read
[Security](https://docs.branchd.run/branchd/pipelines/security) before giving a pool to work
you did not write.

Source: https://docs.branchd.run/branchd/pipelines/bring-your-own-runner

---

# Build and push an image

> Build the repository's Dockerfile, push the image to the branchd registry, and run a job in the image you built.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Test, then build the repository's Dockerfile and push the image to the
# branchd registry on pushes to main. The build job passes the image's
# reference on as an output.
name: CI
on:
  push:
    branches: [main]
  pull_request:
jobs:
  test:
    image: golang:1.26
    steps:
      - run: go test ./...
  build:
    needs: [test]
    if: branch == 'main' && event == 'push'
    outputs:
      image: ${{ steps.image.outputs.image }}
    steps:
      - id: image
        # Also written branchd/steps/images/image-build@v1, the step's address.
        uses: ci/image-build@1
        with:
          image: $CI_REGISTRY_IMAGE
          tag: $CI_PIPELINE_IID
          dockerfile: Dockerfile
  smoke:
    # build runs only on pushes to main, so smoke has the same if:. A need
    # on a job that does not run is refused, unless it is optional: true.
    if: branch == 'main' && event == 'push'
    needs: [build]
    # The job runs in the image the build job pushed.
    image: ${{ needs.build.outputs.image }}
    steps:
      - run: /app/server --version
```

- **`uses: branchd/steps/images/image-build@v1`** is a typed step: one program
  that runs in its own image, published in branchd's shared step repository,
  `branchd/steps`. It builds `dockerfile` from the checkout and pushes
  `image:tag`. Its output `image` is the pushed reference,
  `<image>:<tag>@<digest>`.
- **`$CI_REGISTRY_IMAGE`** is this repository's path in the branchd registry,
  and **`$CI_PIPELINE_IID`** the run's number. `$NAME` of a variable known
  when the run is compiled expands in `with:`.
- **The job's `outputs:`** pass the step's output on. A job that needs
  `build` reads it as `${{ needs.build.outputs.image }}`, here as the
  `image:` of the job that runs next.
- **The same `if:`** on `build` and `smoke`: `smoke` needs `build`, and a need
  on a job that does not run is refused. On a pull request neither runs.

As the job's **only** step, a typed step needs nothing more: the job is the
step, so it has no `image:` and no `run:` steps, and its `if:` goes on the
job. Among `run:` steps it must be marked `isolated: true`; see
[Isolate a step from the job](https://docs.branchd.run/branchd/pipelines/isolated-steps). A
job of its own, as here, is the simpler choice when the next step needs
only its output.

`branchd/steps/images/image-build@v1` takes `image`, `tag` and `dockerfile` (all
required), and `build_args` (a map of `--build-arg` values), `push_latest`
and `build_mode`. `@v1` is the newest published `v1.x.y` tag of
`branchd/steps/images`; `@v1.0.2` is exact. The old name, `ci/image-build@1`,
still resolves, to `branchd/steps/images/image-build` at a release branchd moves;
it is kept for existing files, and new files use the address.

**Go modules in the build.** The step also passes a `GOPROXY` build argument,
`<branchd>/-/go/,direct`, unless `build_args` names `GOPROXY` itself, with
the job's modules token as `CI_JOB_TOKEN`. A Dockerfile opts in with
`ARG GOPROXY` before its `go` commands; it then fetches Go modules,
your team's private ones included, through branchd's module proxy. A
Dockerfile without `ARG GOPROXY` is built as before.

**Lantern releases and source maps in the build.** A Vite build that uses
`@lntrn/web`'s plugin (0.5.3 or later) registers its release with Lantern and
uploads its source maps when it has a Lantern workload token as
`LANTERN_WORKLOAD_TOKEN`. Give the step `lantern_workload: true`. The
`branchd/presets/service` preset sets it on every image build of a publishing
run, so a repository on that preset needs no pipeline change. The step
exchanges a token only when the Dockerfile names `LANTERN_WORKLOAD_TOKEN`, so
any other Dockerfile builds as before. Lantern takes the token only from a
protected run, for a client project that grants the repository (its CI grants)
or that lists the repository among its CI projects. Getting the token is best
effort: on a pull request's run, or when Auth refuses, the build log says so,
the build runs without it, and the plugin uploads nothing.

Declare the token where `vite build` runs, in a build stage that the final
image copies from. Never use `ENV`, and never declare it in the final stage:
that keeps it out of the pushed image's layers and history.

- **`image-build`** (kaniko, the default) passes it as a build argument:

  ```dockerfile
  FROM node:22 AS build
  WORKDIR /app
  COPY . .
  RUN pnpm install --frozen-lockfile
  ARG VERSION
  ARG LANTERN_WORKLOAD_TOKEN
  RUN pnpm build

  FROM nginx:1.27
  COPY --from=build /app/dist /usr/share/nginx/html
  ```

  Put the `ARG` just before the build `RUN`, after the install. The token
  changes every run, so every step after the `ARG` misses the layer cache.

- **`image-build-multiarch`** (`build.platforms` in the preset) mounts it as a
  BuildKit secret with the id `LANTERN_WORKLOAD_TOKEN`, which is in no layer
  and no build record:

  ```dockerfile
  RUN --mount=type=secret,id=LANTERN_WORKLOAD_TOKEN \
      LANTERN_WORKLOAD_TOKEN="$(cat /run/secrets/LANTERN_WORKLOAD_TOKEN 2>/dev/null)" pnpm build
  ```

  A Dockerfile written with the `ARG` form also builds here: the step passes
  the build argument too when the Dockerfile declares
  `ARG LANTERN_WORKLOAD_TOKEN`.

Source: https://docs.branchd.run/branchd/pipelines/build-and-push-an-image

---

# Caches and artifacts

> Keep dependency caches between runs, and hand built files from one job to the jobs that need it.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# A cache keeps Go's module and build caches between runs; artifacts carry
# the built binary from the build job to the jobs that need it.
name: CI
on: [push, pull_request]
jobs:
  build:
    image: golang:1.26
    cache:
      - key: go-mod
        files: [go.sum]
        paths: [.cache/mod]
      - key: go-build-${{ branch }}
        fallback-keys: [go-build-main]
        paths: [.cache/build]
    steps:
      # Steps share one shell, so these exports reach the next step.
      - run: |
          export GOMODCACHE="$PWD/.cache/mod"
          export GOCACHE="$PWD/.cache/build"
      - run: go build -o dist/server ./cmd/server
    artifacts:
      paths: [dist/server]
      when: success
      expire-in: 1 week
  test-binary:
    needs: [build]
    image: debian:stable-slim
    steps:
      - run: ./dist/server --version
  lint:
    # Only the order: this job does not download build's files.
    needs: [{job: build, artifacts: false}]
    image: golangci/golangci-lint:v2.1
    steps:
      - run: golangci-lint run
```

**A cache** is a best-effort copy of some paths, kept between runs and
looked up by key. A job may find it empty, so never depend on it for
correctness.

- `files: [go.sum]` keys the cache on that file's contents, with `key` as the
  prefix.
- `key: go-build-${{ branch }}` gives each branch its own cache;
  `fallback-keys` are tried, in order, when that key has none yet.
- `policy`: `pull-push` (the default) restores and saves, `pull` only
  restores, `push` only saves. `when`: `success` (the default) or `always`
  saves after a failure too.
- `cache:` takes one cache or a list.

**Artifacts** are files a job keeps after it ends. Every job that needs it
finds them in its own working directory, at the same paths.

- `artifacts: [dist]` keeps `dist`. The long form is
  `{paths, when, expire-in}`: `when` is `success` (the default), `failure` or
  `always`, and `expire-in` how long they are kept (`1 week`, `30 days`).
- `needs: [{job: build, artifacts: false}]` waits for `build` without
  downloading its artifacts.
- No artifact path may be, hold or match `.branchd/run/` (`.`, `*`, `**` and
  `.branchd` are refused): branchd keeps a run's own files there.

Source: https://docs.branchd.run/branchd/pipelines/caches-and-artifacts

---

# Reuse a step (composite steps)

> Keep a list of steps with inputs in a file of its own, and use it from any job of the repository.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

The step, in `.branchd/steps/setup-buf/step.yaml`:

```yaml title=".branchd/steps/setup-buf/step.yaml"
# .branchd/steps/setup-buf/step.yaml
# A composite step: steps with inputs, expanded into the job that uses it.
name: Set up buf
description: Installs buf, and signs in to the Buf Schema Registry when asked.
inputs:
  version: {type: string, default: '1.56.0'}
  login: {type: bool, default: 'false'}
secrets:
  BUF_TOKEN: {required: false, description: 'A Buf Schema Registry token, for login.'}
outputs:
  path: ${{ steps.install.outputs.path }}
steps:
  - id: install
    name: Install
    run: |
      curl -fsSLo /usr/local/bin/buf \
        "https://github.com/bufbuild/buf/releases/download/v${{ inputs.version }}/buf-$(uname -s)-$(uname -m)"
      chmod +x /usr/local/bin/buf
      echo "path=/usr/local/bin/buf" >> "$BRANCHD_OUTPUT"
  - name: Sign in
    if: inputs.login
    run: echo "$BUF_TOKEN" | buf registry login buf.build --token-stdin
```

The pipeline that uses it:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Uses the composite step in .branchd/steps/setup-buf/ twice: once with its
# defaults, once with a version and a sign-in.
name: CI
on: [push, pull_request]
jobs:
  lint:
    image: golang:1.26
    steps:
      - uses: ./setup-buf
      - run: buf lint
  push:
    if: branch == 'main' && event == 'push'
    image: golang:1.26
    secrets: [BUF_TOKEN]
    steps:
      - id: buf
        uses: ./setup-buf
        with:
          version: '1.57.0'
          login: true
      - run: ${{ steps.buf.outputs.path }} push
```

- **`uses: ./<name>`** names `.branchd/steps/<name>/step.yaml` of this
  repository, at the run's commit. `<name>` may have several segments
  (`./go/setup` is `.branchd/steps/go/setup/step.yaml`).
- **Expanded when the run is compiled.** Its steps become the job's own, in
  the job's shell: a tool it installs or a variable it exports is there for
  the steps after it. The log labels them `<use's name>: <step's name>`
  (`Set up buf: Install`).
- **`step.yaml`** has `name`, `description`, `inputs`, `secrets`, `outputs` and
  `steps` (required). `steps` are `run:` steps, other composite steps and,
  marked `isolated: true`, typed steps.
- **Inputs** are `{type, default, required, description}`, with `type`
  `string` (the default), `bool` or `int`. An input nobody gives reads its
  default, else `''`, `false` or `0`. `with:` on the use gives them; an input
  the step does not declare is refused.
- **Secrets.** The step reads a secret from the environment (`$BUF_TOKEN`),
  so the job that uses it grants it in its own `secrets:`. A `required: true`
  secret the job does not grant is refused; one with `required: false` is
  optional, and the step must cope without it.
- **Outputs.** `outputs:` maps names to values, usually
  `${{ steps.<id>.outputs.<name> }}` of one of its steps. The job reads
  them through the use's `id`: `${{ steps.buf.outputs.path }}`.
- **The use takes** `id`, `name`, `uses`, `with`, `if`, `env`, `isolated`
  and `workspace` (see [Isolate a step](https://docs.branchd.run/branchd/pipelines/isolated-steps)). `if:` applies
  to all its steps; `env:` is given to each of them, and then each runs in a
  subshell, so its exports no longer reach the steps after it.
- **What its expressions can read:** the run's facts (`branch`, `event`, …),
  its own `inputs` and its own steps' outputs. The calling job's `matrix`,
  `needs`, `env` and `vars` are refused there: pass them in `with:`.
- **To share it** with other repositories, see
  [Steps and pipelines of another repository](https://docs.branchd.run/branchd/pipelines/other-repositories).
- **It is not isolated.** A composite step runs in the job's shell with
  everything the job has: its secrets, its job token and its workspace.
- **Limits.** `uses:` nests at most 4 deep; a cycle is refused; at most 64 uses
  are expanded in one file; a job has at most 256 steps, its composite steps'
  included.

Source: https://docs.branchd.run/branchd/pipelines/composite-steps

---

# Concepts

> The few ideas a pipeline file is built from, and what branchd decides before a run starts.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## Pipeline file

One file in `.branchd/pipelines/` is one pipeline. Its name is its `name:`,
or the file name without `.yaml`. A repository can have several; each is
compiled on its own, so a broken file does not stop the others. See
[Several pipelines in one repository](https://docs.branchd.run/branchd/pipelines/several-pipelines).

A repository uses either pipeline files or the older CI files (such as
`.xeonr-ci.yaml`), never both: having both is refused.

## Run

A run is one execution of one pipeline for one event: a push, a pull
request, a schedule, a manual start, or a trigger from another repository.
`on:` decides which events start a run. Runs are numbered per repository.

By default a newer run of the same ref supersedes an older one: on an
unprotected branch the older run is cancelled, and on a protected branch
the newer run waits for it. `concurrency: {cancel-in-progress: false}` at
the top of a file opts out.

## Job

A job is a unit of work with its own container and its own check. It has an
`image` and `steps`, or it calls a reusable pipeline (`uses:`), or it
starts another repository's pipeline (`trigger:`). Jobs run in parallel.

## Step

A step is one `run:` (shell commands) or one `uses:` (a
[composite step](https://docs.branchd.run/branchd/pipelines/composite-steps), or a typed step
such as `branchd/steps/images/image-build@v1`). A job's `run:` steps share one shell, in
order: a `cd` or an `export` in one step is seen by the next. The shell is
bash when the image has it, else sh, with `set -e`. The first step that
fails stops the job, apart from steps with `if: always()` or
`if: failure()`.

## needs

`needs: [build]` makes a job wait for `build` and run only if it succeeded.
It also brings `build`'s artifacts and lets the job read `build`'s outputs.
There are no stages: `needs` is the only ordering.

A need on a job that does not run for this event is refused, so that a
missing job is never silently skipped. Give the two jobs the same `if:`, or
write the need as `{job: build, optional: true}`.

## How a job gets its code

Every job starts in a checkout of the run's commit, with `.git`. Nothing to
write, and nothing needed in the image, not even git: branchd fetches the
commit before the job's container starts, with a token the job never sees.
The `origin` remote is the repository's URL, and `git fetch origin` or
`git push origin` (with `permissions: {contents: write}`) use the
[job token](https://docs.branchd.run/branchd/pipelines/job-token) when the image has git.
`checkout: false` skips it; `checkout: {depth: 0, tags: true}` fetches the
whole history and the tags.

## Decided before the run starts

`on:`, every job's `if:`, `matrix:`, `uses:` and every `${{ }}` that does
not read an output are evaluated when the run is compiled, from facts
branchd knows at that moment: the event, branch, tag, changed paths,
inputs, and the repository's settings variables. That is why:

- `branchd ci plan` can list, for any branch or event, every job and why it
  runs or does not, before you push;
- a pull request's checks are known as soon as it is opened;
- an `if:` cannot read another job's outputs, which only exist once that job
  has run.

Two kinds of value are known only while a job runs: a step's outputs
(`steps.<id>.outputs.<name>`) and a needed job's outputs
(`needs.<job>.outputs.<name>`). They can be used in `run:`, `env:`,
`image:`, `with:` and a job's `outputs:`, never in `if:`.

## Expressions never become shell code

`${{ inputs.version }}` in a `run:` is not pasted into the script. It
becomes an environment variable of the job, and the script reads that
variable, so a branch name or an input such as `$(rm -rf /)` stays a value.
It expands where the shell expands variables, so not inside single quotes.

Source: https://docs.branchd.run/branchd/pipelines/concepts

---

# Deploy

> Build on every push and deploy to stage from the stage branch and to production from main, one deploy per environment at a time.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Build on every push, deploy to stage from the stage branch and to
# production from main. One deploy per environment runs at a time.
name: CI
on:
  push:
    branches: [main, stage]
jobs:
  build:
    image: golang:1.26
    outputs:
      version: ${{ steps.version.outputs.version }}
    steps:
      - run: go build -o dist/server ./cmd/server
      - id: version
        run: echo "version=$CI_COMMIT_SHORT_SHA" >> "$BRANCHD_OUTPUT"
    artifacts: [dist]
  deploy:
    needs: [build]
    if: branch == 'main' || branch == 'stage'
    image: alpine:3
    environment:
      name: ${{ branch == 'main' && 'production' || 'stage' }}
      url: ${{ branch == 'main' && 'https://app.example.com' || 'https://stage.app.example.com' }}
    concurrency: deploy-${{ branch }}
    secrets: [DEPLOY_TOKEN]
    steps:
      - run: ./scripts/deploy.sh "${{ branch }}" "${{ needs.build.outputs.version }}"
```

- **One deploy job for two environments.** `&&` and `||` return one of their
  operands, so `${{ branch == 'main' && 'production' || 'stage' }}` is
  `production` on `main` and `stage` elsewhere.
- **`environment:`** records a deployment of that name, with its `url`, on
  each run of the job.
- **`concurrency: deploy-${{ branch }}`** is a lock: one job holding
  `deploy-main` runs at a time in this repository, and the next waits. Two
  runs never deploy one environment at once.
- **`secrets: [DEPLOY_TOKEN]`** grants the job the secret, as the
  environment variable `$DEPLOY_TOKEN`. See [Secrets](https://docs.branchd.run/branchd/pipelines/secrets).
- **Outputs and artifacts.** `deploy` reads `build`'s `version` output, and
  finds `build`'s `dist/` (its artifacts) in its working directory.

To make a person release the production deploy, see
[Environments and manual approval](https://docs.branchd.run/branchd/pipelines/environments-and-approval).

Source: https://docs.branchd.run/branchd/pipelines/deploy

---

# Environments and manual approval

> Record deployments to named environments, and hold a job until a person releases it.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Deploy to production only after a person releases the job. It waits up
# to a day, then is skipped; the run is not held open for it.
name: CI
on:
  push:
    branches: [main]
jobs:
  test:
    image: golang:1.26
    steps:
      - run: go test ./...
  deploy-stage:
    needs: [test]
    image: alpine:3
    environment: {name: stage, url: 'https://stage.app.example.com'}
    secrets: [DEPLOY_TOKEN]
    steps:
      - run: ./scripts/deploy.sh stage
  deploy-production:
    needs: [deploy-stage]
    image: alpine:3
    environment: {name: production, url: 'https://app.example.com'}
    concurrency: {group: production}
    manual:
      wait: 24h
      on-expiry: skip
      blocking: false
    secrets: [DEPLOY_TOKEN]
    steps:
      - run: ./scripts/deploy.sh production
```

- **`environment:`** is a name, or `{name, url}`. Each run of the job records
  a deployment to it.
- **`manual:`** holds the job until a person releases it. `manual: true`
  waits without limit. The long form is `{wait, on-expiry, blocking}`: `wait`
  how long to wait (`24h`), `on-expiry` what happens then (`fail` or `skip`),
  and `blocking: false` lets the rest of the run finish while it waits.
- **Releasing.** On the run's page in the browser, or
  `branchd run release <run> <job>`. Who may release is set by the branch's
  rules: on a protected branch, one of the rule's merge roles, and only a
  person (or an agent acting for one, which counts as that person) when the
  rule asks for a person's approval; never a bot or a job.
- **`concurrency: {group: production}`** keeps two production deploys from
  overlapping.

`if:` cannot ask a person: it is decided when the run is compiled. Use
`manual:` for a decision made while the run is going.

Source: https://docs.branchd.run/branchd/pipelines/environments-and-approval

---

# Refusals

> The refusals you are most likely to meet when a pipeline file is compiled, and what to do about each.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

A refused file has no run. `branchd ci lint` and `branchd ci plan` print the
same refusal that the run would, as `invalid pipeline file: <file>:<line>: <message>`. Where the message is about a file a `uses:` read, it names that
file and line, then each `uses:` that led there:
`…; used by .branchd/pipelines/ci.yaml:6 (uses ./outer)`. Messages below
are shortened with `…`; the part you will see is enough to find them.

## Files and layout

| Message                                                                                     | What to do                                                                                                                          |
| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `a pipeline file ends in .yaml, not .yml`                                                   | Rename the file.                                                                                                                    |
| `on: is required: it says when the pipeline runs …`                                         | Add `on:`.                                                                                                                          |
| `jobs: is required, and holds at least one job`                                             | Add a job.                                                                                                                          |
| `… and .branchd/pipelines/ are both here: a repository uses one layout …`                   | Remove the older CI file once its jobs are in pipeline files.                                                                       |
| `… are both named "A"; checks are named <pipeline> / <job>, so a pipeline's name is unique` | Give one file another `name:`.                                                                                                      |
| `line 2: did not find expected ',' or ']'`, and other YAML errors                           | The file is not valid YAML at that line. A flow map or list (`{…}`, `[…]`) with a comma or colon in a value needs the value quoted. |

## Keys

| Message                                                                                                     | What to do                                                                                                                                                                                                                                                                                                                                   |
| ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `job "j": unknown key "imag" (steps, uses, with, …)`                                                        | A misspelt key; the list is every key allowed there. The same form appears for every map: `checkout: unknown key …`, `cache: unknown key …`.                                                                                                                                                                                                 |
| `stages: do not exist in a pipeline file; order jobs with needs:`                                           | Delete `stages:`; add `needs:` to each job.                                                                                                                                                                                                                                                                                                  |
| `variables: is env: in a pipeline file`                                                                     | Rename it. Each GitLab CI key is refused with its replacement in the message: `script:`, `rules:`, `tags:`, `extends:`, `when:`, `allow_failure:`, `resource_group:`, `parallel:`, `interruptible:`, `before_script:`, `after_script:`, `default:`, `workflow:`, `include:`. See [Coming from GitLab CI](https://docs.branchd.run/branchd/pipelines/from-gitlab-ci). |
| `max-parallel: is not available yet: pipelines cannot limit how many jobs of a run run at once; remove it`  | Remove it: branchd cannot yet limit how many jobs of a run run at once.                                                                                                                                                                                                                                                                      |
| `permissions: unknown permission "issues" (contents, pull-requests, checks, releases, packages, pipelines)` | Use a name from the list, each `read` or `write`. See [The job token](https://docs.branchd.run/branchd/pipelines/job-token).                                                                                                                                                                                                                                         |
| `a preset of this repository (./presets/x) cannot run on the forge yet: …`                                  | Publish the preset in another repository and use `<group>/<repo>/<path>@v1`.                                                                                                                                                                                                                                                                 |
| `preset branchd/presets/service@v1: …`                                                                      | The preset refused its `with:`; the message names the key. A preset you may not read is refused as one that does not exist.                                                                                                                                                                                                                  |
| `job "a": step 2 (…/lantern-apply) must be marked isolated: true: this job has other steps, …`              | Add `isolated: true` and a `workspace:` listing what it needs; the message prints the step as it should be. See [Isolate a step](https://docs.branchd.run/branchd/pipelines/isolated-steps).                                                                                                                                                                         |
| `concurrency.group is a name of 1 to 200 characters`                                                        | Give the group a name, such as `deploy-${{ branch }}`.                                                                                                                                                                                                                                                                                       |

## Jobs and needs

| Message                                                                                                        | What to do                                                                                                                            |
| -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `job "j": image is required (set it on the job or under defaults:)`                                            | Add `image:`, or `defaults: {image: …}` for every job.                                                                                |
| `job "j": steps: is required, a list of {run: …}`                                                              | Add `steps:`, or `uses:` to call a pipeline.                                                                                          |
| `job "build:api": a job id is letters, digits, _ and -, starting with a letter or _`                           | Rename the job: `build-api`.                                                                                                          |
| `job "j" needs "nope", which is not a job of this file (needs across pipelines do not exist)`                  | Fix the id. A job cannot need a job of another file.                                                                                  |
| `job "j" needs "a", which does not run here (if … is false); mark the need optional: true if that is expected` | Give `j` the same `if:` as `a`, or write `needs: [{job: a, optional: true}]`. Check with `branchd ci plan` for the event in question. |
| `job "j": if: failure() in a job's if: is not available …`                                                     | Use `if: always()` on the job, and check the outcome in a step.                                                                       |
| `job "j": matrix.fail-fast must be true or false`                                                              | Write `true` (the default) or `false`.                                                                                                |
| `job "j": a matrix job has no outputs: which cell's would they be?`                                            | Move the output to a job without a matrix.                                                                                            |
| `job "j": artifacts: "." is or holds .branchd/run/ …`                                                          | Name the directories to keep (`dist`), not the whole workspace.                                                                       |
| `job "t": a trigger: job runs nothing in this repository, so it takes no image (…)`                            | Remove the key; a trigger job takes only the keys listed.                                                                             |
| `job "j": tag "deploy" is … deploy runner, which runs only the steps …`                                        | Remove `deploy` from `runs-on`.                                                                                                       |

## Expressions and outputs

| Message                                                                                                            | What to do                                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `github is not a context (branch, tag, event, …)`                                                                  | Use one of the listed contexts: `${{ sha }}`, not `${{ github.sha }}`. See [Expressions](https://docs.branchd.run/branchd/pipelines/expressions).                                          |
| `hashFiles() is not a function (changed, exists, contains, …)`                                                     | Use a listed function; for a cache keyed on files, use `cache.files`.                                                                                              |
| `inputs.x: this pipeline declares no inputs …`, `inputs.x is not declared (inputs: …)`                             | Declare the input under `on: manual`, `on: trigger` or `on: call`.                                                                                                 |
| `job "j": if: > with an output is not available: an output is a string, compared with == or !=`                    | Compare the output with a string (`== 'true'`), or use `contains`, `startsWith` or `endsWith`. See [if: on outputs](https://docs.branchd.run/branchd/pipelines/expressions#if-on-outputs). |
| `step 2: if: > with an output is not available: an output is a string, compared with == or !=`                     | As for a job's `if:`: compare with a string, or test the output inside the step's `run:`.                                                                          |
| `run: needs.a.outputs.o: job "a" is not among this job's needs`                                                    | Add `a` to `needs`.                                                                                                                                                |
| `job "j": outputs.o is "a\nb", which has a line break; an output is one line`                                      | Keep each output to one line.                                                                                                                                      |
| `jobs.j.env: "a-b" is not a variable name`                                                                         | Use letters, digits and `_`.                                                                                                                                       |
| `job "j": step 1 sets an EXIT trap, which would replace the one that runs step 2 (if: always()) after a failure …` | Set the trap in a subshell, `( trap … EXIT; … )`, or add `shell: bash` to the step.                                                                                |

## Steps

| Message                                                                                                                                        | What to do                                                                   |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `job "j": a typed step runs in its own image, so the job takes no image`                                                                       | Remove `image:` from that job.                                               |
| `job "j": step 1: uses: ci/nope@1: a typed step is used by its repository's path, <group>/<repo>/<path>@<version>, or by a name branchd knows` | Check the step's name, and use it by its address: `branchd/steps/<step>@v1`. |

## Composite steps and reusable pipelines

| Message                                                                                                | What to do                                                                                            |
| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| `uses ./s: .branchd/steps/s/step.yaml does not exist`                                                  | Create the file, or fix the name. `./s` is `.branchd/steps/s/step.yaml`.                              |
| `uses ./s: with.nope is not an input (…)`                                                              | Declare the input in `step.yaml`, or fix its name.                                                    |
| `uses ./s needs the secret T: grant it to the job (secrets: [T])`                                      | Add the secret to the job's `secrets:`.                                                               |
| `matrix.a: a composite step reads its inputs, not the calling job's matrix; pass the value in with: …` | Declare an input and pass `${{ matrix.a }}` in `with:`. The same holds for `needs`, `env` and `vars`. |
| `uses: goes round in a cycle: …`                                                                       | A step uses itself, directly or through others.                                                       |
| `… it has no on: call, so a job cannot use it …`                                                       | Add `on: call` to the called file.                                                                    |
| `… requires input v, and job "c" gives none`                                                           | Add it under the calling job's `with:`.                                                               |
| `vars.X: a called pipeline reads its inputs, not the calling repository's settings variables …`        | Declare an input and pass `${{ vars.X }}` in the caller's `with:`.                                    |

## Other repositories

| Message                                                                                                                                                              | What to do                                                                                        |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `@main is neither a version (@v1, @v1.4, @v1.4.2) nor a 40-character commit; branches are not accepted …`                                                            | Use a version tag.                                                                                |
| `xeonr/forge/steps has no tag that @v2 names (a tag v2.<minor>.<patch>)`                                                                                             | The publisher has no such version yet.                                                            |
| `xeonr/forge/steps does not list t in .branchd/packages.yaml, so other repositories may not use it (it lists …)`                                                     | Ask the publisher to list it, or fix the path.                                                    |
| `no repository in that path exists that this repository may read`                                                                                                    | The repository does not exist, or its visibility does not reach yours.                            |
| `job "c / j" sets environment: prod, and a pipeline of another repository may choose the environment only when the calling job "c" allows it (allow: [environment])` | Add `allow: [environment]` to the calling job, or set `environment:` on the calling job yourself. |

## Events and inputs

| Message                                                                       | What to do            |
| ----------------------------------------------------------------------------- | --------------------- |
| `on.schedule.cron: "0 3 * *" is not a five-field cron expression`             | Write five fields.    |
| `on.manual.inputs.c: a choice needs options`                                  | Add `options:`.       |
| `on.trigger needs from: (organisation, company, or a list of repositories) …` | Say who may start it. |

Source: https://docs.branchd.run/branchd/pipelines/errors

---

# Expressions and variables

> The ${{ }} expression language, its contexts and functions, and the environment variables every job gets.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## Where expressions go

- **`if:`** is one expression, with or without `${{ }}` around it.
- **`${{ … }}` inside any string** substitutes its value: in `env:`, `image:`,
  `run:`, `with:`, `services:`, `environment:`, `concurrency:`, cache keys,
  `outputs:` and the rest.
- **Decided when the run is compiled**, from branchd's facts, so
  `branchd ci plan` gives the reason each job is in or out. Only outputs
  (`steps.*`, `needs.*`) wait until the job runs, and those are allowed only
  in `run:`, `env:`, `image:`, `with:` and a job's `outputs:`, never in `if:`.

## Syntax

|              |                                                                                                                                                |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Literals     | `'text'` (a quote inside is `''`), numbers, `true`, `false`, `null`                                                                            |
| Comparison   | `==`, `!=`, `<`, `<=`, `>`, `>=`. Strings compare case-sensitively; anything compared with a number or a boolean is compared as a number.      |
| Logic        | `!`, `&&`, `\|\|`, parentheses. `&&` and `\|\|` short-circuit and return one operand, so `branch == 'main' && 'prod' \|\| 'stage'` is a value. |
| False values | `false`, `null`, `0` and `''`                                                                                                                  |
| Nesting      | Parentheses, `!` and calls nest at most 64 deep.                                                                                               |

## Contexts

| Context                               | Value                                                                                  |
| ------------------------------------- | -------------------------------------------------------------------------------------- |
| `branch`                              | The branch pushed; for a pull request, its source branch. `''` for a tag.              |
| `tag`                                 | The tag pushed, else `''`.                                                             |
| `event`                               | `push`, `pull_request`, `schedule`, `manual` or `trigger`.                             |
| `sha`                                 | The commit.                                                                            |
| `ref`                                 | The full ref, `refs/heads/main` or `refs/tags/v1.0.0`.                                 |
| `repository`                          | The repository's path, `<team>/<group>/<name>`.                                        |
| `default_branch`                      | The repository's default branch.                                                       |
| `protected`                           | Whether the ref is protected.                                                          |
| `pr.number`, `pr.source`, `pr.target` | The pull request's number, source and target branches; `null` outside a pull request.  |
| `inputs.<name>`                       | An input of `on: manual`, `on: trigger` or `on: call`.                                 |
| `matrix.<key>`                        | The cell's value; `''` for a key this cell has no value for.                           |
| `vars.<NAME>`                         | A settings variable of the repository or its groups.                                   |
| `env.<NAME>`                          | The file's, job's and step's `env:`, as written. `NAME` must be a shell variable name. |
| `steps.<id>.outputs.<name>`           | A step's output, known while the job runs.                                             |
| `needs.<job>.outputs.<name>`          | A needed job's output, known while the job runs. The job must be in `needs`.           |
| `jobs.<id>.outputs.<name>`            | Only in `on.call.outputs`: a job of the called pipeline.                               |

## Functions

| Function                             | True when                                                                                                                                                                    |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `changed('glob', …)`                 | Any changed path matches any glob. A new branch, a tag, or a push with more changes than branchd lists counts as everything changed.                                         |
| `exists('glob', …)`                  | A file of the commit matches, at any depth (`exists('src/**/*.go')`). Same globs as `changed()`.                                                                             |
| `contains(a, b)`                     | `a` contains `b`.                                                                                                                                                            |
| `startsWith(a, b)`, `endsWith(a, b)` | `a` starts or ends with `b`.                                                                                                                                                 |
| `always()`                           | Always. In a job's `if:`, the job runs even after a failed need; in a step's, after a failed step.                                                                           |
| `success()`                          | Nothing has failed.                                                                                                                                                          |
| `failure()`                          | In a step's `if:` only: an earlier step failed.                                                                                                                              |
| `cancelled()`                        | In a step's `if:` only: the job was cancelled. Such a step, and an `always()` one, runs after a cancel; see [Cancelled jobs](https://docs.branchd.run/branchd/pipelines/expressions#cancelled-jobs). |

Globs: `*` within one path segment, `**` across segments, `?`, `[…]`,
`{a,b}`, and a leading `!` to exclude; the last pattern that matches
decides. A file uses at most 1,000 different globs.

## In a run: script

`${{ }}` in a `run:` is never pasted into the script. Each expression becomes
an environment variable of the job, and the script reads it:

- `${{ inputs.version }}` is `${BRANCHD_INPUTS_VERSION}`; another expression is
  `${BRANCHD_EXPR_<n>}`; `${{ env.X }}` is `${X}`.
- So it expands where the shell expands variables, and not inside single
  quotes: write `echo "${{ inputs.version }}"`, not
  `echo '${{ inputs.version }}'`.
- A value that would hold `${{` is refused.

## $NAME in values

In `env:`, `image:`, `with:` and other values, `$NAME` of a variable known
when the run is compiled (the `CI_*` variables below, and `env:`) expands,
and `$$` is a literal `$`. In `run:`, the shell expands `$NAME` as usual.

## Variables every job gets

| Variable                                                                                                          | Value                                                                                                    |
| ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `CI`                                                                                                              | `true`                                                                                                   |
| `CI_COMMIT_SHA`, `CI_COMMIT_SHORT_SHA`                                                                            | The commit.                                                                                              |
| `CI_COMMIT_BEFORE_SHA`                                                                                            | The previous head of the branch, else forty zeros.                                                       |
| `CI_COMMIT_REF_NAME`, `CI_COMMIT_REF_SLUG`                                                                        | The branch or tag, and a lower-case form safe in URLs and host names.                                    |
| `CI_COMMIT_BRANCH`                                                                                                | The branch (a pull request's source branch too).                                                         |
| `CI_COMMIT_TAG`                                                                                                   | The tag, for a tag.                                                                                      |
| `CI_COMMIT_REF_PROTECTED`                                                                                         | `true` or `false`.                                                                                       |
| `CI_DEFAULT_BRANCH`                                                                                               | The default branch.                                                                                      |
| `CI_PIPELINE_SOURCE`                                                                                              | What started the run.                                                                                    |
| `CI_PIPELINE_IID`                                                                                                 | The run's number in the repository.                                                                      |
| `CI_PROJECT_PATH`, `CI_PROJECT_PATH_SLUG`, `CI_PROJECT_NAME`, `CI_PROJECT_NAMESPACE`, `CI_PROJECT_ROOT_NAMESPACE` | The repository's path, its slug, its name, its group path and its team.                                  |
| `CI_SERVER_URL`, `CI_SERVER_HOST`, `CI_PROJECT_URL`                                                               | branchd's address and the repository's page.                                                             |
| `CI_REGISTRY`, `CI_REGISTRY_IMAGE`                                                                                | The registry, and this repository's image path in it.                                                    |
| `CI_MERGE_REQUEST_IID`, `CI_MERGE_REQUEST_SOURCE_BRANCH_NAME`, `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`              | In a pull request's run.                                                                                 |
| `BRANCHD_OUTPUT`                                                                                                  | In each step: the file to write `name=value` outputs to.                                                 |
| `BRANCHD_TOKEN`, `BRANCHD_TOKEN_COMMAND`                                                                          | The job token, and a command that prints a fresh one. See [The job token](https://docs.branchd.run/branchd/pipelines/job-token). |
| `BRANCHD_API_URL`, `BRANCHD_REPOSITORY`, `BRANCHD_PR`                                                             | branchd's API; this repository's path; the pull request's number, in a pull request's run.               |
| `FORGE_REPOSITORY_URL`                                                                                            | This repository's HTTPS URL as the runner reaches it, with no credential; the checkout's `origin`.       |
| `FORGE_SHA`, `FORGE_RUN_NUMBER`                                                                                   | The commit and the run's number.                                                                         |

There is no `CI_JOB_STAGE`: there are no stages.

## if: on outputs

An `if:` may read outputs, which are known only while the run runs:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
on: push
jobs:
  api:
    image: alpine:3.20
    outputs:
      changed: ${{ steps.changes.outputs.api }}
    steps:
      - id: changes
        run: echo "api=$(git diff --quiet HEAD~1 -- api || echo true)" >> "$BRANCHD_OUTPUT"
      - if: steps.changes.outputs.api == 'true' && branch == 'main'
        run: make build-api
  deploy:
    needs: [api]
    if: needs.api.outputs.changed == 'true'
    image: alpine:3.20
    steps:
      - run: make deploy-api
```

- **A step's `if:`** may read `steps.<id>.outputs.<name>` of an earlier step
  and `needs.<job>.outputs.<name>` of a needed job. It is decided when the
  step's turn comes; the log says when a step is skipped.
- **A job's `if:`** may read `needs.<job>.outputs.<name>`. It is decided when
  the jobs it needs have run. A job whose `if:` is false then is **skipped**,
  and so are the jobs that need it (unless they use `always()`). A manual
  job's `if:` cannot read outputs.
- **What is decided first.** The parts known when the run is compiled are
  decided then: off `main`, `branch == 'main' && …` is false, and the step or
  job never runs.
- **What reads an output.** An output is a string. `==` and `!=` against a
  string (`'true'`) or another output, `contains`, `startsWith` and
  `endsWith` with a string, the output on its own (true when not empty: as
  on GitHub, `'false'` is true), and `!`, `&&`, `||` over these. `<`, `>`,
  `== true` (write `== 'true'`) and other functions of an output are refused.
- **An output never set** reads as `''`. An output's value is never run as
  shell code.

## Cancelled jobs

When a job is cancelled (its run cancelled or superseded, or a fail-fast
matrix stopping it), its steps with `if: always()` or `if: cancelled()` still
run, as GitLab's `after_script` does: after the cancel, in a fresh shell, with
up to 30 seconds by default. Each runs in its own subshell, with its `env:` and
`working-directory:`, in the job's working directory; a failure is reported
and the next one runs. They do not see earlier steps' outputs or what the
script exported, and a step whose `if:` reads an output does not run after a
cancel. `failure()` steps do not run after a cancel. This is how a host job
removes its temporary files when it is stopped:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
on: push
jobs:
  ios:
    host: true
    runs-on: [macos]
    steps:
      - run: eas build --local --platform ios
      - if: always()
        run: rm -rf "$TMPDIR/eas-build"
```

Source: https://docs.branchd.run/branchd/pipelines/expressions

---

# Coming from GitLab CI

> How each GitLab CI construct is written in a branchd pipeline file, with a worked conversion.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## Mapping

| GitLab CI                                                 | Pipeline file                                                                                                                         |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `.gitlab-ci.yml`                                          | `.branchd/pipelines/<name>.yaml`, one file per pipeline                                                                               |
| `stages:`, `stage:`                                       | None. Order jobs with `needs:`.                                                                                                       |
| `workflow: rules:`                                        | `on:`                                                                                                                                 |
| `rules:`, `only:`, `except:`                              | One `if:` per job; `changed()` for `rules: changes:`                                                                                  |
| `when: manual`                                            | `manual: true`                                                                                                                        |
| `when: always` (a job)                                    | `if: always()`                                                                                                                        |
| `script:`                                                 | `steps:`, each `- run: …`                                                                                                             |
| `before_script:`                                          | The first steps                                                                                                                       |
| `after_script:`                                           | A last step with `if: always()`                                                                                                       |
| `variables:`                                              | `env:`                                                                                                                                |
| `default:`                                                | `defaults:` (`image`, `runs-on`)                                                                                                      |
| `image:`                                                  | `image:`                                                                                                                              |
| `services: [{name, alias}]`                               | `services: {<alias>: {image, env}}`                                                                                                   |
| `tags:`                                                   | `runs-on:`                                                                                                                            |
| `cache: {key: {files, prefix}}`                           | `cache: {files, key}`                                                                                                                 |
| `artifacts: {expire_in}`                                  | `artifacts: {expire-in}`                                                                                                              |
| `dependencies:`, `needs: {artifacts: false}`              | `needs: [{job, artifacts: false}]`                                                                                                    |
| `parallel: matrix:`                                       | `matrix:`                                                                                                                             |
| `allow_failure:`                                          | `continue-on-error:`                                                                                                                  |
| `resource_group:`                                         | `concurrency:` (a lock name)                                                                                                          |
| `interruptible: true`                                     | `concurrency: {cancel-in-progress: true}`                                                                                             |
| `environment:`                                            | `environment:`                                                                                                                        |
| `retry:`                                                  | `retry:`                                                                                                                              |
| `timeout:`                                                | `timeout:`                                                                                                                            |
| `extends:`, hidden jobs, `!reference`                     | A [composite step](https://docs.branchd.run/branchd/pipelines/composite-steps), a [reusable pipeline](https://docs.branchd.run/branchd/pipelines/reusable-pipelines), or YAML anchors |
| `include:`                                                | `uses:`                                                                                                                               |
| `trigger:` (multi-project)                                | [`trigger:`](https://docs.branchd.run/branchd/pipelines/trigger-another-repository), and the target declares `on: trigger`                                    |
| Child pipelines                                           | Several files, or a reusable pipeline                                                                                                 |
| `$CI_*` variables                                         | Still set, apart from `CI_JOB_STAGE`                                                                                                  |
| `rules: if: $CI_COMMIT_BRANCH == "main"`                  | `if: branch == 'main'`                                                                                                                |
| `rules: if: $CI_PIPELINE_SOURCE == "merge_request_event"` | `if: event == 'pull_request'`                                                                                                         |
| Pipeline schedules in settings                            | `on: schedule` in the file                                                                                                            |
| `[skip ci]`, `[ci skip]`, `git push -o ci.skip`           | The same: [Skip a push's pipelines](https://docs.branchd.run/branchd/pipelines/skip-a-run)                                                                    |

## A worked conversion

Before:

```yaml title=".gitlab-ci.yml"
# .gitlab-ci.yml
# Before: a GitLab CI file with stages, rules, a service, a cache and a
# manual deploy.
stages: [test, build, deploy]

variables:
  GOFLAGS: -mod=readonly

default:
  image: golang:1.26

test:
  stage: test
  services:
    - name: mysql:8
      alias: mysql
      variables: {MYSQL_ROOT_PASSWORD: test}
  cache:
    key: {files: [go.sum], prefix: go-mod}
    paths: [.cache/mod]
  before_script:
    - export GOMODCACHE="$CI_PROJECT_DIR/.cache/mod"
  script:
    - go test ./...
  after_script:
    - ./scripts/collect-logs.sh

build:
  stage: build
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  script:
    - go build -o dist/server ./cmd/server
  artifacts:
    paths: [dist/]
    expire_in: 1 week

deploy:
  stage: deploy
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
      when: manual
  resource_group: production
  environment: {name: production, url: https://app.example.com}
  script:
    - ./scripts/deploy.sh production
```

After:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# After: the same pipeline. Stages become needs:, rules: become on: and
# if:, before_script and after_script become steps.
name: CI
on:
  push:
    branches: [main]
  pull_request:
env:
  GOFLAGS: -mod=readonly
defaults:
  image: golang:1.26
jobs:
  test:
    services:
      mysql:
        image: mysql:8
        env: {MYSQL_ROOT_PASSWORD: test}
    cache:
      key: go-mod
      files: [go.sum]
      paths: [.cache/mod]
    steps:
      - run: export GOMODCACHE="$PWD/.cache/mod"
      - run: go test ./...
      - if: always()
        run: ./scripts/collect-logs.sh
  build:
    needs: [test]
    if: branch == 'main' && event == 'push'
    steps:
      - run: go build -o dist/server ./cmd/server
    artifacts:
      paths: [dist]
      expire-in: 1 week
  deploy:
    needs: [build]
    if: branch == 'main' && event == 'push'
    manual: true
    concurrency: production
    environment: {name: production, url: 'https://app.example.com'}
    steps:
      - run: ./scripts/deploy.sh production
```

What changed:

- `stages` went; `build` needs `test` and `deploy` needs `build`.
- The two `rules:` became one `if:` each, and `on:` says the pipeline runs on
  pushes to `main` and on pull requests.
- `default: image` became `defaults: image`.
- The service's alias became its key.
- `before_script` became a first step. Steps share a shell, so its `export`
  reaches the next step. `after_script` became a step with `if: always()`.
- `when: manual` became `manual: true`, and `resource_group` became
  `concurrency`.
- `$CI_PROJECT_DIR` became `$PWD`: a step starts in the checkout.

`branchd ci lint` names any key you missed, with its replacement.

Source: https://docs.branchd.run/branchd/pipelines/from-gitlab-ci

---

# Coming from .xeonr-ci.yaml

> Move a repository from .xeonr-ci.yaml to a pipeline file that uses the service preset, with its own jobs beside it.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

A `.xeonr-ci.yaml` is the service preset's configuration on its own. In a
pipeline file the same keys go, unchanged, under `preset.with`, and jobs of
your own sit beside the preset's under `jobs:`.

## Mapping

| `.xeonr-ci.yaml`                                                                       | Pipeline file                                                                                                      |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| The file's keys (`apps`, `lint`, `commits`, `migrations`, `buf`, `lantern`, `docs`, …) | The same keys under `preset: {uses: branchd/presets/service@v1, with: …}`                                          |
| Extra jobs in `.gitlab-ci.yml` beside it                                               | `jobs:` in the same file, with `needs: [preset.<address>]`                                                         |
| A job of yours that a preset job must wait for                                         | `needs:` on the preset entry (`apps.<name>.needs`, `test.needs`, `lint.needs`, `migrations.needs`) naming your job |
| `XEONR_CI_CHANGES` in `.gitlab-ci.yml`                                                 | `changes: true` under `with`                                                                                       |
| Overriding a preset job by its name                                                    | Not possible: change `with:`, or ask for a setting in the preset                                                   |
| `build:api`, `deploy:api:prod` job names                                               | Addresses: `preset.apps.api.build`, `preset.gitops.prod`                                                           |
| `docs: enabled: true`                                                                  | The same; `docs.pipeline` names the docs repository's pipeline (default `build`)                                   |

The service preset takes the `k8s`, `cf-worker`, `renderer`, `electron`
and `upl-im` (or `upl-pipelines`) app types, and `helm:` charts. A `k8s` app
deploys with `deploy.method: flux`; another method is refused with a
message, so move the app to Flux first. Apps of type `cli`, `npm`,
`library`, `proto` and `mobile` are refused by the service preset: each is
a preset of its own (`branchd/presets/cli@v1`, and so on).

## A worked conversion

Before:

```yaml title=".xeonr-ci.yaml"
# .xeonr-ci.yaml
# Before: the service preset's configuration on its own.
lint:
  golangci: true
commits:
  lint: true
apps:
  api:
    type: k8s
    test:
      image: golang:1.26
      command: go vet ./... && go test -race -count=1 ./...
    build:
      image: api
```

After:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# After: the same keys under preset.with, unchanged. A job of your own sits
# beside the preset's and waits for one of them by its address.
name: CI
preset:
  uses: branchd/presets/service@v1
  with:
    lint:
      golangci: true
    commits:
      lint: true
    apps:
      api:
        type: k8s
        test:
          image: golang:1.26
          command: go vet ./... && go test -race -count=1 ./...
        build:
          image: api
jobs:
  e2e:
    needs: [preset.apps.api.build]
    image: ${{ needs.preset.apps.api.build.outputs.image }}
    steps:
      - run: /app/e2e.sh
```

Then delete `.xeonr-ci.yaml`: a repository with both is refused. Check the
result with `branchd ci plan`: the preset's jobs are listed by address
beside yours.

Source: https://docs.branchd.run/branchd/pipelines/from-xeonr-ci

---

# Isolate a step from the job

> Run a typed step among run: steps with isolated: true, and choose what it receives and hands back with workspace:.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

A job's steps are processes in one container, so a `run:` line can read
anything a neighbouring step holds. A typed step (`uses: branchd/steps/…`) carries an
identity or secrets of its own, so it never shares a container with the
job's other steps. Written among them, it says so with `isolated: true`, and
says what it needs from the steps before it with `workspace:`:

```yaml title=".branchd/pipelines/dashboards.yaml"
# .branchd/pipelines/dashboards.yaml
# A typed step among run: steps is marked isolated: true. It runs as a node
# of its own, receives dashboards/** from the steps before it, and hands
# back what it writes there. Nothing else crosses: not $HOME, not exported
# variables, not services. Step outputs do.
name: Dashboards
on:
  push:
    branches: [main]
jobs:
  deploy:
    image: node:22
    steps:
      - id: gen
        run: |
          npm ci
          npm run dashboards
          echo "count=$(ls dashboards | wc -l)" >> "$BRANCHD_OUTPUT"
      # Also written lantern/cli/steps/apply@v1, the step's address.
      - uses: ci/lantern-apply@1
        isolated: true
        workspace: [dashboards/**]
      - run: echo "applied ${{ steps.gen.outputs.count }} dashboards"
      - if: always()
        run: rm -rf node_modules/.cache
```

- **The marker is required.** A typed step among other steps without
  `isolated: true` is refused. The refusal names the step, says why it runs
  on its own (an image package; the identity tokens it asks for; the secrets
  it reads), and prints the step with `isolated: true` and a `workspace:`.
- **`workspace:`** is what the step receives from the working directory as
  the steps before it left it, generated, untracked and ignored files
  included:
  - a list of paths, globs relative to the working directory (`dashboards/**`,
    `dist`, `*.json`), at most 32. **A list carries only what it names**, so
    a step that runs git on its tree needs `.git/**` in it;
  - `all`, everything;
  - left out, **the checkout only**: the step gets what it would as a job of
    its own, and hands nothing back.
- **What it writes inside those paths comes back** to the steps after it. A
  file it deletes comes back deleted only with `workspace: all`.
- **Nothing else crosses**, either way: anything outside the working
  directory (`$HOME`, `/tmp`, tools installed into the image), exported
  variables and shell functions, the current directory, background
  processes, and services (each part starts its own). **Step outputs do
  cross**: `${{ steps.gen.outputs.count }}` above.
- **`isolated: true` on a `run:` step or a composite step** works the same:
  that step runs as a node of its own.

## How it runs

The job is split into parts, one node each: the steps before the isolated
step, the step itself, and the steps after it. Each part is a check, named
`<job> [k/n]`, and the last has the job's own name, so `needs: [deploy]` and
`needs.deploy.outputs` reach it unchanged. Here: `Dashboards / deploy [1/3]`,
`Dashboards / deploy [2/3]` and `Dashboards / deploy`. Require the last one
in a branch rule.

- **The cost.** The working directory is packed and unpacked at each
  boundary. With `node_modules` or build output that can be hundreds of
  megabytes, and each part starts its own container, services and cache
  restore. If a hand-over is slow, make the step a job of its own and pass
  only what it needs as `artifacts:`.
- **`if: always()` after it** runs whatever the parts before it did. The
  isolated step needs a `workspace:` then, to carry its result back.
  `if: failure()` on the isolated step is refused.
- **`continue-on-error`** on the isolated step lets the steps after it run.
  On the job it is refused.
- **Refused on the job:** a `concurrency` lock (another run could take it
  between the parts) and `continue-on-error`.
- **Secrets.** The isolated step gets only the secrets its package declares.
  One it reads that is also listed on the job reaches the other parts too,
  and the plan warns.
- At most 8 isolated steps in a job.

`branchd ci plan` prints the job once, with its parts and, under the
isolated step, what it receives, what it hands back and what does not cross.

> **Not yet available** (console): showing a job's parts as the one job you wrote. Each part is its own check for now.

Source: https://docs.branchd.run/branchd/pipelines/isolated-steps

---

# The job token

> Use $BRANCHD_TOKEN with git and curl, ask for more with permissions:, and what it can never do.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

Every job gets `BRANCHD_TOKEN`, a short-lived token for its run. `git` uses it
without set-up, and branchd's API takes it as a bearer token. **It reads its
own repository and nothing else**: another repository, even one of the same
team, answers "not found", as it would for anyone who may not read it.
`permissions:` asks for more, in this repository only.

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# The job token, $BRANCHD_TOKEN, with nothing installed but curl and git.
# Without permissions: a job reads this repository and nothing else.
name: CI
on:
  push:
    branches: [main]
  pull_request:
jobs:
  test:
    image: golang:1.26
    steps:
      - run: go test -coverprofile=c.out ./... && go tool cover -func=c.out | tail -1 > summary.txt
    artifacts: [summary.txt]
  coverage:
    # Comment the coverage on the pull request: pull-requests: write is
    # under the default ceiling, so it works on the pull request's own run.
    if: event == 'pull_request'
    needs: [test]
    image: golang:1.26
    permissions: {pull-requests: write}
    steps:
      - run: |
          body=$(sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/\t/ /g' summary.txt | awk '{printf "%s\\n", $0}')
          curl -fsS -H "Authorization: Bearer $BRANCHD_TOKEN" -H 'Content-Type: application/json' \
            "$BRANCHD_API_URL/xeonr.forge.v1.ReviewService/CreateComment" \
            -d "{\"pullRequest\":\"$BRANCHD_REPOSITORY!$BRANCHD_PR\",\"body\":\"Coverage: $body\"}"
  tag:
    # Tag main's commit once the tests pass: contents: write on a
    # protected branch. git uses the token with no set-up.
    if: branch == 'main' && event == 'push'
    needs: [test]
    image: golang:1.26
    permissions: {contents: write}
    steps:
      - run: |
          git tag "build-$FORGE_RUN_NUMBER" "$FORGE_SHA"
          git push origin "build-$FORGE_RUN_NUMBER"
  report:
    # Report a check of your own on the commit.
    needs: [test]
    image: alpine:3.20
    permissions: {checks: write}
    steps:
      - run: |
          apk add --no-cache curl >/dev/null
          curl -fsS -H "Authorization: Bearer $($BRANCHD_TOKEN_COMMAND)" -H 'Content-Type: application/json' \
            "$BRANCHD_API_URL/xeonr.forge.v1.CheckService/CreateCheck" \
            -d "{\"repository\":\"$BRANCHD_REPOSITORY\",\"headOid\":\"$FORGE_SHA\",\"name\":\"coverage-recorded\",\"state\":\"CHECK_STATE_SUCCEEDED\"}"
```

```yaml title=".branchd/pipelines/nightly.yaml"
# .branchd/pipelines/nightly.yaml
# Every night, start this repository's Release pipeline on main with an
# input: pipelines: write. (Release's on: lists manual.)
name: Nightly
on:
  schedule:
    - name: nightly-release
      cron: '0 2 * * *'
jobs:
  kick:
    image: golang:1.26
    permissions: {pipelines: write}
    steps:
      - run: |
          curl -fsS -H "Authorization: Bearer $BRANCHD_TOKEN" -H 'Content-Type: application/json' \
            "$BRANCHD_API_URL/xeonr.forge.v1.RunService/CreateRun" \
            -d "{\"repository\":\"$BRANCHD_REPOSITORY\",\"ref\":\"main\",\"pipeline\":\"Release\",\"inputs\":{\"channel\":\"beta\"}}"
```

```yaml title=".branchd/pipelines/release.yaml"
# .branchd/pipelines/release.yaml
# Started by hand, or by the nightly job above, with its channel input.
name: Release
on:
  manual:
    inputs:
      channel:
        type: choice
        options: [stable, beta]
        default: beta
jobs:
  publish:
    image: golang:1.26
    steps:
      - run: echo "publishing to ${{ inputs.channel }}"
```

## Calling the API

Each call is an HTTP `POST` of JSON to
`$BRANCHD_API_URL/xeonr.forge.v1.<Service>/<Method>`, with
`Authorization: Bearer $BRANCHD_TOKEN` and `Content-Type: application/json`.
Fields are the request's, in lowerCamelCase. A repository is named by its path
(`$BRANCHD_REPOSITORY`), a pull request as `<path>!<number>`. A refusal is a
non-2xx answer whose JSON `message` says why; `curl -fsS` fails the step on
it.

- **A body built from text the job made must be valid JSON**: escape `\` and
  `"`, and turn tabs and newlines into spaces or `\n`, as the coverage job
  does with `sed` and `awk`.
- **A token lives for minutes.** `git` gets a fresh one when it needs one. A
  long job's later `curl` uses `"$($BRANCHD_TOKEN_COMMAND)"`, which prints a
  fresh token, as the `report` job does.
- **The variables:** `BRANCHD_TOKEN`; `BRANCHD_TOKEN_COMMAND`;
  `BRANCHD_API_URL` (branchd's API); `BRANCHD_REPOSITORY` (this repository's
  path); `BRANCHD_PR` (the pull request's number, on a pull request's run).
- **The CLI is not in the job.** Everything above is `curl` and `git`, which
  work on `golang:1.26` or any image with `curl` and a shell.

> **Not yet available** (cli in a job): the `branchd` CLI has no download a job can reach with its own token. It reads `BRANCHD_TOKEN` without set-up once it is on the `PATH`, so this changes when it has one.

## permissions:

| Permission        | `read`                                                                                                                                   | `write`                                                                                                                                                                                                                                    |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `contents`        | Always granted: this repository's commits, trees, blobs, diffs, branches and tags; `git fetch`.                                          | `git push`; creating and deleting branches and tags.                                                                                                                                                                                       |
| `pull-requests`   | Pull requests, their diffs, revisions, reviews and comments.                                                                             | Comment; edit and delete its own comments; resolve threads; a review that only comments; open, edit (not the target branch), close and reopen a pull request.                                                                              |
| `checks`          | Checks on commits.                                                                                                                       | Report a check on a commit (an external check: it never decides a merge).                                                                                                                                                                  |
| `releases`        | Releases and their files.                                                                                                                | Create, edit and delete releases; upload their files (`ReleaseService/CreateReleaseAsset`, the upload URL it answers, then `CompleteReleaseAsset`).                                                                                        |
| `packages`        | The repository's container images and generic packages, and the npm packages a CI grant lets it reach: list, pull, download and install. | Push images: `docker login -u job` with the token as the password. Publish [generic](https://docs.branchd.run/branchd/packages/generic#in-a-pipeline) and [npm](https://docs.branchd.run/branchd/packages/npm#in-a-pipeline) packages, and move their aliases and dist-tags; never delete. |
| `pipelines`       | Runs, their logs, plans and failures.                                                                                                    | Start, retry and cancel runs.                                                                                                                                                                                                              |
| `terraform-state` | This repository's [Terraform states](https://docs.branchd.run/branchd/terraform-state#in-a-pipeline).                                                            | Write them and take and release their locks; never delete.                                                                                                                                                                                 |

- **Where.** At the top of the file, `permissions:` is the default for every
  job; a job's own `permissions:` replaces it. With neither, `contents: read`.
- **Levels.** `read` or `write`; `write` includes `read`. An unknown name or
  level is refused with its line, and so is an empty `permissions:`.
- **Protected refs.** A `contents`, `releases`, `packages` or `terraform-state` write needs a
  protected ref, and a push or manual run by a person, an agent or the
  team's own bot. A scheduled or triggered run only reads them. Branch rules
  still apply to a push.
- **Pull requests and unprotected branches.** A pull request can change its
  own pipeline file, so on its run, and on any unprotected branch, writes are
  capped by the repository's ceiling: by default `pull-requests: write` and
  `checks: write`, and then only on that pull request and that commit. A
  repository's maintainers can lower the ceiling or add `pipelines` to it
  (the job token ceiling in its settings). Reads are never capped.
- **Never**, whatever is declared: change the repository's settings,
  variables, secrets, branch rules, members or visibility; approve, request
  changes on, merge or queue a pull request; release a manual job; write to
  another repository.
- **Called pipelines and composite steps.** A called pipeline's jobs get the
  calling job's permissions, and may narrow them, never widen them. A
  composite step runs with the permissions of the job that uses it.
- **Audit.** Every API call the token makes is recorded, allowed or refused,
  with the job, the permission and what it was limited to. A `git push` is
  recorded as a push by the job.

## Other repositories

The token reads another repository only where that repository grants it.
To use one:

- **its steps or pipelines**: `uses: <group>/<repo>/<path>@v1`
  ([Other repositories](https://docs.branchd.run/branchd/pipelines/other-repositories)), which
  branchd reads when the run is compiled;
- **its pipeline**: a `trigger:` job ([Trigger another repository](https://docs.branchd.run/branchd/pipelines/trigger-another-repository));
- **its packages** (images and generic packages): a
  [CI grant](https://docs.branchd.run/branchd/packages/access#another-repositorys-jobs) made
  there for this repository, which this job's own token then uses;
- **its Terraform states**: a [CI grant on the Terraform state area](https://docs.branchd.run/branchd/terraform-state#let-another-repositorys-jobs-in)
  made there, and `terraform-state: read` in this job's `permissions:`.
  `outputs` is enough for `terraform_remote_state`;
- **an npm scope or package**, which belongs to a group and not to a
  repository: a [CI grant on the scope or the package](https://docs.branchd.run/branchd/packages/npm#pipelines).
  A repository in the group that claimed the scope has one already;
- **its files at run time**: a [secret](https://docs.branchd.run/branchd/pipelines/secrets)
  holding a token that may read it.

A job also reads its team's private Go modules through branchd's module
proxy, with nothing to set up.

Source: https://docs.branchd.run/branchd/pipelines/job-token

---

# Limits

> The bounds on what one pipeline file can ask of the compiler and of a run.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

| What                                                                 | Limit                                                           |
| -------------------------------------------------------------------- | --------------------------------------------------------------- |
| One file (a pipeline file, a `step.yaml`, a called pipeline)         | 256 KiB                                                         |
| Jobs in one pipeline, called jobs and matrix cells included          | 500                                                             |
| `max-parallel`                                                       | Refused for now                                                 |
| Pipeline files in one commit                                         | 50                                                              |
| Schedules                                                            | 10 a file, 50 a repository; at most one fire every 5 minutes    |
| Triggered runs                                                       | 20 started by one run; 120 an hour into one repository          |
| Isolated steps in one job                                            | 8                                                               |
| `workspace:` paths of an isolated step                               | 32                                                              |
| Presets                                                              | One a file; 8 a push, 15 seconds of module time in all          |
| Steps in one job, its composite steps' included                      | 256                                                             |
| Matrix cells                                                         | 256; the product of the dimensions up to 1,024 before `exclude` |
| Matrix `include` and `exclude` entries                               | 256 each                                                        |
| `uses:` nesting                                                      | 4 deep, the file's own use counted as 1; a cycle is refused     |
| `uses:` expanded in one file                                         | 64, each use counted                                            |
| Files expanded by `uses:`                                            | 1 MiB in all, each use counted                                  |
| YAML values parsed for one file and what it uses                     | 200,000, each alias counted as what it expands to               |
| What one file compiles to                                            | 4 MiB                                                           |
| References to other repositories in a run                            | 32 distinct                                                     |
| Version tags of one major read per repository                        | 1,000                                                           |
| Different globs in one file (`on:` filters, `changed()`, `exists()`) | 1,000                                                           |
| Path-and-glob comparisons in one compile                             | 2,000,000                                                       |
| Expression nesting (parentheses, `!`, calls)                         | 64                                                              |
| `retry.max`                                                          | 0 to 10                                                         |
| Pipeline name                                                        | 1 to 64 characters, no `/`                                      |
| Schedule name                                                        | 64 characters: letters, digits, `.`, `_`, `-`                   |
| Secret name                                                          | Letters, digits and `_`, not starting with a digit, at most 93  |

Source: https://docs.branchd.run/branchd/pipelines/limits

---

# Run a runner on a Mac

> Install branchd's runner agent on your own Mac with one command, for jobs that need macOS, Xcode or a keychain.
> **Not yet available** (jobs on a Mac runner): the install works and the Mac joins its pool, but a Mac runner takes only trusted, protected work, and branchd cannot yet mark a pool that way. Until it can, the runner refuses every job it is handed, and the job fails with the reason.

A Mac runner is your own Mac (Apple silicon) running branchd's runner agent
for one of your runner pools. Jobs whose `runs-on` labels match the pool run
**on the Mac itself, as the Mac user you install it as**, with that user's
tools, files, GUI session and login keychain. There is no container and no
sandbox. Use it only for jobs that need macOS, and give the pool only to
work you trust (see [Security](https://docs.branchd.run/branchd/pipelines/security)).

## Install

1. Make a pool and get its registration token (`fpt_…`), with a signed-in
   [branchd CLI](https://docs.branchd.run/branchd/pipelines/quickstart):

   ```sh
   branchd pool create <owner> macos --labels macos,xcode --description "Our Mac: Xcode builds"
   ```

   `branchd pool rotate-token <pool>` prints a new token for an existing pool.

2. On the Mac, logged in as the user jobs should run as (not root, not
   `sudo`), run:

   ```sh
   curl -fsSL https://updater.xeonr.io/96/download/dst_f7c2d19cf6a09d65 | sh
   ```

   It asks for the pool token, registers the Mac with the pool, and starts
   the agent as a LaunchAgent of that user. It needs no other credential.

Running it again upgrades the agent and keeps its registration. The Mac user
must stay logged in, because a LaunchAgent stops at logout. Set the Mac to
log in automatically if the runner must survive a reboot.

| Setting              | Default                   |                                                                |
| -------------------- | ------------------------- | -------------------------------------------------------------- |
| `BRANCHD_POOL_TOKEN` | asked for                 | The pool's registration token. Used only on the first install. |
| `RUNNER_NAME`        | the Mac's local host name | The runner's name in the pool.                                 |
| `HEALTH_PORT`        | `8080`                    | The agent's local health port.                                 |

Put a setting before `sh`, for example `… | RUNNER_NAME=build-mac sh`.

## What it installs, and how it is checked

The agent and its step helper go in `~/Library/Pipelines/bin`, their state and
each job's working directory under `~/Library/Pipelines`, and the LaunchAgent
in `~/Library/LaunchAgents/io.xeonr.pipelines.runner.agent.plist`. Both
binaries are downloaded over HTTPS from the Xeonr Updater. Each archive's
SHA-256 must match the one written into the installer, and the one the
Updater recorded when it was published. If either differs, the installer
stops before installing anything.

## Check and uninstall

```sh
launchctl print gui/$(id -u)/io.xeonr.pipelines.runner.agent | head -20
tail -f ~/Library/Pipelines/runner.log
branchd runner list <pool>
```

To remove it, run this on the Mac, then drain the runner so the pool stops
listing it:

```sh
curl -fsSL https://updater.xeonr.io/96/download/dst_f7c2d19cf6a09d65 | sh -s -- --uninstall
branchd runner drain <runner>
```

Source: https://docs.branchd.run/branchd/pipelines/mac-runner

---

# A manual pipeline with inputs

> Let a person start a pipeline by hand, with typed inputs that the jobs read.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/release.yaml"
# .branchd/pipelines/release.yaml
# Started by hand, with typed inputs. On any other event an input reads its
# default, so the if: below works everywhere.
name: Release
on:
  manual:
    inputs:
      version:
        type: string
        required: true
        description: The version to tag, such as 1.4.0.
      channel:
        type: choice
        options: [stable, beta]
        default: beta
      dry_run:
        type: boolean
        default: true
jobs:
  release:
    image: alpine/git:2.47
    env:
      CHANNEL: ${{ inputs.channel }}
    steps:
      - run: echo "releasing ${{ inputs.version }} to $CHANNEL"
      - if: ${{ !inputs.dry_run }}
        run: ./scripts/tag-release.sh "${{ inputs.version }}"
```

- **`on: manual`** lets a person start this pipeline. `inputs:` declares what
  they give, each with a `type`: `string` (the default), `boolean`,
  `number` or `choice` (which needs `options`). `default`, `required` and
  `description` are optional.
- **Checked before the run starts.** A value of the wrong type, a `choice`
  outside its options, an input the file does not declare, or a missing
  required input with no default refuses the run.
- **`${{ inputs.<name> }}`** reads one, in `if:`, `env:`, `run:` and
  `with:`. In a `run:` it is a variable, never shell text.
- **On every other event** an input reads its default, else `''`, `false` or
  `0`, so an `if:` that reads one works for every event the file has.
- An input declared under both `manual` and `trigger` must have one type.

## Start it

From a terminal, inside the clone (a run of `main`'s current commit):

```bash
branchd run start main --pipeline Release --input version=1.4.0 --input channel=stable --input dry_run=false
```

From a job or a script, with the API (a job needs `permissions: {pipelines: write}`, see [The job token](https://docs.branchd.run/branchd/pipelines/job-token)):

```bash
curl -fsS -H "Authorization: Bearer $BRANCHD_TOKEN" -H 'Content-Type: application/json' \
  "$BRANCHD_API_URL/xeonr.forge.v1.RunService/CreateRun" \
  -d '{"repository":"acme/app","ref":"main","pipeline":"Release","inputs":{"version":"1.4.0","channel":"stable","dry_run":"false"}}'
```

`--pipeline` is the pipeline's `name:` (else its file name without
`.yaml`); its `on:` must list `manual`. Inputs are sent as text and checked
against their types: a refusal exits 2 and says which input and why.

To see what it would run first:

```bash
branchd ci plan --event manual --pipeline Release --input version=1.4.0
```

> **Not yet available** (cli 0.39.0): `branchd run start --pipeline … --input …` is in the next CLI release; until then use the API form above.

> **Not yet available** (console): the console's **Run pipeline** starts a run of a branch only, with no pipeline or inputs to choose.

Source: https://docs.branchd.run/branchd/pipelines/manual-runs

---

# Run a job for several versions (matrix)

> Run one job once for each combination of values, such as Go versions and databases.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Test on two Go versions and two databases: four jobs. The include entry
# adds race: true to the cell it agrees with, (1.26, mysql:8).
name: CI
on: [push, pull_request]
jobs:
  test:
    matrix:
      go: ['1.25', '1.26']
      db: ['mysql:8', 'mariadb:11']
      include:
        - {go: '1.26', db: 'mysql:8', race: true}
    image: golang:${{ matrix.go }}
    services:
      db:
        image: ${{ matrix.db }}
        env: {MYSQL_ROOT_PASSWORD: test, MARIADB_ROOT_PASSWORD: test}
    env:
      RACE: ${{ matrix.race }}
    steps:
      - run: go test ${RACE:+-race} ./...
  report:
    # Waits for every cell of test.
    needs: [test]
    image: alpine:3
    steps:
      - run: echo "all cells passed"
```

- **Cells.** `matrix:` maps keys to lists. The job runs once for each
  combination: here `test (1.25, mysql:8)`, `test (1.25, mariadb:11)`,
  `test (1.26, mysql:8)` and `test (1.26, mariadb:11)`. Each is a check of its
  own, such as `CI / test (1.26, mysql:8)`.
- **`${{ matrix.<key> }}`** reads a cell's value, in `image:`, `services:`,
  `env:`, `run:` and `if:`. Each cell's `if:` is decided on its own.
- **`include`** entries join every cell whose values they agree with, adding
  their other keys: `race: true` lands on the `(1.26, mysql:8)` cell. An entry
  that agrees with no cell is a cell of its own. In other cells
  `matrix.race` is empty, so `${RACE:+-race}` adds nothing.
- **`exclude`** entries remove the cells they match.
- **`needs: [test]`** waits for every cell that runs.
- **A failed cell stops the others,** as on GitHub: once a cell fails (after
  its retries), the cells that have not started never start, and running
  cells are cancelled. Jobs that need a cancelled cell are skipped, unless
  they run whatever happened (`if: always()`). Write `fail-fast: false` to let
  every cell run to its end.
- A matrix job has no `outputs:`.

Limits: at most 256 cells; the product of the lists may be up to 1,024
before `exclude` removes cells.

Source: https://docs.branchd.run/branchd/pipelines/matrix

---

# Steps and pipelines from another repository

> Use a composite step or a reusable pipeline that another repository publishes, pinned to a version.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

`xeonr/forge/steps` holds steps no product owns, for every repository to
use. In the publishing repository:

```yaml title="xeonr/forge/steps: .branchd/packages.yaml"
# xeonr/forge/steps: .branchd/packages.yaml
# What other repositories may use from xeonr/forge/steps. It is read at the head
# of the default branch, never at the commit being used.
packages:
  - setup-buf
  - .branchd/pipelines/deploy.yaml
```

```yaml title="xeonr/forge/steps: setup-buf/step.yaml"
# xeonr/forge/steps: setup-buf/step.yaml
# Used from another repository as xeonr/forge/steps/setup-buf@v1.
name: Set up buf
description: Installs buf.
inputs:
  version: {type: string, default: '1.56.0'}
outputs:
  path: ${{ steps.install.outputs.path }}
steps:
  - id: install
    run: |
      curl -fsSLo /usr/local/bin/buf \
        "https://github.com/bufbuild/buf/releases/download/v${{ inputs.version }}/buf-$(uname -s)-$(uname -m)"
      chmod +x /usr/local/bin/buf
      echo "path=/usr/local/bin/buf" >> "$BRANCHD_OUTPUT"
```

```yaml title="xeonr/forge/steps: .branchd/pipelines/deploy.yaml"
# xeonr/forge/steps: .branchd/pipelines/deploy.yaml
# Used from another repository as
# xeonr/forge/steps/.branchd/pipelines/deploy.yaml@v1. Its jobs run as the
# calling repository, with the secrets the calling job passes.
on:
  call:
    inputs:
      environment: {type: choice, options: [stage, production], default: stage}
    secrets:
      DEPLOY_TOKEN: {required: true}
jobs:
  apply:
    image: alpine:3
    environment: ${{ inputs.environment }}
    secrets: [DEPLOY_TOKEN]
    steps:
      - run: echo "deploying to ${{ inputs.environment }}"
```

In the repository that uses them:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Uses a composite step and a reusable pipeline of xeonr/forge/steps, each at the
# newest v1.x.y tag. The deploy pipeline chooses its environment, which
# this job allows.
name: CI
on:
  push:
    branches: [main]
jobs:
  lint:
    image: golang:1.26
    steps:
      - id: buf
        uses: xeonr/forge/steps/setup-buf@v1
        with: {version: '1.57.0'}
      - run: ${{ steps.buf.outputs.path }} lint
  deploy:
    needs: [lint]
    uses: xeonr/forge/steps/.branchd/pipelines/deploy.yaml@v1
    allow: [environment]
    with: {environment: production}
    secrets: [DEPLOY_TOKEN]
```

## The reference

`<group>/<repo>/<path>@<version>`. `<path>` is a directory holding
`step.yaml` (a step), or a `.yaml` file declaring `on: call` (a pipeline),
by its path from that repository's root. A repository's own path can have
several levels; the shortest leading part of at least two segments that is a
repository you can read is the repository.

## Versions

Versions are tags, resolved to one commit when the run is compiled:

| You write                | It is                                                                 |
| ------------------------ | --------------------------------------------------------------------- |
| `@v1`                    | the newest tag `v1.x.y`                                               |
| `@v1.4`                  | the newest tag `v1.4.y`                                               |
| `@v1.4.2`                | exactly that tag                                                      |
| `@1`, `@1.4`, `@1.4.2`   | the same, for tags without the `v`                                    |
| `@<40-character commit>` | that commit, if it is a version tag's commit or on the default branch |
| `@main`                  | refused: what runs must be fixed by a tag                             |

Only tags of the form `[v]X.Y.Z` count, with no leading zeros:
`v1.5.0-rc1` is never picked. Nobody has to move a `v1` tag. The run
records the tag and commit each reference resolved to, and
`branchd ci plan` prints them.

## packages.yaml: what may be used

The publishing repository lists what others may use in
`.branchd/packages.yaml`, read at the head of its default branch (never at
the commit being used, so a commit cannot list itself). A reference to a
path it does not list is refused, and so is any reference to a repository
without the file. Inside a used step or pipeline, `./<name>` is the
publisher's own `.branchd/steps/<name>`, which need not be listed.

## Who may use it

The publishing repository's visibility, judged for **your repository**
(never for the person who pushed):

| Its visibility | Usable by                                                             |
| -------------- | --------------------------------------------------------------------- |
| Private        | **That repository only**: not even the other repositories of its team |
| Company        | Every repository of a team the same company owns                      |
| Organisation   | Every repository of the organisation                                  |
| Public         | Any repository                                                        |

So to share steps, pipelines or a preset, give the repository company or
organisation visibility. A repository you cannot read is refused exactly as
one that does not exist, so the message never says which it was.

- **A nested reference** (a used step that uses another) must be readable by
  every repository in the chain, yours and each after it: a publisher cannot
  pull in what you may read and it may not.
- The job token plays no part: branchd reads the other repository when the
  run is compiled, as your repository. At run time the token still reads only
  your own.

## Consent: what another repository's pipeline may choose

A called pipeline of another repository runs as your repository, so it may
not choose for you, unless the calling job allows it:

- **`environment:`** on one of its jobs needs `allow: [environment]` on the
  calling job (or set `environment:` on the calling job yourself);
- **`trigger:`** jobs in it need `allow: [trigger]`;
- **runner labels** (`runs-on`) it asks for must each be listed in the calling
  job's own `runs-on`, which lends them.

## What you trust

A step of another repository runs in your job's shell, with your job's
secrets, job token and workspace. A pipeline of another repository is that
team's jobs running as your repository, with the secrets you pass it. Use
one only from a repository whose code you would run yourself. See
[Security](https://docs.branchd.run/branchd/pipelines/security).

Limits: at most 32 different references to other repositories in a run, and
the limits of [composite steps](https://docs.branchd.run/branchd/pipelines/composite-steps),
which count these uses too.

Source: https://docs.branchd.run/branchd/pipelines/other-repositories

---

# Pass outputs between steps and jobs

> Write a value in one step and read it in a later step of the same job, or in a job that needs this one.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# A step writes name=value lines to $BRANCHD_OUTPUT. A later step of the
# same job reads them as steps.<id>.outputs.<name>; a job that needs this
# one reads the job's outputs as needs.<job>.outputs.<name>.
name: CI
on: push
jobs:
  version:
    image: alpine:3
    outputs:
      version: ${{ steps.v.outputs.version }}
      channel: ${{ steps.v.outputs.channel }}
    steps:
      - id: v
        run: |
          echo "version=1.4.$CI_PIPELINE_IID" >> "$BRANCHD_OUTPUT"
          echo "channel=${{ branch == 'main' && 'stable' || 'beta' }}" >> "$BRANCHD_OUTPUT"
      - name: Use it in the same job
        run: echo "building ${{ steps.v.outputs.version }}"
  package:
    needs: [version]
    image: alpine:3
    env:
      VERSION: ${{ needs.version.outputs.version }}
    steps:
      - run: echo "packaging $VERSION for ${{ needs.version.outputs.channel }}"
```

- **Writing.** A step writes `name=value` lines to the file named by
  `$BRANCHD_OUTPUT`. Each step gets a fresh one.
- **In the same job.** A step with an `id:` makes its outputs readable by later
  steps as `${{ steps.<id>.outputs.<name> }}`.
- **To other jobs.** The job's `outputs:` map names to values, usually a
  step's output. A job that needs it reads `${{ needs.<job>.outputs.<name> }}`
  in `run:`, `env:`, `with:` and `image:`.
- **One line each.** An output is one line; a value whose fixed text has a
  line break is refused.
- **Known only while the job runs.** A job that reads another's outputs must
  need it, directly. An `if:` may read them: a step's `if:` reads an earlier
  step's (`if: steps.changes.outputs.api == 'true'`), decided when the step's
  turn comes, and a job's `if:` reads a needed job's
  (`if: needs.release.outputs.released == 'true'`), decided when its needs have
  run; a job whose `if:` is then false is skipped, with the jobs that need it.
  Only `==`, `!=`, `contains`, `startsWith`, `endsWith`, an output on its own
  (true when not empty), `!`, `&&` and `||` read an output in an `if:`; an
  output never set reads as `''`. See
  [Expressions](https://docs.branchd.run/branchd/pipelines/expressions#if-on-outputs).
- **Names.** Two step ids, job ids or output names that differ only in `-`
  and `_` are refused: they would name the same variable.
- **Where they reach.** A `run:` job's outputs reach the `run:` steps and
  `env:` of the jobs that need it. To feed a typed step's `with:` or a job's
  `image:`, the value must come from a typed step's job, as in
  [Build and push an image](https://docs.branchd.run/branchd/pipelines/build-and-push-an-image).
- A matrix job has no outputs.

> **Not yet available** (script outputs to images): a `run:` job's outputs reaching another job's `image:` or a typed step's `with:`. Only a typed step's outputs reach those.

Source: https://docs.branchd.run/branchd/pipelines/outputs

---

# Run only when certain paths change

> Start a pipeline only when files you care about change, and run each job only for the part that changed.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# The pipeline runs only when something under api/ or web/ changes; each
# job then runs only for the part that changed.
name: CI
on:
  push:
    branches: [main]
    paths: ['api/**', 'web/**', '!**/*.md']
  pull_request:
    paths: ['api/**', 'web/**', '!**/*.md']
jobs:
  api:
    if: changed('api/**')
    image: golang:1.26
    steps:
      - run: go test ./...
        working-directory: api
  web:
    if: changed('web/**') && exists('web/package.json')
    image: node:24
    steps:
      - run: npm ci && npm test
        working-directory: web
```

- **`paths:`** under `push` or `pull_request` starts the pipeline only when a
  changed path matches. Without a match, the file has no run for that commit,
  and `plan` says why.
- **Globs.** `*` matches within one path segment and `**` across segments;
  `?`, `[…]` and `{a,b}` work too. A leading `!` excludes, and the last
  pattern that matches decides: `'!**/*.md'` after `'api/**'` drops
  Markdown changes under `api/`.
- **`changed('glob', …)`** in an `if:` is true when any changed path matches.
- **`exists('glob', …)`** is true when a file of the commit matches.
- **Everything counts as changed** for a new branch, a tag, and a push with
  more changes than branchd lists. `paths` is not read for a tag.
- **Quote globs** that start with `*`, `!` or `{`: YAML reads those
  characters itself.

Do not require a check from a pipeline filtered by `paths:`: on a pull
request that changes nothing it matches, the check never reports, and the
pull request cannot merge. See
[Several pipelines in one repository](https://docs.branchd.run/branchd/pipelines/several-pipelines).

Source: https://docs.branchd.run/branchd/pipelines/paths

---

# Presets

> Get a whole set of standard jobs from a preset, configure it under with:, and add jobs of your own that wait for its jobs.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# The service preset tests and builds the api app. This file's own job
# waits for the preset's build job and reads its image output.
name: CI
preset:
  uses: branchd/presets/service@v1
  with:
    apps:
      api:
        type: k8s
        test:
          image: golang:1.26
          command: go vet ./... && go test -race -count=1 ./...
        build: {image: api}
jobs:
  smoke:
    needs: [preset.apps.api.build]
    image: ${{ needs.preset.apps.api.build.outputs.image }}
    steps:
      - run: /app/server --version
```

- **`preset:`** is `{uses, with}`. `uses` names the preset,
  `<group>/<repo>[/<path>]@<version>`, by repository and version as
  [other repositories](https://docs.branchd.run/branchd/pipelines/other-repositories) are named;
  `with` is its configuration. A file has at most one.
- **Finding one.** Every published preset you can use is in
  [Steps & presets](https://docs.branchd.run/branchd/pipelines/steps-and-presets).
- **Where presets come from.** Another repository, which lists the preset's
  path in its `.branchd/packages.yaml` and holds the built module at
  `<path>/preset.wasm` at the tagged commit. Who may use it is that
  repository's visibility, as for steps: a private repository's preset only
  by itself. `uses: ./<path>`, a preset of the same repository, is refused
  for now.
- **branchd's own presets** (`cli`, `library`, `mobile`, `npm`, `proto`,
  `service`) are one repository each in the `branchd/presets` group, each
  written, built and released on its own: write
  `branchd/presets/<preset>@v1`. Their old addresses
  (`xeonr/forge/presets/<preset>`, `branchd/presets-legacy/<preset>`) are
  retired.
- **Steps inside a preset.** A preset names each typed step it uses at an
  exact release of its repository, never `@v1`, so a new step release
  reaches a preset's jobs only through a new preset release. Your own jobs
  beside the preset may use `branchd/steps/<family>/<step>@v1`.
- **Trust.** A preset's jobs run with your repository's full context: they
  may name any of its secrets, set environments, start triggers and ask for
  runner labels, as your own jobs may. Pin a version you trust. To narrow
  what it may use, give `preset:` any of `secrets: [...]`, `allow: [environment, trigger]`, `runs-on: [...]` and `permissions: {...}`. The
  module itself never sees a secret's value.
- **Optional permissions.** A preset job may ask for a permission it can do
  without. It gets it only as far as the `preset:` block's `permissions:`
  grants it, else the file's top-level `permissions:`, else the default
  (`contents: read`); short of that the job runs with less, and nothing is
  refused.
- **A preset is a program** that reads `with:` and the run's facts and
  returns ordinary jobs. branchd runs it when the run is compiled, so
  `branchd ci plan` lists its jobs with yours.
- **Addresses.** Each preset job is at the path of the configuration that made
  it, under `preset.`: `preset.apps.api.test`, `preset.apps.api.build`. A
  prefix is a group: `needs: [preset.apps.api]` waits for every job of that
  app that runs, and `needs: [preset]` for the whole preset.
- **A need on one preset job** that does not run for this event is refused,
  unless it is `optional: true`. A need on an address the preset does not
  produce is refused, and the message lists the addresses it does.
- **Outputs.** A job that needs a preset job reads
  `${{ needs.preset.<address>.outputs.<name> }}`; any job that waits for it,
  directly or through other jobs, can read
  `${{ preset.<address>.outputs.<name> }}`.
- **Nothing patches a preset's job.** Your jobs sit beside them. A change to a
  preset's job is a change to `with:`; if the preset has no setting for it, it
  is added to the preset.
- **`on:` is optional.** Without it, the preset's own triggers apply. With it,
  the file runs when both match; an event the preset never runs on is refused.
- Your own job ids may not start with `preset.`.

## The service preset

`branchd/presets/service` tests, builds, migrates and deploys Kubernetes services
and the node app types, and takes the keys `.xeonr-ci.yaml` takes. Its jobs:

| Address                                                                                   | Job                                                                                                 |
| ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `test`, `apps.<name>.test`                                                                | The repository's and each app's tests                                                               |
| `lint.golangci`                                                                           | golangci-lint                                                                                       |
| `commits.lint`                                                                            | The commit subject check                                                                            |
| `migrations.check`, `migrations.<env>`                                                    | Strata migration check and migration                                                                |
| `buf.check`, `apps.<name>.generate`                                                       | buf check or generation                                                                             |
| `apps.<name>.retain`, `apps.<name>.build`                                                 | Retained assets; the image (outputs `image`, `tag`, `digest`)                                       |
| `apps.<name>.public`, `apps.<name>.release`, `apps.<name>.release-platforms`              | The public image copy; the released binary                                                          |
| `gitops.<env>`                                                                            | The environment's deploy commit                                                                     |
| `lantern.lint`, `lantern.apply`                                                           | Lantern declarations                                                                                |
| `docs`                                                                                    | The documentation site's build                                                                      |
| `install`                                                                                 | The node apps' dependency install                                                                   |
| `apps.<name>.check`                                                                       | A `renderer` or `upl-im` app's development build, on branches other than prod and stage             |
| `apps.<name>.build`, `apps.<name>.build.<env>`, `apps.<name>.build.linux`, `.win`, `.mac` | A `cf-worker`'s build; a `renderer`'s build per environment; an `electron` app's build per platform |
| `apps.<name>.deploy.<env>`, `apps.<name>.publish.<env>`                                   | A `cf-worker`, `renderer` or `electron` app's deploy or publish; an `upl-im` app's publish          |
| `helm.<name>.lint`, `helm.<name>.publish`                                                 | Each chart's lint and render on every run; its publish from the prod and stage branches             |

The `gitops.<env>` jobs ask for `contents: write` as an optional permission,
for the deploy commit. Grant it with `permissions: {contents: write}` under
`preset:` (or, when `preset:` sets no `permissions:`, at the top of the
file); without it they get the token the file
grants (see **Optional permissions** above).

Its app types are `k8s`, `cf-worker`, `renderer`, `electron` and `upl-im`;
`cli`, `npm`, `library`, `proto` and `mobile` are presets of their own
(`branchd/presets/<name>@v1`), and the service preset refuses them with
a message saying so. See [Coming from .xeonr-ci.yaml](https://docs.branchd.run/branchd/pipelines/from-xeonr-ci).

Source: https://docs.branchd.run/branchd/pipelines/presets

---

# Quick start

> In five minutes, add a pipeline to a repository, check it locally, push it, and read its checks.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## 1. Install the CLI (one minute)

```bash
curl -fsSL https://updater.xeonr.io/96/install.sh | sh   # or, if you have it: branchd upgrade
branchd auth login
```

`branchd ci lint` and `branchd ci plan` compile your pipeline files on your
machine with the same compiler branchd runs. They need no sign-in for a
repository's own files.

> **Not yet available** (cli 0.39.0): `branchd ci lint` checking every event a file lists, as the push check does, comes in the next CLI release. Releases from 0.33.0 read pipeline files and check the usual situations.

## 2. Add the file

Create `.branchd/pipelines/ci.yaml` in the root of your repository:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# The smallest useful pipeline: test every push to main and every pull request.
name: CI
on:
  push:
    branches: [main]
  pull_request:
jobs:
  test:
    image: golang:1.26
    steps:
      - run: go vet ./...
      - run: go test ./...
```

- `on:` says when the pipeline runs: pushes to `main`, and every pull request.
- `jobs:` holds one job, `test`. It runs in the `golang:1.26` image.
- `steps:` run in order, in one shell, in a checkout of the commit. You do
  not write a checkout step, and the image does not need git: every job
  starts with the repository's files, and `.git`, in its working directory.

A file must end in `.yaml`. A file ending in `.yml` is refused. A repository
uses pipeline files or the old `.forge-ci.yaml` / `.xeonr-ci.yaml`, never
both: delete the old file in the same commit.

## 3. Check it before you push

From the repository's root:

```bash
branchd ci lint
```

`lint` compiles every file in `.branchd/pipelines/` from your working tree
(uncommitted edits included) as branchd will: for a push to the default
branch, to `stage` and to a feature branch, a `v` tag, a pull request, a
scheduled run and a manual run of each manual pipeline, and then each file
for every event its `on:` lists. It prints one line per case and exits 1 if
any is refused. A refusal is `file:line:column: message`, and the message
says what to write instead.

To see what one push would run, and why:

```bash
branchd ci plan                        # a push of the current branch
branchd ci plan --event pull_request   # this branch as a pull request
```

```
pipeline CI (.branchd/pipelines/ci.yaml)
  read: .branchd/pipelines/ci.yaml
  1 of 1 jobs run (1 nodes)
  + test  no if
      platform/script as node test
  note: on: push to main (branches main)
```

A `+` job runs and a `-` job does not, each with the reason. On a branch the
file does not match, the plan says `nothing runs` and why, for example
`on: push: branch dev matches none of branches main`.

## 4. Push

```bash
git add .branchd/pipelines/ci.yaml
git commit -m "ci: add a pipeline"
git push
```

**branchd checks the push.** When a push changes `.branchd/pipelines/`,
`.branchd/steps/` or `.branchd/packages.yaml`, branchd compiles each changed
pipeline file for every event its `on:` lists before it accepts the push,
and answers in the push itself:

- a file that compiles: one line per pipeline saying which jobs run for this
  push, or when the pipeline runs if not for it;
- a file this push breaks: **the push is refused**, with
  `file:line:column: message` for each problem, as `branchd ci lint` prints
  it. Only the pushed branch's tip is checked, and only for what the push
  changed: a file that was already broken in the same way is a warning, not
  a refusal, so a revert or an old branch can always be pushed.
- If the check cannot run in time, the push goes through with a line saying
  so; the run's checks then report the problem.

Someone who may bypass the branch's rules can push a broken file anyway,
with `git push -o ci.allow-invalid`. The push is recorded as bypassed, and
the refusal shows that option only to people who may use it.

On the push, branchd reads `.branchd/pipelines/` at the pushed commit and
starts one run for each pipeline whose `on:` matches.

## 5. Read the checks

Each job reports a check on the commit, named `<pipeline> / <job>`, the job
as the file names it: here `CI / test`. A matrix cell is
`CI / test (1.26)`, a job of a called pipeline `CI / deploy / plan`. The
pipeline named exactly `ci` (lower case) is the exception: its checks are the bare job names
(`test`), as the old files' always were, unless the job's name itself holds
`/` (`ci / lib / prep`). A pull request shows the same checks; a branch
rule requires them by these names.

- In the browser: the repository's **Pipelines** tab,
  `https://branchd.run/<team>/<repository>/-/pipelines`, and one run at
  `…/-/pipelines/<number>`.
- From a terminal, inside the clone:

```bash
branchd run list                 # newest first; --pipeline CI for one pipeline
branchd run watch 12             # follow run 12 until it is over
branchd run log 12 test          # one job's log
branchd run failure 12           # why it failed: the failed job and its log's end
branchd pr checks                # the checks of the current branch's pull request
```

A newer push of the same branch or pull request **supersedes** the older
run: on a pull request or an unprotected branch the older run is cancelled,
on a protected branch the newer one waits for it. See
[Superseding](https://docs.branchd.run/branchd/pipelines/reference#superseding).

## Next

- [Run tests on a pull request](https://docs.branchd.run/branchd/pipelines/test-on-pull-request), with the checks to require.
- [Concepts](https://docs.branchd.run/branchd/pipelines/concepts): what a run, a job and a step are, and what is decided before a run starts.
- [Reference](https://docs.branchd.run/branchd/pipelines/reference): every key, on one page.

Source: https://docs.branchd.run/branchd/pipelines/quickstart

---

# Pipeline file reference

> The complete reference for .branchd/pipelines/*.yaml on one page, with every key, what it takes, what is refused, the job token, superseding, other repositories and presets. Also served as Markdown at /branchd/pipelines/reference.md.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

This page is the whole language on one page, and is served as Markdown at
[`/branchd/pipelines/reference.md`](https://docs.branchd.run/branchd/pipelines/reference.md)
for agents. [Expressions](https://docs.branchd.run/branchd/pipelines/expressions),
[Step files](https://docs.branchd.run/branchd/pipelines/step-files),
[Limits](https://docs.branchd.run/branchd/pipelines/limits) and
[Refusals](https://docs.branchd.run/branchd/pipelines/errors) go into more detail. The
[JSON Schema](https://docs.branchd.run/schemas/branchd/pipeline.json) is generated from the same key
tables as the compiler. These pages follow the compiler branchd runs.

## Files

- Each file in `.branchd/pipelines/` ending in `.yaml` is one pipeline. A file
  ending in `.yml` is refused.
- Each file is compiled on its own; a refused file does not stop the others.
- A repository with `.branchd/pipelines/` and an older CI file (such as
  `.xeonr-ci.yaml`) beside it is refused.
- YAML anchors and aliases (`&x`, `*x`, `<<: *x`) work.
- A repository that branchd has not switched to pipeline files ignores
  `.branchd/pipelines/` and runs its old files.
- One commit holds at most 50 pipeline files.

## Check names

Each job reports a check on the commit, `<pipeline> / <job>`, the job as the
file names it:

| Job                                        | Check                                                                                                        |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| a job                                      | `CI / build`                                                                                                 |
| a matrix cell                              | `CI / test (1.26, linux)`, `CI / cell (1, x)`                                                                |
| a job of a called pipeline                 | `CI / deploy / plan`                                                                                         |
| a preset's job                             | `CI / preset.apps.api.build`                                                                                 |
| an isolated step's earlier parts           | `CI / build [1/2]`; the last part is `CI / build`                                                            |
| any job of the pipeline named exactly `ci` | `build`, without `ci / `, as the old files' checks were; but `ci / lib / prep` when the job's name holds `/` |

A branch rule's required check is written the same way, and keeps matching
while the file names the job the same.

## Push checks

A push that changes `.branchd/pipelines/`, `.branchd/steps/` or
`.branchd/packages.yaml` is checked before it is accepted: each changed
pipeline file is compiled for the push's own run (or its pull request's)
and for **every event its `on:` lists**, with branch, tag, path, schedule
and `from:` filters treated as matching (a push to a branch and of a tag, a
pull request, each schedule up to three, manual and trigger with each
input's default, and for `on: call` a job of this repository calling it).

- A file the push breaks refuses the push, with `file:line:column: message`
  lines. A file that failed the same way at the branch's previous tip is a
  warning, so a revert or an old branch can always be pushed. Only the tip
  of each pushed branch is judged.
- Only what a file itself gets wrong refuses (syntax, unknown keys,
  expressions, limits, needs cycles, steps of this repository that do not
  exist). What depends on another repository is a warning.
- The check fails open: if it cannot run in time, the push goes through with
  a line saying so.
- `git push -o ci.allow-invalid` lets a broken file through, for those who
  may bypass the branch's rules; the push is recorded as bypassed.
- `branchd ci lint` (0.39.0 and later) runs the same every-event check
  locally.

## Top-level keys

| Key            | Takes                                                | Meaning                                                                                                                                                                                                                                                                                                                                                                                                    |
| -------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`         | string                                               | The pipeline's name, 1 to 64 characters, no `/`. Default: the file name without `.yaml`. Unique in the repository. Checks are named `<name> / <job>`.                                                                                                                                                                                                                                                      |
| `on`           | event, list, or map                                  | When it runs. Required. See [on](https://docs.branchd.run/branchd/pipelines/reference#on).                                                                                                                                                                                                                                                                                                                                         |
| `env`          | map                                                  | Environment for every job. May read `inputs.*`.                                                                                                                                                                                                                                                                                                                                                            |
| `defaults`     | `{image, runs-on}`                                   | The `image` and `runs-on` of jobs that set neither.                                                                                                                                                                                                                                                                                                                                                        |
| `max-parallel` |                                                      | **Refused for now**: branchd cannot yet limit how many jobs of a run run at once.                                                                                                                                                                                                                                                                                                                          |
| `concurrency`  | `{group, cancel-in-progress}`                        | With `group`, the repository's runs in the group never overlap: a newer run waits for the older, or cancels it with `cancel-in-progress: true` (GitHub's concurrency group). Without `group`, `true` lets a newer run cancel this pipeline's runs on a protected branch too, and `false` stops newer runs cancelling or queueing behind them. See [Superseding](https://docs.branchd.run/branchd/pipelines/reference#superseding). |
| `permissions`  | map                                                  | What the job token may do, for every job that does not set its own. See [The job token](https://docs.branchd.run/branchd/pipelines/reference#the-job-token).                                                                                                                                                                                                                                                                       |
| `preset`       | `{uses, with, secrets, allow, runs-on, permissions}` | The jobs of a preset of another repository. See [Presets](https://docs.branchd.run/branchd/pipelines/reference#presets).                                                                                                                                                                                                                                                                                                           |
| `jobs`         | map of ids to jobs                                   | Required, at least one, unless the file has a preset. See [Job keys](https://docs.branchd.run/branchd/pipelines/reference#job-keys).                                                                                                                                                                                                                                                                                               |

`on` is required unless the file has a preset, whose default triggers it
then narrows.

**Refused:** `max-parallel`; and
the GitLab CI keys `stages`, `variables` (use `env`), `default` (use
`defaults`), `workflow` (use `on`), `include` (use `uses`) and `schedules`
(use `on: schedule`).

## on

`on:` is an event (`on: push`), a list (`on: [push, pull_request]`), or a map
of events to their keys. A run is for one event. A file whose `on:` does not
match the event has no run, and `branchd ci plan` says why.

| Event          | Keys                           | Runs when                                                                                                                                                        |
| -------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `push`         | `branches`, `tags`, `paths`    | A push of a branch or a tag. With only `branches`, tags never run it; with only `tags`, branches never do; with neither, both do. `paths` is not read for a tag. |
| `pull_request` | `paths`                        | A pull request's run, for each new head.                                                                                                                         |
| `schedule`     | list of `{cron, name, ref}`    | A scheduled run of one of the file's schedules.                                                                                                                  |
| `manual`       | `inputs`                       | A person starts this pipeline.                                                                                                                                   |
| `trigger`      | `from` (required), `inputs`    | Another repository's `trigger:` job starts it.                                                                                                                   |
| `call`         | `inputs`, `secrets`, `outputs` | Never on its own: a job's `uses:` brings this file's jobs into its run. See [Reusable pipelines](https://docs.branchd.run/branchd/pipelines/reusable-pipelines).                         |

- **`branches`, `tags`, `paths`** are a glob or a list of globs. `*` matches
  within one path segment, `**` across segments; `?`, `[…]` and `{a,b}`
  work. A leading `!` excludes, and the last pattern that matches decides.
  `paths` holds when any changed path matches. A new branch, a tag, or a push
  with more changes than branchd lists counts as everything changed.
- **`schedule`**: `cron` (required) is five fields in UTC, firing at most
  every five minutes. `name` is letters, digits, `.`, `_` and `-`, at most
  64, unique in the repository; default `<file name>-<n>`. `ref` is a
  branch; empty is the default branch. At most 10 a file and 50 a
  repository. branchd keeps the schedules in line with the files on the
  **default branch**; each fire runs the file on `ref` at its newest commit.
- **`trigger.from`**: `organisation` (any repository), `company` (repositories
  of teams the same company owns as this repository's), or a list of
  repository paths. It is read from the default branch's file. A repository
  triggering its own pipeline must list itself.
- **The merge queue.** A merge-queue commit is a `push` to its target for
  `on:` alone, so `on: push: branches: [main]` runs on it. Its jobs see the
  queue's ref: `branch` is empty, `protected` false, `merge_queue` true, so a
  deploy gated on `branch == 'main'` is left out of it.
- **`inputs`** (under `manual`, `trigger` and `call`) map names to
  `{type, options, default, required, description}`:

  - `type`: `string` (default), `boolean`, `number` or `choice`;
  - `options`: the values of a `choice`, which needs them (and only a
    `choice` takes them);
  - `default`: the value when none is given;
  - `required`: a value must be given when there is no default;
  - `description`: for people.

  A run's inputs are checked against the types before it starts. An input
  the file does not declare is refused. On any other event an input reads
  its default, else `''`, `false` or `0`. A name declared under both
  `manual` and `trigger` must have one type. Two input names that differ
  only in case, `-` and `_` are refused.
- **`call.secrets`** map names to `{required, description}`.
  **`call.outputs`** map names to `${{ jobs.<id>.outputs.<name> }}`, or
  `{value, description}`.

## Job keys

A job id is letters, digits, `_` and `-`, starting with a letter or `_`. Ids
starting with `preset.` are reserved. Two ids that differ only in `-` and
`_` are refused.

| Key                       | Takes                                                         | Meaning                                                                                                                                                                                                                                                                                                                                                                                                           |
| ------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `steps`                   | list of steps                                                 | The job's steps. Required unless the job has `uses` or `trigger`. See [Step keys](https://docs.branchd.run/branchd/pipelines/reference#step-keys).                                                                                                                                                                                                                                                                                        |
| `uses`                    | string                                                        | Instead of `steps`: call a reusable pipeline, `./<path>.yaml` or `<group>/<repo>/<path>.yaml@<version>`. See [Calling jobs](https://docs.branchd.run/branchd/pipelines/reference#calling-jobs).                                                                                                                                                                                                                                           |
| `with`                    | map                                                           | The called pipeline's inputs. Only with `uses`.                                                                                                                                                                                                                                                                                                                                                                   |
| `allow`                   | list: `environment`, `trigger`                                | Only with `uses` of another repository: what it may choose for this run. See [Consent](https://docs.branchd.run/branchd/pipelines/reference#consent).                                                                                                                                                                                                                                                                                     |
| `needs`                   | id, list of ids, or `{job, optional, artifacts}`              | The jobs this one waits for, which must succeed. `optional: true`: the need is dropped when that job does not run for this event, and is an ordinary need when it does. `artifacts: false`: wait without downloading its artifacts. A need on a matrix job waits for each of its cells. A need on a job that does not run is refused unless optional. Needs name jobs of the same file only.                      |
| `if`                      | expression                                                    | False leaves the job out, with the reason. Decided when the run is compiled. It may use `always()` (run even after a failed need) and `success()`, not `failure()`. It may not read outputs.                                                                                                                                                                                                                      |
| `matrix`                  | map                                                           | One job per combination. See [matrix](https://docs.branchd.run/branchd/pipelines/reference#matrix).                                                                                                                                                                                                                                                                                                                                       |
| `trigger`                 | map                                                           | Start a run of another repository's pipeline. See [trigger](https://docs.branchd.run/branchd/pipelines/reference#trigger).                                                                                                                                                                                                                                                                                                                |
| `image`                   | string                                                        | The container image the job's `run:` steps run in. Required for a `run:` job, here or under `defaults`. A whole `${{ needs.<job>.outputs.<name> }}` of a typed step's job runs in an image built earlier in the run.                                                                                                                                                                                              |
| `runs-on`                 | string or list                                                | Runner labels. The label `deploy` is reserved for branchd's own deploy steps.                                                                                                                                                                                                                                                                                                                                     |
| `services`                | map of aliases                                                | Containers beside the job: an image, or `{image, env, command, entrypoint, ports}`. The alias is the service's host name.                                                                                                                                                                                                                                                                                         |
| `env`                     | map                                                           | Environment for the job's steps.                                                                                                                                                                                                                                                                                                                                                                                  |
| `outputs`                 | map                                                           | Values the jobs that need this one read as `${{ needs.<job>.outputs.<name> }}`. Each is one line. A matrix job has none.                                                                                                                                                                                                                                                                                          |
| `artifacts`               | list of paths, or `{paths, when, expire-in}`                  | Files kept after the job and placed in each job that needs it. `when`: `success` (default), `failure` or `always`. A path that is, holds or could match `.branchd/run/` (`.`, `*`, `**`, `.branchd`) is refused.                                                                                                                                                                                                  |
| `cache`                   | `{key, files, paths, policy, when, fallback-keys}`, or a list | `paths` (required) are kept between runs. `files` keys the cache on those files' contents, with `key` as the prefix. `policy`: `pull-push` (default), `pull` or `push`. `when`: `success` (default) or `always`. `fallback-keys` are tried when `key` has none.                                                                                                                                                   |
| `secrets`                 | list of names, or map of names to `{type, target, optional}`  | The secrets granted, as environment variables. `target` renames the variable; `type` is `env` (default) or `file` (a file secret; its path arrives in `target`). A listed secret set nowhere fails the job's attempt; a step's optional secret is skipped instead. `optional: true` grants it when its policy lets it reach the run, and withholds it, the job running without it, when it is missing or refused. |
| `checkout`                | `false`, or `{depth, tags, submodules}`                       | The checkout is automatic and needs nothing in the image, not even git. `depth` defaults to 50; `0` is the whole history. `tags: true` fetches tags. `submodules: true` checks out the submodules, `recursive` theirs too; a submodule must be readable without a credential (public, or internal on branchd), since the job token reads this repository only. `false` leaves the working directory empty.        |
| `repository-code-secrets` | boolean                                                       | Allows typed steps that execute repository code to receive secrets whose policy permits the step package. Anyone who can change that code can access those secrets.                                                                                                                                                                                                                                               |
| `permissions`             | map                                                           | What the job's token may do; replaces the file's. See [The job token](https://docs.branchd.run/branchd/pipelines/reference#the-job-token).                                                                                                                                                                                                                                                                                                |
| `permissions-optional`    | map                                                           | A preset's job only: permissions it asks for as far as the file grants them, clamped to the `preset:` block's `permissions:` (else the file's) and never refused. A file's own job is refused it. See [Presets](https://docs.branchd.run/branchd/pipelines/reference#presets).                                                                                                                                                            |
| `environment`             | name, or `{name, url}`                                        | Record a deployment to this environment.                                                                                                                                                                                                                                                                                                                                                                          |
| `concurrency`             | lock name, or `{group, cancel-in-progress}`                   | `group`: one job holding the lock runs at a time in the repository; others queue. `cancel-in-progress: true`: a newer run may stop this job part-way; `false`: never. Unset, the run's default decides ([Superseding](https://docs.branchd.run/branchd/pipelines/reference#superseding)).                                                                                                                                                 |
| `manual`                  | `true`, or `{wait, on-expiry, blocking}`                      | The job waits for a person to release it. `wait`: how long (`24h`); `on-expiry`: `fail` or `skip`; `blocking: false`: the run may finish without it.                                                                                                                                                                                                                                                              |
| `timeout`                 | duration                                                      | How long the job may run: `10m`, `1h30m`, `1 hour`.                                                                                                                                                                                                                                                                                                                                                               |
| `resources`               | `{cpu, memory}`                                               | What the job's step asks for: `cpu` in cores (`2`, `0.5`) or millicores (`500m`), `memory` as `8Gi` or `512Mi`. Only a runner pool whose job sizes hold the request takes the job; one no pool can hold fails `no_worker`. A host job takes none.                                                                                                                                                                 |
| `host`                    | `true`                                                        | The job's steps run in the shell of a runner's own machine, with no image or container.                                                                                                                                                                                                                                                                                                                           |
| `retry`                   | number, or `{max, when}`                                      | Retry a failed job up to `max` times (0 to 10). `when` lists failure kinds: `always`, `script_failure`, `stuck_or_timeout_failure`, `job_execution_timeout`, `runner_system_failure`, `unmet_prerequisites`, `missing_dependency_failure`, `api_failure`, `scheduler_failure`, `unknown_failure`, `data_integrity_failure`, `downstream_failure`.                                                                 |
| `continue-on-error`       | `true`, or `{exit-codes: […]}`                                | The job may fail and the run goes on; with `exit-codes`, only for those codes.                                                                                                                                                                                                                                                                                                                                    |

**Refused:** the GitLab CI job keys, each with its
replacement: `script` (`steps`), `before_script` (the first steps),
`after_script` (a last step with `if: always()`), `stage` (`needs`), `rules`
and `when` (`if`, or `manual: true`), `variables` (`env`), `allow_failure`
(`continue-on-error`), `resource_group` and `lock` (`concurrency`), `tags`
(`runs-on`), `parallel` (`matrix`), `extends` (`uses`, or YAML anchors),
`interruptible` (`concurrency: {cancel-in-progress: true}`) and
`module_token`.

## Step keys

| Key                 | Takes                     | Meaning                                                                                                                                                                                                                         |
| ------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                | id                        | Names the step in its job; its outputs are `steps.<id>.outputs.<name>`. Unique in the job.                                                                                                                                      |
| `name`              | string                    | What the log shows.                                                                                                                                                                                                             |
| `run`               | string                    | Shell commands. A step has `run` or `uses`.                                                                                                                                                                                     |
| `uses`              | string                    | A composite step, `./<name>` (`.branchd/steps/<name>/step.yaml`) or `<group>/<repo>/<path>@<version>`; or a typed step, such as `branchd/steps/<step>@<version>`, as the job's only step or `isolated: true` among other steps. |
| `with`              | map                       | The inputs of what `uses` names.                                                                                                                                                                                                |
| `if`                | expression                | `always()`, `failure()`, `success()`, and anything decided when the run is compiled. Without a status function it holds only while no step has failed. It may not read outputs.                                                 |
| `env`               | map                       | Added to the job's environment for this step.                                                                                                                                                                                   |
| `working-directory` | path                      | Where the step runs, relative to the workspace and inside it.                                                                                                                                                                   |
| `shell`             | `bash` or `sh`            | Run the step in that shell. Unset: the job's shell.                                                                                                                                                                             |
| `timeout`           | duration                  | The step fails when it runs longer.                                                                                                                                                                                             |
| `continue-on-error` | boolean                   | The job goes on if the step fails.                                                                                                                                                                                              |
| `isolated`          | boolean                   | `true` runs the step as a node of its own, a part of the job. Required for a typed step among other steps. See [Isolated steps](https://docs.branchd.run/branchd/pipelines/reference#isolated-steps).                                                   |
| `workspace`         | `all`, or a list of paths | On an isolated step: what it receives from the steps before it, and hands back. Left out, the checkout only.                                                                                                                    |

**How steps run.**

- A job's `run:` steps share one shell, bash when the image has it, else sh,
  with `set -e` (and `-o pipefail` under bash). A `cd` or an `export` in one
  step is seen by the next.
- A step with `env`, `working-directory`, `shell`, `timeout` or
  `continue-on-error` runs in a subshell of its own: its changes do not reach
  later steps. `shell` and `timeout` start a new shell, which sees exported
  variables only.
- When a step fails, the steps after it with `if: always()` or
  `if: failure()` still run, each in a subshell, and the job fails with the
  first failure's exit code. When the job is cancelled, its `if: always()`
  and `if: cancelled()` steps run after the cancel, in a fresh shell
  ([Cancelled jobs](https://docs.branchd.run/branchd/pipelines/expressions#cancelled-jobs)).
- In a job with such a step, a step that sets or clears the shell's EXIT trap
  is refused. Set it inside a subshell, `( trap 'rm -f x' EXIT; make )`, or
  give the step a `shell:` of its own.
- A step writes outputs as `name=value` lines to `$BRANCHD_OUTPUT`.

**A typed step** is one program, run in its own image, used by its
repository's path. branchd's shared typed steps are in the `branchd/steps`
group, one repository per family (`git`, `forge`, `images`, `go`, `node`,
`deploy`, `opentofu`), one directory with a `step.yaml` per step, each
repository released by its own version tags: `uses:
branchd/steps/<family>/<step>@<version>`, such as
`branchd/steps/images/image-build@v1`. `@v1` is the newest published `v1.x.y` tag
(a tag whose steps are not yet published is skipped); an exact tag, such as
`@v1.0.2`, pins it. The console's step list, and `forge_list_pipeline_steps`
on the Xeonr MCP gateway, are read from these repositories. As its job's
only step a typed step takes `id`, `name`, `uses`, `with`, `env`, `timeout`
and `continue-on-error`, its job takes no `image` or `checkout`, and its
`if:` goes on the job. Among other steps it must be `isolated: true`, and
also takes `if`, `isolated` and `workspace`. Its job's `outputs:` pass its
outputs on, and they reach a dependant's `image:` and `with:`.

**The old step names**, `ci/<name>@<version>` (such as `ci/image-build@1`),
still resolve. Each is an alias that branchd maps to the step's directory in
`branchd/steps` at an exact tag, which it moves with each release, and the
compile notes the address it resolved to. They are kept for existing files;
new files use the address.

**A step published by a product**, `uses: strata/migrate@1`, is a typed
step that the product publishes from its own repository and versions with
its own releases. The name resolves only through branchd's binding of the
namespace (`strata`) to the one repository that may publish into it
(`xeonr/strata/cli`), set by branchd and never by a pipeline file or the
product's repository: the step is the `step.yaml` in `steps/migrate` there,
at the newest `v1.x.y` tag, and it must name exactly `strata/migrate`. It is
also written by its path, `xeonr/strata/cli/steps/migrate@v1`. It gets only
what the job grants it (`secrets:` and `identity:` on the step), each of
which its `step.yaml` must declare. The run records the repository, tag,
commit and version each one resolved to, and the registry digest of that
version, and branchd refuses to start a run naming a product step that was
not read from its namespace's repository.

> **Not yet available** (product steps): no namespace is bound yet, so `uses: strata/migrate@1` is refused with a message saying so. Binary steps of your own repository are not available either.

**A composite step's use** takes `id`, `name`, `uses`, `with`, `if`, `env`,
`isolated` and `workspace`. See [Composite steps](https://docs.branchd.run/branchd/pipelines/composite-steps)
and [Step files](https://docs.branchd.run/branchd/pipelines/step-files).

## Isolated steps

A step marked `isolated: true` runs as a node of its own; the job is split
into parts around it, chained by `needs:`. Full guide:
[Isolate a step from the job](https://docs.branchd.run/branchd/pipelines/isolated-steps).

- `workspace:` lists globs relative to the working directory (at most 32,
  `dir/**` for a tree; `.git` only if listed), or `all`; left out, the step
  gets the checkout only and hands nothing back. A step that takes no
  source can be given `all` or nothing.
- What it writes inside those paths comes back; nothing outside the working
  directory, no exported variable, service or background process crosses.
  Step outputs cross.
- Refused: `if: failure()` on an isolated typed step, `continue-on-error` and
  a `concurrency` lock on the job, more than 8 isolated steps in a job.
- It gets only the secrets its package declares, and its identity tokens
  reach no other part.

## matrix

| Key               | Meaning                                                                                                                                                 |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<key>: [values]` | One dimension. The job runs once per combination of all dimensions.                                                                                     |
| `include`         | A list of maps. Each joins every combination whose values it agrees with, adding its other keys; one that agrees with none is a combination of its own. |
| `exclude`         | A list of maps. Each removes the combinations it matches.                                                                                               |
| `fail-fast`       | `true` (the default): once a cell fails, the others stop. `false`: every cell runs to its end.                                                          |

A cell is named `<id> (<values>)`, such as `test (1.26, linux)`. Values are
read as `${{ matrix.<key> }}`, and each cell's `if:` is decided on its own.
A matrix job has no `outputs`. At most 256 cells; the product of the
dimensions may be up to 1,024 before `exclude`; `include` and `exclude` take
up to 256 entries each.

## trigger

| Key        | Meaning                                                                |
| ---------- | ---------------------------------------------------------------------- |
| `repo`     | The repository to start a run in. Required.                            |
| `pipeline` | The name of the pipeline there (`.branchd/pipelines/<pipeline>.yaml`). |
| `ref`      | A branch there; empty is its default branch.                           |
| `inputs`   | Its `on.trigger.inputs`.                                               |
| `wait`     | `true`: this job takes the other run's result.                         |

The target must declare `on: trigger` with a `from` that allows this
repository. A trigger job takes only `trigger`, `needs`, `if`, `matrix`,
`environment`, `concurrency`, `manual` and `continue-on-error`.

## Calling jobs

A job with `uses:` calls a reusable pipeline (a file with `on: call`). It
takes `uses`, `with`, `needs`, `if`, `secrets`, `allow`, `runs-on`,
`environment`, `concurrency`, `manual` and `matrix`, and runs nothing itself.
With `matrix`, the pipeline is called once per cell, its jobs named
`<calling job> (<values>) / <job>`, and `with:` and `if:` read `matrix.*`.

- The called jobs join the run as `<calling job> / <job>`.
- `if:` false leaves them all out; `always()` lets the first of them run after
  a failed need.
- `needs:` are what the called pipeline's first jobs wait for. A job that
  needs the calling job needs every called job.
- `with:` gives `on.call.inputs`: an input it does not declare, or a missing
  required one, is refused. A whole `${{ needs.<job>.outputs.<name> }}` of a
  job it needs passes that output to a `string` or `choice` input.
- `secrets:` lists the secrets passed; each must be in `on.call.secrets`, and
  every required one must be passed.
- `environment:`, `concurrency:` and `manual:` are set on every called job. A
  called job that also sets `environment` or `concurrency` is refused; the
  caller's `manual` replaces a called job's own.
- Dependants read `on.call.outputs` as `${{ needs.<calling job>.outputs.<name> }}`.
- A called pipeline's expressions read the run's facts, its inputs, its own
  `env:` and its own jobs; `vars` is refused there. Its top-level
  `concurrency` applies only when it runs on its own.
- The calling file's `env:` and the repository's settings variables reach a
  called pipeline of the same repository, and not one of another repository.
- `matrix:` on a calling job is refused.

### Consent

For a pipeline of another repository, the calling job decides:

- an `environment:` on one of its jobs needs `allow: [environment]`;
- a `trigger:` job in it needs `allow: [trigger]`;
- each runner label it asks for (`runs-on`, or its `defaults.runs-on`) must be
  listed in the calling job's `runs-on`, which lends labels without setting
  them;
- a call inside it is allowed only what every calling job above it allowed.

A pipeline of the calling repository may set all of these.

## Other repositories

`uses:` of a step, `<group>/<repo>/<path>@<version>`, or of a pipeline,
`<group>/<repo>/<path>.yaml@<version>`, reads another repository when the
run is compiled. Full guide:
[Steps and pipelines of another repository](https://docs.branchd.run/branchd/pipelines/other-repositories).

- **The form** has at most 8 parts. The shortest leading part of at least two
  that is a repository you may read is the repository
  (`xeonr/forge/steps/setup-buf@v1` is `setup-buf` in `xeonr/forge/steps`).
- **Versions are tags**, resolved to a commit at compile time: `@v1` the
  newest `v1.x.y`, `@v1.4` the newest `v1.4.y`, `@v1.4.2` exactly, `@1` for
  tags without `v`; a 40-character commit only if a version tag names it or
  the default branch reaches it. A branch (`@main`) is refused. Only
  `[v]X.Y.Z` tags count (`v1.5.0-rc1` never does).
- **`.branchd/packages.yaml`** at the head of the publisher's default branch
  lists the step directories, pipeline files and presets others may use;
  anything else is refused. Inside a used step, `./<name>` is the
  publisher's own `.branchd/steps/<name>`.
- **Who may use it** is the publisher's visibility, judged for the calling
  repository: **private, that repository only**; company, repositories of
  the same company's teams; organisation, every repository; public, anyone.
  A repository you may not read is refused exactly as one that does not
  exist. A nested reference must be readable by every repository in the
  chain.
- **Trust.** A used step runs in your job's shell with its secrets, job
  token and workspace; a used pipeline is that team's jobs running as your
  repository with the secrets you pass. `branchd ci plan` lists each with
  the tag and commit it resolved to.
- **Consent.** A called pipeline of another repository may set
  `environment:` only with `allow: [environment]` on the calling job, start
  `trigger:` jobs only with `allow: [trigger]`, and ask only for runner
  labels the calling job's `runs-on` lists.
- At most 32 distinct references to other repositories in a run, and 1,000
  version tags of one major per repository.

## Presets

`preset: {uses: <group>/<repo>[/<path>]@<version>, with: {...}}` runs a
preset, a WebAssembly program in another repository
(`<path>/preset.wasm`, listed in its `packages.yaml`), and adds the jobs it
returns. Full guide: [Presets](https://docs.branchd.run/branchd/pipelines/presets).

- One preset a file. `uses: ./<path>`, a preset of the same repository, is
  refused for now.
- Its jobs are at addresses under `preset.`: `preset.apps.api.build`
  (check `CI / preset.apps.api.build`, node `preset_apps_api_build`). A
  prefix is a group: `needs: [preset.apps.api]`, or `needs: [preset]` for
  all of it.
- A need on one preset job that does not run here is refused unless
  `optional: true`. Its outputs are
  `${{ needs.preset.<address>.outputs.<name> }}`, or
  `${{ preset.<address>.outputs.<name> }}` in any job that waits for it.
- `on:` is optional; the file's own `on:` only narrows the preset's default
  triggers, and an event the preset does not trigger on is refused.
- Nothing in the file redefines a preset job: change `with:`.
- Its jobs have the repository's full context (secrets, environments,
  triggers, runner labels, `permissions:`). `secrets: [...]`, `allow: [environment, trigger]`, `runs-on: [...]` and `permissions: {...}` under
  `preset:` narrow what they may use.
- A preset job may ask for a permission optionally (`permissions-optional`): it gets it as far as
  the `preset:` block's `permissions:` grants it, else the file's, else the
  default, and is never refused for it. The service preset's `gitops.<env>`
  jobs ask for `contents: write` this way.
- branchd's presets (`branchd/presets/<preset>@v1`) are built from the
  `branchd/presets` repository, and name each typed step at an exact
  `branchd/steps` release, so a step release reaches them only through a
  preset release.
- A push runs at most 8 presets, 15 seconds of module time in all.

## The job token

Every job gets `BRANCHD_TOKEN`. `git` uses it with no set-up; the API takes
it as a bearer token (`POST $BRANCHD_API_URL/xeonr.forge.v1.<Service>/<Method>`,
JSON, lowerCamelCase fields). **It reads this repository only.** Full guide
with `curl` examples: [The job token](https://docs.branchd.run/branchd/pipelines/job-token).

| Permission        | `read`                                                                   | `write`                                                            |
| ----------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------ |
| `contents`        | Always: commits, trees, branches, tags, `git fetch`                      | `git push`, branches and tags                                      |
| `pull-requests`   | Pull requests, diffs, reviews, comments                                  | Comment, resolve, a comment-only review, open, edit, close, reopen |
| `checks`          | Checks on commits                                                        | Report an external check                                           |
| `releases`        | Releases and files                                                       | Create, edit, delete, upload                                       |
| `packages`        | List and pull images; download generic packages and install npm packages | Push images; publish generic and npm packages                      |
| `pipelines`       | Runs, logs, plans                                                        | Start, retry, cancel runs                                          |
| `terraform-state` | This repository's Terraform states                                       | Write them, take and release their locks                           |

- `permissions:` at the top is every job's default; a job's own replaces it;
  with neither, `contents: read`. An unknown name or level, or an empty
  `permissions:`, is refused.
- `contents`, `releases`, `packages` and `terraform-state` writes need a protected ref and a
  push or manual run by a person, an agent or the team's own bot. A
  scheduled or triggered run only reads them.
- On a pull request's run and any unprotected branch, writes are capped by
  the repository's ceiling (default `pull-requests: write`, `checks: write`,
  on that pull request and commit).
- Never: settings, variables, secrets, branch rules, members, visibility;
  approving, merging or queueing a pull request; releasing a manual job;
  another repository.
- A called pipeline's jobs get at most the calling job's permissions. A
  composite step has the using job's.
- Variables: `BRANCHD_TOKEN`, `BRANCHD_TOKEN_COMMAND` (prints a fresh token),
  `BRANCHD_API_URL`, `BRANCHD_REPOSITORY`, `BRANCHD_PR`.

## Superseding

A newer run of the same pipeline for the same pull request or branch
supersedes the older run. Runs of different pipelines never do.

| The older run is for                 | By default                                          | `concurrency: {cancel-in-progress: true}` at the top | `… false` at the top |
| ------------------------------------ | --------------------------------------------------- | ---------------------------------------------------- | -------------------- |
| a pull request                       | **cancelled**, its running jobs stopped             | cancelled                                            | runs side by side    |
| a push to an unprotected branch      | **cancelled**, its running jobs stopped             | cancelled                                            | runs side by side    |
| a push to a protected branch         | **runs to the end**; the newer run queues behind it | cancelled                                            | runs side by side    |
| a tag                                | runs side by side (each tag is its own ref)         | side by side                                         | side by side         |
| a manual, scheduled or triggered run | never superseded                                    | never                                                | never                |

- **Never stopped part-way**, whatever the default: a job with
  `environment:` (unless it says `cancel-in-progress: true`), a job whose
  typed step is not safe to interrupt (a deploy, a migration, a publish), and
  a job with `concurrency: {cancel-in-progress: false}`. Once one of those
  has started, the older run is not cancelled at all: it finishes, and the
  newer run queues behind it.
- A cancelled run's checks say `cancelled`, "superseded by run #N", never
  `failed`. A pull request's required checks are judged on its head commit
  only.
- A rollback is just a newer run: on a protected branch it queues behind the
  run in progress.

## Expressions in brief

Everything in `${{ }}` and `if:` is decided when the run is compiled, except
`steps.<id>.outputs.<name>` and `needs.<job>.outputs.<name>`, which are read
while the job runs (in `run:`, `env:`, `image:`, `with:` and job
`outputs:`, and in `if:`: a step's `if:` is decided when the step's turn
comes, a job's when its needs have run). Contexts: `branch`, `tag`, `event`, `pr.number`,
`pr.source`, `pr.target`, `inputs.*`, `matrix.*`, `vars.*`, `env.*`, `sha`,
`ref`, `repository`, `default_branch`, `protected`, `merge_queue`,
`preset.<address>.outputs.*`. Functions: `changed()`, `exists()`,
`contains()`, `startsWith()`, `endsWith()`, `always()`, `success()`,
`failure()`, `cancelled()`. A `${{ }}` in a `run:` becomes an environment variable, never
shell text. Details: [Expressions](https://docs.branchd.run/branchd/pipelines/expressions).

## Not available yet

Each is refused with a message saying so, or documented as missing:

- `max-parallel`.
- A `run:` job's outputs as an `image:` or a typed step's `with:`.
- A preset of the same repository (`./<path>`).
- Steps published by other products; binary steps of your own repository.
- A trigger of another repository that is not yet switched to pipeline
  files (today, every other repository).
- A step-level `secrets:` for an isolated step.

Source: https://docs.branchd.run/branchd/pipelines/reference

---

# Call a pipeline (reusable pipelines)

> Write jobs once in a pipeline file with on: call, and use them as one job of another pipeline.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

The reusable pipeline:

```yaml title=".branchd/pipelines/deploy.yaml"
# .branchd/pipelines/deploy.yaml
# A reusable pipeline: on: call only, so it never runs on its own. A job
# that uses it gets its two jobs, named "<calling job> / plan" and
# "<calling job> / apply".
on:
  call:
    inputs:
      version: {type: string, required: true}
      environment: {type: choice, options: [stage, production], default: stage}
    secrets:
      DEPLOY_TOKEN: {required: true}
    outputs:
      revision: ${{ jobs.apply.outputs.revision }}
env:
  TARGET: ${{ inputs.environment }}
jobs:
  plan:
    image: alpine:3
    steps:
      - run: ./scripts/plan.sh "${{ inputs.version }}" "$TARGET"
  apply:
    needs: [plan]
    image: alpine:3
    secrets: [DEPLOY_TOKEN]
    outputs:
      revision: ${{ steps.apply.outputs.revision }}
    steps:
      - id: apply
        run: ./scripts/apply.sh "${{ inputs.version }}" "$TARGET" >> "$BRANCHD_OUTPUT"
```

The pipeline that calls it, twice:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Calls deploy.yaml twice, once per environment. The run's jobs are build,
# stage / plan, stage / apply, production / plan, production / apply and
# announce.
name: CI
on:
  push:
    branches: [main]
jobs:
  build:
    image: alpine:3
    outputs:
      version: ${{ steps.v.outputs.version }}
    steps:
      - id: v
        run: echo "version=1.0.$CI_PIPELINE_IID" >> "$BRANCHD_OUTPUT"
  stage:
    needs: [build]
    uses: ./.branchd/pipelines/deploy.yaml
    with:
      version: ${{ needs.build.outputs.version }}
      environment: stage
    secrets: [DEPLOY_TOKEN]
  production:
    needs: [build, stage]
    uses: ./.branchd/pipelines/deploy.yaml
    with:
      version: ${{ needs.build.outputs.version }}
      environment: production
    secrets: [DEPLOY_TOKEN]
    environment: production
    manual: true
  announce:
    needs: [production]
    image: alpine:3
    steps:
      - run: echo "deployed ${{ needs.production.outputs.revision }}"
```

- **`on: call`** makes a file callable. It declares `inputs` (typed as for
  [manual runs](https://docs.branchd.run/branchd/pipelines/manual-runs)), `secrets`
  (`{required, description}`) and `outputs`, each output one job's output,
  `${{ jobs.<id>.outputs.<name> }}`. A file that declares only `on: call`
  never runs on its own.
- **A calling job** has `uses:` instead of `steps:`: `./<path>.yaml` from the
  repository's root, at this commit, or another repository's pipeline,
  `<group>/<repo>/<path>.yaml@v1` (see
  [Other repositories](https://docs.branchd.run/branchd/pipelines/other-repositories)). Its called jobs join this run, named
  `<calling job> / <job>`, with checks such as `CI / stage / apply`.
- **The calling job takes** `uses`, `with`, `needs`, `if`, `secrets`, `allow`,
  `runs-on`, `environment`, `concurrency`, `manual` and `matrix`. It runs
  nothing itself.
- **`matrix:`** on the calling job calls the pipeline once per cell, as GitHub
  calls a reusable workflow from a matrix: the cell's jobs are
  `<calling job> (<values>) / <job>`, its `with:` and `if:` read
  `${{ matrix.<key> }}`, and a job that needs the calling job waits for every
  cell's jobs. A matrix call has no outputs. With two or more cells, a failed called
  job cancels unfinished jobs across the call unless its matrix sets
  `fail-fast: false`.
- **`with:`** gives the inputs. A whole `${{ needs.<job>.outputs.<name> }}`
  of a job it needs passes that output to a `string` or `choice` input.
- **`secrets:`** lists what it passes. Each must be declared under
  `on.call.secrets`; a required one must be passed. A called job gets, of the
  secrets in its own `secrets:`, those the caller passed.
- **`needs:`** on the calling job is what the called pipeline's first jobs
  wait for. A job that needs the calling job needs all its jobs, and reads the
  declared outputs as `${{ needs.<calling job>.outputs.<name> }}`.
- **`environment:`, `concurrency:` and `manual:`** on the calling job are set
  on every called job. `manual: true` above makes `production / plan` and
  `production / apply` each wait to be released. A called job that sets its
  own `environment` or `concurrency` as well is refused.
- **What a called pipeline reads:** the run's facts, its inputs, its own
  `env:` and its own jobs. The repository's settings variables (`vars`) are
  refused there: pass them as inputs.
- Its jobs run as the calling repository, with its job token (at most the
  calling job's `permissions:`), runners and the secrets passed. A secret
  `on.call.secrets` declares `required: false` may be left out. A pipeline has at most 500 jobs, called jobs and matrix
  cells included.

Source: https://docs.branchd.run/branchd/pipelines/reusable-pipelines

---

# Run on a schedule

> Run a pipeline on a timetable, on the default branch or another one.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/nightly.yaml"
# .branchd/pipelines/nightly.yaml
# Runs on a timetable. Times are UTC. Each schedule has a name, unique in
# the repository, and a branch to run on (the default branch if empty).
name: Nightly
on:
  schedule:
    - name: nightly
      cron: '0 3 * * *'
    - name: weekly-stage
      cron: '30 6 * * 1'
      ref: stage
jobs:
  integration:
    image: golang:1.26
    timeout: 1h
    steps:
      - run: go test -tags integration ./...
  weekly-report:
    if: event == 'schedule' && branch == 'stage'
    image: alpine:3
    steps:
      - run: ./scripts/report.sh
```

- **`on: schedule`** is a list of `{cron, name, ref}`. `cron` has five fields
  (minute, hour, day of month, month, day of week), in UTC.
- **`name`** is unique in the repository, letters, digits, `.`, `_` and `-`,
  at most 64. Without one, a schedule is `<file name>-<n>` (`nightly-1`).
- **`ref`** is a branch; empty is the default branch.
- **`event == 'schedule'`** is true in a scheduled run, so one file can hold
  jobs for pushes and for schedules and tell them apart in `if:`.
- `timeout:` bounds a long job (`1h`, `90m`).
- **Limits.** A schedule fires at most every five minutes; a file holds at
  most 10 schedules and a repository 50. A file past any of them is refused.
- **Where they come from.** branchd keeps the repository's schedules in
  line with the pipeline files **on the default branch**: a push there that
  adds, changes or removes one updates them. A schedule in a file on another
  branch does nothing until it reaches the default branch. Each fire runs
  that file on the schedule's `ref`, at that branch's newest commit. The
  console can pause a file's schedule, not edit or delete it: change the
  file. A scheduled run reads with the job token and never writes
  `contents`, `releases` or `packages`, and it never starts a `trigger:`.
- **Check it locally:** `branchd ci plan --event schedule --schedule nightly`.

Source: https://docs.branchd.run/branchd/pipelines/schedules

---

# Editor support and the schema

> Use the JSON Schema of pipeline files, step.yaml and packages.yaml in an editor, in a script or in an agent.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

The schemas are generated from the compiler's own key tables, and the
compiler's tests check every example on these pages against them, so they
name exactly the keys the compiler accepts.

| File                        | Schema                                                                                  |
| --------------------------- | --------------------------------------------------------------------------------------- |
| `.branchd/pipelines/*.yaml` | [`https://docs.xeonr.io/schemas/branchd/pipeline.json`](https://docs.branchd.run/schemas/branchd/pipeline.json) |
| `step.yaml`                 | [`https://docs.xeonr.io/schemas/branchd/step.json`](https://docs.branchd.run/schemas/branchd/step.json)         |
| `.branchd/packages.yaml`    | [`https://docs.xeonr.io/schemas/branchd/packages.json`](https://docs.branchd.run/schemas/branchd/packages.json) |

They are JSON Schema draft-07. A refused key that has a replacement (such as
`variables:`, which is `env:`) is listed with the refusal as its
description, so an editor says what to write instead.

A schema checks keys and the shape of values. It does not know whether a
need names a job, what an expression reads, or the limits: `branchd ci lint`
does, and is the check that counts.

## In an editor

Editors that use `yaml-language-server` (VS Code's YAML extension, Neovim,
Helix, Zed, JetBrains IDEs) read a `$schema` comment on the first line of a
file. Put it above the path comment:

```text
# yaml-language-server: $schema=https://docs.xeonr.io/schemas/branchd/pipeline.json
# .branchd/pipelines/ci.yaml
```

Or map the files once, in VS Code's `settings.json`:

```json
{
  "yaml.schemas": {
    "https://docs.xeonr.io/schemas/branchd/pipeline.json": ".branchd/pipelines/*.yaml",
    "https://docs.xeonr.io/schemas/branchd/step.json": ["**/step.yaml"],
    "https://docs.xeonr.io/schemas/branchd/packages.json": ".branchd/packages.yaml"
  }
}
```

## In a script or an agent

Any JSON Schema validator that reads YAML will do. With Node.js:

```bash
npx --yes ajv-cli@5 validate --spec=draft7 \
  -s pipeline.json -d .branchd/pipelines/ci.yaml
```

where `pipeline.json` is the downloaded schema. An agent can fetch the schema
once and check each file it writes before running `branchd ci lint`; see
[Writing pipelines with an AI agent](https://docs.branchd.run/branchd/pipelines/ai-agents).

Source: https://docs.branchd.run/branchd/pipelines/schema

---

# Secrets

> Give a job the secrets it needs, as environment variables or files, and nothing else.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# A job sees only the secrets it lists. publish gets NPM_TOKEN as $NPM_TOKEN;
# apply gets the secret KUBE_TOKEN under another name, $K8S_TOKEN.
name: CI
on:
  push:
    branches: [main]
jobs:
  publish:
    image: node:24
    secrets: [NPM_TOKEN]
    steps:
      - run: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
      - run: npm publish
  apply:
    needs: [publish]
    image: bitnami/kubectl:1.33
    secrets:
      KUBE_TOKEN: {target: K8S_TOKEN}
    steps:
      - run: kubectl --token "$K8S_TOKEN" apply -f k8s/
```

- **Set a secret** on the repository, or on a group so that every repository
  beneath it inherits it, in the repository's or group's pipeline settings
  on branchd. A secret's name is the variable a job reads (`DEPLOY_TOKEN`):
  letters, digits and `_`, not starting with a digit.
- **Which runs may read it** is set with the secret: _protected_ or _all_
  runs. A protected secret reaches only runs of a person's (or an agent's
  acting for a person) push to a protected branch or tag, and runs one of
  them starts by hand of a protected branch's current head. It never
  reaches a pull request, a schedule, a trigger, a bot's run or a re-run of
  an older commit. Use protected for anything that can deploy or publish.
- **Host only** is meant for signing material read only by a host job
  (`host: true`, run on a machine's own user, such as a Mac's Xcode signing
  job). It cannot be set yet. branchd refuses it until the pipelines
  service can hold a secret to host jobs alone. Until then, keep signing
  material protected and limited to the repositories that sign.

## Where to set a secret

Set a secret once, on the level that every repository needing it shares.
A repository gets the nearest setting of a name:

1. the repository's own;
2. each group above it, nearest first, out to the team's own (root) group;
3. the **company** that owns the team, if the team is in one;
4. for plain variables only, the branchd instance.

A secret on a company reaches every repository of every team the company
owns, so a credential several teams use (a package registry token, a store
upload key) lives there once instead of on each repository. A team that
leaves the company, or a repository moved to a team outside it, stops
receiving the company's secrets from its next run. branchd reads a team's
company from Xeonr Auth at most every five minutes. If Auth cannot be
reached, branchd uses its last answer for up to an hour; after that, runs
that need it wait for Auth to answer. Company settings are
changed by the company's owners and the organisation's administrators, the
people who also manage its runner pools, not by a team's admins. In the
console they are under **Company runners → your company → Pipelines**; with
the CLI:

```sh
printf '%s' "$NPM_TOKEN" | branchd secret set NPM_TOKEN --company xeonr --access all
branchd secret list --repo xeonr/forge/ui     # shows NPM_TOKEN as set on company xeonr
branchd variable set GOPROXY https://proxy.golang.org,direct --company xeonr
```

### Limit a secret to the repositories that need it

A secret on a group, team or company reaches every repository beneath it.
For anything that can sign, deploy or publish, limit it to the runs that
need it. Whoever may set the secret sets its limit with it:

- **Teams** (a company's secret only): only repositories of these teams.
- **One group**: only repositories under that group.
- **Repositories**: only these repositories.
- **Steps**: only these step packages are handed it (`platform/script` is
  every free-form job). This guards against accident, not against an
  attacker. A step that runs the repository's own code, such as
  `ci/image-build` or `ci/go-build`, or that has service containers, can
  read any secret it is handed, and any process in a job can read that
  job's secrets. A step limit narrows which steps get the secret, not what
  code can read it there.

Name teams, one group, or repositories, not a mix. A secret's conditions
must all hold, so it cannot say "this team or that repository".
Setting a secret again without a limit keeps its limit; `--no-limit`
clears it. The settings and `branchd secret list` show each secret's limit
and how many teams and repositories it reaches. A protected secret with
no limit says so plainly.

```sh
printf '%s' "$CSC_LINK" | branchd secret set CSC_LINK --company xeonr --access protected \
  --limit-repos pixelstream/tv,pixelstream/tv-new
```

`branchd secret set` reads the value from standard input only, never from an
argument. A repository's or group's pipeline settings list every secret it
inherits and where it is set, never the value.

- **A job sees only what it lists.** `secrets: [NPM_TOKEN]` grants that one,
  as an environment variable of the same name. `secrets:` as a map gives
  each one `{type, target}`: `target` is the variable it arrives in (default:
  the secret's name), and `type` is `env` (the default) or `file`, for a
  secret stored as a file, whose path then arrives in `target`.
- A secret is never in the pipeline file, in `plan` output or in a check.
  Keep it out of logs yourself: do not `echo` it or run with `set -x`.
- **Plain variables** (settings variables, not secret) are also set on a
  repository or group, and read as `${{ vars.NAME }}` or `$NAME`.

## A secret that is not set

- **A secret a job lists that is set nowhere** fails that job's attempt
  before its steps run (the run's other jobs go on), and the plan shows it
  as missing.
- **Optional secrets.** A step can declare a secret it can do without:
  `secrets: {SENTRY_TOKEN: {required: false}}` in a composite step's
  `step.yaml`, or a secret a typed step's package marks optional (such as
  `LANTERN_API_KEY` for `branchd/steps/deploy/gitops-flux`, which only attributes
  deploys).
  When it is set nowhere the job runs without it, and the plan shows it as
  skipped, not as missing. A `required: true` secret of a composite step
  that the job does not grant is refused when the run is compiled.
- **A job's optional grant.** `secrets: {NPM_TOKEN: {optional: true}}` on a
  job grants the secret when its policy lets it reach the run, and withholds
  it, the job running without it, when it is missing or its policy refuses
  it.
- **A reusable pipeline's** `on.call.secrets` are `{required, description}`:
  a caller must pass each required one, and may leave out the others.

What a step from another repository can do with a job's secrets is on the
[Security](https://docs.branchd.run/branchd/pipelines/security) page.

Source: https://docs.branchd.run/branchd/pipelines/secrets

---

# Security

> What a pipeline, a step from another repository and a job token can do, stated plainly.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## A step you use has the whole job

A composite step, yours or another repository's, runs in your job's shell.
It can read every secret granted to the job, use the job token, read and
change the workspace and the checkout, and read the outputs of the steps
before it. Using a step is running its code as your own, exactly as using a
GitHub action is. A reusable pipeline of another repository is that team's
jobs running as your repository, with the secrets you pass it.

`branchd ci plan` prints, under each job, every step and pipeline of another
repository it runs, with the tag and commit, for example:

```
runs step xeonr/forge/steps/setup-buf@v1 (xeonr/forge/steps at v1.0.0 1111…) in this job's shell, with this job's secrets, job token, workspace and earlier steps' outputs
```

## Pinning

- `@v1` follows the publisher's newest `v1.x.y` tag. Each run records the
  commit it used, and a later run picks up a new tag.
- `@v1.4.2` is one tag. A tag is a name the publisher controls; to fix the
  exact code, use the 40-character commit, which must be a version tag's
  commit or on the publisher's default branch. Never a branch.
- Grant a job only the secrets it needs. A step cannot read a secret its
  job does not list.

## Pull requests

- A pull request on branchd is always from a branch of the same repository.
  There are no forks, so no pull request runs code from a repository you do
  not control. Its author can still change the pipeline file on their branch,
  and the run uses that branch's file.
- **Protected secrets** reach only runs of a person's push to a protected
  branch or tag, and a run a person starts by hand of a protected branch's
  current head (only someone the branch rule lets merge may start one, and it
  runs that head's own pipeline file), never a pull request's run. Give
  anything that can deploy or publish protected access.
- **A company's secrets** reach the repositories of the company's teams only,
  decided by branchd from the team each repository belongs to, never by a
  pipeline file.
- Who may use another repository's step is decided for the calling
  repository, never for the person who pushed, so a pull request from
  someone with wider access cannot pull in a package the repository itself
  could not use.

## Expressions are values

`${{ }}` is never pasted into a script: it becomes an environment variable
that the script reads. A branch name, an input, a pull request title or a
matrix value cannot become shell code. A value that would hold `${{` is
refused.

## The job token

Every job gets `BRANCHD_TOKEN`, a token for its run that lives for minutes.
Without `permissions:` it reads **its own repository only**: never another,
even of the same team. `permissions:` adds writes in this repository, and
branchd checks every use against what the job declared:

- `contents`, `releases` and `packages` writes need a protected ref, and a
  push or manual run by a person, an agent or the team's own bot. A
  scheduled or triggered run only reads them.
- On a pull request's run, and on any unprotected branch, writes are capped
  by the repository's ceiling (by default `pull-requests: write` and
  `checks: write`, on that pull request and commit only), because the pull
  request can change its own pipeline file.
- It can never change settings, secrets or branch rules, approve or merge a
  pull request, release a manual job, or write to another repository.
- Every API call it makes is recorded, allowed or refused.

The details and `curl` examples: [The job token](https://docs.branchd.run/branchd/pipelines/job-token).

## Private repositories

A private repository's steps, pipelines and presets are usable **by that
repository alone**. Another repository, of the same team or not, is refused
as if it did not exist. Share them by giving the publishing repository
company or organisation visibility, and keep in mind that whoever may use
them runs that code with their own secrets.

## Where code runs

A job runs in its own container on a runner. Runner labels (`runs-on`)
choose the runner; the label `deploy` is reserved for branchd's own deploy
steps, and a job of repository code that asks for it is refused.

Source: https://docs.branchd.run/branchd/pipelines/security

---

# Several pipelines in one repository

> Split a repository's CI into several files, and know which checks each one reports and which to require.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Checks: "CI / test" and "CI / lint" on every push and pull request.
name: CI
on: [push, pull_request]
jobs:
  test:
    image: golang:1.26
    steps:
      - run: go test ./...
  lint:
    image: golangci/golangci-lint:v2.1
    steps:
      - run: golangci-lint run
```

```yaml title=".branchd/pipelines/release.yaml"
# .branchd/pipelines/release.yaml
# Checks: "Release / binaries" on tags v1.2.3 and the like only.
name: Release
on:
  push:
    tags: ['v*']
jobs:
  binaries:
    image: golang:1.26
    steps:
      - run: GOOS=linux GOARCH=amd64 go build -o dist/app-linux-amd64 ./cmd/app
      - run: GOOS=darwin GOARCH=arm64 go build -o dist/app-darwin-arm64 ./cmd/app
    artifacts: [dist]
```

```yaml title=".branchd/pipelines/docs.yaml"
# .branchd/pipelines/docs.yaml
# Checks: "Docs / build", only when docs/ changes.
name: Docs
on:
  push:
    paths: ['docs/**']
  pull_request:
    paths: ['docs/**']
jobs:
  build:
    image: node:24
    steps:
      - run: npx --yes markdownlint-cli2 'docs/**/*.md'
```

- **One file, one pipeline, one run.** For each event, every file whose `on:`
  matches gets a run of its own. A file that does not match has no run, and
  `plan` notes why.
- **Each file is compiled on its own.** A file with a mistake is refused, with
  its own error, and the others still run.
- **Names.** A pipeline's name is its `name:`, else the file name without
  `.yaml`; 1 to 64 characters with no `/`. Two files with one name are refused.
- **Checks** are named `<pipeline> / <job>`, the job as the file names it:
  `CI / test`, `Release / binaries`, `Docs / build`. A matrix cell adds its
  values: `CI / test (1.26)`, `CI / cell (1, x)`. A job of a called pipeline
  adds the calling job: `CI / deploy / apply`. A part of a job with an
  isolated step is `CI / build [1/2]`. A pipeline named exactly `ci` has bare
  check names (`test`), as the old files' did, unless the name holds `/`
  (`ci / lib / prep`).
- **No needs across files.** A job needs only jobs of its own file. To share
  work, use a [reusable pipeline](https://docs.branchd.run/branchd/pipelines/reusable-pipelines).

## Required checks

A branch rule can require checks before a pull request merges. A required
check that a pull request's run never reports keeps the pull request from
merging, and branchd names it as missing. So require only checks that run on
**every** pull request to that branch:

- require `CI / test` and `CI / lint`, whose pipeline runs on every pull
  request;
- do not require `Docs / build` (filtered by `paths:`) or any job whose `if:`
  can be false on a pull request;
- renaming a pipeline or a job renames its check: change the rule with it.

Source: https://docs.branchd.run/branchd/pipelines/several-pipelines

---

# Skip a push's pipelines

> Push a commit without starting its pipelines, with [skip ci] in the commit message or the ci.skip push option, and what skipping does not affect.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

Some commits do not need a run: a typo in a README, a comment, a merge
that only tidies up. Say so in the commit message and the push starts no
pipeline.

```bash
git commit -m "docs: fix a typo [skip ci]"
git push
```

## The markers

Put one of these anywhere in the message of the **last commit you push**,
in any letter case:

| Marker           | Also read by   |
| ---------------- | -------------- |
| `[skip ci]`      | GitLab, GitHub |
| `[ci skip]`      | GitLab, GitHub |
| `[no ci]`        | GitHub         |
| `[skip actions]` | GitHub         |
| `[actions skip]` | GitHub         |

Only the head commit is read: the commit a pushed branch now points at,
the commit a pushed tag names, or a pull request's newest commit. A marker
in an earlier commit of the same push does nothing. The list is fixed; it
is not a setting.

Or leave the message alone and skip with a push option:

```bash
git push -o ci.skip
```

## What is skipped

|                                                       | A marker in the head commit                         | `git push -o ci.skip` |
| ----------------------------------------------------- | --------------------------------------------------- | --------------------- |
| A push to a branch                                    | Skipped                                             | Skipped               |
| A push of a tag                                       | Skipped, by the message of the commit the tag names | Skipped               |
| A pull request's run for a new commit                 | Skipped                                             | **Runs**              |
| A merge whose merge or squash commit carries a marker | Skipped                                             | –                     |

An annotated tag's own message is not read, only its commit's. The push
option does not skip a pull request's run, as on GitLab.

## What is never skipped

- A run started by hand: **Run pipeline**, `branchd run start`, the API's
  `CreateRun`.
- A re-run: **Re-run**, `branchd run retry <run>`.
- A [schedule](https://docs.branchd.run/branchd/pipelines/schedules).
- A run [another pipeline triggers](https://docs.branchd.run/branchd/pipelines/trigger-another-repository).
- The merge queue's run of a queued pull request.

A skipped push to the default branch still registers the `on: schedule`
entries of its pipeline files.

## A skip is shown, and it is not a pass

Each pipeline the push would have started keeps a run that never started.
It is listed with the commit and the pull request as cancelled, with the
reason **Skipped**, and its page says why:

```text
Skipped: the commit's message contains [skip ci]; re-run it to start it
```

`branchd run list`, `branchd run show` and the MCP's run and check tools
show the same state and reason. A pipeline whose `on:` would not have run for
the push anyway shows nothing, as before.

A skipped run reports no job's check, and its pipeline check is cancelled,
so **it satisfies no required check**. A pull request whose newest commit
was pushed with a marker cannot merge into a branch with required checks,
or join its merge queue, until those checks pass:

```text
required check test did not run on 3f2a1c9: its pipeline was skipped (the
commit's message contains [skip ci]), and a skipped run passes no required check
```

A branch with no required checks merges as it always did.

## Run it after all

Re-run the skipped run. It starts as the push or pull request run it would
have been, so the pipeline file needs no `on: manual`:

```bash
branchd run list --state cancelled   # find the skipped run's number
branchd run retry 42
```

Or push a commit without the marker. In the console, open the skipped run
and choose **Re-run**.

Source: https://docs.branchd.run/branchd/pipelines/skip-a-run

---

# Step and package files

> The keys of a step.yaml (composite and typed) and of .branchd/packages.yaml.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## step.yaml: a composite step

In `.branchd/steps/<name>/step.yaml` of your repository (used as `./<name>`),
or in any listed directory of a publishing repository (used as
`<group>/<repo>/<path>@<version>`).

```yaml title=".branchd/steps/setup-buf/step.yaml"
# .branchd/steps/setup-buf/step.yaml
# A composite step: steps with inputs, expanded into the job that uses it.
name: Set up buf
description: Installs buf, and signs in to the Buf Schema Registry when asked.
inputs:
  version: {type: string, default: '1.56.0'}
  login: {type: bool, default: 'false'}
secrets:
  BUF_TOKEN: {required: false, description: 'A Buf Schema Registry token, for login.'}
outputs:
  path: ${{ steps.install.outputs.path }}
steps:
  - id: install
    name: Install
    run: |
      curl -fsSLo /usr/local/bin/buf \
        "https://github.com/bufbuild/buf/releases/download/v${{ inputs.version }}/buf-$(uname -s)-$(uname -m)"
      chmod +x /usr/local/bin/buf
      echo "path=/usr/local/bin/buf" >> "$BRANCHD_OUTPUT"
  - name: Sign in
    if: inputs.login
    run: echo "$BUF_TOKEN" | buf registry login buf.build --token-stdin
```

| Key           | Takes                                                    | Meaning                                                                                                                                                                                           |
| ------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`        | string                                                   | Prefixes its steps' labels in the log. Default: the directory's name.                                                                                                                             |
| `description` | string                                                   | For people.                                                                                                                                                                                       |
| `inputs`      | map of names to `{type, default, required, description}` | `type`: `string` (default), `bool` or `int`. An input not given reads its default, else `''`, `false` or `0`.                                                                                     |
| `secrets`     | map of names to `{required, description}`                | Secrets it reads from the environment. The job that uses it grants them; a required one it does not grant is refused.                                                                             |
| `outputs`     | map of names to a value, or `{value, description}`       | Usually `${{ steps.<id>.outputs.<name> }}` of one of its steps.                                                                                                                                   |
| `steps`       | list of steps                                            | Required, at least one: `run:` steps and other composite steps, with the [step keys](https://docs.branchd.run/branchd/pipelines/reference#step-keys). A typed step (such as `branchd/steps/…` or `ci/…`) is refused here. |

A `step.yaml` with a binary step's keys is refused where a composite step is
expected.

## step.yaml: a typed step

A typed step is one program that branchd runs in its own image (or, with
`runs.kind: binary`, among a job's `run:` lines). It is written as manifest
version 2: `manifest: 2`. Its registry name comes from the repository and
the directory it is published from, so the file names none; other
repositories use it as `<team>/<repo>/<dir>@<version>`. See
[Writing a step](https://docs.branchd.run/branchd/pipelines/writing-a-step) for publishing.

```yaml title="steps/hello/step.yaml"
# steps/hello/step.yaml
# A typed step (manifest v2): one program, built from the Go main package in
# this directory, run in its own image. Its registry name comes from the
# repository and directory, so the file names none.
manifest: 2
name: Hello
description: Greets someone and says how long the greeting was.
runs:
  main: .
  platforms: [linux/amd64, linux/arm64]
source: true
inputs:
  who:
    type: string
    default: world
    description: Who to greet.
outputs:
  length:
    type: int
    description: The greeting's length in bytes.
secrets:
  GREETING_TOKEN:
    optional: true
    description: Not needed to greet; shown here to declare a secret.
```

### The step

| Key           | Takes  | Meaning                                                                                                                                   |
| ------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `manifest`    | `2`    | Required for every key below. A file without it is the older form (`package`, `main`, `platforms`, `image` at the top level), still read. |
| `name`        | string | Required. Shown in the step gallery and the run plan.                                                                                     |
| `description` | string | At most 1,024 characters.                                                                                                                 |
| `readme`      | path   | A Markdown file beside `step.yaml`, shown in the gallery.                                                                                 |
| `deprecated`  | string | A message printed as a note on every use.                                                                                                 |

### How it runs

| Key                  | Takes                               | Meaning                                                                                                                                                 |
| -------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `runs.main`          | path                                | The Go main package to build, relative to the directory (it may be `../cmd/x`, inside the repository). Or:                                              |
| `runs.binaries`      | map of platforms to paths           | Prebuilt programs.                                                                                                                                      |
| `runs.args`          | list of strings                     | Arguments after the program on its command line, so one program can be several steps.                                                                   |
| `runs.platforms`     | list                                | `linux/amd64` (default), `linux/arm64`, `darwin/arm64`, …                                                                                               |
| `runs.image`         | `{base}`                            | The image the program is added to, by digest. Default: a minimal non-root image.                                                                        |
| `runs.kind`          | `image` (default) or `binary`       | `binary`: per-platform programs that can also run inline among a job's `run:` lines, and on a host.                                                     |
| `runs.host`          | bool                                | It can run in a `host: true` job.                                                                                                                       |
| `source`             | bool                                | It takes the checkout as its `source` input.                                                                                                            |
| `no_repository_code` | bool                                | With `source`: it runs none of the repository's code.                                                                                                   |
| `git`                | `{history, tags, refs, submodules}` | What it needs of the checkout: `history` is `full`, `none` or a depth; `tags: true` fetches tags; `refs` lists more refs, `default_branch` or `refs/…`. |
| `uninterruptible`    | bool                                | A newer run never interrupts a job running it, and `cancel-in-progress` on such a job is refused.                                                       |
| `lock`               | string                              | The lock its job takes when the job names none; `{<input>}` is replaced by that input's value.                                                          |
| `capabilities`       | list                                | What it needs of its sandbox: `services`, and `network`, `privileged` or `host_runtime`, which the repository's step grant must allow.                  |
| `runner`             | `{labels, ignore_labels}`           | `labels`: the runner labels its job asks for when the job names none. `ignore_labels`: older labels a job may still name for it, accepted and dropped.  |
| `env`                | `{job_variables, reserved}`         | `job_variables: true` passes the job's variables to its `env` input; `reserved` lists further names (or prefixes ending `_`) dropped from it.           |

### Inputs and outputs

| Key                         | Takes                                                                                    | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| --------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputs`                    | map of names to `{type, default, required, description, literal, platform, destination}` | `type`: `string`, `int`, `bool`, `duration`, `list`, `map`, `object` or `blob` (no default). `env` and `source` are reserved names.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `inputs.<name>.literal`     | bool                                                                                     | A pipeline file must give a literal value, known at compile time. Required of any input a `when` or `lock` reads.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `inputs.<name>.platform`    | `rollback` or `{remote: {of: <input>}}`                                                  | Only branchd sets it; a pipeline file that does is refused. `rollback`: set on a rollback run of the step. `remote`: the off-branchd remote of the repository another input names, when its owner has recorded one.                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `inputs.<name>.destination` | map                                                                                      | Where the step may send a credential with this value; any other value is refused at compile and again when it runs. `hosts`: host names (`*.` matches one or more labels) a URL may be on; `forge: true`: branchd's own hosts; `paths: true`: the URL may have a path; `version: true`: `x.y.z`, a leading `v`, or `latest`; `any: true`: anywhere, and the step then gets no secret its job does not list; `list: {url: <field>}`: the value is a list of objects whose field holds the URL; `match`: each named field of a list item must match a pattern. An address-like input (`url`, `*_url`, `registry`, `host`, …) without one cannot be set by a file. |
| `outputs`                   | map of names to `{type, required, description, attest}`                                  | `type`: `string`, `int`, `bool`, `json` or `blob`. Required unless `required: false`. `attest: true` carries the value, signed, in the identity token of every job that needs this one.                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

### Secrets and credentials

| Key                     | Takes                                                                          | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ----------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `secrets`               | map of names to `{required, optional, file, description, when, required_when}` | `required`: granted without the job listing it. `optional`: the step works without it. `file`: delivered as a file. `when`: the declaration applies only while a condition on its inputs holds. `required_when`: required only while it holds.                                                                                                                                                                                         |
| `when`, `required_when` | `{input, set}`, `{input, equals}` or `{input, in}`, or a list (all of them)    | The input must be `literal` or `platform`.                                                                                                                                                                                                                                                                                                                                                                                             |
| `accepts_any_secret`    | bool                                                                           | It takes the secrets its job lists beyond those declared; each secret's own limits decide. Needs the repository's step grant.                                                                                                                                                                                                                                                                                                          |
| `credentials`           | list of `{application, scope, env, resources, when, replaces, drops, signal}`  | A token for one Xeonr product, exchanged from the job's identity: `application` (required) names the product; `scope` what it asks for; `env` the variables it is written to; `resources` narrows it from inputs (`{input, type}`); `replaces` lists stored secrets it stands in for (a job that grants one uses it instead); `drops` lists grants dropped when it is used; `signal: true` tells the step which audience it was given. |

### branchd and delivery

| Key        | Takes                                                                                   | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ---------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `forge`    | `{identity, permissions, push_to}`                                                      | `identity`: the branchd surfaces its job token reaches (`git`, `api`, `registry`, `modules`); `permissions`: what its job token must be able to do, in `permissions:` names; `push_to`: the input naming another repository it pushes to, allowed only where that repository's owner granted it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `delivery` | `{role, environment, apps, target, channel, origin, platforms, report, rollback, when}` | What it does for a run's delivery. `role`: `migrate`, `rollout`, `after`, `check` or `publish` (the run's build goes to a product's channel for others to install: not a deploy, so no watch and no rollback). `environment`, `target`: `{input}` naming the input that holds it. `apps`: `{input, field}`, for a rollout or a publish: the list it moves and the field naming each app, or a string input naming one app. `channel`, `origin`, `platforms`: `{input}` naming the inputs that hold the product channel a publish goes to, the product's origin it goes to, and the platforms it carries. `report`: `{output}`, a check's output shown on the pull request. `rollback`: `{inputs}`, what a rollback run of a rollout sets. `when`: conditions on its inputs, as for `secrets`; a node where they do not hold does nothing for the delivery (a dry run). |

Unknown keys are refused.

## .branchd/packages.yaml

In a repository whose steps or pipelines other repositories use. Read at the
head of its default branch.

```yaml title="xeonr/forge/steps: .branchd/packages.yaml"
# xeonr/forge/steps: .branchd/packages.yaml
# What other repositories may use from xeonr/forge/steps. It is read at the head
# of the default branch, never at the commit being used.
packages:
  - setup-buf
  - .branchd/pipelines/deploy.yaml
```

| Key        | Takes         | Meaning                                                                                                                                                    |
| ---------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `packages` | list of paths | Step directories (holding `step.yaml`) and pipeline files (declaring `on: call`) other repositories may use, by path from the repository's root. Required. |

Source: https://docs.branchd.run/branchd/pipelines/step-files

---

# Browse steps and presets

> Find a published step or preset, see what it does, takes and asks for, and get your own listed.
> **Available** on branchd.run to everyone signed in. Signed out, only global entries show, and there are none until a step repository is made public.

**[Steps & presets](https://branchd.run/-/steps)** on branchd lists every
published step and preset you can use. Each entry shows what it does, its
inputs and outputs with their types, the secrets and product credentials it
asks for, the capabilities its repository's grant allows, its versions with
release notes, a snippet to paste into a pipeline file, who publishes it,
and how many repositories ran it in the last 30 days.

## What you see

You see an entry when you can read its repository's code. For everyone
else it does not exist: it is not in search results, and its page is not
found.

Each entry carries a **scope**, taken from its repository's visibility:

| Scope        | The repository is                          | Shown to                                            |
| ------------ | ------------------------------------------ | --------------------------------------------------- |
| Global       | public, with code public                   | everyone, signed in or not                          |
| Organisation | organisation-visible, with code open to it | everyone signed in to branchd's organisation        |
| Company      | company-visible, with code open to it      | the teams of the publisher's company                |
| Team         | private, or code kept to members           | the publishing team, and people it has given access |

A Team entry you reach through an access grant, not as a team member, is
labelled **shared with you**. The page has a section per scope, and shows a
section only when it has entries for you.

A **verified publisher** mark means a branchd administrator has verified the
publishing team. It changes nothing else: it does not decide who sees an
entry or whether it runs.

## From the command line

```sh
branchd ci steps search deploy            # find steps and presets
branchd ci steps search --kind preset --scope global
branchd ci steps show branchd/steps/deploy/gitops-flux
branchd ci steps show branchd/presets/library@v1.0.3
```

`--json` prints the forge's answer for scripts and agents. An agent on the
Xeonr MCP gateway has the same reads as `forge_search_steps` and
`forge_get_step`.

## Getting yours listed

There is no submission. A version is listed once it is published:

- **A step** when its repository's release run publishes it from a version
  tag ([Writing a step](https://docs.branchd.run/branchd/pipelines/writing-a-step)).
- **A preset** when a version tag of a repository whose
  `.branchd/packages.yaml` lists it is pushed, within the hour
  ([Writing a preset](https://docs.branchd.run/branchd/pipelines/writing-a-preset)).

Only directories `.branchd/packages.yaml` lists are listed. A repository's own
`.branchd/steps/` are never listed. To list globally, make the repository
public with code public. Anyone may publish globally, and no verification is
needed.

### Listed well

The catalogue shows what your directory documents. These make a listing
useful, and entries that have them rank higher:

- a **human `name:`** that says what it does ("Build an image"), not an
  alias such as `ci/image-build` and not the directory's name;
- a **`description:`** of a sentence or two;
- a **`README.md`** beside `step.yaml` or `preset.yaml`, rendered on the
  entry's page;
- an **example** in the README: a `yaml` block that writes
  `uses: <your address>@v1`, shown above the generated snippet;
- a **description on every input, output and secret**;
- for a product credential, the **`scope`** it needs;
- for a preset, its **jobs** (`preset.Address`) and the **steps** it runs
  (`preset.Steps`).

To see what your listing lacks, run this in the step's or preset's directory.
It reads what you have pushed:

```sh
branchd ci step lint
```

The repository's maintainers also see the findings on the entry's page.
Findings never block a publish.

Source: https://docs.branchd.run/branchd/pipelines/steps-and-presets

---

# Test a Go service with a database

> Run a Go service's tests against a MySQL database that runs beside the job.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Test a Go service against a MySQL database that runs beside the job.
name: CI
on: [push, pull_request]
jobs:
  test:
    image: golang:1.26
    services:
      mysql:
        image: mysql:8
        env:
          MYSQL_ROOT_PASSWORD: test
          MYSQL_DATABASE: app
    env:
      # The service's alias, mysql, is its host name.
      TEST_MYSQL_DSN: root:test@tcp(mysql:3306)/app?parseTime=true
    steps:
      - name: Wait for MySQL
        run: |
          for i in $(seq 1 60); do
            (echo > /dev/tcp/mysql/3306) 2>/dev/null && exit 0
            sleep 1
          done
          echo "MySQL did not start" >&2
          exit 1
        shell: bash
      - run: go vet ./...
      - name: Test
        run: go test -race -count=1 ./...
```

- **`services:`** starts each listed image beside the job, for the job's
  whole life. The key, `mysql`, is the service's host name: the tests connect
  to `mysql:3306`. A service is an image, or
  `{image, env, command, entrypoint, ports}`.
- **`env:`** on the job gives every step `TEST_MYSQL_DSN`.
- **Waiting.** A service is started with the job, not waited for. The first
  step polls the port until MySQL answers. It uses bash's `/dev/tcp`, so it
  says `shell: bash`; the job's other steps run in the job's shell (bash when
  the image has it, else sh).
- **`name:`** is what the log shows for a step; without it the log shows the
  command.

To try another database, change `image:` under the service; to test against
several, see [Matrix](https://docs.branchd.run/branchd/pipelines/matrix).

Source: https://docs.branchd.run/branchd/pipelines/test-go-with-database

---

# Test a Node.js project

> Install, lint, test and build a Node.js project with pnpm, keeping the package store between runs.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Install, lint, test and build a Node.js project with pnpm, keeping the
# package store between runs.
name: CI
on: [push, pull_request]
jobs:
  test:
    image: node:24
    env:
      PNPM_STORE_DIR: .pnpm-store
    cache:
      key: pnpm
      files: [pnpm-lock.yaml]
      paths: [.pnpm-store]
    steps:
      - run: corepack enable
      - run: pnpm config set store-dir "$PNPM_STORE_DIR"
      - run: pnpm install --frozen-lockfile
      - run: pnpm lint
      - run: pnpm test
      - run: pnpm build
    artifacts:
      paths: [dist]
      expire-in: 7 days
```

- **`cache:`** keeps `.pnpm-store` between runs. `files: [pnpm-lock.yaml]`
  keys the cache on the lock file's contents, with `key` as the prefix, so a
  new lock file starts a new cache. Cache `paths` are relative to the
  working directory.
- **Steps share one shell**, so `corepack enable` in the first step holds for
  the rest.
- **`artifacts:`** keeps `dist` for 7 days. A job that `needs: [test]` would
  find it in its own working directory.

For npm, replace the pnpm steps with `npm ci` and cache `~/.npm` by setting
`npm_config_cache` to a path inside the working directory.

Source: https://docs.branchd.run/branchd/pipelines/test-node

---

# Run tests on a pull request

> Test every pull request and every push to main, and require the checks before a pull request merges.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# Test every pull request, and every push to main. The checks are
# "CI / lint" and "CI / test (1.25)", "CI / test (1.26)": require those in
# main's branch rule. The lint job's image has no git: the checkout needs
# nothing in the image.
name: CI
on:
  push:
    branches: [main]
  pull_request:
jobs:
  lint:
    image: alpine:3.20
    steps:
      - run: apk add --no-cache shellcheck
      - run: shellcheck scripts/*.sh
  test:
    matrix:
      go: ['1.25', '1.26']
    image: golang:${{ matrix.go }}
    steps:
      - run: go vet ./...
      - name: Test
        run: go test -race -count=1 ./...
```

- **`pull_request:`** with nothing under it runs for every pull request, on
  each new head. On branchd a pull request is always from a branch of the
  same repository, and its run uses that branch's pipeline files.
- **`push: branches: [main]`** also tests what lands on `main`. Without it a
  push to a feature branch that has no pull request runs nothing.
- **No checkout step, no git in the image.** `lint` runs in `alpine:3.20`,
  which has no git. Every job starts in a checkout of the run's commit, with
  `.git`, fetched before the job's container starts. `checkout: {depth: 0}`
  fetches the whole history (50 commits by default), `checkout: {tags:
  true}` the tags, `checkout: false` nothing.
- **Steps share one shell**, bash when the image has it, else sh, with
  `set -e`: the first command that fails fails the job.
- **The checks** are `CI / lint`, `CI / test (1.25)` and `CI / test (1.26)`:
  `<pipeline> / <job>`, with a matrix cell's values in brackets.

## Require the checks

In the branch rule for `main`, require `CI / lint`, `CI / test (1.25)` and
`CI / test (1.26)`. A pull request then cannot merge until each has
succeeded on its head commit.

- Require only checks that run on **every** pull request to that branch. A
  job with an `if:` that can be false, or a pipeline filtered by `paths:`,
  never reports on some pull requests, and they cannot merge. branchd names
  a required check that never reported as missing.
- Renaming the pipeline (`name:`) or a job renames its checks: change the
  rule in the same pull request.

## A newer push cancels the older run

When you push again to a pull request's branch, the newer run supersedes the
older one: the older run is cancelled, its running jobs stopped, and its
checks say `cancelled`, "superseded by run #N". Only the head commit's
checks count for merging. `concurrency: {cancel-in-progress: false}` at the
top of the file keeps older runs going instead. See
[Superseding](https://docs.branchd.run/branchd/pipelines/reference#superseding).

## Check it locally

```bash
branchd ci plan --event pull_request   # this branch as a pull request into the default branch
branchd ci lint                        # every situation and every event
```

Source: https://docs.branchd.run/branchd/pipelines/test-on-pull-request

---

# Trigger another repository's pipeline

> Start a run of a pipeline in another repository, at its own ref and with its own secrets, and optionally wait for its result.
> **Available** for repositories using branchd pipeline files. A trigger job starts a named pipeline in the target repository.

In the repository that starts it:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
# After a release on main, start the documentation site's build pipeline
# in acme/docs, and take its result as this job's.
name: CI
on:
  push:
    branches: [main]
jobs:
  build:
    image: golang:1.26
    steps:
      - run: go build ./...
  docs:
    needs: [build]
    trigger:
      repo: acme/docs
      pipeline: build
      ref: main
      inputs:
        product: notify
      wait: true
```

In the repository it starts, `acme/docs`:

```yaml title=".branchd/pipelines/build.yaml"
# .branchd/pipelines/build.yaml
# In acme/docs: may be started by any repository of the same company, with
# one input. It also runs on its own pushes to main.
name: build
on:
  push:
    branches: [main]
  trigger:
    from: company
    inputs:
      product:
        type: string
        default: all
jobs:
  site:
    image: node:24
    steps:
      - run: npm ci
      - run: npm run build -- --product "${{ inputs.product }}"
```

- **Which runs may trigger.** Only a push to, or a manual run of, a
  **protected branch**, by a person, an agent or the team's own bot. In any
  other run (a pull request's, an unprotected branch's, a scheduled or
  triggered run, a merge queue's commit) the trigger job fails at once and
  its log says why; the push check and `branchd ci plan` say so too. A
  triggered run never triggers again.
- **`trigger:`** in a job starts a run of `pipeline` (the name of
  `.branchd/pipelines/<pipeline>.yaml` there) in `repo`, at `ref` (a branch;
  empty is its default branch), with `inputs`. With `wait: true` the job
  takes that run's result; without it, the job does not wait for that
  result.
- **The target opts in** with `on: trigger`, and `from:` says who may start
  it: `organisation` (anyone in it), `company` (repositories of teams the
  same company owns), or a list of repository paths. `from:` is read from
  the target's default branch, whatever `ref:` names. A repository
  triggering its own pipeline must list itself. A caller it does not allow is
  refused, and the refusal says nothing about the other repository.
- **Limits.** A run may start at most 20 triggered runs, and a repository
  takes at most 120 triggered runs an hour.
- **It runs as the target.** The other run uses the target repository's
  secrets, runners and job token, at the target's ref. That is the opposite
  of a [reusable pipeline](https://docs.branchd.run/branchd/pipelines/reusable-pipelines), whose
  jobs join your run, at your commit, with your secrets.
- **A trigger job runs nothing here**, so it takes only `trigger`, `needs`,
  `if`, `matrix`, `environment`, `concurrency`, `manual` and
  `continue-on-error`.
- In the target, `event == 'trigger'` is true in a triggered run, and inputs
  the caller does not give read their defaults.

## Calling a repository during its GitLab migration

A repository can keep its ordinary builds and deployments on GitLab while
accepting a specific pipeline call on branchd. Ask a branchd operator to
enable inbound triggers for the target repository. Commit the target
pipeline to its default branch and to each branch callers select with
`ref`.

Give that pipeline a single event, `on.trigger`, and list its callers in
`from`. For example, to adapt the target above, remove its `push` event
and set `from: [acme/web]` if `acme/web` is the caller. The default
branch controls admission even when the caller requests another branch.
The caller can keep the same `repo`, `pipeline`, and `ref` when you move
the build to branchd.

Source: https://docs.branchd.run/branchd/pipelines/trigger-another-repository

---

# Troubleshooting

> Find out why a pipeline did not run, why a job was left out, or why a run failed.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

Start with `branchd ci plan` for the same ref and event: it says, for every
job, whether it runs and why, and it is what branchd computes for the run.

```bash
branchd ci plan --ref main                     # a push to main
branchd ci plan --ref feature/x --event pull_request
branchd ci plan --ref v1.2.0                   # a tag
```

## The push was refused

`remote: … pipeline files: refused` with `file:line:column: message` lines
means the push changed a pipeline file (or a step or `packages.yaml` it
uses) so that it no longer compiles, for an event its `on:` lists. Nothing
else about the push was wrong. Run `branchd ci lint`, fix each line it
prints, commit, and push again.

- A file that was already broken in the same way before your push is a
  warning, not a refusal; only what your push breaks is refused.
- A problem that depends on another repository (a step it uses that you
  cannot read, a tag that does not exist) is a warning at push and refuses
  the run instead.
- If you may bypass the branch's rules and must push it anyway:
  `git push -o ci.allow-invalid`. The push is recorded as bypassed.

## No run started

- **The file is refused.** `branchd ci lint` prints the refusal, with the file
  and line. See [Refusals](https://docs.branchd.run/branchd/pipelines/errors).
- **`on:` does not match.** The plan's note says which filter did not:
  `on: push: branch dev matches none of branches main`. `on: [push]` without
  `branches` matches every branch and tag.
- **`paths:` matched nothing.** A pipeline with `paths:` runs only when a
  changed path matches. A tag ignores `paths`; a new branch counts as
  everything changed.
- **The commit's message says `[skip ci]`** (or `[ci skip]`, `[no ci]`,
  `[skip actions]`, `[actions skip]`), or the push used `-o ci.skip`. The
  run is listed as cancelled with the reason Skipped; re-run it to start it.
  See [Skip a push's pipelines](https://docs.branchd.run/branchd/pipelines/skip-a-run).
- **The file ends in `.yml`**, or is not in `.branchd/pipelines/`.
- **The repository also has an older CI file**, which is refused.
- **The repository is not switched to pipeline files yet.** branchd then runs
  `.forge-ci.yaml` or `.xeonr-ci.yaml` and ignores `.branchd/pipelines/`.
- **A pull request's branch** has an open pull request: its pushes run as the
  pull request's runs, so `on: pull_request` is what matters, not `on: push`.

## A job did not run

- **Its `if:` was false.** The plan prints the expression and that it was
  false. Remember that `branch` is a pull request's source branch, and
  `''` for a tag.
- **A job it needs failed.** A job runs only when its needs succeeded, unless
  its `if:` has `always()`.
- **It is waiting for a person** (`manual:`). Release it on the run's page or
  with `branchd run release <run> <job>`.
- **It is waiting for a lock** (`concurrency:`) another run holds.

## A step failed

- `branchd run failure <run>` shows the failed job and the end of its log;
  `branchd run log <run> <job>` the whole log.
- **Something set in one step is missing in the next.** Steps share a shell
  unless a step has `env`, `working-directory`, `shell`, `timeout` or
  `continue-on-error`, which give it a subshell of its own. A `cd` or an
  `export` there does not reach the next step.
- **`${{ }}` came out empty or literal in a script.** It is a variable, and
  single quotes stop the shell expanding it: use double quotes.
- **A service is not ready.** Services start with the job and are not waited
  for: poll the port first, as in
  [Test a Go service with a database](https://docs.branchd.run/branchd/pipelines/test-go-with-database).
- **A secret is empty.** The job must list it in `secrets:`. A protected
  secret reaches only runs of a person's push to a protected branch or tag,
  or a person's manual run of a protected branch's head, never a pull
  request, a schedule or a re-run of an older commit. A company's secret
  reaches only repositories of the company's teams.
- **An artifact is missing.** The job must `need` the job that made it, without
  `artifacts: false`, and the path must be one that job listed.

## A pull request cannot merge

- A required check that the pull request's run never reports keeps it from
  merging. A pipeline filtered by `paths:`, or a job whose `if:` is false on
  pull requests, never reports. See
  [Required checks](https://docs.branchd.run/branchd/pipelines/several-pipelines#required-checks).
- Renaming a pipeline or a job renames its check: update the branch rule.

## The run was cancelled

A newer run of the same unprotected ref cancels an older one. To keep them
both, put `concurrency: {cancel-in-progress: false}` at the top of the file.

Source: https://docs.branchd.run/branchd/pipelines/troubleshooting

---

# Writing a preset

> What a preset program receives, what it returns, and the limits it runs under.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

> The preset SDK, `branchd.run/branchd/sdk/preset`, is MIT licensed and published from the public repository [`branchd/sdk`](https://branchd.run/branchd/sdk).

Start from [`branchd/template-preset`](https://branchd.run/branchd/template-preset):
a preset with its tests, a repository that uses it, golden files, and the CI
that builds and publishes it.

A preset is a Go program, compiled to WebAssembly (`wasip1`), that branchd
runs inside the compiler at every push. It is untrusted code, so it gets no
network, no environment, no arguments, a fixed clock and a read-only view of
the repository.

## What it receives

- **Its configuration**: the pipeline file's `preset.with`, decoded into the
  preset's own configuration type. An unknown key is refused, and the refusal
  lists the known ones. A refusal names a dotted path into `with:`, and the
  compiler shows it at that key's line.
- **The run's facts**: the event, branch, tag, ref and commit, the changed
  paths, the run number, the repository's path and default branch, whether
  the ref is protected, and a pull request's number and target.
- **The repository's files at the commit**, read-only: read a file, ask
  whether one exists, list files by glob.

## What it returns

- **Jobs** in the pipeline-file job form ([reference](https://docs.branchd.run/branchd/pipelines/reference#job-keys)),
  each at an address: the path of the configuration that produced it
  (`apps.api.build`). branchd adds `preset.`. An address is never another's
  prefix.
- **Default triggers**, which a file's own `on:` narrows.
- **Notes and warnings**, which `branchd ci plan` shows.

Return every job the configuration asks for and give each an `if:` for the
events it runs on, rather than leaving it out: a need on a job that does
not run then says why. Needs name the preset's own addresses, or the
repository's own jobs the configuration names (by convention a `needs:` key
on the entry).

## Describe mode

The same program answers a description request with its name, summary,
default triggers, the JSON Schema of its configuration, and its address
patterns and outputs. The documentation and the compiler's messages come
from it.

## Testing it

The SDK's `presettest` package has two levels:

- **In process**: `presettest.Expand` calls the preset as the compiler does
  and returns its jobs; `Refusal` returns the refusal of a configuration that
  must be refused; `Describe` the description. `PushFacts`, `TagFacts` and
  `PullRequestFacts` are the usual runs.

  ```go
  jobs := presettest.Expand(t, expand, presettest.Case{
  	Repo: "testdata/repos/app",
  	With: `{"binaries": ["./cmd/app"]}`,
  })
  ```

- **Through the compiler**: `presettest.Plan(t, presettest.PlanOptions{Repo:
  "testdata/repos/app", Presets: map[string]string{"acme/presets/go": "."}})`
  commits a real repository's files to a scratch repository and runs
  `branchd ci plan --json --offline` on it with your preset's source in place
  of the published module: the compiler branchd runs at a push, so the steps
  your jobs use are resolved and their inputs checked. `RequireOK` fails the
  test naming each refusal. Without the branchd CLI on `PATH` the test is
  skipped; set `PRESETTEST_REQUIRE_CLI=1` in CI.

`presettest.Golden(t, "testdata/golden/app.json", got)` compares jobs or a
plan with a file and rewrites it under `UPDATE_GOLDEN=1`.

## Publishing it

> **Rolling out**: a release run publishing the module (below) needs branchd's preset publishing, which is being deployed. Until it is live, a preset is published by committing the built module at `<path>/preset.wasm` (`GOOS=wasip1 GOARCH=wasm go build -trimpath -ldflags='-s -w' -o preset.wasm .`), as `branchd/presets` does.

The repository holds source only; a release run builds the module and
publishes it as the tag's version.

1. **List** the preset's directory in `.branchd/packages.yaml` on the default
   branch (`.` for a repository that is one preset). Users write
   `preset: {uses: <group>/<repo>[/<path>]@v1}`.
2. **Protect** the default branch and `v*` tags: only the repository's own
   run of a protected `vX.Y.Z` tag at its commit publishes.
3. **Add a release pipeline** on `v*` tags with
   `permissions: {packages: write}` whose job runs
   `go run branchd.run/branchd/sdk/cmd/publish preset <path>`. It builds the
   module (`wasip1`, `-trimpath -buildvcs=false -ldflags='-s -w -buildid='`,
   so the same source and Go give the same bytes), uploads it, and branchd
   checks the upload and records the version with the commit and the
   module's digest. A published version never changes, and every run records
   the digest it compiled with.
4. **Tag** `vX.Y.Z`. Users on `@v1` get the newest published `v1.x.y` when
   their next run is compiled; a tag with no published module is skipped.
   Keep each job's secrets, environments and runner labels stable within a
   major: a user's narrowing (`preset.secrets`, `allow`, `runs-on`) refuses a
   job past it.
5. **Set the visibility** to who may use it: company, organisation or
   public, on the repository (`branchd repo visibility`) or on a group of
   presets (`branchd group visibility`). A private repository's preset is
   usable by that repository alone, and a repository cannot use its own
   preset (`./<path>` is refused for now).

## Limits

| Limit                               | Value                                       |
| ----------------------------------- | ------------------------------------------- |
| Module size                         | 8 MiB                                       |
| Memory                              | 64 MiB of linear memory                     |
| Time                                | 5 seconds a call                            |
| Output                              | 1 MiB on stdout (64 KiB of stderr kept)     |
| Files                               | 1,000 different files a call, 1 MiB each    |
| Globs                               | 1,000 a call                                |
| Request (its `with:` and the facts) | 4 MiB                                       |
| A push                              | 8 presets, 15 seconds of module time in all |

A preset that fails, passes a limit, or returns jobs that do not check fails
the compile of that pipeline file only, with a message naming the preset
(`preset branchd/presets/service@v1: …`). The repository's other files
compile as usual.

## Getting it listed

A preset is listed in [Steps & presets](https://docs.branchd.run/branchd/pipelines/steps-and-presets)
when its directory has a `preset.yaml` and its release has published a
version, for whoever can read your repository's code. `preset.yaml`, beside
the preset's `main.go`, has three keys: `name` and `description` for the
listing (describe mode's `preset.Name` and `preset.Summary` win when set), and
`main`, the preset's Go main package (`.` for the directory itself).
[`branchd/template-preset`](https://branchd.run/branchd/template-preset) has
one to copy. Without it the preset still runs for anyone who may use it, but is not
listed. A version is listed as soon as its release publishes it. Its page shows
what describe mode answers: the `with:` schema, the jobs from
`preset.Address`, and the steps from `preset.Steps`. It also shows a
`README.md` beside `preset.yaml`. `branchd ci step lint` in the preset's
directory shows what the listing lacks.

Source: https://docs.branchd.run/branchd/pipelines/writing-a-preset

---

# Writing a step

> Publish a composite step or a typed step for other repositories to use.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## A composite step for others

A composite step needs no build. Put it in a directory of a repository, list
the directory in `.branchd/packages.yaml`, and tag a version.

```yaml title="xeonr/forge/steps: .branchd/packages.yaml"
# xeonr/forge/steps: .branchd/packages.yaml
# What other repositories may use from xeonr/forge/steps. It is read at the head
# of the default branch, never at the commit being used.
packages:
  - setup-buf
  - .branchd/pipelines/deploy.yaml
```

```yaml title="xeonr/forge/steps: setup-buf/step.yaml"
# xeonr/forge/steps: setup-buf/step.yaml
# Used from another repository as xeonr/forge/steps/setup-buf@v1.
name: Set up buf
description: Installs buf.
inputs:
  version: {type: string, default: '1.56.0'}
outputs:
  path: ${{ steps.install.outputs.path }}
steps:
  - id: install
    run: |
      curl -fsSLo /usr/local/bin/buf \
        "https://github.com/bufbuild/buf/releases/download/v${{ inputs.version }}/buf-$(uname -s)-$(uname -m)"
      chmod +x /usr/local/bin/buf
      echo "path=/usr/local/bin/buf" >> "$BRANCHD_OUTPUT"
```

1. **Lay it out.** One directory per step, holding `step.yaml`
   (`setup-buf/step.yaml`). The directory's path is the step's name in a
   reference: `xeonr/forge/steps/setup-buf@v1`. Its keys are those of a
   [composite step](https://docs.branchd.run/branchd/pipelines/composite-steps).
2. **List it** in `.branchd/packages.yaml` on the default branch. Pipeline
   files declaring `on: call` are listed by their path the same way.
3. **Tag it** `vX.Y.Z`. Consumers write `@v1` and get your newest `v1.x.y`
   when their next run is compiled, so a new tag reaches them without their
   changing anything. Break compatibility only in a new major.
4. **Set the repository's visibility** to who should use it: company or
   organisation for a shared step repository. A private repository's steps
   are usable by that repository alone.
5. **Test it** from a second repository with `branchd ci plan`, which reads a
   sibling checkout's tags and commits (never its working tree): commit and
   tag in the step repository's clone first.

Keep a published step honest about what it touches: it runs with the
caller's secrets and token, and callers read it before they use it.

## A typed step

A typed step is one program that branchd runs in its own image. It reads
typed inputs, writes typed outputs, can ask for a token for one Xeonr
product, and fails with an error or an exit code. It is written in Go on the
branchd SDK (`branchd.run/branchd/sdk`, MIT licensed, from the public
repository [`branchd/sdk`](https://branchd.run/branchd/sdk)), the same SDK
branchd's own steps are written on. Start from
[`branchd/template-step`](https://branchd.run/branchd/template-step): one
step, its tests and the CI that publishes it.

### Write it

Its directory holds the Go main package and a manifest version 2
`step.yaml`:

```yaml title="steps/hello/step.yaml"
# steps/hello/step.yaml
# A typed step (manifest v2): one program, built from the Go main package in
# this directory, run in its own image. Its registry name comes from the
# repository and directory, so the file names none.
manifest: 2
name: Hello
description: Greets someone and says how long the greeting was.
runs:
  main: .
  platforms: [linux/amd64, linux/arm64]
source: true
inputs:
  who:
    type: string
    default: world
    description: Who to greet.
outputs:
  length:
    type: int
    description: The greeting's length in bytes.
secrets:
  GREETING_TOKEN:
    optional: true
    description: Not needed to greet; shown here to declare a secret.
```

[Step and package files](https://docs.branchd.run/branchd/pipelines/step-files#stepyaml-a-typed-step)
lists every key. The file names no registry package: branchd names it from
your repository and the directory.

```go title="steps/hello/main.go"
package main

import (
	"context"

	"branchd.run/branchd/sdk/step"
)

type inputs struct {
	Name string `step:"name,required"`
}

func main() { step.Run(hello) }

func hello(ctx context.Context, s *step.Step, in inputs) error {
	s.Logf("hello %s", in.Name)
	return s.Output("greeting", "hello "+in.Name)
}
```

`go get branchd.run/branchd/sdk@latest` adds the SDK. A default is written in
`step.yaml` only: the build links it into the binary.

### Test it

- **In process**: `steptest.NewAttempt(t, inputs)` and `steptest.Run(a, fn)`
  run the step's function against fixtures (inputs, staged files, tokens)
  and return its outputs, log and error.
- **Every manifest**: `steptest.CheckManifests(t, ".", false)` loads each
  `step.yaml` as the release does, so a manifest the publish would refuse
  fails a pull request.
- **The built binary**: `branchd ci step run steps/hello --with name=Ada`
  builds it for your machine and runs it once in an environment like the
  sandbox's, with only the secrets you give (`--secret-env NAME`).

### Release it

1. **List** the directory in `.branchd/packages.yaml` on the default branch.
2. **Protect** the default branch and `v*` tags.
3. **Ask for a step grant** if it needs `network`, `privileged` or
   `host_runtime`, or takes secrets it does not declare
   (`accepts_any_secret`). An administrator of your repository's company
   grants `network` and `any_secret`; `privileged` and `host_runtime` are an
   instance administrator's. Publishing refuses a step that declares more
   than its repository's grant.
4. **Add a release pipeline** that runs on `v*` tags, with
   `permissions: {packages: write}`:

   ```yaml title=".branchd/pipelines/release.yaml"
   name: Release
   on:
     push:
       tags: ['v*']
   permissions: {packages: write}
   jobs:
     publish:
       image: golang:1.26.4
       steps:
         - run: go run branchd.run/branchd/sdk/cmd/publish step steps/hello
   ```

   For each directory, branchd reads `step.yaml` itself, at the tag, holds
   it to the grant, and gives a push login on the package registry; the
   step is built for its platforms and its image pushed, and branchd records
   the version with your repository and commit as its source. Only a
   protected `vX.Y.Z` tag at the run's commit publishes, once per version.
5. **Tag** `vX.Y.Z`, and use it from another repository as
   `<team>/<repo>/<dir>@v1`: `@v1` takes your newest published `v1.x.y`.

A step's grant and its secrets are its caller's to see: a job that lists
`secrets:` narrows what the step gets, and a required secret it leaves out
is refused at compile, naming it.

## Getting it listed

A published step is listed in [Steps & presets](https://docs.branchd.run/branchd/pipelines/steps-and-presets)
for whoever can read your repository's code, with no submission. Give it a
human `name:`, a `README.md` beside `step.yaml` with a `uses:` example, and a
description on every input and secret. `branchd ci step lint` shows what it
lacks.

Source: https://docs.branchd.run/branchd/pipelines/writing-a-step

---

# Terraform state

> Keep Terraform and OpenTofu state in a repository, through their http backend on registry.branchd.run, with locking, every version kept, and restore and force-unlock in the console.
A repository can hold Terraform and OpenTofu states. Each state has a name,
and lives at one URL on the packages host. That URL serves the state and its
lock:

```
https://registry.branchd.run/terraform/<repository>/<state>
```

- **`<repository>`** is the repository's full path, such as `acme/infra`.
- **`<state>`** is a name you choose: letters, digits and `.` `_` `-`,
  starting with a letter or digit, at most 200 characters. Use one state per
  stack and environment, such as `mysql-prod`.
- **Every write is kept as a version**, numbered from 1. The newest one is
  the current state.
- **A state holds secrets, so it is never public.** Reading one needs write
  access on the repository. It is encrypted at rest, and it is never handed
  out by a link.

## Set up the backend

```hcl
terraform {
  backend "http" {
    address        = "https://registry.branchd.run/terraform/acme/infra/mysql-prod"
    lock_address   = "https://registry.branchd.run/terraform/acme/infra/mysql-prod"
    unlock_address = "https://registry.branchd.run/terraform/acme/infra/mysql-prod"
    username       = "token"
  }
}
```

- **All three addresses are the same URL.** Keep the default methods: the
  URL answers `GET`, `POST`, `DELETE`, `LOCK` and `UNLOCK`.

- **The password is a token**, from `TF_HTTP_PASSWORD`, so it stays out of
  the file:

  ```sh
  export TF_HTTP_PASSWORD="$(branchd auth token)"   # or a personal API key
  tofu init
  ```

- **Set a username.** Its value is not read, but Terraform sends no password
  without one.

- **The first write creates the state.** There is nothing to create first.

To move an existing state in, change the backend block and run:

```sh
tofu init -migrate-state
```

Terraform copies the current state across as version 1. The old backend
keeps its copy until you delete it.

## Locking

Terraform locks the state for every `plan` and `apply`. A second run is
refused while it holds the lock, and Terraform prints who holds it and for
what:

```
Error acquiring the state lock
Lock Info:
  ID:        6f1c…
  Operation: OperationTypeApply
  Who:       ci@runner-4
```

A run that was killed can leave its lock behind. Release it with
`tofu force-unlock <ID>`, or with **Force unlock** on the state's page in
the console. Both need the maintain level. Only release a lock when you are
sure its run has stopped: two applies writing the same state at once can
lose resources from it.

## In a pipeline

The steps in [`branchd/steps/opentofu`](https://branchd.run/branchd/steps/opentofu)
run OpenTofu against a state of the repository, with the backend and the
job's token set up for you. The stack declares an empty backend:

```hcl
terraform {
  backend "http" {}
}
```

```yaml title=".branchd/pipelines/terraform.yaml"
# .branchd/pipelines/terraform.yaml
# Plans every pull request against the repository's Terraform state `prod`,
# and applies on pushes to main (a protected branch). The stack declares an
# empty `backend "http" {}`: the steps point it at
# https://registry.branchd.run/terraform/<repository>/prod and give it the
# job's token, which also reaches the states its terraform_remote_state
# blocks read where a CI grant lets it.
name: Terraform
on:
  push:
    branches: [main]
  pull_request:
permissions:
  terraform-state: write    # read only, on a pull request's run
  pull-requests: write      # for plan's comment on the pull request
jobs:
  plan:
    if: event == 'pull_request'
    steps:
      - uses: branchd/steps/opentofu/plan@v1
        with: {state: prod, working_directory: infra}
  apply:
    if: branch == 'main' && event == 'push'
    steps:
      - uses: branchd/steps/opentofu/apply@v1
        with: {state: prod, working_directory: infra}
```

- **`plan@v1`** runs `tofu init` and `tofu plan`, and outputs `has_changes`,
  `add`, `change` and `destroy`. On a pull request it comments the plan's
  summary there, and updates the comment on later runs. Without
  `pull-requests: write` it skips the comment and says so.
- **`apply@v1`** applies the plan of an earlier `plan` step in the same job,
  or plans and applies. It outputs the root outputs, sensitive ones left out.
- **`output@v1`** reads a state's non-sensitive outputs into step outputs,
  without OpenTofu or a checkout.
- **The token stays fresh.** A job token lives for minutes, so the steps
  pass OpenTofu a fresh one on every request, and a long apply still writes
  its state and releases its lock.

The job's `permissions:` decide what its token may do:

- **`read`** gets the state. **`write`** also writes it and takes its lock.
- **Writes need a protected ref**, as package writes do. On a pull request
  or an unprotected branch the token only reads, so `plan` there runs with
  `-lock=false`.

Without the steps, set the backend's password from the job's token
yourself:

```sh
export TF_HTTP_USERNAME=job TF_HTTP_PASSWORD="$BRANCHD_TOKEN"
tofu init -input=false && tofu apply -input=false -auto-approve
```

See [Job token](https://docs.branchd.run/branchd/pipelines/job-token#permissions) for every
permission.

## Another repository's state

A stack can read another stack's outputs with `terraform_remote_state`:

```hcl
data "terraform_remote_state" "network" {
  backend = "http"
  config = {
    address  = "https://registry.branchd.run/terraform/acme/network/prod"
    username = "token"
  }
}

resource "aws_instance" "app" {
  subnet_id = data.terraform_remote_state.network.outputs.subnet_id
}
```

- **The password comes from `TF_HTTP_PASSWORD`**, as for the backend: one
  token covers the stack's own state and every state it reads. Leave the
  password out of the block.
- **Always set `address`.** Without it, the block reads the stack's own
  state.
- **You need write access on the other repository** to read its state
  yourself, as for any state.

### Let another repository's jobs in

A job reads another repository's state only where that repository grants
it, with a CI grant on the Terraform state area. Make one on the
repository that holds the state, from its **Terraform** tab
(**Reached by**, then **Grant access**), from its settings (**Access**,
then **CI access**), or with the CLI:

```sh
branchd tfstate grant acme/network --to repo:acme/app --level outputs
```

| Level     | The other repository's jobs may                                                                                                                                               |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `outputs` | Read the state's root outputs, sensitive ones included, and nothing else. Its resources, and the secrets they hold, are left out. This is all `terraform_remote_state` needs. |
| `read`    | Read the whole state, every secret in it included.                                                                                                                            |
| `write`   | Also write the state and take its lock, on a protected run only.                                                                                                              |

- **The reading job also declares** `permissions: terraform-state: read` in
  its own pipeline file.
- **A grant can name** a repository, a group, a team or the company, and
  apply to any run, protected runs only, or as the run's owner, as
  [CI grants](https://docs.branchd.run/branchd/packages/access#another-repositorys-jobs) do
  for packages. A grant made on a group covers every repository under it.
- **No grant deletes a state.**
- **A refused read shows only "invalid auth"** in OpenTofu's output, because
  it does not print the answer's body. The full reason is in the run's
  audit, and `branchd repo grant explain acme/network --from acme/app`
  says which grant would apply.

## From the CLI

`branchd tfstate` (CLI 0.73 or later) works with a repository's states. Inside
a clone, `-R` can be left out.

| Command                                     | Does                                                                                     |
| ------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `branchd tfstate list`                      | Lists the states, with their newest version and lock                                     |
| `branchd tfstate show <state>`              | Shows a version's resources and outputs, never their values                              |
| `branchd tfstate versions <state>`          | Lists the versions, newest first                                                         |
| `eval "$(branchd tfstate env <state>)"`     | Sets the `TF_HTTP_*` variables, a fresh token included, for an empty `backend "http" {}` |
| `branchd tfstate backend <state>`           | Prints the backend block, or with `--remote <name>` a `terraform_remote_state` block     |
| `branchd tfstate pull <state>`              | Downloads a version's state file (it contains secrets)                                   |
| `branchd tfstate unlock <state>`            | Releases a held lock                                                                     |
| `branchd tfstate restore <state> <version>` | Makes an earlier version current again                                                   |
| `branchd tfstate grant <repo> --to <who>`   | Lets another repository's jobs reach the states, at `--level outputs`, `read` or `write` |

## Versions, restore and delete

The **Terraform** tab of a repository lists its states: each state's
current version, serial, resource count, who wrote it and when, and its
lock if one is held. A state's page shows:

- **its versions**, newest first, with the Terraform version and the caller
  that wrote each one: a person, an agent or a pipeline run;
- **a version's resources**, by module and type, and its outputs, with
  sensitive ones marked. Attribute and output values are never shown;
- **what changed since the version before**: resources added and removed,
  and instance counts that changed.

At the maintain level you can also:

- **download** a version's state file. It contains every secret the state
  holds;
- **restore** an earlier version. Its contents are written as a new version,
  so the history keeps every write. The next plan compares your
  infrastructure with the restored state, so it may plan to create again
  what was made after that version. Restore is refused while the state is
  locked;
- **delete** an earlier version. The newest cannot be deleted;
- **delete** the state with every version. Terraform then finds no state at
  that URL, and plans every resource as new.

Deleting cannot be undone.

## Access

| To                                           | Needs                                                            |
| -------------------------------------------- | ---------------------------------------------------------------- |
| Read a state (`terraform plan`, the console) | Write access on the repository, and `forge:terraform-state:read` |
| Write and lock it (`terraform apply`)        | Write access, and `forge:terraform-state:edit`                   |
| Download, restore, force-unlock or delete    | The maintain level, and `forge:terraform-state:admin`            |

A personal API key at the write level holds the first two scopes, and one at
the maintain level holds all three. See [Scopes](https://docs.branchd.run/branchd/access/scopes).

Source: https://docs.branchd.run/branchd/terraform-state
