# Rules

The checks a project adds to its tasks: required fields, assertions, Typst checks, body rules and comment policy.

Rules are the checks that `mt check` and every command that writes a task file run. They check each field against the config, such as a status against the [status legend](https://mlavrinenko.github.io/mindtape/statuses/index.md), plus any checks you add with the keys on this page. Rules from an ancestor directory’s defaults and from rule packs add to your project’s own, as [Configuration](https://mlavrinenko.github.io/mindtape/config/index.md) describes. To share one set of rules between projects, see [Packs](https://mlavrinenko.github.io/mindtape/packs/index.md). To read the rules your project ends up with, run [`mt config show --resolved`](https://mlavrinenko.github.io/mindtape/cli/config/index.md). Its `[[tasks.rules]]`, `[[commits.rules]]` and `[[on.flip]]`/`[[on.rm]]` sections hold them, each rule with its `when`, `assert`, `severity` and `message`, and a `when` or `assert` shows every tag the rule reads.

A new check on an added task is a config expression, not Rust code. Write a `[[tasks.rules]]` assertion to check a value, or an [`[[on.add]]`](https://mlavrinenko.github.io/mindtape/hooks/index.md) action to set a default. A `dir` assertion holds the folder layout a hook chooses:

```toml
[[tasks.rules]]
name = "fixes-live-in-their-dir"
when = 'kind == "fix"'
assert = 'dir == "tasks/fixes"'
```

## Required fields

`required` takes `true`, `false`, or a [filter expression](https://mlavrinenko.github.io/mindtape/filters/index.md). With an expression, the expression requires the field on exactly the tasks it matches. You can set it on `[tasks.priority]`, `[tasks.difficulty]`, `[tasks.estimate]`, `[tasks.assignee]` and each `[tasks.fields.<name>]`:

```toml
# examples/rules/.mindtape/config.toml: required while open; an estimate on bugs only; a known assignee
[tasks.priority]
required = "!terminal"

[tasks.estimate]
units = ["hours"]
required = 'kind == "bug"'

[tasks.assignee]
allowed = ["ada", "lin"]
required = "!terminal"
```

`mt` refuses a write that would leave a required field empty:

```
$ mt set add-csv-export kind=bug
error: tasks/add-csv-export.typ:3: estimate: required field is missing
```

`mt` parses each expression once, when it loads the config. A broken one then gives you one error that reports the field.

## Assertions

A `[[tasks.rules]]` entry with `assert` checks every task it selects against a filter expression. Unlike `required`, it can test a field’s value:

```toml
# examples/rules/.mindtape/config.toml: an error on open bugs, and a warning on every task
[[tasks.rules]]
name = "bugs-outrank-the-low-band"
when = 'kind == "bug" && !terminal'
assert = "priority >= 3"
message = "raise the bug's priority or close it"
severity = "error"

[[tasks.rules]]
name = "no-full-stop-in-titles"
assert = '!matches(title, "\\.$")'
message = "drop the full stop at the end of the title"
severity = "warn"
```

| Key | Default | Purpose |
| --- | --- | --- |
| `assert` |  | Filter expression that must evaluate true for every task the rule applies to. The rule sets exactly one of this and `check`. |
| `check` |  | A Typst function to call instead of an `assert` expression. The rule sets exactly one of this and `assert`. |
| `message` |  | What an `assert` breach tells the author to do, in place of the default advice that quotes the `assert` expression. A `check` rule ignores it and prints each string its function returns. |
| `name` |  | The name a report shows for the rule (`rules.<name>`). Optional: an unnamed rule reports by its position instead (`rules[0]`). |
| `severity` | `"error"` | Whether a breach fails the command or only reports. Default `error`. |
| `when` |  | Filter expression gating which tasks the rule applies to. Absent means every task. |

`severity` is `error` by default, and a breach refuses the write. Write `severity = "warn"` to make a rule advisory instead.

An `error` breach refuses the write, and `mt` doesn’t write the file:

```
$ mt set fix-the-session-timeout priority=1
error: tasks/fix-the-session-timeout.typ:3: rules.bugs-outrank-the-low-band: raise the bug's priority or close it
```

A `warn` breach prints a warning, and the write goes ahead:

```
$ mt set add-csv-export 'title=Add CSV export to the report page.'
warning: tasks/add-csv-export.typ:3: rules.no-full-stop-in-titles: drop the full stop at the end of the title
set add-csv-export (Add CSV export to the report page): title: "Add CSV export to the report page."
next: mt eval add-csv-export
```

`mt check` reports the same breach at the line of the task’s `task.with(…)` call. A rule with no `name` reports by its position, `rules[0]`, so you can always find the entry. `mt` runs each `assert` and `when` once against a sample task when it loads the config. So a rule that references an unknown field, [view or dictionary](https://mlavrinenko.github.io/mindtape/named-sets/index.md) gives you one config error. You don’t get one breach per task.

`mt check` also files each [template](https://mlavrinenko.github.io/mindtape/templates/index.md) with its examples, and with its defaults under `[templates] check-defaults`. It checks each result as a task. A filled template is not a task file, though, so two kinds of rule have no answer for it. `mt` leaves out of the template report a rule that reads the whole set, such as a `count(...)` cap. It also leaves out a rule that reads where the file lives, through `path` or `dir`. A rule about the template’s own fields still reports, so a stale template cannot slip through.

## Work-in-progress caps

`count(...)` counts the loaded tasks a filter matches (see [Filter language](https://mlavrinenko.github.io/mindtape/filters/index.md)). Compare it with a number to cap how many tasks can be in a set at once:

```toml
# examples/rules/.mindtape/config.toml: at most one task in flight
[[tasks.rules]]
name = "one-task-in-flight"
when = 'status == "wip"'
assert = 'count(status == "wip") <= 1'
message = "finish the task in flight before starting another"
severity = "error"
```

`when` repeats the counted filter on purpose. The comparison gives the same answer for every task. The rule then reports a breach on every task `when` selects: the task moving into the set, and each task already in it. The second line below is the breach on the task already in flight, reported against the [flip](https://mlavrinenko.github.io/mindtape/statuses/index.md) that caused it:

```
$ mt flip wip add-csv-export
error: tasks/add-csv-export.typ:3: rules.one-task-in-flight: finish the task in flight before starting another
note: tasks/fix-the-session-timeout.typ:3: rules.one-task-in-flight: finish the task in flight before starting another
```

The capped set can be any filter. The same rule then caps a view (`when = '@stuck'`), a [priority band](https://mlavrinenko.github.io/mindtape/priority/index.md) or a `kind`.

## Derived fields

Some fields are cheaper to compute than to write twice. A [collector](https://mlavrinenko.github.io/mindtape/config/index.md#derived-fields) reads the task and publishes the result as `derived.<name>`, and a rule reads it like any other field. A regex collector reads a body section, so a size cap can read the files a task’s Changes section names instead of a separate estimate:

```toml
[[tasks.collectors]]
name = "changes"
when = "!terminal"
query = { section = "Changes", pattern = "(?m)^\\s*-\\s+`([^`]+)`" }
returns = ["path"]

[[tasks.rules]]
name = "cap-judgment-work-at-max-source-files"
when = '!terminal && difficulty >= 3'
assert = 'count_paths(derived.changes, "@source") <= 5'
message = "split the decision from the mechanical fan-out"
severity = "error"

[dicts.source]
case = "exact"
values = ["**"]
```

An ast-grep collector matches code structure instead. It matches Rust files (`.rs`) through the shared query engine, publishes each matching path once, and lets a rule bound a file count the way it bounds a Changes list:

```toml
# examples/rules/.mindtape/config.toml: the collector and the rule that reads it
[[tasks.collectors]]
name = "callers"
when = "!terminal"
query = { ast_grep = { language = "rust", pattern = "parse_task($$$ARGS)", glob = "@source" } }
returns = ["path"]

[[tasks.rules]]
name = "callers-stay-local"
when = "!terminal && difficulty >= 3"
assert = 'count_paths(derived.callers, "@source") <= 3'
message = "keep the parse-task fan-out small"
severity = "error"

# examples/rules/.mindtape/config.toml: the @source set both read
[dicts.source]
case = "exact"
values = ["src/**"]
```

The query’s optional `glob`, a glob or `@name` path set, narrows the files it reads. Without one, it reads every file of that language git lists. Paths are relative to the repository root, as `changed()` reads them. A nested project then prefixes its directory, as in `sub/src/**`. A file query needs a git working tree. Outside one, `mt check` reports the collector problem, and the error reports `git init` as the fix. A file counts once however many matches it contains. The rule then bounds a file count, not a call-site count.

A Typst collector is the escape hatch for a structure a regex or a pattern cannot read. It calls a project function over the task, or over one field, and the rule reads the value it returns. A failed call is a `Collector` violation at `derived.<name>`, so it fails `mt check` like any other breach.

[`mt config show --resolved`](https://mlavrinenko.github.io/mindtape/cli/config/index.md) lists the collectors under `[[tasks.collectors]]`, each with its `query` and its `returns` type. A Typst collector specifies its module and function. An ast-grep collector specifies its language, pattern and optional glob. A rule whose filter names an undeclared `derived.<name>` fails config load, so a renamed collector cannot leave a rule with nothing to read.

## Typst checks

The filter language reads an `x-<ns>` field’s text, number or list, but can’t look inside a dictionary. `[tasks.fields.x-<ns>]` only covers a list of strings and a `required` rule. For anything else, write a rule with `check` instead of `assert`. It calls a Typst function in the project, with one field’s value or the task:

```toml
# examples/rules/.mindtape/config.toml: every open task lists its acceptance criteria
[[tasks.rules]]
name = "acceptance-criteria"
when = "!terminal"
check = { typst = "lib.typ", function = "check-acceptance", field = "x-acceptance" }
severity = "error"
```

| Key | Default | Purpose |
| --- | --- | --- |
| `field` |  | Field whose value the function receives (`none` when the task omits it). Absent means the function receives the whole task, in the shape `mt eval --json` prints. `markers` is the one reserved input: it yields the task body’s metadata markers as an array of `(label, value)` dicts in document order. It yields an empty array rather than `none` when the body emits none. Every other name is a canonical field or an `x-<ns>` slot. The reserved input is not a task field, so a rule over it lists only the fields its `when` and `assert` expressions read. |
| `function` |  | Name of the function `typst` exports that this rule calls. |
| `typst` |  | Path to the Typst module exporting `function`, relative to the project root (the directory holding `.mindtape/`), or to the directory of the pack that declares the rule. |

The function returns an array of strings. An empty array passes. Each string is one breach, reported like an `assert` breach at the rule’s `severity`:

```typ
// examples/rules/lib.typ — the function the `acceptance-criteria` rule calls.
// It receives the task's `x-acceptance` value, or `none` when the task has
// none, and returns one string per problem. An empty array passes.
#let check-acceptance(criteria) = {
  if criteria == none {
    return ("list what must be true to close this task in x-acceptance",)
  }
  if type(criteria) != array or criteria.len() == 0 {
    return ("x-acceptance is a non-empty list of criteria",)
  }
  criteria
    .enumerate()
    .filter(((i, c)) => type(c) != str or c.trim() == "")
    .map(((i, c)) => "acceptance criterion " + str(i + 1) + " is empty")
}
```

The value arrives as a Typst literal, and a content block in it as its plain text. A date in a `field` value arrives as a `datetime`. Without `field`, the function receives the same task object that `mt eval --json` prints. In that object, a date is a `YYYY-MM-DD` string. A Typst error, a `panic()` in the function, or a return that isn’t an array of strings counts as one breach with the message. The rest of the project still loads.

`markers` is the one reserved `field`. It reads the metadata markers the body emits instead of a task field, and the function receives them as an array of `(label, value)` dicts in document order. `label` is the marker’s Typst label, `none` for a marker without one, and `value` is the whole value the marker carries, so `#metadata((marker: "example", value: 1)) <example>` arrives as `(label: "example", value: (marker: "example", value: 1))`. A task whose body emits none of them passes an empty array, not `none`, so the function can loop over it without a nil guard. A date in a marker value arrives as its `YYYY-MM-DD` text, and a warm load reads the same text back from the cache. Every other `field` is a canonical field or an `x-<ns>` slot.

When `mt` loads the config, it checks that the module exists and exports the function, and reports each failure as its own config error. It doesn’t call the function then, so a function that rejects some values can’t fail the config load. [Self-validating tasks](https://mlavrinenko.github.io/mindtape/self-validating-tasks/index.md) walks through a complete example.

## Body rules

To require every task to have, say, a Summary and acceptance criteria, check its body. Two rule families do that. Both pick sections by a path through the heading tree. A bare string matches a heading’s text exactly, and only among the direct children of the previous step. `{ match = "regex" }` matches heading text with a regex, and `recursive = true` lets it match at any depth.

`[[tasks.body.headers.rules]]` checks which headings exist and in what order:

```toml
# examples/rules/.mindtape/config.toml: one Summary, and no heading outside a fixed set
[[tasks.body.headers.rules]]
name = "one-summary"
path = ["Summary"]
action = "unique"
message = "keep exactly one Summary section"

[[tasks.body.headers.rules]]
name = "known-sections"
action = "allowlist"
allowed = [{ match = "^(Summary|Steps to reproduce|Notes)$" }]
```

| Key | Default | Purpose |
| --- | --- | --- |
| `action` |  | Whether the target headings must exist, must not, or must be unique, or whether this is an `order`/`allowlist` rule. |
| `after` | `[]` | Path whose headings must come after (`order`). |
| `allowed` | `[]` | The permitted headings (`allowlist`). |
| `before` | `[]` | Path whose headings must come first (`order`). |
| `message` |  | Override for the default violation message. |
| `name` |  | The name a report shows for the rule (`body.headers.rules.<name>`). Optional: an unnamed rule reports by its position instead (`body.headers.rules[0]`). Two rules in this array sharing a name is a config error that reports both. |
| `path` | `[]` | Path through the heading tree (`require`, `forbid`, `unique`). |
| `scope` | `[]` | Path selecting the scopes whose children the rule constrains (`allowlist`). Omit it to constrain top-level headings. |
| `when` |  | Optional filter expression gating this rule to matching tasks only. |

`[[tasks.body.content.rules]]` checks the text under a heading: everything down to the next heading of the same or a higher level, subsections included.

```toml
# examples/rules/.mindtape/config.toml: a non-empty Summary, a detailed repro on bugs, and a dash limit
[[tasks.body.content.rules]]
name = "summary-non-empty"
path = ["Summary"]
assert = "non-empty"
message = "write text under the Summary heading or remove the heading"

[[tasks.body.content.rules]]
name = "repro-has-detail"
path = ["Steps to reproduce"]
assert = { words = { min = 15 } }
when = 'kind == "bug"'

[[tasks.body.content.rules]]
name = "one-dash-per-paragraph"
path = [{ match = ".*", recursive = true }]
assert = { density = { pattern = "—", max = 1, per = "paragraph" } }
message = "cut the paragraph to one em-dash at most"
```

`assert` takes one of five forms:

- `"non-empty"`: the section has some text.
- `{ words = { min = N, max = M } }`: at least `N` and / or at most `M` words, where a word is any run of non-whitespace characters containing a letter or a digit. The table must carry `min` or `max`. `mt` refuses a table that carries neither. `count` picks what the count counts:
  - `all` (the default): markup, fenced code, inline code and subsection headings all count.
  - `prose` drops fenced code and keeps inline code as part of the sentence it sits in.
  - `text` drops fenced code and masks inline code, so only the text outside code counts.
- `{ must-match = "regex" }` and `{ must-not-match = "regex" }`: the regex runs against the section’s source text, markup included.
- `{ density = { pattern = "regex", max = N, per = "section" } }`: no single unit contains more than `max` matches. `per` is `section` (the default), `paragraph` or `sentence`. Paragraphs split at blank lines and at each list item. Sentences split after a `.`, `!` or `?` followed by a space or the end. `mt` removes code first, fenced or inline, so a match inside a code sample or a backtick span never counts, and a span never splits a sentence.

| Value | Meaning |
| --- | --- |
| `all` | Every token in the section slice, markup and code included (the default). |
| `prose` | The section’s prose. The count drops fenced code and keeps inline code as part of its sentence. |
| `text` | The section’s text outside code. The count drops fenced code and masks inline raw spans. |

`[tasks.body.content] words = { count = "prose" }` sets the unit once for every content rule that leaves `count` out. A rule’s own `count` overrides it. The section table carries only `count`. `mt` refuses `min` or `max` there, because a bound stays visible on the rule that enforces it.

| Key | Default | Purpose |
| --- | --- | --- |
| `rules` | `[]` | Ordered list of section-content gating rules. |
| `words` | `{ count = "all" }` | Defaults every content rule inherits. |

`mt` refuses a write that breaks a body rule, the same as a field rule. `mt check` reports a body violation at the heading’s line, or at the `task.with(…)` line if a required section is missing, named `body.headers.rules.<name>` or `body.content.rules.<name>`. A content rule’s `message` takes the line, and `mt` prints the check’s default text as a `note:` below it, so you still see which paragraph or sentence broke the rule. `--json` lists them in `notes`.

```
$ mt check
error: tasks/add-csv-export.typ:16: body.content.rules.one-dash-per-paragraph: cut the paragraph to one em-dash at most
note: section `Notes` paragraph 2 ("The export runs on the server…") must carry at most 1 matches of `—` (found 2)
error: 1 problem in 1 task
```

## Review comments

If you or a reviewer leave comments in task files, you may want them cleared before work continues. `[tasks.comments]` sets what `mt check` does with a comment anywhere in a task file, inside `task.with(…)` or in the body:

```toml
# examples/rules/.mindtape/config.toml: fail on any comment except a TODO
[tasks.comments]
policy = "forbid"
allow-pattern = "^TODO:"
```

| Value | Meaning |
| --- | --- |
| `allow` | Comments stay unconstrained. The default. |
| `warn` | `mt check` reports a comment but still succeeds. |
| `forbid` | `mt check` reports a comment and fails. |

`allow-pattern` is a regex matched against the comment’s text, trimmed and without its comment markers. `mt` lets through the comments it matches. `mt` finds comments by parsing the file, so `//` inside a string or a raw block is never reported. Only `mt check` applies this policy. A write command won’t refuse a task for a comment.
