Concepts
Custom Rules
Author repository-specific architecture rules in Python using Fensu's public analysis API.
Custom rules turn repository-specific conventions into executable checks that run
alongside core and pack rules in fensu check, fensu rule, and fensu skills.
Agent-assisted authoring
Section titled “Agent-assisted authoring”Describe the contract with passing and failing examples, and let a coding agent implement and test the rule against Fensu’s public API:
Add a custom Fensu rule that flags a module-level variable named GLOBAL_CLIENTand references to it. The text "GLOBAL_CLIENT" inside a string and unrelated localvariables should not fault. Add tests and run the rule against the repository.Review the contract and boundary tests rather than traversal mechanics: verify
faults point at the right syntax, legitimate near-misses pass, project queries
go through ctx.project, and output is deterministic.
The shape of a rule
Section titled “The shape of a rule”A custom rule is a Python function decorated with @rule. The decorator enforces
a mandatory metadata envelope; the body can be any Python you need:
from __future__ import annotations
import ast
from fensu import Family, Fault, File, RuleContext, rule
@rule( code="X001", family=Family.CUSTOM, slug="no-global-client", message="GLOBAL_CLIENT hides ownership", remediation="Move the value to the module that owns and produces it.",)def no_global_client(*, file: File, ctx: RuleContext) -> list[Fault]: return [ ctx.fault(node=node) for node in ctx.nodes(ast.Name) if isinstance(node, ast.Name) and node.id == "GLOBAL_CLIENT" ]The public API
Section titled “The public API”Import all rule-authoring types, analysis protocols, and test-harness helpers
from the top-level fensu package. Never import from fensu.analysis or other
internal modules.
from fensu import ( Family, Fault, RuleCase, RuleContext, RuleFile, RuleOption, RuleResult, Severity, Threshold, evaluate_rule, rule,)The @rule decorator
Section titled “The @rule decorator”def rule( *, code: str, family: Family | str, slug: str, message: str, remediation: str | None = None, severity: Severity = Severity.ERROR, enabled_by_default: bool = True, options: tuple[RuleOption[object], ...] = (),) -> Callable[[RuleCheck], RuleCheck]: ...| Field | Required | Purpose |
|---|---|---|
code | yes | Permanent identifier; see codes and namespaces. |
family | yes | A Family member; use Family.CUSTOM for project rules. |
slug | yes | Short kebab-case name. |
message | yes | One-sentence statement of the violated contract. |
remediation | no | Correction shown as = help:. |
severity | no | Severity.ERROR (default) or Severity.WARNING. |
enabled_by_default | no | Set False for an opt-in rule enabled only by exact code. |
options | no | Typed options readable via ctx.option(). |
Codes and namespaces
Section titled “Codes and namespaces”Custom codes match X, optional uppercase letters, and one or more digits
(X001, XAC001, XDB042). Core (FF*) and pack (FP*) prefixes are
rejected at load. Because selectors match
prefixes, namespaces nest cleanly (X → XD → XDB → XDB001).
Typed check subjects
Section titled “Typed check subjects”Choose a callback subject matching the scope your rule checks:
| Subject | Signature | Runs |
|---|---|---|
| File | def check(*, file: File, ctx: RuleContext) -> list[Fault] | Once per evaluated source file. |
| Project | def check(*, project: Project, ctx: RuleContext) -> list[Fault] | Once per target (even with zero source files); report via ctx.path_fault(path=...) or ctx.fault_at(location=...). |
| Repository | def check(*, repository: Repository, ctx: RuleContext) -> list[Fault] | Once during an all-target check via top-level [repository_rules]; see Repository rules. |
| Python AST | def check(*, module: ast.Module, ctx: RuleContext) -> list[Fault] | Once per Python file when direct ast.Module access is required. |
The Fault
Section titled “The Fault”Construct faults through ctx.fault(...) so code, path, line, and column are
filled automatically. The frozen dataclass is exported for return annotations:
@dataclass(frozen=True, slots=True)class Fault: code: str path: Path message: str line: int | None = None column: int | None = None remediation: str | None = NoneFamily, Severity, and Threshold
Section titled “Family, Severity, and Threshold”class Family(StrEnum): LAYERS = "layers"; ROLES = "roles"; SHAPE = "shape" NAMING = "naming"; HYGIENE = "hygiene"; TESTS = "tests" ANNOTATIONS = "annotations"; CUSTOM = "custom"
class Severity(StrEnum): ERROR = "error"; WARNING = "warning"Threshold exposes one enum member per key in
[thresholds] (for example
Threshold.MAX_STATEMENTS). Call ctx.threshold(name=Threshold.MAX_STATEMENTS)
to read the effective limit for the current file with global, role, and path
overrides already applied.
The rule context
Section titled “The rule context”RuleContext exposes current-file semantic facts, the discovered project tree,
the resolved import graph, source text, and backend-neutral syntax:
functions = ctx.facts.functions() # current-file semantic factsposition = ctx.project.tree.position(file.path) # typed layout factsimports = ctx.graph.imports(file) # resolved static importsanalysis = ctx.project.analysis(path=other_path) # cross-file analysisline = ctx.text.line(1) # source texthandles = ctx.syntax.handles(kind="Call") # opaque syntax handlesparent = ctx.relations.parent(handles[0]) # syntax relationshipsEvery ctx.project, ctx.project.tree, and ctx.graph query returns
deterministic results and records its inputs for cache invalidation. Prefer
ctx.nodes() over ast.walk(module) so rules share one scan. See the
RuleContext reference for the full API.
Typed rule options
Section titled “Typed rule options”Use RuleOption when a reusable rule needs repository-configurable values:
_ALLOWED_NAMES = RuleOption.string_list( name="allowed_names", default=(), description="Names permitted by this policy.",)
@rule( code="X001", family=Family.CUSTOM, slug="approved-names", message="name is not approved", options=(_ALLOWED_NAMES,),)def approved_names(*, file: File, ctx: RuleContext) -> list[Fault]: allowed_names: tuple[str, ...] = ctx.option(_ALLOWED_NAMES) ...Constructors: boolean, integer (minimum, maximum), string (choices),
string_list, and integer_list (minimum_items). Set required=True when no
default applies. List overrides resolve to immutable tuples. Override values in
TOML under [rule_options.<CODE>] (see
Rule options); a rule can read only
options it declares.
Where rules live
Section titled “Where rules live”Place @rule modules inside a rules/ role directory in your tooling tree,
with shared logic in sibling _helpers/ and constants in sibling constants.py:
scripts/fensu_policy/├── constants.py├── _helpers/│ └── client_ownership.py└── rules/ ├── client_ownership.py └── service_boundaries.pyName files after the policy they enforce; FFR706 rejects filenames that are
just a rule code such as xac001.py.
Loading rules
Section titled “Loading rules”Point fensu.toml at your rule files or modules and select their codes (see
Custom rule loading):
tooling = ["scripts"]rule_modules = [ "scripts.fensu_policy.rules.client_ownership", "scripts.fensu_policy.rules.service_boundaries",]select = ["FF", "X001"]Duplicate codes across core, packs, and custom rules are rejected at startup.
For Rust, TypeScript, and Svelte targets, custom rules share a 30-second default
host timeout; raise it up to 600 with custom_host_timeout_seconds on the
target table.
Testing rules
Section titled “Testing rules”Test custom rules with evaluate_rule, RuleCase, RuleFile, and RuleResult
rather than constructing internal objects. Define a local frozen wrapper in
_test_types.py so tests satisfy FFR707, FFT204, and FFT413 together:
from dataclasses import dataclass
from fensu import RuleFile
@dataclass(frozen=True)class CustomRuleTestCase: description: str path: str source: str expected_fault_count: int files: tuple[RuleFile, ...] = () scope: str = "root" scope_root: str | None = Noneimport pytest
from fensu import RuleCase, RuleResult, evaluate_rulefrom scripts.fensu_policy.rules.client_ownership import no_global_clientfrom tests.unit.scripts.fensu_policy.rules._test_types import CustomRuleTestCase
@pytest.mark.parametrize( "test_case", [ CustomRuleTestCase( description="module-level client faults", path="package/example.py", source="GLOBAL_CLIENT = object()\n", expected_fault_count=1, ), CustomRuleTestCase( description="local client passes", path="package/example.py", source="def build() -> object:\n return object()\n", expected_fault_count=0, ), ], ids=lambda case: case.description,)def test_given_source_when_evaluating_then_matches_contract( test_case: CustomRuleTestCase,) -> None: result: RuleResult = evaluate_rule( rule=no_global_client, test_case=RuleCase( description=test_case.description, path=test_case.path, source=test_case.source, expected_fault_count=test_case.expected_fault_count, files=test_case.files, scope=test_case.scope, scope_root=test_case.scope_root, ), )
assert result.fault_count == test_case.expected_fault_countRuleCase accepts path, scope (root, test, or tooling), scope_root,
supporting files (RuleFile context entries), rule_options, and a config
fragment (contracts, roles, rule_exceptions, rule_ignores,
threshold_overrides, thresholds). RuleResult exposes faults,
dependencies, and fault_count.
FFR707 requires at least min_custom_rule_test_cases (default 1, 0
disables) statically visible RuleCase instances in a pytest.mark.parametrize
list calling evaluate_rule.
Keeping custom rules cacheable
Section titled “Keeping custom rules cacheable”Selecting any custom rule disables fensu check caching by
default because arbitrary Python can read untracked inputs. Set
require_cacheable = true in [cache] to keep
runs cached by verifying every selected custom rule at startup.
A cacheable rule module must:
- Import only pure standard-library modules (
ast,re,dataclasses,typing,collections,enum,functools,itertools,pathlibfor lexical operations),fensu, and configured rule packages (rule_modules). - Never call
open,eval,exec,input, or__import__. - Never read the filesystem directly; use
ctx.project,ctx.project.tree,ctx.graph, andctx.option(), which automatically record inputs for cache invalidation.
Violations fail at startup with the file, line, and reason. Keep helpers in
sibling _helpers/ and constants in sibling constants.py rather than under
rules/ (FFR704).
Selecting and inspecting
Section titled “Selecting and inspecting”Configured custom rules appear in fensu check, fensu rule, and
fensu skills:
fensu rule X001X001 no-global-clientFamily: customSeverity: errorKind: customEnabled by default: yesSource: scripts/fensu_policy/rules/client_ownership.pyMessage: GLOBAL_CLIENT hides ownershipRemediation: Move the value to the module that owns and produces it.