rules.nvim · Debug & inspect · vimdoc

:help rules

A rule/checklist engine for Neovim

doc/rules.txt — rendered from the plugin's own vimdoc

*rules.txt*    A rule/checklist engine for Neovim

CONTENTS *rules-contents*

    Introduction ....... |rules-introduction|
    Setup .............. |rules-setup|
    Commands ........... |rules-commands|
    The form ........... |rules-form|
    Settings files ..... |rules-config|
    Vault .............. |rules-vault|
    Gates .............. |rules-gates|
    Waivers ............ |rules-waivers|
    Work list .......... |rules-work-list|
    Ruleset format ...... |rules-ruleset-format|

INTRODUCTION *rules-introduction*

rules.nvim reads a set of rules you point it at, runs whichever of them can
be checked mechanically against a repo, and reports the rest as a worklist.
It ships with no bundled rules of its own — see the README's "Why no bundled
rules".

SETUP *rules-setup*

    require("rules").setup({
      rulesets = { "~/path/to/your/checklists" },
    })
rulesets is a list of files or directories; every .md file reachable from
each entry is scanned for fenced ```rule blocks. Each entry is expanded
(~, $VAR/${VAR}, %VAR%) before it is checked, so the ~/... form
above works as written; a path that still resolves to neither a directory
nor a readable .md file is a load error, notified rather than silently
loading zero rules.

lua_predicates (boolean, default true) decides whether lua_predicate
checks may run. A rule block body is always evaluated in an empty environment,
but a predicate is arbitrary Lua that runs later; set lua_predicates = false
to run a ruleset you did not write, and each predicate then reports error
("predicate not trusted") instead of running. A predicate also runs only in a
ruleset you named yourself (setup({ rulesets }), your vault from setup() or
$RULES_VAULT, a command line): a ruleset that a project .rules.json names, or
a vault that file names, reports error ("not run: ruleset is not trusted")
unless its folder is in trust (setup({ trust = { "~/rules" } }); headless:
--trust=<dir>, $RULES_TRUST). See docs/CONFIG.md and docs/RULESET-FORMAT.md.

SETTINGS FILES *rules-config*

Besides setup(), rulesets, gates and an agent block can come from a
.rules.json in the root being checked (the path of :Rules check/gate, else
the working directory) and from the .rules.json of a vault. Highest first:
a headless call (--ruleset, --gate, $RULES_RULESETS, $RULES_GATES), setup(),
the project file, the vault file, the defaults. rulesets is taken whole from
the highest place that names it; gates is merged by gate name; agent field
by field. lua_predicates, trust and keys are setup() options only. In a file, []
and {} are told apart: a list where an object is meant (or the reverse) is an
error, not "empty".
    {
      "rulesets": ["docs/rules", "@vault/lua"],
      "gates": { "release": ["REL"] },
      "agent": { "batch_size": 8, "scopes": { "LUA": { "include": ["lua/**"] } } },
      "vault": "../rules-vault"
    }
Paths are relative to the file that holds them. A file that is there but
cannot be used (not JSON, not an object, a value of the wrong shape, over
1 MiB) is an error naming the file and the key, never "no settings"; :Rules
check and :Rules gate stop with it. An unknown key warns, with the nearest
known key as a hint. An absolute path in a project file warns (a path of this
machine in a repository), and so do an entry outside the project folder and a
vault key (their rulesets are not trusted, see |rules-config|). A missing file
is not an error. See docs/CONFIG.md.

VAULT *rules-vault*

The rules-vault is a folder (a repository of its own) with your rulesets under
rulesets/<name>/. It is found from setup({ vault = "~/rules-vault" }),
then $RULES_VAULT, then vault in the project's .rules.json; a path is
never guessed, and no vault is not an error. With a vault, every folder under
rulesets/ is loaded (the vault's own .rules.json may narrow or extend
that), and rulesets entries of setup() or a project file may name one with
@vault/<name> instead of a path. The name in a document's source stays the
folder name (lua, native).
    local vault = require("rules.vault")
    vault.root()      -- path, or nil and a message (also for a broken vault file)
    vault.source()    -- "call" | "setup" | "env" | "project" | nil, then its problem
    vault.rulesets()  -- the folders the vault offers; {} and the problem if broken
:checkhealth rules shows the vault, where it came from, its rulesets, and
whether it is a clean git repository (read-only, no network).

|:RulesVault| opens, copies, links, searches and shows what is in the vault,
and makes one (:RulesVault create <dir>).

COMMANDS *rules-commands*

                                                                  *:Rules_check*
:Rules check [{path}]
    Runs every rule whose ID prefix matches the required |--family| flag
    against {path} (default: the current working directory). Findings go to
    the quickfix list; a readable report opens in a tab, reusing a still-
    open report window instead of piling up a new one on every run. The
    report is a throwaway buffer: it is wiped once its tab is closed or its
    window shows something else. With
    --format=json, prints JSON instead and skips the quickfix list/buffer;
    never quits Neovim, so it is safe to run interactively. For a headless
    CI run with a real exit code, call
    require("rules").check_family_json(family, path) directly — see
    docs/BINDINGS.md in the plugin's repository for the recipe.
    With --format=work-list, prints the work list |rules-work-list| instead:
    every rule of the family with its verdict, text and waiver, the manual
    ones as "unchecked".

    --family={PREFIX}     required, e.g. --family=DEP
    --format={FORMAT}     optional, "json" or "work-list"

                                                                   *:Rules_gate*
:Rules gate {name} [{path}]
    Runs every family configured for gate {name} (see |rules-gates|) as one
    combined report. --diff={ref} narrows findings to files changed since
    that git ref (tracked + untracked); a rule left with no findings inside
    the diff reports "pass"; a check that could not run stays an error.
    --format=json and --format=work-list behave like :Rules check's.

    --diff={REF}          optional, e.g. --diff=main
    --format={FORMAT}     optional, "json" or "work-list"

                                                                   *:Rules_show*
:Rules show {id}
    Jumps straight to one rule's source location by its exact id (e.g.
    :Rules show DEP-06), without running a family check. Errors, rather
    than silently doing nothing, if no loaded rule has that id.

                                                                  *:Rules_stats*
:Rules stats
    A structural overview of every loaded rule: total count, and per-family
    totals split into automated (has a check) vs. manual, plus a severity
    breakdown. No check runs — this is catalog metadata, not a pass/fail
    report; opens in a readable buffer, or prints JSON with --format=json.

    --format={FORMAT}     optional, only "json" is recognized

                                                                  *:Rules_agent*
:Rules agent [{id}] [--family={PREFIX} --manual] [--dry-run] [--yes]
             [--refresh] [--backend={ID}] [--model={NAME}]
    Asks a model, through ai.nvim, about rules that have no check, and keeps
    the answers as proposals (never as results of a check). {id} must be a
    rule without a check; --family needs --manual. --dry-run prints the plan,
    the files, their size and a token estimate and sends nothing. Before
    anything is sent the backend and the model are shown and you are asked
    (--yes skips the question, not the display; with nobody to ask and no
    --yes it refuses). The backend is --backend, else the first of
    agent.backends, else ollama; agent.backends empty means local only.
    Without ai.nvim the command says so and sends nothing. Answers are cached
    by rule, files, backend and model (--refresh asks again). See |:Rules_review|.

:Rules agent --intent={FILE} [--yes] [--backend={ID}] [--model={NAME}]
             [--family={PREFIX}] [--severity={SEVERITY}]
    Takes an intent wkd-intent/1 of another app (a finding of testing.nvim).
    rules.show opens the rule file. rules.new opens the |:Rules_new| form
    filled from the finding; in mode ai-draft a model first words the text
    (title, family, severity and the evidence reference are all it is sent;
    the destination is allowed and shown, and you are asked before it sends).
    The form asks again before anything is created.

                                                                 *:Rules_review*
:Rules review
    The proposals of this session, one block each, marked PROPOSED, with the
    status in words (violation, compliant, unclear). On the one under the
    cursor: a accept (writes .rules-verdicts.json, as g:rules_by or the user
    name), w waive a violation (asks for the reason), x discard, <CR> open
    the first finding, q close. There is no key for all of them.

                                                                *:Rules_catalog*
:Rules catalog [{path}]
    For a ruleset in the one-file-per-rule form (see |rules-ruleset-format|):
    builds the reading documents from their layouts. {path} is a ruleset
    folder (default: every folder in rulesets). A document is written only
    when its content changed. With --check nothing is written and every
    document that is out of date is reported; for CI use
    nvim --headless -u NONE -l scripts/ruleset.lua catalog --check {folder}
    (exit code 1 when one is). Rules that are in no layout are named.

    --check               optional, only report

                                                                    *:Rules_new*
:Rules new [{family} [{title}...]] [severity={level}] [text={text}]
                                  [ruleset={name}] [{place}] [--yes] [--dry]
    Makes a rule in a ruleset of the one-file-per-rule form, at the next
    free id of {family}. With the family, a title and severity= the rule
    is made, placed and opened. With less, a Markdown form opens, filled in
    with what was given (|rules-form|). The command checks nothing of a rule
    itself: it hands one operation of rules-ops/1 to the engine and tells
    the answer. --dry checks everything and writes nothing.

    In a rules-vault that lies behind its upstream (what the last git fetch
    knows) the rule is made and a warning follows: pull before you make a
    rule, or another machine may make the same id. The engine never pulls,
    fetches or commits.

    {family} is 1 to 12 uppercase letters A-Z (DEP), or a family the
    ruleset has already, spelled exactly as there (Dep-01 goes on with
    Dep-02): Fix or dep is refused, so a mistyped title does not make
    a family. A family that no
    rule has yet is asked about before the first rule is made (--yes skips
    the question).

    A key= word may stand before the family (it takes one word); the
    family is the first word that is no known key=. A value is taken
    from the line as typed (runs of blanks and backslashes stay). A word
    with two dashes is a flag, also inside a value. A bare -- ends the
    flags only right behind the first word (the family, the id) or in
    front of a word that starts with a dash, so `text=run with -- --dry
    now is the text run with --dry now (the --` is not part of it);
    anywhere else it is text, kept: text=Use this -- not that --dry is a
    dry run of Use this -- not that.

    {place} is one of
    --to={file}#{section}   layout (its output path) and heading text; write
                            a blank in the heading as \ ; {file} alone is
                            the top of the layout
    --after={id}            right after that rule, in the layout that holds it
    --before={id}           right before that rule
    --first                 with --to: the start of the section, not its end
                            (a section with no rule yet: behind its intro)

                                                                    *:Rules_set*
:Rules set {id} {key}={value}... [--dry]
    Changes parts of a rule's file; every line it was not asked to change
    stays byte for byte (a check= leaves the agent of the block as it is, and
    the other way round). Keys: severity, title, text, check, agent. A value may hold
    spaces (a word that is no known key= goes on with the value before
    it). check= and agent= take a JSON object, or nothing to remove the key.
    An open buffer of the file is reloaded; one with unsaved changes is
    reported as a conflict and left as it is. --dry shows the change as a
    diff.

                                                                 *:Rules_retire*
:Rules retire {id} [--by={id}] [reason={text}] [--yes] [--dry]
    Moves the rule's file to _retired/ and out of every layout; the id
    stays taken. Asks first (--yes skips the question; a session without a
    screen needs it). The engine is asked with a dry run before the
    question, so a rule that is not there is told without one. --by names
    the rule that takes its place. |:Rules_reinstate| brings it back, and
    the message names the command: `put it back with :Rules reinstate
    DEP-03`. The retired file keeps where the rule stood (in every
    layout), and a reinstate without a place takes it; a place that no
    longer fits is told and the rule comes back in no layout.

                                                              *:Rules_reinstate*
:Rules reinstate {id} [--after={id} | --before={id} | --section={heading}
                      [--first]] [--layout={file}] [--yes] [--dry]
    Brings a retired rule back: its file returns from _retired/ and the
    id is in use again (reinstate of rules-ops/1, nothing else). Asks
    first (--yes skips the question; a session without a screen needs it);
    the engine is asked with a dry run before the question, so an id that
    is not retired or a place that does not exist is told without one, in
    the engine's own words. <Tab> offers the retired ids only.

    The place puts the rule into a layout: --after / --before in the layout
    that holds that rule (--layout names it when several do), --section with
    --layout (--first: the start of the section, not its end; write a blank
    in the heading as \ ). It is handed to the engine as typed. Without a
    place the command does not guess one: where the rule stood is not
    recorded on disk, so it comes back in no layout, the question and the
    message say so, and |:Rules_move| puts it in one. Open buffers of the
    layout and of the rule's file are reloaded; one with unsaved changes is
    reported as a conflict and left as it is.

                                                                   *:Rules_move*
:Rules move {id} {place} [--dry]
    Moves the rule's {{rule ID}} line within its layout or into another;
    the rule's own file is not touched. {place} as in |:Rules_new|, one is
    required.

                                                                   *:Rules_list*
:Rules list [--family={PREFIX}] [--severity={level}] [--format=json]
    Puts the rules in the quickfix list, each at its source line. With
    --format=json prints the rules.list document of the machine contract.

                                                                  *:Rules_waive*
:Rules waive {id} reason={text} [expires={YYYY-MM-DD}] [paths={a,b}]
                  [--project={dir}] [--dry]
    Accepts the findings of a rule in this project: a waiver in the project's
    .rules-waivers.json (|rules-waivers|), through waive of rules-ops/1
    and nothing else. reason= is required and may hold spaces (a word that is
    no known key= goes on with the value before it). expires= is the last
    day the waiver counts; a date in the past is written, with a warning (the
    waiver is expired from the start). paths= limits it to those files,
    folders or globs, separated by commas without spaces around them (a blank
    inside a path is part of it, a comma inside braces belongs to a glob:
    paths=src/legacy,docs/**/*.{md,txt}). The engine checks everything and
    answers in its own words: an id no rule has, a waiver that is there
    already (|:Rules_renew| changes it), a path with ... A word after a
    value that nearly is a key (expire=, path=, reasons=) is refused,
    not made part of the reason. <Tab> offers the
    ids of the loaded rules; expires= has no completion, its help names today.
    --dry checks and shows the file that would be written.

    The project is, in this order: --project={dir} (relative to the working
    directory; <Tab> offers folders, a blank is written \ ); the nearest
    folder above the current buffer's file that has a .rules-waivers.json,
    a .rules.json or a .git, when it lies below the working directory;
    else the working directory, whose waivers :Rules check reads. A folder
    outside the working directory is never chosen, and the engine refuses one
    that is named. The message names the file that was written. An open
    buffer of the waivers file is reloaded; one with unsaved changes is
    reported as a conflict and left as it is.

                                                                  *:Rules_renew*
:Rules renew {id} [expires={YYYY-MM-DD} | --no-expiry] [reason={text}]
                  [--project={dir}] [--dry]
    Gives a waiver a new last day (or, with --no-expiry, none) and, with
    reason=, a new reason; its paths stay. This is the way on for a waiver
    that expired, as :Rules check says. The engine wants one of expires= and
    --no-expiry. <Tab> offers the ids that have a waiver in the project. The
    project and the buffers are as for |:Rules_waive|.

                                                                *:Rules_unwaive*
:Rules unwaive {id} [--project={dir}] [--yes] [--dry]
    Removes a waiver: the findings it accepted flag again. Asks first and
    shows the waiver (--yes skips the question; a session without a screen
    needs it); the engine is asked with a dry run before the question, so an
    id without a waiver is told without one. <Tab> offers the ids that have a
    waiver. The project and the buffers are as for |:Rules_waive|.

                                                                   *:RulesVault*
:RulesVault {verb} [{ruleset}|{id}|{family}] [{part}]
    Navigates to where the rules are, like :TasksVault does for tasks. It
    reads and points; it writes nothing but the scaffold of create. A rule
    is made by |:Rules_new|, so there is no new and no paste. The vault is
    found as |rules-vault| says; without one every verb but create says so
    once. A word is read as a ruleset of the vault (its folder name), a part,
    a rule id or a family, in that order; <Tab> offers all of them. {part}
    is one of
    rules                   the rule files, _rules/ (default)
    layouts                 _layouts/
    catalogs                the generated reading documents
    all                     the ruleset folder
    Without a word the ruleset is the one of the current buffer, the only
    one, or a pick. A rule id or a family has no part.

    open                    a rule file (a retired rule too), the folder of a
                            family, or a part of a ruleset
    clipboard               the path to the + register; --rel relative to the
                            current file; --link as [DEP-06](path)
    link                    a Markdown link at the cursor, relative to the
                            current file
    find, grep              a pickers.nvim picker in the ruleset (for an id:
                            searching for the id), the family or the part
    tree                    the ruleset as a tree, family then rules, counts
                            per family, retired rules marked [retired]
    cdx                     a prompt for an agent session to the + register
    create [{dir}] [{name}] a vault: README.md, .rules.json,
                            .gitattributes, .gitignore, the CI workflow and a
                            first ruleset (default name default). Lists
                            first what happens and the step that is left to
                            you (set vault in setup() or $RULES_VAULT: it
                            is marked REQUIRED), then asks. A file that is
                            there is never overwritten; no remote is ever
                            added.

    --git                   create: run git init (only then)
    --yes                   create: skip the question (needed without a screen)
    --force                 create: make a vault although one is in use
    --rel                   clipboard, cdx: relative to the current file
    --link                  clipboard: a Markdown link

                                                                    *rules-form*

THE FORM OF :Rules new

A Markdown buffer (rules://rule-new) with the lines Family, Title, an
optional Ruleset and Place, a list of severities and, below ## text, the
prose of the rule. Family, Title and one severity are required.

    <Space>, <CR>   tick or untick the severity under the cursor (one tick)
    <C-s>           check the form (what is missing is listed at the top as
                    ! lines), ask the engine with a dry run, show what
                    would be made and ask; only "Create the rule" writes
    q, <C-q>        cancel; asks first when something was typed
    g?              help

These are the defaults. setup({ keys = { form = { ... } } }) changes them,
by action: toggle (<Space>), accept (<CR>), submit (<C-s>, normal and
insert mode), close (q), cancel (<C-q>, normal and insert mode) and help
(g?). An action takes a key, a list of keys (all are bound) or false (no
key); one that is not named keeps its default:
    require("rules").setup({
      keys = { form = { submit = "<C-g>", toggle = { "<Space>", "x" }, help = false } },
    })
The hint under the title and g? show the keys that are bound. An action or a
group this plugin does not have, a value of the wrong type and two actions on
one key are warned about by setup(), never ignored silently. keys is a
setup() option only; in a .rules.json it is an unknown key. See
docs/CONFIG.md.

GATES *rules-gates*

A gate is a named bundle of rule families, run together as one report — the
one place in this plugin that checks more than one family at once. No gates
are bundled; define them in setup():
    require("rules").setup({
      gates = {
        release = { "REL" },
        review = { "ERR", "LUA", "PRIN" },
      },
    })
See docs/BINDINGS.md in the plugin's repository for the --diff scoping
semantics in detail. A configured family that matches zero loaded rules
(a typo, or a family not yet migrated to fenced rule blocks) warns rather
than silently running a smaller gate than configured.

WAIVERS *rules-waivers*

A .rules-waivers.json at the checked root records consciously accepted
findings so a re-run doesn't keep flagging them:
    { "DEP-04": "legacy call site, ticket JIRA-123 tracks the actual fix" }
A waived rule that would otherwise fail or error reports as "waived"
instead of "fail" — visible in the buffer report with its reason, excluded
from the quickfix worklist, and never counted by check_family_json's exit
code. See docs/BINDINGS.md in the plugin's repository for detail.

A waiver can also be an object with an expiry and a scope:
    { "DEP-04": { "reason": "legacy", "expires": "2026-12-31",
                "paths": ["src/legacy", "docs/**/*.md"] } }
It counts through its expires day (YYYY-MM-DD); the day after, the finding
flags again and the report says the waiver expired. paths limit it to
findings in those files or folders. A waivers file that cannot be used is an
error of the run, never "no waivers". The format is in docs/CONFIG.md, the
write operations (waive, renew, remove) in docs/CONTRACT.md. In the editor
|:Rules_waive|, |:Rules_renew| and |:Rules_unwaive| write the file through
them; a run that finds expired waivers names the last two.

:checkhealth rules cross-checks the current working directory's waivers
against every loaded rule and warns about an orphaned entry — a waiver
whose rule id was retired or mistyped, which would otherwise sit silently
protecting nothing.

WORK LIST *rules-work-list*

:Rules check --family={PREFIX} --format=work-list and `:Rules gate {name}
--format=work-list print the work list rules-work-list/1`: a versioned
JSON document a task tool turns into tasks without reading a rule file.
Headless, with the exit code of |:Rules_check|'s JSON:
    local json, code, doc, err =
      require("rules").check_family_work_list("ERR", vim.fn.getcwd())
    -- require("rules").run_gate_work_list(name, path, diff_ref)
The head carries schema ("rules-work-list"), schema_version,
generated_at, rulesets (name, source), target (path, commit) and
scope (the family, or the gate with its families). Every rule of the run
is one entry: rule_id, family, severity, kind ("automated" or
"manual"), status ("pass", "fail", "waived" or "unchecked"), title,
section, description, source, findings (file, line, text) and
waiver (reason, expires, paths; suppressed for a waiver limited to
paths, expired for one that ran out). A manual rule is "unchecked", never
a pass; a check that could not run is "unchecked" with its error. The
schema in full is docs/WORK-LIST.md in the plugin's repository.

RULESET FORMAT *rules-ruleset-format*

See docs/RULESET-FORMAT.md in the plugin's repository for the full format —
this is the reference for a Lua project's own :h request, not a duplicate
of that document's detail.

A rule is a Markdown section with a fenced ```rule code block:
    ### `DEP-06` — `vim.tbl_flatten()` is deprecated

    ```rule
    id = "DEP-06",
    severity = "recommended",
    check = { type = "grep", pattern = "vim%.tbl_flatten%(" },
    ```
check is optional. A rule without one is never given an automatic
pass/fail — it appears as a worklist entry instead.

A rule can also be a file of its own: a frontmatter with id and severity
(and optionally family), then the rule as it reads; a ```rule block only
when the rule has a check or an agent, and then without the two identity
lines. The reading documents are generated from layouts (|:Rules_catalog|), and
scripts/ruleset.lua migrate converts a ruleset of documents into that form.
Both forms load side by side. See docs/RULESET-FORMAT.md.