Making AI Coding Assistants Follow the Rules: From Documentation to Automated Enforcement

    This article explains why instruction files alone often fail to keep AI coding assistants consistent, then presents a four-stage maturity model for moving from bare chat to automated and ecosystem-level workflows. It covers practical setup with hooks, Prettier, lint-staged, Husky, and ESLint guard rules, followed by memory, planning, logging, and checklist files for cross-session continuity, plus risk controls and validation steps.

    1. Which Layer Solves Each Pain Point?

    After using AI coding assistants for a while, most teams encounter these situations:

    • After switching to another repository, a code style that was corrected repeatedly reverts to the default style.
    • A design was discussed for three rounds last week, and the code is half written, but in a new session the assistant asks, “What would you like to do?”
    • The configuration states that “all data requests must go through the unified API layer,” but the assistant still calls an HTTP library directly.

    The three problems have different causes and require solutions at different layers.

    Pain point Root cause Solution layer Section
    Code style regression Instruction files are only text; there is no guarantee the model will follow them Hooks for automatic formatting 3.2
    Bypassing the unified API layer The model may ignore textual constraints Static checks and guard rules 3.4
    Cross-session fragmentation State is reset after a session ends, and documentation is not updated automatically Memory, plans, logs, and checklists 4

    Instruction files should be written clearly, but they can only make rules easier to follow; they cannot guarantee that rules will be followed. Rules that tools can verify should be enforced by tools.

    2. A Four-Stage Maturity Model

    Stage Name Main characteristics Typical symptoms
    1 Bare chat Starts from scratch every time, with no persistent configuration Requirements and tech stack must be explained again on every session
    2 File-based Project instruction files and skill files exist Basic environment is configured, but rules occasionally fail
    3 Automated Hooks, formatting, static checks, and guard rules Rules are enforced automatically, but sessions still fragment
    4 Ecosystem-level Memory, task plans, development logs, and project checklists Continuous work across sessions and projects

    Most introductory tutorials stop at stage 2. No matter how detailed the files are at stage 2, the first two categories of problems still occur. There are three reasons: static documentation is passive input, and there is no guarantee that the model reads or remembers it; in long sessions, the context window remains occupied, and early rules are easily diluted; after a session ends, state is reset, and documentation does not automatically record the process.

    Therefore, most teams should first migrate from stage 2 to stage 3, and then evaluate whether stage 4 is needed. Before upgrading, use the following conditions for self-assessment:

    • Stage 2 to 3: At least one rule fails repeatedly and can be checked with a command-line tool.
    • Stage 3 to 4: Every new session requires re-explaining the task, which clearly affects efficiency, or context is lost during handoffs between multiple people.

    Before entering stage 3, confirm the following four items:

    • The project uses Git, and the working tree is clean before automatic modifications run, making changes easy to inspect and roll back.
    • Formatting, checking, and test commands can run independently in the terminal with controllable execution time.
    • You know the hook configuration location and event names for the tool you use, and you rely on the official documentation for that version of the tool.
    • The team or individual has clearly defined which files may be modified automatically.

    3. Stage 3: Turning Rules from Conventions into Execution

    The core principle is simple: rules that tools can verify should be handed to tools for execution, without relying on the model’s self-discipline.

    3.1 Install Dependencies and Verify

    Run this in a project using Node.js 18 or later. The following uses npm as an example; if the project uses another package manager, replace it with the corresponding command:

    1. npm install --save-dev prettier eslint lint-staged husky
    2. npx husky init

    jq is a system tool used to extract file paths from the hook’s input JSON:

    1. # macOS
    2. brew install jq
    3. # Debian / Ubuntu
    4. sudo apt install jq

    Verify that jq handles paths containing spaces correctly:

    1. echo '{"tool_input":{"file_path":"src/my file.ts"}}' | jq -r '.tool_input.file_path'

    The output should be src/my file.ts. Spaces in the path are preserved completely, so variables in later scripts must be wrapped in double quotes.

    3.2 Formatting Hook

    Configure this in the project’s .claude/settings.json to indicate “automatically run the script after a file is written.” Event names and configuration formats are subject to the official documentation for your version:

    1. {
    2. "hooks": {
    3. "PostToolUse": [
    4. {
    5. "matcher": "Edit|Write",
    6. "hooks": [
    7. {
    8. "type": "command",
    9. "command": "bash .claude/hooks/format-changed.sh"
    10. }
    11. ]
    12. }
    13. ]
    14. }
    15. }

    Script .claude/hooks/format-changed.sh:

    1. #!/usr/bin/env bash
    2. # Example script: test in a clean Git working tree first
    3. set -uo pipefail
    4. LOG_FILE=".claude/logs/hooks.log"
    5. mkdir -p "$(dirname "$LOG_FILE")"
    6. log() { printf '%s %s\n' "$(date '+%F %T')" "$*" >> "$LOG_FILE"; }
    7. if ! command -v jq >/dev/null 2>&1; then
    8. log "SKIP jq not installed"
    9. exit 0
    10. fi
    11. file=$(jq -r '.tool_input.file_path // empty')
    12. if [ -z "$file" ]; then
    13. log "SKIP no file_path in input"
    14. exit 0
    15. fi
    16. if [ ! -f "$file" ]; then
    17. log "SKIP file does not exist: $file"
    18. exit 0
    19. fi
    20. case "$file" in
    21. *.ts|*.tsx|*.js|*.jsx|*.json|*.md)
    22. output=$(npx --no-install prettier --write "$file" 2>&1)
    23. rc=$?
    24. if [ "$rc" -eq 0 ]; then
    25. log "OK $file"
    26. else
    27. log "FAIL rc=$rc $file"
    28. printf '%s\n' "$output" >&2
    29. exit 2
    30. fi
    31. ;;
    32. esac
    33. exit 0

    Note the following when using it:

    • For unrecognized input, missing files, or extensions not in the list, log the event and exit normally without interrupting the session.
    • If formatting fails, the script exits with code 2. In PostToolUse, most tools feed stderr back to the model so it can fix the issue. Check the current version’s documentation for specific behavior.
    • Every run writes to .claude/logs/hooks.log. Review this file periodically to confirm the hook is actually working.
    • The script runs with the current user’s permissions. Review it line by line before sharing it with a team. --no-install requires Prettier to already be a project dependency, preventing downloads of unknown versions at runtime.

    3.3 Pre-Commit Checks: lint-staged and Husky

    Add the lint-staged configuration to package.json:

    1. {
    2. "lint-staged": {
    3. "*.{ts,tsx,js,jsx}": ["eslint --fix", "prettier --write"],
    4. "*.{json,md}": ["prettier --write"]
    5. }
    6. }

    Then make Husky’s pre-commit hook call it:

    1. echo "npx --no-install lint-staged" > .husky/pre-commit

    At commit time, only files in the staging area are checked. If the check fails, the commit is aborted; the check is not left to the model’s judgment.

    3.4 Guard Rules: Prevent Bypassing the Unified API Layer

    In the ESLint flat config eslint.config.mjs, prohibit direct calls to HTTP libraries in business code and allow requests only from the src/api/ directory:

    1. export default [
    2. {
    3. files: ["src/**/*.{ts,tsx}"],
    4. ignores: ["src/api/**"],
    5. rules: {
    6. "no-restricted-imports": ["error", {
    7. paths: [
    8. { name: "axios", message: "Use the unified API layer in src/api/ for requests." },
    9. ],
    10. }],
    11. "no-restricted-globals": ["error",
    12. { name: "fetch", message: "Use the unified API layer in src/api/ for requests." },
    13. ],
    14. },
    15. },
    16. ];

    This rule runs during the lint phase. When the model writes violating code, the check reports an error. It can only identify statically visible patterns. Cases bypassed through indirect variable calls, dynamic imports, and similar approaches still require code review as a supplement.

    To check immediately after editing, add another PostToolUse hook in .claude/settings.json to run npx --no-install eslint --max-warnings=0 "$file" for Edit|Write, also exiting with code 2 on failure.

    4. Stage 4: Memory, Plans, Logs, and Checklists

    Stage 4 addresses cross-session fragmentation. The idea is to write state into files so that new sessions can read it. A suggested directory structure is as follows:

    1. CLAUDE.md # Stable rules: tech stack, code style, prohibitions
    2. docs/
    3. memory/decisions.md # Long-term memory: confirmed decisions and rationale
    4. plan/current-plan.md # Current task plan with status checkboxes
    5. logs/2026-11-24.md # Daily development log: what was done, why, and blockers
    6. checklist.md # Pre-commit checklist

    Examples for each file:

    1. <!-- docs/memory/decisions.md -->
    2. ## Decision: All HTTP requests go through src/api/
    3. - Date: 2026-11-20
    4. - Reason: unified auth, retry, and error handling
    5. - Status: Active (if deprecated, mark "Deprecated" and note the replacement)
    1. <!-- docs/plan/current-plan.md -->
    2. ## Task: Add pagination to user list
    3. - [x] Define pagination parameter format (page, pageSize)
    4. - [x] Implement request in src/api/users.ts
    5. - [ ] Connect pagination controls in list component
    6. - [ ] Add pagination boundary tests
    7. Next step: connect pagination controls; first read src/components/UserList.tsx.
    1. <!-- docs/logs/2026-11-24.md -->
    2. ## Today's progress
    3. - Completed paginated request in src/api/users.ts.
    4. ## Issues
    5. - Backend total field may be null; handling not yet confirmed.
    1. <!-- docs/checklist.md -->
    2. - [ ] All tests pass
    3. - [ ] lint has no errors
    4. - [ ] No new code directly calls HTTP libraries
    5. - [ ] Plan file and daily log updated

    At the start and end of every session, require the assistant to perform fixed actions. For example, state in the project instructions: “Before starting work, read CLAUDE.md, docs/plan/current-plan.md, and the most recent log. Restate the current task and next step in three sentences, then begin.” Before finishing, require it to update the plan status and the daily log.

    File loading methods vary by tool. Some tools automatically read CLAUDE.md, while others require explicit file names in the prompt. Confirm before use.

    5. Risk Control and Rollback

    • Confirm the working tree is clean before automatic modifications. After changes, use git diff to inspect all changes.
    • Roll back a single file with git restore -- path. Before running it, confirm the file has no uncommitted manual changes of yours, because this command discards all uncommitted modifications in that file. Do not use git reset --hard to clean the entire working tree.
    • Hook scripts execute on the local machine. Configuration files should be version-controlled and reviewed before merging.
    • Personal preference overrides should be placed in uncommitted local configuration files to avoid affecting colleagues.
    • Memory files become outdated. After a decision changes, update it or mark it deprecated promptly; otherwise, the model will read outdated information.

    6. Verify That the Configuration Works

    Check in the following three steps; each step has a clear expected result:

    1. Create a new file under src/ and directly import axios from "axios". Expected: after editing, ESLint reports “Use the unified API layer in src/api/ for requests.”
    2. Open .claude/logs/hooks.log. Expected: every edit has an OK or SKIP entry.
    3. Start a new session and enter only “continue.” Expected: the assistant first reads the plan file and restates the current task and next step, rather than asking what you want to do.

    Once all three steps pass, the rules are being enforced by tools, and context can continue across sessions.