Enforcing AI Coding Assistant Rules: From Instructions to Execution

    AI coding assistants often forget project rules or violate established constraints due to a reliance on context rather than enforcement. This article explores why prompts alone are insufficient and introduces a four-stage maturity model for human-AI collaboration. It details how to transition from merely telling AI the rules to executing them through structural constraints, check scripts, and engineering mechanisms to ensure consistent code generation.

    1. Why AI “Forgets” and “Crosses Boundaries” Despite Written Rules

    When using AI coding assistants, developers often encounter three typical issues.

    First, after switching project directories, the AI forgets the coding styles and communication preferences that were repeatedly corrected previously. This indicates that preferences exist only within the context of a single conversation and are not solidified into the engineering environment.

    Second, when starting a new session after partially completing a solution discussed the previous week, the AI can only respond with, “What would you like to do?” There is no shared state between sessions; task progress exists only in human memory.

    Third, even if project rules explicitly require that “all data must be fetched through a unified interface,” the AI still directly concatenates request URLs in the code. The rules exist, but there is no mechanism to check whether they are followed.

    The immediate reaction for many is to continue refining the rule documentation: expanding length, adding examples, and splitting into more specialized capability modules. While this approach has some effect, the returns diminish rapidly. The root cause lies in how rules are executed, not in whether they are detailed enough.

    2. Root Cause: Telling vs. Executing Rules

    Rules that rely on “telling” are essentially prompts. The model references them when generating code, but they lack binding force. As the context grows longer, the rules get diluted faster.

    Rules that rely on “executing” are guaranteed by engineering mechanisms and typically possess three characteristics:

    • Violations are automatically detected, rather than relying on human attention during review;
    • Violations are blocked or throw errors, rather than silently passing;
    • Rule check results are saved in the project, independent of any single session’s memory.

    Therefore, the key to improving collaboration efficiency is transforming “hoping the AI complies” into “the system enforces compliance.”

    3. The Four-Stage Maturity Model

    Based on how rules and context are carried, human-AI collaboration can be roughly divided into four stages:

    Stage Name Core Characteristics Typical Pain Points
    1 Raw Chat Every conversation starts from scratch Repeatedly explaining requirements and background
    2 File-based Has rule docs and specialized capability modules Rules rely on prompts; execution is unstable
    3 Automated Checks, hooks, and guard mechanisms Lack of continuity between sessions
    4 Ecosystem Collaboration of memory, plans, logs, and checklists Sustainable progress for multi-project, long-term tasks

    Stages 1 and 2 are well-documented elsewhere and will not be expanded upon here. The focus below is on Stages 3 and 4.

    4. Stage 3: Turning Rules into Mechanisms

    4.1 Making Violations Structurally Impossible

    The most effective rules make violations structurally impossible to implement. Taking “data must be fetched through a unified interface” as an example, you can provide a unified data access layer, allowing all business code to fetch data only through it.

    1. # data_gateway.py: The only module in the project allowed to initiate external requests (illustrative)
    2. class DataGateway:
    3. def __init__(self, transport, registry):
    4. self._transport = transport
    5. self._registry = registry # Registered data sources: name -> address
    6. def fetch(self, source_name: str, params: dict) -> dict:
    7. if source_name not in self._registry:
    8. raise ValueError(f"Unregistered data source: {source_name}")
    9. url = self._registry[source_name]
    10. return self._transport.get(url, params=params)

    This way, even if the AI tries to write the address directly, it will find no available entry point in the project and must call the unified interface.

    4.2 Intercepting Violations with Check Scripts

    Rules that structure cannot cover can be backed up by check scripts. Check scripts should run both in local development and continuous integration.

    1. # check_hardcoded_urls.py: Scans source code for hardcoded addresses (illustrative)
    2. import pathlib
    3. import re
    4. import sys
    5. PATTERN = re.compile(r"https?://")
    6. ALLOWED_FILE = "registry.py" # Addresses are only allowed in the registry file
    7. def scan(root: str) -> list[str]:
    8. violations = []
    9. for path in pathlib.Path(root).rglob("*.py"):
    10. if path.name == ALLOWED_FILE:
    11. continue
    12. lines = path.read_text(encoding="utf-8").splitlines()
    13. for lineno, line in enumerate(lines, start=1):
    14. if PATTERN.search(line):
    15. violations.append(f"{path}:{lineno}")
    16. return violations
    17. if __name__ == "__main__":
    18. found = scan("src")
    19. for item in found:
    20. print(f"Hardcoded address: {item}")
    21. sys.exit(1 if found else 0)

    When the script returns a non-zero exit code, the pipeline stops immediately. This step turns a “reminder” into an “interception.”

    4.3 Constraints with Hooks and Guards