> ## Documentation Index
> Fetch the complete documentation index at: https://bakefile.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> bakefile is a Python task runner with two CLIs: bake runs tasks from bakefile.py, bakefile manages the project. It is not a service or platform.
> Tasks are methods on Bakebook classes in bakefile.py, decorated with @command. Subprocesses run through self.ctx.run().
> Examples are backed by tests; copy them verbatim.

# Managed content

> Spaces keep shared config files identical across repos, while each repo keeps its own edits in editable blocks. Opt-in beta.

A Space can declare **managed files**: files it renders from a template that ships in its package, so every repo using that Space carries the same version. The repo edits only the **editable blocks** the template marks; bake owns the rest. `bake setup-dev` and `bake update` write managed files, `bake lint` reports **drift**, and `bake.lock` at the project root records which files bake wrote and which editable blocks the repo changed.

## Turning it on

Managed content is a beta and is off by default. Set `bake_manage_content` on your Bakebook in `bakefile.py`:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from bakelib import PythonSpace, ZervFlowGitHubActionsSpace


class MyBakebook(ZervFlowGitHubActionsSpace, PythonSpace):
    bake_manage_content: bool = True


bakebook = MyBakebook()
```

Or set the environment variable, which wins over the class default:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
BAKE_MANAGE_CONTENT=true bake mc sync --dry-run
```

With the toggle off, nothing is written or checked, no `bake.lock` is created and `setup-dev`, `update` and `lint` print nothing about managed content. `bake mc sync` and `bake mc lock` exit nonzero with a hint on how to turn it on.

## What each Space manages

| Space | Managed file |
| - | - |
| `BaseSpace` (all Spaces) | `oxfmt.config.ts` (the shared formatter style, with an editable `ignorePatterns` block), `.gitignore`, `.pre-commit-config.yaml` |
| `DvcSpace` | adds a `dvc-push` hook to `.pre-commit-config.yaml` |
| `GitHubActionsSpace` | nothing (workflow linting only) |
| `RenovateSpace` | `.github/renovate.json5` |
| `SecurityGitHubActionsSpace` | `.github/workflows/security.yml` (trivy and gitleaks) |
| `ZervFlowGitHubActionsSpace` | `.releaserc.mjs`, `.github/workflows/semantic-pull-request.yml`, `.github/workflows/ci.yml` and `.github/workflows/cd.yml` (zerv release), plus the reusable workflows your [zerv flow jobs](#the-zerv-flow) call; in ci and cd each section ends in an editable block for your own jobs |

In a managed workflow the `name`, job headers and steps are fixed. The triggers under `on:` are fixed in the pre-commit, publish, test and semantic-pull-request workflows, and one editable block named `events` in ci, cd and security. Each `runs-on` and `timeout-minutes` is an inline editable block, marked by a trailing `# (editable)`, and each pinned action is one too, marked by `# (editable) pin` on the line above its `uses:`, so a Renovate or `actions-up` pin bump and your own runner are kept. In the pre-commit, publish and semantic-pull-request workflows the job's steps end in an editable block for steps only your repo needs, under `# (editable) more steps below`. Each workflow ends with an editable block for jobs only your repo needs, under `# (editable) more jobs below`; ci and cd end each of their sections in one. The workflows grant only read access to their jobs and add write scopes per job where a job needs them, and each sets a `concurrency:` group (cd queues its runs instead of cancelling one mid-release). In the security workflow the triggers, schedule included, are one editable block, and so is the workflow's `permissions:` key with its scopes (`contents: read` by default; empty the block to use the repo's default token permissions, or write `permissions: read-all`). The trivy inputs end in an editable block for more inputs, and the gitleaks-action `env` in one for more variables, such as `GITLEAKS_LICENSE`, which gitleaks-action needs in a repo an organization owns. It also marks three [template hooks](#template-hooks) for company Spaces: `trivy_inputs` (more trivy-action inputs), `gitleaks_env_vars` (more gitleaks-action env) and `extra_jobs` (jobs above the trailing block).

bakelib ships Python workflow templates in `bakelib.spaces.github_actions`'s `managed/` folder: `test.yml` (the OS matrix and Python versions are inline editable blocks), `pre-commit.yml` (runs the pre-commit hooks and `bake lint --slow`) and `publish.yml` (runs `bake publish` with the called version, on the repository's `.python-version` unless the caller passes `python_version`). No Space writes them on its own: with the [zerv flow](#the-zerv-flow), a kind of flow lists them in `ZervFlowJobs.workflows`, next to the [zerv flow jobs](#the-zerv-flow) that call them. The two [shipped Python kinds](#the-zerv-flow) do, so a bakebook that picks one gets them.

They are then managed like any other file: locked in `bake.lock`, with the same editable blocks. An integration test job, if your repo has one, goes in the test workflow's trailing block.

`RustSpace` adds no job to the security workflow, because a cargo audit job needs pinned actions and a pin bake renders would fight Renovate. Add it in the last block of `.github/workflows/security.yml`, indented as a job under `jobs`:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
    # (editable) more jobs below
    cargo-audit:
        name: cargo-audit
        runs-on: ubuntu-24.04
        steps:
            - name: checkout
              uses: actions/checkout@<sha> # <version>

            - name: setup-mise
              uses: jdx/mise-action@<sha> # <version>

            - name: run-cargo-audit
              shell: bash
              run: cargo audit
```

### The zerv flow

`ZervFlowGitHubActionsSpace` writes the [zerv](https://github.com/wislertt/zerv) flow: `ci.yml` versions every pull request with zerv, `cd.yml` has semantic-release cut `vX.Y.Z` on main and zerv add the `vMAJOR` and `vMAJOR.MINOR` tags, `semantic-pull-request.yml` checks pull request titles, and `.releaserc.mjs` configures semantic-release. The ci and cd workflows fix their `permissions:` and `concurrency:`, hold their triggers in one editable block, and their jobs come in sections, always in this order:

| Section | Editable block | Shown |
| - | - | - |
| Versioning | `versioning` | by default |
| Checks | `checks` | with jobs, or when `shown` |
| Deployment with environment | `deploy_with_env` | with jobs, or when `shown` |
| Deployment without environment | `deploy_without_env` | with jobs, or when `shown` |
| Extra | `extra` | with jobs, or when `shown` |

Each section is a ruler banner with its title, its declared jobs as fixed text in list order, then `# (editable) more jobs below` and one editable block, empty by default, for the jobs only your repo needs. A shown section with no declared jobs is the banner, the marker and the block:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
    # ====================================================
    # Checks
    # ====================================================
    lint:
        # (editable) pin
        uses: my-org/workflows/.github/workflows/lint.yml@v1

    # (editable) more jobs below
    my-own-job:
        runs-on: ubuntu-24.04
        ...

    # ====================================================
    # Extra
    # ====================================================
    # (editable) more jobs below
```

**Triggers.** The body of `on:` in ci and in cd is one editable block named `events`, under `# (editable)`, so you change when a workflow runs without detaching the file. ci defaults to `pull_request` with the types `opened`, `synchronize` and `reopened`, and cd to `push` on `main` plus `workflow_dispatch`. Edit the block in the file and sync keeps your triggers. `permissions:` (`contents: read`) and `concurrency:` stay fixed text, so the flow's safety settings are the same in every repo; a job that needs more declares its own `permissions:`.

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
on:
    # (editable)
    push:
        branches:
            - main
    workflow_dispatch:

permissions:
    contents: read
```

A company Space changes the default for its repos with [`set_default()`](#changing-a-parents-template) on the file it gets from `super()._get_managed_files()`, here to give cd's manual run an input. The flow's sections still render in that file, and a repo that edited its block keeps its own triggers:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
CD = ".github/workflows/cd.yml"
CD_EVENTS = """\
    push:
        branches:
            - main
    workflow_dispatch:
        inputs:
            target:
                description: where to deploy
                type: choice
                options: [staging, production]
"""


class CompanySpace(ZervFlowGitHubActionsSpace):
    def _get_managed_files(self):
        files = super()._get_managed_files()
        files[CD] = files[CD].set_default("events", CD_EVENTS)
        return files
```

Write the text as it stands in the file, indented four spaces under `on:`.

**A kind of flow as one value.** A kind of flow (a Python library, a company service) is one `ZervFlowJobs` value that you read top to bottom, and a bakebook or a company Space picks it with one class attribute, `zerv_flow`. `ZervFlowJobs`, `ZervFlowWorkflow`, `ZervFlowSection` and `ZervFlowJob` are exported from `bakelib.spaces.github_actions`. `ci` and `cd` are each a `ZervFlowWorkflow` with one section per keyword (`versioning`, `checks`, `deploy_with_env`, `deploy_without_env`, `extra`), and `workflows` maps a project path to the `ManagedFile` of a reusable workflow your jobs call. Every part is optional, and a section is written as a plain list or tuple of jobs (or as a `ZervFlowSection` when you also set `shown`). A `ZervFlowJob` is a name and the job's YAML text, the body under the job's key, written at column 0; the flow writes the key and indents the body. A section renders its jobs in list order. The jobs refer to zerv directly, such as `needs: zerv-versioning` and `${{ fromJson(needs.zerv-versioning.outputs.versions).pep440 }}`.

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from bakelib import PythonLibSpace, ZervFlowGitHubActionsSpace
from bakelib.spaces.github_actions import ZERV_FLOW_PYTHON_LIB


class MyBakebook(ZervFlowGitHubActionsSpace, PythonLibSpace):
    bake_manage_content: bool = True
    zerv_flow = ZERV_FLOW_PYTHON_LIB
```

**Shipped kinds and jobs.** A Python repo picks one of two kinds bakelib ships and writes no job text. Both are exported from `bakelib.spaces.github_actions`, with the jobs they are built from and the reusable workflow files those jobs call:

| Kind | On top of `ZERV_FLOW_BASE` | `workflows` |
| - | - | - |
| `ZERV_FLOW_PYTHON` | `ZERV_TEST` and `ZERV_PRE_COMMIT` in Checks of ci and cd | `ZERV_PYTHON_WORKFLOWS` |
| `ZERV_FLOW_PYTHON_LIB` | the same, plus `ZERV_PUBLISH_PYPI` in Deployment without environment of cd | `ZERV_PYTHON_LIB_WORKFLOWS` |

| Job | Name | Calls |
| - | - | - |
| `ZERV_TEST` | `test` | `test.yml`, passing `SONAR_TOKEN` and `CODECOV_TOKEN`, which the workflow does not require |
| `ZERV_PRE_COMMIT` | `pre-commit` | `pre-commit.yml` |
| `ZERV_PUBLISH_PYPI` | `publish-pypi` | `publish.yml` with zerv's pep440 version and `registry: pypi`, passing `PYPI_API_TOKEN` |

* `ZERV_PYTHON_WORKFLOWS` holds `test.yml` and `pre-commit.yml`, and `ZERV_PYTHON_LIB_WORKFLOWS` adds `publish.yml`. Each is a dict of project path to `ManagedFile`, ready for `ZervFlowJobs(workflows=...)`.
* The kinds carry `PYTHON` because the three reusable workflows run `uv` and `bake`. Stack Spaces such as `PythonSpace` know nothing about GitHub or the flow: your bakebook composes the flow Space and its stack Space and picks the kind.
* The jobs call their reusable workflows by local path, so they have no pin and no pin block. They read repository secrets; to read them from an environment instead, take the job over in the section's block ("Taking a job over" below).
* Neither kind has a deployment gate or a test-PyPI job. Add the gate in the hook, as "Changes on top" below does, and write your job in the section's block.

**Your own kind.** Write a kind when no shipped one fits, in your bakebook or in a company library, from the exported jobs and your own:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from bakelib import ZervFlowGitHubActionsSpace
from bakelib.spaces.github_actions import (
    ZERV_CD_VERSIONING,
    ZERV_CHECK_DEPLOY_ENV_LABELS,
    ZERV_CI_VERSIONING,
    ZERV_PRE_COMMIT,
    ZERV_PYTHON_WORKFLOWS,
    ZERV_TEST,
    ZervFlowJob,
    ZervFlowJobs,
    ZervFlowWorkflow,
)

COMPANY_CHECKS = [ZERV_TEST, ZERV_PRE_COMMIT, ZervFlowJob("docs", DOCS_JOB)]


def deploy(target: str) -> ZervFlowJob:
    return ZervFlowJob(f"deploy-{target}", DEPLOY_JOB.replace("TARGET", target))


COMPANY_SERVICE = ZervFlowJobs(
    ci=ZervFlowWorkflow(
        versioning=ZERV_CI_VERSIONING,
        checks=COMPANY_CHECKS,
        deploy_with_env=[ZERV_CHECK_DEPLOY_ENV_LABELS, deploy("staging")],
    ),
    cd=ZervFlowWorkflow(
        versioning=ZERV_CD_VERSIONING,
        checks=COMPANY_CHECKS,
        deploy_with_env=[deploy("production")],
    ),
    workflows=ZERV_PYTHON_WORKFLOWS,
)


class CompanyServiceSpace(ZervFlowGitHubActionsSpace):
    zerv_flow = COMPANY_SERVICE
```

* **The default.** A bakebook that sets nothing gets `ZERV_FLOW_BASE`, also exported: the two default versioning sets, no other job and no reusable workflow. The shipped kinds cost nothing until you pick one.
* **Reusable workflows.** `workflows` lists the files your jobs call. Take bakelib's from `ZERV_PYTHON_WORKFLOWS` or `ZERV_PYTHON_LIB_WORKFLOWS`, and add your own with `{**ZERV_PYTHON_WORKFLOWS, ".github/workflows/docs.yml": ManagedFile(...)}`. A kind stores its own copy of the dict.
* **A kind states its versioning set.** A workflow written without `versioning=` has an empty Versioning section, so name the set, as above.
* **Shared pieces.** Kinds are built from job values and lists of jobs, such as `COMPANY_CHECKS` above, so two kinds reuse the same jobs. A job that needs arguments comes from a function that returns a `ZervFlowJob`, such as `deploy()` above, so the kind still reads as one value.
* **A company Space.** A company Space sets `zerv_flow` for every repo that composes it, and a repo's own `zerv_flow` wins over its Space's. The order of your bakebook's bases does not change the output.

**Changes on top.** For one more job or one dropped job, override `_get_zerv_flow_jobs()`, the one hook on `ZervFlowGitHubActionsSpace`, instead of writing a new kind. A shipped kind is changed like any other. Its default returns a deep copy of `zerv_flow`, so the value is yours to change and the shared kind stays as it was for every other bakebook. A subclass extends it through `super()`, the way `_get_managed_files()` composes, and the attribute and the hook work together in one class:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MyBakebook(ZervFlowGitHubActionsSpace, PythonLibSpace):
    bake_manage_content: bool = True
    zerv_flow = ZERV_FLOW_PYTHON_LIB

    def _get_zerv_flow_jobs(self) -> ZervFlowJobs:
        jobs = super()._get_zerv_flow_jobs()
        jobs.ci.checks.jobs.append(ZervFlowJob("docs", DOCS_JOB))
        # the gate a test-PyPI job written in ci's block needs
        jobs.ci.deploy_without_env.jobs.insert(0, ZERV_CHECK_DEPLOY_LABEL)
        jobs.ci.extra.shown = True
        return jobs
```

Every change to a section is ordinary list use: `append`, `insert`, `extend`, `del`, item assignment and `clear`. The one method a section adds is `index(name)`, the position of the job with that name, so a subclass places a job next to one of its parent's, replaces a job where it stands, or drops it:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
section = jobs.ci.checks
section.jobs.insert(0, ZervFlowJob("first", FIRST_JOB))
section.jobs.insert(section.index("pre-commit"), ZervFlowJob("docs", DOCS_JOB))
section.jobs[section.index("test")] = ZervFlowJob("test", OTHER_TEST_JOB)
del section.jobs[section.index("pre-commit")]
```

`index()` of a name the section does not hold fails, naming the section and the job, so you hear on the next sync when a parent renames or drops the job you anchor on. A `ZervFlowJob` is frozen: you replace a job, you do not change one in place. Assigning to a section (`jobs.ci.extra = [job]`, or a `ZervFlowSection`) stores a copy, as the constructor does, so change the section through `jobs.ci.extra` afterwards. The reusable workflows in `workflows` are written only by the flow, so a repo without it gets none; a path a Space already manages, such as `.github/workflows/ci.yml` or `.releaserc.mjs`, fails instead of replacing that file, whatever the order of your bakebook's bases. A Space may still change a declared reusable workflow (a default, an insert), but not put another template on its path.

A job name appears once per workflow. A name twice in one section's list fails, naming the section and the job, and the same name declared in two sections of one workflow fails, naming both sections. See "Job names" below for jobs you write in a block.

**Versioning sets.** Versioning is a section like the others, and its jobs are ordinary jobs. bakelib exports three sets from `bakelib.spaces.github_actions`, each a tuple of jobs in render order:

| Set | Jobs | Used by |
| - | - | - |
| `ZERV_CI_VERSIONING` | `check-pre-release`, `zerv-versioning`, `tag-pre-release` | ci's default |
| `ZERV_CI_VERSIONING_MINIMAL` | `zerv-versioning` | your choice |
| `ZERV_CD_VERSIONING` | `semantic-release`, `zerv-versioning`, `create-version-prefix-tags` | cd's default |

A kind names its set per workflow (`ZervFlowWorkflow(versioning=ZERV_CI_VERSIONING_MINIMAL)` for a repo without pre-releases). The ci default checks the `pre-release` label, versions with zerv on a schema that switches on that label, and tags the pre-release. The cd default has semantic-release cut the release, versions with zerv and pushes the version prefix tags. A set is a tuple, so it cannot be changed in place; in the hook, assign a copy or change the section's own list:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def _get_zerv_flow_jobs(self) -> ZervFlowJobs:
    jobs = super()._get_zerv_flow_jobs()
    # no pre-releases in this repo
    jobs.ci.versioning.jobs = list(ZERV_CI_VERSIONING_MINIMAL)
    # a company fallback schema, in the place of the default job
    section = jobs.cd.versioning
    section.jobs[section.index("zerv-versioning")] = ZervFlowJob("zerv-versioning", COMPANY_ZERV_VERSIONING_JOB)
    # one more versioning job in both workflows, as a monorepo needs
    for workflow in (jobs.ci, jobs.cd):
        workflow.versioning.jobs.append(ZervFlowJob("affected-projects", AFFECTED_PROJECTS_JOB))
    return jobs
```

The section is shown by default, also when a kind gives it a list or tuple, so `jobs.ci.versioning.jobs.clear()` leaves its banner and an empty block where you write your own versioning jobs. Versioning job names count like any other: the same name in another section of that workflow fails.

**Deployment gates.** A gate is a job that reads the pull request's labels once, so a ci deploy job only `needs` it instead of reading labels itself. bakelib exports two, each a single `ZervFlowJob` that carries its own name:

* `ZERV_CHECK_DEPLOY_ENV_LABELS` is `check-deploy-env-labels`, zerv's labels-with-prefix workflow on prefix `deploy-`. Its `labels` output holds the pull request's `deploy-*` labels, one per environment to deploy.
* `ZERV_CHECK_DEPLOY_LABEL` is `check-deploy-label`, zerv's label-and-branch workflow on the `deploy` label. A job runs on it with `if: ${{ needs.check-deploy-label.outputs.has_label == 'true' }}`. This label is separate from `pre-release`, so it works with `ZERV_CI_VERSIONING_MINIMAL` too.

The flow adds no gate on its own, in ci or in cd: whoever declares a ci deploy job puts the gate first in that section. A gate is an ordinary job, so you replace it at its `index()` to change its label, and its name counts like any other.

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
ci = ZervFlowWorkflow(
    versioning=ZERV_CI_VERSIONING,
    deploy_without_env=[ZERV_CHECK_DEPLOY_LABEL, ZervFlowJob("publish-test-pypi", PUBLISH_TEST_PYPI_JOB)],
)
```

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
    publish-test-pypi:
        if: ${{ needs.check-deploy-label.outputs.has_label == 'true' }}
        needs: [zerv-versioning, check-deploy-label]
        uses: $/.github/workflows/publish.yml
```

**Job text in YAML files.** Job text can live in a plain YAML file instead of a Python string, so it gets YAML highlighting and formatting. Write each job's key at column 0, alone on its line, with the body indented four spaces below it. `read_zerv_flow_jobs(path)`, exported from `bakelib.spaces.github_actions`, splits the file at those keys into a tuple of `ZervFlowJob` in file order; a file it cannot split (no job, a job with no body, or a line that is neither a job key nor an indented body line) fails with a message naming the file. Keep such a file next to your Space and outside any `managed/` folder, since it is not a template. bakelib's own sets and gates are read this way.

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
affected-projects:
    uses: my-org/workflows/.github/workflows/affected.yml@v1

zerv-versioning:
    needs: affected-projects
    uses: wislertt/zerv/.github/workflows/shared-zerv-versioning.yml@v1
```

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from pathlib import Path

from bakelib.spaces.github_actions import read_zerv_flow_jobs

COMPANY_CI_VERSIONING = read_zerv_flow_jobs(Path(__file__).parent / "zerv_flow_jobs" / "ci-versioning.yml")
```

**Hidden sections and `shown`.** A section with no jobs in a workflow is left out of that workflow's file, except Versioning, which is shown by default. Set `shown` on it, in a kind (`ZervFlowWorkflow(extra=ZervFlowSection(shown=True))`) or in the hook (`jobs.ci.extra.shown = True`), to get its banner and an empty block for your first job there; `ci` and `cd` are separate, so a section can show in one workflow only.

**One owner per job.** Every job in ci and cd has one owner:

* A **declared job** (from the kind or the hook) is fixed text. Sync rewrites it on every run, so a change to the job in its Space always reaches your repo. Editing it in the file is drift, like any edit outside an editable block.
* A job you write in a section's block, under `# (editable) more jobs below`, is yours. Sync keeps it and never touches it, and the declared jobs above it keep following their Spaces. A block is empty by default and holds only your own jobs, so adding one costs nothing.

**Pins.** In a declared job, each pinned `uses:` (`owner/repo[/path]@ref`, on a job or on a step) gets `# (editable) pin` on the line above, and everything after the `@` (the ref and its version comment) is an inline editable block. A Renovate or `actions-up` bump is kept in `bake.lock`, and the rest of the job still follows its Space. Any ref counts, a SHA, a tag or a branch. Only a `uses:` key of the job itself or of one of its steps counts: a line that looks like one deeper in the job, such as an input named `uses` or a line of a `run:` script, stays fixed. A quoted call (`uses: "owner/repo@ref"`, single or double quotes) gets a block too; its closing quote is after the `@`, so it is part of the block and of the pin `bake.lock` stores. A local path has no ref and stays fixed, and a line of job text that already holds a template tag is left as you wrote it. The block is named `pin_<job>_<owner>_<repo>` in lowercase, with every run of other characters as one `_` (`pin_zerv_versioning_wislertt_zerv`), and a second or third pinned call to the same repository in one job ends in `_2`, `_3`, or in the next free number when another call in that job already has the name (a repository named `<repo>-2`). The repository is in the name, so when a Space points a job at another repository your stored pin is dropped with a note instead of rendering a SHA from the old one. Two declared jobs that give the same block name (`a-b` and `a_b` calling one repository) fail, naming both jobs.

**Pin sources.** A pin block keeps a bump made in the rendered workflow, but the pin in job text you write yourself, in a YAML file or a Python string, is the default and nothing moves it. List where that job text is in `_get_action_pin_sources()`, a hook of `GitHubActionsSpace` that is empty by default and extended through `super()`. A path is a file, or a folder that is searched for `.yml`, `.yaml` and `.py` files, and a relative path starts at the project root. List the sources in the bakebook of the repo that holds them: for a company Space, that is the bakebook of the library's own repo, not of the repos that use it. `bake update` fails, in a dry run too, on a source that resolves outside the project directory or into an installed package (a `site-packages` folder), naming the path, so it never rewrites a library your repo only installs.

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from pathlib import Path

from bakelib import ZervFlowGitHubActionsSpace


class MyBakebook(ZervFlowGitHubActionsSpace):
    def _get_action_pin_sources(self) -> list[Path]:
        return [*super()._get_action_pin_sources(), Path("jobs"), Path("bakefile.py")]
```

`bake update` bumps the listed sources first, with the same minimum age it gives `actions-up` (3 days), and names each file it changed. It then runs `actions-up` on the workflows as before, and the sync at the end of the update renders the new defaults. Sources and workflows get the same bump in one run, so the rendered pin equals the new default and `bake.lock` stores no pin edit for the job. With nothing listed, `bake update` runs the same commands as before, and in a dry run it only names the sources it would bump. Only a pin written as `owner/repo[/path]@<40 character SHA> # <tag>` is bumped, with or without an inline editable block after the `@`, and with or without quotes around the call (`"owner/repo@<SHA>" # <tag>`). A bare tag (`@v4`), a branch and a local path are left as they are.

The bumper is exported as `bump_action_pins(paths, min_age_days)` from `bakelib.spaces.github_actions`, for a command of your own. It takes the same files and folders, needs `actions-up` on the `PATH`, and returns the files it changed.

**Taking a job over.** To own a declared job fully, drop it in the hook and write it in the section's block:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def _get_zerv_flow_jobs(self) -> ZervFlowJobs:
    jobs = super()._get_zerv_flow_jobs()
    section = jobs.ci.checks
    del section.jobs[section.index("lint")]
    section.shown = True
    return jobs
```

Set `shown` when the dropped job was the section's last, so the section and its block stay. From then on the job is yours and no Space changes it.

**Job names.** A job name appears once per workflow, and both ways to break that exit 2 with nothing written and name the two places. A name declared twice, in one section's list or in two sections of one workflow, fails when the Space builds its files, before anything is read or written. A job you wrote in a block that is named like a declared job, or like a job in another block of the same file, fails in the sync plan, and the message says to remove one of the two.

**Dropped content.** If a section whose block you edited stops rendering, for example because you remove `shown`, its content is dropped with a note, and git diff shows it. A stored pin of a job that is no longer declared is dropped the same way. Upgrading from the layout with one `jobs` block drops your edits to the `space_jobs` and `jobs` blocks too; move those jobs into the sections.

Every managed file starts with a header in its own comment syntax:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# managed by bakefile; edit only the parts marked "editable"
```

Each editable block carries a visible `(editable)` comment, so you can see where you may edit: on the line above a block on its own lines, at the end of the line for an inline `runs-on`, and as `# (editable) pin` on the line above a pinned `uses:`.

## Commands and exit codes

| Command | What it does with managed content |
| - | - |
| `bake setup-dev` | Locks, then writes managed files at the start of `BaseSpace`'s project step, before it cleans |
| `bake update` | Locks before any upgrade, then syncs with `--refresh` once tools and dependencies upgrade |
| `bake lint` | Relocks, then fails on drift, before oxfmt or any other formatter runs |
| `bake mc sync` | Locks, then writes managed files |
| `bake mc sync --dry-run` | Shows what would be written or deleted, writes nothing |
| `bake mc sync --force` | Overwrites files that no longer match their template (git diff shows what is dropped) |
| `bake mc sync --refresh` | Also fetches [values from the network](#values-from-the-network) again, from their latest upstream |
| `bake mc lock` | Rebuilds `bake.lock` from the files |

`mc` is a short alias for the `managed-content` command group (`bake managed-content sync` works too).

Exit codes: `0` clean, `1` drift (from `lint`: run `bake mc sync`), `2` error. An error leaves every file untouched: bake prints `nothing written` and writes nothing.

`bake update` writes from a fresh `bake` process, after applying [Migrations](https://bakefile.wisl.dev/bakelib/spaces.md#migrations), so the files use the templates the upgrade just installed. It keeps your `--chdir`, `--global`, `--file-name` and `--book-name` options.

Bake writes a file only when its content changes. A Windows checkout with CRLF line endings, a byte order mark or a missing final newline is not drift. Bake writes LF, no byte order mark and a final newline.

The steps run in `BaseSpace`'s `_setup_project()`, `update()` and `_lint_fast()`. A `bakefile.py` that overrides one of them without calling `super()` skips that part.

## `bake.lock`

Commit `bake.lock`. It is TOML, sorted by path:

```toml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version = 1
revision = 1

[managed-content.".github/renovate.json5"]
template = "bakelib.spaces.misc:renovate.json5"
hash = "sha256:<64 hex>"
editable.rules = "    automerge: true,\n"
```

`template` names the template exactly as the code declares it: `<package>:<name>` for a template from a package, `repo:<path>` for [your own](#your-own-files). `hash` is the file's content as bake last locked or wrote it, and `editable.<name>` holds each editable block you changed from its template default. A block equal to its default is left out, so it follows the default when the template changes.

The lock catches up on its own: every command that writes relocks first, and `bake lint` (so the pre-commit hook) relocks too. Renovate needs no config for it, and CI tolerates a stale lock. A conflicted, missing or hand-edited lock is fixed with `bake mc lock`. A lock that does not parse makes every other command exit 2 with that hint.

## Editable blocks

Your content inside an editable block survives template upgrades:

* A block you changed keeps your content.
* A block you never touched follows the template's new default (for example a pinned tool version).
* A block you emptied stays empty.
* A Renovate or `actions-up` bump inside a block is kept on the next `setup-dev`, `lint` or `update`.
* A block the template no longer has is dropped with a note; a renamed block starts from its default. Git diff shows the dropped content.

An edit outside editable blocks is drift. `sync` names the file and the first line out of place:

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
✗ oxfmt.config.ts: expected '    semi: false,', but line 3 is '    semi: true,'; run `bake mc sync --force` to overwrite it (git diff shows what is dropped), or to keep it as is, call `.detach()` on its entry in `_get_managed_files()` in bakefile.py
```

When a template changes and the file has edits the lock does not know about yet, `sync` exits 2 instead of guessing. Reinstall the previous version of the package the hint names and run `bake mc lock`, or run `bake mc sync --force` and review the diff. An upgrade always works when the lock was current, so you do not need `bake update` for it.

## Files without the header

A file at a managed path without the header (a hand `oxfmt.config.ts`, `renovate.json5`, `.releaserc.mjs` or workflow) is taken over with a note when it already equals what bake would write apart from the header. A template with editable blocks also writes its `(editable)` marker lines, so in practice this covers whole fixed files such as `.releaserc.mjs`.

Any other headerless file, a hand `.gitignore` included, stops sync: it exits 2 with nothing written, whatever the file type. Run `bake mc sync --force` once to write the template with default editable blocks; your old content stays in git history, so review the diff and move what you still need back into the editable blocks. For a `.gitignore`, that is the block under `# (editable)` at the end of the file, and a section you pasted from toptal is replaced by listing the templates you need in `_get_gitignore_templates()`. To keep your own file instead, such as a company workflow the template does not fit, [detach it](#detaching-a-file).

Lines another tool appends to a managed `.gitignore` later land in its trailing editable block, which is not drift.

A file bake wrote that no Space produces any more is deleted with its lock entry, as long as it still matches the hash in `bake.lock`. If you changed it since bake last wrote or locked it, sync keeps it as it is with a one-line note and drops its lock entry, so it becomes a hand file; `--force` does not change this, and `--dry-run` lists only the files it would delete. A file you later recreate at that path is not in the lock, so bake leaves it alone.

## Changing what a Space manages

Managed files come from the `_get_managed_files()` hook, a dict from project path to a `ManagedFile`. Spaces compose it with `super()`, and the most-derived Space on the MRO wins a path.

Drop a file (bake deletes it on the next sync):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MyBakebook(ZervFlowGitHubActionsSpace, PythonSpace):
    bake_manage_content: bool = True

    def _get_managed_files(self):
        files = super()._get_managed_files()
        del files[".github/workflows/semantic-pull-request.yml"]
        return files
```

A `.gitignore` has three parts: the stack section from github/gitignore, the lines from your bakebook's Spaces, then one editable block, under `# (editable)`.

The Space lines come from the `_get_gitignore_lines()` hook, a set of patterns. `BaseSpace` has `.env*`, `*.local.md`, `*.local.toml`, `.claude/settings.local.json`, `.claude/worktrees/`, `.playwright-mcp/`, `.scratch` and the ssh key patterns; `RustSpace` adds `rust-project.json`. Add or remove lines with `super()`:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class NodeSpace(BaseSpace):
    def _get_gitignore_lines(self) -> set[str]:
        return super()._get_gitignore_lines() - {".scratch"} | {"node_modules/"}
```

Bake writes them sorted, with `!` lines last so they re-include what the lines before them ignore. They are a [bakefile value](#bakefile-values): bake rewrites them on every write, so put your own rules in the editable block at the end instead.

The `.gitignore` starts with a generated stack section, built from [github/gitignore](https://github.com/github/gitignore) templates. `_get_gitignore_templates()` lists their paths: `BaseSpace` has `Global/macOS`, `Global/Windows`, `Global/VisualStudioCode` and `Python` (every repo runs `bakefile.py`, which leaves `__pycache__/` behind), and `RustSpace` adds `Rust`. If a `Python` pattern such as `lib/` or `build/` ignores your own files, re-include the path with a `!` line in the editable block at the end, or drop the template with `super()._get_gitignore_templates() - {"Python"}`. Add or remove templates with `super()`; the order you compose them in does not change the file:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MyBakebook(PythonSpace):
    def _get_gitignore_templates(self) -> set[str]:
        return super()._get_gitignore_templates() - {"Global/Windows"} | {"Node"}
```

Bake fetches the templates from GitHub when the section has to change, and the committed `.gitignore` keeps them:

| When | Command | Stack section | Network |
| - | - | - | - |
| First time | `bake setup-dev` or `bake mc sync` | fetched from the latest `main` | yes |
| Normal work | `bake lint`, `bake setup-dev`, `bake mc sync` | kept as committed | no |
| Template list changed | next `bake mc sync` or `bake setup-dev` | fetched at the section's commit | yes |
| Template list changed or section edited | `bake lint` | drift, run `bake mc sync` | no |
| Pick up upstream fixes | `bake update` or `bake mc sync --refresh` | fetched from the latest `main` | yes |

The section's first lines name the github/gitignore commit and the templates, and say to override `_get_gitignore_templates()` in `bakefile.py` to change them; its last line holds a digest of the whole section, so a hand edit anywhere in it, those first lines included, is drift and sync puts the upstream text back. A template github/gitignore does not have, or a failed download, exits 2 with nothing written; if the template was added upstream after the section's commit, run `bake mc sync --refresh`. Bake reads the section only from above the editable block. The section is a [value from the network](#values-from-the-network).

The `.pre-commit-config.yaml` runs the [pre-commit-hooks](https://github.com/pre-commit/pre-commit-hooks) checks (trailing-whitespace, end-of-file-fixer, check-yaml, check-added-large-files), [gitleaks](https://github.com/gitleaks/gitleaks), and a local `lint` hook running `bake lint`. Each `rev` is an inline editable block, so a Renovate or `pre-commit autoupdate` bump is kept, and so is the `--maxkb` limit. Options for check-yaml, such as an `exclude:` pattern, go in the editable block under `# (editable) check-yaml options`. The file ends in an editable block under `# (editable) repo hooks, or more repos below`: write more local hooks there at the indentation of the `lint` hook, or more `- repo:` entries at the indentation of the others. `bake setup-dev` runs `pre-commit install` whether managed content is on or off.

Spaces add local hooks after `lint` through the `_get_pre_commit_hooks()` hook, a dict from hook id to the hook's YAML list item, the way they add gitignore templates. `DvcSpace` adds `dvc-push`, which runs `bake dvc push` at the pre-push stage. Bake writes the hooks sorted by id, so the order you compose Spaces in does not change the file, and each is an editable block named `hook_<id>` (dashes become underscores) under `# (editable) <id> hook`, so your edits to it are kept:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class TypecheckSpace(BaseSpace):
    def _get_pre_commit_hooks(self) -> dict[str, str]:
        hook = "- id: typecheck\n  name: typecheck\n  entry: bake typecheck\n  language: system\n  pass_filenames: false\n"
        return {**super()._get_pre_commit_hooks(), "typecheck": hook}
```

Drop a Space's hook by removing its id from `super()._get_pre_commit_hooks()`.

To replace a parent's file whole, map its path to your own `ManagedFile`. You then stop getting the parent's upgrades for that file.

### Your own files

A plain `bakefile.py` with no package of its own manages its own files with `ManagedFile.from_text()`. Give it the template text, inline or read from a file anywhere in the repo:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from pathlib import Path

from bakelib import BaseSpace
from bakelib.managed_content import ManagedFile

TEMPLATES = Path(__file__).parent / "templates"


class MyBakebook(BaseSpace):
    bake_manage_content: bool = True

    def _get_managed_files(self):
        return {
            **super()._get_managed_files(),
            "_typos.toml": ManagedFile.from_text('[files]\nextend-exclude = ["*.lock"]\n'),
            "docs/NOTES.md": ManagedFile.from_text((TEMPLATES / "notes.md").read_text()),
        }
```

The text is a template like any other: it may have editable blocks, bakefile values and template hooks. `bake.lock` names it `repo:<path>` (`repo:docs/NOTES.md`). Resolve the file against `Path(__file__).parent`, so it is found whatever directory bake runs from.

### Changing a parent's template

A child Space shapes a parent's template without forking it: it takes the `ManagedFile` from `super()._get_managed_files()` and returns a changed copy. Changes apply in MRO order, so each Space builds on the Spaces it inherits from. Two methods each return a new `ManagedFile`:

* `insert(hook, text)` adds text at a [template hook](#template-hooks) the parent marked. The text lands just above the hook's marker, so several inserts at one hook land in MRO order, each after those of the Spaces it builds on. Write the text at column 0: bake indents it to the hook's column, as it does a bakefile value.
* `set_default(block, text)` replaces the default of an editable block. An inline block takes one line. A block that holds a template hook cannot take a new default, only inserts at its hook, so one child cannot wipe out what another inserted.

Take a parent `PlatformSpace` whose `ci.yml` template marks a hook and an inline block:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
jobs:
    build:
        runs-on: {% editable build_runs_on %}ubuntu-24.04{% endeditable %} # (editable)
        steps:
            - run: make build

    {% hook extra_jobs %}
    # (editable) more jobs below
{% editable jobs %}
{% endeditable %}
```

A company Space runs builds on its own runners and adds an audit job:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
CI = ".github/workflows/ci.yml"

AUDIT_JOB = """\
audit:
    runs-on: {% editable audit_runs_on %}ubuntu-24.04{% endeditable %} # (editable)
    steps:
        - run: make audit

"""


class CompanySpace(PlatformSpace):
    audit_job: bool = True

    def _get_managed_files(self):
        files = super()._get_managed_files()
        files[CI] = files[CI].set_default("build_runs_on", "[self-hosted, linux]")
        if self.audit_job:
            files[CI] = files[CI].insert("extra_jobs", AUDIT_JOB)
        return files
```

What a child inserts becomes part of the template: its editable blocks are locked in `bake.lock` and kept across syncs and upgrades like the parent's, so a repo can edit the inserted job and a Renovate bump inside it survives. Template hooks inside the inserted text work like the parent's, so a grandchild can insert there in turn.

Every mistake raises `ManagedContentError` at the child's own call, with the template key in the message: an unknown template hook or block, a block name the template already has, a new default on a block that holds a template hook, or a multi-line default for an inline block. A command reports it as exit 2 with nothing written, so it fails in the Space's own CI.

To let a repo opt out of an insert, offer a switch, as `audit_job` above; there is no removal by name. There is no way to change a template's fixed text by matching it: that text is not part of the template's contract, so the parent may reword it in any release. A child that needs a change there asks the template's owner for a hook or an editable block.

### Detaching a file

When a repo must own text outside the editable blocks, detach the file in its own bakebook: return its entry from `_get_managed_files()` with `.detach()`.

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MyBakebook(SecurityGitHubActionsSpace, PythonSpace):
    bake_manage_content: bool = True

    def _get_managed_files(self):
        files = super()._get_managed_files()
        files[".github/workflows/security.yml"] = files[".github/workflows/security.yml"].detach()
        return files
```

Bake then leaves the file as it is, header included: `sync`, `setup-dev`, `update` and `lint` neither load its template, write, check nor delete it, and a detached path with no file gets nothing written. The first command after you detach drops the file's `bake.lock` entry with a one-line note; later runs say nothing about it. A detached `.gitignore` is never fetched for. The detach lives in code, not in `bake.lock`, so it shows in review.

When a repo needs different fixed text, ask the template's owner for a template hook or an editable block, then use `insert()` or `set_default()`, or edit the block in the file. Detach the file meanwhile, and re-attach once the release that adds the hook or block is out. Detach for good when the file has diverged too far, such as several paragraphs of a markdown file.

To re-attach, remove the `.detach()` call. A file whose header and fixed text still match its template is read on the next sync: its editable blocks are kept and it is locked again. Otherwise sync exits 2 with the `--force` hint; `bake mc sync --force` writes the template with default editable blocks, and git diff shows what it dropped.

## Authoring templates

A Space declares a managed file by package and template name:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from bakelib import BaseSpace
from bakelib.managed_content import ManagedFile


class CompanySpace(BaseSpace):
    team: str = "data-platform"

    def _get_managed_files(self):
        return {
            **super()._get_managed_files(),
            ".github/pull_request_template.md": ManagedFile(
                __package__, "pull_request_template.md"
            ),
        }

    def _get_managed_values(self, fetch):
        return {**super()._get_managed_values(fetch), "team": self.team}
```

The template lives at `<package>/managed/<name>` and is read through `importlib.resources`, so ship the `managed/` folder as package data. Bake reads the editable block and bakefile value names from the template text; give each value's text in `_get_managed_values()`.

`bake.lock` names the template `<package>:<name>` exactly as declared (`bakelib.spaces.github_actions:ci.yml`), so the lock is the same on every machine. When a file drifted and its template changed too, the hint looks up which distribution ships the package and names it.

A template may also be a Python string: `ManagedFile.from_text(CI_TEMPLATE, package=__package__, name="ci.yml")`. It renders exactly like the same text in a file, and its key in `bake.lock` is still `<package>:<name>`. Give both `package` and `name` or neither; with neither, the template is [the repo's own](#your-own-files). Files are the norm for a parent template, since the editor checks them and a review shows the output's shape; strings suit the small snippets a child inserts. Keep such strings in Python modules next to the templates in `managed/`; `TemplateSuite` does not count them as templates.

Bake adds the header; the template starts with the file's first real line. The path's file type picks the comment syntax:

| File type | Header |
| - | - |
| `.yaml`, `.yml`, `.toml`, `.py`, `.sh`, `.gitignore` and other `.*ignore` | `# managed by bakefile; edit only the parts marked "editable"` |
| `.ts`, `.js`, `.mjs`, `.cjs`, `.json5`, `.jsonc` | `// managed by bakefile; edit only the parts marked "editable"` |
| `.md` | `<!-- managed by bakefile; edit only the parts marked "editable" -->` and a blank line |

Plain `.json` (no comments) and any other file type fail when the template loads. Shebang files are not supported yet.

### Template grammar

**Editable block**, on its own lines (multi-line, may be empty):

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# (editable) jobs
{% editable jobs %}
jobs:
    - build
{% endeditable %}
```

**Inline editable block**, within one line (single line):

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
version: {% editable version %}1.0{% endeditable %}
```

The closing tag may repeat the name: `{% endeditable jobs %}`. Rendered files contain no tags, so write the visible `(editable)` comment yourself.

#### Template hooks

`{% hook <name> %}` on its own line marks a place where child Spaces [insert text](#changing-a-parents-template). It renders to nothing, and its indentation sets the column inserted text is indented to. A hook may sit inside an editable block, so a repo can still edit around what children insert. Each hook name appears once per template; a repeated one fails at load. Hooks are optional: a template without them can still be changed through `set_default()`.

Put content with pinned actions (`uses: owner/repo@<sha>`) behind a hook rather than in a bakefile value: bake rewrites values on every write, so a Renovate bump inside one would be reverted, while an inserted pin in an inline editable block is kept.

#### Bakefile values

`{{ bakefile.<name> }}` is filled with text the Space gives. `_get_managed_values()` returns one mapping from name to text for all the Space's templates:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
name: {{ bakefile.project_name }}
jobs:
    # jobs from Spaces
    {{ bakefile.extra_jobs }}
    # end of jobs from Spaces
```

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def _get_managed_values(self, fetch: Fetch) -> dict[str, str]:
    return {
        **super()._get_managed_values(fetch),
        "project_name": self.project_name,
        "extra_jobs": self._get_extra_jobs(),
    }
```

A value is plain text: read a setting, or call a hook that child Spaces extend with `super()`. Child Spaces add values the same way, with `{**super()._get_managed_values(fetch), ...}`.

A bakefile value matches anything when bake reads the file and is never stored in `bake.lock`. When the value changes, the next sync rewrites it with a note; a hand edit inside it is not kept, and `lint` reports it as drift. An empty string removes the value's lines and leaves the fixed text around it.

A value with more than one line must sit alone on its line. Give it at column 0 in the shared style, and bake indents every line to the tag's column. An editable block's default may contain a value; an untouched block then follows the value, as long as `bake.lock` is current when the value changes.

#### Values from the network

`_get_managed_values(fetch)` takes one argument, which says whether the running command may use the network:

| Command | `fetch` | Meaning |
| - | - | - |
| `bake lint`, `bake mc lock` | `Fetch.NEVER` | Stay offline |
| `bake mc sync`, `bake setup-dev` | `Fetch.WHEN_NEEDED` | Fetch only if the text in the file is no longer valid |
| `bake mc sync --refresh`, `bake update` | `Fetch.REFRESH` | Fetch again, from the latest upstream |

Most values ignore it. A value whose text comes from the network reads the committed file as its cache and fetches only when `fetch` allows it:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from pathlib import Path

from bakelib.utils import Fetch


def _get_managed_values(self, fetch: Fetch) -> dict[str, str]:
    return {**super()._get_managed_values(fetch), "license": self._license_text(fetch)}


def _license_text(self, fetch: Fetch) -> str:
    notice = Path("NOTICE.md")
    kept = _license_in(notice.read_text()) if notice.exists() else None
    if kept is not None and fetch is not Fetch.REFRESH:
        return kept
    if fetch is Fetch.NEVER:
        return "license text not fetched yet; run `bake mc sync`\n"
    return _download_license()
```

Under `Fetch.NEVER`, return text that differs from the file when the committed text is not valid, so `bake lint` reports drift; lint writes nothing, so that text never reaches the file. Raise `ManagedContentError` when a fetch fails: sync exits 2 with your message and writes nothing. `bake mc sync --dry-run` fetches too, so it shows the real change.

**Raw**: `{% raw %}...{% endraw %}` passes its text through untouched, for tag-like text such as `{{ bakefile.x }}` in a doc. GitHub Actions expressions like `${{ github.sha }}` need no escaping.

Bake fails at load, before writing anything, on a malformed or near-miss tag (`{%editable x %}`, `{{bakefile.x}}`, a hook not alone on its line), an unclosed block, two blocks or two template hooks with one name, or a value the template uses that `_get_managed_values()` does not give as text.

### Rules for templates

* **Fixed text on both sides.** An editable block or bakefile value needs fixed text between it and the next one, or bake cannot tell where one ends. An empty bakefile value therefore leaves its banner comment in every repo.
* **Hand content goes only in editable blocks.** Use inline blocks only in short single-line spots.
* **Write in the shared oxfmt style.** Bake never runs a formatter. Templates follow `BaseSpace`'s managed `oxfmt.config.ts`, so `bake lint` and format-on-save leave the files alone. A repo that formats managed files differently sees drift; per-repo style is not supported.
* **Formatters that reorder lines** (`toml-sort`, `taplo reorder_keys`, isort) need a whole sorted group in one editable block, or an editable block above every fixed table.
* **Start clean under common linters.** Report-only linters (actionlint, yamllint, markdownlint, zizmor) cause no drift but can flag template output; fixers that rewrite fixed text cause drift.
* **Exclude `managed/` from your own formatter**, so it does not reformat template sources that contain tags: add `"**/managed/"` to the `ignorePatterns` editable block in `oxfmt.config.ts`.
* **Do not name a template after a tool's config file** (such as `oxfmt.config.ts`): the tool reads it as a nested config for `managed/`. `BaseSpace` ships its oxfmt template as `oxfmt-config.ts`.

### Testing templates

`bakelib.managed_content.testing.TemplateSuite` renders every combination your Spaces produce into an empty project: each template as its declaring Space writes it, and each child Space's changed version as that child writes it (expected file `<template>@<Space>.expected`), so a child's inserts are checked like a parent's template. It checks each against an expected file, runs `oxfmt --check` with the shared config, rejects trailing whitespace, reads it back to exactly its defaults and checks a second sync changes nothing. It also compares each template's editable block names with a snapshot next to its expected file: block names are the keys in `bake.lock`, so renaming a block drops every repo's edits to it, and the snapshot makes a rename fail until it is accepted in review. Copy `tests/unit/bakelib/managed_content/test_templates.py` from the bakefile repo and point it at your packages and expected folder. A template in a `managed/` folder that no Space writes fails the suite; list one you ship on purpose for later in `unused=["<package>/managed/<name>"]`. A Space that checks class attributes when it is constructed, as `DvcSpace` checks its remote, gets them through `space_attrs={DvcSpace: {"dvc_remote_name": "origin", "dvc_remote_url": "s3://bucket"}}`, which applies to that Space and its subclasses. A template that no bakelib Space writes on its own, or only a combination of Spaces writes, needs a Space that writes it: define it in the test module and pass it in `spaces=[...]`, as `test_templates.py` does for the reusable Python workflows, through two test Spaces that each pick a shipped Python kind with `zerv_flow`. Job text a Space reads from a YAML file outside `managed/`, as the zerv flow's versioning sets and gates are, is not a template and needs no expected file of its own; render each variant through a test Space that declares it, as `test_templates.py` does for `ZERV_CI_VERSIONING_MINIMAL`, the two gates and the Python jobs.

The suite keeps the `.gitignore` stack section offline: it renders each github/gitignore template as one line naming it, unless you pass `gitignore_upstream`, an `Upstream` that returns the template text, for example from a snapshot kept next to the tests. If your Spaces add their own values from the network, give the upstream a hook on the Space and stub it in your tests.


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