---
title: "Contracts"
description: "Check your project against rules written in Atoll — its declarations, its files and its git history — and see a broken rule at the line that broke it."
---

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

# Contracts

A **contract** is a check written in Atoll that sees your checked program and
the project around it: its files, its manifest and its git history. It reports
diagnostics with a file and a line, and it emits no code. It is what a CI shell
script does today — "every migration has a way back", "the changelog changed
with the API" — moved to where a mistake is shown at the line that made it, by
the same `atoll check` that found the type error.

A script and a contract differ in what they cannot do. A contract is read-only
and sandboxed: it reads only the files the manifest grants it, it cannot run a
program, write a file or reach the network, and its answer is a function of the
files it read, so the same commit gives the same findings on every machine.

## A contract on a declaration

A contract is a `pub` or private function marked `@contract`. Its first
parameter says what it checks — here a function, `meta.Fn` — and its second is
where it reports.

```atoll project=rules file=policy/policy.at
import meta
import project

/// Every public function has a doc comment.
@contract
pub fn documented(target meta.Fn, out &mut meta.Report) void ! meta.Error {
    if target.is_pub() && target.doc().text() == "" {
        out.fail(target.span(), "`${target.name()}` has no doc comment")
    }
}

/// The project keeps a changelog.
@contract
pub fn has_changelog(p meta.Project, out &mut meta.Report) void ! meta.Error {
    if !project.exists("CHANGELOG.md")? {
        out.fail(project.manifest().span(), "the project has no CHANGELOG.md")
    }
}
```

A contract whose first parameter is a view of a declaration — `meta.Fn`,
`meta.Struct`, `meta.Enum`, `meta.Trait`, `meta.Impl`, `meta.Field`,
`meta.Variant` or `meta.Decl` — is **attached**: it runs at each place it is
written, as a decorator does. Written on a function that has no doc comment,
this one fails the check at the function's name:

```atoll project=service file=main.at refused=example.dev/rules/policy.documented
import example.dev/rules/policy

@policy.documented
pub fn total(prices []int) int {
    mut sum := 0
    for p in prices {
        sum = sum + p
    }
    return sum
}

fn main() void {
    println("${total([120, 80])}")
}
```

```text output
error[example.dev/rules/policy.documented]: `total` has no doc comment at main.at:4:8
  label: reported by `@policy.documented`, applied here in main.at
contracts: 3 contracts, 1 error
1 error(s) found
```

The finding's code is the contract's path — its module and its name — so a
finding says whose rule it is. With the comment written, the check passes and
says how many contracts ran:

```atoll project=service file=main.at
import example.dev/rules/policy

/// The total of an order, in cents.
@policy.documented
pub fn total(prices []int) int {
    mut sum := 0
    for p in prices {
        sum = sum + p
    }
    return sum
}

fn main() void {
    println("${total([120, 80])}")
}
```

```text output
contracts: 3 contracts, 0 errors
OK (0 diagnostics)
```

Contracts run after the program checks, so a program with an error runs none,
and a contract can sit in the module it checks. `atoll check` and `atoll lint`
say the `contracts:` line every time; `atoll build`, `atoll run` and `atoll
test` say it only when a contract found an error.

## A contract on the project

A **project contract** takes `meta.Project` and checks what is not a
declaration. The `has_changelog` above looks for a file. This one reads every
migration of the project:

```atoll project=service file=policy/migrations.at
import meta
import project

/// Every migration can be undone.
@contract
pub fn reversible(p meta.Project, out &mut meta.Report) void ! meta.Error {
    for up in project.glob("migrations/*.up.sql")? {
        down := up.path().replace(".up.sql", ".down.sql")
        if !project.exists(down)? {
            out.fail(up.span(), "`${up.path()}` has no down migration; add `${down}`")
        }
    }
}
```

A project contract runs on every `check`, `build`, `run`, `test` and `lint` of
the package that declares it, with nothing to apply. It reads files through
`import project`, and what it may read is the manifest's to say. Nothing is
readable until the manifest grants it, and a read outside the grant stops the
run at the read and says which glob it needed:

```toml
[comptime]
allow = ["std/project", "std/git"]   # the packages contracts may use
files = ["CHANGELOG.md", "migrations/**"]   # the files they may open
base  = "v1.0.0"                      # the release history is compared with
```

A finding is placed where the mistake is: a declaration (`target.span()`), a
file (`up.span()`), one of its lines (`file.line_span(12)`), or the manifest.
`out.fail` is an error; `out.warning` and `out.note` report less.

## Levels, and silencing one

The root manifest sets the level of any contract's findings, as a lint level:

```toml
[comptime.contracts]
"example.dev/rules/policy.documented" = "warning"   # error | warning | note | off
```

`off` runs the contract nowhere. `@allow(documented)` on a declaration silences
an attached contract's findings inside it — by its name, its module's last
segments and its name, or its whole path as a string. A level that is not one
of the four is an error.

## History: the base and what changed since

A contract can compare the project with a release. The comparison is **written
down**, not "whatever `origin/main` is today": the base is a tag or a commit id
(`atoll check --base v1.0.0`, or `base` in the manifest), resolved once to a
commit and printed with the run — `contracts: base v1.0.0 = 4f1c2e9d0b…; 3
contracts, 0 errors`. A branch name, and a remote-tracking ref above all, is
refused: a base must not move. `base = "release"` means the highest `vX.Y.Z`
tag that is an ancestor of HEAD. A base the clone does not have — a shallow
clone — is an error that says so, never an empty comparison.

```atoll project=service file=policy/released.at refused=example.dev/service/policy.never_edited
import git
import meta
import project

/// A migration that shipped in the base release is never edited or removed.
@contract
pub fn never_edited(p meta.Project, out &mut meta.Report) void ! meta.Error {
    base := git.base()?
    for c in git.diff(base.tree(), git.worktree())? {
        if !c.path().starts_with("migrations/") { continue }
        if c.status() == "modified" || c.status() == "deleted" {
            out.fail(
                project.manifest().span(),
                "`${c.path()}` was released in ${base.id().take(10)} and is ${c.status()}; add a new migration instead"
            )
        }
    }
}
```

This book's copy of the project is not a repository, so the check above is
refused by the contract itself, which says the package is in no git
repository. In a repository tagged `v1.0.0`, with `migrations/0001_orders.up.sql`
edited since, it reports at the manifest:

```text nooutput a quote of a repository the book does not keep: the base and its hash are the reader's
error[example.dev/service/policy.never_edited]: `migrations/0001_orders.up.sql` was released in 4f1c2e9d0b and is modified; add a new migration instead at atoll.toml:1:1
contracts: base v1.0.0 = 4f1c2e9d0b…; 4 contracts, 1 error
```

Everything reached from a commit is immutable, so a contract's reads at the
base are kept by the commit's id and never read twice. `import git` reads
history only; it has no operation that writes a ref, an object or the working
tree, and none that fetches.

## A contract a dependency declares

A library can ship rules for the projects that use it, as it ships a
decorator: `pub` contracts in a module of their own. This book's `rules`
package does, in `policy/policy.at` above. Two things a consumer can do:

- **Apply an attached one.** `@policy.documented` above, with `import
  example.dev/rules/policy`, runs the library's contract at that function,
  under the level the consumer gives its path.
- **Name a project one.** A library's project contracts never run in a consumer
  on their own — a library's release discipline is its own CI's business — so
  the consumer asks for one by name, and grants what it reads:

```toml
[comptime]
allow = ["std/project"]
files = ["CHANGELOG.md"]

[comptime.contracts]
"example.dev/rules/policy.has_changelog" = "error"
```

What a dependency's contract reads is the consumer's to grant, so a contract
that reaches `std/project` without `allow` listing it is refused where it is
declared, naming the contract. The library that ships a project contract sets
it `off` in its own manifest, as `rules` does, unless it wants it checked over
the library too.

## Testing a contract

A package that ships contracts tests them with ordinary `test` items.
`std/meta/testing` checks a **fixture** — a small package in a directory of
yours — after a history you script, with the same `atoll` that runs the test,
and answers what it found. The fixture depends on the package under test by
`{package}`, which stands for that package's directory:

```toml
# tests/fixtures/changelog/atoll.toml
module = "example.dev/fixture"
version = "0.1.0"
edition = "2026"

[dependencies]
"example.dev/rules" = { path = "{package}" }

[comptime]
allow = ["std/project"]
files = ["CHANGELOG.md"]

[comptime.contracts]
"example.dev/rules/policy.has_changelog" = "error"
```

```atoll project=rules file=rules_test.at
import std/meta/testing

test "a project without a changelog is refused until it has one" {
    found := testing.contract("tests/fixtures/changelog", [])
    assert(!found.ok(), found.text())
    assert(found.has("the project has no CHANGELOG.md"), found.text())
    kept := testing.contract(
        "tests/fixtures/changelog",
        [testing.write("CHANGELOG.md", "# Changelog\n")]
    )
    assert(kept.ok(), kept.text())
}
```

```text output
$ cd rules
$ atoll test
    PASS [   0.093s] rules_test.at: a project without a changelog is refused until it has one
------------
 Summary [   0.508s] 1 test run: 1 passed, 0 failed
 Slowest: 0.093s rules_test.at: a project without a changelog is refused until it has one
```

`testing.contract(dir, history)` copies the fixture into a scratch directory,
and removes it when the call returns. With a history, the copy first becomes a
git repository, and the steps play in order on its worktree:
`testing.write(path, text)`, `testing.remove(path)`, `testing.commit(message)`
and `testing.tag(name)`. With none, it is no repository, and a contract that
reads history says so. A failed expectation prints what the check printed —
the findings and the `contracts:` line — so the test's failure is the finding.
`Findings` answers `ok()`, `text()`, `findings()`, `errors()`, `warnings()`,
`has(text)` and `has_code(code)`; a finding has a `severity`, a `code`, a
`message` and where it is, `at`.

## What is not here yet

- The editor runs the contracts a project declares on a save, and again when a
  granted file or the repository moves. It does not yet run the contracts a
  dependency declares, or the ones a manifest names, and it does not link
  `std/meta/testing` for an open test file.
- A contract is granted the files it reads, but the grant check walks every
  function the contract can reach, so a read behind a branch the contract never
  takes still needs the grant.

Source: https://docs.atoll.workreef.dev/language/tooling/contracts/index.mdx
