# Draft rulecast rules from a project's docs Use this when asked to draft rulecast rules for a project from a document, usually `AGENTS.md` or `CLAUDE.md`. Every convention in the doc that code can visibly break gets a drafted rule for the developer to keep, edit or drop: one that catches the break and points back at the doc. Load these when you need them. Relative links resolve against this file's own URL. - [reference/rule-format.md](reference/rule-format.md): config and rule keys. - [reference/detectors.md](reference/detectors.md): the detectors this rulecast version has, their config and template variables. Commands below say `rulecast`. If `rulecast` is not on the PATH, use `npx @syv-ai/rulecast`. The steps ask the developer to decide several things, and the developer is there to decide them. Ask, and wait for the answer. If you were told to work without the developer, stop and say why: rulecast enforces conventions the developer chose, and nobody else can choose them. ## 1. Read 1. Read the doc you were pointed at in full. If it says its conventions live elsewhere (`AGENTS.md` saying "see `docs/conventions.md`"), read that doc too and draft from it: the rules cite the sections that hold the conventions, not the pointer. If the doc has no conventions, only commands and architecture, stop: work them out with the developer first, through [CONVENTIONS.md](CONVENTIONS.md). 2. Find the `.rulecast-config.yaml` files above the files the doc talks about. A repository can have one at the top, one per package, or both, and each applies to the files below it on its own. If there is none, stop and set rulecast up with the developer first ([SETUP.md](SETUP.md)). Choose with the developer which config each rule goes in: one about a package in that package's config, one for the whole repository in the top one. Read each config you will use, and run `rulecast list` in its directory. Its first lines say where new conventions are written (the config's `conventions`) and whether llm rules are allowed (`llm.model`). It prints every configured rule, catalog rules included: its `files` and how many project files they match, what its detector looks for (`detects …`), and the doc sections it cites. `rulecast list ` prints one rule with the files it matches, its message and the text of those sections. You need both for the catalog rules in step 2. 3. For each convention, read a few of the files it talks about, so your file and code patterns match the code as it is. 4. When revising a project's existing rules, read `rulecast stats --format json` first (its shape is in [reference/stats.md](reference/stats.md#rulecast-stats)): a rule listed as `noisy` needs a clearer message or a tighter pattern; one in `neverRan` may have a `files` pattern that matches nothing; one in `neverFired` with many `runs` may not be worth keeping, unless it locks in a replacement (section 2), where staying quiet means the lock is working; and one in `stopBlocks` whose block rate climbs with the number of files is sometimes wrong. Before changing the pattern of a rule with `recurringFiles` in `weekly`, read those files: they may hold code the agent keeps copying, or be files the rule is wrong for. ## 2. Sort the conventions - **Checkable**: a break is visible in one file's path or text. "Never edit `src/client/`", "services never raise `HTTPException`", "no `print(` in the backend". - **Guidance**: true and useful, but not visible as a pattern. "Keep services small", "test RBAC both ways". - **Not about code**: commands, deployment, process. No rule for these. Three kinds need care: - **Partly checkable**: one part is visible as a pattern and the rest is not. "Keep services small and free of framework types": a `fastapi` import in a service is visible, "small" is not. Draft a pattern rule for the visible part and a touch rule for the rest, both citing the same section. - **Something must be present**: "every module gets its logger with `logging.getLogger(__name__)`". A detector reports what is in a file, so it cannot see a missing line without firing on every file that lacks it, `__init__.py` included. Check the wrong form instead, if there is one (a logger with another name), and let a touch rule deliver the rest. Scope that touch rule to the files the convention is about, and exclude files that are empty by design, such as `__init__.py`. - **Something is being replaced**: "use `apiClient`, not `fetch`", "new screens use the design system, not `legacy/ui`". Agents copy what they find, and the old form is still in the code, so check the old form: the rule is the lock that keeps it from spreading again. It cites the section or decision record that explains the move, and its message names the replacement. If the doc names only the new form, ask the developer what it replaces, and propose a line in the doc that says so before drafting the rule. Existing uses are backlog: hooks show them and never fail on them, so in step 3 this is the one rule that may flag more than half the files it matches (step 6 there). Touch rules go one per area, not one per section: a single rule whose `files` is the area (`^app/services/`). Its `context` lists the one or two sections agents most often get wrong there, not every section that applies. The first open of a file sends the context of every touch rule that matches it, and what does not fit in one message is only named, for the agent to read. Principles that hold across the codebase belong in the agent doc, which is read at the start of every session, not in a touch rule. Two touch rules on the same files deliver twice as many reminders for the same reading. After drafting, `rulecast doctor` warns about any file whose touch context does not fit in one message. **Catalog rules** (the rules `rulecast list` shows from a URL repo) were written for projects in general. For each one, answer two questions, separately. A rule can need a change for both. 1. **Which section should it cite?** If the project's doc has a section that states the same convention, point the rule at it with a `context` override and change nothing else. The developer's own words beat the package's, even when they agree. A section about the same area is not enough: a section on how to raise errors does not state a rule against swallowing them. A rule you propose to switch off (question 2) keeps its context: pointing it at a section that contradicts it would make it cite the opposite of what it checks. ```yaml - repo: https://github.com/syv-ai/rulecast rev: v0.20.1 # unchanged: keep the entry as init wrote it rules: - id: python/no-silent-except context: - "@AGENTS.md#errors" ``` 2. **Does the project want this check?** The catalog holds only language- and tool-level checks. Read the section the rule cites with `rulecast list `, and compare what it checks (its `detects` line) with the doc and with the files it matches: - **It fits:** nothing more to do. A convention it already enforces needs no local rule. - **It looks in the wrong place**: it misses files the convention covers, or matches files the project treats differently, such as generated code kept where `generated-code` does not look. Tell the developer what it misses or wrongly matches, and propose a way to cover it: `files` or `exclude` on its entry, or a local rule. The developer decides. - **It contradicts the doc**: its cited section says the opposite of the doc, or the developer does not want it. Leave it unchanged, tell the developer why, and propose `enabled: false` on its entry. Add it only if they agree. - **You can't tell**: treat it as a contradiction and propose. Proposing costs nothing, because the developer decides; staying silent hides the question. **Before drafting a checkable convention, look in the catalog.** `rulecast list --catalog` lists its rules, with what each detects and how many of the project's files it matches; `rulecast list --catalog ` shows one in full. If one enforces the convention, offer it to the developer instead of a new rule, and with their agreement run `rulecast add ` in the config's directory, then point its `context` at the project's section (question 1 above). For checkable conventions, use `path` when the file itself is the break. Otherwise use the first of these that can see the break: 1. **`linter`**: a rule of a linter the project runs, or could run (ruff, oxlint, eslint). The linter already knows the language. A linter the project does not run yet has to be installed first: propose that to the developer as a change of its own, and install it only with their approval. When a lint rule the project's config already makes an error enforces the convention, and the config has a `linter` rule for that tool with no `rules` list, the convention is one `context_by_rule` entry on that rule (`eqeqeq: "@docs/conventions.md#comparisons"`), not a new rule. 2. **`command`** or **`hook`**: a tool the project already runs that checks the convention — a type checker, a dead-code finder, a hook in `.pre-commit-config.yaml`, `lefthook.yml` or `hk.pkl`. The tool already knows the code. [reference/tool-recipes.md](reference/tool-recipes.md) has a tested block for each common one. 3. **`ast-grep`**: a pattern over the code's syntax, which never matches inside a comment or a string. 4. **`regex`**: only for a pattern that is text rather than code, such as a comment marker, the content of a string or a file header. Write the narrowest pattern that catches the break: a noisy rule gets ignored. **Do not decide up front that a convention needs an `llm` rule.** Whether a convention needs `llm` depends on how it is worded, so it can't be decided by reading it: attempt a pattern, measure it (step 3), and fall back to `llm` only when the pattern fails. **An `llm` rule needs the developer's agreement first.** `llm.model` in the config you draft into says they gave it: `rulecast list` in that config's directory says `llm rules: allowed` or `not allowed`. Without it, never draft an `llm` rule. When a convention needs one, say so, and ask whether to allow llm rules (it costs money per file, and the file goes to the model's provider). With a yes, add `llm:` with the `model` they choose to that config; otherwise make the convention a touch rule. The model is the developer's choice, never yours: tell them what each can do and let them pick. Haiku is cheap but only reliable on simple, clear questions, such as "is this prose change in `conventions/` in the past tense?". A rule that judges design, or asks whether something in the change is new, needs Sonnet or stronger: on Haiku such a rule failed its own examples every time, which reads as "no findings". A drafted `llm` rule leaves out `model`, so it runs on `llm.model`, unless the developer wants another model for it. Test an `llm` rule with `rulecast test --runs 5`: one passing run says little about a model, and a rule that fails any run fails. ## 3. Draft one rule at a time For each checkable convention, one at a time. When the doc can be read two ways, flag only what both readings call wrong, and name the rest in the summary so the developer can tighten it. "Every module gets its logger with `log = logging.getLogger(__name__)`; no other logger names": `logging.getLogger("users")` is wrong whichever way you read it, so the rule flags it; `logger = logging.getLogger(__name__)` is wrong only if "logger names" means the variable, so the rule leaves it and the summary asks. 1. Show the developer the rule as YAML and the doc section it enforces, and ask to add it to the config so it can be measured (steps 4 to 6 need it there). A dropped rule comes out again (step 7). 2. Add it to the `rules` of the `repo: local` entry in the config chosen for it (section 1), and run the commands below in that config's directory. Add that entry at the end of `repos` if there is none: ```yaml - repo: local rules: - id: backend/no-print name: Backend code logs instead of printing files: ^backend/.*\.py$ exclude: ^backend/tests/ detect: regex: pattern: '^[ \t]*print\(' flags: m message: "{{file}}:{{line}} prints. Use the logger instead." context: - "@AGENTS.md#logging" ``` - `id`: lowercase `area/name`, unique in the config. - `files`: a regex searched in the repo-relative path. Anchor it with `^` so it matches the directory you mean. - `message`: what is wrong at `{{file}}:{{line}}` and what to do instead, in one or two sentences. - `context`: the doc section the rule enforces, as `@#`. The slug is the heading in lowercase, punctuation dropped, spaces turned into `-`. 3. Give it `examples`: two `good`, two `bad` and one `baseline`, no two the same. Each `good` and `bad` example is a `path` the rule matches and the `code` at it. - Quote real code first. Search the files the rule matches for an actual violation to use as `bad` and compliant code for `good`; a violation the repository already has is the best `bad` example there is. - Where it has none, which is usual in a small or clean repository, write your own: the smallest code that shows the break for `bad`, and for `good` a near miss, code that looks like the break and is not. Invented examples are fine. Say which ones are invented in the summary. - A `path` rule judges the file name, not its code: give it `bad` examples only, at paths the rule must refuse. - Every `bad` example gets `expect: { lines: [...] }`: the line each match starts on, counted from 1 (line 1 for a finding about the whole file). Without it, a pattern that fires on the wrong line still passes. - The `baseline` example is an edit: `before` has one violation inside a function or other block, and `after` adds an unrelated line in that same block, next to the violation but not on it, and a second violation. It expects the old violation, on the line it moved to, as `preexisting`, and the added one as `new`. It catches a rule that reports code the edit did not touch as the edit's: a pattern that spans lines, an `ast-grep` match on a whole function, a `scope: container` rule. - Three kinds of rule have no baseline example to give, so skip it for them. A `path` rule: the file is either the break or it is not. An `llm` rule: it only reports lines the edit changed, so the old violation is never reported at all. A `hook` rule whose findings are about the whole file (line 1, as a formatter's are): any edit to the file makes it new. ```yaml examples: good: - path: backend/app/services/users.py code: | log.info("created user %s", user.id) bad: - path: backend/app/services/users.py code: | user = create(name) print("created user", user.id) expect: { lines: [2] } baseline: - path: backend/app/services/users.py before: | def create_user(name): user = create(name) print("created user", user.id) return user after: | def create_user(name): user = create(name) user.save() print("created user", user.id) print("saved") return user expect: { new: [5], preexisting: [4] } ``` 4. Run `rulecast validate` and fix every diagnostic for your rule. An `expect` line past the end of its example is one of them. 5. Run `rulecast test --format json`. The rule passes this gate when its `status` is `passed`. Otherwise each failing outcome's `failures` says why ([reference/output.md](reference/output.md#rulecast-test) has the fields). - A `bad` example with no finding means the pattern is too narrow. A `good` example that fires, or a `bad` one that fires on a line it does not expect, means it is too broad. - A `baseline` example whose old violation comes out `new` means the rule reports code the edit did not touch: a pattern that spans more lines than the violation, or a rule that needs `scope: container`. - A `regex` pattern also matches inside comments and strings. If the only hits it finds in the code are prose — a comment that names `process.env` — that is a slip: use `ast-grep`, which matches code, not text. - A slip is not a revision: a typo, a missing escape, or `\s` crossing a line break (`rulecast test` shows what a failing example matched, and says when it crossed a line). Fix slips as often as you find them. - Revise what the pattern *means* — what it accepts and refuses — **once**. If it still fails, move the rule to an `llm` detector (if the developer allows llm rules, as step 2 says), write its question as [reference/detectors.md](reference/detectors.md#writing-the-question) says, and say in its `description` that a pattern was tried. Do not keep tightening a regex past one attempt: that is how a rule ends up fitting its examples and nothing else. 6. Run `rulecast test --against . --max-rate 0.5 --format json` (without the id it measures every rule, for checking a whole config at once). The rule's own `files` and `exclude` decide which files count, so `.` is right for every rule. - **Exit 1, `against.exceeded: true`**: the rule flags more than half the files it matches. Do not propose it as written. Tell the developer it may describe the code as it is rather than a convention, and propose a narrower `files`, or a touch rule instead. The exception is a rule that locks in a replacement (step 2): there the count is the migration still to do. Report it as backlog, point the developer to `rulecast run --all-files --summary`, and let them decide. - **`against.smallSample: true`**: under 25 matching files, the rate is not applied, because a share of a handful of files says nothing. Report the counts and judge the rule by its doc. - Either way, report both numbers to the developer — `violations`, and `violatingFiles` of `matchingFiles` — before asking them to keep it. Passing the gate is necessary, not sufficient: neither the numbers nor the gate decide it. The developer does. - **An `llm` rule, or a rule about a change rather than a whole file**, is measured on history instead: `rulecast test --history --max-rate 0.5 --format json`. It judges the rule on recent commits the way a session judges an edit, so only what each commit added counts. An `llm` rule costs one model call per file per commit: the first run prints `estimate` and runs nothing. Tell the developer the number of calls, and run it again with `--yes` only if they agree. Add `--label`, and go through `history.findings` with the developer, marking each `real` or `false` in the label file it names. Run it again for the precision. Offer the findings marked `real` as `examples.bad`, and add none the developer did not agree to. - An `llm` rule starts as `severity: warning`, which never blocks a stop. Propose `error` only when the developer has seen its measured precision and accepts it: a rule that is sometimes wrong gets one more chance to block with every file the agent changed. - **When the developer can name faults a rule should have caught**, such as commits a reviewer sent back, test the rule on them too. For each fault, a commit `F` that introduced it and a commit `X` that fixed it: `rulecast run --from-ref F^ --to-ref F` must report it, `rulecast run --from-ref X^ --to-ref X` must not, and `rulecast test --history --commits 80` should fire on nothing but the faults themselves. Report the three results per fault. A rule that fails any of them is not ready, whatever its examples say. 7. Ask the developer to keep, edit or drop the rule. After an edit, repeat steps 4 to 6. Remove dropped rules from the config. For each guidance convention, add a touch rule. It delivers the section the first time an agent reads or edits a matching file, and has no detector or message: ```yaml - id: backend/services name: Service layer conventions files: ^backend/app/services/ stages: [touch] context: - "@AGENTS.md#services" ``` Validate it the same way. A touch rule has no detector, so it takes no `examples` and `rulecast test` has nothing to run for it: skip steps 3, 5 and 6. ## 4. Finish Run `rulecast validate` and `rulecast test --format json` a last time; `validate` must be clean and the document must say `passed: true`. Bare `rulecast test` does not run `llm` rules, because each example costs money, and gives them `status: not-run`: run `rulecast test --format json` for each of those. Every convention you read ends in one of four places: a rule that checks it, a touch rule that delivers it, not about code, or skipped. For each one that no rule checks or delivers, propose a `not_checked` entry in the config you would have drafted its rule in: the section that states it, and the reason in a few words. ```yaml not_checked: - context: "@AGENTS.md#reviews" reason: about how to work, not about the code ``` Other reasons: `needs the whole repository, not one file`, `the type checker already rejects it`. `rulecast list` prints these entries, so a later session sees the convention was considered and why it has no rule, and does not ask again. Write nothing about it in the project's docs. Show the entries with the rest of the diff, and run `rulecast validate`, which reports an entry whose section is missing; the developer keeps or removes them. A convention the developer turned down belongs in the `declined.md` next to the conventions instead ([CONVENTIONS.md](CONVENTIONS.md)), not here. The agent doc (`AGENTS.md` or `CLAUDE.md`) is read at the start of every session, and every line in it competes for the agent's attention. A rule's `context` reaches the agent only when the rule fires, or, for a touch rule, when a matching file is first touched. So when a rule now checks or delivers a section that sits in the agent doc, propose moving that section to where the config's `conventions` points, and repointing the rule's `context` there. If `conventions` is not set, or is the agent doc itself, ask the developer where the section should go; with no other doc, leave it where it is. Leave at most one line in the agent doc if the developer wants one. Move the section; never copy it, because two copies drift apart. Show the move with the rest of the diff, and say what it costs: a section a rule only checks reaches the agent after the convention has been broken, and an agent without rulecast's hooks never sees it. The developer decides. Then summarise: - how many conventions ended up in each of the four places, so a session with few rules is not read as one where every convention is checked; - the rules kept: id, one line each, and the `--against` or `--history` counts, with the precision where findings were marked (touch rules have no count); - where the doc could be read two ways, and the reading you chose; - the rules dropped; - the catalog rules you pointed at the project's doc, propose to cover differently, or propose to switch off, and why; - the examples you invented; - the conventions you skipped, with the reason, and the `not_checked` entries you proposed. ## Never - Never change rules or overrides under other `repos` entries, except to add a `context` override to a catalog rule, or `files`, `exclude` or `enabled: false` when the developer agrees (step 2). Everything else goes in the `repo: local` entry. - Never add a `rulecast-ignore` comment or `enabled: false` unless the developer agrees the finding or the rule is wrong. - Never change code to make a rule pass. Report findings; the developer decides. - Never take a decision these steps give to the developer, or a default in their place. - Never draft a rule for a convention the doc does not state. - Never commit.