Skip to content

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.

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_CLIENT
and references to it. The text "GLOBAL_CLIENT" inside a string and unrelated local
variables 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.

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"
]

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,
)
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]: ...
FieldRequiredPurpose
codeyesPermanent identifier; see codes and namespaces.
familyyesA Family member; use Family.CUSTOM for project rules.
slugyesShort kebab-case name.
messageyesOne-sentence statement of the violated contract.
remediationnoCorrection shown as = help:.
severitynoSeverity.ERROR (default) or Severity.WARNING.
enabled_by_defaultnoSet False for an opt-in rule enabled only by exact code.
optionsnoTyped options readable via ctx.option().

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).

Choose a callback subject matching the scope your rule checks:

SubjectSignatureRuns
Filedef check(*, file: File, ctx: RuleContext) -> list[Fault]Once per evaluated source file.
Projectdef 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=...).
Repositorydef check(*, repository: Repository, ctx: RuleContext) -> list[Fault]Once during an all-target check via top-level [repository_rules]; see Repository rules.
Python ASTdef check(*, module: ast.Module, ctx: RuleContext) -> list[Fault]Once per Python file when direct ast.Module access is required.

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 = None
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.

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 facts
position = ctx.project.tree.position(file.path) # typed layout facts
imports = ctx.graph.imports(file) # resolved static imports
analysis = ctx.project.analysis(path=other_path) # cross-file analysis
line = ctx.text.line(1) # source text
handles = ctx.syntax.handles(kind="Call") # opaque syntax handles
parent = ctx.relations.parent(handles[0]) # syntax relationships

Every 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.

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.

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.py

Name files after the policy they enforce; FFR706 rejects filenames that are just a rule code such as xac001.py.

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.

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 = None
import pytest
from fensu import RuleCase, RuleResult, evaluate_rule
from scripts.fensu_policy.rules.client_ownership import no_global_client
from 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_count

RuleCase 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.

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:

  1. Import only pure standard-library modules (ast, re, dataclasses, typing, collections, enum, functools, itertools, pathlib for lexical operations), fensu, and configured rule packages (rule_modules).
  2. Never call open, eval, exec, input, or __import__.
  3. Never read the filesystem directly; use ctx.project, ctx.project.tree, ctx.graph, and ctx.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).

Configured custom rules appear in fensu check, fensu rule, and fensu skills:

fensu rule X001
X001 no-global-client
Family: custom
Severity: error
Kind: custom
Enabled by default: yes
Source: scripts/fensu_policy/rules/client_ownership.py
Message: GLOBAL_CLIENT hides ownership
Remediation: Move the value to the module that owns and produces it.