Claude Code Prompt Guidelines Enforcement (Feature)

Status Fixed / completed
Maintainer reply ✓ Yes — bcherny
Activity 4 comments · opened Mar 11, 2025 · closed Mar 18, 2025
💡 Likely answer: A maintainer (bcherny, collaborator) responded on this thread — see the highlighted reply below.

Introduction

First, we want to express our tremendous gratitude to the Claude Code team. Your product has already transformed our development workflow, delivering a 20-30x productivity boost across our team. This acceleration is currently limited primarily by architectural pattern divergence as projects scale, which this feature request aims to address.

Problem Statement

In large-scale parallel development activities, teams consistently experience "pattern drift" where carefully established architectural standards gradually erode as multiple developers make incremental changes. Despite detailed documentation, training, and explicit warnings, teams continue to fall back into anti-patterns due to factors such as:

  • Path of Least Resistance: Developers naturally optimize for immediate functionality over architectural integrity
  • Documentation Insufficiency: Even extensive documentation fails to prevent drift (as seen in our LESSONS.md entries)
  • Knowledge Gaps: Not all team members maintain deep understanding of architectural principles
  • LLM-Assisted Development Challenges: AI assistants can exacerbate drift by optimizing for immediate task completion over architectural consistency

Scale-Related Pattern Drift

A critical insight from our experience is that pattern drift accelerates proportionally with project scale. As our codebase grew from dozens to thousands of files:

  • Increasing Drift Rate: The frequency of architectural violations grew exponentially with project size
  • Context Overhead: Developers had to manually inject large amounts of rule context with every prompt to maintain standards
  • Continuous Policing Required: With larger codebases, maintaining architectural integrity required constant vigilance and repetitive reminders of guidelines
  • Memory Limitations: As projects scaled beyond Claude's immediate context window, architectural principles were the first to be forgotten when focusing on individual components
  • Our team found that proactively identifying "drift threat vectors" - specific patterns where Claude 3.7 Sonnet was likely to prioritize task completion over architectural integrity - became standard practice. This defensive approach was necessary as the model would often "achieve the goal at any cost" rather than maintain architectural purity when the two were in conflict.

Real-World Examples From Our Project

SST v3 Infrastructure Pattern Drift:

  • Despite establishing clear guidelines for SST v3 usage, we found ourselves reverting to CloudFormation/CDK -
  • patterns in our infrastructure code, particularly when implementing Aurora Serverless v2 PostgreSQL for -
  • production. This resulted in direct violations of established guidelines:
  • Using app.addOutputs() instead of returning values from run() methods
  • Relying on environment variables rather than the SST Resource object
  • Improperly configuring database settings using CloudFormation patterns

UI Component Framework Drift

Despite our project guidelines clearly stating that Material UI (MUI) components should be used first and exclusively, we found consistent drift toward using raw HTML elements with custom CSS classes. Specific violations included:

  • Using plain HTML elements instead of MUI components
  • Adding custom CSS classes instead of using MUI's sx prop
  • Inconsistent styling causing accessibility and maintenance issues

Proposed Feature: Prompt Guidelines Enforcement

This is intended as a proposition for ideas. We cannot expect a feature be implemented exactly how we we request but the best way to share our insight is by thinking about what we can see as solving or problem. This would be a Claude Code feature that allows developers to to define injectable prompt guidelines with enforcement levels that prevent falling off architectural standards during development (can be used for other things too but beyond this scope). This would include:

Project-Wide Guidelines Repository:
  • A structured format for defining critical project guidelines (.claude-guidelines/)
  • Support for file pattern association (similar to .cursor/rules/)
  • Guidelines validation and conflict resolution
Enforcement Level Configuration:
  1. warn: Alert the assistant and user about potential guideline violations
  2. enforce: Require explicit override from the user to proceed with violating changes
  3. strict: Refuse to generate code that violates guidelines
Contextual Guideline Activation:
  • Auto-activate guidelines based on files being edited
  • Allow for guideline-specific examples showing correct and incorrect implementations
  • Support for linking to detailed documentation
Pattern Recognition:
  • Ability to define patterns that represent guideline violations
  • Support for language-specific pattern matching
  • Integration with existing linting/static analysis tools
Anti-Pattern Catalog:
  • Allow teams to define known "drift threat vectors" based on observed LLM tendencies
  • Provide stronger enforcement for behaviors where models like Sonnet 3.7 typically optimize for completion over compliance
  • Maintain a project-specific catalog of common architectural compromises to watch for

Implementation Example

A sample .claude-guidelines/sst-v3.yaml might look like:

name: "SST v3 Infrastructure Guidelines"
description: "Enforce SST v3 architectural patterns to ensure infrastructure consistency"
version: 1.0
applies_to:
  - "infra/**/*.ts"
  - "sst.config.ts"
enforcement: "enforce"

guidelines:
  - id: "sst-v3-component-naming"
    description: "All SST component names must use PascalCase"
    pattern:
      - language: "typescript"
        match: "new sst\\.aws\\.\\w+\\(\\s*['\"]([^A-Z]\\w*)['\"]"
        examples:
          violation: 'new sst.aws.ApiGatewayV2("api", {});'
          correct: 'new sst.aws.ApiGatewayV2("Api", {});'
    message: "SST component names must use PascalCase - found '{match}'"
    documentation: "/docs/tech/SST_DEV_WORKFLOW.md"
    
  # Anti-Pattern examples (drift threat vectors)
  drift_threats:
    - id: "simplification-under-pressure"
      description: "The model tends to revert to simpler patterns when debugging or under pressure"
      contexts: ["error handling", "debugging", "quick fix"]
      high_risk_patterns:
        - "directly accessing environment variables"
        - "bypassing resource linking"
        - "hardcoding values"
      enforcement: "strict"
````

### Expected Impact
With this feature, we believe we could fully realize the 20-30x productivity boost we're already seeing with Claude Code. Our current specialized setup with MCP servers for KB fetching, memory caching, and headless browser testing has dramatically improved efficiency, but architectural divergence remains the key limiting factor.

By providing Claude with persistent, contextually-aware architectural guardrails, we can maintain consistency at scale without the overhead of constant manual reinforcement. This would complete the productivity transformation that Claude Code has already initiated in our development workflow.

We can also see this concept evolving into a marketplace with a vote/ranking system that could provide what would amount to as 'patching' system for gaps where the current Sonnet version may have tendencies not aligned with some goals.

Again, we deeply appreciate your consideration of this feature request and remain incredibly grateful for the transformative impact Sonnet 3.7 & Claude Code have already had on our development process overnight.

View original on GitHub ↗

4 Comments

mgryning · 1 year ago

I second this request as we are experiencing the same. Claude Code really speed up development, but to really get the benefits, it should respect the architecture documentation and guidelines more strictly. After running /compact, or when the context gets long, Claude tends to forget the guidelines. We have a mcp that links to a confluence page with documentation and help that Claude can use, however this requires that 1) Claude call the mcp, and 2) that it is present in the context / prompt.

Prompt injection or similar mechanism to make sure Claude adhere to the guidelines would really make a difference

bcherny collaborator · 1 year ago

You can do something similar today (we do this for Claude Code itself!):

  1. Create a local prompt with a set of lint guidelines (eg. use X and not Y; always use spaces; no typos; etc.)
  2. Create a Github action to use claude to run this prompt

For Code itself, we call this prompt lint.md. Here's what the full prompt looks like:

You are a code linter. Please analyze the changes versus the main branch (via `git diff` with no arguments - you already have permission) and report any issues related to typos or style guidelines.

## Guidelines

- DO NOT run bash lint/typecheck commands on the codebase. Remember that YOU are the linter.
- Only surface issues in newly added or modified lines
- Keep the CLAUDE.md style guide in mind
- Focus on typos, style issues, and potential bugs
- When the user made an intentional change (eg. for variable naming or content tone), you should generally trust the user's intent and not report an issue
- Use Unicode ellipsis (…) instead of three dots (...) in user-facing text

## Output Format

For each issue found:

1. Filename and line number on one line
2. Description of the issue on the second line
3. Separate issues with a blank line

For example:

\`\`\`
src/commands/loadCommandsDir.ts:123
Avoid `enum`; use unions of string literal types instead
\`\`\`

DO NOT return any other text or explanations. If you don't find any issues, just return "No issues found".

And here's our Github workflow:

name: Claude Lint

on: pull_request

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  lint-claude:
    name: Claude-assisted code linting
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - run: npm run build

      - run: claude -p "/project:lint" --allowedTools "Bash(git log:*)" "Bash(git diff:*)" "Bash(git status:*)"

We're a little behind on documenting this -- hopefully it's useful!

spbreed · 1 year ago

Regarding the architectural guardrails feature: Do we have any guidance on implementing Claude in AWS Lambda with vector store-based guardrails?

  1. Deploying Claude in Lambda with a custom handler that:
  • Initializes with pre-loaded guardrail configurations from vector stores
  • Enforces architectural boundaries at inference time
  • Uses a container image with necessary dependencies
  1. Specific implementation questions:
  • Most efficient approach to pass vector embeddings to Claude during initialization
  • Best practice for structuring guardrail context from vector stores (Pinecone/Weaviate)
  • Memory optimization strategies when using large context windows with guardrails
  1. Challenges encountered:
  • Cold start latency with large guardrail contexts (~2-3 seconds overhead)
  • Lambda memory constraints when passing full architectural patterns
  • Maintaining guardrail consistency across function invocations

Has anyone implemented a similar approach with the Claude API? Particularly interested in patterns for initializing the context window efficiently.

github-actions[bot] · 1 year ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.