# Commit rules

How `mt check --commit-msg` checks a commit’s `Refs` trailer and message against the project’s commit rules.

`mt check --commit-msg <file>` checks the commit you’re writing against the project’s `[commits]` config. Run it from a `commit-msg` hook and git refuses a commit that breaks a rule. `mt check --commits <range>` runs the same checks over commits already made. [Trace commits to tasks](https://mlavrinenko.github.io/mindtape/trace-commits-to-tasks/index.md) walks through the setup, from a refused commit to `touches()`.

The examples run in a git copy of `examples/rules/`, whose config has the three commit rules below. [Packs](https://mlavrinenko.github.io/mindtape/packs/index.md) lists the `mindtape:tasks` rules (`name-task-in-refs-trailer`, `squash-every-autosquash-commit`, `flip-task-with-its-work` and `finish-named-task-at-tip`) and the commit rules of `mindtape:commits` (`add-changelog-entry-for-product-change`, `start-named-task-in-its-commit`) and `mindtape:tweaks` (`keep-tweak-to-one-source-file`).

```toml
# examples/rules/.mindtape/config.toml: the trailer that names tasks
[commits]
trailer = "Refs"
external-refs = ["^r#[0-9]+$"]

# examples/rules/.mindtape/config.toml: a rule that runs once per commit
[[commits.rules]]
name = "migration-names-a-task"
when = 'matches(files, "^migrations/")'
assert = "has(refs)"
message = "add a Refs: <stem> trailer naming the task the migration belongs to"
severity = "error"

# examples/rules/.mindtape/config.toml: a rule that runs once per task the commit touches
[[commits.rules]]
name = "stage-the-flip"
scope = "task"
when = "named"
assert = "worktree(status) == staged(status)"
message = "stage the task's status change with the work it names"
severity = "error"

# examples/rules/.mindtape/config.toml: a rule that runs once per task a range names
[[commits.rules]]
name = "finish-named-tasks"
scope = "tip"
assert = '!(status == "wip")'
message = "run `mt done <stem>` and commit it with the task's last work"
severity = "error"
```

## The hook

The hook is one line. Git passes the message file as its first argument:

```
$ cat .git/hooks/commit-msg
#!/bin/sh
mt check --commit-msg "$1"
```

`mt check` skips a merge commit. The merge joins commits that each went through a check on its own, so `mt check` does not judge the merged branch as one commit. Pass `--check-merges` to check one anyway.

Outside a git repository, `mt check --commit-msg` fails with `not a git repository`.

## The trailer

`[commits] trailer`, `Refs` by default, sets the trailer whose values are task stems, one [stem](https://mlavrinenko.github.io/mindtape/concepts/index.md#identity) per line. A line may list more than one ref, split on commas or whitespace, and the trailer may repeat. Whatever the rules say, `mt` refuses a value that doesn’t point at a task and matches no external pattern. `mt` refuses a path that points at a task too, and asks for its stem. A path changes when a task moves to another folder, and a stem stays unique in the project:

```
$ git commit -qm "feat: add the sessions table" -m "Refs: tasks/fix-the-session-timeout.typ"
error: .git/COMMIT_EDITMSG:3: Refs: `tasks/fix-the-session-timeout.typ` is a path; write the stem: `Refs: fix-the-session-timeout`
error: 1 commit message problem
```

A repo that tracks work elsewhere keeps `Refs:` as its one trailer. `[commits] external-refs` lists regexes. `mt` treats a ref that points at a task as a task ref. It treats one that matches a pattern as an external ref, kept opaque. It refuses the rest. The config above accepts `r#45782`. A ref with a comma or a space goes in double quotes, as in `Refs: "redesign one"`, or escapes that one character with a backslash. `touches()` and a `scope = "task"` rule ignore external refs.

## The message command

`[commits] run` names a command that checks every commit message. `mt check --commit-msg` and `mt check --commits` run it once per message, from the project root, with the message on stdin. A non-zero exit fails the check, and `mt` reports each line the command prints as one problem. The command is the project’s, not `mt`’s: this repo points it at a Vale script, and another project can point it at its own checker.

```toml
[commits]
run = ["bash", ".just/scripts/check-commit-prose.sh"]
```

The `commit-msg` hook runs it through `mt check --commit-msg`, so a bad message never becomes a commit. A merge commit passes, as every commit check skips one.

## Commit rules

`[[commits.rules]]` takes the same keys as `[[tasks.rules]]`: `name`, `when`, `assert`, `message` and `severity`. `scope = "commit"`, the default, runs the rule once per commit, over these fields:

| Field | Holds |
| --- | --- |
| `subject` | The message’s first line. |
| `refs` | The trailer’s `refs` holds task stems and external refs as written. A line may list more than one, split on commas or whitespace. |
| `trailers` | Every trailer line of the message, whatever its key, as `Key: value`. `matches(trailers, "^Changelog: none$")` finds one. |
| `files` | Every staged path, relative to the repository’s top level. A rename gives both its paths. Under `git commit --amend` the paths are diffed against the parent of the commit being replaced, so an amend that adds a task’s flip to its work commit still sees the work. |
| `tasks_only` | Whether the commit stages at least one file and every staged file is a task file: a regular `.typ` file under a `[tasks] roots` entry, outside every reserved `.mindtape`/`.git` component and template dir. It is decided by path, so a markerless `.typ` counts, a tracked-deleted path counts, and a symlink does not. |
| `in_range` | Whether the commit is read from a range: true under `mt check --commits`, false under `mt check --commit-msg`. |
| `is_merge` | Whether the commit has more than one parent. A merge is skipped unless `--check-merges` asks for it. |

Commit classification reads the state’s own config and task files: the index for `mt check --commit-msg`, and each commit’s tree for `mt check --commits`. A path is a task file when [Which files count as tasks](https://mlavrinenko.github.io/mindtape/concepts/index.md#which-files-count-as-tasks) admits it under that state’s `[[tasks.roots]]` and `[templates] dirs`.

The operators come from the [filter language](https://mlavrinenko.github.io/mindtape/filters/index.md). The functions are `has(field)`, `miss(field)` and `matches(field, "regex")`. Over a list, `matches` is true if any entry matches, so `!matches(files, "^services/")` means the commit changes nothing under `services/`.

`count(files, "glob"…)` is a number: how many of the commit’s files the globs admit, with the same `"!glob"` excludes as `changed()`. It sits on the left of a comparison, so `count(files, "!docs/**") <= 1` caps the commit at one file outside `docs/`. A rename counts once, as in `changed()`, while `has` and `matches` still see both of its paths. `"@name"` reads a `[dicts.name]` path set the same way `changed()` does. `subject` also compares with a string.

If a commit-scope rule reads a task field, `mt` refuses it when it loads the config, and lists the fields a commit rule can read.

A breach names the message file and the rule. Here a migration has no `Refs:` trailer, and then the same commit names its task:

```
$ git commit -qm "feat: add the sessions table"
error: .git/COMMIT_EDITMSG: commits.rules.migration-names-a-task: add a Refs: <stem> trailer naming the task the migration belongs to
error: 1 commit message problem
$ git commit -qm "feat: add the sessions table" -m "Refs: fix-the-session-timeout"
ok: commit message valid
```

`subject` is also how a rule exempts a commit autosquash will drop. The `mindtape:tasks` pack’s `name-task-in-refs-trailer` adds `!matches(subject, "^(fixup|squash|amend)! ")` to its `when`, so a `git commit --fixup` needs no `Refs:`. The pack’s `squash-every-autosquash-commit` is the other half. It reads `in_range`, so the hook lets a fixup through and `mt check --commits` refuses one that was not squashed.

Rules merge by `name` across [config layers](https://mlavrinenko.github.io/mindtape/config/index.md#layers) and [rule packs](https://mlavrinenko.github.io/mindtape/packs/index.md), like `[[tasks.rules]]`. To replace a pack’s rule, declare one with its name. To drop it, use `disable`.

## Task scope

To check what a commit does to a task, such as closing it without any work, use `scope = "task"`. It runs the rule once for each task the commit changes or names in its trailer. The rule reads the commit’s fields above, and the task in one of three states:

| Reads | Holds |
| --- | --- |
| `head(<expr>)` | The task as of `HEAD`, before the commit, or of `HEAD^` under `git commit --amend`. |
| `staged(<expr>)` | The task as it stands in the index, which the commit records. |
| `worktree(<expr>)` | The task as it stands on disk. |
| `named` | Whether the trailer names the task. |
| `retires_other` | Whether the commit retires a task other than this one: `HEAD` has it and the index doesn’t, as after `mt rm`. A change to its file, which `records_other` reads, is not a retirement. |
| `records_other` | Whether the commit changes a task file other than this one, as a record correction does. The task’s own flip is not another file, so a close that changes nothing else still fails. |

A wrapper takes any [filter expression](https://mlavrinenko.github.io/mindtape/filters/index.md) and evaluates it against the project in that state, so `ready`, `blocked` and `count(...)` read the tasks as they stand there. Inside a wrapper, `exists` is false if the state has no file for the task, so `head(exists) && !staged(exists)` is a deletion. As one side of a comparison, a wrapper is the field’s value in that state, as in `worktree(status) == staged(status)`. `mt` refuses a bare task field, because a reader could not tell which state the rule means.

`into("s")` means `staged(status == "s") && !head(status == "s")`: the commit moves the task into status `s`.

If either compared state imports a prelude this `mt` does not support, the hook warns and skips every `scope = "task"` rule; the `Refs` trailer check and `scope = "commit"` rules still run. `mt check --commits` skips the commit when its own or its parent tree is unsupported, because a task rule cannot read a state whose prelude does not load.

The `mindtape:tasks` pack’s `flip-task-with-its-work` uses `retires_other` so that a cleanup task closes in the commit that runs `mt rm` on other tasks, though that commit stages nothing but task files. `records_other` is the record correction’s escape: a task whose only work is one line of another task’s record starts and closes in the commit that edits it. The rule also lets a task of `kind: "milestone"` close alone, because a milestone ends through its leaves and has no work of its own. A task with no work at all still needs `kind: "decision"` or `kind: "milestone"`, and the refusal names both.

A breach names the rule, then the task. Here `mt done` changed the task file, but only the code is staged:

```
$ git status --short
M  src/session.rs
 M tasks/fix-the-session-timeout.typ
$ git commit -qm "fix: expire idle sessions" -m "Refs: fix-the-session-timeout"
error: .git/COMMIT_EDITMSG: commits.rules.stage-the-flip: fix-the-session-timeout: stage the task's status change with the work it names
error: 1 commit message problem
$ git add -A && git commit -qm "fix: expire idle sessions" -m "Refs: fix-the-session-timeout"
ok: commit message valid
```

## Tip scope

A branch that works on a task should finish it. `scope = "tip"` runs the rule once for each task a checked commit of a range names in its trailer, over the task as it stands at the tip, the range’s newest commit. Only `mt check --commits` runs it, since `mt check --commit-msg` checks one commit with no range. A tip rule is an ordinary [filter expression](https://mlavrinenko.github.io/mindtape/filters/index.md), like a `[[tasks.rules]]` one: `status`, `ready` and `count(...)` read the tip’s tasks, and there are no commit fields or state wrappers. The `mindtape:tasks` pack ships `finish-named-task-at-tip`, which asserts `!(status == "wip")`, and the config above has the same rule as `finish-named-tasks`. A task named in several commits is checked once, and a breach leads with the tip’s id and names the task. Here a branch starts a task and never finishes it:

```
$ mt check --commits main~1..main
skip: commits.rules.stage-the-flip: reads the working tree, which a past commit has none of
error: d076bff: commits.rules.finish-named-tasks: add-csv-export: run `mt done <stem>` and commit it with the task's last work
error: 1 task broke commit rules
```

A task missing from the tip, because the range deleted or retired it, is skipped: it has no state to be wrong in. A tip rule that calls `changed(...)` is skipped like any rule that reads the working tree.

To refuse a branch at merge time, run `mt check --commits main..HEAD` in the `pre-merge` hook of `wt merge`, or in CI.

## Check a range

A hook doesn’t run under `git commit --no-verify`, so check the commits a push contains in CI too. `mt check --commits <range>` checks every commit `git rev-list` lists for the range, oldest first, with the same trailer check and rules. The only difference is `in_range`, which is true here.

Each commit is read against its first parent. A merge is skipped by default, as above; pass `--check-merges` to read it like any other commit. The newest commit still supplies the tip state when it is a merge, so the tip rules apply to the tree the range ends on. `subject` and `refs` come from the message, and `files` from what the commit changes against its first parent. `staged(...)` reads the commit’s tree and `head(...)` the parent’s. A task ref must name a task the commit’s tree holds. A past commit has no working tree, so `mt` skips a rule that calls `worktree(...)` or `changed(...)`, and says so once. `count(files, …)` reads the commit’s own files, so it still runs. A commit whose tree or parent tree imports a prelude version this `mt` does not support is skipped with one warning per version naming the version and the set, and its refs never reach the rules. A skipped tip state also skips the tip rules. Only commits with something to report are listed, each with its lines indented below it:

```
$ mt check --commits main~3..main
skip: commits.rules.stage-the-flip: reads the working tree, which a past commit has none of
error: a3e8f35: commits.rules.migration-names-a-task: add a Refs: <stem> trailer naming the task the migration belongs to
note: commit: 'chore: drop the legacy table'
error: 1 commit broke commit rules
```
